prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>index.ts<|end_file_name|><|fim▁begin|>/// <reference path="../../../type-declarations/index.d.ts" />
import * as Phaser from 'phaser';
import { BootState } from './states/boot';
import { SplashState } from './states/splash';
import { GameState } from './states/game';
class Game extends Phaser.Game {
constructor() {<|fim▁hole|> let width = document.documentElement.clientWidth > 768 * 1.4 // make room for chat
? 768
: document.documentElement.clientWidth * 0.7;
let height = document.documentElement.clientHeight > 1024 * 1.67 // give navbar some room
? 1024
: document.documentElement.clientHeight * 0.6;
super(width, height, Phaser.AUTO, 'game', null, false, false);
this.state.add('Boot', BootState, false);
this.state.add('Splash', SplashState, false);
this.state.add('Game', GameState, false);
this.state.start('Boot');
}
}
export const runGame = () => {
new Game();
}<|fim▁end|> | |
<|file_name|>server.go<|end_file_name|><|fim▁begin|>// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// HTTP server. See RFC 2616.
package http
import (
"bufio"
"bytes"
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/textproto"
"net/url"
"os"
"path"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"golang_org/x/net/lex/httplex"
)
// Errors used by the HTTP server.
var (
// ErrBodyNotAllowed is returned by ResponseWriter.Write calls
// when the HTTP method or response code does not permit a
// body.
ErrBodyNotAllowed = errors.New("http: request method or response status code does not allow body")
// ErrHijacked is returned by ResponseWriter.Write calls when
// the underlying connection has been hijacked using the
// Hijacker interface. A zero-byte write on a hijacked
// connection will return ErrHijacked without any other side
// effects.
ErrHijacked = errors.New("http: connection has been hijacked")
// ErrContentLength is returned by ResponseWriter.Write calls
// when a Handler set a Content-Length response header with a
// declared size and then attempted to write more bytes than
// declared.
ErrContentLength = errors.New("http: wrote more than the declared Content-Length")
// Deprecated: ErrWriteAfterFlush is no longer used.
ErrWriteAfterFlush = errors.New("unused")
)
// A Handler responds to an HTTP request.
//
// ServeHTTP should write reply headers and data to the ResponseWriter
// and then return. Returning signals that the request is finished; it
// is not valid to use the ResponseWriter or read from the
// Request.Body after or concurrently with the completion of the
// ServeHTTP call.
//
// Depending on the HTTP client software, HTTP protocol version, and
// any intermediaries between the client and the Go server, it may not
// be possible to read from the Request.Body after writing to the
// ResponseWriter. Cautious handlers should read the Request.Body
// first, and then reply.
//
// Except for reading the body, handlers should not modify the
// provided Request.
//
// If ServeHTTP panics, the server (the caller of ServeHTTP) assumes
// that the effect of the panic was isolated to the active request.
// It recovers the panic, logs a stack trace to the server error log,
// and hangs up the connection. To abort a handler so the client sees
// an interrupted response but the server doesn't log an error, panic
// with the value ErrAbortHandler.
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}
// A ResponseWriter interface is used by an HTTP handler to
// construct an HTTP response.
//
// A ResponseWriter may not be used after the Handler.ServeHTTP method
// has returned.
type ResponseWriter interface {
// Header returns the header map that will be sent by
// WriteHeader. The Header map also is the mechanism with which
// Handlers can set HTTP trailers.
//
// Changing the header map after a call to WriteHeader (or
// Write) has no effect unless the modified headers are
// trailers.
//
// There are two ways to set Trailers. The preferred way is to
// predeclare in the headers which trailers you will later
// send by setting the "Trailer" header to the names of the
// trailer keys which will come later. In this case, those
// keys of the Header map are treated as if they were
// trailers. See the example. The second way, for trailer
// keys not known to the Handler until after the first Write,
// is to prefix the Header map keys with the TrailerPrefix
// constant value. See TrailerPrefix.
//
// To suppress implicit response headers (such as "Date"), set
// their value to nil.
Header() Header
// Write writes the data to the connection as part of an HTTP reply.
//
// If WriteHeader has not yet been called, Write calls
// WriteHeader(http.StatusOK) before writing the data. If the Header
// does not contain a Content-Type line, Write adds a Content-Type set
// to the result of passing the initial 512 bytes of written data to
// DetectContentType.
//
// Depending on the HTTP protocol version and the client, calling
// Write or WriteHeader may prevent future reads on the
// Request.Body. For HTTP/1.x requests, handlers should read any
// needed request body data before writing the response. Once the
// headers have been flushed (due to either an explicit Flusher.Flush
// call or writing enough data to trigger a flush), the request body
// may be unavailable. For HTTP/2 requests, the Go HTTP server permits
// handlers to continue to read the request body while concurrently
// writing the response. However, such behavior may not be supported
// by all HTTP/2 clients. Handlers should read before writing if
// possible to maximize compatibility.
Write([]byte) (int, error)
// WriteHeader sends an HTTP response header with status code.
// If WriteHeader is not called explicitly, the first call to Write
// will trigger an implicit WriteHeader(http.StatusOK).
// Thus explicit calls to WriteHeader are mainly used to
// send error codes.
WriteHeader(int)
}
// The Flusher interface is implemented by ResponseWriters that allow
// an HTTP handler to flush buffered data to the client.
//
// The default HTTP/1.x and HTTP/2 ResponseWriter implementations
// support Flusher, but ResponseWriter wrappers may not. Handlers
// should always test for this ability at runtime.
//
// Note that even for ResponseWriters that support Flush,
// if the client is connected through an HTTP proxy,
// the buffered data may not reach the client until the response
// completes.
type Flusher interface {
// Flush sends any buffered data to the client.
Flush()
}
// The Hijacker interface is implemented by ResponseWriters that allow
// an HTTP handler to take over the connection.
//
// The default ResponseWriter for HTTP/1.x connections supports
// Hijacker, but HTTP/2 connections intentionally do not.
// ResponseWriter wrappers may also not support Hijacker. Handlers
// should always test for this ability at runtime.
type Hijacker interface {
// Hijack lets the caller take over the connection.
// After a call to Hijack the HTTP server library
// will not do anything else with the connection.
//
// It becomes the caller's responsibility to manage
// and close the connection.
//
// The returned net.Conn may have read or write deadlines
// already set, depending on the configuration of the
// Server. It is the caller's responsibility to set
// or clear those deadlines as needed.
//
// The returned bufio.Reader may contain unprocessed buffered
// data from the client.
Hijack() (net.Conn, *bufio.ReadWriter, error)
}
// The CloseNotifier interface is implemented by ResponseWriters which
// allow detecting when the underlying connection has gone away.
//
// This mechanism can be used to cancel long operations on the server
// if the client has disconnected before the response is ready.
type CloseNotifier interface {
// CloseNotify returns a channel that receives at most a
// single value (true) when the client connection has gone
// away.
//
// CloseNotify may wait to notify until Request.Body has been
// fully read.
//
// After the Handler has returned, there is no guarantee
// that the channel receives a value.
//
// If the protocol is HTTP/1.1 and CloseNotify is called while
// processing an idempotent request (such a GET) while
// HTTP/1.1 pipelining is in use, the arrival of a subsequent
// pipelined request may cause a value to be sent on the
// returned channel. In practice HTTP/1.1 pipelining is not
// enabled in browsers and not seen often in the wild. If this
// is a problem, use HTTP/2 or only use CloseNotify on methods
// such as POST.
CloseNotify() <-chan bool
}
var (
// ServerContextKey is a context key. It can be used in HTTP
// handlers with context.WithValue to access the server that
// started the handler. The associated value will be of
// type *Server.
ServerContextKey = &contextKey{"http-server"}
// LocalAddrContextKey is a context key. It can be used in
// HTTP handlers with context.WithValue to access the address
// the local address the connection arrived on.
// The associated value will be of type net.Addr.
LocalAddrContextKey = &contextKey{"local-addr"}
)
// A conn represents the server side of an HTTP connection.
type conn struct {
// server is the server on which the connection arrived.
// Immutable; never nil.
server *Server
// cancelCtx cancels the connection-level context.
cancelCtx context.CancelFunc
// rwc is the underlying network connection.
// This is never wrapped by other types and is the value given out
// to CloseNotifier callers. It is usually of type *net.TCPConn or
// *tls.Conn.
rwc net.Conn
// remoteAddr is rwc.RemoteAddr().String(). It is not populated synchronously
// inside the Listener's Accept goroutine, as some implementations block.
// It is populated immediately inside the (*conn).serve goroutine.
// This is the value of a Handler's (*Request).RemoteAddr.
remoteAddr string
// tlsState is the TLS connection state when using TLS.
// nil means not TLS.
tlsState *tls.ConnectionState
// werr is set to the first write error to rwc.
// It is set via checkConnErrorWriter{w}, where bufw writes.
werr error
// r is bufr's read source. It's a wrapper around rwc that provides
// io.LimitedReader-style limiting (while reading request headers)
// and functionality to support CloseNotifier. See *connReader docs.
r *connReader
// bufr reads from r.
bufr *bufio.Reader
// bufw writes to checkConnErrorWriter{c}, which populates werr on error.
bufw *bufio.Writer
// lastMethod is the method of the most recent request
// on this connection, if any.
lastMethod string
curReq atomic.Value // of *response (which has a Request in it)
curState atomic.Value // of ConnState
// mu guards hijackedv
mu sync.Mutex
// hijackedv is whether this connection has been hijacked
// by a Handler with the Hijacker interface.
// It is guarded by mu.
hijackedv bool
}
func (c *conn) hijacked() bool {
c.mu.Lock()
defer c.mu.Unlock()
return c.hijackedv
}
// c.mu must be held.
func (c *conn) hijackLocked() (rwc net.Conn, buf *bufio.ReadWriter, err error) {
if c.hijackedv {
return nil, nil, ErrHijacked
}
c.r.abortPendingRead()
c.hijackedv = true
rwc = c.rwc
rwc.SetDeadline(time.Time{})
buf = bufio.NewReadWriter(c.bufr, bufio.NewWriter(rwc))
if c.r.hasByte {
if _, err := c.bufr.Peek(c.bufr.Buffered() + 1); err != nil {
return nil, nil, fmt.Errorf("unexpected Peek failure reading buffered byte: %v", err)
}
}
c.setState(rwc, StateHijacked)
return
}
// This should be >= 512 bytes for DetectContentType,
// but otherwise it's somewhat arbitrary.
const bufferBeforeChunkingSize = 2048
// chunkWriter writes to a response's conn buffer, and is the writer
// wrapped by the response.bufw buffered writer.
//
// chunkWriter also is responsible for finalizing the Header, including
// conditionally setting the Content-Type and setting a Content-Length
// in cases where the handler's final output is smaller than the buffer
// size. It also conditionally adds chunk headers, when in chunking mode.
//
// See the comment above (*response).Write for the entire write flow.
type chunkWriter struct {
res *response
// header is either nil or a deep clone of res.handlerHeader
// at the time of res.WriteHeader, if res.WriteHeader is
// called and extra buffering is being done to calculate
// Content-Type and/or Content-Length.
header Header
// wroteHeader tells whether the header's been written to "the
// wire" (or rather: w.conn.buf). this is unlike
// (*response).wroteHeader, which tells only whether it was
// logically written.
wroteHeader bool
// set by the writeHeader method:
chunking bool // using chunked transfer encoding for reply body
}
var (
crlf = []byte("\r\n")
colonSpace = []byte(": ")
)
func (cw *chunkWriter) Write(p []byte) (n int, err error) {
if !cw.wroteHeader {
cw.writeHeader(p)
}
if cw.res.req.Method == "HEAD" {
// Eat writes.
return len(p), nil
}
if cw.chunking {
_, err = fmt.Fprintf(cw.res.conn.bufw, "%x\r\n", len(p))
if err != nil {
cw.res.conn.rwc.Close()
return
}
}
n, err = cw.res.conn.bufw.Write(p)
if cw.chunking && err == nil {
_, err = cw.res.conn.bufw.Write(crlf)
}
if err != nil {
cw.res.conn.rwc.Close()
}
return
}
func (cw *chunkWriter) flush() {
if !cw.wroteHeader {
cw.writeHeader(nil)
}
cw.res.conn.bufw.Flush()
}
func (cw *chunkWriter) close() {
if !cw.wroteHeader {
cw.writeHeader(nil)
}
if cw.chunking {
bw := cw.res.conn.bufw // conn's bufio writer
// zero chunk to mark EOF
bw.WriteString("0\r\n")
if trailers := cw.res.finalTrailers(); trailers != nil {
trailers.Write(bw) // the writer handles noting errors
}
// final blank line after the trailers (whether
// present or not)
bw.WriteString("\r\n")
}
}
// A response represents the server side of an HTTP response.
type response struct {
conn *conn
req *Request // request for this response
reqBody io.ReadCloser
cancelCtx context.CancelFunc // when ServeHTTP exits
wroteHeader bool // reply header has been (logically) written
wroteContinue bool // 100 Continue response was written
wants10KeepAlive bool // HTTP/1.0 w/ Connection "keep-alive"
wantsClose bool // HTTP request has Connection "close"
w *bufio.Writer // buffers output in chunks to chunkWriter
cw chunkWriter
// handlerHeader is the Header that Handlers get access to,
// which may be retained and mutated even after WriteHeader.
// handlerHeader is copied into cw.header at WriteHeader
// time, and privately mutated thereafter.
handlerHeader Header
calledHeader bool // handler accessed handlerHeader via Header
written int64 // number of bytes written in body
contentLength int64 // explicitly-declared Content-Length; or -1
status int // status code passed to WriteHeader
// close connection after this reply. set on request and
// updated after response from handler if there's a
// "Connection: keep-alive" response header and a
// Content-Length.
closeAfterReply bool
// requestBodyLimitHit is set by requestTooLarge when
// maxBytesReader hits its max size. It is checked in
// WriteHeader, to make sure we don't consume the
// remaining request body to try to advance to the next HTTP
// request. Instead, when this is set, we stop reading
// subsequent requests on this connection and stop reading
// input from it.
requestBodyLimitHit bool
// trailers are the headers to be sent after the handler
// finishes writing the body. This field is initialized from
// the Trailer response header when the response header is
// written.
trailers []string
handlerDone atomicBool // set true when the handler exits
// Buffers for Date and Content-Length
dateBuf [len(TimeFormat)]byte
clenBuf [10]byte
// closeNotifyCh is the channel returned by CloseNotify.
// TODO(bradfitz): this is currently (for Go 1.8) always
// non-nil. Make this lazily-created again as it used to be?
closeNotifyCh chan bool
didCloseNotify int32 // atomic (only 0->1 winner should send)
}
// TrailerPrefix is a magic prefix for ResponseWriter.Header map keys
// that, if present, signals that the map entry is actually for
// the response trailers, and not the response headers. The prefix
// is stripped after the ServeHTTP call finishes and the values are
// sent in the trailers.
//
// This mechanism is intended only for trailers that are not known
// prior to the headers being written. If the set of trailers is fixed
// or known before the header is written, the normal Go trailers mechanism
// is preferred:
// https://golang.org/pkg/net/http/#ResponseWriter
// https://golang.org/pkg/net/http/#example_ResponseWriter_trailers
const TrailerPrefix = "Trailer:"
// finalTrailers is called after the Handler exits and returns a non-nil
// value if the Handler set any trailers.
func (w *response) finalTrailers() Header {
var t Header
for k, vv := range w.handlerHeader {
if strings.HasPrefix(k, TrailerPrefix) {
if t == nil {
t = make(Header)
}
t[strings.TrimPrefix(k, TrailerPrefix)] = vv
}
}
for _, k := range w.trailers {
if t == nil {
t = make(Header)
}
for _, v := range w.handlerHeader[k] {
t.Add(k, v)
}
}
return t
}
type atomicBool int32
func (b *atomicBool) isSet() bool { return atomic.LoadInt32((*int32)(b)) != 0 }
func (b *atomicBool) setTrue() { atomic.StoreInt32((*int32)(b), 1) }
// declareTrailer is called for each Trailer header when the
// response header is written. It notes that a header will need to be
// written in the trailers at the end of the response.
func (w *response) declareTrailer(k string) {
k = CanonicalHeaderKey(k)
switch k {
case "Transfer-Encoding", "Content-Length", "Trailer":
// Forbidden by RFC 2616 14.40.
return
}
w.trailers = append(w.trailers, k)
}
// requestTooLarge is called by maxBytesReader when too much input has
// been read from the client.
func (w *response) requestTooLarge() {
w.closeAfterReply = true
w.requestBodyLimitHit = true
if !w.wroteHeader {
w.Header().Set("Connection", "close")
}
}
// needsSniff reports whether a Content-Type still needs to be sniffed.
func (w *response) needsSniff() bool {
_, haveType := w.handlerHeader["Content-Type"]
return !w.cw.wroteHeader && !haveType && w.written < sniffLen
}
// writerOnly hides an io.Writer value's optional ReadFrom method
// from io.Copy.
type writerOnly struct {
io.Writer
}
func srcIsRegularFile(src io.Reader) (isRegular bool, err error) {
switch v := src.(type) {
case *os.File:
fi, err := v.Stat()
if err != nil {
return false, err
}
return fi.Mode().IsRegular(), nil
case *io.LimitedReader:
return srcIsRegularFile(v.R)
default:
return
}
}
// ReadFrom is here to optimize copying from an *os.File regular file
// to a *net.TCPConn with sendfile.
func (w *response) ReadFrom(src io.Reader) (n int64, err error) {
// Our underlying w.conn.rwc is usually a *TCPConn (with its
// own ReadFrom method). If not, or if our src isn't a regular
// file, just fall back to the normal copy method.
rf, ok := w.conn.rwc.(io.ReaderFrom)
regFile, err := srcIsRegularFile(src)
if err != nil {
return 0, err
}
if !ok || !regFile {
bufp := copyBufPool.Get().(*[]byte)
defer copyBufPool.Put(bufp)
return io.CopyBuffer(writerOnly{w}, src, *bufp)
}
// sendfile path:
if !w.wroteHeader {
w.WriteHeader(StatusOK)
}
if w.needsSniff() {
n0, err := io.Copy(writerOnly{w}, io.LimitReader(src, sniffLen))
n += n0
if err != nil {
return n, err
}
}
w.w.Flush() // get rid of any previous writes
w.cw.flush() // make sure Header is written; flush data to rwc
// Now that cw has been flushed, its chunking field is guaranteed initialized.
if !w.cw.chunking && w.bodyAllowed() {
n0, err := rf.ReadFrom(src)
n += n0
w.written += n0
return n, err
}
n0, err := io.Copy(writerOnly{w}, src)
n += n0
return n, err
}
// debugServerConnections controls whether all server connections are wrapped
// with a verbose logging wrapper.
const debugServerConnections = false
// Create new connection from rwc.
func (srv *Server) newConn(rwc net.Conn) *conn {
c := &conn{
server: srv,
rwc: rwc,
}
if debugServerConnections {
c.rwc = newLoggingConn("server", c.rwc)
}
return c
}
type readResult struct {
n int
err error
b byte // byte read, if n == 1
}
// connReader is the io.Reader wrapper used by *conn. It combines a
// selectively-activated io.LimitedReader (to bound request header
// read sizes) with support for selectively keeping an io.Reader.Read
// call blocked in a background goroutine to wait for activity and
// trigger a CloseNotifier channel.
type connReader struct {
conn *conn
mu sync.Mutex // guards following
hasByte bool
byteBuf [1]byte
bgErr error // non-nil means error happened on background read
cond *sync.Cond
inRead bool
aborted bool // set true before conn.rwc deadline is set to past
remain int64 // bytes remaining
}
func (cr *connReader) lock() {
cr.mu.Lock()
if cr.cond == nil {
cr.cond = sync.NewCond(&cr.mu)
}
}
func (cr *connReader) unlock() { cr.mu.Unlock() }
func (cr *connReader) startBackgroundRead() {
cr.lock()
defer cr.unlock()
if cr.inRead {
panic("invalid concurrent Body.Read call")
}
if cr.hasByte {
return
}
cr.inRead = true
cr.conn.rwc.SetReadDeadline(time.Time{})
go cr.backgroundRead()
}
func (cr *connReader) backgroundRead() {
n, err := cr.conn.rwc.Read(cr.byteBuf[:])
cr.lock()
if n == 1 {
cr.hasByte = true
// We were at EOF already (since we wouldn't be in a
// background read otherwise), so this is a pipelined
// HTTP request.
cr.closeNotifyFromPipelinedRequest()
}
if ne, ok := err.(net.Error); ok && cr.aborted && ne.Timeout() {
// Ignore this error. It's the expected error from
// another goroutine calling abortPendingRead.
} else if err != nil {
cr.handleReadError(err)
}
cr.aborted = false
cr.inRead = false
cr.unlock()
cr.cond.Broadcast()
}
func (cr *connReader) abortPendingRead() {
cr.lock()
defer cr.unlock()
if !cr.inRead {
return
}
cr.aborted = true
cr.conn.rwc.SetReadDeadline(aLongTimeAgo)
for cr.inRead {
cr.cond.Wait()
}
cr.conn.rwc.SetReadDeadline(time.Time{})
}
func (cr *connReader) setReadLimit(remain int64) { cr.remain = remain }
func (cr *connReader) setInfiniteReadLimit() { cr.remain = maxInt64 }
func (cr *connReader) hitReadLimit() bool { return cr.remain <= 0 }
// may be called from multiple goroutines.
func (cr *connReader) handleReadError(err error) {
cr.conn.cancelCtx()
cr.closeNotify()
}
// closeNotifyFromPipelinedRequest simply calls closeNotify.
//
// This method wrapper is here for documentation. The callers are the
// cases where we send on the closenotify channel because of a
// pipelined HTTP request, per the previous Go behavior and
// documentation (that this "MAY" happen).
//
// TODO: consider changing this behavior and making context
// cancelation and closenotify work the same.
func (cr *connReader) closeNotifyFromPipelinedRequest() {
cr.closeNotify()
}
// may be called from multiple goroutines.
func (cr *connReader) closeNotify() {
res, _ := cr.conn.curReq.Load().(*response)
if res != nil {
if atomic.CompareAndSwapInt32(&res.didCloseNotify, 0, 1) {
res.closeNotifyCh <- true
}
}
}
func (cr *connReader) Read(p []byte) (n int, err error) {
cr.lock()
if cr.inRead {
cr.unlock()
panic("invalid concurrent Body.Read call")
}
if cr.hitReadLimit() {
cr.unlock()
return 0, io.EOF
}
if cr.bgErr != nil {
err = cr.bgErr
cr.unlock()
return 0, err
}
if len(p) == 0 {
cr.unlock()
return 0, nil
}
if int64(len(p)) > cr.remain {
p = p[:cr.remain]
}
if cr.hasByte {
p[0] = cr.byteBuf[0]
cr.hasByte = false
cr.unlock()
return 1, nil
}
cr.inRead = true
cr.unlock()
n, err = cr.conn.rwc.Read(p)
cr.lock()
cr.inRead = false
if err != nil {
cr.handleReadError(err)
}
cr.remain -= int64(n)
cr.unlock()
cr.cond.Broadcast()
return n, err
}
var (
bufioReaderPool sync.Pool
bufioWriter2kPool sync.Pool
bufioWriter4kPool sync.Pool
)
var copyBufPool = sync.Pool{
New: func() interface{} {
b := make([]byte, 32*1024)
return &b
},
}
func bufioWriterPool(size int) *sync.Pool {
switch size {
case 2 << 10:
return &bufioWriter2kPool
case 4 << 10:
return &bufioWriter4kPool
}
return nil
}
func newBufioReader(r io.Reader) *bufio.Reader {
if v := bufioReaderPool.Get(); v != nil {
br := v.(*bufio.Reader)
br.Reset(r)
return br
}
// Note: if this reader size is ever changed, update
// TestHandlerBodyClose's assumptions.
return bufio.NewReader(r)
}
func putBufioReader(br *bufio.Reader) {
br.Reset(nil)
bufioReaderPool.Put(br)
}
func newBufioWriterSize(w io.Writer, size int) *bufio.Writer {
pool := bufioWriterPool(size)
if pool != nil {
if v := pool.Get(); v != nil {
bw := v.(*bufio.Writer)
bw.Reset(w)
return bw
}
}
return bufio.NewWriterSize(w, size)
}
func putBufioWriter(bw *bufio.Writer) {
bw.Reset(nil)
if pool := bufioWriterPool(bw.Available()); pool != nil {
pool.Put(bw)
}
}
// DefaultMaxHeaderBytes is the maximum permitted size of the headers
// in an HTTP request.
// This can be overridden by setting Server.MaxHeaderBytes.
const DefaultMaxHeaderBytes = 1 << 20 // 1 MB
func (srv *Server) maxHeaderBytes() int {
if srv.MaxHeaderBytes > 0 {
return srv.MaxHeaderBytes
}
return DefaultMaxHeaderBytes
}
func (srv *Server) initialReadLimitSize() int64 {
return int64(srv.maxHeaderBytes()) + 4096 // bufio slop
}
// wrapper around io.ReadCloser which on first read, sends an
// HTTP/1.1 100 Continue header
type expectContinueReader struct {
resp *response
readCloser io.ReadCloser
closed bool
sawEOF bool
}
func (ecr *expectContinueReader) Read(p []byte) (n int, err error) {
if ecr.closed {
return 0, ErrBodyReadAfterClose
}
if !ecr.resp.wroteContinue && !ecr.resp.conn.hijacked() {
ecr.resp.wroteContinue = true
ecr.resp.conn.bufw.WriteString("HTTP/1.1 100 Continue\r\n\r\n")
ecr.resp.conn.bufw.Flush()
}
n, err = ecr.readCloser.Read(p)
if err == io.EOF {
ecr.sawEOF = true
}
return
}
func (ecr *expectContinueReader) Close() error {
ecr.closed = true
return ecr.readCloser.Close()
}
// TimeFormat is the time format to use when generating times in HTTP
// headers. It is like time.RFC1123 but hard-codes GMT as the time
// zone. The time being formatted must be in UTC for Format to
// generate the correct format.
//
// For parsing this time format, see ParseTime.
const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"
// appendTime is a non-allocating version of []byte(t.UTC().Format(TimeFormat))
func appendTime(b []byte, t time.Time) []byte {
const days = "SunMonTueWedThuFriSat"
const months = "JanFebMarAprMayJunJulAugSepOctNovDec"
t = t.UTC()
yy, mm, dd := t.Date()
hh, mn, ss := t.Clock()
day := days[3*t.Weekday():]<|fim▁hole|> day[0], day[1], day[2], ',', ' ',
byte('0'+dd/10), byte('0'+dd%10), ' ',
mon[0], mon[1], mon[2], ' ',
byte('0'+yy/1000), byte('0'+(yy/100)%10), byte('0'+(yy/10)%10), byte('0'+yy%10), ' ',
byte('0'+hh/10), byte('0'+hh%10), ':',
byte('0'+mn/10), byte('0'+mn%10), ':',
byte('0'+ss/10), byte('0'+ss%10), ' ',
'G', 'M', 'T')
}
var errTooLarge = errors.New("http: request too large")
// Read next request from connection.
func (c *conn) readRequest(ctx context.Context) (w *response, err error) {
if c.hijacked() {
return nil, ErrHijacked
}
var (
wholeReqDeadline time.Time // or zero if none
hdrDeadline time.Time // or zero if none
)
t0 := time.Now()
if d := c.server.readHeaderTimeout(); d != 0 {
hdrDeadline = t0.Add(d)
}
if d := c.server.ReadTimeout; d != 0 {
wholeReqDeadline = t0.Add(d)
}
c.rwc.SetReadDeadline(hdrDeadline)
if d := c.server.WriteTimeout; d != 0 {
defer func() {
c.rwc.SetWriteDeadline(time.Now().Add(d))
}()
}
c.r.setReadLimit(c.server.initialReadLimitSize())
if c.lastMethod == "POST" {
// RFC 2616 section 4.1 tolerance for old buggy clients.
peek, _ := c.bufr.Peek(4) // ReadRequest will get err below
c.bufr.Discard(numLeadingCRorLF(peek))
}
req, err := readRequest(c.bufr, keepHostHeader)
if err != nil {
if c.r.hitReadLimit() {
return nil, errTooLarge
}
return nil, err
}
if !http1ServerSupportsRequest(req) {
return nil, badRequestError("unsupported protocol version")
}
c.lastMethod = req.Method
c.r.setInfiniteReadLimit()
hosts, haveHost := req.Header["Host"]
isH2Upgrade := req.isH2Upgrade()
if req.ProtoAtLeast(1, 1) && (!haveHost || len(hosts) == 0) && !isH2Upgrade {
return nil, badRequestError("missing required Host header")
}
if len(hosts) > 1 {
return nil, badRequestError("too many Host headers")
}
if len(hosts) == 1 && !httplex.ValidHostHeader(hosts[0]) {
return nil, badRequestError("malformed Host header")
}
for k, vv := range req.Header {
if !httplex.ValidHeaderFieldName(k) {
return nil, badRequestError("invalid header name")
}
for _, v := range vv {
if !httplex.ValidHeaderFieldValue(v) {
return nil, badRequestError("invalid header value")
}
}
}
delete(req.Header, "Host")
ctx, cancelCtx := context.WithCancel(ctx)
req.ctx = ctx
req.RemoteAddr = c.remoteAddr
req.TLS = c.tlsState
if body, ok := req.Body.(*body); ok {
body.doEarlyClose = true
}
// Adjust the read deadline if necessary.
if !hdrDeadline.Equal(wholeReqDeadline) {
c.rwc.SetReadDeadline(wholeReqDeadline)
}
w = &response{
conn: c,
cancelCtx: cancelCtx,
req: req,
reqBody: req.Body,
handlerHeader: make(Header),
contentLength: -1,
closeNotifyCh: make(chan bool, 1),
// We populate these ahead of time so we're not
// reading from req.Header after their Handler starts
// and maybe mutates it (Issue 14940)
wants10KeepAlive: req.wantsHttp10KeepAlive(),
wantsClose: req.wantsClose(),
}
if isH2Upgrade {
w.closeAfterReply = true
}
w.cw.res = w
w.w = newBufioWriterSize(&w.cw, bufferBeforeChunkingSize)
return w, nil
}
// http1ServerSupportsRequest reports whether Go's HTTP/1.x server
// supports the given request.
func http1ServerSupportsRequest(req *Request) bool {
if req.ProtoMajor == 1 {
return true
}
// Accept "PRI * HTTP/2.0" upgrade requests, so Handlers can
// wire up their own HTTP/2 upgrades.
if req.ProtoMajor == 2 && req.ProtoMinor == 0 &&
req.Method == "PRI" && req.RequestURI == "*" {
return true
}
// Reject HTTP/0.x, and all other HTTP/2+ requests (which
// aren't encoded in ASCII anyway).
return false
}
func (w *response) Header() Header {
if w.cw.header == nil && w.wroteHeader && !w.cw.wroteHeader {
// Accessing the header between logically writing it
// and physically writing it means we need to allocate
// a clone to snapshot the logically written state.
w.cw.header = w.handlerHeader.clone()
}
w.calledHeader = true
return w.handlerHeader
}
// maxPostHandlerReadBytes is the max number of Request.Body bytes not
// consumed by a handler that the server will read from the client
// in order to keep a connection alive. If there are more bytes than
// this then the server to be paranoid instead sends a "Connection:
// close" response.
//
// This number is approximately what a typical machine's TCP buffer
// size is anyway. (if we have the bytes on the machine, we might as
// well read them)
const maxPostHandlerReadBytes = 256 << 10
func (w *response) WriteHeader(code int) {
if w.conn.hijacked() {
w.conn.server.logf("http: response.WriteHeader on hijacked connection")
return
}
if w.wroteHeader {
w.conn.server.logf("http: multiple response.WriteHeader calls")
return
}
w.wroteHeader = true
w.status = code
if w.calledHeader && w.cw.header == nil {
w.cw.header = w.handlerHeader.clone()
}
if cl := w.handlerHeader.get("Content-Length"); cl != "" {
v, err := strconv.ParseInt(cl, 10, 64)
if err == nil && v >= 0 {
w.contentLength = v
} else {
w.conn.server.logf("http: invalid Content-Length of %q", cl)
w.handlerHeader.Del("Content-Length")
}
}
}
// extraHeader is the set of headers sometimes added by chunkWriter.writeHeader.
// This type is used to avoid extra allocations from cloning and/or populating
// the response Header map and all its 1-element slices.
type extraHeader struct {
contentType string
connection string
transferEncoding string
date []byte // written if not nil
contentLength []byte // written if not nil
}
// Sorted the same as extraHeader.Write's loop.
var extraHeaderKeys = [][]byte{
[]byte("Content-Type"),
[]byte("Connection"),
[]byte("Transfer-Encoding"),
}
var (
headerContentLength = []byte("Content-Length: ")
headerDate = []byte("Date: ")
)
// Write writes the headers described in h to w.
//
// This method has a value receiver, despite the somewhat large size
// of h, because it prevents an allocation. The escape analysis isn't
// smart enough to realize this function doesn't mutate h.
func (h extraHeader) Write(w *bufio.Writer) {
if h.date != nil {
w.Write(headerDate)
w.Write(h.date)
w.Write(crlf)
}
if h.contentLength != nil {
w.Write(headerContentLength)
w.Write(h.contentLength)
w.Write(crlf)
}
for i, v := range []string{h.contentType, h.connection, h.transferEncoding} {
if v != "" {
w.Write(extraHeaderKeys[i])
w.Write(colonSpace)
w.WriteString(v)
w.Write(crlf)
}
}
}
// writeHeader finalizes the header sent to the client and writes it
// to cw.res.conn.bufw.
//
// p is not written by writeHeader, but is the first chunk of the body
// that will be written. It is sniffed for a Content-Type if none is
// set explicitly. It's also used to set the Content-Length, if the
// total body size was small and the handler has already finished
// running.
func (cw *chunkWriter) writeHeader(p []byte) {
if cw.wroteHeader {
return
}
cw.wroteHeader = true
w := cw.res
keepAlivesEnabled := w.conn.server.doKeepAlives()
isHEAD := w.req.Method == "HEAD"
// header is written out to w.conn.buf below. Depending on the
// state of the handler, we either own the map or not. If we
// don't own it, the exclude map is created lazily for
// WriteSubset to remove headers. The setHeader struct holds
// headers we need to add.
header := cw.header
owned := header != nil
if !owned {
header = w.handlerHeader
}
var excludeHeader map[string]bool
delHeader := func(key string) {
if owned {
header.Del(key)
return
}
if _, ok := header[key]; !ok {
return
}
if excludeHeader == nil {
excludeHeader = make(map[string]bool)
}
excludeHeader[key] = true
}
var setHeader extraHeader
// Don't write out the fake "Trailer:foo" keys. See TrailerPrefix.
trailers := false
for k := range cw.header {
if strings.HasPrefix(k, TrailerPrefix) {
if excludeHeader == nil {
excludeHeader = make(map[string]bool)
}
excludeHeader[k] = true
trailers = true
}
}
for _, v := range cw.header["Trailer"] {
trailers = true
foreachHeaderElement(v, cw.res.declareTrailer)
}
te := header.get("Transfer-Encoding")
hasTE := te != ""
// If the handler is done but never sent a Content-Length
// response header and this is our first (and last) write, set
// it, even to zero. This helps HTTP/1.0 clients keep their
// "keep-alive" connections alive.
// Exceptions: 304/204/1xx responses never get Content-Length, and if
// it was a HEAD request, we don't know the difference between
// 0 actual bytes and 0 bytes because the handler noticed it
// was a HEAD request and chose not to write anything. So for
// HEAD, the handler should either write the Content-Length or
// write non-zero bytes. If it's actually 0 bytes and the
// handler never looked at the Request.Method, we just don't
// send a Content-Length header.
// Further, we don't send an automatic Content-Length if they
// set a Transfer-Encoding, because they're generally incompatible.
if w.handlerDone.isSet() && !trailers && !hasTE && bodyAllowedForStatus(w.status) && header.get("Content-Length") == "" && (!isHEAD || len(p) > 0) {
w.contentLength = int64(len(p))
setHeader.contentLength = strconv.AppendInt(cw.res.clenBuf[:0], int64(len(p)), 10)
}
// If this was an HTTP/1.0 request with keep-alive and we sent a
// Content-Length back, we can make this a keep-alive response ...
if w.wants10KeepAlive && keepAlivesEnabled {
sentLength := header.get("Content-Length") != ""
if sentLength && header.get("Connection") == "keep-alive" {
w.closeAfterReply = false
}
}
// Check for a explicit (and valid) Content-Length header.
hasCL := w.contentLength != -1
if w.wants10KeepAlive && (isHEAD || hasCL || !bodyAllowedForStatus(w.status)) {
_, connectionHeaderSet := header["Connection"]
if !connectionHeaderSet {
setHeader.connection = "keep-alive"
}
} else if !w.req.ProtoAtLeast(1, 1) || w.wantsClose {
w.closeAfterReply = true
}
if header.get("Connection") == "close" || !keepAlivesEnabled {
w.closeAfterReply = true
}
// If the client wanted a 100-continue but we never sent it to
// them (or, more strictly: we never finished reading their
// request body), don't reuse this connection because it's now
// in an unknown state: we might be sending this response at
// the same time the client is now sending its request body
// after a timeout. (Some HTTP clients send Expect:
// 100-continue but knowing that some servers don't support
// it, the clients set a timer and send the body later anyway)
// If we haven't seen EOF, we can't skip over the unread body
// because we don't know if the next bytes on the wire will be
// the body-following-the-timer or the subsequent request.
// See Issue 11549.
if ecr, ok := w.req.Body.(*expectContinueReader); ok && !ecr.sawEOF {
w.closeAfterReply = true
}
// Per RFC 2616, we should consume the request body before
// replying, if the handler hasn't already done so. But we
// don't want to do an unbounded amount of reading here for
// DoS reasons, so we only try up to a threshold.
// TODO(bradfitz): where does RFC 2616 say that? See Issue 15527
// about HTTP/1.x Handlers concurrently reading and writing, like
// HTTP/2 handlers can do. Maybe this code should be relaxed?
if w.req.ContentLength != 0 && !w.closeAfterReply {
var discard, tooBig bool
switch bdy := w.req.Body.(type) {
case *expectContinueReader:
if bdy.resp.wroteContinue {
discard = true
}
case *body:
bdy.mu.Lock()
switch {
case bdy.closed:
if !bdy.sawEOF {
// Body was closed in handler with non-EOF error.
w.closeAfterReply = true
}
case bdy.unreadDataSizeLocked() >= maxPostHandlerReadBytes:
tooBig = true
default:
discard = true
}
bdy.mu.Unlock()
default:
discard = true
}
if discard {
_, err := io.CopyN(ioutil.Discard, w.reqBody, maxPostHandlerReadBytes+1)
switch err {
case nil:
// There must be even more data left over.
tooBig = true
case ErrBodyReadAfterClose:
// Body was already consumed and closed.
case io.EOF:
// The remaining body was just consumed, close it.
err = w.reqBody.Close()
if err != nil {
w.closeAfterReply = true
}
default:
// Some other kind of error occurred, like a read timeout, or
// corrupt chunked encoding. In any case, whatever remains
// on the wire must not be parsed as another HTTP request.
w.closeAfterReply = true
}
}
if tooBig {
w.requestTooLarge()
delHeader("Connection")
setHeader.connection = "close"
}
}
code := w.status
if bodyAllowedForStatus(code) {
// If no content type, apply sniffing algorithm to body.
_, haveType := header["Content-Type"]
if !haveType && !hasTE {
setHeader.contentType = DetectContentType(p)
}
} else {
for _, k := range suppressedHeaders(code) {
delHeader(k)
}
}
if _, ok := header["Date"]; !ok {
setHeader.date = appendTime(cw.res.dateBuf[:0], time.Now())
}
if hasCL && hasTE && te != "identity" {
// TODO: return an error if WriteHeader gets a return parameter
// For now just ignore the Content-Length.
w.conn.server.logf("http: WriteHeader called with both Transfer-Encoding of %q and a Content-Length of %d",
te, w.contentLength)
delHeader("Content-Length")
hasCL = false
}
if w.req.Method == "HEAD" || !bodyAllowedForStatus(code) {
// do nothing
} else if code == StatusNoContent {
delHeader("Transfer-Encoding")
} else if hasCL {
delHeader("Transfer-Encoding")
} else if w.req.ProtoAtLeast(1, 1) {
// HTTP/1.1 or greater: Transfer-Encoding has been set to identity, and no
// content-length has been provided. The connection must be closed after the
// reply is written, and no chunking is to be done. This is the setup
// recommended in the Server-Sent Events candidate recommendation 11,
// section 8.
if hasTE && te == "identity" {
cw.chunking = false
w.closeAfterReply = true
} else {
// HTTP/1.1 or greater: use chunked transfer encoding
// to avoid closing the connection at EOF.
cw.chunking = true
setHeader.transferEncoding = "chunked"
if hasTE && te == "chunked" {
// We will send the chunked Transfer-Encoding header later.
delHeader("Transfer-Encoding")
}
}
} else {
// HTTP version < 1.1: cannot do chunked transfer
// encoding and we don't know the Content-Length so
// signal EOF by closing connection.
w.closeAfterReply = true
delHeader("Transfer-Encoding") // in case already set
}
// Cannot use Content-Length with non-identity Transfer-Encoding.
if cw.chunking {
delHeader("Content-Length")
}
if !w.req.ProtoAtLeast(1, 0) {
return
}
if w.closeAfterReply && (!keepAlivesEnabled || !hasToken(cw.header.get("Connection"), "close")) {
delHeader("Connection")
if w.req.ProtoAtLeast(1, 1) {
setHeader.connection = "close"
}
}
w.conn.bufw.WriteString(statusLine(w.req, code))
cw.header.WriteSubset(w.conn.bufw, excludeHeader)
setHeader.Write(w.conn.bufw)
w.conn.bufw.Write(crlf)
}
// foreachHeaderElement splits v according to the "#rule" construction
// in RFC 2616 section 2.1 and calls fn for each non-empty element.
func foreachHeaderElement(v string, fn func(string)) {
v = textproto.TrimString(v)
if v == "" {
return
}
if !strings.Contains(v, ",") {
fn(v)
return
}
for _, f := range strings.Split(v, ",") {
if f = textproto.TrimString(f); f != "" {
fn(f)
}
}
}
// statusLines is a cache of Status-Line strings, keyed by code (for
// HTTP/1.1) or negative code (for HTTP/1.0). This is faster than a
// map keyed by struct of two fields. This map's max size is bounded
// by 2*len(statusText), two protocol types for each known official
// status code in the statusText map.
var (
statusMu sync.RWMutex
statusLines = make(map[int]string)
)
// statusLine returns a response Status-Line (RFC 2616 Section 6.1)
// for the given request and response status code.
func statusLine(req *Request, code int) string {
// Fast path:
key := code
proto11 := req.ProtoAtLeast(1, 1)
if !proto11 {
key = -key
}
statusMu.RLock()
line, ok := statusLines[key]
statusMu.RUnlock()
if ok {
return line
}
// Slow path:
proto := "HTTP/1.0"
if proto11 {
proto = "HTTP/1.1"
}
codestring := fmt.Sprintf("%03d", code)
text, ok := statusText[code]
if !ok {
text = "status code " + codestring
}
line = proto + " " + codestring + " " + text + "\r\n"
if ok {
statusMu.Lock()
defer statusMu.Unlock()
statusLines[key] = line
}
return line
}
// bodyAllowed reports whether a Write is allowed for this response type.
// It's illegal to call this before the header has been flushed.
func (w *response) bodyAllowed() bool {
if !w.wroteHeader {
panic("")
}
return bodyAllowedForStatus(w.status)
}
// The Life Of A Write is like this:
//
// Handler starts. No header has been sent. The handler can either
// write a header, or just start writing. Writing before sending a header
// sends an implicitly empty 200 OK header.
//
// If the handler didn't declare a Content-Length up front, we either
// go into chunking mode or, if the handler finishes running before
// the chunking buffer size, we compute a Content-Length and send that
// in the header instead.
//
// Likewise, if the handler didn't set a Content-Type, we sniff that
// from the initial chunk of output.
//
// The Writers are wired together like:
//
// 1. *response (the ResponseWriter) ->
// 2. (*response).w, a *bufio.Writer of bufferBeforeChunkingSize bytes
// 3. chunkWriter.Writer (whose writeHeader finalizes Content-Length/Type)
// and which writes the chunk headers, if needed.
// 4. conn.buf, a bufio.Writer of default (4kB) bytes, writing to ->
// 5. checkConnErrorWriter{c}, which notes any non-nil error on Write
// and populates c.werr with it if so. but otherwise writes to:
// 6. the rwc, the net.Conn.
//
// TODO(bradfitz): short-circuit some of the buffering when the
// initial header contains both a Content-Type and Content-Length.
// Also short-circuit in (1) when the header's been sent and not in
// chunking mode, writing directly to (4) instead, if (2) has no
// buffered data. More generally, we could short-circuit from (1) to
// (3) even in chunking mode if the write size from (1) is over some
// threshold and nothing is in (2). The answer might be mostly making
// bufferBeforeChunkingSize smaller and having bufio's fast-paths deal
// with this instead.
func (w *response) Write(data []byte) (n int, err error) {
return w.write(len(data), data, "")
}
func (w *response) WriteString(data string) (n int, err error) {
return w.write(len(data), nil, data)
}
// either dataB or dataS is non-zero.
func (w *response) write(lenData int, dataB []byte, dataS string) (n int, err error) {
if w.conn.hijacked() {
if lenData > 0 {
w.conn.server.logf("http: response.Write on hijacked connection")
}
return 0, ErrHijacked
}
if !w.wroteHeader {
w.WriteHeader(StatusOK)
}
if lenData == 0 {
return 0, nil
}
if !w.bodyAllowed() {
return 0, ErrBodyNotAllowed
}
w.written += int64(lenData) // ignoring errors, for errorKludge
if w.contentLength != -1 && w.written > w.contentLength {
return 0, ErrContentLength
}
if dataB != nil {
return w.w.Write(dataB)
} else {
return w.w.WriteString(dataS)
}
}
func (w *response) finishRequest() {
w.handlerDone.setTrue()
if !w.wroteHeader {
w.WriteHeader(StatusOK)
}
w.w.Flush()
putBufioWriter(w.w)
w.cw.close()
w.conn.bufw.Flush()
w.conn.r.abortPendingRead()
// Close the body (regardless of w.closeAfterReply) so we can
// re-use its bufio.Reader later safely.
w.reqBody.Close()
if w.req.MultipartForm != nil {
w.req.MultipartForm.RemoveAll()
}
}
// shouldReuseConnection reports whether the underlying TCP connection can be reused.
// It must only be called after the handler is done executing.
func (w *response) shouldReuseConnection() bool {
if w.closeAfterReply {
// The request or something set while executing the
// handler indicated we shouldn't reuse this
// connection.
return false
}
if w.req.Method != "HEAD" && w.contentLength != -1 && w.bodyAllowed() && w.contentLength != w.written {
// Did not write enough. Avoid getting out of sync.
return false
}
// There was some error writing to the underlying connection
// during the request, so don't re-use this conn.
if w.conn.werr != nil {
return false
}
if w.closedRequestBodyEarly() {
return false
}
return true
}
func (w *response) closedRequestBodyEarly() bool {
body, ok := w.req.Body.(*body)
return ok && body.didEarlyClose()
}
func (w *response) Flush() {
if !w.wroteHeader {
w.WriteHeader(StatusOK)
}
w.w.Flush()
w.cw.flush()
}
func (c *conn) finalFlush() {
if c.bufr != nil {
// Steal the bufio.Reader (~4KB worth of memory) and its associated
// reader for a future connection.
putBufioReader(c.bufr)
c.bufr = nil
}
if c.bufw != nil {
c.bufw.Flush()
// Steal the bufio.Writer (~4KB worth of memory) and its associated
// writer for a future connection.
putBufioWriter(c.bufw)
c.bufw = nil
}
}
// Close the connection.
func (c *conn) close() {
c.finalFlush()
c.rwc.Close()
}
// rstAvoidanceDelay is the amount of time we sleep after closing the
// write side of a TCP connection before closing the entire socket.
// By sleeping, we increase the chances that the client sees our FIN
// and processes its final data before they process the subsequent RST
// from closing a connection with known unread data.
// This RST seems to occur mostly on BSD systems. (And Windows?)
// This timeout is somewhat arbitrary (~latency around the planet).
const rstAvoidanceDelay = 500 * time.Millisecond
type closeWriter interface {
CloseWrite() error
}
var _ closeWriter = (*net.TCPConn)(nil)
// closeWrite flushes any outstanding data and sends a FIN packet (if
// client is connected via TCP), signalling that we're done. We then
// pause for a bit, hoping the client processes it before any
// subsequent RST.
//
// See https://golang.org/issue/3595
func (c *conn) closeWriteAndWait() {
c.finalFlush()
if tcp, ok := c.rwc.(closeWriter); ok {
tcp.CloseWrite()
}
time.Sleep(rstAvoidanceDelay)
}
// validNPN reports whether the proto is not a blacklisted Next
// Protocol Negotiation protocol. Empty and built-in protocol types
// are blacklisted and can't be overridden with alternate
// implementations.
func validNPN(proto string) bool {
switch proto {
case "", "http/1.1", "http/1.0":
return false
}
return true
}
func (c *conn) setState(nc net.Conn, state ConnState) {
srv := c.server
switch state {
case StateNew:
srv.trackConn(c, true)
case StateHijacked, StateClosed:
srv.trackConn(c, false)
}
c.curState.Store(connStateInterface[state])
if hook := srv.ConnState; hook != nil {
hook(nc, state)
}
}
// connStateInterface is an array of the interface{} versions of
// ConnState values, so we can use them in atomic.Values later without
// paying the cost of shoving their integers in an interface{}.
var connStateInterface = [...]interface{}{
StateNew: StateNew,
StateActive: StateActive,
StateIdle: StateIdle,
StateHijacked: StateHijacked,
StateClosed: StateClosed,
}
// badRequestError is a literal string (used by in the server in HTML,
// unescaped) to tell the user why their request was bad. It should
// be plain text without user info or other embedded errors.
type badRequestError string
func (e badRequestError) Error() string { return "Bad Request: " + string(e) }
// ErrAbortHandler is a sentinel panic value to abort a handler.
// While any panic from ServeHTTP aborts the response to the client,
// panicking with ErrAbortHandler also suppresses logging of a stack
// trace to the server's error log.
var ErrAbortHandler = errors.New("net/http: abort Handler")
// isCommonNetReadError reports whether err is a common error
// encountered during reading a request off the network when the
// client has gone away or had its read fail somehow. This is used to
// determine which logs are interesting enough to log about.
func isCommonNetReadError(err error) bool {
if err == io.EOF {
return true
}
if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
return true
}
if oe, ok := err.(*net.OpError); ok && oe.Op == "read" {
return true
}
return false
}
// Serve a new connection.
func (c *conn) serve(ctx context.Context) {
c.remoteAddr = c.rwc.RemoteAddr().String()
defer func() {
if err := recover(); err != nil && err != ErrAbortHandler {
const size = 64 << 10
buf := make([]byte, size)
buf = buf[:runtime.Stack(buf, false)]
c.server.logf("http: panic serving %v: %v\n%s", c.remoteAddr, err, buf)
}
if !c.hijacked() {
c.close()
c.setState(c.rwc, StateClosed)
}
}()
if tlsConn, ok := c.rwc.(*tls.Conn); ok {
if d := c.server.ReadTimeout; d != 0 {
c.rwc.SetReadDeadline(time.Now().Add(d))
}
if d := c.server.WriteTimeout; d != 0 {
c.rwc.SetWriteDeadline(time.Now().Add(d))
}
if err := tlsConn.Handshake(); err != nil {
c.server.logf("http: TLS handshake error from %s: %v", c.rwc.RemoteAddr(), err)
return
}
c.tlsState = new(tls.ConnectionState)
*c.tlsState = tlsConn.ConnectionState()
if proto := c.tlsState.NegotiatedProtocol; validNPN(proto) {
if fn := c.server.TLSNextProto[proto]; fn != nil {
h := initNPNRequest{tlsConn, serverHandler{c.server}}
fn(c.server, tlsConn, h)
}
return
}
}
// HTTP/1.x from here on.
ctx, cancelCtx := context.WithCancel(ctx)
c.cancelCtx = cancelCtx
defer cancelCtx()
c.r = &connReader{conn: c}
c.bufr = newBufioReader(c.r)
c.bufw = newBufioWriterSize(checkConnErrorWriter{c}, 4<<10)
for {
w, err := c.readRequest(ctx)
if c.r.remain != c.server.initialReadLimitSize() {
// If we read any bytes off the wire, we're active.
c.setState(c.rwc, StateActive)
}
if err != nil {
const errorHeaders = "\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\n"
if err == errTooLarge {
// Their HTTP client may or may not be
// able to read this if we're
// responding to them and hanging up
// while they're still writing their
// request. Undefined behavior.
const publicErr = "431 Request Header Fields Too Large"
fmt.Fprintf(c.rwc, "HTTP/1.1 "+publicErr+errorHeaders+publicErr)
c.closeWriteAndWait()
return
}
if isCommonNetReadError(err) {
return // don't reply
}
publicErr := "400 Bad Request"
if v, ok := err.(badRequestError); ok {
publicErr = publicErr + ": " + string(v)
}
fmt.Fprintf(c.rwc, "HTTP/1.1 "+publicErr+errorHeaders+publicErr)
return
}
// Expect 100 Continue support
req := w.req
if req.expectsContinue() {
if req.ProtoAtLeast(1, 1) && req.ContentLength != 0 {
// Wrap the Body reader with one that replies on the connection
req.Body = &expectContinueReader{readCloser: req.Body, resp: w}
}
} else if req.Header.get("Expect") != "" {
w.sendExpectationFailed()
return
}
c.curReq.Store(w)
if requestBodyRemains(req.Body) {
registerOnHitEOF(req.Body, w.conn.r.startBackgroundRead)
} else {
if w.conn.bufr.Buffered() > 0 {
w.conn.r.closeNotifyFromPipelinedRequest()
}
w.conn.r.startBackgroundRead()
}
// HTTP cannot have multiple simultaneous active requests.[*]
// Until the server replies to this request, it can't read another,
// so we might as well run the handler in this goroutine.
// [*] Not strictly true: HTTP pipelining. We could let them all process
// in parallel even if their responses need to be serialized.
// But we're not going to implement HTTP pipelining because it
// was never deployed in the wild and the answer is HTTP/2.
serverHandler{c.server}.ServeHTTP(w, w.req)
w.cancelCtx()
if c.hijacked() {
return
}
w.finishRequest()
if !w.shouldReuseConnection() {
if w.requestBodyLimitHit || w.closedRequestBodyEarly() {
c.closeWriteAndWait()
}
return
}
c.setState(c.rwc, StateIdle)
c.curReq.Store((*response)(nil))
if !w.conn.server.doKeepAlives() {
// We're in shutdown mode. We might've replied
// to the user without "Connection: close" and
// they might think they can send another
// request, but such is life with HTTP/1.1.
return
}
if d := c.server.idleTimeout(); d != 0 {
c.rwc.SetReadDeadline(time.Now().Add(d))
if _, err := c.bufr.Peek(4); err != nil {
return
}
}
c.rwc.SetReadDeadline(time.Time{})
}
}
func (w *response) sendExpectationFailed() {
// TODO(bradfitz): let ServeHTTP handlers handle
// requests with non-standard expectation[s]? Seems
// theoretical at best, and doesn't fit into the
// current ServeHTTP model anyway. We'd need to
// make the ResponseWriter an optional
// "ExpectReplier" interface or something.
//
// For now we'll just obey RFC 2616 14.20 which says
// "If a server receives a request containing an
// Expect field that includes an expectation-
// extension that it does not support, it MUST
// respond with a 417 (Expectation Failed) status."
w.Header().Set("Connection", "close")
w.WriteHeader(StatusExpectationFailed)
w.finishRequest()
}
// Hijack implements the Hijacker.Hijack method. Our response is both a ResponseWriter
// and a Hijacker.
func (w *response) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error) {
if w.handlerDone.isSet() {
panic("net/http: Hijack called after ServeHTTP finished")
}
if w.wroteHeader {
w.cw.flush()
}
c := w.conn
c.mu.Lock()
defer c.mu.Unlock()
// Release the bufioWriter that writes to the chunk writer, it is not
// used after a connection has been hijacked.
rwc, buf, err = c.hijackLocked()
if err == nil {
putBufioWriter(w.w)
w.w = nil
}
return rwc, buf, err
}
func (w *response) CloseNotify() <-chan bool {
if w.handlerDone.isSet() {
panic("net/http: CloseNotify called after ServeHTTP finished")
}
return w.closeNotifyCh
}
func registerOnHitEOF(rc io.ReadCloser, fn func()) {
switch v := rc.(type) {
case *expectContinueReader:
registerOnHitEOF(v.readCloser, fn)
case *body:
v.registerOnHitEOF(fn)
default:
panic("unexpected type " + fmt.Sprintf("%T", rc))
}
}
// requestBodyRemains reports whether future calls to Read
// on rc might yield more data.
func requestBodyRemains(rc io.ReadCloser) bool {
if rc == NoBody {
return false
}
switch v := rc.(type) {
case *expectContinueReader:
return requestBodyRemains(v.readCloser)
case *body:
return v.bodyRemains()
default:
panic("unexpected type " + fmt.Sprintf("%T", rc))
}
}
// The HandlerFunc type is an adapter to allow the use of
// ordinary functions as HTTP handlers. If f is a function
// with the appropriate signature, HandlerFunc(f) is a
// Handler that calls f.
type HandlerFunc func(ResponseWriter, *Request)
// ServeHTTP calls f(w, r).
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
f(w, r)
}
// Helper handlers
// Error replies to the request with the specified error message and HTTP code.
// It does not otherwise end the request; the caller should ensure no further
// writes are done to w.
// The error message should be plain text.
func Error(w ResponseWriter, error string, code int) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(code)
fmt.Fprintln(w, error)
}
// NotFound replies to the request with an HTTP 404 not found error.
func NotFound(w ResponseWriter, r *Request) { Error(w, "404 page not found", StatusNotFound) }
// NotFoundHandler returns a simple request handler
// that replies to each request with a ``404 page not found'' reply.
func NotFoundHandler() Handler { return HandlerFunc(NotFound) }
// StripPrefix returns a handler that serves HTTP requests
// by removing the given prefix from the request URL's Path
// and invoking the handler h. StripPrefix handles a
// request for a path that doesn't begin with prefix by
// replying with an HTTP 404 not found error.
func StripPrefix(prefix string, h Handler) Handler {
if prefix == "" {
return h
}
return HandlerFunc(func(w ResponseWriter, r *Request) {
if p := strings.TrimPrefix(r.URL.Path, prefix); len(p) < len(r.URL.Path) {
r2 := new(Request)
*r2 = *r
r2.URL = new(url.URL)
*r2.URL = *r.URL
r2.URL.Path = p
h.ServeHTTP(w, r2)
} else {
NotFound(w, r)
}
})
}
// Redirect replies to the request with a redirect to url,
// which may be a path relative to the request path.
//
// The provided code should be in the 3xx range and is usually
// StatusMovedPermanently, StatusFound or StatusSeeOther.
func Redirect(w ResponseWriter, r *Request, urlStr string, code int) {
if u, err := url.Parse(urlStr); err == nil {
// If url was relative, make absolute by
// combining with request path.
// The browser would probably do this for us,
// but doing it ourselves is more reliable.
// NOTE(rsc): RFC 2616 says that the Location
// line must be an absolute URI, like
// "http://www.google.com/redirect/",
// not a path like "/redirect/".
// Unfortunately, we don't know what to
// put in the host name section to get the
// client to connect to us again, so we can't
// know the right absolute URI to send back.
// Because of this problem, no one pays attention
// to the RFC; they all send back just a new path.
// So do we.
if u.Scheme == "" && u.Host == "" {
oldpath := r.URL.Path
if oldpath == "" { // should not happen, but avoid a crash if it does
oldpath = "/"
}
// no leading http://server
if urlStr == "" || urlStr[0] != '/' {
// make relative path absolute
olddir, _ := path.Split(oldpath)
urlStr = olddir + urlStr
}
var query string
if i := strings.Index(urlStr, "?"); i != -1 {
urlStr, query = urlStr[:i], urlStr[i:]
}
// clean up but preserve trailing slash
trailing := strings.HasSuffix(urlStr, "/")
urlStr = path.Clean(urlStr)
if trailing && !strings.HasSuffix(urlStr, "/") {
urlStr += "/"
}
urlStr += query
}
}
w.Header().Set("Location", hexEscapeNonASCII(urlStr))
w.WriteHeader(code)
// RFC 2616 recommends that a short note "SHOULD" be included in the
// response because older user agents may not understand 301/307.
// Shouldn't send the response for POST or HEAD; that leaves GET.
if r.Method == "GET" {
note := "<a href=\"" + htmlEscape(urlStr) + "\">" + statusText[code] + "</a>.\n"
fmt.Fprintln(w, note)
}
}
var htmlReplacer = strings.NewReplacer(
"&", "&",
"<", "<",
">", ">",
// """ is shorter than """.
`"`, """,
// "'" is shorter than "'" and apos was not in HTML until HTML5.
"'", "'",
)
func htmlEscape(s string) string {
return htmlReplacer.Replace(s)
}
// Redirect to a fixed URL
type redirectHandler struct {
url string
code int
}
func (rh *redirectHandler) ServeHTTP(w ResponseWriter, r *Request) {
Redirect(w, r, rh.url, rh.code)
}
// RedirectHandler returns a request handler that redirects
// each request it receives to the given url using the given
// status code.
//
// The provided code should be in the 3xx range and is usually
// StatusMovedPermanently, StatusFound or StatusSeeOther.
func RedirectHandler(url string, code int) Handler {
return &redirectHandler{url, code}
}
// ServeMux is an HTTP request multiplexer.
// It matches the URL of each incoming request against a list of registered
// patterns and calls the handler for the pattern that
// most closely matches the URL.
//
// Patterns name fixed, rooted paths, like "/favicon.ico",
// or rooted subtrees, like "/images/" (note the trailing slash).
// Longer patterns take precedence over shorter ones, so that
// if there are handlers registered for both "/images/"
// and "/images/thumbnails/", the latter handler will be
// called for paths beginning "/images/thumbnails/" and the
// former will receive requests for any other paths in the
// "/images/" subtree.
//
// Note that since a pattern ending in a slash names a rooted subtree,
// the pattern "/" matches all paths not matched by other registered
// patterns, not just the URL with Path == "/".
//
// If a subtree has been registered and a request is received naming the
// subtree root without its trailing slash, ServeMux redirects that
// request to the subtree root (adding the trailing slash). This behavior can
// be overridden with a separate registration for the path without
// the trailing slash. For example, registering "/images/" causes ServeMux
// to redirect a request for "/images" to "/images/", unless "/images" has
// been registered separately.
//
// Patterns may optionally begin with a host name, restricting matches to
// URLs on that host only. Host-specific patterns take precedence over
// general patterns, so that a handler might register for the two patterns
// "/codesearch" and "codesearch.google.com/" without also taking over
// requests for "http://www.google.com/".
//
// ServeMux also takes care of sanitizing the URL request path,
// redirecting any request containing . or .. elements or repeated slashes
// to an equivalent, cleaner URL.
type ServeMux struct {
mu sync.RWMutex
m map[string]muxEntry
hosts bool // whether any patterns contain hostnames
}
type muxEntry struct {
explicit bool
h Handler
pattern string
}
// NewServeMux allocates and returns a new ServeMux.
func NewServeMux() *ServeMux { return new(ServeMux) }
// DefaultServeMux is the default ServeMux used by Serve.
var DefaultServeMux = &defaultServeMux
var defaultServeMux ServeMux
// Does path match pattern?
func pathMatch(pattern, path string) bool {
if len(pattern) == 0 {
// should not happen
return false
}
n := len(pattern)
if pattern[n-1] != '/' {
return pattern == path
}
return len(path) >= n && path[0:n] == pattern
}
// Return the canonical path for p, eliminating . and .. elements.
func cleanPath(p string) string {
if p == "" {
return "/"
}
if p[0] != '/' {
p = "/" + p
}
np := path.Clean(p)
// path.Clean removes trailing slash except for root;
// put the trailing slash back if necessary.
if p[len(p)-1] == '/' && np != "/" {
np += "/"
}
return np
}
// stripHostPort returns h without any trailing ":<port>".
func stripHostPort(h string) string {
// If no port on host, return unchanged
if strings.IndexByte(h, ':') == -1 {
return h
}
host, _, err := net.SplitHostPort(h)
if err != nil {
return h // on error, return unchanged
}
return host
}
// Find a handler on a handler map given a path string.
// Most-specific (longest) pattern wins.
func (mux *ServeMux) match(path string) (h Handler, pattern string) {
// Check for exact match first.
v, ok := mux.m[path]
if ok {
return v.h, v.pattern
}
// Check for longest valid match.
var n = 0
for k, v := range mux.m {
if !pathMatch(k, path) {
continue
}
if h == nil || len(k) > n {
n = len(k)
h = v.h
pattern = v.pattern
}
}
return
}
// Handler returns the handler to use for the given request,
// consulting r.Method, r.Host, and r.URL.Path. It always returns
// a non-nil handler. If the path is not in its canonical form, the
// handler will be an internally-generated handler that redirects
// to the canonical path. If the host contains a port, it is ignored
// when matching handlers.
//
// The path and host are used unchanged for CONNECT requests.
//
// Handler also returns the registered pattern that matches the
// request or, in the case of internally-generated redirects,
// the pattern that will match after following the redirect.
//
// If there is no registered handler that applies to the request,
// Handler returns a ``page not found'' handler and an empty pattern.
func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string) {
// CONNECT requests are not canonicalized.
if r.Method == "CONNECT" {
return mux.handler(r.Host, r.URL.Path)
}
// All other requests have any port stripped and path cleaned
// before passing to mux.handler.
host := stripHostPort(r.Host)
path := cleanPath(r.URL.Path)
if path != r.URL.Path {
_, pattern = mux.handler(host, path)
url := *r.URL
url.Path = path
return RedirectHandler(url.String(), StatusMovedPermanently), pattern
}
return mux.handler(host, r.URL.Path)
}
// handler is the main implementation of Handler.
// The path is known to be in canonical form, except for CONNECT methods.
func (mux *ServeMux) handler(host, path string) (h Handler, pattern string) {
mux.mu.RLock()
defer mux.mu.RUnlock()
// Host-specific pattern takes precedence over generic ones
if mux.hosts {
h, pattern = mux.match(host + path)
}
if h == nil {
h, pattern = mux.match(path)
}
if h == nil {
h, pattern = NotFoundHandler(), ""
}
return
}
// ServeHTTP dispatches the request to the handler whose
// pattern most closely matches the request URL.
func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) {
if r.RequestURI == "*" {
if r.ProtoAtLeast(1, 1) {
w.Header().Set("Connection", "close")
}
w.WriteHeader(StatusBadRequest)
return
}
h, _ := mux.Handler(r)
h.ServeHTTP(w, r)
}
// Handle registers the handler for the given pattern.
// If a handler already exists for pattern, Handle panics.
func (mux *ServeMux) Handle(pattern string, handler Handler) {
mux.mu.Lock()
defer mux.mu.Unlock()
if pattern == "" {
panic("http: invalid pattern " + pattern)
}
if handler == nil {
panic("http: nil handler")
}
if mux.m[pattern].explicit {
panic("http: multiple registrations for " + pattern)
}
if mux.m == nil {
mux.m = make(map[string]muxEntry)
}
mux.m[pattern] = muxEntry{explicit: true, h: handler, pattern: pattern}
if pattern[0] != '/' {
mux.hosts = true
}
// Helpful behavior:
// If pattern is /tree/, insert an implicit permanent redirect for /tree.
// It can be overridden by an explicit registration.
n := len(pattern)
if n > 0 && pattern[n-1] == '/' && !mux.m[pattern[0:n-1]].explicit {
// If pattern contains a host name, strip it and use remaining
// path for redirect.
path := pattern
if pattern[0] != '/' {
// In pattern, at least the last character is a '/', so
// strings.Index can't be -1.
path = pattern[strings.Index(pattern, "/"):]
}
url := &url.URL{Path: path}
mux.m[pattern[0:n-1]] = muxEntry{h: RedirectHandler(url.String(), StatusMovedPermanently), pattern: pattern}
}
}
// HandleFunc registers the handler function for the given pattern.
func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
mux.Handle(pattern, HandlerFunc(handler))
}
// Handle registers the handler for the given pattern
// in the DefaultServeMux.
// The documentation for ServeMux explains how patterns are matched.
func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) }
// HandleFunc registers the handler function for the given pattern
// in the DefaultServeMux.
// The documentation for ServeMux explains how patterns are matched.
func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
DefaultServeMux.HandleFunc(pattern, handler)
}
// Serve accepts incoming HTTP connections on the listener l,
// creating a new service goroutine for each. The service goroutines
// read requests and then call handler to reply to them.
// Handler is typically nil, in which case the DefaultServeMux is used.
func Serve(l net.Listener, handler Handler) error {
srv := &Server{Handler: handler}
return srv.Serve(l)
}
// A Server defines parameters for running an HTTP server.
// The zero value for Server is a valid configuration.
type Server struct {
Addr string // TCP address to listen on, ":http" if empty
Handler Handler // handler to invoke, http.DefaultServeMux if nil
TLSConfig *tls.Config // optional TLS config, used by ListenAndServeTLS
// ReadTimeout is the maximum duration for reading the entire
// request, including the body.
//
// Because ReadTimeout does not let Handlers make per-request
// decisions on each request body's acceptable deadline or
// upload rate, most users will prefer to use
// ReadHeaderTimeout. It is valid to use them both.
ReadTimeout time.Duration
// ReadHeaderTimeout is the amount of time allowed to read
// request headers. The connection's read deadline is reset
// after reading the headers and the Handler can decide what
// is considered too slow for the body.
ReadHeaderTimeout time.Duration
// WriteTimeout is the maximum duration before timing out
// writes of the response. It is reset whenever a new
// request's header is read. Like ReadTimeout, it does not
// let Handlers make decisions on a per-request basis.
WriteTimeout time.Duration
// IdleTimeout is the maximum amount of time to wait for the
// next request when keep-alives are enabled. If IdleTimeout
// is zero, the value of ReadTimeout is used. If both are
// zero, there is no timeout.
IdleTimeout time.Duration
// MaxHeaderBytes controls the maximum number of bytes the
// server will read parsing the request header's keys and
// values, including the request line. It does not limit the
// size of the request body.
// If zero, DefaultMaxHeaderBytes is used.
MaxHeaderBytes int
// TLSNextProto optionally specifies a function to take over
// ownership of the provided TLS connection when an NPN/ALPN
// protocol upgrade has occurred. The map key is the protocol
// name negotiated. The Handler argument should be used to
// handle HTTP requests and will initialize the Request's TLS
// and RemoteAddr if not already set. The connection is
// automatically closed when the function returns.
// If TLSNextProto is not nil, HTTP/2 support is not enabled
// automatically.
TLSNextProto map[string]func(*Server, *tls.Conn, Handler)
// ConnState specifies an optional callback function that is
// called when a client connection changes state. See the
// ConnState type and associated constants for details.
ConnState func(net.Conn, ConnState)
// ErrorLog specifies an optional logger for errors accepting
// connections and unexpected behavior from handlers.
// If nil, logging goes to os.Stderr via the log package's
// standard logger.
ErrorLog *log.Logger
disableKeepAlives int32 // accessed atomically.
inShutdown int32 // accessed atomically (non-zero means we're in Shutdown)
nextProtoOnce sync.Once // guards setupHTTP2_* init
nextProtoErr error // result of http2.ConfigureServer if used
mu sync.Mutex
listeners map[net.Listener]struct{}
activeConn map[*conn]struct{}
doneChan chan struct{}
}
func (s *Server) getDoneChan() <-chan struct{} {
s.mu.Lock()
defer s.mu.Unlock()
return s.getDoneChanLocked()
}
func (s *Server) getDoneChanLocked() chan struct{} {
if s.doneChan == nil {
s.doneChan = make(chan struct{})
}
return s.doneChan
}
func (s *Server) closeDoneChanLocked() {
ch := s.getDoneChanLocked()
select {
case <-ch:
// Already closed. Don't close again.
default:
// Safe to close here. We're the only closer, guarded
// by s.mu.
close(ch)
}
}
// Close immediately closes all active net.Listeners and any
// connections in state StateNew, StateActive, or StateIdle. For a
// graceful shutdown, use Shutdown.
//
// Close does not attempt to close (and does not even know about)
// any hijacked connections, such as WebSockets.
//
// Close returns any error returned from closing the Server's
// underlying Listener(s).
func (srv *Server) Close() error {
srv.mu.Lock()
defer srv.mu.Unlock()
srv.closeDoneChanLocked()
err := srv.closeListenersLocked()
for c := range srv.activeConn {
c.rwc.Close()
delete(srv.activeConn, c)
}
return err
}
// shutdownPollInterval is how often we poll for quiescence
// during Server.Shutdown. This is lower during tests, to
// speed up tests.
// Ideally we could find a solution that doesn't involve polling,
// but which also doesn't have a high runtime cost (and doesn't
// involve any contentious mutexes), but that is left as an
// exercise for the reader.
var shutdownPollInterval = 500 * time.Millisecond
// Shutdown gracefully shuts down the server without interrupting any
// active connections. Shutdown works by first closing all open
// listeners, then closing all idle connections, and then waiting
// indefinitely for connections to return to idle and then shut down.
// If the provided context expires before the shutdown is complete,
// then the context's error is returned.
//
// Shutdown does not attempt to close nor wait for hijacked
// connections such as WebSockets. The caller of Shutdown should
// separately notify such long-lived connections of shutdown and wait
// for them to close, if desired.
func (srv *Server) Shutdown(ctx context.Context) error {
atomic.AddInt32(&srv.inShutdown, 1)
defer atomic.AddInt32(&srv.inShutdown, -1)
srv.mu.Lock()
lnerr := srv.closeListenersLocked()
srv.closeDoneChanLocked()
srv.mu.Unlock()
ticker := time.NewTicker(shutdownPollInterval)
defer ticker.Stop()
for {
if srv.closeIdleConns() {
return lnerr
}
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
}
}
}
// closeIdleConns closes all idle connections and reports whether the
// server is quiescent.
func (s *Server) closeIdleConns() bool {
s.mu.Lock()
defer s.mu.Unlock()
quiescent := true
for c := range s.activeConn {
st, ok := c.curState.Load().(ConnState)
if !ok || st != StateIdle {
quiescent = false
continue
}
c.rwc.Close()
delete(s.activeConn, c)
}
return quiescent
}
func (s *Server) closeListenersLocked() error {
var err error
for ln := range s.listeners {
if cerr := ln.Close(); cerr != nil && err == nil {
err = cerr
}
delete(s.listeners, ln)
}
return err
}
// A ConnState represents the state of a client connection to a server.
// It's used by the optional Server.ConnState hook.
type ConnState int
const (
// StateNew represents a new connection that is expected to
// send a request immediately. Connections begin at this
// state and then transition to either StateActive or
// StateClosed.
StateNew ConnState = iota
// StateActive represents a connection that has read 1 or more
// bytes of a request. The Server.ConnState hook for
// StateActive fires before the request has entered a handler
// and doesn't fire again until the request has been
// handled. After the request is handled, the state
// transitions to StateClosed, StateHijacked, or StateIdle.
// For HTTP/2, StateActive fires on the transition from zero
// to one active request, and only transitions away once all
// active requests are complete. That means that ConnState
// cannot be used to do per-request work; ConnState only notes
// the overall state of the connection.
StateActive
// StateIdle represents a connection that has finished
// handling a request and is in the keep-alive state, waiting
// for a new request. Connections transition from StateIdle
// to either StateActive or StateClosed.
StateIdle
// StateHijacked represents a hijacked connection.
// This is a terminal state. It does not transition to StateClosed.
StateHijacked
// StateClosed represents a closed connection.
// This is a terminal state. Hijacked connections do not
// transition to StateClosed.
StateClosed
)
var stateName = map[ConnState]string{
StateNew: "new",
StateActive: "active",
StateIdle: "idle",
StateHijacked: "hijacked",
StateClosed: "closed",
}
func (c ConnState) String() string {
return stateName[c]
}
// serverHandler delegates to either the server's Handler or
// DefaultServeMux and also handles "OPTIONS *" requests.
type serverHandler struct {
srv *Server
}
func (sh serverHandler) ServeHTTP(rw ResponseWriter, req *Request) {
handler := sh.srv.Handler
if handler == nil {
handler = DefaultServeMux
}
if req.RequestURI == "*" && req.Method == "OPTIONS" {
handler = globalOptionsHandler{}
}
handler.ServeHTTP(rw, req)
}
// ListenAndServe listens on the TCP network address srv.Addr and then
// calls Serve to handle requests on incoming connections.
// Accepted connections are configured to enable TCP keep-alives.
// If srv.Addr is blank, ":http" is used.
// ListenAndServe always returns a non-nil error.
func (srv *Server) ListenAndServe() error {
addr := srv.Addr
if addr == "" {
addr = ":http"
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
return srv.Serve(tcpKeepAliveListener{ln.(*net.TCPListener)})
}
var testHookServerServe func(*Server, net.Listener) // used if non-nil
// shouldDoServeHTTP2 reports whether Server.Serve should configure
// automatic HTTP/2. (which sets up the srv.TLSNextProto map)
func (srv *Server) shouldConfigureHTTP2ForServe() bool {
if srv.TLSConfig == nil {
// Compatibility with Go 1.6:
// If there's no TLSConfig, it's possible that the user just
// didn't set it on the http.Server, but did pass it to
// tls.NewListener and passed that listener to Serve.
// So we should configure HTTP/2 (to set up srv.TLSNextProto)
// in case the listener returns an "h2" *tls.Conn.
return true
}
// The user specified a TLSConfig on their http.Server.
// In this, case, only configure HTTP/2 if their tls.Config
// explicitly mentions "h2". Otherwise http2.ConfigureServer
// would modify the tls.Config to add it, but they probably already
// passed this tls.Config to tls.NewListener. And if they did,
// it's too late anyway to fix it. It would only be potentially racy.
// See Issue 15908.
return strSliceContains(srv.TLSConfig.NextProtos, http2NextProtoTLS)
}
// ErrServerClosed is returned by the Server's Serve, ListenAndServe,
// and ListenAndServeTLS methods after a call to Shutdown or Close.
var ErrServerClosed = errors.New("http: Server closed")
// Serve accepts incoming connections on the Listener l, creating a
// new service goroutine for each. The service goroutines read requests and
// then call srv.Handler to reply to them.
//
// For HTTP/2 support, srv.TLSConfig should be initialized to the
// provided listener's TLS Config before calling Serve. If
// srv.TLSConfig is non-nil and doesn't include the string "h2" in
// Config.NextProtos, HTTP/2 support is not enabled.
//
// Serve always returns a non-nil error. After Shutdown or Close, the
// returned error is ErrServerClosed.
func (srv *Server) Serve(l net.Listener) error {
defer l.Close()
if fn := testHookServerServe; fn != nil {
fn(srv, l)
}
var tempDelay time.Duration // how long to sleep on accept failure
if err := srv.setupHTTP2_Serve(); err != nil {
return err
}
srv.trackListener(l, true)
defer srv.trackListener(l, false)
baseCtx := context.Background() // base is always background, per Issue 16220
ctx := context.WithValue(baseCtx, ServerContextKey, srv)
ctx = context.WithValue(ctx, LocalAddrContextKey, l.Addr())
for {
rw, e := l.Accept()
if e != nil {
select {
case <-srv.getDoneChan():
return ErrServerClosed
default:
}
if ne, ok := e.(net.Error); ok && ne.Temporary() {
if tempDelay == 0 {
tempDelay = 5 * time.Millisecond
} else {
tempDelay *= 2
}
if max := 1 * time.Second; tempDelay > max {
tempDelay = max
}
srv.logf("http: Accept error: %v; retrying in %v", e, tempDelay)
time.Sleep(tempDelay)
continue
}
return e
}
tempDelay = 0
c := srv.newConn(rw)
c.setState(c.rwc, StateNew) // before Serve can return
go c.serve(ctx)
}
}
func (s *Server) trackListener(ln net.Listener, add bool) {
s.mu.Lock()
defer s.mu.Unlock()
if s.listeners == nil {
s.listeners = make(map[net.Listener]struct{})
}
if add {
// If the *Server is being reused after a previous
// Close or Shutdown, reset its doneChan:
if len(s.listeners) == 0 && len(s.activeConn) == 0 {
s.doneChan = nil
}
s.listeners[ln] = struct{}{}
} else {
delete(s.listeners, ln)
}
}
func (s *Server) trackConn(c *conn, add bool) {
s.mu.Lock()
defer s.mu.Unlock()
if s.activeConn == nil {
s.activeConn = make(map[*conn]struct{})
}
if add {
s.activeConn[c] = struct{}{}
} else {
delete(s.activeConn, c)
}
}
func (s *Server) idleTimeout() time.Duration {
if s.IdleTimeout != 0 {
return s.IdleTimeout
}
return s.ReadTimeout
}
func (s *Server) readHeaderTimeout() time.Duration {
if s.ReadHeaderTimeout != 0 {
return s.ReadHeaderTimeout
}
return s.ReadTimeout
}
func (s *Server) doKeepAlives() bool {
return atomic.LoadInt32(&s.disableKeepAlives) == 0 && !s.shuttingDown()
}
func (s *Server) shuttingDown() bool {
return atomic.LoadInt32(&s.inShutdown) != 0
}
// SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled.
// By default, keep-alives are always enabled. Only very
// resource-constrained environments or servers in the process of
// shutting down should disable them.
func (srv *Server) SetKeepAlivesEnabled(v bool) {
if v {
atomic.StoreInt32(&srv.disableKeepAlives, 0)
return
}
atomic.StoreInt32(&srv.disableKeepAlives, 1)
// Close idle HTTP/1 conns:
srv.closeIdleConns()
// Close HTTP/2 conns, as soon as they become idle, but reset
// the chan so future conns (if the listener is still active)
// still work and don't get a GOAWAY immediately, before their
// first request:
srv.mu.Lock()
defer srv.mu.Unlock()
srv.closeDoneChanLocked() // closes http2 conns
srv.doneChan = nil
}
func (s *Server) logf(format string, args ...interface{}) {
if s.ErrorLog != nil {
s.ErrorLog.Printf(format, args...)
} else {
log.Printf(format, args...)
}
}
// ListenAndServe listens on the TCP network address addr
// and then calls Serve with handler to handle requests
// on incoming connections.
// Accepted connections are configured to enable TCP keep-alives.
// Handler is typically nil, in which case the DefaultServeMux is
// used.
//
// A trivial example server is:
//
// package main
//
// import (
// "io"
// "net/http"
// "log"
// )
//
// // hello world, the web server
// func HelloServer(w http.ResponseWriter, req *http.Request) {
// io.WriteString(w, "hello, world!\n")
// }
//
// func main() {
// http.HandleFunc("/hello", HelloServer)
// log.Fatal(http.ListenAndServe(":12345", nil))
// }
//
// ListenAndServe always returns a non-nil error.
func ListenAndServe(addr string, handler Handler) error {
server := &Server{Addr: addr, Handler: handler}
return server.ListenAndServe()
}
// ListenAndServeTLS acts identically to ListenAndServe, except that it
// expects HTTPS connections. Additionally, files containing a certificate and
// matching private key for the server must be provided. If the certificate
// is signed by a certificate authority, the certFile should be the concatenation
// of the server's certificate, any intermediates, and the CA's certificate.
//
// A trivial example server is:
//
// import (
// "log"
// "net/http"
// )
//
// func handler(w http.ResponseWriter, req *http.Request) {
// w.Header().Set("Content-Type", "text/plain")
// w.Write([]byte("This is an example server.\n"))
// }
//
// func main() {
// http.HandleFunc("/", handler)
// log.Printf("About to listen on 10443. Go to https://127.0.0.1:10443/")
// err := http.ListenAndServeTLS(":10443", "cert.pem", "key.pem", nil)
// log.Fatal(err)
// }
//
// One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem.
//
// ListenAndServeTLS always returns a non-nil error.
func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error {
server := &Server{Addr: addr, Handler: handler}
return server.ListenAndServeTLS(certFile, keyFile)
}
// ListenAndServeTLS listens on the TCP network address srv.Addr and
// then calls Serve to handle requests on incoming TLS connections.
// Accepted connections are configured to enable TCP keep-alives.
//
// Filenames containing a certificate and matching private key for the
// server must be provided if neither the Server's TLSConfig.Certificates
// nor TLSConfig.GetCertificate are populated. If the certificate is
// signed by a certificate authority, the certFile should be the
// concatenation of the server's certificate, any intermediates, and
// the CA's certificate.
//
// If srv.Addr is blank, ":https" is used.
//
// ListenAndServeTLS always returns a non-nil error.
func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error {
addr := srv.Addr
if addr == "" {
addr = ":https"
}
// Setup HTTP/2 before srv.Serve, to initialize srv.TLSConfig
// before we clone it and create the TLS Listener.
if err := srv.setupHTTP2_ListenAndServeTLS(); err != nil {
return err
}
config := cloneTLSConfig(srv.TLSConfig)
if !strSliceContains(config.NextProtos, "http/1.1") {
config.NextProtos = append(config.NextProtos, "http/1.1")
}
configHasCert := len(config.Certificates) > 0 || config.GetCertificate != nil
if !configHasCert || certFile != "" || keyFile != "" {
var err error
config.Certificates = make([]tls.Certificate, 1)
config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return err
}
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
tlsListener := tls.NewListener(tcpKeepAliveListener{ln.(*net.TCPListener)}, config)
return srv.Serve(tlsListener)
}
// setupHTTP2_ListenAndServeTLS conditionally configures HTTP/2 on
// srv and returns whether there was an error setting it up. If it is
// not configured for policy reasons, nil is returned.
func (srv *Server) setupHTTP2_ListenAndServeTLS() error {
srv.nextProtoOnce.Do(srv.onceSetNextProtoDefaults)
return srv.nextProtoErr
}
// setupHTTP2_Serve is called from (*Server).Serve and conditionally
// configures HTTP/2 on srv using a more conservative policy than
// setupHTTP2_ListenAndServeTLS because Serve may be called
// concurrently.
//
// The tests named TestTransportAutomaticHTTP2* and
// TestConcurrentServerServe in server_test.go demonstrate some
// of the supported use cases and motivations.
func (srv *Server) setupHTTP2_Serve() error {
srv.nextProtoOnce.Do(srv.onceSetNextProtoDefaults_Serve)
return srv.nextProtoErr
}
func (srv *Server) onceSetNextProtoDefaults_Serve() {
if srv.shouldConfigureHTTP2ForServe() {
srv.onceSetNextProtoDefaults()
}
}
// onceSetNextProtoDefaults configures HTTP/2, if the user hasn't
// configured otherwise. (by setting srv.TLSNextProto non-nil)
// It must only be called via srv.nextProtoOnce (use srv.setupHTTP2_*).
func (srv *Server) onceSetNextProtoDefaults() {
if strings.Contains(os.Getenv("GODEBUG"), "http2server=0") {
return
}
// Enable HTTP/2 by default if the user hasn't otherwise
// configured their TLSNextProto map.
if srv.TLSNextProto == nil {
srv.nextProtoErr = http2ConfigureServer(srv, nil)
}
}
// TimeoutHandler returns a Handler that runs h with the given time limit.
//
// The new Handler calls h.ServeHTTP to handle each request, but if a
// call runs for longer than its time limit, the handler responds with
// a 503 Service Unavailable error and the given message in its body.
// (If msg is empty, a suitable default message will be sent.)
// After such a timeout, writes by h to its ResponseWriter will return
// ErrHandlerTimeout.
//
// TimeoutHandler buffers all Handler writes to memory and does not
// support the Hijacker or Flusher interfaces.
func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler {
return &timeoutHandler{
handler: h,
body: msg,
dt: dt,
}
}
// ErrHandlerTimeout is returned on ResponseWriter Write calls
// in handlers which have timed out.
var ErrHandlerTimeout = errors.New("http: Handler timeout")
type timeoutHandler struct {
handler Handler
body string
dt time.Duration
// When set, no timer will be created and this channel will
// be used instead.
testTimeout <-chan time.Time
}
func (h *timeoutHandler) errorBody() string {
if h.body != "" {
return h.body
}
return "<html><head><title>Timeout</title></head><body><h1>Timeout</h1></body></html>"
}
func (h *timeoutHandler) ServeHTTP(w ResponseWriter, r *Request) {
var t *time.Timer
timeout := h.testTimeout
if timeout == nil {
t = time.NewTimer(h.dt)
timeout = t.C
}
done := make(chan struct{})
tw := &timeoutWriter{
w: w,
h: make(Header),
}
go func() {
h.handler.ServeHTTP(tw, r)
close(done)
}()
select {
case <-done:
tw.mu.Lock()
defer tw.mu.Unlock()
dst := w.Header()
for k, vv := range tw.h {
dst[k] = vv
}
if !tw.wroteHeader {
tw.code = StatusOK
}
w.WriteHeader(tw.code)
w.Write(tw.wbuf.Bytes())
if t != nil {
t.Stop()
}
case <-timeout:
tw.mu.Lock()
defer tw.mu.Unlock()
w.WriteHeader(StatusServiceUnavailable)
io.WriteString(w, h.errorBody())
tw.timedOut = true
return
}
}
type timeoutWriter struct {
w ResponseWriter
h Header
wbuf bytes.Buffer
mu sync.Mutex
timedOut bool
wroteHeader bool
code int
}
func (tw *timeoutWriter) Header() Header { return tw.h }
func (tw *timeoutWriter) Write(p []byte) (int, error) {
tw.mu.Lock()
defer tw.mu.Unlock()
if tw.timedOut {
return 0, ErrHandlerTimeout
}
if !tw.wroteHeader {
tw.writeHeader(StatusOK)
}
return tw.wbuf.Write(p)
}
func (tw *timeoutWriter) WriteHeader(code int) {
tw.mu.Lock()
defer tw.mu.Unlock()
if tw.timedOut || tw.wroteHeader {
return
}
tw.writeHeader(code)
}
func (tw *timeoutWriter) writeHeader(code int) {
tw.wroteHeader = true
tw.code = code
}
// tcpKeepAliveListener sets TCP keep-alive timeouts on accepted
// connections. It's used by ListenAndServe and ListenAndServeTLS so
// dead TCP connections (e.g. closing laptop mid-download) eventually
// go away.
type tcpKeepAliveListener struct {
*net.TCPListener
}
func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) {
tc, err := ln.AcceptTCP()
if err != nil {
return
}
tc.SetKeepAlive(true)
tc.SetKeepAlivePeriod(3 * time.Minute)
return tc, nil
}
// globalOptionsHandler responds to "OPTIONS *" requests.
type globalOptionsHandler struct{}
func (globalOptionsHandler) ServeHTTP(w ResponseWriter, r *Request) {
w.Header().Set("Content-Length", "0")
if r.ContentLength != 0 {
// Read up to 4KB of OPTIONS body (as mentioned in the
// spec as being reserved for future use), but anything
// over that is considered a waste of server resources
// (or an attack) and we abort and close the connection,
// courtesy of MaxBytesReader's EOF behavior.
mb := MaxBytesReader(w, r.Body, 4<<10)
io.Copy(ioutil.Discard, mb)
}
}
// initNPNRequest is an HTTP handler that initializes certain
// uninitialized fields in its *Request. Such partially-initialized
// Requests come from NPN protocol handlers.
type initNPNRequest struct {
c *tls.Conn
h serverHandler
}
func (h initNPNRequest) ServeHTTP(rw ResponseWriter, req *Request) {
if req.TLS == nil {
req.TLS = &tls.ConnectionState{}
*req.TLS = h.c.ConnectionState()
}
if req.Body == nil {
req.Body = NoBody
}
if req.RemoteAddr == "" {
req.RemoteAddr = h.c.RemoteAddr().String()
}
h.h.ServeHTTP(rw, req)
}
// loggingConn is used for debugging.
type loggingConn struct {
name string
net.Conn
}
var (
uniqNameMu sync.Mutex
uniqNameNext = make(map[string]int)
)
func newLoggingConn(baseName string, c net.Conn) net.Conn {
uniqNameMu.Lock()
defer uniqNameMu.Unlock()
uniqNameNext[baseName]++
return &loggingConn{
name: fmt.Sprintf("%s-%d", baseName, uniqNameNext[baseName]),
Conn: c,
}
}
func (c *loggingConn) Write(p []byte) (n int, err error) {
log.Printf("%s.Write(%d) = ....", c.name, len(p))
n, err = c.Conn.Write(p)
log.Printf("%s.Write(%d) = %d, %v", c.name, len(p), n, err)
return
}
func (c *loggingConn) Read(p []byte) (n int, err error) {
log.Printf("%s.Read(%d) = ....", c.name, len(p))
n, err = c.Conn.Read(p)
log.Printf("%s.Read(%d) = %d, %v", c.name, len(p), n, err)
return
}
func (c *loggingConn) Close() (err error) {
log.Printf("%s.Close() = ...", c.name)
err = c.Conn.Close()
log.Printf("%s.Close() = %v", c.name, err)
return
}
// checkConnErrorWriter writes to c.rwc and records any write errors to c.werr.
// It only contains one field (and a pointer field at that), so it
// fits in an interface value without an extra allocation.
type checkConnErrorWriter struct {
c *conn
}
func (w checkConnErrorWriter) Write(p []byte) (n int, err error) {
n, err = w.c.rwc.Write(p)
if err != nil && w.c.werr == nil {
w.c.werr = err
w.c.cancelCtx()
}
return
}
func numLeadingCRorLF(v []byte) (n int) {
for _, b := range v {
if b == '\r' || b == '\n' {
n++
continue
}
break
}
return
}
func strSliceContains(ss []string, s string) bool {
for _, v := range ss {
if v == s {
return true
}
}
return false
}<|fim▁end|> | mon := months[3*(mm-1):]
return append(b, |
<|file_name|>touch-events.js<|end_file_name|><|fim▁begin|>// Copyright (c) Microsoft Corporation. All rights reserved.
// Based in part on code from Apache Ripple, https://github.com/apache/incubator-ripple<|fim▁hole|> _isMouseDown;
// NOTE: missing view, detail, touches, targetTouches, scale and rotation
function _createTouchEvent(type, canBubble, cancelable, eventData) {
var touchEvent = window.document.createEvent('Event');
touchEvent.initEvent(type, canBubble, cancelable);
utils.mixin(eventData, touchEvent);
return touchEvent;
}
function _simulateTouchEvent(type, mouseevent) {
if (_lastMouseEvent &&
mouseevent.type === _lastMouseEvent.type &&
mouseevent.pageX === _lastMouseEvent.pageX &&
mouseevent.pageY === _lastMouseEvent.pageY) {
return;
}
_lastMouseEvent = mouseevent;
var touchObj = {
clientX: mouseevent.pageX,
clientY: mouseevent.pageY,
pageX: mouseevent.pageX,
pageY: mouseevent.pageY,
screenX: mouseevent.pageX,
screenY: mouseevent.pageY,
target: mouseevent.target,
identifier: ''
};
var eventData = {
altKey: mouseevent.altKey,
ctrlKey: mouseevent.ctrlKey,
shiftKey: mouseevent.shiftKey,
metaKey: mouseevent.metaKey,
changedTouches: [touchObj],
targetTouches: type === 'touchend' ? [] : [touchObj],
touches: type === 'touchend' ? [] : [touchObj]
};
utils.mixin(touchObj, eventData);
var itemFn = function (index) {
return this[index];
};
eventData.touches.item = itemFn;
eventData.changedTouches.item = itemFn;
eventData.targetTouches.item = itemFn;
var listenerName = 'on' + type,
simulatedEvent = _createTouchEvent(type, true, true, eventData);
mouseevent.target.dispatchEvent(simulatedEvent);
if (typeof mouseevent.target[listenerName] === 'function') {
mouseevent.target[listenerName].apply(mouseevent.target, [simulatedEvent]);
}
}
function init() {
window.document.addEventListener('mousedown', function (event) {
_isMouseDown = true;
_simulateTouchEvent('touchstart', event);
}, true);
window.document.addEventListener('mousemove', function (event) {
if (_isMouseDown) {
_simulateTouchEvent('touchmove', event);
}
}, true);
window.document.addEventListener('mouseup', function (event) {
_isMouseDown = false;
_simulateTouchEvent('touchend', event);
}, true);
window.Node.prototype.ontouchstart = null;
window.Node.prototype.ontouchend = null;
window.Node.prototype.ontouchmove = null;
}
module.exports.init = init;<|fim▁end|> |
var utils = require('utils');
var _lastMouseEvent, |
<|file_name|>filter.py<|end_file_name|><|fim▁begin|>##
# Copyright (c) 2009-2017 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##
from twistedcaldav.ical import Component as iComponent
from twistedcaldav.vcard import Component as vComponent
__all__ = [
"CalendarFilter",
"AddressFilter",
]
class CalendarFilter(object):
"""
Abstract class that defines an iCalendar filter/merge object
"""
def __init__(self):
pass
def filter(self, ical):
"""
Filter the supplied iCalendar object using the request information.
@param ical: iCalendar object
@type ical: L{Component}
@return: L{Component} for the filtered calendar data
"""
raise NotImplementedError
def merge(self, icalnew, icalold):
"""
Merge the old iCalendar object into the new iCalendar data using the request information.
@param icalnew: new iCalendar object to merge data into
@type icalnew: L{Component}
@param icalold: old iCalendar data to merge data from
@type icalold: L{Component}
"""
raise NotImplementedError
def validCalendar(self, ical):
# If we were passed a string, parse it out as a Component
if isinstance(ical, str):
try:
ical = iComponent.fromString(ical)
except ValueError:
raise ValueError("Not a calendar: %r" % (ical,))<|fim▁hole|>
if ical is None or ical.name() != "VCALENDAR":
raise ValueError("Not a calendar: %r" % (ical,))
return ical
class AddressFilter(object):
"""
Abstract class that defines a vCard filter/merge object
"""
def __init__(self):
pass
def filter(self, vcard):
"""
Filter the supplied vCard object using the request information.
@param vcard: iCalendar object
@type vcard: L{Component}
@return: L{Component} for the filtered vcard data
"""
raise NotImplementedError
def merge(self, vcardnew, vcardold):
"""
Merge the old vcard object into the new vcard data using the request information.
@param vcardnew: new vcard object to merge data into
@type vcardnew: L{Component}
@param vcardold: old vcard data to merge data from
@type vcardold: L{Component}
"""
raise NotImplementedError
def validAddress(self, vcard):
# If we were passed a string, parse it out as a Component
if isinstance(vcard, str):
try:
vcard = vComponent.fromString(vcard)
except ValueError:
raise ValueError("Not a vcard: %r" % (vcard,))
if vcard is None or vcard.name() != "VCARD":
raise ValueError("Not a vcard: %r" % (vcard,))
return vcard<|fim▁end|> | |
<|file_name|>webglprogram.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use canvas_traits::CanvasMsg;
use dom::bindings::codegen::Bindings::WebGLProgramBinding;
use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLRenderingContextConstants as constants;
use dom::bindings::js::{JS, MutNullableHeap, Root};
use dom::bindings::reflector::{Reflectable, reflect_dom_object};
use dom::bindings::str::DOMString;
use dom::globalscope::GlobalScope;
use dom::webglactiveinfo::WebGLActiveInfo;
use dom::webglobject::WebGLObject;
use dom::webglrenderingcontext::MAX_UNIFORM_AND_ATTRIBUTE_LEN;
use dom::webglshader::WebGLShader;
use ipc_channel::ipc::{self, IpcSender};
use std::cell::Cell;
use webrender_traits::{WebGLCommand, WebGLError, WebGLParameter};
use webrender_traits::{WebGLProgramId, WebGLResult};
#[dom_struct]
pub struct WebGLProgram {
webgl_object: WebGLObject,
id: WebGLProgramId,
is_deleted: Cell<bool>,
link_called: Cell<bool>,
linked: Cell<bool>,
fragment_shader: MutNullableHeap<JS<WebGLShader>>,
vertex_shader: MutNullableHeap<JS<WebGLShader>>,
#[ignore_heap_size_of = "Defined in ipc-channel"]
renderer: IpcSender<CanvasMsg>,
}
impl WebGLProgram {
fn new_inherited(renderer: IpcSender<CanvasMsg>,
id: WebGLProgramId)
-> WebGLProgram {
WebGLProgram {
webgl_object: WebGLObject::new_inherited(),
id: id,
is_deleted: Cell::new(false),
link_called: Cell::new(false),
linked: Cell::new(false),
fragment_shader: Default::default(),
vertex_shader: Default::default(),
renderer: renderer,
}
}
pub fn maybe_new(global: &GlobalScope, renderer: IpcSender<CanvasMsg>)
-> Option<Root<WebGLProgram>> {
let (sender, receiver) = ipc::channel().unwrap();
renderer.send(CanvasMsg::WebGL(WebGLCommand::CreateProgram(sender))).unwrap();
let result = receiver.recv().unwrap();
result.map(|program_id| WebGLProgram::new(global, renderer, program_id))
}
pub fn new(global: &GlobalScope,
renderer: IpcSender<CanvasMsg>,
id: WebGLProgramId)
-> Root<WebGLProgram> {
reflect_dom_object(box WebGLProgram::new_inherited(renderer, id),
global,
WebGLProgramBinding::Wrap)
}
}
impl WebGLProgram {
pub fn id(&self) -> WebGLProgramId {
self.id
}
/// glDeleteProgram
pub fn delete(&self) {
if !self.is_deleted.get() {
self.is_deleted.set(true);
let _ = self.renderer.send(CanvasMsg::WebGL(WebGLCommand::DeleteProgram(self.id)));
if let Some(shader) = self.fragment_shader.get() {
shader.decrement_attached_counter();
}
if let Some(shader) = self.vertex_shader.get() {
shader.decrement_attached_counter();
}
}
}
pub fn is_deleted(&self) -> bool {
self.is_deleted.get()
}
pub fn is_linked(&self) -> bool {
self.linked.get()
}
/// glLinkProgram
pub fn link(&self) -> WebGLResult<()> {
if self.is_deleted() {
return Err(WebGLError::InvalidOperation);
}
self.linked.set(false);
self.link_called.set(true);
match self.fragment_shader.get() {
Some(ref shader) if shader.successfully_compiled() => {},
_ => return Ok(()), // callers use gl.LINK_STATUS to check link errors
}
match self.vertex_shader.get() {
Some(ref shader) if shader.successfully_compiled() => {},
_ => return Ok(()), // callers use gl.LINK_STATUS to check link errors
}
self.linked.set(true);
self.renderer.send(CanvasMsg::WebGL(WebGLCommand::LinkProgram(self.id))).unwrap();
Ok(())
}
/// glUseProgram
pub fn use_program(&self) -> WebGLResult<()> {
if self.is_deleted() {
return Err(WebGLError::InvalidOperation);
}
if !self.linked.get() {
return Err(WebGLError::InvalidOperation);
}
self.renderer.send(CanvasMsg::WebGL(WebGLCommand::UseProgram(self.id))).unwrap();
Ok(())
}
/// glValidateProgram
pub fn validate(&self) -> WebGLResult<()> {
if self.is_deleted() {
return Err(WebGLError::InvalidOperation);
}
self.renderer.send(CanvasMsg::WebGL(WebGLCommand::ValidateProgram(self.id))).unwrap();
Ok(())
}
/// glAttachShader
pub fn attach_shader(&self, shader: &WebGLShader) -> WebGLResult<()> {
if self.is_deleted() || shader.is_deleted() {
return Err(WebGLError::InvalidOperation);
}
let shader_slot = match shader.gl_type() {
constants::FRAGMENT_SHADER => &self.fragment_shader,
constants::VERTEX_SHADER => &self.vertex_shader,
_ => {
error!("detachShader: Unexpected shader type");
return Err(WebGLError::InvalidValue);
}
};
// TODO(emilio): Differentiate between same shader already assigned and other previous
// shader.
if shader_slot.get().is_some() {
return Err(WebGLError::InvalidOperation);
}
shader_slot.set(Some(shader));
shader.increment_attached_counter();
self.renderer.send(CanvasMsg::WebGL(WebGLCommand::AttachShader(self.id, shader.id()))).unwrap();<|fim▁hole|>
/// glDetachShader
pub fn detach_shader(&self, shader: &WebGLShader) -> WebGLResult<()> {
if self.is_deleted() {
return Err(WebGLError::InvalidOperation);
}
let shader_slot = match shader.gl_type() {
constants::FRAGMENT_SHADER => &self.fragment_shader,
constants::VERTEX_SHADER => &self.vertex_shader,
_ => {
error!("detachShader: Unexpected shader type");
return Err(WebGLError::InvalidValue);
}
};
match shader_slot.get() {
Some(ref attached_shader) if attached_shader.id() != shader.id() =>
return Err(WebGLError::InvalidOperation),
None =>
return Err(WebGLError::InvalidOperation),
_ => {}
}
shader_slot.set(None);
shader.decrement_attached_counter();
self.renderer.send(CanvasMsg::WebGL(WebGLCommand::DetachShader(self.id, shader.id()))).unwrap();
Ok(())
}
/// glBindAttribLocation
pub fn bind_attrib_location(&self, index: u32, name: DOMString) -> WebGLResult<()> {
if self.is_deleted() {
return Err(WebGLError::InvalidOperation);
}
if name.len() > MAX_UNIFORM_AND_ATTRIBUTE_LEN {
return Err(WebGLError::InvalidValue);
}
// Check if the name is reserved
if name.starts_with("gl_") || name.starts_with("webgl") || name.starts_with("_webgl_") {
return Err(WebGLError::InvalidOperation);
}
self.renderer
.send(CanvasMsg::WebGL(WebGLCommand::BindAttribLocation(self.id, index, String::from(name))))
.unwrap();
Ok(())
}
pub fn get_active_uniform(&self, index: u32) -> WebGLResult<Root<WebGLActiveInfo>> {
if self.is_deleted() {
return Err(WebGLError::InvalidValue);
}
let (sender, receiver) = ipc::channel().unwrap();
self.renderer
.send(CanvasMsg::WebGL(WebGLCommand::GetActiveUniform(self.id, index, sender)))
.unwrap();
receiver.recv().unwrap().map(|(size, ty, name)|
WebGLActiveInfo::new(&self.global(), size, ty, DOMString::from(name)))
}
/// glGetActiveAttrib
pub fn get_active_attrib(&self, index: u32) -> WebGLResult<Root<WebGLActiveInfo>> {
if self.is_deleted() {
return Err(WebGLError::InvalidValue);
}
let (sender, receiver) = ipc::channel().unwrap();
self.renderer
.send(CanvasMsg::WebGL(WebGLCommand::GetActiveAttrib(self.id, index, sender)))
.unwrap();
receiver.recv().unwrap().map(|(size, ty, name)|
WebGLActiveInfo::new(&self.global(), size, ty, DOMString::from(name)))
}
/// glGetAttribLocation
pub fn get_attrib_location(&self, name: DOMString) -> WebGLResult<Option<i32>> {
if !self.is_linked() || self.is_deleted() {
return Err(WebGLError::InvalidOperation);
}
if name.len() > MAX_UNIFORM_AND_ATTRIBUTE_LEN {
return Err(WebGLError::InvalidValue);
}
// Check if the name is reserved
if name.starts_with("gl_") {
return Err(WebGLError::InvalidOperation);
}
if name.starts_with("webgl") || name.starts_with("_webgl_") {
return Ok(None);
}
let (sender, receiver) = ipc::channel().unwrap();
self.renderer
.send(CanvasMsg::WebGL(WebGLCommand::GetAttribLocation(self.id, String::from(name), sender)))
.unwrap();
Ok(receiver.recv().unwrap())
}
/// glGetUniformLocation
pub fn get_uniform_location(&self, name: DOMString) -> WebGLResult<Option<i32>> {
if !self.is_linked() || self.is_deleted() {
return Err(WebGLError::InvalidOperation);
}
if name.len() > MAX_UNIFORM_AND_ATTRIBUTE_LEN {
return Err(WebGLError::InvalidValue);
}
// Check if the name is reserved
if name.starts_with("webgl") || name.starts_with("_webgl_") {
return Ok(None);
}
let (sender, receiver) = ipc::channel().unwrap();
self.renderer
.send(CanvasMsg::WebGL(WebGLCommand::GetUniformLocation(self.id, String::from(name), sender)))
.unwrap();
Ok(receiver.recv().unwrap())
}
/// glGetProgramInfoLog
pub fn get_info_log(&self) -> WebGLResult<String> {
if self.is_deleted() {
return Err(WebGLError::InvalidOperation);
}
if self.link_called.get() {
let shaders_compiled = match (self.fragment_shader.get(), self.vertex_shader.get()) {
(Some(fs), Some(vs)) => fs.successfully_compiled() && vs.successfully_compiled(),
_ => false
};
if !shaders_compiled {
return Ok("One or more shaders failed to compile".to_string());
}
}
let (sender, receiver) = ipc::channel().unwrap();
self.renderer.send(CanvasMsg::WebGL(WebGLCommand::GetProgramInfoLog(self.id, sender))).unwrap();
Ok(receiver.recv().unwrap())
}
/// glGetProgramParameter
pub fn parameter(&self, param_id: u32) -> WebGLResult<WebGLParameter> {
let (sender, receiver) = ipc::channel().unwrap();
self.renderer.send(CanvasMsg::WebGL(WebGLCommand::GetProgramParameter(self.id, param_id, sender))).unwrap();
receiver.recv().unwrap()
}
}
impl Drop for WebGLProgram {
fn drop(&mut self) {
self.delete();
}
}<|fim▁end|> |
Ok(())
} |
<|file_name|>resource_fixtures.py<|end_file_name|><|fim▁begin|># Copyright (C) 2018-2022 Yannick Jadoul
#
# This file is part of Parselmouth.
#
# Parselmouth is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or<|fim▁hole|># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Parselmouth. If not, see <http://www.gnu.org/licenses/>
import pytest
import pytest_lazyfixture
import parselmouth
def combined_fixture(*args, **kwargs):
return pytest.fixture(params=map(pytest_lazyfixture.lazy_fixture, args), ids=args, **kwargs)
@pytest.fixture
def sound_path(resources):
yield resources["the_north_wind_and_the_sun.wav"]
@pytest.fixture
def sound(sound_path):
yield parselmouth.read(sound_path)
@pytest.fixture
def intensity(sound):
yield sound.to_intensity()
@pytest.fixture
def pitch(sound):
yield sound.to_pitch()
@pytest.fixture
def spectrogram(sound):
yield sound.to_spectrogram()
@combined_fixture('intensity', 'pitch', 'spectrogram', 'sound')
def sampled(request):
yield request.param
@combined_fixture('sampled')
def thing(request):
yield request.param
@pytest.fixture
def text_grid_path(resources):
yield resources["the_north_wind_and_the_sun.TextGrid"]
@pytest.fixture
def text_grid(text_grid_path):
yield parselmouth.read(text_grid_path)
@pytest.fixture
def script_path(resources):
yield resources["script.praat"]<|fim▁end|> | # (at your option) any later version.
#
# Parselmouth is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
<|file_name|>ErrorLogService.java<|end_file_name|><|fim▁begin|>package org.superboot.service;
import com.querydsl.core.types.Predicate;
import org.springframework.data.domain.Pageable;
import org.superboot.base.BaseException;
import org.superboot.base.BaseResponse;
/**
* <b> 错误日志服务接口 </b>
* <p>
* 功能描述:
* </p>
*/
public interface ErrorLogService {
/**
* 按照微服务模块进行分组统计
*
* @return
* @throws BaseException
*/
BaseResponse getErrorLogGroupByAppName() throws BaseException;<|fim▁hole|> * 获取错误日志列表信息
*
* @param pageable 分页信息
* @param predicate 查询参数
* @return
* @throws BaseException
*/
BaseResponse getErrorLogList(Pageable pageable, Predicate predicate) throws BaseException;
/**
* 获取错误日志记录数
*
* @return
* @throws BaseException
*/
BaseResponse getErrorLogCount(Predicate predicate) throws BaseException;
/**
* 查询错误日志详细信息
*
* @param id
* @return
* @throws BaseException
*/
BaseResponse getErrorLogItem(String id) throws BaseException;
}<|fim▁end|> |
/** |
<|file_name|>csv2geojson.js<|end_file_name|><|fim▁begin|>/* */
"format cjs";
(function(e){if("function"==typeof bootstrap)bootstrap("csv2geojson",e);else if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else if("undefined"!=typeof ses){if(!ses.ok())return;ses.makeCsv2geojson=e}else"undefined"!=typeof window?window.csv2geojson=e():global.csv2geojson=e()})(function(){var define,ses,bootstrap,module,exports;
return (function(e,t,n){function r(n,i){if(!t[n]){if(!e[n]){var s=typeof require=="function"&&require;if(!i&&s)return s(n,!0);throw new Error("Cannot find module '"+n+"'")}var o=t[n]={exports:{}};e[n][0](function(t){var i=e[n][1][t];return r(i?i:t)},o,o.exports)}return t[n].exports}for(var i=0;i<n.length;i++)r(n[i]);return r})({1:[function(require,module,exports){
function csv(text) {
var header;
return csv_parseRows(text, function(row, i) {
if (i) {
var o = {}, j = -1, m = header.length;
while (++j < m) o[header[j]] = row[j];
return o;
} else {
header = row;
return null;
}
});
function csv_parseRows (text, f) {
var EOL = {}, // sentinel value for end-of-line
EOF = {}, // sentinel value for end-of-file
rows = [], // output rows
re = /\r\n|[,\r\n]/g, // field separator regex
n = 0, // the current line number
t, // the current token
eol; // is the current token followed by EOL?
re.lastIndex = 0; // work-around bug in FF 3.6
/** @private Returns the next token. */
function token() {
if (re.lastIndex >= text.length) return EOF; // special case: end of file
if (eol) { eol = false; return EOL; } // special case: end of line
// special case: quotes
var j = re.lastIndex;
if (text.charCodeAt(j) === 34) {
var i = j;
while (i++ < text.length) {
if (text.charCodeAt(i) === 34) {
if (text.charCodeAt(i + 1) !== 34) break;
i++;
}
}
re.lastIndex = i + 2;
var c = text.charCodeAt(i + 1);
if (c === 13) {
eol = true;
if (text.charCodeAt(i + 2) === 10) re.lastIndex++;
} else if (c === 10) {
eol = true;
}
return text.substring(j + 1, i).replace(/""/g, "\"");
}
// common case
var m = re.exec(text);
if (m) {
eol = m[0].charCodeAt(0) !== 44;
return text.substring(j, m.index);
}
re.lastIndex = text.length;
return text.substring(j);
}
while ((t = token()) !== EOF) {
var a = [];
while ((t !== EOL) && (t !== EOF)) {
a.push(t);
t = token();
}
if (f && !(a = f(a, n++))) continue;
rows.push(a);
}
return rows;
}
}
function csv2geojson(x, lonfield, latfield) {
var features = [],
featurecollection = {
type: 'FeatureCollection',
features: features
};
var parsed = csv(x);
if (!parsed.length) return featurecollection;
latfield = latfield || '';
lonfield = lonfield || '';
for (var f in parsed[0]) {
if (!latfield && f.match(/^Lat/i)) latfield = f;
if (!lonfield && f.match(/^Lon/i)) lonfield = f;
}
if (!latfield || !lonfield) {
var fields = [];
for (var k in parsed[0]) fields.push(k);
return fields;
}
for (var i = 0; i < parsed.length; i++) {
if (parsed[i][lonfield] !== undefined &&
parsed[i][lonfield] !== undefined) {
features.push({
type: 'Feature',
properties: parsed[i],
geometry: {
type: 'Point',
coordinates: [
parseFloat(parsed[i][lonfield]),
parseFloat(parsed[i][latfield])]
}
});
}
}
return featurecollection;
}
function toline(gj) {
var features = gj.features;
var line = {
type: 'Feature',
geometry: {
type: 'LineString',
coordinates: []
}
};
for (var i = 0; i < features.length; i++) {
line.geometry.coordinates.push(features[i].geometry.coordinates);
}
line.properties = features[0].properties;
return {
type: 'FeatureSet',
features: [line]
};
}
function topolygon(gj) {
var features = gj.features;
var poly = {
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates: [[]]
}
};<|fim▁hole|> poly.geometry.coordinates[0].push(features[i].geometry.coordinates);
}
poly.properties = features[0].properties;
return {
type: 'FeatureSet',
features: [poly]
};
}
module.exports = {
csv: csv,
toline: toline,
topolygon: topolygon,
csv2geojson: csv2geojson
};
},{}]},{},[1])(1)
});
;<|fim▁end|> | for (var i = 0; i < features.length; i++) { |
<|file_name|>issue-28871.rs<|end_file_name|><|fim▁begin|>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
<|fim▁hole|>// Regression test for #28871. The problem is that rustc encountered
// two ways to project, one from a where clause and one from the where
// clauses on the trait definition. (In fact, in this case, the where
// clauses originated from the trait definition as well.) The true
// cause of the error is that the trait definition where clauses are
// not being normalized, and hence the two sources are considered in
// conflict, and not a duplicate. Hacky solution is to prefer where
// clauses over the data found in the trait definition.
trait T {
type T;
}
struct S;
impl T for S {
type T = S;
}
trait T2 {
type T: Iterator<Item=<S as T>::T>;
}
fn main() { }<|fim▁end|> | // compile-pass |
<|file_name|>app.js<|end_file_name|><|fim▁begin|>//APP
var app = angular.module('PortfolioApp', ['ngRoute', 'slick']);
//ROUTING
app.config(function ($routeProvider) {
"ngInject";
$routeProvider
.when('/', {
controller: "HomeController",
templateUrl: "js/angular/views/home-view.html"
})
.when('/work/:projectId', {
controller: 'ProjectController',
templateUrl: 'js/angular/views/project-view.html'
})
.otherwise({
redirectTo: '/'
});
});
//CONTROLLERS
app.controller('HomeController', ['$scope', 'projects', function($scope, projects) {
"ngInject";
projects.success(function(data) {
$scope.projects = data;
});
//init function for binding
function bindListeners() {
$("header").on("click", ".mobile-toggle", function() {
$(this).toggleClass("active");
})
$("header, .about").on("click", ".nav-link", function(e) {
e.preventDefault();
e.stopImmediatePropagation();
if($(window).width() <= 740)
$(".mobile-toggle").removeClass("active");
var anchor = $(this).attr("href");
$('html, body').animate({
scrollTop: $(anchor).offset().top - 70
}, 500);
})
}
//Home page initializations
angular.element(document).ready(function () {
bindListeners();
});<|fim▁hole|>
app.controller('ProjectController', ['$scope', '$routeParams', '$http',
function($scope, $routeParams, $http, $sce) {
"ngInject";
$scope.video = false;
$http.get('projects/' + $routeParams.projectId + '.json').success(function(data) {
$scope.detail = data;
})
.error(function(data) {
console.log("Failed to get data")
});
}
]);
//SERVICES
app.factory('projects', ['$http', function($http) {
"ngInject";
return $http.get('projects/project-list.json')
.success(function(data) {
return data;
})
.error(function(data) {
return data;
console.log("Failed to get data")
});
}]);
//FILTERS
app.filter('safe', function($sce) {
"ngInject";
return function(val) {
return $sce.trustAsHtml(val);
};
});<|fim▁end|> | }]); |
<|file_name|>outbound_protocol.js<|end_file_name|><|fim▁begin|>'use strict';
<|fim▁hole|>var fs = require('fs');
var vm = require('vm');
var config = require('../config');
var path = require('path');
var util_hmailitem = require('./fixtures/util_hmailitem');
var queue_dir = path.resolve(__dirname + '/test-queue/');
var ensureTestQueueDirExists = function(done) {
fs.exists(queue_dir, function (exists) {
if (exists) {
done();
}
else {
fs.mkdir(queue_dir, function (err) {
if (err) {
return done(err);
}
done();
});
}
});
};
var removeTestQueueDir = function (done) {
fs.exists(queue_dir, function (exists) {
if (exists) {
var files = fs.readdirSync(queue_dir);
files.forEach(function(file,index){
var curPath = queue_dir + "/" + file;
if (fs.lstatSync(curPath).isDirectory()) { // recurse
return done(new Error('did not expect an sub folder here ("' + curPath + '")! cancel'));
}
});
files.forEach(function(file,index){
var curPath = queue_dir + "/" + file;
fs.unlinkSync(curPath);
});
done();
}
else {
done();
}
});
};
exports.outbound_protocol_tests = {
setUp : ensureTestQueueDirExists,
tearDown : removeTestQueueDir,
};
vm_harness.add_tests(
path.join(__dirname, '/../outbound.js'),
path.join(__dirname, 'outbound_protocol/'),
exports.outbound_protocol_tests,
{
test_queue_dir: queue_dir,
process: process
}
);<|fim▁end|> | require('../configfile').watch_files = false;
var vm_harness = require('./fixtures/vm_harness'); |
<|file_name|>sandbox_dns_unix.go<|end_file_name|><|fim▁begin|>// +build !windows
package libnetwork
import (
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
log "github.com/Sirupsen/logrus"
"github.com/docker/libnetwork/etchosts"
"github.com/docker/libnetwork/resolvconf"
"github.com/docker/libnetwork/types"
)
const (
defaultPrefix = "/var/lib/docker/network/files"
dirPerm = 0755
filePerm = 0644
)
func (sb *sandbox) startResolver(restore bool) {
sb.resolverOnce.Do(func() {
var err error
sb.resolver = NewResolver(sb)
defer func() {
if err != nil {
sb.resolver = nil
}
}()
// In the case of live restore container is already running with
// right resolv.conf contents created before. Just update the
// external DNS servers from the restored sandbox for embedded
// server to use.
if !restore {
err = sb.rebuildDNS()
if err != nil {
log.Errorf("Updating resolv.conf failed for container %s, %q", sb.ContainerID(), err)
return
}
}
sb.resolver.SetExtServers(sb.extDNS)
sb.osSbox.InvokeFunc(sb.resolver.SetupFunc())
if err = sb.resolver.Start(); err != nil {
log.Errorf("Resolver Setup/Start failed for container %s, %q", sb.ContainerID(), err)
}
})
}
func (sb *sandbox) setupResolutionFiles() error {
if err := sb.buildHostsFile(); err != nil {
return err
}
if err := sb.updateParentHosts(); err != nil {
return err
}
if err := sb.setupDNS(); err != nil {
return err
}
return nil
}
func (sb *sandbox) buildHostsFile() error {
if sb.config.hostsPath == "" {
sb.config.hostsPath = defaultPrefix + "/" + sb.id + "/hosts"
}
dir, _ := filepath.Split(sb.config.hostsPath)<|fim▁hole|>
// This is for the host mode networking
if sb.config.originHostsPath != "" {
if err := copyFile(sb.config.originHostsPath, sb.config.hostsPath); err != nil && !os.IsNotExist(err) {
return types.InternalErrorf("could not copy source hosts file %s to %s: %v", sb.config.originHostsPath, sb.config.hostsPath, err)
}
return nil
}
extraContent := make([]etchosts.Record, 0, len(sb.config.extraHosts))
for _, extraHost := range sb.config.extraHosts {
extraContent = append(extraContent, etchosts.Record{Hosts: extraHost.name, IP: extraHost.IP})
}
return etchosts.Build(sb.config.hostsPath, "", sb.config.hostName, sb.config.domainName, extraContent)
}
func (sb *sandbox) updateHostsFile(ifaceIP string) error {
var mhost string
if ifaceIP == "" {
return nil
}
if sb.config.originHostsPath != "" {
return nil
}
if sb.config.domainName != "" {
mhost = fmt.Sprintf("%s.%s %s", sb.config.hostName, sb.config.domainName,
sb.config.hostName)
} else {
mhost = sb.config.hostName
}
extraContent := []etchosts.Record{{Hosts: mhost, IP: ifaceIP}}
sb.addHostsEntries(extraContent)
return nil
}
func (sb *sandbox) addHostsEntries(recs []etchosts.Record) {
if err := etchosts.Add(sb.config.hostsPath, recs); err != nil {
log.Warnf("Failed adding service host entries to the running container: %v", err)
}
}
func (sb *sandbox) deleteHostsEntries(recs []etchosts.Record) {
if err := etchosts.Delete(sb.config.hostsPath, recs); err != nil {
log.Warnf("Failed deleting service host entries to the running container: %v", err)
}
}
func (sb *sandbox) updateParentHosts() error {
var pSb Sandbox
for _, update := range sb.config.parentUpdates {
sb.controller.WalkSandboxes(SandboxContainerWalker(&pSb, update.cid))
if pSb == nil {
continue
}
if err := etchosts.Update(pSb.(*sandbox).config.hostsPath, update.ip, update.name); err != nil {
return err
}
}
return nil
}
func (sb *sandbox) restorePath() {
if sb.config.resolvConfPath == "" {
sb.config.resolvConfPath = defaultPrefix + "/" + sb.id + "/resolv.conf"
}
sb.config.resolvConfHashFile = sb.config.resolvConfPath + ".hash"
if sb.config.hostsPath == "" {
sb.config.hostsPath = defaultPrefix + "/" + sb.id + "/hosts"
}
}
func (sb *sandbox) setupDNS() error {
var newRC *resolvconf.File
if sb.config.resolvConfPath == "" {
sb.config.resolvConfPath = defaultPrefix + "/" + sb.id + "/resolv.conf"
}
sb.config.resolvConfHashFile = sb.config.resolvConfPath + ".hash"
dir, _ := filepath.Split(sb.config.resolvConfPath)
if err := createBasePath(dir); err != nil {
return err
}
// This is for the host mode networking
if sb.config.originResolvConfPath != "" {
if err := copyFile(sb.config.originResolvConfPath, sb.config.resolvConfPath); err != nil {
return fmt.Errorf("could not copy source resolv.conf file %s to %s: %v", sb.config.originResolvConfPath, sb.config.resolvConfPath, err)
}
return nil
}
currRC, err := resolvconf.Get()
if err != nil {
return err
}
if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 || len(sb.config.dnsOptionsList) > 0 {
var (
err error
dnsList = resolvconf.GetNameservers(currRC.Content, types.IP)
dnsSearchList = resolvconf.GetSearchDomains(currRC.Content)
dnsOptionsList = resolvconf.GetOptions(currRC.Content)
)
if len(sb.config.dnsList) > 0 {
dnsList = sb.config.dnsList
}
if len(sb.config.dnsSearchList) > 0 {
dnsSearchList = sb.config.dnsSearchList
}
if len(sb.config.dnsOptionsList) > 0 {
dnsOptionsList = sb.config.dnsOptionsList
}
newRC, err = resolvconf.Build(sb.config.resolvConfPath, dnsList, dnsSearchList, dnsOptionsList)
if err != nil {
return err
}
} else {
// Replace any localhost/127.* (at this point we have no info about ipv6, pass it as true)
if newRC, err = resolvconf.FilterResolvDNS(currRC.Content, true); err != nil {
return err
}
// No contention on container resolv.conf file at sandbox creation
if err := ioutil.WriteFile(sb.config.resolvConfPath, newRC.Content, filePerm); err != nil {
return types.InternalErrorf("failed to write unhaltered resolv.conf file content when setting up dns for sandbox %s: %v", sb.ID(), err)
}
}
// Write hash
if err := ioutil.WriteFile(sb.config.resolvConfHashFile, []byte(newRC.Hash), filePerm); err != nil {
return types.InternalErrorf("failed to write resolv.conf hash file when setting up dns for sandbox %s: %v", sb.ID(), err)
}
return nil
}
func (sb *sandbox) updateDNS(ipv6Enabled bool) error {
var (
currHash string
hashFile = sb.config.resolvConfHashFile
)
// This is for the host mode networking
if sb.config.originResolvConfPath != "" {
return nil
}
if len(sb.config.dnsList) > 0 || len(sb.config.dnsSearchList) > 0 || len(sb.config.dnsOptionsList) > 0 {
return nil
}
currRC, err := resolvconf.GetSpecific(sb.config.resolvConfPath)
if err != nil {
if !os.IsNotExist(err) {
return err
}
} else {
h, err := ioutil.ReadFile(hashFile)
if err != nil {
if !os.IsNotExist(err) {
return err
}
} else {
currHash = string(h)
}
}
if currHash != "" && currHash != currRC.Hash {
// Seems the user has changed the container resolv.conf since the last time
// we checked so return without doing anything.
//log.Infof("Skipping update of resolv.conf file with ipv6Enabled: %t because file was touched by user", ipv6Enabled)
return nil
}
// replace any localhost/127.* and remove IPv6 nameservers if IPv6 disabled.
newRC, err := resolvconf.FilterResolvDNS(currRC.Content, ipv6Enabled)
if err != nil {
return err
}
err = ioutil.WriteFile(sb.config.resolvConfPath, newRC.Content, 0644)
if err != nil {
return err
}
// write the new hash in a temp file and rename it to make the update atomic
dir := path.Dir(sb.config.resolvConfPath)
tmpHashFile, err := ioutil.TempFile(dir, "hash")
if err != nil {
return err
}
if err = tmpHashFile.Chmod(filePerm); err != nil {
tmpHashFile.Close()
return err
}
_, err = tmpHashFile.Write([]byte(newRC.Hash))
if err1 := tmpHashFile.Close(); err == nil {
err = err1
}
if err != nil {
return err
}
return os.Rename(tmpHashFile.Name(), hashFile)
}
// Embedded DNS server has to be enabled for this sandbox. Rebuild the container's
// resolv.conf by doing the follwing
// - Save the external name servers in resolv.conf in the sandbox
// - Add only the embedded server's IP to container's resolv.conf
// - If the embedded server needs any resolv.conf options add it to the current list
func (sb *sandbox) rebuildDNS() error {
currRC, err := resolvconf.GetSpecific(sb.config.resolvConfPath)
if err != nil {
return err
}
// localhost entries have already been filtered out from the list
// retain only the v4 servers in sb for forwarding the DNS queries
sb.extDNS = resolvconf.GetNameservers(currRC.Content, types.IPv4)
var (
dnsList = []string{sb.resolver.NameServer()}
dnsOptionsList = resolvconf.GetOptions(currRC.Content)
dnsSearchList = resolvconf.GetSearchDomains(currRC.Content)
)
// external v6 DNS servers has to be listed in resolv.conf
dnsList = append(dnsList, resolvconf.GetNameservers(currRC.Content, types.IPv6)...)
// Resolver returns the options in the format resolv.conf expects
dnsOptionsList = append(dnsOptionsList, sb.resolver.ResolverOptions()...)
_, err = resolvconf.Build(sb.config.resolvConfPath, dnsList, dnsSearchList, dnsOptionsList)
return err
}
func createBasePath(dir string) error {
return os.MkdirAll(dir, dirPerm)
}
func createFile(path string) error {
var f *os.File
dir, _ := filepath.Split(path)
err := createBasePath(dir)
if err != nil {
return err
}
f, err = os.Create(path)
if err == nil {
f.Close()
}
return err
}
func copyFile(src, dst string) error {
sBytes, err := ioutil.ReadFile(src)
if err != nil {
return err
}
return ioutil.WriteFile(dst, sBytes, filePerm)
}<|fim▁end|> | if err := createBasePath(dir); err != nil {
return err
} |
<|file_name|>_security_rules_operations.py<|end_file_name|><|fim▁begin|># coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class SecurityRulesOperations:
"""SecurityRulesOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.network.v2017_10_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
async def _delete_initial(
self,
resource_group_name: str,
network_security_group_name: str,
security_rule_name: str,
**kwargs: Any
) -> None:
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-10-01"
# Construct URL
url = self._delete_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'networkSecurityGroupName': self._serialize.url("network_security_group_name", network_security_group_name, 'str'),
'securityRuleName': self._serialize.url("security_rule_name", security_rule_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
request = self._client.delete(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}'} # type: ignore
async def begin_delete(
self,
resource_group_name: str,
network_security_group_name: str,
security_rule_name: str,
**kwargs: Any
) -> AsyncLROPoller[None]:
"""Deletes the specified network security rule.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param network_security_group_name: The name of the network security group.
:type network_security_group_name: str
:param security_rule_name: The name of the security rule.
:type security_rule_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling.
Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType[None]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial(
resource_group_name=resource_group_name,
network_security_group_name=network_security_group_name,
security_rule_name=security_rule_name,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
if cls:
return cls(pipeline_response, None, {})
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'networkSecurityGroupName': self._serialize.url("network_security_group_name", network_security_group_name, 'str'),
'securityRuleName': self._serialize.url("security_rule_name", security_rule_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}'} # type: ignore
async def get(
self,
resource_group_name: str,
network_security_group_name: str,
security_rule_name: str,
**kwargs: Any
) -> "_models.SecurityRule":
"""Get the specified network security rule.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param network_security_group_name: The name of the network security group.
:type network_security_group_name: str
:param security_rule_name: The name of the security rule.
:type security_rule_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SecurityRule, or the result of cls(response)
:rtype: ~azure.mgmt.network.v2017_10_01.models.SecurityRule
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.SecurityRule"]
error_map = {<|fim▁hole|> }
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-10-01"
accept = "application/json, text/json"
# Construct URL
url = self.get.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'networkSecurityGroupName': self._serialize.url("network_security_group_name", network_security_group_name, 'str'),
'securityRuleName': self._serialize.url("security_rule_name", security_rule_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('SecurityRule', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}'} # type: ignore
async def _create_or_update_initial(
self,
resource_group_name: str,
network_security_group_name: str,
security_rule_name: str,
security_rule_parameters: "_models.SecurityRule",
**kwargs: Any
) -> "_models.SecurityRule":
cls = kwargs.pop('cls', None) # type: ClsType["_models.SecurityRule"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-10-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json, text/json"
# Construct URL
url = self._create_or_update_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'networkSecurityGroupName': self._serialize.url("network_security_group_name", network_security_group_name, 'str'),
'securityRuleName': self._serialize.url("security_rule_name", security_rule_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(security_rule_parameters, 'SecurityRule')
body_content_kwargs['content'] = body_content
request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('SecurityRule', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('SecurityRule', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}'} # type: ignore
async def begin_create_or_update(
self,
resource_group_name: str,
network_security_group_name: str,
security_rule_name: str,
security_rule_parameters: "_models.SecurityRule",
**kwargs: Any
) -> AsyncLROPoller["_models.SecurityRule"]:
"""Creates or updates a security rule in the specified network security group.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param network_security_group_name: The name of the network security group.
:type network_security_group_name: str
:param security_rule_name: The name of the security rule.
:type security_rule_name: str
:param security_rule_parameters: Parameters supplied to the create or update network security
rule operation.
:type security_rule_parameters: ~azure.mgmt.network.v2017_10_01.models.SecurityRule
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling.
Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either SecurityRule or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2017_10_01.models.SecurityRule]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.SecurityRule"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_or_update_initial(
resource_group_name=resource_group_name,
network_security_group_name=network_security_group_name,
security_rule_name=security_rule_name,
security_rule_parameters=security_rule_parameters,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('SecurityRule', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'networkSecurityGroupName': self._serialize.url("network_security_group_name", network_security_group_name, 'str'),
'securityRuleName': self._serialize.url("security_rule_name", security_rule_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}'} # type: ignore
def list(
self,
resource_group_name: str,
network_security_group_name: str,
**kwargs: Any
) -> AsyncIterable["_models.SecurityRuleListResult"]:
"""Gets all security rules in a network security group.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param network_security_group_name: The name of the network security group.
:type network_security_group_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either SecurityRuleListResult or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2017_10_01.models.SecurityRuleListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.SecurityRuleListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2017-10-01"
accept = "application/json, text/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'networkSecurityGroupName': self._serialize.url("network_security_group_name", network_security_group_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('SecurityRuleListResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules'} # type: ignore<|fim▁end|> | 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>use crate::variants::GameContextActorInformationsVariant;
use crate::variants::GameFightFighterInformationsVariant;
use protocol_derive::{Decode, Encode};
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 5864)]
pub struct GameFightShowFighterMessage<'a> {
pub informations: GameFightFighterInformationsVariant<'a>,
}
#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 6218)]
pub struct GameFightShowFighterRandomStaticPoseMessage<'a> {<|fim▁hole|>#[derive(Clone, PartialEq, Debug, Encode, Decode)]
#[protocol(id = 6309)]
pub struct GameFightRefreshFighterMessage<'a> {
pub informations: GameContextActorInformationsVariant<'a>,
}<|fim▁end|> | pub base: GameFightShowFighterMessage<'a>,
}
|
<|file_name|>tools.py<|end_file_name|><|fim▁begin|># Name: tools.py
# Purpose: XRC editor, toolbar
# Author: Roman Rolinsky <[email protected]>
# Created: 19.03.2003
# RCS-ID: $Id: tools.py,v 1.12 2006/05/17 03:57:57 RD Exp $
from xxx import * # xxx imports globals and params
from tree import ID_NEW
# Icons
import images
# Groups of controls
GROUPNUM = 4
GROUP_WINDOWS, GROUP_MENUS, GROUP_SIZERS, GROUP_CONTROLS = range(GROUPNUM)
# States depending on current selection and Control/Shift keys
STATE_ROOT, STATE_MENUBAR, STATE_TOOLBAR, STATE_MENU, STATE_STDDLGBTN, STATE_ELSE = range(6)
# Left toolbar for GUI elements
class Tools(wx.Panel):
TOOL_SIZE = (30, 30)
def __init__(self, parent):
if wx.Platform == '__WXGTK__':
wx.Panel.__init__(self, parent, -1,
style=wx.RAISED_BORDER|wx.WANTS_CHARS)
else:
wx.Panel.__init__(self, parent, -1, style=wx.WANTS_CHARS)
# Create sizer for groups
self.sizer = wx.BoxSizer(wx.VERTICAL)
# Data to create buttons
self.groups = []
self.ctrl = self.shift = False
# Current state (what to enable/disable)
self.state = None
groups = [
["Windows",
(ID_NEW.FRAME, images.getToolFrameBitmap()),
(ID_NEW.DIALOG, images.getToolDialogBitmap()),
(ID_NEW.PANEL, images.getToolPanelBitmap())],
["Menus",
(ID_NEW.TOOL_BAR, images.getToolToolBarBitmap()),
(ID_NEW.MENU_BAR, images.getToolMenuBarBitmap()),
(ID_NEW.MENU, images.getToolMenuBitmap()),
(ID_NEW.TOOL, images.getToolToolBitmap()),
(ID_NEW.MENU_ITEM, images.getToolMenuItemBitmap()),
(ID_NEW.SEPARATOR, images.getToolSeparatorBitmap())],
["Sizers",
(ID_NEW.BOX_SIZER, images.getToolBoxSizerBitmap()),
(ID_NEW.STATIC_BOX_SIZER, images.getToolStaticBoxSizerBitmap()),
(ID_NEW.GRID_SIZER, images.getToolGridSizerBitmap()),
(ID_NEW.FLEX_GRID_SIZER, images.getToolFlexGridSizerBitmap()),
(ID_NEW.GRID_BAG_SIZER, images.getToolGridBagSizerBitmap()),
(ID_NEW.SPACER, images.getToolSpacerBitmap())],
["Controls",
(ID_NEW.STATIC_TEXT, images.getToolStaticTextBitmap()),
(ID_NEW.STATIC_BITMAP, images.getToolStaticBitmapBitmap()),
(ID_NEW.STATIC_LINE, images.getToolStaticLineBitmap()),
(ID_NEW.BUTTON, images.getToolButtonBitmap()),
(ID_NEW.BITMAP_BUTTON, images.getToolBitmapButtonBitmap()),
(ID_NEW.STATIC_BOX, images.getToolStaticBoxBitmap()),
(ID_NEW.TEXT_CTRL, images.getToolTextCtrlBitmap()),
(ID_NEW.COMBO_BOX, images.getToolComboBoxBitmap()),
(ID_NEW.CHOICE, images.getToolChoiceBitmap()),
(ID_NEW.RADIO_BUTTON, images.getToolRadioButtonBitmap()),
(ID_NEW.CHECK_BOX, images.getToolCheckBoxBitmap()),
(ID_NEW.RADIO_BOX, images.getToolRadioBoxBitmap()),
(ID_NEW.SPIN_CTRL, images.getToolSpinCtrlBitmap()),
(ID_NEW.SPIN_BUTTON, images.getToolSpinButtonBitmap()),
(ID_NEW.SCROLL_BAR, images.getToolScrollBarBitmap()),
(ID_NEW.SLIDER, images.getToolSliderBitmap()),
(ID_NEW.GAUGE, images.getToolGaugeBitmap()),
(ID_NEW.TREE_CTRL, images.getToolTreeCtrlBitmap()),
(ID_NEW.LIST_BOX, images.getToolListBoxBitmap()),
(ID_NEW.CHECK_LIST, images.getToolCheckListBitmap()),
(ID_NEW.LIST_CTRL, images.getToolListCtrlBitmap()),
(ID_NEW.NOTEBOOK, images.getToolNotebookBitmap()),
(ID_NEW.SPLITTER_WINDOW, images.getToolSplitterWindowBitmap()),
(ID_NEW.UNKNOWN, images.getToolUnknownBitmap())]
]
from tree import customCreateMap
if customCreateMap:
customGroup=['Custom']
for id in customCreateMap:
customGroup.append( (id, images.getToolUnknownBitmap()))
groups.append(customGroup)
for grp in groups:
self.AddGroup(grp[0])
for b in grp[1:]:
self.AddButton(b[0], b[1], g.pullDownMenu.createMap[b[0]])
self.SetAutoLayout(True)
self.SetSizerAndFit(self.sizer)
# Allow to be resized in vertical direction only
self.SetSizeHints(self.GetSize()[0], -1)
# Events
wx.EVT_COMMAND_RANGE(self, ID_NEW.PANEL, ID_NEW.LAST,
wx.wxEVT_COMMAND_BUTTON_CLICKED, g.frame.OnCreate)
wx.EVT_KEY_DOWN(self, self.OnKeyDown)
wx.EVT_KEY_UP(self, self.OnKeyUp)
def AddButton(self, id, image, text):
from wx.lib import buttons
button = buttons.GenBitmapButton(self, id, image, size=self.TOOL_SIZE,
style=wx.NO_BORDER|wx.WANTS_CHARS)
button.SetBezelWidth(0)
wx.EVT_KEY_DOWN(button, self.OnKeyDown)
wx.EVT_KEY_UP(button, self.OnKeyUp)
button.SetToolTipString(text)
self.curSizer.Add(button)
self.groups[-1][1][id] = button
def AddGroup(self, name):
# Each group is inside box
box = wx.StaticBox(self, -1, name, style=wx.WANTS_CHARS)
box.SetFont(g.smallerFont())
boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
boxSizer.Add((0, 4))
self.curSizer = wx.GridSizer(0, 3)
boxSizer.Add(self.curSizer)
self.sizer.Add(boxSizer, 0, wx.TOP | wx.LEFT | wx.RIGHT, 4)
self.groups.append((box,{}))
# Enable/disable group
def EnableGroup(self, gnum, enable = True):
grp = self.groups[gnum]
grp[0].Enable(enable)
for b in grp[1].values(): b.Enable(enable)
# Enable/disable group item
def EnableGroupItem(self, gnum, id, enable = True):
grp = self.groups[gnum]
grp[1][id].Enable(enable)
# Enable/disable group items
def EnableGroupItems(self, gnum, ids, enable = True):
grp = self.groups[gnum]
for id in ids:
grp[1][id].Enable(enable)
# Process key events
def OnKeyDown(self, evt):
if evt.GetKeyCode() == wx.WXK_CONTROL:
g.tree.ctrl = True
elif evt.GetKeyCode() == wx.WXK_SHIFT:
g.tree.shift = True
self.UpdateIfNeeded()
evt.Skip()
def OnKeyUp(self, evt):
if evt.GetKeyCode() == wx.WXK_CONTROL:
g.tree.ctrl = False
elif evt.GetKeyCode() == wx.WXK_SHIFT:
g.tree.shift = False
self.UpdateIfNeeded()
evt.Skip()
def OnMouse(self, evt):
# Update control and shift states
g.tree.ctrl = evt.ControlDown()<|fim▁hole|> # Update UI after key presses, if necessary
def UpdateIfNeeded(self):
tree = g.tree
if self.ctrl != tree.ctrl or self.shift != tree.shift:
# Enabling is needed only for ctrl
if self.ctrl != tree.ctrl: self.UpdateUI()
self.ctrl = tree.ctrl
self.shift = tree.shift
if tree.ctrl:
status = 'SBL'
elif tree.shift:
status = 'INS'
else:
status = ''
g.frame.SetStatusText(status, 1)
# Update interface
def UpdateUI(self):
if not self.IsShown(): return
# Update status bar
tree = g.tree
item = tree.selection
# If nothing selected, disable everything and return
if not item:
# Disable everything
for grp in range(GROUPNUM):
self.EnableGroup(grp, False)
self.state = None
return
if tree.ctrl: needInsert = True
else: needInsert = tree.NeedInsert(item)
# Enable depending on selection
if item == tree.root or needInsert and tree.GetItemParent(item) == tree.root:
state = STATE_ROOT
else:
xxx = tree.GetPyData(item).treeObject()
# Check parent for possible child nodes if inserting sibling
if needInsert: xxx = xxx.parent
if xxx.__class__ == xxxMenuBar:
state = STATE_MENUBAR
elif xxx.__class__ in [xxxToolBar, xxxTool] or \
xxx.__class__ == xxxSeparator and xxx.parent.__class__ == xxxToolBar:
state = STATE_TOOLBAR
elif xxx.__class__ in [xxxMenu, xxxMenuItem]:
state = STATE_MENU
elif xxx.__class__ == xxxStdDialogButtonSizer:
state = STATE_STDDLGBTN
else:
state = STATE_ELSE
# Enable depending on selection
if state != self.state:
# Disable everything
for grp in range(GROUPNUM):
self.EnableGroup(grp, False)
# Enable some
if state == STATE_ROOT:
self.EnableGroup(GROUP_WINDOWS, True)
self.EnableGroup(GROUP_MENUS, True)
# But disable items
self.EnableGroupItems(GROUP_MENUS,
[ ID_NEW.TOOL,
ID_NEW.MENU_ITEM,
ID_NEW.SEPARATOR ],
False)
elif state == STATE_STDDLGBTN:
pass # nothing can be added from toolbar
elif state == STATE_MENUBAR:
self.EnableGroup(GROUP_MENUS)
self.EnableGroupItems(GROUP_MENUS,
[ ID_NEW.TOOL_BAR,
ID_NEW.MENU_BAR,
ID_NEW.TOOL ],
False)
elif state == STATE_TOOLBAR:
self.EnableGroup(GROUP_MENUS)
self.EnableGroupItems(GROUP_MENUS,
[ ID_NEW.TOOL_BAR,
ID_NEW.MENU,
ID_NEW.MENU_BAR,
ID_NEW.MENU_ITEM ],
False)
self.EnableGroup(GROUP_CONTROLS)
self.EnableGroupItems(GROUP_CONTROLS,
[ ID_NEW.TREE_CTRL,
ID_NEW.NOTEBOOK,
ID_NEW.SPLITTER_WINDOW ],
False)
elif state == STATE_MENU:
self.EnableGroup(GROUP_MENUS)
self.EnableGroupItems(GROUP_MENUS,
[ ID_NEW.TOOL_BAR,
ID_NEW.MENU_BAR,
ID_NEW.TOOL ],
False)
else:
self.EnableGroup(GROUP_WINDOWS)
self.EnableGroupItems(GROUP_WINDOWS,
[ ID_NEW.FRAME,
ID_NEW.DIALOG ],
False)
self.EnableGroup(GROUP_MENUS)
self.EnableGroupItems(GROUP_MENUS,
[ ID_NEW.MENU_BAR,
ID_NEW.MENU_BAR,
ID_NEW.MENU,
ID_NEW.MENU_ITEM,
ID_NEW.TOOL,
ID_NEW.SEPARATOR ],
False)
self.EnableGroup(GROUP_SIZERS)
self.EnableGroup(GROUP_CONTROLS)
# Special case for *book (always executed)
if state == STATE_ELSE:
if xxx.__class__ in [xxxNotebook, xxxChoicebook, xxxListbook]:
self.EnableGroup(GROUP_SIZERS, False)
else:
self.EnableGroup(GROUP_SIZERS)
if not (xxx.isSizer or xxx.parent and xxx.parent.isSizer):
self.EnableGroupItem(GROUP_SIZERS, ID_NEW.SPACER, False)
if xxx.__class__ == xxxFrame:
self.EnableGroupItem(GROUP_MENUS, ID_NEW.MENU_BAR)
# Save state
self.state = state<|fim▁end|> | g.tree.shift = evt.ShiftDown()
self.UpdateIfNeeded()
evt.Skip()
|
<|file_name|>work-dashboard.component.ts<|end_file_name|><|fim▁begin|>import { Component, OnInit } from '@angular/core';
import { CurrentWorkService } from '../current-work/current-work.service';
import { Work } from 'src/app/services/work/work';
import { Chapter } from 'src/app/services/chapter/chapter';
import { WorkReview } from 'src/app/services/review/work-review';
import { ReviewModalComponent } from '../../review-modal/review-modal.component';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'app-work-dashboard',
templateUrl: './work-dashboard.component.html',
styleUrls: ['./work-dashboard.component.css']
})
export class WorkDashboardComponent implements OnInit {
work: Work;
workChapters: Chapter[];
workReviews: WorkReview[];
openReview(review: WorkReview) {
const activeModal = this.modalService.open(ReviewModalComponent, { size: 'lg', scrollable: true, centered: true });
activeModal.componentInstance.review = review;
}
constructor(
private currentWork: CurrentWorkService,
private modalService: NgbModal,
) { }
ngOnInit() {
this.currentWork.work<|fim▁hole|> .subscribe(chapters => this.workChapters = chapters);
this.currentWork.reviews
.subscribe(reviews => this.workReviews = reviews);
}
}<|fim▁end|> | .subscribe(work => this.work = work);
this.currentWork.chapters |
<|file_name|>compiler.ts<|end_file_name|><|fim▁begin|>import * as debug from "debug";
import * as llvm from "llvm-node";
import * as ts from "typescript";
import {BuiltInSymbols} from "./built-in-symbols";
import {CodeGenerationDiagnostics, isCodeGenerationDiagnostic} from "./code-generation-diagnostic";
import {DefaultCodeGenerationContextFactory} from "./code-generation/default-code-generation-context-factory";
import {NotYetImplementedCodeGenerator} from "./code-generation/not-yet-implemented-code-generator";
import {PerFileCodeGenerator} from "./code-generation/per-file/per-file-code-generator";
import {CompilationContext} from "./compilation-context";
import {SpeedyJSCompilerOptions} from "./speedyjs-compiler-options";
import {LogUnknownTransformVisitor} from "./transform/log-unknown-transform-visitor";
import {SpeedyJSTransformVisitor} from "./transform/speedyjs-transform-visitor";
import {createTransformVisitorFactory} from "./transform/transform-visitor";
import {TypeScriptTypeChecker} from "./typescript-type-checker";
const LOG = debug("compiler");
/**
* The main Interface for compiling a SpeedyJS Program.
* The compiler creates compiles all with "use speedyjs" marked functions and rewrites the original source file
* to invoke the web assembly function instead of executing the function body in the JS runtime.
*/
export class Compiler {
/**
* Creates a new instance that uses the given compilation options and compiler host
* @param compilerOptions the compilation options
* @param compilerHost the compiler host
*/
constructor(private compilerOptions: SpeedyJSCompilerOptions, private compilerHost: ts.CompilerHost) {
}
/**
* Compiles the source files with the given names
* @param rootFileNames the file names of the source files to compile
* @return the result of the compilation.
*/
compile(rootFileNames: string[]): { exitStatus: ts.ExitStatus, diagnostics: ts.Diagnostic[] } {
LOG("Start Compiling");
Compiler.initLLVM();
const program: ts.Program = ts.createProgram(rootFileNames, this.compilerOptions, this.compilerHost);
const diagnostics = [
...program.getSyntacticDiagnostics(),
...program.getOptionsDiagnostics(),
...program.getGlobalDiagnostics(),
...program.getSemanticDiagnostics()
];
if (diagnostics.length > 0) {
return { diagnostics, exitStatus: ts.ExitStatus.DiagnosticsPresent_OutputsSkipped };
}
const context = new llvm.LLVMContext();
const builtIns = BuiltInSymbols.create(program, this.compilerHost);<|fim▁hole|> llvmContext: context,
typeChecker: new TypeScriptTypeChecker(program.getTypeChecker()),
rootDir: (program as any).getCommonSourceDirectory()
};
return Compiler.emit(program, compilationContext);
}
private static initLLVM() {
llvm.initializeAllTargets();
llvm.initializeAllTargetInfos();
llvm.initializeAllAsmPrinters();
llvm.initializeAllTargetMCs();
llvm.initializeAllAsmParsers();
}
private static emit(program: ts.Program, compilationContext: CompilationContext) {
const codeGenerationContextFactory = new DefaultCodeGenerationContextFactory(new NotYetImplementedCodeGenerator());
const codeGenerator = new PerFileCodeGenerator(compilationContext.llvmContext, codeGenerationContextFactory);
const logUnknownVisitor = new LogUnknownTransformVisitor();
const speedyJSVisitor = new SpeedyJSTransformVisitor(compilationContext, codeGenerator);
try {
const emitResult = program.emit(undefined, undefined, undefined, undefined, { before: [
createTransformVisitorFactory(logUnknownVisitor),
createTransformVisitorFactory(speedyJSVisitor)
]});
let exitStatus;
if (emitResult.emitSkipped) {
exitStatus = ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
} else {
codeGenerator.completeCompilation();
exitStatus = ts.ExitStatus.Success;
}
LOG("Program compiled");
return { exitStatus, diagnostics: emitResult.diagnostics };
} catch (ex) {
if (isCodeGenerationDiagnostic(ex)) {
return { exitStatus: ts.ExitStatus.DiagnosticsPresent_OutputsSkipped, diagnostics: [ CodeGenerationDiagnostics.toDiagnostic(ex) ]};
} else {
LOG(`Compilation failed`, ex);
throw ex;
}
}
}
}<|fim▁end|> | const compilationContext: CompilationContext = {
builtIns,
compilerHost: this.compilerHost,
compilerOptions: this.compilerOptions, |
<|file_name|>contact.js<|end_file_name|><|fim▁begin|>function __processArg(obj, key) {
var arg = null;
if (obj) {
arg = obj[key] || null;
delete obj[key];
}
return arg;
}
function Controller() {
function goSlide(event) {
var index = event.source.mod;
var arrViews = $.scrollableView.getViews();
switch (index) {
case "0":
$.lbl1.backgroundColor = "#453363";
$.lbl1.color = "#AA9DB6";
$.lbl2.backgroundColor = "#E6E7E9";
$.lbl2.color = "#4CC4D2";
$.lbl3.backgroundColor = "#E6E7E9";
$.lbl3.color = "#4CC4D2";
break;
case "1":
$.lbl1.backgroundColor = "#E6E7E9";
$.lbl1.color = "#4CC4D2";
$.lbl2.backgroundColor = "#453363";
$.lbl2.color = "#AA9DB6";
$.lbl3.backgroundColor = "#E6E7E9";
$.lbl3.color = "#4CC4D2";
break;
case "2":
$.lbl1.backgroundColor = "#E6E7E9";
$.lbl1.color = "#4CC4D2";
$.lbl2.backgroundColor = "#E6E7E9";
$.lbl2.color = "#4CC4D2";
$.lbl3.backgroundColor = "#453363";
$.lbl3.color = "#AA9DB6";
}
$.scrollableView.scrollToView(arrViews[index]);
}
require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
this.__controllerPath = "contact";
if (arguments[0]) {
var __parentSymbol = __processArg(arguments[0], "__parentSymbol");
{
__processArg(arguments[0], "$model");
}
{
__processArg(arguments[0], "__itemTemplate");
}
}
var $ = this;
var exports = {};
var __defers = {};
$.__views.win = Ti.UI.createView({
layout: "vertical",
id: "win",
backgroundColor: "white"
});
$.__views.win && $.addTopLevelView($.__views.win);
$.__views.__alloyId87 = Alloy.createController("_header", {
id: "__alloyId87",
__parentSymbol: $.__views.win
});
$.__views.__alloyId87.setParent($.__views.win);
$.__views.__alloyId88 = Ti.UI.createView({
height: "20%",
backgroundColor: "#836EAF",
id: "__alloyId88"
});
$.__views.win.add($.__views.__alloyId88);
$.__views.__alloyId89 = Ti.UI.createLabel({
text: "Contact us",
left: "10",
top: "10",
color: "white",
id: "__alloyId89"
});
$.__views.__alloyId88.add($.__views.__alloyId89);
$.__views.menu = Ti.UI.createView({
id: "menu",
layout: "horizontal",
height: "50",
width: "100%"
});
$.__views.win.add($.__views.menu);
$.__views.lbl1 = Ti.UI.createLabel({
text: "Our Offices",
id: "lbl1",
mod: "0",
height: "100%",
width: "33%",
textAlign: "center",
backgroundColor: "#453363",
color: "#AA9DB6"
});
$.__views.menu.add($.__views.lbl1);
goSlide ? $.__views.lbl1.addEventListener("touchend", goSlide) : __defers["$.__views.lbl1!touchend!goSlide"] = true;
$.__views.__alloyId90 = Ti.UI.createView({
backgroundColor: "#4CC4D2",
height: "100%",
width: "0.45%",
id: "__alloyId90"
});
$.__views.menu.add($.__views.__alloyId90);
$.__views.lbl2 = Ti.UI.createLabel({
text: "Care Center",
id: "lbl2",
mod: "1",
height: "100%",
width: "33%",
textAlign: "center",
backgroundColor: "#E6E7E9",
color: "#4CC4D2"
});
$.__views.menu.add($.__views.lbl2);
goSlide ? $.__views.lbl2.addEventListener("touchend", goSlide) : __defers["$.__views.lbl2!touchend!goSlide"] = true;
$.__views.__alloyId91 = Ti.UI.createView({
backgroundColor: "#4CC4D2",
height: "100%",
width: "0.45%",
id: "__alloyId91"
});<|fim▁hole|> id: "lbl3",
mod: "2",
height: "100%",
width: "33%",
textAlign: "center",
backgroundColor: "#E6E7E9",
color: "#4CC4D2"
});
$.__views.menu.add($.__views.lbl3);
goSlide ? $.__views.lbl3.addEventListener("touchend", goSlide) : __defers["$.__views.lbl3!touchend!goSlide"] = true;
var __alloyId92 = [];
$.__views.__alloyId93 = Alloy.createController("contact1", {
id: "__alloyId93",
__parentSymbol: __parentSymbol
});
__alloyId92.push($.__views.__alloyId93.getViewEx({
recurse: true
}));
$.__views.__alloyId94 = Alloy.createController("contact2", {
id: "__alloyId94",
__parentSymbol: __parentSymbol
});
__alloyId92.push($.__views.__alloyId94.getViewEx({
recurse: true
}));
$.__views.__alloyId95 = Alloy.createController("contact3", {
id: "__alloyId95",
__parentSymbol: __parentSymbol
});
__alloyId92.push($.__views.__alloyId95.getViewEx({
recurse: true
}));
$.__views.scrollableView = Ti.UI.createScrollableView({
views: __alloyId92,
id: "scrollableView",
showPagingControl: "false",
scrollingEnabled: "false"
});
$.__views.win.add($.__views.scrollableView);
exports.destroy = function() {};
_.extend($, $.__views);
var storeModel = Alloy.createCollection("storeLocator");
var details = storeModel.getStoreList();
console.log(details);
__defers["$.__views.lbl1!touchend!goSlide"] && $.__views.lbl1.addEventListener("touchend", goSlide);
__defers["$.__views.lbl2!touchend!goSlide"] && $.__views.lbl2.addEventListener("touchend", goSlide);
__defers["$.__views.lbl3!touchend!goSlide"] && $.__views.lbl3.addEventListener("touchend", goSlide);
_.extend($, exports);
}
var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;
module.exports = Controller;<|fim▁end|> | $.__views.menu.add($.__views.__alloyId91);
$.__views.lbl3 = Ti.UI.createLabel({
text: "XOX Dealers", |
<|file_name|>introHCI.js<|end_file_name|><|fim▁begin|>'use strict';
<|fim▁hole|>})
/*
* Function that is called when the document is ready.
*/
function initializePage() {
$('.project a').click(addProjectDetails);
$('#colorBtn').click(randomizeColors);
$('#apibutton').click(getExternalApi);
}
/*
* Make an AJAX call to retrieve project details and add it in
*/
function addProjectDetails(e) {
// Prevent following the link
e.preventDefault();
// Get the div ID, e.g., "project3"
var projectID = $(this).closest('.project').attr('id');
// get rid of 'project' from the front of the id 'project3'
var idNumber = projectID.substr('project'.length);
console.log("User clicked on project " + idNumber);
$.get('/project/' + idNumber, addProject);
console.log('/project/' + idNumber);
}
function addProject(result) {
console.log(result);
var projectHTML = '<a href="#" class="thumbnail">' +
'<img src="' + result['image'] + '" class="detalsImage">' +
'<p>' + result['title'] + '</p>' +
'<p> <small>' + result['date'] + '</small></p>' +
'<p>' + result['summary'] + '</p> </a>';
$("#project" + result['id'] + " .details").html(projectHTML);
}
/*
* Make an AJAX call to retrieve a color palette for the site
* and apply it
*/
function randomizeColors(e) {
e.preventDefault();
$.get('/palette', addColor);
}
function addColor(result) {
console.log(result);
var colors = result['colors']['hex'];
$('body').css('background-color', colors[0]);
$('.thumbnail').css('background-color', colors[1]);
$('h1, h2, h3, h4, h5, h5').css('color', colors[2]);
$('p').css('color', colors[3]);
$('.project img').css('opacity', .75);
}
function getExternalApi(e) {
e.preventDefault();
$.get('https://api.spotify.com/v1/artists/4dpARuHxo51G3z768sgnrY', getAPI);
}
function getAPI(result) {
console.log(result);
var images = result['images'];
console.log(images);
var adeleHTML = '<h1>' + result['name'] + '</h1>' +
'<p> popularity: ' + result['popularity'] + '</p>' +
'<p> genre: ' + result['genres'][0] + '</p>' +
'<img src="' + images[2]['url'] + '"> <br />' ;
$("#output").html(adeleHTML);
}<|fim▁end|> | // Call this function when the page loads (the "ready" event)
$(document).ready(function() {
initializePage(); |
<|file_name|>decoding.rs<|end_file_name|><|fim▁begin|>use serde::de::DeserializeOwned;
use crate::algorithms::AlgorithmFamily;
use crate::crypto::verify;
use crate::errors::{new_error, ErrorKind, Result};
use crate::header::Header;
#[cfg(feature = "use_pem")]
use crate::pem::decoder::PemEncodedKey;
use crate::serialization::{b64_decode, DecodedJwtPartClaims};
use crate::validation::{validate, Validation};
/// The return type of a successful call to [decode](fn.decode.html).
#[derive(Debug)]
pub struct TokenData<T> {
/// The decoded JWT header
pub header: Header,
/// The decoded JWT claims
pub claims: T,
}
/// Takes the result of a rsplit and ensure we only get 2 parts
/// Errors if we don't
macro_rules! expect_two {
($iter:expr) => {{
let mut i = $iter;
match (i.next(), i.next(), i.next()) {
(Some(first), Some(second), None) => (first, second),
_ => return Err(new_error(ErrorKind::InvalidToken)),
}
}};
}
#[derive(Clone)]
pub(crate) enum DecodingKeyKind {
SecretOrDer(Vec<u8>),
RsaModulusExponent { n: Vec<u8>, e: Vec<u8> },
}
/// All the different kind of keys we can use to decode a JWT
/// This key can be re-used so make sure you only initialize it once if you can for better performance
#[derive(Clone)]
pub struct DecodingKey {
pub(crate) family: AlgorithmFamily,
pub(crate) kind: DecodingKeyKind,
}
impl DecodingKey {
/// If you're using HMAC, use this.
pub fn from_secret(secret: &[u8]) -> Self {
DecodingKey {
family: AlgorithmFamily::Hmac,
kind: DecodingKeyKind::SecretOrDer(secret.to_vec()),
}
}
/// If you're using HMAC with a base64 encoded secret, use this.
pub fn from_base64_secret(secret: &str) -> Result<Self> {
let out = base64::decode(&secret)?;
Ok(DecodingKey { family: AlgorithmFamily::Hmac, kind: DecodingKeyKind::SecretOrDer(out) })
}
/// If you are loading a public RSA key in a PEM format, use this.
/// Only exists if the feature `use_pem` is enabled.
#[cfg(feature = "use_pem")]
pub fn from_rsa_pem(key: &[u8]) -> Result<Self> {
let pem_key = PemEncodedKey::new(key)?;
let content = pem_key.as_rsa_key()?;
Ok(DecodingKey {
family: AlgorithmFamily::Rsa,
kind: DecodingKeyKind::SecretOrDer(content.to_vec()),
})
}
/// If you have (n, e) RSA public key components as strings, use this.
pub fn from_rsa_components(modulus: &str, exponent: &str) -> Result<Self> {
let n = b64_decode(modulus)?;
let e = b64_decode(exponent)?;
Ok(DecodingKey {
family: AlgorithmFamily::Rsa,
kind: DecodingKeyKind::RsaModulusExponent { n, e },
})
}
/// If you have (n, e) RSA public key components already decoded, use this.
pub fn from_rsa_raw_components(modulus: &[u8], exponent: &[u8]) -> Self {
DecodingKey {
family: AlgorithmFamily::Rsa,
kind: DecodingKeyKind::RsaModulusExponent { n: modulus.to_vec(), e: exponent.to_vec() },
}
}
/// If you have a ECDSA public key in PEM format, use this.
/// Only exists if the feature `use_pem` is enabled.
#[cfg(feature = "use_pem")]
pub fn from_ec_pem(key: &[u8]) -> Result<Self> {
let pem_key = PemEncodedKey::new(key)?;
let content = pem_key.as_ec_public_key()?;
Ok(DecodingKey {
family: AlgorithmFamily::Ec,
kind: DecodingKeyKind::SecretOrDer(content.to_vec()),
})
}
/// If you have a EdDSA public key in PEM format, use this.
/// Only exists if the feature `use_pem` is enabled.
#[cfg(feature = "use_pem")]
pub fn from_ed_pem(key: &[u8]) -> Result<Self> {
let pem_key = PemEncodedKey::new(key)?;<|fim▁hole|> Ok(DecodingKey {
family: AlgorithmFamily::Ed,
kind: DecodingKeyKind::SecretOrDer(content.to_vec()),
})
}
/// If you know what you're doing and have a RSA DER encoded public key, use this.
pub fn from_rsa_der(der: &[u8]) -> Self {
DecodingKey {
family: AlgorithmFamily::Rsa,
kind: DecodingKeyKind::SecretOrDer(der.to_vec()),
}
}
/// If you know what you're doing and have a RSA EC encoded public key, use this.
pub fn from_ec_der(der: &[u8]) -> Self {
DecodingKey {
family: AlgorithmFamily::Ec,
kind: DecodingKeyKind::SecretOrDer(der.to_vec()),
}
}
/// If you know what you're doing and have a Ed DER encoded public key, use this.
pub fn from_ed_der(der: &[u8]) -> Self {
DecodingKey {
family: AlgorithmFamily::Ed,
kind: DecodingKeyKind::SecretOrDer(der.to_vec()),
}
}
pub(crate) fn as_bytes(&self) -> &[u8] {
match &self.kind {
DecodingKeyKind::SecretOrDer(b) => b,
DecodingKeyKind::RsaModulusExponent { .. } => unreachable!(),
}
}
}
/// Verify signature of a JWT, and return header object and raw payload
///
/// If the token or its signature is invalid, it will return an error.
fn verify_signature<'a>(
token: &'a str,
key: &DecodingKey,
validation: &Validation,
) -> Result<(Header, &'a str)> {
if validation.validate_signature && validation.algorithms.is_empty() {
return Err(new_error(ErrorKind::MissingAlgorithm));
}
if validation.validate_signature {
for alg in &validation.algorithms {
if key.family != alg.family() {
return Err(new_error(ErrorKind::InvalidAlgorithm));
}
}
}
let (signature, message) = expect_two!(token.rsplitn(2, '.'));
let (payload, header) = expect_two!(message.rsplitn(2, '.'));
let header = Header::from_encoded(header)?;
if validation.validate_signature && !validation.algorithms.contains(&header.alg) {
return Err(new_error(ErrorKind::InvalidAlgorithm));
}
if validation.validate_signature && !verify(signature, message.as_bytes(), key, header.alg)? {
return Err(new_error(ErrorKind::InvalidSignature));
}
Ok((header, payload))
}
/// Decode and validate a JWT
///
/// If the token or its signature is invalid or the claims fail validation, it will return an error.
///
/// ```rust
/// use serde::{Deserialize, Serialize};
/// use jsonwebtoken::{decode, DecodingKey, Validation, Algorithm};
///
/// #[derive(Debug, Serialize, Deserialize)]
/// struct Claims {
/// sub: String,
/// company: String
/// }
///
/// let token = "a.jwt.token".to_string();
/// // Claims is a struct that implements Deserialize
/// let token_message = decode::<Claims>(&token, &DecodingKey::from_secret("secret".as_ref()), &Validation::new(Algorithm::HS256));
/// ```
pub fn decode<T: DeserializeOwned>(
token: &str,
key: &DecodingKey,
validation: &Validation,
) -> Result<TokenData<T>> {
match verify_signature(token, key, validation) {
Err(e) => Err(e),
Ok((header, claims)) => {
let decoded_claims = DecodedJwtPartClaims::from_jwt_part_claims(claims)?;
let claims = decoded_claims.deserialize()?;
validate(decoded_claims.deserialize()?, validation)?;
Ok(TokenData { header, claims })
}
}
}
/// Decode a JWT without any signature verification/validations and return its [Header](struct.Header.html).
///
/// If the token has an invalid format (ie 3 parts separated by a `.`), it will return an error.
///
/// ```rust
/// use jsonwebtoken::decode_header;
///
/// let token = "a.jwt.token".to_string();
/// let header = decode_header(&token);
/// ```
pub fn decode_header(token: &str) -> Result<Header> {
let (_, message) = expect_two!(token.rsplitn(2, '.'));
let (_, header) = expect_two!(message.rsplitn(2, '.'));
Header::from_encoded(header)
}<|fim▁end|> | let content = pem_key.as_ed_public_key()?; |
<|file_name|>urls.py<|end_file_name|><|fim▁begin|><|fim▁hole|>from django.urls import path
import users.views
urlpatterns = [
path("settings/", users.views.user_settings, name="settings"),
path("reset_token/", users.views.reset_token, name="reset_token"),
path("panel_hide/", users.views.panel_hide, name="hide_new_panel"),
]<|fim▁end|> | |
<|file_name|>history.py<|end_file_name|><|fim▁begin|>"""Provide history manager for SCCTool."""
import json
import logging
import scctool.settings.translation
from scctool.settings import getJsonFile, idx2race, race2idx
module_logger = logging.getLogger(__name__)
_ = scctool.settings.translation.gettext
class HistoryManager:
"""History manager for SCCTool."""
__max_length = 100
def __init__(self):
"""Init the history manager."""
self.loadJson()
self.updateDataStructure()
def loadJson(self):
"""Read json data from file."""
try:
with open(getJsonFile('history'), 'r',
encoding='utf-8-sig') as json_file:
data = json.load(json_file)
except Exception:
data = dict()
self.__player_history = data.get('player', [])
self.__team_history = data.get('team', [])
def dumpJson(self):
"""Write json data to file."""
data = dict()
data['player'] = self.__player_history
data['team'] = self.__team_history
try:
with open(getJsonFile('history'), 'w',
encoding='utf-8-sig') as outfile:
json.dump(data, outfile)
except Exception:
module_logger.exception("message")
def updateDataStructure(self):
"""Update the data structure (from a previous version)."""
for idx, item in enumerate(self.__team_history):
if isinstance(item, str):
self.__team_history[idx] = {'team': item, 'logo': '0'}
<|fim▁hole|> def insertPlayer(self, player, race):
"""Insert a player into the history."""
player = player.strip()
if not player or player.lower() == "tbd":
return
if race is str:
race = race2idx(race)
race = idx2race(race)
for item in self.__player_history:
if item.get('player', '').lower() == player.lower():
self.__player_history.remove(item)
if race == "Random":
race = item.get('race', 'Random')
break
self.__player_history.insert(0, {"player": player, "race": race})
# self.enforeMaxLength("player")
def insertTeam(self, team, logo='0'):
"""Insert a team into the history."""
team = team.strip()
if not team or team.lower() == "tbd":
return
for item in self.__team_history:
if item.get('team', '').lower() == team.lower():
self.__team_history.remove(item)
if logo == '0':
logo = item.get('logo', '0')
break
self.__team_history.insert(0, {"team": team, "logo": logo})
# self.enforeMaxLength("team")
def enforeMaxLength(self, scope=None):
"""Delete old history elements."""
if not scope or scope == "player":
while len(self.__player_history) > self.__max_length:
self.__player_history.pop()
if not scope or scope == "team":
while len(self.__team_history) > self.__max_length:
self.__team_history.pop()
def getPlayerList(self):
"""Return a list of all players in history."""
playerList = list()
for item in self.__player_history:
player = item['player']
if player not in playerList:
playerList.append(player)
return playerList
def getTeamList(self):
"""Return a list of all teams in history."""
teamList = list()
for item in self.__team_history:
team = item.get('team')
if team not in teamList:
teamList.append(team)
return teamList
def getRace(self, player):
"""Look up the race of a player in the history."""
player = player.lower().strip()
race = "Random"
for item in self.__player_history:
if item.get('player', '').lower() == player:
race = item.get('race', 'Random')
break
return race
def getLogo(self, team):
"""Look up the logo of a team in history."""
team = team.lower().strip()
logo = '0'
for item in self.__team_history:
if item.get('team', '').lower() == team:
logo = item.get('logo', '0')
break
return logo<|fim▁end|> | |
<|file_name|>cp_mgmt_address_range_facts.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Ansible module to manage Check Point Firewall (c) 2019
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = """
---
module: cp_mgmt_address_range_facts
short_description: Get address-range objects facts on Check Point over Web Services API
description:
- Get address-range objects facts on Check Point devices.
- All operations are performed over Web Services API.
- This module handles both operations, get a specific object and get several objects,
For getting a specific object use the parameter 'name'.
version_added: "2.9"<|fim▁hole|>options:
name:
description:
- Object name.
This parameter is relevant only for getting a specific object.
type: str
details_level:
description:
- The level of detail for some of the fields in the response can vary from showing only the UID value of the object to a fully detailed
representation of the object.
type: str
choices: ['uid', 'standard', 'full']
limit:
description:
- No more than that many results will be returned.
This parameter is relevant only for getting few objects.
type: int
offset:
description:
- Skip that many results before beginning to return them.
This parameter is relevant only for getting few objects.
type: int
order:
description:
- Sorts results by the given field. By default the results are sorted in the ascending order by name.
This parameter is relevant only for getting few objects.
type: list
suboptions:
ASC:
description:
- Sorts results by the given field in ascending order.
type: str
choices: ['name']
DESC:
description:
- Sorts results by the given field in descending order.
type: str
choices: ['name']
show_membership:
description:
- Indicates whether to calculate and show "groups" field for every object in reply.
type: bool
extends_documentation_fragment: checkpoint_facts
"""
EXAMPLES = """
- name: show-address-range
cp_mgmt_address_range_facts:
name: New Address Range 1
- name: show-address-ranges
cp_mgmt_address_range_facts:
details_level: standard
limit: 50
offset: 0
"""
RETURN = """
ansible_facts:
description: The checkpoint object facts.
returned: always.
type: dict
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.checkpoint.checkpoint import checkpoint_argument_spec_for_facts, api_call_facts
def main():
argument_spec = dict(
name=dict(type='str'),
details_level=dict(type='str', choices=['uid', 'standard', 'full']),
limit=dict(type='int'),
offset=dict(type='int'),
order=dict(type='list', options=dict(
ASC=dict(type='str', choices=['name']),
DESC=dict(type='str', choices=['name'])
)),
show_membership=dict(type='bool')
)
argument_spec.update(checkpoint_argument_spec_for_facts)
module = AnsibleModule(argument_spec=argument_spec)
api_call_object = "address-range"
api_call_object_plural_version = "address-ranges"
result = api_call_facts(module, api_call_object, api_call_object_plural_version)
module.exit_json(ansible_facts=result)
if __name__ == '__main__':
main()<|fim▁end|> | author: "Or Soffer (@chkp-orso)" |
<|file_name|>epub.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Max Fillinger <[email protected]>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.
# The epub format specification is available at http://idpf.org/epub/201
'''Contains the EpubBuilder class to build epub2.0.1 files with the getebook
module.'''
import html
import re
import datetime
import getebook
import os.path
import re
import zipfile
__all__ = ['EpubBuilder', 'EpubTOC', 'Author']
def _normalize(name):
'''Transform "Firstname [Middlenames] Lastname" into
"Lastname, Firstname [Middlenames]".'''
split = name.split()
if len(split) == 1:
return name
return split[-1] + ', ' + ' '.join(name[0:-1])
def _make_starttag(tag, attrs):
'Write a starttag.'
out = '<' + tag
for key in attrs:
out += ' {}="{}"'.format(key, html.escape(attrs[key]))
out += '>'
return out
def _make_xml_elem(tag, text, attr = []):
'Write a flat xml element.'
out = ' <' + tag
for (key, val) in attr:
out += ' {}="{}"'.format(key, val)
if text:
out += '>{}</{}>\n'.format(text, tag)
else:
out += ' />\n'
return out
class EpubTOC(getebook.TOC):
'Table of contents.'
_head = ((
'<?xml version="1.0" encoding="UTF-8"?>\n'
'<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1" xml:lang="en-US">\n'
' <head>\n'
' <meta name="dtb:uid" content="{}" />\n'
' <meta name="dtb:depth" content="{}" />\n'
' <meta name="dtb:totalPageCount" content="0" />\n'
' <meta name="dtb:maxPageNumber" content="0" />\n'
' </head>\n'
' <docTitle>\n'
' <text>{}</text>\n'
' </docTitle>\n'
))
_doc_author = ((
' <docAuthor>\n'
' <text>{}</text>\n'
' </docAuthor>\n'
))
_navp = ((
'{0}<navPoint id="nav{1}">\n'
'{0} <navLabel>\n'
'{0} <text>{2}</text>\n'
'{0} </navLabel>\n'
'{0} <content src="{3}" />\n'
))
def _navp_xml(self, entry, indent_lvl):
'Write xml for an entry and all its subentries.'
xml = self._navp.format(' '*indent_lvl, str(entry.no), entry.text,
entry.target)
for sub in entry.entries:
xml += self._navp_xml(sub, indent_lvl+1)
xml += ' '*indent_lvl + '</navPoint>\n'
return xml
def write_xml(self, uid, title, authors):
'Write the xml code for the table of contents.'
xml = self._head.format(uid, self.max_depth, title)
for aut in authors:
xml += self._doc_author.format(aut)
xml += ' <navMap>\n'
for entry in self.entries:
xml += self._navp_xml(entry, 2)
xml += ' </navMap>\n</ncx>'
return xml
class _Fileinfo:
'Information about a component file of an epub.'
def __init__(self, name, in_spine = True, guide_title = None,
guide_type = None):
'''Initialize the object. If the file does not belong in the
reading order, in_spine should be set to False. If it should
appear in the guide, set guide_title and guide_type.'''
self.name = name
(self.ident, ext) = os.path.splitext(name)
name_split = name.rsplit('.', 1)
self.ident = name_split[0]
self.in_spine = in_spine
self.guide_title = guide_title
self.guide_type = guide_type
# Infer media-type from file extension
ext = ext.lower()
if ext in ('.htm', '.html', '.xhtml'):
self.media_type = 'application/xhtml+xml'
elif ext in ('.png', '.gif', '.jpeg'):
self.media_type = 'image/' + ext
elif ext == '.jpg':
self.media_type = 'image/jpeg'
elif ext == '.css':
self.media_type = 'text/css'
elif ext == '.ncx':
self.media_type = 'application/x-dtbncx+xml'
else:
raise ValueError('Can\'t infer media-type from extension: %s' % ext)
def manifest_entry(self):
'Write the XML element for the manifest.'
return _make_xml_elem('item', '',
[
('href', self.name),
('id', self.ident),
('media-type', self.media_type)
])
def spine_entry(self):
'''Write the XML element for the spine.
(Empty string if in_spine is False.)'''
if self.in_spine:
return _make_xml_elem('itemref', '', [('idref', self.ident)])
else:
return ''
def guide_entry(self):
'''Write the XML element for the guide.
(Empty string if no guide title and type are given.)'''
if self.guide_title and self.guide_type:
return _make_xml_elem('reference', '',
[
('title', self.guide_title),
('type', self.guide_type),
('href', self.name)
])
else:
return ''
class _EpubMeta:
'Metadata entry for an epub file.'
def __init__(self, tag, text, *args):
'''The metadata entry is an XML element. *args is used for
supplying the XML element's attributes as (key, value) pairs.'''
self.tag = tag
self.text = text
self.attr = args
def write_xml(self):
'Write the XML element.'
return _make_xml_elem(self.tag, self.text, self.attr)
def __repr__(self):
'Returns the text.'
return self.text
def __str__(self):
'Returns the text.'
return self.text
class _EpubDate(_EpubMeta):
'Metadata element for the publication date.'
_date_re = re.compile('^([0-9]{4})(-[0-9]{2}(-[0-9]{2})?)?$')
def __init__(self, date):
'''date must be a string of the form "YYYY[-MM[-DD]]". If it is
not of this form, or if the date is invalid, ValueError is
raised.'''
m = self._date_re.match(date)
if not m:
raise ValueError('invalid date format')
year = int(m.group(1))
try:
mon = int(m.group(2)[1:])
if mon < 0 or mon > 12:
raise ValueError('month must be in 1..12')
except IndexError:
pass
try:
day = int(m.group(3)[1:])
datetime.date(year, mon, day) # raises ValueError if invalid
except IndexError:
pass
self.tag = 'dc:date'
self.text = date
self.attr = ()
class _EpubLang(_EpubMeta):
'Metadata element for the language of the book.'
_lang_re = re.compile('^[a-z]{2}(-[A-Z]{2})?$')
def __init__(self, lang):
'''lang must be a lower-case two-letter language code,
optionally followed by a "-" and a upper-case two-letter country
code. (e.g., "en", "en-US", "en-UK", "de", "de-DE", "de-AT")'''
if self._lang_re.match(lang):
self.tag = 'dc:language'
self.text = lang
self.attr = ()
else:
raise ValueError('invalid language format')
class Author(_EpubMeta):
'''To control the file-as and role attribute for the authors, pass
an Author object to the EpubBuilder instead of a string. The file-as
attribute is a form of the name used for sorting. The role attribute
describes how the person was involved in the work.
You ONLY need this if an author's name is not of the form
"Given-name Family-name", or if you want to specify a role other
than author. Otherwise, you can just pass a string.
The value of role should be a MARC relator, e.g., "aut" for author
or "edt" for editor. See http://www.loc.gov/marc/relators/ for a
full list.'''
def __init__(self, name, fileas = None, role = 'aut'):
'''Initialize the object. If the argument "fileas" is not given,
"Last-name, First-name" is used for the file-as attribute. If
the argument "role" is not given, "aut" is used for the role
attribute.'''
if not fileas:
fileas = _normalize(name)
self.tag = 'dc:creator'
self.text = name
self.attr = (('opf:file-as', fileas), ('opf:role', role))
class _OPFfile:
'''Class for writing the OPF (Open Packaging Format) file for an
epub file. The OPF file contains the metadata, a manifest of all
component files in the epub, a "spine" which specifies the reading
order and a guide which points to important components of the book
such as the title page.'''
_opf = (
'<?xml version="1.0" encoding="UTF-8"?>\n'
'<package version="2.0" xmlns="http://www.idpf.org/2007/opf" unique_identifier="uid_id">\n'
' <metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:opf="http://www.idpf.org/2007/opf">\n'
'{}'
' </metadata>\n'
' <manifest>\n'
'{}'
' </manifest>\n'
' <spine toc="toc">\n'
'{}'
' </spine>\n'
' <guide>\n'
'{}'
' </guide>\n'
'</package>\n'
)
def __init__(self):
'Initialize.'
self.meta = []
self.filelist = []
def write_xml(self):
'Write the XML code for the OPF file.'
metadata = ''
for elem in self.meta:
metadata += elem.write_xml()
manif = ''
spine = ''
guide = ''
for finfo in self.filelist:
manif += finfo.manifest_entry()
spine += finfo.spine_entry()
guide += finfo.guide_entry()
return self._opf.format(metadata, manif, spine, guide)
class EpubBuilder:
'''Builds an epub2.0.1 file. Some of the attributes of this class
(title, uid, lang) are marked as "mandatory" because they represent
metadata that is required by the epub specification. If these
attributes are left unset, default values will be used.'''
_style_css = (
'h1, h2, h3, h4, h5, h6 {\n'
' text-align: center;\n'
'}\n'
'p {\n'
' text-align: justify;\n'
' margin-top: 0.125em;\n'
' margin-bottom: 0em;\n'
' text-indent: 1.0em;\n'
'}\n'
'.getebook-tp {\n'
' margin-top: 8em;\n'
'}\n'
'.getebook-tp-authors {\n'
' font-size: 2em;\n'
' text-align: center;\n'
' margin-bottom: 1em;\n'
'}\n'
'.getebook-tp-title {\n'
' font-weight: bold;\n'
' font-size: 3em;\n'
' text-align: center;\n'
'}\n'
'.getebook-tp-sub {\n'
' text-align: center;\n'
' font-weight: normal;\n'
' font-size: 0.8em;\n'
' margin-top: 1em;\n'
'}\n'
'.getebook-false-h {\n'
' font-weight: bold;\n'
' font-size: 1.5em;\n'
'}\n'
'.getebook-small-h {\n'
' font-style: normal;\n'
' font-weight: normal;\n'
' font-size: 0.8em;\n'
'}\n'
)
_container_xml = (
'<?xml version="1.0"?>\n'
'<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">\n'
' <rootfiles>\n'
' <rootfile full-path="package.opf" media-type="application/oebps-package+xml"/>\n'
' </rootfiles>\n'
'</container>\n'
)
_html = (
'<?xml version="1.0" encoding="utf-8"?>\n'
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">\n'
'<html xmlns="http://www.w3.org/1999/xhtml">\n'
' <head>\n'
' <title>{}</title>\n'
' <meta http-equiv="content-type" content="application/xtml+xml; charset=utf-8" />\n'
' <link href="style.css" rel="stylesheet" type="text/css" />\n'
' </head>\n'
' <body>\n{}'
' </body>\n'
'</html>\n'
)
_finalized = False
def __init__(self, epub_file):
'''Initialize the EpubBuilder instance. "epub_file" is the
filename of the epub to be created.'''
self.epub_f = zipfile.ZipFile(epub_file, 'w', zipfile.ZIP_DEFLATED)
self.epub_f.writestr('mimetype', 'application/epub+zip')
self.epub_f.writestr('META-INF/container.xml', self._container_xml)
self.toc = EpubTOC()
self.opf = _OPFfile()
self.opf.filelist.append(_Fileinfo('toc.ncx', False))
self.opf.filelist.append(_Fileinfo('style.css', False))
self._authors = []
self.opt_meta = {} # Optional metadata (other than authors)
self.content = ''
self.part_no = 0
self.cont_filename = 'part%03d.html' % self.part_no
def __enter__(self):
'Return self for use in with ... as ... statement.'
return self
def __exit__(self, except_type, except_val, traceback):
'Call finalize() and close the file.'
try:
self.finalize()
finally:
# Close again in case an exception happened in finalize()
self.epub_f.close()
return False
@property
def uid(self):
'''Unique identifier of the ebook. (mandatory)
If this property is left unset, a pseudo-random string will be
generated which is long enough for collisions with existing
ebooks to be extremely unlikely.'''
try:
return self._uid
except AttributeError:
import random
from string import (ascii_letters, digits)
alnum = ascii_letters + digits
self.uid = ''.join([random.choice(alnum) for i in range(15)])
return self._uid
@uid.setter
def uid(self, val):
self._uid = _EpubMeta('dc:identifier', str(val), ('id', 'uid_id'))
@property
def title(self):
'''Title of the ebook. (mandatory)
If this property is left unset, it defaults to "Untitled".'''
try:
return self._title
except AttributeError:
self.title = 'Untitled'
return self._title
@title.setter
def title(self, val):
# If val is not a string, raise TypeError now rather than later.
self._title = _EpubMeta('dc:title', '' + val)
@property
def lang(self):
'''Language of the ebook. (mandatory)
The language must be given as a lower-case two-letter code, optionally
followed by a "-" and an upper-case two-letter country code.
(e.g., "en", "en-US", "en-UK", "de", "de-DE", "de-AT")
If this property is left unset, it defaults to "en".'''
try:
return self._lang
except AttributeError:
self.lang = 'en'
return self._lang
@lang.setter
def lang(self, val):
self._lang = _EpubLang(val)
@property
def author(self):
'''Name of the author. (optional)
If there are multiple authors, pass a list of strings.
To control the file-as and role attribute, use author objects instead
of strings; file-as is an alternate form of the name used for sorting.
For a description of the role attribute, see the docstring of the
author class.'''
if len(self._authors) == 1:
return self._authors[0]
return tuple([aut for aut in self._authors])
@author.setter
def author(self, val):
if isinstance(val, Author) or isinstance(val, str):
authors = [val]
else:
authors = val
for aut in authors:
try:
self._authors.append(Author('' + aut))
except TypeError:
# aut is not a string, so it should be an Author object
self._authors.append(aut)
@author.deleter
def author(self):
self._authors = []
@property
def date(self):
'''Publication date. (optional)
Must be given in "YYYY[-MM[-DD]]" format.'''
try:
return self.opt_meta['date']
except KeyError:
return None
@date.setter
def date(self, val):
self.opt_meta['date'] = _EpubDate(val)
@date.deleter
def date(self):
del self._date
@property
def rights(self):
'Copyright/licensing information. (optional)'
try:
return self.opt_meta['rights']
except KeyError:
return None
@rights.setter
def rights(self, val):
self.opt_meta['rights'] = _EpubMeta('dc:rights', '' + val)
@rights.deleter
def rights(self):
del self._rights
@property
def publisher(self):
'Publisher name. (optional)'
try:
return self.opt_meta['publisher']
except KeyError:
return None
@publisher.setter
def publisher(self, val):
self.opt_meta['publisher'] = _EpubMeta('dc:publisher', '' + val)
@publisher.deleter
def publisher(self):
del self._publisher
@property
def style_css(self):
'''CSS stylesheet for the files that are generated by the EpubBuilder
instance. Can be overwritten or extended, but not deleted.'''
return self._style_css
@style_css.setter
def style_css(self, val):
self._style_css = '' + val
def titlepage(self, main_title = None, subtitle = None):
'''Create a title page for the ebook. If no main_title is given,
the title attribute of the EpubBuilder instance is used.'''
tp = '<div class="getebook-tp">\n'
if len(self._authors) >= 1:
if len(self._authors) == 1:
aut_str = str(self._authors[0])
else:
aut_str = ', '.join(str(self._authors[0:-1])) + ', and ' \
+ str(self._authors[-1])
tp += '<div class="getebook-tp-authors">%s</div>\n' % aut_str
if not main_title:
main_title = str(self.title)
tp += '<div class="getebook-tp-title">%s' % main_title
if subtitle:
tp += '<div class="getebook-tp-sub">%s</div>' % subtitle
tp += '</div>\n</div>\n'
self.opf.filelist.insert(0, _Fileinfo('title.html',
guide_title = 'Titlepage', guide_type = 'title-page'))
self.epub_f.writestr('title.html', self._html.format(self.title, tp))
def headingpage(self, heading, subtitle = None, toc_text = None):
'''Create a page containing only a (large) heading, optionally
with a smaller subtitle. If toc_text is not given, it defaults
to the heading.'''
self.new_part()
tag = 'h%d' % min(6, self.toc.depth)
self.content += '<div class="getebook-tp">'
self.content += '<{} class="getebook-tp-title">{}'.format(tag, heading)
if subtitle:
self.content += '<div class="getebook-tp-sub">%s</div>' % subtitle
self.content += '</%s>\n' % tag
if not toc_text:
toc_text = heading
self.toc.new_entry(toc_text, self.cont_filename)
self.new_part()
def insert_file(self, name, in_spine = False, guide_title = None,
guide_type = None, arcname = None):
'''Include an external file into the ebook. By default, it will
be added to the archive under its basename; the argument
"arcname" can be used to specify a different name.'''
if not arcname:
arcname = os.path.basename(name)
self.opf.filelist.append(_Fileinfo(arcname, in_spine, guide_title,
guide_type))
self.epub_f.write(name, arcname)
def add_file(self, arcname, str_or_bytes, in_spine = False,
guide_title = None, guide_type = None):
'''Add the string or bytes instance str_or_bytes to the archive
under the name arcname.'''
self.opf.filelist.append(_Fileinfo(arcname, in_spine, guide_title,
guide_type))
self.epub_f.writestr(arcname, str_or_bytes)
def false_heading(self, elem):
'''Handle a "false heading", i.e., text that appears in heading
tags in the source even though it is not a chapter heading.'''
elem.attrs['class'] = 'getebook-false-h'
elem.tag = 'p'
self.handle_elem(elem)
def _heading(self, elem):
'''Write a heading.'''
# Handle paragraph heading if we have one waiting (see the
# par_heading method). We don\'t use _handle_par_h here because
# we merge it with the subsequent proper heading.
try:
par_h = self.par_h
del self.par_h
except AttributeError:
toc_text = elem.text
else:
# There is a waiting paragraph heading, we merge it with the
# new heading.
toc_text = par_h.text + '. ' + elem.text
par_h.tag = 'div'
par_h.attrs['class'] = 'getebook-small-h'
elem.children.insert(0, par_h)
# Set the class attribute value.
elem.attrs['class'] = 'getebook-chapter-h'
self.toc.new_entry(toc_text, self.cont_filename)
# Add heading to the epub.
tag = 'h%d' % min(self.toc.depth, 6)
self.content += _make_starttag(tag, elem.attrs)
for elem in elem.children:
self.handle_elem(elem)
self.content += '</%s>\n' % tag
def par_heading(self, elem):
'''Handle a "paragraph heading", i.e., a chaper heading or part
of a chapter heading inside paragraph tags. If it is immediately
followed by a heading, they will be merged into one.'''
self.par_h = elem
def _handle_par_h(self):
'Check if there is a waiting paragraph heading and handle it.'
try:
self._heading(self.par_h)
except AttributeError:
pass
def handle_elem(self, elem):
'Handle html element as supplied by getebook.EbookParser.'
try:
tag = elem.tag
except AttributeError:
# elem should be a string
is_string = True
tag = None
else:
is_string = False
if tag in getebook._headings:
self._heading(elem)<|fim▁hole|> self._heading(self.par_h)
except AttributeError:
pass
if is_string:
self.content += elem
elif tag == 'br':
self.content += '<br />\n'
elif tag == 'img':
self.content += self._handle_image(elem.attrs) + '\n'
elif tag == 'a' or tag == 'noscript':
# Ignore tag, just write child elements
for child in elem.children:
self.handle_elem(child)
else:
self.content += _make_starttag(tag, elem.attrs)
for child in elem.children:
self.handle_elem(child)
self.content += '</%s>' % tag
if tag == 'p':
self.content += '\n'
def _handle_image(self, attrs):
'Returns the alt text of an image tag.'
try:
return attrs['alt']
except KeyError:
return ''
def new_part(self):
'''Begin a new part of the epub. Write the current html document
to the archive and begin a new one.'''
# Handle waiting par_h (see par_heading)
try:
self._heading(self.par_h)
except AttributeError:
pass
if self.content:
html = self._html.format(self.title, self.content)
self.epub_f.writestr(self.cont_filename, html)
self.part_no += 1
self.content = ''
self.cont_filename = 'part%03d.html' % self.part_no
self.opf.filelist.append(_Fileinfo(self.cont_filename))
def finalize(self):
'Complete and close the epub file.'
# Handle waiting par_h (see par_heading)
if self._finalized:
# Avoid finalizing twice. Otherwise, calling finalize inside
# a with-block would lead to an exception when __exit__
# calls finalize again.
return
try:
self._heading(self.par_h)
except AttributeError:
pass
if self.content:
html = self._html.format(self.title, self.content)
self.epub_f.writestr(self.cont_filename, html)
self.opf.meta = [self.uid, self.lang, self.title] + self._authors
self.opf.meta += self.opt_meta.values()
self.epub_f.writestr('package.opf', self.opf.write_xml())
self.epub_f.writestr('toc.ncx',
self.toc.write_xml(self.uid, self.title, self._authors))
self.epub_f.writestr('style.css', self._style_css)
self.epub_f.close()
self._finalized = True<|fim▁end|> | else:
# Handle waiting par_h if necessary (see par_heading)
try: |
<|file_name|>sggl.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
# Copyright 2015 Dietrich Epp.
# This file is part of SGGL. SGGL is licensed under the terms of the
# 2-clause BSD license. For more information, see LICENSE.txt.
import glgen.__main__<|fim▁hole|><|fim▁end|> | glgen.__main__.main() |
<|file_name|>submit-queue-batch.go<|end_file_name|><|fim▁begin|>/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package mungers
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/golang/glog"
githubapi "github.com/google/go-github/github"
"k8s.io/contrib/mungegithub/github"
)
// xref k8s.io/test-infra/prow/cmd/deck/jobs.go
type prowJob struct {
Type string `json:"type"`
Repo string `json:"repo"`
Refs string `json:"refs"`
State string `json:"state"`
Context string `json:"context"`
}
type prowJobs []prowJob
// getJobs reads job information as JSON from a given URL.
func getJobs(url string) (prowJobs, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
jobs := prowJobs{}
err = json.Unmarshal(body, &jobs)
if err != nil {
return nil, err
}
return jobs, nil
}
func (j prowJobs) filter(pred func(prowJob) bool) prowJobs {
out := prowJobs{}
for _, job := range j {
if pred(job) {
out = append(out, job)
}
}
return out
}
func (j prowJobs) repo(repo string) prowJobs {
return j.filter(func(job prowJob) bool { return job.Repo == repo })
}
func (j prowJobs) batch() prowJobs {
return j.filter(func(job prowJob) bool { return job.Type == "batch" })
}
func (j prowJobs) successful() prowJobs {
return j.filter(func(job prowJob) bool { return job.State == "success" })
}
func (j prowJobs) firstUnfinished() *prowJob {
for _, job := range j {
if job.State == "triggered" || job.State == "pending" {
return &job
}
}
return nil
}
type batchPull struct {
Number int
Sha string
}
// Batch represents a specific merge state:
// a base branch and SHA, and the SHAs of each PR merged into it.
type Batch struct {
BaseName string
BaseSha string
Pulls []batchPull
}
func (b *Batch) String() string {
out := b.BaseName + ":" + b.BaseSha
for _, pull := range b.Pulls {
out += "," + strconv.Itoa(pull.Number) + ":" + pull.Sha
}
return out
}
// batchRefToBatch parses a string into a Batch.
// The input is a comma-separated list of colon-separated ref/sha pairs,
// like "master:abcdef0,123:f00d,456:f00f".
func batchRefToBatch(batchRef string) (Batch, error) {
batch := Batch{}
for i, ref := range strings.Split(batchRef, ",") {
parts := strings.Split(ref, ":")
if len(parts) != 2 {
return Batch{}, errors.New("bad batchref: " + batchRef)
}
if i == 0 {
batch.BaseName = parts[0]
batch.BaseSha = parts[1]
} else {
num, err := strconv.ParseInt(parts[0], 10, 32)
if err != nil {
return Batch{}, fmt.Errorf("bad batchref: %s (%v)", batchRef, err)
}
batch.Pulls = append(batch.Pulls, batchPull{int(num), parts[1]})
}
}
return batch, nil
}
// getCompleteBatches returns a list of Batches that passed all
// required tests.
func (sq *SubmitQueue) getCompleteBatches(jobs prowJobs) []Batch {
// for each batch specifier, a set of successful contexts
batchContexts := make(map[string]map[string]interface{})
for _, job := range jobs {
if batchContexts[job.Refs] == nil {
batchContexts[job.Refs] = make(map[string]interface{})
}
batchContexts[job.Refs][job.Context] = nil
}
batches := []Batch{}
for batchRef, contexts := range batchContexts {
match := true
// Did this succeed in all the contexts we want?
for _, ctx := range sq.RequiredStatusContexts {
if _, ok := contexts[ctx]; !ok {
match = false
}
}
for _, ctx := range sq.RequiredRetestContexts {
if _, ok := contexts[ctx]; !ok {
match = false
}
}
if match {
batch, err := batchRefToBatch(batchRef)
if err != nil {
continue
}
batches = append(batches, batch)
}
}
return batches
}
// batchIntersectsQueue returns whether at least one PR in the batch is queued.
func (sq *SubmitQueue) batchIntersectsQueue(batch Batch) bool {
sq.Lock()
defer sq.Unlock()
for _, pull := range batch.Pulls {
if _, ok := sq.githubE2EQueue[pull.Number]; ok {
return true
}
}
return false
}
// matchesCommit determines if the batch can be merged given some commits.
// That is, does it contain exactly:
// 1) the batch's BaseSha
// 2) (optional) merge commits for PRs in the batch
// 3) any merged PRs in the batch are sequential from the beginning
// The return value is the number of PRs already merged, and any errors.
func (b *Batch) matchesCommits(commits []*githubapi.RepositoryCommit) (int, error) {
if len(commits) == 0 {
return 0, errors.New("no commits")
}
shaToPR := make(map[string]int)
for _, pull := range b.Pulls {
shaToPR[pull.Sha] = pull.Number
}
matchedPRs := []int{}
// convert the list of commits into a DAG for easy following
dag := make(map[string]*githubapi.RepositoryCommit)
for _, commit := range commits {
dag[*commit.SHA] = commit
}
ref := *commits[0].SHA
for {
if ref == b.BaseSha {
break // found the base ref (condition #1)
}
commit, ok := dag[ref]
if !ok {
return 0, errors.New("ran out of commits (missing ref " + ref + ")")
}
message := ""
if commit.Commit != nil && commit.Commit.Message != nil {
// The actual commit message is buried a little oddly.
message = *commit.Commit.Message
}
if len(commit.Parents) == 2 && strings.HasPrefix(message, "Merge") {
// looks like a merge commit!
// first parent is the normal branch
ref = *commit.Parents[0].SHA
// second parent is the PR
pr, ok := shaToPR[*commit.Parents[1].SHA]
if !ok {
return 0, errors.New("Merge of something not in batch")
}
matchedPRs = append(matchedPRs, pr)
} else {
return 0, errors.New("Unknown non-merge commit " + ref)
}
}
// Now, ensure that the merged PRs are ordered correctly.
for i, pr := range matchedPRs {
if b.Pulls[len(matchedPRs)-1-i].Number != pr {
return 0, errors.New("Batch PRs merged out-of-order")
}
}
return len(matchedPRs), nil
}
// batchIsApplicable returns whether a successful batch result can be used--
// 1) some of the batch is still unmerged and in the queue.
// 2) the recent commits are the batch head ref or merges of batch PRs.
// 3) all unmerged PRs in the batch are still in the queue.
// The return value is the number of PRs already merged, and any errors.
func (sq *SubmitQueue) batchIsApplicable(batch Batch) (int, error) {
// batch must intersect the queue
if !sq.batchIntersectsQueue(batch) {
return 0, errors.New("batch has no PRs in Queue")
}
commits, err := sq.githubConfig.GetBranchCommits(batch.BaseName, 100)
if err != nil {
glog.Errorf("Error getting commits for batchIsApplicable: %v", err)
return 0, errors.New("failed to get branch commits: " + err.Error())
}
return batch.matchesCommits(commits)
}
func (sq *SubmitQueue) handleGithubE2EBatchMerge() {
repo := sq.githubConfig.Org + "/" + sq.githubConfig.Project
for range time.Tick(1 * time.Minute) {
allJobs, err := getJobs(sq.BatchURL)
if err != nil {
glog.Errorf("Error reading batch jobs from Prow URL %v: %v", sq.BatchURL, err)
continue
}
batchJobs := allJobs.batch().repo(repo)
jobs := batchJobs.successful()
batches := sq.getCompleteBatches(jobs)
batchErrors := make(map[string]string)
for _, batch := range batches {
_, err := sq.batchIsApplicable(batch)
if err != nil {
batchErrors[batch.String()] = err.Error()
continue
}
sq.doBatchMerge(batch)
}
sq.batchStatus.Error = batchErrors
sq.batchStatus.Running = batchJobs.firstUnfinished()
}
}
// doBatchMerge iteratively merges PRs in the batch if possible.
// If you modify this, consider modifying doGithubE2EAndMerge too.
func (sq *SubmitQueue) doBatchMerge(batch Batch) {
sq.mergeLock.Lock()
defer sq.mergeLock.Unlock()
// Test again inside the merge lock, in case some other merge snuck in.
match, err := sq.batchIsApplicable(batch)
if err != nil {
glog.Errorf("unexpected! batchIsApplicable failed after success %v", err)
return
}<|fim▁hole|> if !sq.e2eStable(true) {
return
}
glog.Infof("merging batch: %s", batch)
prs := []*github.MungeObject{}
// Check entire batch's preconditions first.
for _, pull := range batch.Pulls[match:] {
obj, err := sq.githubConfig.GetObject(pull.Number)
if err != nil {
glog.Errorf("error getting object for pr #%d: %v", pull.Number, err)
return
}
if sha, _, ok := obj.GetHeadAndBase(); !ok {
glog.Errorf("error getting pr #%d sha", pull.Number, err)
return
} else if sha != pull.Sha {
glog.Errorf("error: batch PR #%d HEAD changed: %s instead of %s",
sha, pull.Sha)
return
}
if !sq.validForMergeExt(obj, false) {
return
}
prs = append(prs, obj)
}
// Make the merge less confusing: describe the overall batch.
prStrings := []string{}
for _, pull := range batch.Pulls {
prStrings = append(prStrings, strconv.Itoa(pull.Number))
}
extra := fmt.Sprintf(" (batch tested with PRs %s)", strings.Join(prStrings, ", "))
// then merge each
for _, pr := range prs {
ok := sq.mergePullRequest(pr, mergedBatch, extra)
if !ok {
return
}
atomic.AddInt32(&sq.batchMerges, 1)
}
}<|fim▁end|> | |
<|file_name|>paypal.py<|end_file_name|><|fim▁begin|>import paypalrestsdk
import logging
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from settings import PAYPAL_MODE, PAYPAL_CLIENT_ID, PAYPAL_CLIENT_SECRET
def paypal_create(request):<|fim▁hole|> """
logging.basicConfig(level=logging.DEBUG)
paypalrestsdk.configure({
"mode": PAYPAL_MODE,
"client_id": PAYPAL_CLIENT_ID,
"client_secret": PAYPAL_CLIENT_SECRET })
payment = paypalrestsdk.Payment({
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"redirect_urls": {
"return_url": request.build_absolute_uri(reverse('paypal_execute')),
"cancel_url": request.build_absolute_uri(reverse('home page')) },
"transactions": [{
"item_list": {
"items": [{
"name": "name of your item 1",
"price": "10.00",
"currency": "GBP",
"quantity": 1,
"sku": "1"
}, {
"name": "name of your item 2",
"price": "10.00",
"currency": "GBP",
"quantity": 1,
"sku": "2"
}]
},
"amount": {
"total": "20.00",
"currency": "GBP"
},
"description": "purchase description"
}]
})
redirect_url = ""
if payment.create():
# Store payment id in user session
request.session['payment_id'] = payment.id
# Redirect the user to given approval url
for link in payment.links:
if link.method == "REDIRECT":
redirect_url = link.href
return HttpResponseRedirect(redirect_url)
else:
messages.error(request, 'We are sorry but something went wrong. We could not redirect you to Paypal.')
return HttpResponse('<p>We are sorry but something went wrong. We could not redirect you to Paypal.</p><p>'+str(payment.error)+'</p>')
#return HttpResponseRedirect(reverse('thank you'))
def paypal_execute(request):
"""
MyApp > Paypal > Execute a Payment
"""
payment_id = request.session['payment_id']
payer_id = request.GET['PayerID']
paypalrestsdk.configure({
"mode": PAYPAL_MODE,
"client_id": PAYPAL_CLIENT_ID,
"client_secret": PAYPAL_CLIENT_SECRET })
payment = paypalrestsdk.Payment.find(payment_id)
payment_name = payment.transactions[0].description
if payment.execute({"payer_id": payer_id}):
# the payment has been accepted
return HttpResponse('<p>the payment "'+payment_name+'" has been accepted</p>')
else:
# the payment is not valid
return HttpResponse('<p>We are sorry but something went wrong. </p><p>'+str(payment.error)+'</p>')<|fim▁end|> | """
MyApp > Paypal > Create a Payment |
<|file_name|>test_qgslayoutlegend.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsLayoutItemLegend.
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__author__ = '(C) 2017 by Nyall Dawson'
__date__ = '24/10/2017'
__copyright__ = 'Copyright 2017, The QGIS Project'
from qgis.PyQt.QtCore import QRectF, QDir
from qgis.PyQt.QtGui import QColor<|fim▁hole|>
from qgis.core import (QgsPrintLayout,
QgsLayoutItemLegend,
QgsLayoutItemMap,
QgsLayout,
QgsMapSettings,
QgsVectorLayer,
QgsMarkerSymbol,
QgsSingleSymbolRenderer,
QgsRectangle,
QgsProject,
QgsLayoutObject,
QgsProperty,
QgsLayoutMeasurement,
QgsLayoutItem,
QgsLayoutPoint,
QgsLayoutSize,
QgsExpression,
QgsMapLayerLegendUtils,
QgsLegendStyle,
QgsFontUtils,
QgsLineSymbol,
QgsMapThemeCollection,
QgsCategorizedSymbolRenderer,
QgsRendererCategory,
QgsFillSymbol,
QgsApplication)
from qgis.testing import (start_app,
unittest
)
from utilities import unitTestDataPath
from qgslayoutchecker import QgsLayoutChecker
import os
from time import sleep
from test_qgslayoutitem import LayoutItemTestCase
start_app()
TEST_DATA_DIR = unitTestDataPath()
class TestQgsLayoutItemLegend(unittest.TestCase, LayoutItemTestCase):
@classmethod
def setUpClass(cls):
cls.item_class = QgsLayoutItemLegend
def setUp(self):
self.report = "<h1>Python QgsLayoutItemLegend Tests</h1>\n"
def tearDown(self):
report_file_path = "%s/qgistest.html" % QDir.tempPath()
with open(report_file_path, 'a') as report_file:
report_file.write(self.report)
def testInitialSizeSymbolMapUnits(self):
"""Test initial size of legend with a symbol size in map units"""
QgsProject.instance().removeAllMapLayers()
point_path = os.path.join(TEST_DATA_DIR, 'points.shp')
point_layer = QgsVectorLayer(point_path, 'points', 'ogr')
QgsProject.instance().clear()
QgsProject.instance().addMapLayers([point_layer])
marker_symbol = QgsMarkerSymbol.createSimple(
{'color': '#ff0000', 'outline_style': 'no', 'size': '5', 'size_unit': 'MapUnit'})
point_layer.setRenderer(QgsSingleSymbolRenderer(marker_symbol))
s = QgsMapSettings()
s.setLayers([point_layer])
layout = QgsLayout(QgsProject.instance())
layout.initializeDefaults()
map = QgsLayoutItemMap(layout)
map.attemptSetSceneRect(QRectF(20, 20, 80, 80))
map.setFrameEnabled(True)
map.setLayers([point_layer])
layout.addLayoutItem(map)
map.setExtent(point_layer.extent())
legend = QgsLayoutItemLegend(layout)
legend.setTitle("Legend")
legend.attemptSetSceneRect(QRectF(120, 20, 80, 80))
legend.setFrameEnabled(True)
legend.setFrameStrokeWidth(QgsLayoutMeasurement(2))
legend.setBackgroundColor(QColor(200, 200, 200))
legend.setTitle('')
layout.addLayoutItem(legend)
legend.setLinkedMap(map)
checker = QgsLayoutChecker(
'composer_legend_mapunits', layout)
checker.setControlPathPrefix("composer_legend")
result, message = checker.testLayout()
self.report += checker.report()
self.assertTrue(result, message)
# resize with non-top-left reference point
legend.setResizeToContents(False)
legend.setReferencePoint(QgsLayoutItem.LowerRight)
legend.attemptMove(QgsLayoutPoint(120, 90))
legend.attemptResize(QgsLayoutSize(50, 60))
self.assertEqual(legend.positionWithUnits().x(), 120.0)
self.assertEqual(legend.positionWithUnits().y(), 90.0)
self.assertAlmostEqual(legend.pos().x(), 70, -1)
self.assertAlmostEqual(legend.pos().y(), 30, -1)
legend.setResizeToContents(True)
legend.updateLegend()
self.assertEqual(legend.positionWithUnits().x(), 120.0)
self.assertEqual(legend.positionWithUnits().y(), 90.0)
self.assertAlmostEqual(legend.pos().x(), 91, -1)
self.assertAlmostEqual(legend.pos().y(), 71, -1)
QgsProject.instance().removeMapLayers([point_layer.id()])
def testResizeWithMapContent(self):
"""Test test legend resizes to match map content"""
point_path = os.path.join(TEST_DATA_DIR, 'points.shp')
point_layer = QgsVectorLayer(point_path, 'points', 'ogr')
QgsProject.instance().addMapLayers([point_layer])
s = QgsMapSettings()
s.setLayers([point_layer])
layout = QgsLayout(QgsProject.instance())
layout.initializeDefaults()
map = QgsLayoutItemMap(layout)
map.attemptSetSceneRect(QRectF(20, 20, 80, 80))
map.setFrameEnabled(True)
map.setLayers([point_layer])
layout.addLayoutItem(map)
map.setExtent(point_layer.extent())
legend = QgsLayoutItemLegend(layout)
legend.setTitle("Legend")
legend.attemptSetSceneRect(QRectF(120, 20, 80, 80))
legend.setFrameEnabled(True)
legend.setFrameStrokeWidth(QgsLayoutMeasurement(2))
legend.setBackgroundColor(QColor(200, 200, 200))
legend.setTitle('')
legend.setLegendFilterByMapEnabled(True)
layout.addLayoutItem(legend)
legend.setLinkedMap(map)
map.setExtent(QgsRectangle(-102.51, 41.16, -102.36, 41.30))
checker = QgsLayoutChecker(
'composer_legend_size_content', layout)
checker.setControlPathPrefix("composer_legend")
result, message = checker.testLayout()
self.report += checker.report()
self.assertTrue(result, message)
QgsProject.instance().removeMapLayers([point_layer.id()])
def testResizeWithMapContentNoDoublePaint(self):
"""Test test legend resizes to match map content"""
poly_path = os.path.join(TEST_DATA_DIR, 'polys.shp')
poly_layer = QgsVectorLayer(poly_path, 'polys', 'ogr')
p = QgsProject()
p.addMapLayers([poly_layer])
fill_symbol = QgsFillSymbol.createSimple({'color': '255,0,0,125', 'outline_style': 'no'})
poly_layer.setRenderer(QgsSingleSymbolRenderer(fill_symbol))
s = QgsMapSettings()
s.setLayers([poly_layer])
layout = QgsLayout(p)
layout.initializeDefaults()
map = QgsLayoutItemMap(layout)
map.attemptSetSceneRect(QRectF(20, 20, 80, 80))
map.setFrameEnabled(True)
map.setLayers([poly_layer])
layout.addLayoutItem(map)
map.setExtent(poly_layer.extent())
legend = QgsLayoutItemLegend(layout)
legend.setTitle("Legend")
legend.attemptSetSceneRect(QRectF(120, 20, 80, 80))
legend.setFrameEnabled(True)
legend.setFrameStrokeWidth(QgsLayoutMeasurement(2))
legend.setBackgroundEnabled(False)
legend.setTitle('')
layout.addLayoutItem(legend)
legend.setLinkedMap(map)
map.setExtent(QgsRectangle(-102.51, 41.16, -102.36, 41.30))
checker = QgsLayoutChecker(
'composer_legend_size_content_no_double_paint', layout)
checker.setControlPathPrefix("composer_legend")
result, message = checker.testLayout()
self.report += checker.report()
self.assertTrue(result, message)
def testResizeDisabled(self):
"""Test that test legend does not resize if auto size is disabled"""
point_path = os.path.join(TEST_DATA_DIR, 'points.shp')
point_layer = QgsVectorLayer(point_path, 'points', 'ogr')
QgsProject.instance().addMapLayers([point_layer])
s = QgsMapSettings()
s.setLayers([point_layer])
layout = QgsLayout(QgsProject.instance())
layout.initializeDefaults()
map = QgsLayoutItemMap(layout)
map.attemptSetSceneRect(QRectF(20, 20, 80, 80))
map.setFrameEnabled(True)
map.setLayers([point_layer])
layout.addLayoutItem(map)
map.setExtent(point_layer.extent())
legend = QgsLayoutItemLegend(layout)
legend.setTitle("Legend")
legend.attemptSetSceneRect(QRectF(120, 20, 80, 80))
legend.setFrameEnabled(True)
legend.setFrameStrokeWidth(QgsLayoutMeasurement(2))
legend.setBackgroundColor(QColor(200, 200, 200))
legend.setTitle('')
legend.setLegendFilterByMapEnabled(True)
# disable auto resizing
legend.setResizeToContents(False)
layout.addLayoutItem(legend)
legend.setLinkedMap(map)
map.setExtent(QgsRectangle(-102.51, 41.16, -102.36, 41.30))
checker = QgsLayoutChecker(
'composer_legend_noresize', layout)
checker.setControlPathPrefix("composer_legend")
result, message = checker.testLayout()
self.report += checker.report()
self.assertTrue(result, message)
QgsProject.instance().removeMapLayers([point_layer.id()])
def testResizeDisabledCrop(self):
"""Test that if legend resizing is disabled, and legend is too small, then content is cropped"""
point_path = os.path.join(TEST_DATA_DIR, 'points.shp')
point_layer = QgsVectorLayer(point_path, 'points', 'ogr')
QgsProject.instance().addMapLayers([point_layer])
s = QgsMapSettings()
s.setLayers([point_layer])
layout = QgsLayout(QgsProject.instance())
layout.initializeDefaults()
map = QgsLayoutItemMap(layout)
map.attemptSetSceneRect(QRectF(20, 20, 80, 80))
map.setFrameEnabled(True)
map.setLayers([point_layer])
layout.addLayoutItem(map)
map.setExtent(point_layer.extent())
legend = QgsLayoutItemLegend(layout)
legend.setTitle("Legend")
legend.attemptSetSceneRect(QRectF(120, 20, 20, 20))
legend.setFrameEnabled(True)
legend.setFrameStrokeWidth(QgsLayoutMeasurement(2))
legend.setBackgroundColor(QColor(200, 200, 200))
legend.setTitle('')
legend.setLegendFilterByMapEnabled(True)
# disable auto resizing
legend.setResizeToContents(False)
layout.addLayoutItem(legend)
legend.setLinkedMap(map)
map.setExtent(QgsRectangle(-102.51, 41.16, -102.36, 41.30))
checker = QgsLayoutChecker(
'composer_legend_noresize_crop', layout)
checker.setControlPathPrefix("composer_legend")
result, message = checker.testLayout()
self.report += checker.report()
self.assertTrue(result, message)
QgsProject.instance().removeMapLayers([point_layer.id()])
def testDataDefinedTitle(self):
layout = QgsLayout(QgsProject.instance())
layout.initializeDefaults()
legend = QgsLayoutItemLegend(layout)
layout.addLayoutItem(legend)
legend.setTitle('original')
self.assertEqual(legend.title(), 'original')
self.assertEqual(legend.legendSettings().title(), 'original')
legend.dataDefinedProperties().setProperty(QgsLayoutObject.LegendTitle, QgsProperty.fromExpression("'new'"))
legend.refreshDataDefinedProperty()
self.assertEqual(legend.title(), 'original')
self.assertEqual(legend.legendSettings().title(), 'new')
def testDataDefinedColumnCount(self):
layout = QgsLayout(QgsProject.instance())
layout.initializeDefaults()
legend = QgsLayoutItemLegend(layout)
legend.setTitle("Legend")
layout.addLayoutItem(legend)
legend.setColumnCount(2)
self.assertEqual(legend.columnCount(), 2)
self.assertEqual(legend.legendSettings().columnCount(), 2)
legend.dataDefinedProperties().setProperty(QgsLayoutObject.LegendColumnCount, QgsProperty.fromExpression("5"))
legend.refreshDataDefinedProperty()
self.assertEqual(legend.columnCount(), 2)
self.assertEqual(legend.legendSettings().columnCount(), 5)
def testLegendScopeVariables(self):
layout = QgsLayout(QgsProject.instance())
layout.initializeDefaults()
legend = QgsLayoutItemLegend(layout)
legend.setTitle("Legend")
layout.addLayoutItem(legend)
legend.setColumnCount(2)
legend.setWrapString('d')
legend.setLegendFilterOutAtlas(True)
expc = legend.createExpressionContext()
exp1 = QgsExpression("@legend_title")
self.assertEqual(exp1.evaluate(expc), "Legend")
exp2 = QgsExpression("@legend_column_count")
self.assertEqual(exp2.evaluate(expc), 2)
exp3 = QgsExpression("@legend_wrap_string")
self.assertEqual(exp3.evaluate(expc), 'd')
exp4 = QgsExpression("@legend_split_layers")
self.assertEqual(exp4.evaluate(expc), False)
exp5 = QgsExpression("@legend_filter_out_atlas")
self.assertEqual(exp5.evaluate(expc), True)
map = QgsLayoutItemMap(layout)
map.attemptSetSceneRect(QRectF(20, 20, 80, 80))
map.setFrameEnabled(True)
map.setExtent(QgsRectangle(781662.375, 3339523.125, 793062.375, 3345223.125))
layout.addLayoutItem(map)
map.setScale(15000)
legend.setLinkedMap(map)
expc2 = legend.createExpressionContext()
exp6 = QgsExpression("@map_scale")
self.assertAlmostEqual(exp6.evaluate(expc2), 15000, 2)
def testExpressionInText(self):
"""Test expressions embedded in legend node text"""
point_path = os.path.join(TEST_DATA_DIR, 'points.shp')
point_layer = QgsVectorLayer(point_path, 'points', 'ogr')
layout = QgsPrintLayout(QgsProject.instance())
layout.setName('LAYOUT')
layout.initializeDefaults()
map = QgsLayoutItemMap(layout)
map.attemptSetSceneRect(QRectF(20, 20, 80, 80))
map.setFrameEnabled(True)
map.setLayers([point_layer])
layout.addLayoutItem(map)
map.setExtent(point_layer.extent())
legend = QgsLayoutItemLegend(layout)
legend.setTitle("Legend")
legend.attemptSetSceneRect(QRectF(120, 20, 100, 100))
legend.setFrameEnabled(True)
legend.setFrameStrokeWidth(QgsLayoutMeasurement(2))
legend.setBackgroundColor(QColor(200, 200, 200))
legend.setTitle('')
legend.setLegendFilterByMapEnabled(False)
legend.setStyleFont(QgsLegendStyle.Title, QgsFontUtils.getStandardTestFont('Bold', 16))
legend.setStyleFont(QgsLegendStyle.Group, QgsFontUtils.getStandardTestFont('Bold', 16))
legend.setStyleFont(QgsLegendStyle.Subgroup, QgsFontUtils.getStandardTestFont('Bold', 16))
legend.setStyleFont(QgsLegendStyle.Symbol, QgsFontUtils.getStandardTestFont('Bold', 16))
legend.setStyleFont(QgsLegendStyle.SymbolLabel, QgsFontUtils.getStandardTestFont('Bold', 16))
legend.setAutoUpdateModel(False)
QgsProject.instance().addMapLayers([point_layer])
s = QgsMapSettings()
s.setLayers([point_layer])
group = legend.model().rootGroup().addGroup("Group [% 1 + 5 %] [% @layout_name %]")
layer_tree_layer = group.addLayer(point_layer)
layer_tree_layer.setCustomProperty("legend/title-label",
'bbbb [% 1+2 %] xx [% @layout_name %] [% @layer_name %]')
QgsMapLayerLegendUtils.setLegendNodeUserLabel(layer_tree_layer, 0, 'xxxx')
legend.model().refreshLayerLegend(layer_tree_layer)
legend.model().layerLegendNodes(layer_tree_layer)[0].setUserLabel(
'bbbb [% 1+2 %] xx [% @layout_name %] [% @layer_name %]')
layout.addLayoutItem(legend)
legend.setLinkedMap(map)
map.setExtent(QgsRectangle(-102.51, 41.16, -102.36, 41.30))
checker = QgsLayoutChecker(
'composer_legend_expressions', layout)
checker.setControlPathPrefix("composer_legend")
result, message = checker.testLayout()
self.report += checker.report()
self.assertTrue(result, message)
QgsProject.instance().removeMapLayers([point_layer.id()])
def testSymbolExpressions(self):
"Test expressions embedded in legend node text"
QgsProject.instance().clear()
point_path = os.path.join(TEST_DATA_DIR, 'points.shp')
point_layer = QgsVectorLayer(point_path, 'points', 'ogr')
layout = QgsPrintLayout(QgsProject.instance())
layout.initializeDefaults()
map = QgsLayoutItemMap(layout)
map.setLayers([point_layer])
layout.addLayoutItem(map)
map.setExtent(point_layer.extent())
legend = QgsLayoutItemLegend(layout)
layer = QgsProject.instance().addMapLayer(point_layer)
legendlayer = legend.model().rootGroup().addLayer(point_layer)
counterTask = point_layer.countSymbolFeatures()
counterTask.waitForFinished()
legend.model().refreshLayerLegend(legendlayer)
legendnodes = legend.model().layerLegendNodes(legendlayer)
legendnodes[0].setUserLabel('[% @symbol_id %]')
legendnodes[1].setUserLabel('[% @symbol_count %]')
legendnodes[2].setUserLabel('[% sum("Pilots") %]')
label1 = legendnodes[0].evaluateLabel()
label2 = legendnodes[1].evaluateLabel()
label3 = legendnodes[2].evaluateLabel()
self.assertEqual(label1, '0')
# self.assertEqual(label2, '5')
# self.assertEqual(label3, '12')
legendlayer.setLabelExpression("Concat(@symbol_label, @symbol_id)")
label1 = legendnodes[0].evaluateLabel()
label2 = legendnodes[1].evaluateLabel()
label3 = legendnodes[2].evaluateLabel()
self.assertEqual(label1, ' @symbol_id 0')
# self.assertEqual(label2, '@symbol_count 1')
# self.assertEqual(label3, 'sum("Pilots") 2')
QgsProject.instance().clear()
def testSymbolExpressionRender(self):
"""Test expressions embedded in legend node text"""
point_path = os.path.join(TEST_DATA_DIR, 'points.shp')
point_layer = QgsVectorLayer(point_path, 'points', 'ogr')
layout = QgsPrintLayout(QgsProject.instance())
layout.setName('LAYOUT')
layout.initializeDefaults()
map = QgsLayoutItemMap(layout)
map.attemptSetSceneRect(QRectF(20, 20, 80, 80))
map.setFrameEnabled(True)
map.setLayers([point_layer])
layout.addLayoutItem(map)
map.setExtent(point_layer.extent())
legend = QgsLayoutItemLegend(layout)
legend.setTitle("Legend")
legend.attemptSetSceneRect(QRectF(120, 20, 100, 100))
legend.setFrameEnabled(True)
legend.setFrameStrokeWidth(QgsLayoutMeasurement(2))
legend.setBackgroundColor(QColor(200, 200, 200))
legend.setTitle('')
legend.setLegendFilterByMapEnabled(False)
legend.setStyleFont(QgsLegendStyle.Title, QgsFontUtils.getStandardTestFont('Bold', 16))
legend.setStyleFont(QgsLegendStyle.Group, QgsFontUtils.getStandardTestFont('Bold', 16))
legend.setStyleFont(QgsLegendStyle.Subgroup, QgsFontUtils.getStandardTestFont('Bold', 16))
legend.setStyleFont(QgsLegendStyle.Symbol, QgsFontUtils.getStandardTestFont('Bold', 16))
legend.setStyleFont(QgsLegendStyle.SymbolLabel, QgsFontUtils.getStandardTestFont('Bold', 16))
legend.setAutoUpdateModel(False)
QgsProject.instance().addMapLayers([point_layer])
s = QgsMapSettings()
s.setLayers([point_layer])
group = legend.model().rootGroup().addGroup("Group [% 1 + 5 %] [% @layout_name %]")
layer_tree_layer = group.addLayer(point_layer)
counterTask = point_layer.countSymbolFeatures()
counterTask.waitForFinished()
layer_tree_layer.setCustomProperty("legend/title-label",
'bbbb [% 1+2 %] xx [% @layout_name %] [% @layer_name %]')
QgsMapLayerLegendUtils.setLegendNodeUserLabel(layer_tree_layer, 0, 'xxxx')
legend.model().refreshLayerLegend(layer_tree_layer)
layer_tree_layer.setLabelExpression('Concat(@symbol_id, @symbol_label, count("Class"))')
legend.model().layerLegendNodes(layer_tree_layer)[0].setUserLabel(' sym 1')
legend.model().layerLegendNodes(layer_tree_layer)[1].setUserLabel('[%@symbol_count %]')
legend.model().layerLegendNodes(layer_tree_layer)[2].setUserLabel('[% count("Class") %]')
layout.addLayoutItem(legend)
legend.setLinkedMap(map)
legend.updateLegend()
print(layer_tree_layer.labelExpression())
map.setExtent(QgsRectangle(-102.51, 41.16, -102.36, 41.30))
checker = QgsLayoutChecker(
'composer_legend_symbol_expression', layout)
checker.setControlPathPrefix("composer_legend")
sleep(4)
result, message = checker.testLayout()
self.assertTrue(result, message)
QgsProject.instance().removeMapLayers([point_layer.id()])
def testThemes(self):
layout = QgsPrintLayout(QgsProject.instance())
layout.setName('LAYOUT')
map = QgsLayoutItemMap(layout)
layout.addLayoutItem(map)
legend = QgsLayoutItemLegend(layout)
self.assertFalse(legend.themeName())
legend.setLinkedMap(map)
self.assertFalse(legend.themeName())
map.setFollowVisibilityPresetName('theme1')
map.setFollowVisibilityPreset(True)
self.assertEqual(legend.themeName(), 'theme1')
map.setFollowVisibilityPresetName('theme2')
self.assertEqual(legend.themeName(), 'theme2')
map.setFollowVisibilityPreset(False)
self.assertFalse(legend.themeName())
# with theme set before linking map
map2 = QgsLayoutItemMap(layout)
map2.setFollowVisibilityPresetName('theme3')
map2.setFollowVisibilityPreset(True)
legend.setLinkedMap(map2)
self.assertEqual(legend.themeName(), 'theme3')
map2.setFollowVisibilityPresetName('theme2')
self.assertEqual(legend.themeName(), 'theme2')
# replace with map with no theme
map3 = QgsLayoutItemMap(layout)
legend.setLinkedMap(map3)
self.assertFalse(legend.themeName())
def testLegendRenderWithMapTheme(self):
"""Test rendering legends linked to map themes"""
QgsProject.instance().removeAllMapLayers()
point_path = os.path.join(TEST_DATA_DIR, 'points.shp')
point_layer = QgsVectorLayer(point_path, 'points', 'ogr')
line_path = os.path.join(TEST_DATA_DIR, 'lines.shp')
line_layer = QgsVectorLayer(line_path, 'lines', 'ogr')
QgsProject.instance().clear()
QgsProject.instance().addMapLayers([point_layer, line_layer])
marker_symbol = QgsMarkerSymbol.createSimple({'color': '#ff0000', 'outline_style': 'no', 'size': '5'})
point_layer.setRenderer(QgsSingleSymbolRenderer(marker_symbol))
point_layer.styleManager().addStyleFromLayer("red")
line_symbol = QgsLineSymbol.createSimple({'color': '#ff0000', 'line_width': '2'})
line_layer.setRenderer(QgsSingleSymbolRenderer(line_symbol))
line_layer.styleManager().addStyleFromLayer("red")
red_record = QgsMapThemeCollection.MapThemeRecord()
point_red_record = QgsMapThemeCollection.MapThemeLayerRecord(point_layer)
point_red_record.usingCurrentStyle = True
point_red_record.currentStyle = 'red'
red_record.addLayerRecord(point_red_record)
line_red_record = QgsMapThemeCollection.MapThemeLayerRecord(line_layer)
line_red_record.usingCurrentStyle = True
line_red_record.currentStyle = 'red'
red_record.addLayerRecord(line_red_record)
QgsProject.instance().mapThemeCollection().insert('red', red_record)
marker_symbol1 = QgsMarkerSymbol.createSimple({'color': '#0000ff', 'outline_style': 'no', 'size': '5'})
marker_symbol2 = QgsMarkerSymbol.createSimple(
{'color': '#0000ff', 'name': 'diamond', 'outline_style': 'no', 'size': '5'})
marker_symbol3 = QgsMarkerSymbol.createSimple(
{'color': '#0000ff', 'name': 'rectangle', 'outline_style': 'no', 'size': '5'})
point_layer.setRenderer(QgsCategorizedSymbolRenderer('Class', [QgsRendererCategory('B52', marker_symbol1, ''),
QgsRendererCategory('Biplane', marker_symbol2,
''),
QgsRendererCategory('Jet', marker_symbol3, ''),
]))
point_layer.styleManager().addStyleFromLayer("blue")
line_symbol = QgsLineSymbol.createSimple({'color': '#0000ff', 'line_width': '2'})
line_layer.setRenderer(QgsSingleSymbolRenderer(line_symbol))
line_layer.styleManager().addStyleFromLayer("blue")
blue_record = QgsMapThemeCollection.MapThemeRecord()
point_blue_record = QgsMapThemeCollection.MapThemeLayerRecord(point_layer)
point_blue_record.usingCurrentStyle = True
point_blue_record.currentStyle = 'blue'
blue_record.addLayerRecord(point_blue_record)
line_blue_record = QgsMapThemeCollection.MapThemeLayerRecord(line_layer)
line_blue_record.usingCurrentStyle = True
line_blue_record.currentStyle = 'blue'
blue_record.addLayerRecord(line_blue_record)
QgsProject.instance().mapThemeCollection().insert('blue', blue_record)
layout = QgsLayout(QgsProject.instance())
layout.initializeDefaults()
map1 = QgsLayoutItemMap(layout)
map1.attemptSetSceneRect(QRectF(20, 20, 80, 80))
map1.setFrameEnabled(True)
map1.setLayers([point_layer, line_layer])
layout.addLayoutItem(map1)
map1.setExtent(point_layer.extent())
map1.setFollowVisibilityPreset(True)
map1.setFollowVisibilityPresetName('red')
map2 = QgsLayoutItemMap(layout)
map2.attemptSetSceneRect(QRectF(20, 120, 80, 80))
map2.setFrameEnabled(True)
map2.setLayers([point_layer, line_layer])
layout.addLayoutItem(map2)
map2.setExtent(point_layer.extent())
map2.setFollowVisibilityPreset(True)
map2.setFollowVisibilityPresetName('blue')
legend = QgsLayoutItemLegend(layout)
legend.setTitle("Legend")
legend.attemptSetSceneRect(QRectF(120, 20, 80, 80))
legend.setFrameEnabled(True)
legend.setFrameStrokeWidth(QgsLayoutMeasurement(2))
legend.setBackgroundColor(QColor(200, 200, 200))
legend.setTitle('')
layout.addLayoutItem(legend)
legend.setLinkedMap(map1)
legend2 = QgsLayoutItemLegend(layout)
legend2.setTitle("Legend")
legend2.attemptSetSceneRect(QRectF(120, 120, 80, 80))
legend2.setFrameEnabled(True)
legend2.setFrameStrokeWidth(QgsLayoutMeasurement(2))
legend2.setBackgroundColor(QColor(200, 200, 200))
legend2.setTitle('')
layout.addLayoutItem(legend2)
legend2.setLinkedMap(map2)
checker = QgsLayoutChecker(
'composer_legend_theme', layout)
checker.setControlPathPrefix("composer_legend")
result, message = checker.testLayout()
self.report += checker.report()
self.assertTrue(result, message)
QgsProject.instance().clear()
if __name__ == '__main__':
unittest.main()<|fim▁end|> | |
<|file_name|>mount.go<|end_file_name|><|fim▁begin|>/*
Copyright 2014 The Kubernetes Authors.
<|fim▁hole|>Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// TODO(thockin): This whole pkg is pretty linux-centric. As soon as we have
// an alternate platform, we will need to abstract further.
package mount
import (
"os"
"path/filepath"
"strings"
)
type FileType string
const (
// Default mount command if mounter path is not specified
defaultMountCommand = "mount"
MountsInGlobalPDPath = "mounts"
FileTypeDirectory FileType = "Directory"
FileTypeFile FileType = "File"
FileTypeSocket FileType = "Socket"
FileTypeCharDev FileType = "CharDevice"
FileTypeBlockDev FileType = "BlockDevice"
)
type Interface interface {
// Mount mounts source to target as fstype with given options.
Mount(source string, target string, fstype string, options []string) error
// Unmount unmounts given target.
Unmount(target string) error
// List returns a list of all mounted filesystems. This can be large.
// On some platforms, reading mounts is not guaranteed consistent (i.e.
// it could change between chunked reads). This is guaranteed to be
// consistent.
List() ([]MountPoint, error)
// IsMountPointMatch determines if the mountpoint matches the dir
IsMountPointMatch(mp MountPoint, dir string) bool
// IsNotMountPoint determines if a directory is a mountpoint.
// It should return ErrNotExist when the directory does not exist.
// IsNotMountPoint is more expensive than IsLikelyNotMountPoint.
// IsNotMountPoint detects bind mounts in linux.
// IsNotMountPoint enumerates all the mountpoints using List() and
// the list of mountpoints may be large, then it uses
// IsMountPointMatch to evaluate whether the directory is a mountpoint
IsNotMountPoint(file string) (bool, error)
// IsLikelyNotMountPoint uses heuristics to determine if a directory
// is a mountpoint.
// It should return ErrNotExist when the directory does not exist.
// IsLikelyNotMountPoint does NOT properly detect all mountpoint types
// most notably linux bind mounts.
IsLikelyNotMountPoint(file string) (bool, error)
// DeviceOpened determines if the device is in use elsewhere
// on the system, i.e. still mounted.
DeviceOpened(pathname string) (bool, error)
// PathIsDevice determines if a path is a device.
PathIsDevice(pathname string) (bool, error)
// GetDeviceNameFromMount finds the device name by checking the mount path
// to get the global mount path which matches its plugin directory
GetDeviceNameFromMount(mountPath, pluginDir string) (string, error)
// MakeRShared checks that given path is on a mount with 'rshared' mount
// propagation. If not, it bind-mounts the path as rshared.
MakeRShared(path string) error
// GetFileType checks for file/directory/socket/block/character devices.
// Will operate in the host mount namespace if kubelet is running in a container
GetFileType(pathname string) (FileType, error)
// MakeFile creates an empty file.
// Will operate in the host mount namespace if kubelet is running in a container
MakeFile(pathname string) error
// MakeDir creates a new directory.
// Will operate in the host mount namespace if kubelet is running in a container
MakeDir(pathname string) error
// ExistsPath checks whether the path exists.
// Will operate in the host mount namespace if kubelet is running in a container
ExistsPath(pathname string) bool
}
// Exec executes command where mount utilities are. This can be either the host,
// container where kubelet runs or even a remote pod with mount utilities.
// Usual pkg/util/exec interface is not used because kubelet.RunInContainer does
// not provide stdin/stdout/stderr streams.
type Exec interface {
// Run executes a command and returns its stdout + stderr combined in one
// stream.
Run(cmd string, args ...string) ([]byte, error)
}
// Compile-time check to ensure all Mounter implementations satisfy
// the mount interface
var _ Interface = &Mounter{}
// This represents a single line in /proc/mounts or /etc/fstab.
type MountPoint struct {
Device string
Path string
Type string
Opts []string
Freq int
Pass int
}
// SafeFormatAndMount probes a device to see if it is formatted.
// Namely it checks to see if a file system is present. If so it
// mounts it otherwise the device is formatted first then mounted.
type SafeFormatAndMount struct {
Interface
Exec
}
// FormatAndMount formats the given disk, if needed, and mounts it.
// That is if the disk is not formatted and it is not being mounted as
// read-only it will format it first then mount it. Otherwise, if the
// disk is already formatted or it is being mounted as read-only, it
// will be mounted without formatting.
func (mounter *SafeFormatAndMount) FormatAndMount(source string, target string, fstype string, options []string) error {
// Don't attempt to format if mounting as readonly. Go straight to mounting.
for _, option := range options {
if option == "ro" {
return mounter.Interface.Mount(source, target, fstype, options)
}
}
return mounter.formatAndMount(source, target, fstype, options)
}
// GetMountRefsByDev finds all references to the device provided
// by mountPath; returns a list of paths.
func GetMountRefsByDev(mounter Interface, mountPath string) ([]string, error) {
mps, err := mounter.List()
if err != nil {
return nil, err
}
slTarget, err := filepath.EvalSymlinks(mountPath)
if err != nil {
slTarget = mountPath
}
// Finding the device mounted to mountPath
diskDev := ""
for i := range mps {
if slTarget == mps[i].Path {
diskDev = mps[i].Device
break
}
}
// Find all references to the device.
var refs []string
for i := range mps {
if mps[i].Device == diskDev || mps[i].Device == slTarget {
if mps[i].Path != slTarget {
refs = append(refs, mps[i].Path)
}
}
}
return refs, nil
}
// GetDeviceNameFromMount: given a mnt point, find the device from /proc/mounts
// returns the device name, reference count, and error code
func GetDeviceNameFromMount(mounter Interface, mountPath string) (string, int, error) {
mps, err := mounter.List()
if err != nil {
return "", 0, err
}
// Find the device name.
// FIXME if multiple devices mounted on the same mount path, only the first one is returned
device := ""
// If mountPath is symlink, need get its target path.
slTarget, err := filepath.EvalSymlinks(mountPath)
if err != nil {
slTarget = mountPath
}
for i := range mps {
if mps[i].Path == slTarget {
device = mps[i].Device
break
}
}
// Find all references to the device.
refCount := 0
for i := range mps {
if mps[i].Device == device {
refCount++
}
}
return device, refCount, nil
}
// IsNotMountPoint determines if a directory is a mountpoint.
// It should return ErrNotExist when the directory does not exist.
// This method uses the List() of all mountpoints
// It is more extensive than IsLikelyNotMountPoint
// and it detects bind mounts in linux
func IsNotMountPoint(mounter Interface, file string) (bool, error) {
// IsLikelyNotMountPoint provides a quick check
// to determine whether file IS A mountpoint
notMnt, notMntErr := mounter.IsLikelyNotMountPoint(file)
if notMntErr != nil && os.IsPermission(notMntErr) {
// We were not allowed to do the simple stat() check, e.g. on NFS with
// root_squash. Fall back to /proc/mounts check below.
notMnt = true
notMntErr = nil
}
if notMntErr != nil {
return notMnt, notMntErr
}
// identified as mountpoint, so return this fact
if notMnt == false {
return notMnt, nil
}
// check all mountpoints since IsLikelyNotMountPoint
// is not reliable for some mountpoint types
mountPoints, mountPointsErr := mounter.List()
if mountPointsErr != nil {
return notMnt, mountPointsErr
}
for _, mp := range mountPoints {
if mounter.IsMountPointMatch(mp, file) {
notMnt = false
break
}
}
return notMnt, nil
}
// isBind detects whether a bind mount is being requested and makes the remount options to
// use in case of bind mount, due to the fact that bind mount doesn't respect mount options.
// The list equals:
// options - 'bind' + 'remount' (no duplicate)
func isBind(options []string) (bool, []string) {
bindRemountOpts := []string{"remount"}
bind := false
if len(options) != 0 {
for _, option := range options {
switch option {
case "bind":
bind = true
break
case "remount":
break
default:
bindRemountOpts = append(bindRemountOpts, option)
}
}
}
return bind, bindRemountOpts
}
// TODO: this is a workaround for the unmount device issue caused by gci mounter.
// In GCI cluster, if gci mounter is used for mounting, the container started by mounter
// script will cause additional mounts created in the container. Since these mounts are
// irrelavant to the original mounts, they should be not considered when checking the
// mount references. Current solution is to filter out those mount paths that contain
// the string of original mount path.
// Plan to work on better approach to solve this issue.
func HasMountRefs(mountPath string, mountRefs []string) bool {
count := 0
for _, ref := range mountRefs {
if !strings.Contains(ref, mountPath) {
count = count + 1
}
}
return count > 0
}<|fim▁end|> | |
<|file_name|>CCLabelTTF.cpp<|end_file_name|><|fim▁begin|>/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCLabelTTF.h"
#include "CCDirector.h"
#include "shaders/CCGLProgram.h"
#include "shaders/CCShaderCache.h"
#include "CCApplication.h"
NS_CC_BEGIN
#if CC_USE_LA88_LABELS
#define SHADER_PROGRAM kCCShader_PositionTextureColor
#else
#define SHADER_PROGRAM kCCShader_PositionTextureA8Color
#endif
//
//CCLabelTTF
//
CCLabelTTF::CCLabelTTF()
: m_hAlignment(kCCTextAlignmentCenter)
, m_vAlignment(kCCVerticalTextAlignmentTop)
, m_pFontName(NULL)
, m_fFontSize(0.0)
, m_string("")
, m_shadowEnabled(false)
, m_strokeEnabled(false)
, m_textFillColor(ccWHITE)
{
}
CCLabelTTF::~CCLabelTTF()
{
CC_SAFE_DELETE(m_pFontName);
}
CCLabelTTF * CCLabelTTF::create()
{
CCLabelTTF * pRet = new CCLabelTTF();
if (pRet && pRet->init())
{
pRet->autorelease();
}
else
{
CC_SAFE_DELETE(pRet);
}
return pRet;
}
CCLabelTTF * CCLabelTTF::create(const char *string, const char *fontName, float fontSize)
{
return CCLabelTTF::create(string, fontName, fontSize,
CCSizeZero, kCCTextAlignmentCenter, kCCVerticalTextAlignmentTop);
}
CCLabelTTF * CCLabelTTF::create(const char *string, const char *fontName, float fontSize,
const CCSize& dimensions, CCTextAlignment hAlignment)
{
return CCLabelTTF::create(string, fontName, fontSize, dimensions, hAlignment, kCCVerticalTextAlignmentTop);
}
CCLabelTTF* CCLabelTTF::create(const char *string, const char *fontName, float fontSize,
const CCSize &dimensions, CCTextAlignment hAlignment,
CCVerticalTextAlignment vAlignment)
{
CCLabelTTF *pRet = new CCLabelTTF();
if(pRet && pRet->initWithString(string, fontName, fontSize, dimensions, hAlignment, vAlignment))
{
pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
CCLabelTTF * CCLabelTTF::createWithFontDefinition(const char *string, ccFontDefinition &textDefinition)
{
CCLabelTTF *pRet = new CCLabelTTF();
if(pRet && pRet->initWithStringAndTextDefinition(string, textDefinition))
{
pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
bool CCLabelTTF::init()
{
return this->initWithString("", "Helvetica", 12);
}
bool CCLabelTTF::initWithString(const char *label, const char *fontName, float fontSize,
const CCSize& dimensions, CCTextAlignment alignment)
{
return this->initWithString(label, fontName, fontSize, dimensions, alignment, kCCVerticalTextAlignmentTop);
}
bool CCLabelTTF::initWithString(const char *label, const char *fontName, float fontSize)
{
return this->initWithString(label, fontName, fontSize,
CCSizeZero, kCCTextAlignmentLeft, kCCVerticalTextAlignmentTop);
}
bool CCLabelTTF::initWithString(const char *string, const char *fontName, float fontSize,
const cocos2d::CCSize &dimensions, CCTextAlignment hAlignment,
CCVerticalTextAlignment vAlignment)
{
if (CCSprite::init())
{
// shader program
this->setShaderProgram(CCShaderCache::sharedShaderCache()->programForKey(SHADER_PROGRAM));
m_tDimensions = CCSizeMake(dimensions.width, dimensions.height);
m_hAlignment = hAlignment;
m_vAlignment = vAlignment;
m_pFontName = new std::string(fontName);
m_fFontSize = fontSize;
this->setString(string);
return true;
}
return false;
}
bool CCLabelTTF::initWithStringAndTextDefinition(const char *string, ccFontDefinition &textDefinition)
{
if (CCSprite::init())
{
// shader program
this->setShaderProgram(CCShaderCache::sharedShaderCache()->programForKey(SHADER_PROGRAM));
// prepare everythin needed to render the label
_updateWithTextDefinition(textDefinition, false);
// set the string
this->setString(string);
//
return true;
}
else
{
return false;
}
}
void CCLabelTTF::setString(const char *string)
{
CCAssert(string != NULL, "Invalid string");
if (m_string.compare(string))
{
m_string = string;
this->updateTexture();
}
}
const char* CCLabelTTF::getString(void)
{
return m_string.c_str();
}
const char* CCLabelTTF::description()
{
return CCString::createWithFormat("<CCLabelTTF | FontName = %s, FontSize = %.1f>", m_pFontName->c_str(), m_fFontSize)->getCString();
}
CCTextAlignment CCLabelTTF::getHorizontalAlignment()
{
return m_hAlignment;
}
void CCLabelTTF::setHorizontalAlignment(CCTextAlignment alignment)
{
if (alignment != m_hAlignment)
{
m_hAlignment = alignment;
// Force update
if (m_string.size() > 0)
{
this->updateTexture();
}
}
}
CCVerticalTextAlignment CCLabelTTF::getVerticalAlignment()
{
return m_vAlignment;
}
void CCLabelTTF::setVerticalAlignment(CCVerticalTextAlignment verticalAlignment)
{
if (verticalAlignment != m_vAlignment)
{
m_vAlignment = verticalAlignment;
// Force update
if (m_string.size() > 0)
{
this->updateTexture();
}
}
}
CCSize CCLabelTTF::getDimensions()
{
return m_tDimensions;
}
void CCLabelTTF::setDimensions(const CCSize &dim)
{
if (dim.width != m_tDimensions.width || dim.height != m_tDimensions.height)
{
m_tDimensions = dim;
// Force update
if (m_string.size() > 0)
{
this->updateTexture();
}
}
}
float CCLabelTTF::getFontSize()
{
return m_fFontSize;
}
void CCLabelTTF::setFontSize(float fontSize)
{
if (m_fFontSize != fontSize)
{
m_fFontSize = fontSize;
// Force update
if (m_string.size() > 0)
{
this->updateTexture();
}
}
}
const char* CCLabelTTF::getFontName()
{
return m_pFontName->c_str();
}
void CCLabelTTF::setFontName(const char *fontName)
{
if (m_pFontName->compare(fontName))
{
delete m_pFontName;
m_pFontName = new std::string(fontName);
// Force update
if (m_string.size() > 0)
{
this->updateTexture();
}
}
}
// Helper
bool CCLabelTTF::updateTexture()
{
CCTexture2D *tex;
tex = new CCTexture2D();
if (!tex)
return false;
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
ccFontDefinition texDef = _prepareTextDefinition(true);
tex->initWithString( m_string.c_str(), &texDef );
#else
tex->initWithString( m_string.c_str(),
m_pFontName->c_str(),
m_fFontSize * CC_CONTENT_SCALE_FACTOR(),
CC_SIZE_POINTS_TO_PIXELS(m_tDimensions),
m_hAlignment,
m_vAlignment);
#endif
// set the texture
this->setTexture(tex);
// release it
tex->release();
// set the size in the sprite
CCRect rect =CCRectZero;
rect.size = m_pobTexture->getContentSize();
this->setTextureRect(rect);
//ok
return true;
}
void CCLabelTTF::enableShadow(const CCSize &shadowOffset, float shadowOpacity, float shadowBlur, bool updateTexture)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
bool valueChanged = false;
if (false == m_shadowEnabled)
{
m_shadowEnabled = true;
valueChanged = true;
}
if ( (m_shadowOffset.width != shadowOffset.width) || (m_shadowOffset.height!=shadowOffset.height) )
{
m_shadowOffset.width = shadowOffset.width;
m_shadowOffset.height = shadowOffset.height;
valueChanged = true;
}
if (m_shadowOpacity != shadowOpacity )
{
m_shadowOpacity = shadowOpacity;
valueChanged = true;
}
if (m_shadowBlur != shadowBlur)
{
m_shadowBlur = shadowBlur;
valueChanged = true;
}
if ( valueChanged && updateTexture )
{
this->updateTexture();
}
#else
CCLOGERROR("Currently only supported on iOS and Android!");
#endif
}
void CCLabelTTF::disableShadow(bool updateTexture)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
<|fim▁hole|> {
m_shadowEnabled = false;
if (updateTexture)
this->updateTexture();
}
#else
CCLOGERROR("Currently only supported on iOS and Android!");
#endif
}
void CCLabelTTF::enableStroke(const ccColor3B &strokeColor, float strokeSize, bool updateTexture)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
bool valueChanged = false;
if(m_strokeEnabled == false)
{
m_strokeEnabled = true;
valueChanged = true;
}
if ( (m_strokeColor.r != strokeColor.r) || (m_strokeColor.g != strokeColor.g) || (m_strokeColor.b != strokeColor.b) )
{
m_strokeColor = strokeColor;
valueChanged = true;
}
if (m_strokeSize!=strokeSize)
{
m_strokeSize = strokeSize;
valueChanged = true;
}
if ( valueChanged && updateTexture )
{
this->updateTexture();
}
#else
CCLOGERROR("Currently only supported on iOS and Android!");
#endif
}
void CCLabelTTF::disableStroke(bool updateTexture)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
if (m_strokeEnabled)
{
m_strokeEnabled = false;
if (updateTexture)
this->updateTexture();
}
#else
CCLOGERROR("Currently only supported on iOS and Android!");
#endif
}
void CCLabelTTF::setFontFillColor(const ccColor3B &tintColor, bool updateTexture)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
if (m_textFillColor.r != tintColor.r || m_textFillColor.g != tintColor.g || m_textFillColor.b != tintColor.b)
{
m_textFillColor = tintColor;
if (updateTexture)
this->updateTexture();
}
#else
CCLOGERROR("Currently only supported on iOS and Android!");
#endif
}
void CCLabelTTF::setTextDefinition(ccFontDefinition *theDefinition)
{
if (theDefinition)
{
_updateWithTextDefinition(*theDefinition, true);
}
}
ccFontDefinition *CCLabelTTF::getTextDefinition()
{
ccFontDefinition *tempDefinition = new ccFontDefinition;
*tempDefinition = _prepareTextDefinition(false);
return tempDefinition;
}
void CCLabelTTF::_updateWithTextDefinition(ccFontDefinition & textDefinition, bool mustUpdateTexture)
{
m_tDimensions = CCSizeMake(textDefinition.m_dimensions.width, textDefinition.m_dimensions.height);
m_hAlignment = textDefinition.m_alignment;
m_vAlignment = textDefinition.m_vertAlignment;
m_pFontName = new std::string(textDefinition.m_fontName);
m_fFontSize = textDefinition.m_fontSize;
// shadow
if ( textDefinition.m_shadow.m_shadowEnabled )
{
enableShadow(textDefinition.m_shadow.m_shadowOffset, textDefinition.m_shadow.m_shadowOpacity, textDefinition.m_shadow.m_shadowBlur, false);
}
// stroke
if ( textDefinition.m_stroke.m_strokeEnabled )
{
enableStroke(textDefinition.m_stroke.m_strokeColor, textDefinition.m_stroke.m_strokeSize, false);
}
// fill color
setFontFillColor(textDefinition.m_fontFillColor, false);
if (mustUpdateTexture)
updateTexture();
}
ccFontDefinition CCLabelTTF::_prepareTextDefinition(bool adjustForResolution)
{
ccFontDefinition texDef;
if (adjustForResolution)
texDef.m_fontSize = m_fFontSize * CC_CONTENT_SCALE_FACTOR();
else
texDef.m_fontSize = m_fFontSize;
texDef.m_fontName = *m_pFontName;
texDef.m_alignment = m_hAlignment;
texDef.m_vertAlignment = m_vAlignment;
if (adjustForResolution)
texDef.m_dimensions = CC_SIZE_POINTS_TO_PIXELS(m_tDimensions);
else
texDef.m_dimensions = m_tDimensions;
// stroke
if ( m_strokeEnabled )
{
texDef.m_stroke.m_strokeEnabled = true;
texDef.m_stroke.m_strokeColor = m_strokeColor;
if (adjustForResolution)
texDef.m_stroke.m_strokeSize = m_strokeSize * CC_CONTENT_SCALE_FACTOR();
else
texDef.m_stroke.m_strokeSize = m_strokeSize;
}
else
{
texDef.m_stroke.m_strokeEnabled = false;
}
// shadow
if ( m_shadowEnabled )
{
texDef.m_shadow.m_shadowEnabled = true;
texDef.m_shadow.m_shadowBlur = m_shadowBlur;
texDef.m_shadow.m_shadowOpacity = m_shadowOpacity;
if (adjustForResolution)
texDef.m_shadow.m_shadowOffset = CC_SIZE_POINTS_TO_PIXELS(m_shadowOffset);
else
texDef.m_shadow.m_shadowOffset = m_shadowOffset;
}
else
{
texDef.m_shadow.m_shadowEnabled = false;
}
// text tint
texDef.m_fontFillColor = m_textFillColor;
return texDef;
}
NS_CC_END<|fim▁end|> | if (m_shadowEnabled) |
<|file_name|>settings.py<|end_file_name|><|fim▁begin|>"""
Django settings for findtorun project.
Generated by 'django-admin startproject' using Django 1.11.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '3@i55e)e-m8af#@st3n98!$64fe-3ti-6o=j5g*k%3n6ri9yx!'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
DEBUG = True
log_level = 'DEBUG'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
},
'formatters': {
'simple': {
'format': '%(filename)s %(lineno)d %(asctime)s %(levelname)s %(message)s'
}
},
'loggers': {
'find2run': {
'handlers': ['console'],
'level': log_level,
},
},
}
ALLOWED_HOSTS = [
'ec2-54-193-111-20.us-west-1.compute.amazonaws.com',
'localhost',
'api.findtorun.fun'
]
# Application definition
INSTALLED_APPS = [
'find2run.apps.Find2RunConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [<|fim▁hole|> 'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'findtorun.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'findtorun.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'findtorun',
'USER': 'findtorun_user',
'PASSWORD': 'p@$$w0rd111!!!',
'HOST': 'localhost',
'PORT': '5432',
'TEST': {
'NAME': 'findtorun_test'
},
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'<|fim▁end|> | 'django.middleware.security.SecurityMiddleware', |
<|file_name|>build.ts<|end_file_name|><|fim▁begin|>import Future = require("fibers/future");
import { AddPlatformCommand } from "./add-platform";
export class BuildCommandBase {
constructor(protected $options: IOptions,
private $platformService: IPlatformService) { }
executeCore(args: string[], buildConfig?: IBuildConfig): IFuture<void> {
return (() => {
let platform = args[0].toLowerCase();
this.$platformService.preparePlatform(platform, true).wait();
this.$platformService.buildPlatform(platform, buildConfig).wait();
if(this.$options.copyTo) {
this.$platformService.copyLastOutput(platform, this.$options.copyTo, {isForDevice: this.$options.forDevice}).wait();
}
}).future<void>()();
}
}
export class BuildIosCommand extends BuildCommandBase implements ICommand {
constructor(protected $options: IOptions,
private $platformsData: IPlatformsData,
$platformService: IPlatformService) {
super($options, $platformService);
}
public allowedParameters: ICommandParameter[] = [];
public execute(args: string[]): IFuture<void> {
return this.executeCore([this.$platformsData.availablePlatforms.iOS]);
}
}
$injector.registerCommand("build|ios", BuildIosCommand);
export class BuildAndroidCommand extends BuildCommandBase implements ICommand {
constructor(protected $options: IOptions,
private $platformsData: IPlatformsData,
private $errors: IErrors,
$platformService: IPlatformService) {
super($options, $platformService);
}
public execute(args: string[]): IFuture<void> {
return this.executeCore([this.$platformsData.availablePlatforms.Android]);
}
public allowedParameters: ICommandParameter[] = [];
public canExecute(args: string[]): IFuture<boolean> {
return (() => {
if (this.$options.release && (!this.$options.keyStorePath || !this.$options.keyStorePassword || !this.$options.keyStoreAlias || !this.$options.keyStoreAliasPassword)) {
this.$errors.fail("When producing a release build, you need to specify all --key-store-* options.");
}
return args.length === 0;
}).future<boolean>()();
}
}
$injector.registerCommand("build|android", BuildAndroidCommand);
export class BuildVRCommand extends AddPlatformCommand {
constructor(protected $projectData: IProjectData,
$platformService: IPlatformService,
protected $errors: IErrors,
$fs: IFileSystem,
protected $logger: ILogger) {
super($projectData, $platformService, $errors, $fs, $logger);
}
protected pathToApk: string;
public allowedParameters: ICommandParameter[] = [];
public execute(args: string[]): IFuture<void> {
return (() => {
super.execute(["vr"]).wait();
let vr = require("nativescript-cli-vr");
let buildFuture = new Future<string>();
this.$logger.info("Building...");
let promise: any = vr.build(this.$projectData.projectId, this.$projectData.projectDir);
promise
.then((result: string) => buildFuture.return(result))
.catch((e: Error) => buildFuture.throw(e));
this.pathToApk = buildFuture.wait();
this.$logger.printMarkdown(`Successfully built application \`${this.$projectData.projectId}\` for \`Virtual Reality\`.`);
}).future<void>()();<|fim▁hole|> }
}
$injector.registerCommand("build|vr", BuildVRCommand);<|fim▁end|> | |
<|file_name|>background.mako.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("Background", inherited=False) %>
${helpers.predefined_type(
"background-color",
"Color",
"computed_value::T::transparent()",
initial_specified_value="SpecifiedValue::transparent()",
spec="https://drafts.csswg.org/css-backgrounds/#background-color",
animation_value_type="AnimatedColor",
ignored_when_colors_disabled=True,
allow_quirks=True,
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER \
CAN_ANIMATE_ON_COMPOSITOR",
)}
${helpers.predefined_type(
"background-image",
"ImageLayer",
initial_value="Either::First(None_)",
initial_specified_value="Either::First(None_)",
spec="https://drafts.csswg.org/css-backgrounds/#the-background-image",
vector="True",
animation_value_type="discrete",
ignored_when_colors_disabled="True",
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER",
)}
% for (axis, direction, initial) in [("x", "Horizontal", "left"), ("y", "Vertical", "top")]:
${helpers.predefined_type(
"background-position-" + axis,
"position::" + direction + "Position",
initial_value="computed::LengthOrPercentage::zero()",
initial_specified_value="SpecifiedValue::initial_specified_value()",
spec="https://drafts.csswg.org/css-backgrounds-4/#propdef-background-position-" + axis,
animation_value_type="ComputedValue",
vector=True,
vector_animation_type="repeatable_list",
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER",
)}
% endfor
${helpers.predefined_type(
"background-repeat",
"BackgroundRepeat",
"computed::BackgroundRepeat::repeat()",
initial_specified_value="specified::BackgroundRepeat::repeat()",
animation_value_type="discrete",
vector=True,
spec="https://drafts.csswg.org/css-backgrounds/#the-background-repeat",
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER",
)}
${helpers.single_keyword(
"background-attachment",
"scroll fixed" + (" local" if product == "gecko" else ""),
vector=True,
gecko_enum_prefix="StyleImageLayerAttachment",
spec="https://drafts.csswg.org/css-backgrounds/#the-background-attachment",
animation_value_type="discrete",
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER",
)}
${helpers.single_keyword(
"background-clip",
"border-box padding-box content-box",<|fim▁hole|> gecko_enum_prefix="StyleGeometryBox",
gecko_inexhaustive=True,
spec="https://drafts.csswg.org/css-backgrounds/#the-background-clip",
animation_value_type="discrete",
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER",
)}
${helpers.single_keyword(
"background-origin",
"padding-box border-box content-box",
vector=True, extra_prefixes="webkit",
gecko_enum_prefix="StyleGeometryBox",
gecko_inexhaustive=True,
spec="https://drafts.csswg.org/css-backgrounds/#the-background-origin",
animation_value_type="discrete",
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER"
)}
${helpers.predefined_type(
"background-size",
"BackgroundSize",
initial_value="computed::BackgroundSize::auto()",
initial_specified_value="specified::BackgroundSize::auto()",
spec="https://drafts.csswg.org/css-backgrounds/#the-background-size",
vector=True,
vector_animation_type="repeatable_list",
animation_value_type="BackgroundSizeList",
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER",
extra_prefixes="webkit")}
// https://drafts.fxtf.org/compositing/#background-blend-mode
${helpers.single_keyword(
"background-blend-mode",
"""normal multiply screen overlay darken lighten color-dodge
color-burn hard-light soft-light difference exclusion hue
saturation color luminosity""",
gecko_constant_prefix="NS_STYLE_BLEND",
gecko_pref="layout.css.background-blend-mode.enabled",
vector=True, products="gecko", animation_value_type="discrete",
spec="https://drafts.fxtf.org/compositing/#background-blend-mode",
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER",
)}<|fim▁end|> | extra_gecko_values="text",
vector=True, extra_prefixes="webkit", |
<|file_name|>Typefaces.java<|end_file_name|><|fim▁begin|>package kc.spark.pixels.android.ui.assets;
import static org.solemnsilence.util.Py.map;
import java.util.Map;
import android.content.Context;
import android.graphics.Typeface;
public class Typefaces {
// NOTE: this is tightly coupled to the filenames in assets/fonts
public static enum Style {
BOLD("Arial.ttf"),
BOLD_ITALIC("Arial.ttf"),
BOOK("Arial.ttf"),
BOOK_ITALIC("Arial.ttf"),
LIGHT("Arial.ttf"),
LIGHT_ITALIC("Arial.ttf"),
MEDIUM("Arial.ttf"),
MEDIUM_ITALIC("Arial.ttf");
// BOLD("gotham_bold.otf"),
// BOLD_ITALIC("gotham_bold_ita.otf"),
// BOOK("gotham_book.otf"),
// BOOK_ITALIC("gotham_book_ita.otf"),
// LIGHT("gotham_light.otf"),
// LIGHT_ITALIC("gotham_light_ita.otf"),
// MEDIUM("gotham_medium.otf"),
// MEDIUM_ITALIC("gotham_medium_ita.otf");
public final String fileName;
private Style(String name) {
fileName = name;
}
}
private static final Map<Style, Typeface> typefaces = map();
public static Typeface getTypeface(Context ctx, Style style) {
Typeface face = typefaces.get(style);
if (face == null) {<|fim▁hole|> face = Typeface.createFromAsset(ctx.getAssets(), "fonts/" + style.fileName);
typefaces.put(style, face);
}
return face;
}
}<|fim▁end|> | |
<|file_name|>0003_matterattachment_link_obtained_at.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('cityhallmonitor', '0002_matter_attachments_obtained_at'),
]
operations = [<|fim▁hole|> ),
]<|fim▁end|> | migrations.AddField(
model_name='matterattachment',
name='link_obtained_at',
field=models.DateTimeField(null=True), |
<|file_name|>trait-impl-different-num-params.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.<|fim▁hole|>// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
trait foo {
fn bar(&self, x: uint) -> Self;
}
impl foo for int {
fn bar(&self) -> int {
//~^ ERROR method `bar` has 1 parameter but the declaration in trait `foo::bar` has 2
*self
}
}
fn main() {
}<|fim▁end|> | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
<|file_name|>postal.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from gramfuzz.fields import *
import names
TOP_CAT = "postal"
# Adapted from https://en.wikipedia.org/wiki/Backus%E2%80%93Naur_form
# The name rules have been modified and placed into names.py
class PDef(Def):
cat = "postal_def"
class PRef(Ref):
cat = "postal_def"
EOL = "\n"
# this will be the top-most rule
Def("postal_address",
PRef("name-part"), PRef("street-address"), PRef("zip-part"),
cat="postal")
# these will be the grammar rules that should not be randomly generated
# as a top-level rule
PDef("name-part",
Ref("name", cat=names.TOP_CAT), EOL
)
PDef("street-address",
PRef("house-num"), PRef("street-name"), Opt(PRef("apt-num")), EOL,
sep=" ")
PDef("house-num", UInt)
PDef("street-name", Or(
"Sesame Street", "Yellow Brick Road", "Jump Street", "Evergreen Terrace",
"Elm Street", "Baker Street", "Paper Street", "Wisteria Lane",
"Coronation Street", "Rainey Street", "Spooner Street",
"0day Causeway", "Diagon Alley",
))
PDef("zip-part",
PRef("town-name"), ", ", PRef("state-code"), " ", PRef("zip-code"), EOL
)
PDef("apt-num",
UInt(min=0, max=10000), Opt(String(charset=String.charset_alpha_upper, min=1, max=2))<|fim▁hole|>)
PDef("town-name", Or(
"Seoul", "São Paulo", "Bombay", "Jakarta", "Karachi", "Moscow",
"Istanbul", "Mexico City", "Shanghai", "Tokyo", "New York", "Bangkok",
"Beijing", "Delhi", "London", "HongKong", "Cairo", "Tehran", "Bogota",
"Bandung", "Tianjin", "Lima", "Rio de Janeiro" "Lahore", "Bogor",
"Santiago", "St Petersburg", "Shenyang", "Calcutta", "Wuhan", "Sydney",
"Guangzhou", "Singapore", "Madras", "Baghdad", "Pusan", "Los Angeles",
"Yokohama", "Dhaka", "Berlin", "Alexandria", "Bangalore", "Malang",
"Hyderabad", "Chongqing", "Ho Chi Minh City",
))
PDef("state-code", Or(
"AL", "AK", "AS", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FL", "GA",
"GU", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MH",
"MA", "MI", "FM", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM",
"NY", "NC", "ND", "MP", "OH", "OK", "OR", "PW", "PA", "PR", "RI", "SC",
"SD", "TN", "TX", "UT", "VT", "VA", "VI", "WA", "WV", "WI", "WY",
))
PDef("zip-code",
String(charset="123456789",min=1,max=2), String(charset="0123456789",min=4,max=5),
Opt("-", String(charset="0123456789",min=4,max=5))
)<|fim▁end|> | |
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals
import re
from django.contrib.auth.models import (AbstractBaseUser, PermissionsMixin,
UserManager)
from django.core import validators
from django.core.mail import send_mail
from django.utils.translation import ugettext_lazy as _
from notifications.models import *
from broadcast.models import Broadcast
class CustomUser(AbstractBaseUser, PermissionsMixin):
"""
A custom user class that basically mirrors Django's `AbstractUser` class
and doesn'0t force `first_name` or `last_name` with sensibilities for
international names.
http://www.w3.org/International/questions/qa-personal-names
"""
username = models.CharField(_('username'), max_length=30, unique=True,
help_text=_('Required. 30 characters or fewer. Letters, numbers and '
'@/./+/-/_ characters'),
validators=[
validators.RegexValidator(re.compile(
'^[\w.@+-]+$'), _('Enter a valid username.'), 'invalid')
])
full_name = models.CharField(_('full name'), max_length=254, blank=False)
short_name = models.CharField(_('short name'), max_length=30, blank=True)
choices = (('Male', 'Male'), ('Female', 'Female'))
sex = models.CharField(_('sex'), max_length=30, blank=False, choices=choices)
email = models.EmailField(_('email address'), max_length=254, unique=True)
phone_number = models.CharField(_('phone number'), max_length=20, validators=[
validators.RegexValidator(re.compile(
'^[0-9]+$'), _('Only numbers are allowed.'), 'invalid')
])
user_choices = (('Driver', 'Driver'), ('Passenger', 'Passenger'))
user_type = models.CharField(_('user type'), max_length=30, blank=False, choices=user_choices)
address = models.TextField(_('location'), max_length=400, blank=False)
is_staff = models.BooleanField(_('staff status'), default=False,
help_text=_('Designates whether the user can log into this admin '
'site.'))
is_verified = models.BooleanField(_('user verified'), default=False,
help_text=_('Designates whether the user is a vershified user'))
is_active = models.BooleanField(_('active'), default=True,
help_text=_('Designates whether this user should be treated as '
'active. Unselect this instead of deleting accounts.'))
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
objects = UserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def __unicode__(self):
return self.username
def get_absolute_url(self):
return "/profile/%s" % self.username
def get_full_name(self):
"""
Returns the first_name plus the last_name, with a space in between.
"""
full_name = self.full_name
return full_name.strip()
def get_short_name(self):
"Returns the short name for the user."
return self.short_name.strip()
def get_sex(self):
return self.sex
def email_user(self, subject, message, from_email=None):
"""
Sends an email to this User.
"""
send_mail(subject, message, from_email, [self.email])
def get_no_messages(self):
number = Message.objects.filter(recipient=self, read=False)
if number.count() > 0:
return number.count()
else:
return None
def get_messages(self):
msg = Message.objects.filter(recipient=self, read=False).order_by('date').reverse()
return msg
def get_messages_all(self):
msg = Message.objects.filter(recipient=self).order_by('date').reverse()
return msg
def get_notifications(self):
return self.notifications.unread()
def get_no_notifs(self):
return self.notifications.unread().count()
def is_follows(self, user_1):
foll = Follow.objects.filter(follower=self, followee=user_1)
if foll.exists():
return True
else:
return False
def get_no_followers(self):
num = Follow.objects.filter(followee=self).count()
return num
def get_no_following(self):
num = Follow.objects.filter(follower=self).count()
return num
def get_following(self):
num = Follow.objects.filter(follower=self).values_list('followee')
result = []
for follower in num:
user = CustomUser.objects.get(pk=follower[0])
result.append(user)
return result
def get_profile(self):
profile = Profile.objects.get(user=self)
return profile
def no_of_rides_shared(self):
return self.vehiclesharing_set.filter(user=self, ended=True).count()
def no_of_request_completed(self):
return self.request_set.filter(status='approved', user=self).count()
def get_no_broadcast(self):
return Broadcast.objects.filter(user=self).count()
def get_broadcast(self):
all_broad = Broadcast.objects.filter(user=self)[0:10]
return all_broad
class Vehicle(models.Model):
year = models.IntegerField(_('year of purchase'), blank=False)
make = models.CharField(_('vehicle make'), max_length=254, blank=False)
plate = models.CharField(_('liscenced plate number'), max_length=10, blank=False)
model = models.CharField(_('vehicle model'), max_length=254, blank=False)
seats = models.IntegerField(_('no of seats'), blank=False)
user_choices = (('private', 'private'), ('hired', 'hired'))
type = models.CharField(_('vehicle type'), max_length=30, blank=False, choices=user_choices)
user_choices = (('Car', 'Car'), ('Bus', 'Bus'), ('Coaster', 'Coaster'), ('Truck', 'Truck'))
category = models.CharField(_('vehicle category'), max_length=30, blank=False, choices=user_choices)
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
def get_absolute_url(self):
return "/app/ride/%d/view" % self.pk
def __str__(self):
return self.make + " " + self.model + " belonging to " + self.user.username
class VehicleSharing(models.Model):
start = models.CharField(_('starting point'), max_length=256, blank=False, )
dest = models.CharField(_('destination'), max_length=256, blank=False)
cost = models.IntegerField(_('cost'), blank=False)
date = models.DateField(_('date'), default=timezone.now)
start_time = models.TimeField(_('start time'), max_length=256, blank=False)
arrival_time = models.TimeField(_('estimated arrivak'), max_length=256, blank=False)
no_pass = models.IntegerField(_('no of passengers'), blank=False)
details = models.TextField(_('ride details'), blank=False)
choices = (('Male', 'Male'), ('Female', 'Female'), ('Both', 'Both'))
sex = models.CharField(_('gender preference'), max_length=30, blank=False, choices=choices)
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE)
ended = models.BooleanField(_('sharing ended'), default=False)
def __str__(self):
return self.start + " to " + self.dest
def get_user(self):
return self.user
def get_absolute_url(self):
return "/app/sharing/%d/view" % self.pk
class Request(models.Model):
pick = models.CharField(_('pick up point'), max_length=256, blank=False, )
dest = models.CharField(_('destination'), max_length=256, blank=False)
reg_date = models.DateTimeField(_('registration date'), default=timezone.now)
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
bearable = models.IntegerField(_('bearable cost'), blank=False)
status = models.CharField(_('status'), max_length=256, blank=False, default='pending')
ride = models.ForeignKey(VehicleSharing, on_delete=models.CASCADE)
def __str__(self):
return "request from " + self.user.get_full_name() + " on " + self.reg_date.isoformat(' ')[0:16]
def get_absolute_url(self):
return "/app/request/%d/view" % self.pk
class Message(models.Model):
sender = models.ForeignKey(CustomUser, related_name='sender', on_delete=models.CASCADE)
recipient = models.ForeignKey(CustomUser, related_name='recipient', on_delete=models.CASCADE)
subject = models.CharField(default='(No Subject)', max_length=256)
message = models.TextField(blank=False)
date = models.DateTimeField(_('time sent'), default=timezone.now)
read = models.BooleanField(_('read'), default=False)
deleted = models.BooleanField(_('deleted'), default=False)
def __str__(self):
return self.sender.username + ' to ' + self.recipient.username + ' - ' + self.message[0:20] + '...'
def url(self):
return '/app/user/dashboard/messages/%d/read/' % self.pk
def send(self, user, recipient, subject, message):
message = Message()<|fim▁hole|> message.recipient = recipient
message.subject = subject
message.message = message
message.save()
class Follow(models.Model):
follower = models.ForeignKey(CustomUser, related_name='follower', on_delete=models.CASCADE, default=None)
followee = models.ForeignKey(CustomUser, related_name='followee', on_delete=models.CASCADE, default=None)
time = models.DateTimeField(_('time'), default=timezone.now)
def __unicode__(self):
return str(self.follower) + ' follows ' + str(self.followee)
def __str__(self):
return str(self.follower) + ' follows ' + str(self.followee)
def is_follows(self, user_1, user_2):
foll = Follow.objects.filter(user=user_1, follower=user_2)
if foll.exists():
return True
else:
return False
def get_absolute_url(self):
return "/app/profile/%s" % self.follower.username
class Profile(models.Model):
user = models.OneToOneField(CustomUser, related_name='profile', on_delete=models.CASCADE, unique=True)
picture = models.FileField(blank=True, default='user.png')
education = models.TextField(blank=True)
work = models.TextField(blank=True)
social_facebook = models.CharField(max_length=256, blank=True)
social_twitter = models.CharField(max_length=256, blank=True)
social_instagram = models.CharField(max_length=256, blank=True)
bio = models.TextField(blank=True)
is_public = models.BooleanField(default=False)
def __str__(self):
return self.user.username
class DriverInfo(models.Model):
driver = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
liscence_no = models.CharField(_('liscence number'), max_length=30, blank=False)
date_issuance = models.DateField(_('date of first issuance'), blank=True)
scanned = models.ImageField(_('picture of driver\'s liscence'), blank=True)
confirmed = models.BooleanField(_('confirmed'), default=False)<|fim▁end|> | message.sender = user |
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>pub mod release;
use std::env::args;
use std::process::exit;
use crate::release::*;
use compat::getpid;
use config::Config;
use logger::{Level, Logger};
use networking::Server;
fn main() {
let mut config = Config::new(Logger::new(Level::Notice));
if let Some(f) = args().nth(1) {
if config.parsefile(f).is_err() {<|fim▁hole|>
let (port, daemonize) = (config.port, config.daemonize);
let mut server = Server::new(config);
{
let mut db = server.get_mut_db();
db.git_sha1 = GIT_SHA1;
db.git_dirty = GIT_DIRTY;
db.version = env!("CARGO_PKG_VERSION");
db.rustc_version = RUSTC_VERSION;
}
if !daemonize {
println!("Port: {}", port);
println!("PID: {}", getpid());
}
server.run();
}<|fim▁end|> | exit(1);
}
} |
<|file_name|>test_Chromosome.py<|end_file_name|><|fim▁begin|>import pytest<|fim▁hole|>
@pytest.fixture
def chr1():
return Chromosome("chr1", "A" * 500000)
@pytest.fixture
def chr2():
return Chromosome("chr1", "C" * 500000)
def test_init(chr1):
assert chr1
def test_init_from_seq():
x = Chromosome("chr1", ["a", "c", "g", "t"])
assert True
def test_slice(chr1):
x = chr1[1:100]
assert len(x) == 100
def test_invalid_slice(chr1):
with pytest.raises(ValueError):
chr1[0:100]
def test_get_bp(chr1):
assert chr1[12] == "A"
def test_get_bp_invalid_coordinate(chr1):
with pytest.raises(ValueError):
chr1[0]
def test_repr(chr1):
assert repr(chr1) == "Chromosome('AAAAAAAAAAAA...AAAAAAAAAAAAA')"
def test_equals(chr1, chr2):
x = chr1
y = chr2
assert x == x
assert x != y
def test_N_in_chromosome():
Chromosome("test", "aaacccgggtttAN")
assert True
def test_bad_nucleotide_in_chromosome_seq():
with pytest.raises(KeyError):
Chromosome("test", "abcd")
assert True<|fim▁end|> | from locuspocus import Chromosome
|
<|file_name|>recover.go<|end_file_name|><|fim▁begin|>package emperror
import (
"errors"
"fmt"
)
// Recover accepts a recovered panic (if any) and converts it to an error (if necessary).
func Recover(r interface{}) (err error) {
if r != nil {
switch x := r.(type) {<|fim▁hole|> err = x
default:
err = fmt.Errorf("unknown panic, received: %v", r)
}
if _, ok := StackTrace(err); !ok {
err = &wrappedError{
err: err,
stack: callers()[2:], // TODO: improve callers?
}
}
}
return err
}<|fim▁end|> | case string:
err = errors.New(x)
case error: |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>//! A buffer is a memory location accessible to the video card.
//!
//! The purpose of buffers is to serve as a space where the GPU can read from or write data to.
//! It can contain a list of vertices, indices, uniform data, etc.
//!
//! # Buffers management in glium
//!
//! There are three levels of abstraction in glium:
//!
//! - An `Alloc` corresponds to an OpenGL buffer object and is unsafe to use.
//! This type is not public.
//! - A `Buffer` wraps around an `Alloc` and provides safety by handling the data type and fences.
//! - The `VertexBuffer`, `IndexBuffer`, `UniformBuffer`, `PixelBuffer`, etc. types are
//! abstractions over a `Buffer` indicating their specific purpose. They implement `Deref`
//! for the `Buffer`. These types are in the `vertex`, `index`, etc. modules.
//!
//! # Unsized types
//!
//! In order to put some data in a buffer, it must implement the `Content` trait. This trait is
//! automatically implemented on all `Sized` types and on slices (like `[u8]`). This means that
//! you can create a `Buffer<Foo>` (if `Foo` is sized) or a `Buffer<[u8]>` for example without
//! worrying about it.
//!
//! However unsized structs don't automatically implement this trait and you must call the
//! `implement_buffer_content!` macro on them. You must then use the `empty_unsized` constructor.
//!
//! ```no_run
//! # #[macro_use] extern crate glium; fn main() {
//! # use std::mem;<|fim▁hole|>//! # let display: glium::Display = unsafe { mem::uninitialized() };
//! struct Data {
//! data: [f32], // `[f32]` is unsized, therefore `Data` is unsized too
//! }
//!
//! implement_buffer_content!(Data); // without this, you can't put `Data` in a glium buffer
//!
//! // creates a buffer of 64 bytes, which thus holds 8 f32s
//! let mut buffer = glium::buffer::Buffer::<Data>::empty_unsized(&display, BufferType::UniformBuffer,
//! 64, BufferMode::Default).unwrap();
//!
//! // you can then write to it like you normally would
//! buffer.map().data[4] = 2.1;
//! # }
//! ```
//!
pub use self::view::{Buffer, BufferAny, BufferMutSlice};
pub use self::view::{BufferSlice, BufferAnySlice};
pub use self::alloc::{Mapping, WriteMapping, ReadMapping, ReadError, CopyError};
pub use self::alloc::{is_buffer_read_supported};
pub use self::fences::Inserter;
/// DEPRECATED. Only here for backward compatibility.
pub use self::view::Buffer as BufferView;
/// DEPRECATED. Only here for backward compatibility.
pub use self::view::BufferSlice as BufferViewSlice;
/// DEPRECATED. Only here for backward compatibility.
pub use self::view::BufferMutSlice as BufferViewMutSlice;
/// DEPRECATED. Only here for backward compatibility.
pub use self::view::BufferAny as BufferViewAny;
/// DEPRECATED. Only here for backward compatibility.
pub use self::view::BufferAnySlice as BufferViewAnySlice;
use gl;
use std::error::Error;
use std::fmt;
use std::mem;
use std::slice;
mod alloc;
mod fences;
mod view;
/// Trait for types of data that can be put inside buffers.
pub unsafe trait Content {
/// A type that holds a sized version of the content.
type Owned;
/// Prepares an output buffer, then turns this buffer into an `Owned`.
fn read<F, E>(size: usize, F) -> Result<Self::Owned, E>
where F: FnOnce(&mut Self) -> Result<(), E>;
/// Returns the size of each element.
fn get_elements_size() -> usize;
/// Produces a pointer to the data.
fn to_void_ptr(&self) -> *const ();
/// Builds a pointer to this type from a raw pointer.
fn ref_from_ptr<'a>(ptr: *mut (), size: usize) -> Option<*mut Self>;
/// Returns true if the size is suitable to store a type like this.
fn is_size_suitable(usize) -> bool;
}
unsafe impl<T> Content for T where T: Copy {
type Owned = T;
#[inline]
fn read<F, E>(size: usize, f: F) -> Result<T, E> where F: FnOnce(&mut T) -> Result<(), E> {
assert!(size == mem::size_of::<T>());
let mut value = unsafe { mem::uninitialized() };
try!(f(&mut value));
Ok(value)
}
#[inline]
fn get_elements_size() -> usize {
mem::size_of::<T>()
}
#[inline]
fn to_void_ptr(&self) -> *const () {
self as *const T as *const ()
}
#[inline]
fn ref_from_ptr<'a>(ptr: *mut (), size: usize) -> Option<*mut T> {
if size != mem::size_of::<T>() {
return None;
}
Some(ptr as *mut T)
}
#[inline]
fn is_size_suitable(size: usize) -> bool {
size == mem::size_of::<T>()
}
}
unsafe impl<T> Content for [T] where T: Copy {
type Owned = Vec<T>;
#[inline]
fn read<F, E>(size: usize, f: F) -> Result<Vec<T>, E>
where F: FnOnce(&mut [T]) -> Result<(), E>
{
assert!(size % mem::size_of::<T>() == 0);
let len = size / mem::size_of::<T>();
let mut value = Vec::with_capacity(len);
unsafe { value.set_len(len) };
try!(f(&mut value));
Ok(value)
}
#[inline]
fn get_elements_size() -> usize {
mem::size_of::<T>()
}
#[inline]
fn to_void_ptr(&self) -> *const () {
&self[0] as *const T as *const ()
}
#[inline]
fn ref_from_ptr<'a>(ptr: *mut (), size: usize) -> Option<*mut [T]> {
if size % mem::size_of::<T>() != 0 {
return None;
}
let ptr = ptr as *mut T;
let size = size / mem::size_of::<T>();
Some(unsafe { slice::from_raw_parts_mut(&mut *ptr, size) as *mut [T] })
}
#[inline]
fn is_size_suitable(size: usize) -> bool {
size % mem::size_of::<T>() == 0
}
}
/// Error that can happen when creating a buffer.
#[derive(Debug, Copy, Clone)]
pub enum BufferCreationError {
/// Not enough memory to create the buffer.
OutOfMemory,
/// This type of buffer is not supported.
BufferTypeNotSupported,
}
impl fmt::Display for BufferCreationError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{}", self.description())
}
}
impl Error for BufferCreationError {
fn description(&self) -> &str {
match self {
&BufferCreationError::OutOfMemory => "Not enough memory to create the buffer",
&BufferCreationError::BufferTypeNotSupported => "This type of buffer is not supported",
}
}
}
/// How the buffer is created.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum BufferMode {
/// This is the default mode suitable for any usage. Will never be slow, will never be fast
/// either.
///
/// Other modes should always be preferred, but you can use this one if you don't know what
/// will happen to the buffer.
///
/// # Implementation
///
/// Tries to use `glBufferStorage` with the `GL_DYNAMIC_STORAGE_BIT` flag.
///
/// If this function is not available, falls back to `glBufferData` with `GL_STATIC_DRAW`.
///
Default,
/// The mode to use when you modify a buffer multiple times per frame. Simiar to `Default` in
/// that it is suitable for most usages.
///
/// Use this if you do a quick succession of modify the buffer, draw, modify, draw, etc. This
/// is something that you shouldn't do by the way.
///
/// With this mode, the OpenGL driver automatically manages the buffer for us. It will try to
/// find the most appropriate storage depending on how we use it. It is guaranteed to never be
/// too slow, but it won't be too fast either.
///
/// # Implementation
///
/// Tries to use `glBufferStorage` with the `GL_DYNAMIC_STORAGE_BIT` and
/// `GL_CLIENT_STORAGE_BIT` flags.
///
/// If this function is not available, falls back to `glBufferData` with `GL_DYNAMIC_DRAW`.
///
Dynamic,
/// Optimized for when you modify a buffer exactly once per frame. You can modify it more than
/// once per frame, but if you modify it too often things will slow down.
///
/// With this mode, glium automatically handles synchronization to prevent the buffer from
/// being access by both the GPU and the CPU simultaneously. If you try to modify the buffer,
/// the execution will block until the GPU has finished using it. For this reason, a quick
/// succession of modifying and drawing using the same buffer will be very slow.
///
/// When using persistent mapping, it is recommended to use triple buffering. This is done by
/// creating a buffer that has three times the capacity that it would normally have. You modify
/// and draw the first third, then modify and draw the second third, then the last part, then
/// go back to the first third, etc.
///
/// # Implementation
///
/// Tries to use `glBufferStorage` with `GL_MAP_PERSISTENT_BIT`. Sync fences are automatically
/// managed by glium.
///
/// If this function is not available, falls back to `glBufferData` with `GL_DYNAMIC_DRAW`.
///
Persistent,
/// Optimized when you will never touch the content of the buffer.
///
/// Immutable buffers should be created once and never touched again. Modifying their content
/// is permitted, but is very slow.
///
/// # Implementation
///
/// Tries to use `glBufferStorage` without any flag. Modifications are done by creating
/// temporary buffers and making the GPU copy the data from the temporary buffer to the real
/// one.
///
/// If this function is not available, falls back to `glBufferData` with `GL_STATIC_DRAW`.
///
Immutable,
}
impl Default for BufferMode {
fn default() -> BufferMode {
BufferMode::Default
}
}
/// Type of a buffer.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum BufferType {
ArrayBuffer,
PixelPackBuffer,
PixelUnpackBuffer,
UniformBuffer,
CopyReadBuffer,
CopyWriteBuffer,
AtomicCounterBuffer,
DispatchIndirectBuffer,
DrawIndirectBuffer,
QueryBuffer,
ShaderStorageBuffer,
TextureBuffer,
TransformFeedbackBuffer,
ElementArrayBuffer,
}
impl BufferType {
fn to_glenum(&self) -> gl::types::GLenum {
match *self {
BufferType::ArrayBuffer => gl::ARRAY_BUFFER,
BufferType::PixelPackBuffer => gl::PIXEL_PACK_BUFFER,
BufferType::PixelUnpackBuffer => gl::PIXEL_UNPACK_BUFFER,
BufferType::UniformBuffer => gl::UNIFORM_BUFFER,
BufferType::CopyReadBuffer => gl::COPY_READ_BUFFER,
BufferType::CopyWriteBuffer => gl::COPY_WRITE_BUFFER,
BufferType::AtomicCounterBuffer => gl::ATOMIC_COUNTER_BUFFER,
BufferType::DispatchIndirectBuffer => gl::DISPATCH_INDIRECT_BUFFER,
BufferType::DrawIndirectBuffer => gl::DRAW_INDIRECT_BUFFER,
BufferType::QueryBuffer => gl::QUERY_BUFFER,
BufferType::ShaderStorageBuffer => gl::SHADER_STORAGE_BUFFER,
BufferType::TextureBuffer => gl::TEXTURE_BUFFER,
BufferType::TransformFeedbackBuffer => gl::TRANSFORM_FEEDBACK_BUFFER,
BufferType::ElementArrayBuffer => gl::ELEMENT_ARRAY_BUFFER,
}
}
}<|fim▁end|> | //! # use glium::buffer::{BufferType, BufferMode}; |
<|file_name|>.eslintrc.js<|end_file_name|><|fim▁begin|>const OFF = 0;
const WARN = 1;
const ERROR = 2;
module.exports = {
extends: "../.eslintrc.js",<|fim▁hole|> "es6": true,
"node": true,
"mocha": true,
},
};<|fim▁end|> | rules: {
"max-len": [ ERROR, 100 ],
},
env: { |
<|file_name|>Fme.cc<|end_file_name|><|fim▁begin|>/*
* @BEGIN LICENSE
*
* Psi4: an open-source quantum chemistry software package
*
* Copyright (c) 2007-2021 The Psi4 Developers.
*
* The copyrights for code used from other parties are included in
* the corresponding files.
*
* This file is part of Psi4.
*
* Psi4 is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, version 3.
*
* Psi4 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along
* with Psi4; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* @END LICENSE
*/
/*! \file
\ingroup CCENERGY
\brief Enter brief description of file here
*/
#include <cstdio>
#include <cstdlib>
#include "psi4/libdpd/dpd.h"
#include "Params.h"
#include "psi4/cc/ccwave.h"
namespace psi {
namespace ccenergy {
void CCEnergyWavefunction::Fme_build() {
dpdfile2 FME, Fme, fIA, fia, tIA, tia;
dpdbuf4 D_anti, D;
if (params_.ref == 0) { /** RHF **/
global_dpd_->file2_init(&fIA, PSIF_CC_OEI, 0, 0, 1, "fIA");
global_dpd_->file2_copy(&fIA, PSIF_CC_OEI, "FME");
global_dpd_->file2_close(&fIA);
global_dpd_->file2_init(&FME, PSIF_CC_OEI, 0, 0, 1, "FME");
global_dpd_->buf4_init(&D_anti, PSIF_CC_DINTS, 0, 0, 5, 0, 5, 0, "D <ij||ab>");<|fim▁hole|>
global_dpd_->dot13(&tIA, &D_anti, &FME, 0, 0, 1.0, 1.0);
global_dpd_->dot13(&tIA, &D, &FME, 0, 0, 1.0, 1.0);
global_dpd_->file2_close(&tIA);
global_dpd_->buf4_close(&D_anti);
global_dpd_->buf4_close(&D);
global_dpd_->file2_close(&FME);
} else if (params_.ref == 1) { /** ROHF **/
global_dpd_->file2_init(&fIA, PSIF_CC_OEI, 0, 0, 1, "fIA");
global_dpd_->file2_copy(&fIA, PSIF_CC_OEI, "FME");
global_dpd_->file2_close(&fIA);
global_dpd_->file2_init(&fia, PSIF_CC_OEI, 0, 0, 1, "fia");
global_dpd_->file2_copy(&fia, PSIF_CC_OEI, "Fme");
global_dpd_->file2_close(&fia);
global_dpd_->file2_init(&FME, PSIF_CC_OEI, 0, 0, 1, "FME");
global_dpd_->file2_init(&Fme, PSIF_CC_OEI, 0, 0, 1, "Fme");
global_dpd_->buf4_init(&D_anti, PSIF_CC_DINTS, 0, 0, 5, 0, 5, 0, "D <ij||ab>");
global_dpd_->buf4_init(&D, PSIF_CC_DINTS, 0, 0, 5, 0, 5, 0, "D <ij|ab>");
global_dpd_->file2_init(&tIA, PSIF_CC_OEI, 0, 0, 1, "tIA");
global_dpd_->file2_init(&tia, PSIF_CC_OEI, 0, 0, 1, "tia");
global_dpd_->dot13(&tIA, &D_anti, &FME, 0, 0, 1.0, 1.0);
global_dpd_->dot13(&tia, &D, &FME, 0, 0, 1.0, 1.0);
global_dpd_->dot13(&tia, &D_anti, &Fme, 0, 0, 1.0, 1.0);
global_dpd_->dot13(&tIA, &D, &Fme, 0, 0, 1.0, 1.0);
global_dpd_->file2_close(&tIA);
global_dpd_->file2_close(&tia);
global_dpd_->buf4_close(&D_anti);
global_dpd_->buf4_close(&D);
global_dpd_->file2_close(&FME);
global_dpd_->file2_close(&Fme);
} else if (params_.ref == 2) { /** UHF **/
global_dpd_->file2_init(&fIA, PSIF_CC_OEI, 0, 0, 1, "fIA");
global_dpd_->file2_copy(&fIA, PSIF_CC_OEI, "FME");
global_dpd_->file2_close(&fIA);
global_dpd_->file2_init(&fia, PSIF_CC_OEI, 0, 2, 3, "fia");
global_dpd_->file2_copy(&fia, PSIF_CC_OEI, "Fme");
global_dpd_->file2_close(&fia);
global_dpd_->file2_init(&FME, PSIF_CC_OEI, 0, 0, 1, "FME");
global_dpd_->file2_init(&Fme, PSIF_CC_OEI, 0, 2, 3, "Fme");
global_dpd_->file2_init(&tIA, PSIF_CC_OEI, 0, 0, 1, "tIA");
global_dpd_->file2_init(&tia, PSIF_CC_OEI, 0, 2, 3, "tia");
global_dpd_->buf4_init(&D, PSIF_CC_DINTS, 0, 20, 20, 20, 20, 0, "D <IJ||AB> (IA,JB)");
global_dpd_->contract422(&D, &tIA, &FME, 0, 0, 1, 1);
global_dpd_->buf4_close(&D);
global_dpd_->buf4_init(&D, PSIF_CC_DINTS, 0, 20, 30, 20, 30, 0, "D <Ij|Ab> (IA,jb)");
global_dpd_->contract422(&D, &tia, &FME, 0, 0, 1, 1);
global_dpd_->buf4_close(&D);
global_dpd_->buf4_init(&D, PSIF_CC_DINTS, 0, 30, 30, 30, 30, 0, "D <ij||ab> (ia,jb)");
global_dpd_->contract422(&D, &tia, &Fme, 0, 0, 1, 1);
global_dpd_->buf4_close(&D);
global_dpd_->buf4_init(&D, PSIF_CC_DINTS, 0, 30, 20, 30, 20, 0, "D <Ij|Ab> (ia,JB)");
global_dpd_->contract422(&D, &tIA, &Fme, 0, 0, 1, 1);
global_dpd_->buf4_close(&D);
global_dpd_->file2_close(&tIA);
global_dpd_->file2_close(&tia);
global_dpd_->file2_close(&FME);
global_dpd_->file2_close(&Fme);
}
}
} // namespace ccenergy
} // namespace psi<|fim▁end|> | global_dpd_->buf4_init(&D, PSIF_CC_DINTS, 0, 0, 5, 0, 5, 0, "D <ij|ab>");
global_dpd_->file2_init(&tIA, PSIF_CC_OEI, 0, 0, 1, "tIA"); |
<|file_name|>BeanUtil.java<|end_file_name|><|fim▁begin|>package com.anteoy.coreJava.reflect;
import java.lang.reflect.Method;
public class BeanUtil {
/**
* ���ݱ�javaBean�������������ȡ������ֵ
*
* @param obj
* @param propertyName
* @return
*/
public static Object getValueByPropertyName(Object obj, String propertyName) {
// 1.�����������ƾͿ��Ի�ȡ��get����
String getMethodName = "get"
+ propertyName.substring(0, 1).toUpperCase()
+ propertyName.substring(1);
//2.��ȡ��������
Class c = obj.getClass();
try {
//get��������public��������
Method m = c.getMethod(getMethodName);
//3 ͨ�������ķ����������
Object value = m.invoke(obj);
return value;
} catch (Exception e) {
e.printStackTrace();
return null;<|fim▁hole|><|fim▁end|> | }
}
} |
<|file_name|>79.cpp<|end_file_name|><|fim▁begin|># include <stdio.h>
int n;
int a[25][25];
int main()
{
while (~scanf("%d", &n)) {
int cnt = 0;
int xl = 1, yl = 1, xr = n, yr = n;<|fim▁hole|> for (int i = xl; cnt<n*n && i <= xr; ++i) a[yl][i] = ++cnt;
for (int i = yl+1; cnt<n*n && i <= yr; ++i) a[i][xr] = ++cnt;
for (int i = xr-1; cnt<n*n && i >= xl; --i) a[yr][i] = ++cnt;
for (int i = yr-1; cnt<n*n && i >= yl+1; --i) a[i][xl] = ++cnt;
++xl, ++yl, --xr, --yr;
}
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
if (j>1) putchar(' ');
printf("%d", a[i][j]);
}
printf("\n");
}
printf("\n");
}
return 0;
}<|fim▁end|> | while (cnt < n*n) { |
<|file_name|>ITDnsTest.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2016 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.dns.it;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.api.gax.paging.Page;
import com.google.cloud.dns.ChangeRequest;
import com.google.cloud.dns.ChangeRequestInfo;
import com.google.cloud.dns.Dns;
import com.google.cloud.dns.Dns.ChangeRequestField;
import com.google.cloud.dns.Dns.ProjectField;
import com.google.cloud.dns.Dns.RecordSetField;
import com.google.cloud.dns.Dns.ZoneField;
import com.google.cloud.dns.DnsBatch;
import com.google.cloud.dns.DnsBatchResult;
import com.google.cloud.dns.DnsException;
import com.google.cloud.dns.DnsOptions;
import com.google.cloud.dns.ProjectInfo;
import com.google.cloud.dns.RecordSet;
import com.google.cloud.dns.Zone;
import com.google.cloud.dns.ZoneInfo;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
public class ITDnsTest {
private static final String PREFIX = "gcldjvit-";
private static final Dns DNS = DnsOptions.getDefaultInstance().getService();
private static final String ZONE_NAME1 = (PREFIX + UUID.randomUUID()).substring(0, 32);
private static final String ZONE_NAME_EMPTY_DESCRIPTION =
(PREFIX + UUID.randomUUID()).substring(0, 32);
private static final String ZONE_NAME_TOO_LONG = ZONE_NAME1 + UUID.randomUUID();
private static final String ZONE_DESCRIPTION1 = "first zone";
private static final String ZONE_DNS_NAME1 = ZONE_NAME1 + ".com.";
private static final String ZONE_DNS_EMPTY_DESCRIPTION = ZONE_NAME_EMPTY_DESCRIPTION + ".com.";
private static final String ZONE_DNS_NAME_NO_PERIOD = ZONE_NAME1 + ".com";
private static final ZoneInfo ZONE1 =
ZoneInfo.of(ZONE_NAME1, ZONE_DNS_EMPTY_DESCRIPTION, ZONE_DESCRIPTION1);
private static final ZoneInfo ZONE_EMPTY_DESCRIPTION =
ZoneInfo.of(ZONE_NAME_EMPTY_DESCRIPTION, ZONE_DNS_NAME1, ZONE_DESCRIPTION1);
private static final ZoneInfo ZONE_NAME_ERROR =
ZoneInfo.of(ZONE_NAME_TOO_LONG, ZONE_DNS_NAME1, ZONE_DESCRIPTION1);
private static final ZoneInfo ZONE_DNS_NO_PERIOD =
ZoneInfo.of(ZONE_NAME1, ZONE_DNS_NAME_NO_PERIOD, ZONE_DESCRIPTION1);
private static final RecordSet A_RECORD_ZONE1 =
RecordSet.newBuilder("www." + ZONE1.getDnsName(), RecordSet.Type.A)
.setRecords(ImmutableList.of("123.123.55.1"))
.setTtl(25, TimeUnit.SECONDS)
.build();
private static final RecordSet AAAA_RECORD_ZONE1 =
RecordSet.newBuilder("www." + ZONE1.getDnsName(), RecordSet.Type.AAAA)
.setRecords(ImmutableList.of("ed:ed:12:aa:36:3:3:105"))
.setTtl(25, TimeUnit.SECONDS)
.build();
private static final ChangeRequestInfo CHANGE_ADD_ZONE1 =
ChangeRequest.newBuilder().add(A_RECORD_ZONE1).add(AAAA_RECORD_ZONE1).build();
private static final ChangeRequestInfo CHANGE_DELETE_ZONE1 =
ChangeRequest.newBuilder().delete(A_RECORD_ZONE1).delete(AAAA_RECORD_ZONE1).build();
private static final List<String> ZONE_NAMES =
ImmutableList.of(ZONE_NAME1, ZONE_NAME_EMPTY_DESCRIPTION);
@Rule public Timeout globalTimeout = Timeout.seconds(300);
private static void clear() {
for (String zoneName : ZONE_NAMES) {
Zone zone = DNS.getZone(zoneName);
if (zone != null) {
/* We wait for all changes to complete before retrieving a list of DNS records to be
deleted. Waiting is necessary as changes potentially might create more records between
when the list has been retrieved and executing the subsequent delete operation. */
Iterator<ChangeRequest> iterator = zone.listChangeRequests().iterateAll().iterator();
while (iterator.hasNext()) {
waitForChangeToComplete(zoneName, iterator.next().getGeneratedId());
}
Iterator<RecordSet> recordSetIterator = zone.listRecordSets().iterateAll().iterator();
List<RecordSet> toDelete = new LinkedList<>();
while (recordSetIterator.hasNext()) {
RecordSet recordSet = recordSetIterator.next();
if (!ImmutableList.of(RecordSet.Type.NS, RecordSet.Type.SOA)
.contains(recordSet.getType())) {
toDelete.add(recordSet);
}
}
if (!toDelete.isEmpty()) {
ChangeRequest deletion =
zone.applyChangeRequest(ChangeRequest.newBuilder().setDeletions(toDelete).build());
waitForChangeToComplete(zone.getName(), deletion.getGeneratedId());
}
zone.delete();
}
}
}
private static List<Zone> filter(Iterator<Zone> iterator) {
List<Zone> result = new LinkedList<>();
while (iterator.hasNext()) {
Zone zone = iterator.next();
if (ZONE_NAMES.contains(zone.getName())) {
result.add(zone);
}
}
return result;
}
@BeforeClass
public static void before() {
clear();
}
@AfterClass
public static void after() {
clear();
}
private static void assertEqChangesIgnoreStatus(ChangeRequest expected, ChangeRequest actual) {
assertEquals(expected.getAdditions(), actual.getAdditions());
assertEquals(expected.getDeletions(), actual.getDeletions());
assertEquals(expected.getGeneratedId(), actual.getGeneratedId());
assertEquals(expected.getStartTimeMillis(), actual.getStartTimeMillis());
}
private static void waitForChangeToComplete(String zoneName, String changeId) {
ChangeRequest changeRequest =
DNS.getChangeRequest(
zoneName, changeId, Dns.ChangeRequestOption.fields(ChangeRequestField.STATUS));
waitForChangeToComplete(changeRequest);
}
private static void waitForChangeToComplete(ChangeRequest changeRequest) {
while (!changeRequest.isDone()) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
fail("Thread was interrupted while waiting for change processing.");
}
}
}
@Test
public void testCreateValidZone() {
try {
Zone created = DNS.create(ZONE1);
assertEquals(ZONE1.getDescription(), created.getDescription());
assertEquals(ZONE1.getDnsName(), created.getDnsName());
assertEquals(ZONE1.getName(), created.getName());
assertNotNull(created.getCreationTimeMillis());
assertNotNull(created.getNameServers());
assertNull(created.getNameServerSet());
assertNotNull(created.getGeneratedId());
Zone retrieved = DNS.getZone(ZONE1.getName());
assertEquals(created, retrieved);
created = DNS.create(ZONE_EMPTY_DESCRIPTION);
assertEquals(ZONE_EMPTY_DESCRIPTION.getDescription(), created.getDescription());
assertEquals(ZONE_EMPTY_DESCRIPTION.getDnsName(), created.getDnsName());
assertEquals(ZONE_EMPTY_DESCRIPTION.getName(), created.getName());
assertNotNull(created.getCreationTimeMillis());
assertNotNull(created.getNameServers());
assertNull(created.getNameServerSet());
assertNotNull(created.getGeneratedId());
retrieved = DNS.getZone(ZONE_EMPTY_DESCRIPTION.getName());
assertEquals(created, retrieved);
} finally {
DNS.delete(ZONE1.getName());
DNS.delete(ZONE_EMPTY_DESCRIPTION.getName());
}
}
@Test
public void testCreateZoneWithErrors() {
try {
try {
DNS.create(ZONE_NAME_ERROR);
fail("Zone name is too long. The service returns an error.");
} catch (DnsException ex) {
// expected
assertFalse(ex.isRetryable());
}
try {
DNS.create(ZONE_DNS_NO_PERIOD);
fail("Zone name is missing a period. The service returns an error.");
} catch (DnsException ex) {
// expected
assertFalse(ex.isRetryable());
}
} finally {
DNS.delete(ZONE_NAME_ERROR.getName());
DNS.delete(ZONE_DNS_NO_PERIOD.getName());
}
}
@Test
public void testCreateZoneWithOptions() {
try {
Zone created = DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.CREATION_TIME));
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNotNull(created.getCreationTimeMillis());
assertNull(created.getDescription());
assertNull(created.getDnsName());
assertTrue(created.getNameServers().isEmpty()); // never returns null
assertNull(created.getNameServerSet());
assertNull(created.getGeneratedId());
created.delete();
created = DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.DESCRIPTION));
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNull(created.getCreationTimeMillis());
assertEquals(ZONE1.getDescription(), created.getDescription());
assertNull(created.getDnsName());
assertTrue(created.getNameServers().isEmpty()); // never returns null
assertNull(created.getNameServerSet());
assertNull(created.getGeneratedId());
created.delete();
created = DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.DNS_NAME));
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNull(created.getCreationTimeMillis());
assertEquals(ZONE1.getDnsName(), created.getDnsName());
assertNull(created.getDescription());
assertTrue(created.getNameServers().isEmpty()); // never returns null
assertNull(created.getNameServerSet());
assertNull(created.getGeneratedId());
created.delete();
created = DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME));
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNull(created.getCreationTimeMillis());
assertNull(created.getDnsName());
assertNull(created.getDescription());
assertTrue(created.getNameServers().isEmpty()); // never returns null
assertNull(created.getNameServerSet());
assertNull(created.getGeneratedId());
created.delete();
created = DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME_SERVER_SET));
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNull(created.getCreationTimeMillis());
assertNull(created.getDnsName());
assertNull(created.getDescription());
assertTrue(created.getNameServers().isEmpty()); // never returns null
assertNull(created.getNameServerSet()); // we did not set it
assertNull(created.getGeneratedId());
created.delete();
created = DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME_SERVERS));
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNull(created.getCreationTimeMillis());
assertNull(created.getDnsName());
assertNull(created.getDescription());
assertFalse(created.getNameServers().isEmpty());
assertNull(created.getNameServerSet());
assertNull(created.getGeneratedId());
created.delete();
created = DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.ZONE_ID));
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNull(created.getCreationTimeMillis());
assertNull(created.getDnsName());
assertNull(created.getDescription());
assertNotNull(created.getNameServers());
assertTrue(created.getNameServers().isEmpty()); // never returns null
assertNotNull(created.getGeneratedId());
created.delete();
// combination of multiple things
created =
DNS.create(
ZONE1,
Dns.ZoneOption.fields(
ZoneField.ZONE_ID,
ZoneField.NAME_SERVERS,
ZoneField.NAME_SERVER_SET,
ZoneField.DESCRIPTION));
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNull(created.getCreationTimeMillis());
assertNull(created.getDnsName());
assertEquals(ZONE1.getDescription(), created.getDescription());
assertFalse(created.getNameServers().isEmpty());
assertNull(created.getNameServerSet()); // we did not set it
assertNotNull(created.getGeneratedId());
} finally {
DNS.delete(ZONE1.getName());
}
}
@Test
public void testGetZone() {
try {
DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME));
Zone created = DNS.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.CREATION_TIME));
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNotNull(created.getCreationTimeMillis());
assertNull(created.getDescription());
assertNull(created.getDnsName());
assertTrue(created.getNameServers().isEmpty()); // never returns null
assertNull(created.getNameServerSet());
assertNull(created.getGeneratedId());
created = DNS.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.DESCRIPTION));
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNull(created.getCreationTimeMillis());
assertEquals(ZONE1.getDescription(), created.getDescription());
assertNull(created.getDnsName());
assertTrue(created.getNameServers().isEmpty()); // never returns null
assertNull(created.getNameServerSet());
assertNull(created.getGeneratedId());
created = DNS.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.DNS_NAME));
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNull(created.getCreationTimeMillis());
assertEquals(ZONE1.getDnsName(), created.getDnsName());
assertNull(created.getDescription());
assertTrue(created.getNameServers().isEmpty()); // never returns null
assertNull(created.getNameServerSet());
assertNull(created.getGeneratedId());
created = DNS.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.NAME));
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNull(created.getCreationTimeMillis());
assertNull(created.getDnsName());
assertNull(created.getDescription());
assertTrue(created.getNameServers().isEmpty()); // never returns null
assertNull(created.getNameServerSet());
assertNull(created.getGeneratedId());
created = DNS.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.NAME_SERVER_SET));
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNull(created.getCreationTimeMillis());
assertNull(created.getDnsName());
assertNull(created.getDescription());
assertTrue(created.getNameServers().isEmpty()); // never returns null
assertNull(created.getNameServerSet()); // we did not set it
assertNull(created.getGeneratedId());
created = DNS.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.NAME_SERVERS));
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNull(created.getCreationTimeMillis());
assertNull(created.getDnsName());
assertNull(created.getDescription());
assertFalse(created.getNameServers().isEmpty());
assertNull(created.getNameServerSet());
assertNull(created.getGeneratedId());
created = DNS.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.ZONE_ID));
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNull(created.getCreationTimeMillis());
assertNull(created.getDnsName());
assertNull(created.getDescription());
assertNotNull(created.getNameServers());
assertTrue(created.getNameServers().isEmpty()); // never returns null
assertNotNull(created.getGeneratedId());
// combination of multiple things
created =
DNS.getZone(
ZONE1.getName(),
Dns.ZoneOption.fields(
ZoneField.ZONE_ID,
ZoneField.NAME_SERVERS,
ZoneField.NAME_SERVER_SET,
ZoneField.DESCRIPTION));
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNull(created.getCreationTimeMillis());
assertNull(created.getDnsName());
assertEquals(ZONE1.getDescription(), created.getDescription());
assertFalse(created.getNameServers().isEmpty());
assertNull(created.getNameServerSet()); // we did not set it
assertNotNull(created.getGeneratedId());
} finally {
DNS.delete(ZONE1.getName());
}
}
@Test
public void testListZones() {
try {
List<Zone> zones = filter(DNS.listZones().iterateAll().iterator());
assertEquals(0, zones.size());
// some zones exists
Zone created = DNS.create(ZONE1);
zones = filter(DNS.listZones().iterateAll().iterator());
assertEquals(created, zones.get(0));
assertEquals(1, zones.size());
created = DNS.create(ZONE_EMPTY_DESCRIPTION);
zones = filter(DNS.listZones().iterateAll().iterator());
assertEquals(2, zones.size());
assertTrue(zones.contains(created));
// error in options
try {
DNS.listZones(Dns.ZoneListOption.pageSize(0));
fail();
} catch (DnsException ex) {
// expected
assertEquals(400, ex.getCode());
assertFalse(ex.isRetryable());
}
try {
DNS.listZones(Dns.ZoneListOption.pageSize(-1));
fail();
} catch (DnsException ex) {
// expected
assertEquals(400, ex.getCode());
assertFalse(ex.isRetryable());
}
// ok size
zones = filter(DNS.listZones(Dns.ZoneListOption.pageSize(1000)).iterateAll().iterator());
assertEquals(2, zones.size()); // we still have only 2 zones
// dns name problems
try {
DNS.listZones(Dns.ZoneListOption.dnsName("aaaaa"));
fail();
} catch (DnsException ex) {
// expected
assertEquals(400, ex.getCode());
assertFalse(ex.isRetryable());
}
// ok name
zones =
filter(
DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.getDnsName()))
.iterateAll()
.iterator());
assertEquals(1, zones.size());
// field options
Iterator<Zone> zoneIterator =
DNS.listZones(
Dns.ZoneListOption.dnsName(ZONE1.getDnsName()),
Dns.ZoneListOption.fields(ZoneField.ZONE_ID))
.iterateAll()
.iterator();
Zone zone = zoneIterator.next();
assertNull(zone.getCreationTimeMillis());
assertNotNull(zone.getName());
assertNull(zone.getDnsName());
assertNull(zone.getDescription());
assertNull(zone.getNameServerSet());
assertTrue(zone.getNameServers().isEmpty());
assertNotNull(zone.getGeneratedId());
assertFalse(zoneIterator.hasNext());
zoneIterator =
DNS.listZones(
Dns.ZoneListOption.dnsName(ZONE1.getDnsName()),
Dns.ZoneListOption.fields(ZoneField.CREATION_TIME))
.iterateAll()
.iterator();
zone = zoneIterator.next();
assertNotNull(zone.getCreationTimeMillis());
assertNotNull(zone.getName());
assertNull(zone.getDnsName());
assertNull(zone.getDescription());
assertNull(zone.getNameServerSet());
assertTrue(zone.getNameServers().isEmpty());
assertNull(zone.getGeneratedId());
assertFalse(zoneIterator.hasNext());
zoneIterator =
DNS.listZones(
Dns.ZoneListOption.dnsName(ZONE1.getDnsName()),
Dns.ZoneListOption.fields(ZoneField.DNS_NAME))
.iterateAll()
.iterator();
zone = zoneIterator.next();
assertNull(zone.getCreationTimeMillis());
assertNotNull(zone.getName());
assertNotNull(zone.getDnsName());
assertNull(zone.getDescription());
assertNull(zone.getNameServerSet());
assertTrue(zone.getNameServers().isEmpty());
assertNull(zone.getGeneratedId());
assertFalse(zoneIterator.hasNext());
zoneIterator =
DNS.listZones(
Dns.ZoneListOption.dnsName(ZONE1.getDnsName()),
Dns.ZoneListOption.fields(ZoneField.DESCRIPTION))
.iterateAll()
.iterator();
zone = zoneIterator.next();
assertNull(zone.getCreationTimeMillis());
assertNotNull(zone.getName());
assertNull(zone.getDnsName());
assertNotNull(zone.getDescription());
assertNull(zone.getNameServerSet());
assertTrue(zone.getNameServers().isEmpty());
assertNull(zone.getGeneratedId());
assertFalse(zoneIterator.hasNext());
zoneIterator =
DNS.listZones(
Dns.ZoneListOption.dnsName(ZONE1.getDnsName()),
Dns.ZoneListOption.fields(ZoneField.NAME_SERVERS))
.iterateAll()
.iterator();
zone = zoneIterator.next();
assertNull(zone.getCreationTimeMillis());
assertNotNull(zone.getName());
assertNull(zone.getDnsName());
assertNull(zone.getDescription());
assertNull(zone.getNameServerSet());
assertFalse(zone.getNameServers().isEmpty());
assertNull(zone.getGeneratedId());
assertFalse(zoneIterator.hasNext());
zoneIterator =
DNS.listZones(
Dns.ZoneListOption.dnsName(ZONE1.getDnsName()),
Dns.ZoneListOption.fields(ZoneField.NAME_SERVER_SET))
.iterateAll()
.iterator();
zone = zoneIterator.next();
assertNull(zone.getCreationTimeMillis());
assertNotNull(zone.getName());
assertNull(zone.getDnsName());
assertNull(zone.getDescription());
assertNull(zone.getNameServerSet()); // we cannot set it using google-cloud
assertTrue(zone.getNameServers().isEmpty());
assertNull(zone.getGeneratedId());
assertFalse(zoneIterator.hasNext());
// several combined
zones =
filter(
DNS.listZones(
Dns.ZoneListOption.fields(ZoneField.ZONE_ID, ZoneField.DESCRIPTION),
Dns.ZoneListOption.pageSize(1))
.iterateAll()
.iterator());
assertEquals(2, zones.size());
for (Zone current : zones) {
assertNull(current.getCreationTimeMillis());
assertNotNull(current.getName());
assertNull(current.getDnsName());
assertNotNull(current.getDescription());
assertNull(current.getNameServerSet());
assertTrue(zone.getNameServers().isEmpty());
assertNotNull(current.getGeneratedId());
}
} finally {
DNS.delete(ZONE1.getName());
DNS.delete(ZONE_EMPTY_DESCRIPTION.getName());
}
}
@Test
public void testDeleteZone() {
try {
Zone created = DNS.create(ZONE1);
assertEquals(created, DNS.getZone(ZONE1.getName()));
DNS.delete(ZONE1.getName());
assertNull(DNS.getZone(ZONE1.getName()));
} finally {
DNS.delete(ZONE1.getName());
}
}
@Test
public void testCreateChange() {
try {
DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME));
ChangeRequest created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1);
assertEquals(CHANGE_ADD_ZONE1.getAdditions(), created.getAdditions());
assertNotNull(created.getStartTimeMillis());
assertTrue(created.getDeletions().isEmpty());
assertNotNull(created.getGeneratedId());
assertTrue(
ImmutableList.of(ChangeRequest.Status.PENDING, ChangeRequest.Status.DONE)
.contains(created.status()));
assertEqChangesIgnoreStatus(created, DNS.getChangeRequest(ZONE1.getName(), "1"));
waitForChangeToComplete(created);
created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1);
waitForChangeToComplete(created);
// with options
created =
DNS.applyChangeRequest(
ZONE1.getName(),
CHANGE_ADD_ZONE1,
Dns.ChangeRequestOption.fields(ChangeRequestField.ID));
assertTrue(created.getAdditions().isEmpty());
assertNull(created.getStartTimeMillis());
assertTrue(created.getDeletions().isEmpty());
assertNotNull(created.getGeneratedId());
assertNull(created.status());
waitForChangeToComplete(created);
created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1);
waitForChangeToComplete(created);
created =
DNS.applyChangeRequest(
ZONE1.getName(),
CHANGE_ADD_ZONE1,
Dns.ChangeRequestOption.fields(ChangeRequestField.STATUS));
assertTrue(created.getAdditions().isEmpty());
assertNull(created.getStartTimeMillis());
assertTrue(created.getDeletions().isEmpty());
assertNotNull(created.getGeneratedId());
assertNotNull(created.status());
waitForChangeToComplete(created);
created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1);
waitForChangeToComplete(created);
created =
DNS.applyChangeRequest(
ZONE1.getName(),
CHANGE_ADD_ZONE1,
Dns.ChangeRequestOption.fields(ChangeRequestField.START_TIME));
assertTrue(created.getAdditions().isEmpty());
assertNotNull(created.getStartTimeMillis());
assertTrue(created.getDeletions().isEmpty());
assertNotNull(created.getGeneratedId());
assertNull(created.status());
waitForChangeToComplete(created);
created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1);
waitForChangeToComplete(created);
created =
DNS.applyChangeRequest(
ZONE1.getName(),
CHANGE_ADD_ZONE1,
Dns.ChangeRequestOption.fields(ChangeRequestField.ADDITIONS));
assertEquals(CHANGE_ADD_ZONE1.getAdditions(), created.getAdditions());
assertNull(created.getStartTimeMillis());
assertTrue(created.getDeletions().isEmpty());
assertNotNull(created.getGeneratedId());
assertNull(created.status());
// finishes with delete otherwise we cannot delete the zone
waitForChangeToComplete(created);
created =
DNS.applyChangeRequest(
ZONE1.getName(),
CHANGE_DELETE_ZONE1,
Dns.ChangeRequestOption.fields(ChangeRequestField.DELETIONS));
waitForChangeToComplete(created);
assertEquals(CHANGE_DELETE_ZONE1.getDeletions(), created.getDeletions());
assertNull(created.getStartTimeMillis());
assertTrue(created.getAdditions().isEmpty());
assertNotNull(created.getGeneratedId());
assertNull(created.status());
waitForChangeToComplete(created);
} finally {
clear();
}
}
@Test
public void testInvalidChangeRequest() {
Zone zone = DNS.create(ZONE1);
RecordSet validA =
RecordSet.newBuilder("subdomain." + zone.getDnsName(), RecordSet.Type.A)
.setRecords(ImmutableList.of("0.255.1.5"))
.build();
boolean recordAdded = false;
try {
ChangeRequestInfo validChange = ChangeRequest.newBuilder().add(validA).build();
zone.applyChangeRequest(validChange);
recordAdded = true;
try {
zone.applyChangeRequest(validChange);
fail("Created a record set which already exists.");
} catch (DnsException ex) {
// expected
assertFalse(ex.isRetryable());
assertEquals(409, ex.getCode());
}
// delete with field mismatch
RecordSet mismatch = validA.toBuilder().setTtl(20, TimeUnit.SECONDS).build();
ChangeRequestInfo deletion = ChangeRequest.newBuilder().delete(mismatch).build();
try {
zone.applyChangeRequest(deletion);
fail("Deleted a record set without a complete match.");
} catch (DnsException ex) {
// expected
assertEquals(412, ex.getCode());
assertFalse(ex.isRetryable());
}
// delete and add SOA
Iterator<RecordSet> recordSetIterator = zone.listRecordSets().iterateAll().iterator();
LinkedList<RecordSet> deletions = new LinkedList<>();
LinkedList<RecordSet> additions = new LinkedList<>();
while (recordSetIterator.hasNext()) {
RecordSet recordSet = recordSetIterator.next();
if (recordSet.getType() == RecordSet.Type.SOA) {
deletions.add(recordSet);
// the subdomain is necessary to get 400 instead of 412
RecordSet copy = recordSet.toBuilder().setName("x." + recordSet.getName()).build();
additions.add(copy);
break;
}
}
deletion = deletion.toBuilder().setDeletions(deletions).build();
ChangeRequestInfo addition = ChangeRequest.newBuilder().setAdditions(additions).build();
try {
zone.applyChangeRequest(deletion);
fail("Deleted SOA.");
} catch (DnsException ex) {
// expected
assertFalse(ex.isRetryable());
assertEquals(400, ex.getCode());
}
try {
zone.applyChangeRequest(addition);
fail("Added second SOA.");
} catch (DnsException ex) {
// expected
assertFalse(ex.isRetryable());
assertEquals(400, ex.getCode());
}
} finally {
if (recordAdded) {
ChangeRequestInfo deletion = ChangeRequest.newBuilder().delete(validA).build();
ChangeRequest request = zone.applyChangeRequest(deletion);
waitForChangeToComplete(zone.getName(), request.getGeneratedId());
}
zone.delete();
}
}
@Test
public void testListChanges() {
try {
// no such zone exists
try {
DNS.listChangeRequests(ZONE1.getName());
fail();
} catch (DnsException ex) {
// expected
assertEquals(404, ex.getCode());
assertFalse(ex.isRetryable());
}
// zone exists but has no changes
DNS.create(ZONE1);
ImmutableList<ChangeRequest> changes =
ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.getName()).iterateAll());
assertEquals(1, changes.size()); // default change creating SOA and NS
// zone has changes
ChangeRequest change = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1);
waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId());
change = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1);
waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId());
change = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1);
waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId());
change = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1);
waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId());
changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.getName()).iterateAll());
assertEquals(5, changes.size());
// error in options
try {
DNS.listChangeRequests(ZONE1.getName(), Dns.ChangeRequestListOption.pageSize(0));
fail();
} catch (DnsException ex) {
// expected
assertEquals(400, ex.getCode());
assertFalse(ex.isRetryable());
}
try {
DNS.listChangeRequests(ZONE1.getName(), Dns.ChangeRequestListOption.pageSize(-1));
fail();
} catch (DnsException ex) {
// expected
assertEquals(400, ex.getCode());
assertFalse(ex.isRetryable());
}
// sorting order
ImmutableList<ChangeRequest> ascending =
ImmutableList.copyOf(
DNS.listChangeRequests(
ZONE1.getName(),
Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING))
.iterateAll());
ImmutableList<ChangeRequest> descending =
ImmutableList.copyOf(
DNS.listChangeRequests(
ZONE1.getName(),
Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.DESCENDING))
.iterateAll());
int size = 5;
assertEquals(size, descending.size());
assertEquals(size, ascending.size());
for (int i = 0; i < size; i++) {
assertEquals(descending.get(i), ascending.get(size - i - 1));
}
// field options
changes =
ImmutableList.copyOf(
DNS.listChangeRequests(
ZONE1.getName(),
Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING),
Dns.ChangeRequestListOption.fields(ChangeRequestField.ADDITIONS))
.iterateAll());
change = changes.get(1);
assertEquals(CHANGE_ADD_ZONE1.getAdditions(), change.getAdditions());
assertTrue(change.getDeletions().isEmpty());
assertNotNull(change.getGeneratedId());
assertNull(change.getStartTimeMillis());
assertNull(change.status());
changes =
ImmutableList.copyOf(
DNS.listChangeRequests(
ZONE1.getName(),
Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING),
Dns.ChangeRequestListOption.fields(ChangeRequestField.DELETIONS))
.iterateAll());
change = changes.get(2);
assertTrue(change.getAdditions().isEmpty());
assertNotNull(change.getDeletions());
assertNotNull(change.getGeneratedId());
assertNull(change.getStartTimeMillis());
assertNull(change.status());
changes =
ImmutableList.copyOf(
DNS.listChangeRequests(
ZONE1.getName(),
Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING),
Dns.ChangeRequestListOption.fields(ChangeRequestField.ID))
.iterateAll());
change = changes.get(1);
assertTrue(change.getAdditions().isEmpty());
assertTrue(change.getDeletions().isEmpty());
assertNotNull(change.getGeneratedId());
assertNull(change.getStartTimeMillis());
assertNull(change.status());
changes =
ImmutableList.copyOf(
DNS.listChangeRequests(
ZONE1.getName(),
Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING),
Dns.ChangeRequestListOption.fields(ChangeRequestField.START_TIME))
.iterateAll());
change = changes.get(1);
assertTrue(change.getAdditions().isEmpty());
assertTrue(change.getDeletions().isEmpty());
assertNotNull(change.getGeneratedId());
assertNotNull(change.getStartTimeMillis());
assertNull(change.status());
changes =
ImmutableList.copyOf(
DNS.listChangeRequests(
ZONE1.getName(),
Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING),
Dns.ChangeRequestListOption.fields(ChangeRequestField.STATUS))
.iterateAll());
change = changes.get(1);
assertTrue(change.getAdditions().isEmpty());
assertTrue(change.getDeletions().isEmpty());
assertNotNull(change.getGeneratedId());
assertNull(change.getStartTimeMillis());
assertEquals(ChangeRequest.Status.DONE, change.status());
} finally {
clear();
}
}
@Test
public void testGetChange() {
try {
Zone zone = DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME));
ChangeRequest created = zone.applyChangeRequest(CHANGE_ADD_ZONE1);
ChangeRequest retrieved = DNS.getChangeRequest(zone.getName(), created.getGeneratedId());
assertEqChangesIgnoreStatus(created, retrieved);
waitForChangeToComplete(zone.getName(), created.getGeneratedId());
zone.applyChangeRequest(CHANGE_DELETE_ZONE1);
// with options
created =
zone.applyChangeRequest(
CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.ID));
retrieved =
DNS.getChangeRequest(
zone.getName(),
created.getGeneratedId(),
Dns.ChangeRequestOption.fields(ChangeRequestField.ID));
assertEqChangesIgnoreStatus(created, retrieved);
waitForChangeToComplete(zone.getName(), created.getGeneratedId());
zone.applyChangeRequest(CHANGE_DELETE_ZONE1);
created =
zone.applyChangeRequest(
CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.STATUS));
retrieved =
DNS.getChangeRequest(
zone.getName(),
created.getGeneratedId(),
Dns.ChangeRequestOption.fields(ChangeRequestField.STATUS));
assertEqChangesIgnoreStatus(created, retrieved);
waitForChangeToComplete(zone.getName(), created.getGeneratedId());
zone.applyChangeRequest(CHANGE_DELETE_ZONE1);
created =
zone.applyChangeRequest(
CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.START_TIME));
retrieved =
DNS.getChangeRequest(
zone.getName(),
created.getGeneratedId(),
Dns.ChangeRequestOption.fields(ChangeRequestField.START_TIME));
assertEqChangesIgnoreStatus(created, retrieved);
waitForChangeToComplete(zone.getName(), created.getGeneratedId());
zone.applyChangeRequest(CHANGE_DELETE_ZONE1);
created =
zone.applyChangeRequest(
CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.ADDITIONS));
retrieved =
DNS.getChangeRequest(
zone.getName(),
created.getGeneratedId(),
Dns.ChangeRequestOption.fields(ChangeRequestField.ADDITIONS));
assertEqChangesIgnoreStatus(created, retrieved);
waitForChangeToComplete(zone.getName(), created.getGeneratedId());
// finishes with delete otherwise we cannot delete the zone
created =
zone.applyChangeRequest(
CHANGE_DELETE_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.DELETIONS));
retrieved =
DNS.getChangeRequest(
zone.getName(),
created.getGeneratedId(),
Dns.ChangeRequestOption.fields(ChangeRequestField.DELETIONS));
assertEqChangesIgnoreStatus(created, retrieved);
waitForChangeToComplete(zone.getName(), created.getGeneratedId());
} finally {
clear();
}
}
@Test
public void testGetProject() {
// fetches all fields
ProjectInfo project = DNS.getProject();
assertNotNull(project.getQuota());
// options
project = DNS.getProject(Dns.ProjectOption.fields(ProjectField.QUOTA));
assertNotNull(project.getQuota());
project = DNS.getProject(Dns.ProjectOption.fields(ProjectField.PROJECT_ID));
assertNull(project.getQuota());
project = DNS.getProject(Dns.ProjectOption.fields(ProjectField.PROJECT_NUMBER));
assertNull(project.getQuota());
project =
DNS.getProject(
Dns.ProjectOption.fields(
ProjectField.PROJECT_NUMBER, ProjectField.QUOTA, ProjectField.PROJECT_ID));
assertNotNull(project.getQuota());
}
@Test
public void testListDnsRecords() {
try {
Zone zone = DNS.create(ZONE1);
ImmutableList<RecordSet> recordSets =
ImmutableList.copyOf(DNS.listRecordSets(zone.getName()).iterateAll());
assertEquals(2, recordSets.size());
ImmutableList<RecordSet.Type> defaultRecords =
ImmutableList.of(RecordSet.Type.NS, RecordSet.Type.SOA);
for (RecordSet recordSet : recordSets) {
assertTrue(defaultRecords.contains(recordSet.getType()));
}
// field options
Iterator<RecordSet> recordSetIterator =
DNS.listRecordSets(zone.getName(), Dns.RecordSetListOption.fields(RecordSetField.TTL))
.iterateAll()
.iterator();
int counter = 0;
while (recordSetIterator.hasNext()) {
RecordSet recordSet = recordSetIterator.next();
assertEquals(recordSets.get(counter).getTtl(), recordSet.getTtl());
assertEquals(recordSets.get(counter).getName(), recordSet.getName());
assertEquals(recordSets.get(counter).getType(), recordSet.getType());
assertTrue(recordSet.getRecords().isEmpty());
counter++;
}
assertEquals(2, counter);
recordSetIterator =
DNS.listRecordSets(zone.getName(), Dns.RecordSetListOption.fields(RecordSetField.NAME))
.iterateAll()
.iterator();
counter = 0;
while (recordSetIterator.hasNext()) {
RecordSet recordSet = recordSetIterator.next();
assertEquals(recordSets.get(counter).getName(), recordSet.getName());
assertEquals(recordSets.get(counter).getType(), recordSet.getType());
assertTrue(recordSet.getRecords().isEmpty());
assertNull(recordSet.getTtl());
counter++;
}
assertEquals(2, counter);
recordSetIterator =
DNS.listRecordSets(
zone.getName(), Dns.RecordSetListOption.fields(RecordSetField.DNS_RECORDS))
.iterateAll()
.iterator();
counter = 0;
while (recordSetIterator.hasNext()) {
RecordSet recordSet = recordSetIterator.next();
assertEquals(recordSets.get(counter).getRecords(), recordSet.getRecords());
assertEquals(recordSets.get(counter).getName(), recordSet.getName());
assertEquals(recordSets.get(counter).getType(), recordSet.getType());
assertNull(recordSet.getTtl());
counter++;
}
assertEquals(2, counter);
recordSetIterator =
DNS.listRecordSets(
zone.getName(),
Dns.RecordSetListOption.fields(RecordSetField.TYPE),
Dns.RecordSetListOption.pageSize(1))
.iterateAll()
.iterator(); // also test paging
counter = 0;
while (recordSetIterator.hasNext()) {
RecordSet recordSet = recordSetIterator.next();
assertEquals(recordSets.get(counter).getType(), recordSet.getType());
assertEquals(recordSets.get(counter).getName(), recordSet.getName());
assertTrue(recordSet.getRecords().isEmpty());
assertNull(recordSet.getTtl());
counter++;
}
assertEquals(2, counter);
// test page size
Page<RecordSet> recordSetPage =
DNS.listRecordSets(
zone.getName(),
Dns.RecordSetListOption.fields(RecordSetField.TYPE),
Dns.RecordSetListOption.pageSize(1));
assertEquals(1, ImmutableList.copyOf(recordSetPage.getValues().iterator()).size());
// test name filter
ChangeRequest change = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1);
waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId());
recordSetIterator =
DNS.listRecordSets(
ZONE1.getName(), Dns.RecordSetListOption.dnsName(A_RECORD_ZONE1.getName()))
.iterateAll()
.iterator();
counter = 0;
while (recordSetIterator.hasNext()) {
RecordSet recordSet = recordSetIterator.next();
assertTrue(
ImmutableList.of(A_RECORD_ZONE1.getType(), AAAA_RECORD_ZONE1.getType())
.contains(recordSet.getType()));
counter++;
}
assertEquals(2, counter);
// test type filter
waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId());
recordSetIterator =
DNS.listRecordSets(
ZONE1.getName(),
Dns.RecordSetListOption.dnsName(A_RECORD_ZONE1.getName()),
Dns.RecordSetListOption.type(A_RECORD_ZONE1.getType()))
.iterateAll()
.iterator();
counter = 0;
while (recordSetIterator.hasNext()) {
RecordSet recordSet = recordSetIterator.next();
assertEquals(A_RECORD_ZONE1, recordSet);
counter++;
}
assertEquals(1, counter);
change = zone.applyChangeRequest(CHANGE_DELETE_ZONE1);
// check wrong arguments
try {
// name is not set
DNS.listRecordSets(ZONE1.getName(), Dns.RecordSetListOption.type(A_RECORD_ZONE1.getType()));
fail();
} catch (DnsException ex) {
// expected
assertEquals(400, ex.getCode());
assertFalse(ex.isRetryable());
}
try {
DNS.listRecordSets(ZONE1.getName(), Dns.RecordSetListOption.pageSize(0));
fail();
} catch (DnsException ex) {
// expected
assertEquals(400, ex.getCode());
assertFalse(ex.isRetryable());
}
try {
DNS.listRecordSets(ZONE1.getName(), Dns.RecordSetListOption.pageSize(-1));
fail();
} catch (DnsException ex) {
// expected
assertEquals(400, ex.getCode());
assertFalse(ex.isRetryable());
}
waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId());
} finally {
clear();
}
}
@Test
public void testListZonesBatch() {
try {
DnsBatch batch = DNS.batch();
DnsBatchResult<Page<Zone>> result = batch.listZones();
batch.submit();
List<Zone> zones = filter(result.get().iterateAll().iterator());
assertEquals(0, zones.size());
// some zones exists
Zone firstZone = DNS.create(ZONE1);
batch = DNS.batch();
result = batch.listZones();
batch.submit();
zones = filter(result.get().iterateAll().iterator());
assertEquals(1, zones.size());
assertEquals(firstZone, zones.get(0));
Zone created = DNS.create(ZONE_EMPTY_DESCRIPTION);
batch = DNS.batch();
result = batch.listZones();
DnsBatchResult<Page<Zone>> zeroSizeError = batch.listZones(Dns.ZoneListOption.pageSize(0));
DnsBatchResult<Page<Zone>> negativeSizeError =
batch.listZones(Dns.ZoneListOption.pageSize(-1));
DnsBatchResult<Page<Zone>> okSize = batch.listZones(Dns.ZoneListOption.pageSize(1));
DnsBatchResult<Page<Zone>> nameError = batch.listZones(Dns.ZoneListOption.dnsName("aaaaa"));
DnsBatchResult<Page<Zone>> okName =
batch.listZones(Dns.ZoneListOption.dnsName(ZONE1.getDnsName()));
DnsBatchResult<Page<Zone>> idResult =
batch.listZones(
Dns.ZoneListOption.dnsName(ZONE1.getDnsName()),
Dns.ZoneListOption.fields(ZoneField.ZONE_ID));
DnsBatchResult<Page<Zone>> timeResult =
batch.listZones(
Dns.ZoneListOption.dnsName(ZONE1.getDnsName()),
Dns.ZoneListOption.fields(ZoneField.CREATION_TIME));
DnsBatchResult<Page<Zone>> dnsNameResult =
batch.listZones(
Dns.ZoneListOption.dnsName(ZONE1.getDnsName()),
Dns.ZoneListOption.fields(ZoneField.DNS_NAME));
DnsBatchResult<Page<Zone>> descriptionResult =
batch.listZones(
Dns.ZoneListOption.dnsName(ZONE1.getDnsName()),
Dns.ZoneListOption.fields(ZoneField.DESCRIPTION));
DnsBatchResult<Page<Zone>> nameServersResult =
batch.listZones(
Dns.ZoneListOption.dnsName(ZONE1.getDnsName()),
Dns.ZoneListOption.fields(ZoneField.NAME_SERVERS));
DnsBatchResult<Page<Zone>> nameServerSetResult =
batch.listZones(
Dns.ZoneListOption.dnsName(ZONE1.getDnsName()),
Dns.ZoneListOption.fields(ZoneField.NAME_SERVER_SET));
DnsBatchResult<Page<Zone>> combinationResult =
batch.listZones(
Dns.ZoneListOption.fields(ZoneField.ZONE_ID, ZoneField.DESCRIPTION),
Dns.ZoneListOption.pageSize(1));
batch.submit();
zones = filter(result.get().iterateAll().iterator());
assertEquals(2, zones.size());
assertTrue(zones.contains(firstZone));
assertTrue(zones.contains(created));
// error in options
try {
zeroSizeError.get();
fail();
} catch (DnsException ex) {
// expected
assertEquals(400, ex.getCode());
assertFalse(ex.isRetryable());
}
try {
negativeSizeError.get();
fail();
} catch (DnsException ex) {
// expected
assertEquals(400, ex.getCode());
assertFalse(ex.isRetryable());
}
// ok size
assertEquals(1, Iterables.size(okSize.get().getValues()));
// dns name problems
try {
nameError.get();
fail();
} catch (DnsException ex) {
// expected
assertEquals(400, ex.getCode());
assertFalse(ex.isRetryable());
}
// ok name
zones = filter(okName.get().iterateAll().iterator());
assertEquals(1, zones.size());
// field options
Iterator<Zone> zoneIterator = idResult.get().iterateAll().iterator();
Zone zone = zoneIterator.next();
assertNull(zone.getCreationTimeMillis());
assertNotNull(zone.getName());
assertNull(zone.getDnsName());
assertNull(zone.getDescription());
assertNull(zone.getNameServerSet());
assertTrue(zone.getNameServers().isEmpty());
assertNotNull(zone.getGeneratedId());
assertFalse(zoneIterator.hasNext());
zoneIterator = timeResult.get().iterateAll().iterator();
zone = zoneIterator.next();
assertNotNull(zone.getCreationTimeMillis());
assertNotNull(zone.getName());
assertNull(zone.getDnsName());
assertNull(zone.getDescription());
assertNull(zone.getNameServerSet());
assertTrue(zone.getNameServers().isEmpty());
assertNull(zone.getGeneratedId());
assertFalse(zoneIterator.hasNext());
zoneIterator = dnsNameResult.get().iterateAll().iterator();
zone = zoneIterator.next();
assertNull(zone.getCreationTimeMillis());
assertNotNull(zone.getName());
assertNotNull(zone.getDnsName());
assertNull(zone.getDescription());
assertNull(zone.getNameServerSet());
assertTrue(zone.getNameServers().isEmpty());
assertNull(zone.getGeneratedId());
assertFalse(zoneIterator.hasNext());
zoneIterator = descriptionResult.get().iterateAll().iterator();
zone = zoneIterator.next();
assertNull(zone.getCreationTimeMillis());
assertNotNull(zone.getName());
assertNull(zone.getDnsName());
assertNotNull(zone.getDescription());
assertNull(zone.getNameServerSet());
assertTrue(zone.getNameServers().isEmpty());
assertNull(zone.getGeneratedId());
assertFalse(zoneIterator.hasNext());
zoneIterator = nameServersResult.get().iterateAll().iterator();
zone = zoneIterator.next();
assertNull(zone.getCreationTimeMillis());
assertNotNull(zone.getName());
assertNull(zone.getDnsName());
assertNull(zone.getDescription());
assertNull(zone.getNameServerSet());
assertFalse(zone.getNameServers().isEmpty());
assertNull(zone.getGeneratedId());
assertFalse(zoneIterator.hasNext());
zoneIterator = nameServerSetResult.get().iterateAll().iterator();
zone = zoneIterator.next();
assertNull(zone.getCreationTimeMillis());
assertNotNull(zone.getName());
assertNull(zone.getDnsName());
assertNull(zone.getDescription());
assertNull(zone.getNameServerSet()); // we cannot set it using google-cloud
assertTrue(zone.getNameServers().isEmpty());
assertNull(zone.getGeneratedId());
assertFalse(zoneIterator.hasNext());
// several combined
zones = filter(combinationResult.get().iterateAll().iterator());
assertEquals(2, zones.size());
for (Zone current : zones) {
assertNull(current.getCreationTimeMillis());
assertNotNull(current.getName());
assertNull(current.getDnsName());
assertNotNull(current.getDescription());
assertNull(current.getNameServerSet());
assertTrue(zone.getNameServers().isEmpty());
assertNotNull(current.getGeneratedId());
}
} finally {
DNS.delete(ZONE1.getName());
DNS.delete(ZONE_EMPTY_DESCRIPTION.getName());
}
}
@Test
public void testCreateValidZoneBatch() {
try {
DnsBatch batch = DNS.batch();
DnsBatchResult<Zone> completeZoneResult = batch.createZone(ZONE1);
DnsBatchResult<Zone> partialZoneResult = batch.createZone(ZONE_EMPTY_DESCRIPTION);
batch.submit();
Zone created = completeZoneResult.get();
assertEquals(ZONE1.getDescription(), created.getDescription());
assertEquals(ZONE1.getDnsName(), created.getDnsName());
assertEquals(ZONE1.getName(), created.getName());
assertNotNull(created.getCreationTimeMillis());
assertNotNull(created.getNameServers());
assertNull(created.getNameServerSet());
assertNotNull(created.getGeneratedId());
Zone retrieved = DNS.getZone(ZONE1.getName());
assertEquals(created, retrieved);
created = partialZoneResult.get();
assertEquals(ZONE_EMPTY_DESCRIPTION.getDescription(), created.getDescription());
assertEquals(ZONE_EMPTY_DESCRIPTION.getDnsName(), created.getDnsName());
assertEquals(ZONE_EMPTY_DESCRIPTION.getName(), created.getName());
assertNotNull(created.getCreationTimeMillis());
assertNotNull(created.getNameServers());
assertNull(created.getNameServerSet());
assertNotNull(created.getGeneratedId());
retrieved = DNS.getZone(ZONE_EMPTY_DESCRIPTION.getName());
assertEquals(created, retrieved);
} finally {
DNS.delete(ZONE1.getName());
DNS.delete(ZONE_EMPTY_DESCRIPTION.getName());
}
}
@Test
public void testCreateZoneWithErrorsBatch() {
try {
DnsBatch batch = DNS.batch();
DnsBatchResult<Zone> nameErrorResult = batch.createZone(ZONE_NAME_ERROR);
DnsBatchResult<Zone> noPeriodResult = batch.createZone(ZONE_DNS_NO_PERIOD);
batch.submit();
try {
nameErrorResult.get();
fail("Zone name is too long. The service returns an error.");
} catch (DnsException ex) {
// expected
assertFalse(ex.isRetryable());
}
try {
noPeriodResult.get();
fail("Zone name is missing a period. The service returns an error.");
} catch (DnsException ex) {
// expected
assertFalse(ex.isRetryable());
}
} finally {
DNS.delete(ZONE_NAME_ERROR.getName());
DNS.delete(ZONE_DNS_NO_PERIOD.getName());
}
}
@Test
public void testCreateZoneWithOptionsBatch() {
try {
DnsBatch batch = DNS.batch();
DnsBatchResult<Zone> batchResult =
batch.createZone(ZONE1, Dns.ZoneOption.fields(ZoneField.CREATION_TIME));
batch.submit();
Zone created = batchResult.get();
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNotNull(created.getCreationTimeMillis());
assertNull(created.getDescription());
assertNull(created.getDnsName());
assertTrue(created.getNameServers().isEmpty()); // never returns null
assertNull(created.getNameServerSet());
assertNull(created.getGeneratedId());
created.delete();
batch = DNS.batch();
batchResult = batch.createZone(ZONE1, Dns.ZoneOption.fields(ZoneField.DESCRIPTION));
batch.submit();
created = batchResult.get();
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNull(created.getCreationTimeMillis());
assertEquals(ZONE1.getDescription(), created.getDescription());
assertNull(created.getDnsName());
assertTrue(created.getNameServers().isEmpty()); // never returns null
assertNull(created.getNameServerSet());
assertNull(created.getGeneratedId());
created.delete();
batch = DNS.batch();
batchResult = batch.createZone(ZONE1, Dns.ZoneOption.fields(ZoneField.DNS_NAME));
batch.submit();
created = batchResult.get();
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNull(created.getCreationTimeMillis());
assertEquals(ZONE1.getDnsName(), created.getDnsName());
assertNull(created.getDescription());
assertTrue(created.getNameServers().isEmpty()); // never returns null
assertNull(created.getNameServerSet());
assertNull(created.getGeneratedId());
created.delete();
batch = DNS.batch();
batchResult = batch.createZone(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME));
batch.submit();
created = batchResult.get();
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNull(created.getCreationTimeMillis());
assertNull(created.getDnsName());
assertNull(created.getDescription());
assertTrue(created.getNameServers().isEmpty()); // never returns null
assertNull(created.getNameServerSet());
assertNull(created.getGeneratedId());
created.delete();
batch = DNS.batch();
batchResult = batch.createZone(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME_SERVER_SET));
batch.submit();
created = batchResult.get();
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNull(created.getCreationTimeMillis());
assertNull(created.getDnsName());
assertNull(created.getDescription());
assertTrue(created.getNameServers().isEmpty()); // never returns null
assertNull(created.getNameServerSet()); // we did not set it
assertNull(created.getGeneratedId());
created.delete();
batch = DNS.batch();
batchResult = batch.createZone(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME_SERVERS));
batch.submit();
created = batchResult.get();
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNull(created.getCreationTimeMillis());
assertNull(created.getDnsName());
assertNull(created.getDescription());
assertFalse(created.getNameServers().isEmpty());
assertNull(created.getNameServerSet());
assertNull(created.getGeneratedId());
created.delete();
batch = DNS.batch();
batchResult = batch.createZone(ZONE1, Dns.ZoneOption.fields(ZoneField.ZONE_ID));
batch.submit();
created = batchResult.get();
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNull(created.getCreationTimeMillis());
assertNull(created.getDnsName());
assertNull(created.getDescription());
assertNotNull(created.getNameServers());
assertTrue(created.getNameServers().isEmpty()); // never returns null
assertNotNull(created.getGeneratedId());
created.delete();
batch = DNS.batch();
batchResult =
batch.createZone(
ZONE1,
Dns.ZoneOption.fields(
ZoneField.ZONE_ID,
ZoneField.NAME_SERVERS,
ZoneField.NAME_SERVER_SET,
ZoneField.DESCRIPTION));
batch.submit();
// combination of multiple things
created = batchResult.get();
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNull(created.getCreationTimeMillis());
assertNull(created.getDnsName());
assertEquals(ZONE1.getDescription(), created.getDescription());
assertFalse(created.getNameServers().isEmpty());
assertNull(created.getNameServerSet()); // we did not set it
assertNotNull(created.getGeneratedId());
} finally {
DNS.delete(ZONE1.getName());
}
}
@Test
public void testGetZoneBatch() {
try {
DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME));
DnsBatch batch = DNS.batch();
DnsBatchResult<Zone> timeResult =
batch.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.CREATION_TIME));
DnsBatchResult<Zone> descriptionResult =
batch.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.DESCRIPTION));
DnsBatchResult<Zone> dnsNameResult =
batch.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.DNS_NAME));
DnsBatchResult<Zone> nameResult =
batch.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.NAME));
DnsBatchResult<Zone> nameServerSetResult =
batch.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.NAME_SERVER_SET));
DnsBatchResult<Zone> nameServersResult =
batch.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.NAME_SERVERS));
DnsBatchResult<Zone> idResult =
batch.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.ZONE_ID));
DnsBatchResult<Zone> combinationResult =
batch.getZone(
ZONE1.getName(),
Dns.ZoneOption.fields(
ZoneField.ZONE_ID,
ZoneField.NAME_SERVERS,
ZoneField.NAME_SERVER_SET,
ZoneField.DESCRIPTION));
batch.submit();
Zone created = timeResult.get();
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNotNull(created.getCreationTimeMillis());
assertNull(created.getDescription());
assertNull(created.getDnsName());
assertTrue(created.getNameServers().isEmpty()); // never returns null
assertNull(created.getNameServerSet());
assertNull(created.getGeneratedId());
created = descriptionResult.get();
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNull(created.getCreationTimeMillis());
assertEquals(ZONE1.getDescription(), created.getDescription());
assertNull(created.getDnsName());
assertTrue(created.getNameServers().isEmpty()); // never returns null
assertNull(created.getNameServerSet());
assertNull(created.getGeneratedId());
created = dnsNameResult.get();
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNull(created.getCreationTimeMillis());
assertEquals(ZONE1.getDnsName(), created.getDnsName());
assertNull(created.getDescription());
assertTrue(created.getNameServers().isEmpty()); // never returns null
assertNull(created.getNameServerSet());
assertNull(created.getGeneratedId());
created = nameResult.get();
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNull(created.getCreationTimeMillis());
assertNull(created.getDnsName());
assertNull(created.getDescription());
assertTrue(created.getNameServers().isEmpty()); // never returns null
assertNull(created.getNameServerSet());
assertNull(created.getGeneratedId());
created = nameServerSetResult.get();
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNull(created.getCreationTimeMillis());
assertNull(created.getDnsName());
assertNull(created.getDescription());
assertTrue(created.getNameServers().isEmpty()); // never returns null
assertNull(created.getNameServerSet()); // we did not set it
assertNull(created.getGeneratedId());
created = nameServersResult.get();
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNull(created.getCreationTimeMillis());
assertNull(created.getDnsName());
assertNull(created.getDescription());
assertFalse(created.getNameServers().isEmpty());
assertNull(created.getNameServerSet());
assertNull(created.getGeneratedId());
created = idResult.get();
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNull(created.getCreationTimeMillis());
assertNull(created.getDnsName());
assertNull(created.getDescription());
assertNotNull(created.getNameServers());
assertTrue(created.getNameServers().isEmpty()); // never returns null
assertNotNull(created.getGeneratedId());
// combination of multiple things
created = combinationResult.get();
assertEquals(ZONE1.getName(), created.getName()); // always returned
assertNull(created.getCreationTimeMillis());
assertNull(created.getDnsName());
assertEquals(ZONE1.getDescription(), created.getDescription());
assertFalse(created.getNameServers().isEmpty());
assertNull(created.getNameServerSet()); // we did not set it
assertNotNull(created.getGeneratedId());
} finally {
DNS.delete(ZONE1.getName());
}
}
@Test
public void testDeleteZoneBatch() {
try {
Zone created = DNS.create(ZONE1);
assertEquals(created, DNS.getZone(ZONE1.getName()));
DnsBatch batch = DNS.batch();
DnsBatchResult<Boolean> result = batch.deleteZone(ZONE1.getName());
batch.submit();
assertNull(DNS.getZone(ZONE1.getName()));
assertTrue(result.get());
} finally {
DNS.delete(ZONE1.getName());
}
}
@Test
public void testGetProjectBatch() {
// fetches all fields
DnsBatch batch = DNS.batch();
DnsBatchResult<ProjectInfo> result = batch.getProject();
DnsBatchResult<ProjectInfo> resultQuota =
batch.getProject(Dns.ProjectOption.fields(ProjectField.QUOTA));
DnsBatchResult<ProjectInfo> resultId =
batch.getProject(Dns.ProjectOption.fields(ProjectField.PROJECT_ID));
DnsBatchResult<ProjectInfo> resultNumber =
batch.getProject(Dns.ProjectOption.fields(ProjectField.PROJECT_NUMBER));
DnsBatchResult<ProjectInfo> resultCombination =
batch.getProject(
Dns.ProjectOption.fields(
ProjectField.PROJECT_NUMBER, ProjectField.QUOTA, ProjectField.PROJECT_ID));
batch.submit();
assertNotNull(result.get().getQuota());
assertNotNull(resultQuota.get().getQuota());
assertNull(resultId.get().getQuota());
assertNull(resultNumber.get().getQuota());
assertNotNull(resultCombination.get().getQuota());
}
@Test
public void testCreateChangeBatch() {
try {
DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME));
DnsBatch batch = DNS.batch();
DnsBatchResult<ChangeRequest> result =
batch.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1);
batch.submit();
ChangeRequest created = result.get();
assertEquals(CHANGE_ADD_ZONE1.getAdditions(), created.getAdditions());
assertNotNull(created.getStartTimeMillis());
assertTrue(created.getDeletions().isEmpty());
assertNotNull(created.getGeneratedId());
assertTrue(
ImmutableList.of(ChangeRequest.Status.PENDING, ChangeRequest.Status.DONE)
.contains(created.status()));
assertEqChangesIgnoreStatus(created, DNS.getChangeRequest(ZONE1.getName(), "1"));
waitForChangeToComplete(created);
created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1);
waitForChangeToComplete(created);
// with options
batch = DNS.batch();
result =
batch.applyChangeRequest(
ZONE1.getName(),
CHANGE_ADD_ZONE1,
Dns.ChangeRequestOption.fields(ChangeRequestField.ID));
batch.submit();
created = result.get();
assertTrue(created.getAdditions().isEmpty());
assertNull(created.getStartTimeMillis());
assertTrue(created.getDeletions().isEmpty());
assertNotNull(created.getGeneratedId());
assertNull(created.status());
waitForChangeToComplete(created);
created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1);
waitForChangeToComplete(created);
batch = DNS.batch();
result =
batch.applyChangeRequest(
ZONE1.getName(),
CHANGE_ADD_ZONE1,
Dns.ChangeRequestOption.fields(ChangeRequestField.STATUS));
batch.submit();
created = result.get();
assertTrue(created.getAdditions().isEmpty());
assertNull(created.getStartTimeMillis());
assertTrue(created.getDeletions().isEmpty());
assertNotNull(created.getGeneratedId());
assertNotNull(created.status());
waitForChangeToComplete(created);
created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1);
waitForChangeToComplete(created);
batch = DNS.batch();
result =
batch.applyChangeRequest(
ZONE1.getName(),
CHANGE_ADD_ZONE1,
Dns.ChangeRequestOption.fields(ChangeRequestField.START_TIME));
batch.submit();
created = result.get();
assertTrue(created.getAdditions().isEmpty());
assertNotNull(created.getStartTimeMillis());
assertTrue(created.getDeletions().isEmpty());
assertNotNull(created.getGeneratedId());
assertNull(created.status());
waitForChangeToComplete(created);
created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1);
waitForChangeToComplete(created);
batch = DNS.batch();
result =
batch.applyChangeRequest(
ZONE1.getName(),
CHANGE_ADD_ZONE1,
Dns.ChangeRequestOption.fields(ChangeRequestField.ADDITIONS));
batch.submit();
created = result.get();
assertEquals(CHANGE_ADD_ZONE1.getAdditions(), created.getAdditions());
assertNull(created.getStartTimeMillis());
assertTrue(created.getDeletions().isEmpty());
assertNotNull(created.getGeneratedId());
assertNull(created.status());
// finishes with delete otherwise we cannot delete the zone
waitForChangeToComplete(created);
batch = DNS.batch();
result =
batch.applyChangeRequest(
ZONE1.getName(),
CHANGE_DELETE_ZONE1,
Dns.ChangeRequestOption.fields(ChangeRequestField.DELETIONS));
batch.submit();
created = result.get();
waitForChangeToComplete(created);
assertEquals(CHANGE_DELETE_ZONE1.getDeletions(), created.getDeletions());
assertNull(created.getStartTimeMillis());
assertTrue(created.getAdditions().isEmpty());
assertNotNull(created.getGeneratedId());
assertNull(created.status());
waitForChangeToComplete(created);
} finally {
clear();
}
}
@Test
public void testGetChangeBatch() {
try {
Zone zone = DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME));
ChangeRequest created = zone.applyChangeRequest(CHANGE_ADD_ZONE1);
waitForChangeToComplete(zone.getName(), created.getGeneratedId());
DnsBatch batch = DNS.batch();
DnsBatchResult<ChangeRequest> completeResult =
batch.getChangeRequest(zone.getName(), created.getGeneratedId());
DnsBatchResult<ChangeRequest> idResult =
batch.getChangeRequest(
zone.getName(),
created.getGeneratedId(),
Dns.ChangeRequestOption.fields(ChangeRequestField.ID));
DnsBatchResult<ChangeRequest> statusResult =
batch.getChangeRequest(
zone.getName(),
created.getGeneratedId(),
Dns.ChangeRequestOption.fields(ChangeRequestField.STATUS));
DnsBatchResult<ChangeRequest> timeResult =
batch.getChangeRequest(
zone.getName(),
created.getGeneratedId(),
Dns.ChangeRequestOption.fields(ChangeRequestField.START_TIME));
DnsBatchResult<ChangeRequest> additionsResult =
batch.getChangeRequest(
zone.getName(),
created.getGeneratedId(),
Dns.ChangeRequestOption.fields(ChangeRequestField.ADDITIONS));
batch.submit();
assertEqChangesIgnoreStatus(created, completeResult.get());
// with options
ChangeRequest retrieved = idResult.get();
assertEquals(created.getGeneratedId(), retrieved.getGeneratedId());
assertEquals(0, retrieved.getAdditions().size());
assertEquals(0, retrieved.getDeletions().size());
assertNull(retrieved.getStartTimeMillis());
assertNull(retrieved.status());
retrieved = statusResult.get();
assertEquals(created.getGeneratedId(), retrieved.getGeneratedId());
assertEquals(0, retrieved.getAdditions().size());
assertEquals(0, retrieved.getDeletions().size());
assertNull(retrieved.getStartTimeMillis());
assertEquals(ChangeRequestInfo.Status.DONE, retrieved.status());
retrieved = timeResult.get();
assertEquals(created.getGeneratedId(), retrieved.getGeneratedId());
assertEquals(0, retrieved.getAdditions().size());
assertEquals(0, retrieved.getDeletions().size());
assertEquals(created.getStartTimeMillis(), retrieved.getStartTimeMillis());
assertNull(retrieved.status());
retrieved = additionsResult.get();
assertEquals(created.getGeneratedId(), retrieved.getGeneratedId());
assertEquals(2, retrieved.getAdditions().size());
assertTrue(retrieved.getAdditions().contains(A_RECORD_ZONE1));
assertTrue(retrieved.getAdditions().contains(AAAA_RECORD_ZONE1));
assertEquals(0, retrieved.getDeletions().size());
assertNull(retrieved.getStartTimeMillis());
assertNull(retrieved.status());
// finishes with delete otherwise we cannot delete the zone
created =
zone.applyChangeRequest(
CHANGE_DELETE_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.DELETIONS));
batch = DNS.batch();
DnsBatchResult<ChangeRequest> deletionsResult =
batch.getChangeRequest(
zone.getName(),
created.getGeneratedId(),
Dns.ChangeRequestOption.fields(ChangeRequestField.DELETIONS));
batch.submit();
retrieved = deletionsResult.get();
assertEquals(created.getGeneratedId(), retrieved.getGeneratedId());
assertEquals(0, retrieved.getAdditions().size());
assertEquals(2, retrieved.getDeletions().size());
assertTrue(retrieved.getDeletions().contains(AAAA_RECORD_ZONE1));
assertTrue(retrieved.getDeletions().contains(A_RECORD_ZONE1));
assertNull(retrieved.getStartTimeMillis());
assertNull(retrieved.status());
waitForChangeToComplete(zone.getName(), created.getGeneratedId());
} finally {
clear();
}
}
@Test
public void testListChangesBatch() {
try {
DnsBatch batch = DNS.batch();
DnsBatchResult<Page<ChangeRequest>> result = batch.listChangeRequests(ZONE1.getName());
batch.submit();
try {
result.get();
fail("Zone does not exist yet");
} catch (DnsException ex) {
// expected
assertEquals(404, ex.getCode());
assertFalse(ex.isRetryable());
}
// zone exists but has no changes
DNS.create(ZONE1);
batch = DNS.batch();
result = batch.listChangeRequests(ZONE1.getName());
batch.submit();
// default change creating SOA and NS
assertEquals(1, Iterables.size(result.get().getValues()));
// zone has changes
ChangeRequest change = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1);
waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId());
change = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1);
waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId());
batch = DNS.batch();
result = batch.listChangeRequests(ZONE1.getName());
DnsBatchResult<Page<ChangeRequest>> errorPageSize =
batch.listChangeRequests(ZONE1.getName(), Dns.ChangeRequestListOption.pageSize(0));
DnsBatchResult<Page<ChangeRequest>> errorPageNegative =
batch.listChangeRequests(ZONE1.getName(), Dns.ChangeRequestListOption.pageSize(-1));
DnsBatchResult<Page<ChangeRequest>> resultAscending =
batch.listChangeRequests(
ZONE1.getName(), Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING));
DnsBatchResult<Page<ChangeRequest>> resultDescending =
batch.listChangeRequests(
ZONE1.getName(), Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.DESCENDING));
DnsBatchResult<Page<ChangeRequest>> resultAdditions =
batch.listChangeRequests(
ZONE1.getName(),
Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING),
Dns.ChangeRequestListOption.fields(ChangeRequestField.ADDITIONS));
DnsBatchResult<Page<ChangeRequest>> resultDeletions =
batch.listChangeRequests(
ZONE1.getName(),
Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING),
Dns.ChangeRequestListOption.fields(ChangeRequestField.DELETIONS));
DnsBatchResult<Page<ChangeRequest>> resultId =
batch.listChangeRequests(
ZONE1.getName(),
Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING),
Dns.ChangeRequestListOption.fields(ChangeRequestField.ID));
DnsBatchResult<Page<ChangeRequest>> resultTime =
batch.listChangeRequests(
ZONE1.getName(),
Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING),
Dns.ChangeRequestListOption.fields(ChangeRequestField.START_TIME));
DnsBatchResult<Page<ChangeRequest>> resultStatus =
batch.listChangeRequests(
ZONE1.getName(),
Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING),
Dns.ChangeRequestListOption.fields(ChangeRequestField.STATUS));
batch.submit();
assertEquals(3, Iterables.size(result.get().getValues()));
// error in options
try {
errorPageSize.get();
fail();
} catch (DnsException ex) {
// expected
assertEquals(400, ex.getCode());
assertFalse(ex.isRetryable());
}
try {
errorPageNegative.get();
fail();
} catch (DnsException ex) {
// expected
assertEquals(400, ex.getCode());
assertFalse(ex.isRetryable());
}
// sorting order
ImmutableList<ChangeRequest> ascending =
ImmutableList.copyOf(resultAscending.get().iterateAll());
ImmutableList<ChangeRequest> descending =
ImmutableList.copyOf(resultDescending.get().iterateAll());<|fim▁hole|> int size = 3;
assertEquals(size, descending.size());
assertEquals(size, ascending.size());
for (int i = 0; i < size; i++) {
assertEquals(descending.get(i), ascending.get(size - i - 1));
}
// field options
change = Iterables.get(resultAdditions.get().getValues(), 1);
assertEquals(CHANGE_ADD_ZONE1.getAdditions(), change.getAdditions());
assertTrue(change.getDeletions().isEmpty());
assertNotNull(change.getGeneratedId());
assertNull(change.getStartTimeMillis());
assertNull(change.status());
change = Iterables.get(resultDeletions.get().getValues(), 2);
assertTrue(change.getAdditions().isEmpty());
assertNotNull(change.getDeletions());
assertNotNull(change.getGeneratedId());
assertNull(change.getStartTimeMillis());
assertNull(change.status());
change = Iterables.get(resultId.get().getValues(), 1);
assertTrue(change.getAdditions().isEmpty());
assertTrue(change.getDeletions().isEmpty());
assertNotNull(change.getGeneratedId());
assertNull(change.getStartTimeMillis());
assertNull(change.status());
change = Iterables.get(resultTime.get().getValues(), 1);
assertTrue(change.getAdditions().isEmpty());
assertTrue(change.getDeletions().isEmpty());
assertNotNull(change.getGeneratedId());
assertNotNull(change.getStartTimeMillis());
assertNull(change.status());
change = Iterables.get(resultStatus.get().getValues(), 1);
assertTrue(change.getAdditions().isEmpty());
assertTrue(change.getDeletions().isEmpty());
assertNotNull(change.getGeneratedId());
assertNull(change.getStartTimeMillis());
assertEquals(ChangeRequest.Status.DONE, change.status());
} finally {
clear();
}
}
@Test
public void testListDnsRecordSetsBatch() {
try {
Zone zone = DNS.create(ZONE1);
DnsBatch batch = DNS.batch();
DnsBatchResult<Page<RecordSet>> result = batch.listRecordSets(zone.getName());
batch.submit();
ImmutableList<RecordSet> recordSets = ImmutableList.copyOf(result.get().iterateAll());
assertEquals(2, recordSets.size());
ImmutableList<RecordSet.Type> defaultRecords =
ImmutableList.of(RecordSet.Type.NS, RecordSet.Type.SOA);
for (RecordSet recordSet : recordSets) {
assertTrue(defaultRecords.contains(recordSet.getType()));
}
// field options
batch = DNS.batch();
DnsBatchResult<Page<RecordSet>> ttlResult =
batch.listRecordSets(zone.getName(), Dns.RecordSetListOption.fields(RecordSetField.TTL));
DnsBatchResult<Page<RecordSet>> nameResult =
batch.listRecordSets(zone.getName(), Dns.RecordSetListOption.fields(RecordSetField.NAME));
DnsBatchResult<Page<RecordSet>> recordsResult =
batch.listRecordSets(
zone.getName(), Dns.RecordSetListOption.fields(RecordSetField.DNS_RECORDS));
DnsBatchResult<Page<RecordSet>> pageSizeResult =
batch.listRecordSets(
zone.getName(),
Dns.RecordSetListOption.fields(RecordSetField.TYPE),
Dns.RecordSetListOption.pageSize(1));
batch.submit();
Iterator<RecordSet> recordSetIterator = ttlResult.get().iterateAll().iterator();
int counter = 0;
while (recordSetIterator.hasNext()) {
RecordSet recordSet = recordSetIterator.next();
assertEquals(recordSets.get(counter).getTtl(), recordSet.getTtl());
assertEquals(recordSets.get(counter).getName(), recordSet.getName());
assertEquals(recordSets.get(counter).getType(), recordSet.getType());
assertTrue(recordSet.getRecords().isEmpty());
counter++;
}
assertEquals(2, counter);
recordSetIterator = nameResult.get().iterateAll().iterator();
counter = 0;
while (recordSetIterator.hasNext()) {
RecordSet recordSet = recordSetIterator.next();
assertEquals(recordSets.get(counter).getName(), recordSet.getName());
assertEquals(recordSets.get(counter).getType(), recordSet.getType());
assertTrue(recordSet.getRecords().isEmpty());
assertNull(recordSet.getTtl());
counter++;
}
assertEquals(2, counter);
recordSetIterator = recordsResult.get().iterateAll().iterator();
counter = 0;
while (recordSetIterator.hasNext()) {
RecordSet recordSet = recordSetIterator.next();
assertEquals(recordSets.get(counter).getRecords(), recordSet.getRecords());
assertEquals(recordSets.get(counter).getName(), recordSet.getName());
assertEquals(recordSets.get(counter).getType(), recordSet.getType());
assertNull(recordSet.getTtl());
counter++;
}
assertEquals(2, counter);
recordSetIterator = pageSizeResult.get().iterateAll().iterator(); // also test paging
counter = 0;
while (recordSetIterator.hasNext()) {
RecordSet recordSet = recordSetIterator.next();
assertEquals(recordSets.get(counter).getType(), recordSet.getType());
assertEquals(recordSets.get(counter).getName(), recordSet.getName());
assertTrue(recordSet.getRecords().isEmpty());
assertNull(recordSet.getTtl());
counter++;
}
assertEquals(2, counter);
// test page size
Page<RecordSet> recordSetPage = pageSizeResult.get();
assertEquals(1, ImmutableList.copyOf(recordSetPage.getValues().iterator()).size());
// test name filter
ChangeRequest change = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1);
waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId());
batch = DNS.batch();
result =
batch.listRecordSets(
ZONE1.getName(), Dns.RecordSetListOption.dnsName(A_RECORD_ZONE1.getName()));
batch.submit();
recordSetIterator = result.get().iterateAll().iterator();
counter = 0;
while (recordSetIterator.hasNext()) {
RecordSet recordSet = recordSetIterator.next();
assertTrue(
ImmutableList.of(A_RECORD_ZONE1.getType(), AAAA_RECORD_ZONE1.getType())
.contains(recordSet.getType()));
counter++;
}
assertEquals(2, counter);
// test type filter
batch = DNS.batch();
result =
batch.listRecordSets(
ZONE1.getName(),
Dns.RecordSetListOption.dnsName(A_RECORD_ZONE1.getName()),
Dns.RecordSetListOption.type(A_RECORD_ZONE1.getType()));
batch.submit();
recordSetIterator = result.get().iterateAll().iterator();
counter = 0;
while (recordSetIterator.hasNext()) {
RecordSet recordSet = recordSetIterator.next();
assertEquals(A_RECORD_ZONE1, recordSet);
counter++;
}
assertEquals(1, counter);
batch = DNS.batch();
DnsBatchResult<Page<RecordSet>> noNameError =
batch.listRecordSets(
ZONE1.getName(), Dns.RecordSetListOption.type(A_RECORD_ZONE1.getType()));
DnsBatchResult<Page<RecordSet>> zeroSizeError =
batch.listRecordSets(ZONE1.getName(), Dns.RecordSetListOption.pageSize(0));
DnsBatchResult<Page<RecordSet>> negativeSizeError =
batch.listRecordSets(ZONE1.getName(), Dns.RecordSetListOption.pageSize(-1));
batch.submit();
// check wrong arguments
try {
// name is not set
noNameError.get();
fail();
} catch (DnsException ex) {
// expected
assertEquals(400, ex.getCode());
assertFalse(ex.isRetryable());
}
try {
zeroSizeError.get();
fail();
} catch (DnsException ex) {
// expected
assertEquals(400, ex.getCode());
assertFalse(ex.isRetryable());
}
try {
negativeSizeError.get();
fail();
} catch (DnsException ex) {
// expected
assertEquals(400, ex.getCode());
assertFalse(ex.isRetryable());
}
waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId());
} finally {
clear();
}
}
@Test
public void testBatchCombined() {
// only testing that the combination is possible
// the results are validated in the other test methods
try {
DNS.create(ZONE1);
DnsBatch batch = DNS.batch();
DnsBatchResult<Zone> zoneResult = batch.getZone(ZONE_NAME1);
DnsBatchResult<ChangeRequest> changeRequestResult = batch.getChangeRequest(ZONE_NAME1, "0");
DnsBatchResult<Page<RecordSet>> pageResult = batch.listRecordSets(ZONE_NAME1);
DnsBatchResult<ProjectInfo> projectResult = batch.getProject();
assertFalse(zoneResult.completed());
try {
zoneResult.get();
fail("this should be submitted first");
} catch (IllegalStateException ex) {
// expected
}
batch.submit();
assertNotNull(zoneResult.get().getCreationTimeMillis());
assertEquals(ZONE1.getDnsName(), zoneResult.get().getDnsName());
assertEquals(ZONE1.getDescription(), zoneResult.get().getDescription());
assertFalse(zoneResult.get().getNameServers().isEmpty());
assertNull(zoneResult.get().getNameServerSet()); // we did not set it
assertNotNull(zoneResult.get().getGeneratedId());
assertNotNull(projectResult.get().getQuota());
assertEquals(2, Iterables.size(pageResult.get().getValues()));
assertNotNull(changeRequestResult.get());
} finally {
DNS.delete(ZONE1.getName());
}
}
}<|fim▁end|> | |
<|file_name|>path.py<|end_file_name|><|fim▁begin|>#
# Copyright (C) 2003-2022 Sébastien Helleu <[email protected]><|fim▁hole|>#
# This file is part of WeeChat.org.
#
# WeeChat.org is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# WeeChat.org is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with WeeChat.org. If not, see <https://www.gnu.org/licenses/>.
#
"""Some useful path functions."""
import os
from django.conf import settings
def __path_join(base, *args):
"""
Join multiple paths after 'base' and ensure the result is still
under 'base'.
"""
base = os.path.normpath(base)
directory = os.path.normpath(os.path.join(base, *args))
if directory.startswith(base):
return directory
return ''
def project_path_join(*args):
"""Join multiple paths after settings.BASE_DIR."""
return __path_join(settings.BASE_DIR, *args)
def files_path_join(*args):
"""Join multiple paths after settings.FILES_ROOT."""
return __path_join(settings.FILES_ROOT, *args)
def media_path_join(*args):
"""Join multiple paths after settings.MEDIA_ROOT."""
return __path_join(settings.MEDIA_ROOT, *args)
def repo_path_join(*args):
"""Join multiple paths after settings.REPO_DIR."""
return __path_join(settings.REPO_DIR, *args)<|fim▁end|> | |
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>// Copyright © 2015, Peter Atashian
// Licensed under the MIT License <LICENSE.md>
//! FFI bindings to davclnt.
#![no_std]
#![experimental]
extern crate winapi;
use winapi::*;
extern "system" {<|fim▁hole|><|fim▁end|> | } |
<|file_name|>[email protected]<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="ca@valencia" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About GSMcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+39"/>
<source><b>GSMcoin</b> version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The GSMcoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>Doble click per editar la direccio o la etiqueta</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Crear nova direccio</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copieu l'adreça seleccionada al porta-retalls del sistema</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-46"/>
<source>These are your GSMcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<source>&Copy Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a GSMcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Verify a message to ensure it was signed with a specified GSMcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>Eliminar</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+35"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-58"/>
<source>GSMcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+282"/>
<source>Sign &message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+251"/>
<source>Synchronizing with network...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-319"/>
<source>&Overview</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-13"/>
<source>&Receive coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show the list of addresses for receiving payments</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-7"/>
<source>&Send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>E&xit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show information about GSMcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+259"/>
<source>~%n block(s) remaining</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-256"/>
<source>&Export...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-64"/>
<source>Send coins to a GSMcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+47"/>
<source>Modify configuration options for GSMcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Encrypt or decrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup wallet to another location</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-202"/>
<source>GSMcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+180"/>
<source>&About GSMcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Unlock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>&File</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Tabs toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Actions toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+9"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+60"/>
<source>GSMcoin client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+75"/>
<source>%n active connection(s) to GSMcoin network</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+40"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+413"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-403"/>
<source>%n second(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="-312"/>
<source>About GSMcoin card</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about GSMcoin card</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>&Unlock Wallet...</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+297"/>
<source>%n minute(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Up to date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Catching up...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Last received block was generated %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid GSMcoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+76"/>
<source>%n second(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message><|fim▁hole|> <message>
<location filename="../bitcoin.cpp" line="+109"/>
<source>A fatal error occurred. GSMcoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+90"/>
<source>Network Alert</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+551"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-515"/>
<source>Copy address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+155"/>
<source>DUST</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+66"/>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+20"/>
<source>New receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid GSMcoin address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+420"/>
<location line="+12"/>
<source>GSMcoin-Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start GSMcoin after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start GSMcoin on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Detach databases at shutdown</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Automatically open the GSMcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Connect to the GSMcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting GSMcoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Whether to show GSMcoin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Whether to show coin control features or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+55"/>
<source>default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+149"/>
<location line="+9"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting GSMcoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+33"/>
<location line="+231"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the GSMcoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-160"/>
<source>Stake:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-107"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Total:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-108"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+113"/>
<location line="+1"/>
<source>out of sync</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+348"/>
<source>N/A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the GSMcoin-Qt help message to get a list with possible GSMcoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-104"/>
<source>GSMcoin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>GSMcoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the GSMcoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-33"/>
<source>Welcome to the GSMcoin RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+182"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<location line="+86"/>
<location line="+86"/>
<location line="+32"/>
<source>0.00 GSM</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-191"/>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Balance:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>123.456 GSM</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-173"/>
<source>Enter a GSMcoin address (e.g. GSMcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+86"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+251"/>
<source>WARNING: Invalid GSMcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<location filename="../sendcoinsentry.cpp" line="+25"/>
<source>Enter a label for this address to add it to your address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to send the payment to (e.g. GSMcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Choose address from address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a GSMcoin address (e.g. GSMcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-118"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. GSMcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this GSMcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-64"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. GSMcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified GSMcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a GSMcoin address (e.g. GSMcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter GSMcoin signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+19"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-2"/>
<source>Open for %n block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+8"/>
<source>conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-211"/>
<source>, has not been successfully broadcast yet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>unknown</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+226"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+190"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+55"/>
<location line="+16"/>
<source>All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+144"/>
<source>Export Transaction Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+206"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+33"/>
<source>GSMcoin version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or GSMcoind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: GSMcoin.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: GSMcoind.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Listen for connections on <port> (default: 15714 or testnet: 25714)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Stake your coins to support network and gain reward (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Detach block and address databases. Increases shutdown time (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+109"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>Listen for JSON-RPC connections on <port> (default: 15715 or testnet: 25715)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-11"/>
<source>Accept command line and JSON-RPC commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+101"/>
<source>Error: Transaction creation failed </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-8"/>
<source>Importing blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Importing bootstrap blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-88"/>
<source>Run in the background as a daemon and accept commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-24"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-38"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+117"/>
<source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+61"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong GSMcoin will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-31"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-18"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-30"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-62"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+94"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-90"/>
<source>Find peers using DNS lookup (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync checkpoints policy (default: strict)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+83"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-82"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-16"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-74"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-42"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+109"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<source>Username for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+47"/>
<source>Verifying database integrity...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+57"/>
<source>WARNING: syncronized checkpoint violation detected, but skipped!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-48"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-54"/>
<source>Password for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-84"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=GSMcoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "GSMcoin Alert" [email protected]
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+53"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-158"/>
<source>This help message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+95"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot obtain a lock on data directory %s. GSMcoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-98"/>
<source>GSMcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+140"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-130"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+122"/>
<source>Loading addresses...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<source>Error loading blkindex.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of GSMcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart GSMcoin to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-24"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Error: could not start node</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-34"/>
<source>Loading block index...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-103"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+122"/>
<source>Unable to bind to %s on this computer. GSMcoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-97"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Loading wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot initialize keypool</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Done loading</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-167"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation type="unfinished"/>
</message>
</context>
</TS><|fim▁end|> | <location line="+18"/>
<source>Not staking</source>
<translation type="unfinished"/>
</message> |
<|file_name|>index.js<|end_file_name|><|fim▁begin|>// @flow
import React, { Component } from 'react'
import { Helmet } from 'react-helmet'
import AlternativeMedia from './AlternativeMedia'
import ImageViewer from './ImageViewer'
import { Code, CodeBlock, Title } from '../components'
const propFn = k => {
const style = { display: 'inline-block', marginBottom: 4, marginRight: 4 }
return (
<span key={k} style={style}>
<Code>{k}</Code>
</span>
)
}
const commonProps = [
'carouselProps',
'currentIndex',
'currentView',
'frameProps',
'getStyles',
'isFullscreen',
'isModal',
'modalProps',
'interactionIsIdle',
'trackProps',
'views',
]
export default class CustomComponents extends Component<*> {
render() {
return (
<div>
<Helmet>
<title>Components - React Images</title>
<meta
name="description"
content="React Images allows you to augment layout and functionality by
replacing the default components with your own."
/>
</Helmet>
<Title>Components</Title>
<p>
The main feature of this library is providing consumers with the building blocks necessary to create <em>their</em> component.
</p>
<h3>Replacing Components</h3>
<p>
React-Images allows you to augment layout and functionality by replacing the default components with your own, using the <Code>components</Code>{' '}
property. These components are given all the current props and state letting you achieve anything you dream up.
</p>
<h3>Inner Props</h3>
<p>
All functional properties that the component needs are provided in <Code>innerProps</Code> which you must spread.
</p>
<h3>Common Props</h3>
<p>
Every component receives <Code>commonProps</Code> which are spread onto the component. These include:
</p>
<p>{commonProps.map(propFn)}</p>
<CodeBlock>
{`import React from 'react';
import Carousel from 'react-images';
const CustomHeader = ({ innerProps, isModal }) => isModal ? (
<div {...innerProps}>
// your component internals
</div>
) : null;
class Component extends React.Component {
render() {
return <Carousel components={{ Header: CustomHeader }} />;
}<|fim▁hole|> </CodeBlock>
<h2>Component API</h2>
<h3>{'<Container />'}</h3>
<p>Wrapper for the carousel. Attachment point for mouse and touch event listeners.</p>
<h3>{'<Footer />'}</h3>
<p>
Element displayed beneath the views. Renders <Code>FooterCaption</Code> and <Code>FooterCount</Code> by default.
</p>
<h3>{'<FooterCaption />'}</h3>
<p>
Text associated with the current view. Renders <Code>{'{viewData.caption}'}</Code> by default.
</p>
<h3>{'<FooterCount />'}</h3>
<p>
How far through the carousel the user is. Renders{' '}
<Code>
{'{currentIndex}'} of {'{totalViews}'}
</Code>{' '}
by default
</p>
<h3>{'<Header />'}</h3>
<p>
Element displayed above the views. Renders <Code>FullscreenButton</Code> and <Code>CloseButton</Code> by default.
</p>
<h3>{'<HeaderClose />'}</h3>
<p>
The button to close the modal. Accepts the <Code>onClose</Code> function.
</p>
<h3>{'<HeaderFullscreen />'}</h3>
<p>
The button to fullscreen the modal. Accepts the <Code>toggleFullscreen</Code> function.
</p>
<h3>{'<Navigation />'}</h3>
<p>
Wrapper for the <Code>{'<NavigationNext />'}</Code> and <Code>{'<NavigationPrev />'}</Code> buttons.
</p>
<h3>{'<NavigationPrev />'}</h3>
<p>
Button allowing the user to navigate to the previous view. Accepts an <Code>onClick</Code> function.
</p>
<h3>{'<NavigationNext />'}</h3>
<p>
Button allowing the user to navigate to the next view. Accepts an <Code>onClick</Code> function.
</p>
<h3>{'<View />'}</h3>
<p>
The view component renders your media to the user. Receives the current view object as the <Code>data</Code> property.
</p>
<h2>Examples</h2>
<ImageViewer {...this.props} />
<AlternativeMedia />
</div>
)
}
}<|fim▁end|> | }`} |
<|file_name|>AccountController.js<|end_file_name|><|fim▁begin|>/**
* Module dependencies
*/
var _ = require('lodash');
var async = require('async');
var path = require('path');
var router = require('express')
.Router();
/**
* Models
*/
var Account = require('../models/Account');
var App = require('../models/App');
var Invite = require('../models/Invite');
/**
* Policies
*/
var isAuthenticated = require('../policies/isAuthenticated');
/**
* Services
*/
var accountMailer = require('../services/account-mailer');
/**
* Helpers
*/
var logger = require('../../helpers/logger');
function sendConfirmationMail(acc, verifyToken, cb) {
/**
* Apps config
*/
var config = require('../../../config')('api');
var dashboardUrl = config.hosts.dashboard;
var confirmUrl = dashboardUrl + '/account/' + acc._id.toString() +
'/verify-email/' + verifyToken;
var mailOptions = {
locals: {
confirmUrl: confirmUrl,
name: acc.name
},
to: {
email: acc.email,
name: acc.name
}
};
accountMailer.sendConfirmation(mailOptions, cb);
}
/**
* GET /account/
*
* NOTE: isAuthenticated middleware is called only for
* get /account and not post /account
*/
router
.route('/')
.get(isAuthenticated)
.get(function (req, res, next) {
if (!req.user) {
return res.notFound();
}
res
.status(200)
.json(req.user);
});
/**
* POST /account
*
* Create a new account
*
* Check if invited:
* - if invited, add as team member to app
* - else, send email confirmation mail (TODO)
*/
router
.route('/')
.post(function (req, res, next) {
/**
* Apps config
*/
var config = require('../../../config')('api');
var account = req.body;
async.waterfall(
[
function createAccount(cb) {
account.emailVerified = false;
Account.create(account, cb);
},
function defaultApp(acc, cb) {
App.createDefaultApp(acc._id, acc.name, function (err, app) {
cb(err, acc, app);
});
},
function createVerifyToken(acc, app, cb) {
acc.createVerifyToken(function (err, acc, verifyToken) {
cb(err, acc, app, verifyToken);
});
},
function sendMail(acc, app, verifyToken, cb) {
sendConfirmationMail(acc, verifyToken, function (err) {
cb(err, acc, app);
});
},
function autoLogin(acc, app, cb) {
req.login(acc, function (err) {
cb(err, acc, app);
});
}
],
function callback(err, acc, app) {
if (err) return next(err);
return res
.status(201)
.json({
account: acc,
app: app,
message: 'Logged In Successfully'
});
}
);
});
/**
* POST /account/invite
*
* Create a new account with invite
*
* Check if invited:
* - if invited, add as team member to app
* - else, send email confirmation mail (TODO)
*/
router
.route('/invite')
.post(function (req, res, next) {
/**
* Apps config
*/
var config = require('../../../config')('api');
var account = req.body;
var inviteId = req.body.inviteId;
logger.trace({
at: 'AccountController:createInvite',
body: req.body
});
if (!inviteId) return res.badRequest('inviteId is required');
async.waterfall(
[
function findInvite(cb) {
Invite
.findById(inviteId)
.exec(function (err, invite) {
if (err) return cb(err);
if (!invite) return cb(new Error('Invite not found'));
cb(null, invite);
});
},
function createAccount(invite, cb) {
// set emailVerified as true
account.emailVerified = true;
Account.create(account, function (err, acc) {
cb(err, acc, invite);
});
},
function addMember(acc, invite, cb) {
// add as a team member to the app the user was invited to
App.addMember(invite.aid, acc._id, acc.name, function (err, app) {
cb(err, acc, invite, app);
});
},
function deleteInvite(acc, invite, app, cb) {
// delete invite
Invite.findByIdAndRemove(invite._id, function (err) {
cb(err, acc, app);
});
}
],
function callback(err, acc, app) {
if (err) return next(err);
return res
.status(201)
.json({
account: acc,
app: app,
message: 'Logged In Successfully'
});
}
);
});
/**
* POST /account/invite
*
* Creates a new account with an invite id
*
* Check if invited:
* - if invited, add as team member to app
* - else, send email confirmation mail (TODO)
*/
router
.route('/')
.post(function (req, res, next) {
/**
* Apps config
*/
var config = require('../../../config')('api');
var account = req.body;
var inviteId = req.body.inviteId;
var respond = function (err, acc, app) {
if (err) return next(err);
req.login(acc, function (err) {
if (err) return next(err);
return res
.status(201)
.json({
account: acc,
app: app,
message: 'Logged In Successfully'
});
});
}
if (!inviteId) return signupWithoutInvite(account, respond);
signupWithInvite(account, inviteId, function (err, acc) {
if (err && err.message === 'Invite not found') {
return signupWithoutInvite(account, respond);
}
respond(err, acc);
});
});
/**
* POST /account/verify-email/resend
*
* Resend verification email
*
* @param {string} email email-address-of-account
*
*/
router
.route('/verify-email/resend')
.post(function (req, res, next) {
var email = req.body.email;
if (!email) return res.badRequest('Please provide your email');
Account
.findOne({
email: email
})
.select('verifyToken emailVerified name email')
.exec(function (err, acc) {
if (err) return next(err);
if (!acc) return res.notFound('Account not found');
if (acc.emailVerified) {
return res.badRequest(
'Your email is already verified. Please login to access your account'
);
}
sendConfirmationMail(acc, acc.verifyToken, function (err) {
if (err) return next(err);
res
.status(200)
.json({
message: 'Verification email has been sent'
});
});
});
});
/**
* GET /account/:id/verify-email/:token
*
* TODO : Update this endpoint to /account/verify-email/:token
* for consistency
*/
router
.route('/:id/verify-email/:token')
.get(function (req, res, next) {
var accountId = req.params.id;
var token = req.params.token;
Account
.verify(accountId, token, function (err, account) {
if (err) {
if (_.contains(['Invalid Token', 'Account Not Found'], err.message)) {
return res.badRequest('Invalid Attempt');
}<|fim▁hole|>
return next(err);
}
res
.status(200)
.json(account);
});
});
/**
* PUT /account/forgot-password/new
*
*
* @param {string} token reset-password-token
* @param {string} password new-password
*
* Verfies reset password token and updates password
*
* TODO: Make this more secure by prepending the account id to the token
*/
router
.route('/forgot-password/new')
.put(function (req, res, next) {
var token = req.body.token;
var newPass = req.body.password;
if (!token || !newPass) {
return res.badRequest('Please provide token and new password');
}
logger.trace({
at: 'AccountController forgot-password/new',
body: req.body
})
async.waterfall([
function verify(cb) {
Account
.findOne({
passwordResetToken: token,
})
.exec(function (err, account) {
if (err) return cb(err);
if (!account) return cb(new Error('INVALID_TOKEN'));
cb(null, account);
});
},
function updatePasswordAndRemoveToken(account, cb) {
account.passwordResetToken = undefined;
account.password = newPass
account.save(cb);
}
],
function (err, account) {
if (err) {
if (err.message === 'INVALID_TOKEN') {
return res.badRequest('Invalid Attempt. Please try again.');
}
return next(err);
}
// remove password from response
if (account.toJSON) account = account.toJSON();
delete account.password;
res
.status(200)
.json({
message: 'Password token verified',
account: account
});
});
});
/**
* PUT /account/name
* Update account name
*/
router
.route('/name')
.put(isAuthenticated)
.put(function (req, res, next) {
req.user.name = req.body.name;
req.user.save(function (err, account) {
if (err) {
return next(err);
}
res
.status(200)
.json(account);
});
});
/**
* PUT /account/default-app
* Update account default app
*
* @param {string} defaultApp
*/
router
.route('/default-app')
.put(isAuthenticated)
.put(function (req, res, next) {
var defaultApp = req.body.defaultApp;
if (!defaultApp) return res.badRequest('Please provide the app id');
req.user.defaultApp = defaultApp;
req.user.save(function (err, account) {
if (err) {
return next(err);
}
res
.status(200)
.json({
message: 'Updated default app',
account: account
});
});
});
/**
* PUT /account/forgot-password
*
* TODO: add the respective get request
* which will check the token and redirect
* user to new-password page
*/
router
.route('/forgot-password')
.put(function (req, res, next) {
Account.createResetPasswordToken(req.body.email, function (err, account) {
if (err) {
if (err.message === 'Invalid Email') {
return res.badRequest('Provide a valid email');
}
if (err.message === 'Account Not Found') {
return res.notFound('Provide a valid email');
}
return next(err);
}
/**
* Apps config
*/
var config = require('../../../config')('api');
var dashboardUrl = config.hosts.dashboard;
accountMailer.sendForgotPassword({
locals: {
url: dashboardUrl + '/forgot-password/' + account.passwordResetToken,
name: account.name
},
to: {
email: account.email,
name: account.name
},
}, function (err) {
if (err) return next(err);
res
.status(200)
.json({
message: 'Reset password email sent'
});
});
});
});
/**
* PUT /account/password/update
* Update account password
*/
router
.route('/password/update')
.put(isAuthenticated)
.put(function (req, res, next) {
var currPass = req.body.currentPassword;
var newPass = req.body.newPassword;
req.user.updatePassword(currPass, newPass, function (err) {
if (err) {
if (err.message === 'Incorrect Password') {
return res.badRequest(
'Please provide the correct current password');
}
return next(err);
}
res
.status(200)
.json({
message: 'Password updated'
});
});
});
module.exports = router;<|fim▁end|> | |
<|file_name|>concept_dicts.py<|end_file_name|><|fim▁begin|>lookup = {}
lookup = dict()
lookup = {'age': 42, 'loc': 'Italy'}
lookup = dict(age=42, loc='Italy')
print(lookup)
print(lookup['loc'])
lookup['cat'] = 'cat'
if 'cat' in lookup:
print(lookup['cat'])
class Wizard:
# This actually creates a key value dictionary
def __init__(self, name, level):
self.level = level
self.name = name
# There is an implicit dictionary that stores this data
gandolf = Wizard('Gladolf', 42)
print(gandolf.__dict__)
# The takeway is that all objects are built around the concept of dictionary data structures
# Here is another example
import collections
User = collections.namedtuple('User', 'id, name, email')
users = [
User(1, 'user1', '[email protected]'),
User(2, 'user2', '[email protected]'),
<|fim▁hole|>lookup = dict()
for u in users:
lookup[u.email] = u
print(lookup['[email protected]'])<|fim▁end|> | User(3, 'user3', '[email protected]'),
]
|
<|file_name|>datasource_utils.py<|end_file_name|><|fim▁begin|>import json
import maps
import traceback
from requests import get
from requests import post
from requests import put
from tendrl.commons.utils import log_utils as logger
from tendrl.monitoring_integration.grafana import constants
from tendrl.monitoring_integration.grafana import exceptions
from tendrl.monitoring_integration.grafana import utils
def _post_datasource(datasource_json):
config = maps.NamedDict(NS.config.data)
if utils.port_open(config.grafana_port, config.grafana_host):
resp = post(
"http://{}:{}/api/datasources".format(
config.grafana_host,
config.grafana_port
),
headers=constants.HEADERS,
auth=config.credentials,
data=datasource_json
)
else:
raise exceptions.ConnectionFailedException
return resp
<|fim▁hole|> + str(config.datasource_port)
datasource_json = (
{'name': config.datasource_name,
'type': config.datasource_type,
'url': url,
'access': config.access,
'basicAuth': config.basicAuth,
'isDefault': config.isDefault
}
)
return datasource_json
def create_datasource():
try:
datasource_json = form_datasource_json()
response = _post_datasource(json.dumps(datasource_json))
return response
except exceptions.ConnectionFailedException:
logger.log("error", NS.get("publisher_id", None),
{'message': str(traceback.print_stack())})
raise exceptions.ConnectionFailedException
def get_data_source():
config = maps.NamedDict(NS.config.data)
if utils.port_open(config.grafana_port, config.grafana_host):
resp = get(
"http://{}:{}/api/datasources/id/{}".format(
config.grafana_host,
config.grafana_port,
config.datasource_name
),
auth=config.credentials
)
else:
raise exceptions.ConnectionFailedException
return resp
def update_datasource(datasource_id):
try:
config = maps.NamedDict(NS.config.data)
datasource_json = form_datasource_json()
datasource_str = json.dumps(datasource_json)
if utils.port_open(config.grafana_port, config.grafana_host):
response = put(
"http://{}:{}/api/datasources/{}".format(
config.grafana_host,
config.grafana_port,
datasource_id
),
headers=constants.HEADERS,
auth=config.credentials,
data=datasource_str
)
else:
raise exceptions.ConnectionFailedException
return response
except exceptions.ConnectionFailedException as ex:
logger.log("error", NS.get("publisher_id", None),
{'message': str(ex)})
raise ex<|fim▁end|> |
def form_datasource_json():
config = maps.NamedDict(NS.config.data)
url = "http://" + str(config.datasource_host) + ":" \ |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | """
Tools to put to good use INE data
""" |
<|file_name|>fbclient.js<|end_file_name|><|fim▁begin|>var $ = require('common:widget/ui/jquery/jquery.js');
var UT = require('common:widget/ui/ut/ut.js');
var FBClient = {};
var TPL_CONF = require('home:widget/ui/facebook/fbclient-tpl.js');
/**
* Fackbook module init function
* @return {object} [description]
*/
var WIN = window,
DOC = document,
conf = WIN.conf.FBClient,
undef;
var UI_CONF = {
// ui el
uiMod: "#fbMod"
, uiBtnLogin: ".fb-mod_login_btn"
, uiBtnLogout: ".fb-mod_logout"
, uiBtnRefresh: ".fb-mod_refresh"
, uiSide: ".fb-mod_side"
, uiBtnClose: ".fb-mod_close"
, uiWrap: ".fb-mod_wrap"
, uiList: ".fb-mod_list"
, uiUsrinfo: ".fb-mod_usrinfo"
, uiAvatar: ".fb-mod_avatar"
, uiTextareaSubmit: ".fb-mod_submit"
, uiBtnSubmit: ".fb-mod_submit_btn"
, uiBody: ".fb-mod_body"
, uiTip: ".fb-mod_tip"
, uiSideHome: ".fb-mod_side_home"
, uiSideFriend: ".fb-mod_side_friend em"
, uiSideMessages: ".fb-mod_side_messages em"
, uiSideNotifications: ".fb-mod_side_notifications em"
, uiBodyLoader: ".fb-mod_body_loader"
};
FBClient.init = function() {
// DOC.body.innerHTML += '<div id="fb-root"></div>';
var that = this,
$this = $(UI_CONF.uiMod);
/*
ui controller
*/
that.ui = {
uiMod: $this
, side: $this.find(UI_CONF.uiSide)
, btnLogin: $this.find(UI_CONF.uiBtnLogin)
, btnLogout: $this.find(UI_CONF.uiBtnLogout)
, btnClose: $this.find(UI_CONF.uiBtnClose)
, btnRefresh: $this.find(UI_CONF.uiBtnRefresh)
, wrap: $this.find(UI_CONF.uiWrap)
, list: $this.find(UI_CONF.uiList)
, usrinfo: $this.find(UI_CONF.uiUsrinfo)
, avatar: $this.find(UI_CONF.uiAvatar)
, textareaSubmit: $this.find(UI_CONF.uiTextareaSubmit)
, btnSubmit: $this.find(UI_CONF.uiBtnSubmit)
, body: $this.find(UI_CONF.uiBody)
, tip: $this.find(UI_CONF.uiTip)
, sideHome: $this.find(UI_CONF.uiSideHome)
, sideFriend: $this.find(UI_CONF.uiSideFriend)
, sideNotifications: $this.find(UI_CONF.uiSideNotifications)
, sideMessages: $this.find(UI_CONF.uiSideMessages)
, bodyLoader: $this.find(UI_CONF.uiBodyLoader)
, panelHome: $this.find(".fb-mod_c")
, panelFriend: $('<div class="fb-mod_c fb-mod_c_friend" style="display:none"><div class="fb-mod_c_loading"><div class="fb-mod_loader"></div></div></div>')
, panelNotifications: $('<div class="fb-mod_c fb-mod_c_notifications" style="display:none"><div class="fb-mod_c_loading"><div class="fb-mod_loader"></div></div></div>')
, panelMessages: $('<div class="fb-mod_c fb-mod_c_messages" style="display:none"><div class="fb-mod_c_loading"><div class="fb-mod_loader"></div></div></div>')
, bubble: $('<div class="fb-mod_bubble">' + (conf.tplBubble || "NEW") + '</div>')
, placeholder: function(first, last) {
return $(TPL_CONF.tplPlaceholder.replaceTpl({first: first,
last: last
}))
}
};
// live loader
that.ui.liveLoader = that.ui.bodyLoader.clone(!0)
.css({"width": "370px"})
.insertBefore(that.ui.list).hide();
$("body").append('<div id="fb-root" class=" fb_reset"></div>');
that.ui.wrap.append(that.ui.panelFriend).append(that.ui.panelNotifications).append(that.ui.panelMessages);
// window.ActiveXObject && !window.XMLHttpRequest &&
$("body").append(that.ui.fakeBox = $(that.ui.textareaSubmit[0].cloneNode(false)).css({
"position": "absolute"
, "top" : "0"
, "left": "0"
, "right": "-10000px"
, "visibility": "hidden"
, "padding-top": "0"
, "padding-bottom": "0"
, "height": "18" //for fixed
, "width": that.ui.textareaSubmit.width()
}));
that.supportAnimate = function(style, name) {
return 't' + name in style
|| 'webkitT' + name in style
|| 'MozT' + name in style
|| 'OT' + name in style;
}((new Image).style, "ransition");
/*
status controller
0 ==> none
1 ==> doing
2 ==> done
*/
that.status = {
login: 0
, fold: 0
, sdkLoaded: 0
, scrollLoaded: 0
, insertLoaded: 0
, fixed: 0
, eventBinded: 0
, bubble: 0
};
// bubble
!$.cookie("fb_bubble") && (that.status.bubble = 1, that.ui.uiMod.append(that.ui.bubble));
/*
post status cache
*/
that.cache = {
prePost: null
, nextPost: null
, refreshPost: null
, noOldPost: 0
, myPost: 0
, stayTip: ""
, userID: null
, userName: ""
, panel: that.ui.panelHome
, curSideType: ""
, panelRendered: 0
};
that.ui.btnClose.mousedown(function(e) {
UT && UT.send({"type": "click", "position": "fb", "sort": that.status.fold === 0 ? "pull" : "fold","modId":"fb-box"});
that.foldHandle.call(that, e);
});
$(".fb-mod_side_logo").mousedown(function(e) {
UT && UT.send({"type": "click", "position": "fb", "sort": that.status.fold === 0 ? "pull" : "fold","modId":"fb-box"});
that.foldHandle.call(that, e);
});
$(".fb-mod_side_home").mousedown(function(e) {
UT && that.status.fold === 0 && UT.send({"type": "click", "position": "fb", "sort": "pull","modId":"fb-box"});
UT && UT.send({"type": "click", "position": "fb", "sort": "icon_home","modId":"fb-box"});
that.status.fold === 0 && that.foldHandle.call(that, e);
that.clickHandle($(this), "fb-mod_side_home_cur", that.ui.panelHome);
});
$(".fb-mod_side_friend").mousedown(function(e) {
var logObj = {
"type": "click",
"position": "fb",
"sort": "icon_friend",
"modId": "fb-box"
};
if(that.status.login !== 2) {
logObj.ac = "b";
}
UT && UT.send(logObj);
<|fim▁hole|> });
$(".fb-mod_side_messages").mousedown(function(e) {
var logObj = {
"type": "click",
"position": "fb",
"sort": "icon_messages",
"modId": "fb-box"
};
if(that.status.login !== 2) {
logObj.ac = "b";
}
UT && UT.send(logObj);
if(that.status.login !== 2) return false;
that.status.fold === 0 && that.foldHandle.call(that, e);
that.clickHandle($(this), "fb-mod_side_messages_cur", that.ui.panelMessages);
});
$(".fb-mod_side_notifications").mousedown(function(e) {
var logObj = {
"type": "click",
"position": "fb",
"sort": "icon_notifications",
"modId": "fb-box"
};
if(that.status.login !== 2) {
logObj.ac = "b";
}
UT && UT.send(logObj);
if(that.status.login !== 2) return false;
that.status.fold === 0 && that.foldHandle.call(that, e);
that.clickHandle($(this), "fb-mod_side_notifications_cur", that.ui.panelNotifications);
});
that.ui.btnRefresh.mousedown(function(e) {
UT && UT.send({"type": "click", "position": "fb", "sort": "refresh","modId":"fb-box"});
});
$(".fb-mod_side_friend").click(function(e) {
e.preventDefault();
});
$(".fb-mod_side_messages").click(function(e) {
e.preventDefault();
});
$(".fb-mod_side_notifications").click(function(e) {
e.preventDefault();
});
// 7. FB-APP的打开、收缩机制;——点击F、箭头、new三个地方打开,点击F、箭头两个地方关闭;做上新功能上线的提示图标,放cookies内;
//
// kill the feature
// that.ui.side.mouseover(function(e) {
// that.status.fold === 0 && that.foldHandle.call(that, e);
// });
that.ui.textareaSubmit.attr("placeholder", conf.tplSuggestText);
// sdk loading
that.status.sdkLoaded = 1;
/*$.ajax({
url: that.conf.modPath,
dataType: "script",
cache: true,
success: function() {
},
error: function() {
}
});*/
require.async('home:widget/ui/facebook/fbclient-core.js');
};
if(window.ActiveXObject && !window.XMLHttpRequest) {
var body = DOC.body;
if(body) {
body.style.backgroundAttachment = 'fixed';
if(body.currentStyle.backgroundImage == "none") {
body.style.backgroundImage = (DOC.domain.indexOf("https:") == 0) ? 'url(https:///)' : 'url(about:blank)';
}
}
}
FBClient.clickHandle = function($el, type, panel) {
var that = this,
fold = that.status.fold,
sideHome = that.ui.sideHome,
cache = that.cache;
// fold && sideHome.removeClass(type);
cache.curSide && cache.curSide.removeClass(cache.curSideType);
$el && $el.addClass(type);
cache.curSide = $el;
cache.curSideType = type;
cache.panel && cache.panel.hide();
panel && panel.show();
cache.panel = panel;
};
FBClient.foldHandle = function(e) {
var that = this,
fold = that.status.fold,
sdkLoaded = that.status.sdkLoaded;
// playing animation
if(fold === 1) return;
that.status.fold = 1;
that.clickHandle(fold ? null : that.ui.sideHome, fold ? "" : "fb-mod_side_home_cur", that.ui.panelHome);
that.status.bubble && ($.cookie("fb_bubble", 1), that.status.bubble = 0, that.ui.bubble.hide());
fold
? that.ui.uiMod.removeClass("fb-mod--fixed").addClass("fb-mod--fold")
: that.ui.uiMod.removeClass("fb-mod--fold");
setTimeout(function() {
// fold ? sideHome.removeClass("fb-mod_side_home_cur") : that.ui.sideHome.addClass("fb-mod_side_home_cur"), that.cache.curSideType = "fb-mod_side_home_cur";
(that.status.fold = fold ? 0 : 2) && that.status.fixed && that.ui.uiMod.addClass("fb-mod--fixed");
if (!that.status.eventBinded) {
if (sdkLoaded === 2) {
that.bindEvent.call(that);
that.status.eventBinded = 2;
} else {
var t = setInterval(function () {
if (that.status.sdkLoaded === 2) {
that.bindEvent.call(that);
that.status.eventBinded = 2;
clearInterval(t);
}
}, 1000);
}
}
if(fold || sdkLoaded) return;
!function(el) {
if($.browser.mozilla){
el.addEventListener('DOMMouseScroll',function(e){
el.scrollTop += e.detail > 0 ? 30 : -30;
e.preventDefault();
}, !1);
}
else el.onmousewheel = function(e){
e = e || WIN.event;
el.scrollTop += e.wheelDelta > 0 ? -30 : 30;
e.returnValue = false;
};
}(that.ui.body[0])
}, that.supportAnimate ? 300 : 0);
};
module.exports = FBClient;<|fim▁end|> | if(that.status.login !== 2) return false;
that.status.fold === 0 && that.foldHandle.call(that, e);
that.clickHandle($(this), "fb-mod_side_friend_cur", that.ui.panelFriend); |
<|file_name|>factories.py<|end_file_name|><|fim▁begin|>import pickle
from pueue.client.socket import connect_socket, receive_data, process_response
def command_factory(command):
"""A factory which returns functions for direct daemon communication.
This factory will create a function which sends a payload to the daemon
and returns the unpickled object which is returned by the daemon.
Args:
command (string): The type of payload this should be. This determines
as what kind of instruction this will be interpreted by the daemon.
Returns:
function: The created function.<|fim▁hole|>
This function sends a payload to the daemon and returns the unpickled
object sent by the daemon.
Args:
body (dir): Any other arguments that should be put into the payload.
root_dir (str): The root directory in which we expect the daemon.
We need this to connect to the daemons socket.
Returns:
function: The returned payload.
"""
client = connect_socket(root_dir)
body['mode'] = command
# Delete the func entry we use to call the correct function with argparse
# as functions can't be pickled and this shouldn't be send to the daemon.
if 'func' in body:
del body['func']
data_string = pickle.dumps(body, -1)
client.send(data_string)
# Receive message, unpickle and return it
response = receive_data(client)
return response
return communicate
def print_command_factory(command):
"""A factory which returns functions for direct daemon communication.
This factory will create a function which sends a payload to the daemon
and prints the response of the daemon. If the daemon sends a
`response['status'] == 'error'`, the pueue client will exit with `1`.
Args:
command (string): The type of payload this should be. This determines
as what kind of instruction this will be interpreted by the daemon.
Returns:
function: The created function.
"""
def communicate(body={}, root_dir=None):
client = connect_socket(root_dir)
body['mode'] = command
# Delete the func entry we use to call the correct function with argparse
# as functions can't be pickled and this shouldn't be send to the daemon.
if 'func' in body:
del body['func']
data_string = pickle.dumps(body, -1)
client.send(data_string)
# Receive message and print it. Exit with 1, if an error has been sent.
response = receive_data(client)
process_response(response)
return communicate<|fim▁end|> | """
def communicate(body={}, root_dir=None):
"""Communicate with the daemon. |
<|file_name|>util.rs<|end_file_name|><|fim▁begin|><|fim▁hole|>extern crate toml;
use std::io::prelude::*;
use std::fs::File;
use std::path::Path;
use toml::Value;
pub fn slurp_config(path: &str) -> Value {
let mut config_file = File::open(&Path::new(path)).unwrap();
let mut config_text = String::new();
let _ = config_file.read_to_string(&mut config_text);
let mut parser = toml::Parser::new(&config_text[..]);
match parser.parse() {
Some(value) => return Value::Table(value),
None => {
println!("Parsing {} failed.", path);
for error in parser.errors.iter() {
let (ll, lc) = parser.to_linecol(error.lo);
let (hl, hc) = parser.to_linecol(error.hi);
println!("{}({}:{}-{}:{}): {}", path, ll+1, lc+1, hl+1, hc+1, error.desc);
}
panic!("Parsing config failed.");
},
}
}
pub fn get_strings<'r>(config: &'r toml::Value, key: &'r str) -> Vec<&'r str> {
let slice = config.lookup(key).and_then(|x| x.as_slice());
let strings = slice.and_then(|x| x.iter().map(|c| c.as_str()).collect());
return strings.unwrap_or(Vec::new());
}
pub fn nick_of(usermask: &str) -> &str {
let parts: Vec<&str> = usermask.split('!').collect();
let nick = parts[0];
if nick.starts_with(":") {
return &nick[1..];
} else {
return nick;
}
}
#[cfg(test)]
mod tests {
use super::*;
use toml;
#[test]
fn test_get_strings() {
let mut parser = toml::Parser::new("[irc]\nautojoin = [\"#a\", \"#b\"]");
let config = parser.parse().map(|x| toml::Value::Table(x)).unwrap();
assert!(get_strings(&config, "irc.does_not_exist").is_empty());
assert_eq!(get_strings(&config, "irc.autojoin"), ["#a", "#b"]);
}
}<|fim▁end|> | |
<|file_name|>transform-with-as-to-hash.js<|end_file_name|><|fim▁begin|>/**
@module ember
@submodule ember-htmlbars
*/
/**
An HTMLBars AST transformation that replaces all instances of
```handlebars
{{#with foo.bar as bar}}
{{/with}}
```
with
```handlebars
{{#with foo.bar keywordName="bar"}}
{{/with}}
```
@private
@class TransformWithAsToHash
*/
function TransformWithAsToHash() {
// set later within HTMLBars to the syntax package
this.syntax = null;
}
/**
@private
@method transform
@param {AST} The AST to be transformed.
*/
TransformWithAsToHash.prototype.transform = function TransformWithAsToHash_transform(ast) {
var pluginContext = this;
var walker = new pluginContext.syntax.Walker();
var b = pluginContext.syntax.builders;
walker.visit(ast, function(node) {
if (pluginContext.validate(node)) {
var removedParams = node.sexpr.params.splice(1, 2);
var keyword = removedParams[1].original;
// TODO: This may not be necessary.
if (!node.sexpr.hash) {
node.sexpr.hash = b.hash();
}
node.sexpr.hash.pairs.push(b.pair(
'keywordName',<|fim▁hole|> });
return ast;
};
TransformWithAsToHash.prototype.validate = function TransformWithAsToHash_validate(node) {
return node.type === 'BlockStatement' &&
node.sexpr.path.original === 'with' &&
node.sexpr.params.length === 3 &&
node.sexpr.params[1].type === 'PathExpression' &&
node.sexpr.params[1].original === 'as';
};
export default TransformWithAsToHash;<|fim▁end|> | b.string(keyword)
));
} |
<|file_name|>glnoise.js<|end_file_name|><|fim▁begin|>// Seriously awesome GLSL noise functions. (C) Credits and kudos go to
// Copyright (C) Stefan Gustavson, Ian McEwan Ashima Arts
// MIT License.
define(function(require, exports){
exports.permute1 = function(x){
return mod((34.0 * x + 1.0) * x, 289.0)
}
exports.permute3 = function(x){
return mod((34.0 * x + 1.0) * x, 289.0)
}
exports.permute4 = function(x){
return mod((34.0 * x + 1.0) * x, 289.0)
}
exports.isqrtT1 = function(r){
return 1.79284291400159 - 0.85373472095314 * r
}
exports.isqrtT4 = function(r){
return vec4(1.79284291400159 - 0.85373472095314 * r)
}
exports.snoise2 = function(x, y){
return snoise2v(vec2(x,y,z))
}
exports.noise2d =
exports.s2d =
exports.snoise2v = function(v){
var C = vec4(0.211324865405187,0.366025403784439,-0.577350269189626,0.024390243902439)
var i = floor(v + dot(v, C.yy) )
var x0 = v - i + dot(i, C.xx)
var i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0)
var x12 = x0.xyxy + C.xxzz
x12.xy -= i1
i = mod(i, 289.0) // Avoid truncation effects in permutation
var p = permute3(permute3(i.y + vec3(0.0, i1.y, 1.0)) + i.x + vec3(0.0, i1.x, 1.0 ))
var m = max(0.5 - vec3(dot(x0,x0), dot(x12.xy,x12.xy), dot(x12.zw,x12.zw)), 0.0)
m = m*m
m = m*m
var x = 2.0 * fract(p * C.www) - 1.0
var h = abs(x) - 0.5
var ox = floor(x + 0.5)
var a0 = x - ox
m *= (1.79284291400159 - 0.85373472095314 * ( a0*a0 + h*h ))
var g = vec3()
g.x = a0.x * x0.x + h.x * x0.y
g.yz = a0.yz * x12.xz + h.yz * x12.yw
return 130.0 * dot(m, g)
}
exports.snoise3 = function(x, y, z){
return snoise3v(vec3(x,y,z))
}
exports.noise3d =
exports.snoise3v = function(v){
var C = vec2(1.0/6.0, 1.0/3.0)
var D = vec4(0.0, 0.5, 1.0, 2.0)
// First corner
var i = floor(v + dot(v, C.yyy))
var x0 = v - i + dot(i, C.xxx)
var g = step(x0.yzx, x0.xyz)
var l = 1.0 - g
var i1 = min(g.xyz, l.zxy)
var i2 = max(g.xyz, l.zxy)
var x1 = x0 - i1 + 1.0 * C.xxx
var x2 = x0 - i2 + 2.0 * C.xxx
var x3 = x0 - 1. + 3.0 * C.xxx
// Permutations
i = mod(i, 289.0)
var p = permute4(permute4(permute4(
i.z + vec4(0.0, i1.z, i2.z, 1.0))
+ i.y + vec4(0.0, i1.y, i2.y, 1.0))
+ i.x + vec4(0.0, i1.x, i2.x, 1.0))
// ( N*N points uniformly over a square, mapped onto an octahedron.)
var n_ = 1.0/7.0
var ns = n_ * D.wyz - D.xzx
var j = p - 49.0 * floor(p * ns.z *ns.z)
var x_ = floor(j * ns.z)
var y_ = floor(j - 7.0 * x_)
var x = x_ * ns.x + ns.yyyy
var y = y_ * ns.x + ns.yyyy
var h = 1.0 - abs(x) - abs(y)
var b0 = vec4( x.xy, y.xy )
var b1 = vec4( x.zw, y.zw )
var s0 = floor(b0)*2.0 + 1.0
var s1 = floor(b1)*2.0 + 1.0
var sh = -step(h, vec4(0.0))
var a0 = b0.xzyw + s0.xzyw*sh.xxyy
var a1 = b1.xzyw + s1.xzyw*sh.zzww
var p0 = vec3(a0.xy, h.x)
var p1 = vec3(a0.zw, h.y)
var p2 = vec3(a1.xy, h.z)
var p3 = vec3(a1.zw, h.w)
//Normalise gradients<|fim▁hole|> p2 *= norm.z;
p3 *= norm.w;
// Mix final noise value
var m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0)
m = m * m
return 42.0 * dot( m*m, vec4( dot(p0,x0), dot(p1,x1),
dot(p2,x2), dot(p3,x3) ) )
}
exports.snoise4_g = function(j, ip){
var p = vec4()
p.xyz = floor( fract (vec3(j) * ip.xyz) * 7.0) * ip.z - 1.0
p.w = 1.5 - dot(abs(p.xyz), vec3(1.0,1.0,1.0))
var s = vec4(lessThan(p, vec4(0.0)))
p.xyz = p.xyz + (s.xyz*2.0 - 1.0) * s.www
return p
}
exports.snoise4 = function(x, y, z, w){
return snoise4v(vec4(x,y,z,w))
}
exports.snoise4v = function(v){
var C = vec4(0.138196601125011,0.276393202250021,0.414589803375032,-0.447213595499958)
// First corner
var i = floor(v + dot(v, vec4(0.309016994374947451)) )
var x0 = v - i + dot(i, C.xxxx)
var i0 = vec4()
var isX = step( x0.yzw, x0.xxx )
var isYZ = step( x0.zww, x0.yyz )
i0.x = isX.x + isX.y + isX.z
i0.yzw = 1.0 - isX
i0.y += isYZ.x + isYZ.y
i0.zw += 1.0 - isYZ.xy
i0.z += isYZ.z
i0.w += 1.0 - isYZ.z
var i3 = clamp( i0, 0.0, 1.0 )
var i2 = clamp( i0-1.0, 0.0, 1.0 )
var i1 = clamp( i0-2.0, 0.0, 1.0 )
var x1 = x0 - i1 + C.xxxx
var x2 = x0 - i2 + C.yyyy
var x3 = x0 - i3 + C.zzzz
var x4 = x0 + C.wwww
// Permutations
i = mod(i, 289.0 )
var j0 = permute1( permute1( permute1( permute1(i.w) + i.z) + i.y) + i.x)
var j1 = permute4( permute4( permute4( permute4(
i.w + vec4(i1.w, i2.w, i3.w, 1.0 ))
+ i.z + vec4(i1.z, i2.z, i3.z, 1.0 ))
+ i.y + vec4(i1.y, i2.y, i3.y, 1.0 ))
+ i.x + vec4(i1.x, i2.x, i3.x, 1.0 ))
// Gradients: 7x7x6 points over a cube, mapped onto a 4-cross polytope
// 7*7*6 = 294, which is close to the ring size 17*17 = 289.
var ip = vec4(1.0/294.0, 1.0/49.0, 1.0/7.0, 0.0)
var p0 = snoise4_g(j0, ip)
var p1 = snoise4_g(j1.x, ip)
var p2 = snoise4_g(j1.y, ip)
var p3 = snoise4_g(j1.z, ip)
var p4 = snoise4_g(j1.w, ip)
// Normalise gradients
var nr = isqrtT4(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)))
p0 *= nr.x
p1 *= nr.y
p2 *= nr.z
p3 *= nr.w
p4 *= isqrtT1(dot(p4,p4))
// Mix contributions from the five corners
var m0 = max(0.6 - vec3(dot(x0,x0), dot(x1,x1), dot(x2,x2)), 0.0)
var m1 = max(0.6 - vec2(dot(x3,x3), dot(x4,x4)), 0.0)
m0 = m0 * m0
m1 = m1 * m1
return 49.0 * (dot(m0*m0, vec3(dot( p0, x0 ), dot(p1, x1), dot(p2, x2)))
+ dot(m1*m1, vec2( dot(p3, x3), dot(p4, x4))))
}
exports.cell2v = function(v){
return cell3v(vec3(v.x, v.y,0))
}
exports.cell3v = function(P){
var K = 0.142857142857 // 1/7
var Ko = 0.428571428571 // 1/2-K/2
var K2 = 0.020408163265306 // 1/(7*7)
var Kz = 0.166666666667 // 1/6
var Kzo = 0.416666666667 // 1/2-1/6*2
var ji = 0.8 // smaller jitter gives less errors in F2
var Pi = mod(floor(P), 289.0)
var Pf = fract(P)
var Pfx = Pf.x + vec4(0.0, -1.0, 0.0, -1.0)
var Pfy = Pf.y + vec4(0.0, 0.0, -1.0, -1.0)
var p = permute4(Pi.x + vec4(0.0, 1.0, 0.0, 1.0))
p = permute4(p + Pi.y + vec4(0.0, 0.0, 1.0, 1.0))
var p1 = permute4(p + Pi.z) // z+0
var p2 = permute4(p + Pi.z + vec4(1.0)) // z+1
var ox1 = fract(p1*K) - Ko
var oy1 = mod(floor(p1*K), 7.0)*K - Ko
var oz1 = floor(p1*K2)*Kz - Kzo // p1 < 289 guaranteed
var ox2 = fract(p2*K) - Ko
var oy2 = mod(floor(p2*K), 7.0)*K - Ko
var oz2 = floor(p2*K2)*Kz - Kzo
var dx1 = Pfx + ji*ox1
var dy1 = Pfy + ji*oy1
var dz1 = Pf.z + ji*oz1
var dx2 = Pfx + ji*ox2
var dy2 = Pfy + ji*oy2
var dz2 = Pf.z - 1.0 + ji*oz2
var d1 = dx1 * dx1 + dy1 * dy1 + dz1 * dz1 // z+0
var d2 = dx2 * dx2 + dy2 * dy2 + dz2 * dz2 // z+1
var d = min(d1,d2) // F1 is now in d
d2 = max(d1,d2) // Make sure we keep all candidates for F2
d.xy = (d.x < d.y) ? d.xy : d.yx // Swap smallest to d.x
d.xz = (d.x < d.z) ? d.xz : d.zx
d.xw = (d.x < d.w) ? d.xw : d.wx // F1 is now in d.x
d.yzw = min(d.yzw, d2.yzw) // F2 now not in d2.yzw
d.y = min(d.y, d.z) // nor in d.z
d.y = min(d.y, d.w) // nor in d.w
d.y = min(d.y, d2.x) // F2 is now in d.y
return sqrt(d.xy) // F1 and F2
},
exports.cell3w = function(P){
var K = 0.142857142857
var Ko = 0.428571428571 // 1/2-K/2
var K2 = 0.020408163265306// 1/(7*7)
var Kz = 0.166666666667// 1/6
var Kzo = 0.416666666667// 1/2-1/6*2
var ji = 1.0// smaller jitter gives more regular pattern
var Pi = mod(floor(P), 289.0)
var Pf = fract(P) - 0.5
var Pfx = Pf.x + vec3(1.0, 0.0, -1.0)
var Pfy = Pf.y + vec3(1.0, 0.0, -1.0)
var Pfz = Pf.z + vec3(1.0, 0.0, -1.0)
var p = permute3(Pi.x + vec3(-1.0, 0.0, 1.0))
var p1 = permute3(p + Pi.y - 1.0)
var p2 = permute3(p + Pi.y)
var p3 = permute3(p + Pi.y + 1.0)
var p11 = permute3(p1 + Pi.z - 1.0)
var p12 = permute3(p1 + Pi.z)
var p13 = permute3(p1 + Pi.z + 1.0)
var p21 = permute3(p2 + Pi.z - 1.0)
var p22 = permute3(p2 + Pi.z)
var p23 = permute3(p2 + Pi.z + 1.0)
var p31 = permute3(p3 + Pi.z - 1.0)
var p32 = permute3(p3 + Pi.z)
var p33 = permute3(p3 + Pi.z + 1.0)
var ox11 = fract(p11*K) - Ko
var oy11 = mod(floor(p11*K), 7.0)*K - Ko
var oz11 = floor(p11*K2)*Kz - Kzo // p11 < 289 guaranteed
var ox12 = fract(p12*K) - Ko
var oy12 = mod(floor(p12*K), 7.0)*K - Ko
var oz12 = floor(p12*K2)*Kz - Kzo
var ox13 = fract(p13*K) - Ko
var oy13 = mod(floor(p13*K), 7.0)*K - Ko
var oz13 = floor(p13*K2)*Kz - Kzo
var ox21 = fract(p21*K) - Ko
var oy21 = mod(floor(p21*K), 7.0)*K - Ko
var oz21 = floor(p21*K2)*Kz - Kzo
var ox22 = fract(p22*K) - Ko
var oy22 = mod(floor(p22*K), 7.0)*K - Ko
var oz22 = floor(p22*K2)*Kz - Kzo
var ox23 = fract(p23*K) - Ko
var oy23 = mod(floor(p23*K), 7.0)*K - Ko
var oz23 = floor(p23*K2)*Kz - Kzo
var ox31 = fract(p31*K) - Ko
var oy31 = mod(floor(p31*K), 7.0)*K - Ko
var oz31 = floor(p31*K2)*Kz - Kzo
var ox32 = fract(p32*K) - Ko
var oy32 = mod(floor(p32*K), 7.0)*K - Ko
var oz32 = floor(p32*K2)*Kz - Kzo
var ox33 = fract(p33*K) - Ko
var oy33 = mod(floor(p33*K), 7.0)*K - Ko
var oz33 = floor(p33*K2)*Kz - Kzo
var dx11 = Pfx + ji*ox11
var dy11 = Pfy.x + ji*oy11
var dz11 = Pfz.x + ji*oz11
var dx12 = Pfx + ji*ox12
var dy12 = Pfy.x + ji*oy12
var dz12 = Pfz.y + ji*oz12
var dx13 = Pfx + ji*ox13
var dy13 = Pfy.x + ji*oy13
var dz13 = Pfz.z + ji*oz13
var dx21 = Pfx + ji*ox21
var dy21 = Pfy.y + ji*oy21
var dz21 = Pfz.x + ji*oz21
var dx22 = Pfx + ji*ox22
var dy22 = Pfy.y + ji*oy22
var dz22 = Pfz.y + ji*oz22
var dx23 = Pfx + ji*ox23
var dy23 = Pfy.y + ji*oy23
var dz23 = Pfz.z + ji*oz23
var dx31 = Pfx + ji*ox31
var dy31 = Pfy.z + ji*oy31
var dz31 = Pfz.x + ji*oz31
var dx32 = Pfx + ji*ox32
var dy32 = Pfy.z + ji*oy32
var dz32 = Pfz.y + ji*oz32
var dx33 = Pfx + ji*ox33
var dy33 = Pfy.z + ji*oy33
var dz33 = Pfz.z + ji*oz33
var d11 = dx11 * dx11 + dy11 * dy11 + dz11 * dz11
var d12 = dx12 * dx12 + dy12 * dy12 + dz12 * dz12
var d13 = dx13 * dx13 + dy13 * dy13 + dz13 * dz13
var d21 = dx21 * dx21 + dy21 * dy21 + dz21 * dz21
var d22 = dx22 * dx22 + dy22 * dy22 + dz22 * dz22
var d23 = dx23 * dx23 + dy23 * dy23 + dz23 * dz23
var d31 = dx31 * dx31 + dy31 * dy31 + dz31 * dz31
var d32 = dx32 * dx32 + dy32 * dy32 + dz32 * dz32
var d33 = dx33 * dx33 + dy33 * dy33 + dz33 * dz33
var d1a = min(d11, d12)
d12 = max(d11, d12)
d11 = min(d1a, d13) // Smallest now not in d12 or d13
d13 = max(d1a, d13)
d12 = min(d12, d13) // 2nd smallest now not in d13
var d2a = min(d21, d22)
d22 = max(d21, d22)
d21 = min(d2a, d23) // Smallest now not in d22 or d23
d23 = max(d2a, d23)
d22 = min(d22, d23) // 2nd smallest now not in d23
var d3a = min(d31, d32)
d32 = max(d31, d32)
d31 = min(d3a, d33) // Smallest now not in d32 or d33
d33 = max(d3a, d33)
d32 = min(d32, d33) // 2nd smallest now not in d33
var da = min(d11, d21)
d21 = max(d11, d21)
d11 = min(da, d31) // Smallest now in d11
d31 = max(da, d31) // 2nd smallest now not in d31
d11.xy = (d11.x < d11.y) ? d11.xy : d11.yx
d11.xz = (d11.x < d11.z) ? d11.xz : d11.zx // d11.x now smallest
d12 = min(d12, d21) // 2nd smallest now not in d21
d12 = min(d12, d22) // nor in d22
d12 = min(d12, d31) // nor in d31
d12 = min(d12, d32) // nor in d32
d11.yz = min(d11.yz, d12.xy) // nor in d12.yz
d11.y = min(d11.y, d12.z) // Only two more to go
d11.y = min(d11.y, d11.z) // Done! (Phew!)
return sqrt(d11.xy) // F1, F2
}
})<|fim▁end|> | var norm = isqrtT4(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)))
p0 *= norm.x;
p1 *= norm.y; |
<|file_name|>01-run.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Test behaviour of the test running and the term program interaction."""
import sys
import pexpect
from testrunner import run
def _shellping(child, timeout=1):
"""Issue a 'shellping' command.
Raises a pexpect exception on failure.
:param timeout: timeout for the answer
"""
child.sendline('shellping')
child.expect_exact('shellpong\r\n', timeout=timeout)
def _wait_shell_ready(child, numtries=5):
"""Wait until the shell is ready by using 'shellping'."""
for _ in range(numtries - 1):
try:
_shellping(child)
except pexpect.TIMEOUT:
pass
else:
break
else:
# This one should fail
_shellping(child)
def _test_no_local_echo(child):
"""Verify that there is not local echo while testing."""
msg = 'true this should not be echoed'
child.sendline(msg)
res = child.expect_exact([pexpect.TIMEOUT, msg], timeout=1)
assert res == 0, "There should have been a timeout and not match stdin"
def testfunc(child):
"""Run some tests to verify the board under test behaves correctly.
It currently tests:
* local echo
"""
child.expect_exact("Running 'tests_tools' application")
_wait_shell_ready(child)
# Verify there is no local and remote echo as it is disabled<|fim▁hole|>
# The node should still answer after the previous one
_shellping(child)
if __name__ == "__main__":
sys.exit(run(testfunc))<|fim▁end|> | _test_no_local_echo(child) |
<|file_name|>main.cpp<|end_file_name|><|fim▁begin|>#include <iostream><|fim▁hole|>int main()
{
try
{
Game game;
game.run();
}
catch (std::exception& e)
{
std::cout << "\nEXCEPTION: " << e.what() <<std::endl;
}
}<|fim▁end|> | #include <stdexcept>
#include "game.h"
|
<|file_name|>test_cargo_profiles.rs<|end_file_name|><|fim▁begin|>use std::env;
use std::path::MAIN_SEPARATOR as SEP;
<|fim▁hole|>use support::{project, execs};
use support::{COMPILING, RUNNING};
use hamcrest::assert_that;
fn setup() {
}
test!(profile_overrides {
let mut p = project("foo");
p = p
.file("Cargo.toml", r#"
[package]
name = "test"
version = "0.0.0"
authors = []
[profile.dev]
opt-level = 1
debug = false
rpath = true
"#)
.file("src/lib.rs", "");
assert_that(p.cargo_process("build").arg("-v"),
execs().with_status(0).with_stdout(&format!("\
{compiling} test v0.0.0 ({url})
{running} `rustc src{sep}lib.rs --crate-name test --crate-type lib \
-C opt-level=1 \
-C debug-assertions=on \
-C metadata=[..] \
-C extra-filename=-[..] \
-C rpath \
--out-dir {dir}{sep}target{sep}debug \
--emit=dep-info,link \
-L dependency={dir}{sep}target{sep}debug \
-L dependency={dir}{sep}target{sep}debug{sep}deps`
",
running = RUNNING, compiling = COMPILING, sep = SEP,
dir = p.root().display(),
url = p.url(),
)));
});
test!(top_level_overrides_deps {
let mut p = project("foo");
p = p
.file("Cargo.toml", r#"
[package]
name = "test"
version = "0.0.0"
authors = []
[profile.release]
opt-level = 1
debug = true
[dependencies.foo]
path = "foo"
"#)
.file("src/lib.rs", "")
.file("foo/Cargo.toml", r#"
[package]
name = "foo"
version = "0.0.0"
authors = []
[profile.release]
opt-level = 0
debug = false
[lib]
name = "foo"
crate_type = ["dylib", "rlib"]
"#)
.file("foo/src/lib.rs", "");
assert_that(p.cargo_process("build").arg("-v").arg("--release"),
execs().with_status(0).with_stdout(&format!("\
{compiling} foo v0.0.0 ({url})
{running} `rustc foo{sep}src{sep}lib.rs --crate-name foo \
--crate-type dylib --crate-type rlib -C prefer-dynamic \
-C opt-level=1 \
-g \
-C metadata=[..] \
-C extra-filename=-[..] \
--out-dir {dir}{sep}target{sep}release{sep}deps \
--emit=dep-info,link \
-L dependency={dir}{sep}target{sep}release{sep}deps \
-L dependency={dir}{sep}target{sep}release{sep}deps`
{compiling} test v0.0.0 ({url})
{running} `rustc src{sep}lib.rs --crate-name test --crate-type lib \
-C opt-level=1 \
-g \
-C metadata=[..] \
-C extra-filename=-[..] \
--out-dir {dir}{sep}target{sep}release \
--emit=dep-info,link \
-L dependency={dir}{sep}target{sep}release \
-L dependency={dir}{sep}target{sep}release{sep}deps \
--extern foo={dir}{sep}target{sep}release{sep}deps{sep}\
{prefix}foo-[..]{suffix} \
--extern foo={dir}{sep}target{sep}release{sep}deps{sep}libfoo-[..].rlib`
",
running = RUNNING,
compiling = COMPILING,
dir = p.root().display(),
url = p.url(),
sep = SEP,
prefix = env::consts::DLL_PREFIX,
suffix = env::consts::DLL_SUFFIX)));
});<|fim▁end|> | |
<|file_name|>notfica.js<|end_file_name|><|fim▁begin|>document.addEventListener('deviceready', ondeviceready, false);
function Notifi (){
cordova.plugins.notification.local.schedule({
id: 1,
title: "Atento!!!!!",
message: "Este evento se ha agregado a tu lista "
<|fim▁hole|><|fim▁end|> | });
} |
<|file_name|>middleware.py<|end_file_name|><|fim▁begin|>try:
from hashlib import md5
except ImportError:
from md5 import md5
class ratingMiddleware(object):<|fim▁hole|> def generate_token(self, request):
raise NotImplementedError
class ratingIpMiddleware(ratingMiddleware):
def generate_token(self, request):
return request.META['REMOTE_ADDR']
class ratingIpUseragentMiddleware(ratingMiddleware):
def generate_token(self, request):
s = ''.join((request.META['REMOTE_ADDR'], request.META['HTTP_USER_AGENT']))
return md5(s).hexdigest()<|fim▁end|> | def process_request(self, request):
request.rating_token = self.generate_token(request)
|
<|file_name|>Header.js<|end_file_name|><|fim▁begin|>/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import {
Nav,
NavItem,
NavDropdown,
MenuItem,
ProgressBar,
} from 'react-bootstrap';
import Navbar, {Brand} from 'react-bootstrap/lib/Navbar';
import history from '../../core/history';
import $ from "jquery";
import Sidebar from '../Sidebar';
const logo = require('./logo.png');
function Header() {
return (
<div id="wrapper" className="content">
<Navbar fluid={true} style={ {margin: 0} }>
<Brand>
<span>
<img src={logo} alt="Start React" title="Start React" />
<span> SB Admin React - </span>
<a href="http://startreact.com/" title="Start React" rel="home">StartReact.com</a>
<button type="button" className="navbar-toggle" onClick={() => {toggleMenu();}} style={{position: 'absolute', right: 0, top: 0}}>
<span className="sr-only">Toggle navigation</span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
</button>
</span>
</Brand>
<ul className="nav navbar-top-links navbar-right">
<NavDropdown bsClass="dropdown" title={<span><i className="fa fa-envelope fa-fw"></i></span>} id="navDropdown1">
<MenuItem style={ {width: 300} } eventKey="1">
<div> <strong>John Smith</strong> <span className="pull-right text-muted"> <em>Yesterday</em> </span> </div>
<div> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eleifend...</div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="2">
<div> <strong>John Smith</strong> <span className="pull-right text-muted"> <em>Yesterday</em> </span> </div>
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eleifend...</div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="3">
<div> <strong>John Smith</strong> <span className="pull-right text-muted"> <em>Yesterday</em> </span> </div>
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eleifend...</div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="4" className="text-center">
<strong>Read All Messages</strong> <i className="fa fa-angle-right"></i>
</MenuItem>
</NavDropdown>
<NavDropdown title={<span><i className="fa fa-tasks fa-fw"></i> </span>} id = 'navDropdown2222'>
<MenuItem eventKey="1" style={ {width: 300} }>
<div>
<p> <strong>Task 1</strong> <span className="pull-right text-muted">40% Complete</span> </p>
<div>
<ProgressBar bsStyle="success" now={40} />
</div>
</div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="2">
<div>
<p> <strong>Task 2</strong> <span className="pull-right text-muted">20% Complete</span> </p>
<div>
<ProgressBar bsStyle="info" now={20} />
</div>
</div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="3">
<div>
<p> <strong>Task 3</strong> <span className="pull-right text-muted">60% Complete</span> </p>
<div>
<ProgressBar bsStyle="warning" now={60} />
</div>
</div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="4">
<div>
<p> <strong>Task 4</strong> <span className="pull-right text-muted">80% Complete</span> </p>
<div>
<ProgressBar bsStyle="danger" now={80} />
</div>
</div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="5">
<strong>See All Tasks</strong> <i className="fa fa-angle-right"></i>
</MenuItem>
</NavDropdown>
<NavDropdown title={<i className="fa fa-bell fa-fw"></i>} id = 'navDropdown3'>
<MenuItem eventKey="1" style={ {width: 300} }>
<div> <i className="fa fa-comment fa-fw"></i> New Comment <span className="pull-right text-muted small">4 minutes ago</span> </div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="2">
<div> <i className="fa fa-twitter fa-fw"></i> 3 New Followers <span className="pull-right text-muted small">12 minutes ago</span> </div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="3">
<div> <i className="fa fa-envelope fa-fw"></i> Message Sent <span className="pull-right text-muted small">4 minutes ago</span> </div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="4">
<div> <i className="fa fa-tasks fa-fw"></i> New Task <span className="pull-right text-muted small">4 minutes ago</span> </div>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey="5"><|fim▁hole|> <MenuItem divider />
<MenuItem eventKey="6">
<strong>See All Alerts</strong> <i className="fa fa-angle-right"></i>
</MenuItem>
</NavDropdown>
<NavDropdown title={<i className="fa fa-user fa-fw"></i> } id = 'navDropdown4'>
<MenuItem eventKey="1">
<span> <i className="fa fa-user fa-fw"></i> User Profile </span>
</MenuItem>
<MenuItem eventKey="2">
<span><i className="fa fa-gear fa-fw"></i> Settings </span>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey = "3" href = 'http://www.strapui.com' >
<span> <i className = "fa fa-eye fa-fw" /> Premium React Themes </span>
</MenuItem>
<MenuItem divider />
<MenuItem eventKey = "4" onClick = {(event) => { history.push('/login');}}>
<span> <i className = "fa fa-sign-out fa-fw" /> Logout </span>
</MenuItem>
</NavDropdown>
</ul>
<Sidebar />
</Navbar>
</div>
);
}
function toggleMenu(){
if($(".navbar-collapse").hasClass('collapse')){
$(".navbar-collapse").removeClass('collapse');
}
else{
$(".navbar-collapse").addClass('collapse');
}
}
export default Header;<|fim▁end|> | <div> <i className="fa fa-upload fa-fw"></i> Server Rebooted <span className="pull-right text-muted small">4 minutes ago</span> </div>
</MenuItem> |
<|file_name|>IStatsView.ts<|end_file_name|><|fim▁begin|>
interface IStatsView {
Update(stats: StatsModel): void ;<|fim▁hole|>}<|fim▁end|> | Clear(): void ; |
<|file_name|>AudioPlayer.js<|end_file_name|><|fim▁begin|>define(['jquery', 'pubsub'], function($, pubsub) {
function AudioPlayer(audio){
this.audio = audio;
this._initSubscribe();
this.startPos = 0;
this.endPos = 0;<|fim▁hole|> AudioPlayer.prototype._initSubscribe = function() {
var self = this;
$.subscribe("AudioCursor-clickedAudio", function(el, posCursor) {
self.startPos = posCursor;
self.audio.disableLoop();
});
$.subscribe("AudioCursor-selectedAudio", function(el, startPos, endPos) {
self.startPos = startPos;
self.endPos = endPos;
self.audio.loop(startPos, endPos);
});
$.subscribe("ToPlayer-play", function() {
self.audio.play(self.startPos);
});
$.subscribe("ToPlayer-pause", function() {
self.startPos = null;
self.audio.pause();
});
$.subscribe("Audio-end", function(){
self.startPos = null;
});
$.subscribe("ToPlayer-stop", function() {
self.startPos = null;
self.audio.stop();
});
$.subscribe('ToAudioPlayer-disable', function(){
self.audio.disable(true); //true to not disable audio
});
$.subscribe('ToAudioPlayer-enable', function(){
self.audio.enable(true); //true to not disable audio
});
$.subscribe('ToPlayer-playPause', function() {
if (self.audio.isPlaying){
$.publish('ToPlayer-pause');
} else {
self.audio.play(self.startPos);
}
});
$.subscribe('ToPlayer-toggleLoop', function() {
var toggle;
if (self.loopEnabled){
toggle = self.audio.disableLoopSong();
}else{
toggle = self.audio.enableLoopSong();
}
if (toggle){
self.loopEnabled = !self.loopEnabled;
$.publish('PlayerModel-toggleLoop', self.loopEnabled);
}
});
};
return AudioPlayer;
});<|fim▁end|> | this.loopEnabled = false;
}
|
<|file_name|>SDR14_Playlist_example.py<|end_file_name|><|fim▁begin|>#
# (C)opyright 2015 Signal Processing Devices Sweden AB
#
# This script showcases in Python
# - How to connect to ADQ devices in Python
# - Upload of waveforms to the SDR14
# - Using a playlist on the SDR14
# - How to setup an acquisition of data
# - How to read data by GetData API in Python
# - How to plot data in Python
#
# Note: The example is intended to use the SDR14 device connected in loopback mode (i.e. connect DAC output to ADC input)
import numpy as np
import ctypes as ct
import matplotlib.pyplot as plt
def set_playlist( adq_cu, adq_num, dac_id, tcstr ):
tc = {}
if (tcstr == 'basic1'):
ns = 2 # Number of items
tc["ns"] = ns
# 1 2 3 4 5 6 7 8 9
tc["index"] = (ct.c_uint32 * ns)( 1, 2)
tc["segment"] = (ct.c_uint32 * ns)( 1, 2)
tc["next"] = (ct.c_uint32 * ns)( 2, 1)
tc["wrap"] = (ct.c_uint32 * ns)( 4, 3)
tc["ulsign"] = (ct.c_uint32 * ns)( 0, 0)
tc["trigtype"] = (ct.c_uint32 * ns)( 1, 1)
tc["triglength"] = (ct.c_uint32 * ns)( 50, 50)
tc["trigpolarity"]=(ct.c_uint32 * ns)( 0, 0)
tc["trigsample"]= (ct.c_uint32 * ns)( 1, 1)
tc["writemask"]= (ct.c_uint32 * ns)( 15, 15)
# Transfer playlist to device
ADQAPI.ADQ_AWGWritePlaylist( adq_cu, adq_num, dac_id, tc['ns'], ct.byref(tc['index']), ct.byref(tc['writemask']), ct.byref(tc['segment']), ct.byref(tc['wrap']), ct.byref(tc['next']), ct.byref(tc['trigtype']), ct.byref(tc['triglength']), ct.byref(tc['trigpolarity']), ct.byref(tc['trigsample']), ct.byref(tc['ulsign']) )
# Select the Playlist mode
ADQAPI.ADQ_AWGPlaylistMode( adq_cu, adq_num, dac_id, 1)
return tc
def lessen_to_14bits( databuf ):
for x in range(0,4096):
databuf[x] = databuf[x] & 0x3FFF;
return databuf
def define_and_upload_segments( adq_cu, adq_num, dac_id ):
# Setup target buffers for upload of data
number_of_data_segments = 3
data_length = 4096
data_buffers=(ct.POINTER(ct.c_int16*data_length)*number_of_data_segments)()
databuf = np.zeros((number_of_data_segments,data_length))
for bufp in data_buffers:
bufp.contents = (ct.c_int16*data_length)()
# Re-arrange data in numpy arrays
databuf = np.frombuffer(data_buffers[0].contents,dtype=np.int16)
#Create sawtooth
for x in range(0, 1024):
databuf[x] = x
databuf[x+1024] = 1024 - x
databuf[x+2048] = -x
databuf[x+2048+1024] = -1024 + x
databuf = lessen_to_14bits(databuf)
databuf = np.frombuffer(data_buffers[1].contents,dtype=np.int16)
#Create positive pulse
for x in range(0, 128):
databuf[x] = 1024+x
databuf[x+128] = 1300+x
databuf[x+256] = 1300+128-x
for x in range(384, 4096):
databuf[x] = 0
databuf = lessen_to_14bits(databuf)
#Create negative pulse (one level)
databuf = np.frombuffer(data_buffers[2].contents,dtype=np.int16)
for x in range(0, 256):
databuf[x] = -512
for x in range(256, 4096):
databuf[x] = 0
databuf = lessen_to_14bits(databuf)
length_np = (ct.c_uint32 * number_of_data_segments)(data_length, data_length, data_length)
segId_np = (ct.c_uint32 * number_of_data_segments)(1, 2, 3)
NofLaps_np = (ct.c_uint32 * number_of_data_segments)(3, 3, 3)
for idx,bufp in enumerate(data_buffers):
ADQAPI.ADQ_AWGSegmentMalloc( adq_cu, adq_num, dac_id, idx+1, length_np[idx], 0)
ADQAPI.ADQ_AWGWriteSegments( adq_cu, adq_num, dac_id, number_of_data_segments, ct.byref(segId_np), ct.byref(NofLaps_np), ct.byref(length_np), data_buffers )
# Note: In playlist mode, all used segments must be in the enabled range, otherwise plaqyback will stop
ADQAPI.ADQ_AWGEnableSegments( adq_cu, adq_num, dac_id, number_of_data_segments )
return
# For Python under Linux (uncomment in Linux)
#ADQAPI = ct.cdll.LoadLibrary("libadq.so")
# For Python under Windows
ADQAPI = ct.cdll.LoadLibrary("ADQAPI.dll")
ADQAPI.ADQAPI_GetRevision()
# Manually set return type from some ADQAPI functions
ADQAPI.CreateADQControlUnit.restype = ct.c_void_p
ADQAPI.ADQ_GetRevision.restype = ct.c_void_p
ADQAPI.ADQ_GetPtrStream.restype = ct.POINTER(ct.c_int16)
ADQAPI.ADQControlUnit_FindDevices.argtypes = [ct.c_void_p]
# Create ADQControlUnit
adq_cu = ct.c_void_p(ADQAPI.CreateADQControlUnit())
ADQAPI.ADQControlUnit_EnableErrorTrace(adq_cu, 3, '.')
adq_num = 1
dac_id = 1
bypass_analog = 1
# Convenience function
def adq_status(status):
if (status==0):
return 'FAILURE'
else:
return 'OK'
# Find ADQ devices
ADQAPI.ADQControlUnit_FindDevices(adq_cu)
n_of_ADQ = ADQAPI.ADQControlUnit_NofADQ(adq_cu)
print('Number of ADQ found: {}'.format(n_of_ADQ))
if n_of_ADQ > 0:
# Get revision info from ADQ
rev = ADQAPI.ADQ_GetRevision(adq_cu, adq_num)
revision = ct.cast(rev,ct.POINTER(ct.c_int))
print('\nConnected to ADQ #1')
# Print revision information
print('FPGA Revision: {}'.format(revision[0]))
if (revision[1]):
print('Local copy')
else :
print('SVN Managed')
if (revision[2]):
print('Mixed Revision')
else :
print('SVN Updated')
print('')
# Choose whether to bypass_analog
ADQAPI.ADQ_WriteRegister(adq_cu, adq_num, 10240, 0, 2*bypass_analog);
# Upload data to SDR14<|fim▁hole|> set_playlist(adq_cu, adq_num, dac_id, 'basic1')
ADQAPI.ADQ_AWGAutoRearm(adq_cu, adq_num, dac_id, 1)
ADQAPI.ADQ_AWGContinuous(adq_cu, adq_num, dac_id, 0)
ADQAPI.ADQ_AWGSetTriggerEnable(adq_cu, adq_num, 31)
ADQAPI.ADQ_AWGArm(adq_cu, adq_num, dac_id)
#ADQAPI.ADQ_AWGTrig(adq_cu, adq_num, dac_id)
# Set clock source
ADQ_CLOCK_INT_INTREF = 0
ADQAPI.ADQ_SetClockSource(adq_cu, adq_num, ADQ_CLOCK_INT_INTREF);
# Set trig mode
SW_TRIG = 1
EXT_TRIG_1 = 2
EXT_TRIG_2 = 7
EXT_TRIG_3 = 8
LVL_TRIG = 3
INT_TRIG = 4
LVL_FALLING = 0
LVL_RISING = 1
trigger = SW_TRIG
success = ADQAPI.ADQ_SetTriggerMode(adq_cu, adq_num, trigger)
if (success == 0):
print('ADQ_SetTriggerMode failed.')
number_of_records = 1
samples_per_record = 65536
# Start acquisition
ADQAPI.ADQ_MultiRecordSetup(adq_cu, adq_num,
number_of_records,
samples_per_record)
ADQAPI.ADQ_DisarmTrigger(adq_cu, adq_num)
ADQAPI.ADQ_ArmTrigger(adq_cu, adq_num)
while(ADQAPI.ADQ_GetAcquiredAll(adq_cu,adq_num) == 0):
if (trigger == SW_TRIG):
ADQAPI.ADQ_SWTrig(adq_cu, adq_num)
print('Waiting for trigger')
# Setup target buffers for data
max_number_of_channels = 2
target_buffers=(ct.POINTER(ct.c_int16*samples_per_record*number_of_records)*max_number_of_channels)()
for bufp in target_buffers:
bufp.contents = (ct.c_int16*samples_per_record*number_of_records)()
# Get data from ADQ
ADQ_TRANSFER_MODE_NORMAL = 0
ADQ_CHANNELS_MASK = 0x3
status = ADQAPI.ADQ_GetData(adq_cu, adq_num, target_buffers,
samples_per_record*number_of_records, 2,
0, number_of_records, ADQ_CHANNELS_MASK,
0, samples_per_record, ADQ_TRANSFER_MODE_NORMAL);
print('ADQ_GetData returned {}'.format(adq_status(status)))
# Re-arrange data in numpy arrays
data_16bit_ch0 = np.frombuffer(target_buffers[0].contents[0],dtype=np.int16)
data_16bit_ch1 = np.frombuffer(target_buffers[1].contents[0],dtype=np.int16)
# Plot data
if True:
plt.figure(1)
plt.clf()
plt.plot(data_16bit_ch0, '.-')
plt.plot(data_16bit_ch1, '.--')
plt.show()
# Only disarm trigger after data is collected
ADQAPI.ADQ_DisarmTrigger(adq_cu, adq_num)
ADQAPI.ADQ_MultiRecordClose(adq_cu, adq_num);
# Delete ADQControlunit
ADQAPI.DeleteADQControlUnit(adq_cu);
print('Done')
else:
print('No ADQ connected.')
# This can be used to completely unload the DLL in Windows
#ct.windll.kernel32.FreeLibrary(ADQAPI._handle)<|fim▁end|> | define_and_upload_segments(adq_cu, adq_num, dac_id) |
<|file_name|>hooks.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / |
# | | |___| | | | __/ (__| < | | | | . \ |
# | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ |
# | |
# | Copyright Mathias Kettner 2014 [email protected] |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation in version 2. check_mk is distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY; with-
# out even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU General Public License for more de-
# ails. You should have received a copy of the GNU General Public
# License along with GNU Make; see the file COPYING. If not, write
# to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301 USA.
import config, sys
hooks = {}
# Datastructures and functions needed before plugins can be loaded
loaded_with_language = False
# Load all login plugins
def load_plugins():
global loaded_with_language
if loaded_with_language == current_language:
return
# Cleanup all registered hooks. They need to be renewed by load_plugins()
# of the other modules<|fim▁hole|> # This must be set after plugin loading to make broken plugins raise
# exceptions all the time and not only the first time (when the plugins
# are loaded).
loaded_with_language = current_language
def unregister():
global hooks
hooks = {}
def register(name, func):
hooks.setdefault(name, []).append(func)
def get(name):
return hooks.get(name, [])
def registered(name):
""" Returns True if at least one function is registered for the given hook """
return hooks.get(name, []) != []
def call(name, *args):
n = 0
for hk in hooks.get(name, []):
n += 1
try:
hk(*args)
except Exception, e:
if config.debug:
import traceback, StringIO
txt = StringIO.StringIO()
t, v, tb = sys.exc_info()
traceback.print_exception(t, v, tb, None, txt)
html.show_error("<h1>" + _("Error executing hook") + " %s #%d: %s</h1>"
"<pre>%s</pre>" % (name, n, e, txt.getvalue()))
raise<|fim▁end|> | unregister()
|
<|file_name|>test_functions_loader.py<|end_file_name|><|fim▁begin|>import unittest
from nose2 import events, loader, session
from nose2.plugins.loader import functions
from nose2.tests._common import TestCase
class TestFunctionLoader(TestCase):
def setUp(self):
self.session = session.Session()
self.loader = loader.PluggableTestLoader(self.session)
self.plugin = functions.Functions(session=self.session)
def test_can_load_test_functions_from_module(self):
class Mod(object):
pass
def test():
pass
m = Mod()
m.test = test
event = events.LoadFromModuleEvent(self.loader, m)
self.session.hooks.loadTestsFromModule(event)
self.assertEqual(len(event.extraTests), 1)
assert isinstance(event.extraTests[0], unittest.FunctionTestCase)
def test_ignores_generator_functions(self):<|fim▁hole|>
def test():
yield
m = Mod()
m.test = test
event = events.LoadFromModuleEvent(self.loader, m)
self.session.hooks.loadTestsFromModule(event)
self.assertEqual(len(event.extraTests), 0)
def test_ignores_functions_that_take_args(self):
class Mod(object):
pass
def test(a):
pass
m = Mod()
m.test = test
event = events.LoadFromModuleEvent(self.loader, m)
self.session.hooks.loadTestsFromModule(event)
self.assertEqual(len(event.extraTests), 0)<|fim▁end|> | class Mod(object):
pass |
<|file_name|>clean.js<|end_file_name|><|fim▁begin|>"use strict";
var gulp = require('gulp');
var clean = require('gulp-clean');
var cleanTask = function() {
return gulp.src('dist', { read: false })
.pipe(clean());
};
gulp.task('clean', cleanTask);<|fim▁hole|>module.exports = cleanTask;<|fim▁end|> | |
<|file_name|>Gurobi_Primal_Standard.py<|end_file_name|><|fim▁begin|>'''
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
'''
# Building a Standard Primal Linear Programming Problem
# in Python/Gurobi[gurobipy]
#
'''
Adapted from:
Daskin, M. S.
1995
Network and Discrete Location: Models, Algorithms, and Applications
Hoboken, NJ, USA: John Wiley & Sons, Inc.
'''
# Imports
import numpy as np
import gurobipy as gbp
import datetime as dt
def GbpStPrimLP():
# Constants
Aij = np.random.randint(5, 50, 25)
Aij = Aij.reshape(5,5)
AijSum = np.sum(Aij)
Cj = np.random.randint(10, 20, 5)
CjSum = np.sum(Cj)
Bi = np.random.randint(10, 20, 5)
BiSum = np.sum(Bi)
# Matrix Shape
rows = range(len(Aij))
cols = range(len(Aij[0]))
# Instantiate Model
mPrimal_Standard_GUROBI = gbp.Model(' -- Standard Primal Linear Programming Problem -- ')
# Set Focus to Optimality
gbp.setParam('MIPFocus', 2)
# Decision Variables
desc_var = []
for dest in cols:
desc_var.append([])
desc_var[dest].append(mPrimal_Standard_GUROBI.addVar(vtype=gbp.GRB.CONTINUOUS,
name='y'+str(dest+1)))
# Surplus Variables
surp_var = []
for orig in rows:
surp_var.append([])
surp_var[orig].append(mPrimal_Standard_GUROBI.addVar(vtype=gbp.GRB.CONTINUOUS,
name='s'+str(orig+1)))
# Update Model
mPrimal_Standard_GUROBI.update()
#Objective Function
mPrimal_Standard_GUROBI.setObjective(gbp.quicksum(Cj[dest]*desc_var[dest][0]
for dest in cols),
gbp.GRB.MINIMIZE)
# Constraints
for orig in rows:
mPrimal_Standard_GUROBI.addConstr(gbp.quicksum(Aij[orig][dest]*desc_var[dest][0]
for dest in cols)
- surp_var[orig][0]
- Bi[orig] == 0)
# Optimize
try:
mPrimal_Standard_GUROBI.optimize()
except Exception as e:
print ' ################################################################'
print ' < ISSUE : ', e, ' >'
print ' ################################################################'
# Write LP file
mPrimal_Standard_GUROBI.write('LP.lp')
print '\n*************************************************************************'
print ' | Decision Variables'
for v in mPrimal_Standard_GUROBI.getVars():
print ' | ', v.VarName, '=', v.x
print '*************************************************************************'
val = mPrimal_Standard_GUROBI.objVal
print ' | Objective Value ------------------ ', val
print ' | Aij Sum -------------------------- ', AijSum
print ' | Cj Sum --------------------------- ', CjSum
print ' | Bi Sum --------------------------- ', BiSum
print ' | Matrix Dimensions ---------------- ', Aij.shape
print ' | Date/Time ------------------------ ', dt.datetime.now()<|fim▁hole|> print '-- Gurobi Standard Primal Linear Programming Problem --'
try:
GbpStPrimLP()
print '\nJames Gaboardi, 2015'
except Exception as e:
print ' ################################################################'
print ' < ISSUE : ', e, ' >'
print ' ################################################################'<|fim▁end|> | print '*************************************************************************' |
<|file_name|>single-number-ii.go<|end_file_name|><|fim▁begin|>package problem0137
func singleNumber(nums []int) int {<|fim▁hole|> if (num & (1 << uint(i))) > 0 {
cnt++
}
}
if cnt%3 == 1 {
ans |= 1 << uint(i)
}
}
return int(ans)
}<|fim▁end|> | var ans int32
for i := 0; i < 32; i++ {
cnt := 0
for _, num := range nums { |
<|file_name|>ptr_32_le.go<|end_file_name|><|fim▁begin|>//go:build 386 || amd64p32 || arm || mipsle || mips64p32le
// +build 386 amd64p32 arm mipsle mips64p32le<|fim▁hole|>import (
"unsafe"
)
// Pointer wraps an unsafe.Pointer to be 64bit to
// conform to the syscall specification.
type Pointer struct {
ptr unsafe.Pointer
pad uint32
}<|fim▁end|> |
package sys
|
<|file_name|>conf.py<|end_file_name|><|fim▁begin|><|fim▁hole|># 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.
# -- General configuration ----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
'sphinx.ext.autodoc',
'sphinxcontrib.apidoc',
'openstackdocstheme',
]
# openstackdocstheme options
openstackdocs_repo_name = 'openstack/oslo.privsep'
openstackdocs_bug_project = 'oslo.privsep'
openstackdocs_bug_tag = ''
# The suffix of source filenames.
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
copyright = u'2014, OpenStack Foundation'
# If true, '()' will be appended to :func: etc. cross-reference text.
add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
add_module_names = True
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'native'
# -- Options for HTML output --------------------------------------------------
# The theme to use for HTML and HTML Help pages. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
html_theme = 'openstackdocs'
# -- sphinxcontrib.apidoc configuration --------------------------------------
apidoc_module_dir = '../../oslo_privsep'
apidoc_output_dir = 'reference/api'
apidoc_excluded_paths = [
'tests',
]<|fim▁end|> | # -*- coding: utf-8 -*-
# Copyright (C) 2020 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); |
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>"""schmankerl URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
from schmankerlapp import views
from django.contrib.auth import views as auth_views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.home, name='home'),
<|fim▁hole|> #restaurant
url(r'^restaurant/sign-in/$', auth_views.login,
{'template_name': 'restaurant/sign-in.html'},
name = 'restaurant-sign-in'),
url(r'^restaurant/sign-out', auth_views.logout,
{'next_page': '/'}, name='restaurant-sign-out'),
url(r'^restaurant/sign-up', views.restaurant_sign_up,
name='restaurant-sign-up'),
url(r'^restaurant/$', views.restaurant_home, name='restaurant-home'),
url(r'^restaurant/account/$', views.restaurant_account, name='restaurant-account'),
url(r'^restaurant/meal/$', views.restaurant_meal, name='restaurant-meal'),
url(r'^restaurant/meal/add$', views.restaurant_add_meal, name='restaurant-add-meal'),
url(r'^restaurant/order/$', views.restaurant_order, name='restaurant-order'),
url(r'^restaurant/report/$', views.restaurant_report, name='restaurant-report'),
#sign-up, sign-in, sign-out
url(r'^api/social/', include('rest_framework_social_oauth2.urls')),
# /convert-token (sign-in, sign-out)
# /revoke-token (sign-out)
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)<|fim▁end|> | |
<|file_name|>buildconfiguration.cpp<|end_file_name|><|fim▁begin|>/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include "buildconfiguration.h"
#include "buildenvironmentwidget.h"
#include "buildinfo.h"
#include "buildsteplist.h"
#include "kit.h"
#include "kitinformation.h"
#include "kitmanager.h"
#include "project.h"
#include "projectexplorer.h"
#include "projectexplorerconstants.h"
#include "projectmacroexpander.h"
#include "projecttree.h"
#include "target.h"
#include <coreplugin/idocument.h>
#include <utils/qtcassert.h>
#include <utils/macroexpander.h>
#include <utils/algorithm.h>
#include <utils/mimetypes/mimetype.h>
#include <utils/mimetypes/mimedatabase.h>
#include <QDebug>
static const char BUILD_STEP_LIST_COUNT[] = "ProjectExplorer.BuildConfiguration.BuildStepListCount";
static const char BUILD_STEP_LIST_PREFIX[] = "ProjectExplorer.BuildConfiguration.BuildStepList.";
static const char CLEAR_SYSTEM_ENVIRONMENT_KEY[] = "ProjectExplorer.BuildConfiguration.ClearSystemEnvironment";
static const char USER_ENVIRONMENT_CHANGES_KEY[] = "ProjectExplorer.BuildConfiguration.UserEnvironmentChanges";
static const char BUILDDIRECTORY_KEY[] = "ProjectExplorer.BuildConfiguration.BuildDirectory";
namespace ProjectExplorer {
BuildConfiguration::BuildConfiguration(Target *target, Core::Id id)
: ProjectConfiguration(target, id)
{
Utils::MacroExpander *expander = macroExpander();
expander->setDisplayName(tr("Build Settings"));
expander->setAccumulating(true);
expander->registerSubProvider([target] { return target->macroExpander(); });
expander->registerVariable("buildDir", tr("Build directory"),
[this] { return buildDirectory().toUserOutput(); });
expander->registerVariable(Constants::VAR_CURRENTBUILD_NAME, tr("Name of current build"),
[this] { return displayName(); }, false);
expander->registerPrefix(Constants::VAR_CURRENTBUILD_ENV,
tr("Variables in the current build environment"),
[this](const QString &var) { return environment().value(var); });
updateCacheAndEmitEnvironmentChanged();
connect(target, &Target::kitChanged,
this, &BuildConfiguration::updateCacheAndEmitEnvironmentChanged);
connect(this, &BuildConfiguration::environmentChanged,
this, &BuildConfiguration::emitBuildDirectoryChanged);
// Many macroexpanders are based on the current project, so they may change the environment:
connect(ProjectTree::instance(), &ProjectTree::currentProjectChanged,
this, &BuildConfiguration::updateCacheAndEmitEnvironmentChanged);
}
Utils::FileName BuildConfiguration::buildDirectory() const
{
const QString path = macroExpander()->expand(QDir::cleanPath(environment().expandVariables(m_buildDirectory.toString())));
return Utils::FileName::fromString(QDir::cleanPath(QDir(target()->project()->projectDirectory().toString()).absoluteFilePath(path)));
}
Utils::FileName BuildConfiguration::rawBuildDirectory() const
{
return m_buildDirectory;
}
void BuildConfiguration::setBuildDirectory(const Utils::FileName &dir)
{
if (dir == m_buildDirectory)
return;
m_buildDirectory = dir;
emitBuildDirectoryChanged();
}
void BuildConfiguration::initialize(const BuildInfo *info)
{
setDisplayName(info->displayName);
setDefaultDisplayName(info->displayName);
setBuildDirectory(info->buildDirectory);
m_stepLists.append(new BuildStepList(this, Constants::BUILDSTEPS_BUILD));
m_stepLists.append(new BuildStepList(this, Constants::BUILDSTEPS_CLEAN));
}
QList<NamedWidget *> BuildConfiguration::createSubConfigWidgets()
{
return QList<NamedWidget *>() << new BuildEnvironmentWidget(this);
}
QList<Core::Id> BuildConfiguration::knownStepLists() const
{
return Utils::transform(m_stepLists, &BuildStepList::id);
}
BuildStepList *BuildConfiguration::stepList(Core::Id id) const
{
return Utils::findOrDefault(m_stepLists, Utils::equal(&BuildStepList::id, id));
}
QVariantMap BuildConfiguration::toMap() const
{
QVariantMap map(ProjectConfiguration::toMap());
map.insert(QLatin1String(CLEAR_SYSTEM_ENVIRONMENT_KEY), m_clearSystemEnvironment);
map.insert(QLatin1String(USER_ENVIRONMENT_CHANGES_KEY), Utils::EnvironmentItem::toStringList(m_userEnvironmentChanges));
map.insert(QLatin1String(BUILDDIRECTORY_KEY), m_buildDirectory.toString());
map.insert(QLatin1String(BUILD_STEP_LIST_COUNT), m_stepLists.count());
for (int i = 0; i < m_stepLists.count(); ++i)
map.insert(QLatin1String(BUILD_STEP_LIST_PREFIX) + QString::number(i), m_stepLists.at(i)->toMap());
return map;
}
bool BuildConfiguration::fromMap(const QVariantMap &map)
{
m_clearSystemEnvironment = map.value(QLatin1String(CLEAR_SYSTEM_ENVIRONMENT_KEY)).toBool();
m_userEnvironmentChanges = Utils::EnvironmentItem::fromStringList(map.value(QLatin1String(USER_ENVIRONMENT_CHANGES_KEY)).toStringList());
m_buildDirectory = Utils::FileName::fromString(map.value(QLatin1String(BUILDDIRECTORY_KEY)).toString());
updateCacheAndEmitEnvironmentChanged();
qDeleteAll(m_stepLists);
m_stepLists.clear();
int maxI = map.value(QLatin1String(BUILD_STEP_LIST_COUNT), 0).toInt();
for (int i = 0; i < maxI; ++i) {
QVariantMap data = map.value(QLatin1String(BUILD_STEP_LIST_PREFIX) + QString::number(i)).toMap();
if (data.isEmpty()) {
qWarning() << "No data for build step list" << i << "found!";
continue;
}
auto list = new BuildStepList(this, idFromMap(data));
if (!list->fromMap(data)) {
qWarning() << "Failed to restore build step list" << i;
delete list;
return false;
}
m_stepLists.append(list);
}
// We currently assume there to be at least a clean and build list!
QTC_CHECK(knownStepLists().contains(Core::Id(Constants::BUILDSTEPS_BUILD)));
QTC_CHECK(knownStepLists().contains(Core::Id(Constants::BUILDSTEPS_CLEAN)));
return ProjectConfiguration::fromMap(map);
}
void BuildConfiguration::updateCacheAndEmitEnvironmentChanged()
{
Utils::Environment env = baseEnvironment();
env.modify(userEnvironmentChanges());
if (env == m_cachedEnvironment)
return;
m_cachedEnvironment = env;
emit environmentChanged(); // might trigger buildDirectoryChanged signal!
}
void BuildConfiguration::emitBuildDirectoryChanged()
{
if (buildDirectory() != m_lastEmmitedBuildDirectory) {
m_lastEmmitedBuildDirectory = buildDirectory();
emit buildDirectoryChanged();
}
}
Target *BuildConfiguration::target() const
{
return static_cast<Target *>(parent());
}
Project *BuildConfiguration::project() const
{
return target()->project();
}
Utils::Environment BuildConfiguration::baseEnvironment() const
{
Utils::Environment result;
if (useSystemEnvironment())
result = Utils::Environment::systemEnvironment();
addToEnvironment(result);
target()->kit()->addToEnvironment(result);
return result;
}
QString BuildConfiguration::baseEnvironmentText() const
{
if (useSystemEnvironment())
return tr("System Environment");
else
return tr("Clean Environment");
}
Utils::Environment BuildConfiguration::environment() const
{
return m_cachedEnvironment;
}
void BuildConfiguration::setUseSystemEnvironment(bool b)
{
if (useSystemEnvironment() == b)
return;
m_clearSystemEnvironment = !b;
updateCacheAndEmitEnvironmentChanged();
}
void BuildConfiguration::addToEnvironment(Utils::Environment &env) const
{
Q_UNUSED(env);
}
bool BuildConfiguration::useSystemEnvironment() const
{
return !m_clearSystemEnvironment;
}
QList<Utils::EnvironmentItem> BuildConfiguration::userEnvironmentChanges() const
{
return m_userEnvironmentChanges;
}
void BuildConfiguration::setUserEnvironmentChanges(const QList<Utils::EnvironmentItem> &diff)
{
if (m_userEnvironmentChanges == diff)
return;
m_userEnvironmentChanges = diff;
updateCacheAndEmitEnvironmentChanged();
}
bool BuildConfiguration::isEnabled() const
{
return true;
}
QString BuildConfiguration::disabledReason() const
{
return QString();
}
bool BuildConfiguration::regenerateBuildFiles(Node *node)
{
Q_UNUSED(node);
return false;
}
QString BuildConfiguration::buildTypeName(BuildConfiguration::BuildType type)
{
switch (type) {
case ProjectExplorer::BuildConfiguration::Debug:
return QLatin1String("debug");
case ProjectExplorer::BuildConfiguration::Profile:
return QLatin1String("profile");
case ProjectExplorer::BuildConfiguration::Release:
return QLatin1String("release");
case ProjectExplorer::BuildConfiguration::Unknown: // fallthrough
default:
return QLatin1String("unknown");
}
}
bool BuildConfiguration::isActive() const
{
return target()->isActive() && target()->activeBuildConfiguration() == this;
}
/*!
* Helper function that prepends the directory containing the C++ toolchain to
* PATH. This is used to in build configurations targeting broken build systems
* to provide hints about which compiler to use.
*/
void BuildConfiguration::prependCompilerPathToEnvironment(Utils::Environment &env) const
{
return prependCompilerPathToEnvironment(target()->kit(), env);
}
void BuildConfiguration::prependCompilerPathToEnvironment(Kit *k, Utils::Environment &env)
{
const ToolChain *tc
= ToolChainKitInformation::toolChain(k, ProjectExplorer::Constants::CXX_LANGUAGE_ID);
if (!tc)
return;
const Utils::FileName compilerDir = tc->compilerCommand().parentDir();
if (!compilerDir.isEmpty())
env.prependOrSetPath(compilerDir.toString());
}
///
// IBuildConfigurationFactory
///
static QList<IBuildConfigurationFactory *> g_buildConfigurationFactories;
IBuildConfigurationFactory::IBuildConfigurationFactory()
{
g_buildConfigurationFactories.append(this);
}
IBuildConfigurationFactory::~IBuildConfigurationFactory()
{
g_buildConfigurationFactories.removeOne(this);
}
int IBuildConfigurationFactory::priority(const Target *parent) const
{
return canHandle(parent) ? m_basePriority : -1;
}
bool IBuildConfigurationFactory::supportsTargetDeviceType(Core::Id id) const
{
if (m_supportedTargetDeviceTypes.isEmpty())
return true;
return m_supportedTargetDeviceTypes.contains(id);
}
int IBuildConfigurationFactory::priority(const Kit *k, const QString &projectPath) const
{
QTC_ASSERT(!m_supportedProjectMimeTypeName.isEmpty(), return -1);
if (k && Utils::mimeTypeForFile(projectPath).matchesName(m_supportedProjectMimeTypeName)
&& supportsTargetDeviceType(DeviceTypeKitInformation::deviceTypeId(k))) {
return m_basePriority;
}
return -1;
}
// setup
IBuildConfigurationFactory *IBuildConfigurationFactory::find(const Kit *k, const QString &projectPath)
{
IBuildConfigurationFactory *factory = nullptr;
int priority = -1;
for (IBuildConfigurationFactory *i : g_buildConfigurationFactories) {
int iPriority = i->priority(k, projectPath);
if (iPriority > priority) {
factory = i;
priority = iPriority;
}
}
return factory;
}
// create
IBuildConfigurationFactory * IBuildConfigurationFactory::find(Target *parent)
{
IBuildConfigurationFactory *factory = nullptr;
int priority = -1;
for (IBuildConfigurationFactory *i : g_buildConfigurationFactories) {
int iPriority = i->priority(parent);
if (iPriority > priority) {
factory = i;
priority = iPriority;
}
}
return factory;
}
void IBuildConfigurationFactory::setSupportedProjectType(Core::Id id)
{
m_supportedProjectType = id;
}
void IBuildConfigurationFactory::setSupportedProjectMimeTypeName(const QString &mimeTypeName)
{
m_supportedProjectMimeTypeName = mimeTypeName;
}
void IBuildConfigurationFactory::setSupportedTargetDeviceTypes(const QList<Core::Id> &ids)
{
m_supportedTargetDeviceTypes = ids;
}
void IBuildConfigurationFactory::setBasePriority(int basePriority)
{
m_basePriority = basePriority;
}
bool IBuildConfigurationFactory::canHandle(const Target *target) const
{
if (m_supportedProjectType.isValid() && m_supportedProjectType != target->project()->id())
return false;
if (containsType(target->project()->projectIssues(target->kit()), Task::TaskType::Error))
return false;
if (!supportsTargetDeviceType(DeviceTypeKitInformation::deviceTypeId(target->kit())))
return false;
return true;
}
BuildConfiguration *IBuildConfigurationFactory::create(Target *parent, const BuildInfo *info) const
{
if (!canHandle(parent))
return nullptr;
QTC_ASSERT(m_creator, return nullptr);
BuildConfiguration *bc = m_creator(parent);
if (!bc)
return nullptr;
bc->initialize(info);
return bc;
}
BuildConfiguration *IBuildConfigurationFactory::restore(Target *parent, const QVariantMap &map)
{
IBuildConfigurationFactory *factory = nullptr;
int priority = -1;
for (IBuildConfigurationFactory *i : g_buildConfigurationFactories) {
if (!i->canHandle(parent))
continue;
const Core::Id id = idFromMap(map);
if (!id.name().startsWith(i->m_buildConfigId.name()))
continue;
int iPriority = i->priority(parent);<|fim▁hole|> factory = i;
priority = iPriority;
}
}
if (!factory)
return nullptr;
QTC_ASSERT(factory->m_creator, return nullptr);
BuildConfiguration *bc = factory->m_creator(parent);
QTC_ASSERT(bc, return nullptr);
if (!bc->fromMap(map)) {
delete bc;
bc = nullptr;
}
return bc;
}
BuildConfiguration *IBuildConfigurationFactory::clone(Target *parent,
const BuildConfiguration *source)
{
return restore(parent, source->toMap());
}
} // namespace ProjectExplorer<|fim▁end|> | if (iPriority > priority) { |
<|file_name|>test_bit_manipulators.py<|end_file_name|><|fim▁begin|>from infection_monkey.utils import bit_manipulators
def test_flip_bits_in_single_byte():
for i in range(0, 256):
assert bit_manipulators.flip_bits_in_single_byte(i) == (255 - i)
def test_flip_bits():
test_input = bytes(b"ABCDEFGHIJNLMNOPQRSTUVWXYZabcdefghijnlmnopqrstuvwxyz1234567890!@#$%^&*()")
expected_output = (
b"\xbe\xbd\xbc\xbb\xba\xb9\xb8\xb7\xb6\xb5\xb1\xb3\xb2\xb1\xb0\xaf\xae\xad"
b"\xac\xab\xaa\xa9\xa8\xa7\xa6\xa5\x9e\x9d\x9c\x9b\x9a\x99\x98\x97\x96\x95"
b"\x91\x93\x92\x91\x90\x8f\x8e\x8d\x8c\x8b\x8a\x89\x88\x87\x86\x85\xce\xcd"
b"\xcc\xcb\xca\xc9\xc8\xc7\xc6\xcf\xde\xbf\xdc\xdb\xda\xa1\xd9\xd5\xd7\xd6"<|fim▁hole|>
def test_flip_bits__reversible():
test_input = bytes(
b"ABCDEFGHIJNLM\xffNOPQRSTUVWXYZabcde\xf5fghijnlmnopqr\xC3stuvwxyz1\x87234567890!@#$%^&*()"
)
test_output = bit_manipulators.flip_bits(test_input)
test_output = bit_manipulators.flip_bits(test_output)
assert test_input == test_output<|fim▁end|> | )
assert bit_manipulators.flip_bits(test_input) == expected_output
|
<|file_name|>gcimporter_test.go<|end_file_name|><|fim▁begin|>// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gcimporter
import (
"go/build"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
"go/types"
)
// skipSpecialPlatforms causes the test to be skipped for platforms where
// builders (build.golang.org) don't have access to compiled packages for
// import.
func skipSpecialPlatforms(t *testing.T) {
switch platform := runtime.GOOS + "-" + runtime.GOARCH; platform {
case "nacl-amd64p32",
"nacl-386",
"darwin-arm",
"darwin-arm64":
t.Skipf("no compiled packages available for import on %s", platform)
}
}
var gcPath string // Go compiler path
func init() {
if char, err := build.ArchChar(runtime.GOARCH); err == nil {
gcPath = filepath.Join(build.ToolDir, char+"g")
return
}
gcPath = "unknown-GOARCH-compiler"
}
func compile(t *testing.T, dirname, filename string) string {
cmd := exec.Command(gcPath, filename)
cmd.Dir = dirname
out, err := cmd.CombinedOutput()
if err != nil {
t.Logf("%s", out)
t.Fatalf("%s %s failed: %s", gcPath, filename, err)
}
archCh, _ := build.ArchChar(runtime.GOARCH)
// filename should end with ".go"
return filepath.Join(dirname, filename[:len(filename)-2]+archCh)
}
// Use the same global imports map for all tests. The effect is
// as if all tested packages were imported into a single package.
var imports = make(map[string]*types.Package)
func testPath(t *testing.T, path string) bool {
t0 := time.Now()
_, err := Import(imports, path)
if err != nil {
t.Errorf("testPath(%s): %s", path, err)
return false
}
t.Logf("testPath(%s): %v", path, time.Since(t0))
return true
}
const maxTime = 30 * time.Second
func testDir(t *testing.T, dir string, endTime time.Time) (nimports int) {
dirname := filepath.Join(runtime.GOROOT(), "pkg", runtime.GOOS+"_"+runtime.GOARCH, dir)
list, err := ioutil.ReadDir(dirname)
if err != nil {
t.Fatalf("testDir(%s): %s", dirname, err)
}
for _, f := range list {
if time.Now().After(endTime) {
t.Log("testing time used up")
return
}
switch {
case !f.IsDir():
// try extensions
for _, ext := range pkgExts {
if strings.HasSuffix(f.Name(), ext) {
name := f.Name()[0 : len(f.Name())-len(ext)] // remove extension
if testPath(t, filepath.Join(dir, name)) {
nimports++
}
}
}
case f.IsDir():
nimports += testDir(t, filepath.Join(dir, f.Name()), endTime)
}
}
return
}
func TestImport(t *testing.T) {
// This package only handles gc export data.
if runtime.Compiler != "gc" {
t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler)
return
}
// On cross-compile builds, the path will not exist.
// Need to use GOHOSTOS, which is not available.
if _, err := os.Stat(gcPath); err != nil {
t.Skipf("skipping test: %v", err)
}
if outFn := compile(t, "testdata", "exports.go"); outFn != "" {
defer os.Remove(outFn)
}
nimports := 0
if testPath(t, "./testdata/exports") {
nimports++
}
nimports += testDir(t, "", time.Now().Add(maxTime)) // installed packages
t.Logf("tested %d imports", nimports)
}
var importedObjectTests = []struct {
name string
want string
}{
{"unsafe.Pointer", "type Pointer unsafe.Pointer"},
{"math.Pi", "const Pi untyped float"},
{"io.Reader", "type Reader interface{Read(p []byte) (n int, err error)}"},
{"io.ReadWriter", "type ReadWriter interface{Read(p []byte) (n int, err error); Write(p []byte) (n int, err error)}"},
{"math.Sin", "func Sin(x float64) float64"},
// TODO(gri) add more tests
}
func TestImportedTypes(t *testing.T) {
skipSpecialPlatforms(t)
// This package only handles gc export data.
if runtime.Compiler != "gc" {
t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler)
return
}
for _, test := range importedObjectTests {
s := strings.Split(test.name, ".")
if len(s) != 2 {
t.Fatal("inconsistent test data")
}
importPath := s[0]
objName := s[1]
pkg, err := Import(imports, importPath)
if err != nil {
t.Error(err)
continue
}
obj := pkg.Scope().Lookup(objName)
if obj == nil {
t.Errorf("%s: object not found", test.name)
continue
}
<|fim▁hole|> }
}
func TestIssue5815(t *testing.T) {
skipSpecialPlatforms(t)
// This package only handles gc export data.
if runtime.Compiler != "gc" {
t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler)
return
}
pkg, err := Import(make(map[string]*types.Package), "strings")
if err != nil {
t.Fatal(err)
}
scope := pkg.Scope()
for _, name := range scope.Names() {
obj := scope.Lookup(name)
if obj.Pkg() == nil {
t.Errorf("no pkg for %s", obj)
}
if tname, _ := obj.(*types.TypeName); tname != nil {
named := tname.Type().(*types.Named)
for i := 0; i < named.NumMethods(); i++ {
m := named.Method(i)
if m.Pkg() == nil {
t.Errorf("no pkg for %s", m)
}
}
}
}
}
// Smoke test to ensure that imported methods get the correct package.
func TestCorrectMethodPackage(t *testing.T) {
skipSpecialPlatforms(t)
// This package only handles gc export data.
if runtime.Compiler != "gc" {
t.Skipf("gc-built packages not available (compiler = %s)", runtime.Compiler)
return
}
imports := make(map[string]*types.Package)
_, err := Import(imports, "net/http")
if err != nil {
t.Fatal(err)
}
mutex := imports["sync"].Scope().Lookup("Mutex").(*types.TypeName).Type()
mset := types.NewMethodSet(types.NewPointer(mutex)) // methods of *sync.Mutex
sel := mset.Lookup(nil, "Lock")
lock := sel.Obj().(*types.Func)
if got, want := lock.Pkg().Path(), "sync"; got != want {
t.Errorf("got package path %q; want %q", got, want)
}
}<|fim▁end|> | got := types.ObjectString(pkg, obj)
if got != test.want {
t.Errorf("%s: got %q; want %q", test.name, got, test.want)
} |
<|file_name|>places_sidebar.rs<|end_file_name|><|fim▁begin|>// Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! GtkPlacesSidebar — Sidebar that displays frequently-used places in the file system
use ffi;
use FFIWidget;
use cast::GTK_PLACES_SIDEBAR;
use glib::{to_bool, to_gboolean};
struct_Widget!(PlacesSidebar);
impl PlacesSidebar {
pub fn new() -> Option<PlacesSidebar> {
let tmp_pointer = unsafe { ffi::gtk_places_sidebar_new() };
check_pointer!(tmp_pointer, PlacesSidebar)
}
pub fn set_open_flags(&self, flags: ::PlacesOpenFlags) {
unsafe { ffi::gtk_places_sidebar_set_open_flags(GTK_PLACES_SIDEBAR(self.unwrap_widget()), flags) }
}
pub fn get_open_flags(&self) -> ::PlacesOpenFlags {
unsafe { ffi::gtk_places_sidebar_get_open_flags(GTK_PLACES_SIDEBAR(self.unwrap_widget())) }
}
pub fn set_show_desktop(&self, show_desktop: bool) {
unsafe { ffi::gtk_places_sidebar_set_show_desktop(GTK_PLACES_SIDEBAR(self.unwrap_widget()), to_gboolean(show_desktop)) }
}
pub fn get_show_desktop(&self) -> bool {
unsafe { to_bool(ffi::gtk_places_sidebar_get_show_desktop(GTK_PLACES_SIDEBAR(self.unwrap_widget()))) }
}
pub fn set_show_connect_to_server(&self, show_connect_to_server: bool) {
unsafe { ffi::gtk_places_sidebar_set_show_connect_to_server(GTK_PLACES_SIDEBAR(self.unwrap_widget()),
to_gboolean(show_connect_to_server)) }
}
pub fn get_show_connect_to_server(&self) -> bool {
unsafe { to_bool(ffi::gtk_places_sidebar_get_show_connect_to_server(GTK_PLACES_SIDEBAR(self.unwrap_widget()))) }
}
#[cfg(gtk_3_12)]<|fim▁hole|>
#[cfg(gtk_3_12)]
pub fn get_local_only(&self) -> bool {
unsafe { to_bool(ffi::gtk_places_sidebar_get_local_only(GTK_PLACES_SIDEBAR(self.unwrap_widget()))) }
}
#[cfg(gtk_3_14)]
pub fn set_show_enter_location(&self, show_enter_location: bool) {
unsafe { ffi::gtk_places_sidebar_set_show_enter_location(GTK_PLACES_SIDEBAR(self.unwrap_widget()),
to_gboolean(show_enter_location)) }
}
#[cfg(gtk_3_14)]
pub fn get_show_enter_location(&self) -> bool {
unsafe { to_bool(ffi::gtk_places_sidebar_get_show_enter_location(GTK_PLACES_SIDEBAR(self.unwrap_widget()))) }
}
}
impl_drop!(PlacesSidebar);
impl_TraitWidget!(PlacesSidebar);
impl ::ContainerTrait for PlacesSidebar {}
impl ::BinTrait for PlacesSidebar {}
impl ::ScrolledWindowTrait for PlacesSidebar {}<|fim▁end|> | pub fn set_local_only(&self, local_only: bool) {
unsafe { ffi::gtk_places_sidebar_set_local_only(GTK_PLACES_SIDEBAR(self.unwrap_widget()), to_gboolean(local_only)) }
} |
<|file_name|>c_tga_header.cpp<|end_file_name|><|fim▁begin|>#include "c_tga_header.h"
#include <cstring>
namespace Img {
bool TGAHeader::LoadHeader(IO::FileReader::Ptr file) {
if (file->Size() - file->Position() < 19) {
return false;
}
file->ReadFull(&IdSize, 1);
file->ReadFull(&ColorMapType, 1);
file->ReadFull(&ImageType, 1);
file->ReadFull(&ColorMapStart, 2);
file->ReadFull(&ColorMapLength, 2);
file->ReadFull(&ColorMapBits, 1);
// Skip X/Y start coordinates
file->Seek(4, IO::SeekMethod::Current);
file->ReadFull(&Size.Width, 2);
file->ReadFull(&Size.Height, 2);
file->ReadFull(&ColorDepth, 1);
// 00vhaaaa (vertical flip, horizontal flip, alpha bits)
uint8_t desc;<|fim▁hole|>
// Parse the desc-byte
AlphaBits = desc & 0x0f;
FlipHorizontal = ((desc & 0x10) != 0);
FlipVertical = ((desc & 0x20) == 0);
if (AlphaBits) {
AttributesType = AT_Alpha;
}
FileInt headerEnd = file->Position();
file->Seek(file->Size() - 26, IO::SeekMethod::Begin);
char footer[26];
file->ReadFull(footer, 26);
if (memcmp(footer + 8, "TRUEVISION-XFILE", 16) == 0) {
AttributesType = AT_UndefinedIgnore;
// New TGA format. See if there's an extension area
file->Seek(file->Size() - 26, IO::SeekMethod::Begin);
uint32_t offset = 0;
file->ReadFull(&offset, 4);
if (offset != 0) {
file->Seek(offset, IO::SeekMethod::Begin);
if (!ReadExtensionArea(file)) {
return false;
}
}
}
file->Seek(headerEnd, IO::SeekMethod::Begin);
return true;
}
bool TGAHeader::ReadExtensionArea( IO::FileReader::Ptr file ) {
uint16_t size;
file->ReadFull(&size, 2);
if (size < 495) return false;
// Skip tons of worthless crap
file->Seek(492, IO::SeekMethod::Current);
AttributesType = AT_NoAlpha;
file->ReadFull(&AttributesType, 1);
// HACK: Some software writes NoAlpha even though alpha-bits are present
if (AttributesType == AT_NoAlpha && AlphaBits) {
AttributesType = AT_Alpha;
}
return true;
}
Img::Format TGAHeader::SurfaceFormat() {
if (ColorDepth == 8) {
return Img::Format::Index8;
}
if (ColorDepth == 16) {
if (AttributesType == AT_Alpha) {
return Img::Format::ARGB1555;
}
else {
return Img::Format::XRGB1555;
}
}
if (ColorDepth == 24) {
return Img::Format::XRGB8888;
}
if (ColorDepth == 32) {
if (AttributesType == AT_Alpha) {
return Img::Format::ARGB8888;
}
else {
return Img::Format::XRGB8888;
}
}
return Img::Format::Undefined;
}
}<|fim▁end|> | file->ReadFull(&desc, 1); |
<|file_name|>rulerctrl.py<|end_file_name|><|fim▁begin|># --------------------------------------------------------------------------------- #
# RULERCTRL wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 03 Nov 2006
# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List
#
# 1. Any idea?
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
# Write To Me At:
#
# [email protected]
# [email protected]
#
# Or, Obviously, To The wxPython Mailing List!!!
#
#
# End Of Comments
# --------------------------------------------------------------------------------- #
"""
:class:`RulerCtrl` implements a ruler window that can be placed on top, bottom, left or right
to any wxPython widget.
Description
===========
:class:`RulerCtrl` implements a ruler window that can be placed on top, bottom, left or right
to any wxPython widget. It is somewhat similar to the rulers you can find in text
editors software, though not so powerful.
:class:`RulerCtrl` has the following characteristics:
- Can be horizontal or vertical;
- 4 built-in formats: integer, real, time and linearDB formats;
- Units (as ``cm``, ``dB``, ``inches``) can be displayed together with the label values;
- Possibility to add a number of "paragraph indicators", small arrows that point at
the current indicator position;
- Customizable background colour, tick colour, label colour;
- Possibility to flip the ruler (i.e. changing the tick alignment);
- Changing individually the indicator colour (requires PIL at the moment);
- Different window borders are supported (``wx.STATIC_BORDER``, ``wx.SUNKEN_BORDER``,
``wx.DOUBLE_BORDER``, ``wx.NO_BORDER``, ``wx.RAISED_BORDER``, ``wx.SIMPLE_BORDER``);
- Logarithmic scale available;
- Possibility to draw a thin line over a selected window when moving an indicator,
which emulates the text editors software.
And a lot more. See the demo for a review of the functionalities.
Usage
=====
Usage example::
import wx
import wx.lib.agw.rulerctrl as RC
class MyFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, -1, "RulerCtrl Demo")
panel = wx.Panel(self)
text = wx.TextCtrl(panel, -1, "Hello World! wxPython rules", style=wx.TE_MULTILINE)
ruler1 = RC.RulerCtrl(panel, -1, orient=wx.HORIZONTAL, style=wx.SUNKEN_BORDER)
ruler2 = RC.RulerCtrl(panel, -1, orient=wx.VERTICAL, style=wx.SUNKEN_BORDER)
mainsizer = wx.BoxSizer(wx.HORIZONTAL)
leftsizer = wx.BoxSizer(wx.VERTICAL)
bottomleftsizer = wx.BoxSizer(wx.HORIZONTAL)
topsizer = wx.BoxSizer(wx.HORIZONTAL)
leftsizer.Add((20, 20), 0, wx.ADJUST_MINSIZE, 0)
topsizer.Add((39, 0), 0, wx.ADJUST_MINSIZE, 0)
topsizer.Add(ruler1, 1, wx.EXPAND, 0)
leftsizer.Add(topsizer, 0, wx.EXPAND, 0)
bottomleftsizer.Add((10, 0))
bottomleftsizer.Add(ruler2, 0, wx.EXPAND, 0)
bottomleftsizer.Add(text, 1, wx.EXPAND, 0)
leftsizer.Add(bottomleftsizer, 1, wx.EXPAND, 0)
mainsizer.Add(leftsizer, 3, wx.EXPAND, 0)
panel.SetSizer(mainsizer)
# our normal wxApp-derived class, as usual
app = wx.App(0)
frame = MyFrame(None)
app.SetTopWindow(frame)
frame.Show()
app.MainLoop()
Events
======
:class:`RulerCtrl` implements the following events related to indicators:
- ``EVT_INDICATOR_CHANGING``: the user is about to change the position of one indicator;
- ``EVT_INDICATOR_CHANGED``: the user has changed the position of one indicator.
Supported Platforms
===================
:class:`RulerCtrl` has been tested on the following platforms:
* Windows (Windows XP);
* Linux Ubuntu (Dapper 6.06)
Window Styles
=============
`No particular window styles are available for this class.`
Events Processing
=================
This class processes the following events:
========================== ==================================================
Event Name Description
========================== ==================================================
``EVT_INDICATOR_CHANGED`` The user has changed the indicator value.
``EVT_INDICATOR_CHANGING`` The user is about to change the indicator value.
========================== ==================================================
License And Version
===================
:class:`RulerCtrl` is distributed under the wxPython license.
Latest Revision: Andrea Gavana @ 17 Aug 2011, 15.00 GMT
Version 0.3
"""
__docformat__ = "epytext"
import wx
import math
import cStringIO, zlib
# Try to import PIL, if possible.
# This is used only to change the colour for an indicator arrow.
_hasPIL = False
try:
import Image
_hasPIL = True
except:
pass
# Built-in formats
IntFormat = 1
""" Integer format. """
RealFormat = 2
""" Real format. """
TimeFormat = 3
""" Time format. """
LinearDBFormat = 4
""" Linear DB format. """
HHMMSS_Format = 5
""" HHMMSS format. """
# Events
wxEVT_INDICATOR_CHANGING = wx.NewEventType()
wxEVT_INDICATOR_CHANGED = wx.NewEventType()
EVT_INDICATOR_CHANGING = wx.PyEventBinder(wxEVT_INDICATOR_CHANGING, 2)
""" The user is about to change the indicator value. """
EVT_INDICATOR_CHANGED = wx.PyEventBinder(wxEVT_INDICATOR_CHANGED, 2)
""" The user has changed the indicator value. """
# Some accessor functions
#----------------------------------------------------------------------
def GetIndicatorData():
""" Returns the image indicator as a decompressed stream of characters. """
return zlib.decompress(
'x\xda\x01x\x01\x87\xfe\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\n\x00\
\x00\x00\n\x08\x06\x00\x00\x00\x8d2\xcf\xbd\x00\x00\x00\x04sBIT\x08\x08\x08\
\x08|\x08d\x88\x00\x00\x01/IDAT\x18\x95m\xceO(\x83q\x1c\xc7\xf1\xf7\xef\xf9\
\xcd\xf6D6\xca\x1c\xc8\x9f\x14\'J-\xc4A9(9(-\xe5 \xed\xe4\xe2\xe2\xb2\x928\
\xb9\xec\xc2\x01\x17.\x0e\xe4\xe6B\xed\xb2\x1c\xdc$5\x97\xf9S\xb3\x14+\x0eO\
\xdb\xccZ\x9e\xfd\xf9\xba\x98E{\x1d\xbf\xbd\xfb\xf4U\x00\x18\x9d\xc3\xad\x1d\
\xa1+\xa7S\x15\xf8\xa1\xb5i\xbc\xc4\xd7\x0f\xca\xc5\xd82U3[\x97\xb1\x82\xc4S\
"\x89\xb4\xc8SZ\xc4\xb2E\xfa\x06CR)\x1c\x00\xb8\x8cb"-|\x94@\x01\x0e\r\xee&\
\xf8\x12\xc5\xdf\xd0\xd4\xf2\xf6i\x90/\x82\xe9\x82\xdb\xe72\xa7\xe7%\x92\x99\
\xdfA\xb4j\x9b]\xa5\xaek\xbag|\xaa\xdd\xca)\xceb\x10\xbe\x87\xacm VT\xd0N\
\x0f\xf9\xd7\x94\xd6\xde\xb1\xdd\xf9\xcdm_\x83\xdb\x81\x95W\x88\x02\xad\x159\
\x01\xcc!U2}\xa3$\x0f\x1dZR\xd1\xfd\xbb\x9b\xc7\x89\xc99\x7f\xb7\xb7\xd1\x00\
\xc0.B\xbe\xac\xc8\xbe?P\x8e\x8c\x1ccg\x02\xd5\x1f\x9a\x07\xf6\x82a[6.D\xfc\
\'"\x9e\xc0\xb5\xa0\xeb\xd7\xa8\xc9\xdd\xbf\xb3pdI\xefRD\xc0\x08\xd6\x8e*\\-\
+\xa0\x17\xff\x9f\xbf\x01{\xb5t\x9e\x99]a\x97\x00\x00\x00\x00IEND\xaeB`\x82G\
\xbf\xa8>' )
def GetIndicatorBitmap():
""" Returns the image indicator as a :class:`Bitmap`. """
return wx.BitmapFromImage(GetIndicatorImage())
def GetIndicatorImage():
""" Returns the image indicator as a :class:`Image`. """
stream = cStringIO.StringIO(GetIndicatorData())
return wx.ImageFromStream(stream)
def MakePalette(tr, tg, tb):
"""
Creates a palette to be applied on an image based on input colour.
:param `tr`: the red intensity of the input colour;
:param `tg`: the green intensity of the input colour;
:param `tb`: the blue intensity of the input colour.
"""
l = []
for i in range(255):
l.extend([tr*i / 255, tg*i / 255, tb*i / 255])
return l
def ConvertWXToPIL(bmp):
"""
Converts a :class:`Image` into a PIL image.
:param `bmp`: an instance of :class:`Image`.
:note: Requires PIL (Python Imaging Library), which can be downloaded from
http://www.pythonware.com/products/pil/
"""
width = bmp.GetWidth()
height = bmp.GetHeight()
img = Image.fromstring("RGBA", (width, height), bmp.GetData())
return img
def ConvertPILToWX(pil, alpha=True):
"""
Converts a PIL image into a :class:`Image`.
:param `pil`: a PIL image;
:param `alpha`: ``True`` if the image contains alpha transparency, ``False``
otherwise.
:note: Requires PIL (Python Imaging Library), which can be downloaded from
http://www.pythonware.com/products/pil/
"""
if alpha:
image = apply(wx.EmptyImage, pil.size)
image.SetData(pil.convert("RGB").tostring())
image.SetAlphaData(pil.convert("RGBA").tostring()[3::4])
else:
image = wx.EmptyImage(pil.size[0], pil.size[1])
new_image = pil.convert('RGB')
data = new_image.tostring()
image.SetData(data)
return image
# ---------------------------------------------------------------------------- #
# Class RulerCtrlEvent
# ---------------------------------------------------------------------------- #
class RulerCtrlEvent(wx.PyCommandEvent):
"""
Represent details of the events that the :class:`RulerCtrl` object sends.
"""
def __init__(self, eventType, eventId=1):
"""
Default class constructor.
:param `eventType`: the event type;
:param `eventId`: the event identifier.
"""
wx.PyCommandEvent.__init__(self, eventType, eventId)
def SetValue(self, value):
"""
Sets the event value.
:param `value`: the new indicator position.
"""
self._value = value
def GetValue(self):
""" Returns the event value. """
return self._value
def SetOldValue(self, oldValue):
"""
Sets the event old value.
:param `value`: the old indicator position.
"""
self._oldValue = oldValue
def GetOldValue(self):
""" Returns the event old value. """
return self._oldValue
# ---------------------------------------------------------------------------- #
# Class Label
# ---------------------------------------------------------------------------- #
class Label(object):
"""
Auxilary class. Just holds information about a label in :class:`RulerCtrl`.
"""
def __init__(self, pos=-1, lx=-1, ly=-1, text=""):
"""
Default class constructor.
:param `pos`: the indicator position;
:param `lx`: the indicator `x` coordinate;
:param `ly`: the indicator `y` coordinate;
:param `text`: the label text.
"""
self.pos = pos
self.lx = lx
self.ly = ly
self.text = text
# ---------------------------------------------------------------------------- #
# Class Indicator
# ---------------------------------------------------------------------------- #
class Indicator(object):
"""
This class holds all the information about a single indicator inside :class:`RulerCtrl`.
You should not call this class directly. Use::
ruler.AddIndicator(id, value)
to add an indicator to your :class:`RulerCtrl`.
"""
def __init__(self, parent, id=wx.ID_ANY, value=0):
"""
Default class constructor.
:param `parent`: the parent window, an instance of :class:`RulerCtrl`;
:param `id`: the indicator identifier;
:param `value`: the initial value of the indicator.
"""
self._parent = parent
if id == wx.ID_ANY:
id = wx.NewId()
self._id = id
self._colour = None
self.RotateImage(GetIndicatorImage())
self.SetValue(value)
def GetPosition(self):
""" Returns the position at which we should draw the indicator bitmap. """
orient = self._parent._orientation
flip = self._parent._flip
left, top, right, bottom = self._parent.GetBounds()
minval = self._parent._min
maxval = self._parent._max
value = self._value
if self._parent._log:
value = math.log10(value)
maxval = math.log10(maxval)
minval = math.log10(minval)
pos = float(value-minval)/abs(maxval - minval)
if orient == wx.HORIZONTAL:
xpos = int(pos*right) - self._img.GetWidth()/2
if flip:
ypos = top
else:
ypos = bottom - self._img.GetHeight()
else:
ypos = int(pos*bottom) - self._img.GetHeight()/2
if flip:
xpos = left
else:
xpos = right - self._img.GetWidth()
return xpos, ypos
def GetImageSize(self):
""" Returns the indicator bitmap size. """
return self._img.GetWidth(), self._img.GetHeight()
def GetRect(self):
""" Returns the indicator client rectangle. """
return self._rect
def RotateImage(self, img=None):
"""
Rotates the default indicator bitmap.
:param `img`: if not ``None``, the indicator image.
"""
if img is None:
img = GetIndicatorImage()
orient = self._parent._orientation
flip = self._parent._flip
left, top, right, bottom = self._parent.GetBounds()
if orient == wx.HORIZONTAL:
if flip:
img = img.Rotate(math.pi, (5, 5), True)
else:
if flip:
img = img.Rotate(-math.pi/2, (5, 5), True)
else:
img = img.Rotate(math.pi/2, (5, 5), True)
self._img = img
def SetValue(self, value):
"""
Sets the indicator value.
:param `value`: the new indicator value.
"""
if value < self._parent._min:
value = self._parent._min
if value > self._parent._max:
value = self._parent._max
self._value = value
self._rect = wx.Rect()
self._parent.Refresh()
def GetValue(self):
""" Returns the indicator value. """
return self._value
def Draw(self, dc):
"""
Actually draws the indicator.
:param `dc`: an instance of :class:`DC`.
"""
xpos, ypos = self.GetPosition()
bmp = wx.BitmapFromImage(self._img)
dc.DrawBitmap(bmp, xpos, ypos, True)
self._rect = wx.Rect(xpos, ypos, self._img.GetWidth(), self._img.GetHeight())
def GetId(self):
""" Returns the indicator id. """
return self._id
def SetColour(self, colour):
"""
Sets the indicator colour.
:param `colour`: the new indicator colour, an instance of :class:`Colour`.
:note: Requires PIL (Python Imaging Library), which can be downloaded from
http://www.pythonware.com/products/pil/
"""
if not _hasPIL:
return
palette = colour.Red(), colour.Green(), colour.Blue()
img = ConvertWXToPIL(GetIndicatorBitmap())
l = MakePalette(*palette)
# The Palette Can Be Applied Only To "L" And "P" Images, Not "RGBA"
img = img.convert("L")
# Apply The New Palette
img.putpalette(l)
# Convert The Image Back To RGBA
img = img.convert("RGBA")
img = ConvertPILToWX(img)
self.RotateImage(img)
self._parent.Refresh()
# ---------------------------------------------------------------------------- #
# Class RulerCtrl
# ---------------------------------------------------------------------------- #
class RulerCtrl(wx.PyPanel):
"""
:class:`RulerCtrl` implements a ruler window that can be placed on top, bottom, left or right
to any wxPython widget. It is somewhat similar to the rulers you can find in text
editors software, though not so powerful.
"""
def __init__(self, parent, id=-1, pos=wx.DefaultPosition, size=wx.DefaultSize,
style=wx.STATIC_BORDER, orient=wx.HORIZONTAL):
"""
Default class constructor.
:param `parent`: parent window. Must not be ``None``;
:param `id`: window identifier. A value of -1 indicates a default value;
:param `pos`: the control position. A value of (-1, -1) indicates a default position,
chosen by either the windowing system or wxPython, depending on platform;
:param `size`: the control size. A value of (-1, -1) indicates a default size,
chosen by either the windowing system or wxPython, depending on platform;
:param `style`: the window style;
:param `orient`: sets the orientation of the :class:`RulerCtrl`, and can be either
``wx.HORIZONTAL`` of ``wx.VERTICAL``.
"""
wx.PyPanel.__init__(self, parent, id, pos, size, style)
self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
width, height = size
self._min = 0.0
self._max = 10.0
self._orientation = orient
self._spacing = 5
self._hassetspacing = False
self._format = RealFormat
self._flip = False
self._log = False
self._labeledges = False
self._units = ""
self._drawingparent = None
self._drawingpen = wx.Pen(wx.BLACK, 2)
self._left = -1
self._top = -1
self._right = -1
self._bottom = -1
self._major = 1
self._minor = 1
self._indicators = []
self._currentIndicator = None
fontsize = 10
if wx.Platform == "__WXMSW__":
fontsize = 8
self._minorfont = wx.Font(fontsize, wx.SWISS, wx.NORMAL, wx.NORMAL)
self._majorfont = wx.Font(fontsize, wx.SWISS, wx.NORMAL, wx.BOLD)
if wx.Platform == "__WXMAC__":
self._minorfont.SetNoAntiAliasing(True)
self._majorfont.SetNoAntiAliasing(True)
self._bits = []
self._userbits = []
self._userbitlen = 0
self._tickmajor = True
self._tickminor = True
self._timeformat = IntFormat
self._labelmajor = True
self._labelminor = True
self._tickpen = wx.Pen(wx.BLACK)
self._textcolour = wx.BLACK
self._background = wx.WHITE
self._valid = False
self._state = 0
self._style = style
self._orientation = orient
wbound, hbound = self.CheckStyle()
if orient & wx.VERTICAL:
self.SetBestSize((28, height))
else:
self.SetBestSize((width, 28))
self.SetBounds(0, 0, wbound, hbound)
self.Bind(wx.EVT_SIZE, self.OnSize)
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouseEvents)
self.Bind(wx.EVT_MOUSE_CAPTURE_LOST, lambda evt: True)
def OnMouseEvents(self, event):
"""
Handles the ``wx.EVT_MOUSE_EVENTS`` event for :class:`RulerCtrl`.
:param `event`: a :class:`MouseEvent` event to be processed.
"""
if not self._indicators:
event.Skip()
return
mousePos = event.GetPosition()
if event.LeftDown():
self.CaptureMouse()
self.GetIndicator(mousePos)
self._mousePosition = mousePos
self.SetIndicatorValue(sendEvent=False)
elif event.Dragging() and self._currentIndicator:
self._mousePosition = mousePos
self.SetIndicatorValue()
elif event.LeftUp():
if self.HasCapture():
self.ReleaseMouse()
self.SetIndicatorValue(sendEvent=False)
if self._drawingparent:
self._drawingparent.Refresh()
self._currentIndicator = None
#else:
# self._currentIndicator = None
event.Skip()
def OnPaint(self, event):
"""
Handles the ``wx.EVT_PAINT`` event for :class:`RulerCtrl`.
:param `event`: a :class:`PaintEvent` event to be processed.
"""
dc = wx.BufferedPaintDC(self)
dc.SetBackground(wx.Brush(self._background))
dc.Clear()
self.Draw(dc)
def OnSize(self, event):
"""
Handles the ``wx.EVT_SIZE`` event for :class:`RulerCtrl`.
:param `event`: a :class:`SizeEvent` event to be processed.
"""
width, height = self.CheckStyle()
self.SetBounds(0, 0, width, height)
self.Invalidate()
event.Skip()
def OnEraseBackground(self, event):
"""
Handles the ``wx.EVT_ERASE_BACKGROUND`` event for :class:`RulerCtrl`.
:param `event`: a :class:`EraseEvent` event to be processed.
:note: This method is intentionally empty to reduce flicker.
"""
pass
def SetIndicatorValue(self, sendEvent=True):
"""
Sets the indicator value.
:param `sendEvent`: ``True`` to send a :class:`RulerCtrlEvent`, ``False`` otherwise.
"""
if self._currentIndicator is None:
return
left, top, right, bottom = self.GetBounds()
x = self._mousePosition.x
y = self._mousePosition.y
maxvalue = self._max
minvalue = self._min
if self._log:
minvalue = math.log10(minvalue)
maxvalue = math.log10(maxvalue)
deltarange = abs(self._max - self._min)
if self._orientation == wx.HORIZONTAL: # only x moves
value = deltarange*float(x)/(right - left)
else:
value = deltarange*float(y)/(bottom - top)
value += minvalue
if self._log:
value = 10**value
if value < self._min or value > self._max:
return
self.DrawOnParent(self._currentIndicator)
if sendEvent:
event = RulerCtrlEvent(wxEVT_INDICATOR_CHANGING, self._currentIndicator.GetId())
event.SetOldValue(self._currentIndicator.GetValue())
event.SetValue(value)
event.SetEventObject(self)
if self.GetEventHandler().ProcessEvent(event):
self.DrawOnParent(self._currentIndicator)
return
self._currentIndicator.SetValue(value)
if sendEvent:
event.SetEventType(wxEVT_INDICATOR_CHANGED)
event.SetOldValue(value)
self.GetEventHandler().ProcessEvent(event)
self.DrawOnParent(self._currentIndicator)
self.Refresh()
def GetIndicator(self, mousePos):
"""
Returns the indicator located at the mouse position `mousePos` (if any).
:param `mousePos`: the mouse position, an instance of :class:`Point`.
"""
for indicator in self._indicators:
if indicator.GetRect().Contains(mousePos):
self._currentIndicator = indicator
break
def CheckStyle(self):
""" Adjust the :class:`RulerCtrl` style accordingly to borders, units, etc..."""
width, height = self.GetSize()
if self._orientation & wx.HORIZONTAL:
if self._style & wx.NO_BORDER:
hbound = 28
wbound = width-1
elif self._style & wx.SIMPLE_BORDER:
hbound = 27
wbound = width-1
elif self._style & wx.STATIC_BORDER:
hbound = 26
wbound = width-3
elif self._style & wx.SUNKEN_BORDER:
hbound = 24
wbound = width-5
elif self._style & wx.RAISED_BORDER:
hbound = 22
wbound = width-7
elif self._style & wx.DOUBLE_BORDER:
hbound = 22
wbound = width-7
else:
if self._style & wx.NO_BORDER:
wbound = 28
hbound = height-1
elif self._style & wx.SIMPLE_BORDER:
wbound = 27
hbound = height-1
elif self._style & wx.STATIC_BORDER:
wbound = 26
hbound = height-3
elif self._style & wx.SUNKEN_BORDER:
wbound = 24
hbound = height-5
elif self._style & wx.RAISED_BORDER:
wbound = 22
hbound = height-7
elif self._style & wx.DOUBLE_BORDER:
wbound = 22
hbound = height-7
minText = self.LabelString(self._min, major=True)
maxText = self.LabelString(self._max, major=True)
dc = wx.ClientDC(self)
minWidth, minHeight = dc.GetTextExtent(minText)
maxWidth, maxHeight = dc.GetTextExtent(maxText)
maxWidth = max(maxWidth, minWidth)
maxHeight = max(maxHeight, minHeight)
if self._orientation == wx.HORIZONTAL:
if maxHeight + 4 > hbound:
hbound = maxHeight
self.SetBestSize((-1, maxHeight + 4))
if self.GetContainingSizer():
self.GetContainingSizer().Layout()
else:
if maxWidth + 4 > wbound:
wbound = maxWidth
self.SetBestSize((maxWidth + 4, -1))
if self.GetContainingSizer():
self.GetContainingSizer().Layout()
return wbound, hbound
def TickMajor(self, tick=True):
"""
Sets whether the major ticks should be ticked or not.
:param `tick`: ``True`` to show major ticks, ``False`` otherwise.
"""
if self._tickmajor != tick:
self._tickmajor = tick
self.Invalidate()
def TickMinor(self, tick=True):
"""
Sets whether the minor ticks should be ticked or not.
:param `tick`: ``True`` to show minor ticks, ``False`` otherwise.
"""
if self._tickminor != tick:
self._tickminor = tick
self.Invalidate()
def LabelMinor(self, label=True):
"""
Sets whether the minor ticks should be labeled or not.
:param `label`: ``True`` to label minor ticks, ``False`` otherwise.
"""
if self._labelminor != label:
self._labelminor = label
self.Invalidate()
def LabelMajor(self, label=True):
"""
Sets whether the major ticks should be labeled or not.
:param `label`: ``True`` to label major ticks, ``False`` otherwise.
"""
if self._labelmajor != label:
self._labelmajor = label
self.Invalidate()
def GetTimeFormat(self):
""" Returns the time format. """
return self._timeformat
def SetTimeFormat(self, format=TimeFormat):
"""
Sets the time format.
:param `format`: the format used to display time values.
"""
if self._timeformat != format:
self._timeformat = format
self.Invalidate()
def SetFormat(self, format):
"""
Sets the format for :class:`RulerCtrl`.
:param `format`: the format used to display values in :class:`RulerCtrl`. This can be
one of the following bits:
====================== ======= ==============================
Format Value Description
====================== ======= ==============================
``IntFormat`` 1 Integer format
``RealFormat`` 2 Real format
``TimeFormat`` 3 Time format
``LinearDBFormat`` 4 Linear DB format
``HHMMSS_Format`` 5 HHMMSS format
====================== ======= ==============================
"""
if self._format != format:
self._format = format
self.Invalidate()
def GetFormat(self):
"""
Returns the format used to display values in :class:`RulerCtrl`.
:see: :meth:`RulerCtrl.SetFormat` for a list of possible formats.
"""
return self._format
def SetLog(self, log=True):
"""
Sets whether :class:`RulerCtrl` should have a logarithmic scale or not.
:param `log`: ``True`` to use a logarithmic scake, ``False`` to use a
linear one.
"""
if self._log != log:
self._log = log
self.Invalidate()
def SetUnits(self, units):
"""
Sets the units that should be displayed beside the labels.
:param `units`: the units that should be displayed beside the labels.
"""
# Specify the name of the units (like "dB") if you
# want numbers like "1.6" formatted as "1.6 dB".
if self._units != units:
self._units = units
self.Invalidate()
def SetBackgroundColour(self, colour):
"""
Sets the :class:`RulerCtrl` background colour.
:param `colour`: an instance of :class:`Colour`.
:note: Overridden from :class:`PyPanel`.
"""
self._background = colour
wx.PyPanel.SetBackgroundColour(self, colour)
self.Refresh()
def SetOrientation(self, orient=None):
"""
Sets the :class:`RulerCtrl` orientation.
:param `orient`: can be ``wx.HORIZONTAL`` or ``wx.VERTICAL``.
"""
if orient is None:
orient = wx.HORIZONTAL
if self._orientation != orient:
self._orientation = orient
if self._orientation == wx.VERTICAL and not self._hassetspacing:
self._spacing = 2
self.Invalidate()
def SetRange(self, minVal, maxVal):
"""
Sets the :class:`RulerCtrl` range.
:param `minVal`: the minimum value of :class:`RulerCtrl`;
:param `maxVal`: the maximum value of :class:`RulerCtrl`.
"""
# For a horizontal ruler,
# minVal is the value in the center of pixel "left",
# maxVal is the value in the center of pixel "right".
if self._min != minVal or self._max != maxVal:
self._min = minVal
self._max = maxVal
self.Invalidate()
def SetSpacing(self, spacing):
"""
Sets the :class:`RulerCtrl` spacing between labels.
:param `spacing`: the spacing between labels, in pixels.
"""
self._hassetspacing = True
if self._spacing != spacing:
self._spacing = spacing
self.Invalidate()
def SetLabelEdges(self, labelEdges=True):
"""
Sets whether the edge values should always be displayed or not.
<|fim▁hole|>
:param `labelEdges`: ``True`` to always display edge labels, ``False`` otherwise/
"""
# If this is True, the edges of the ruler will always
# receive a label. If not, the nearest round number is
# labeled (which may or may not be the edge).
if self._labeledges != labelEdges:
self._labeledges = labelEdges
self.Invalidate()
def SetFlip(self, flip=True):
"""
Sets whether the orientation of the tick marks should be reversed.
:param `flip`: ``True`` to reverse the orientation of the tick marks, ``False``
otherwise.
"""
# If this is True, the orientation of the tick marks
# is reversed from the default eg. above the line
# instead of below
if self._flip != flip:
self._flip = flip
self.Invalidate()
for indicator in self._indicators:
indicator.RotateImage()
def SetFonts(self, minorFont, majorFont):
"""
Sets the fonts for minor and major tick labels.
:param `minorFont`: the font used to draw minor ticks, a valid :class:`Font` object;
:param `majorFont`: the font used to draw major ticks, a valid :class:`Font` object.
"""
self._minorfont = minorFont
self._majorfont = majorFont
if wx.Platform == "__WXMAC__":
self._minorfont.SetNoAntiAliasing(True)
self._majorfont.SetNoAntiAliasing(True)
self.Invalidate()
def SetTickPenColour(self, colour=wx.BLACK):
"""
Sets the pen colour to draw the ticks.
:param `colour`: a valid :class:`Colour` object.
"""
self._tickpen = wx.Pen(colour)
self.Refresh()
def SetLabelColour(self, colour=wx.BLACK):
"""
Sets the labels colour.
:param `colour`: a valid :class:`Colour` object.
"""
self._textcolour = colour
self.Refresh()
def OfflimitsPixels(self, start, end):
""" Used internally. """
if not self._userbits:
if self._orientation == wx.HORIZONTAL:
self._length = self._right-self._left
else:
self._length = self._bottom-self._top
self._userbits = [0]*self._length
self._userbitlen = self._length+1
if end < start:
i = end
end = start
start = i
if start < 0:
start = 0
if end > self._length:
end = self._length
for ii in xrange(start, end+1):
self._userbits[ii] = 1
def SetBounds(self, left, top, right, bottom):
"""
Sets the bounds for :class:`RulerCtrl` (its client rectangle).
:param `left`: the left corner of the client rectangle;
:param `top`: the top corner of the client rectangle;
:param `right`: the right corner of the client rectangle;
:param `bottom`: the bottom corner of the client rectangle.
"""
if self._left != left or self._top != top or self._right != right or \
self._bottom != bottom:
self._left = left
self._top = top
self._right = right
self._bottom = bottom
self.Invalidate()
def GetBounds(self):
""" Returns the :class:`RulerCtrl` bounds (its client rectangle). """
return self._left, self._top, self._right, self._bottom
def AddIndicator(self, id, value):
"""
Adds an indicator to :class:`RulerCtrl`. You should pass a unique `id` and a starting
`value` for the indicator.
:param `id`: the indicator identifier;
:param `value`: the indicator initial value.
"""
self._indicators.append(Indicator(self, id, value))
self.Refresh()
def SetIndicatorColour(self, id, colour=None):
"""
Sets the indicator colour.
:param `id`: the indicator identifier;
:param `colour`: a valid :class:`Colour` object.
:note: This method requires PIL to change the image palette.
"""
if not _hasPIL:
return
if colour is None:
colour = wx.WHITE
for indicator in self._indicators:
if indicator.GetId() == id:
indicator.SetColour(colour)
break
def Invalidate(self):
""" Invalidates the ticks calculations. """
self._valid = False
if self._orientation == wx.HORIZONTAL:
self._length = self._right - self._left
else:
self._length = self._bottom - self._top
self._majorlabels = []
self._minorlabels = []
self._bits = []
self._userbits = []
self._userbitlen = 0
self.Refresh()
def FindLinearTickSizes(self, UPP):
""" Used internally. """
# Given the dimensions of the ruler, the range of values it
# has to display, and the format (i.e. Int, Real, Time),
# figure out how many units are in one Minor tick, and
# in one Major tick.
#
# The goal is to always put tick marks on nice round numbers
# that are easy for humans to grok. This is the most tricky
# with time.
# As a heuristic, we want at least 16 pixels
# between each minor tick
units = 16.0*abs(UPP)
self._digits = 0
if self._format == LinearDBFormat:
if units < 0.1:
self._minor = 0.1
self._major = 0.5
return
if units < 1.0:
self._minor = 1.0
self._major = 6.0
return
self._minor = 3.0
self._major = 12.0
return
elif self._format == IntFormat:
d = 1.0
while 1:
if units < d:
self._minor = d
self._major = d*5.0
return
d = d*5.0
if units < d:
self._minor = d
self._major = d*2.0
return
d = 2.0*d
elif self._format == TimeFormat:
if units > 0.5:
if units < 1.0: # 1 sec
self._minor = 1.0
self._major = 5.0
return
if units < 5.0: # 5 sec
self._minor = 5.0
self._major = 15.0
return
if units < 10.0:
self._minor = 10.0
self._major = 30.0
return
if units < 15.0:
self._minor = 15.0
self._major = 60.0
return
if units < 30.0:
self._minor = 30.0
self._major = 60.0
return
if units < 60.0: # 1 min
self._minor = 60.0
self._major = 300.0
return
if units < 300.0: # 5 min
self._minor = 300.0
self._major = 900.0
return
if units < 600.0: # 10 min
self._minor = 600.0
self._major = 1800.0
return
if units < 900.0: # 15 min
self._minor = 900.0
self._major = 3600.0
return
if units < 1800.0: # 30 min
self._minor = 1800.0
self._major = 3600.0
return
if units < 3600.0: # 1 hr
self._minor = 3600.0
self._major = 6*3600.0
return
if units < 6*3600.0: # 6 hrs
self._minor = 6*3600.0
self._major = 24*3600.0
return
if units < 24*3600.0: # 1 day
self._minor = 24*3600.0
self._major = 7*24*3600.0
return
self._minor = 24.0*7.0*3600.0 # 1 week
self._major = 24.0*7.0*3600.0
# Otherwise fall through to RealFormat
# (fractions of a second should be dealt with
# the same way as for RealFormat)
elif self._format == RealFormat:
d = 0.000001
self._digits = 6
while 1:
if units < d:
self._minor = d
self._major = d*5.0
return
d = d*5.0
if units < d:
self._minor = d
self._major = d*2.0
return
d = d*2.0
self._digits = self._digits - 1
def LabelString(self, d, major=None):
""" Used internally. """
# Given a value, turn it into a string according
# to the current ruler format. The number of digits of
# accuracy depends on the resolution of the ruler,
# i.e. how far zoomed in or out you are.
s = ""
if d < 0.0 and d + self._minor > 0.0:
d = 0.0
if self._format == IntFormat:
s = "%d"%int(math.floor(d+0.5))
elif self._format == LinearDBFormat:
if self._minor >= 1.0:
s = "%d"%int(math.floor(d+0.5))
else:
s = "%0.1f"%d
elif self._format == RealFormat:
if self._minor >= 1.0:
s = "%d"%int(math.floor(d+0.5))
else:
s = (("%." + str(self._digits) + "f")%d).strip()
elif self._format == TimeFormat:
if major:
if d < 0:
s = "-"
d = -d
if self.GetTimeFormat() == HHMMSS_Format:
secs = int(d + 0.5)
if self._minor >= 1.0:
s = ("%d:%02d:%02d")%(secs/3600, (secs/60)%60, secs%60)
else:
t1 = ("%d:%02d:")%(secs/3600, (secs/60)%60)
format = "%" + "%0d.%dlf"%(self._digits+3, self._digits)
t2 = format%(d%60.0)
s = s + t1 + t2
else:
if self._minor >= 3600.0:
hrs = int(d/3600.0 + 0.5)
h = "%d:00:00"%hrs
s = s + h
elif self._minor >= 60.0:
minutes = int(d/60.0 + 0.5)
if minutes >= 60:
m = "%d:%02d:00"%(minutes/60, minutes%60)
else:
m = "%d:00"%minutes
s = s + m
elif self._minor >= 1.0:
secs = int(d + 0.5)
if secs >= 3600:
t = "%d:%02d:%02d"%(secs/3600, (secs/60)%60, secs%60)
elif secs >= 60:
t = "%d:%02d"%(secs/60, secs%60)
else:
t = "%d"%secs
s = s + t
else:
secs = int(d)
if secs >= 3600:
t1 = "%d:%02d:"%(secs/3600, (secs/60)%60)
elif secs >= 60:
t1 = "%d:"%(secs/60)
if secs >= 60:
format = "%%0%d.%dlf"%(self._digits+3, self._digits)
else:
format = "%%%d.%dlf"%(self._digits+3, self._digits)
t2 = format%(d%60.0)
s = s + t1 + t2
if self._units != "":
s = s + " " + self._units
return s
def Tick(self, dc, pos, d, major):
"""
Ticks a particular position.
:param `dc`: an instance of :class:`DC`;
:param `pos`: the label position;
:param `d`: the current label value;
:param `major`: ``True`` if it is a major ticks, ``False`` if it is a minor one.
"""
if major:
label = Label()
self._majorlabels.append(label)
else:
label = Label()
self._minorlabels.append(label)
label.pos = pos
label.lx = self._left - 2000 # don't display
label.ly = self._top - 2000 # don't display
label.text = ""
dc.SetFont((major and [self._majorfont] or [self._minorfont])[0])
l = self.LabelString(d, major)
strw, strh = dc.GetTextExtent(l)
if self._orientation == wx.HORIZONTAL:
strlen = strw
strpos = pos - strw/2
if strpos < 0:
strpos = 0
if strpos + strw >= self._length:
strpos = self._length - strw
strleft = self._left + strpos
if self._flip:
strtop = self._top + 4
self._maxheight = max(self._maxheight, 4 + strh)
else:
strtop = self._bottom - strh - 6
self._maxheight = max(self._maxheight, strh + 6)
else:
strlen = strh
strpos = pos - strh/2
if strpos < 0:
strpos = 0
if strpos + strh >= self._length:
strpos = self._length - strh
strtop = self._top + strpos
if self._flip:
strleft = self._left + 5
self._maxwidth = max(self._maxwidth, 5 + strw)
else:
strleft = self._right - strw - 6
self._maxwidth = max(self._maxwidth, strw + 6)
# See if any of the pixels we need to draw this
# label is already covered
if major and self._labelmajor or not major and self._labelminor:
for ii in xrange(strlen):
if self._bits[strpos+ii]:
return
# If not, position the label and give it text
label.lx = strleft
label.ly = strtop
label.text = l
if major:
if self._tickmajor and not self._labelmajor:
label.text = ""
self._majorlabels[-1] = label
else:
if self._tickminor and not self._labelminor:
label.text = ""
label.text = label.text.replace(self._units, "")
self._minorlabels[-1] = label
# And mark these pixels, plus some surrounding
# ones (the spacing between labels), as covered
if (not major and self._labelminor) or (major and self._labelmajor):
leftmargin = self._spacing
if strpos < leftmargin:
leftmargin = strpos
strpos = strpos - leftmargin
strlen = strlen + leftmargin
rightmargin = self._spacing
if strpos + strlen > self._length - self._spacing:
rightmargin = self._length - strpos - strlen
strlen = strlen + rightmargin
for ii in xrange(strlen):
self._bits[strpos+ii] = 1
def Update(self, dc):
"""
Updates all the ticks calculations.
:param `dc`: an instance of :class:`DC`.
"""
# This gets called when something has been changed
# (i.e. we've been invalidated). Recompute all
# tick positions.
if self._orientation == wx.HORIZONTAL:
self._maxwidth = self._length
self._maxheight = 0
else:
self._maxwidth = 0
self._maxheight = self._length
self._bits = [0]*(self._length+1)
self._middlepos = []
if self._userbits:
for ii in xrange(self._length):
self._bits[ii] = self._userbits[ii]
else:
for ii in xrange(self._length):
self._bits[ii] = 0
if not self._log:
UPP = (self._max - self._min)/float(self._length) # Units per pixel
self.FindLinearTickSizes(UPP)
# Left and Right Edges
if self._labeledges:
self.Tick(dc, 0, self._min, True)
self.Tick(dc, self._length, self._max, True)
# Zero (if it's in the middle somewhere)
if self._min*self._max < 0.0:
mid = int(self._length*(self._min/(self._min-self._max)) + 0.5)
self.Tick(dc, mid, 0.0, True)
sg = ((UPP > 0.0) and [1.0] or [-1.0])[0]
# Major ticks
d = self._min - UPP/2
lastd = d
majorint = int(math.floor(sg*d/self._major))
ii = -1
while ii <= self._length:
ii = ii + 1
lastd = d
d = d + UPP
if int(math.floor(sg*d/self._major)) > majorint:
majorint = int(math.floor(sg*d/self._major))
self.Tick(dc, ii, sg*majorint*self._major, True)
# Minor ticks
d = self._min - UPP/2
lastd = d
minorint = int(math.floor(sg*d/self._minor))
ii = -1
while ii <= self._length:
ii = ii + 1
lastd = d
d = d + UPP
if int(math.floor(sg*d/self._minor)) > minorint:
minorint = int(math.floor(sg*d/self._minor))
self.Tick(dc, ii, sg*minorint*self._minor, False)
# Left and Right Edges
if self._labeledges:
self.Tick(dc, 0, self._min, True)
self.Tick(dc, self._length, self._max, True)
else:
# log case
lolog = math.log10(self._min)
hilog = math.log10(self._max)
scale = self._length/(hilog - lolog)
lodecade = int(math.floor(lolog))
hidecade = int(math.ceil(hilog))
# Left and Right Edges
if self._labeledges:
self.Tick(dc, 0, self._min, True)
self.Tick(dc, self._length, self._max, True)
startdecade = 10.0**lodecade
# Major ticks are the decades
decade = startdecade
for ii in xrange(lodecade, hidecade):
if ii != lodecade:
val = decade
if val > self._min and val < self._max:
pos = int(((math.log10(val) - lolog)*scale)+0.5)
self.Tick(dc, pos, val, True)
decade = decade*10.0
# Minor ticks are multiples of decades
decade = startdecade
for ii in xrange(lodecade, hidecade):
for jj in xrange(2, 10):
val = decade*jj
if val >= self._min and val < self._max:
pos = int(((math.log10(val) - lolog)*scale)+0.5)
self.Tick(dc, pos, val, False)
decade = decade*10.0
self._valid = True
def Draw(self, dc):
"""
Actually draws the whole :class:`RulerCtrl`.
:param `dc`: an instance of :class:`DC`.
"""
if not self._valid:
self.Update(dc)
dc.SetBrush(wx.Brush(self._background))
dc.SetPen(self._tickpen)
dc.SetTextForeground(self._textcolour)
dc.DrawRectangleRect(self.GetClientRect())
if self._orientation == wx.HORIZONTAL:
if self._flip:
dc.DrawLine(self._left, self._top, self._right+1, self._top)
else:
dc.DrawLine(self._left, self._bottom-1, self._right+1, self._bottom-1)
else:
if self._flip:
dc.DrawLine(self._left, self._top, self._left, self._bottom+1)
else:
dc.DrawLine(self._right-1, self._top, self._right-1, self._bottom+1)
dc.SetFont(self._majorfont)
for label in self._majorlabels:
pos = label.pos
if self._orientation == wx.HORIZONTAL:
if self._flip:
dc.DrawLine(self._left + pos, self._top,
self._left + pos, self._top + 5)
else:
dc.DrawLine(self._left + pos, self._bottom - 5,
self._left + pos, self._bottom)
else:
if self._flip:
dc.DrawLine(self._left, self._top + pos,
self._left + 5, self._top + pos)
else:
dc.DrawLine(self._right - 5, self._top + pos,
self._right, self._top + pos)
if label.text != "":
dc.DrawText(label.text, label.lx, label.ly)
dc.SetFont(self._minorfont)
for label in self._minorlabels:
pos = label.pos
if self._orientation == wx.HORIZONTAL:
if self._flip:
dc.DrawLine(self._left + pos, self._top,
self._left + pos, self._top + 3)
else:
dc.DrawLine(self._left + pos, self._bottom - 3,
self._left + pos, self._bottom)
else:
if self._flip:
dc.DrawLine(self._left, self._top + pos,
self._left + 3, self._top + pos)
else:
dc.DrawLine(self._right - 3, self._top + pos,
self._right, self._top + pos)
if label.text != "":
dc.DrawText(label.text, label.lx, label.ly)
for indicator in self._indicators:
indicator.Draw(dc)
def SetDrawingParent(self, dparent):
"""
Sets the window to which :class:`RulerCtrl` draws a thin line over.
:param `dparent`: an instance of :class:`Window`, representing the window to
which :class:`RulerCtrl` draws a thin line over.
"""
self._drawingparent = dparent
def GetDrawingParent(self):
""" Returns the window to which :class:`RulerCtrl` draws a thin line over. """
return self._drawingparent
def DrawOnParent(self, indicator):
"""
Actually draws the thin line over the drawing parent window.
:param `indicator`: the current indicator, an instance of :class:`Indicator`.
:note: This method is currently not available on wxMac as it uses :class:`ScreenDC`.
"""
if not self._drawingparent:
return
xpos, ypos = indicator.GetPosition()
parentrect = self._drawingparent.GetClientRect()
dc = wx.ScreenDC()
dc.SetLogicalFunction(wx.INVERT)
dc.SetPen(self._drawingpen)
dc.SetBrush(wx.TRANSPARENT_BRUSH)
imgx, imgy = indicator.GetImageSize()
if self._orientation == wx.HORIZONTAL:
x1 = xpos+ imgx/2
y1 = parentrect.y
x2 = x1
y2 = parentrect.height
x1, y1 = self._drawingparent.ClientToScreenXY(x1, y1)
x2, y2 = self._drawingparent.ClientToScreenXY(x2, y2)
elif self._orientation == wx.VERTICAL:
x1 = parentrect.x
y1 = ypos + imgy/2
x2 = parentrect.width
y2 = y1
x1, y1 = self._drawingparent.ClientToScreenXY(x1, y1)
x2, y2 = self._drawingparent.ClientToScreenXY(x2, y2)
dc.DrawLine(x1, y1, x2, y2)
dc.SetLogicalFunction(wx.COPY)<|fim▁end|> | |
<|file_name|>PatternCompiler.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.structuralsearch.impl.matcher.compiler;
import com.intellij.codeInsight.template.Template;
import com.intellij.codeInsight.template.TemplateManager;
import com.intellij.dupLocator.util.NodeFilter;
import com.intellij.lang.Language;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.LanguageFileType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiErrorElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiRecursiveElementWalkingVisitor;
import com.intellij.psi.impl.source.tree.LeafElement;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.structuralsearch.*;
import com.intellij.structuralsearch.impl.matcher.CompiledPattern;
import com.intellij.structuralsearch.impl.matcher.MatcherImplUtil;
import com.intellij.structuralsearch.impl.matcher.PatternTreeContext;
import com.intellij.structuralsearch.impl.matcher.filters.LexicalNodesFilter;
import com.intellij.structuralsearch.impl.matcher.handlers.MatchingHandler;
import com.intellij.structuralsearch.impl.matcher.handlers.SubstitutionHandler;
import com.intellij.structuralsearch.impl.matcher.predicates.*;
import com.intellij.structuralsearch.plugin.ui.Configuration;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.SmartList;
import gnu.trove.TIntArrayList;
import gnu.trove.TIntHashSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Compiles the handlers for usability
*/
public class PatternCompiler {
private static CompileContext lastTestingContext;
public static CompiledPattern compilePattern(final Project project, final MatchOptions options)
throws MalformedPatternException, NoMatchFoundException, UnsupportedOperationException {
FileType fileType = options.getFileType();
assert fileType instanceof LanguageFileType;
Language language = ((LanguageFileType)fileType).getLanguage();
StructuralSearchProfile profile = StructuralSearchUtil.getProfileByLanguage(language);
assert profile != null;
CompiledPattern result = profile.createCompiledPattern();
final String[] prefixes = result.getTypedVarPrefixes();
assert prefixes.length > 0;
final CompileContext context = new CompileContext(result, options, project);
if (ApplicationManager.getApplication().isUnitTestMode()) lastTestingContext = context;
try {
List<PsiElement> elements = compileByAllPrefixes(project, options, result, context, prefixes);
final CompiledPattern pattern = context.getPattern();
checkForUnknownVariables(pattern, elements);
pattern.setNodes(elements);
if (context.getSearchHelper().doOptimizing() && context.getSearchHelper().isScannedSomething()) {
final Set<PsiFile> set = context.getSearchHelper().getFilesSetToScan();
final List<PsiFile> filesToScan = new SmartList<>();
final GlobalSearchScope scope = (GlobalSearchScope)options.getScope();
for (final PsiFile file : set) {
if (!scope.contains(file.getVirtualFile())) {
continue;
}
filesToScan.add(file);
}
if (filesToScan.size() == 0) {
throw new NoMatchFoundException(SSRBundle.message("ssr.will.not.find.anything", scope.getDisplayName()));
}
result.setScope(new LocalSearchScope(PsiUtilCore.toPsiElementArray(filesToScan)));
}
} finally {
context.clear();
}
return result;
}
private static void checkForUnknownVariables(final CompiledPattern pattern, List<PsiElement> elements) {
for (PsiElement element : elements) {
element.accept(new PsiRecursiveElementWalkingVisitor() {
@Override
public void visitElement(PsiElement element) {
if (element.getUserData(CompiledPattern.HANDLER_KEY) != null) {
return;
}
super.visitElement(element);
if (!(element instanceof LeafElement) || !pattern.isTypedVar(element)) {
return;
}
final MatchingHandler handler = pattern.getHandler(pattern.getTypedVarString(element));
if (handler == null) {
throw new MalformedPatternException();
}
}
});
}
}
public static String getLastFindPlan() {
return ((TestModeOptimizingSearchHelper)lastTestingContext.getSearchHelper()).getSearchPlan();
}
@NotNull
private static List<PsiElement> compileByAllPrefixes(Project project,
MatchOptions options,
CompiledPattern pattern,
CompileContext context,
String[] applicablePrefixes) throws MalformedPatternException {
if (applicablePrefixes.length == 0) {
return Collections.emptyList();
}
List<PsiElement> elements = doCompile(project, options, pattern, new ConstantPrefixProvider(applicablePrefixes[0]), context);
if (elements.isEmpty()) {
return elements;
}
final PsiFile file = elements.get(0).getContainingFile();
if (file == null) {
return elements;
}
final PsiElement last = elements.get(elements.size() - 1);
final Pattern[] patterns = new Pattern[applicablePrefixes.length];
for (int i = 0; i < applicablePrefixes.length; i++) {
patterns[i] = Pattern.compile(StructuralSearchUtil.shieldRegExpMetaChars(applicablePrefixes[i]) + "\\w+\\b");
}
final int[] varEndOffsets = findAllTypedVarOffsets(file, patterns);
final int patternEndOffset = last.getTextRange().getEndOffset();
if (elements.size() == 0 ||
checkErrorElements(file, patternEndOffset, patternEndOffset, varEndOffsets, true) != Boolean.TRUE) {
return elements;
}
final int varCount = varEndOffsets.length;
final String[] prefixSequence = new String[varCount];
for (int i = 0; i < varCount; i++) {
prefixSequence[i] = applicablePrefixes[0];
}
final List<PsiElement> finalElements =
compileByPrefixes(project, options, pattern, context, applicablePrefixes, patterns, prefixSequence, 0);
return finalElements != null
? finalElements
: doCompile(project, options, pattern, new ConstantPrefixProvider(applicablePrefixes[0]), context);
}
@Nullable
private static List<PsiElement> compileByPrefixes(Project project,
MatchOptions options,
CompiledPattern pattern,
CompileContext context,
String[] applicablePrefixes,
Pattern[] substitutionPatterns,
String[] prefixSequence,
int index) throws MalformedPatternException {
if (index >= prefixSequence.length) {
final List<PsiElement> elements = doCompile(project, options, pattern, new ArrayPrefixProvider(prefixSequence), context);
if (elements.isEmpty()) {
return elements;
}
final PsiElement parent = elements.get(0).getParent();
final PsiElement last = elements.get(elements.size() - 1);
final int[] varEndOffsets = findAllTypedVarOffsets(parent.getContainingFile(), substitutionPatterns);
final int patternEndOffset = last.getTextRange().getEndOffset();
return checkErrorElements(parent, patternEndOffset, patternEndOffset, varEndOffsets, false) != Boolean.TRUE
? elements
: null;
}
String[] alternativeVariant = null;
for (String applicablePrefix : applicablePrefixes) {
prefixSequence[index] = applicablePrefix;
List<PsiElement> elements = doCompile(project, options, pattern, new ArrayPrefixProvider(prefixSequence), context);
if (elements.isEmpty()) {
return elements;
}
final PsiFile file = elements.get(0).getContainingFile();
if (file == null) {
return elements;
}
final int[] varEndOffsets = findAllTypedVarOffsets(file, substitutionPatterns);
final int offset = varEndOffsets[index];
final int patternEndOffset = elements.get(elements.size() - 1).getTextRange().getEndOffset();
final Boolean result = checkErrorElements(file, offset, patternEndOffset, varEndOffsets, false);
if (result == Boolean.TRUE) {
continue;
}
if (result == Boolean.FALSE || (result == null && alternativeVariant == null)) {
final List<PsiElement> finalElements =
compileByPrefixes(project, options, pattern, context, applicablePrefixes, substitutionPatterns, prefixSequence, index + 1);
if (finalElements != null) {
if (result == Boolean.FALSE) {
return finalElements;
}
alternativeVariant = new String[prefixSequence.length];
System.arraycopy(prefixSequence, 0, alternativeVariant, 0, prefixSequence.length);
}
}
}
return alternativeVariant != null ?
compileByPrefixes(project, options, pattern, context, applicablePrefixes, substitutionPatterns, alternativeVariant, index + 1) :
null;
}
@NotNull
private static int[] findAllTypedVarOffsets(final PsiFile file, final Pattern[] substitutionPatterns) {
final TIntHashSet result = new TIntHashSet();
file.accept(new PsiRecursiveElementWalkingVisitor() {
@Override
public void visitElement(PsiElement element) {
super.visitElement(element);
if (element instanceof LeafElement) {
final String text = element.getText();
for (Pattern pattern : substitutionPatterns) {
final Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
result.add(element.getTextRange().getStartOffset() + matcher.end());
}
}
}
}
});
final int[] resultArray = result.toArray();
Arrays.sort(resultArray);
return resultArray;
}
/**
* False: there are no error elements before offset, except patternEndOffset
* Null: there are only error elements located exactly after template variables or at the end of the pattern
* True: otherwise
*/
@Nullable
private static Boolean checkErrorElements(PsiElement element,
final int offset,
final int patternEndOffset,
final int[] varEndOffsets,
final boolean strict) {
final TIntArrayList errorOffsets = new TIntArrayList();
final boolean[] containsErrorTail = {false};
final TIntHashSet varEndOffsetsSet = new TIntHashSet(varEndOffsets);
element.accept(new PsiRecursiveElementWalkingVisitor() {
@Override
public void visitErrorElement(PsiErrorElement element) {
super.visitErrorElement(element);
final int startOffset = element.getTextRange().getStartOffset();
if ((strict || !varEndOffsetsSet.contains(startOffset)) && startOffset != patternEndOffset) {
errorOffsets.add(startOffset);
}
if (startOffset == offset) {
containsErrorTail[0] = true;
}
}
});
for (int i = 0; i < errorOffsets.size(); i++) {
final int errorOffset = errorOffsets.get(i);
if (errorOffset <= offset) {
return true;
}
}
return containsErrorTail[0] ? null : false;
}
private interface PrefixProvider {
String getPrefix(int varIndex);
}<|fim▁hole|>
ConstantPrefixProvider(String prefix) {
myPrefix = prefix;
}
@Override
public String getPrefix(int varIndex) {
return myPrefix;
}
}
private static class ArrayPrefixProvider implements PrefixProvider {
private final String[] myPrefixes;
ArrayPrefixProvider(String[] prefixes) {
myPrefixes = prefixes;
}
@Override
public String getPrefix(int varIndex) {
if (varIndex >= myPrefixes.length) return null;
return myPrefixes[varIndex];
}
}
private static List<PsiElement> doCompile(Project project,
MatchOptions options,
CompiledPattern result,
PrefixProvider prefixProvider,
CompileContext context) throws MalformedPatternException {
result.clearHandlers();
final StringBuilder buf = new StringBuilder();
Template template = TemplateManager.getInstance(project).createTemplate("","",options.getSearchPattern());
int segmentsCount = template.getSegmentsCount();
String text = template.getTemplateText();
int prevOffset = 0;
for(int i=0;i<segmentsCount;++i) {
final int offset = template.getSegmentOffset(i);
final String name = template.getSegmentName(i);
final String prefix = prefixProvider.getPrefix(i);
if (prefix == null) {
throw new MalformedPatternException();
}
buf.append(text.substring(prevOffset,offset));
buf.append(prefix);
buf.append(name);
MatchVariableConstraint constraint = options.getVariableConstraint(name);
if (constraint==null) {
// we do not edited the constraints
constraint = new MatchVariableConstraint();
constraint.setName( name );
options.addVariableConstraint(constraint);
}
SubstitutionHandler handler = result.createSubstitutionHandler(
name,
prefix + name,
constraint.isPartOfSearchResults(),
constraint.getMinCount(),
constraint.getMaxCount(),
constraint.isGreedy()
);
if(constraint.isWithinHierarchy()) {
handler.setSubtype(true);
}
if(constraint.isStrictlyWithinHierarchy()) {
handler.setStrictSubtype(true);
}
MatchPredicate predicate;
if (!StringUtil.isEmptyOrSpaces(constraint.getRegExp())) {
predicate = new RegExpPredicate(
constraint.getRegExp(),
options.isCaseSensitiveMatch(),
name,
constraint.isWholeWordsOnly(),
constraint.isPartOfSearchResults()
);
if (constraint.isInvertRegExp()) {
predicate = new NotPredicate(predicate);
}
addPredicate(handler,predicate);
}
if (constraint.isReference()) {
predicate = new ReferencePredicate( constraint.getNameOfReferenceVar() );
if (constraint.isInvertReference()) {
predicate = new NotPredicate(predicate);
}
addPredicate(handler,predicate);
}
addExtensionPredicates(options, constraint, handler);
addScriptConstraint(project, name, constraint, handler);
if (!StringUtil.isEmptyOrSpaces(constraint.getContainsConstraint())) {
predicate = new ContainsPredicate(name, constraint.getContainsConstraint());
if (constraint.isInvertContainsConstraint()) {
predicate = new NotPredicate(predicate);
}
addPredicate(handler,predicate);
}
if (!StringUtil.isEmptyOrSpaces(constraint.getWithinConstraint())) {
assert false;
}
prevOffset = offset;
}
MatchVariableConstraint constraint = options.getVariableConstraint(Configuration.CONTEXT_VAR_NAME);
if (constraint != null) {
SubstitutionHandler handler = result.createSubstitutionHandler(
Configuration.CONTEXT_VAR_NAME,
Configuration.CONTEXT_VAR_NAME,
constraint.isPartOfSearchResults(),
constraint.getMinCount(),
constraint.getMaxCount(),
constraint.isGreedy()
);
if (!StringUtil.isEmptyOrSpaces(constraint.getWithinConstraint())) {
MatchPredicate predicate = new WithinPredicate(constraint.getWithinConstraint(), options.getFileType(), project);
if (constraint.isInvertWithinConstraint()) {
predicate = new NotPredicate(predicate);
}
addPredicate(handler,predicate);
}
addExtensionPredicates(options, constraint, handler);
addScriptConstraint(project, Configuration.CONTEXT_VAR_NAME, constraint, handler);
}
buf.append(text.substring(prevOffset,text.length()));
PsiElement[] matchStatements;
try {
matchStatements = MatcherImplUtil.createTreeFromText(buf.toString(), PatternTreeContext.Block, options.getFileType(),
options.getDialect(), options.getPatternContext(), project, false);
if (matchStatements.length==0) throw new MalformedPatternException();
} catch (IncorrectOperationException e) {
throw new MalformedPatternException(e.getMessage());
}
NodeFilter filter = LexicalNodesFilter.getInstance();
GlobalCompilingVisitor compilingVisitor = new GlobalCompilingVisitor();
compilingVisitor.compile(matchStatements,context);
List<PsiElement> elements = new SmartList<>();
for (PsiElement matchStatement : matchStatements) {
if (!filter.accepts(matchStatement)) {
elements.add(matchStatement);
}
}
new DeleteNodesAction(compilingVisitor.getLexicalNodes()).run();
return elements;
}
private static void addExtensionPredicates(MatchOptions options, MatchVariableConstraint constraint, SubstitutionHandler handler) {
Set<MatchPredicate> predicates = new LinkedHashSet<>();
for (MatchPredicateProvider matchPredicateProvider : Extensions.getExtensions(MatchPredicateProvider.EP_NAME)) {
matchPredicateProvider.collectPredicates(constraint, handler.getName(), options, predicates);
}
for (MatchPredicate matchPredicate : predicates) {
addPredicate(handler, matchPredicate);
}
}
private static void addScriptConstraint(Project project, String name, MatchVariableConstraint constraint, SubstitutionHandler handler)
throws MalformedPatternException {
if (constraint.getScriptCodeConstraint()!= null && constraint.getScriptCodeConstraint().length() > 2) {
final String script = StringUtil.unquoteString(constraint.getScriptCodeConstraint());
final String problem = ScriptSupport.checkValidScript(script);
if (problem != null) {
throw new MalformedPatternException("Script constraint for " + constraint.getName() + " has problem " + problem);
}
addPredicate(handler, new ScriptPredicate(project, name, script));
}
}
private static void addPredicate(SubstitutionHandler handler, MatchPredicate predicate) {
if (handler.getPredicate()==null) {
handler.setPredicate(predicate);
} else {
handler.setPredicate(new AndPredicate(handler.getPredicate(), predicate));
}
}
}<|fim▁end|> |
private static class ConstantPrefixProvider implements PrefixProvider {
private final String myPrefix; |
<|file_name|>ObjectFactory.cpp<|end_file_name|><|fim▁begin|>// Torc - Copyright 2011-2013 University of Southern California. All Rights Reserved.
// $HeadURL$
// $Id$
// This program is free software: you can redistribute it and/or modify it under the terms of the
// GNU General Public License as published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
// the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with this program. If
// not, see <http://www.gnu.org/licenses/>.
#ifndef HAVE_CONFIG_H
#include "torc/generic/config.h"
#endif
#include "torc/generic/ObjectFactory.hpp"
namespace torc {
namespace generic {
<|fim▁hole|>ObjectFactory::ObjectFactory() :
Cell::Factory(),
Design::Factory(),
Library::Factory(),
InstanceArray::Factory(),
InstanceArrayMember::Factory(),
NetBundle::Factory(),
ParameterArray::Factory(),
PortBundle::Factory(),
PortBundleReference::Factory(),
Property::Factory(),
ParameterArrayElement::Factory(),
PortList::Factory(),
PortListAlias::Factory(),
Root::Factory(),
ScalarNet::Factory(),
ScalarPort::Factory(),
ScalarPortReference::Factory(),
SingleInstance::Factory(),
SingleParameter::Factory(),
Status::Factory(),
VectorNet::Factory(),
VectorNetBit::Factory(),
VectorPort::Factory(),
VectorPortBit::Factory(),
VectorPortReference::Factory(),
VectorPortBitReference::Factory(),
View::Factory(),
Written::Factory(),
Permutable::Factory(),
InterfaceJoinedInfo::Factory(),
LogicValue::Factory(),
SimulationInfo::Factory(),
Simulate::Factory(),
Apply::Factory(),
LogicalResponse::Factory(),
LogicElement::Factory(),
WaveValue::Factory(),
Timing::Factory(),
PathDelay::Factory(),
Event::Factory(),
ForbiddenEvent::Factory() {}
ObjectFactory::~ObjectFactory() throw() {}
} // namespace generic
} // namespace torc<|fim▁end|> | |
<|file_name|>remove_files.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
data = {
"default_prefix": "OSVC_COMP_REMOVE_FILES_",
"example_value": """
[
"/tmp/foo",<|fim▁hole|>""",
"description": """* Verify files and file trees are uninstalled
""",
"form_definition": """
Desc: |
A rule defining a set of files to remove, fed to the 'remove_files' compliance object.
Css: comp48
Outputs:
-
Dest: compliance variable
Class: remove_files
Type: json
Format: list
Inputs:
-
Id: path
Label: File path
DisplayModeLabel: ""
LabelCss: edit16
Mandatory: Yes
Help: You must set paths in fully qualified form.
Type: string
""",
}
import os
import sys
import re
import json
from glob import glob
import shutil
sys.path.append(os.path.dirname(__file__))
from comp import *
blacklist = [
"/",
"/root"
]
class CompRemoveFiles(CompObject):
def __init__(self, prefix=None):
CompObject.__init__(self, prefix=prefix, data=data)
def init(self):
patterns = self.get_rules()
patterns = sorted(list(set(patterns)))
self.files = self.expand_patterns(patterns)
if len(self.files) == 0:
pinfo("no files matching patterns")
raise NotApplicable
def expand_patterns(self, patterns):
l = []
for pattern in patterns:
l += glob(pattern)
return l
def fixable(self):
return RET_NA
def check_file(self, _file):
if not os.path.exists(_file):
pinfo(_file, "does not exist. on target.")
return RET_OK
perror(_file, "exists. shouldn't")
return RET_ERR
def fix_file(self, _file):
if not os.path.exists(_file):
return RET_OK
try:
if os.path.isdir(_file) and not os.path.islink(_file):
shutil.rmtree(_file)
else:
os.unlink(_file)
pinfo(_file, "deleted")
except Exception as e:
perror("failed to delete", _file, "(%s)"%str(e))
return RET_ERR
return RET_OK
def check(self):
r = 0
for _file in self.files:
r |= self.check_file(_file)
return r
def fix(self):
r = 0
for _file in self.files:
r |= self.fix_file(_file)
return r
if __name__ == "__main__":
main(CompRemoveFiles)<|fim▁end|> | "/bar/to/delete"
] |
<|file_name|>0009_auto__add_field_imagerevision_width__add_field_imagerevision_height.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
try:
from django.contrib.auth import get_user_model
except ImportError: # django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
user_orm_label = '%s.%s' % (User._meta.app_label, User._meta.object_name)
user_model_label = '%s.%s' % (User._meta.app_label, User._meta.module_name)
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'ImageRevision.width'
db.add_column('wiki_imagerevision', 'width',
self.gf('django.db.models.fields.SmallIntegerField')(default=0),
keep_default=False)
# Adding field 'ImageRevision.height'
db.add_column('wiki_imagerevision', 'height',
self.gf('django.db.models.fields.SmallIntegerField')(default=0),
keep_default=False)
def backwards(self, orm):
# Deleting field 'ImageRevision.width'
db.delete_column('wiki_imagerevision', 'width')
# Deleting field 'ImageRevision.height'
db.delete_column('wiki_imagerevision', 'height')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
user_model_label: {
'Meta': {'object_name': User.__name__, 'db_table': "'%s'" % User._meta.db_table},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'django_notify.notificationtype': {
'Meta': {'object_name': 'NotificationType', 'db_table': "'notify_notificationtype'"},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']", 'null': 'True', 'blank': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '128', 'primary_key': 'True'}),
'label': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'})
},
'django_notify.settings': {
'Meta': {'object_name': 'Settings', 'db_table': "'notify_settings'"},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'interval': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['%s']" % user_orm_label})
},
'django_notify.subscription': {
'Meta': {'object_name': 'Subscription', 'db_table': "'notify_subscription'"},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'notification_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['django_notify.NotificationType']"}),
'object_id': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True', 'blank': 'True'}),
'send_emails': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'settings': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['django_notify.Settings']"})
},
'sites.site': {
'Meta': {'ordering': "('domain',)", 'object_name': 'Site', 'db_table': "'django_site'"},
'domain': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'wiki.article': {
'Meta': {'object_name': 'Article'},
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'current_revision': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'current_set'", 'unique': 'True', 'null': 'True', 'to': "orm['wiki.ArticleRevision']"}),
'group': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.Group']", 'null': 'True', 'blank': 'True'}),
'group_read': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'group_write': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'other_read': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'other_write': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'owned_articles'", 'null': 'True', 'to': "orm['%s']" % user_orm_label})
},
'wiki.articleforobject': {
'Meta': {'unique_together': "(('content_type', 'object_id'),)", 'object_name': 'ArticleForObject'},
'article': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['wiki.Article']"}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'content_type_set_for_articleforobject'", 'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_mptt': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'object_id': ('django.db.models.fields.PositiveIntegerField', [], {})
},
'wiki.articleplugin': {
'Meta': {'object_name': 'ArticlePlugin'},
'article': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['wiki.Article']"}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'wiki.articlerevision': {
'Meta': {'ordering': "('created',)", 'unique_together': "(('article', 'revision_number'),)", 'object_name': 'ArticleRevision'},
'article': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['wiki.Article']"}),
'automatic_log': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'content': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'ip_address': ('django.db.models.fields.IPAddressField', [], {'max_length': '15', 'null': 'True', 'blank': 'True'}),
'locked': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'previous_revision': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['wiki.ArticleRevision']", 'null': 'True', 'blank': 'True'}),
'revision_number': ('django.db.models.fields.IntegerField', [], {}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '512'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['%s']" % user_orm_label, 'null': 'True', 'blank': 'True'}),
'user_message': ('django.db.models.fields.TextField', [], {'blank': 'True'})
},
'wiki.articlesubscription': {
'Meta': {'object_name': 'ArticleSubscription', '_ormbases': ['wiki.ArticlePlugin', 'django_notify.Subscription']},
'articleplugin_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['wiki.ArticlePlugin']", 'unique': 'True', 'primary_key': 'True'}),
'subscription_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['django_notify.Subscription']", 'unique': 'True'})
},
'wiki.attachment': {
'Meta': {'object_name': 'Attachment', '_ormbases': ['wiki.ReusablePlugin']},
'current_revision': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'current_set'", 'unique': 'True', 'null': 'True', 'to': "orm['wiki.AttachmentRevision']"}),
'original_filename': ('django.db.models.fields.CharField', [], {'max_length': '256', 'null': 'True', 'blank': 'True'}),
'reusableplugin_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['wiki.ReusablePlugin']", 'unique': 'True', 'primary_key': 'True'})
},
'wiki.attachmentrevision': {
'Meta': {'ordering': "('created',)", 'object_name': 'AttachmentRevision'},
'attachment': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['wiki.Attachment']"}),
'automatic_log': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'file': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'ip_address': ('django.db.models.fields.IPAddressField', [], {'max_length': '15', 'null': 'True', 'blank': 'True'}),
'locked': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'previous_revision': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['wiki.AttachmentRevision']", 'null': 'True', 'blank': 'True'}),
'revision_number': ('django.db.models.fields.IntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['%s']" % user_orm_label, 'null': 'True', 'blank': 'True'}),
'user_message': ('django.db.models.fields.TextField', [], {'blank': 'True'})
},<|fim▁hole|> 'wiki.imagerevision': {
'Meta': {'object_name': 'ImageRevision', '_ormbases': ['wiki.RevisionPluginRevision']},
'height': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '2000'}),
'revisionpluginrevision_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['wiki.RevisionPluginRevision']", 'unique': 'True', 'primary_key': 'True'}),
'width': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'})
},
'wiki.reusableplugin': {
'Meta': {'object_name': 'ReusablePlugin', '_ormbases': ['wiki.ArticlePlugin']},
'articleplugin_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['wiki.ArticlePlugin']", 'unique': 'True', 'primary_key': 'True'}),
'articles': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'shared_plugins_set'", 'symmetrical': 'False', 'to': "orm['wiki.Article']"})
},
'wiki.revisionplugin': {
'Meta': {'object_name': 'RevisionPlugin', '_ormbases': ['wiki.ArticlePlugin']},
'articleplugin_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['wiki.ArticlePlugin']", 'unique': 'True', 'primary_key': 'True'}),
'current_revision': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'plugin_set'", 'unique': 'True', 'null': 'True', 'to': "orm['wiki.RevisionPluginRevision']"})
},
'wiki.revisionpluginrevision': {
'Meta': {'object_name': 'RevisionPluginRevision'},
'automatic_log': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'ip_address': ('django.db.models.fields.IPAddressField', [], {'max_length': '15', 'null': 'True', 'blank': 'True'}),
'locked': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'plugin': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'revision_set'", 'to': "orm['wiki.RevisionPlugin']"}),
'previous_revision': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['wiki.RevisionPluginRevision']", 'null': 'True', 'blank': 'True'}),
'revision_number': ('django.db.models.fields.IntegerField', [], {}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['%s']" % user_orm_label, 'null': 'True', 'blank': 'True'}),
'user_message': ('django.db.models.fields.TextField', [], {'blank': 'True'})
},
'wiki.simpleplugin': {
'Meta': {'object_name': 'SimplePlugin', '_ormbases': ['wiki.ArticlePlugin']},
'article_revision': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['wiki.ArticleRevision']"}),
'articleplugin_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['wiki.ArticlePlugin']", 'unique': 'True', 'primary_key': 'True'})
},
'wiki.urlpath': {
'Meta': {'unique_together': "(('site', 'parent', 'slug'),)", 'object_name': 'URLPath'},
'article': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['wiki.Article']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'parent': ('mptt.fields.TreeForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['wiki.URLPath']"}),
'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sites.Site']"}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'})
}
}
complete_apps = ['wiki']<|fim▁end|> | 'wiki.image': {
'Meta': {'object_name': 'Image', '_ormbases': ['wiki.RevisionPlugin']},
'revisionplugin_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['wiki.RevisionPlugin']", 'unique': 'True', 'primary_key': 'True'})
}, |
<|file_name|>.eslintrc.js<|end_file_name|><|fim▁begin|>module.exports = {
env: {
mocha: true
},
plugins: [
'mocha'
]<|fim▁hole|><|fim▁end|> | }; |
<|file_name|>hmr-reducer.js<|end_file_name|><|fim▁begin|>"use strict";
exports.hmrReducer = function (appReducer) { return function (state, _a) {
var type = _a.type, payload = _a.payload;
switch (type) {<|fim▁hole|> case 'HMR_SET_STATE': return payload;
default: return appReducer(state, { type: type, payload: payload });
}
}; };
//# sourceMappingURL=hmr-reducer.js.map<|fim▁end|> | |
<|file_name|>archive.py<|end_file_name|><|fim▁begin|>import os
import logging
import boto3
import mimetypes
from datetime import datetime
from morphium.util import env, TAG_LATEST
log = logging.getLogger(__name__)
config = {}
class Archive(object):
"""A scraper archive on S3. This is called when a scraper has generated a
file which needs to be backed up to a bucket."""
def __init__(self, bucket=None, prefix=None):
self.tag = datetime.utcnow().date().isoformat()
self.bucket = bucket or env('aws_bucket')
self.prefix = prefix or 'data'
@property
def client(self):
if not hasattr(self, '_client'):
if self.bucket is None:
log.warning("No $AWS_BUCKET, skipping upload.")
self._client = None
return None
access_key = env('aws_access_key_id')<|fim▁hole|> self._client = None
return None
secret_key = env('aws_secret_access_key')
if secret_key is None:
log.warning("No $AWS_SECRET_ACCESS_KEY, skipping upload.")
self._client = None
return None
session = boto3.Session(aws_access_key_id=access_key,
aws_secret_access_key=secret_key)
self._client = session.client('s3')
return self._client
def upload_file(self, source_path, file_name=None, mime_type=None):
"""Upload a file to the given bucket."""
if self.client is None:
return
if file_name is None:
file_name = os.path.basename(source_path)
if mime_type is None:
mime_type, _ = mimetypes.guess_type(file_name)
mime_type = mime_type or 'application/octet-stream'
key_name = os.path.join(self.prefix, self.tag, file_name)
log.info("Uploading [%s]: %s", self.bucket, key_name)
args = {
'ContentType': mime_type,
'ACL': 'public-read',
}
self.client.upload_file(source_path, self.bucket, key_name,
ExtraArgs=args)
copy_name = os.path.join(self.prefix, TAG_LATEST, file_name)
copy_source = {'Key': key_name, 'Bucket': self.bucket}
self.client.copy(copy_source, self.bucket, copy_name,
ExtraArgs=args)
return 'http://%s/%s' % (self.bucket, key_name)<|fim▁end|> | if access_key is None:
log.warning("No $AWS_ACCESS_KEY_ID, skipping upload.") |
<|file_name|>E-value-distribution.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2
import sys, getopt
import re
import time
def get_option():
opts, args = getopt.getopt(sys.argv[1:], "hi:o:")
input_file = ""
output_file = ""
h = ""
for op, value in opts:
if op == "-i":
input_file = value
elif op == "-o":
output_file = value
elif op == "-h":
h = "E-value distribution.\n-i : inputfile\n-o : outputfile\n"
return input_file,output_file,h
def main(input_file, output_file):<|fim▁hole|> o = a = b = c = d = e = g = 0
fout = open(output_file, 'w')
with open (input_file) as f:
for i in f:
i = float(i[:-1])
if i == 0:
o +=1
elif i < float(1e-150):
a +=1
elif i < float(1e-100):
b +=1
elif i < float(1e-50):
c +=1
elif i < 1e-10:
d +=1
else :
g +=1
out = str(o) + " " + str(a) + " " + str(b) + " " + str(c) + " " + str(d) +" " + str(g)
fout.write(out)
fout.close()
if __name__ == "__main__":
time_start = time.time()
input_file,output_file,h = get_option()
if str(h) == "":
main(input_file, output_file)
print ("time: " + str (time.time()-time_start))
else:
print (h)<|fim▁end|> | |
<|file_name|>letters.py<|end_file_name|><|fim▁begin|>print " A BBBBBB CCCC DDDDD EEEEEEE FFFFFFF GGGG H H IIIII JJJJJJ"
print " A A B B C C D D E F G G H H I J"
print " A A B B C D D E F G H H I J"
print "AAAAAAA BBBBBB C D D EEEEE FFFFF G GGG HHHHHHH I J"
print "A A B B C D D E F G G H H I J"<|fim▁hole|><|fim▁end|> | print "A A B B C C D D E F G G H H I J J"
print "A A BBBBBB CCCC DDDDD EEEEEEE F GGGG H H IIIII JJJJ" |
<|file_name|>index.d.ts<|end_file_name|><|fim▁begin|>// Type definitions for truncate-middle 1.0
// Project: https://github.com/kahwee/truncate-middle#readme
// Definitions by: Gary King <https://github.com/garyking>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare function truncateMiddle(text: string | null, frontLength?: number, backLength?: number, ellipsis?: string): string;
<|fim▁hole|>export = truncateMiddle;<|fim▁end|> | |
<|file_name|>app.d.ts<|end_file_name|><|fim▁begin|><|fim▁hole|>}<|fim▁end|> | declare module "jquery-ui/datepicker" {
export = $; |
<|file_name|>pascals-triangle.rs<|end_file_name|><|fim▁begin|>extern crate pascals_triangle;
use pascals_triangle::*;
#[test]
fn no_rows() {
let pt = PascalsTriangle::new(0);
let expected: Vec<Vec<u32>> = Vec::new();
assert_eq!(expected, pt.rows());
}
#[test]
fn one_row() {
let pt = PascalsTriangle::new(1);
let expected: Vec<Vec<u32>> = vec![vec![1]];
assert_eq!(expected, pt.rows());
}
#[test]
fn two_rows() {
let pt = PascalsTriangle::new(2);
let expected: Vec<Vec<u32>> = vec![vec![1], vec![1, 1]];<|fim▁hole|>
#[test]
fn three_rows() {
let pt = PascalsTriangle::new(3);
let expected: Vec<Vec<u32>> = vec![vec![1], vec![1, 1], vec![1, 2, 1]];
assert_eq!(expected, pt.rows());
}
#[test]
fn last_of_four_rows() {
let pt = PascalsTriangle::new(4);
let expected: Vec<u32> = vec![1, 3, 3, 1];
assert_eq!(expected, pt.rows().pop().unwrap());
}<|fim▁end|> | assert_eq!(expected, pt.rows());
} |
<|file_name|>svn_fetch.py<|end_file_name|><|fim▁begin|>##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, [email protected], All rights reserved.
# LLNL-CODE-647188<|fim▁hole|># For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
import os
import pytest
import spack
from llnl.util.filesystem import join_path, touch, working_dir
from spack.spec import Spec
from spack.version import ver
from spack.util.executable import which
pytestmark = pytest.mark.skipif(
not which('svn'), reason='requires subversion to be installed')
@pytest.mark.parametrize("type_of_test", ['default', 'rev0'])
@pytest.mark.parametrize("secure", [True, False])
def test_fetch(
type_of_test,
secure,
mock_svn_repository,
config,
refresh_builtin_mock
):
"""Tries to:
1. Fetch the repo using a fetch strategy constructed with
supplied args (they depend on type_of_test).
2. Check if the test_file is in the checked out repository.
3. Assert that the repository is at the revision supplied.
4. Add and remove some files, then reset the repo, and
ensure it's all there again.
"""
# Retrieve the right test parameters
t = mock_svn_repository.checks[type_of_test]
h = mock_svn_repository.hash
# Construct the package under test
spec = Spec('svn-test')
spec.concretize()
pkg = spack.repo.get(spec)
pkg.versions[ver('svn')] = t.args
# Enter the stage directory and check some properties
with pkg.stage:
try:
spack.insecure = secure
pkg.do_stage()
finally:
spack.insecure = False
with working_dir(pkg.stage.source_path):
assert h() == t.revision
file_path = join_path(pkg.stage.source_path, t.file)
assert os.path.isdir(pkg.stage.source_path)
assert os.path.isfile(file_path)
os.unlink(file_path)
assert not os.path.isfile(file_path)
untracked_file = 'foobarbaz'
touch(untracked_file)
assert os.path.isfile(untracked_file)
pkg.do_restage()
assert not os.path.isfile(untracked_file)
assert os.path.isdir(pkg.stage.source_path)
assert os.path.isfile(file_path)
assert h() == t.revision<|fim▁end|> | # |
<|file_name|>filter.go<|end_file_name|><|fim▁begin|>package netlink
import (
"fmt"
"net"
)
type Filter interface {
Attrs() *FilterAttrs
Type() string
}
// FilterAttrs represents a netlink filter. A filter is associated with a link,
// has a handle and a parent. The root filter of a device should have a
// parent == HANDLE_ROOT.
type FilterAttrs struct {
LinkIndex int
Handle uint32
Parent uint32
Priority uint16 // lower is higher priority
Protocol uint16 // unix.ETH_P_*
}
func (q FilterAttrs) String() string {
return fmt.Sprintf("{LinkIndex: %d, Handle: %s, Parent: %s, Priority: %d, Protocol: %d}", q.LinkIndex, HandleStr(q.Handle), HandleStr(q.Parent), q.Priority, q.Protocol)
}
type TcAct int32
const (
TC_ACT_UNSPEC TcAct = -1
TC_ACT_OK TcAct = 0
TC_ACT_RECLASSIFY TcAct = 1
TC_ACT_SHOT TcAct = 2
TC_ACT_PIPE TcAct = 3
TC_ACT_STOLEN TcAct = 4
TC_ACT_QUEUED TcAct = 5
TC_ACT_REPEAT TcAct = 6
TC_ACT_REDIRECT TcAct = 7
TC_ACT_JUMP TcAct = 0x10000000
)
func (a TcAct) String() string {
switch a {
case TC_ACT_UNSPEC:
return "unspec"
case TC_ACT_OK:
return "ok"
case TC_ACT_RECLASSIFY:
return "reclassify"
case TC_ACT_SHOT:
return "shot"
case TC_ACT_PIPE:
return "pipe"
case TC_ACT_STOLEN:
return "stolen"
case TC_ACT_QUEUED:
return "queued"
case TC_ACT_REPEAT:
return "repeat"
case TC_ACT_REDIRECT:
return "redirect"
case TC_ACT_JUMP:
return "jump"
}
return fmt.Sprintf("0x%x", int32(a))
}
type TcPolAct int32
const (
TC_POLICE_UNSPEC TcPolAct = TcPolAct(TC_ACT_UNSPEC)
TC_POLICE_OK TcPolAct = TcPolAct(TC_ACT_OK)
TC_POLICE_RECLASSIFY TcPolAct = TcPolAct(TC_ACT_RECLASSIFY)
TC_POLICE_SHOT TcPolAct = TcPolAct(TC_ACT_SHOT)
TC_POLICE_PIPE TcPolAct = TcPolAct(TC_ACT_PIPE)
)
func (a TcPolAct) String() string {
switch a {
case TC_POLICE_UNSPEC:
return "unspec"
case TC_POLICE_OK:
return "ok"
case TC_POLICE_RECLASSIFY:
return "reclassify"
case TC_POLICE_SHOT:
return "shot"
case TC_POLICE_PIPE:
return "pipe"
}
return fmt.Sprintf("0x%x", int32(a))
}
type ActionAttrs struct {
Index int
Capab int
Action TcAct
Refcnt int
Bindcnt int
}
func (q ActionAttrs) String() string {
return fmt.Sprintf("{Index: %d, Capab: %x, Action: %s, Refcnt: %d, Bindcnt: %d}", q.Index, q.Capab, q.Action.String(), q.Refcnt, q.Bindcnt)
}
// Action represents an action in any supported filter.
type Action interface {
Attrs() *ActionAttrs
Type() string
}
type GenericAction struct {
ActionAttrs
}
func (action *GenericAction) Type() string {
return "generic"
}
func (action *GenericAction) Attrs() *ActionAttrs {
return &action.ActionAttrs
}
type BpfAction struct {
ActionAttrs
Fd int
Name string
}
func (action *BpfAction) Type() string {
return "bpf"
}
func (action *BpfAction) Attrs() *ActionAttrs {
return &action.ActionAttrs
}<|fim▁hole|> Zone uint16
}
func (action *ConnmarkAction) Type() string {
return "connmark"
}
func (action *ConnmarkAction) Attrs() *ActionAttrs {
return &action.ActionAttrs
}
func NewConnmarkAction() *ConnmarkAction {
return &ConnmarkAction{
ActionAttrs: ActionAttrs{
Action: TC_ACT_PIPE,
},
}
}
type MirredAct uint8
func (a MirredAct) String() string {
switch a {
case TCA_EGRESS_REDIR:
return "egress redir"
case TCA_EGRESS_MIRROR:
return "egress mirror"
case TCA_INGRESS_REDIR:
return "ingress redir"
case TCA_INGRESS_MIRROR:
return "ingress mirror"
}
return "unknown"
}
const (
TCA_EGRESS_REDIR MirredAct = 1 /* packet redirect to EGRESS*/
TCA_EGRESS_MIRROR MirredAct = 2 /* mirror packet to EGRESS */
TCA_INGRESS_REDIR MirredAct = 3 /* packet redirect to INGRESS*/
TCA_INGRESS_MIRROR MirredAct = 4 /* mirror packet to INGRESS */
)
type MirredAction struct {
ActionAttrs
MirredAction MirredAct
Ifindex int
}
func (action *MirredAction) Type() string {
return "mirred"
}
func (action *MirredAction) Attrs() *ActionAttrs {
return &action.ActionAttrs
}
func NewMirredAction(redirIndex int) *MirredAction {
return &MirredAction{
ActionAttrs: ActionAttrs{
Action: TC_ACT_STOLEN,
},
MirredAction: TCA_EGRESS_REDIR,
Ifindex: redirIndex,
}
}
type TunnelKeyAct int8
const (
TCA_TUNNEL_KEY_SET TunnelKeyAct = 1 // set tunnel key
TCA_TUNNEL_KEY_UNSET TunnelKeyAct = 2 // unset tunnel key
)
type TunnelKeyAction struct {
ActionAttrs
Action TunnelKeyAct
SrcAddr net.IP
DstAddr net.IP
KeyID uint32
DestPort uint16
}
func (action *TunnelKeyAction) Type() string {
return "tunnel_key"
}
func (action *TunnelKeyAction) Attrs() *ActionAttrs {
return &action.ActionAttrs
}
func NewTunnelKeyAction() *TunnelKeyAction {
return &TunnelKeyAction{
ActionAttrs: ActionAttrs{
Action: TC_ACT_PIPE,
},
}
}
type SkbEditAction struct {
ActionAttrs
QueueMapping *uint16
PType *uint16
Priority *uint32
Mark *uint32
}
func (action *SkbEditAction) Type() string {
return "skbedit"
}
func (action *SkbEditAction) Attrs() *ActionAttrs {
return &action.ActionAttrs
}
func NewSkbEditAction() *SkbEditAction {
return &SkbEditAction{
ActionAttrs: ActionAttrs{
Action: TC_ACT_PIPE,
},
}
}
type PoliceAction struct {
ActionAttrs
Rate uint32 // in byte per second
Burst uint32 // in byte
RCellLog int
Mtu uint32
Mpu uint16 // in byte
PeakRate uint32 // in byte per second
PCellLog int
AvRate uint32 // in byte per second
Overhead uint16
LinkLayer int
ExceedAction TcPolAct
NotExceedAction TcPolAct
}
func (action *PoliceAction) Type() string {
return "police"
}
func (action *PoliceAction) Attrs() *ActionAttrs {
return &action.ActionAttrs
}
func NewPoliceAction() *PoliceAction {
return &PoliceAction{
RCellLog: -1,
PCellLog: -1,
LinkLayer: 1, // ETHERNET
ExceedAction: TC_POLICE_RECLASSIFY,
NotExceedAction: TC_POLICE_OK,
}
}
// MatchAll filters match all packets
type MatchAll struct {
FilterAttrs
ClassId uint32
Actions []Action
}
func (filter *MatchAll) Attrs() *FilterAttrs {
return &filter.FilterAttrs
}
func (filter *MatchAll) Type() string {
return "matchall"
}
type FwFilter struct {
FilterAttrs
ClassId uint32
InDev string
Mask uint32
Police *PoliceAction
}
func (filter *FwFilter) Attrs() *FilterAttrs {
return &filter.FilterAttrs
}
func (filter *FwFilter) Type() string {
return "fw"
}
type BpfFilter struct {
FilterAttrs
ClassId uint32
Fd int
Name string
DirectAction bool
Id int
Tag string
}
func (filter *BpfFilter) Type() string {
return "bpf"
}
func (filter *BpfFilter) Attrs() *FilterAttrs {
return &filter.FilterAttrs
}
// GenericFilter filters represent types that are not currently understood
// by this netlink library.
type GenericFilter struct {
FilterAttrs
FilterType string
}
func (filter *GenericFilter) Attrs() *FilterAttrs {
return &filter.FilterAttrs
}
func (filter *GenericFilter) Type() string {
return filter.FilterType
}<|fim▁end|> |
type ConnmarkAction struct {
ActionAttrs |
<|file_name|>unpause.go<|end_file_name|><|fim▁begin|>package daemon
import (
derr "github.com/docker/docker/api/errors"
)
// ContainerUnpause unpauses a container
func (daemon *Daemon) ContainerUnpause(name string) error {
container, err := daemon.Get(name)
if err != nil {<|fim▁hole|> }
if err := container.unpause(); err != nil {
return derr.ErrorCodeCantUnpause.WithArgs(name, err)
}
return nil
}<|fim▁end|> | return err |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A (mostly) lock-free concurrent work-stealing deque
//!
//! This module contains an implementation of the Chase-Lev work stealing deque
//! described in "Dynamic Circular Work-Stealing Deque". The implementation is
//! heavily based on the pseudocode found in the paper.
//!
//! This implementation does not want to have the restriction of a garbage
//! collector for reclamation of buffers, and instead it uses a shared pool of
//! buffers. This shared pool is required for correctness in this
//! implementation.
//!
//! The only lock-synchronized portions of this deque are the buffer allocation
//! and deallocation portions. Otherwise all operations are lock-free.
//!
//! # Example
//!
//! use util::deque::BufferPool;
//!
//! let mut pool = BufferPool::new();
//! let (mut worker, mut stealer) = pool.deque();
//!
//! // Only the worker may push/pop
//! worker.push(1i);
//! worker.pop();
//!
//! // Stealers take data from the other end of the deque
//! worker.push(1i);
//! stealer.steal();
//!
//! // Stealers can be cloned to have many stealers stealing in parallel
//! worker.push(1i);
//! let mut stealer2 = stealer.clone();
//! stealer2.steal();
// NB: the "buffer pool" strategy is not done for speed, but rather for
// correctness. For more info, see the comment on `swap_buffer`
// FIXME: all atomic operations in this module use a SeqCst ordering. That is
// probably overkill
pub use self::Stolen::{Empty, Abort, Data};
use alloc::arc::Arc;
use alloc::heap::{allocate, deallocate};
use std::marker;
use std::mem::{forget, min_align_of, size_of, transmute};
use std::ptr;
use std::sync::Mutex;
use std::sync::atomic::{AtomicIsize, AtomicPtr};
use std::sync::atomic::Ordering::SeqCst;
// Once the queue is less than 1/K full, then it will be downsized. Note that
// the deque requires that this number be less than 2.
static K: isize = 4;
// Minimum number of bits that a buffer size should be. No buffer will resize to
// under this value, and all deques will initially contain a buffer of this
// size.
//
// The size in question is 1 << MIN_BITS
static MIN_BITS: usize = 7;
struct Deque<T> {
bottom: AtomicIsize,
top: AtomicIsize,
array: AtomicPtr<Buffer<T>>,
pool: BufferPool<T>,
}
unsafe impl<T> Send for Deque<T> {}
/// Worker half of the work-stealing deque. This worker has exclusive access to
/// one side of the deque, and uses `push` and `pop` method to manipulate it.
///
/// There may only be one worker per deque.
pub struct Worker<T> {
deque: Arc<Deque<T>>,
}
impl<T> !marker::Sync for Worker<T> {}
/// The stealing half of the work-stealing deque. Stealers have access to the
/// opposite end of the deque from the worker, and they only have access to the<|fim▁hole|> deque: Arc<Deque<T>>,
}
impl<T> !marker::Sync for Stealer<T> {}
/// When stealing some data, this is an enumeration of the possible outcomes.
#[derive(PartialEq, Debug)]
pub enum Stolen<T> {
/// The deque was empty at the time of stealing
Empty,
/// The stealer lost the race for stealing data, and a retry may return more
/// data.
Abort,
/// The stealer has successfully stolen some data.
Data(T),
}
/// The allocation pool for buffers used by work-stealing deques. Right now this
/// structure is used for reclamation of memory after it is no longer in use by
/// deques.
///
/// This data structure is protected by a mutex, but it is rarely used. Deques
/// will only use this structure when allocating a new buffer or deallocating a
/// previous one.
pub struct BufferPool<T> {
// FIXME: This entire file was copied from std::sync::deque before it was removed,
// I converted `Exclusive` to `Mutex` here, but that might not be ideal
pool: Arc<Mutex<Vec<Box<Buffer<T>>>>>,
}
/// An internal buffer used by the chase-lev deque. This structure is actually
/// implemented as a circular buffer, and is used as the intermediate storage of
/// the data in the deque.
///
/// This type is implemented with *T instead of Vec<T> for two reasons:
///
/// 1. There is nothing safe about using this buffer. This easily allows the
/// same value to be read twice in to rust, and there is nothing to
/// prevent this. The usage by the deque must ensure that one of the
/// values is forgotten. Furthermore, we only ever want to manually run
/// destructors for values in this buffer (on drop) because the bounds
/// are defined by the deque it's owned by.
///
/// 2. We can certainly avoid bounds checks using *T instead of Vec<T>, although
/// LLVM is probably pretty good at doing this already.
struct Buffer<T> {
storage: *const T,
log_size: usize,
}
unsafe impl<T: 'static> Send for Buffer<T> { }
impl<T: Send + 'static> BufferPool<T> {
/// Allocates a new buffer pool which in turn can be used to allocate new
/// deques.
pub fn new() -> BufferPool<T> {
BufferPool { pool: Arc::new(Mutex::new(Vec::new())) }
}
/// Allocates a new work-stealing deque which will send/receiving memory to
/// and from this buffer pool.
pub fn deque(&self) -> (Worker<T>, Stealer<T>) {
let a = Arc::new(Deque::new(self.clone()));
let b = a.clone();
(Worker { deque: a }, Stealer { deque: b })
}
fn alloc(&mut self, bits: usize) -> Box<Buffer<T>> {
unsafe {
let mut pool = self.pool.lock().unwrap();
match pool.iter().position(|x| x.size() >= (1 << bits)) {
Some(i) => pool.remove(i),
None => box Buffer::new(bits)
}
}
}
}
impl<T> BufferPool<T> {
fn free(&self, buf: Box<Buffer<T>>) {
let mut pool = self.pool.lock().unwrap();
match pool.iter().position(|v| v.size() > buf.size()) {
Some(i) => pool.insert(i, buf),
None => pool.push(buf),
}
}
}
impl<T: Send> Clone for BufferPool<T> {
fn clone(&self) -> BufferPool<T> { BufferPool { pool: self.pool.clone() } }
}
impl<T: Send + 'static> Worker<T> {
/// Pushes data onto the front of this work queue.
pub fn push(&self, t: T) {
unsafe { self.deque.push(t) }
}
/// Pops data off the front of the work queue, returning `None` on an empty
/// queue.
pub fn pop(&self) -> Option<T> {
unsafe { self.deque.pop() }
}
/// Gets access to the buffer pool that this worker is attached to. This can
/// be used to create more deques which share the same buffer pool as this
/// deque.
pub fn pool<'a>(&'a self) -> &'a BufferPool<T> {
&self.deque.pool
}
}
impl<T: Send + 'static> Stealer<T> {
/// Steals work off the end of the queue (opposite of the worker's end)
pub fn steal(&self) -> Stolen<T> {
unsafe { self.deque.steal() }
}
/// Gets access to the buffer pool that this stealer is attached to. This
/// can be used to create more deques which share the same buffer pool as
/// this deque.
pub fn pool<'a>(&'a self) -> &'a BufferPool<T> {
&self.deque.pool
}
}
impl<T: Send> Clone for Stealer<T> {
fn clone(&self) -> Stealer<T> {
Stealer { deque: self.deque.clone() }
}
}
// Almost all of this code can be found directly in the paper so I'm not
// personally going to heavily comment what's going on here.
impl<T: Send + 'static> Deque<T> {
fn new(mut pool: BufferPool<T>) -> Deque<T> {
let buf = pool.alloc(MIN_BITS);
Deque {
bottom: AtomicIsize::new(0),
top: AtomicIsize::new(0),
array: AtomicPtr::new(unsafe { transmute(buf) }),
pool: pool,
}
}
unsafe fn push(&self, data: T) {
let mut b = self.bottom.load(SeqCst);
let t = self.top.load(SeqCst);
let mut a = self.array.load(SeqCst);
let size = b - t;
if size >= (*a).size() - 1 {
// You won't find this code in the chase-lev deque paper. This is
// alluded to in a small footnote, however. We always free a buffer
// when growing in order to prevent leaks.
a = self.swap_buffer(b, a, (*a).resize(b, t, 1));
b = self.bottom.load(SeqCst);
}
(*a).put(b, data);
self.bottom.store(b + 1, SeqCst);
}
unsafe fn pop(&self) -> Option<T> {
let b = self.bottom.load(SeqCst);
let a = self.array.load(SeqCst);
let b = b - 1;
self.bottom.store(b, SeqCst);
let t = self.top.load(SeqCst);
let size = b - t;
if size < 0 {
self.bottom.store(t, SeqCst);
return None;
}
let data = (*a).get(b);
if size > 0 {
self.maybe_shrink(b, t);
return Some(data);
}
if self.top.compare_and_swap(t, t + 1, SeqCst) == t {
self.bottom.store(t + 1, SeqCst);
return Some(data);
} else {
self.bottom.store(t + 1, SeqCst);
forget(data); // someone else stole this value
return None;
}
}
unsafe fn steal(&self) -> Stolen<T> {
let t = self.top.load(SeqCst);
let old = self.array.load(SeqCst);
let b = self.bottom.load(SeqCst);
let a = self.array.load(SeqCst);
let size = b - t;
if size <= 0 { return Empty }
if size % (*a).size() == 0 {
if a == old && t == self.top.load(SeqCst) {
return Empty
}
return Abort
}
let data = (*a).get(t);
if self.top.compare_and_swap(t, t + 1, SeqCst) == t {
Data(data)
} else {
forget(data); // someone else stole this value
Abort
}
}
unsafe fn maybe_shrink(&self, b: isize, t: isize) {
let a = self.array.load(SeqCst);
if b - t < (*a).size() / K && b - t > (1 << MIN_BITS) {
self.swap_buffer(b, a, (*a).resize(b, t, -1));
}
}
// Helper routine not mentioned in the paper which is used in growing and
// shrinking buffers to swap in a new buffer into place. As a bit of a
// recap, the whole point that we need a buffer pool rather than just
// calling malloc/free directly is that stealers can continue using buffers
// after this method has called 'free' on it. The continued usage is simply
// a read followed by a forget, but we must make sure that the memory can
// continue to be read after we flag this buffer for reclamation.
unsafe fn swap_buffer(&self, b: isize, old: *mut Buffer<T>,
buf: Buffer<T>) -> *mut Buffer<T> {
let newbuf: *mut Buffer<T> = transmute(box buf);
self.array.store(newbuf, SeqCst);
let ss = (*newbuf).size();
self.bottom.store(b + ss, SeqCst);
let t = self.top.load(SeqCst);
if self.top.compare_and_swap(t, t + ss, SeqCst) != t {
self.bottom.store(b, SeqCst);
}
self.pool.free(transmute(old));
return newbuf;
}
}
impl<T> Drop for Deque<T> {
fn drop(&mut self) {
let t = self.top.load(SeqCst);
let b = self.bottom.load(SeqCst);
let a = self.array.load(SeqCst);
// Free whatever is leftover in the dequeue, and then move the buffer
// back into the pool.
for i in t..b {
let _: T = unsafe { (*a).get(i) };
}
self.pool.free(unsafe { transmute(a) });
}
}
#[inline]
fn buffer_alloc_size<T>(log_size: usize) -> usize {
(1 << log_size) * size_of::<T>()
}
impl<T> Buffer<T> {
unsafe fn new(log_size: usize) -> Buffer<T> {
let size = buffer_alloc_size::<T>(log_size);
let buffer = allocate(size, min_align_of::<T>());
if buffer.is_null() { ::alloc::oom() }
Buffer {
storage: buffer as *const T,
log_size: log_size,
}
}
fn size(&self) -> isize { 1 << self.log_size }
// Apparently LLVM cannot optimize (foo % (1 << bar)) into this implicitly
fn mask(&self) -> isize { (1 << self.log_size) - 1 }
unsafe fn elem(&self, i: isize) -> *const T {
self.storage.offset(i & self.mask())
}
// This does not protect against loading duplicate values of the same cell,
// nor does this clear out the contents contained within. Hence, this is a
// very unsafe method which the caller needs to treat specially in case a
// race is lost.
unsafe fn get(&self, i: isize) -> T {
ptr::read(self.elem(i))
}
// Unsafe because this unsafely overwrites possibly uninitialized or
// initialized data.
unsafe fn put(&self, i: isize, t: T) {
ptr::write(self.elem(i) as *mut T, t);
}
// Again, unsafe because this has incredibly dubious ownership violations.
// It is assumed that this buffer is immediately dropped.
unsafe fn resize(&self, b: isize, t: isize, delta: isize) -> Buffer<T> {
// NB: not entirely obvious, but thanks to 2's complement,
// casting delta to usize and then adding gives the desired
// effect.
let buf = Buffer::new(self.log_size.wrapping_add(delta as usize));
for i in t..b {
buf.put(i, self.get(i));
}
return buf;
}
}
impl<T> Drop for Buffer<T> {
fn drop(&mut self) {
// It is assumed that all buffers are empty on drop.
let size = buffer_alloc_size::<T>(self.log_size);
unsafe { deallocate(self.storage as *mut u8, size, min_align_of::<T>()) }
}
}<|fim▁end|> | /// `steal` method.
pub struct Stealer<T> { |
<|file_name|>save_movie.py<|end_file_name|><|fim▁begin|>"""
Create movie from MEG inverse solution
=======================================
Data were computed using mne-python (http://martinos.org/mne)
"""
import os
import numpy as np
from surfer import Brain
from surfer.io import read_stc
print(__doc__)
"""
create Brain object for visualization
"""
brain = Brain('fsaverage', 'split', 'inflated', size=(800, 400))
"""
read and display MNE dSPM inverse solution
"""
stc_fname = os.path.join('example_data', 'meg_source_estimate-%s.stc')
for hemi in ['lh', 'rh']:
stc = read_stc(stc_fname % hemi)
data = stc['data']
times = np.arange(data.shape[1]) * stc['tstep'] + stc['tmin']<|fim▁hole|> smoothing_steps=10, time=times, hemi=hemi,
time_label=lambda t: '%s ms' % int(round(t * 1e3)))
"""
scale colormap
"""
brain.scale_data_colormap(fmin=13, fmid=18, fmax=22, transparent=True)
"""
Save a movie. Use a large value for time_dilation because the sample stc only
covers 30 ms.
"""
brain.save_movie('example_current.mov', time_dilation=30)
brain.close()<|fim▁end|> | brain.add_data(data, colormap='hot', vertices=stc['vertices'], |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.