text:
import { rgbToHsla } from './utils/color';

export default class Point {
  x: number;
  y: number;
  radius = 1;
  color = 'black';

  private _canvasColor?: string;

  static colorAtPoint(
    point: Point,
    imageData: ImageData,
    colorSpace: 'hsla' | 'rgb' = 'hsla',
  ): string {
    // use canvas edge colors if off-canvas
    const x = Math.min(point.x, imageData.width - 1);
    const y = Math.min(point.y, imageData.height - 1);

    // imageData array is flat, goes by rows then cols, four values per pixel
    const idx = Math.floor(y) * imageData.width * 4 + Math.floor(x) * 4;
    const rgb = Array.prototype.slice.call(imageData.data, idx, idx + 3) as [
      number,
      number,
      number,
    ];

    if (colorSpace === 'hsla') {
      return rgbToHsla(rgb);
    } else {
      return 'rgb(' + rgb.join(',') + ')';
    }
  }

  constructor(x: [number, number]);
  constructor(x: number, y: number);
  constructor(x: [number, number] | number, y?: number) {
    if (Array.isArray(x)) {
      this.x = x[0];
      this.y = x[1];
    } else {
      this.x = x;
      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
      this.y = y!;
    }
  }

  // draw the point
  render(ctx: CanvasRenderingContext2D, color?: string): void {
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false);
    ctx.fillStyle = color || this.color;
    ctx.fill();
    ctx.closePath();
  }

  /**
   * converts to string, used in the pointMap to detect unique points
   * @returns string @example "(2,3)"
   */
  toString(): string {
    return '(' + this.x + ',' + this.y + ')';
  }

  /**
   * grab the color of the canvas at the point
   * imageData is required so we don't grab each point individually, which is really expensive
   */
  canvasColorAtPoint(
    imageData: ImageData,
    colorSpace: 'hsla' | 'rgb' = 'hsla',
  ): string {
    // only find the canvas color if we don't already know it
    if (!this._canvasColor) {
      this._canvasColor = Point.colorAtPoint(this, imageData, colorSpace);
    }
    return this._canvasColor;
  }

  getCoords(): [number, number] {
    return [this.x, this.y];
  }

  getMidPoint(point: Point): Point {
    return new Point((this.x + point.x) / 2, (this.y + point.y) / 2);
  }

  // distance to another point
  getDistanceTo(point: Point): number {
    // √(x2−x1)^2+(y2−y1)^2
    return Math.sqrt(
      Math.pow(this.x - point.x, 2) + Math.pow(this.y - point.y, 2),
    );
  }

  /**
   * scale points from [A, B] to [C, D]
   * xA => old x min, xB => old x max
   * yA => old y min, yB => old y max
   * xC => new x min, xD => new x max
   * yC => new y min, yD => new y max
   */
  rescale(
    xA: number,
    xB: number,
    yA: number,
    yB: number,
    xC: number,
    xD: number,
    yC: number,
    yD: number,
  ): void {
    // NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin

    const xOldRange = xB - xA;
    const yOldRange = yB - yA;

    const xNewRange = xD - xC;
    const yNewRange = yD - yC;

    this.x = ((this.x - xA) * xNewRange) / xOldRange + xC;
    this.y = ((this.y - yA) * yNewRange) / yOldRange + yC;
  }

  resetColor(): void {
    this._canvasColor = undefined;
  }
}


text:
package core

import (
	"encoding/binary"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"sync"
	"time"
	"io/ioutil"
	"github.com/hmli/simplefs/utils"
)

const (
	TruncateSize  uint64 = 1 << 30            //1GB
	MaxVolumeSize uint64 = 128 * TruncateSize // 128GB
	InitIndexSize uint64 = 8
	DefaultDir    string = "/tmp/fs"
)

// TODO Compression
// TODO Several volumes make up a Store
type Volume struct {
	ID            uint64
	File          *os.File
	Directory     Directory
	Size          uint64
	Path          string
	CurrentOffset uint64 // 从文件中恢复的时候, 第一个byte就是currentoffset. 每次写入文件也要更新此offset。
	lock          sync.Mutex
}

func NewVolume(id uint64, dir string) (v *Volume, err error) {
	if dir == "" {
		dir = DefaultDir
	}
	pathMustExists(dir)
	filepath := filepath.Join(dir, strconv.FormatUint(id, 10)+".data")
	v = new(Volume)
	v.ID = id
	v.Path = dir
	v.File, err = os.OpenFile(filepath, os.O_CREATE|os.O_RDWR, 0666)
	if err != nil {
		return nil, fmt.Errorf("Open file: ", err)
	}
	v.Directory, err = NewLeveldbDirectory(dir)
	if err != nil {
		return nil, fmt.Errorf("Leveldb: ", err)
	}

	var oldCurrentIndex []byte = make([]byte, InitIndexSize)
	_, err = v.File.ReadAt(oldCurrentIndex, 0) // Read old current index from file
	if err != nil && err != io.EOF{
		return nil, err
	}
	oldCurrentIndexNum := binary.BigEndian.Uint64(oldCurrentIndex)
	if oldCurrentIndexNum > InitIndexSize {
		v.setCurrentIndex(oldCurrentIndexNum)
	} else {
		v.setCurrentIndex(InitIndexSize)
	}
	v.Size = MaxVolumeSize
	v.lock = sync.Mutex{}
	return
}

func (v *Volume) GetNeedle(id uint64) (n *Needle, err error) {
	n, err = v.Directory.Get(id)
	if err != nil {
		return
	}
	n.File = v.File
	return
}

func (v *Volume) GetFile(id uint64) (data []byte, ext string, err error) {
	needle, err := v.GetNeedle(id)
	if err != nil {
		return data, ext, fmt.Errorf("Get needle ", err)
	}
	ext = needle.FileExt
	data, err = ioutil.ReadAll(needle)
	if err != nil {
		return nil, "", err
	}
	checksum := utils.Checksum(data)
	if checksum != needle.Checksum {
		return nil, "", ErrWrongCheckSum
	}
	return
}

func (v *Volume) DelNeedle(id uint64) (err error) {
	v.lock.Lock()
	defer v.lock.Unlock()
	_, err = v.GetNeedle(id)
	if err != nil && err != ErrDeleted{
		return err
	}
	return v.Directory.Del(id)
}

// NewNeedle allocate a new needle.
func (v *Volume) NewNeedle(id uint64, data []byte, filename string) (n *Needle, err error) {
	size := uint64(len(data))
	v.lock.Lock()
	defer v.lock.Unlock()
	// 1. alloc space
	// 2. set needle's header
	// 3. make needle
	ext := Ext(filename)
	offset, err := v.allocSpace(size, uint64(len(ext)))
	if err != nil {
		return nil, err
	}
	n = new(Needle)
	n.ID = id
	n.Size = size
	n.Offset = offset
	n.Checksum = utils.Checksum(data)
	now := time.Now()
	n.CreatedAt = now
	n.UpdatedAt = now
	n.File = v.File
	n.FileExt = ext
	needleData, err := NeedleMarshal(n)
	if err != nil {
		return
	}
	v.File.WriteAt(needleData, int64(n.Offset))
	err = v.Directory.New(n)
	if err != nil {
		err = fmt.Errorf("Leveldb: ", err)
	}
	return n, err
}

func (v *Volume) NewFile(data []byte, filename string) (id uint64, err error) {
	id = utils.UniqueId()
	//needle, err := v.NewNeedle(id, uint64(len(data)), filename)
	needle, err := v.NewNeedle(id, data, filename)

	if err != nil {
		return id, fmt.Errorf("New needle : ", err)
	}
	_, err = needle.Write(data)
	if err != nil {
		return
	}
	return id, err
}

func (v *Volume) currentOffset() (offset uint64, err error) {
	var i []byte = make([]byte, 8)
	_, err = v.File.ReadAt(i, 0)
	if err != nil {
		return 0, err
	}
	offset = binary.BigEndian.Uint64(i)
	return
}

func (v *Volume) allocSpace(filesize uint64, extsize uint64) (offset uint64, err error) {
	remainingSize := v.RemainingSpace()
	totalSize := filesize + HeaderSize(extsize)
	if remainingSize < totalSize {
		return v.CurrentOffset, ErrLeakSpace
	}
	offset = v.CurrentOffset
	v.setCurrentIndex( v.CurrentOffset + HeaderSize(extsize) + filesize)
	return
}

func (v *Volume) setCurrentIndex(currentOffset uint64) (err error) {
	v.CurrentOffset = currentOffset
	var offsetByte []byte = make([]byte, 8) // starts with 1 byte storing current index
	binary.BigEndian.PutUint64(offsetByte, v.CurrentOffset)
	_, err = v.File.WriteAt(offsetByte, 0)
	return
}

func (v *Volume) RemainingSpace() (size uint64) {
	return v.Size - v.CurrentOffset
}

func (v *Volume) Fragment() (err error) {
	v.lock.Lock()
	defer v.lock.Unlock()
	newFilePath := v.File.Name() + ".temp" // filepath.Join(v.Path, strconv.FormatUint(v.ID, 10)+".temp")
	newFile, err := os.OpenFile(newFilePath, os.O_CREATE|os.O_RDWR, 0666)
	if err != nil {
		return  fmt.Errorf("Open file: ", err)
	}
	iter := v.Directory.Iter()
	var key []byte = make([]byte, 8)
	var exists bool = true
	var currentOffset int64 = int64(InitIndexSize)
	for exists {
		key, exists = iter.Next()
		if !exists {
			break
		}
		id := binary.BigEndian.Uint64(key)
		needle, err := v.GetNeedle(id) // 读取一个needle
		if err != nil {
			fmt.Println("Read needle err: ", err)
			continue
		}
		offset := int64(needle.Offset)
		size := int64(needle.Size) + int64(HeaderSize(uint64(len(needle.FileExt))))
		var needleData []byte = make([]byte, size)
		v.File.ReadAt(needleData, offset)
		_, err = newFile.WriteAt(needleData, currentOffset) // 修改 offset, 并写到新文件中
		fmt.Println("Write: ", currentOffset, needleData)
		if err != nil {
			fmt.Println("Write err: ",err)
			continue
		}
		fmt.Println("Current offset: ", currentOffset)
		needle.Offset = uint64(currentOffset)
		v.Directory.Set(needle.ID, needle) // 更新 needle
		currentOffset += size
	}
	var currentOffsetByte = make([]byte, InitIndexSize)
	binary.BigEndian.PutUint64(currentOffsetByte, uint64(currentOffset))
	newFile.WriteAt(currentOffsetByte, 0)
	v.setCurrentIndex(uint64(currentOffset))
	fullpath:= v.File.Name()
	// 给老文件改名
	delpath := fullpath + ".del"
	fmt.Println("Old change name: ", fullpath, delpath)
	delFile , err := os.OpenFile(delpath, os.O_CREATE|os.O_RDWR, 0666)
	if err != nil {
		return
	}
	if delFile != nil {
		defer delFile.Close()
	}
	err = os.Rename(fullpath, delpath)
	if err != nil {
		return
	}
	err = os.Rename(newFilePath, fullpath)
	if err != nil {
		os.Rename(delpath, fullpath) // 出错, 把已经改掉的老文件的名字改回去
		return
	}
	v.File = newFile
	v.Path = newFilePath
	fmt.Println("New change name: ", delpath, fullpath)
	err = os.Remove(delpath)
	fmt.Println("Deleted: ", delpath)
	return
}

func (v *Volume) Print() {
	iter := v.Directory.Iter()
	var hasNext bool = true
	for hasNext {
		var key []byte
		key, hasNext = iter.Next()
		if hasNext {
			id := binary.BigEndian.Uint64(key)
			n, err := v.GetNeedle(id)
			if err != nil && err != ErrDeleted  {
				fmt.Println("Err: ", err)
			}
			fmt.Printf("id: %d, offset: %d \n", id, n.Offset)
			var b []byte = make([]byte, n.Size)
			dataOffset := n.Offset + HeaderSize(uint64(len(n.FileExt)))
			v.File.ReadAt(b, int64(dataOffset))
			fmt.Println("data: ", n.FileExt, string(b))
		} else {
			fmt.Println("-------- Finish-------")
		}
	}
	iter.Release()
}

func (v *Volume) CheckCurrentIndex() (same bool) {
	i1 := v.CurrentOffset
	b := make([]byte, InitIndexSize)
	v.File.ReadAt(b, 0)
	fmt.Println(b)
	i2 := binary.BigEndian.Uint64(b)
	return i1 == i2
}

func (v *Volume) ReadHeader(offset int64) (header []byte, err error) {
	var b []byte = make([]byte, NeedleFixSize)
	v.File.ReadAt(b, offset)
	fmt.Println(b)
	n, err := NeedleUnmarshal(b)
	if err != nil {
		return
	}
	header = make([]byte, len(b) + len(n.FileExt))
	v.File.ReadAt(header[:len(b)], offset)
	v.File.ReadAt(header[len(b):], offset + int64(len(b)))
	return
}

// 从完整文件名中获取扩展名
func Ext(filename string) (ext string) {
	index := strings.LastIndex(filename, ".")
	fmt.Println(index)
	if index == -1 {
		return ""
	}
	return strings.TrimSpace(filename[index+1:])
}

func pathExist(path string) bool {
	_, err := os.Stat(path)
	if err != nil && os.IsNotExist(err) {
		return false
	}
	return true
}

func pathMustExists(path string) {
	exists := pathExist(path)
	if !exists {
		err := os.MkdirAll(path, 0755)
		if err != nil {
			panic("Path Must exists: " +  err.Error())
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

import gulp from 'gulp';
import del from 'del';

// clean the build dir
gulp.task('clean', () => {
    del([`${global.paths.dist}/*`]);
});


text:
SBOX_SRC=../src/rtl/aes_sbox.v
INV_SBOX_SRC=../src/rtl/aes_inv_sbox.v
KEYMEM_SRC=../src/rtl/aes_key_mem.v
ENCIPHER_SRC=../src/rtl/aes_encipher_block.v
DECIPHER_SRC=../src/rtl/aes_decipher_block.v
CORE_SRC=../src/rtl/aes_core.v $(KEYMEM_SRC) $(SBOX_SRC) $(INV_SBOX_SRC) $(ENCIPHER_SRC) $(DECIPHER_SRC)
TOP_SRC=../src/rtl/aes.v $(CORE_SRC)

TB_TOP_SRC =../src/tb/tb_aes.v
TB_CORE_SRC =../src/tb/tb_aes_core.v
TB_KEYMEM_SRC =../src/tb/tb_aes_key_mem.v
TB_ENCIPHER_SRC =../src/tb/tb_aes_encipher_block.v
TB_DECIPHER_SRC =../src/tb/tb_aes_decipher_block.v

CC = iverilog
CC_FLAGS = -Wall

LINT = verilator
LINT_FLAGS = +1364-2001ext+ --lint-only  -Wall -Wno-fatal -Wno-DECLFILENAME

all: top.sim core.sim keymem.sim encipher.sim decipher.sim

top.sim: $(TB_TOP_SRC) $(TOP_SRC)
	$(CC) $(CC_FLAGS) -o $@ $^

core.sim: $(TB_CORE_SRC) $(CORE_SRC)
	$(CC) $(CC_FLAGS) -o $@ $^

keymem.sim:  $(TB_KEYMEM_SRC) $(KEYMEM_SRC) $(SBOX_SRC)
	$(CC) $(CC_FLAGS) -o $@ $^

encipher.sim:  $(TB_ENCIPHER_SRC) $(ENCIPHER_SRC) $(SBOX_SRC)
	$(CC) $(CC_FLAGS) -o $@ $^

decipher.sim:  $(TB_DECIPHER_SRC) $(DECIPHER_SRC) $(INV_SBOX_SRC)
	$(CC) $(CC_FLAGS) -o $@ $^

sim-keymem: keymem.sim
	./keymem.sim

sim-encipher: encipher.sim
	./encipher.sim

sim-decipher: decipher.sim
	./decipher.sim

sim-core: core.sim
	./core.sim

sim-top: top.sim
	./top.sim

lint:  $(TOP_SRC)
	$(LINT) $(LINT_FLAGS) $^

clean:
	rm -f decipher.sim
	rm -f encipher.sim
	rm -f keymem.sim
	rm -f core.sim
	rm -f top.sim

help:
	@echo "Build system for simulation of AES Verilog core"
	@echo ""
	@echo "Supported targets:"
	@echo "------------------"
	@echo "all:          Build all simulation targets."
	@echo "top.sim:      Build top level simulation target."
	@echo "core.sim:     Build core level simulation target."
	@echo "keymem.sim:   Build key memory simulation target."
	@echo "encipher.sim: Build encipher block simulation target."
	@echo "decipher.sim: Build decipher block simulation target."
	@echo "sim-top:      Run top level simulation."
	@echo "sim-core:     Run core level simulation."
	@echo "sim-keymem    Run keymem simulation."
	@echo "sim-encipher  Run encipher block simulation."
	@echo "sim-decipher  Run decipher block simulation."
	@echo "lint:         Lint all rtl source files."
	@echo "clean:        Delete all built files."

#===================================================================
# EOF Makefile
#===================================================================


text:
import * as React from 'react'
import { Dispatcher } from '../../lib/dispatcher'
import {
  SignInState,
  SignInStep,
  IEndpointEntryState,
  IAuthenticationState,
  ITwoFactorAuthenticationState,
} from '../../lib/stores'
import { assertNever } from '../../lib/fatal-error'
import { Button } from '../lib/button'
import { LinkButton } from '../lib/link-button'
import { Octicon, OcticonSymbol } from '../octicons'
import { Row } from '../lib/row'
import { TextBox } from '../lib/text-box'
import { ButtonGroup } from '../lib/button-group'
import { Dialog, DialogError, DialogContent, DialogFooter } from '../dialog'

import { getWelcomeMessage } from '../../lib/2fa'

interface ISignInProps {
  readonly dispatcher: Dispatcher
  readonly signInState: SignInState | null
  readonly onDismissed: () => void
}

interface ISignInState {
  readonly endpoint: string
  readonly username: string
  readonly password: string
  readonly otpToken: string
}

export class SignIn extends React.Component<ISignInProps, ISignInState> {
  public constructor(props: ISignInProps) {
    super(props)

    this.state = {
      endpoint: '',
      username: '',
      password: '',
      otpToken: '',
    }
  }

  public componentWillReceiveProps(nextProps: ISignInProps) {
    if (nextProps.signInState !== this.props.signInState) {
      if (
        nextProps.signInState &&
        nextProps.signInState.kind === SignInStep.Success
      ) {
        this.props.onDismissed()
      }
    }
  }

  private onSubmit = () => {
    const state = this.props.signInState

    if (!state) {
      return
    }

    const stepKind = state.kind

    switch (state.kind) {
      case SignInStep.EndpointEntry:
        this.props.dispatcher.setSignInEndpoint(this.state.endpoint)
        break
      case SignInStep.Authentication:
        if (!state.supportsBasicAuth) {
          this.props.dispatcher.requestBrowserAuthentication()
        } else {
          this.props.dispatcher.setSignInCredentials(
            this.state.username,
            this.state.password
          )
        }
        break
      case SignInStep.TwoFactorAuthentication:
        this.props.dispatcher.setSignInOTP(this.state.otpToken)
        break
      case SignInStep.Success:
        this.props.onDismissed()
        break
      default:
        return assertNever(state, `Unknown sign in step ${stepKind}`)
    }
  }

  private onEndpointChanged = (endpoint: string) => {
    this.setState({ endpoint })
  }

  private onUsernameChanged = (username: string) => {
    this.setState({ username })
  }

  private onPasswordChanged = (password: string) => {
    this.setState({ password })
  }

  private onOTPTokenChanged = (otpToken: string) => {
    this.setState({ otpToken })
  }

  private onSignInWithBrowser = () => {
    this.props.dispatcher.requestBrowserAuthentication()
  }

  private renderFooter(): JSX.Element | null {
    const state = this.props.signInState

    if (!state || state.kind === SignInStep.Success) {
      return null
    }

    let disableSubmit = false

    let primaryButtonText: string
    const stepKind = state.kind

    switch (state.kind) {
      case SignInStep.EndpointEntry:
        disableSubmit = this.state.endpoint.length === 0
        primaryButtonText = 'Continue'
        break
      case SignInStep.TwoFactorAuthentication:
        // ensure user has entered non-whitespace characters
        const codeProvided = /\S+/.test(this.state.otpToken)
        disableSubmit = !codeProvided
        primaryButtonText = 'Sign in'
        break
      case SignInStep.Authentication:
        if (!state.supportsBasicAuth) {
          primaryButtonText = __DARWIN__
            ? 'Continue With Browser'
            : 'Continue with browser'
        } else {
          const validUserName = this.state.username.length > 0
          const validPassword = this.state.password.length > 0
          disableSubmit = !validUserName || !validPassword
          primaryButtonText = 'Sign in'
        }
        break
      default:
        return assertNever(state, `Unknown sign in step ${stepKind}`)
    }

    return (
      <DialogFooter>
        <ButtonGroup>
          <Button disabled={disableSubmit} type="submit">
            {primaryButtonText}
          </Button>
          <Button onClick={this.props.onDismissed}>Cancel</Button>
        </ButtonGroup>
      </DialogFooter>
    )
  }

  private renderEndpointEntryStep(state: IEndpointEntryState) {
    return (
      <DialogContent>
        <Row>
          <TextBox
            label="Enterprise server address"
            value={this.state.endpoint}
            onValueChanged={this.onEndpointChanged}
            placeholder="https://github.example.com"
          />
        </Row>
      </DialogContent>
    )
  }

  private renderAuthenticationStep(state: IAuthenticationState) {
    if (!state.supportsBasicAuth) {
      return (
        <DialogContent>

            Your GitHub Enterprise instance requires you to sign in with your
            browser.

        </DialogContent>
      )
    }

    const disableSubmit = state.loading

    return (
      <DialogContent>
        <Row>
          <TextBox
            label="Username or email address"
            value={this.state.username}
            onValueChanged={this.onUsernameChanged}
          />
        </Row>
        <Row>
          <TextBox
            label="Password"
            value={this.state.password}
            type="password"
            onValueChanged={this.onPasswordChanged}
            labelLinkText="Forgot password?"
            labelLinkUri={state.forgotPasswordUrl}
          />
        </Row>

          or

        <Row className="sign-in-with-browser">
          <LinkButton
            className="link-with-icon"
            onClick={this.onSignInWithBrowser}
            disabled={disableSubmit}
          >
            Sign in using your browser
            <Octicon symbol={OcticonSymbol.linkExternal} />
          </LinkButton>
        </Row>
      </DialogContent>
    )
  }

  private renderTwoFactorAuthenticationStep(
    state: ITwoFactorAuthenticationState
  ) {
    return (
      <DialogContent>

{getWelcomeMessage(state.type)}

        <Row>
          <TextBox
            label="Authentication code"
            value={this.state.otpToken}
            onValueChanged={this.onOTPTokenChanged}
            labelLinkText={`What's this?`}
            labelLinkUri="https://help.github.com/articles/providing-your-2fa-authentication-code/"
          />
        </Row>
      </DialogContent>
    )
  }

  private renderStep(): JSX.Element | null {
    const state = this.props.signInState

    if (!state) {
      return null
    }

    const stepKind = state.kind

    switch (state.kind) {
      case SignInStep.EndpointEntry:
        return this.renderEndpointEntryStep(state)
      case SignInStep.Authentication:
        return this.renderAuthenticationStep(state)
      case SignInStep.TwoFactorAuthentication:
        return this.renderTwoFactorAuthenticationStep(state)
      case SignInStep.Success:
        return null
      default:
        return assertNever(state, `Unknown sign in step ${stepKind}`)
    }
  }

  public render() {
    const state = this.props.signInState

    if (!state || state.kind === SignInStep.Success) {
      return null
    }

    const disabled = state.loading

    const errors = state.error ? (
      <DialogError>{state.error.message}</DialogError>
    ) : null

    return (
      <Dialog
        id="sign-in"
        title="Sign in"
        disabled={disabled}
        onDismissed={this.props.onDismissed}
        onSubmit={this.onSubmit}
        loading={state.loading}
      >
        {errors}
        {this.renderStep()}
        {this.renderFooter()}
      </Dialog>
    )
  }
}


text:
@keyframes ngBoxBounce {
  0%,10% {
    transform: translateY(0%);
  }
  90%,100% {
    transform: translateY(-100%);
  }
}
.ngBoxBounceWrapper {
  overflow: hidden;
}
.ngBoxBounceScroller {
  animation-name: ngBoxBounce;
  animation-iteration-count: infinite;
  animation-direction: alternate;
  animation-fill-mode: forwards;
}


text:
"""
Caches for memoization
"""

from __future__ import absolute_import, unicode_literals

__all__ = ("LRUCache", "FIFOCache", "TimedCache")

from collections import OrderedDict
from time import time

class LRUCache(OrderedDict):
    """Self-pruning cache using an LRU strategy.

    If instantiated with a ``max_size`` other than ``0``, will
    automatically prune the least-recently-used (LRU) key/value
    pair when inserting an item after reaching the specified size.

    An item is considered to be "used" when it is inserted or
    accessed, at which point its position in recently used
    queue is updated to the most recent.

    Supports all standard dictionary methods.

    :param int max_size: maximum number of entries to save
        before pruning
    """

    def __init__(self, max_size=0, *args, **kwargs):
        super(LRUCache, self).__init__(*args, **kwargs)
        self._max_size = max_size

    def __getitem__(self, key, **kwargs):
        value = OrderedDict.__getitem__(self, key)
        del self[key]
        OrderedDict.__setitem__(self, key, value, **kwargs)  # type: ignore
        return value

    def __setitem__(self, key, value, **kwargs):
        if key in self:
            del self[key]
        OrderedDict.__setitem__(self, key, value, **kwargs)  # type: ignore
        if self._max_size and len(self) > self._max_size:
            self.popitem(last=False)

class FIFOCache(OrderedDict):
    """Self-pruning cache using a FIFO strategy

    If instantiated with a ``max_size`` other than ``0``, will
    automatically prune the least-recently-inserted key/value
    pair when inserting an item after reaching the specified
    size.

    Supports all standard dictionary methods.

    :param int max_size: maximum number of entries to save
        before pruning
    """

    def __init__(self, max_size=0, *args, **kwargs):
        super(FIFOCache, self).__init__(*args, **kwargs)
        self._max_size = max_size

    def __setitem__(self, key, value, **kwargs):
        OrderedDict.__setitem__(self, key, value)
        if self._max_size and len(self) > self._max_size:
            self.popitem(last=False)

class TimedCache(dict):
    """Self-pruning cache whose entries can be set to expire

    If instantiated with a ``max_age`` other than ``0``, will
    consider entries older than the specified age to be invalid,
    removing them from the cache upon an attempt to access them
    and returning as though they do not exist.

    Supports all standard dictionary methods.

    :param int max_age: age in seconds beyond which entries
        should be considered invalid. The default is 0, which
        means that entries should be stored forever.
    """

    def __init__(self, max_age=0, *args, **kwargs):
        super(TimedCache, self).__init__(*args, **kwargs)
        self._max_age = max_age

    def __getitem__(self, key):
        value, last_time = dict.__getitem__(self, key)
        now = time()
        if self._max_age and now - last_time > self._max_age:
            del self[key]
            raise KeyError(key)
        else:
            return value

    def __setitem__(self, key, value):
        now = time()
        dict.__setitem__(self, key, (value, now))

    def __contains__(self, key):
        try:
            self.__getitem__(key)
        except KeyError:
            return False
        return True


text:
package com.imagepicker.ui;

import android.support.test.espresso.ViewInteraction;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.LargeTest;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

import com.imagepicker.R;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withClassName;
import static android.support.test.espresso.matcher.ViewMatchers.withContentDescription;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.is;

@LargeTest
@RunWith(AndroidJUnit4.class)
public class PickerActivityTest2 {

    @Rule
    public ActivityTestRule<PickerActivity> mActivityTestRule = new ActivityTestRule<>(PickerActivity.class);

    @Test
    public void pickerActivityTest2() {
        // Added a sleep statement to match the app's execution delay.
        // The recommended way to handle such scenarios is to use Espresso idling resources:
        // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html
        try {
            Thread.sleep(60000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        ViewInteraction appCompatButton = onView(
                allOf(withId(R.id.btn_gallery), withText("Open Gallery"),
                        childAtPosition(
                                childAtPosition(
                                        withClassName(is("android.support.design.widget.CoordinatorLayout")),
                                        1),
                                0),
                        isDisplayed()));
        appCompatButton.perform(click());

        // Added a sleep statement to match the app's execution delay.
        // The recommended way to handle such scenarios is to use Espresso idling resources:
        // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html
        try {
            Thread.sleep(60000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        ViewInteraction simpleDraweeView = onView(
                allOf(withId(R.id.media_image), withContentDescription("Media Item"),
                        childAtPosition(
                                childAtPosition(
                                        withClassName(is("android.support.v7.widget.CardView")),
                                        0),
                                0),
                        isDisplayed()));
        simpleDraweeView.perform(click());

        ViewInteraction simpleDraweeView2 = onView(
                allOf(withId(R.id.media_image), withContentDescription("Media Item"),
                        childAtPosition(
                                childAtPosition(
                                        withClassName(is("android.support.v7.widget.CardView")),
                                        0),
                                0),
                        isDisplayed()));
        simpleDraweeView2.perform(click());

        ViewInteraction appCompatSpinner = onView(
                allOf(withId(R.id.spinner_folder),
                        childAtPosition(
                                allOf(withId(R.id.toolbar),
                                        childAtPosition(
                                                withId(R.id.appbar),
                                                0)),
                                0),
                        isDisplayed()));
        appCompatSpinner.perform(click());

        ViewInteraction actionMenuItemView = onView(
                allOf(withId(R.id.action_save), withText("Save"),
                        childAtPosition(
                                childAtPosition(
                                        withId(R.id.toolbar),
                                        2),
                                1),
                        isDisplayed()));
        actionMenuItemView.perform(click());

    }

    private static Matcher<View> childAtPosition(
            final Matcher<View> parentMatcher, final int position) {

        return new TypeSafeMatcher<View>() {
            @Override
            public void describeTo(Description description) {
                description.appendText("Child at position " + position + " in parent ");
                parentMatcher.describeTo(description);
            }

            @Override
            public boolean matchesSafely(View view) {
                ViewParent parent = view.getParent();
                return parent instanceof ViewGroup && parentMatcher.matches(parent)
                        && view.equals(((ViewGroup) parent).getChildAt(position));
            }
        };
    }
}


text:
module DockerCloud
  class Provider < DockerCloud::Type
    attr_accessor :name, :label, :regions, :available

    def name
      info[:name]
    end

    def label
      info[:label]
    end

    def resource_uri
      info[:resource_uri]
    end

    def available
      info[:available]
    end

    def regions
      if @regions.nil?
        @regions = []
        info[:regions].each do |region|
          @regions.push(client.regions.get_from_uri(region))
        end
      end
      @regions
    end
  end
end


text:
namespace hana = boost::hana;

template <char op>
constexpr auto function = hana::nothing;

template <>
BOOST_HANA_CONSTEXPR_LAMBDA auto function<'+'> = hana::just([](auto x, auto y) {
    return x + y;
});

template <>
BOOST_HANA_CONSTEXPR_LAMBDA auto function<'-'> = hana::just([](auto x, auto y) {
    return x - y;
});

// and so on...

template <char n>
constexpr auto digit = hana::if_(hana::bool_c<(n >= '0' && n <= '9')>,
    hana::just(static_cast<int>(n - 48)),
    hana::nothing
);

template <char x, char op, char y>
BOOST_HANA_CONSTEXPR_LAMBDA auto evaluate = hana::ap(function<op>, digit<x>, digit<y>);

int main() {
    BOOST_HANA_CONSTEXPR_CHECK(evaluate<'1', '+', '2'> == hana::just(1 + 2));

    BOOST_HANA_CONSTANT_CHECK(evaluate<'?', '+', '2'> == hana::nothing);
    BOOST_HANA_CONSTANT_CHECK(evaluate<'1', '?', '2'> == hana::nothing);
    BOOST_HANA_CONSTANT_CHECK(evaluate<'1', '+', '?'> == hana::nothing);
    BOOST_HANA_CONSTANT_CHECK(evaluate<'?', '?', '?'> == hana::nothing);

    static_assert(hana::lift<hana::optional_tag>(123) == hana::just(123), "");
}


text:
<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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
        <properties>
            <project.build.sourceEncoding>ISO-8859-1</project.build.sourceEncoding>
        </properties>
	<parent>
		<artifactId>parent-pom-os</artifactId>
		<groupId>es.upm.oeg</groupId>
		<version>1.0</version>
	</parent>

	<groupId>es.upm.oeg.geolinkeddata</groupId>
	<artifactId>map4rdf</artifactId>
	<version>0.0.3-OL-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>Map4RDF</name>

	<dependencies>
		<dependency>
			<groupId>de.micromata.jak</groupId>
			<artifactId>JavaAPIforKml</artifactId>
			<version>2.2.0</version>
		</dependency>
		<dependency>
			<groupId>com.google.gwt</groupId>
			<artifactId>gwt-user</artifactId>
			<version>2.0.4</version>
		</dependency>
		<dependency>
			<groupId>com.google.gwt</groupId>
			<artifactId>gwt-servlet</artifactId>
			<version>2.0.4</version>
		</dependency>
		<dependency>
			<groupId>com.google.gwt.google-apis</groupId>
			<artifactId>gwt-maps</artifactId>
			<version>1.0.4</version>
		</dependency>
		<dependency>
			<groupId>com.googlecode.gwtquery</groupId>
			<artifactId>gquery-plugin-archetype</artifactId>
			<version>0.5</version>
		</dependency>
		<dependency>
			<groupId>name.alexdeleon.lib</groupId>
			<artifactId>gwt-blocks</artifactId>
			<version>0.0.7</version>
		</dependency>
		<dependency>
			<groupId>com.google.inject</groupId>
			<artifactId>guice</artifactId>
			<version>2.0</version>
		</dependency>
		<dependency>
			<groupId>org.tmatesoft.sqljet</groupId>
			<artifactId>sqljet</artifactId>
			<version>1.0.7</version>
		</dependency>
		<dependency>
			<groupId>com.google.inject.extensions</groupId>
			<artifactId>guice-servlet</artifactId>
			<version>2.0</version>
		</dependency>
		<dependency>
			<groupId>com.hp.hpl.jena</groupId>
			<artifactId>arq</artifactId>
			<version>2.8.3</version>
		</dependency>
		<dependency>
			<groupId>org.xerial</groupId>
			<artifactId>sqlite-jdbc</artifactId>
			<version>3.7.2</version>
		</dependency>
		<dependency>
		  <groupId>map4rdf_maven</groupId>
		  <artifactId>fake_compiler</artifactId>
		  <version>0.1</version>
		  <type>class</type>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</version>
			<exclusions>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.5.6</version>
		</dependency>
		<dependency>
		  <groupId>com.smartgwt</groupId>
		  <artifactId>smartgwt</artifactId>
		  <version>2.0</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.5.6</version>
		</dependency>
		<dependency>
			<groupId>com.google.gwt</groupId>
			<artifactId>gwt-incubator</artifactId>
			<version>2.0.1</version>
		</dependency>

		<dependency>
			<groupId>org.gwtopenmaps.openlayers</groupId>
			<artifactId>gwt-openlayers-client</artifactId>
			<version>0.7</version>
		</dependency>
		<dependency>
			<groupId>org.mindrot</groupId>
			<artifactId>jbcrypt</artifactId>
			<version>0.3m</version>
		</dependency>
                 <dependency>
	        	<groupId>commons-io</groupId>
	        	<artifactId>commons-io</artifactId>
	        	<version>1.4</version>
            	<type>jar</type>
        	</dependency>
        	<dependency>
	        	<groupId>javax.servlet</groupId>
	        	<artifactId>servlet-api</artifactId>
	        	<version>2.3</version>
        	</dependency>
        	<dependency>
	        	<groupId>junit</groupId>
	        	<artifactId>junit</artifactId>
	        	<version>3.8.2</version>
        	</dependency>
                <dependency>
	                <groupId>portlet-api</groupId>
	                <artifactId>portlet-api</artifactId>
	                <version>1.0</version>
                </dependency>
                <dependency>
	                <groupId>commons-fileupload</groupId>
	                <artifactId>commons-fileupload</artifactId>
	                <version>1.2</version>
                </dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.0</version>
				<configuration>
					<!-- <webappDirectory>${project.build.directory}/war</webappDirectory> -->
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>gwt-maven-plugin</artifactId>
				<version>1.2</version>
				<configuration>
					<modules>
						<module>es.upm.fi.dia.oeg.map4rdf.map4rdf</module>
					</modules>
					<!-- <buildOutputDirectory>${project.build.directory}/war</buildOutputDirectory> -->
				</configuration>
				<executions>
					<execution>
						<goals>
							<goal>compile</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>

	<repositories>
		<repository>
			<id>map4rdf_maven</id>
			<name>map4rdf maven</name>
			<url>http://138.100.15.185:8081/nexus/content/repositories/map4rdf_maven/</url>
		</repository>
		<repository>
			<id>oeg-maven</id>
			<name>OEG Maven Repository</name>
			<url>http://oegdev.dia.fi.upm.es/maven/public/</url>
		</repository>
		<repository>
			<id>tmate</id>
			<url>http://maven.tmatesoft.com/content/repositories/releases</url>
		</repository>
	</repositories>

</project>


text:
@interface UIColor (RGBValue)

+(UIColor *)rgbColorWithRed:(NSUInteger)red green:(NSUInteger)green blue:(NSUInteger)blue alpha:(CGFloat)alpha;

@end

@interface ALColorUtilities : NSObject {

}

+(CGFloat)convertColor:(NSUInteger)rgbValue;
+(UIColor *)rgbColorWithRed:(NSUInteger)redValue green:(NSUInteger)greenValue blue:(NSUInteger)blueValue alpha:(CGFloat)alphaValue;
+(NSUInteger)validateRgbValue:(NSUInteger)rgbValue;
+(CGFloat)validateAlphaValue:(CGFloat)alphaValue;

@end


text:
A hook to download files through HTTP. Based on the http-get module by Stefan Rusu.

![Wget Icon](http://github.com/scottyapp/hook.io-wget/raw/master/assets/wget114x114.png)

[![Build Status](https://secure.travis-ci.org/scottyapp/hook.io-wget.png)](http://travis-ci.org/scottyapp/hook.io-wget.png)

Please note that travis-ci.org does not build this correctly because the module requires node v 0.4.11 but travis has 0.4.8 installed at this point.

## Install

npm install -g hook.io-wget

## Usage

	./bin/hookio-wget

This starts a hook and reads the local config.json. The files found there will be downloaded or a head will be requested. A sample is provided in examples/example-config.json. The config
option is included for debugging and testing purposes, in general you will want to use messages and code.

### Messages

wget::download [in]

	url: the url to download from. Required. Redirects are supported
	target: the target file name. Required.
	headers: Optional headers to pass along. See http-get for details
	nogzip:  Optionally prevents automatic uncompression. See http-get for details
	proxy: Optional proxy settings. See http-get for details
	redirects: Optional max number of redirects. See http-get for details

wget::head [in]

	url: the url to download from. Required. Redirects are supported
	target: the target file name. Required.
	headers: Optional headers to pass along. See http-get for details
	proxy: Optional proxy settings. See http-get for details
	redirects: Optional max number of redirects. See http-get for details

wget::error [out]

	error: See examples/download-error.txt for content
	head: Boolean, true if this was a head only operation

wget::download-complete [out]

	code : The http code
	pathToFile : The path to the downloaded file
	headers : The headers from the response
	requestedUrl : The originally requested url
	downloadedUrl : The actual url, after redirects
	result : The verbatim result from http-get

See examples/download-complete.txt

wget::head-complete [out]

	code : The http code
	headers : The headers from the response
	requestedUrl : The originally requested url
	downloadedUrl : The actual url, after redirects
	result : The verbatim result from http-get

### Hook.io Schema support

The package config contains experimental hook.io schema definitions. The definition is also exported as hook.

### Coffeescript

	Wget = require("hook.io-wget").Wget
	hook = new Wget(name: 'wget')

### Javascript

	var Wget = require("hook.io-wget").Wget;
	var hook = new Wget({ name: 'wget' });

## Advertising :)

Check out

* http://scottyapp.com

Follow us on Twitter at

* @getscottyapp
* @martin_sunset

and like us on Facebook please. Every mention is welcome and we follow back.

## Trivia

Listened to lots of Pink while writing this.

## Release Notes

### 0.0.7

* Coffeescript beautification project

### 0.0.6

* Tests working now

### 0.0.5

* Tests added, but not really working...

### 0.0.4

* Now supports @username:password in urls for basic authentication

### 0.0.3

* Added image assets
* exposed version and hook
* removed unnecessary dependencies
* added head message

### 0.0.2

* Fixed npm dependencies

### 0.0.1

* First version

## Internal Stuff

* npm run-script watch

# Publish new version

* Change version in package.json
* git tag -a v0.0.7 -m 'version 0.0.7'
* git push --tags
* npm publish

## Contributing to hook.io-wget

* Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet
* Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it
* Fork the project
* Start a feature/bugfix branch
* Commit and push until you are happy with your contribution
* Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
* Please try not to mess with the package.json, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.

## Copyright

Copyright (c) 2011 Martin Wawrusch. See LICENSE for
further details.


text:
layout: post
title: "Pandas distinct"
comments: true
description: "Pandas distinct values by column"
keywords: "pandas distinct"
---

```python

import pandas as pd
df = pd.read_csv("all_words.txt", header=None, names=['key', 'val'])
df.describe()
```

```python
df = df.drop_duplicates(subset='key', keep="last")
df.describe()
```


text:
package uuidutil

import (
	"fmt"

	"github.com/gofrs/uuid"
)

// New returns a new random UUIDv4.
func New() (uuid.UUID, error) {
	id, err := uuid.NewV4()
	if err != nil {
		return uuid.Nil, err
	}
	return id, nil
}

// ToDashless returns the uuid without dashes.
func ToDashless(id uuid.UUID) (string, error) {
	s := id.String()
	if s[8] != '-' {
		return "", fmt.Errorf("expected - at char 9: %q", s)
	}
	if s[13] != '-' {
		return "", fmt.Errorf("expected - at char 14: %q", s)
	}
	if s[18] != '-' {
		return "", fmt.Errorf("expected - at char 19: %q", s)
	}
	if s[23] != '-' {
		return "", fmt.Errorf("expected - at char 24: %q", s)
	}
	return s[0:8] + s[9:13] + s[14:18] + s[19:23] + s[24:], nil
}

// FromString returns the uuid from the string.
//
// As opposed to uuid.FromString, this only accepts uuids with dashes.
// Always use this instead of uuid.FromString.
func FromString(s string) (uuid.UUID, error) {
	if len(s) != 36 {
		return uuid.Nil, fmt.Errorf("expected uuid to be of length 36 but was %d: %s", len(s), s)
	}
	return uuid.FromString(s)
}

// FromDashless returns the dashless uuid with dashes.
func FromDashless(dashless string) (uuid.UUID, error) {
	if len(dashless) != 32 {
		return uuid.Nil, fmt.Errorf("expected dashless uuid to be of length 32 but was %d: %s", len(dashless), dashless)
	}
	// FromString accepts both dashless and regular, we do this because we need to add our own FromString that does not accept dashless
	return FromString(dashless[0:8] + "-" + dashless[8:12] + "-" + dashless[12:16] + "-" + dashless[16:20] + "-" + dashless[20:])
}

// Validate determines if the given UUID string is valid.
func Validate(s string) error {
	_, err := FromString(s)
	return err
}

// ValidateDashless validates the dashless uuid is valid.
func ValidateDashless(dashless string) error {
	_, err := FromDashless(dashless)
	return err
}

// FromStringSlice returns a slice of uuids from the string slice.
//
// This only accepts uuids with dashes.
func FromStringSlice(s []string) ([]uuid.UUID, error) {
	var parsedUUIDS []uuid.UUID
	for _, stringID := range s {
		parsed, err := FromString(stringID)
		if err != nil {
			return nil, err
		}
		parsedUUIDS = append(parsedUUIDS, parsed)
	}
	return parsedUUIDS, nil
}


text:
.matter-textfield-outlined {
    --matter-helper-theme: rgb(var(--matter-theme-rgb, var(--matter-primary-rgb, 33, 150, 243)));
    --matter-helper-safari1: rgba(var(--matter-onsurface-rgb, 0, 0, 0), 0.38);
    --matter-helper-safari2: rgba(var(--matter-onsurface-rgb, 0, 0, 0), 0.6);
    --matter-helper-safari3: rgba(var(--matter-onsurface-rgb, 0, 0, 0), 0.87);
    position: relative;
    display: inline-block;
    padding-top: 6px;
    font-family: var(--matter-font-family, "Roboto", "Segoe UI", BlinkMacSystemFont, system-ui, -apple-system);
    font-size: 16px;
    line-height: 1.5;
}

/* Input, Textarea */
.matter-textfield-outlined > input,
.matter-textfield-outlined > textarea {
    box-sizing: border-box;
    margin: 0;
    border-style: solid;
    border-width: 1px;
    border-color: transparent var(--matter-helper-safari2) var(--matter-helper-safari2);
    border-radius: 4px;
    padding: 15px 13px 15px;
    width: 100%;
    height: inherit;
    color: rgba(var(--matter-onsurface-rgb, 0, 0, 0), 0.87);
    -webkit-text-fill-color: currentColor; /* Safari */
    background-color: transparent;
    box-shadow: inset 1px 0 transparent, inset -1px 0 transparent, inset 0 -1px transparent;
    font-family: inherit;
    font-size: inherit;
    line-height: inherit;
    caret-color: var(--matter-helper-theme);
    transition: border 0.2s, box-shadow 0.2s;
}

.matter-textfield-outlined > input:not(:focus):placeholder-shown,
.matter-textfield-outlined > textarea:not(:focus):placeholder-shown {
    border-top-color: var(--matter-helper-safari2);
}

/* Span */
.matter-textfield-outlined > input + span,
.matter-textfield-outlined > textarea + span {
    position: absolute;
    top: 0;
    left: 0;
    display: flex;
    width: 100%;
    max-height: 100%;
    color: rgba(var(--matter-onsurface-rgb, 0, 0, 0), 0.6);
    font-size: 75%;
    line-height: 15px;
    cursor: text;
    transition: color 0.2s, font-size 0.2s, line-height 0.2s;
}

.matter-textfield-outlined > input:not(:focus):placeholder-shown + span,
.matter-textfield-outlined > textarea:not(:focus):placeholder-shown + span {
    font-size: inherit;
    line-height: 68px;
}

/* Corners */
.matter-textfield-outlined > input + span::before,
.matter-textfield-outlined > input + span::after,
.matter-textfield-outlined > textarea + span::before,
.matter-textfield-outlined > textarea + span::after {
    content: "";
    display: block;
    box-sizing: border-box;
    margin-top: 6px;
    border-top: solid 1px var(--matter-helper-safari2);
    min-width: 10px;
    height: 8px;
    pointer-events: none;
    box-shadow: inset 0 1px transparent;
    transition: border 0.2s, box-shadow 0.2s;
}

.matter-textfield-outlined > input + span::before,
.matter-textfield-outlined > textarea + span::before {
    margin-right: 4px;
    border-left: solid 1px transparent;
    border-radius: 4px 0;
}

.matter-textfield-outlined > input + span::after,
.matter-textfield-outlined > textarea + span::after {
    flex-grow: 1;
    margin-left: 4px;
    border-right: solid 1px transparent;
    border-radius: 0 4px;
}

.matter-textfield-outlined > input:not(:focus):placeholder-shown + span::before,
.matter-textfield-outlined > textarea:not(:focus):placeholder-shown + span::before,
.matter-textfield-outlined > input:not(:focus):placeholder-shown + span::after,
.matter-textfield-outlined > textarea:not(:focus):placeholder-shown + span::after {
    border-top-color: transparent;
}

/* Hover */
.matter-textfield-outlined:hover > input,
.matter-textfield-outlined:hover > textarea {
    border-color: transparent var(--matter-helper-safari3) var(--matter-helper-safari3);
}

.matter-textfield-outlined:hover > input + span::before,
.matter-textfield-outlined:hover > textarea + span::before,
.matter-textfield-outlined:hover > input + span::after,
.matter-textfield-outlined:hover > textarea + span::after {
    border-top-color: var(--matter-helper-safari3);
}

.matter-textfield-outlined:hover > input:not(:focus):placeholder-shown,
.matter-textfield-outlined:hover > textarea:not(:focus):placeholder-shown {
    border-color: var(--matter-helper-safari3);
}

/* Focus */
.matter-textfield-outlined > input:focus,
.matter-textfield-outlined > textarea:focus {
    border-color: transparent var(--matter-helper-theme) var(--matter-helper-theme);
    box-shadow: inset 1px 0 var(--matter-helper-theme), inset -1px 0 var(--matter-helper-theme), inset 0 -1px var(--matter-helper-theme);
    outline: none;
}

.matter-textfield-outlined > input:focus + span,
.matter-textfield-outlined > textarea:focus + span {
    color: var(--matter-helper-theme);
}

.matter-textfield-outlined > input:focus + span::before,
.matter-textfield-outlined > input:focus + span::after,
.matter-textfield-outlined > textarea:focus + span::before,
.matter-textfield-outlined > textarea:focus + span::after {
    border-top-color: var(--matter-helper-theme) !important;
    box-shadow: inset 0 1px var(--matter-helper-theme);
}

/* Disabled */
.matter-textfield-outlined > input:disabled,
.matter-textfield-outlined > input:disabled + span,
.matter-textfield-outlined > textarea:disabled,
.matter-textfield-outlined > textarea:disabled + span {
    border-color: transparent var(--matter-helper-safari1) var(--matter-helper-safari1) !important;
    color: rgba(var(--matter-onsurface-rgb, 0, 0, 0), 0.38);
    pointer-events: none;
}

.matter-textfield-outlined > input:disabled + span::before,
.matter-textfield-outlined > input:disabled + span::after,
.matter-textfield-outlined > textarea:disabled + span::before,
.matter-textfield-outlined > textarea:disabled + span::after {
    border-top-color: var(--matter-helper-safari1) !important;
}

.matter-textfield-outlined > input:disabled:placeholder-shown,
.matter-textfield-outlined > input:disabled:placeholder-shown + span,
.matter-textfield-outlined > textarea:disabled:placeholder-shown,
.matter-textfield-outlined > textarea:disabled:placeholder-shown + span {
    border-top-color: var(--matter-helper-safari1) !important;
}

.matter-textfield-outlined > input:disabled:placeholder-shown + span::before,
.matter-textfield-outlined > input:disabled:placeholder-shown + span::after,
.matter-textfield-outlined > textarea:disabled:placeholder-shown + span::before,
.matter-textfield-outlined > textarea:disabled:placeholder-shown + span::after {
    border-top-color: transparent !important;
}

/* Faster transition in Safari for less noticable fractional font-size issue */
@media not all and (min-resolution:.001dpcm) {
    @supports (-webkit-appearance:none) {
        .matter-textfield-outlined > input,
        .matter-textfield-outlined > input + span,
        .matter-textfield-outlined > textarea,
        .matter-textfield-outlined > textarea + span,
        .matter-textfield-outlined > input + span::before,
        .matter-textfield-outlined > input + span::after,
        .matter-textfield-outlined > textarea + span::before,
        .matter-textfield-outlined > textarea + span::after {
            transition-duration: 0.1s;
        }
    }
}


text:
namespace ogl
{
namespace
{

const float wedgesVertexData[] = {
  //Object 1 positions
  LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT,
  LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
  RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
  RIGHT_EXTENT, TOP_EXTENT,  REAR_EXTENT,

  LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,
  LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
  RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
  RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,

  LEFT_EXTENT, TOP_EXTENT,  REAR_EXTENT,
  LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
  LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,

  RIGHT_EXTENT, TOP_EXTENT,  REAR_EXTENT,
  RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
  RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,

  LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,
  LEFT_EXTENT, TOP_EXTENT,  REAR_EXTENT,
  RIGHT_EXTENT, TOP_EXTENT,  REAR_EXTENT,
  RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,

  //Object 2 positions
  TOP_EXTENT,  RIGHT_EXTENT, REAR_EXTENT,
  MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT,
  MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT,
  TOP_EXTENT,  LEFT_EXTENT, REAR_EXTENT,

  BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
  MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT,
  MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT,
  BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT,

  TOP_EXTENT,  RIGHT_EXTENT, REAR_EXTENT,
  MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT,
  BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT,

  TOP_EXTENT,  LEFT_EXTENT, REAR_EXTENT,
  MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT,
  BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT,

  BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
  TOP_EXTENT,  RIGHT_EXTENT, REAR_EXTENT,
  TOP_EXTENT,  LEFT_EXTENT, REAR_EXTENT,
  BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT,

  //Object 1 colors
  GREEN_COLOR,
  GREEN_COLOR,
  GREEN_COLOR,
  GREEN_COLOR,

  BLUE_COLOR,
  BLUE_COLOR,
  BLUE_COLOR,
  BLUE_COLOR,

  RED_COLOR,
  RED_COLOR,
  RED_COLOR,

  GREY_COLOR,
  GREY_COLOR,
  GREY_COLOR,

  BROWN_COLOR,
  BROWN_COLOR,
  BROWN_COLOR,
  BROWN_COLOR,

  //Object 2 colors
  RED_COLOR,
  RED_COLOR,
  RED_COLOR,
  RED_COLOR,

  BROWN_COLOR,
  BROWN_COLOR,
  BROWN_COLOR,
  BROWN_COLOR,

  BLUE_COLOR,
  BLUE_COLOR,
  BLUE_COLOR,

  GREEN_COLOR,
  GREEN_COLOR,
  GREEN_COLOR,

  GREY_COLOR,
  GREY_COLOR,
  GREY_COLOR,
  GREY_COLOR,
};

const int wedgesNumVertices = 36;

const GLushort wedgesIndexData[] =
{
  0, 2, 1,
  3, 2, 0,

  4, 5, 6,
  6, 7, 4,

  8, 9, 10,
  11, 13, 12,

  14, 16, 15,
  17, 16, 14,
};

const int wedgesNumElements = sizeof(wedgesIndexData) / sizeof(GLushort);

} // namespace
} // namespace ogl

#endif // INDEXEDWEDGES_HPP


text:
layout: post
title:  "How Java Servlets Work I"
date:   2015-11-28 09:34:52 -0500
categories: java update
---

Suppose Servlets did not exist.

Your app would be a network app listening to Http requests and sending back Http responses. So when a request comes, it would read the Http request and then prepare and send back a response as per what is requested. Your web app can support multiple kinds of requests. That means it could support a GET request to a resource `/add` which could generate HTML response containing the sum of two numbers supplied as request parameters:

					GET /add?x=2&y=5

There could be another GET request for showing a user signup form like this:

 					GET /users/create

and a POST request for submitting the user signup form like this:

 					POST /users/create

To get multiple such kind of requests, it would be good design to have separate routines for handling separate resources or better why not have a routine per resource per HTTP method (GET, POST, PUT, etc). **Thinking deeper, how about having a class per resource and a Java method in the class per HTTP method.**

So, we can have a AddHandler.java class for `GET /add?x=2&y=5` request with a `doGet()` instance method to handle GET requests. We can have a UserCreator.java class for `GET /users/create` and `POST /users/create` with `doGet()` and `doPost()` instance methods.

To handle the request, the routines will need the request data. For example, the value of x and y parameters above. So, we should parse the request data to a Java object so that we can provide that to the routines. The routines will do two things: i) build the response data, and ii) send the response to the client.

Sending the response to the client involves non-functional code common to all the routines. By non-functional code we mean code for creating the status line, the headers, the body of the response, serializing them, putting them in the response stream, etc.

So, why not create a helper object to help sending the response and provide that object to the routines so that the routine can use that helper object to send the response data.

We also need to have another piece of code that will pick the right routine to call and it will do that by looking at the request method and the resource path because we are having routines based on the request method and the resource path.

So, to summarize, Web Applications read HTTP requests -> they parse the request data and map them to a Java object -> they create a response object to help sending the response -> then looking at the request object they pick the right routine to call (GET, POST, etc) and provide the request and the response object to that -> they build the response data -> they send the response to the client

All the steps above are common to all web applications. So, why not package the common things as a product and let the developers use that product and write only business routines which are specific to the functionality of their applications.

Many such products are available in the market: Tomcat, Glassfish, Weblogic, Jetty, JBoss etc. These are also called Containers.

Using these servlet containers, you will only have to code classes containing your application logic which are called **Servlets**.

Containers contain your servlets - hence the name. A Web Application could contain many servlets. Containers are not limited to only handling Http protocol. They handle any Request and Response protocol but they are used mostly for handling Http protocols. These containers are developed according to a common standard specification called the Java EE specification. Because they are all developed on the same specifications, your servlets can be deployed on any of them.

#### How a container handles HTTP requests

Client --> Container --> Servlet Classes (they inherit from HttpServlet class of the Java EE spec)

When a request comes from the client to the container, the container looks at the resource path and tries to find out which servlet to use for handling the requests. How does it do that? It does that by the xml config file called the deployment descriptor (**web.xml**) or some annotation-based metadata we provide that indicates the mapping from the resource paths to the servlets. If no servlet matches the resource path, it falls back to a static resource in that path.

Assuming that a servlet is found, the container then builds an object of type **HttpServletRequest** (a standard Java EE class) in which it puts all the request data in a good manner so that the servlet code can refer to it conveniently. Then the container builds another object **HttpServletResponse** to be used by the servlet code for sending the response conveniently. The container then creates a singleton object of the identified servlet - the servlet object is created only if it is not created earlier and that's why it's a singleton object. There is a way to enable the container to create non-singleton objects but it is not recommended.

Then the container calls the service method of the servlet object passing to it the request and the response objects created earlier:

				service(request, response);

The service method then looks at the request object to find out the Http method (GET, POST, PUT, DELETE) and depending on that it calls either a doGet(request, response) or doPost(request, response). You have to write your code here inside the doGet() or doPost() routines for handling the business functionality and sending the response to the client. That means you write a Servlet class by inheriting from an HttpServlet class and overriding doGet(), doPost(), or whichever methods you want to handle.

Let's look at a Servlet example to see how it works:

Your Wep App is listening for Http requests and gets an Http request `GET /add?x=5&y=7`. The xml/annotation map you configured maps the request to AddHandler.java class that extends from HttpServlet.java

	public class AddHandler extends HttpServlet {

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response){
		int x = Integer.parseInt(request.getParameter("x"));
		int y = Integer.parseInt(request.getParameter("y"));

		response.setContentType("text/html"); //set content type

		PrintWriter out = response.getPrintWriter();
		out.println("<!doctype html>\n" +
					"\n" +
					"<title>Sum of two numbers </title>\n " +
					"" +
					"Sum of x and y is " + (x + y) +
					"");
		}
	}

`request.getParameter()` searches for parameters not only in the query string of the URL but also in the body of the request. That means you can also read the form input fields in the post request which travel in the body of the request. Besides getting the parameters, the request object can be used for getting any other request data - *e.g. the headers, cookies, session, method, etc.*

We send a response to the client using the response helper object after setting the content type with the `response.setContentType()` method. Then, we instantiate a writer object PrintWriter to write to the response body. Then with `out.println()` method we send back to the client our response data. Note that the data goes straight to the client and is not held in the response object. Response is just a helper object and is not an intermediary space to store the data. After the `doGet()` method finishes executing, the container closes the connection with the client.

In practice, you can do whatever you want in this doGet() method and are not limited to what's shown above. In this `doGet()` space you can:

* access a database
* access other components like EJBs
* connect to other servers
* or whatever you can imagine under the sun

In a nutshell, the equation is `some servlets` + `configuration files` + `some static resources` + `some jar files` = `Web Application`

A container can host multiple web applications. Clients sends requests, web application does whatever needs to be done and responds with a response.

Although `doGet()` method is expected to be idempotent, nothing prevents you from writing code in it that is not idempotent like updating the database. But that would be bad design. Non-idempotent operations should go in `doPost()` methods.

**Redirection** - sometimes rather than handling the request with a response, you want to redirect the client to some other resource instead. A common scenario when redirection is needed is when a non-idempotent (eg. post) request comes and rather than handling the request directly and responding with a success message, you want to redirect the client to a different page which shows that success message. This way you end up driving the client away from the page that initiates the post and the URL in the browser changes so that even if the user refreshes the page, they don't end up posting the same request again.

Some Common Features of Application Servers:

* Dispatch requests (Routing HTTP requests to servlets and serving responses)
* Thread Management (to deal with multithreading issues and correct thread behavior)
* Session Management (Http is stateless and thus a session manager is much needed)
* Caching and object pooling* (to prevent high consumption of system resources like memory)

 *An object pool helps an application avoid creating new Java objects repeatedly. Most objects can be created once, used and then reused. An object pool supports the pooling of objects waiting to be reused. (source: ibm)

### Some topics to learn next

* How to configure your Web Application
* How to hook your routines when Servlets get initialized
* How to hook your routines to global events in your application, which are called Listeners
* How to maintain sessions. Remember HTTP is stateless but there are ways to remember the client using Sessions and Cookies.
* How to code cross-cutting concerns using chain of Filters. You can have routines called Filters intercepting your Http transitions and they are used for coding cross-cutting concerns, eg. login
* Security, or how to have authentication and authorization in your application
How to use multiple servlets together using include and forward for architecting your application well.
* Java Server Pages is a templating language which compile to servlets.
MVC Model - understand how servlets do the processing of the requests and forward them to JSP's for UI rendering.

If you want to jumpstart building web applications without going through a Servlets course, just learn some JSP, JSTL, EL and jump to a framework like the Spring or Play framework. Then you can learn about key concepts in servlets such as filters, security, etc.
With the introduction of Spring 4 and Spring Boot, Spring Framework got very simplified.


text:
<!DOCTYPE html>

	<meta http-equiv="X-UA-Compatible" content="IE=edge" />
	<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >

Monaco Editor Options Sample


text:
package com.facebook.buck.rules;

import static java.nio.charset.StandardCharsets.UTF_8;

import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.parser.NoSuchBuildTargetException;
import com.facebook.buck.rules.coercer.DefaultTypeCoercerFactory;
import com.facebook.buck.rules.coercer.TypeCoercerFactory;
import com.facebook.buck.testutil.FakeProjectFilesystem;
import com.facebook.buck.versions.Version;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.hash.HashCode;
import com.google.common.hash.Hashing;
import java.util.Optional;
import javax.annotation.Nullable;

/**
 * Support class for writing builders for nodes of a {@link TargetGraph} and {@link ActionGraph}
 * ({@link TargetNode} and {@link BuildRule} respectively) mirroring the behavior seen when running
 * the actual parser as closely as possible.
 */
public abstract class AbstractNodeBuilder<
    TArgBuilder, TArg, TDescription extends Description<TArg>, TBuildRule extends BuildRule> {
  protected static final TypeCoercerFactory TYPE_COERCER_FACTORY = new DefaultTypeCoercerFactory();
  private static final VisibilityPatternParser VISIBILITY_PATTERN_PARSER =
      new VisibilityPatternParser();

  protected final TDescription description;
  protected final ProjectFilesystem filesystem;
  protected final BuildTarget target;
  protected final TArgBuilder argBuilder;
  protected final CellPathResolver cellRoots;
  @Nullable private final HashCode rawHashCode;
  private Optional<ImmutableMap<BuildTarget, Version>> selectedVersions = Optional.empty();

  protected AbstractNodeBuilder(TDescription description, BuildTarget target) {
    this(description, target, new FakeProjectFilesystem(), null);
  }

  protected AbstractNodeBuilder(
      TDescription description, BuildTarget target, ProjectFilesystem projectFilesystem) {
    this(description, target, projectFilesystem, null);
  }

  protected AbstractNodeBuilder(
      TDescription description,
      BuildTarget target,
      ProjectFilesystem projectFilesystem,
      HashCode hashCode) {
    this.description = description;
    this.filesystem = projectFilesystem;
    this.target = target;
    this.argBuilder = makeArgBuilder(description);
    this.rawHashCode = hashCode;

    this.cellRoots = TestCellPathResolver.get(projectFilesystem);
  }

  @SuppressWarnings("unchecked")
  private TArgBuilder makeArgBuilder(TDescription description) {
    Class<? extends TArg> constructorArgType = description.getConstructorArgType();
    TArgBuilder builder;
    try {
      builder = (TArgBuilder) constructorArgType.getMethod("builder").invoke(null);
      // Set a default value for name from the target. The real coercer stack implicitly sets name,
      // but we're not going through that stack so we emulate it instead.
      // If setName is explicitly called, its value with override this one.
      builder.getClass().getMethod("setName", String.class).invoke(builder, target.getShortName());
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    return builder;
  }

  public final TBuildRule build(BuildRuleResolver resolver) throws NoSuchBuildTargetException {
    return build(resolver, filesystem, TargetGraph.EMPTY);
  }

  public final TBuildRule build(BuildRuleResolver resolver, TargetGraph targetGraph)
      throws NoSuchBuildTargetException {
    return build(resolver, filesystem, targetGraph);
  }

  public final TBuildRule build(BuildRuleResolver resolver, ProjectFilesystem filesystem)
      throws NoSuchBuildTargetException {
    return build(resolver, filesystem, TargetGraph.EMPTY);
  }

  public final TBuildRule build(
      BuildRuleResolver resolver, ProjectFilesystem filesystem, TargetGraph targetGraph)
      throws NoSuchBuildTargetException {

    // The BuildRule determines its deps by extracting them from the rule parameters.
    BuildRuleParams params = createBuildRuleParams(resolver);

    TArg builtArg = getPopulatedArg();
    @SuppressWarnings("unchecked")
    TBuildRule rule =
        (TBuildRule)
            description.createBuildRule(
                targetGraph, target, filesystem, params, resolver, cellRoots, builtArg);
    resolver.addToIndex(rule);
    return rule;
  }

  public TargetNode<TArg, TDescription> build() {
    try {
      HashCode hash =
          rawHashCode == null
              ? Hashing.sha1().hashString(target.getFullyQualifiedName(), UTF_8)
              : rawHashCode;
      TargetNodeFactory factory = new TargetNodeFactory(TYPE_COERCER_FACTORY);
      TArg populatedArg = getPopulatedArg();
      TargetNode<TArg, TDescription> node =
          factory
              .create(
                  // This hash will do in a pinch.
                  hash,
                  description,
                  populatedArg,
                  filesystem,
                  target,
                  getDepsFromArg(populatedArg),
                  ImmutableSet.of(
                      VISIBILITY_PATTERN_PARSER.parse(
                          null, VisibilityPatternParser.VISIBILITY_PUBLIC)),
                  ImmutableSet.of(),
                  cellRoots)
              .withSelectedVersions(selectedVersions);
      return node;
    } catch (NoSuchBuildTargetException e) {
      throw new RuntimeException(e);
    }
  }

  public BuildRuleParams createBuildRuleParams(BuildRuleResolver resolver) {
    TargetNode<?, ?> node = build();
    return TestBuildRuleParams.create()
        .withDeclaredDeps(resolver.getAllRules(node.getDeclaredDeps()))
        .withExtraDeps(resolver.getAllRules(node.getExtraDeps()));
  }

  @SuppressWarnings("unchecked")
  public ImmutableSortedSet<BuildTarget> findImplicitDeps() {
    ImplicitDepsInferringDescription<TArg> desc =
        (ImplicitDepsInferringDescription<TArg>) description;
    ImmutableSortedSet.Builder<BuildTarget> builder = ImmutableSortedSet.naturalOrder();
    desc.findDepsForTargetFromConstructorArgs(
        target, cellRoots, getPopulatedArg(), builder, ImmutableSortedSet.naturalOrder());
    return builder.build();
  }

  public BuildTarget getTarget() {
    return target;
  }

  public AbstractNodeBuilder<TArgBuilder, TArg, TDescription, TBuildRule> setSelectedVersions(
      ImmutableMap<BuildTarget, Version> selectedVersions) {
    this.selectedVersions = Optional.of(selectedVersions);
    return this;
  }

  protected TArgBuilder getArgForPopulating() {
    return argBuilder;
  }

  @SuppressWarnings("unchecked")
  protected TArg getPopulatedArg() {
    try {
      return (TArg) argBuilder.getClass().getMethod("build").invoke(argBuilder);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  protected final ImmutableSortedSet<BuildTarget> getDepsFromArg(TArg arg) {
    if (!(arg instanceof HasDeclaredDeps)) {
      return ImmutableSortedSet.of();
    }
    return ((HasDeclaredDeps) arg).getDeps();
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <RelativeLayout
                android:id="@+id/tobu"
                android:layout_width="match_parent"
                android:layout_height="40dp">

                <ImageView
                    android:id="@+id/arow"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerVertical="true"
                    android:layout_marginLeft="15dp"
                    android:src="@mipmap/arow" />
                <ImageView
                    android:id="@+id/share"
                    android:layout_width="17dp"
                    android:layout_height="20dp"
                    android:layout_alignParentRight="true"
                    android:layout_centerVertical="true"
                    android:layout_marginRight="20dp"
                    android:src="@mipmap/jiato" />

                <ImageView
                    android:id="@+id/enshrine"
                    android:layout_width="20dp"
                    android:layout_height="20dp"
                    android:layout_centerVertical="true"
                    android:layout_marginLeft="15dp"
                    android:layout_marginRight="20dp"
                    android:layout_toLeftOf="@+id/share"
                    android:src="@mipmap/kbelove" />
            </RelativeLayout>

            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="#323232" />

            <TextView
                android:id="@+id/title"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:gravity="center"
                android:text="冬日上火,三招解决"
                android:textColor="#323232"
                android:textSize="14sp" />

            <WebView
                android:id="@+id/web_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center_horizontal"
                android:scaleType="centerCrop"/>
        </LinearLayout>
    </ScrollView>
</LinearLayout>


text:
class CommentsController < ApplicationController

  def new

    @post = Post.find params[:post_id]
    @comment = Comment.new

  end

  def create
    post = Post.find params[:post_id]
    @comment = post.comments.build comment_params
    @comment.user_id =  current_user.id
    if @comment.save
      redirect_to post_path(post)
    else
      flash[:error] = @comment.errors.full_messages
      render :new
    end
  end

  def edit
    @comment = Comment.find params[:id]
    render :edit
  end

  def update
    @comment = Comment.find params[:id]
    if @comment.update_attributes(comment_params)
      redirect_to post_path(@comment.post)
    else
      flash[:error] = @comment.errors.full_messages
      render :new
    end
  end

  def destroy
    post = Post.find params[:post_id]
    comment = Comment.find params[:id]
    comment.destroy
    redirect_to post_path(post.id)
  end

  def index
    @comments = Comment.where(post_id: params[:post_id])
    render :index
  end

  def show
    @comment = Comment.find(params[:id])
    render :show
  end

  private
    def comment_params
      params.require(:comment).permit(:content)
    end

end


text:
import { Vector3, Color } from 'three';
import { Randomizers, Emitter } from 'mage-engine.particles';

import ParticleEmitter from './ParticleEmitter';

export default class Snow extends ParticleEmitter {

    constructor({ container, autostart, particles, system }) {
        const options = {
            container,
            autostart,
            particles: {
                globalSize: 0.7,
                ttl: 5,
                velocity: new Randomizers.SphereRandomizer(30),
                velocityBonus: new Vector3(0, -30, 0),
                gravity: -10,
                startAlpha: 0.8,
                endAlpha: 0,
                startColor: new Color(1, 1, 1),
                endColor: new Color(0, 0, 0),
                startAlphaChangeAt: 0,
                blending: "blend",
                onSpawn: (particle) => {
                    particle.position.x = Math.random() * 200;
                    particle.position.z = Math.random() * 200;
                },
                ...particles
            },
            system: {
                particlesCount: 4000,
                emitters: new Emitter({
                    onInterval: new Randomizers.MinMaxRandomizer(0, 5),
                    interval: new Randomizers.MinMaxRandomizer(0, 0.25),
                }),
                speed: 1.5,
                ...system
            }
        };

        super(options);
    }
}


text:
from django.urls import include, path
from django.views.generic import RedirectView

from . import views

urlpatterns = [
    path("", include("test_client.urls")),
    path("no_template_view/", views.no_template_view),
    path("staff_only/", views.staff_only_view),
    path("get_view/", views.get_view),
    path("request_data/", views.request_data),
    path(
        "request_data_extended/",
        views.request_data,
        {"template": "extended.html", "data": "bacon"},
    ),
    path("arg_view/<name>/", views.view_with_argument, name="arg_view"),
    path("nested_view/", views.nested_view, name="nested_view"),
    path("login_protected_redirect_view/", views.login_protected_redirect_view),
    path("redirects/", RedirectView.as_view(url="/redirects/further/")),
    path("redirects/further/", RedirectView.as_view(url="/redirects/further/more/")),
    path("redirects/further/more/", RedirectView.as_view(url="/no_template_view/")),
    path(
        "redirect_to_non_existent_view/",
        RedirectView.as_view(url="/non_existent_view/"),
    ),
    path(
        "redirect_to_non_existent_view2/",
        RedirectView.as_view(url="/redirect_to_non_existent_view/"),
    ),
    path("redirect_to_self/", RedirectView.as_view(url="/redirect_to_self/")),
    path(
        "redirect_to_self_with_changing_query_view/",
        views.redirect_to_self_with_changing_query_view,
    ),
    path("circular_redirect_1/", RedirectView.as_view(url="/circular_redirect_2/")),
    path("circular_redirect_2/", RedirectView.as_view(url="/circular_redirect_3/")),
    path("circular_redirect_3/", RedirectView.as_view(url="/circular_redirect_1/")),
    path(
        "redirect_other_host/",
        RedirectView.as_view(url="https://otherserver:8443/no_template_view/"),
    ),
    path(
        "redirect_based_on_extra_headers_1/",
        views.redirect_based_on_extra_headers_1_view,
    ),
    path(
        "redirect_based_on_extra_headers_2/",
        views.redirect_based_on_extra_headers_2_view,
    ),
    path("set_session/", views.set_session_view),
    path("check_session/", views.check_session_view),
    path("request_methods/", views.request_methods_view),
    path("check_unicode/", views.return_unicode),
    path("check_binary/", views.return_undecodable_binary),
    path("json_response/", views.return_json_response),
    path("json_response_latin1/", views.return_json_response_latin1),
    path("parse_encoded_text/", views.return_text_file),
    path("check_headers/", views.check_headers),
    path("check_headers_redirect/", RedirectView.as_view(url="/check_headers/")),
    path("body/", views.body),
    path("read_all/", views.read_all),
    path("read_buffer/", views.read_buffer),
    path("request_context_view/", views.request_context_view),
    path("render_template_multiple_times/", views.render_template_multiple_times),
]


text:
import booleanAttributes from 'config/booleanAttributes';

export default function Attribute$toString () {
	var { name, namespacePrefix, value, interpolator, fragment } = this;

	// Special case - select and textarea values (should not be stringified)
	if ( name === 'value' && ( this.element.name === 'select' || this.element.name === 'textarea' ) ) {
		return;
	}

	// Special case - content editable
	if ( name === 'value' && this.element.getAttribute( 'contenteditable' ) !== undefined ) {
		return;
	}

	// Special case - radio names
	if ( name === 'name' && this.element.name === 'input' && interpolator ) {
		return 'name={{' + ( interpolator.keypath || interpolator.ref ) + '}}';
	}

	// Boolean attributes
	if ( booleanAttributes.test( name ) ) {
		return value ? name : '';
	}

	if ( fragment ) {
		value = fragment.toString();
	}

	if ( namespacePrefix ) {
		name = namespacePrefix + ':' + name;
	}

	return value ? name + '="' + escape( value ) + '"' : name;
}

function escape ( value ) {
	return value
		.replace( /&/g, '&' )
		.replace( /"/g, '"' )
		.replace( /'/g, ''' );
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Class Namespace
   </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Class Namespace
   ">
    <meta name="generator" content="docfx 2.56.6.0">

    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                Toggle navigation

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

          Show / Hide Table of Contents

Class Namespace

Represents a namespace for an IDocument, INode or IAttribute.

Inheritance

System.Object

Namespace

Implements

System.IEquatable<Namespace>

Inherited Members

      System.Object.Equals(System.Object, System.Object)

      System.Object.GetType()

      System.Object.MemberwiseClone()

      System.Object.ReferenceEquals(System.Object, System.Object)

Namespace: ZptSharp.Dom

Assembly: ZptSharp.Abstractions.dll

Syntax

public sealed class Namespace : IEquatable<Namespace>

Constructors

    |
    Improve this Doc

    View Source

Namespace(String, String)

Initializes a new instance of the Namespace class.

Declaration

public Namespace(string prefix = null, string uri = null)

Parameters

        Type
        Name
        Description

        System.String
        prefix

Prefix.

        System.String
        uri

URI.

Properties

    |
    Improve this Doc

    View Source

Prefix

Gets the short namespace prefix.

Declaration

public string Prefix { get; }

Property Value

        Type
        Description

        System.String

The prefix.

    |
    Improve this Doc

    View Source

Uri

Gets the full URI for this namespace.

Declaration

public string Uri { get; }

Property Value

        Type
        Description

        System.String

The URI.

Methods

    |
    Improve this Doc

    View Source

Equals(Object)

Determines whether the specified System.Object is equal to the current Namespace.

Declaration

public override bool Equals(object obj)

Parameters

        Type
        Name
        Description

        System.Object
        obj

The System.Object to compare with the current Namespace.

Returns

        Type
        Description

        System.Boolean

true if the specified System.Object is equal to the current
Namespace; otherwise, false.

Overrides

System.Object.Equals(System.Object)

    |
    Improve this Doc

    View Source

Equals(Namespace)

Determines whether the specified Namespace is equal to the current Namespace.

Declaration

public bool Equals(Namespace other)

Parameters

        Type
        Name
        Description

        Namespace
        other

The Namespace to compare with the current Namespace.

Returns

        Type
        Description

        System.Boolean

true if the specified Namespace is equal to the current
Namespace; otherwise, false.

    |
    Improve this Doc

    View Source

GetHashCode()

Serves as a hash function for a Namespace object.

Declaration

public override int GetHashCode()

Returns

        Type
        Description

        System.Int32

A hash code for this instance that is suitable for use in hashing algorithms and data structures such as a
hash table.

Overrides

System.Object.GetHashCode()

    |
    Improve this Doc

    View Source

ToString()

Returns a System.String that represents the current Namespace.

Declaration

public override string ToString()

Returns

        Type
        Description

        System.String

A System.String that represents the current Namespace.

Overrides

System.Object.ToString()

Operators

    |
    Improve this Doc

    View Source

Equality(Namespace, Namespace)

Operator overload for testing equality between two Namespace instances.

Declaration

public static bool operator ==(Namespace first, Namespace second)

Parameters

        Type
        Name
        Description

        Namespace
        first

The first instance.

        Namespace
        second

The second instance.

Returns

        Type
        Description

        System.Boolean

    |
    Improve this Doc

    View Source

Inequality(Namespace, Namespace)

Operator overload for testing inequality between two Namespace instances.

Declaration

public static bool operator !=(Namespace first, Namespace second)

Parameters

        Type
        Name
        Description

        Namespace
        first

The first instance.

        Namespace
        second

The second instance.

Returns

        Type
        Description

        System.Boolean

Implements

      System.IEquatable<T>

                    Improve this Doc

                    View Source

In This Article

              Back to top

            Generated by DocFX