text:
package gcimporter

import (
	"go/token"
	"go/types"
	"strings"

	"golang.org/x/tools/internal/pkgbits"
)

// A pkgReader holds the shared state for reading a unified IR package
// description.
type pkgReader struct {
	pkgbits.PkgDecoder

	fake fakeFileSet

	ctxt    *types.Context
	imports map[string]*types.Package // previously imported packages, indexed by path

	// lazily initialized arrays corresponding to the unified IR
	// PosBase, Pkg, and Type sections, respectively.
	posBases []string // position bases (i.e., file names)
	pkgs     []*types.Package
	typs     []types.Type

	// laterFns holds functions that need to be invoked at the end of
	// import reading.
	laterFns []func()
	// laterFors is used in case of 'type A B' to ensure that B is processed before A.
	laterFors map[types.Type]int

	// ifaces holds a list of constructed Interfaces, which need to have
	// Complete called after importing is done.
	ifaces []*types.Interface
}

// later adds a function to be invoked at the end of import reading.
func (pr *pkgReader) later(fn func()) {
	pr.laterFns = append(pr.laterFns, fn)
}

// See cmd/compile/internal/noder.derivedInfo.
type derivedInfo struct {
	idx    pkgbits.Index
	needed bool
}

// See cmd/compile/internal/noder.typeInfo.
type typeInfo struct {
	idx     pkgbits.Index
	derived bool
}

func UImportData(fset *token.FileSet, imports map[string]*types.Package, data []byte, path string) (_ int, pkg *types.Package, err error) {
	s := string(data)
	s = s[:strings.LastIndex(s, "\n$$\n")]
	input := pkgbits.NewPkgDecoder(path, s)
	pkg = readUnifiedPackage(fset, nil, imports, input)
	return
}

// laterFor adds a function to be invoked at the end of import reading, and records the type that function is finishing.
func (pr *pkgReader) laterFor(t types.Type, fn func()) {
	if pr.laterFors == nil {
		pr.laterFors = make(map[types.Type]int)
	}
	pr.laterFors[t] = len(pr.laterFns)
	pr.laterFns = append(pr.laterFns, fn)
}

// readUnifiedPackage reads a package description from the given
// unified IR export data decoder.
func readUnifiedPackage(fset *token.FileSet, ctxt *types.Context, imports map[string]*types.Package, input pkgbits.PkgDecoder) *types.Package {
	pr := pkgReader{
		PkgDecoder: input,

		fake: fakeFileSet{
			fset:  fset,
			files: make(map[string]*fileInfo),
		},

		ctxt:    ctxt,
		imports: imports,

		posBases: make([]string, input.NumElems(pkgbits.RelocPosBase)),
		pkgs:     make([]*types.Package, input.NumElems(pkgbits.RelocPkg)),
		typs:     make([]types.Type, input.NumElems(pkgbits.RelocType)),
	}
	defer pr.fake.setLines()

	r := pr.newReader(pkgbits.RelocMeta, pkgbits.PublicRootIdx, pkgbits.SyncPublic)
	pkg := r.pkg()
	r.Bool() // has init

	for i, n := 0, r.Len(); i < n; i++ {
		// As if r.obj(), but avoiding the Scope.Lookup call,
		// to avoid eager loading of imports.
		r.Sync(pkgbits.SyncObject)
		assert(!r.Bool())
		r.p.objIdx(r.Reloc(pkgbits.RelocObj))
		assert(r.Len() == 0)
	}

	r.Sync(pkgbits.SyncEOF)

	for _, fn := range pr.laterFns {
		fn()
	}

	for _, iface := range pr.ifaces {
		iface.Complete()
	}

	pkg.MarkComplete()
	return pkg
}

// A reader holds the state for reading a single unified IR element
// within a package.
type reader struct {
	pkgbits.Decoder

	p *pkgReader

	dict *readerDict
}

// A readerDict holds the state for type parameters that parameterize
// the current unified IR element.
type readerDict struct {
	// bounds is a slice of typeInfos corresponding to the underlying
	// bounds of the element's type parameters.
	bounds []typeInfo

	// tparams is a slice of the constructed TypeParams for the element.
	tparams []*types.TypeParam

	// devived is a slice of types derived from tparams, which may be
	// instantiated while reading the current element.
	derived      []derivedInfo
	derivedTypes []types.Type // lazily instantiated from derived
}

func (pr *pkgReader) newReader(k pkgbits.RelocKind, idx pkgbits.Index, marker pkgbits.SyncMarker) *reader {
	return &reader{
		Decoder: pr.NewDecoder(k, idx, marker),
		p:       pr,
	}
}

func (pr *pkgReader) tempReader(k pkgbits.RelocKind, idx pkgbits.Index, marker pkgbits.SyncMarker) *reader {
	return &reader{
		Decoder: pr.TempDecoder(k, idx, marker),
		p:       pr,
	}
}

func (pr *pkgReader) retireReader(r *reader) {
	pr.RetireDecoder(&r.Decoder)
}

// @@@ Positions

func (r *reader) pos() token.Pos {
	r.Sync(pkgbits.SyncPos)
	if !r.Bool() {
		return token.NoPos
	}

	// TODO(mdempsky): Delta encoding.
	posBase := r.posBase()
	line := r.Uint()
	col := r.Uint()
	return r.p.fake.pos(posBase, int(line), int(col))
}

func (r *reader) posBase() string {
	return r.p.posBaseIdx(r.Reloc(pkgbits.RelocPosBase))
}

func (pr *pkgReader) posBaseIdx(idx pkgbits.Index) string {
	if b := pr.posBases[idx]; b != "" {
		return b
	}

	var filename string
	{
		r := pr.tempReader(pkgbits.RelocPosBase, idx, pkgbits.SyncPosBase)

		// Within types2, position bases have a lot more details (e.g.,
		// keeping track of where //line directives appeared exactly).
		//
		// For go/types, we just track the file name.

		filename = r.String()

		if r.Bool() { // file base
			// Was: "b = token.NewTrimmedFileBase(filename, true)"
		} else { // line base
			pos := r.pos()
			line := r.Uint()
			col := r.Uint()

			// Was: "b = token.NewLineBase(pos, filename, true, line, col)"
			_, _, _ = pos, line, col
		}
		pr.retireReader(r)
	}
	b := filename
	pr.posBases[idx] = b
	return b
}

// @@@ Packages

func (r *reader) pkg() *types.Package {
	r.Sync(pkgbits.SyncPkg)
	return r.p.pkgIdx(r.Reloc(pkgbits.RelocPkg))
}

func (pr *pkgReader) pkgIdx(idx pkgbits.Index) *types.Package {
	// TODO(mdempsky): Consider using some non-nil pointer to indicate
	// the universe scope, so we don't need to keep re-reading it.
	if pkg := pr.pkgs[idx]; pkg != nil {
		return pkg
	}

	pkg := pr.newReader(pkgbits.RelocPkg, idx, pkgbits.SyncPkgDef).doPkg()
	pr.pkgs[idx] = pkg
	return pkg
}

func (r *reader) doPkg() *types.Package {
	path := r.String()
	switch path {
	case "":
		path = r.p.PkgPath()
	case "builtin":
		return nil // universe
	case "unsafe":
		return types.Unsafe
	}

	if pkg := r.p.imports[path]; pkg != nil {
		return pkg
	}

	name := r.String()

	pkg := types.NewPackage(path, name)
	r.p.imports[path] = pkg

	imports := make([]*types.Package, r.Len())
	for i := range imports {
		imports[i] = r.pkg()
	}
	pkg.SetImports(flattenImports(imports))

	return pkg
}

// flattenImports returns the transitive closure of all imported
// packages rooted from pkgs.
func flattenImports(pkgs []*types.Package) []*types.Package {
	var res []*types.Package
	seen := make(map[*types.Package]struct{})
	for _, pkg := range pkgs {
		if _, ok := seen[pkg]; ok {
			continue
		}
		seen[pkg] = struct{}{}
		res = append(res, pkg)

		// pkg.Imports() is already flattened.
		for _, pkg := range pkg.Imports() {
			if _, ok := seen[pkg]; ok {
				continue
			}
			seen[pkg] = struct{}{}
			res = append(res, pkg)
		}
	}
	return res
}

// @@@ Types

func (r *reader) typ() types.Type {
	return r.p.typIdx(r.typInfo(), r.dict)
}

func (r *reader) typInfo() typeInfo {
	r.Sync(pkgbits.SyncType)
	if r.Bool() {
		return typeInfo{idx: pkgbits.Index(r.Len()), derived: true}
	}
	return typeInfo{idx: r.Reloc(pkgbits.RelocType), derived: false}
}

func (pr *pkgReader) typIdx(info typeInfo, dict *readerDict) types.Type {
	idx := info.idx
	var where *types.Type
	if info.derived {
		where = &dict.derivedTypes[idx]
		idx = dict.derived[idx].idx
	} else {
		where = &pr.typs[idx]
	}

	if typ := *where; typ != nil {
		return typ
	}

	var typ types.Type
	{
		r := pr.tempReader(pkgbits.RelocType, idx, pkgbits.SyncTypeIdx)
		r.dict = dict

		typ = r.doTyp()
		assert(typ != nil)
		pr.retireReader(r)
	}
	// See comment in pkgReader.typIdx explaining how this happens.
	if prev := *where; prev != nil {
		return prev
	}

	*where = typ
	return typ
}

func (r *reader) doTyp() (res types.Type) {
	switch tag := pkgbits.CodeType(r.Code(pkgbits.SyncType)); tag {
	default:
		errorf("unhandled type tag: %v", tag)
		panic("unreachable")

	case pkgbits.TypeBasic:
		return types.Typ[r.Len()]

	case pkgbits.TypeNamed:
		obj, targs := r.obj()
		name := obj.(*types.TypeName)
		if len(targs) != 0 {
			t, _ := types.Instantiate(r.p.ctxt, name.Type(), targs, false)
			return t
		}
		return name.Type()

	case pkgbits.TypeTypeParam:
		return r.dict.tparams[r.Len()]

	case pkgbits.TypeArray:
		len := int64(r.Uint64())
		return types.NewArray(r.typ(), len)
	case pkgbits.TypeChan:
		dir := types.ChanDir(r.Len())
		return types.NewChan(dir, r.typ())
	case pkgbits.TypeMap:
		return types.NewMap(r.typ(), r.typ())
	case pkgbits.TypePointer:
		return types.NewPointer(r.typ())
	case pkgbits.TypeSignature:
		return r.signature(nil, nil, nil)
	case pkgbits.TypeSlice:
		return types.NewSlice(r.typ())
	case pkgbits.TypeStruct:
		return r.structType()
	case pkgbits.TypeInterface:
		return r.interfaceType()
	case pkgbits.TypeUnion:
		return r.unionType()
	}
}

func (r *reader) structType() *types.Struct {
	fields := make([]*types.Var, r.Len())
	var tags []string
	for i := range fields {
		pos := r.pos()
		pkg, name := r.selector()
		ftyp := r.typ()
		tag := r.String()
		embedded := r.Bool()

		fields[i] = types.NewField(pos, pkg, name, ftyp, embedded)
		if tag != "" {
			for len(tags) < i {
				tags = append(tags, "")
			}
			tags = append(tags, tag)
		}
	}
	return types.NewStruct(fields, tags)
}

func (r *reader) unionType() *types.Union {
	terms := make([]*types.Term, r.Len())
	for i := range terms {
		terms[i] = types.NewTerm(r.Bool(), r.typ())
	}
	return types.NewUnion(terms)
}

func (r *reader) interfaceType() *types.Interface {
	methods := make([]*types.Func, r.Len())
	embeddeds := make([]types.Type, r.Len())
	implicit := len(methods) == 0 && len(embeddeds) == 1 && r.Bool()

	for i := range methods {
		pos := r.pos()
		pkg, name := r.selector()
		mtyp := r.signature(nil, nil, nil)
		methods[i] = types.NewFunc(pos, pkg, name, mtyp)
	}

	for i := range embeddeds {
		embeddeds[i] = r.typ()
	}

	iface := types.NewInterfaceType(methods, embeddeds)
	if implicit {
		iface.MarkImplicit()
	}

	// We need to call iface.Complete(), but if there are any embedded
	// defined types, then we may not have set their underlying
	// interface type yet. So we need to defer calling Complete until
	// after we've called SetUnderlying everywhere.
	//
	// TODO(mdempsky): After CL 424876 lands, it should be safe to call
	// iface.Complete() immediately.
	r.p.ifaces = append(r.p.ifaces, iface)

	return iface
}

func (r *reader) signature(recv *types.Var, rtparams, tparams []*types.TypeParam) *types.Signature {
	r.Sync(pkgbits.SyncSignature)

	params := r.params()
	results := r.params()
	variadic := r.Bool()

	return types.NewSignatureType(recv, rtparams, tparams, params, results, variadic)
}

func (r *reader) params() *types.Tuple {
	r.Sync(pkgbits.SyncParams)

	params := make([]*types.Var, r.Len())
	for i := range params {
		params[i] = r.param()
	}

	return types.NewTuple(params...)
}

func (r *reader) param() *types.Var {
	r.Sync(pkgbits.SyncParam)

	pos := r.pos()
	pkg, name := r.localIdent()
	typ := r.typ()

	return types.NewParam(pos, pkg, name, typ)
}

// @@@ Objects

func (r *reader) obj() (types.Object, []types.Type) {
	r.Sync(pkgbits.SyncObject)

	assert(!r.Bool())

	pkg, name := r.p.objIdx(r.Reloc(pkgbits.RelocObj))
	obj := pkgScope(pkg).Lookup(name)

	targs := make([]types.Type, r.Len())
	for i := range targs {
		targs[i] = r.typ()
	}

	return obj, targs
}

func (pr *pkgReader) objIdx(idx pkgbits.Index) (*types.Package, string) {

	var objPkg *types.Package
	var objName string
	var tag pkgbits.CodeObj
	{
		rname := pr.tempReader(pkgbits.RelocName, idx, pkgbits.SyncObject1)

		objPkg, objName = rname.qualifiedIdent()
		assert(objName != "")

		tag = pkgbits.CodeObj(rname.Code(pkgbits.SyncCodeObj))
		pr.retireReader(rname)
	}

	if tag == pkgbits.ObjStub {
		assert(objPkg == nil || objPkg == types.Unsafe)
		return objPkg, objName
	}

	// Ignore local types promoted to global scope (#55110).
	if _, suffix := splitVargenSuffix(objName); suffix != "" {
		return objPkg, objName
	}

	if objPkg.Scope().Lookup(objName) == nil {
		dict := pr.objDictIdx(idx)

		r := pr.newReader(pkgbits.RelocObj, idx, pkgbits.SyncObject1)
		r.dict = dict

		declare := func(obj types.Object) {
			objPkg.Scope().Insert(obj)
		}

		switch tag {
		default:
			panic("weird")

		case pkgbits.ObjAlias:
			pos := r.pos()
			typ := r.typ()
			declare(types.NewTypeName(pos, objPkg, objName, typ))

		case pkgbits.ObjConst:
			pos := r.pos()
			typ := r.typ()
			val := r.Value()
			declare(types.NewConst(pos, objPkg, objName, typ, val))

		case pkgbits.ObjFunc:
			pos := r.pos()
			tparams := r.typeParamNames()
			sig := r.signature(nil, nil, tparams)
			declare(types.NewFunc(pos, objPkg, objName, sig))

		case pkgbits.ObjType:
			pos := r.pos()

			obj := types.NewTypeName(pos, objPkg, objName, nil)
			named := types.NewNamed(obj, nil, nil)
			declare(obj)

			named.SetTypeParams(r.typeParamNames())

			rhs := r.typ()
			pk := r.p
			pk.laterFor(named, func() {
				// First be sure that the rhs is initialized, if it needs to be initialized.
				delete(pk.laterFors, named) // prevent cycles
				if i, ok := pk.laterFors[rhs]; ok {
					f := pk.laterFns[i]
					pk.laterFns[i] = func() {} // function is running now, so replace it with a no-op
					f()                        // initialize RHS
				}
				underlying := rhs.Underlying()

				// If the underlying type is an interface, we need to
				// duplicate its methods so we can replace the receiver
				// parameter's type (#49906).
				if iface, ok := underlying.(*types.Interface); ok && iface.NumExplicitMethods() != 0 {
					methods := make([]*types.Func, iface.NumExplicitMethods())
					for i := range methods {
						fn := iface.ExplicitMethod(i)
						sig := fn.Type().(*types.Signature)

						recv := types.NewVar(fn.Pos(), fn.Pkg(), "", named)
						methods[i] = types.NewFunc(fn.Pos(), fn.Pkg(), fn.Name(), types.NewSignature(recv, sig.Params(), sig.Results(), sig.Variadic()))
					}

					embeds := make([]types.Type, iface.NumEmbeddeds())
					for i := range embeds {
						embeds[i] = iface.EmbeddedType(i)
					}

					newIface := types.NewInterfaceType(methods, embeds)
					r.p.ifaces = append(r.p.ifaces, newIface)
					underlying = newIface
				}

				named.SetUnderlying(underlying)
			})

			for i, n := 0, r.Len(); i < n; i++ {
				named.AddMethod(r.method())
			}

		case pkgbits.ObjVar:
			pos := r.pos()
			typ := r.typ()
			declare(types.NewVar(pos, objPkg, objName, typ))
		}
	}

	return objPkg, objName
}

func (pr *pkgReader) objDictIdx(idx pkgbits.Index) *readerDict {

	var dict readerDict

	{
		r := pr.tempReader(pkgbits.RelocObjDict, idx, pkgbits.SyncObject1)
		if implicits := r.Len(); implicits != 0 {
			errorf("unexpected object with %v implicit type parameter(s)", implicits)
		}

		dict.bounds = make([]typeInfo, r.Len())
		for i := range dict.bounds {
			dict.bounds[i] = r.typInfo()
		}

		dict.derived = make([]derivedInfo, r.Len())
		dict.derivedTypes = make([]types.Type, len(dict.derived))
		for i := range dict.derived {
			dict.derived[i] = derivedInfo{r.Reloc(pkgbits.RelocType), r.Bool()}
		}

		pr.retireReader(r)
	}
	// function references follow, but reader doesn't need those

	return &dict
}

func (r *reader) typeParamNames() []*types.TypeParam {
	r.Sync(pkgbits.SyncTypeParamNames)

	// Note: This code assumes it only processes objects without
	// implement type parameters. This is currently fine, because
	// reader is only used to read in exported declarations, which are
	// always package scoped.

	if len(r.dict.bounds) == 0 {
		return nil
	}

	// Careful: Type parameter lists may have cycles. To allow for this,
	// we construct the type parameter list in two passes: first we
	// create all the TypeNames and TypeParams, then we construct and
	// set the bound type.

	r.dict.tparams = make([]*types.TypeParam, len(r.dict.bounds))
	for i := range r.dict.bounds {
		pos := r.pos()
		pkg, name := r.localIdent()

		tname := types.NewTypeName(pos, pkg, name, nil)
		r.dict.tparams[i] = types.NewTypeParam(tname, nil)
	}

	typs := make([]types.Type, len(r.dict.bounds))
	for i, bound := range r.dict.bounds {
		typs[i] = r.p.typIdx(bound, r.dict)
	}

	// TODO(mdempsky): This is subtle, elaborate further.
	//
	// We have to save tparams outside of the closure, because
	// typeParamNames() can be called multiple times with the same
	// dictionary instance.
	//
	// Also, this needs to happen later to make sure SetUnderlying has
	// been called.
	//
	// TODO(mdempsky): Is it safe to have a single "later" slice or do
	// we need to have multiple passes? See comments on CL 386002 and
	// go.dev/issue/52104.
	tparams := r.dict.tparams
	r.p.later(func() {
		for i, typ := range typs {
			tparams[i].SetConstraint(typ)
		}
	})

	return r.dict.tparams
}

func (r *reader) method() *types.Func {
	r.Sync(pkgbits.SyncMethod)
	pos := r.pos()
	pkg, name := r.selector()

	rparams := r.typeParamNames()
	sig := r.signature(r.param(), rparams, nil)

	_ = r.pos() // TODO(mdempsky): Remove; this is a hacker for linker.go.
	return types.NewFunc(pos, pkg, name, sig)
}

func (r *reader) qualifiedIdent() (*types.Package, string) { return r.ident(pkgbits.SyncSym) }
func (r *reader) localIdent() (*types.Package, string)     { return r.ident(pkgbits.SyncLocalIdent) }
func (r *reader) selector() (*types.Package, string)       { return r.ident(pkgbits.SyncSelector) }

func (r *reader) ident(marker pkgbits.SyncMarker) (*types.Package, string) {
	r.Sync(marker)
	return r.pkg(), r.String()
}

// pkgScope returns pkg.Scope().
// If pkg is nil, it returns types.Universe instead.
//
// TODO(mdempsky): Remove after x/tools can depend on Go 1.19.
func pkgScope(pkg *types.Package) *types.Scope {
	if pkg != nil {
		return pkg.Scope()
	}
	return types.Universe
}


text:
import React from 'react';
import PropTypes from 'prop-types';

const Head = ({title}) => (
	<head>
		<meta charSet="utf-8"/>
		<meta httpEquiv="X-UA-Compatible" content="IE=edge"/>
		<meta name="viewport" content="width=device-width, initial-scale=1"/>
		<meta property="og:image" content="http://vision100.org/sites/vision100.org/files/nfd-social-media.jpg"/>
		<title>{title}</title>
		<link rel="stylesheet" type="text/css" href="/main.css"/>
		<link rel="shortcut icon" href="https://vision100.org/sites/vision100.org/files/nfd-logo-favicon.ico"/>
		<script src="/critical.js"/>
	</head>
);

Head.propTypes = {
	title: PropTypes.string.isRequired
};

export default Head;

redpajama_set_name: RedPajamaGithub


text:
module RuboCop
  module Cop
    module Style
      # This cop checks that arrays are sliced with endless ranges instead of
      # `ary[start..-1]` on Ruby 2.6+.
      #
      # @example
      #   # bad
      #   items[1..-1]
      #
      #   # good
      #   items[1..]
      class SlicingWithRange < Base
        extend AutoCorrector
        extend TargetRubyVersion

        minimum_target_ruby_version 2.6

        MSG = 'Prefer ary[n..] over ary[n..-1].'
        RESTRICT_ON_SEND = %i[[]].freeze

        def_node_matcher :range_till_minus_one?, '(irange !nil? (int -1))'

        def on_send(node)
          return unless node.arguments.count == 1
          return unless range_till_minus_one?(node.arguments.first)

          add_offense(node.first_argument) do |corrector|
            corrector.remove(node.first_argument.end)
          end
        end
      end
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="activity_resolver_use_always">"Her zaman"</string>
  <string name="activity_resolver_use_once">"Yalnızca bir defa"</string>
  <string name="candidates_style">"adaylar"</string>
  <string name="capital_off">"KAPALI"</string>
  <string name="capital_on">"AÇIK"</string>
  <string name="chooseActivity">"İşlem seçin"</string>
  <string name="loading">"Yükleniyor..."</string>
  <string name="noApplications">"Bu eylemi hiçbir uygulama gerçekleştiremez."</string>
  <string name="number_picker_decrement_button">"Azalt"</string>
  <string name="number_picker_increment_button">"Artır"</string>
  <string name="number_picker_increment_scroll_action">"Artırmak için yukarı, azaltmak için aşağı kaydırın."</string>
  <string name="number_picker_increment_scroll_mode">"</string>
  <string name="ringtone_default">"Varsayılan zil sesi"</string>
  <string name="ringtone_picker_title">"Zil sesleri"</string>
  <string name="ringtone_silent">"Yok"</string>
  <string name="whichApplication">"İşlemi şunu kullanarak tamamla"</string>
</resources>


text:
时间限制	内存限制	代码长度限制	判题程序	作者

400 ms	65536 kB	16000 B	Standard	CHEN, Yue

#### Given a pair of positive integers, for example, 6 and 110, can this equation 6 = 110 be true? The answer is "yes", if 6 is a decimal number and 110 is a binary number.

#### Now for any pair of positive integers N1 and N2, your task is to find the radix of one number while that of the other is given.

### Input Specification:

#### Each input file contains one test case. Each case occupies a line which contains 4 positive integers:
#### N1 N2 tag radix
#### Here N1 and N2 each has no more than 10 digits. A digit is less than its radix and is chosen from the set {0-9, a-z} where 0-9 represent the decimal numbers 0-9, and a-z represent the decimal numbers 10-35. The last number "radix" is the radix of N1 if "tag" is 1, or of N2 if "tag" is 2.

### Output Specification:

#### For each test case, print in one line the radix of the other number so that the equation N1 = N2 is true. If the equation is impossible, print "Impossible". If the solution is not unique, output the smallest possible radix.

Sample Input1	Sample Output1

6 110 1 10	2

Sample Input2	Sample Output2

1 ab 1 2	Impossible


text:
<?hh // strict
namespace traitorous\http\headers\response;

use traitorous\http\headers\HttpResponseHeader;

class TransferEncodingHeader extends HttpResponseHeader {

    public function getKey(): string {
        return "Transfer-Encoding";
    }

}


text:
//
//  Toast+UIView.m
//  Toast
//  Version 2.0
//
//  Copyright 2013 Charles Scalesse.
//  Modified 2013 Tomas Linhart
//

#import "Toast+UIView.h"
#import <QuartzCore/QuartzCore.h>
#import <objc/runtime.h>

#pragma clang diagnostic push
#pragma ide diagnostic ignored "OCUnusedMethodInspection"

/*
 *  CONFIGURE THESE VALUES TO ADJUST LOOK & FEEL,
 *  DISPLAY DURATION, ETC.
 */

// general appearance
static const CGFloat CSToastMaxWidth = 0.8;      // 80% of parent view width
static const CGFloat CSToastMaxHeight = 0.8;      // 80% of parent view height
static const CGFloat CSToastHorizontalPadding = 10.0;
static const CGFloat CSToastVerticalPadding = 10.0;
static const CGFloat CSToastCornerRadius = 4.0;
static const CGFloat CSToastOpacity = 0.8;
static const CGFloat CSToastFontSize = 14.0;
static const NSUInteger CSToastMaxTitleLines = 0;
static const NSUInteger CSToastMaxMessageLines = 0;
static const CGFloat CSToastFadeDuration = 0.3;

// shadow appearance
static const CGFloat CSToastShadowOpacity = 0.8;
static const CGFloat CSToastShadowRadius = 6.0;
static const CGSize CSToastShadowOffset = { 4.0, 4.0 };
static const BOOL CSToastDisplayShadow = NO;

// display duration and position
static const CGFloat CSToastDefaultDuration = 3.0;
static const NSString *CSToastDefaultPosition = @"bottom";

// image view size
static const CGFloat CSToastImageViewWidth = 80.0;
static const CGFloat CSToastImageViewHeight = 80.0;

// activity
static const CGFloat CSToastActivityWidth = 100.0;
static const CGFloat CSToastActivityHeight = 100.0;
static const NSString *CSToastActivityDefaultPosition = @"center";
static const NSString *CSToastActivityViewKey = @"CSToastActivityViewKey";

@interface UIView (ToastPrivate)

- (CGPoint)centerPointForPosition:(id)position withToast:(UIView *)toast;

- (UIView *)viewForMessage:(NSString *)message title:(NSString *)title image:(UIImage *)image;

@end

@implementation UIView (Toast)

#pragma mark - Toast Methods

- (UIView *)makeToast:(NSString *)message
{
    return [self makeToast:message duration:CSToastDefaultDuration position:CSToastDefaultPosition];
}

- (UIView *)makeToast:(NSString *)message duration:(CGFloat)interval position:(id)position
{
    UIView *toast = [self viewForMessage:message title:nil image:nil];
    [self showToast:toast duration:interval position:position];
    return toast;
}

- (UIView *)makeToast:(NSString *)message duration:(CGFloat)interval position:(id)position title:(NSString *)title
{
    UIView *toast = [self viewForMessage:message title:title image:nil];
    [self showToast:toast duration:interval position:position];
    return toast;
}

- (UIView *)makeToast:(NSString *)message duration:(CGFloat)interval position:(id)position image:(UIImage *)image
{
    UIView *toast = [self viewForMessage:message title:nil image:image];
    [self showToast:toast duration:interval position:position];
    return toast;
}

- (UIView *)makeToast:(NSString *)message duration:(CGFloat)interval  position:(id)position title:(NSString *)title image:(UIImage *)image
{
    UIView *toast = [self viewForMessage:message title:title image:image];
    [self showToast:toast duration:interval position:position];
    return toast;
}

- (void)showToast:(UIView *)toast
{
    [self showToast:toast duration:CSToastDefaultDuration position:CSToastDefaultPosition];
}

- (void)showToast:(UIView *)toast duration:(CGFloat)interval position:(id)point
{
    toast.center = [self centerPointForPosition:point withToast:toast];
    toast.alpha = 0.0;
    [self addSubview:toast];

    [UIView animateWithDuration:CSToastFadeDuration
                          delay:0.0
                        options:UIViewAnimationOptionCurveEaseOut
            animations:^{
                toast.alpha = 1.0;
            } completion:^(BOOL finished) {
        [UIView animateWithDuration:CSToastFadeDuration
                              delay:interval
                            options:UIViewAnimationOptionCurveEaseIn
                animations:^{
                    toast.alpha = 0.0;
                } completion:^(BOOL anotherFinished) {
            [toast removeFromSuperview];
        }];
    }];
}

#pragma mark - Toast Activity Methods

- (void)makeToastActivity
{
    [self makeToastActivity:CSToastActivityDefaultPosition];
}

- (void)makeToastActivity:(id)position
{
    // sanity
    UIView *existingActivityView = (UIView *) objc_getAssociatedObject(self, &CSToastActivityViewKey);
    if (existingActivityView != nil) {return;}

    UIView *activityView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CSToastActivityWidth, CSToastActivityHeight)];
    activityView.center = [self centerPointForPosition:position withToast:activityView];
    activityView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:CSToastOpacity];
    activityView.alpha = 0.0;
    activityView.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin);
    activityView.layer.cornerRadius = CSToastCornerRadius;

    if (CSToastDisplayShadow) {
        activityView.layer.shadowColor = [UIColor blackColor].CGColor;
        activityView.layer.shadowOpacity = CSToastShadowOpacity;
        activityView.layer.shadowRadius = CSToastShadowRadius;
        activityView.layer.shadowOffset = CSToastShadowOffset;
    }

    UIActivityIndicatorView *activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    activityIndicatorView.center = CGPointMake(activityView.bounds.size.width / 2, activityView.bounds.size.height / 2);
    [activityView addSubview:activityIndicatorView];
    [activityIndicatorView startAnimating];

    // associate ourselves with the activity view
    objc_setAssociatedObject(self, &CSToastActivityViewKey, activityView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

    [self addSubview:activityView];

    [UIView animateWithDuration:CSToastFadeDuration
                          delay:0.0
                        options:UIViewAnimationOptionCurveEaseOut
            animations:^{
                activityView.alpha = 1.0;
            } completion:nil];
}

- (void)hideToastActivity
{
    UIView *existingActivityView = (UIView *) objc_getAssociatedObject(self, &CSToastActivityViewKey);
    if (existingActivityView != nil) {
        [UIView animateWithDuration:CSToastFadeDuration
                              delay:0.0
                            options:(UIViewAnimationOptionCurveEaseIn | UIViewAnimationOptionBeginFromCurrentState)
                animations:^{
                    existingActivityView.alpha = 0.0;
                } completion:^(BOOL finished) {
            [existingActivityView removeFromSuperview];
            objc_setAssociatedObject(self, &CSToastActivityViewKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        }];
    }
}

#pragma mark - Private Methods

- (CGPoint)centerPointForPosition:(id)point withToast:(UIView *)toast
{
    if ([point isKindOfClass:[NSString class]]) {
        // convert string literals @"top", @"bottom", @"center", or any point wrapped in an NSValue object into a CGPoint
        if ([point caseInsensitiveCompare:@"top"] == NSOrderedSame) {
            return CGPointMake(self.bounds.size.width / 2, (toast.frame.size.height / 2) + CSToastVerticalPadding);
        } else if ([point caseInsensitiveCompare:@"bottom"] == NSOrderedSame) {
            return CGPointMake(self.bounds.size.width / 2, (self.bounds.size.height - (toast.frame.size.height / 2)) - CSToastVerticalPadding);
        } else if ([point caseInsensitiveCompare:@"center"] == NSOrderedSame) {
            return CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2);
        }
    } else if ([point isKindOfClass:[NSValue class]]) {
        return [point CGPointValue];
    }

    NSLog(@"Warning: Invalid position for toast.");
    return [self centerPointForPosition:CSToastDefaultPosition withToast:toast];
}

- (UIView *)viewForMessage:(NSString *)message title:(NSString *)title image:(UIImage *)image
{
    // sanity
    if ((message == nil) && (title == nil) && (image == nil)) {return nil;}

    // dynamically build a toast view with any combination of message, title, & image.
    UILabel *messageLabel = nil;
    UILabel *titleLabel = nil;
    UIImageView *imageView = nil;

    // create the parent view
    UIView *wrapperView = [[UIView alloc] init];
    wrapperView.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin);
    wrapperView.layer.cornerRadius = CSToastCornerRadius;

    if (CSToastDisplayShadow) {
        wrapperView.layer.shadowColor = [UIColor blackColor].CGColor;
        wrapperView.layer.shadowOpacity = CSToastShadowOpacity;
        wrapperView.layer.shadowRadius = CSToastShadowRadius;
        wrapperView.layer.shadowOffset = CSToastShadowOffset;
    }

    wrapperView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:CSToastOpacity];

    if (image != nil) {
        imageView = [[UIImageView alloc] initWithImage:image];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        imageView.frame = CGRectMake(CSToastHorizontalPadding, CSToastVerticalPadding, CSToastImageViewWidth, CSToastImageViewHeight);
    }

    CGFloat imageWidth, imageHeight, imageLeft;

    // the imageView frame values will be used to size & position the other views
    if (imageView != nil) {
        imageWidth = imageView.bounds.size.width;
        imageHeight = imageView.bounds.size.height;
        imageLeft = CSToastHorizontalPadding;
    } else {
        imageWidth = imageHeight = imageLeft = 0.0;
    }

    if (title != nil) {
        titleLabel = [[UILabel alloc] init];
        titleLabel.numberOfLines = CSToastMaxTitleLines;
        titleLabel.font = [UIFont boldSystemFontOfSize:CSToastFontSize];
        titleLabel.textAlignment = NSTextAlignmentLeft;
        titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
        titleLabel.textColor = [UIColor whiteColor];
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.alpha = 1.0;
        titleLabel.text = title;

        // size the title label according to the length of the text
        CGSize maxSizeTitle = CGSizeMake((self.bounds.size.width * CSToastMaxWidth) - imageWidth, self.bounds.size.height * CSToastMaxHeight);

        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineBreakMode = titleLabel.lineBreakMode;

        CGRect textRect = [message boundingRectWithSize:maxSizeTitle
                                              options:NSStringDrawingUsesLineFragmentOrigin
                                           attributes:@{
                                                   NSFontAttributeName : titleLabel.font,
                                                   NSParagraphStyleAttributeName : paragraphStyle
                                           }
                                              context:nil];
        titleLabel.frame = textRect;
    }

    if (message != nil) {
        messageLabel = [[UILabel alloc] init];
        messageLabel.numberOfLines = CSToastMaxMessageLines;
        messageLabel.font = [UIFont systemFontOfSize:CSToastFontSize];
        messageLabel.lineBreakMode = NSLineBreakByWordWrapping;
        messageLabel.textColor = [UIColor whiteColor];
        messageLabel.backgroundColor = [UIColor clearColor];
        messageLabel.alpha = 1.0;
        messageLabel.text = message;
        messageLabel.textAlignment = NSTextAlignmentCenter;

        // size the message label according to the length of the text
        CGSize maxSizeMessage = CGSizeMake((self.bounds.size.width * CSToastMaxWidth) - imageWidth, self.bounds.size.height * CSToastMaxHeight);
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineBreakMode = messageLabel.lineBreakMode;

        CGRect textRect = [message boundingRectWithSize:maxSizeMessage
                                                options:NSStringDrawingUsesLineFragmentOrigin
                                             attributes:@{
                                                     NSFontAttributeName : messageLabel.font,
                                                     NSParagraphStyleAttributeName : paragraphStyle
                                             }
                                                context:nil];
        messageLabel.frame = textRect;
    }

    // titleLabel frame values
    CGFloat titleWidth, titleHeight, titleTop, titleLeft;

    if (titleLabel != nil) {
        titleWidth = titleLabel.bounds.size.width;
        titleHeight = titleLabel.bounds.size.height;
        titleTop = CSToastVerticalPadding;
        titleLeft = imageLeft + imageWidth + CSToastHorizontalPadding;
    } else {
        titleWidth = titleHeight = titleTop = titleLeft = 0.0;
    }

    // messageLabel frame values
    CGFloat messageWidth, messageHeight, messageLeft, messageTop;

    if (messageLabel != nil) {
        messageWidth = messageLabel.bounds.size.width;
        messageHeight = messageLabel.bounds.size.height;
        messageLeft = imageLeft + imageWidth + CSToastHorizontalPadding;
        messageTop = titleTop + titleHeight + CSToastVerticalPadding;
    } else {
        messageWidth = messageHeight = messageLeft = messageTop = 0.0;
    }

    CGFloat longerWidth = MAX(titleWidth, messageWidth);
    CGFloat longerLeft = MAX(titleLeft, messageLeft);

    // wrapper width uses the longerWidth or the image width, whatever is larger. same logic applies to the wrapper height
    CGFloat wrapperWidth = MAX((imageWidth + (CSToastHorizontalPadding * 2)), (longerLeft + longerWidth + CSToastHorizontalPadding));
    CGFloat wrapperHeight = MAX((messageTop + messageHeight + CSToastVerticalPadding), (imageHeight + (CSToastVerticalPadding * 2)));

    wrapperView.frame = CGRectMake(0.0, 0.0, wrapperWidth, wrapperHeight);

    if (titleLabel != nil) {
        titleLabel.frame = CGRectMake(titleLeft, titleTop, titleWidth, titleHeight);
        [wrapperView addSubview:titleLabel];
    }

    if (messageLabel != nil) {
        messageLabel.frame = CGRectMake(messageLeft, messageTop, messageWidth, messageHeight);
        [wrapperView addSubview:messageLabel];
    }

    if (imageView != nil) {
        [wrapperView addSubview:imageView];
    }

    return wrapperView;
}

@end

#pragma clang diagnostic pop


text:
kmath
=====

Javascript Numeric Math Utilities


text:
package apple.uikit;

import java.io.*;
import java.nio.*;
import java.util.*;
import com.google.j2objc.annotations.*;
import com.google.j2objc.runtime.*;
import com.google.j2objc.runtime.block.*;
import apple.audiotoolbox.*;
import apple.corefoundation.*;
import apple.coregraphics.*;
import apple.coreservices.*;
import apple.foundation.*;
import apple.coreanimation.*;
import apple.coredata.*;
import apple.coreimage.*;
import apple.coretext.*;
import apple.corelocation.*;

/*<javadoc>*/
/*</javadoc>*/
@Adapter
public abstract class UIToolbarDelegateAdapter
    extends UIBarPositioningDelegateAdapter
    implements UIToolbarDelegate {

}


text:
from crossword.core import Crossword, CrosswordCell
from crossword.exceptions import CrosswordException

def from_ipuz(ipuz_dict):
    for kind in ipuz_dict['kind']:
        if not kind.startswith("http://ipuz.org/crossword"):
            raise CrosswordException

    known_keys = (
        "dimensions",
        "editor",
        "author",
        "date",
        "notes",
        "uniqueid",
        "publisher",
        "copyright",
        "title",
        "block",
        "empty",
        "clues",
        "puzzle",
        "solution",
    )
    crossword = Crossword(
        ipuz_dict['dimensions']['width'],
        ipuz_dict['dimensions']['height']
    )
    crossword._format_identifier = Crossword.IPUZ
    crossword.meta.contributor = ipuz_dict.get('editor')
    crossword.meta.creator = ipuz_dict.get('author')
    crossword.meta.date = ipuz_dict.get('date')
    crossword.meta.description = ipuz_dict.get('notes')
    crossword.meta.identifier = ipuz_dict.get('uniqueid')
    crossword.meta.publisher = ipuz_dict.get('publisher')
    crossword.meta.rights = ipuz_dict.get('copyright')
    crossword.meta.title = ipuz_dict.get('title')
    crossword.block = ipuz_dict.get('block')
    crossword.empty = ipuz_dict.get('empty')

    for number, clue in ipuz_dict.get('clues', {}).get('Across', []):
        crossword.clues.across[number] = clue
    for number, clue in ipuz_dict.get('clues', {}).get('Down', []):
        crossword.clues.down[number] = clue

    for x, y in crossword.cells:
        crossword[x, y] = CrosswordCell()

    for key in ('puzzle', 'solution'):
        entry = ipuz_dict.get(key)
        for x, y in crossword.cells:
            try:
                crossword[x, y][key] = entry[y][x]
            except (IndexError, TypeError):
                crossword[x, y][key] = None

    for key, value in ipuz_dict.items():
        if key not in known_keys:
            crossword._format[key] = value

    return crossword

def to_ipuz(crossword):
    ipuz_dict = {
        "version": "http://ipuz.org/v1",
        "dimensions": {
            "width": crossword.width,
            "height": crossword.height,
        },
        "puzzle": [
            [getattr(cell, "puzzle", None) for cell in row]
            for row in crossword._data
        ],
        "solution": [
            [getattr(cell, "solution", None) for cell in row]
            for row in crossword._data
        ],
    }
    if crossword.meta.creator is not None:
        ipuz_dict["author"] = crossword.meta.creator
    if crossword.meta.rights is not None:
        ipuz_dict["copyright"] = crossword.meta.rights
    if crossword.meta.date is not None:
        ipuz_dict["date"] = crossword.meta.date
    if crossword.meta.contributor is not None:
        ipuz_dict["editor"] = crossword.meta.contributor
    if crossword.meta.description is not None:
        ipuz_dict["notes"] = crossword.meta.description
    if crossword.meta.publisher is not None:
        ipuz_dict["publisher"] = crossword.meta.publisher
    if crossword.meta.identifier is not None:
        ipuz_dict["uniqueid"] = crossword.meta.identifier
    if crossword.meta.title is not None:
        ipuz_dict["title"] = crossword.meta.title
    if crossword.block is not None:
        ipuz_dict["block"] = crossword.block
    if crossword.empty is not None:
        ipuz_dict["empty"] = crossword.empty

    across_clues = [list(item) for item in crossword.clues.across()]
    down_clues = [list(item) for item in crossword.clues.down()]
    if across_clues or down_clues:
        ipuz_dict["clues"] = {}
        if across_clues:
            ipuz_dict["clues"]['Across'] = across_clues
        if down_clues:
            ipuz_dict["clues"]['Down'] = down_clues

    if crossword._format_identifier == Crossword.IPUZ:
        ipuz_dict.update(crossword._format)
    return ipuz_dict


text:
import threading

from queue import Queue

class WorkQueue(Queue):
    '''Simple wrapper to also provide ability to indicate when no more work is expected.
    '''
    def __init__(self, *args):
        Queue.__init__(self, *args)  # Queue does not inherit from object (is an old-style class)
        self._all_jobs_submitted = threading.Event()

    def all_jobs_submitted(self):
        '''Indicate that no more work is expected on this queue.'''
        self._all_jobs_submitted.set()

    def is_done(self):
        '''Determine if there is more work expected on this queue.'''
        return self._all_jobs_submitted.is_set() and self.empty()


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">

  <title>Get your ESNcard</title>
  <link rel="shortcut icon" href="img/esn-star.png" type="image/png">

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

  <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">

  <link href="css/freelancer.min.css" rel="stylesheet">

<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.0.3/cookieconsent.min.css" />

      ESNcard Poland
      <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive"
        aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
          Menu

        </button>

            What is ESNcard?

            Partners

            Get your ESNcard

            Contact

        What is ESNcard?

        The ESNcard is the membership card of the Erasmus Student Network (ESN).
          It is a proof of membership in an ESN section and so indirectly of the ESN network. The ESNcard
          is also used as a discount card in many cities and countries around Europe. Its main objective
          is to support and give opportunities to international students during and after their exchange
          period. The ESNcard is used annually by over 140.000 students in 40 countries, and the numbers
          are growing every year.

Partners

You can find more discounts at ESNcard.org

Get your ESNcard

Application form for Erasmus students

          I'm an Erasmus

Application form for Buddy students

          I'm a Buddy

Application form for ESNers

          I'm an ESNer

You can find a detailed instruction below

          ESNcard Guidebook

Contact Us!

        card@esn.pl

Address

ESN Poland Association

Al. Reymonta 12A

Poland, 01-842 Warsaw

ESN Poland

            Copyright © ESN Poland IT Committee 2017

Ryanair

15% discount on 8 single flights (or 4 return flights)

Free check-in luggage of 20kg with each of these 8 flights booked

Weekly travel offers for Erasmus students

Tailored Ryanair in-journey offers on the mobile app

https://esncard.org/ryanair

                <button class="btn btn-success" type="button" data-dismiss="modal">
                     Close</button>

Uniplaces

All Erasmus students have access to a special promotion: 25% discount of the service fee in
                  over 30.000 rooms from Lisbon to Paris, London to Valencia, Bologna to Nottingham - and pretty soon all
                  over Europe!

Don't forget to use the following promo code when at the "Pay and Book" page: ESNINTERNATIONAL.

https://esncard.org/uniplaces

                <button class="btn btn-success" type="button" data-dismiss="modal">

                    Close</button>

Logitech

Focused on innovation and quality, the personal device manifacturer Logitech designs personal devices
                  to help people enjoy a better experience with the digital world. Among the products Logitech sells
                  you can find webcams, speakers, keyboards, mice, audio products, gaming products, accessories for tablets
                  and smartphones, video security to digital home equipment and more.

All ESNcard holders enjoy an exclusive 35% discount on all products in the Logitech e-shop!

https://esncard.org/logitech

                <button class="btn btn-success" type="button" data-dismiss="modal">

                    Close</button>


text:
package org.altbeacon.beacon.service;

import org.altbeacon.beacon.BeaconManager;
import org.altbeacon.beacon.logging.LogManager;

public class MonitorState {
    private static final String TAG = "MonitorState";
    private boolean inside = false;
    private long lastSeenTime = 0l;
    private final Callback callback;

    public MonitorState(Callback c) {
        callback = c;
    }

    public Callback getCallback() {
        return callback;
    }

    // returns true if it is newly inside
    public boolean markInside() {
        lastSeenTime = System.currentTimeMillis();
        if (!inside) {
            inside = true;
            return true;
        }
        return false;
    }
    public boolean isNewlyOutside() {
        if (inside) {
            if (lastSeenTime > 0 && System.currentTimeMillis() - lastSeenTime > BeaconManager.getRegionExitPeriod()) {
                inside = false;
                LogManager.d(TAG, "We are newly outside the region because the lastSeenTime of %s "
                                + "was %s seconds ago, and that is over the expiration duration "
                                + "of %s", lastSeenTime, System.currentTimeMillis() - lastSeenTime,
                        BeaconManager.getRegionExitPeriod());
                lastSeenTime = 0l;
                return true;
            }
        }
        return false;
    }
    public boolean isInside() {
        if (inside) {
            if (!isNewlyOutside()) {
                return true;
            }
        }
        return false;
    }
}


text:
"""
=========================================
Tractography Clustering with QuickBundles
=========================================

This example explains how we can use QuickBundles [Garyfallidis12]_ to
simplify/cluster streamlines.

First import the necessary modules.
"""

import numpy as np
from nibabel import trackvis as tv
from dipy.segment.clustering import QuickBundles
from dipy.io.pickles import save_pickle
from dipy.data import get_data
from dipy.viz import fvtk

"""
For educational purposes we will try to cluster a small streamline bundle known
from neuroanatomy as the fornix.
"""

fname = get_data('fornix')

"""
Load fornix streamlines.
"""

streams, hdr = tv.read(fname)

streamlines = [i[0] for i in streams]

"""
Perform QuickBundles clustering using the MDF metric and a 10mm distance
threshold. Keep in mind that since the MDF metric requires streamlines to have
the same number of points, the clustering algorithm will internally use a
representation of streamlines that have been automatically downsampled/upsampled
so they have only 12 points (To set manually the number of points,
see :ref:`clustering-examples-ResampleFeature`).
"""

qb = QuickBundles(threshold=10.)
clusters = qb.cluster(streamlines)

"""
`clusters` is a `ClusterMap` object which contains attributes that
provide information about the clustering result.
"""

print("Nb. clusters:", len(clusters))
print("Cluster sizes:", map(len, clusters))
print("Small clusters:", clusters < 10)
print("Streamlines indices of the first cluster:\n", clusters[0].indices)
print("Centroid of the last cluster:\n", clusters[-1].centroid)

"""

::

    Nb. clusters: 4

    Cluster sizes: [64, 191, 47, 1]

    Small clusters: array([False, False, False, True], dtype=bool)

    Streamlines indices of the first cluster:
    [0, 7, 8, 10, 11, 12, 13, 14, 15, 18, 26, 30, 33, 35, 41, 65, 66, 85, 100,
     101, 105, 115, 116, 119, 122, 123, 124, 125, 126, 128, 129, 135, 139, 142,
     143, 144, 148, 151, 159, 167, 175, 180, 181, 185, 200, 208, 210, 224, 237,
     246, 249, 251, 256, 267, 270, 280, 284, 293, 296, 297, 299]

    Centroid of the last cluster:
    array([[  84.83773804,  117.92590332,   77.32278442],
           [  86.10850525,  115.84362793,   81.91885376],
           [  86.40357208,  112.25676727,   85.72930145],
           [  86.48336792,  107.60327911,   88.13782501],
           [  86.23897552,  102.5100708 ,   89.29447174],
           [  85.04563904,   97.46020508,   88.54240417],
           [  82.60240173,   93.14851379,   86.84208679],
           [  78.98937225,   89.57682037,   85.63652039],
           [  74.72344208,   86.60827637,   84.9391861 ],
           [  70.40846252,   85.15874481,   82.4484024 ],
           [  66.74534607,   86.00262451,   78.82582092],
           [  64.02451324,   88.43942261,   75.0697403 ]], dtype=float32)

`clusters` has also attributes like `centroids` (cluster representatives), and
methods like `add`, `remove`, and `clear` to modify the clustering result.

Lets first show the initial dataset.
"""

ren = fvtk.ren()
ren.SetBackground(1, 1, 1)
fvtk.add(ren, fvtk.streamtube(streamlines, fvtk.colors.white))
fvtk.record(ren, n_frames=1, out_path='fornix_initial.png', size=(600, 600))

"""
.. figure:: fornix_initial.png
   :align: center

   **Initial Fornix dataset**.

Show the centroids of the fornix after clustering (with random colors):
"""

colormap = fvtk.create_colormap(np.arange(len(clusters)))

fvtk.clear(ren)
ren.SetBackground(1, 1, 1)
fvtk.add(ren, fvtk.streamtube(streamlines, fvtk.colors.white, opacity=0.05))
fvtk.add(ren, fvtk.streamtube(clusters.centroids, colormap, linewidth=0.4))
fvtk.record(ren, n_frames=1, out_path='fornix_centroids.png', size=(600, 600))

"""
.. figure:: fornix_centroids.png
   :align: center

   **Showing the different QuickBundles centroids with random colors**.

Show the labeled fornix (colors from centroids).
"""

colormap_full = np.ones((len(streamlines), 3))
for cluster, color in zip(clusters, colormap):
    colormap_full[cluster.indices] = color

fvtk.clear(ren)
ren.SetBackground(1, 1, 1)
fvtk.add(ren, fvtk.streamtube(streamlines, colormap_full))
fvtk.record(ren, n_frames=1, out_path='fornix_clusters.png', size=(600, 600))

"""
.. figure:: fornix_clusters.png
   :align: center

   **Showing the different clusters**.

It is also possible to save the complete `ClusterMap` object with pickling.
"""

save_pickle('QB.pkl', clusters)

"""
Finally, here is a video of QuickBundles applied on a larger dataset.

.. raw:: html

    <iframe width="420" height="315" src="http://www.youtube.com/embed/kstL7KKqu94" frameborder="0" allowfullscreen></iframe>

.. include:: ../links_names.inc

.. [Garyfallidis12] Garyfallidis E. et al., QuickBundles a method for
                    tractography simplification, Frontiers in Neuroscience, vol
                    6, no 175, 2012.

"""


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

    <!--

        Licensed to the Apache Software Foundation (ASF) under one or more
        contributor license agreements.  See the NOTICE file distributed with
        this work for additional information regarding copyright ownership.
        The ASF licenses this file to You 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.
    -->

    <modelVersion>4.0.0</modelVersion>

    <parent>
		<groupId>org.beamfoundry.bundles.spring-data</groupId>
        <artifactId>org.beamfoundry.bundles.spring-data-parent</artifactId>
		<version>1.4.4.RELEASE_3-SNAPSHOT</version>
		<relativePath>../spring-data-parent/pom.xml</relativePath>
    </parent>

    <groupId>org.beamfoundry.bundles.spring-data</groupId>
    <artifactId>org.beamfoundry.bundles.spring-data-commons</artifactId>
	<version>1.8.4.RELEASE_3-SNAPSHOT</version>
    <packaging>bundle</packaging>
    <name>Bundles :: spring-data :: Commons</name>

    <properties>

        <pkgGroupId>org.springframework.data</pkgGroupId>
        <pkgArtifactId>spring-data-commons</pkgArtifactId>
		<pkgVersion>${springdata.commons}</pkgVersion>
		<servicemix.osgi.dynamicimport.pkg>*</servicemix.osgi.dynamicimport.pkg>
        <servicemix.osgi.export.pkg>
            org.springframework.data
        </servicemix.osgi.export.pkg>
		<servicemix.osgi.import.pkg>
			<!--
			com.fasterxml.jackson.core,
			com.fasterxml.jackson.databind,
			com.fasterxml.jackson.databind.annotation,
			com.fasterxml.jackson.databind.module,-->
			com.fasterxml.jackson.*;version="[${jackson}, 3.0.0)";resolution:=optional,
			com.google.common.base;version="${guava}";resolution:=optional,
			com.mysema.query.types;version="[${querydsl}, 3.4.0)";resolution:=optional,
			<!--
			javax.enterprise.context,
			javax.enterprise.context.spi,
			javax.enterprise.event,
			javax.enterprise.inject,
			javax.enterprise.inject.spi,
			javax.enterprise.util,
			 -->
			javax.enterprise.*;version="${cdi}";resolution:=optional,
			javax.inject;resolution:=optional,
			javax.xml.*;version="[2.2.0, 2.3.0)";resolution:=optional,
			org.aopalliance.aop;version="[1,2)";resolution:=optional,
            org.aopalliance.intercept;version="[1,2)";resolution:=optional,
			org.joda.time;version="${jodatime}";resolution:=optional,
			org.slf4j;version="[1.7.0, 1.9.0)",
			org.springframework.aop.framework;version="[${spring.osgi},4.1)",
			org.springframework.aop.target;version="[${spring.osgi},4.1)",
			org.springframework.beans;version="[${spring.osgi},4.1)",
			org.springframework.beans.factory;version="[${spring.osgi},4.1)",
			org.springframework.beans.factory.annotation;version="[${spring.osgi},4.1)",
			org.springframework.beans.factory.config;version="[${spring.osgi},4.1)",
			org.springframework.beans.factory.parsing;version="[${spring.osgi},4.1)",
			org.springframework.beans.factory.support;version="[${spring.osgi},4.1)",
			org.springframework.beans.factory.xml;version="[${spring.osgi},4.1)",
			org.springframework.context;version="[${spring.osgi},4.1)",
			org.springframework.context.annotation;version="[${spring.osgi},4.1)",
			org.springframework.context.event;version="[${spring.osgi},4.1)",
			org.springframework.context.expression;version="[${spring.osgi},4.1)",
			org.springframework.core;version="[${spring.osgi},4.1)",
			org.springframework.core.annotation;version="[${spring.osgi},4.1)",
			org.springframework.core.convert;version="[${spring.osgi},4.1)",
			org.springframework.core.convert.converter;version="[${spring.osgi},4.1)",
			org.springframework.core.convert.support;version="[${spring.osgi},4.1)",
			org.springframework.core.env;version="[${spring.osgi},4.1)",
			org.springframework.core.io;version="[${spring.osgi},4.1)",
			org.springframework.core.io.support;version="[${spring.osgi},4.1)",
			org.springframework.core.type;version="[${spring.osgi},4.1)",
			org.springframework.core.type.classreading;version="[${spring.osgi},4.1)",
			org.springframework.core.type.filter;version="[${spring.osgi},4.1)",
			org.springframework.dao;version="[${spring.osgi},4.1)",
			org.springframework.dao.support;version="[${spring.osgi},4.1)",
			org.springframework.expression;version="[${spring.osgi},4.1)",
			org.springframework.expression.spel.standard;version="[${spring.osgi},4.1)",
			org.springframework.expression.spel.support;version="[${spring.osgi},4.1)",
			org.springframework.format;version="[${spring.osgi},4.1)",
			org.springframework.format.support;version="[${spring.osgi},4.1)",
			org.springframework.hateoas;version="${springhateoas.osgi}";resolution:=optional,
			org.springframework.hateoas.core;version="${springhateoas.osgi}";resolution:=optional,
			org.springframework.hateoas.mvc;version="${springhateoas.osgi}";resolution:=optional,
			org.springframework.oxm;version="[${spring.osgi},4.1)",
			org.springframework.scheduling.annotation;version="[${spring.osgi},4.1)",
			org.springframework.transaction;version="[${spring.osgi},4.1)",
			org.springframework.transaction.annotation;version="[${spring.osgi},4.1)",
			org.springframework.transaction.interceptor;version="[${spring.osgi},4.1)",
			org.springframework.transaction.support;version="[${spring.osgi},4.1)",
			org.springframework.util;version="[${spring.osgi},4.1)",
			org.springframework.web.bind.support;version="[${spring.osgi},4.1)";resolution:=optional,
			org.springframework.web.context.request;version="[${spring.osgi},4.1)";resolution:=optional,
			org.springframework.web.method.support;version="[${spring.osgi},4.1)";resolution:=optional,
			org.springframework.web.servlet.config.annotation;version="[${spring.osgi},4.1)";resolution:=optional,
			org.springframework.web.servlet.support;version="[${spring.osgi},4.1)";resolution:=optional,
			org.springframework.web.util;version="[${spring.osgi},4.1)";resolution:=optional,
			org.w3c.dom;resolution:=optional,
        </servicemix.osgi.import.pkg>
    </properties>

    <dependencies>
        <dependency>
            <groupId>${pkgGroupId}</groupId>
            <artifactId>${pkgArtifactId}</artifactId>
            <version>${pkgVersion}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-beans</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-core</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-api</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>jcl-over-slf4j</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
			<!--
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <version>2.3.7</version>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
                        <Bundle-Description>${project.description}</Bundle-Description>
                        <Export-Package>${servicemix.osgi.export}</Export-Package>
                        <Import-Package>${servicemix.osgi.import.pkg}</Import-Package>
                        <Private-Package>${servicemix.osgi.private.pkg}</Private-Package>
                        <DynamicImport-Package>${servicemix.osgi.dynamicimport.pkg}</DynamicImport-Package>
                        <Embed-Dependency>${servicemix.osgi.embed.dependency}</Embed-Dependency>
                        <Bundle-NativeCode>${servicemix.osgi.native}</Bundle-NativeCode>
                        <Bundle-Activator>${servicemix.osgi.activator}</Bundle-Activator>
                        <Fragment-Host>${servicemix.osgi.fragment.host}</Fragment-Host>
                        <Provide-Capability>${servicemix.osgi.provide.capability}</Provide-Capability>
                        <Require-Capability>${servicemix.osgi.require.capability}</Require-Capability>
                        <SPI-Provider>${servicemix.spi.provider}</SPI-Provider>
                        <SPI-Consumer>${servicemix.spi.consumer}</SPI-Consumer>
                        <_failok>${servicemix.osgi.failok}</_failok>
                        <_versionpolicy>[$(version;==;$(@)),$(version;+;$(@)))</_versionpolicy>
                        <_removeheaders>Ignore-Package,Include-Resource,Private-Package,Embed-Dependency
                        </_removeheaders>
                    </instructions>
                    <unpackBundle>true</unpackBundle>
                </configuration>
            </plugin>
			-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <artifactSet>
                                <includes>
                                    <include>${pkgGroupId}:${pkgArtifactId}</include>
                                </includes>
                            </artifactSet>
                            <filters>
                                <filter>
                                    <artifact>${pkgGroupId}:${pkgArtifactId}</artifact>
									<includes>
										<include>META-INF/services/**</include>
										<include>META-INF/spring.*</include>
										<include>**/*.xsd</include>
									</includes>
                                </filter>
                            </filters>
                            <promoteTransitiveDependencies>true</promoteTransitiveDependencies>
                            <createDependencyReducedPom>true</createDependencyReducedPom>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
package org.apache.geode.cache.lucene;

import static org.apache.geode.cache.lucene.test.IndexRepositorySpy.doOnce;
import static org.apache.geode.cache.lucene.test.LuceneTestUtilities.DEFAULT_FIELD;
import static org.apache.geode.cache.lucene.test.LuceneTestUtilities.INDEX_NAME;
import static org.apache.geode.cache.lucene.test.LuceneTestUtilities.REGION_NAME;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.geode.DataSerializable;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.control.RebalanceOperation;
import org.apache.geode.cache.control.RebalanceResults;
import org.apache.geode.cache.lucene.internal.LuceneIndexFactorySpy;
import org.apache.geode.cache.lucene.internal.LuceneIndexImpl;
import org.apache.geode.cache.lucene.test.IndexRepositorySpy;
import org.apache.geode.cache.partition.PartitionRegionHelper;
import org.apache.geode.distributed.DistributedMember;
import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
import org.apache.geode.internal.cache.InitialImageOperation;
import org.apache.geode.internal.cache.PartitionedRegion;
import org.apache.geode.internal.cache.partitioned.BecomePrimaryBucketMessage;
import org.apache.geode.internal.cache.partitioned.BecomePrimaryBucketMessage.BecomePrimaryBucketResponse;
import org.apache.geode.test.dunit.Host;
import org.apache.geode.test.dunit.VM;

public class LuceneQueriesAccessorBase extends LuceneDUnitTest {

  protected VM accessor;

  @Override
  public void postSetUp() throws Exception {
    super.postSetUp();
    accessor = Host.getHost(0).getVM(3);
  }

  protected boolean waitForFlushBeforeExecuteTextSearch(VM vm, int ms) {
    return vm.invoke(() -> {
      Cache cache = getCache();

      LuceneService service = LuceneServiceProvider.get(cache);
      LuceneIndexImpl index = (LuceneIndexImpl) service.getIndex(INDEX_NAME, REGION_NAME);

      return service.waitUntilFlushed(INDEX_NAME, REGION_NAME, ms, TimeUnit.MILLISECONDS);
    });
  }

  protected void executeTextSearch(VM vm) {
    vm.invoke(() -> {
      Cache cache = getCache();
      Region<Object, Object> region = cache.getRegion(REGION_NAME);

      LuceneService service = LuceneServiceProvider.get(cache);
      LuceneQuery<Integer, TestObject> query;
      query = service.createLuceneQueryFactory().create(INDEX_NAME, REGION_NAME, "text:world",
          DEFAULT_FIELD);
      PageableLuceneQueryResults<Integer, TestObject> results = query.findPages();
      assertEquals(3, results.size());
      List<LuceneResultStruct<Integer, TestObject>> page = results.next();

      Map<Integer, TestObject> data = new HashMap<Integer, TestObject>();
      for (LuceneResultStruct<Integer, TestObject> row : page) {
        data.put(row.getKey(), row.getValue());
      }

      assertEquals(new HashMap(region), data);
      return null;
    });
  }

  protected void executeTextSearch(VM vm, String queryString, String defaultField,
      int expectedResultsSize) {
    vm.invoke(() -> {
      Cache cache = getCache();

      LuceneService service = LuceneServiceProvider.get(cache);
      LuceneQuery<Integer, TestObject> query;
      query = service.createLuceneQueryFactory().setLimit(1000).setPageSize(1000).create(INDEX_NAME,
          REGION_NAME, queryString, defaultField);
      Collection<?> results = query.findKeys();

      assertEquals(expectedResultsSize, results.size());
    });
  }

  protected void executeTextSearchWithExpectedException(VM vm, String queryString,
      String defaultField, Class expctedExceptionClass) {
    vm.invoke(() -> {
      Cache cache = getCache();

      LuceneService service = LuceneServiceProvider.get(cache);
      LuceneQuery<Integer, TestObject> query;
      query = service.createLuceneQueryFactory().setLimit(1000).setPageSize(1000).create(INDEX_NAME,
          REGION_NAME, queryString, defaultField);
      try {
        Collection<?> results = query.findKeys();
        fail("Query " + defaultField + ":" + queryString + " should not have succeeded");
      } catch (Exception e) {
        assertEquals(expctedExceptionClass, e.getClass());
      }
    });
  }

  protected void addCallbackToTriggerRebalance(VM vm) {
    vm.invoke(() -> {
      IndexRepositorySpy spy = IndexRepositorySpy.injectSpy();

      spy.beforeWriteIndexRepository(doOnce(key -> rebalanceRegion(vm)));
    });
  }

  protected void addCallbackToMoveBucket(VM vm, final DistributedMember destination) {
    vm.invoke(() -> {
      IndexRepositorySpy spy = IndexRepositorySpy.injectSpy();

      spy.beforeWriteIndexRepository(doOnce(key -> moveBucket(destination, key)));
    });
  }

  protected void addCallbackToMovePrimary(VM vm, final DistributedMember destination) {
    vm.invoke(() -> {
      IndexRepositorySpy spy = IndexRepositorySpy.injectSpy();

      spy.beforeWriteIndexRepository(doOnce(key -> movePrimary(destination, key)));
    });
  }

  protected void addCallbackToMovePrimaryOnQuery(VM vm, final DistributedMember destination) {
    vm.invoke(() -> {
      LuceneIndexFactorySpy factorySpy = LuceneIndexFactorySpy.injectSpy();

      factorySpy.setGetRespositoryConsumer(doOnce(key -> moveBucket(destination, key)));
    });
  }

  private void moveBucket(final DistributedMember destination, final Object key) {
    Region<Object, Object> region = getCache().getRegion(REGION_NAME);
    DistributedMember source = getCache().getDistributedSystem().getDistributedMember();
    PartitionRegionHelper.moveBucketByKey(region, source, destination, key);
  }

  private void movePrimary(final DistributedMember destination, final Object key) {
    PartitionedRegion region = (PartitionedRegion) getCache().getRegion(REGION_NAME);

    BecomePrimaryBucketResponse response =
        BecomePrimaryBucketMessage.send((InternalDistributedMember) destination, region,
            region.getKeyInfo(key).getBucketId(), true);
    assertNotNull(response);
    assertTrue(response.waitForResponse());
  }

  protected void removeCallback(VM vm) {
    vm.invoke(() -> {
      IndexRepositorySpy.remove();
      InitialImageOperation.resetAllGIITestHooks();
      LuceneIndexFactorySpy.remove();
    });
  }

  protected void rebalanceRegion(VM vm) {
    // Do a rebalance
    vm.invoke(() -> {
      RebalanceOperation op = getCache().getResourceManager().createRebalanceFactory().start();
      RebalanceResults results = op.getResults();
    });
  }

  protected static class TestObject implements DataSerializable {
    private static final long serialVersionUID = 1L;
    private String text;

    public TestObject() {}

    public TestObject(String text) {
      this.text = text;
    }

    @Override
    public int hashCode() {
      final int prime = 31;
      int result = 1;
      result = prime * result + ((text == null) ? 0 : text.hashCode());
      return result;
    }

    @Override
    public boolean equals(Object obj) {
      if (this == obj)
        return true;
      if (obj == null)
        return false;
      if (getClass() != obj.getClass())
        return false;
      TestObject other = (TestObject) obj;
      if (text == null) {
        if (other.text != null)
          return false;
      } else if (!text.equals(other.text))
        return false;
      return true;
    }

    @Override
    public String toString() {
      return "TestObject[" + text + "]";
    }

    @Override
    public void toData(DataOutput out) throws IOException {
      out.writeUTF(text);
    }

    @Override
    public void fromData(DataInput in) throws IOException, ClassNotFoundException {
      text = in.readUTF();
    }
  }
}


text:
The only truly secure data is the one that never leaves a secure enclave. From the time when a secret has been accessible by a possibly corrupted tool/network/environment/device it's not truly safe anymore.
Therefore you realize you have to use derivative secrets with different trust levels to allow your phone to sign messages, a web service to prove your ownership, ...
Everything is your definition and usage of the trust levels.

- GPG key set :
  - root, most secure one
  - per segregation case : devices, application, service provider, ...

## Create it

    gpg --expert --full-generate-key --allow-freeform-uid

- `--expert` gives the full choice of algorithms (it's good to know what's available even though I'm not using ECC right now)
- `--allow-freeform-uid` allows to use an URL instead of an email (so I'm not spammed) for keys not intended for email communications. However to get benefit from automatic E-mail encryption it's mandatory to have the encryption key (or one of its signers?) attached to a key with your email.
- *Curve 25519* algorithm, based on several lectures ; it's a bet on the future and might reveal wrong so let be ready to renew keys in some time anyway

Choosing RSA and 4096 because of compatibility **BUT does it makes sense for the primary key ???**.

## Make it useable

### On public directories

I've never been far in there because of one main reason : **spam**.

## User interface

As far as I know there is no user-friendly interface. The best one for me being kgpg for years and it has missing icons on Ubuntu and still launches a terminal to properly edit keys...

I put it on the fact that, because of its highly secure design, GPG is not easy to integrate in other programs.

It's not vital to have a graphic interface dedicated to gpg because most use cases are handled within a client application (e.g. mail app, chat app, ...).
However it's a major pain point when coming to generate or edit keys, as people usually don't remember gpg commands and options they use once a year...

### Enters keybase.io

Same problems but more integrations available.
Decreased (say adapted) security but acceptable use : each one must be aware this hasn't been battle-tested as pgp.
See [NCC_Group_Keybase_KB2018_Public_Report_2019-02-27_v1.3.pdf](https://keybase.io/docs-assets/blog/NCC_Group_Keybase_KB2018_Public_Report_2019-02-27_v1.3.pdf).

Account created early, lost key (as usual because I've just not used it enough to make it in my long-term memory).

Main security aspects :
- It's now using its own separate cryptography system (it's not PGP anymore) but it can still certify PGP keys.
- It's centralized (1 server provider ; see below)
- It eases identities spreading by:
    - providing a unique directory for identities (keybase.io)
    - automatically creating a key per device, signed by any other owned key, that can be easily revoked (no more sacrosanct private key that can never be touched)

It allows to sign generic statements (not only keys) and therefore can be used to certify almost anything like ownership of online accounts (twitter, Mastodon, ...) but also websites and PGP keys.

IMHO it's still a very nice tool to advertise online identities (including PGP keys) and allow people to send you encrypted messages without having to reveal an email address to spammers or to set up an online form.

The apps are quite good and they provide services over the main mechanism : encrypted chat, encrypted file system, encrypted git repository. The user experience they provide is far behind the big commercial ones (far less reactive) but it does the job. The biggest issue for me is the high battery drain it occurs (my Android phone mainly, which I suspect is very dependent on the phone's hardware).

One huge advantage is the availability of client apps for all platforms, which made me use it to securely* exchange data between my devices (PC, Android, iOS devices) through chat or file transfer.

I've started to use encrypted git repositories for not-so-sensitive-projects-that-I-still-don't-want-to-publish to prevent me from hosting my own, but I don't mean it as a target solution because I'm worried what would happen to my data if keybase turns off...

The main issue for me is its centralised architecture :
- its availability and integrity depends on a unique provider (might be possible to deploy other instances but I haven't seen any and they would not federate, defeating the purpose of being a centralised directory)
- its terms and privacy rules can change at any time
- as a cloud service, gathers data about their users (see [their privacy policy](https://keybase.io/docs/privacypolicy))
- as a US-hosted service it depends on US law (which forces the provider to disclose data, restricts cryptography exports)

=> unfortunately proved right on May 7, 2020 when Keybase announced they were bought by Zoom...

### keys.openpgp.org

https://keys.openpgp.org/about/faq

A key server that's not part of the federated SKS pool (not compatible).

It brings confidentiality features by separating identifying data from public one. It has plans to federated several instances.

## OpenKeychain

OpenKeychain is an implementation of OpenPGP for Android.

It let's you generate/import/export keys and is integrated with a few essential apps.

It has several limitations like reduced algorithms choice and forcing the presence of an email on new keys (but can import keys without one) but you probably won't find a better app nowadays.

It does the job.

## Wrap up

- master key with email
- keybase.io to advertise keys and online accounts
- separate keys per usage
- unencrypted backup on hidden USB key

## References

- https://alexcabal.com/creating-the-perfect-gpg-keypair
- [OpenPGP Best Practices](https://riseup.net/en/security/message-security/openpgp/best-practices#openpgp-key-checks)
- [Guide to using YubiKey for GPG and SSH](https://github.com/drduh/YubiKey-Guide)
- [SafeCurves: choosing safe curves for elliptic-curve cryptography](https://safecurves.cr.yp.to/)
- [Offline GnuPG Master Key and Subkeys on YubiKey NEO Smartcard](https://blog.josefsson.org/2014/06/23/offline-gnupg-master-key-and-subkeys-on-yubikey-neo-smartcard/)
- [GnuPG, clefs, YubiKey : c'est parti](https://www.unicoda.com/?p=3230)


text:
package com.rackspacecloud.blueflood.io;

import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.connectionpool.exceptions.PoolTimeoutException;
import com.rackspacecloud.blueflood.utils.Metrics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory;

public class Instrumentation implements InstrumentationMBean {
    private static final Logger log = LoggerFactory.getLogger(Instrumentation.class);
    private static ReadTimers readTimers = new ReadTimers();
    private static WriteTimers writeTimers = new WriteTimers();
    private static final Meter writeErrMeter;
    private static final Meter readErrMeter;
    private static final Meter batchReadErrMeter;

    // One-off meters
    private static final Meter scanAllColumnFamiliesMeter;
    private static final Meter allPoolsExhaustedException;
    private static final Meter fullResMetricWritten;
    private static final Meter fullResPreaggregatedMetricWritten;
    private static final Meter metricsWithShortDelayReceived;
    private static final Meter metricsWithLongDelayReceived;

    static {
        Class kls = Instrumentation.class;
        writeErrMeter = Metrics.meter(kls, "writes", "Cassandra Write Errors");
        readErrMeter = Metrics.meter(kls, "reads", "Cassandra Read Errors");
        batchReadErrMeter = Metrics.meter(kls, "reads", "Batch Cassandra Read Errors");
        scanAllColumnFamiliesMeter = Metrics.meter(kls, "Scan all ColumnFamilies");
        allPoolsExhaustedException = Metrics.meter(kls, "All Pools Exhausted");
        fullResMetricWritten = Metrics.meter(kls, "Full Resolution Metrics Written");
        fullResPreaggregatedMetricWritten = Metrics.meter(kls, "Full Resolution Preaggregated Metrics Written");
        metricsWithShortDelayReceived = Metrics.meter(kls, "Metrics with short delay received");
        metricsWithLongDelayReceived = Metrics.meter(kls, "Metrics with long delay received");

            try {
                final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
                final String name = String.format("com.rackspacecloud.blueflood.io:type=%s", Instrumentation.class.getSimpleName());
                final ObjectName nameObj = new ObjectName(name);
                mbs.registerMBean(new Instrumentation() { }, nameObj);
            } catch (Exception exc) {
                log.error("Unable to register mbean for " + Instrumentation.class.getSimpleName(), exc);
            }
    }

    private Instrumentation() {/* Used for JMX exposure */}

    public static Timer.Context getReadTimerContext(String queryCF) {
        return readTimers.getTimerContext(queryCF, false);
    }

    public static Timer.Context getBatchReadTimerContext(String queryCF) {
        return readTimers.getTimerContext(queryCF, true);
    }

    public static Timer.Context getWriteTimerContext(String queryCF) {
        return writeTimers.getTimerContext(queryCF, false);
    }

    public static Timer.Context getBatchWriteTimerContext(String queryCF) {
        return writeTimers.getTimerContext(queryCF, true);
    }

    // Most error tracking is done in InstrumentedConnectionPoolMonitor
    // However, some issues can't be properly tracked using that alone.
    // For example, there is no good way to differentiate (in the connectionpoolmonitor)
    // a PoolTimeoutException indicating that Astyanax has to look in another host-specific-pool
    // to find a connection from one indicating Astyanax already looked in every pool and is
    // going to bubble up the exception to our reader/writer
    public static void markReadError() {
        readErrMeter.mark();
    }

    public static void markBatchReadError(ConnectionException e) {
        batchReadErrMeter.mark();
        if (e instanceof PoolTimeoutException) {
            allPoolsExhaustedException.mark();
        }
    }

    /**
     * Caller should explicitly call {@link com.rackspacecloud.blueflood.io.Instrumentation#markPoolExhausted()}
     * and {@link com.rackspacecloud.blueflood.io.Instrumentation#markReadError()}
     * @param e
     */
    @Deprecated
    public static void markReadError(ConnectionException e) {
        markReadError();
        if (e instanceof PoolTimeoutException) {
            allPoolsExhaustedException.mark();
        }
    }

    public static void markPoolExhausted() {
        allPoolsExhaustedException.mark();
    }

    public static void markWriteError() {
        writeErrMeter.mark();
    }

    public static void markWriteError(ConnectionException e) {
        markWriteError();
        if (e instanceof PoolTimeoutException) {
            allPoolsExhaustedException.mark();
        }
    }

    private static class ReadTimers {
        public Timer.Context getTimerContext(String queryCF, boolean batch) {
            final String metricName = (batch ? MetricRegistry.name("batched-", queryCF) : queryCF);

            final Timer timer = Metrics.timer(Instrumentation.class, "reads", metricName);
            return timer.time();
        }
    }

    private static class WriteTimers {
        public Timer.Context getTimerContext(String queryCF, boolean batch) {
            final String metricName = (batch ? MetricRegistry.name("batched", queryCF) : queryCF);

            final Timer timer = Metrics.timer(Instrumentation.class, "writes", metricName);
            return timer.time();
        }
    }

    public static void markNotFound(String columnFamilyName) {
        final Meter meter = Metrics.meter(Instrumentation.class, "reads", "Not Found", columnFamilyName);
        meter.mark();

    }

    public static void markScanAllColumnFamilies() {
        scanAllColumnFamiliesMeter.mark();
    }

    public static void markFullResMetricWritten() {
        fullResMetricWritten.mark();
    }

    public static void markFullResPreaggregatedMetricWritten() {
        fullResPreaggregatedMetricWritten.mark();
    }

    public static void markMetricsWithShortDelayReceived() {
        metricsWithShortDelayReceived.mark();
    }

    public static void markMetricsWithLongDelayReceived() {
        metricsWithLongDelayReceived.mark();
    }
}


text:
from django.apps import AppConfig

class ConferenceConfig(AppConfig):
    name = "symposion.conference"
    label = "symposion_conference"
    verbose_name = "Symposion Conference"


text:
namespace content {

TEST(URLSchemesTest, IsOriginSecure) {
  EXPECT_TRUE(IsOriginSecure(GURL("file:///test/fun.html")));
  EXPECT_TRUE(IsOriginSecure(GURL("file:///test/")));

  EXPECT_TRUE(IsOriginSecure(GURL("https://example.com/fun.html")));
  EXPECT_FALSE(IsOriginSecure(GURL("http://example.com/fun.html")));

  EXPECT_TRUE(IsOriginSecure(GURL("wss://example.com/fun.html")));
  EXPECT_FALSE(IsOriginSecure(GURL("ws://example.com/fun.html")));

  EXPECT_TRUE(IsOriginSecure(GURL("http://localhost/fun.html")));
  EXPECT_TRUE(IsOriginSecure(GURL("http://pumpkin.localhost/fun.html")));
  EXPECT_TRUE(
      IsOriginSecure(GURL("http://crumpet.pumpkin.localhost/fun.html")));
  EXPECT_TRUE(IsOriginSecure(GURL("http://pumpkin.localhost:8080/fun.html")));
  EXPECT_TRUE(
      IsOriginSecure(GURL("http://crumpet.pumpkin.localhost:3000/fun.html")));
  EXPECT_FALSE(IsOriginSecure(GURL("http://localhost.com/fun.html")));
  EXPECT_TRUE(IsOriginSecure(GURL("https://localhost.com/fun.html")));

  EXPECT_TRUE(IsOriginSecure(GURL("http://127.0.0.1/fun.html")));
  EXPECT_TRUE(IsOriginSecure(GURL("ftp://127.0.0.1/fun.html")));
  EXPECT_TRUE(IsOriginSecure(GURL("http://127.3.0.1/fun.html")));
  EXPECT_FALSE(IsOriginSecure(GURL("http://127.example.com/fun.html")));
  EXPECT_TRUE(IsOriginSecure(GURL("https://127.example.com/fun.html")));

  EXPECT_TRUE(IsOriginSecure(GURL("http://[::1]/fun.html")));
  EXPECT_FALSE(IsOriginSecure(GURL("http://[::2]/fun.html")));
  EXPECT_FALSE(IsOriginSecure(GURL("http://[::1].example.com/fun.html")));

  EXPECT_FALSE(
      IsOriginSecure(GURL("filesystem:http://www.example.com/temporary/")));
  EXPECT_FALSE(
      IsOriginSecure(GURL("filesystem:ftp://www.example.com/temporary/")));
  EXPECT_TRUE(IsOriginSecure(GURL("filesystem:ftp://127.0.0.1/temporary/")));
  EXPECT_TRUE(
      IsOriginSecure(GURL("filesystem:https://www.example.com/temporary/")));
}

}  // namespace content


text:
There's an easy way to reference ranges of commits by partial string matches on their messages.

Given four commits:

```bash
758d337 Freeze-dry ice cream
f983ef8 Update firmware
7ba375f Fix heat shields
cd1ccfc Add rocket thrusters
```

To interactively rebase the last three commits, I might have previously done:

```bash
git rebase -i HEAD^^^

# Or:

git rebase -i HEAD~3
```

The same thing can be accomplished with the much more readable:

```bash
git rebase -i :/rocket
```

Note that the range is referencing the fourth most recent commit, which will tell `rebase` to give us the last three.

This technique is also useful when using `git commit --fixup`.


text:
declare module 'rimraf' {
  declare type Options = {
	  maxBusyTries?: number,
	  emfileWait?: number,
	  glob?: boolean,
	  disableGlob?: boolean
  };

  declare type Callback = (err: ?Error, path: ?string) => void;

  declare module.exports: {
    (f: string, opts?: Options | Callback, callback?: Callback): void;
    sync(path: string, opts?: Options): void;
  };
}


text:
cordova.define('cordova/plugin_list', function(require, exports, module) {
module.exports = [
    {
        "file": "plugins/cordova-plugin-device-motion/www/Acceleration.js",
        "id": "cordova-plugin-device-motion.Acceleration",
        "pluginId": "cordova-plugin-device-motion",
        "clobbers": [
            "Acceleration"
        ]
    },
    {
        "file": "plugins/cordova-plugin-device-motion/www/accelerometer.js",
        "id": "cordova-plugin-device-motion.accelerometer",
        "pluginId": "cordova-plugin-device-motion",
        "clobbers": [
            "navigator.accelerometer"
        ]
    },
    {
        "file": "plugins/cordova-plugin-device-motion/src/browser/AccelerometerProxy.js",
        "id": "cordova-plugin-device-motion.AccelerometerProxy",
        "pluginId": "cordova-plugin-device-motion",
        "runs": true
    },
    {
        "file": "plugins/cordova-plugin-file/www/DirectoryEntry.js",
        "id": "cordova-plugin-file.DirectoryEntry",
        "pluginId": "cordova-plugin-file",
        "clobbers": [
            "window.DirectoryEntry"
        ]
    },
    {
        "file": "plugins/cordova-plugin-file/www/DirectoryReader.js",
        "id": "cordova-plugin-file.DirectoryReader",
        "pluginId": "cordova-plugin-file",
        "clobbers": [
            "window.DirectoryReader"
        ]
    },
    {
        "file": "plugins/cordova-plugin-file/www/Entry.js",
        "id": "cordova-plugin-file.Entry",
        "pluginId": "cordova-plugin-file",
        "clobbers": [
            "window.Entry"
        ]
    },
    {
        "file": "plugins/cordova-plugin-file/www/File.js",
        "id": "cordova-plugin-file.File",
        "pluginId": "cordova-plugin-file",
        "clobbers": [
            "window.File"
        ]
    },
    {
        "file": "plugins/cordova-plugin-file/www/FileEntry.js",
        "id": "cordova-plugin-file.FileEntry",
        "pluginId": "cordova-plugin-file",
        "clobbers": [
            "window.FileEntry"
        ]
    },
    {
        "file": "plugins/cordova-plugin-file/www/FileError.js",
        "id": "cordova-plugin-file.FileError",
        "pluginId": "cordova-plugin-file",
        "clobbers": [
            "window.FileError"
        ]
    },
    {
        "file": "plugins/cordova-plugin-file/www/FileReader.js",
        "id": "cordova-plugin-file.FileReader",
        "pluginId": "cordova-plugin-file",
        "clobbers": [
            "window.FileReader"
        ]
    },
    {
        "file": "plugins/cordova-plugin-file/www/FileSystem.js",
        "id": "cordova-plugin-file.FileSystem",
        "pluginId": "cordova-plugin-file",
        "clobbers": [
            "window.FileSystem"
        ]
    },
    {
        "file": "plugins/cordova-plugin-file/www/FileUploadOptions.js",
        "id": "cordova-plugin-file.FileUploadOptions",
        "pluginId": "cordova-plugin-file",
        "clobbers": [
            "window.FileUploadOptions"
        ]
    },
    {
        "file": "plugins/cordova-plugin-file/www/FileUploadResult.js",
        "id": "cordova-plugin-file.FileUploadResult",
        "pluginId": "cordova-plugin-file",
        "clobbers": [
            "window.FileUploadResult"
        ]
    },
    {
        "file": "plugins/cordova-plugin-file/www/FileWriter.js",
        "id": "cordova-plugin-file.FileWriter",
        "pluginId": "cordova-plugin-file",
        "clobbers": [
            "window.FileWriter"
        ]
    },
    {
        "file": "plugins/cordova-plugin-file/www/Flags.js",
        "id": "cordova-plugin-file.Flags",
        "pluginId": "cordova-plugin-file",
        "clobbers": [
            "window.Flags"
        ]
    },
    {
        "file": "plugins/cordova-plugin-file/www/LocalFileSystem.js",
        "id": "cordova-plugin-file.LocalFileSystem",
        "pluginId": "cordova-plugin-file",
        "clobbers": [
            "window.LocalFileSystem"
        ],
        "merges": [
            "window"
        ]
    },
    {
        "file": "plugins/cordova-plugin-file/www/Metadata.js",
        "id": "cordova-plugin-file.Metadata",
        "pluginId": "cordova-plugin-file",
        "clobbers": [
            "window.Metadata"
        ]
    },
    {
        "file": "plugins/cordova-plugin-file/www/ProgressEvent.js",
        "id": "cordova-plugin-file.ProgressEvent",
        "pluginId": "cordova-plugin-file",
        "clobbers": [
            "window.ProgressEvent"
        ]
    },
    {
        "file": "plugins/cordova-plugin-file/www/fileSystems.js",
        "id": "cordova-plugin-file.fileSystems",
        "pluginId": "cordova-plugin-file"
    },
    {
        "file": "plugins/cordova-plugin-file/www/requestFileSystem.js",
        "id": "cordova-plugin-file.requestFileSystem",
        "pluginId": "cordova-plugin-file",
        "clobbers": [
            "window.requestFileSystem"
        ]
    },
    {
        "file": "plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js",
        "id": "cordova-plugin-file.resolveLocalFileSystemURI",
        "pluginId": "cordova-plugin-file",
        "merges": [
            "window"
        ]
    },
    {
        "file": "plugins/cordova-plugin-file/www/browser/isChrome.js",
        "id": "cordova-plugin-file.isChrome",
        "pluginId": "cordova-plugin-file",
        "runs": true
    },
    {
        "file": "plugins/cordova-plugin-file/www/browser/Preparing.js",
        "id": "cordova-plugin-file.Preparing",
        "pluginId": "cordova-plugin-file",
        "runs": true
    },
    {
        "file": "plugins/cordova-plugin-file/src/browser/FileProxy.js",
        "id": "cordova-plugin-file.browserFileProxy",
        "pluginId": "cordova-plugin-file",
        "runs": true
    },
    {
        "file": "plugins/cordova-plugin-file/www/fileSystemPaths.js",
        "id": "cordova-plugin-file.fileSystemPaths",
        "pluginId": "cordova-plugin-file",
        "merges": [
            "cordova"
        ],
        "runs": true
    },
    {
        "file": "plugins/cordova-plugin-file/www/browser/FileSystem.js",
        "id": "cordova-plugin-file.firefoxFileSystem",
        "pluginId": "cordova-plugin-file",
        "merges": [
            "window.FileSystem"
        ]
    },
    {
        "file": "plugins/cordova-plugin-media/www/MediaError.js",
        "id": "cordova-plugin-media.MediaError",
        "pluginId": "cordova-plugin-media",
        "clobbers": [
            "window.MediaError"
        ]
    },
    {
        "file": "plugins/cordova-plugin-media/www/Media.js",
        "id": "cordova-plugin-media.Media",
        "pluginId": "cordova-plugin-media",
        "clobbers": [
            "window.Media"
        ]
    },
    {
        "file": "plugins/cordova-plugin-media/www/browser/Media.js",
        "id": "cordova-plugin-media.BrowserMedia",
        "pluginId": "cordova-plugin-media",
        "clobbers": [
            "window.Media"
        ]
    }
];
module.exports.metadata =
// TOP OF METADATA
{
    "cordova-plugin-device-motion": "1.2.2",
    "cordova-plugin-compat": "1.1.0",
    "cordova-plugin-file": "4.3.1",
    "cordova-plugin-media": "2.4.1",
    "cordova-plugin-crosswalk-webview": "2.1.0"
}
// BOTTOM OF METADATA
});


text:
package io.github.ihongs.test;

import io.github.ihongs.Cnst;
import io.github.ihongs.Core;
import io.github.ihongs.cmdlet.CmdletRunner;
import io.github.ihongs.util.Dawn;
import io.github.ihongs.util.Synt;
import io.github.ihongs.util.verify.IsNumber;
import io.github.ihongs.util.verify.IsString;
import io.github.ihongs.util.verify.Repeated;
import io.github.ihongs.util.verify.Required;
import io.github.ihongs.util.verify.Verify;
import io.github.ihongs.util.verify.Wrongs;
import java.io.IOException;
import java.util.Map;
import junit.framework.TestCase;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 *
 * @author Hongs
 */
public class TestVerify extends TestCase {

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    @Override
    public void setUp() {
    }

    @After
    @Override
    public void tearDown() {
    }

    @Test
    public void testVerify() throws IOException {
        // 避免路径缺失致写入项目主目录
        CmdletRunner.init(new String[] {"--COREPATH", "target"});

        try {
            Verify verify = new Verify()
                .addRule("name",
                    new Required(),
                    new IsString().config(Synt.mapOf("minlength", 3, "maxlength", 8))
                )
                .addRule("size",
                    new Repeated().config(Synt.mapOf("slice", ",")),
                    new IsNumber().config(Synt.mapOf("min", 10, "max", 99))
                );
            Map values = Synt.mapOf(
                "name", "abcdef",
                "size", "11,22"
            );
            Map cleans = verify.verify(values, false, false);
            System.out.println(Dawn.toString(cleans));
        }
        catch (Wrongs wr) {
            Core.ACTION_LANG.set(Cnst.LANG_DEF);
            fail(Dawn.toString(wr.getErrors()));
        }
    }

}