text:
#include "SkPoint.h"

void SkIPoint::rotateCW(SkIPoint* dst) const {
    SkASSERT(dst);

    // use a tmp in case this == dst
    int32_t tmp = fX;
    dst->fX = -fY;
    dst->fY = tmp;
}

void SkIPoint::rotateCCW(SkIPoint* dst) const {
    SkASSERT(dst);

    // use a tmp in case this == dst
    int32_t tmp = fX;
    dst->fX = fY;
    dst->fY = -tmp;
}

///////////////////////////////////////////////////////////////////////////////

void SkPoint::setIRectFan(int l, int t, int r, int b, size_t stride) {
    SkASSERT(stride >= sizeof(SkPoint));

    ((SkPoint*)((intptr_t)this + 0 * stride))->set(SkIntToScalar(l),
                                                   SkIntToScalar(t));
    ((SkPoint*)((intptr_t)this + 1 * stride))->set(SkIntToScalar(l),
                                                   SkIntToScalar(b));
    ((SkPoint*)((intptr_t)this + 2 * stride))->set(SkIntToScalar(r),
                                                   SkIntToScalar(b));
    ((SkPoint*)((intptr_t)this + 3 * stride))->set(SkIntToScalar(r),
                                                   SkIntToScalar(t));
}

void SkPoint::setRectFan(SkScalar l, SkScalar t, SkScalar r, SkScalar b,
                         size_t stride) {
    SkASSERT(stride >= sizeof(SkPoint));

    ((SkPoint*)((intptr_t)this + 0 * stride))->set(l, t);
    ((SkPoint*)((intptr_t)this + 1 * stride))->set(l, b);
    ((SkPoint*)((intptr_t)this + 2 * stride))->set(r, b);
    ((SkPoint*)((intptr_t)this + 3 * stride))->set(r, t);
}

void SkPoint::rotateCW(SkPoint* dst) const {
    SkASSERT(dst);

    // use a tmp in case this == dst
    SkScalar tmp = fX;
    dst->fX = -fY;
    dst->fY = tmp;
}

void SkPoint::rotateCCW(SkPoint* dst) const {
    SkASSERT(dst);

    // use a tmp in case this == dst
    SkScalar tmp = fX;
    dst->fX = fY;
    dst->fY = -tmp;
}

void SkPoint::scale(SkScalar scale, SkPoint* dst) const {
    SkASSERT(dst);
    dst->set(SkScalarMul(fX, scale), SkScalarMul(fY, scale));
}

bool SkPoint::normalize() {
    return this->setLength(fX, fY, SK_Scalar1);
}

bool SkPoint::setNormalize(SkScalar x, SkScalar y) {
    return this->setLength(x, y, SK_Scalar1);
}

bool SkPoint::setLength(SkScalar length) {
    return this->setLength(fX, fY, length);
}

#ifdef SK_SCALAR_IS_FLOAT

// Returns the square of the Euclidian distance to (dx,dy).
static inline float getLengthSquared(float dx, float dy) {
    return dx * dx + dy * dy;
}

// Calculates the square of the Euclidian distance to (dx,dy) and stores it in
// *lengthSquared.  Returns true if the distance is judged to be "nearly zero".
//
// This logic is encapsulated in a helper method to make it explicit that we
// always perform this check in the same manner, to avoid inconsistencies
// (see http://code.google.com/p/skia/issues/detail?id=560 ).
static inline bool isLengthNearlyZero(float dx, float dy,
                                      float *lengthSquared) {
    *lengthSquared = getLengthSquared(dx, dy);
    return *lengthSquared <= (SK_ScalarNearlyZero * SK_ScalarNearlyZero);
}

SkScalar SkPoint::Normalize(SkPoint* pt) {
    float x = pt->fX;
    float y = pt->fY;
    float mag2;
    if (isLengthNearlyZero(x, y, &mag2)) {
        return 0;
    }

    float mag, scale;
    if (SkScalarIsFinite(mag2)) {
        mag = sk_float_sqrt(mag2);
        scale = 1 / mag;
    } else {
        // our mag2 step overflowed to infinity, so use doubles instead.
        // much slower, but needed when x or y are very large, other wise we
        // divide by inf. and return (0,0) vector.
        double xx = x;
        double yy = y;
        double magmag = sqrt(xx * xx + yy * yy);
        mag = (float)magmag;
        // we perform the divide with the double magmag, to stay exactly the
        // same as setLength. It would be faster to perform the divide with
        // mag, but it is possible that mag has overflowed to inf. but still
        // have a non-zero value for scale (thanks to denormalized numbers).
        scale = (float)(1 / magmag);
    }
    pt->set(x * scale, y * scale);
    return mag;
}

SkScalar SkPoint::Length(SkScalar dx, SkScalar dy) {
    float mag2 = dx * dx + dy * dy;
    if (SkScalarIsFinite(mag2)) {
        return sk_float_sqrt(mag2);
    } else {
        double xx = dx;
        double yy = dy;
        return (float)sqrt(xx * xx + yy * yy);
    }
}

/*
 *  We have to worry about 2 tricky conditions:
 *  1. underflow of mag2 (compared against nearlyzero^2)
 *  2. overflow of mag2 (compared w/ isfinite)
 *
 *  If we underflow, we return false. If we overflow, we compute again using
 *  doubles, which is much slower (3x in a desktop test) but will not overflow.
 */
bool SkPoint::setLength(float x, float y, float length) {
    float mag2;
    if (isLengthNearlyZero(x, y, &mag2)) {
        return false;
    }

    float scale;
    if (SkScalarIsFinite(mag2)) {
        scale = length / sk_float_sqrt(mag2);
    } else {
        // our mag2 step overflowed to infinity, so use doubles instead.
        // much slower, but needed when x or y are very large, other wise we
        // divide by inf. and return (0,0) vector.
        double xx = x;
        double yy = y;
        scale = (float)(length / sqrt(xx * xx + yy * yy));
    }
    fX = x * scale;
    fY = y * scale;
    return true;
}

#else

#include "Sk64.h"

// Returns the square of the Euclidian distance to (dx,dy) in *result.
static inline void getLengthSquared(SkScalar dx, SkScalar dy, Sk64 *result) {
    Sk64    dySqr;

    result->setMul(dx, dx);
    dySqr.setMul(dy, dy);
    result->add(dySqr);
}

// Calculates the square of the Euclidian distance to (dx,dy) and stores it in
// *lengthSquared.  Returns true if the distance is judged to be "nearly zero".
//
// This logic is encapsulated in a helper method to make it explicit that we
// always perform this check in the same manner, to avoid inconsistencies
// (see http://code.google.com/p/skia/issues/detail?id=560 ).
static inline bool isLengthNearlyZero(SkScalar dx, SkScalar dy,
                                      Sk64 *lengthSquared) {
    Sk64 tolSqr;
    getLengthSquared(dx, dy, lengthSquared);

    // we want nearlyzero^2, but to compute it fast we want to just do a
    // 32bit multiply, so we require that it not exceed 31bits. That is true
    // if nearlyzero is <= 0xB504, which should be trivial, since usually
    // nearlyzero is a very small fixed-point value.
    SkASSERT(SK_ScalarNearlyZero <= 0xB504);

    tolSqr.set(0, SK_ScalarNearlyZero * SK_ScalarNearlyZero);
    return *lengthSquared <= tolSqr;
}

SkScalar SkPoint::Normalize(SkPoint* pt) {
    Sk64 mag2;
    if (!isLengthNearlyZero(pt->fX, pt->fY, &mag2)) {
        SkScalar mag = mag2.getSqrt();
        SkScalar scale = SkScalarInvert(mag);
        pt->fX = SkScalarMul(pt->fX, scale);
        pt->fY = SkScalarMul(pt->fY, scale);
        return mag;
    }
    return 0;
}

bool SkPoint::CanNormalize(SkScalar dx, SkScalar dy) {
    Sk64 mag2_unused;
    return !isLengthNearlyZero(dx, dy, &mag2_unused);
}

SkScalar SkPoint::Length(SkScalar dx, SkScalar dy) {
    Sk64    tmp;
    getLengthSquared(dx, dy, &tmp);
    return tmp.getSqrt();
}

#ifdef SK_DEBUGx
static SkFixed fixlen(SkFixed x, SkFixed y) {
    float fx = (float)x;
    float fy = (float)y;

    return (int)floorf(sqrtf(fx*fx + fy*fy) + 0.5f);
}
#endif

static inline uint32_t squarefixed(unsigned x) {
    x >>= 16;
    return x*x;
}

#if 1   // Newton iter for setLength

static inline unsigned invsqrt_iter(unsigned V, unsigned U) {
    unsigned x = V * U >> 14;
    x = x * U >> 14;
    x = (3 << 14) - x;
    x = (U >> 1) * x >> 14;
    return x;
}

static const uint16_t gInvSqrt14GuessTable[] = {
    0x4000, 0x3c57, 0x393e, 0x3695, 0x3441, 0x3235, 0x3061,
    0x2ebd, 0x2d41, 0x2be7, 0x2aaa, 0x2987, 0x287a, 0x2780,
    0x2698, 0x25be, 0x24f3, 0x2434, 0x2380, 0x22d6, 0x2235,
    0x219d, 0x210c, 0x2083, 0x2000, 0x1f82, 0x1f0b, 0x1e99,
    0x1e2b, 0x1dc2, 0x1d5d, 0x1cfc, 0x1c9f, 0x1c45, 0x1bee,
    0x1b9b, 0x1b4a, 0x1afc, 0x1ab0, 0x1a67, 0x1a20, 0x19dc,
    0x1999, 0x1959, 0x191a, 0x18dd, 0x18a2, 0x1868, 0x1830,
    0x17fa, 0x17c4, 0x1791, 0x175e, 0x172d, 0x16fd, 0x16ce
};

#define BUILD_INVSQRT_TABLEx
#ifdef BUILD_INVSQRT_TABLE
static void build_invsqrt14_guess_table() {
    for (int i = 8; i <= 63; i++) {
        unsigned x = SkToU16((1 << 28) / SkSqrt32(i << 25));
        printf("0x%x, ", x);
    }
    printf("\n");
}
#endif

static unsigned fast_invsqrt(uint32_t x) {
#ifdef BUILD_INVSQRT_TABLE
    unsigned top2 = x >> 25;
    SkASSERT(top2 >= 8 && top2 <= 63);

    static bool gOnce;
    if (!gOnce) {
        build_invsqrt14_guess_table();
        gOnce = true;
    }
#endif

    unsigned V = x >> 14;   // make V .14

    unsigned top = x >> 25;
    SkASSERT(top >= 8 && top <= 63);
    SkASSERT(top - 8 < SK_ARRAY_COUNT(gInvSqrt14GuessTable));
    unsigned U = gInvSqrt14GuessTable[top - 8];

    U = invsqrt_iter(V, U);
    return invsqrt_iter(V, U);
}

/*  We "normalize" x,y to be .14 values (so we can square them and stay 32bits.
    Then we Newton-iterate this in .14 space to compute the invser-sqrt, and
    scale by it at the end. The .14 space means we can execute our iterations
    and stay in 32bits as well, making the multiplies much cheaper than calling
    SkFixedMul.
*/
bool SkPoint::setLength(SkFixed ox, SkFixed oy, SkFixed length) {
    if (ox == 0) {
        if (oy == 0) {
            return false;
        }
        this->set(0, SkApplySign(length, SkExtractSign(oy)));
        return true;
    }
    if (oy == 0) {
        this->set(SkApplySign(length, SkExtractSign(ox)), 0);
        return true;
    }

    unsigned x = SkAbs32(ox);
    unsigned y = SkAbs32(oy);
    int zeros = SkCLZ(x | y);

    // make x,y 1.14 values so our fast sqr won't overflow
    if (zeros > 17) {
        x <<= zeros - 17;
        y <<= zeros - 17;
    } else {
        x >>= 17 - zeros;
        y >>= 17 - zeros;
    }
    SkASSERT((x | y) <= 0x7FFF);

    unsigned invrt = fast_invsqrt(x*x + y*y);

    x = x * invrt >> 12;
    y = y * invrt >> 12;

    if (length != SK_Fixed1) {
        x = SkFixedMul(x, length);
        y = SkFixedMul(y, length);
    }
    this->set(SkApplySign(x, SkExtractSign(ox)),
              SkApplySign(y, SkExtractSign(oy)));
    return true;
}
#else
/*
    Normalize x,y, and then scale them by length.

    The obvious way to do this would be the following:
        S64 tmp1, tmp2;
        tmp1.setMul(x,x);
        tmp2.setMul(y,y);
        tmp1.add(tmp2);
        len = tmp1.getSqrt();
        x' = SkFixedDiv(x, len);
        y' = SkFixedDiv(y, len);
    This is fine, but slower than what we do below.

    The present technique does not compute the starting length, but
    rather fiddles with x,y iteratively, all the while checking its
    magnitude^2 (avoiding a sqrt).

    We normalize by first shifting x,y so that at least one of them
    has bit 31 set (after taking the abs of them).
    Then we loop, refining x,y by squaring them and comparing
    against a very large 1.0 (1 << 28), and then adding or subtracting
    a delta (which itself is reduced by half each time through the loop).
    For speed we want the squaring to be with a simple integer mul. To keep
    that from overflowing we shift our coordinates down until we are dealing
    with at most 15 bits (2^15-1)^2 * 2 says withing 32 bits)
    When our square is close to 1.0, we shift x,y down into fixed range.
*/
bool SkPoint::setLength(SkFixed ox, SkFixed oy, SkFixed length) {
    if (ox == 0) {
        if (oy == 0)
            return false;
        this->set(0, SkApplySign(length, SkExtractSign(oy)));
        return true;
    }
    if (oy == 0) {
        this->set(SkApplySign(length, SkExtractSign(ox)), 0);
        return true;
    }

    SkFixed x = SkAbs32(ox);
    SkFixed y = SkAbs32(oy);

    // shift x,y so that the greater of them is 15bits (1.14 fixed point)
    {
        int shift = SkCLZ(x | y);
        // make them .30
        x <<= shift - 1;
        y <<= shift - 1;
    }

    SkFixed dx = x;
    SkFixed dy = y;

    for (int i = 0; i < 17; i++) {
        dx >>= 1;
        dy >>= 1;

        U32 len2 = squarefixed(x) + squarefixed(y);
        if (len2 >> 28) {
            x -= dx;
            y -= dy;
        } else {
            x += dx;
            y += dy;
        }
    }
    x >>= 14;
    y >>= 14;

#ifdef SK_DEBUGx    // measure how far we are from unit-length
    {
        static int gMaxError;
        static int gMaxDiff;

        SkFixed len = fixlen(x, y);
        int err = len - SK_Fixed1;
        err = SkAbs32(err);

        if (err > gMaxError) {
            gMaxError = err;
            SkDebugf("gMaxError %d\n", err);
        }

        float fx = SkAbs32(ox)/65536.0f;
        float fy = SkAbs32(oy)/65536.0f;
        float mag = sqrtf(fx*fx + fy*fy);
        fx /= mag;
        fy /= mag;
        SkFixed xx = (int)floorf(fx * 65536 + 0.5f);
        SkFixed yy = (int)floorf(fy * 65536 + 0.5f);
        err = SkMax32(SkAbs32(xx-x), SkAbs32(yy-y));
        if (err > gMaxDiff) {
            gMaxDiff = err;
            SkDebugf("gMaxDiff %d\n", err);
        }
    }
#endif

    x = SkApplySign(x, SkExtractSign(ox));
    y = SkApplySign(y, SkExtractSign(oy));
    if (length != SK_Fixed1) {
        x = SkFixedMul(x, length);
        y = SkFixedMul(y, length);
    }

    this->set(x, y);
    return true;
}
#endif

#endif

///////////////////////////////////////////////////////////////////////////////

SkScalar SkPoint::distanceToLineBetweenSqd(const SkPoint& a,
                                           const SkPoint& b,
                                           Side* side) const {

    SkVector u = b - a;
    SkVector v = *this - a;

    SkScalar uLengthSqd = u.lengthSqd();
    SkScalar det = u.cross(v);
    if (NULL != side) {
        SkASSERT(-1 == SkPoint::kLeft_Side &&
                  0 == SkPoint::kOn_Side &&
                  1 == kRight_Side);
        *side = (Side) SkScalarSignAsInt(det);
    }
    return SkScalarMulDiv(det, det, uLengthSqd);
}

SkScalar SkPoint::distanceToLineSegmentBetweenSqd(const SkPoint& a,
                                                  const SkPoint& b) const {
    // See comments to distanceToLineBetweenSqd. If the projection of c onto
    // u is between a and b then this returns the same result as that
    // function. Otherwise, it returns the distance to the closer of a and
    // b. Let the projection of v onto u be v'.  There are three cases:
    //    1. v' points opposite to u. c is not between a and b and is closer
    //       to a than b.
    //    2. v' points along u and has magnitude less than y. c is between
    //       a and b and the distance to the segment is the same as distance
    //       to the line ab.
    //    3. v' points along u and has greater magnitude than u. c is not
    //       not between a and b and is closer to b than a.
    // v' = (u dot v) * u / |u|. So if (u dot v)/|u| is less than zero we're
    // in case 1. If (u dot v)/|u| is > |u| we are in case 3. Otherwise
    // we're in case 2. We actually compare (u dot v) to 0 and |u|^2 to
    // avoid a sqrt to compute |u|.

    SkVector u = b - a;
    SkVector v = *this - a;

    SkScalar uLengthSqd = u.lengthSqd();
    SkScalar uDotV = SkPoint::DotProduct(u, v);

    if (uDotV <= 0) {
        return v.lengthSqd();
    } else if (uDotV > uLengthSqd) {
        return b.distanceToSqd(*this);
    } else {
        SkScalar det = u.cross(v);
        return SkScalarMulDiv(det, det, uLengthSqd);
    }
}


text:
package auth

import (
	"encoding/base64"
	"fmt"
	"log"
	"net/http"
	"strings"
	"time"

	"github.com/garyburd/redigo/redis"
)

type RedisAuth struct {
	Address  string
	TTL      int
	Limit    int
	Username string
	Password string

	pool *redis.Pool
}

func (ra *RedisAuth) Connect() {
	ra.pool = &redis.Pool{
		MaxIdle:     3,
		IdleTimeout: 240 * time.Second,
		Dial: func() (redis.Conn, error) {
			con, err := redis.Dial("tcp", ra.Address)
			if err != nil {
				return nil, err
			}
			return con, err
		},
		TestOnBorrow: func(con redis.Conn, t time.Time) error {
			_, err := con.Do("PING")
			return err
		},
	}
}

func (ra *RedisAuth) Handler() func(http.Handler) http.Handler {
	return Wrap(ra.handler, "Restricted")
}

func (ra *RedisAuth) handler(r *http.Request, opts []string) bool {
	authString := fmt.Sprintf("%s:%s", ra.Username, ra.Password)
	auth := r.Header.Get("Authorization")
	prefix := "Basic "
	if !strings.HasPrefix(auth, prefix) {
		return false
	}
	givenSecret := auth[len(prefix):]
	decodedSecret, err := base64.StdEncoding.DecodeString(givenSecret)
	if err != nil {
		return false
	}
	user := strings.Split(string(decodedSecret), ":")[0]

	blocked, err := ra.checkUser(user)
	if err != nil {
		return false
	}
	if blocked {
		log.Printf("%s is blocked", user)
		return false
	}

	p, err := decodePlainAuth(givenSecret)
	if err != nil || p != authString {
		log.Println("Failed to authorize", user)
		ra.failUser(user)
		return false
	}
	log.Println("Authorized", user)
	return true
}

func (ra *RedisAuth) checkUser(user string) (bool, error) {
	c := ra.pool.Get()
	defer c.Close()

	result, err := redis.Int(c.Do("GET", user))
	if err != nil {
		_, e := c.Do("SET", user, 0)
		if e != nil {
			return true, e
		}
		return true, nil
	}

	if result > ra.Limit {
		return true, nil
	}
	return false, nil
}

func (ra *RedisAuth) failUser(user string) error {
	c := ra.pool.Get()
	defer c.Close()

	c.Send("MULTI")
	c.Send("INCR", user)
	c.Send("EXPIRE", user, ra.TTL)
	_, err := c.Do("EXEC")
	return err
}

redpajama_set_name: RedPajamaGithub


text:
namespace bubblefs {
namespace mysimcc {

// Variant type that can hold Any other type
class Any {
public:
    Any() : content_(NULL) {}
    ~Any() {
        delete content_;
    }

    template<typename ValueType>
    explicit Any(const ValueType& value)
        : content_(new Holder<ValueType>(value)) {}

    Any(const Any& rhs)
        : content_(rhs.content_ ? rhs.content_->Clone() : NULL) {}

public:
    Any& swap(Any& rhs) {
        std::swap(content_, rhs.content_);
        return *this;
    }

    template<typename ValueType>
    Any& operator=(const ValueType& rhs) {
        Any(rhs).swap(*this);
        return*this;
    }

    Any& operator=(const Any& rhs) {
        Any(rhs).swap(*this);
        return*this;
    }

    bool IsEmpty() const {
        return !content_;
    }

    const std::type_info& GetType() const {
        return content_ ? content_->GetType() : typeid(void);
    }

    template<typename ValueType>
    ValueType operator()() const {
        if (GetType() == typeid(ValueType)) {
            return static_cast<Any::Holder<ValueType>*>(content_)->held_;
        } else {
            return ValueType();
        }
    }
protected:
    class PlaceHolder {
    public:
        virtual ~PlaceHolder() {}
    public:
        virtual const std::type_info& GetType() const = 0;
        virtual PlaceHolder* Clone() const = 0;
    };

    template<typename ValueType>
    class Holder : public PlaceHolder {
    public:
        Holder(const ValueType& value)
            : held_(value) {}

        virtual const std::type_info& GetType() const {
            return typeid(ValueType);
        }

        virtual PlaceHolder* Clone() const {
            return new Holder(held_);
        }

        ValueType held_;
    };

protected:
    PlaceHolder* content_;

    template<typename ValueType>
    friend ValueType* any_cast(Any*);
};

template<typename ValueType>
ValueType* any_cast(Any* any) {
    if (any && any->GetType() == typeid(ValueType)) {
        return &(static_cast<Any::Holder<ValueType>*>(any->content_)->held_);
    }

    return NULL;
}

template<typename ValueType>
const ValueType* any_cast(const Any* any) {
    return any_cast<ValueType>(const_cast<Any*>(any));
}

template<typename ValueType>
ValueType any_cast(const Any& any) {
    const ValueType* result = any_cast<ValueType>(&any);
    assert(result);

    if (!result) {
        return ValueType();
    }

    return *result;
}

} // namespace mysimcc
} // namespace bubblefs

#endif // BUBBLEFS_UTILS_SIMCC_ANY_H_


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Coryphantha vivipara var. kaibabensis P.C. Fischer

### Remarks
null


text:
package me.alexray.lagom.converters

import java.util.concurrent.CompletionStage

import scala.compat.java8.FutureConverters.CompletionStageOps
import scala.compat.java8.FutureConverters.FutureOps
import scala.concurrent.Future
import akka.NotUsed
import scala.concurrent.ExecutionContext.Implicits.global

import scala.language.implicitConversions

trait CompletionStageConverters {

  implicit def asCompletionStage[A](f: Future[A]): CompletionStage[A] = f.toJava
  implicit def asFuture[A](f: CompletionStage[A]): Future[A] = f.toScala

  implicit def asUnusedCompletionStage(f: CompletionStage[_]): CompletionStage[NotUsed] =
    f.map(_ => NotUsed.getInstance()).toJava
}

object CompletionStageConverters extends CompletionStageConverters


text:
<link href='http://fonts.googleapis.com/css?family=Headland+One|Open+Sans:400,300&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="http://labs.voronianski.com/media/style/reset.css">
<link rel="stylesheet" href="static/css/style.css">
<link rel="stylesheet" href="static/css/avgrund.css">

{% extends "template.html" %}
{% block content %}

{% for message in messages %}

{% endfor %}

Pomodoro Technique

Pomodoro Technique helps you plan your work in an efficient manner.

Enter the details for every task and click the "+" button to add one 25 minutes to your assignments.

When you are ready, click "Get To Work!" button to start.

"   "

	Get To Work!

    {% for m in messages_range %}

    {% endfor %}

{% endblock %}


text:
using Atlas.Core.Collections.Group;
using Atlas.ECS.Components.Component;
using Atlas.ECS.Systems;
using System;

namespace Atlas.ECS.Components.SystemManager
{
	public interface ISystemManager : IComponent<ISystemManager>
	{
		bool HasSystem(Type type);
		bool HasSystem<TKey>()
			where TKey : class, ISystem, new();

		bool AddSystem(Type type);
		bool AddSystem<TKey>()
			where TKey : class, ISystem, new();

		bool RemoveSystem(Type type);
		bool RemoveSystem<TKey>()
			where TKey : class, ISystem, new();
		bool RemoveSystems();

		IReadOnlyGroup<Type> Systems { get; }
	}
}


text:
try:
    import mayaHooks.override.dagMenuProc
    import pdil.tool.animDagMenu

    mayaHooks.override.dagMenuProc.callback_customDagMenu.register(pdil.tool.animDagMenu.animationSwitchMenu)

except Exception:
    import traceback
    print( traceback.format_exc() )
    print( "See above error text, something went wrong in userSetup.py" )


text:
class Bucket:

    """Class for Group, which is used to keep records
    Store tree node in instances.
    self.iloss: information loss of the whole group
    self.member: records in group
    self.value: group value
    self.level: tree level (top is 0)
    """

    def __init__(self, data_index, value = ('*'), level = ()):
        self.iloss = 0.0
        self.split_list = []
        self.member_index = data_index
        self.value = list(value)
        self.level = list(level)
        self.leftover = []
        self.splitable = True

    def merge_group(self, guest, middle):
        "merge guest into hostgourp"
        while guest.member_index:
            temp = guest.member_index.pop()
            self.member_index.append(temp)
        self.value = middle[:]

    def merge_record(self, rtemp, middle):
        "merge record into hostgourp"
        self.member_index.append(rtemp)
        self.value = middle[:]


text:
import xml.etree.cElementTree as ElementTree
import bz2
import gc

def parse(filename):
    def _connect():
        import psycopg2

        conn = psycopg2.connect("dbname='osmusers' host='localhost' user='osm' password='osm' options='-c log_min_messages=PANIC'")

        return conn

    def _get_information(name, attribute):
        if 'user' in attribute:
            username = attribute['user']
        else:
            username = 'anonymous'
        if 'uid' in attribute:
            uid = attribute['uid']
        else:
            uid = 0

        return uid, username

    connect = _connect()

    f = bz2.BZ2File(filename,'r')
    counter = 0
    data = iter(ElementTree.iterparse(f, events=('start', 'end')))

    event, root = data.next()

    for event, elem in data:
        if event == 'start' and elem.tag in ('node', 'way', 'relation'):
            uid, username = _get_information(elem.tag, elem.attrib)

            cursor = connect.cursor()
            try:
                cursor.execute("""INSERT INTO users (userid, username) VALUES (%s, %s);""", (uid, username))
                connect.commit()
            except:
                connect.rollback()
            cursor.close()
            del cursor

        if event == 'end':
            root.clear()


text:
"""
parse_operational.py

Created by Thomas Mangin on 2015-06-05.
Copyright (c) 2009-2015 Exa Networks. All rights reserved.
"""

from exabgp.configuration.core import Section

from exabgp.configuration.operational.parser import asm
from exabgp.configuration.operational.parser import adm
from exabgp.configuration.operational.parser import rpcq
from exabgp.configuration.operational.parser import rpcp
from exabgp.configuration.operational.parser import apcq
from exabgp.configuration.operational.parser import apcp
from exabgp.configuration.operational.parser import lpcq
from exabgp.configuration.operational.parser import lpcp

class ParseOperational (Section):
	syntax = \
		'syntax:\n' \
		''

	known = {
		'asm':  asm,
		'adm':  adm,
		'rpcq': rpcq,
		'rpcp': rpcp,
		'apcq': apcq,
		'apcp': apcp,
		'lpcq': lpcq,
		'lpcp': lpcp,
	}

	action = {
		'asm':  'append-name',
		'adm':  'append-name',
		'rpcq': 'append-name',
		'rpcp': 'append-name',
		'apcq': 'append-name',
		'apcp': 'append-name',
		'lpcq': 'append-name',
		'lpcp': 'append-name',
	}

	name = 'operational'

	def __init__ (self, tokeniser, scope, error, logger):
		Section.__init__(self,tokeniser,scope,error,logger)

	def clear (self):
		pass

	def pre (self):
		self.scope.to_context()
		return True

	def post (self):
		routes = self.scope.pop(self.name)
		if routes:
			self.scope.set('routes',routes)
		return True


text:
```console
usage: taiga-stats [-h] [-v] [--url URL] [--auth-token AUTH_TOKEN]
                   {config_template,list_projects,list_us_statuses,burnup,store_daily,points_sum,cfd,deps_dot_nodes,deps_dot}
                   ...

Taiga statistic tool. Default values for many options can be set config file;
see the command 'config_template'.

positional arguments:
  {config_template,list_projects,list_us_statuses,burnup,store_daily,points_sum,cfd,deps_dot_nodes,deps_dot}
                        Commands. Run $(taiga-stats <command> -h) for more
                        info about a command.
    config_template     Generate a template configuration file.
    list_projects       List all found project IDs and names on the server
                        that you have access to read.
    list_us_statuses    List all the ID and names of User Story statuses.
    burnup              Print burn(up|down) statistics. Typically used for
                        entering in an Excel sheet or such that plots a
                        burnup.
    store_daily         Store the current state of a project on file so that
                        the CFD command can generate a diagram with this data.
    points_sum          Print out the sum of points in User Story statuses.
    cfd                 Generate a Cumulative Flow Diagram from stored data.
    deps_dot_nodes      Print User Story nodes in .dot file format.
    deps_dot            Print US in .dot file format with dependencies too!
                        Create a custom attribute for User Stories named
                        'Depends On' by going to Settings>Attributes>Custom
                        Fields. Then go to a User Story and put in a comma
                        separated list of stories that this story depends on
                        e.g. '#123,#456'.

optional arguments:
  -h, --help            show this help message and exit
  -v, --version         show program's version number and exit
  --url URL             URL to Taiga server.
  --auth-token AUTH_TOKEN
                        Authentication token. Instructions on how to get one
                        is found at
                        https://docs.taiga.io/api.html#_authentication

Support: please go to https://github.com/erikw/taiga-stats/issues
```

Full documentation at [github.com/erikw/taiga-stats](https://github.com/erikw/taiga-stats).


text:
import { HttpModule } from '@angular/http';
import { TestBed, inject } from '@angular/core/testing';

import { AuthGuardService } from './auth-guard.service';
import { AuthenticationService } from 'app/user/authentication.service';
import { RouterTestingModule } from '@angular/router/testing';

describe('AuthGuardService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpModule, RouterTestingModule ],
      providers: [AuthGuardService, AuthenticationService]
    });
  });

  it('should be created', inject([AuthGuardService], (service: AuthGuardService) => {
    expect(service).toBeTruthy();
  }));
});


text:
package bob.sun.bender.utils;

import android.os.Environment;

/**
 * Created by bob.sun on 09/02/2017.
 */

public class AppConstants {

    public static final int RepeatAll       =   0x233;
    public static final int RepeatOne       =   0x234;
    public static final int RepeatNone      =   0x235;

    //Theme
    public static final int ThemeShapeOval    = 0;
    public static final int ThemeShapeRect    = 1;
    public static final int ThemeShapePolygon = 2;

    public static final String pref_tag = "mpod_app_settings";
    public static final String kShuffle = "mpod_app_settings.key.shuffle";
    public static final String kRepeat = "mpod_app_settings.key.repeat";

    public static final String broadcastSongChange = "sun.bob.bender.songchanged";
    public static final String broadcastPermission = "sun.bob.bender.allow_broadcast";

    private static final String playlistfile = "/data/data/bob.sun.bender/playlistobject";
    private static final String packageFolder = "/data/data/bob.sun.bender/";

    public static final String themeFolder = "/data/Prodigal/Themes/";

    public static String getPlayistfile() {
        return Environment.getExternalStorageDirectory().getPath() + playlistfile;
    }

    public static String getExtFolder() {
        return Environment.getExternalStorageDirectory().getPath() + packageFolder;
    }

}


text:
namespace Envoy {
namespace Extensions {
namespace Wasm {

using Extensions::Bootstrap::Wasm::WasmServicePtr;

class WasmFactoryTest : public testing::TestWithParam<std::string> {
protected:
  WasmFactoryTest() {
    config_.mutable_config()->mutable_vm_config()->set_runtime(
        absl::StrCat("envoy.wasm.runtime.", GetParam()));
    if (GetParam() != "null") {
      config_.mutable_config()->mutable_vm_config()->mutable_code()->mutable_local()->set_filename(
          TestEnvironment::substitute(
              "{{ test_rundir }}/test/extensions/bootstrap/wasm/test_data/start_cpp.wasm"));
    } else {
      config_.mutable_config()
          ->mutable_vm_config()
          ->mutable_code()
          ->mutable_local()
          ->set_inline_bytes("WasmStartCpp");
    }
    config_.mutable_config()->set_name("test");
    config_.set_singleton(true);
  }

  void initializeWithConfig(const envoy::extensions::wasm::v3::WasmService& config) {
    auto factory =
        Registry::FactoryRegistry<Server::Configuration::BootstrapExtensionFactory>::getFactory(
            "envoy.bootstrap.wasm");
    ASSERT_NE(factory, nullptr);
    api_ = Api::createApiForTest(stats_store_);
    EXPECT_CALL(context_, api()).WillRepeatedly(testing::ReturnRef(*api_));
    EXPECT_CALL(context_, initManager()).WillRepeatedly(testing::ReturnRef(init_manager_));
    EXPECT_CALL(context_, lifecycleNotifier())
        .WillRepeatedly(testing::ReturnRef(lifecycle_notifier_));
    extension_ = factory->createBootstrapExtension(config, context_);
    static_cast<Bootstrap::Wasm::WasmServiceExtension*>(extension_.get())->wasmService();
    EXPECT_CALL(init_watcher_, ready());
    init_manager_.initialize(init_watcher_);
  }

  envoy::extensions::wasm::v3::WasmService config_;
  testing::NiceMock<Server::Configuration::MockServerFactoryContext> context_;
  testing::NiceMock<Server::MockServerLifecycleNotifier> lifecycle_notifier_;
  Init::ExpectableWatcherImpl init_watcher_;
  Stats::IsolatedStoreImpl stats_store_;
  Api::ApiPtr api_;
  Init::ManagerImpl init_manager_{"init_manager"};
  Server::BootstrapExtensionPtr extension_;
};

// NB: this is required by VC++ which can not handle the use of macros in the macro definitions
// used by INSTANTIATE_TEST_SUITE_P.
auto testing_values = testing::Values(
#if defined(ENVOY_WASM_V8)
    "v8",
#endif
#if defined(ENVOY_WASM_WAVM)
    "wavm",
#endif
    "null");
INSTANTIATE_TEST_SUITE_P(Runtimes, WasmFactoryTest, testing_values);

TEST_P(WasmFactoryTest, CreateWasmFromWasm) {
  auto factory = std::make_unique<Bootstrap::Wasm::WasmFactory>();
  auto empty_config = factory->createEmptyConfigProto();

  initializeWithConfig(config_);

  EXPECT_NE(extension_, nullptr);
}

TEST_P(WasmFactoryTest, CreateWasmFromWasmPerThread) {
  config_.set_singleton(false);
  initializeWithConfig(config_);

  EXPECT_NE(extension_, nullptr);
  extension_.reset();
  context_.threadLocal().shutdownThread();
}

TEST_P(WasmFactoryTest, MissingImport) {
  if (GetParam() == "null") {
    return;
  }
  config_.mutable_config()->mutable_vm_config()->mutable_code()->mutable_local()->set_filename(
      TestEnvironment::substitute(
          "{{ test_rundir }}/test/extensions/bootstrap/wasm/test_data/missing_cpp.wasm"));
  EXPECT_THROW_WITH_MESSAGE(initializeWithConfig(config_), Extensions::Common::Wasm::WasmException,
                            "Unable to create Wasm service test");
}

TEST_P(WasmFactoryTest, UnspecifiedRuntime) {
  config_.mutable_config()->mutable_vm_config()->set_runtime("");

  EXPECT_THROW_WITH_REGEX(
      initializeWithConfig(config_), EnvoyException,
      "Proto constraint validation failed \\(WasmServiceValidationError\\.Config");
}

TEST_P(WasmFactoryTest, UnknownRuntime) {
  config_.mutable_config()->mutable_vm_config()->set_runtime("envoy.wasm.runtime.invalid");

  EXPECT_THROW_WITH_MESSAGE(initializeWithConfig(config_), Extensions::Common::Wasm::WasmException,
                            "Unable to create Wasm service test");
}

TEST_P(WasmFactoryTest, StartFailed) {
  ProtobufWkt::StringValue plugin_configuration;
  plugin_configuration.set_value("bad");
  config_.mutable_config()->mutable_vm_config()->mutable_configuration()->PackFrom(
      plugin_configuration);

  EXPECT_THROW_WITH_MESSAGE(initializeWithConfig(config_), Extensions::Common::Wasm::WasmException,
                            "Unable to create Wasm service test");
}

TEST_P(WasmFactoryTest, StartFailedOpen) {
  ProtobufWkt::StringValue plugin_configuration;
  plugin_configuration.set_value("bad");
  config_.mutable_config()->mutable_vm_config()->mutable_configuration()->PackFrom(
      plugin_configuration);
  config_.mutable_config()->set_fail_open(true);

  EXPECT_THROW_WITH_MESSAGE(initializeWithConfig(config_), Extensions::Common::Wasm::WasmException,
                            "Unable to create Wasm service test");
}

TEST_P(WasmFactoryTest, ConfigureFailed) {
  ProtobufWkt::StringValue plugin_configuration;
  plugin_configuration.set_value("bad");
  config_.mutable_config()->mutable_configuration()->PackFrom(plugin_configuration);

  EXPECT_THROW_WITH_MESSAGE(initializeWithConfig(config_), Extensions::Common::Wasm::WasmException,
                            "Unable to create Wasm service test");
}

} // namespace Wasm
} // namespace Extensions
} // namespace Envoy


text:
package io.druid.indexing.common.task;

import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import io.druid.indexing.common.TaskStatus;
import io.druid.indexing.common.TaskToolbox;
import io.druid.indexing.common.actions.TaskActionClient;
import io.druid.query.Query;
import io.druid.query.QueryRunner;

import java.util.Map;

/**
 * Represents a task that can run on a worker. The general contracts surrounding Tasks are:
 *

 *
Tasks must operate on a single datasource.

 *
Tasks should be immutable, since the task ID is used as a proxy for the task in many locations.

 *
Task IDs must be unique. This can be done by naming them using UUIDs or the current timestamp.

 *
Tasks are each part of a "task group", which is a set of tasks that can share interval locks. These are
 * useful for producing sharded segments.

 *
Tasks do not need to explicitly release locks; they are released upon task completion. Tasks may choose
 * to release locks early if they desire.

 *

 */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes(value = {
    @JsonSubTypes.Type(name = "append", value = AppendTask.class),
    @JsonSubTypes.Type(name = "merge", value = MergeTask.class),
    @JsonSubTypes.Type(name = "kill", value = KillTask.class),
    @JsonSubTypes.Type(name = "move", value = MoveTask.class),
    @JsonSubTypes.Type(name = "archive", value = ArchiveTask.class),
    @JsonSubTypes.Type(name = "restore", value = RestoreTask.class),
    @JsonSubTypes.Type(name = "index", value = IndexTask.class),
    @JsonSubTypes.Type(name = "index_hadoop", value = HadoopIndexTask.class),
    @JsonSubTypes.Type(name = "hadoop_convert_segment", value = HadoopConverterTask.class),
    @JsonSubTypes.Type(name = "hadoop_convert_segment_sub", value = HadoopConverterTask.ConverterSubTask.class),
    @JsonSubTypes.Type(name = "index_realtime", value = RealtimeIndexTask.class),
    @JsonSubTypes.Type(name = "noop", value = NoopTask.class),
    @JsonSubTypes.Type(name = "version_converter", value = ConvertSegmentBackwardsCompatibleTask.class), // Backwards compat - Deprecated
    @JsonSubTypes.Type(name = "version_converter_sub", value = ConvertSegmentBackwardsCompatibleTask.SubTask.class), // backwards compat - Deprecated
    @JsonSubTypes.Type(name = "convert_segment", value = ConvertSegmentTask.class),
    @JsonSubTypes.Type(name = "convert_segment_sub", value = ConvertSegmentTask.SubTask.class)
})
public interface Task
{
  /**
   * Returns ID of this task. Must be unique across all tasks ever created.
   *
   * @return task ID
   */
  public String getId();

  /**
   * Returns group ID of this task. Tasks with the same group ID can share locks. If tasks do not need to share locks,
   * a common convention is to set group ID equal to task ID.
   *
   * @return task group ID
   */
  public String getGroupId();

  /**
   * Returns a {@link io.druid.indexing.common.task.TaskResource} for this task. Task resources define specific
   * worker requirements a task may require.
   *
   * @return {@link io.druid.indexing.common.task.TaskResource} for this task
   */
  public TaskResource getTaskResource();

  /**
   * Returns a descriptive label for this task type. Used for metrics emission and logging.
   *
   * @return task type label
   */
  public String getType();

  /**
   * Get the nodeType for if/when this task publishes on zookeeper.
   *
   * @return the nodeType to use when publishing the server to zookeeper. null if the task doesn't expect to
   * publish to zookeeper.
   */
  public String getNodeType();

  /**
   * Returns the datasource this task operates on. Each task can operate on only one datasource.
   */
  public String getDataSource();

  /**
   * Returns query runners for this task. If this task is not meant to answer queries over its datasource, this method
   * should return null.
   *
   * @param <T> query result type
   *
   * @return query runners for this task
   */
  public <T> QueryRunner<T> getQueryRunner(Query<T> query);

  /**
   * Returns an extra classpath that should be prepended to the default classpath when running this task. If no
   * extra classpath should be prepended, this should return null or the empty string.
   */
  public String getClasspathPrefix();

  /**
   * Execute preflight actions for a task. This can be used to acquire locks, check preconditions, and so on. The
   * actions must be idempotent, since this method may be executed multiple times. This typically runs on the
   * coordinator. If this method throws an exception, the task should be considered a failure.
   *

   * This method must be idempotent, as it may be run multiple times per task.
   *
   * @param taskActionClient action client for this task (not the full toolbox)
   *
   * @return true if ready, false if not ready yet
   *
   * @throws Exception if the task should be considered a failure
   */
  public boolean isReady(TaskActionClient taskActionClient) throws Exception;

  /**
   * Returns whether or not this task can restore its progress from its on-disk working directory. Restorable tasks
   * may be started with a non-empty working directory. Tasks that exit uncleanly may still have a chance to attempt
   * restores, meaning that restorable tasks should be able to deal with potentially partially written on-disk state.
   */
  public boolean canRestore();

  /**
   * Asks a task to arrange for its "run" method to exit promptly. This method will only be called if
   * {@link #canRestore()} returns true. Tasks that take too long to stop gracefully will be terminated with
   * extreme prejudice.
   */
  public void stopGracefully();

  /**
   * Execute a task. This typically runs on a worker as determined by a TaskRunner, and will be run while
   * holding a lock on our dataSource and implicit lock interval (if any). If this method throws an exception, the task
   * should be considered a failure.
   *
   * @param toolbox Toolbox for this task
   *
   * @return Some kind of finished status (isRunnable must be false).
   *
   * @throws Exception if this task failed
   */
  public TaskStatus run(TaskToolbox toolbox) throws Exception;

  public Map<String, Object> getContext();

  public Object getContextValue(String key);

}


text:
from setuptools import find_packages
from setuptools import setup

REQUIRED_PACKAGES = [
    'nltk>=3.3',
    'typed_ast==1.3.2',
    'tensorflow-hub==0.1.1',
    'bert-tensorflow==1.0.1'
]

setup(
    name='tf_trainer',
    version='0.1',
    install_requires=REQUIRED_PACKAGES,
    packages=find_packages(),
    include_package_data=True,
    description='TF Estimator modelling framework.')


text:
--- include/util.h.orig	2018-08-30 18:48:15 UTC
+++ include/util.h
@@ -53,11 +53,15 @@
 	typedef void (*exitfn_ptr) (int,void*);
 	int on_exit( exitfn_ptr exitfn, void* data) ;
 #endif
-#define malloc(s) use_btmalloc_instead
-#define calloc(n,s) use_btcalloc_instead
-#define realloc(p,s) use_btrealloc_instead
+/*
+ #define malloc(s) use_btmalloc_instead
+ #define calloc(n,s) use_btcalloc_instead
+ #define realloc(p,s) use_btrealloc_instead
+/*
 #undef free
+/*
 #define free(p) use_btfree_instead
+*/

 void hexdump( void *buf, int buflen);


text:
"""
Support for Rflink sensors.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.rflink/
"""
import logging

import voluptuous as vol

from homeassistant.components.rflink import (
    CONF_ALIASES, CONF_ALIASSES, CONF_AUTOMATIC_ADD, CONF_DEVICES,
    DATA_DEVICE_REGISTER, DATA_ENTITY_LOOKUP, EVENT_KEY_ID,
    EVENT_KEY_SENSOR, EVENT_KEY_UNIT, RflinkDevice, remove_deprecated,
    SIGNAL_AVAILABILITY, SIGNAL_HANDLE_EVENT, TMP_ENTITY)
from homeassistant.components.sensor import (
    PLATFORM_SCHEMA)
import homeassistant.helpers.config_validation as cv
from homeassistant.const import (
    ATTR_UNIT_OF_MEASUREMENT, CONF_NAME, CONF_UNIT_OF_MEASUREMENT)
from homeassistant.helpers.dispatcher import (async_dispatcher_connect)

DEPENDENCIES = ['rflink']

_LOGGER = logging.getLogger(__name__)

SENSOR_ICONS = {
    'humidity': 'mdi:water-percent',
    'battery': 'mdi:battery',
    'temperature': 'mdi:thermometer',
}

CONF_SENSOR_TYPE = 'sensor_type'

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Optional(CONF_AUTOMATIC_ADD, default=True): cv.boolean,
    vol.Optional(CONF_DEVICES, default={}): {
        cv.string: vol.Schema({
            vol.Optional(CONF_NAME): cv.string,
            vol.Required(CONF_SENSOR_TYPE): cv.string,
            vol.Optional(CONF_UNIT_OF_MEASUREMENT): cv.string,
            vol.Optional(CONF_ALIASES, default=[]):
                vol.All(cv.ensure_list, [cv.string]),
            # deprecated config options
            vol.Optional(CONF_ALIASSES):
                vol.All(cv.ensure_list, [cv.string]),
        })
    },
}, extra=vol.ALLOW_EXTRA)

def lookup_unit_for_sensor_type(sensor_type):
    """Get unit for sensor type.

    Async friendly.
    """
    from rflink.parser import UNITS, PACKET_FIELDS
    field_abbrev = {v: k for k, v in PACKET_FIELDS.items()}

    return UNITS.get(field_abbrev.get(sensor_type))

def devices_from_config(domain_config):
    """Parse configuration and add Rflink sensor devices."""
    devices = []
    for device_id, config in domain_config[CONF_DEVICES].items():
        if ATTR_UNIT_OF_MEASUREMENT not in config:
            config[ATTR_UNIT_OF_MEASUREMENT] = lookup_unit_for_sensor_type(
                config[CONF_SENSOR_TYPE])
        remove_deprecated(config)
        device = RflinkSensor(device_id, **config)
        devices.append(device)

    return devices

async def async_setup_platform(hass, config, async_add_entities,
                               discovery_info=None):
    """Set up the Rflink platform."""
    async_add_entities(devices_from_config(config))

    async def add_new_device(event):
        """Check if device is known, otherwise create device entity."""
        device_id = event[EVENT_KEY_ID]

        device = RflinkSensor(device_id, event[EVENT_KEY_SENSOR],
                              event[EVENT_KEY_UNIT], initial_event=event)
        # Add device entity
        async_add_entities([device])

    if config[CONF_AUTOMATIC_ADD]:
        hass.data[DATA_DEVICE_REGISTER][EVENT_KEY_SENSOR] = add_new_device

class RflinkSensor(RflinkDevice):
    """Representation of a Rflink sensor."""

    def __init__(self, device_id, sensor_type, unit_of_measurement,
                 initial_event=None, **kwargs):
        """Handle sensor specific args and super init."""
        self._sensor_type = sensor_type
        self._unit_of_measurement = unit_of_measurement
        super().__init__(device_id, initial_event=initial_event, **kwargs)

    def _handle_event(self, event):
        """Domain specific event handler."""
        self._state = event['value']

    async def async_added_to_hass(self):
        """Register update callback."""
        # Remove temporary bogus entity_id if added
        tmp_entity = TMP_ENTITY.format(self._device_id)
        if tmp_entity in self.hass.data[DATA_ENTITY_LOOKUP][
                EVENT_KEY_SENSOR][self._device_id]:
            self.hass.data[DATA_ENTITY_LOOKUP][
                EVENT_KEY_SENSOR][self._device_id].remove(tmp_entity)

        # Register id and aliases
        self.hass.data[DATA_ENTITY_LOOKUP][
            EVENT_KEY_SENSOR][self._device_id].append(self.entity_id)
        if self._aliases:
            for _id in self._aliases:
                self.hass.data[DATA_ENTITY_LOOKUP][
                    EVENT_KEY_SENSOR][_id].append(self.entity_id)
        async_dispatcher_connect(self.hass, SIGNAL_AVAILABILITY,
                                 self._availability_callback)
        async_dispatcher_connect(self.hass,
                                 SIGNAL_HANDLE_EVENT.format(self.entity_id),
                                 self.handle_event_callback)

        # Process the initial event now that the entity is created
        if self._initial_event:
            self.handle_event_callback(self._initial_event)

    @property
    def unit_of_measurement(self):
        """Return measurement unit."""
        return self._unit_of_measurement

    @property
    def state(self):
        """Return value."""
        return self._state

    @property
    def icon(self):
        """Return possible sensor specific icon."""
        if self._sensor_type in SENSOR_ICONS:
            return SENSOR_ICONS[self._sensor_type]


text:
package br.gov.servicos.busca;

import br.gov.servicos.cms.Conteudo;
import lombok.experimental.FieldDefaults;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.FacetedPageImpl;

import static br.gov.servicos.fixtures.TestData.CONTEUDO;
import static java.util.Collections.singletonList;
import static java.util.Optional.of;
import static java.util.Optional.ofNullable;
import static lombok.AccessLevel.PRIVATE;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.verify;
import static org.springframework.test.web.ModelAndViewAssert.assertModelAttributeValue;
import static org.springframework.test.web.ModelAndViewAssert.assertViewName;

@RunWith(MockitoJUnitRunner.class)
@FieldDefaults(level = PRIVATE)
public class BuscaControllerTest {

    @Mock
    BuscadorConteudo buscador;

    Page<Conteudo> umConteudo = new FacetedPageImpl<>(singletonList(CONTEUDO));
    BuscaController controller;

    @Before
    public void setUp() {
        controller = new BuscaController(buscador);
    }

    @Test
    public void buscaRedirecionaParaPaginaDeResultados() {
        assertViewName(controller.busca(null, 1), "resultados-busca");
    }

    @Test
    public void buscaRetornaTermoBuscado() {
        assertModelAttributeValue(controller.busca("trabalho", 1), "termo", "trabalho");
    }

    @Test
    public void buscaRetornaResultadosParaAPagina() {
        doReturn(umConteudo)
                .when(buscador)
                .busca(of("emprego"), 0);

        assertModelAttributeValue(controller.busca("emprego", 1), "resultados", umConteudo);
    }

    @Test
    public void deveUsarBase0AoBuscarResultadosPaginados() {
        controller.busca("qualquer servico", 20);
        verify(buscador).busca(of("qualquer servico"), 19);
    }

    @Test
    public void retornaSugestoesDeBusca() throws Exception {
        doReturn(singletonList(CONTEUDO.withNome("Seguro-desemprego")))
                .when(buscador)
                .buscaSemelhante(ofNullable("empreg"));

        String sugestao = controller.sugestao("empreg");

        assertThat(sugestao, is("[\"empreg\", [\"Seguro-desemprego\"]]"));
    }

    @Test
    public void deveExibirXmlDoOpenSearch() {
        assertThat(controller.openSearch().getViewName(), is("opensearch"));
    }

    @Test
    public void deveRedirecionarEmUrlsDeBuscaLegada() {
        assertThat(controller.search("blah"), is("redirect:/busca?q=blah"));
    }
}


text:
using System.Diagnostics;
using GitLabCLI.Core;

namespace GitLabCLI.Console
{
    public sealed class BrowserProcessStarter : IBrowser
    {
        public void Open(string url)
        {
            Process.Start(new ProcessStartInfo(url)
            {
                UseShellExecute = true
            });
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
J. Indian bot. Soc. 54(1-2): 50 (1975)

#### Original name
Macrophoma cannae-indicae N.D. Sharma

### Remarks
null


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.01.29 at 11:21:24 PM IST
//

package in.imcod.whitebear.stub;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="Fields">
 *           <complexType>
 *             <complexContent>
 *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                 <sequence>
 *                   <element name="Field" maxOccurs="unbounded">
 *                     <complexType>
 *                       <complexContent>
 *                         <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                           <sequence>
 *                             <element name="Value" maxOccurs="unbounded" minOccurs="0">
 *                               <complexType>
 *                                 <simpleContent>
 *                                   <extension base="<http://www.w3.org/2001/XMLSchema>string">
 *                                     <attribute name="ReferenceValue" type="{http://www.w3.org/2001/XMLSchema}string" />
 *                                   </extension>
 *                                 </simpleContent>
 *                               </complexType>
 *                             </element>
 *                           </sequence>
 *                           <attribute name="Name" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
 *                         </restriction>
 *                       </complexContent>
 *                     </complexType>
 *                   </element>
 *                 </sequence>
 *               </restriction>
 *             </complexContent>
 *           </complexType>
 *         </element>
 *       </sequence>
 *       <attribute name="Type" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "fields"
})
@XmlRootElement(name = "Entity")
public class Entity {

    @XmlElement(name = "Fields", required = true)
    protected Entity.Fields fields;
    @XmlAttribute(name = "Type", required = true)
    protected String type;

    /**
     * Gets the value of the fields property.
     *
     * @return
     *     possible object is
     *     {@link Entity.Fields }
     *
     */
    public Entity.Fields getFields() {
        return fields;
    }

    /**
     * Sets the value of the fields property.
     *
     * @param value
     *     allowed object is
     *     {@link Entity.Fields }
     *
     */
    public void setFields(Entity.Fields value) {
        this.fields = value;
    }

    /**
     * Gets the value of the type property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getType() {
        return type;
    }

    /**
     * Sets the value of the type property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setType(String value) {
        this.type = value;
    }

    /**
     *
Java class for anonymous complex type.
     *
     *
The following schema fragment specifies the expected content contained within this class.
     *
     *

     * <complexType>
     *   <complexContent>
     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *       <sequence>
     *         <element name="Field" maxOccurs="unbounded">
     *           <complexType>
     *             <complexContent>
     *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *                 <sequence>
     *                   <element name="Value" maxOccurs="unbounded" minOccurs="0">
     *                     <complexType>
     *                       <simpleContent>
     *                         <extension base="<http://www.w3.org/2001/XMLSchema>string">
     *                           <attribute name="ReferenceValue" type="{http://www.w3.org/2001/XMLSchema}string" />
     *                         </extension>
     *                       </simpleContent>
     *                     </complexType>
     *                   </element>
     *                 </sequence>
     *                 <attribute name="Name" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
     *               </restriction>
     *             </complexContent>
     *           </complexType>
     *         </element>
     *       </sequence>
     *     </restriction>
     *   </complexContent>
     * </complexType>
     *

     *
     *
     */
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
        "field"
    })
    public static class Fields {

        @XmlElement(name = "Field", required = true)
        protected List<Entity.Fields.Field> field;

        /**
         * Gets the value of the field property.
         *
         *

         * This accessor method returns a reference to the live list,
         * not a snapshot. Therefore any modification you make to the
         * returned list will be present inside the JAXB object.
         * This is why there is not a set method for the field property.
         *
         *

         * For example, to add a new item, do as follows:
         *

         *    getField().add(newItem);
         *

         *
         *
         *

         * Objects of the following type(s) are allowed in the list
         * {@link Entity.Fields.Field }
         *
         *
         */
        public List<Entity.Fields.Field> getField() {
            if (field == null) {
                field = new ArrayList<Entity.Fields.Field>();
            }
            return this.field;
        }

        /**
         *
Java class for anonymous complex type.
         *
         *
The following schema fragment specifies the expected content contained within this class.
         *
         *

         * <complexType>
         *   <complexContent>
         *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
         *       <sequence>
         *         <element name="Value" maxOccurs="unbounded" minOccurs="0">
         *           <complexType>
         *             <simpleContent>
         *               <extension base="<http://www.w3.org/2001/XMLSchema>string">
         *                 <attribute name="ReferenceValue" type="{http://www.w3.org/2001/XMLSchema}string" />
         *               </extension>
         *             </simpleContent>
         *           </complexType>
         *         </element>
         *       </sequence>
         *       <attribute name="Name" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
         *     </restriction>
         *   </complexContent>
         * </complexType>
         *

         *
         *
         */
        @XmlAccessorType(XmlAccessType.FIELD)
        @XmlType(name = "", propOrder = {
            "value"
        })
        public static class Field {

            @XmlElement(name = "Value")
            protected List<Entity.Fields.Field.Value> value;
            @XmlAttribute(name = "Name", required = true)
            protected String name;

            /**
             * Gets the value of the value property.
             *
             *

             * This accessor method returns a reference to the live list,
             * not a snapshot. Therefore any modification you make to the
             * returned list will be present inside the JAXB object.
             * This is why there is not a set method for the value property.
             *
             *

             * For example, to add a new item, do as follows:
             *

             *    getValue().add(newItem);
             *

             *
             *
             *

             * Objects of the following type(s) are allowed in the list
             * {@link Entity.Fields.Field.Value }
             *
             *
             */
            public List<Entity.Fields.Field.Value> getValue() {
                if (value == null) {
                    value = new ArrayList<Entity.Fields.Field.Value>();
                }
                return this.value;
            }

            /**
             * Gets the value of the name property.
             *
             * @return
             *     possible object is
             *     {@link String }
             *
             */
            public String getName() {
                return name;
            }

            /**
             * Sets the value of the name property.
             *
             * @param value
             *     allowed object is
             *     {@link String }
             *
             */
            public void setName(String value) {
                this.name = value;
            }

            /**
             *
Java class for anonymous complex type.
             *
             *
The following schema fragment specifies the expected content contained within this class.
             *
             *

             * <complexType>
             *   <simpleContent>
             *     <extension base="<http://www.w3.org/2001/XMLSchema>string">
             *       <attribute name="ReferenceValue" type="{http://www.w3.org/2001/XMLSchema}string" />
             *     </extension>
             *   </simpleContent>
             * </complexType>
             *

             *
             *
             */
            @XmlAccessorType(XmlAccessType.FIELD)
            @XmlType(name = "", propOrder = {
                "value"
            })
            public static class Value {

                @XmlValue
                protected String value;
                @XmlAttribute(name = "ReferenceValue")
                protected String referenceValue;

                /**
                 * Gets the value of the value property.
                 *
                 * @return
                 *     possible object is
                 *     {@link String }
                 *
                 */
                public String getValue() {
                    return value;
                }

                /**
                 * Sets the value of the value property.
                 *
                 * @param value
                 *     allowed object is
                 *     {@link String }
                 *
                 */
                public void setValue(String value) {
                    this.value = value;
                }

                /**
                 * Gets the value of the referenceValue property.
                 *
                 * @return
                 *     possible object is
                 *     {@link String }
                 *
                 */
                public String getReferenceValue() {
                    return referenceValue;
                }

                /**
                 * Sets the value of the referenceValue property.
                 *
                 * @param value
                 *     allowed object is
                 *     {@link String }
                 *
                 */
                public void setReferenceValue(String value) {
                    this.referenceValue = value;
                }

            }

        }

    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

        <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <TITLE>
            Uses of Class org.apache.commons.cli.Parser (Commons CLI 1.2 API)
        </TITLE>

        <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

                            Package
                            Class
                          Use
                            Tree
                            Deprecated
                            Index
                            Help

                     PREV
                     NEXT

                    FRAMES
                     NO FRAMES

                        All Classes

            Uses of Class
org.apache.commons.cli.Parser

                    Uses of Parser in org.apache.commons.cli

            Subclasses of Parser in org.apache.commons.cli

                     class
            BasicParser

                          The class BasicParser provides a very simple implementation of
                the flatten method.

                     class
            GnuParser

                          The class GnuParser provides an implementation of the
                flatten method.

                     class
            PosixParser

                          The class PosixParser provides an implementation of the
                flatten method.

                            Package
                            Class
                          Use
                            Tree
                            Deprecated
                            Index
                            Help

                     PREV
                     NEXT

                    FRAMES
                     NO FRAMES

                        All Classes

    Copyright © 2002-2009 The Apache Software Foundation. All Rights Reserved.


text:
using System.Collections.Generic;
using Azure.Core;
using Azure.ResourceManager.OperationalInsights;

namespace Azure.ResourceManager.OperationalInsights.Models
{
    /// <summary> The list linked service operation response. </summary>
    internal partial class LinkedServiceListResult
    {
        /// <summary> Initializes a new instance of LinkedServiceListResult. </summary>
        internal LinkedServiceListResult()
        {
            Value = new ChangeTrackingList<LinkedServiceData>();
        }

        /// <summary> Initializes a new instance of LinkedServiceListResult. </summary>
        /// <param name="value"> The list of linked service instances. </param>
        internal LinkedServiceListResult(IReadOnlyList<LinkedServiceData> value)
        {
            Value = value;
        }

        /// <summary> The list of linked service instances. </summary>
        public IReadOnlyList<LinkedServiceData> Value { get; }
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!--
  ~ Copyright (c) 2016 Haulmont
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<window xmlns="http://schemas.haulmont.com/cuba/screen/window.xsd" caption="msg://editCaption"
        focusComponent="form"
        messagesPack="com.haulmont.timesheets.gui.holiday">
    <data>
        <instance id="holidayDc" class="com.haulmont.timesheets.entity.Holiday" view="_local">
            <loader/>
        </instance>
    </data>
    <dialogMode width="AUTO" height="AUTO"/>
    <layout expand="editActions" spacing="true">
        <form id="form" dataContainer="holidayDc">
            <column width="250px">
                <textField id="name" property="name"/>
                <dateField id="startDate" property="startDate"/>
                <dateField id="endDate" property="endDate"/>
                <resizableTextArea id="description"  height="100px" resizable="true" property="description"/>
            </column>
        </form>
        <hbox id="editActions" spacing="true">
            <button action="windowCommitAndClose"/>
            <button action="windowClose"/>
        </hbox>
    </layout>
</window>


text:
require 'net/telnet'

require 'irrc/connecting'
require 'irrc/logging'
require 'irrc/parameter'
require 'irrc/prefix'
require 'irrc/runner'
require 'irrc/socket'
require 'irrc/whoisd/api'

module Irrc
  module Whoisd

    # Public: Whoisd client worker.
    class Client
      include Irrc::Connecting
      include Irrc::Logging
      include Irrc::Parameter
      include Irrc::Prefix
      include Irrc::Runner
      include Irrc::Whoisd::Api

      private

      def process(query)
        case query.object_type
        when 'as-set'
          expand_set query, 'as-set'
        when 'route-set'
          expand_set query, 'route-set'
        when 'aut-num'
          expand_aut_num query
        end

        query
      end

      # Public: Expand an as-set or route-set object into any object.
      def expand_set(query, type)
        result = cache(query.object, query.sources) {
          begin
            command = expand_set_command(query.object, query.sources, type)
            execute(command)
          rescue
            raise "'#{command}' failed on '#{@fqdn}' (#{$!.message})."
          end
        }

        parse_objects_from_set(result).each do |object|
          next if query.ancestor_object?(object)

          child = query.fork(object)

          case child.object_type
          when 'aut-num'
            query.add_aut_num_result object
          when nil  # it looks prefix which is a member of route-set
            prefix = classify_by_protocol(object)
            query.protocols.each do |protocol|
              query.add_prefix_result prefix[protocol], nil, protocol
            end
          end
        end
      end

      # Public: Expand an aut-num object into routes
      def expand_aut_num(query)
        return if query.protocols.empty?

        result = cache(query.object, query.sources) {
          begin
            command = expand_aut_num_command(query.object, query.sources)
            execute(command)
          rescue
            raise "'#{command}' failed on '#{@fqdn}' (#{$!.message})."
          end
        }

        query.protocols.each do |protocol|
          query.add_prefix_result parse_prefixes_from_aut_num(result, protocol), query.object, protocol
        end
      end
    end
  end
end


text:
Nez Persistence: JSON
==========

## Description

A little JSON library that does big things.

## Features

* Transmogrify objects into JSON and back again.
* Uses reflection to dump and load object graphs automagically.
* Supports object graphs with references preserved.
* Supports primitives, classes, structs, enums, lists, dictionaries and arrays.
* Supports single dimensional arrays, multidimensional arrays and jagged arrays.
* Polymorphic classes supported with a type hint encoded into the JSON automatically.
* Supports optionally pretty printing JSON output.
* Supports optionally encoding properties and private fields (via the `JsonIncludeAttribute` on them).
* Supports optionally excluding public fields (via the `JsonExcludeAttribute` on them)
* Supports decoding fields and properties from aliased names.
* Unit tested.

## Usage

The API is namespaced under `Nez.Persistence` and the primary class is `Json`. There are really only a few methods you need to know:

```csharp
namespace Nez.Persistence
{
	public static class Json
	{
		public static string ToJson( object obj, JsonSettings options = null )
		public static object FromJson( string json, JsonSettings settings = null )
		public static void FromJsonOverwrite( string json, object item )
	}
}
```

`ToJson()` will take a C# object, list, dictionary or primitive value type and turn it into JSON.

```csharp
var data = new List<int>() { { 0 }, { 1 }, { 2 } };
Console.WriteLine( Json.ToJson( data ) ); // output: [1,2,3]
```

`FromJson()` will load a string of JSON, returns `null` if invalid or an object if successful.

```csharp
var data = Json.FromJson( "{\"foo\": 1, \"bar\": 2.34}" ) as IDictionary;
var i = Convert.ToInt32( data["foo"] );
var f = Convert.ToSingle( data["bar"] );
```

`FromJson<T>()` will load a string of JSON, returns `null` if invalid or a an object of type `T` if successful.

```csharp
var obj = Json.FromJson<SomeClass>( json );
```

Json can also handle classes, structs, enums and nested objects. Given these definitions:

```csharp
enum TestEnum
{
	Thing1,
	Thing2,
	Thing3
}

struct TestStruct
{
	public int x;
	public int y;
}

class TestClass
{
	public string name;
	public TestEnum type;
	public List<TestStruct> data = new List<TestStruct>();

	[JsonExclude]
	public int _ignored;

	[BeforeEncode]
	public void BeforeEncode()
	{
		Console.WriteLine( "BeforeEncode callback fired!" );
	}

	[AfterDecode]
	public void AfterDecode()
	{
		Console.WriteLine( "AfterDecode callback fired!" );
	}
}
```

The following code:

```csharp
var testClass = new TestClass();
testClass.name = "Rumpelstiltskin Jones";
testClass.type = TestEnum.Thing2;
testClass.data.Add( new TestStruct() { x = 1, y = 2 } );
testClass.data.Add( new TestStruct() { x = 3, y = 4 } );
testClass.data.Add( new TestStruct() { x = 5, y = 6 } );

var testClassJson = Json.ToJson( testClass, prettyPrint: true );
Console.WriteLine( testClassJson );
```

Will output (if pretty printed):

```json
{
	"name": "Rumpelstiltskin Jones",
	"type": "Thing2",
	"data": [
		{
			"x": 1,
			"y": 2
		},
		{
			"x": 3,
			"y": 4
		},
		{
			"x": 5,
			"y": 6
		}
	]
}
```

And then you can rehydrate your object from the JSON using `FromJson<T>`:

```csharp
var obj = Json.FromJson<TestClass>( testClassJson );
```

You can also use `FromJsonOverwrite` to reconstruct partial or full JSON data back into an existing object. It will overwrite any properties/fields on the object with the data in JSON:

```csharp
var testClass = new TestClass();
Json.FromJsonOverwrite( json, testClass );
```

Finally, you'll notice that `TestClass` has the methods `BeforeEncode()` and `AfterDecode()` which have the `BeforeEncode` and `AfterDecode` attributes. These methods will be called *before* the object starts being serialized and *after* the object has been fully deserialized. This is useful when some further preparation or initialization logic is required.

By default, public fields and properties are encoded, not private fields. You can tag any field or property to be included with the `Serialized` attribute, or force a public field to be excluded with the `NonSerialized` attribute.

## Decode Aliases

Fields and properties can be decoded from aliases using the `DecodeAlias` attribute. While decoding, if no matching data is found in the JSON for a given field or property, its aliases will also be searched for.

```csharp
class TestClass
{
	[JsonInclude] // note that properties are opt-in! You must tell Json you want them serialized.
	public int index { get; set; }

	[DecodeAlias("anotherName")]
	public string name; // decode from "name" or "anotherName"

	[DecodeAlias("anotherNumber", "yetAnotherNumber")]
	public int number; // decode from "number", "anotherNumber", or "yetAnotherNumber"
}
```

## Type Hinting

When decoding polymorphic types, Json has no way of knowing which subclass to instantiate unless a type hint is included. So, optionally Json will add a key named `@type` to each encoded object with the fully qualified type of the object. You can request this by passing a `JsonSettings` object to the `Json.Decode` method:

```csharp
var settings = new JsonSettings()
{
	TypeNameHandling = TypeNameHandling.Auto
};
```

## Reference Handling and Polymorphic Types. The Reason this Code Exists

Json has the ability to detect and restore references (opt in). For example, if a List contains two of the same Entity objects Json has the ability to maintain the references when deserializing and rebuild the same List.

Json can also optionally deal with Polymorphic types. Lets say you have a `Component` class and then a bunch of subclasses of `Component`. If you store these all in a `List<Component>`, most JSON libs will give you back a List full of just `Component` objects even if your list had subclasses in it. Json remedies that issue.

Let's look at a simple example of both reference handling and dealing with polymorphic types. Here are our classes for the demonstration:

```csharp
class Entity
{
	public List<Component> components;
}

class Component
{
	public Entity entity;
}

class Sprite : Component
{}
```

Now, let's create an `Entity` and populate it with a `Component` and a `Sprite` then serialize it to JSON. Note the `JsonSettings` object. It lets you opt in to the features. One really neat option is the `TypeNameHandling.Auto`. Json will figure out on the fly if it needs to inject the objects type into the JSON or not. You'll see the results in the JSON below.

```csharp
var entity = new Entity
{
	components = new List<Component> { new Component(), new Sprite() }
};

var settings = new JsonSettings
{
	PrettyPrint = true,
	TypeNameHandling = TypeNameHandling.Auto,
	PreserveReferencesHandling = true
};

// or for convenience since this is used often: var settings = JsonSettings.HandlesReferences
var json = Json.ToJson( entity, settings );
```

And the resulting JSON. What we have in there is some extra metadata Json can use when it decodes this JSON into an Entity again. Each object gets a unique @id field and any references to existing objects get replaced by a @ref field. Magic!

```json
{
	"@id": "1",
	"components": [
		{
			"entity": null
		},
		{
			"@id": "3",
			"@type": "TestTypeHintAndReferences+Sprite",
			"entity": {
				"@ref": "1"
			}
		}
	]
}
```

## Encode Options

Several options are currently available for JSON encoding, and can be passed in as a second parameter to `Json.ToJson()`.

* `PrettyPrint` will output nicely formatted JSON to make it more readable.
* `PreserveReferencesHandling` will add extra metadata into the JSON so an object graph with circular references can be rebuilt
* `TypeNameHandling` lets you specify when type names will be injected into the JSON
* `TypeConverters` lets you augment the encoding/decoding of the object. More on this later.

## Using Generics

For most use cases you can just assign, cast or make your object graph using the API outlined above, but at times you may need to work with the intermediate objects to dig through and iterate over a collection. To do this, just omit the type when calling `FromJson`. You will get back either a primitive, a `List<object>` or a `Dictionary<string, object>`:

```csharp
var list = Json.Decode( "[1,2,3]" );
foreach( var item in list as IList )
{
	var number = item;
	Console.WriteLine( number );
	// note that if you want to strongly type the number `Convert.ChangeType`/`Convert.ToInt32` and friends work best
}

var dict = Json.Decode( "{\"x\":1,\"y\":2}" );
foreach( var pair in dict as IDictionary )
{
	var value = pair.Value;
	Console.WriteLine( pair.Key + " = " + value );
}
```

## Advanced: JsonTypeConverter for custom encoding/decoding

Json lets you add some custom data to the JSON and then fetch it for any strongly typed object. You can also fully take over encoding to JSON writing whatever you want for any particular object. You can do this by creating a `JsonTypeConverter<T>` and implementing the abstract methods. Any time Json comes accross an object of Type `T` it will pass it off to your `JsonObjectConverter`.

The `JsonTypeConverter` indicates what it wants to do via the three properties `CanRead` (defaults to true), `CanWrite` (defaults to true) and `WantsExclusiveWrite` (defaults to false).

If `CanWrite` is true, the `WriteJson` method will be passed an `IJsonEncoder` which can be used to write custom JSON for your object. It will be called *before* the encoder encodes the object's fields and properties. If you do not want the encoder to write any data at all you can override `WantsExclusiveWrite` returning `true` (see second example below).

When encoding the JSON back to an object, if `CanRead` is true, the `OnFoundCustomData` method will be passed any key/value pairs that do not have corresponding fields/properties.

```csharp
class Doodle
{
	public int x;
	public int y;
	public int z;
}

class DoodleJsonConverter : JsonTypeConverter<Doodle>
{
	public override void WriteJson( IJsonEncoder encoder, Doodle value )
	{
		// EncodeKeyValuePair can take any primitive, list, array, dictionary or object
		encoder.EncodeKeyValuePair( "key-that-isnt-on-object", true );
		encoder.EncodeKeyValuePair( "another_key", "with a value" );
	}

	public override void OnFoundCustomData( Doodle instance, string key, object value )
	{
		Debug.log( $"field name: {key}, value: {value}" );
	}
}

```

To use a `JsonTypeConverter` you just have to tell Json about it by sticking it in your JsonSettings object:

```csharp
var doodle = new Doodle();

// convert to JSON. The WriteJson method will be called
var settings = new JsonSettings { TypeConverters = new JsonTypeConverter[] { new DoodleJsonConverter() } };
var json = Json.ToJson( doodle, settings );

// rehydrate the JSON. The OnFoundCustomData will be called twice given the demo code above.
var newDoodle = Json.Decode<Doodle>( json, settings );
```

This example `JsonTypeConverter` fully takes over JSON encoding by returning `true` for `WantsExclusiveWrite`. The only thing the encoder will write in this case is id/reference data for reference tracking if enabled.

```csharp
class WantsExclusiveWriteConverter : JsonTypeConverter<Doodle>
{
	public override bool WantsExclusiveWrite => true;

	public override void WriteJson( IJsonEncoder encoder, Doodle value )
	{
		encoder.EncodeKeyValuePair( "key-that-isnt-on-object", true );
		encoder.EncodeKeyValuePair( "another_key", "with a value" );
		encoder.EncodeKeyValuePair( "string_array", new string[] { "first", "second" } );
	}

	public override void OnFoundCustomData( Doodle instance, string key, object value )
	{}
}

// using the converter
var doodle = new Doodle();

// Convert to JSON. The WriteJson method will be called.
// Since WantsExclusiveWrite is true, no other data will be present in the JSON string.
var settings = new JsonSettings { TypeConverters = new JsonTypeConverter[] { new WantsExclusiveWriteConverter() } };
var json = Json.ToJson( doodle, settings );

// rehydrate the JSON. The OnFoundCustomData will be called three times given the demo code above.
var newDoodle = Json.Decode<Doodle>( json, settings );
```

The resulting json would be the following. Notice that none of the normal `Doodle` data is present:

`{"key-that-isnt-on-object":true,"another_key":"with a value","string_array":["first","second"]}`

## Advanced: JsonObjectFactory to override object creation

Creating a `JsonObjectFactory` lets you override object creation entirely. This is extremely useful when you have an object that needs a specific constructor called or some object-specific setup. You can write any data you want and then override how the object gets instantiated and populated.

Continuing to use our Doodle class above, we will create a `JsonObjectFactory` that overrides object creation:

```csharp
class ObjectFactoryConverter : JsonObjectFactory<Doodle>
{
	public override Doodle Create( Type objectType, IDictionary objectData )
	{
		var doodle = new Doodle();

		doodle.x = Convert.ToInt32( objectData["x"] );
		doodle.y = Convert.ToInt32( objectData["y"] );
		doodle.z = Convert.ToInt32( objectData["z"] );

		return doodle;
	}
}
```

`JsonObjectFactory` is actually a subclass of `JsonTypeConverter` so usage is identical. You just add your `JsonObjectFactory` to the `TypeConverters` on the `JsonSettings` object and pass it in to `FromJson`:

```csharp
var settings = new JsonSettings { TypeConverters = new JsonTypeConverter[] { new ObjectFactoryConverter() } };
var newDoodle = Json.FromJson<Doodle>( json, settings );
```

## Meta

Forked and hacked from the excellent [TinyJSON](https://github.com/pbhogan/TinyJSON) by Patrick Hogan [twitter](http://twitter.com/pbhogan)

Released under the [MIT License](http://www.opensource.org/licenses/mit-license.php).


text:
package org.simpleflatmapper.lombok;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.simpleflatmapper.map.annotation.Key;

@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
public class GroupDTO {

    @Key
    private Long id;
    private String name;

}


text:
(function ($) {
    $.fn.dragDivResize = function () {
        var deltaX, deltaY, _startX, _startY;
        var resizeW, resizeH;
        var size = 20;
        var minSize = 10;
        var scroll = getScrollOffsets();
        var _this = this;
        for (var i = 0; i < _this.length; i++) {
            var target = this[i];
            $(target).on("mouseover mousemove", overHandler);
        }
        function outHandler() {
            for (var i = 0; i < _this.length; i++) {
                target.style.outline = "none";
            }
            document.body.style.cursor = "default";
        }
        function overHandler(event) {
            target = event.target || event.srcElement;
            var startX = event.clientX + scroll.x;
            var startY = event.clientY + scroll.y;
            var w = $(target).width();
            var h = $(target).height();
            _startX = parseInt(startX);
            _startY = parseInt(startY);
            if ((0 < target.offsetLeft + w - _startX && target.offsetLeft + w - _startX < size) || (0 < target.offsetTop + h - _startY && target.offsetTop + h - _startY < size)) {
                target.style.outline = "1px solid #438eb9";
                if ((0 > target.offsetLeft + w - _startX || target.offsetLeft + w - _startX > size) && 0 < target.offsetTop + h - _startY && target.offsetTop + h - _startY < size) {
                    resizeW = false;
                    resizeH = true;
                    document.body.style.cursor = "s-resize";
                }
                if (0 < target.offsetLeft + w - _startX && target.offsetLeft + w - _startX < size && (0 > target.offsetTop + h - _startY || target.offsetTop + h - _startY > size)) {
                    resizeW = true;
                    resizeH = false;
                    document.body.style.cursor = "w-resize";
                }
                if (0 < target.offsetLeft + w - _startX && target.offsetLeft + w - _startX < size && 0 < target.offsetTop + h - _startY && target.offsetTop + h - _startY < size) {
                    resizeW = true;
                    resizeH = true;
                    document.body.style.cursor = "se-resize";
                }
                $(target).on('mousedown', downHandler);
            } else {
                resizeW = false;
                resizeH = false;
                $(target).off('mousedown', downHandler);
            }
        }
        function downHandler(event) {
            target = event.target || event.srcElement;
            var startX = event.clientX + scroll.x;
            var startY = event.clientY + scroll.y;
            _startX = parseInt(startX);
            _startY = parseInt(startY);
            if (document.addEventListener) {
                document.addEventListener("mousemove", moveHandler, true);
                document.addEventListener("mouseup", upHandler, true);
            } else if (document.attachEvent) {
                target.setCapture();
                target.attachEvent("onlosecapeture", upHandler);
                target.attachEvent("onmouseup", upHandler);
                target.attachEvent("onmousemove", moveHandler);
            }
            if (event.stopPropagation) {
                event.stopPropagation();
            } else {
                event.cancelBubble = true;
            }
            if (event.preventDefault) {
                event.preventDefault();
            } else {
                event.returnValue = false;
            }
        }
        function moveHandler(e) {
            if (!e) e = window.event;
            var w, h;
            var startX = parseInt(e.clientX + scroll.x);
            var startY = parseInt(e.clientY + scroll.y);
            target = target || e.target || e.srcElement;
            if (target == document.body) {
                return;
            }
            if (resizeW) {
                deltaX = startX - _startX;
                w = $(target).width() + deltaX < minSize ? minSize : $(target).width() + deltaX;
                target.style.width = w + "px";
                _startX = startX;
            }
            if (resizeH) {
                deltaY = startY - _startY;
                h = $(target).height() + deltaY < minSize ? minSize : $(target).height() + deltaY;
                target.style.height = h + "px";
                _startY = startY;
            }
            if (e.stopPropagation) {
                e.stopPropagation();
            } else {
                e.cancelBubble = true;
            }
        }
        function upHandler(e) {
            if (!e) {
                e = window.event;
            }
            resizeW = false;
            resizeH = false;
            target = e.target || e.srcElement;
            $(target).on("mouseout", outHandler);
            if (document.removeEventListener) {
                document.removeEventListener("mousemove", moveHandler, true);
                document.removeEventListener("mouseup", upHandler, true);
            } else if (document.detachEvent) {
                target.detachEvent("onlosecapeture", upHandler);
                target.detachEvent("onmouseup", upHandler);
                target.detachEvent("onmousemove", moveHandler);
                target.releaseCapture();
            }
            if (e.stopPropagation) {
                e.stopPropagation();
            } else {
                e.cancelBubble = true;
            }
        }
        function getScrollOffsets(w) {
            w = w || window;
            if (w.pageXOffset != null) {
                return { x: w.pageXOffset, y: w.pageYOffset };
            }
            var d = w.document;
            if (document.compatMode == "CSS1Compat") {
                return { x: d.documentElement.scrollLeft, y: d.documentElement.scrollTop };
            }
            return { x: d.body.scrollLeft, y: d.body.scrollTop };
        }
    }
}(jQuery));


text:
/**
 * <copyright>
 * </copyright>
 *
 * $Id$
 */
package gov.nasa.arc.spife.europa.clientside.esmconfig.tests;

import gov.nasa.arc.spife.europa.clientside.esmconfig.EsmConfigFactory;
import gov.nasa.arc.spife.europa.clientside.esmconfig.EuropaServerType;

import junit.framework.TestCase;

import junit.textui.TestRunner;

/**
 *
 * A test case for the model object 'Europa Server Type'.
 *
 * @generated
 */
public class EuropaServerTypeTest extends TestCase {

	/**
	 * The fixture for this Europa Server Type test case.
	 *
	 *
	 * @generated
	 */
	protected EuropaServerType fixture = null;

	/**
	 *
	 *
	 * @generated
	 */
	public static void main(String[] args) {
		TestRunner.run(EuropaServerTypeTest.class);
	}

	/**
	 * Constructs a new Europa Server Type test case with the given name.
	 *
	 *
	 * @generated
	 */
	public EuropaServerTypeTest(String name) {
		super(name);
	}

	/**
	 * Sets the fixture for this Europa Server Type test case.
	 *
	 *
	 * @generated
	 */
	protected void setFixture(EuropaServerType fixture) {
		this.fixture = fixture;
	}

	/**
	 * Returns the fixture for this Europa Server Type test case.
	 *
	 *
	 * @generated
	 */
	protected EuropaServerType getFixture() {
		return fixture;
	}

	/**
	 *
	 *
	 * @see junit.framework.TestCase#setUp()
	 * @generated
	 */
	@Override
	protected void setUp() throws Exception {
		setFixture(EsmConfigFactory.eINSTANCE.createEuropaServerType());
	}

	/**
	 *
	 *
	 * @see junit.framework.TestCase#tearDown()
	 * @generated
	 */
	@Override
	protected void tearDown() throws Exception {
		setFixture(null);
	}

} //EuropaServerTypeTest


text:
package io.hydrosphere.mist.master.data

import java.io.File
import java.nio.file.{Files, Path}
import java.util.concurrent.Executors

import com.typesafe.config.{ConfigFactory, ConfigRenderOptions}
import io.hydrosphere.mist.master.ContextsSettings
import io.hydrosphere.mist.master.data.FsStorage._
import io.hydrosphere.mist.master.models.{ContextConfig, NamedConfig}
import io.hydrosphere.mist.utils.{Logger, fs}

import scala.concurrent.{ExecutionContext, Future}
import scala.util._

class FsStorage[A <: NamedConfig](
  dir: Path,
  repr: ConfigRepr[A],
  renderOptions: ConfigRenderOptions = DefaultRenderOptions
) extends Logger with RwLock { self =>

  def entries: Seq[A] = {
    def files = dir.toFile.listFiles(fs.mkFilter(_.endsWith(".conf")))

    withReadLock {
      files.map(parseFile).foldLeft(List.empty[A])({
        case (list, Failure(e)) =>
          logger.warn("Invalid configuration", e)
          list
        case (list, Success(context)) => list :+ context
      })
    }
  }

  def entry(name: String): Option[A] = {
    val filePath = dir.resolve(s"$name.conf")

    withReadLock {
      val file = filePath.toFile
      if (file.exists()) parseFile(file).toOption else None
    }
  }

  def delete(name: String): Option[A] = {
    entry(name).map(e => {
      withWriteLock { Files.delete(filePath(name)) }
      e
    })
  }

  private def filePath(name: String): Path = dir.resolve(s"$name.conf")

  private def parseFile(f: File): Try[A] = {
    val name = f.getName.replace(".conf", "")
    Try(ConfigFactory.parseFile(f)).map(c => repr.fromConfig(name, c))
  }

  def write(name: String, entry: A): A = {
    val config = repr.toConfig(entry)

    val data = config.root().render(renderOptions)

    withWriteLock {
      Files.write(filePath(name), data.getBytes)
      entry
    }
  }

}

object FsStorage {

  val DefaultRenderOptions =
    ConfigRenderOptions.defaults()
      .setComments(false)
      .setOriginComments(false)
      .setJson(false)
      .setFormatted(true)

  def create[A <: NamedConfig](path: String, repr: ConfigRepr[A]): FsStorage[A] =
    new FsStorage[A](checkDirectory(path), repr)

}


text:
var manifest = chrome.runtime.getManifest();
var options = { 'url' : manifest.main, 'type': 'popup' };
var title = null;
if (manifest.window) {
  //options.innerBounds = {};
  if (manifest.window.frame === false)
    options.frameless = true;
  if (manifest.window.resizable === false)
    options.resizable = false;
  if (manifest.window.height)
    options.height = manifest.window.height;
  if (manifest.window.width)
    options.width = manifest.window.width;
  if (manifest.window.min_width)
    options.minWidth = manifest.window.min_width;
  if (manifest.window.max_width)
    options.maxWidth = manifest.window.max_width;
  if (manifest.window.min_height)
    options.minHeight = manifest.window.min_height;
  if (manifest.window.max_height)
    options.maxHeight = manifest.window.max_height;
  if (manifest.window.fullscreen === true)
    options.state = 'fullscreen';
  if (manifest.window.show === false)
    options.hidden = true;
  if (manifest.window.show_in_taskbar === false)
    options.showInTaskbar = false;
  if (manifest.window['always_on_top'] === true)
    options.alwaysOnTop = true;
  if (manifest.window['visible_on_all_workspaces'] === true)
    options.allVisible = true;
  if (manifest.window.transparent)
    options.alphaEnabled = true;
  if (manifest.window.kiosk === true)
    options.kiosk = true;
  if (manifest.window.position)
    options.position = manifest.window.position;
  if (manifest.window.icon)
    options.icon = manifest.window.icon;
  if (manifest.window.title)
    options.title = manifest.window.title;
  if (manifest.window.id)
    options.id = manifest.window.id;
}

chrome.windows.create(options, function(win) {
});