text
stringlengths 2
100k
| meta
dict |
---|---|
// mksyscall.pl -l32 -netbsd -tags netbsd,386 syscall_bsd.go syscall_netbsd.go syscall_netbsd_386.go
// Code generated by the command above; see README.md. DO NOT EDIT.
// +build netbsd,386
package unix
import (
"syscall"
"unsafe"
)
var _ syscall.Errno
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getgroups(ngid int, gid *_Gid_t) (n int, err error) {
r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func setgroups(ngid int, gid *_Gid_t) (err error) {
_, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) {
r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0)
wpid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) {
r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)))
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) {
_, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) {
_, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func socket(domain int, typ int, proto int) (fd int, err error) {
r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto))
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) {
_, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) {
_, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) {
_, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) {
_, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Shutdown(s int, how int) (err error) {
_, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) {
_, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) {
var _p0 unsafe.Pointer
if len(buf) > 0 {
_p0 = unsafe.Pointer(&buf[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) {
r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) {
r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) {
r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) {
var _p0 unsafe.Pointer
if len(mib) > 0 {
_p0 = unsafe.Pointer(&mib[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func utimes(path string, timeval *[2]Timeval) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func futimes(fd int, timeval *[2]Timeval) (err error) {
_, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func fcntl(fd int, cmd int, arg int) (val int, err error) {
r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg))
val = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func poll(fds *PollFd, nfds int, timeout int) (n int, err error) {
r0, _, e1 := Syscall(SYS_POLL, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Madvise(b []byte, behav int) (err error) {
var _p0 unsafe.Pointer
if len(b) > 0 {
_p0 = unsafe.Pointer(&b[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(behav))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mlock(b []byte) (err error) {
var _p0 unsafe.Pointer
if len(b) > 0 {
_p0 = unsafe.Pointer(&b[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mlockall(flags int) (err error) {
_, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mprotect(b []byte, prot int) (err error) {
var _p0 unsafe.Pointer
if len(b) > 0 {
_p0 = unsafe.Pointer(&b[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Msync(b []byte, flags int) (err error) {
var _p0 unsafe.Pointer
if len(b) > 0 {
_p0 = unsafe.Pointer(&b[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall(SYS_MSYNC, uintptr(_p0), uintptr(len(b)), uintptr(flags))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Munlock(b []byte) (err error) {
var _p0 unsafe.Pointer
if len(b) > 0 {
_p0 = unsafe.Pointer(&b[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Munlockall() (err error) {
_, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func pipe() (fd1 int, fd2 int, err error) {
r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0)
fd1 = int(r0)
fd2 = int(r1)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getdents(fd int, buf []byte) (n int, err error) {
var _p0 unsafe.Pointer
if len(buf) > 0 {
_p0 = unsafe.Pointer(&buf[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_GETDENTS, uintptr(fd), uintptr(_p0), uintptr(len(buf)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getcwd(buf []byte) (n int, err error) {
var _p0 unsafe.Pointer
if len(buf) > 0 {
_p0 = unsafe.Pointer(&buf[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ioctl(fd int, req uint, arg uintptr) (err error) {
_, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Access(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Adjtime(delta *Timeval, olddelta *Timeval) (err error) {
_, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chdir(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chflags(path string, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chmod(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chown(path string, uid int, gid int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chroot(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Close(fd int) (err error) {
_, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Dup(fd int) (nfd int, err error) {
r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0)
nfd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Dup2(from int, to int) (err error) {
_, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Exit(code int) {
Syscall(SYS_EXIT, uintptr(code), 0, 0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchdir(fd int) (err error) {
_, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchflags(fd int, flags int) (err error) {
_, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchmod(fd int, mode uint32) (err error) {
_, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchown(fd int, uid int, gid int) (err error) {
_, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Flock(fd int, how int) (err error) {
_, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fpathconf(fd int, name int) (val int, err error) {
r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0)
val = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fstat(fd int, stat *Stat_t) (err error) {
_, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fsync(fd int) (err error) {
_, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Ftruncate(fd int, length int64) (err error) {
_, _, e1 := Syscall6(SYS_FTRUNCATE, uintptr(fd), 0, uintptr(length), uintptr(length>>32), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getegid() (egid int) {
r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0)
egid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Geteuid() (uid int) {
r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0)
uid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getgid() (gid int) {
r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0)
gid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpgid(pid int) (pgid int, err error) {
r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0)
pgid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpgrp() (pgrp int) {
r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0)
pgrp = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpid() (pid int) {
r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0)
pid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getppid() (ppid int) {
r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0)
ppid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpriority(which int, who int) (prio int, err error) {
r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0)
prio = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getrlimit(which int, lim *Rlimit) (err error) {
_, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getrusage(who int, rusage *Rusage) (err error) {
_, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getsid(pid int) (sid int, err error) {
r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0)
sid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Gettimeofday(tv *Timeval) (err error) {
_, _, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getuid() (uid int) {
r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0)
uid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Issetugid() (tainted bool) {
r0, _, _ := Syscall(SYS_ISSETUGID, 0, 0, 0)
tainted = bool(r0 != 0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Kill(pid int, signum syscall.Signal) (err error) {
_, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Kqueue() (fd int, err error) {
r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0)
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Lchown(path string, uid int, gid int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Link(path string, link string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(link)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Listen(s int, backlog int) (err error) {
_, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Lstat(path string, stat *Stat_t) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_LSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdir(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkfifo(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mknod(path string, mode uint32, dev int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Nanosleep(time *Timespec, leftover *Timespec) (err error) {
_, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Open(path string, mode int, perm uint32) (fd int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm))
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Pathconf(path string, name int) (val int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0)
val = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Pread(fd int, p []byte, offset int64) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Pwrite(fd int, p []byte, offset int64) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), 0, uintptr(offset), uintptr(offset>>32))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func read(fd int, p []byte) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Readlink(path string, buf []byte) (n int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 unsafe.Pointer
if len(buf) > 0 {
_p1 = unsafe.Pointer(&buf[0])
} else {
_p1 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Rename(from string, to string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(from)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(to)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Revoke(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Rmdir(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
r0, r1, e1 := Syscall6(SYS_LSEEK, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(whence), 0)
newoffset = int64(int64(r1)<<32 | int64(r0))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) {
_, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setegid(egid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETEGID, uintptr(egid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Seteuid(euid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setgid(gid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setpgid(pid int, pgid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setpriority(which int, who int, prio int) (err error) {
_, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setregid(rgid int, egid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setreuid(ruid int, euid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setrlimit(which int, lim *Rlimit) (err error) {
_, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setsid() (pid int, err error) {
r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0)
pid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Settimeofday(tp *Timeval) (err error) {
_, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setuid(uid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Stat(path string, stat *Stat_t) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Symlink(path string, link string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(link)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Sync() (err error) {
_, _, e1 := Syscall(SYS_SYNC, 0, 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Truncate(path string, length int64) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall6(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), 0, uintptr(length), uintptr(length>>32), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Umask(newmask int) (oldmask int) {
r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0)
oldmask = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Unlink(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Unmount(path string, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func write(fd int, p []byte) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) {
r0, _, e1 := Syscall9(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), 0, uintptr(pos), uintptr(pos>>32), 0)
ret = uintptr(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func munmap(addr uintptr, length uintptr) (err error) {
_, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func readlen(fd int, buf *byte, nbuf int) (n int, err error) {
r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func writelen(fd int, buf *byte, nbuf int) (n int, err error) {
r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
| {
"pile_set_name": "Github"
} |
/*
* linux/net/sunrpc/xprtsock.c
*
* Client-side transport implementation for sockets.
*
* TCP callback races fixes (C) 1998 Red Hat
* TCP send fixes (C) 1998 Red Hat
* TCP NFS related read + write fixes
* (C) 1999 Dave Airlie, University of Limerick, Ireland <[email protected]>
*
* Rewrite of larges part of the code in order to stabilize TCP stuff.
* Fix behaviour when socket buffer is full.
* (C) 1999 Trond Myklebust <[email protected]>
*
* IP socket transport implementation, (C) 2005 Chuck Lever <[email protected]>
*
* IPv6 support contributed by Gilles Quillard, Bull Open Source, 2005.
* <[email protected]>
*/
#include <linux/types.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/capability.h>
#include <linux/pagemap.h>
#include <linux/errno.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/net.h>
#include <linux/mm.h>
#include <linux/un.h>
#include <linux/udp.h>
#include <linux/tcp.h>
#include <linux/sunrpc/clnt.h>
#include <linux/sunrpc/sched.h>
#include <linux/sunrpc/svcsock.h>
#include <linux/sunrpc/xprtsock.h>
#include <linux/file.h>
#ifdef CONFIG_SUNRPC_BACKCHANNEL
#include <linux/sunrpc/bc_xprt.h>
#endif
#include <net/sock.h>
#include <net/checksum.h>
#include <net/udp.h>
#include <net/tcp.h>
#include "sunrpc.h"
static void xs_close(struct rpc_xprt *xprt);
/*
* xprtsock tunables
*/
static unsigned int xprt_udp_slot_table_entries = RPC_DEF_SLOT_TABLE;
static unsigned int xprt_tcp_slot_table_entries = RPC_MIN_SLOT_TABLE;
static unsigned int xprt_max_tcp_slot_table_entries = RPC_MAX_SLOT_TABLE;
static unsigned int xprt_min_resvport = RPC_DEF_MIN_RESVPORT;
static unsigned int xprt_max_resvport = RPC_DEF_MAX_RESVPORT;
#define XS_TCP_LINGER_TO (15U * HZ)
static unsigned int xs_tcp_fin_timeout __read_mostly = XS_TCP_LINGER_TO;
/*
* We can register our own files under /proc/sys/sunrpc by
* calling register_sysctl_table() again. The files in that
* directory become the union of all files registered there.
*
* We simply need to make sure that we don't collide with
* someone else's file names!
*/
#ifdef RPC_DEBUG
static unsigned int min_slot_table_size = RPC_MIN_SLOT_TABLE;
static unsigned int max_slot_table_size = RPC_MAX_SLOT_TABLE;
static unsigned int max_tcp_slot_table_limit = RPC_MAX_SLOT_TABLE_LIMIT;
static unsigned int xprt_min_resvport_limit = RPC_MIN_RESVPORT;
static unsigned int xprt_max_resvport_limit = RPC_MAX_RESVPORT;
static struct ctl_table_header *sunrpc_table_header;
/*
* FIXME: changing the UDP slot table size should also resize the UDP
* socket buffers for existing UDP transports
*/
static ctl_table xs_tunables_table[] = {
{
.procname = "udp_slot_table_entries",
.data = &xprt_udp_slot_table_entries,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = &min_slot_table_size,
.extra2 = &max_slot_table_size
},
{
.procname = "tcp_slot_table_entries",
.data = &xprt_tcp_slot_table_entries,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = &min_slot_table_size,
.extra2 = &max_slot_table_size
},
{
.procname = "tcp_max_slot_table_entries",
.data = &xprt_max_tcp_slot_table_entries,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = &min_slot_table_size,
.extra2 = &max_tcp_slot_table_limit
},
{
.procname = "min_resvport",
.data = &xprt_min_resvport,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = &xprt_min_resvport_limit,
.extra2 = &xprt_max_resvport_limit
},
{
.procname = "max_resvport",
.data = &xprt_max_resvport,
.maxlen = sizeof(unsigned int),
.mode = 0644,
.proc_handler = proc_dointvec_minmax,
.extra1 = &xprt_min_resvport_limit,
.extra2 = &xprt_max_resvport_limit
},
{
.procname = "tcp_fin_timeout",
.data = &xs_tcp_fin_timeout,
.maxlen = sizeof(xs_tcp_fin_timeout),
.mode = 0644,
.proc_handler = proc_dointvec_jiffies,
},
{ },
};
static ctl_table sunrpc_table[] = {
{
.procname = "sunrpc",
.mode = 0555,
.child = xs_tunables_table
},
{ },
};
#endif
/*
* Wait duration for a reply from the RPC portmapper.
*/
#define XS_BIND_TO (60U * HZ)
/*
* Delay if a UDP socket connect error occurs. This is most likely some
* kind of resource problem on the local host.
*/
#define XS_UDP_REEST_TO (2U * HZ)
/*
* The reestablish timeout allows clients to delay for a bit before attempting
* to reconnect to a server that just dropped our connection.
*
* We implement an exponential backoff when trying to reestablish a TCP
* transport connection with the server. Some servers like to drop a TCP
* connection when they are overworked, so we start with a short timeout and
* increase over time if the server is down or not responding.
*/
#define XS_TCP_INIT_REEST_TO (3U * HZ)
#define XS_TCP_MAX_REEST_TO (5U * 60 * HZ)
/*
* TCP idle timeout; client drops the transport socket if it is idle
* for this long. Note that we also timeout UDP sockets to prevent
* holding port numbers when there is no RPC traffic.
*/
#define XS_IDLE_DISC_TO (5U * 60 * HZ)
#ifdef RPC_DEBUG
# undef RPC_DEBUG_DATA
# define RPCDBG_FACILITY RPCDBG_TRANS
#endif
#ifdef RPC_DEBUG_DATA
static void xs_pktdump(char *msg, u32 *packet, unsigned int count)
{
u8 *buf = (u8 *) packet;
int j;
dprintk("RPC: %s\n", msg);
for (j = 0; j < count && j < 128; j += 4) {
if (!(j & 31)) {
if (j)
dprintk("\n");
dprintk("0x%04x ", j);
}
dprintk("%02x%02x%02x%02x ",
buf[j], buf[j+1], buf[j+2], buf[j+3]);
}
dprintk("\n");
}
#else
static inline void xs_pktdump(char *msg, u32 *packet, unsigned int count)
{
/* NOP */
}
#endif
struct sock_xprt {
struct rpc_xprt xprt;
/*
* Network layer
*/
struct socket * sock;
struct sock * inet;
/*
* State of TCP reply receive
*/
__be32 tcp_fraghdr,
tcp_xid,
tcp_calldir;
u32 tcp_offset,
tcp_reclen;
unsigned long tcp_copied,
tcp_flags;
/*
* Connection of transports
*/
struct delayed_work connect_worker;
struct sockaddr_storage srcaddr;
unsigned short srcport;
/*
* UDP socket buffer size parameters
*/
size_t rcvsize,
sndsize;
/*
* Saved socket callback addresses
*/
void (*old_data_ready)(struct sock *, int);
void (*old_state_change)(struct sock *);
void (*old_write_space)(struct sock *);
};
/*
* TCP receive state flags
*/
#define TCP_RCV_LAST_FRAG (1UL << 0)
#define TCP_RCV_COPY_FRAGHDR (1UL << 1)
#define TCP_RCV_COPY_XID (1UL << 2)
#define TCP_RCV_COPY_DATA (1UL << 3)
#define TCP_RCV_READ_CALLDIR (1UL << 4)
#define TCP_RCV_COPY_CALLDIR (1UL << 5)
/*
* TCP RPC flags
*/
#define TCP_RPC_REPLY (1UL << 6)
static inline struct sockaddr *xs_addr(struct rpc_xprt *xprt)
{
return (struct sockaddr *) &xprt->addr;
}
static inline struct sockaddr_un *xs_addr_un(struct rpc_xprt *xprt)
{
return (struct sockaddr_un *) &xprt->addr;
}
static inline struct sockaddr_in *xs_addr_in(struct rpc_xprt *xprt)
{
return (struct sockaddr_in *) &xprt->addr;
}
static inline struct sockaddr_in6 *xs_addr_in6(struct rpc_xprt *xprt)
{
return (struct sockaddr_in6 *) &xprt->addr;
}
static void xs_format_common_peer_addresses(struct rpc_xprt *xprt)
{
struct sockaddr *sap = xs_addr(xprt);
struct sockaddr_in6 *sin6;
struct sockaddr_in *sin;
struct sockaddr_un *sun;
char buf[128];
switch (sap->sa_family) {
case AF_LOCAL:
sun = xs_addr_un(xprt);
strlcpy(buf, sun->sun_path, sizeof(buf));
xprt->address_strings[RPC_DISPLAY_ADDR] =
kstrdup(buf, GFP_KERNEL);
break;
case AF_INET:
(void)rpc_ntop(sap, buf, sizeof(buf));
xprt->address_strings[RPC_DISPLAY_ADDR] =
kstrdup(buf, GFP_KERNEL);
sin = xs_addr_in(xprt);
snprintf(buf, sizeof(buf), "%08x", ntohl(sin->sin_addr.s_addr));
break;
case AF_INET6:
(void)rpc_ntop(sap, buf, sizeof(buf));
xprt->address_strings[RPC_DISPLAY_ADDR] =
kstrdup(buf, GFP_KERNEL);
sin6 = xs_addr_in6(xprt);
snprintf(buf, sizeof(buf), "%pi6", &sin6->sin6_addr);
break;
default:
BUG();
}
xprt->address_strings[RPC_DISPLAY_HEX_ADDR] = kstrdup(buf, GFP_KERNEL);
}
static void xs_format_common_peer_ports(struct rpc_xprt *xprt)
{
struct sockaddr *sap = xs_addr(xprt);
char buf[128];
snprintf(buf, sizeof(buf), "%u", rpc_get_port(sap));
xprt->address_strings[RPC_DISPLAY_PORT] = kstrdup(buf, GFP_KERNEL);
snprintf(buf, sizeof(buf), "%4hx", rpc_get_port(sap));
xprt->address_strings[RPC_DISPLAY_HEX_PORT] = kstrdup(buf, GFP_KERNEL);
}
static void xs_format_peer_addresses(struct rpc_xprt *xprt,
const char *protocol,
const char *netid)
{
xprt->address_strings[RPC_DISPLAY_PROTO] = protocol;
xprt->address_strings[RPC_DISPLAY_NETID] = netid;
xs_format_common_peer_addresses(xprt);
xs_format_common_peer_ports(xprt);
}
static void xs_update_peer_port(struct rpc_xprt *xprt)
{
kfree(xprt->address_strings[RPC_DISPLAY_HEX_PORT]);
kfree(xprt->address_strings[RPC_DISPLAY_PORT]);
xs_format_common_peer_ports(xprt);
}
static void xs_free_peer_addresses(struct rpc_xprt *xprt)
{
unsigned int i;
for (i = 0; i < RPC_DISPLAY_MAX; i++)
switch (i) {
case RPC_DISPLAY_PROTO:
case RPC_DISPLAY_NETID:
continue;
default:
kfree(xprt->address_strings[i]);
}
}
#define XS_SENDMSG_FLAGS (MSG_DONTWAIT | MSG_NOSIGNAL)
static int xs_send_kvec(struct socket *sock, struct sockaddr *addr, int addrlen, struct kvec *vec, unsigned int base, int more)
{
struct msghdr msg = {
.msg_name = addr,
.msg_namelen = addrlen,
.msg_flags = XS_SENDMSG_FLAGS | (more ? MSG_MORE : 0),
};
struct kvec iov = {
.iov_base = vec->iov_base + base,
.iov_len = vec->iov_len - base,
};
if (iov.iov_len != 0)
return kernel_sendmsg(sock, &msg, &iov, 1, iov.iov_len);
return kernel_sendmsg(sock, &msg, NULL, 0, 0);
}
static int xs_send_pagedata(struct socket *sock, struct xdr_buf *xdr, unsigned int base, int more)
{
struct page **ppage;
unsigned int remainder;
int err, sent = 0;
remainder = xdr->page_len - base;
base += xdr->page_base;
ppage = xdr->pages + (base >> PAGE_SHIFT);
base &= ~PAGE_MASK;
for(;;) {
unsigned int len = min_t(unsigned int, PAGE_SIZE - base, remainder);
int flags = XS_SENDMSG_FLAGS;
remainder -= len;
if (remainder != 0 || more)
flags |= MSG_MORE;
err = sock->ops->sendpage(sock, *ppage, base, len, flags);
if (remainder == 0 || err != len)
break;
sent += err;
ppage++;
base = 0;
}
if (sent == 0)
return err;
if (err > 0)
sent += err;
return sent;
}
/**
* xs_sendpages - write pages directly to a socket
* @sock: socket to send on
* @addr: UDP only -- address of destination
* @addrlen: UDP only -- length of destination address
* @xdr: buffer containing this request
* @base: starting position in the buffer
*
*/
static int xs_sendpages(struct socket *sock, struct sockaddr *addr, int addrlen, struct xdr_buf *xdr, unsigned int base)
{
unsigned int remainder = xdr->len - base;
int err, sent = 0;
if (unlikely(!sock))
return -ENOTSOCK;
clear_bit(SOCK_ASYNC_NOSPACE, &sock->flags);
if (base != 0) {
addr = NULL;
addrlen = 0;
}
if (base < xdr->head[0].iov_len || addr != NULL) {
unsigned int len = xdr->head[0].iov_len - base;
remainder -= len;
err = xs_send_kvec(sock, addr, addrlen, &xdr->head[0], base, remainder != 0);
if (remainder == 0 || err != len)
goto out;
sent += err;
base = 0;
} else
base -= xdr->head[0].iov_len;
if (base < xdr->page_len) {
unsigned int len = xdr->page_len - base;
remainder -= len;
err = xs_send_pagedata(sock, xdr, base, remainder != 0);
if (remainder == 0 || err != len)
goto out;
sent += err;
base = 0;
} else
base -= xdr->page_len;
if (base >= xdr->tail[0].iov_len)
return sent;
err = xs_send_kvec(sock, NULL, 0, &xdr->tail[0], base, 0);
out:
if (sent == 0)
return err;
if (err > 0)
sent += err;
return sent;
}
static void xs_nospace_callback(struct rpc_task *task)
{
struct sock_xprt *transport = container_of(task->tk_rqstp->rq_xprt, struct sock_xprt, xprt);
transport->inet->sk_write_pending--;
clear_bit(SOCK_ASYNC_NOSPACE, &transport->sock->flags);
}
/**
* xs_nospace - place task on wait queue if transmit was incomplete
* @task: task to put to sleep
*
*/
static int xs_nospace(struct rpc_task *task)
{
struct rpc_rqst *req = task->tk_rqstp;
struct rpc_xprt *xprt = req->rq_xprt;
struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
int ret = -EAGAIN;
dprintk("RPC: %5u xmit incomplete (%u left of %u)\n",
task->tk_pid, req->rq_slen - req->rq_bytes_sent,
req->rq_slen);
/* Protect against races with write_space */
spin_lock_bh(&xprt->transport_lock);
/* Don't race with disconnect */
if (xprt_connected(xprt)) {
if (test_bit(SOCK_ASYNC_NOSPACE, &transport->sock->flags)) {
/*
* Notify TCP that we're limited by the application
* window size
*/
set_bit(SOCK_NOSPACE, &transport->sock->flags);
transport->inet->sk_write_pending++;
/* ...and wait for more buffer space */
xprt_wait_for_buffer_space(task, xs_nospace_callback);
}
} else {
clear_bit(SOCK_ASYNC_NOSPACE, &transport->sock->flags);
ret = -ENOTCONN;
}
spin_unlock_bh(&xprt->transport_lock);
return ret;
}
/*
* Construct a stream transport record marker in @buf.
*/
static inline void xs_encode_stream_record_marker(struct xdr_buf *buf)
{
u32 reclen = buf->len - sizeof(rpc_fraghdr);
rpc_fraghdr *base = buf->head[0].iov_base;
*base = cpu_to_be32(RPC_LAST_STREAM_FRAGMENT | reclen);
}
/**
* xs_local_send_request - write an RPC request to an AF_LOCAL socket
* @task: RPC task that manages the state of an RPC request
*
* Return values:
* 0: The request has been sent
* EAGAIN: The socket was blocked, please call again later to
* complete the request
* ENOTCONN: Caller needs to invoke connect logic then call again
* other: Some other error occured, the request was not sent
*/
static int xs_local_send_request(struct rpc_task *task)
{
struct rpc_rqst *req = task->tk_rqstp;
struct rpc_xprt *xprt = req->rq_xprt;
struct sock_xprt *transport =
container_of(xprt, struct sock_xprt, xprt);
struct xdr_buf *xdr = &req->rq_snd_buf;
int status;
xs_encode_stream_record_marker(&req->rq_snd_buf);
xs_pktdump("packet data:",
req->rq_svec->iov_base, req->rq_svec->iov_len);
status = xs_sendpages(transport->sock, NULL, 0,
xdr, req->rq_bytes_sent);
dprintk("RPC: %s(%u) = %d\n",
__func__, xdr->len - req->rq_bytes_sent, status);
if (likely(status >= 0)) {
req->rq_bytes_sent += status;
req->rq_xmit_bytes_sent += status;
if (likely(req->rq_bytes_sent >= req->rq_slen)) {
req->rq_bytes_sent = 0;
return 0;
}
status = -EAGAIN;
}
switch (status) {
case -EAGAIN:
status = xs_nospace(task);
break;
default:
dprintk("RPC: sendmsg returned unrecognized error %d\n",
-status);
case -EPIPE:
xs_close(xprt);
status = -ENOTCONN;
}
return status;
}
/**
* xs_udp_send_request - write an RPC request to a UDP socket
* @task: address of RPC task that manages the state of an RPC request
*
* Return values:
* 0: The request has been sent
* EAGAIN: The socket was blocked, please call again later to
* complete the request
* ENOTCONN: Caller needs to invoke connect logic then call again
* other: Some other error occurred, the request was not sent
*/
static int xs_udp_send_request(struct rpc_task *task)
{
struct rpc_rqst *req = task->tk_rqstp;
struct rpc_xprt *xprt = req->rq_xprt;
struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
struct xdr_buf *xdr = &req->rq_snd_buf;
int status;
xs_pktdump("packet data:",
req->rq_svec->iov_base,
req->rq_svec->iov_len);
if (!xprt_bound(xprt))
return -ENOTCONN;
status = xs_sendpages(transport->sock,
xs_addr(xprt),
xprt->addrlen, xdr,
req->rq_bytes_sent);
dprintk("RPC: xs_udp_send_request(%u) = %d\n",
xdr->len - req->rq_bytes_sent, status);
if (status >= 0) {
req->rq_xmit_bytes_sent += status;
if (status >= req->rq_slen)
return 0;
/* Still some bytes left; set up for a retry later. */
status = -EAGAIN;
}
switch (status) {
case -ENOTSOCK:
status = -ENOTCONN;
/* Should we call xs_close() here? */
break;
case -EAGAIN:
status = xs_nospace(task);
break;
default:
dprintk("RPC: sendmsg returned unrecognized error %d\n",
-status);
case -ENETUNREACH:
case -EPIPE:
case -ECONNREFUSED:
/* When the server has died, an ICMP port unreachable message
* prompts ECONNREFUSED. */
clear_bit(SOCK_ASYNC_NOSPACE, &transport->sock->flags);
}
return status;
}
/**
* xs_tcp_shutdown - gracefully shut down a TCP socket
* @xprt: transport
*
* Initiates a graceful shutdown of the TCP socket by calling the
* equivalent of shutdown(SHUT_WR);
*/
static void xs_tcp_shutdown(struct rpc_xprt *xprt)
{
struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
struct socket *sock = transport->sock;
if (sock != NULL)
kernel_sock_shutdown(sock, SHUT_WR);
}
/**
* xs_tcp_send_request - write an RPC request to a TCP socket
* @task: address of RPC task that manages the state of an RPC request
*
* Return values:
* 0: The request has been sent
* EAGAIN: The socket was blocked, please call again later to
* complete the request
* ENOTCONN: Caller needs to invoke connect logic then call again
* other: Some other error occurred, the request was not sent
*
* XXX: In the case of soft timeouts, should we eventually give up
* if sendmsg is not able to make progress?
*/
static int xs_tcp_send_request(struct rpc_task *task)
{
struct rpc_rqst *req = task->tk_rqstp;
struct rpc_xprt *xprt = req->rq_xprt;
struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
struct xdr_buf *xdr = &req->rq_snd_buf;
int status;
xs_encode_stream_record_marker(&req->rq_snd_buf);
xs_pktdump("packet data:",
req->rq_svec->iov_base,
req->rq_svec->iov_len);
/* Continue transmitting the packet/record. We must be careful
* to cope with writespace callbacks arriving _after_ we have
* called sendmsg(). */
while (1) {
status = xs_sendpages(transport->sock,
NULL, 0, xdr, req->rq_bytes_sent);
dprintk("RPC: xs_tcp_send_request(%u) = %d\n",
xdr->len - req->rq_bytes_sent, status);
if (unlikely(status < 0))
break;
/* If we've sent the entire packet, immediately
* reset the count of bytes sent. */
req->rq_bytes_sent += status;
req->rq_xmit_bytes_sent += status;
if (likely(req->rq_bytes_sent >= req->rq_slen)) {
req->rq_bytes_sent = 0;
return 0;
}
if (status != 0)
continue;
status = -EAGAIN;
break;
}
switch (status) {
case -ENOTSOCK:
status = -ENOTCONN;
/* Should we call xs_close() here? */
break;
case -EAGAIN:
status = xs_nospace(task);
break;
default:
dprintk("RPC: sendmsg returned unrecognized error %d\n",
-status);
case -ECONNRESET:
xs_tcp_shutdown(xprt);
case -ECONNREFUSED:
case -ENOTCONN:
case -EPIPE:
clear_bit(SOCK_ASYNC_NOSPACE, &transport->sock->flags);
}
return status;
}
/**
* xs_tcp_release_xprt - clean up after a tcp transmission
* @xprt: transport
* @task: rpc task
*
* This cleans up if an error causes us to abort the transmission of a request.
* In this case, the socket may need to be reset in order to avoid confusing
* the server.
*/
static void xs_tcp_release_xprt(struct rpc_xprt *xprt, struct rpc_task *task)
{
struct rpc_rqst *req;
if (task != xprt->snd_task)
return;
if (task == NULL)
goto out_release;
req = task->tk_rqstp;
if (req == NULL)
goto out_release;
if (req->rq_bytes_sent == 0)
goto out_release;
if (req->rq_bytes_sent == req->rq_snd_buf.len)
goto out_release;
set_bit(XPRT_CLOSE_WAIT, &task->tk_xprt->state);
out_release:
xprt_release_xprt(xprt, task);
}
static void xs_save_old_callbacks(struct sock_xprt *transport, struct sock *sk)
{
transport->old_data_ready = sk->sk_data_ready;
transport->old_state_change = sk->sk_state_change;
transport->old_write_space = sk->sk_write_space;
}
static void xs_restore_old_callbacks(struct sock_xprt *transport, struct sock *sk)
{
sk->sk_data_ready = transport->old_data_ready;
sk->sk_state_change = transport->old_state_change;
sk->sk_write_space = transport->old_write_space;
}
static void xs_reset_transport(struct sock_xprt *transport)
{
struct socket *sock = transport->sock;
struct sock *sk = transport->inet;
if (sk == NULL)
return;
transport->srcport = 0;
write_lock_bh(&sk->sk_callback_lock);
transport->inet = NULL;
transport->sock = NULL;
sk->sk_user_data = NULL;
xs_restore_old_callbacks(transport, sk);
write_unlock_bh(&sk->sk_callback_lock);
sk->sk_no_check = 0;
sock_release(sock);
}
/**
* xs_close - close a socket
* @xprt: transport
*
* This is used when all requests are complete; ie, no DRC state remains
* on the server we want to save.
*
* The caller _must_ be holding XPRT_LOCKED in order to avoid issues with
* xs_reset_transport() zeroing the socket from underneath a writer.
*/
static void xs_close(struct rpc_xprt *xprt)
{
struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
dprintk("RPC: xs_close xprt %p\n", xprt);
xs_reset_transport(transport);
xprt->reestablish_timeout = 0;
smp_mb__before_clear_bit();
clear_bit(XPRT_CONNECTION_ABORT, &xprt->state);
clear_bit(XPRT_CLOSE_WAIT, &xprt->state);
clear_bit(XPRT_CLOSING, &xprt->state);
smp_mb__after_clear_bit();
xprt_disconnect_done(xprt);
}
static void xs_tcp_close(struct rpc_xprt *xprt)
{
if (test_and_clear_bit(XPRT_CONNECTION_CLOSE, &xprt->state))
xs_close(xprt);
else
xs_tcp_shutdown(xprt);
}
/**
* xs_destroy - prepare to shutdown a transport
* @xprt: doomed transport
*
*/
static void xs_destroy(struct rpc_xprt *xprt)
{
struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
dprintk("RPC: xs_destroy xprt %p\n", xprt);
cancel_delayed_work_sync(&transport->connect_worker);
xs_close(xprt);
xs_free_peer_addresses(xprt);
xprt_free(xprt);
module_put(THIS_MODULE);
}
static inline struct rpc_xprt *xprt_from_sock(struct sock *sk)
{
return (struct rpc_xprt *) sk->sk_user_data;
}
static int xs_local_copy_to_xdr(struct xdr_buf *xdr, struct sk_buff *skb)
{
struct xdr_skb_reader desc = {
.skb = skb,
.offset = sizeof(rpc_fraghdr),
.count = skb->len - sizeof(rpc_fraghdr),
};
if (xdr_partial_copy_from_skb(xdr, 0, &desc, xdr_skb_read_bits) < 0)
return -1;
if (desc.count)
return -1;
return 0;
}
/**
* xs_local_data_ready - "data ready" callback for AF_LOCAL sockets
* @sk: socket with data to read
* @len: how much data to read
*
* Currently this assumes we can read the whole reply in a single gulp.
*/
static void xs_local_data_ready(struct sock *sk, int len)
{
struct rpc_task *task;
struct rpc_xprt *xprt;
struct rpc_rqst *rovr;
struct sk_buff *skb;
int err, repsize, copied;
u32 _xid;
__be32 *xp;
read_lock_bh(&sk->sk_callback_lock);
dprintk("RPC: %s...\n", __func__);
xprt = xprt_from_sock(sk);
if (xprt == NULL)
goto out;
skb = skb_recv_datagram(sk, 0, 1, &err);
if (skb == NULL)
goto out;
if (xprt->shutdown)
goto dropit;
repsize = skb->len - sizeof(rpc_fraghdr);
if (repsize < 4) {
dprintk("RPC: impossible RPC reply size %d\n", repsize);
goto dropit;
}
/* Copy the XID from the skb... */
xp = skb_header_pointer(skb, sizeof(rpc_fraghdr), sizeof(_xid), &_xid);
if (xp == NULL)
goto dropit;
/* Look up and lock the request corresponding to the given XID */
spin_lock(&xprt->transport_lock);
rovr = xprt_lookup_rqst(xprt, *xp);
if (!rovr)
goto out_unlock;
task = rovr->rq_task;
copied = rovr->rq_private_buf.buflen;
if (copied > repsize)
copied = repsize;
if (xs_local_copy_to_xdr(&rovr->rq_private_buf, skb)) {
dprintk("RPC: sk_buff copy failed\n");
goto out_unlock;
}
xprt_complete_rqst(task, copied);
out_unlock:
spin_unlock(&xprt->transport_lock);
dropit:
skb_free_datagram(sk, skb);
out:
read_unlock_bh(&sk->sk_callback_lock);
}
/**
* xs_udp_data_ready - "data ready" callback for UDP sockets
* @sk: socket with data to read
* @len: how much data to read
*
*/
static void xs_udp_data_ready(struct sock *sk, int len)
{
struct rpc_task *task;
struct rpc_xprt *xprt;
struct rpc_rqst *rovr;
struct sk_buff *skb;
int err, repsize, copied;
u32 _xid;
__be32 *xp;
read_lock_bh(&sk->sk_callback_lock);
dprintk("RPC: xs_udp_data_ready...\n");
if (!(xprt = xprt_from_sock(sk)))
goto out;
if ((skb = skb_recv_datagram(sk, 0, 1, &err)) == NULL)
goto out;
if (xprt->shutdown)
goto dropit;
repsize = skb->len - sizeof(struct udphdr);
if (repsize < 4) {
dprintk("RPC: impossible RPC reply size %d!\n", repsize);
goto dropit;
}
/* Copy the XID from the skb... */
xp = skb_header_pointer(skb, sizeof(struct udphdr),
sizeof(_xid), &_xid);
if (xp == NULL)
goto dropit;
/* Look up and lock the request corresponding to the given XID */
spin_lock(&xprt->transport_lock);
rovr = xprt_lookup_rqst(xprt, *xp);
if (!rovr)
goto out_unlock;
task = rovr->rq_task;
if ((copied = rovr->rq_private_buf.buflen) > repsize)
copied = repsize;
/* Suck it into the iovec, verify checksum if not done by hw. */
if (csum_partial_copy_to_xdr(&rovr->rq_private_buf, skb)) {
UDPX_INC_STATS_BH(sk, UDP_MIB_INERRORS);
goto out_unlock;
}
UDPX_INC_STATS_BH(sk, UDP_MIB_INDATAGRAMS);
/* Something worked... */
dst_confirm(skb_dst(skb));
xprt_adjust_cwnd(task, copied);
xprt_complete_rqst(task, copied);
out_unlock:
spin_unlock(&xprt->transport_lock);
dropit:
skb_free_datagram(sk, skb);
out:
read_unlock_bh(&sk->sk_callback_lock);
}
/*
* Helper function to force a TCP close if the server is sending
* junk and/or it has put us in CLOSE_WAIT
*/
static void xs_tcp_force_close(struct rpc_xprt *xprt)
{
set_bit(XPRT_CONNECTION_CLOSE, &xprt->state);
xprt_force_disconnect(xprt);
}
static inline void xs_tcp_read_fraghdr(struct rpc_xprt *xprt, struct xdr_skb_reader *desc)
{
struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
size_t len, used;
char *p;
p = ((char *) &transport->tcp_fraghdr) + transport->tcp_offset;
len = sizeof(transport->tcp_fraghdr) - transport->tcp_offset;
used = xdr_skb_read_bits(desc, p, len);
transport->tcp_offset += used;
if (used != len)
return;
transport->tcp_reclen = ntohl(transport->tcp_fraghdr);
if (transport->tcp_reclen & RPC_LAST_STREAM_FRAGMENT)
transport->tcp_flags |= TCP_RCV_LAST_FRAG;
else
transport->tcp_flags &= ~TCP_RCV_LAST_FRAG;
transport->tcp_reclen &= RPC_FRAGMENT_SIZE_MASK;
transport->tcp_flags &= ~TCP_RCV_COPY_FRAGHDR;
transport->tcp_offset = 0;
/* Sanity check of the record length */
if (unlikely(transport->tcp_reclen < 8)) {
dprintk("RPC: invalid TCP record fragment length\n");
xs_tcp_force_close(xprt);
return;
}
dprintk("RPC: reading TCP record fragment of length %d\n",
transport->tcp_reclen);
}
static void xs_tcp_check_fraghdr(struct sock_xprt *transport)
{
if (transport->tcp_offset == transport->tcp_reclen) {
transport->tcp_flags |= TCP_RCV_COPY_FRAGHDR;
transport->tcp_offset = 0;
if (transport->tcp_flags & TCP_RCV_LAST_FRAG) {
transport->tcp_flags &= ~TCP_RCV_COPY_DATA;
transport->tcp_flags |= TCP_RCV_COPY_XID;
transport->tcp_copied = 0;
}
}
}
static inline void xs_tcp_read_xid(struct sock_xprt *transport, struct xdr_skb_reader *desc)
{
size_t len, used;
char *p;
len = sizeof(transport->tcp_xid) - transport->tcp_offset;
dprintk("RPC: reading XID (%Zu bytes)\n", len);
p = ((char *) &transport->tcp_xid) + transport->tcp_offset;
used = xdr_skb_read_bits(desc, p, len);
transport->tcp_offset += used;
if (used != len)
return;
transport->tcp_flags &= ~TCP_RCV_COPY_XID;
transport->tcp_flags |= TCP_RCV_READ_CALLDIR;
transport->tcp_copied = 4;
dprintk("RPC: reading %s XID %08x\n",
(transport->tcp_flags & TCP_RPC_REPLY) ? "reply for"
: "request with",
ntohl(transport->tcp_xid));
xs_tcp_check_fraghdr(transport);
}
static inline void xs_tcp_read_calldir(struct sock_xprt *transport,
struct xdr_skb_reader *desc)
{
size_t len, used;
u32 offset;
char *p;
/*
* We want transport->tcp_offset to be 8 at the end of this routine
* (4 bytes for the xid and 4 bytes for the call/reply flag).
* When this function is called for the first time,
* transport->tcp_offset is 4 (after having already read the xid).
*/
offset = transport->tcp_offset - sizeof(transport->tcp_xid);
len = sizeof(transport->tcp_calldir) - offset;
dprintk("RPC: reading CALL/REPLY flag (%Zu bytes)\n", len);
p = ((char *) &transport->tcp_calldir) + offset;
used = xdr_skb_read_bits(desc, p, len);
transport->tcp_offset += used;
if (used != len)
return;
transport->tcp_flags &= ~TCP_RCV_READ_CALLDIR;
/*
* We don't yet have the XDR buffer, so we will write the calldir
* out after we get the buffer from the 'struct rpc_rqst'
*/
switch (ntohl(transport->tcp_calldir)) {
case RPC_REPLY:
transport->tcp_flags |= TCP_RCV_COPY_CALLDIR;
transport->tcp_flags |= TCP_RCV_COPY_DATA;
transport->tcp_flags |= TCP_RPC_REPLY;
break;
case RPC_CALL:
transport->tcp_flags |= TCP_RCV_COPY_CALLDIR;
transport->tcp_flags |= TCP_RCV_COPY_DATA;
transport->tcp_flags &= ~TCP_RPC_REPLY;
break;
default:
dprintk("RPC: invalid request message type\n");
xs_tcp_force_close(&transport->xprt);
}
xs_tcp_check_fraghdr(transport);
}
static inline void xs_tcp_read_common(struct rpc_xprt *xprt,
struct xdr_skb_reader *desc,
struct rpc_rqst *req)
{
struct sock_xprt *transport =
container_of(xprt, struct sock_xprt, xprt);
struct xdr_buf *rcvbuf;
size_t len;
ssize_t r;
rcvbuf = &req->rq_private_buf;
if (transport->tcp_flags & TCP_RCV_COPY_CALLDIR) {
/*
* Save the RPC direction in the XDR buffer
*/
memcpy(rcvbuf->head[0].iov_base + transport->tcp_copied,
&transport->tcp_calldir,
sizeof(transport->tcp_calldir));
transport->tcp_copied += sizeof(transport->tcp_calldir);
transport->tcp_flags &= ~TCP_RCV_COPY_CALLDIR;
}
len = desc->count;
if (len > transport->tcp_reclen - transport->tcp_offset) {
struct xdr_skb_reader my_desc;
len = transport->tcp_reclen - transport->tcp_offset;
memcpy(&my_desc, desc, sizeof(my_desc));
my_desc.count = len;
r = xdr_partial_copy_from_skb(rcvbuf, transport->tcp_copied,
&my_desc, xdr_skb_read_bits);
desc->count -= r;
desc->offset += r;
} else
r = xdr_partial_copy_from_skb(rcvbuf, transport->tcp_copied,
desc, xdr_skb_read_bits);
if (r > 0) {
transport->tcp_copied += r;
transport->tcp_offset += r;
}
if (r != len) {
/* Error when copying to the receive buffer,
* usually because we weren't able to allocate
* additional buffer pages. All we can do now
* is turn off TCP_RCV_COPY_DATA, so the request
* will not receive any additional updates,
* and time out.
* Any remaining data from this record will
* be discarded.
*/
transport->tcp_flags &= ~TCP_RCV_COPY_DATA;
dprintk("RPC: XID %08x truncated request\n",
ntohl(transport->tcp_xid));
dprintk("RPC: xprt = %p, tcp_copied = %lu, "
"tcp_offset = %u, tcp_reclen = %u\n",
xprt, transport->tcp_copied,
transport->tcp_offset, transport->tcp_reclen);
return;
}
dprintk("RPC: XID %08x read %Zd bytes\n",
ntohl(transport->tcp_xid), r);
dprintk("RPC: xprt = %p, tcp_copied = %lu, tcp_offset = %u, "
"tcp_reclen = %u\n", xprt, transport->tcp_copied,
transport->tcp_offset, transport->tcp_reclen);
if (transport->tcp_copied == req->rq_private_buf.buflen)
transport->tcp_flags &= ~TCP_RCV_COPY_DATA;
else if (transport->tcp_offset == transport->tcp_reclen) {
if (transport->tcp_flags & TCP_RCV_LAST_FRAG)
transport->tcp_flags &= ~TCP_RCV_COPY_DATA;
}
}
/*
* Finds the request corresponding to the RPC xid and invokes the common
* tcp read code to read the data.
*/
static inline int xs_tcp_read_reply(struct rpc_xprt *xprt,
struct xdr_skb_reader *desc)
{
struct sock_xprt *transport =
container_of(xprt, struct sock_xprt, xprt);
struct rpc_rqst *req;
dprintk("RPC: read reply XID %08x\n", ntohl(transport->tcp_xid));
/* Find and lock the request corresponding to this xid */
spin_lock(&xprt->transport_lock);
req = xprt_lookup_rqst(xprt, transport->tcp_xid);
if (!req) {
dprintk("RPC: XID %08x request not found!\n",
ntohl(transport->tcp_xid));
spin_unlock(&xprt->transport_lock);
return -1;
}
xs_tcp_read_common(xprt, desc, req);
if (!(transport->tcp_flags & TCP_RCV_COPY_DATA))
xprt_complete_rqst(req->rq_task, transport->tcp_copied);
spin_unlock(&xprt->transport_lock);
return 0;
}
#if defined(CONFIG_SUNRPC_BACKCHANNEL)
/*
* Obtains an rpc_rqst previously allocated and invokes the common
* tcp read code to read the data. The result is placed in the callback
* queue.
* If we're unable to obtain the rpc_rqst we schedule the closing of the
* connection and return -1.
*/
static inline int xs_tcp_read_callback(struct rpc_xprt *xprt,
struct xdr_skb_reader *desc)
{
struct sock_xprt *transport =
container_of(xprt, struct sock_xprt, xprt);
struct rpc_rqst *req;
req = xprt_alloc_bc_request(xprt);
if (req == NULL) {
printk(KERN_WARNING "Callback slot table overflowed\n");
xprt_force_disconnect(xprt);
return -1;
}
req->rq_xid = transport->tcp_xid;
dprintk("RPC: read callback XID %08x\n", ntohl(req->rq_xid));
xs_tcp_read_common(xprt, desc, req);
if (!(transport->tcp_flags & TCP_RCV_COPY_DATA)) {
struct svc_serv *bc_serv = xprt->bc_serv;
/*
* Add callback request to callback list. The callback
* service sleeps on the sv_cb_waitq waiting for new
* requests. Wake it up after adding enqueing the
* request.
*/
dprintk("RPC: add callback request to list\n");
spin_lock(&bc_serv->sv_cb_lock);
list_add(&req->rq_bc_list, &bc_serv->sv_cb_list);
spin_unlock(&bc_serv->sv_cb_lock);
wake_up(&bc_serv->sv_cb_waitq);
}
req->rq_private_buf.len = transport->tcp_copied;
return 0;
}
static inline int _xs_tcp_read_data(struct rpc_xprt *xprt,
struct xdr_skb_reader *desc)
{
struct sock_xprt *transport =
container_of(xprt, struct sock_xprt, xprt);
return (transport->tcp_flags & TCP_RPC_REPLY) ?
xs_tcp_read_reply(xprt, desc) :
xs_tcp_read_callback(xprt, desc);
}
#else
static inline int _xs_tcp_read_data(struct rpc_xprt *xprt,
struct xdr_skb_reader *desc)
{
return xs_tcp_read_reply(xprt, desc);
}
#endif /* CONFIG_SUNRPC_BACKCHANNEL */
/*
* Read data off the transport. This can be either an RPC_CALL or an
* RPC_REPLY. Relay the processing to helper functions.
*/
static void xs_tcp_read_data(struct rpc_xprt *xprt,
struct xdr_skb_reader *desc)
{
struct sock_xprt *transport =
container_of(xprt, struct sock_xprt, xprt);
if (_xs_tcp_read_data(xprt, desc) == 0)
xs_tcp_check_fraghdr(transport);
else {
/*
* The transport_lock protects the request handling.
* There's no need to hold it to update the tcp_flags.
*/
transport->tcp_flags &= ~TCP_RCV_COPY_DATA;
}
}
static inline void xs_tcp_read_discard(struct sock_xprt *transport, struct xdr_skb_reader *desc)
{
size_t len;
len = transport->tcp_reclen - transport->tcp_offset;
if (len > desc->count)
len = desc->count;
desc->count -= len;
desc->offset += len;
transport->tcp_offset += len;
dprintk("RPC: discarded %Zu bytes\n", len);
xs_tcp_check_fraghdr(transport);
}
static int xs_tcp_data_recv(read_descriptor_t *rd_desc, struct sk_buff *skb, unsigned int offset, size_t len)
{
struct rpc_xprt *xprt = rd_desc->arg.data;
struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
struct xdr_skb_reader desc = {
.skb = skb,
.offset = offset,
.count = len,
};
dprintk("RPC: xs_tcp_data_recv started\n");
do {
/* Read in a new fragment marker if necessary */
/* Can we ever really expect to get completely empty fragments? */
if (transport->tcp_flags & TCP_RCV_COPY_FRAGHDR) {
xs_tcp_read_fraghdr(xprt, &desc);
continue;
}
/* Read in the xid if necessary */
if (transport->tcp_flags & TCP_RCV_COPY_XID) {
xs_tcp_read_xid(transport, &desc);
continue;
}
/* Read in the call/reply flag */
if (transport->tcp_flags & TCP_RCV_READ_CALLDIR) {
xs_tcp_read_calldir(transport, &desc);
continue;
}
/* Read in the request data */
if (transport->tcp_flags & TCP_RCV_COPY_DATA) {
xs_tcp_read_data(xprt, &desc);
continue;
}
/* Skip over any trailing bytes on short reads */
xs_tcp_read_discard(transport, &desc);
} while (desc.count);
dprintk("RPC: xs_tcp_data_recv done\n");
return len - desc.count;
}
/**
* xs_tcp_data_ready - "data ready" callback for TCP sockets
* @sk: socket with data to read
* @bytes: how much data to read
*
*/
static void xs_tcp_data_ready(struct sock *sk, int bytes)
{
struct rpc_xprt *xprt;
read_descriptor_t rd_desc;
int read;
dprintk("RPC: xs_tcp_data_ready...\n");
read_lock_bh(&sk->sk_callback_lock);
if (!(xprt = xprt_from_sock(sk)))
goto out;
if (xprt->shutdown)
goto out;
/* Any data means we had a useful conversation, so
* the we don't need to delay the next reconnect
*/
if (xprt->reestablish_timeout)
xprt->reestablish_timeout = 0;
/* We use rd_desc to pass struct xprt to xs_tcp_data_recv */
rd_desc.arg.data = xprt;
do {
rd_desc.count = 65536;
read = tcp_read_sock(sk, &rd_desc, xs_tcp_data_recv);
} while (read > 0);
out:
read_unlock_bh(&sk->sk_callback_lock);
}
/*
* Do the equivalent of linger/linger2 handling for dealing with
* broken servers that don't close the socket in a timely
* fashion
*/
static void xs_tcp_schedule_linger_timeout(struct rpc_xprt *xprt,
unsigned long timeout)
{
struct sock_xprt *transport;
if (xprt_test_and_set_connecting(xprt))
return;
set_bit(XPRT_CONNECTION_ABORT, &xprt->state);
transport = container_of(xprt, struct sock_xprt, xprt);
queue_delayed_work(rpciod_workqueue, &transport->connect_worker,
timeout);
}
static void xs_tcp_cancel_linger_timeout(struct rpc_xprt *xprt)
{
struct sock_xprt *transport;
transport = container_of(xprt, struct sock_xprt, xprt);
if (!test_bit(XPRT_CONNECTION_ABORT, &xprt->state) ||
!cancel_delayed_work(&transport->connect_worker))
return;
clear_bit(XPRT_CONNECTION_ABORT, &xprt->state);
xprt_clear_connecting(xprt);
}
static void xs_sock_reset_connection_flags(struct rpc_xprt *xprt)
{
smp_mb__before_clear_bit();
clear_bit(XPRT_CONNECTION_ABORT, &xprt->state);
clear_bit(XPRT_CONNECTION_CLOSE, &xprt->state);
clear_bit(XPRT_CLOSE_WAIT, &xprt->state);
clear_bit(XPRT_CLOSING, &xprt->state);
smp_mb__after_clear_bit();
}
static void xs_sock_mark_closed(struct rpc_xprt *xprt)
{
xs_sock_reset_connection_flags(xprt);
/* Mark transport as closed and wake up all pending tasks */
xprt_disconnect_done(xprt);
}
/**
* xs_tcp_state_change - callback to handle TCP socket state changes
* @sk: socket whose state has changed
*
*/
static void xs_tcp_state_change(struct sock *sk)
{
struct rpc_xprt *xprt;
read_lock_bh(&sk->sk_callback_lock);
if (!(xprt = xprt_from_sock(sk)))
goto out;
dprintk("RPC: xs_tcp_state_change client %p...\n", xprt);
dprintk("RPC: state %x conn %d dead %d zapped %d sk_shutdown %d\n",
sk->sk_state, xprt_connected(xprt),
sock_flag(sk, SOCK_DEAD),
sock_flag(sk, SOCK_ZAPPED),
sk->sk_shutdown);
switch (sk->sk_state) {
case TCP_ESTABLISHED:
spin_lock(&xprt->transport_lock);
if (!xprt_test_and_set_connected(xprt)) {
struct sock_xprt *transport = container_of(xprt,
struct sock_xprt, xprt);
/* Reset TCP record info */
transport->tcp_offset = 0;
transport->tcp_reclen = 0;
transport->tcp_copied = 0;
transport->tcp_flags =
TCP_RCV_COPY_FRAGHDR | TCP_RCV_COPY_XID;
xprt_wake_pending_tasks(xprt, -EAGAIN);
}
spin_unlock(&xprt->transport_lock);
break;
case TCP_FIN_WAIT1:
/* The client initiated a shutdown of the socket */
xprt->connect_cookie++;
xprt->reestablish_timeout = 0;
set_bit(XPRT_CLOSING, &xprt->state);
smp_mb__before_clear_bit();
clear_bit(XPRT_CONNECTED, &xprt->state);
clear_bit(XPRT_CLOSE_WAIT, &xprt->state);
smp_mb__after_clear_bit();
xs_tcp_schedule_linger_timeout(xprt, xs_tcp_fin_timeout);
break;
case TCP_CLOSE_WAIT:
/* The server initiated a shutdown of the socket */
xprt->connect_cookie++;
clear_bit(XPRT_CONNECTED, &xprt->state);
xs_tcp_force_close(xprt);
case TCP_CLOSING:
/*
* If the server closed down the connection, make sure that
* we back off before reconnecting
*/
if (xprt->reestablish_timeout < XS_TCP_INIT_REEST_TO)
xprt->reestablish_timeout = XS_TCP_INIT_REEST_TO;
break;
case TCP_LAST_ACK:
set_bit(XPRT_CLOSING, &xprt->state);
xs_tcp_schedule_linger_timeout(xprt, xs_tcp_fin_timeout);
smp_mb__before_clear_bit();
clear_bit(XPRT_CONNECTED, &xprt->state);
smp_mb__after_clear_bit();
break;
case TCP_CLOSE:
xs_tcp_cancel_linger_timeout(xprt);
xs_sock_mark_closed(xprt);
}
out:
read_unlock_bh(&sk->sk_callback_lock);
}
static void xs_write_space(struct sock *sk)
{
struct socket *sock;
struct rpc_xprt *xprt;
if (unlikely(!(sock = sk->sk_socket)))
return;
clear_bit(SOCK_NOSPACE, &sock->flags);
if (unlikely(!(xprt = xprt_from_sock(sk))))
return;
if (test_and_clear_bit(SOCK_ASYNC_NOSPACE, &sock->flags) == 0)
return;
xprt_write_space(xprt);
}
/**
* xs_udp_write_space - callback invoked when socket buffer space
* becomes available
* @sk: socket whose state has changed
*
* Called when more output buffer space is available for this socket.
* We try not to wake our writers until they can make "significant"
* progress, otherwise we'll waste resources thrashing kernel_sendmsg
* with a bunch of small requests.
*/
static void xs_udp_write_space(struct sock *sk)
{
read_lock_bh(&sk->sk_callback_lock);
/* from net/core/sock.c:sock_def_write_space */
if (sock_writeable(sk))
xs_write_space(sk);
read_unlock_bh(&sk->sk_callback_lock);
}
/**
* xs_tcp_write_space - callback invoked when socket buffer space
* becomes available
* @sk: socket whose state has changed
*
* Called when more output buffer space is available for this socket.
* We try not to wake our writers until they can make "significant"
* progress, otherwise we'll waste resources thrashing kernel_sendmsg
* with a bunch of small requests.
*/
static void xs_tcp_write_space(struct sock *sk)
{
read_lock_bh(&sk->sk_callback_lock);
/* from net/core/stream.c:sk_stream_write_space */
if (sk_stream_wspace(sk) >= sk_stream_min_wspace(sk))
xs_write_space(sk);
read_unlock_bh(&sk->sk_callback_lock);
}
static void xs_udp_do_set_buffer_size(struct rpc_xprt *xprt)
{
struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
struct sock *sk = transport->inet;
if (transport->rcvsize) {
sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
sk->sk_rcvbuf = transport->rcvsize * xprt->max_reqs * 2;
}
if (transport->sndsize) {
sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
sk->sk_sndbuf = transport->sndsize * xprt->max_reqs * 2;
sk->sk_write_space(sk);
}
}
/**
* xs_udp_set_buffer_size - set send and receive limits
* @xprt: generic transport
* @sndsize: requested size of send buffer, in bytes
* @rcvsize: requested size of receive buffer, in bytes
*
* Set socket send and receive buffer size limits.
*/
static void xs_udp_set_buffer_size(struct rpc_xprt *xprt, size_t sndsize, size_t rcvsize)
{
struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
transport->sndsize = 0;
if (sndsize)
transport->sndsize = sndsize + 1024;
transport->rcvsize = 0;
if (rcvsize)
transport->rcvsize = rcvsize + 1024;
xs_udp_do_set_buffer_size(xprt);
}
/**
* xs_udp_timer - called when a retransmit timeout occurs on a UDP transport
* @task: task that timed out
*
* Adjust the congestion window after a retransmit timeout has occurred.
*/
static void xs_udp_timer(struct rpc_task *task)
{
xprt_adjust_cwnd(task, -ETIMEDOUT);
}
static unsigned short xs_get_random_port(void)
{
unsigned short range = xprt_max_resvport - xprt_min_resvport;
unsigned short rand = (unsigned short) net_random() % range;
return rand + xprt_min_resvport;
}
/**
* xs_set_port - reset the port number in the remote endpoint address
* @xprt: generic transport
* @port: new port number
*
*/
static void xs_set_port(struct rpc_xprt *xprt, unsigned short port)
{
dprintk("RPC: setting port for xprt %p to %u\n", xprt, port);
rpc_set_port(xs_addr(xprt), port);
xs_update_peer_port(xprt);
}
static unsigned short xs_get_srcport(struct sock_xprt *transport)
{
unsigned short port = transport->srcport;
if (port == 0 && transport->xprt.resvport)
port = xs_get_random_port();
return port;
}
static unsigned short xs_next_srcport(struct sock_xprt *transport, unsigned short port)
{
if (transport->srcport != 0)
transport->srcport = 0;
if (!transport->xprt.resvport)
return 0;
if (port <= xprt_min_resvport || port > xprt_max_resvport)
return xprt_max_resvport;
return --port;
}
static int xs_bind(struct sock_xprt *transport, struct socket *sock)
{
struct sockaddr_storage myaddr;
int err, nloop = 0;
unsigned short port = xs_get_srcport(transport);
unsigned short last;
memcpy(&myaddr, &transport->srcaddr, transport->xprt.addrlen);
do {
rpc_set_port((struct sockaddr *)&myaddr, port);
err = kernel_bind(sock, (struct sockaddr *)&myaddr,
transport->xprt.addrlen);
if (port == 0)
break;
if (err == 0) {
transport->srcport = port;
break;
}
last = port;
port = xs_next_srcport(transport, port);
if (port > last)
nloop++;
} while (err == -EADDRINUSE && nloop != 2);
if (myaddr.ss_family == AF_INET)
dprintk("RPC: %s %pI4:%u: %s (%d)\n", __func__,
&((struct sockaddr_in *)&myaddr)->sin_addr,
port, err ? "failed" : "ok", err);
else
dprintk("RPC: %s %pI6:%u: %s (%d)\n", __func__,
&((struct sockaddr_in6 *)&myaddr)->sin6_addr,
port, err ? "failed" : "ok", err);
return err;
}
/*
* We don't support autobind on AF_LOCAL sockets
*/
static void xs_local_rpcbind(struct rpc_task *task)
{
xprt_set_bound(task->tk_xprt);
}
static void xs_local_set_port(struct rpc_xprt *xprt, unsigned short port)
{
}
#ifdef CONFIG_DEBUG_LOCK_ALLOC
static struct lock_class_key xs_key[2];
static struct lock_class_key xs_slock_key[2];
static inline void xs_reclassify_socketu(struct socket *sock)
{
struct sock *sk = sock->sk;
BUG_ON(sock_owned_by_user(sk));
sock_lock_init_class_and_name(sk, "slock-AF_LOCAL-RPC",
&xs_slock_key[1], "sk_lock-AF_LOCAL-RPC", &xs_key[1]);
}
static inline void xs_reclassify_socket4(struct socket *sock)
{
struct sock *sk = sock->sk;
BUG_ON(sock_owned_by_user(sk));
sock_lock_init_class_and_name(sk, "slock-AF_INET-RPC",
&xs_slock_key[0], "sk_lock-AF_INET-RPC", &xs_key[0]);
}
static inline void xs_reclassify_socket6(struct socket *sock)
{
struct sock *sk = sock->sk;
BUG_ON(sock_owned_by_user(sk));
sock_lock_init_class_and_name(sk, "slock-AF_INET6-RPC",
&xs_slock_key[1], "sk_lock-AF_INET6-RPC", &xs_key[1]);
}
static inline void xs_reclassify_socket(int family, struct socket *sock)
{
switch (family) {
case AF_LOCAL:
xs_reclassify_socketu(sock);
break;
case AF_INET:
xs_reclassify_socket4(sock);
break;
case AF_INET6:
xs_reclassify_socket6(sock);
break;
}
}
#else
static inline void xs_reclassify_socketu(struct socket *sock)
{
}
static inline void xs_reclassify_socket4(struct socket *sock)
{
}
static inline void xs_reclassify_socket6(struct socket *sock)
{
}
static inline void xs_reclassify_socket(int family, struct socket *sock)
{
}
#endif
static struct socket *xs_create_sock(struct rpc_xprt *xprt,
struct sock_xprt *transport, int family, int type, int protocol)
{
struct socket *sock;
int err;
err = __sock_create(xprt->xprt_net, family, type, protocol, &sock, 1);
if (err < 0) {
dprintk("RPC: can't create %d transport socket (%d).\n",
protocol, -err);
goto out;
}
xs_reclassify_socket(family, sock);
err = xs_bind(transport, sock);
if (err) {
sock_release(sock);
goto out;
}
return sock;
out:
return ERR_PTR(err);
}
static int xs_local_finish_connecting(struct rpc_xprt *xprt,
struct socket *sock)
{
struct sock_xprt *transport = container_of(xprt, struct sock_xprt,
xprt);
if (!transport->inet) {
struct sock *sk = sock->sk;
write_lock_bh(&sk->sk_callback_lock);
xs_save_old_callbacks(transport, sk);
sk->sk_user_data = xprt;
sk->sk_data_ready = xs_local_data_ready;
sk->sk_write_space = xs_udp_write_space;
sk->sk_allocation = GFP_ATOMIC;
xprt_clear_connected(xprt);
/* Reset to new socket */
transport->sock = sock;
transport->inet = sk;
write_unlock_bh(&sk->sk_callback_lock);
}
/* Tell the socket layer to start connecting... */
xprt->stat.connect_count++;
xprt->stat.connect_start = jiffies;
return kernel_connect(sock, xs_addr(xprt), xprt->addrlen, 0);
}
/**
* xs_local_setup_socket - create AF_LOCAL socket, connect to a local endpoint
* @xprt: RPC transport to connect
* @transport: socket transport to connect
* @create_sock: function to create a socket of the correct type
*
* Invoked by a work queue tasklet.
*/
static void xs_local_setup_socket(struct work_struct *work)
{
struct sock_xprt *transport =
container_of(work, struct sock_xprt, connect_worker.work);
struct rpc_xprt *xprt = &transport->xprt;
struct socket *sock;
int status = -EIO;
if (xprt->shutdown)
goto out;
current->flags |= PF_FSTRANS;
clear_bit(XPRT_CONNECTION_ABORT, &xprt->state);
status = __sock_create(xprt->xprt_net, AF_LOCAL,
SOCK_STREAM, 0, &sock, 1);
if (status < 0) {
dprintk("RPC: can't create AF_LOCAL "
"transport socket (%d).\n", -status);
goto out;
}
xs_reclassify_socketu(sock);
dprintk("RPC: worker connecting xprt %p via AF_LOCAL to %s\n",
xprt, xprt->address_strings[RPC_DISPLAY_ADDR]);
status = xs_local_finish_connecting(xprt, sock);
switch (status) {
case 0:
dprintk("RPC: xprt %p connected to %s\n",
xprt, xprt->address_strings[RPC_DISPLAY_ADDR]);
xprt_set_connected(xprt);
break;
case -ENOENT:
dprintk("RPC: xprt %p: socket %s does not exist\n",
xprt, xprt->address_strings[RPC_DISPLAY_ADDR]);
break;
default:
printk(KERN_ERR "%s: unhandled error (%d) connecting to %s\n",
__func__, -status,
xprt->address_strings[RPC_DISPLAY_ADDR]);
}
out:
xprt_clear_connecting(xprt);
xprt_wake_pending_tasks(xprt, status);
current->flags &= ~PF_FSTRANS;
}
static void xs_udp_finish_connecting(struct rpc_xprt *xprt, struct socket *sock)
{
struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
if (!transport->inet) {
struct sock *sk = sock->sk;
write_lock_bh(&sk->sk_callback_lock);
xs_save_old_callbacks(transport, sk);
sk->sk_user_data = xprt;
sk->sk_data_ready = xs_udp_data_ready;
sk->sk_write_space = xs_udp_write_space;
sk->sk_no_check = UDP_CSUM_NORCV;
sk->sk_allocation = GFP_ATOMIC;
xprt_set_connected(xprt);
/* Reset to new socket */
transport->sock = sock;
transport->inet = sk;
write_unlock_bh(&sk->sk_callback_lock);
}
xs_udp_do_set_buffer_size(xprt);
}
static void xs_udp_setup_socket(struct work_struct *work)
{
struct sock_xprt *transport =
container_of(work, struct sock_xprt, connect_worker.work);
struct rpc_xprt *xprt = &transport->xprt;
struct socket *sock = transport->sock;
int status = -EIO;
if (xprt->shutdown)
goto out;
current->flags |= PF_FSTRANS;
/* Start by resetting any existing state */
xs_reset_transport(transport);
sock = xs_create_sock(xprt, transport,
xs_addr(xprt)->sa_family, SOCK_DGRAM, IPPROTO_UDP);
if (IS_ERR(sock))
goto out;
dprintk("RPC: worker connecting xprt %p via %s to "
"%s (port %s)\n", xprt,
xprt->address_strings[RPC_DISPLAY_PROTO],
xprt->address_strings[RPC_DISPLAY_ADDR],
xprt->address_strings[RPC_DISPLAY_PORT]);
xs_udp_finish_connecting(xprt, sock);
status = 0;
out:
xprt_clear_connecting(xprt);
xprt_wake_pending_tasks(xprt, status);
current->flags &= ~PF_FSTRANS;
}
/*
* We need to preserve the port number so the reply cache on the server can
* find our cached RPC replies when we get around to reconnecting.
*/
static void xs_abort_connection(struct sock_xprt *transport)
{
int result;
struct sockaddr any;
dprintk("RPC: disconnecting xprt %p to reuse port\n", transport);
/*
* Disconnect the transport socket by doing a connect operation
* with AF_UNSPEC. This should return immediately...
*/
memset(&any, 0, sizeof(any));
any.sa_family = AF_UNSPEC;
result = kernel_connect(transport->sock, &any, sizeof(any), 0);
if (!result)
xs_sock_reset_connection_flags(&transport->xprt);
dprintk("RPC: AF_UNSPEC connect return code %d\n", result);
}
static void xs_tcp_reuse_connection(struct sock_xprt *transport)
{
unsigned int state = transport->inet->sk_state;
if (state == TCP_CLOSE && transport->sock->state == SS_UNCONNECTED) {
/* we don't need to abort the connection if the socket
* hasn't undergone a shutdown
*/
if (transport->inet->sk_shutdown == 0)
return;
dprintk("RPC: %s: TCP_CLOSEd and sk_shutdown set to %d\n",
__func__, transport->inet->sk_shutdown);
}
if ((1 << state) & (TCPF_ESTABLISHED|TCPF_SYN_SENT)) {
/* we don't need to abort the connection if the socket
* hasn't undergone a shutdown
*/
if (transport->inet->sk_shutdown == 0)
return;
dprintk("RPC: %s: ESTABLISHED/SYN_SENT "
"sk_shutdown set to %d\n",
__func__, transport->inet->sk_shutdown);
}
xs_abort_connection(transport);
}
static int xs_tcp_finish_connecting(struct rpc_xprt *xprt, struct socket *sock)
{
struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
int ret = -ENOTCONN;
if (!transport->inet) {
struct sock *sk = sock->sk;
write_lock_bh(&sk->sk_callback_lock);
xs_save_old_callbacks(transport, sk);
sk->sk_user_data = xprt;
sk->sk_data_ready = xs_tcp_data_ready;
sk->sk_state_change = xs_tcp_state_change;
sk->sk_write_space = xs_tcp_write_space;
sk->sk_allocation = GFP_ATOMIC;
/* socket options */
sk->sk_userlocks |= SOCK_BINDPORT_LOCK;
sock_reset_flag(sk, SOCK_LINGER);
tcp_sk(sk)->linger2 = 0;
tcp_sk(sk)->nonagle |= TCP_NAGLE_OFF;
xprt_clear_connected(xprt);
/* Reset to new socket */
transport->sock = sock;
transport->inet = sk;
write_unlock_bh(&sk->sk_callback_lock);
}
if (!xprt_bound(xprt))
goto out;
/* Tell the socket layer to start connecting... */
xprt->stat.connect_count++;
xprt->stat.connect_start = jiffies;
ret = kernel_connect(sock, xs_addr(xprt), xprt->addrlen, O_NONBLOCK);
switch (ret) {
case 0:
case -EINPROGRESS:
/* SYN_SENT! */
xprt->connect_cookie++;
if (xprt->reestablish_timeout < XS_TCP_INIT_REEST_TO)
xprt->reestablish_timeout = XS_TCP_INIT_REEST_TO;
}
out:
return ret;
}
/**
* xs_tcp_setup_socket - create a TCP socket and connect to a remote endpoint
* @xprt: RPC transport to connect
* @transport: socket transport to connect
* @create_sock: function to create a socket of the correct type
*
* Invoked by a work queue tasklet.
*/
static void xs_tcp_setup_socket(struct work_struct *work)
{
struct sock_xprt *transport =
container_of(work, struct sock_xprt, connect_worker.work);
struct socket *sock = transport->sock;
struct rpc_xprt *xprt = &transport->xprt;
int status = -EIO;
if (xprt->shutdown)
goto out;
current->flags |= PF_FSTRANS;
if (!sock) {
clear_bit(XPRT_CONNECTION_ABORT, &xprt->state);
sock = xs_create_sock(xprt, transport,
xs_addr(xprt)->sa_family, SOCK_STREAM, IPPROTO_TCP);
if (IS_ERR(sock)) {
status = PTR_ERR(sock);
goto out;
}
} else {
int abort_and_exit;
abort_and_exit = test_and_clear_bit(XPRT_CONNECTION_ABORT,
&xprt->state);
/* "close" the socket, preserving the local port */
xs_tcp_reuse_connection(transport);
if (abort_and_exit)
goto out_eagain;
}
dprintk("RPC: worker connecting xprt %p via %s to "
"%s (port %s)\n", xprt,
xprt->address_strings[RPC_DISPLAY_PROTO],
xprt->address_strings[RPC_DISPLAY_ADDR],
xprt->address_strings[RPC_DISPLAY_PORT]);
status = xs_tcp_finish_connecting(xprt, sock);
dprintk("RPC: %p connect status %d connected %d sock state %d\n",
xprt, -status, xprt_connected(xprt),
sock->sk->sk_state);
switch (status) {
default:
printk("%s: connect returned unhandled error %d\n",
__func__, status);
case -EADDRNOTAVAIL:
/* We're probably in TIME_WAIT. Get rid of existing socket,
* and retry
*/
xs_tcp_force_close(xprt);
break;
case -ECONNREFUSED:
case -ECONNRESET:
case -ENETUNREACH:
/* retry with existing socket, after a delay */
case 0:
case -EINPROGRESS:
case -EALREADY:
xprt_clear_connecting(xprt);
current->flags &= ~PF_FSTRANS;
return;
case -EINVAL:
/* Happens, for instance, if the user specified a link
* local IPv6 address without a scope-id.
*/
goto out;
}
out_eagain:
status = -EAGAIN;
out:
xprt_clear_connecting(xprt);
xprt_wake_pending_tasks(xprt, status);
current->flags &= ~PF_FSTRANS;
}
/**
* xs_connect - connect a socket to a remote endpoint
* @task: address of RPC task that manages state of connect request
*
* TCP: If the remote end dropped the connection, delay reconnecting.
*
* UDP socket connects are synchronous, but we use a work queue anyway
* to guarantee that even unprivileged user processes can set up a
* socket on a privileged port.
*
* If a UDP socket connect fails, the delay behavior here prevents
* retry floods (hard mounts).
*/
static void xs_connect(struct rpc_task *task)
{
struct rpc_xprt *xprt = task->tk_xprt;
struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
if (transport->sock != NULL && !RPC_IS_SOFTCONN(task)) {
dprintk("RPC: xs_connect delayed xprt %p for %lu "
"seconds\n",
xprt, xprt->reestablish_timeout / HZ);
queue_delayed_work(rpciod_workqueue,
&transport->connect_worker,
xprt->reestablish_timeout);
xprt->reestablish_timeout <<= 1;
if (xprt->reestablish_timeout < XS_TCP_INIT_REEST_TO)
xprt->reestablish_timeout = XS_TCP_INIT_REEST_TO;
if (xprt->reestablish_timeout > XS_TCP_MAX_REEST_TO)
xprt->reestablish_timeout = XS_TCP_MAX_REEST_TO;
} else {
dprintk("RPC: xs_connect scheduled xprt %p\n", xprt);
queue_delayed_work(rpciod_workqueue,
&transport->connect_worker, 0);
}
}
/**
* xs_local_print_stats - display AF_LOCAL socket-specifc stats
* @xprt: rpc_xprt struct containing statistics
* @seq: output file
*
*/
static void xs_local_print_stats(struct rpc_xprt *xprt, struct seq_file *seq)
{
long idle_time = 0;
if (xprt_connected(xprt))
idle_time = (long)(jiffies - xprt->last_used) / HZ;
seq_printf(seq, "\txprt:\tlocal %lu %lu %lu %ld %lu %lu %lu "
"%llu %llu %lu %llu %llu\n",
xprt->stat.bind_count,
xprt->stat.connect_count,
xprt->stat.connect_time,
idle_time,
xprt->stat.sends,
xprt->stat.recvs,
xprt->stat.bad_xids,
xprt->stat.req_u,
xprt->stat.bklog_u,
xprt->stat.max_slots,
xprt->stat.sending_u,
xprt->stat.pending_u);
}
/**
* xs_udp_print_stats - display UDP socket-specifc stats
* @xprt: rpc_xprt struct containing statistics
* @seq: output file
*
*/
static void xs_udp_print_stats(struct rpc_xprt *xprt, struct seq_file *seq)
{
struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
seq_printf(seq, "\txprt:\tudp %u %lu %lu %lu %lu %llu %llu "
"%lu %llu %llu\n",
transport->srcport,
xprt->stat.bind_count,
xprt->stat.sends,
xprt->stat.recvs,
xprt->stat.bad_xids,
xprt->stat.req_u,
xprt->stat.bklog_u,
xprt->stat.max_slots,
xprt->stat.sending_u,
xprt->stat.pending_u);
}
/**
* xs_tcp_print_stats - display TCP socket-specifc stats
* @xprt: rpc_xprt struct containing statistics
* @seq: output file
*
*/
static void xs_tcp_print_stats(struct rpc_xprt *xprt, struct seq_file *seq)
{
struct sock_xprt *transport = container_of(xprt, struct sock_xprt, xprt);
long idle_time = 0;
if (xprt_connected(xprt))
idle_time = (long)(jiffies - xprt->last_used) / HZ;
seq_printf(seq, "\txprt:\ttcp %u %lu %lu %lu %ld %lu %lu %lu "
"%llu %llu %lu %llu %llu\n",
transport->srcport,
xprt->stat.bind_count,
xprt->stat.connect_count,
xprt->stat.connect_time,
idle_time,
xprt->stat.sends,
xprt->stat.recvs,
xprt->stat.bad_xids,
xprt->stat.req_u,
xprt->stat.bklog_u,
xprt->stat.max_slots,
xprt->stat.sending_u,
xprt->stat.pending_u);
}
/*
* Allocate a bunch of pages for a scratch buffer for the rpc code. The reason
* we allocate pages instead doing a kmalloc like rpc_malloc is because we want
* to use the server side send routines.
*/
static void *bc_malloc(struct rpc_task *task, size_t size)
{
struct page *page;
struct rpc_buffer *buf;
BUG_ON(size > PAGE_SIZE - sizeof(struct rpc_buffer));
page = alloc_page(GFP_KERNEL);
if (!page)
return NULL;
buf = page_address(page);
buf->len = PAGE_SIZE;
return buf->data;
}
/*
* Free the space allocated in the bc_alloc routine
*/
static void bc_free(void *buffer)
{
struct rpc_buffer *buf;
if (!buffer)
return;
buf = container_of(buffer, struct rpc_buffer, data);
free_page((unsigned long)buf);
}
/*
* Use the svc_sock to send the callback. Must be called with svsk->sk_mutex
* held. Borrows heavily from svc_tcp_sendto and xs_tcp_send_request.
*/
static int bc_sendto(struct rpc_rqst *req)
{
int len;
struct xdr_buf *xbufp = &req->rq_snd_buf;
struct rpc_xprt *xprt = req->rq_xprt;
struct sock_xprt *transport =
container_of(xprt, struct sock_xprt, xprt);
struct socket *sock = transport->sock;
unsigned long headoff;
unsigned long tailoff;
xs_encode_stream_record_marker(xbufp);
tailoff = (unsigned long)xbufp->tail[0].iov_base & ~PAGE_MASK;
headoff = (unsigned long)xbufp->head[0].iov_base & ~PAGE_MASK;
len = svc_send_common(sock, xbufp,
virt_to_page(xbufp->head[0].iov_base), headoff,
xbufp->tail[0].iov_base, tailoff);
if (len != xbufp->len) {
printk(KERN_NOTICE "Error sending entire callback!\n");
len = -EAGAIN;
}
return len;
}
/*
* The send routine. Borrows from svc_send
*/
static int bc_send_request(struct rpc_task *task)
{
struct rpc_rqst *req = task->tk_rqstp;
struct svc_xprt *xprt;
struct svc_sock *svsk;
u32 len;
dprintk("sending request with xid: %08x\n", ntohl(req->rq_xid));
/*
* Get the server socket associated with this callback xprt
*/
xprt = req->rq_xprt->bc_xprt;
svsk = container_of(xprt, struct svc_sock, sk_xprt);
/*
* Grab the mutex to serialize data as the connection is shared
* with the fore channel
*/
if (!mutex_trylock(&xprt->xpt_mutex)) {
rpc_sleep_on(&xprt->xpt_bc_pending, task, NULL);
if (!mutex_trylock(&xprt->xpt_mutex))
return -EAGAIN;
rpc_wake_up_queued_task(&xprt->xpt_bc_pending, task);
}
if (test_bit(XPT_DEAD, &xprt->xpt_flags))
len = -ENOTCONN;
else
len = bc_sendto(req);
mutex_unlock(&xprt->xpt_mutex);
if (len > 0)
len = 0;
return len;
}
/*
* The close routine. Since this is client initiated, we do nothing
*/
static void bc_close(struct rpc_xprt *xprt)
{
}
/*
* The xprt destroy routine. Again, because this connection is client
* initiated, we do nothing
*/
static void bc_destroy(struct rpc_xprt *xprt)
{
}
static struct rpc_xprt_ops xs_local_ops = {
.reserve_xprt = xprt_reserve_xprt,
.release_xprt = xs_tcp_release_xprt,
.alloc_slot = xprt_alloc_slot,
.rpcbind = xs_local_rpcbind,
.set_port = xs_local_set_port,
.connect = xs_connect,
.buf_alloc = rpc_malloc,
.buf_free = rpc_free,
.send_request = xs_local_send_request,
.set_retrans_timeout = xprt_set_retrans_timeout_def,
.close = xs_close,
.destroy = xs_destroy,
.print_stats = xs_local_print_stats,
};
static struct rpc_xprt_ops xs_udp_ops = {
.set_buffer_size = xs_udp_set_buffer_size,
.reserve_xprt = xprt_reserve_xprt_cong,
.release_xprt = xprt_release_xprt_cong,
.alloc_slot = xprt_alloc_slot,
.rpcbind = rpcb_getport_async,
.set_port = xs_set_port,
.connect = xs_connect,
.buf_alloc = rpc_malloc,
.buf_free = rpc_free,
.send_request = xs_udp_send_request,
.set_retrans_timeout = xprt_set_retrans_timeout_rtt,
.timer = xs_udp_timer,
.release_request = xprt_release_rqst_cong,
.close = xs_close,
.destroy = xs_destroy,
.print_stats = xs_udp_print_stats,
};
static struct rpc_xprt_ops xs_tcp_ops = {
.reserve_xprt = xprt_reserve_xprt,
.release_xprt = xs_tcp_release_xprt,
.alloc_slot = xprt_lock_and_alloc_slot,
.rpcbind = rpcb_getport_async,
.set_port = xs_set_port,
.connect = xs_connect,
.buf_alloc = rpc_malloc,
.buf_free = rpc_free,
.send_request = xs_tcp_send_request,
.set_retrans_timeout = xprt_set_retrans_timeout_def,
.close = xs_tcp_close,
.destroy = xs_destroy,
.print_stats = xs_tcp_print_stats,
};
/*
* The rpc_xprt_ops for the server backchannel
*/
static struct rpc_xprt_ops bc_tcp_ops = {
.reserve_xprt = xprt_reserve_xprt,
.release_xprt = xprt_release_xprt,
.alloc_slot = xprt_alloc_slot,
.rpcbind = xs_local_rpcbind,
.buf_alloc = bc_malloc,
.buf_free = bc_free,
.send_request = bc_send_request,
.set_retrans_timeout = xprt_set_retrans_timeout_def,
.close = bc_close,
.destroy = bc_destroy,
.print_stats = xs_tcp_print_stats,
};
static int xs_init_anyaddr(const int family, struct sockaddr *sap)
{
static const struct sockaddr_in sin = {
.sin_family = AF_INET,
.sin_addr.s_addr = htonl(INADDR_ANY),
};
static const struct sockaddr_in6 sin6 = {
.sin6_family = AF_INET6,
.sin6_addr = IN6ADDR_ANY_INIT,
};
switch (family) {
case AF_LOCAL:
break;
case AF_INET:
memcpy(sap, &sin, sizeof(sin));
break;
case AF_INET6:
memcpy(sap, &sin6, sizeof(sin6));
break;
default:
dprintk("RPC: %s: Bad address family\n", __func__);
return -EAFNOSUPPORT;
}
return 0;
}
static struct rpc_xprt *xs_setup_xprt(struct xprt_create *args,
unsigned int slot_table_size,
unsigned int max_slot_table_size)
{
struct rpc_xprt *xprt;
struct sock_xprt *new;
if (args->addrlen > sizeof(xprt->addr)) {
dprintk("RPC: xs_setup_xprt: address too large\n");
return ERR_PTR(-EBADF);
}
xprt = xprt_alloc(args->net, sizeof(*new), slot_table_size,
max_slot_table_size);
if (xprt == NULL) {
dprintk("RPC: xs_setup_xprt: couldn't allocate "
"rpc_xprt\n");
return ERR_PTR(-ENOMEM);
}
new = container_of(xprt, struct sock_xprt, xprt);
memcpy(&xprt->addr, args->dstaddr, args->addrlen);
xprt->addrlen = args->addrlen;
if (args->srcaddr)
memcpy(&new->srcaddr, args->srcaddr, args->addrlen);
else {
int err;
err = xs_init_anyaddr(args->dstaddr->sa_family,
(struct sockaddr *)&new->srcaddr);
if (err != 0) {
xprt_free(xprt);
return ERR_PTR(err);
}
}
return xprt;
}
static const struct rpc_timeout xs_local_default_timeout = {
.to_initval = 10 * HZ,
.to_maxval = 10 * HZ,
.to_retries = 2,
};
/**
* xs_setup_local - Set up transport to use an AF_LOCAL socket
* @args: rpc transport creation arguments
*
* AF_LOCAL is a "tpi_cots_ord" transport, just like TCP
*/
static struct rpc_xprt *xs_setup_local(struct xprt_create *args)
{
struct sockaddr_un *sun = (struct sockaddr_un *)args->dstaddr;
struct sock_xprt *transport;
struct rpc_xprt *xprt;
struct rpc_xprt *ret;
xprt = xs_setup_xprt(args, xprt_tcp_slot_table_entries,
xprt_max_tcp_slot_table_entries);
if (IS_ERR(xprt))
return xprt;
transport = container_of(xprt, struct sock_xprt, xprt);
xprt->prot = 0;
xprt->tsh_size = sizeof(rpc_fraghdr) / sizeof(u32);
xprt->max_payload = RPC_MAX_FRAGMENT_SIZE;
xprt->bind_timeout = XS_BIND_TO;
xprt->reestablish_timeout = XS_TCP_INIT_REEST_TO;
xprt->idle_timeout = XS_IDLE_DISC_TO;
xprt->ops = &xs_local_ops;
xprt->timeout = &xs_local_default_timeout;
switch (sun->sun_family) {
case AF_LOCAL:
if (sun->sun_path[0] != '/') {
dprintk("RPC: bad AF_LOCAL address: %s\n",
sun->sun_path);
ret = ERR_PTR(-EINVAL);
goto out_err;
}
xprt_set_bound(xprt);
INIT_DELAYED_WORK(&transport->connect_worker,
xs_local_setup_socket);
xs_format_peer_addresses(xprt, "local", RPCBIND_NETID_LOCAL);
break;
default:
ret = ERR_PTR(-EAFNOSUPPORT);
goto out_err;
}
dprintk("RPC: set up xprt to %s via AF_LOCAL\n",
xprt->address_strings[RPC_DISPLAY_ADDR]);
if (try_module_get(THIS_MODULE))
return xprt;
ret = ERR_PTR(-EINVAL);
out_err:
xprt_free(xprt);
return ret;
}
static const struct rpc_timeout xs_udp_default_timeout = {
.to_initval = 5 * HZ,
.to_maxval = 30 * HZ,
.to_increment = 5 * HZ,
.to_retries = 5,
};
/**
* xs_setup_udp - Set up transport to use a UDP socket
* @args: rpc transport creation arguments
*
*/
static struct rpc_xprt *xs_setup_udp(struct xprt_create *args)
{
struct sockaddr *addr = args->dstaddr;
struct rpc_xprt *xprt;
struct sock_xprt *transport;
struct rpc_xprt *ret;
xprt = xs_setup_xprt(args, xprt_udp_slot_table_entries,
xprt_udp_slot_table_entries);
if (IS_ERR(xprt))
return xprt;
transport = container_of(xprt, struct sock_xprt, xprt);
xprt->prot = IPPROTO_UDP;
xprt->tsh_size = 0;
/* XXX: header size can vary due to auth type, IPv6, etc. */
xprt->max_payload = (1U << 16) - (MAX_HEADER << 3);
xprt->bind_timeout = XS_BIND_TO;
xprt->reestablish_timeout = XS_UDP_REEST_TO;
xprt->idle_timeout = XS_IDLE_DISC_TO;
xprt->ops = &xs_udp_ops;
xprt->timeout = &xs_udp_default_timeout;
switch (addr->sa_family) {
case AF_INET:
if (((struct sockaddr_in *)addr)->sin_port != htons(0))
xprt_set_bound(xprt);
INIT_DELAYED_WORK(&transport->connect_worker,
xs_udp_setup_socket);
xs_format_peer_addresses(xprt, "udp", RPCBIND_NETID_UDP);
break;
case AF_INET6:
if (((struct sockaddr_in6 *)addr)->sin6_port != htons(0))
xprt_set_bound(xprt);
INIT_DELAYED_WORK(&transport->connect_worker,
xs_udp_setup_socket);
xs_format_peer_addresses(xprt, "udp", RPCBIND_NETID_UDP6);
break;
default:
ret = ERR_PTR(-EAFNOSUPPORT);
goto out_err;
}
if (xprt_bound(xprt))
dprintk("RPC: set up xprt to %s (port %s) via %s\n",
xprt->address_strings[RPC_DISPLAY_ADDR],
xprt->address_strings[RPC_DISPLAY_PORT],
xprt->address_strings[RPC_DISPLAY_PROTO]);
else
dprintk("RPC: set up xprt to %s (autobind) via %s\n",
xprt->address_strings[RPC_DISPLAY_ADDR],
xprt->address_strings[RPC_DISPLAY_PROTO]);
if (try_module_get(THIS_MODULE))
return xprt;
ret = ERR_PTR(-EINVAL);
out_err:
xprt_free(xprt);
return ret;
}
static const struct rpc_timeout xs_tcp_default_timeout = {
.to_initval = 60 * HZ,
.to_maxval = 60 * HZ,
.to_retries = 2,
};
/**
* xs_setup_tcp - Set up transport to use a TCP socket
* @args: rpc transport creation arguments
*
*/
static struct rpc_xprt *xs_setup_tcp(struct xprt_create *args)
{
struct sockaddr *addr = args->dstaddr;
struct rpc_xprt *xprt;
struct sock_xprt *transport;
struct rpc_xprt *ret;
xprt = xs_setup_xprt(args, xprt_tcp_slot_table_entries,
xprt_max_tcp_slot_table_entries);
if (IS_ERR(xprt))
return xprt;
transport = container_of(xprt, struct sock_xprt, xprt);
xprt->prot = IPPROTO_TCP;
xprt->tsh_size = sizeof(rpc_fraghdr) / sizeof(u32);
xprt->max_payload = RPC_MAX_FRAGMENT_SIZE;
xprt->bind_timeout = XS_BIND_TO;
xprt->reestablish_timeout = XS_TCP_INIT_REEST_TO;
xprt->idle_timeout = XS_IDLE_DISC_TO;
xprt->ops = &xs_tcp_ops;
xprt->timeout = &xs_tcp_default_timeout;
switch (addr->sa_family) {
case AF_INET:
if (((struct sockaddr_in *)addr)->sin_port != htons(0))
xprt_set_bound(xprt);
INIT_DELAYED_WORK(&transport->connect_worker,
xs_tcp_setup_socket);
xs_format_peer_addresses(xprt, "tcp", RPCBIND_NETID_TCP);
break;
case AF_INET6:
if (((struct sockaddr_in6 *)addr)->sin6_port != htons(0))
xprt_set_bound(xprt);
INIT_DELAYED_WORK(&transport->connect_worker,
xs_tcp_setup_socket);
xs_format_peer_addresses(xprt, "tcp", RPCBIND_NETID_TCP6);
break;
default:
ret = ERR_PTR(-EAFNOSUPPORT);
goto out_err;
}
if (xprt_bound(xprt))
dprintk("RPC: set up xprt to %s (port %s) via %s\n",
xprt->address_strings[RPC_DISPLAY_ADDR],
xprt->address_strings[RPC_DISPLAY_PORT],
xprt->address_strings[RPC_DISPLAY_PROTO]);
else
dprintk("RPC: set up xprt to %s (autobind) via %s\n",
xprt->address_strings[RPC_DISPLAY_ADDR],
xprt->address_strings[RPC_DISPLAY_PROTO]);
if (try_module_get(THIS_MODULE))
return xprt;
ret = ERR_PTR(-EINVAL);
out_err:
xprt_free(xprt);
return ret;
}
/**
* xs_setup_bc_tcp - Set up transport to use a TCP backchannel socket
* @args: rpc transport creation arguments
*
*/
static struct rpc_xprt *xs_setup_bc_tcp(struct xprt_create *args)
{
struct sockaddr *addr = args->dstaddr;
struct rpc_xprt *xprt;
struct sock_xprt *transport;
struct svc_sock *bc_sock;
struct rpc_xprt *ret;
if (args->bc_xprt->xpt_bc_xprt) {
/*
* This server connection already has a backchannel
* export; we can't create a new one, as we wouldn't be
* able to match replies based on xid any more. So,
* reuse the already-existing one:
*/
return args->bc_xprt->xpt_bc_xprt;
}
xprt = xs_setup_xprt(args, xprt_tcp_slot_table_entries,
xprt_tcp_slot_table_entries);
if (IS_ERR(xprt))
return xprt;
transport = container_of(xprt, struct sock_xprt, xprt);
xprt->prot = IPPROTO_TCP;
xprt->tsh_size = sizeof(rpc_fraghdr) / sizeof(u32);
xprt->max_payload = RPC_MAX_FRAGMENT_SIZE;
xprt->timeout = &xs_tcp_default_timeout;
/* backchannel */
xprt_set_bound(xprt);
xprt->bind_timeout = 0;
xprt->reestablish_timeout = 0;
xprt->idle_timeout = 0;
xprt->ops = &bc_tcp_ops;
switch (addr->sa_family) {
case AF_INET:
xs_format_peer_addresses(xprt, "tcp",
RPCBIND_NETID_TCP);
break;
case AF_INET6:
xs_format_peer_addresses(xprt, "tcp",
RPCBIND_NETID_TCP6);
break;
default:
ret = ERR_PTR(-EAFNOSUPPORT);
goto out_err;
}
dprintk("RPC: set up xprt to %s (port %s) via %s\n",
xprt->address_strings[RPC_DISPLAY_ADDR],
xprt->address_strings[RPC_DISPLAY_PORT],
xprt->address_strings[RPC_DISPLAY_PROTO]);
/*
* Once we've associated a backchannel xprt with a connection,
* we want to keep it around as long as long as the connection
* lasts, in case we need to start using it for a backchannel
* again; this reference won't be dropped until bc_xprt is
* destroyed.
*/
xprt_get(xprt);
args->bc_xprt->xpt_bc_xprt = xprt;
xprt->bc_xprt = args->bc_xprt;
bc_sock = container_of(args->bc_xprt, struct svc_sock, sk_xprt);
transport->sock = bc_sock->sk_sock;
transport->inet = bc_sock->sk_sk;
/*
* Since we don't want connections for the backchannel, we set
* the xprt status to connected
*/
xprt_set_connected(xprt);
if (try_module_get(THIS_MODULE))
return xprt;
xprt_put(xprt);
ret = ERR_PTR(-EINVAL);
out_err:
xprt_free(xprt);
return ret;
}
static struct xprt_class xs_local_transport = {
.list = LIST_HEAD_INIT(xs_local_transport.list),
.name = "named UNIX socket",
.owner = THIS_MODULE,
.ident = XPRT_TRANSPORT_LOCAL,
.setup = xs_setup_local,
};
static struct xprt_class xs_udp_transport = {
.list = LIST_HEAD_INIT(xs_udp_transport.list),
.name = "udp",
.owner = THIS_MODULE,
.ident = XPRT_TRANSPORT_UDP,
.setup = xs_setup_udp,
};
static struct xprt_class xs_tcp_transport = {
.list = LIST_HEAD_INIT(xs_tcp_transport.list),
.name = "tcp",
.owner = THIS_MODULE,
.ident = XPRT_TRANSPORT_TCP,
.setup = xs_setup_tcp,
};
static struct xprt_class xs_bc_tcp_transport = {
.list = LIST_HEAD_INIT(xs_bc_tcp_transport.list),
.name = "tcp NFSv4.1 backchannel",
.owner = THIS_MODULE,
.ident = XPRT_TRANSPORT_BC_TCP,
.setup = xs_setup_bc_tcp,
};
/**
* init_socket_xprt - set up xprtsock's sysctls, register with RPC client
*
*/
int init_socket_xprt(void)
{
#ifdef RPC_DEBUG
if (!sunrpc_table_header)
sunrpc_table_header = register_sysctl_table(sunrpc_table);
#endif
xprt_register_transport(&xs_local_transport);
xprt_register_transport(&xs_udp_transport);
xprt_register_transport(&xs_tcp_transport);
xprt_register_transport(&xs_bc_tcp_transport);
return 0;
}
/**
* cleanup_socket_xprt - remove xprtsock's sysctls, unregister
*
*/
void cleanup_socket_xprt(void)
{
#ifdef RPC_DEBUG
if (sunrpc_table_header) {
unregister_sysctl_table(sunrpc_table_header);
sunrpc_table_header = NULL;
}
#endif
xprt_unregister_transport(&xs_local_transport);
xprt_unregister_transport(&xs_udp_transport);
xprt_unregister_transport(&xs_tcp_transport);
xprt_unregister_transport(&xs_bc_tcp_transport);
}
static int param_set_uint_minmax(const char *val,
const struct kernel_param *kp,
unsigned int min, unsigned int max)
{
unsigned long num;
int ret;
if (!val)
return -EINVAL;
ret = strict_strtoul(val, 0, &num);
if (ret == -EINVAL || num < min || num > max)
return -EINVAL;
*((unsigned int *)kp->arg) = num;
return 0;
}
static int param_set_portnr(const char *val, const struct kernel_param *kp)
{
return param_set_uint_minmax(val, kp,
RPC_MIN_RESVPORT,
RPC_MAX_RESVPORT);
}
static struct kernel_param_ops param_ops_portnr = {
.set = param_set_portnr,
.get = param_get_uint,
};
#define param_check_portnr(name, p) \
__param_check(name, p, unsigned int);
module_param_named(min_resvport, xprt_min_resvport, portnr, 0644);
module_param_named(max_resvport, xprt_max_resvport, portnr, 0644);
static int param_set_slot_table_size(const char *val,
const struct kernel_param *kp)
{
return param_set_uint_minmax(val, kp,
RPC_MIN_SLOT_TABLE,
RPC_MAX_SLOT_TABLE);
}
static struct kernel_param_ops param_ops_slot_table_size = {
.set = param_set_slot_table_size,
.get = param_get_uint,
};
#define param_check_slot_table_size(name, p) \
__param_check(name, p, unsigned int);
static int param_set_max_slot_table_size(const char *val,
const struct kernel_param *kp)
{
return param_set_uint_minmax(val, kp,
RPC_MIN_SLOT_TABLE,
RPC_MAX_SLOT_TABLE_LIMIT);
}
static struct kernel_param_ops param_ops_max_slot_table_size = {
.set = param_set_max_slot_table_size,
.get = param_get_uint,
};
#define param_check_max_slot_table_size(name, p) \
__param_check(name, p, unsigned int);
module_param_named(tcp_slot_table_entries, xprt_tcp_slot_table_entries,
slot_table_size, 0644);
module_param_named(tcp_max_slot_table_entries, xprt_max_tcp_slot_table_entries,
max_slot_table_size, 0644);
module_param_named(udp_slot_table_entries, xprt_udp_slot_table_entries,
slot_table_size, 0644);
| {
"pile_set_name": "Github"
} |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.action.percolate;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.CompositeIndicesRequest;
import org.elasticsearch.action.IndicesRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.XContent;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.elasticsearch.action.ValidateActions.addValidationError;
import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeStringArrayValue;
import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeStringValue;
/**
* A multi percolate request that encapsulates multiple {@link PercolateRequest} instances in a single api call.
*/
public class MultiPercolateRequest extends ActionRequest<MultiPercolateRequest> implements CompositeIndicesRequest {
private String[] indices;
private String documentType;
private IndicesOptions indicesOptions = IndicesOptions.strictExpandOpenAndForbidClosed();
private List<PercolateRequest> requests = new ArrayList<>();
/**
* Embeds a percolate request to this multi percolate request
*/
public MultiPercolateRequest add(PercolateRequestBuilder requestBuilder) {
return add(requestBuilder.request());
}
/**
* Embeds a percolate request to this multi percolate request
*/
public MultiPercolateRequest add(PercolateRequest request) {
if (request.indices() == null && indices != null) {
request.indices(indices);
}
if (request.documentType() == null && documentType != null) {
request.documentType(documentType);
}
if (request.indicesOptions() == IndicesOptions.strictExpandOpenAndForbidClosed() && indicesOptions != IndicesOptions.strictExpandOpenAndForbidClosed()) {
request.indicesOptions(indicesOptions);
}
requests.add(request);
return this;
}
/**
* Embeds a percolate request which request body is defined as raw bytes to this multi percolate request
*/
public MultiPercolateRequest add(byte[] data, int from, int length) throws Exception {
return add(new BytesArray(data, from, length), true);
}
/**
* Embeds a percolate request which request body is defined as raw bytes to this multi percolate request
*/
public MultiPercolateRequest add(BytesReference data, boolean allowExplicitIndex) throws Exception {
XContent xContent = XContentFactory.xContent(data);
int from = 0;
int length = data.length();
byte marker = xContent.streamSeparator();
while (true) {
int nextMarker = findNextMarker(marker, from, data, length);
if (nextMarker == -1) {
break;
}
// support first line with \n
if (nextMarker == 0) {
from = nextMarker + 1;
continue;
}
PercolateRequest percolateRequest = new PercolateRequest();
if (indices != null) {
percolateRequest.indices(indices);
}
if (documentType != null) {
percolateRequest.documentType(documentType);
}
if (indicesOptions != IndicesOptions.strictExpandOpenAndForbidClosed()) {
percolateRequest.indicesOptions(indicesOptions);
}
// now parse the action
if (nextMarker - from > 0) {
try (XContentParser parser = xContent.createParser(data.slice(from, nextMarker - from))) {
// Move to START_OBJECT, if token is null, its an empty data
XContentParser.Token token = parser.nextToken();
if (token != null) {
// Top level json object
assert token == XContentParser.Token.START_OBJECT;
token = parser.nextToken();
if (token != XContentParser.Token.FIELD_NAME) {
throw new ElasticsearchParseException("Expected field");
}
token = parser.nextToken();
if (token != XContentParser.Token.START_OBJECT) {
throw new ElasticsearchParseException("expected start object");
}
String percolateAction = parser.currentName();
if ("percolate".equals(percolateAction)) {
parsePercolateAction(parser, percolateRequest, allowExplicitIndex);
} else if ("count".equals(percolateAction)) {
percolateRequest.onlyCount(true);
parsePercolateAction(parser, percolateRequest, allowExplicitIndex);
} else {
throw new ElasticsearchParseException("[{}] isn't a supported percolate operation", percolateAction);
}
}
}
}
// move pointers
from = nextMarker + 1;
// now for the body
nextMarker = findNextMarker(marker, from, data, length);
if (nextMarker == -1) {
break;
}
percolateRequest.source(data.slice(from, nextMarker - from));
// move pointers
from = nextMarker + 1;
add(percolateRequest);
}
return this;
}
@Override
public List<? extends IndicesRequest> subRequests() {
List<IndicesRequest> indicesRequests = new ArrayList<>();
for (PercolateRequest percolateRequest : this.requests) {
indicesRequests.addAll(percolateRequest.subRequests());
}
return indicesRequests;
}
private void parsePercolateAction(XContentParser parser, PercolateRequest percolateRequest, boolean allowExplicitIndex) throws IOException {
String globalIndex = indices != null && indices.length > 0 ? indices[0] : null;
Map<String, Object> header = parser.map();
if (header.containsKey("id")) {
GetRequest getRequest = new GetRequest(globalIndex);
percolateRequest.getRequest(getRequest);
for (Map.Entry<String, Object> entry : header.entrySet()) {
Object value = entry.getValue();
if ("id".equals(entry.getKey())) {
getRequest.id(nodeStringValue(value, null));
header.put("id", entry.getValue());
} else if ("index".equals(entry.getKey()) || "indices".equals(entry.getKey())) {
if (!allowExplicitIndex) {
throw new IllegalArgumentException("explicit index in multi percolate is not allowed");
}
getRequest.index(nodeStringValue(value, null));
} else if ("type".equals(entry.getKey())) {
getRequest.type(nodeStringValue(value, null));
} else if ("preference".equals(entry.getKey())) {
getRequest.preference(nodeStringValue(value, null));
} else if ("routing".equals(entry.getKey())) {
getRequest.routing(nodeStringValue(value, null));
} else if ("percolate_index".equals(entry.getKey()) || "percolate_indices".equals(entry.getKey()) || "percolateIndex".equals(entry.getKey()) || "percolateIndices".equals(entry.getKey())) {
percolateRequest.indices(nodeStringArrayValue(value));
} else if ("percolate_type".equals(entry.getKey()) || "percolateType".equals(entry.getKey())) {
percolateRequest.documentType(nodeStringValue(value, null));
} else if ("percolate_preference".equals(entry.getKey()) || "percolatePreference".equals(entry.getKey())) {
percolateRequest.preference(nodeStringValue(value, null));
} else if ("percolate_routing".equals(entry.getKey()) || "percolateRouting".equals(entry.getKey())) {
percolateRequest.routing(nodeStringValue(value, null));
}
}
// Setting values based on get request, if needed...
if ((percolateRequest.indices() == null || percolateRequest.indices().length == 0) && getRequest.index() != null) {
percolateRequest.indices(getRequest.index());
}
if (percolateRequest.documentType() == null && getRequest.type() != null) {
percolateRequest.documentType(getRequest.type());
}
if (percolateRequest.routing() == null && getRequest.routing() != null) {
percolateRequest.routing(getRequest.routing());
}
if (percolateRequest.preference() == null && getRequest.preference() != null) {
percolateRequest.preference(getRequest.preference());
}
} else {
for (Map.Entry<String, Object> entry : header.entrySet()) {
Object value = entry.getValue();
if ("index".equals(entry.getKey()) || "indices".equals(entry.getKey())) {
if (!allowExplicitIndex) {
throw new IllegalArgumentException("explicit index in multi percolate is not allowed");
}
percolateRequest.indices(nodeStringArrayValue(value));
} else if ("type".equals(entry.getKey())) {
percolateRequest.documentType(nodeStringValue(value, null));
} else if ("preference".equals(entry.getKey())) {
percolateRequest.preference(nodeStringValue(value, null));
} else if ("routing".equals(entry.getKey())) {
percolateRequest.routing(nodeStringValue(value, null));
}
}
}
percolateRequest.indicesOptions(IndicesOptions.fromMap(header, indicesOptions));
}
private int findNextMarker(byte marker, int from, BytesReference data, int length) {
for (int i = from; i < length; i++) {
if (data.get(i) == marker) {
return i;
}
}
return -1;
}
/**
* @return The list of already set percolate requests.
*/
public List<PercolateRequest> requests() {
return this.requests;
}
/**
* @return Returns the {@link IndicesOptions} that is used as default for all percolate requests.
*/
public IndicesOptions indicesOptions() {
return indicesOptions;
}
/**
* Sets the {@link IndicesOptions} for all percolate request that don't have this set.
*
* Warning: This should be set before adding any percolate requests. Setting this after adding percolate requests
* will have no effect on any percolate requests already added.
*/
public MultiPercolateRequest indicesOptions(IndicesOptions indicesOptions) {
this.indicesOptions = indicesOptions;
return this;
}
/**
* @return The default indices for all percolate request.
*/
public String[] indices() {
return indices;
}
/**
* Sets the default indices for any percolate request that doesn't have indices defined.
*
* Warning: This should be set before adding any percolate requests. Setting this after adding percolate requests
* will have no effect on any percolate requests already added.
*/
public MultiPercolateRequest indices(String... indices) {
this.indices = indices;
return this;
}
/**
* @return Sets the default type for all percolate requests
*/
public String documentType() {
return documentType;
}
/**
* Sets the default document type for any percolate request that doesn't have a document type set.
*
* Warning: This should be set before adding any percolate requests. Setting this after adding percolate requests
* will have no effect on any percolate requests already added.
*/
public MultiPercolateRequest documentType(String type) {
this.documentType = type;
return this;
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (requests.isEmpty()) {
validationException = addValidationError("no requests added", validationException);
}
for (int i = 0; i < requests.size(); i++) {
ActionRequestValidationException ex = requests.get(i).validate();
if (ex != null) {
if (validationException == null) {
validationException = new ActionRequestValidationException();
}
validationException.addValidationErrors(ex.validationErrors());
}
}
return validationException;
}
@Override
public void readFrom(StreamInput in) throws IOException {
super.readFrom(in);
indices = in.readStringArray();
documentType = in.readOptionalString();
indicesOptions = IndicesOptions.readIndicesOptions(in);
int size = in.readVInt();
for (int i = 0; i < size; i++) {
PercolateRequest request = new PercolateRequest();
request.readFrom(in);
requests.add(request);
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeStringArrayNullable(indices);
out.writeOptionalString(documentType);
indicesOptions.writeIndicesOptions(out);
out.writeVInt(requests.size());
for (PercolateRequest request : requests) {
request.writeTo(out);
}
}
}
| {
"pile_set_name": "Github"
} |
abstract class DrawEvent {}
| {
"pile_set_name": "Github"
} |
version https://git-lfs.github.com/spec/v1
oid sha256:b862890e7e1001e0bc511618acb1940bee8be0640535dca7bf5f9fe6293c3c96
size 13008
| {
"pile_set_name": "Github"
} |
using System;
using CitizenFX.Core.Native;
namespace CitizenFX.Core
{
public sealed class VehicleDoor
{
#region Fields
Vehicle _owner;
#endregion
internal VehicleDoor(Vehicle owner, VehicleDoorIndex index)
{
_owner = owner;
Index = index;
}
public VehicleDoorIndex Index { get; private set; }
public float AngleRatio
{
get
{
return API.GetVehicleDoorAngleRatio(_owner.Handle, (int)Index);
}
set
{
API.SetVehicleDoorControl(_owner.Handle, (int)Index, 1, value);
}
}
public bool CanBeBroken
{
set
{
API.SetVehicleDoorBreakable(_owner.Handle, (int)Index, value);
}
}
public bool IsOpen
{
get
{
return AngleRatio > 0;
}
}
public bool IsFullyOpen
{
get
{
return API.IsVehicleDoorFullyOpen(_owner.Handle, (int)Index);
}
}
public bool IsBroken
{
get
{
return API.IsVehicleDoorDamaged(_owner.Handle, (int)Index);
}
}
public Vehicle Vehicle
{
get { return _owner; }
}
public void Open(bool loose = false, bool instantly = false)
{
API.SetVehicleDoorOpen(_owner.Handle, (int)Index, loose, instantly);
}
public void Close(bool instantly = false)
{
API.SetVehicleDoorShut(_owner.Handle, (int)Index, instantly);
}
public void Break(bool stayInTheWorld = true)
{
API.SetVehicleDoorBroken(_owner.Handle, (int)Index, !stayInTheWorld);
}
}
}
| {
"pile_set_name": "Github"
} |
{
"name": "lodash",
"version": "0.9.2",
"description": "A utility library delivering consistency, customization, performance, and extras.",
"homepage": "http://lodash.com",
"license": "MIT",
"main": "./lodash.js",
"keywords": [
"browser",
"client",
"functional",
"performance",
"server",
"speed",
"util"
],
"author": {
"name": "John-David Dalton",
"email": "[email protected]",
"url": "http://allyoucanleet.com/"
},
"contributors": [
{
"name": "John-David Dalton",
"email": "[email protected]",
"url": "http://allyoucanleet.com/"
},
{
"name": "Blaine Bublitz",
"email": "[email protected]",
"url": "http://iceddev.com/"
},
{
"name": "Kit Cambridge",
"email": "[email protected]",
"url": "http://kitcambridge.be/"
},
{
"name": "Mathias Bynens",
"email": "[email protected]",
"url": "http://mathiasbynens.be/"
}
],
"bugs": {
"url": "https://github.com/lodash/lodash/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/lodash/lodash.git"
},
"engines": [
"node",
"rhino"
],
"jam": {
"main": "./lodash.js"
},
"readme": "# Lo-Dash v0.9.2\n\nA utility library delivering consistency, [customization](http://lodash.com/custom-builds), [performance](http://lodash.com/benchmarks), & [extras](http://lodash.com/#features).\n\n## Download\n\n * [Development build](https://raw.github.com/lodash/lodash/0.9.2/lodash.js)\n * [Production build](https://raw.github.com/lodash/lodash/0.9.2/lodash.min.js)\n * [Underscore build](https://raw.github.com/lodash/lodash/0.9.2/lodash.underscore.min.js) tailored for projects already using Underscore\n * CDN copies of ≤ v0.9.2’s [Production](http://cdnjs.cloudflare.com/ajax/libs/lodash.js/0.9.2/lodash.min.js), [Underscore](http://cdnjs.cloudflare.com/ajax/libs/lodash.js/0.9.2/lodash.underscore.min.js), and [Development](http://cdnjs.cloudflare.com/ajax/libs/lodash.js/0.9.2/lodash.js) builds are available on [cdnjs](http://cdnjs.com/) thanks to [CloudFlare](http://www.cloudflare.com/)\n * For optimal file size, [create a custom build](http://lodash.com/custom-builds) with only the features you need\n\n## Dive in\n\nWe’ve got [API docs](http://lodash.com/docs), [benchmarks](http://lodash.com/benchmarks), and [unit tests](http://lodash.com/tests).\n\nCreate your own benchmarks at [jsPerf](http://jsperf.com), or [search](http://jsperf.com/search?q=lodash) for existing ones.\n\nFor a list of upcoming features, check out our [roadmap](https://github.com/lodash/lodash/wiki/Roadmap).\n\n## Screencasts\n\nFor more information check out these screencasts over Lo-Dash:\n\n * [Introducing Lo-Dash](https://vimeo.com/44154599)\n * [Lo-Dash optimizations and custom builds](https://vimeo.com/44154601)\n * [Lo-Dash’s origin and why it’s a better utility belt](https://vimeo.com/44154600)\n * [Unit testing in Lo-Dash](https://vimeo.com/45865290)\n * [Lo-Dash’s approach to native method use](https://vimeo.com/48576012)\n\n## Features\n\n * AMD loader support ([RequireJS](http://requirejs.org/), [curl.js](https://github.com/cujojs/curl), etc.)\n * [_.clone](http://lodash.com/docs#clone) supports *“deep”* cloning\n * [_.contains](http://lodash.com/docs#contains) accepts a `fromIndex` argument\n * [_.forEach](http://lodash.com/docs#forEach) is chainable and supports exiting iteration early\n * [_.forIn](http://lodash.com/docs#forIn) for iterating over an object’s own and inherited properties\n * [_.forOwn](http://lodash.com/docs#forOwn) for iterating over an object’s own properties\n * [_.isPlainObject](http://lodash.com/docs#isPlainObject) checks if values are created by the `Object` constructor\n * [_.lateBind](http://lodash.com/docs#lateBind) for late binding\n * [_.merge](http://lodash.com/docs#merge) for a *“deep”* [_.extend](http://lodash.com/docs#extend)\n * [_.partial](http://lodash.com/docs#partial) for partial application without `this` binding\n * [_.pick](http://lodash.com/docs#pick) and [_.omit](http://lodash.com/docs#omit) accepts `callback` and `thisArg` arguments\n * [_.template](http://lodash.com/docs#template) supports [ES6 delimiters](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-7.8.6) and utilizes [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) for easier debugging\n * [_.contains](http://lodash.com/docs#contains), [_.size](http://lodash.com/docs#size), [_.toArray](http://lodash.com/docs#toArray),\n [and more…](http://lodash.com/docs \"_.countBy, _.every, _.filter, _.find, _.forEach, _.groupBy, _.invoke, _.map, _.max, _.min, _.pluck, _.reduce, _.reduceRight, _.reject, _.shuffle, _.some, _.sortBy, _.where\") accept strings\n\n## Support\n\nLo-Dash has been tested in at least Chrome 5~23, Firefox 1~16, IE 6-10, Opera 9.25-12, Safari 3-6, Node.js 0.4.8-0.8.14, Narwhal 0.3.2, RingoJS 0.8, and Rhino 1.7RC5.\n\n## Installation and usage\n\nIn browsers:\n\n```html\n<script src=\"lodash.js\"></script>\n```\n\nUsing [npm](http://npmjs.org/):\n\n```bash\nnpm install lodash\n\nnpm install -g lodash\nnpm link lodash\n```\n\nIn [Node.js](http://nodejs.org/) and [RingoJS v0.8.0+](http://ringojs.org/):\n\n```js\nvar _ = require('lodash');\n```\n\n**Note:** If Lo-Dash is installed globally, [run `npm link lodash`](http://blog.nodejs.org/2011/03/23/npm-1-0-global-vs-local-installation/) in your project’s root directory before requiring it.\n\nIn [RingoJS v0.7.0-](http://ringojs.org/):\n\n```js\nvar _ = require('lodash')._;\n```\n\nIn [Rhino](http://www.mozilla.org/rhino/):\n\n```js\nload('lodash.js');\n```\n\nIn an AMD loader like [RequireJS](http://requirejs.org/):\n\n```js\nrequire({\n 'paths': {\n 'underscore': 'path/to/lodash'\n }\n},\n['underscore'], function(_) {\n console.log(_.VERSION);\n});\n```\n\n## Resolved Underscore.js issues\n\n * Allow iteration of objects with a `length` property [[#799](https://github.com/documentcloud/underscore/pull/799), [test](https://github.com/lodash/lodash/blob/0.9.2/test/test.js#L545-551)]\n * Fix cross-browser object iteration bugs [[#60](https://github.com/documentcloud/underscore/issues/60), [#376](https://github.com/documentcloud/underscore/issues/376), [test](https://github.com/lodash/lodash/blob/0.9.2/test/test.js#L558-582)]\n * Methods should work on pages with incorrectly shimmed native methods [[#7](https://github.com/documentcloud/underscore/issues/7), [#742](https://github.com/documentcloud/underscore/issues/742), [test](https://github.com/lodash/lodash/blob/0.9.2/test/test.js#L140-146)]\n * `_.isEmpty` should support jQuery/MooTools DOM query collections [[#690](https://github.com/documentcloud/underscore/pull/690), [test](https://github.com/lodash/lodash/blob/0.9.2/test/test.js#L747-752)]\n * `_.isObject` should avoid V8 bug [#2291](http://code.google.com/p/8/issues/detail?id=2291) [[#605](https://github.com/documentcloud/underscore/issues/605), [test](https://github.com/lodash/lodash/blob/0.9.2/test/test.js#L828-840)]\n * `_.keys` should work with `arguments` objects cross-browser [[#396](https://github.com/documentcloud/underscore/issues/396), [test](https://github.com/lodash/lodash/blob/0.9.2/test/test.js#L921-923)]\n * `_.range` should coerce arguments to numbers [[#634](https://github.com/documentcloud/underscore/issues/634), [#683](https://github.com/documentcloud/underscore/issues/683), [test](https://github.com/lodash/lodash/blob/0.9.2/test/test.js#L1337-1340)]\n\n## Release Notes\n\n### <sup>v0.9.2</sup>\n\n * Added `fromIndex` argument to `_.contains`\n * Added `moduleId` build option\n * Added Closure Compiler *“simple”* optimizations to the build process\n * Added support for strings in `_.max` and `_.min`\n * Added support for ES6 template delimiters to `_.template`\n * Ensured re-minification of Lo-Dash by third parties avoids Closure Compiler bugs\n * Optimized `_.every`, `_.find`, `_.some`, and `_.uniq`\n\nThe full changelog is available [here](https://github.com/lodash/lodash/wiki/Changelog).\n\n## BestieJS\n\nLo-Dash is part of the [BestieJS](https://github.com/bestiejs) *“Best in Class”* module collection. This means we promote solid browser/environment support, ES5 precedents, unit testing, and plenty of documentation.\n\n## Author\n\n| [](http://twitter.com/jdalton \"Follow @jdalton on Twitter\") |\n|---|\n| [John-David Dalton](http://allyoucanleet.com/) |\n\n## Contributors\n\n| [](http://twitter.com/blainebublitz \"Follow @BlaineBublitz on Twitter\") | [](https://twitter.com/kitcambridge \"Follow @kitcambridge on Twitter\") | [](http://twitter.com/mathias \"Follow @mathias on Twitter\") |\n|---|---|---|\n| [Blaine Bublitz](http://iceddev.com/) | [Kit Cambridge](http://kitcambridge.github.io/) | [Mathias Bynens](http://mathiasbynens.be/) |\n",
"readmeFilename": "README.md",
"_id": "[email protected]",
"_from": "lodash@~0.9.2"
}
| {
"pile_set_name": "Github"
} |
################################################################################
#①配置根Logger,其语法为:
#
#log4j.rootLogger =[level],appenderName,appenderName2,...
#level是日志记录的优先级,分为OFF,TRACE,DEBUG,INFO,WARN,ERROR,FATAL,ALL
##Log4j建议只使用四个级别,优先级从低到高分别是DEBUG,INFO,WARN,ERROR
#通过在这里定义的级别,您可以控制到应用程序中相应级别的日志信息的开关
#比如在这里定义了INFO级别,则应用程序中所有DEBUG级别的日志信息将不被打印出来
#appenderName就是指定日志信息输出到哪个地方。可同时指定多个输出目的
################################################################################
################################################################################
#②配置日志信息输出目的地Appender,其语法为:
#
#log4j.appender.appenderName =fully.qualified.name.of.appender.class
#log4j.appender.appenderName.optionN =valueN
#
#Log4j提供的appender有以下几种:
#1)org.apache.log4j.ConsoleAppender(输出到控制台)
#2)org.apache.log4j.FileAppender(输出到文件)
#3)org.apache.log4j.DailyRollingFileAppender(每天产生一个日志文件)
#4)org.apache.log4j.RollingFileAppender(文件大小到达指定尺寸的时候产生一个新的文件)
#5)org.apache.log4j.WriterAppender(将日志信息以流格式发送到任意指定的地方)
#
#1)ConsoleAppender选项属性
# -Threshold = DEBUG:指定日志消息的输出最低层次
# -ImmediateFlush = TRUE:默认值是true,所有的消息都会被立即输出
# -Target = System.err:默认值System.out,输出到控制台(err为红色,out为黑色)
#
#2)FileAppender选项属性
# -Threshold = INFO:指定日志消息的输出最低层次
# -ImmediateFlush = TRUE:默认值是true,所有的消息都会被立即输出
# -File = C:\log4j.log:指定消息输出到C:\log4j.log文件
# -Append = FALSE:默认值true,将消息追加到指定文件中,false指将消息覆盖指定的文件内容
# -Encoding = UTF-8:可以指定文件编码格式
#
#3)DailyRollingFileAppender选项属性
#-Threshold = WARN:指定日志消息的输出最低层次
#-ImmediateFlush = TRUE:默认值是true,所有的消息都会被立即输出
# -File =C:\log4j.log:指定消息输出到C:\log4j.log文件
# -Append= FALSE:默认值true,将消息追加到指定文件中,false指将消息覆盖指定的文件内容
#-DatePattern='.'yyyy-ww:每周滚动一次文件,即每周产生一个新的文件。还可以按用以下参数:
# '.'yyyy-MM:每月
# '.'yyyy-ww:每周
# '.'yyyy-MM-dd:每天
# '.'yyyy-MM-dd-a:每天两次
# '.'yyyy-MM-dd-HH:每小时
# '.'yyyy-MM-dd-HH-mm:每分钟
#-Encoding = UTF-8:可以指定文件编码格式
#
#4)RollingFileAppender选项属性
#-Threshold = ERROR:指定日志消息的输出最低层次
#-ImmediateFlush = TRUE:默认值是true,所有的消息都会被立即输出
# -File =C:/log4j.log:指定消息输出到C:/log4j.log文件
# -Append= FALSE:默认值true,将消息追加到指定文件中,false指将消息覆盖指定的文件内容
#-MaxFileSize = 100KB:后缀可以是KB,MB,GB.在日志文件到达该大小时,将会自动滚动.如:log4j.log.1
#-MaxBackupIndex = 2:指定可以产生的滚动文件的最大数
#-Encoding = UTF-8:可以指定文件编码格式
################################################################################
################################################################################
#③配置日志信息的格式(布局),其语法为:
#
#log4j.appender.appenderName.layout=fully.qualified.name.of.layout.class
#log4j.appender.appenderName.layout.optionN= valueN
#
#Log4j提供的layout有以下几种:
#5)org.apache.log4j.HTMLLayout(以HTML表格形式布局)
#6)org.apache.log4j.PatternLayout(可以灵活地指定布局模式)
#7)org.apache.log4j.SimpleLayout(包含日志信息的级别和信息字符串)
#8)org.apache.log4j.TTCCLayout(包含日志产生的时间、线程、类别等等信息)
#9)org.apache.log4j.xml.XMLLayout(以XML形式布局)
#
#5)HTMLLayout选项属性
#-LocationInfo = TRUE:默认值false,输出java文件名称和行号
#-Title=Struts Log Message:默认值 Log4JLog Messages
#
#6)PatternLayout选项属性
#-ConversionPattern = %m%n:格式化指定的消息(参数意思下面有)
#
#9)XMLLayout选项属性
#-LocationInfo = TRUE:默认值false,输出java文件名称和行号
#
#Log4J采用类似C语言中的printf函数的打印格式格式化日志信息,打印参数如下:
#%m 输出代码中指定的消息
#%p 输出优先级,即DEBUG,INFO,WARN,ERROR,FATAL
#%r 输出自应用启动到输出该log信息耗费的毫秒数
#%c 输出所属的类目,通常就是所在类的全名
#%t 输出产生该日志事件的线程名
#%n 输出一个回车换行符,Windows平台为“\r\n”,Unix平台为“\n”
#%d 输出日志时间点的日期或时间,默认格式为ISO8601,也可以在其后指定格式
# 如:%d{yyyy年MM月dd日HH:mm:ss,SSS},输出类似:2012年01月05日 22:10:28,921
#%l 输出日志事件的发生位置,包括类目名、发生的线程,以及在代码中的行数
# 如:Testlog.main(TestLog.java:10)
#%F 输出日志消息产生时所在的文件名称
#%L 输出代码中的行号
#%x 输出和当前线程相关联的NDC(嵌套诊断环境),像javaservlets多客户多线程的应用中
#%% 输出一个"%"字符
#
# 可以在%与模式字符之间加上修饰符来控制其最小宽度、最大宽度、和文本的对齐方式。如:
# %5c: 输出category名称,最小宽度是5,category<5,默认的情况下右对齐
# %-5c:输出category名称,最小宽度是5,category<5,"-"号指定左对齐,会有空格
# %.5c:输出category名称,最大宽度是5,category>5,就会将左边多出的字符截掉,<5不会有空格
# %20.30c:category名称<20补空格,并且右对齐,>30字符,就从左边交远销出的字符截掉
################################################################################
################################################################################
#④指定特定包的输出特定的级别
#log4j.logger.org.springframework=DEBUG
################################################################################
#OFF,systemOut,logFile,logDailyFile,logRollingFile,logMail,logDB,ALL
#log4j.rootLogger=INFO,systemOut
#输出到控制台
#log4j.appender.systemOut= org.apache.log4j.ConsoleAppender
#log4j.appender.systemOut.layout= org.apache.log4j.PatternLayout
#log4j.appender.systemOut.layout.ConversionPattern= [%-5p][%-20d{yyyy/MM/dd HH:mm:ss}][%c] %m%n
#log4j.appender.systemOut.Threshold= INFO
#log4j.appender.systemOut.ImmediateFlush= TRUE
#log4j.appender.systemOut.Target= System.out
# Root logger option
log4j.rootLogger=INFO,stdout
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%d{yyyy-MM-dd HH:mm:ss}] %-5p %c{1}:%L - %m%n | {
"pile_set_name": "Github"
} |
'use strict';
// 21.2.5.3 get RegExp.prototype.flags
var anObject = require('./_an-object');
module.exports = function(){
var that = anObject(this)
, result = '';
if(that.global) result += 'g';
if(that.ignoreCase) result += 'i';
if(that.multiline) result += 'm';
if(that.unicode) result += 'u';
if(that.sticky) result += 'y';
return result;
}; | {
"pile_set_name": "Github"
} |
export default (thing) =>
thing && !thing[Symbol('__is_proxy')] && thing.__matches
| {
"pile_set_name": "Github"
} |
{
"word": "Decorative",
"definitions": [
"Serving to make something look more attractive; ornamental.",
"Relating to decoration.",
"(of a woman) attractive."
],
"parts-of-speech": "Adjective"
} | {
"pile_set_name": "Github"
} |
/*
* Warewolf - Once bitten, there's no going back
* Copyright 2019 by Warewolf Ltd <[email protected]>
* Licensed under GNU Affero General Public License 3.0 or later.
* Some rights reserved.
* Visit our website for more information <http://warewolf.io/>
* AUTHORS <http://warewolf.io/authors.php> , CONTRIBUTORS <http://warewolf.io/contributors.php>
* @license GNU Affero General Public License <http://www.gnu.org/licenses/agpl-3.0.html>
*/
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Dev2.Infrastructure.Tests.Providers.Validation.Rules
{
[TestClass]
public class RuleBaseTests
{
[TestMethod]
[Owner("Trevor Williams-Ros")]
[TestCategory("Rule_Constructor")]
[ExpectedException(typeof(ArgumentNullException))]
public void Rule_Constructor_GetValueIsNull_ThrowsArgumentNullException()
{
//------------Setup for test--------------------------
//------------Execute Test---------------------------
new TestRuleBase(null);
//------------Assert Results-------------------------
}
[TestMethod]
[Owner("Trevor Williams-Ros")]
[TestCategory("Rule_Constructor")]
public void Rule_Constructor_GetValueIsNotNull_PropertiesInitialized()
{
//------------Setup for test--------------------------
//------------Execute Test---------------------------
var rule = new TestRuleBase(() => "");
//------------Assert Results-------------------------
Assert.AreEqual("", rule.LabelText);
Assert.AreEqual("Value is invalid.", rule.ErrorText);
Assert.IsNull(rule.DoError);
}
[TestMethod]
[Owner("Trevor Williams-Ros")]
[TestCategory("Rule_CreatError")]
public void Rule_CreatError_ReturnsNonNullError()
{
//------------Setup for test--------------------------
var doErrorWasAssigned = false;
Action doError = () => { doErrorWasAssigned = true; };
var rule = new TestRuleBase(() => "") { DoError = doError };
//------------Execute Test---------------------------
var error = rule.TestCreatError();
//------------Assert Results-------------------------
Assert.IsNotNull(error);
Assert.AreEqual("Value is invalid.", error.Message);
error.Do();
Assert.IsTrue(doErrorWasAssigned);
}
}
}
| {
"pile_set_name": "Github"
} |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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/. */
#ifndef mozilla_ServoDeclarationBlock_h
#define mozilla_ServoDeclarationBlock_h
#include "mozilla/ServoBindings.h"
#include "mozilla/DeclarationBlock.h"
namespace mozilla {
class ServoDeclarationBlock final : public DeclarationBlock
{
public:
ServoDeclarationBlock()
: ServoDeclarationBlock(Servo_DeclarationBlock_CreateEmpty().Consume()) {}
ServoDeclarationBlock(const ServoDeclarationBlock& aCopy)
: DeclarationBlock(aCopy)
, mRaw(Servo_DeclarationBlock_Clone(aCopy.mRaw).Consume()) {}
NS_INLINE_DECL_REFCOUNTING(ServoDeclarationBlock)
static already_AddRefed<ServoDeclarationBlock>
FromCssText(const nsAString& aCssText);
RawServoDeclarationBlock* Raw() const { return mRaw; }
RawServoDeclarationBlock* const* RefRaw() const {
static_assert(sizeof(RefPtr<RawServoDeclarationBlock>) ==
sizeof(RawServoDeclarationBlock*),
"RefPtr should just be a pointer");
return reinterpret_cast<RawServoDeclarationBlock* const*>(&mRaw);
}
void ToString(nsAString& aResult) const {
Servo_DeclarationBlock_GetCssText(mRaw, &aResult);
}
uint32_t Count() const {
return Servo_DeclarationBlock_Count(mRaw);
}
bool GetNthProperty(uint32_t aIndex, nsAString& aReturn) const {
aReturn.Truncate();
return Servo_DeclarationBlock_GetNthProperty(mRaw, aIndex, &aReturn);
}
void GetPropertyValue(const nsAString& aProperty, nsAString& aValue) const;
void GetPropertyValueByID(nsCSSPropertyID aPropID, nsAString& aValue) const;
void GetAuthoredPropertyValue(const nsAString& aProperty,
nsAString& aValue) const {
GetPropertyValue(aProperty, aValue);
}
bool GetPropertyIsImportant(const nsAString& aProperty) const;
void RemoveProperty(const nsAString& aProperty);
void RemovePropertyByID(nsCSSPropertyID aPropID);
protected:
explicit ServoDeclarationBlock(
already_AddRefed<RawServoDeclarationBlock> aRaw)
: DeclarationBlock(StyleBackendType::Servo), mRaw(aRaw) {}
private:
~ServoDeclarationBlock() {}
RefPtr<RawServoDeclarationBlock> mRaw;
};
} // namespace mozilla
#endif // mozilla_ServoDeclarationBlock_h
| {
"pile_set_name": "Github"
} |
import React from 'react';
import { shallow, mount } from 'enzyme';
import Slider from '../components/Slider';
describe('Slider', () => {
it('should render with "div" tag', () => {
const wrapper = shallow(<Slider actions={{}} player={{}} />);
expect(wrapper.type()).toBe('div');
});
it('should render with "video-react-slider" class', () => {
const wrapper = shallow(<Slider actions={{}} player={{}} />);
expect(wrapper.hasClass('video-react-slider')).toBe(true);
});
it('simulates click events', () => {
const e = {
preventDefault: jest.fn(),
stopPropagation: jest.fn()
};
const onClick = jest.fn();
const wrapper = shallow(
<Slider actions={{}} player={{}} onClick={onClick} />
);
wrapper.find('div').simulate('click', e);
expect(e.preventDefault).toHaveBeenCalled();
});
it('should render children when passed in', () => {
const wrapper = shallow(
<Slider player={{}}>
<div />
</Slider>
);
expect(wrapper.children().length).toBeGreaterThan(0);
});
it('should bind ref "slider"', () => {
const wrapper = mount(<Slider player={{}} />);
expect(wrapper.instance().slider).toBeTruthy();
});
});
| {
"pile_set_name": "Github"
} |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input.Events;
using osu.Framework.Logging;
using osu.Framework.Screens;
using osu.Framework.Threading;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Graphics.Containers;
using osu.Game.IO.Archives;
using osu.Game.Online.API;
using osu.Game.Overlays;
using osu.Game.Replays;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;
using osu.Game.Scoring;
using osu.Game.Scoring.Legacy;
using osu.Game.Screens.Ranking;
using osu.Game.Skinning;
using osu.Game.Users;
namespace osu.Game.Screens.Play
{
[Cached]
public class Player : ScreenWithBeatmapBackground
{
/// <summary>
/// The delay upon completion of the beatmap before displaying the results screen.
/// </summary>
public const double RESULTS_DISPLAY_DELAY = 1000.0;
public override bool AllowBackButton => false; // handled by HoldForMenuButton
protected override UserActivity InitialActivity => new UserActivity.SoloGame(Beatmap.Value.BeatmapInfo, Ruleset.Value);
public override float BackgroundParallaxAmount => 0.1f;
public override bool HideOverlaysOnEnter => true;
protected override OverlayActivation InitialOverlayActivationMode => OverlayActivation.UserTriggered;
// We are managing our own adjustments (see OnEntering/OnExiting).
public override bool AllowRateAdjustments => false;
/// <summary>
/// Whether gameplay should pause when the game window focus is lost.
/// </summary>
protected virtual bool PauseOnFocusLost => true;
public Action RestartRequested;
public bool HasFailed { get; private set; }
private Bindable<bool> mouseWheelDisabled;
private readonly Bindable<bool> storyboardReplacesBackground = new Bindable<bool>();
public int RestartCount;
[Resolved]
private ScoreManager scoreManager { get; set; }
private RulesetInfo rulesetInfo;
private Ruleset ruleset;
[Resolved]
private IAPIProvider api { get; set; }
[Resolved]
private MusicController musicController { get; set; }
private SampleChannel sampleRestart;
public BreakOverlay BreakOverlay;
private BreakTracker breakTracker;
private SkipOverlay skipOverlay;
protected ScoreProcessor ScoreProcessor { get; private set; }
protected HealthProcessor HealthProcessor { get; private set; }
protected DrawableRuleset DrawableRuleset { get; private set; }
protected HUDOverlay HUDOverlay { get; private set; }
public bool LoadedBeatmapSuccessfully => DrawableRuleset?.Objects.Any() == true;
protected GameplayClockContainer GameplayClockContainer { get; private set; }
public DimmableStoryboard DimmableStoryboard { get; private set; }
[Cached]
[Cached(Type = typeof(IBindable<IReadOnlyList<Mod>>))]
protected new readonly Bindable<IReadOnlyList<Mod>> Mods = new Bindable<IReadOnlyList<Mod>>(Array.Empty<Mod>());
/// <summary>
/// Whether failing should be allowed.
/// By default, this checks whether all selected mods allow failing.
/// </summary>
protected virtual bool CheckModsAllowFailure() => Mods.Value.OfType<IApplicableFailOverride>().All(m => m.PerformFail());
private readonly bool allowPause;
private readonly bool showResults;
/// <summary>
/// Create a new player instance.
/// </summary>
/// <param name="allowPause">Whether pausing should be allowed. If not allowed, attempting to pause will quit.</param>
/// <param name="showResults">Whether results screen should be pushed on completion.</param>
public Player(bool allowPause = true, bool showResults = true)
{
this.allowPause = allowPause;
this.showResults = showResults;
}
private GameplayBeatmap gameplayBeatmap;
private ScreenSuspensionHandler screenSuspension;
private DependencyContainer dependencies;
protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent)
=> dependencies = new DependencyContainer(base.CreateChildDependencies(parent));
protected override void LoadComplete()
{
base.LoadComplete();
PrepareReplay();
}
private Replay recordingReplay;
/// <summary>
/// Run any recording / playback setup for replays.
/// </summary>
protected virtual void PrepareReplay()
{
DrawableRuleset.SetRecordTarget(recordingReplay = new Replay());
}
[BackgroundDependencyLoader]
private void load(AudioManager audio, OsuConfigManager config)
{
Mods.Value = base.Mods.Value.Select(m => m.CreateCopy()).ToArray();
if (Beatmap.Value is DummyWorkingBeatmap)
return;
IBeatmap playableBeatmap = loadPlayableBeatmap();
if (playableBeatmap == null)
return;
sampleRestart = audio.Samples.Get(@"Gameplay/restart");
mouseWheelDisabled = config.GetBindable<bool>(OsuSetting.MouseDisableWheel);
DrawableRuleset = ruleset.CreateDrawableRulesetWith(playableBeatmap, Mods.Value);
ScoreProcessor = ruleset.CreateScoreProcessor();
ScoreProcessor.ApplyBeatmap(playableBeatmap);
ScoreProcessor.Mods.BindTo(Mods);
HealthProcessor = ruleset.CreateHealthProcessor(playableBeatmap.HitObjects[0].StartTime);
HealthProcessor.ApplyBeatmap(playableBeatmap);
if (!ScoreProcessor.Mode.Disabled)
config.BindWith(OsuSetting.ScoreDisplayMode, ScoreProcessor.Mode);
InternalChild = GameplayClockContainer = new GameplayClockContainer(Beatmap.Value, DrawableRuleset.GameplayStartTime);
AddInternal(gameplayBeatmap = new GameplayBeatmap(playableBeatmap));
AddInternal(screenSuspension = new ScreenSuspensionHandler(GameplayClockContainer));
dependencies.CacheAs(gameplayBeatmap);
addUnderlayComponents(GameplayClockContainer);
addGameplayComponents(GameplayClockContainer, Beatmap.Value, playableBeatmap);
addOverlayComponents(GameplayClockContainer, Beatmap.Value);
if (!DrawableRuleset.AllowGameplayOverlays)
{
HUDOverlay.ShowHud.Value = false;
HUDOverlay.ShowHud.Disabled = true;
BreakOverlay.Hide();
skipOverlay.Hide();
}
DrawableRuleset.IsPaused.BindValueChanged(_ => updateOverlayActivationMode());
DrawableRuleset.HasReplayLoaded.BindValueChanged(_ => updateOverlayActivationMode());
breakTracker.IsBreakTime.BindValueChanged(_ => updateOverlayActivationMode());
DrawableRuleset.HasReplayLoaded.BindValueChanged(_ => updatePauseOnFocusLostState(), true);
// bind clock into components that require it
DrawableRuleset.IsPaused.BindTo(GameplayClockContainer.IsPaused);
DrawableRuleset.OnNewResult += r =>
{
HealthProcessor.ApplyResult(r);
ScoreProcessor.ApplyResult(r);
gameplayBeatmap.ApplyResult(r);
};
DrawableRuleset.OnRevertResult += r =>
{
HealthProcessor.RevertResult(r);
ScoreProcessor.RevertResult(r);
};
// Bind the judgement processors to ourselves
ScoreProcessor.HasCompleted.ValueChanged += updateCompletionState;
HealthProcessor.Failed += onFail;
foreach (var mod in Mods.Value.OfType<IApplicableToScoreProcessor>())
mod.ApplyToScoreProcessor(ScoreProcessor);
foreach (var mod in Mods.Value.OfType<IApplicableToHealthProcessor>())
mod.ApplyToHealthProcessor(HealthProcessor);
breakTracker.IsBreakTime.BindValueChanged(onBreakTimeChanged, true);
}
private void addUnderlayComponents(Container target)
{
target.Add(DimmableStoryboard = new DimmableStoryboard(Beatmap.Value.Storyboard) { RelativeSizeAxes = Axes.Both });
}
private void addGameplayComponents(Container target, WorkingBeatmap working, IBeatmap playableBeatmap)
{
var beatmapSkinProvider = new BeatmapSkinProvidingContainer(working.Skin);
// the beatmapSkinProvider is used as the fallback source here to allow the ruleset-specific skin implementation
// full access to all skin sources.
var rulesetSkinProvider = new SkinProvidingContainer(ruleset.CreateLegacySkinProvider(beatmapSkinProvider, playableBeatmap));
// load the skinning hierarchy first.
// this is intentionally done in two stages to ensure things are in a loaded state before exposing the ruleset to skin sources.
target.Add(new ScalingContainer(ScalingMode.Gameplay)
.WithChild(beatmapSkinProvider
.WithChild(target = rulesetSkinProvider)));
target.AddRange(new Drawable[]
{
DrawableRuleset,
new ComboEffects(ScoreProcessor)
});
DrawableRuleset.FrameStableComponents.AddRange(new Drawable[]
{
ScoreProcessor,
HealthProcessor,
breakTracker = new BreakTracker(DrawableRuleset.GameplayStartTime, ScoreProcessor)
{
Breaks = working.Beatmap.Breaks
}
});
}
private void addOverlayComponents(Container target, WorkingBeatmap working)
{
target.AddRange(new[]
{
DimmableStoryboard.OverlayLayerContainer.CreateProxy(),
BreakOverlay = new BreakOverlay(working.Beatmap.BeatmapInfo.LetterboxInBreaks, ScoreProcessor)
{
Clock = DrawableRuleset.FrameStableClock,
ProcessCustomClock = false,
Breaks = working.Beatmap.Breaks
},
// display the cursor above some HUD elements.
DrawableRuleset.Cursor?.CreateProxy() ?? new Container(),
DrawableRuleset.ResumeOverlay?.CreateProxy() ?? new Container(),
HUDOverlay = new HUDOverlay(ScoreProcessor, HealthProcessor, DrawableRuleset, Mods.Value)
{
HoldToQuit =
{
Action = performUserRequestedExit,
IsPaused = { BindTarget = GameplayClockContainer.IsPaused }
},
PlayerSettingsOverlay = { PlaybackSettings = { UserPlaybackRate = { BindTarget = GameplayClockContainer.UserPlaybackRate } } },
KeyCounter =
{
AlwaysVisible = { BindTarget = DrawableRuleset.HasReplayLoaded },
IsCounting = false
},
RequestSeek = GameplayClockContainer.Seek,
Anchor = Anchor.Centre,
Origin = Anchor.Centre
},
skipOverlay = new SkipOverlay(DrawableRuleset.GameplayStartTime)
{
RequestSkip = GameplayClockContainer.Skip
},
FailOverlay = new FailOverlay
{
OnRetry = Restart,
OnQuit = performUserRequestedExit,
},
PauseOverlay = new PauseOverlay
{
OnResume = Resume,
Retries = RestartCount,
OnRetry = Restart,
OnQuit = performUserRequestedExit,
},
new HotkeyRetryOverlay
{
Action = () =>
{
if (!this.IsCurrentScreen()) return;
fadeOut(true);
Restart();
},
},
new HotkeyExitOverlay
{
Action = () =>
{
if (!this.IsCurrentScreen()) return;
fadeOut(true);
performImmediateExit();
},
},
failAnimation = new FailAnimation(DrawableRuleset) { OnComplete = onFailComplete, },
});
}
private void onBreakTimeChanged(ValueChangedEvent<bool> isBreakTime)
{
updatePauseOnFocusLostState();
HUDOverlay.KeyCounter.IsCounting = !isBreakTime.NewValue;
}
private void updateOverlayActivationMode()
{
bool canTriggerOverlays = DrawableRuleset.IsPaused.Value || breakTracker.IsBreakTime.Value;
if (DrawableRuleset.HasReplayLoaded.Value || canTriggerOverlays)
OverlayActivationMode.Value = OverlayActivation.UserTriggered;
else
OverlayActivationMode.Value = OverlayActivation.Disabled;
}
private void updatePauseOnFocusLostState() =>
HUDOverlay.HoldToQuit.PauseOnFocusLost = PauseOnFocusLost
&& !DrawableRuleset.HasReplayLoaded.Value
&& !breakTracker.IsBreakTime.Value;
private IBeatmap loadPlayableBeatmap()
{
IBeatmap playable;
try
{
if (Beatmap.Value.Beatmap == null)
throw new InvalidOperationException("Beatmap was not loaded");
rulesetInfo = Ruleset.Value ?? Beatmap.Value.BeatmapInfo.Ruleset;
ruleset = rulesetInfo.CreateInstance();
try
{
playable = Beatmap.Value.GetPlayableBeatmap(ruleset.RulesetInfo, Mods.Value);
}
catch (BeatmapInvalidForRulesetException)
{
// A playable beatmap may not be creatable with the user's preferred ruleset, so try using the beatmap's default ruleset
rulesetInfo = Beatmap.Value.BeatmapInfo.Ruleset;
ruleset = rulesetInfo.CreateInstance();
playable = Beatmap.Value.GetPlayableBeatmap(rulesetInfo, Mods.Value);
}
if (playable.HitObjects.Count == 0)
{
Logger.Log("Beatmap contains no hit objects!", level: LogLevel.Error);
return null;
}
}
catch (Exception e)
{
Logger.Error(e, "Could not load beatmap successfully!");
//couldn't load, hard abort!
return null;
}
return playable;
}
private void performImmediateExit()
{
// if a restart has been requested, cancel any pending completion (user has shown intent to restart).
completionProgressDelegate?.Cancel();
ValidForResume = false;
performUserRequestedExit();
}
private void performUserRequestedExit()
{
if (!this.IsCurrentScreen()) return;
if (ValidForResume && HasFailed && !FailOverlay.IsPresent)
{
failAnimation.FinishTransforms(true);
return;
}
if (canPause)
Pause();
else
this.Exit();
}
/// <summary>
/// Restart gameplay via a parent <see cref="PlayerLoader"/>.
/// <remarks>This can be called from a child screen in order to trigger the restart process.</remarks>
/// </summary>
public void Restart()
{
sampleRestart?.Play();
RestartRequested?.Invoke();
if (this.IsCurrentScreen())
performImmediateExit();
else
this.MakeCurrent();
}
private ScheduledDelegate completionProgressDelegate;
private void updateCompletionState(ValueChangedEvent<bool> completionState)
{
// screen may be in the exiting transition phase.
if (!this.IsCurrentScreen())
return;
if (!completionState.NewValue)
{
completionProgressDelegate?.Cancel();
completionProgressDelegate = null;
ValidForResume = true;
return;
}
if (completionProgressDelegate != null)
throw new InvalidOperationException($"{nameof(updateCompletionState)} was fired more than once");
// Only show the completion screen if the player hasn't failed
if (HealthProcessor.HasFailed)
return;
ValidForResume = false;
if (!showResults) return;
using (BeginDelayedSequence(RESULTS_DISPLAY_DELAY))
completionProgressDelegate = Schedule(GotoRanking);
}
protected virtual ScoreInfo CreateScore()
{
var score = new ScoreInfo
{
Beatmap = Beatmap.Value.BeatmapInfo,
Ruleset = rulesetInfo,
Mods = Mods.Value.ToArray(),
};
if (DrawableRuleset.ReplayScore != null)
score.User = DrawableRuleset.ReplayScore.ScoreInfo?.User ?? new GuestUser();
else
score.User = api.LocalUser.Value;
ScoreProcessor.PopulateScore(score);
return score;
}
protected override bool OnScroll(ScrollEvent e) => mouseWheelDisabled.Value && !GameplayClockContainer.IsPaused.Value;
protected virtual ResultsScreen CreateResults(ScoreInfo score) => new SoloResultsScreen(score);
#region Fail Logic
protected FailOverlay FailOverlay { get; private set; }
private FailAnimation failAnimation;
private bool onFail()
{
if (!CheckModsAllowFailure())
return false;
HasFailed = true;
// There is a chance that we could be in a paused state as the ruleset's internal clock (see FrameStabilityContainer)
// could process an extra frame after the GameplayClock is stopped.
// In such cases we want the fail state to precede a user triggered pause.
if (PauseOverlay.State.Value == Visibility.Visible)
PauseOverlay.Hide();
failAnimation.Start();
if (Mods.Value.OfType<IApplicableFailOverride>().Any(m => m.RestartOnFail))
Restart();
return true;
}
// Called back when the transform finishes
private void onFailComplete()
{
GameplayClockContainer.Stop();
FailOverlay.Retries = RestartCount;
FailOverlay.Show();
}
#endregion
#region Pause Logic
public bool IsResuming { get; private set; }
/// <summary>
/// The amount of gameplay time after which a second pause is allowed.
/// </summary>
private const double pause_cooldown = 1000;
protected PauseOverlay PauseOverlay { get; private set; }
private double? lastPauseActionTime;
private bool canPause =>
// must pass basic screen conditions (beatmap loaded, instance allows pause)
LoadedBeatmapSuccessfully && allowPause && ValidForResume
// replays cannot be paused and exit immediately
&& !DrawableRuleset.HasReplayLoaded.Value
// cannot pause if we are already in a fail state
&& !HasFailed
// cannot pause if already paused (or in a cooldown state) unless we are in a resuming state.
&& (IsResuming || (GameplayClockContainer.IsPaused.Value == false && !pauseCooldownActive));
private bool pauseCooldownActive =>
lastPauseActionTime.HasValue && GameplayClockContainer.GameplayClock.CurrentTime < lastPauseActionTime + pause_cooldown;
private bool canResume =>
// cannot resume from a non-paused state
GameplayClockContainer.IsPaused.Value
// cannot resume if we are already in a fail state
&& !HasFailed
// already resuming
&& !IsResuming;
public void Pause()
{
if (!canPause) return;
if (IsResuming)
{
DrawableRuleset.CancelResume();
IsResuming = false;
}
GameplayClockContainer.Stop();
PauseOverlay.Show();
lastPauseActionTime = GameplayClockContainer.GameplayClock.CurrentTime;
}
public void Resume()
{
if (!canResume) return;
IsResuming = true;
PauseOverlay.Hide();
// breaks and time-based conditions may allow instant resume.
if (breakTracker.IsBreakTime.Value)
completeResume();
else
DrawableRuleset.RequestResume(completeResume);
void completeResume()
{
GameplayClockContainer.Start();
IsResuming = false;
}
}
#endregion
#region Screen Logic
public override void OnEntering(IScreen last)
{
base.OnEntering(last);
if (!LoadedBeatmapSuccessfully)
return;
Alpha = 0;
this
.ScaleTo(0.7f)
.ScaleTo(1, 750, Easing.OutQuint)
.Delay(250)
.FadeIn(250);
Background.EnableUserDim.Value = true;
Background.BlurAmount.Value = 0;
// bind component bindables.
Background.IsBreakTime.BindTo(breakTracker.IsBreakTime);
DimmableStoryboard.IsBreakTime.BindTo(breakTracker.IsBreakTime);
Background.StoryboardReplacesBackground.BindTo(storyboardReplacesBackground);
DimmableStoryboard.StoryboardReplacesBackground.BindTo(storyboardReplacesBackground);
storyboardReplacesBackground.Value = Beatmap.Value.Storyboard.ReplacesBackground && Beatmap.Value.Storyboard.HasDrawable;
GameplayClockContainer.Restart();
GameplayClockContainer.FadeInFromZero(750, Easing.OutQuint);
foreach (var mod in Mods.Value.OfType<IApplicableToPlayer>())
mod.ApplyToPlayer(this);
foreach (var mod in Mods.Value.OfType<IApplicableToHUD>())
mod.ApplyToHUD(HUDOverlay);
// Our mods are local copies of the global mods so they need to be re-applied to the track.
// This is done through the music controller (for now), because resetting speed adjustments on the beatmap track also removes adjustments provided by DrawableTrack.
// Todo: In the future, player will receive in a track and will probably not have to worry about this...
musicController.ResetTrackAdjustments();
foreach (var mod in Mods.Value.OfType<IApplicableToTrack>())
mod.ApplyToTrack(musicController.CurrentTrack);
updateOverlayActivationMode();
}
public override void OnSuspending(IScreen next)
{
screenSuspension?.Expire();
fadeOut();
base.OnSuspending(next);
}
public override bool OnExiting(IScreen next)
{
screenSuspension?.Expire();
if (completionProgressDelegate != null && !completionProgressDelegate.Cancelled && !completionProgressDelegate.Completed)
{
// proceed to result screen if beatmap already finished playing
completionProgressDelegate.RunTask();
return true;
}
// ValidForResume is false when restarting
if (ValidForResume)
{
if (pauseCooldownActive && !GameplayClockContainer.IsPaused.Value)
// still want to block if we are within the cooldown period and not already paused.
return true;
}
// GameplayClockContainer performs seeks / start / stop operations on the beatmap's track.
// as we are no longer the current screen, we cannot guarantee the track is still usable.
GameplayClockContainer?.StopUsingBeatmapClock();
musicController.ResetTrackAdjustments();
fadeOut();
return base.OnExiting(next);
}
protected virtual void GotoRanking()
{
if (DrawableRuleset.ReplayScore != null)
{
// if a replay is present, we likely don't want to import into the local database.
this.Push(CreateResults(CreateScore()));
return;
}
LegacyByteArrayReader replayReader = null;
var score = new Score { ScoreInfo = CreateScore() };
if (recordingReplay?.Frames.Count > 0)
{
score.Replay = recordingReplay;
using (var stream = new MemoryStream())
{
new LegacyScoreEncoder(score, gameplayBeatmap.PlayableBeatmap).Encode(stream);
replayReader = new LegacyByteArrayReader(stream.ToArray(), "replay.osr");
}
}
scoreManager.Import(score.ScoreInfo, replayReader)
.ContinueWith(imported => Schedule(() =>
{
// screen may be in the exiting transition phase.
if (this.IsCurrentScreen())
this.Push(CreateResults(imported.Result));
}));
}
private void fadeOut(bool instant = false)
{
float fadeOutDuration = instant ? 0 : 250;
this.FadeOut(fadeOutDuration);
Background.EnableUserDim.Value = false;
storyboardReplacesBackground.Value = false;
}
#endregion
}
}
| {
"pile_set_name": "Github"
} |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Microsoft.Samples.VisualStudio.IronPython.Interfaces;
using Microsoft.VisualStudio.IronPythonInference;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.TextManager.Interop;
namespace IronPython.EditorExtensions
{
/// <summary>
/// Implementation of <see cref="ICompletionSource"/>. Provides the completion sets for the editor.
/// </summary>
internal class CompletionSource : ICompletionSource
{
internal static string CompletionSetName = "IronPython Completion";
private ITextBuffer textBuffer;
private IGlyphService glyphService;
private IServiceProvider serviceProvider;
internal CompletionSource(ITextBuffer textBuffer, IGlyphService glyphService, IServiceProvider serviceProvider)
{
this.textBuffer = textBuffer;
this.glyphService = glyphService;
this.serviceProvider = serviceProvider;
}
#region ICompletionSource Members
void ICompletionSource.AugmentCompletionSession(ICompletionSession session, IList<CompletionSet> completionSets)
{
int position = session.GetTriggerPoint(session.TextView.TextBuffer).GetPosition(textBuffer.CurrentSnapshot);
int line = textBuffer.CurrentSnapshot.GetLineNumberFromPosition(position);
int column = position - textBuffer.CurrentSnapshot.GetLineFromPosition(position).Start.Position;
Microsoft.VisualStudio.IronPythonInference.Modules modules = new Microsoft.VisualStudio.IronPythonInference.Modules();
IList<Declaration> attributes;
if (textBuffer.GetReadOnlyExtents(new Span(0, textBuffer.CurrentSnapshot.Length)).Count > 0)
{
int start;
var readWriteText = TextOfLine(textBuffer, line, column, out start, true);
var module = modules.AnalyzeModule(new QuietCompilerSink(), textBuffer.GetFileName(), readWriteText);
attributes = module.GetAttributesAt(1, column - 1);
foreach (var attribute in GetEngineAttributes(readWriteText, column - start - 1))
{
attributes.Add(attribute);
}
}
else
{
var module = modules.AnalyzeModule(new QuietCompilerSink(), textBuffer.GetFileName(), textBuffer.CurrentSnapshot.GetText());
attributes = module.GetAttributesAt(line + 1, column);
}
completionSets.Add(GetCompletions((List<Declaration>)attributes, session));
}
private IList<Declaration> GetEngineAttributes(string lineText, int column)
{
var declarations = new List<Declaration>();
int start = lineText.Substring(0, column).LastIndexOfAny(Constants.Separators) + 1;
// Now build the string to pass to the engine.
string engineCommand = string.Format(
System.Globalization.CultureInfo.InvariantCulture,
"dir({0})",
lineText.Substring(start, column - start));
try
{
var members = Engine.Evaluate(engineCommand) as IEnumerable;
if (null != members)
{
foreach (string member in members)
{
declarations.Add(new Declaration(member));
}
}
}
catch
{
// Do nothing => Return the empty declarations list
}
return declarations;
}
private IEngine engine;
private IEngine Engine
{
get
{
if (null == engine)
{
var provider = (IPythonEngineProvider)serviceProvider.GetService(typeof(IPythonEngineProvider));
engine = provider.GetSharedEngine();
}
return engine;
}
}
/// <summary>
/// Get a piece of text of a given line in a text buffer
/// </summary>
public string TextOfLine(ITextBuffer textBuffer, int lineNumber, int endColumn, out int start, bool skipReadOnly)
{
start = 0;
var line = textBuffer.CurrentSnapshot.GetLineFromLineNumber(lineNumber);
if (textBuffer.IsReadOnly(line.Extent.Span))
{
start = GetReadOnlyLength(textBuffer.CurrentSnapshot) - line.Start;
}
return line.GetText().Substring(start, endColumn - start);
}
private int GetReadOnlyLength(ITextSnapshot textSnapshot)
{
return textSnapshot.TextBuffer.GetReadOnlyExtents(new Span(0, textSnapshot.Length)).Max(region => region.End);
}
/// <summary>
/// Gets the declarations and snippet entries for the completion
/// </summary>
private CompletionSet GetCompletions(List<Declaration> attributes, ICompletionSession session)
{
// Add IPy completion
var completions = new List<Completion>();
completions.AddRange(attributes.Select(declaration => new PyCompletion(declaration, glyphService)));
if (completions.Count > 0)
{
// Add Snippets entries
var expansionManager = (IVsTextManager2)this.serviceProvider.GetService(typeof(SVsTextManager));
var snippetsEnumerator = new SnippetsEnumerator(expansionManager, Constants.IronPythonLanguageServiceGuid);
completions.AddRange(snippetsEnumerator.Select(expansion => new PyCompletion(expansion, glyphService)));
}
// we want the user to get a sorted list
completions.Sort();
return
new CompletionSet("IPyCompletion",
"IronPython Completion",
CreateTrackingSpan(session.GetTriggerPoint(session.TextView.TextBuffer).GetPosition(textBuffer.CurrentSnapshot)),
completions,
null)
;
}
private ITrackingSpan CreateTrackingSpan(int position)
{
char[] separators = new[] { '\n', '\r', '\t', ' ', '.', ':', '(', ')', '[', ']', '{', '}', '?', '/', '+', '-', ';', '=', '*', '!', ',', '<', '>' };
string text = textBuffer.CurrentSnapshot.GetText();
int last = text.Substring(position).IndexOfAny(separators);
int first = text.Substring(0, position).LastIndexOfAny(separators) + 1;
if (last == -1)
last = text.Length - position;
return textBuffer.CurrentSnapshot.CreateTrackingSpan(new Span(first, (last + position) - first), SpanTrackingMode.EdgeInclusive);
}
#endregion
public void Dispose()
{ }
}
} | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">AdAway</string>
</resources>
| {
"pile_set_name": "Github"
} |
FRAMEWORK_SEARCH_PATHS = "$PODS_FRAMEWORK_BUILD_PATH"
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks'
OTHER_CFLAGS = $(inherited) -iquote "$PODS_FRAMEWORK_BUILD_PATH/QueryKit.framework/Headers"
OTHER_LDFLAGS = $(inherited) -ObjC -framework "QueryKit"
OTHER_LIBTOOLFLAGS = $(OTHER_LDFLAGS)
OTHER_SWIFT_FLAGS = "-D COCOAPODS"
PODS_FRAMEWORK_BUILD_PATH = $(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)/Pods-TestProject
PODS_ROOT = ${SRCROOT}/Pods | {
"pile_set_name": "Github"
} |
// Copyright 2012 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.
// +build windows
package main
import (
"fmt"
"time"
"golang.org/x/sys/windows/svc"
"golang.org/x/sys/windows/svc/debug"
"golang.org/x/sys/windows/svc/eventlog"
)
var elog debug.Log
type myservice struct{}
func (m *myservice) Execute(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (ssec bool, errno uint32) {
const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown | svc.AcceptPauseAndContinue
changes <- svc.Status{State: svc.StartPending}
fasttick := time.Tick(500 * time.Millisecond)
slowtick := time.Tick(2 * time.Second)
tick := fasttick
changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
loop:
for {
select {
case <-tick:
beep()
elog.Info(1, "beep")
case c := <-r:
switch c.Cmd {
case svc.Interrogate:
changes <- c.CurrentStatus
// Testing deadlock from https://code.google.com/p/winsvc/issues/detail?id=4
time.Sleep(100 * time.Millisecond)
changes <- c.CurrentStatus
case svc.Stop, svc.Shutdown:
break loop
case svc.Pause:
changes <- svc.Status{State: svc.Paused, Accepts: cmdsAccepted}
tick = slowtick
case svc.Continue:
changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted}
tick = fasttick
default:
elog.Error(1, fmt.Sprintf("unexpected control request #%d", c))
}
}
}
changes <- svc.Status{State: svc.StopPending}
return
}
func runService(name string, isDebug bool) {
var err error
if isDebug {
elog = debug.New(name)
} else {
elog, err = eventlog.Open(name)
if err != nil {
return
}
}
defer elog.Close()
elog.Info(1, fmt.Sprintf("starting %s service", name))
run := svc.Run
if isDebug {
run = debug.Run
}
err = run(name, &myservice{})
if err != nil {
elog.Error(1, fmt.Sprintf("%s service failed: %v", name, err))
return
}
elog.Info(1, fmt.Sprintf("%s service stopped", name))
}
| {
"pile_set_name": "Github"
} |
require 'sidekiq/exception_handler'
module Sidetiq
class Handler
include Logging
include Sidekiq::ExceptionHandler
def dispatch(worker, tick)
schedule = worker.schedule
return unless schedule.schedule_next?(tick)
Lock::Redis.new(worker).synchronize do |redis|
if schedule.backfill? && (last = worker.last_scheduled_occurrence) > 0
last = Sidetiq.config.utc ? Time.at(last).utc : Time.at(last)
schedule.occurrences_between(last + 1, tick).each do |past_t|
enqueue(worker, past_t, redis)
end
end
enqueue(worker, schedule.next_occurrence(tick), redis)
end
rescue StandardError => e
handle_exception(e, context: "Sidetiq::Handler#dispatch")
raise e
end
private
def enqueue(worker, time, redis)
key = "sidetiq:#{worker.name}"
time_f = time.to_f
next_run = (redis.get("#{key}:next") || -1).to_f
if next_run < time_f
info "Enqueue: #{worker.name} (at: #{time_f}) (last: #{next_run})"
redis.mset("#{key}:last", next_run, "#{key}:next", time_f)
case worker.instance_method(:perform).arity.abs
when 0
worker.perform_at(time)
when 1
worker.perform_at(time, next_run)
else
worker.perform_at(time, next_run, time_f)
end
end
rescue StandardError => e
handle_exception(e, context: "Sidetiq::Handler#enqueue")
raise e
end
end
end
| {
"pile_set_name": "Github"
} |
//
// impl/use_future.hpp
// ~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef NET_TS_IMPL_USE_FUTURE_HPP
#define NET_TS_IMPL_USE_FUTURE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <experimental/__net_ts/detail/config.hpp>
#include <tuple>
#include <experimental/__net_ts/async_result.hpp>
#include <experimental/__net_ts/detail/memory.hpp>
#include <system_error>
#include <experimental/__net_ts/packaged_task.hpp>
#include <system_error>
#include <experimental/__net_ts/system_executor.hpp>
#include <experimental/__net_ts/detail/push_options.hpp>
namespace std {
namespace experimental {
namespace net {
inline namespace v1 {
namespace detail {
#if defined(NET_TS_HAS_VARIADIC_TEMPLATES)
template <typename T, typename F, typename... Args>
inline void promise_invoke_and_set(std::promise<T>& p,
F& f, NET_TS_MOVE_ARG(Args)... args)
{
#if !defined(NET_TS_NO_EXCEPTIONS)
try
#endif // !defined(NET_TS_NO_EXCEPTIONS)
{
p.set_value(f(NET_TS_MOVE_CAST(Args)(args)...));
}
#if !defined(NET_TS_NO_EXCEPTIONS)
catch (...)
{
p.set_exception(std::current_exception());
}
#endif // !defined(NET_TS_NO_EXCEPTIONS)
}
template <typename F, typename... Args>
inline void promise_invoke_and_set(std::promise<void>& p,
F& f, NET_TS_MOVE_ARG(Args)... args)
{
#if !defined(NET_TS_NO_EXCEPTIONS)
try
#endif // !defined(NET_TS_NO_EXCEPTIONS)
{
f(NET_TS_MOVE_CAST(Args)(args)...);
p.set_value();
}
#if !defined(NET_TS_NO_EXCEPTIONS)
catch (...)
{
p.set_exception(std::current_exception());
}
#endif // !defined(NET_TS_NO_EXCEPTIONS)
}
#else // defined(NET_TS_HAS_VARIADIC_TEMPLATES)
template <typename T, typename F>
inline void promise_invoke_and_set(std::promise<T>& p, F& f)
{
#if !defined(NET_TS_NO_EXCEPTIONS)
try
#endif // !defined(NET_TS_NO_EXCEPTIONS)
{
p.set_value(f());
}
#if !defined(NET_TS_NO_EXCEPTIONS)
catch (...)
{
p.set_exception(std::current_exception());
}
#endif // !defined(NET_TS_NO_EXCEPTIONS)
}
template <typename F, typename Args>
inline void promise_invoke_and_set(std::promise<void>& p, F& f)
{
#if !defined(NET_TS_NO_EXCEPTIONS)
try
#endif // !defined(NET_TS_NO_EXCEPTIONS)
{
f();
p.set_value();
#if !defined(NET_TS_NO_EXCEPTIONS)
}
catch (...)
{
p.set_exception(std::current_exception());
}
#endif // !defined(NET_TS_NO_EXCEPTIONS)
}
#if defined(NET_TS_NO_EXCEPTIONS)
#define NET_TS_PRIVATE_PROMISE_INVOKE_DEF(n) \
template <typename T, typename F, NET_TS_VARIADIC_TPARAMS(n)> \
inline void promise_invoke_and_set(std::promise<T>& p, \
F& f, NET_TS_VARIADIC_MOVE_PARAMS(n)) \
{ \
p.set_value(f(NET_TS_VARIADIC_MOVE_ARGS(n))); \
} \
\
template <typename F, NET_TS_VARIADIC_TPARAMS(n)> \
inline void promise_invoke_and_set(std::promise<void>& p, \
F& f, NET_TS_VARIADIC_MOVE_PARAMS(n)) \
{ \
f(NET_TS_VARIADIC_MOVE_ARGS(n)); \
p.set_value(); \
} \
/**/
NET_TS_VARIADIC_GENERATE(NET_TS_PRIVATE_PROMISE_INVOKE_DEF)
#undef NET_TS_PRIVATE_PROMISE_INVOKE_DEF
#else // defined(NET_TS_NO_EXCEPTIONS)
#define NET_TS_PRIVATE_PROMISE_INVOKE_DEF(n) \
template <typename T, typename F, NET_TS_VARIADIC_TPARAMS(n)> \
inline void promise_invoke_and_set(std::promise<T>& p, \
F& f, NET_TS_VARIADIC_MOVE_PARAMS(n)) \
{ \
try \
{ \
p.set_value(f(NET_TS_VARIADIC_MOVE_ARGS(n))); \
} \
catch (...) \
{ \
p.set_exception(std::current_exception()); \
} \
} \
\
template <typename F, NET_TS_VARIADIC_TPARAMS(n)> \
inline void promise_invoke_and_set(std::promise<void>& p, \
F& f, NET_TS_VARIADIC_MOVE_PARAMS(n)) \
{ \
try \
{ \
f(NET_TS_VARIADIC_MOVE_ARGS(n)); \
p.set_value(); \
} \
catch (...) \
{ \
p.set_exception(std::current_exception()); \
} \
} \
/**/
NET_TS_VARIADIC_GENERATE(NET_TS_PRIVATE_PROMISE_INVOKE_DEF)
#undef NET_TS_PRIVATE_PROMISE_INVOKE_DEF
#endif // defined(NET_TS_NO_EXCEPTIONS)
#endif // defined(NET_TS_HAS_VARIADIC_TEMPLATES)
// A function object adapter to invoke a nullary function object and capture
// any exception thrown into a promise.
template <typename T, typename F>
class promise_invoker
{
public:
promise_invoker(const shared_ptr<std::promise<T> >& p,
NET_TS_MOVE_ARG(F) f)
: p_(p), f_(NET_TS_MOVE_CAST(F)(f))
{
}
void operator()()
{
#if !defined(NET_TS_NO_EXCEPTIONS)
try
#endif // !defined(NET_TS_NO_EXCEPTIONS)
{
f_();
}
#if !defined(NET_TS_NO_EXCEPTIONS)
catch (...)
{
p_->set_exception(std::current_exception());
}
#endif // !defined(NET_TS_NO_EXCEPTIONS)
}
private:
shared_ptr<std::promise<T> > p_;
typename decay<F>::type f_;
};
// An executor that adapts the system_executor to capture any exeption thrown
// by a submitted function object and save it into a promise.
template <typename T>
class promise_executor
{
public:
explicit promise_executor(const shared_ptr<std::promise<T> >& p)
: p_(p)
{
}
execution_context& context() const NET_TS_NOEXCEPT
{
return system_executor().context();
}
void on_work_started() const NET_TS_NOEXCEPT {}
void on_work_finished() const NET_TS_NOEXCEPT {}
template <typename F, typename A>
void dispatch(NET_TS_MOVE_ARG(F) f, const A&) const
{
promise_invoker<T, F>(p_, NET_TS_MOVE_CAST(F)(f))();
}
template <typename F, typename A>
void post(NET_TS_MOVE_ARG(F) f, const A& a) const
{
system_executor().post(
promise_invoker<T, F>(p_, NET_TS_MOVE_CAST(F)(f)), a);
}
template <typename F, typename A>
void defer(NET_TS_MOVE_ARG(F) f, const A& a) const
{
system_executor().defer(
promise_invoker<T, F>(p_, NET_TS_MOVE_CAST(F)(f)), a);
}
friend bool operator==(const promise_executor& a,
const promise_executor& b) NET_TS_NOEXCEPT
{
return a.p_ == b.p_;
}
friend bool operator!=(const promise_executor& a,
const promise_executor& b) NET_TS_NOEXCEPT
{
return a.p_ != b.p_;
}
private:
shared_ptr<std::promise<T> > p_;
};
// The base class for all completion handlers that create promises.
template <typename T>
class promise_creator
{
public:
typedef promise_executor<T> executor_type;
executor_type get_executor() const NET_TS_NOEXCEPT
{
return executor_type(p_);
}
typedef std::future<T> future_type;
future_type get_future()
{
return p_->get_future();
}
protected:
template <typename Allocator>
void create_promise(const Allocator& a)
{
NET_TS_REBIND_ALLOC(Allocator, char) b(a);
p_ = std::allocate_shared<std::promise<T>>(b, std::allocator_arg, b);
}
shared_ptr<std::promise<T> > p_;
};
// For completion signature void().
class promise_handler_0
: public promise_creator<void>
{
public:
void operator()()
{
this->p_->set_value();
}
};
// For completion signature void(error_code).
class promise_handler_ec_0
: public promise_creator<void>
{
public:
void operator()(const std::error_code& ec)
{
if (ec)
{
this->p_->set_exception(
std::make_exception_ptr(
std::system_error(ec)));
}
else
{
this->p_->set_value();
}
}
};
// For completion signature void(exception_ptr).
class promise_handler_ex_0
: public promise_creator<void>
{
public:
void operator()(const std::exception_ptr& ex)
{
if (ex)
{
this->p_->set_exception(ex);
}
else
{
this->p_->set_value();
}
}
};
// For completion signature void(T).
template <typename T>
class promise_handler_1
: public promise_creator<T>
{
public:
template <typename Arg>
void operator()(NET_TS_MOVE_ARG(Arg) arg)
{
this->p_->set_value(NET_TS_MOVE_CAST(Arg)(arg));
}
};
// For completion signature void(error_code, T).
template <typename T>
class promise_handler_ec_1
: public promise_creator<T>
{
public:
template <typename Arg>
void operator()(const std::error_code& ec,
NET_TS_MOVE_ARG(Arg) arg)
{
if (ec)
{
this->p_->set_exception(
std::make_exception_ptr(
std::system_error(ec)));
}
else
this->p_->set_value(NET_TS_MOVE_CAST(Arg)(arg));
}
};
// For completion signature void(exception_ptr, T).
template <typename T>
class promise_handler_ex_1
: public promise_creator<T>
{
public:
template <typename Arg>
void operator()(const std::exception_ptr& ex,
NET_TS_MOVE_ARG(Arg) arg)
{
if (ex)
this->p_->set_exception(ex);
else
this->p_->set_value(NET_TS_MOVE_CAST(Arg)(arg));
}
};
// For completion signature void(T1, ..., Tn);
template <typename T>
class promise_handler_n
: public promise_creator<T>
{
public:
#if defined(NET_TS_HAS_VARIADIC_TEMPLATES)
template <typename... Args>
void operator()(NET_TS_MOVE_ARG(Args)... args)
{
this->p_->set_value(
std::forward_as_tuple(
NET_TS_MOVE_CAST(Args)(args)...));
}
#else // defined(NET_TS_HAS_VARIADIC_TEMPLATES)
#define NET_TS_PRIVATE_CALL_OP_DEF(n) \
template <NET_TS_VARIADIC_TPARAMS(n)> \
void operator()(NET_TS_VARIADIC_MOVE_PARAMS(n)) \
{\
this->p_->set_value( \
std::forward_as_tuple( \
NET_TS_VARIADIC_MOVE_ARGS(n))); \
} \
/**/
NET_TS_VARIADIC_GENERATE(NET_TS_PRIVATE_CALL_OP_DEF)
#undef NET_TS_PRIVATE_CALL_OP_DEF
#endif // defined(NET_TS_HAS_VARIADIC_TEMPLATES)
};
// For completion signature void(error_code, T1, ..., Tn);
template <typename T>
class promise_handler_ec_n
: public promise_creator<T>
{
public:
#if defined(NET_TS_HAS_VARIADIC_TEMPLATES)
template <typename... Args>
void operator()(const std::error_code& ec,
NET_TS_MOVE_ARG(Args)... args)
{
if (ec)
{
this->p_->set_exception(
std::make_exception_ptr(
std::system_error(ec)));
}
else
{
this->p_->set_value(
std::forward_as_tuple(
NET_TS_MOVE_CAST(Args)(args)...));
}
}
#else // defined(NET_TS_HAS_VARIADIC_TEMPLATES)
#define NET_TS_PRIVATE_CALL_OP_DEF(n) \
template <NET_TS_VARIADIC_TPARAMS(n)> \
void operator()(const std::error_code& ec, \
NET_TS_VARIADIC_MOVE_PARAMS(n)) \
{\
if (ec) \
{ \
this->p_->set_exception( \
std::make_exception_ptr( \
std::system_error(ec))); \
} \
else \
{ \
this->p_->set_value( \
std::forward_as_tuple( \
NET_TS_VARIADIC_MOVE_ARGS(n))); \
} \
} \
/**/
NET_TS_VARIADIC_GENERATE(NET_TS_PRIVATE_CALL_OP_DEF)
#undef NET_TS_PRIVATE_CALL_OP_DEF
#endif // defined(NET_TS_HAS_VARIADIC_TEMPLATES)
};
// For completion signature void(exception_ptr, T1, ..., Tn);
template <typename T>
class promise_handler_ex_n
: public promise_creator<T>
{
public:
#if defined(NET_TS_HAS_VARIADIC_TEMPLATES)
template <typename... Args>
void operator()(const std::exception_ptr& ex,
NET_TS_MOVE_ARG(Args)... args)
{
if (ex)
this->p_->set_exception(ex);
else
{
this->p_->set_value(
std::forward_as_tuple(
NET_TS_MOVE_CAST(Args)(args)...));
}
}
#else // defined(NET_TS_HAS_VARIADIC_TEMPLATES)
#define NET_TS_PRIVATE_CALL_OP_DEF(n) \
template <NET_TS_VARIADIC_TPARAMS(n)> \
void operator()(const std::exception_ptr& ex, \
NET_TS_VARIADIC_MOVE_PARAMS(n)) \
{\
if (ex) \
this->p_->set_exception(ex); \
else \
{ \
this->p_->set_value( \
std::forward_as_tuple( \
NET_TS_VARIADIC_MOVE_ARGS(n))); \
} \
} \
/**/
NET_TS_VARIADIC_GENERATE(NET_TS_PRIVATE_CALL_OP_DEF)
#undef NET_TS_PRIVATE_CALL_OP_DEF
#endif // defined(NET_TS_HAS_VARIADIC_TEMPLATES)
};
// Helper template to choose the appropriate concrete promise handler
// implementation based on the supplied completion signature.
template <typename> class promise_handler_selector;
template <>
class promise_handler_selector<void()>
: public promise_handler_0 {};
template <>
class promise_handler_selector<void(std::error_code)>
: public promise_handler_ec_0 {};
template <>
class promise_handler_selector<void(std::exception_ptr)>
: public promise_handler_ex_0 {};
template <typename Arg>
class promise_handler_selector<void(Arg)>
: public promise_handler_1<Arg> {};
template <typename Arg>
class promise_handler_selector<void(std::error_code, Arg)>
: public promise_handler_ec_1<Arg> {};
template <typename Arg>
class promise_handler_selector<void(std::exception_ptr, Arg)>
: public promise_handler_ex_1<Arg> {};
#if defined(NET_TS_HAS_VARIADIC_TEMPLATES)
template <typename... Arg>
class promise_handler_selector<void(Arg...)>
: public promise_handler_n<std::tuple<Arg...> > {};
template <typename... Arg>
class promise_handler_selector<void(std::error_code, Arg...)>
: public promise_handler_ec_n<std::tuple<Arg...> > {};
template <typename... Arg>
class promise_handler_selector<void(std::exception_ptr, Arg...)>
: public promise_handler_ex_n<std::tuple<Arg...> > {};
#else // defined(NET_TS_HAS_VARIADIC_TEMPLATES)
#define NET_TS_PRIVATE_PROMISE_SELECTOR_DEF(n) \
template <typename Arg, NET_TS_VARIADIC_TPARAMS(n)> \
class promise_handler_selector< \
void(Arg, NET_TS_VARIADIC_TARGS(n))> \
: public promise_handler_n< \
std::tuple<Arg, NET_TS_VARIADIC_TARGS(n)> > {}; \
\
template <typename Arg, NET_TS_VARIADIC_TPARAMS(n)> \
class promise_handler_selector< \
void(std::error_code, Arg, NET_TS_VARIADIC_TARGS(n))> \
: public promise_handler_ec_n< \
std::tuple<Arg, NET_TS_VARIADIC_TARGS(n)> > {}; \
\
template <typename Arg, NET_TS_VARIADIC_TPARAMS(n)> \
class promise_handler_selector< \
void(std::exception_ptr, Arg, NET_TS_VARIADIC_TARGS(n))> \
: public promise_handler_ex_n< \
std::tuple<Arg, NET_TS_VARIADIC_TARGS(n)> > {}; \
/**/
NET_TS_VARIADIC_GENERATE(NET_TS_PRIVATE_PROMISE_SELECTOR_DEF)
#undef NET_TS_PRIVATE_PROMISE_SELECTOR_DEF
#endif // defined(NET_TS_HAS_VARIADIC_TEMPLATES)
// Completion handlers produced from the use_future completion token, when not
// using use_future::operator().
template <typename Signature, typename Allocator>
class promise_handler
: public promise_handler_selector<Signature>
{
public:
typedef Allocator allocator_type;
typedef void result_type;
promise_handler(use_future_t<Allocator> u)
: allocator_(u.get_allocator())
{
this->create_promise(allocator_);
}
allocator_type get_allocator() const NET_TS_NOEXCEPT
{
return allocator_;
}
private:
Allocator allocator_;
};
template <typename Function, typename Signature, typename Allocator>
inline void networking_ts_handler_invoke(Function& f,
promise_handler<Signature, Allocator>* h)
{
typename promise_handler<Signature, Allocator>::executor_type
ex(h->get_executor());
ex.dispatch(NET_TS_MOVE_CAST(Function)(f), std::allocator<void>());
}
template <typename Function, typename Signature, typename Allocator>
inline void networking_ts_handler_invoke(const Function& f,
promise_handler<Signature, Allocator>* h)
{
typename promise_handler<Signature, Allocator>::executor_type
ex(h->get_executor());
ex.dispatch(f, std::allocator<void>());
}
// Helper base class for async_result specialisation.
template <typename Signature, typename Allocator>
class promise_async_result
{
public:
typedef promise_handler<Signature, Allocator> completion_handler_type;
typedef typename completion_handler_type::future_type return_type;
explicit promise_async_result(completion_handler_type& h)
: future_(h.get_future())
{
}
return_type get()
{
return NET_TS_MOVE_CAST(return_type)(future_);
}
private:
return_type future_;
};
// Return value from use_future::operator().
template <typename Function, typename Allocator>
class packaged_token
{
public:
packaged_token(Function f, const Allocator& a)
: function_(NET_TS_MOVE_CAST(Function)(f)),
allocator_(a)
{
}
//private:
Function function_;
Allocator allocator_;
};
// Completion handlers produced from the use_future completion token, when
// using use_future::operator().
template <typename Function, typename Allocator, typename Result>
class packaged_handler
: public promise_creator<Result>
{
public:
typedef Allocator allocator_type;
typedef void result_type;
packaged_handler(packaged_token<Function, Allocator> t)
: function_(NET_TS_MOVE_CAST(Function)(t.function_)),
allocator_(t.allocator_)
{
this->create_promise(allocator_);
}
allocator_type get_allocator() const NET_TS_NOEXCEPT
{
return allocator_;
}
#if defined(NET_TS_HAS_VARIADIC_TEMPLATES)
template <typename... Args>
void operator()(NET_TS_MOVE_ARG(Args)... args)
{
(promise_invoke_and_set)(*this->p_,
function_, NET_TS_MOVE_CAST(Args)(args)...);
}
#else // defined(NET_TS_HAS_VARIADIC_TEMPLATES)
void operator()()
{
(promise_invoke_and_set)(*this->p_, function_);
}
#define NET_TS_PRIVATE_CALL_OP_DEF(n) \
template <NET_TS_VARIADIC_TPARAMS(n)> \
void operator()(NET_TS_VARIADIC_MOVE_PARAMS(n)) \
{\
(promise_invoke_and_set)(*this->p_, \
function_, NET_TS_VARIADIC_MOVE_ARGS(n)); \
} \
/**/
NET_TS_VARIADIC_GENERATE(NET_TS_PRIVATE_CALL_OP_DEF)
#undef NET_TS_PRIVATE_CALL_OP_DEF
#endif // defined(NET_TS_HAS_VARIADIC_TEMPLATES)
private:
Function function_;
Allocator allocator_;
};
template <typename Function,
typename Function1, typename Allocator, typename Result>
inline void networking_ts_handler_invoke(Function& f,
packaged_handler<Function1, Allocator, Result>* h)
{
typename packaged_handler<Function1, Allocator, Result>::executor_type
ex(h->get_executor());
ex.dispatch(NET_TS_MOVE_CAST(Function)(f), std::allocator<void>());
}
template <typename Function,
typename Function1, typename Allocator, typename Result>
inline void networking_ts_handler_invoke(const Function& f,
packaged_handler<Function1, Allocator, Result>* h)
{
typename packaged_handler<Function1, Allocator, Result>::executor_type
ex(h->get_executor());
ex.dispatch(f, std::allocator<void>());
}
// Helper base class for async_result specialisation.
template <typename Function, typename Allocator, typename Result>
class packaged_async_result
{
public:
typedef packaged_handler<Function, Allocator, Result> completion_handler_type;
typedef typename completion_handler_type::future_type return_type;
explicit packaged_async_result(completion_handler_type& h)
: future_(h.get_future())
{
}
return_type get()
{
return NET_TS_MOVE_CAST(return_type)(future_);
}
private:
return_type future_;
};
} // namespace detail
template <typename Allocator> template <typename Function>
inline detail::packaged_token<typename decay<Function>::type, Allocator>
use_future_t<Allocator>::operator()(NET_TS_MOVE_ARG(Function) f) const
{
return detail::packaged_token<typename decay<Function>::type, Allocator>(
NET_TS_MOVE_CAST(Function)(f), allocator_);
}
#if !defined(GENERATING_DOCUMENTATION)
#if defined(NET_TS_HAS_VARIADIC_TEMPLATES)
template <typename Allocator, typename Result, typename... Args>
class async_result<use_future_t<Allocator>, Result(Args...)>
: public detail::promise_async_result<
void(typename decay<Args>::type...), Allocator>
{
public:
explicit async_result(
typename detail::promise_async_result<void(typename decay<Args>::type...),
Allocator>::completion_handler_type& h)
: detail::promise_async_result<
void(typename decay<Args>::type...), Allocator>(h)
{
}
};
template <typename Function, typename Allocator,
typename Result, typename... Args>
class async_result<detail::packaged_token<Function, Allocator>, Result(Args...)>
: public detail::packaged_async_result<Function, Allocator,
typename result_of<Function(Args...)>::type>
{
public:
explicit async_result(
typename detail::packaged_async_result<Function, Allocator,
typename result_of<Function(Args...)>::type>::completion_handler_type& h)
: detail::packaged_async_result<Function, Allocator,
typename result_of<Function(Args...)>::type>(h)
{
}
};
#else // defined(NET_TS_HAS_VARIADIC_TEMPLATES)
template <typename Allocator, typename Result>
class async_result<use_future_t<Allocator>, Result()>
: public detail::promise_async_result<void(), Allocator>
{
public:
explicit async_result(
typename detail::promise_async_result<
void(), Allocator>::completion_handler_type& h)
: detail::promise_async_result<void(), Allocator>(h)
{
}
};
template <typename Function, typename Allocator, typename Result>
class async_result<detail::packaged_token<Function, Allocator>, Result()>
: public detail::packaged_async_result<Function, Allocator,
typename result_of<Function()>::type>
{
public:
explicit async_result(
typename detail::packaged_async_result<Function, Allocator,
typename result_of<Function()>::type>::completion_handler_type& h)
: detail::packaged_async_result<Function, Allocator,
typename result_of<Function()>::type>(h)
{
}
};
#define NET_TS_PRIVATE_ASYNC_RESULT_DEF(n) \
template <typename Allocator, \
typename Result, NET_TS_VARIADIC_TPARAMS(n)> \
class async_result<use_future_t<Allocator>, \
Result(NET_TS_VARIADIC_TARGS(n))> \
: public detail::promise_async_result< \
void(NET_TS_VARIADIC_DECAY(n)), Allocator> \
{ \
public: \
explicit async_result( \
typename detail::promise_async_result< \
void(NET_TS_VARIADIC_DECAY(n)), \
Allocator>::completion_handler_type& h) \
: detail::promise_async_result< \
void(NET_TS_VARIADIC_DECAY(n)), Allocator>(h) \
{ \
} \
}; \
\
template <typename Function, typename Allocator, \
typename Result, NET_TS_VARIADIC_TPARAMS(n)> \
class async_result<detail::packaged_token<Function, Allocator>, \
Result(NET_TS_VARIADIC_TARGS(n))> \
: public detail::packaged_async_result<Function, Allocator, \
typename result_of<Function(NET_TS_VARIADIC_TARGS(n))>::type> \
{ \
public: \
explicit async_result( \
typename detail::packaged_async_result<Function, Allocator, \
typename result_of<Function(NET_TS_VARIADIC_TARGS(n))>::type \
>::completion_handler_type& h) \
: detail::packaged_async_result<Function, Allocator, \
typename result_of<Function(NET_TS_VARIADIC_TARGS(n))>::type>(h) \
{ \
} \
}; \
/**/
NET_TS_VARIADIC_GENERATE(NET_TS_PRIVATE_ASYNC_RESULT_DEF)
#undef NET_TS_PRIVATE_ASYNC_RESULT_DEF
#endif // defined(NET_TS_HAS_VARIADIC_TEMPLATES)
#endif // !defined(GENERATING_DOCUMENTATION)
} // inline namespace v1
} // namespace net
} // namespace experimental
} // namespace std
#include <experimental/__net_ts/detail/pop_options.hpp>
#endif // NET_TS_IMPL_USE_FUTURE_HPP
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of the Ford Motor Company nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef SRC_COMPONENTS_INCLUDE_TELEMETRY_MONITOR_TELEMETRY_OBSERVABLE_H_
#define SRC_COMPONENTS_INCLUDE_TELEMETRY_MONITOR_TELEMETRY_OBSERVABLE_H_
namespace telemetry_monitor {
template <class TelemetryObserver>
class TelemetryObservable {
public:
virtual void SetTelemetryObserver(TelemetryObserver* observer) = 0;
};
} // namespace telemetry_monitor
#endif // SRC_COMPONENTS_INCLUDE_TELEMETRY_MONITOR_TELEMETRY_OBSERVABLE_H_
| {
"pile_set_name": "Github"
} |
/*
* Destination option/media support for CUPS.
*
* Copyright © 2012-2019 by Apple Inc.
*
* Licensed under Apache License v2.0. See the file "LICENSE" for more
* information.
*/
/*
* Include necessary headers...
*/
#include "cups-private.h"
#include "debug-internal.h"
/*
* Local constants...
*/
#define _CUPS_MEDIA_READY_TTL 30 /* Life of xxx-ready values */
/*
* Local functions...
*/
static void cups_add_dconstres(cups_array_t *a, ipp_t *collection);
static int cups_collection_contains(ipp_t *test, ipp_t *match);
static size_t cups_collection_string(ipp_attribute_t *attr, char *buffer, size_t bufsize) _CUPS_NONNULL((1,2));
static int cups_compare_dconstres(_cups_dconstres_t *a,
_cups_dconstres_t *b);
static int cups_compare_media_db(_cups_media_db_t *a,
_cups_media_db_t *b);
static _cups_media_db_t *cups_copy_media_db(_cups_media_db_t *mdb);
static void cups_create_cached(http_t *http, cups_dinfo_t *dinfo,
unsigned flags);
static void cups_create_constraints(cups_dinfo_t *dinfo);
static void cups_create_defaults(cups_dinfo_t *dinfo);
static void cups_create_media_db(cups_dinfo_t *dinfo,
unsigned flags);
static void cups_free_media_db(_cups_media_db_t *mdb);
static int cups_get_media_db(http_t *http, cups_dinfo_t *dinfo,
pwg_media_t *pwg, unsigned flags,
cups_size_t *size);
static int cups_is_close_media_db(_cups_media_db_t *a,
_cups_media_db_t *b);
static cups_array_t *cups_test_constraints(cups_dinfo_t *dinfo,
const char *new_option,
const char *new_value,
int num_options,
cups_option_t *options,
int *num_conflicts,
cups_option_t **conflicts);
static void cups_update_ready(http_t *http, cups_dinfo_t *dinfo);
/*
* 'cupsAddDestMediaOptions()' - Add the option corresponding to the specified media size.
*
* @since CUPS 2.3/macOS 10.14@
*/
int /* O - New number of options */
cupsAddDestMediaOptions(
http_t *http, /* I - Connection to destination */
cups_dest_t *dest, /* I - Destination */
cups_dinfo_t *dinfo, /* I - Destination information */
unsigned flags, /* I - Media matching flags */
cups_size_t *size, /* I - Media size */
int num_options, /* I - Current number of options */
cups_option_t **options) /* IO - Options */
{
cups_array_t *db; /* Media database */
_cups_media_db_t *mdb; /* Media database entry */
char value[2048]; /* Option value */
/*
* Range check input...
*/
if (!http || !dest || !dinfo || !size || !options)
{
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
return (num_options);
}
/*
* Find the matching media size...
*/
if (flags & CUPS_MEDIA_FLAGS_READY)
db = dinfo->ready_db;
else
db = dinfo->media_db;
DEBUG_printf(("1cupsAddDestMediaOptions: size->media=\"%s\"", size->media));
for (mdb = (_cups_media_db_t *)cupsArrayFirst(db); mdb; mdb = (_cups_media_db_t *)cupsArrayNext(db))
{
if (mdb->key && !strcmp(mdb->key, size->media))
break;
else if (mdb->size_name && !strcmp(mdb->size_name, size->media))
break;
}
if (!mdb)
{
for (mdb = (_cups_media_db_t *)cupsArrayFirst(db); mdb; mdb = (_cups_media_db_t *)cupsArrayNext(db))
{
if (mdb->width == size->width && mdb->length == size->length && mdb->bottom == size->bottom && mdb->left == size->left && mdb->right == size->right && mdb->top == size->top)
break;
}
}
if (!mdb)
{
for (mdb = (_cups_media_db_t *)cupsArrayFirst(db); mdb; mdb = (_cups_media_db_t *)cupsArrayNext(db))
{
if (mdb->width == size->width && mdb->length == size->length)
break;
}
}
if (!mdb)
{
DEBUG_puts("1cupsAddDestMediaOptions: Unable to find matching size.");
return (num_options);
}
DEBUG_printf(("1cupsAddDestMediaOptions: MATCH mdb%p [key=\"%s\" size_name=\"%s\" source=\"%s\" type=\"%s\" width=%d length=%d B%d L%d R%d T%d]", (void *)mdb, mdb->key, mdb->size_name, mdb->source, mdb->type, mdb->width, mdb->length, mdb->bottom, mdb->left, mdb->right, mdb->top));
if (mdb->source)
{
if (mdb->type)
snprintf(value, sizeof(value), "{media-size={x-dimension=%d y-dimension=%d} media-bottom-margin=%d media-left-margin=%d media-right-margin=%d media-top-margin=%d media-source=\"%s\" media-type=\"%s\"}", mdb->width, mdb->length, mdb->bottom, mdb->left, mdb->right, mdb->top, mdb->source, mdb->type);
else
snprintf(value, sizeof(value), "{media-size={x-dimension=%d y-dimension=%d} media-bottom-margin=%d media-left-margin=%d media-right-margin=%d media-top-margin=%d media-source=\"%s\"}", mdb->width, mdb->length, mdb->bottom, mdb->left, mdb->right, mdb->top, mdb->source);
}
else if (mdb->type)
{
snprintf(value, sizeof(value), "{media-size={x-dimension=%d y-dimension=%d} media-bottom-margin=%d media-left-margin=%d media-right-margin=%d media-top-margin=%d media-type=\"%s\"}", mdb->width, mdb->length, mdb->bottom, mdb->left, mdb->right, mdb->top, mdb->type);
}
else
{
snprintf(value, sizeof(value), "{media-size={x-dimension=%d y-dimension=%d} media-bottom-margin=%d media-left-margin=%d media-right-margin=%d media-top-margin=%d}", mdb->width, mdb->length, mdb->bottom, mdb->left, mdb->right, mdb->top);
}
num_options = cupsAddOption("media-col", value, num_options, options);
return (num_options);
}
/*
* 'cupsCheckDestSupported()' - Check that the option and value are supported
* by the destination.
*
* Returns 1 if supported, 0 otherwise.
*
* @since CUPS 1.6/macOS 10.8@
*/
int /* O - 1 if supported, 0 otherwise */
cupsCheckDestSupported(
http_t *http, /* I - Connection to destination */
cups_dest_t *dest, /* I - Destination */
cups_dinfo_t *dinfo, /* I - Destination information */
const char *option, /* I - Option */
const char *value) /* I - Value or @code NULL@ */
{
int i; /* Looping var */
char temp[1024]; /* Temporary string */
int int_value; /* Integer value */
int xres_value, /* Horizontal resolution */
yres_value; /* Vertical resolution */
ipp_res_t units_value; /* Resolution units */
ipp_attribute_t *attr; /* Attribute */
_ipp_value_t *attrval; /* Current attribute value */
_ipp_option_t *map; /* Option mapping information */
/*
* Get the default connection as needed...
*/
if (!http)
http = _cupsConnect();
/*
* Range check input...
*/
if (!http || !dest || !dinfo || !option)
return (0);
/*
* Lookup the attribute...
*/
if (strstr(option, "-supported"))
attr = ippFindAttribute(dinfo->attrs, option, IPP_TAG_ZERO);
else
{
snprintf(temp, sizeof(temp), "%s-supported", option);
attr = ippFindAttribute(dinfo->attrs, temp, IPP_TAG_ZERO);
}
if (!attr)
return (0);
if (!value)
return (1);
/*
* Compare values...
*/
if (!strcmp(option, "media") && !strncmp(value, "custom_", 7))
{
/*
* Check range of custom media sizes...
*/
pwg_media_t *pwg; /* Current PWG media size info */
int min_width, /* Minimum width */
min_length, /* Minimum length */
max_width, /* Maximum width */
max_length; /* Maximum length */
/*
* Get the minimum and maximum size...
*/
min_width = min_length = INT_MAX;
max_width = max_length = 0;
for (i = attr->num_values, attrval = attr->values;
i > 0;
i --, attrval ++)
{
if (!strncmp(attrval->string.text, "custom_min_", 11) &&
(pwg = pwgMediaForPWG(attrval->string.text)) != NULL)
{
min_width = pwg->width;
min_length = pwg->length;
}
else if (!strncmp(attrval->string.text, "custom_max_", 11) &&
(pwg = pwgMediaForPWG(attrval->string.text)) != NULL)
{
max_width = pwg->width;
max_length = pwg->length;
}
}
/*
* Check the range...
*/
if (min_width < INT_MAX && max_width > 0 &&
(pwg = pwgMediaForPWG(value)) != NULL &&
pwg->width >= min_width && pwg->width <= max_width &&
pwg->length >= min_length && pwg->length <= max_length)
return (1);
}
else
{
/*
* Check literal values...
*/
map = _ippFindOption(option);
switch (attr->value_tag)
{
case IPP_TAG_INTEGER :
if (map && map->value_tag == IPP_TAG_STRING)
return (strlen(value) <= (size_t)attr->values[0].integer);
case IPP_TAG_ENUM :
int_value = atoi(value);
for (i = 0; i < attr->num_values; i ++)
if (attr->values[i].integer == int_value)
return (1);
break;
case IPP_TAG_BOOLEAN :
return (attr->values[0].boolean);
case IPP_TAG_RANGE :
if (map && map->value_tag == IPP_TAG_STRING)
int_value = (int)strlen(value);
else
int_value = atoi(value);
for (i = 0; i < attr->num_values; i ++)
if (int_value >= attr->values[i].range.lower &&
int_value <= attr->values[i].range.upper)
return (1);
break;
case IPP_TAG_RESOLUTION :
if (sscanf(value, "%dx%d%15s", &xres_value, &yres_value, temp) != 3)
{
if (sscanf(value, "%d%15s", &xres_value, temp) != 2)
return (0);
yres_value = xres_value;
}
if (!strcmp(temp, "dpi"))
units_value = IPP_RES_PER_INCH;
else if (!strcmp(temp, "dpc") || !strcmp(temp, "dpcm"))
units_value = IPP_RES_PER_CM;
else
return (0);
for (i = attr->num_values, attrval = attr->values;
i > 0;
i --, attrval ++)
{
if (attrval->resolution.xres == xres_value &&
attrval->resolution.yres == yres_value &&
attrval->resolution.units == units_value)
return (1);
}
break;
case IPP_TAG_TEXT :
case IPP_TAG_NAME :
case IPP_TAG_KEYWORD :
case IPP_TAG_CHARSET :
case IPP_TAG_URI :
case IPP_TAG_URISCHEME :
case IPP_TAG_MIMETYPE :
case IPP_TAG_LANGUAGE :
case IPP_TAG_TEXTLANG :
case IPP_TAG_NAMELANG :
for (i = 0; i < attr->num_values; i ++)
if (!strcmp(attr->values[i].string.text, value))
return (1);
break;
default :
break;
}
}
/*
* If we get there the option+value is not supported...
*/
return (0);
}
/*
* 'cupsCopyDestConflicts()' - Get conflicts and resolutions for a new
* option/value pair.
*
* "num_options" and "options" represent the currently selected options by the
* user. "new_option" and "new_value" are the setting the user has just
* changed.
*
* Returns 1 if there is a conflict, 0 if there are no conflicts, and -1 if
* there was an unrecoverable error such as a resolver loop.
*
* If "num_conflicts" and "conflicts" are not @code NULL@, they are set to
* contain the list of conflicting option/value pairs. Similarly, if
* "num_resolved" and "resolved" are not @code NULL@ they will be set to the
* list of changes needed to resolve the conflict.
*
* If cupsCopyDestConflicts returns 1 but "num_resolved" and "resolved" are set
* to 0 and @code NULL@, respectively, then the conflict cannot be resolved.
*
* @since CUPS 1.6/macOS 10.8@
*/
int /* O - 1 if there is a conflict, 0 if none, -1 on error */
cupsCopyDestConflicts(
http_t *http, /* I - Connection to destination */
cups_dest_t *dest, /* I - Destination */
cups_dinfo_t *dinfo, /* I - Destination information */
int num_options, /* I - Number of current options */
cups_option_t *options, /* I - Current options */
const char *new_option, /* I - New option */
const char *new_value, /* I - New value */
int *num_conflicts, /* O - Number of conflicting options */
cups_option_t **conflicts, /* O - Conflicting options */
int *num_resolved, /* O - Number of options to resolve */
cups_option_t **resolved) /* O - Resolved options */
{
int i, /* Looping var */
have_conflicts = 0, /* Do we have conflicts? */
changed, /* Did we change something? */
tries, /* Number of tries for resolution */
num_myconf = 0, /* My number of conflicting options */
num_myres = 0; /* My number of resolved options */
cups_option_t *myconf = NULL, /* My conflicting options */
*myres = NULL, /* My resolved options */
*myoption, /* My current option */
*option; /* Current option */
cups_array_t *active = NULL, /* Active conflicts */
*pass = NULL, /* Resolvers for this pass */
*resolvers = NULL, /* Resolvers we have used */
*test; /* Test array for conflicts */
_cups_dconstres_t *c, /* Current constraint */
*r; /* Current resolver */
ipp_attribute_t *attr; /* Current attribute */
char value[2048]; /* Current attribute value as string */
const char *myvalue; /* Current value of an option */
/*
* Clear returned values...
*/
if (num_conflicts)
*num_conflicts = 0;
if (conflicts)
*conflicts = NULL;
if (num_resolved)
*num_resolved = 0;
if (resolved)
*resolved = NULL;
/*
* Get the default connection as needed...
*/
if (!http)
http = _cupsConnect();
/*
* Range check input...
*/
if (!http || !dest || !dinfo ||
(num_conflicts != NULL) != (conflicts != NULL) ||
(num_resolved != NULL) != (resolved != NULL))
return (0);
/*
* Load constraints as needed...
*/
if (!dinfo->constraints)
cups_create_constraints(dinfo);
if (cupsArrayCount(dinfo->constraints) == 0)
return (0);
if (!dinfo->num_defaults)
cups_create_defaults(dinfo);
/*
* If we are resolving, create a shadow array...
*/
if (num_resolved)
{
for (i = num_options, option = options; i > 0; i --, option ++)
num_myres = cupsAddOption(option->name, option->value, num_myres, &myres);
if (new_option && new_value)
num_myres = cupsAddOption(new_option, new_value, num_myres, &myres);
}
else
{
num_myres = num_options;
myres = options;
}
/*
* Check for any conflicts...
*/
if (num_resolved)
pass = cupsArrayNew((cups_array_func_t)cups_compare_dconstres, NULL);
for (tries = 0; tries < 100; tries ++)
{
/*
* Check for any conflicts...
*/
if (num_conflicts || num_resolved)
{
cupsFreeOptions(num_myconf, myconf);
num_myconf = 0;
myconf = NULL;
active = cups_test_constraints(dinfo, new_option, new_value,
num_myres, myres, &num_myconf,
&myconf);
}
else
active = cups_test_constraints(dinfo, new_option, new_value, num_myres,
myres, NULL, NULL);
have_conflicts = (active != NULL);
if (!active || !num_resolved)
break; /* All done */
/*
* Scan the constraints that were triggered to apply resolvers...
*/
if (!resolvers)
resolvers = cupsArrayNew((cups_array_func_t)cups_compare_dconstres, NULL);
for (c = (_cups_dconstres_t *)cupsArrayFirst(active), changed = 0;
c;
c = (_cups_dconstres_t *)cupsArrayNext(active))
{
if (cupsArrayFind(pass, c))
continue; /* Already applied this resolver... */
if (cupsArrayFind(resolvers, c))
{
DEBUG_printf(("1cupsCopyDestConflicts: Resolver loop with %s.",
c->name));
have_conflicts = -1;
goto cleanup;
}
if ((r = cupsArrayFind(dinfo->resolvers, c)) == NULL)
{
DEBUG_printf(("1cupsCopyDestConflicts: Resolver %s not found.",
c->name));
have_conflicts = -1;
goto cleanup;
}
/*
* Add the options from the resolver...
*/
cupsArrayAdd(pass, r);
cupsArrayAdd(resolvers, r);
for (attr = ippFirstAttribute(r->collection);
attr;
attr = ippNextAttribute(r->collection))
{
if (new_option && !strcmp(attr->name, new_option))
continue; /* Ignore this if we just changed it */
if (ippAttributeString(attr, value, sizeof(value)) >= sizeof(value))
continue; /* Ignore if the value is too long */
if ((test = cups_test_constraints(dinfo, attr->name, value, num_myres,
myres, NULL, NULL)) == NULL)
{
/*
* That worked, flag it...
*/
changed = 1;
}
else
cupsArrayDelete(test);
/*
* Add the option/value from the resolver regardless of whether it
* worked; this makes sure that we can cascade several changes to
* make things resolve...
*/
num_myres = cupsAddOption(attr->name, value, num_myres, &myres);
}
}
if (!changed)
{
DEBUG_puts("1cupsCopyDestConflicts: Unable to resolve constraints.");
have_conflicts = -1;
goto cleanup;
}
cupsArrayClear(pass);
cupsArrayDelete(active);
active = NULL;
}
if (tries >= 100)
{
DEBUG_puts("1cupsCopyDestConflicts: Unable to resolve after 100 tries.");
have_conflicts = -1;
goto cleanup;
}
/*
* Copy resolved options as needed...
*/
if (num_resolved)
{
for (i = num_myres, myoption = myres; i > 0; i --, myoption ++)
{
if ((myvalue = cupsGetOption(myoption->name, num_options,
options)) == NULL ||
strcmp(myvalue, myoption->value))
{
if (new_option && !strcmp(new_option, myoption->name) &&
new_value && !strcmp(new_value, myoption->value))
continue;
*num_resolved = cupsAddOption(myoption->name, myoption->value,
*num_resolved, resolved);
}
}
}
/*
* Clean up...
*/
cleanup:
cupsArrayDelete(active);
cupsArrayDelete(pass);
cupsArrayDelete(resolvers);
if (num_resolved)
{
/*
* Free shadow copy of options...
*/
cupsFreeOptions(num_myres, myres);
}
if (num_conflicts)
{
/*
* Return conflicting options to caller...
*/
*num_conflicts = num_myconf;
*conflicts = myconf;
}
else
{
/*
* Free conflicting options...
*/
cupsFreeOptions(num_myconf, myconf);
}
return (have_conflicts);
}
/*
* 'cupsCopyDestInfo()' - Get the supported values/capabilities for the
* destination.
*
* The caller is responsible for calling @link cupsFreeDestInfo@ on the return
* value. @code NULL@ is returned on error.
*
* @since CUPS 1.6/macOS 10.8@
*/
cups_dinfo_t * /* O - Destination information */
cupsCopyDestInfo(
http_t *http, /* I - Connection to destination */
cups_dest_t *dest) /* I - Destination */
{
cups_dinfo_t *dinfo; /* Destination information */
unsigned dflags; /* Destination flags */
ipp_t *request, /* Get-Printer-Attributes request */
*response; /* Supported attributes */
int tries, /* Number of tries so far */
delay, /* Current retry delay */
prev_delay; /* Next retry delay */
const char *uri; /* Printer URI */
char resource[1024]; /* Resource path */
int version; /* IPP version */
ipp_status_t status; /* Status of request */
_cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
static const char * const requested_attrs[] =
{ /* Requested attributes */
"job-template",
"media-col-database",
"printer-description"
};
DEBUG_printf(("cupsCopyDestInfo(http=%p, dest=%p(%s))", (void *)http, (void *)dest, dest ? dest->name : ""));
/*
* Get the default connection as needed...
*/
if (!http)
{
DEBUG_puts("1cupsCopyDestInfo: Default server connection.");
http = _cupsConnect();
dflags = CUPS_DEST_FLAGS_NONE;
}
#ifdef AF_LOCAL
else if (httpAddrFamily(http->hostaddr) == AF_LOCAL)
{
DEBUG_puts("1cupsCopyDestInfo: Connection to server (domain socket).");
dflags = CUPS_DEST_FLAGS_NONE;
}
#endif /* AF_LOCAL */
else if ((strcmp(http->hostname, cg->server) && cg->server[0] != '/') || cg->ipp_port != httpAddrPort(http->hostaddr))
{
DEBUG_printf(("1cupsCopyDestInfo: Connection to device (%s).", http->hostname));
dflags = CUPS_DEST_FLAGS_DEVICE;
}
else
{
DEBUG_printf(("1cupsCopyDestInfo: Connection to server (%s).", http->hostname));
dflags = CUPS_DEST_FLAGS_NONE;
}
/*
* Range check input...
*/
if (!http || !dest)
return (NULL);
/*
* Get the printer URI and resource path...
*/
if ((uri = _cupsGetDestResource(dest, dflags, resource, sizeof(resource))) == NULL)
{
DEBUG_puts("1cupsCopyDestInfo: Unable to get resource.");
return (NULL);
}
/*
* Get the supported attributes...
*/
delay = 1;
prev_delay = 1;
tries = 0;
version = 20;
do
{
/*
* Send a Get-Printer-Attributes request...
*/
request = ippNewRequest(IPP_OP_GET_PRINTER_ATTRIBUTES);
ippSetVersion(request, version / 10, version % 10);
ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL, uri);
ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name", NULL, cupsUser());
ippAddStrings(request, IPP_TAG_OPERATION, IPP_TAG_KEYWORD, "requested-attributes", (int)(sizeof(requested_attrs) / sizeof(requested_attrs[0])), NULL, requested_attrs);
response = cupsDoRequest(http, request, resource);
status = cupsLastError();
if (status > IPP_STATUS_OK_IGNORED_OR_SUBSTITUTED)
{
DEBUG_printf(("1cupsCopyDestInfo: Get-Printer-Attributes for '%s' returned %s (%s)", dest->name, ippErrorString(status), cupsLastErrorString()));
ippDelete(response);
response = NULL;
if ((status == IPP_STATUS_ERROR_BAD_REQUEST || status == IPP_STATUS_ERROR_VERSION_NOT_SUPPORTED) && version > 11)
{
version = 11;
}
else if (status == IPP_STATUS_ERROR_BUSY)
{
sleep((unsigned)delay);
delay = _cupsNextDelay(delay, &prev_delay);
}
else
return (NULL);
}
tries ++;
}
while (!response && tries < 10);
if (!response)
{
DEBUG_puts("1cupsCopyDestInfo: Unable to get printer attributes.");
return (NULL);
}
/*
* Allocate a cups_dinfo_t structure and return it...
*/
if ((dinfo = calloc(1, sizeof(cups_dinfo_t))) == NULL)
{
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(errno), 0);
ippDelete(response);
return (NULL);
}
DEBUG_printf(("1cupsCopyDestInfo: version=%d, uri=\"%s\", resource=\"%s\".", version, uri, resource));
dinfo->version = version;
dinfo->uri = uri;
dinfo->resource = _cupsStrAlloc(resource);
dinfo->attrs = response;
return (dinfo);
}
/*
* 'cupsFindDestDefault()' - Find the default value(s) for the given option.
*
* The returned value is an IPP attribute. Use the @code ippGetBoolean@,
* @code ippGetCollection@, @code ippGetCount@, @code ippGetDate@,
* @code ippGetInteger@, @code ippGetOctetString@, @code ippGetRange@,
* @code ippGetResolution@, @code ippGetString@, and @code ippGetValueTag@
* functions to inspect the default value(s) as needed.
*
* @since CUPS 1.7/macOS 10.9@
*/
ipp_attribute_t * /* O - Default attribute or @code NULL@ for none */
cupsFindDestDefault(
http_t *http, /* I - Connection to destination */
cups_dest_t *dest, /* I - Destination */
cups_dinfo_t *dinfo, /* I - Destination information */
const char *option) /* I - Option/attribute name */
{
char name[IPP_MAX_NAME]; /* Attribute name */
/*
* Get the default connection as needed...
*/
if (!http)
http = _cupsConnect();
/*
* Range check input...
*/
if (!http || !dest || !dinfo || !option)
{
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
return (NULL);
}
/*
* Find and return the attribute...
*/
snprintf(name, sizeof(name), "%s-default", option);
return (ippFindAttribute(dinfo->attrs, name, IPP_TAG_ZERO));
}
/*
* 'cupsFindDestReady()' - Find the default value(s) for the given option.
*
* The returned value is an IPP attribute. Use the @code ippGetBoolean@,
* @code ippGetCollection@, @code ippGetCount@, @code ippGetDate@,
* @code ippGetInteger@, @code ippGetOctetString@, @code ippGetRange@,
* @code ippGetResolution@, @code ippGetString@, and @code ippGetValueTag@
* functions to inspect the default value(s) as needed.
*
* @since CUPS 1.7/macOS 10.9@
*/
ipp_attribute_t * /* O - Default attribute or @code NULL@ for none */
cupsFindDestReady(
http_t *http, /* I - Connection to destination */
cups_dest_t *dest, /* I - Destination */
cups_dinfo_t *dinfo, /* I - Destination information */
const char *option) /* I - Option/attribute name */
{
char name[IPP_MAX_NAME]; /* Attribute name */
/*
* Get the default connection as needed...
*/
if (!http)
http = _cupsConnect();
/*
* Range check input...
*/
if (!http || !dest || !dinfo || !option)
{
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
return (NULL);
}
/*
* Find and return the attribute...
*/
cups_update_ready(http, dinfo);
snprintf(name, sizeof(name), "%s-ready", option);
return (ippFindAttribute(dinfo->ready_attrs, name, IPP_TAG_ZERO));
}
/*
* 'cupsFindDestSupported()' - Find the default value(s) for the given option.
*
* The returned value is an IPP attribute. Use the @code ippGetBoolean@,
* @code ippGetCollection@, @code ippGetCount@, @code ippGetDate@,
* @code ippGetInteger@, @code ippGetOctetString@, @code ippGetRange@,
* @code ippGetResolution@, @code ippGetString@, and @code ippGetValueTag@
* functions to inspect the default value(s) as needed.
*
* @since CUPS 1.7/macOS 10.9@
*/
ipp_attribute_t * /* O - Default attribute or @code NULL@ for none */
cupsFindDestSupported(
http_t *http, /* I - Connection to destination */
cups_dest_t *dest, /* I - Destination */
cups_dinfo_t *dinfo, /* I - Destination information */
const char *option) /* I - Option/attribute name */
{
char name[IPP_MAX_NAME]; /* Attribute name */
/*
* Get the default connection as needed...
*/
if (!http)
http = _cupsConnect();
/*
* Range check input...
*/
if (!http || !dest || !dinfo || !option)
{
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
return (NULL);
}
/*
* Find and return the attribute...
*/
snprintf(name, sizeof(name), "%s-supported", option);
return (ippFindAttribute(dinfo->attrs, name, IPP_TAG_ZERO));
}
/*
* 'cupsFreeDestInfo()' - Free destination information obtained using
* @link cupsCopyDestInfo@.
*
* @since CUPS 1.6/macOS 10.8@
*/
void
cupsFreeDestInfo(cups_dinfo_t *dinfo) /* I - Destination information */
{
/*
* Range check input...
*/
if (!dinfo)
return;
/*
* Free memory and return...
*/
_cupsStrFree(dinfo->resource);
cupsArrayDelete(dinfo->constraints);
cupsArrayDelete(dinfo->resolvers);
cupsArrayDelete(dinfo->localizations);
cupsArrayDelete(dinfo->media_db);
cupsArrayDelete(dinfo->cached_db);
ippDelete(dinfo->ready_attrs);
cupsArrayDelete(dinfo->ready_db);
ippDelete(dinfo->attrs);
free(dinfo);
}
/*
* 'cupsGetDestMediaByIndex()' - Get a media name, dimension, and margins for a
* specific size.
*
* The @code flags@ parameter determines which set of media are indexed. For
* example, passing @code CUPS_MEDIA_FLAGS_BORDERLESS@ will get the Nth
* borderless size supported by the printer.
*
* @since CUPS 1.7/macOS 10.9@
*/
int /* O - 1 on success, 0 on failure */
cupsGetDestMediaByIndex(
http_t *http, /* I - Connection to destination */
cups_dest_t *dest, /* I - Destination */
cups_dinfo_t *dinfo, /* I - Destination information */
int n, /* I - Media size number (0-based) */
unsigned flags, /* I - Media flags */
cups_size_t *size) /* O - Media size information */
{
_cups_media_db_t *nsize; /* Size for N */
pwg_media_t *pwg; /* PWG media name for size */
/*
* Get the default connection as needed...
*/
if (!http)
http = _cupsConnect();
/*
* Range check input...
*/
if (size)
memset(size, 0, sizeof(cups_size_t));
if (!http || !dest || !dinfo || n < 0 || !size)
{
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
return (0);
}
/*
* Load media list as needed...
*/
if (flags & CUPS_MEDIA_FLAGS_READY)
cups_update_ready(http, dinfo);
if (!dinfo->cached_db || dinfo->cached_flags != flags)
cups_create_cached(http, dinfo, flags);
/*
* Copy the size over and return...
*/
if ((nsize = (_cups_media_db_t *)cupsArrayIndex(dinfo->cached_db, n)) == NULL)
{
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
return (0);
}
if (nsize->key)
strlcpy(size->media, nsize->key, sizeof(size->media));
else if (nsize->size_name)
strlcpy(size->media, nsize->size_name, sizeof(size->media));
else if ((pwg = pwgMediaForSize(nsize->width, nsize->length)) != NULL)
strlcpy(size->media, pwg->pwg, sizeof(size->media));
else
{
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
return (0);
}
size->width = nsize->width;
size->length = nsize->length;
size->bottom = nsize->bottom;
size->left = nsize->left;
size->right = nsize->right;
size->top = nsize->top;
return (1);
}
/*
* 'cupsGetDestMediaByName()' - Get media names, dimensions, and margins.
*
* The "media" string is a PWG media name. "Flags" provides some matching
* guidance (multiple flags can be combined):
*
* CUPS_MEDIA_FLAGS_DEFAULT = find the closest size supported by the printer,
* CUPS_MEDIA_FLAGS_BORDERLESS = find a borderless size,
* CUPS_MEDIA_FLAGS_DUPLEX = find a size compatible with 2-sided printing,
* CUPS_MEDIA_FLAGS_EXACT = find an exact match for the size, and
* CUPS_MEDIA_FLAGS_READY = if the printer supports media sensing, find the
* size amongst the "ready" media.
*
* The matching result (if any) is returned in the "cups_size_t" structure.
*
* Returns 1 when there is a match and 0 if there is not a match.
*
* @since CUPS 1.6/macOS 10.8@
*/
int /* O - 1 on match, 0 on failure */
cupsGetDestMediaByName(
http_t *http, /* I - Connection to destination */
cups_dest_t *dest, /* I - Destination */
cups_dinfo_t *dinfo, /* I - Destination information */
const char *media, /* I - Media name */
unsigned flags, /* I - Media matching flags */
cups_size_t *size) /* O - Media size information */
{
pwg_media_t *pwg; /* PWG media info */
/*
* Get the default connection as needed...
*/
if (!http)
http = _cupsConnect();
/*
* Range check input...
*/
if (size)
memset(size, 0, sizeof(cups_size_t));
if (!http || !dest || !dinfo || !media || !size)
{
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
return (0);
}
/*
* Lookup the media size name...
*/
if ((pwg = pwgMediaForPWG(media)) == NULL)
if ((pwg = pwgMediaForLegacy(media)) == NULL)
{
DEBUG_printf(("1cupsGetDestMediaByName: Unknown size '%s'.", media));
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unknown media size name."), 1);
return (0);
}
/*
* Lookup the size...
*/
return (cups_get_media_db(http, dinfo, pwg, flags, size));
}
/*
* 'cupsGetDestMediaBySize()' - Get media names, dimensions, and margins.
*
* "Width" and "length" are the dimensions in hundredths of millimeters.
* "Flags" provides some matching guidance (multiple flags can be combined):
*
* CUPS_MEDIA_FLAGS_DEFAULT = find the closest size supported by the printer,
* CUPS_MEDIA_FLAGS_BORDERLESS = find a borderless size,
* CUPS_MEDIA_FLAGS_DUPLEX = find a size compatible with 2-sided printing,
* CUPS_MEDIA_FLAGS_EXACT = find an exact match for the size, and
* CUPS_MEDIA_FLAGS_READY = if the printer supports media sensing, find the
* size amongst the "ready" media.
*
* The matching result (if any) is returned in the "cups_size_t" structure.
*
* Returns 1 when there is a match and 0 if there is not a match.
*
* @since CUPS 1.6/macOS 10.8@
*/
int /* O - 1 on match, 0 on failure */
cupsGetDestMediaBySize(
http_t *http, /* I - Connection to destination */
cups_dest_t *dest, /* I - Destination */
cups_dinfo_t *dinfo, /* I - Destination information */
int width, /* I - Media width in hundredths of
* of millimeters */
int length, /* I - Media length in hundredths of
* of millimeters */
unsigned flags, /* I - Media matching flags */
cups_size_t *size) /* O - Media size information */
{
pwg_media_t *pwg; /* PWG media info */
/*
* Get the default connection as needed...
*/
if (!http)
http = _cupsConnect();
/*
* Range check input...
*/
if (size)
memset(size, 0, sizeof(cups_size_t));
if (!http || !dest || !dinfo || width <= 0 || length <= 0 || !size)
{
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
return (0);
}
/*
* Lookup the media size name...
*/
if ((pwg = pwgMediaForSize(width, length)) == NULL)
{
DEBUG_printf(("1cupsGetDestMediaBySize: Invalid size %dx%d.", width,
length));
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Invalid media size."), 1);
return (0);
}
/*
* Lookup the size...
*/
return (cups_get_media_db(http, dinfo, pwg, flags, size));
}
/*
* 'cupsGetDestMediaCount()' - Get the number of sizes supported by a
* destination.
*
* The @code flags@ parameter determines the set of media sizes that are
* counted. For example, passing @code CUPS_MEDIA_FLAGS_BORDERLESS@ will return
* the number of borderless sizes.
*
* @since CUPS 1.7/macOS 10.9@
*/
int /* O - Number of sizes */
cupsGetDestMediaCount(
http_t *http, /* I - Connection to destination */
cups_dest_t *dest, /* I - Destination */
cups_dinfo_t *dinfo, /* I - Destination information */
unsigned flags) /* I - Media flags */
{
/*
* Get the default connection as needed...
*/
if (!http)
http = _cupsConnect();
/*
* Range check input...
*/
if (!http || !dest || !dinfo)
{
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
return (0);
}
/*
* Load media list as needed...
*/
if (flags & CUPS_MEDIA_FLAGS_READY)
cups_update_ready(http, dinfo);
if (!dinfo->cached_db || dinfo->cached_flags != flags)
cups_create_cached(http, dinfo, flags);
return (cupsArrayCount(dinfo->cached_db));
}
/*
* 'cupsGetDestMediaDefault()' - Get the default size for a destination.
*
* The @code flags@ parameter determines which default size is returned. For
* example, passing @code CUPS_MEDIA_FLAGS_BORDERLESS@ will return the default
* borderless size, typically US Letter or A4, but sometimes 4x6 photo media.
*
* @since CUPS 1.7/macOS 10.9@
*/
int /* O - 1 on success, 0 on failure */
cupsGetDestMediaDefault(
http_t *http, /* I - Connection to destination */
cups_dest_t *dest, /* I - Destination */
cups_dinfo_t *dinfo, /* I - Destination information */
unsigned flags, /* I - Media flags */
cups_size_t *size) /* O - Media size information */
{
const char *media; /* Default media size */
/*
* Get the default connection as needed...
*/
if (!http)
http = _cupsConnect();
/*
* Range check input...
*/
if (size)
memset(size, 0, sizeof(cups_size_t));
if (!http || !dest || !dinfo || !size)
{
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
return (0);
}
/*
* Get the default media size, if any...
*/
if ((media = cupsGetOption("media", dest->num_options, dest->options)) == NULL)
media = "na_letter_8.5x11in";
if (cupsGetDestMediaByName(http, dest, dinfo, media, flags, size))
return (1);
if (strcmp(media, "na_letter_8.5x11in") && cupsGetDestMediaByName(http, dest, dinfo, "iso_a4_210x297mm", flags, size))
return (1);
if (strcmp(media, "iso_a4_210x297mm") && cupsGetDestMediaByName(http, dest, dinfo, "na_letter_8.5x11in", flags, size))
return (1);
if ((flags & CUPS_MEDIA_FLAGS_BORDERLESS) && cupsGetDestMediaByName(http, dest, dinfo, "na_index_4x6in", flags, size))
return (1);
/*
* Fall back to the first matching media size...
*/
return (cupsGetDestMediaByIndex(http, dest, dinfo, 0, flags, size));
}
/*
* 'cups_add_dconstres()' - Add a constraint or resolver to an array.
*/
static void
cups_add_dconstres(
cups_array_t *a, /* I - Array */
ipp_t *collection) /* I - Collection value */
{
ipp_attribute_t *attr; /* Attribute */
_cups_dconstres_t *temp; /* Current constraint/resolver */
if ((attr = ippFindAttribute(collection, "resolver-name",
IPP_TAG_NAME)) == NULL)
return;
if ((temp = calloc(1, sizeof(_cups_dconstres_t))) == NULL)
return;
temp->name = attr->values[0].string.text;
temp->collection = collection;
cupsArrayAdd(a, temp);
}
/*
* 'cups_collection_contains()' - Check whether test collection is contained in the matching collection.
*/
static int /* O - 1 on a match, 0 on a non-match */
cups_collection_contains(ipp_t *test, /* I - Collection to test */
ipp_t *match) /* I - Matching values */
{
int i, j, /* Looping vars */
mcount, /* Number of match values */
tcount; /* Number of test values */
ipp_attribute_t *tattr, /* Testing attribute */
*mattr; /* Matching attribute */
const char *tval; /* Testing string value */
for (mattr = ippFirstAttribute(match); mattr; mattr = ippNextAttribute(match))
{
if ((tattr = ippFindAttribute(test, ippGetName(mattr), IPP_TAG_ZERO)) == NULL)
return (0);
tcount = ippGetCount(tattr);
switch (ippGetValueTag(mattr))
{
case IPP_TAG_INTEGER :
case IPP_TAG_ENUM :
if (ippGetValueTag(tattr) != ippGetValueTag(mattr))
return (0);
for (i = 0; i < tcount; i ++)
{
if (!ippContainsInteger(mattr, ippGetInteger(tattr, i)))
return (0);
}
break;
case IPP_TAG_RANGE :
if (ippGetValueTag(tattr) != IPP_TAG_INTEGER)
return (0);
for (i = 0; i < tcount; i ++)
{
if (!ippContainsInteger(mattr, ippGetInteger(tattr, i)))
return (0);
}
break;
case IPP_TAG_BOOLEAN :
if (ippGetValueTag(tattr) != IPP_TAG_BOOLEAN || ippGetBoolean(tattr, 0) != ippGetBoolean(mattr, 0))
return (0);
break;
case IPP_TAG_TEXTLANG :
case IPP_TAG_NAMELANG :
case IPP_TAG_TEXT :
case IPP_TAG_NAME :
case IPP_TAG_KEYWORD :
case IPP_TAG_URI :
case IPP_TAG_URISCHEME :
case IPP_TAG_CHARSET :
case IPP_TAG_LANGUAGE :
case IPP_TAG_MIMETYPE :
for (i = 0; i < tcount; i ++)
{
if ((tval = ippGetString(tattr, i, NULL)) == NULL || !ippContainsString(mattr, tval))
return (0);
}
break;
case IPP_TAG_BEGIN_COLLECTION :
for (i = 0; i < tcount; i ++)
{
ipp_t *tcol = ippGetCollection(tattr, i);
/* Testing collection */
for (j = 0, mcount = ippGetCount(mattr); j < mcount; j ++)
if (!cups_collection_contains(tcol, ippGetCollection(mattr, j)))
return (0);
}
break;
default :
return (0);
}
}
return (1);
}
/*
* 'cups_collection_string()' - Convert an IPP collection to an option string.
*/
static size_t /* O - Number of bytes needed */
cups_collection_string(
ipp_attribute_t *attr, /* I - Collection attribute */
char *buffer, /* I - String buffer */
size_t bufsize) /* I - Size of buffer */
{
int i, j, /* Looping vars */
count, /* Number of collection values */
mcount; /* Number of member values */
ipp_t *col; /* Collection */
ipp_attribute_t *first, /* First member attribute */
*member; /* Member attribute */
char *bufptr, /* Pointer into buffer */
*bufend, /* End of buffer */
temp[100]; /* Temporary string */
const char *mptr; /* Pointer into member value */
int mlen; /* Length of octetString */
bufptr = buffer;
bufend = buffer + bufsize - 1;
for (i = 0, count = ippGetCount(attr); i < count; i ++)
{
col = ippGetCollection(attr, i);
if (i)
{
if (bufptr < bufend)
*bufptr++ = ',';
else
bufptr ++;
}
if (bufptr < bufend)
*bufptr++ = '{';
else
bufptr ++;
for (member = first = ippFirstAttribute(col); member; member = ippNextAttribute(col))
{
const char *mname = ippGetName(member);
if (member != first)
{
if (bufptr < bufend)
*bufptr++ = ' ';
else
bufptr ++;
}
if (ippGetValueTag(member) == IPP_TAG_BOOLEAN)
{
if (!ippGetBoolean(member, 0))
{
if (bufptr < bufend)
strlcpy(bufptr, "no", (size_t)(bufend - bufptr + 1));
bufptr += 2;
}
if (bufptr < bufend)
strlcpy(bufptr, mname, (size_t)(bufend - bufptr + 1));
bufptr += strlen(mname);
continue;
}
if (bufptr < bufend)
strlcpy(bufptr, mname, (size_t)(bufend - bufptr + 1));
bufptr += strlen(mname);
if (bufptr < bufend)
*bufptr++ = '=';
else
bufptr ++;
if (ippGetValueTag(member) == IPP_TAG_BEGIN_COLLECTION)
{
/*
* Convert sub-collection...
*/
bufptr += cups_collection_string(member, bufptr, bufptr < bufend ? (size_t)(bufend - bufptr + 1) : 0);
}
else
{
/*
* Convert simple type...
*/
for (j = 0, mcount = ippGetCount(member); j < mcount; j ++)
{
if (j)
{
if (bufptr < bufend)
*bufptr++ = ',';
else
bufptr ++;
}
switch (ippGetValueTag(member))
{
case IPP_TAG_INTEGER :
case IPP_TAG_ENUM :
bufptr += snprintf(bufptr, bufptr < bufend ? (size_t)(bufend - bufptr + 1) : 0, "%d", ippGetInteger(member, j));
break;
case IPP_TAG_STRING :
if (bufptr < bufend)
*bufptr++ = '\"';
else
bufptr ++;
for (mptr = (const char *)ippGetOctetString(member, j, &mlen); mlen > 0; mlen --, mptr ++)
{
if (*mptr == '\"' || *mptr == '\\')
{
if (bufptr < bufend)
*bufptr++ = '\\';
else
bufptr ++;
}
if (bufptr < bufend)
*bufptr++ = *mptr;
else
bufptr ++;
}
if (bufptr < bufend)
*bufptr++ = '\"';
else
bufptr ++;
break;
case IPP_TAG_DATE :
{
unsigned year; /* Year */
const ipp_uchar_t *date = ippGetDate(member, j);
/* Date value */
year = ((unsigned)date[0] << 8) + (unsigned)date[1];
if (date[9] == 0 && date[10] == 0)
snprintf(temp, sizeof(temp), "%04u-%02u-%02uT%02u:%02u:%02uZ", year, date[2], date[3], date[4], date[5], date[6]);
else
snprintf(temp, sizeof(temp), "%04u-%02u-%02uT%02u:%02u:%02u%c%02u%02u", year, date[2], date[3], date[4], date[5], date[6], date[8], date[9], date[10]);
if (bufptr < bufend)
strlcpy(bufptr, temp, (size_t)(bufend - bufptr + 1));
bufptr += strlen(temp);
}
break;
case IPP_TAG_RESOLUTION :
{
int xres, /* Horizontal resolution */
yres; /* Vertical resolution */
ipp_res_t units; /* Resolution units */
xres = ippGetResolution(member, j, &yres, &units);
if (xres == yres)
snprintf(temp, sizeof(temp), "%d%s", xres, units == IPP_RES_PER_INCH ? "dpi" : "dpcm");
else
snprintf(temp, sizeof(temp), "%dx%d%s", xres, yres, units == IPP_RES_PER_INCH ? "dpi" : "dpcm");
if (bufptr < bufend)
strlcpy(bufptr, temp, (size_t)(bufend - bufptr + 1));
bufptr += strlen(temp);
}
break;
case IPP_TAG_RANGE :
{
int lower, /* Lower bound */
upper; /* Upper bound */
lower = ippGetRange(member, j, &upper);
snprintf(temp, sizeof(temp), "%d-%d", lower, upper);
if (bufptr < bufend)
strlcpy(bufptr, temp, (size_t)(bufend - bufptr + 1));
bufptr += strlen(temp);
}
break;
case IPP_TAG_TEXTLANG :
case IPP_TAG_NAMELANG :
case IPP_TAG_TEXT :
case IPP_TAG_NAME :
case IPP_TAG_KEYWORD :
case IPP_TAG_URI :
case IPP_TAG_URISCHEME :
case IPP_TAG_CHARSET :
case IPP_TAG_LANGUAGE :
case IPP_TAG_MIMETYPE :
if (bufptr < bufend)
*bufptr++ = '\"';
else
bufptr ++;
for (mptr = ippGetString(member, j, NULL); *mptr; mptr ++)
{
if (*mptr == '\"' || *mptr == '\\')
{
if (bufptr < bufend)
*bufptr++ = '\\';
else
bufptr ++;
}
if (bufptr < bufend)
*bufptr++ = *mptr;
else
bufptr ++;
}
if (bufptr < bufend)
*bufptr++ = '\"';
else
bufptr ++;
break;
default :
break;
}
}
}
}
if (bufptr < bufend)
*bufptr++ = '}';
else
bufptr ++;
}
*bufptr = '\0';
return ((size_t)(bufptr - buffer + 1));
}
/*
* 'cups_compare_dconstres()' - Compare to resolver entries.
*/
static int /* O - Result of comparison */
cups_compare_dconstres(
_cups_dconstres_t *a, /* I - First resolver */
_cups_dconstres_t *b) /* I - Second resolver */
{
return (strcmp(a->name, b->name));
}
/*
* 'cups_compare_media_db()' - Compare two media entries.
*/
static int /* O - Result of comparison */
cups_compare_media_db(
_cups_media_db_t *a, /* I - First media entries */
_cups_media_db_t *b) /* I - Second media entries */
{
int result; /* Result of comparison */
if ((result = a->width - b->width) == 0)
result = a->length - b->length;
return (result);
}
/*
* 'cups_copy_media_db()' - Copy a media entry.
*/
static _cups_media_db_t * /* O - New media entry */
cups_copy_media_db(
_cups_media_db_t *mdb) /* I - Media entry to copy */
{
_cups_media_db_t *temp; /* New media entry */
if ((temp = calloc(1, sizeof(_cups_media_db_t))) == NULL)
return (NULL);
if (mdb->color)
temp->color = _cupsStrAlloc(mdb->color);
if (mdb->key)
temp->key = _cupsStrAlloc(mdb->key);
if (mdb->info)
temp->info = _cupsStrAlloc(mdb->info);
if (mdb->size_name)
temp->size_name = _cupsStrAlloc(mdb->size_name);
if (mdb->source)
temp->source = _cupsStrAlloc(mdb->source);
if (mdb->type)
temp->type = _cupsStrAlloc(mdb->type);
temp->width = mdb->width;
temp->length = mdb->length;
temp->bottom = mdb->bottom;
temp->left = mdb->left;
temp->right = mdb->right;
temp->top = mdb->top;
return (temp);
}
/*
* 'cups_create_cached()' - Create the media selection cache.
*/
static void
cups_create_cached(http_t *http, /* I - Connection to destination */
cups_dinfo_t *dinfo, /* I - Destination information */
unsigned flags) /* I - Media selection flags */
{
cups_array_t *db; /* Media database array to use */
_cups_media_db_t *mdb, /* Media database entry */
*first; /* First entry this size */
DEBUG_printf(("3cups_create_cached(http=%p, dinfo=%p, flags=%u)", (void *)http, (void *)dinfo, flags));
if (dinfo->cached_db)
cupsArrayDelete(dinfo->cached_db);
dinfo->cached_db = cupsArrayNew(NULL, NULL);
dinfo->cached_flags = flags;
if (flags & CUPS_MEDIA_FLAGS_READY)
{
DEBUG_puts("4cups_create_cached: ready media");
cups_update_ready(http, dinfo);
db = dinfo->ready_db;
}
else
{
DEBUG_puts("4cups_create_cached: supported media");
if (!dinfo->media_db)
cups_create_media_db(dinfo, CUPS_MEDIA_FLAGS_DEFAULT);
db = dinfo->media_db;
}
for (mdb = (_cups_media_db_t *)cupsArrayFirst(db), first = mdb;
mdb;
mdb = (_cups_media_db_t *)cupsArrayNext(db))
{
DEBUG_printf(("4cups_create_cached: %p key=\"%s\", type=\"%s\", %dx%d, B%d L%d R%d T%d", (void *)mdb, mdb->key, mdb->type, mdb->width, mdb->length, mdb->bottom, mdb->left, mdb->right, mdb->top));
if (flags & CUPS_MEDIA_FLAGS_BORDERLESS)
{
if (!mdb->left && !mdb->right && !mdb->top && !mdb->bottom)
{
DEBUG_printf(("4cups_create_cached: add %p", (void *)mdb));
cupsArrayAdd(dinfo->cached_db, mdb);
}
}
else if (flags & CUPS_MEDIA_FLAGS_DUPLEX)
{
if (first->width != mdb->width || first->length != mdb->length)
{
DEBUG_printf(("4cups_create_cached: add %p", (void *)first));
cupsArrayAdd(dinfo->cached_db, first);
first = mdb;
}
else if (mdb->left >= first->left && mdb->right >= first->right && mdb->top >= first->top && mdb->bottom >= first->bottom &&
(mdb->left != first->left || mdb->right != first->right || mdb->top != first->top || mdb->bottom != first->bottom))
first = mdb;
}
else
{
DEBUG_printf(("4cups_create_cached: add %p", (void *)mdb));
cupsArrayAdd(dinfo->cached_db, mdb);
}
}
if (flags & CUPS_MEDIA_FLAGS_DUPLEX)
{
DEBUG_printf(("4cups_create_cached: add %p", (void *)first));
cupsArrayAdd(dinfo->cached_db, first);
}
}
/*
* 'cups_create_constraints()' - Create the constraints and resolvers arrays.
*/
static void
cups_create_constraints(
cups_dinfo_t *dinfo) /* I - Destination information */
{
int i; /* Looping var */
ipp_attribute_t *attr; /* Attribute */
_ipp_value_t *val; /* Current value */
dinfo->constraints = cupsArrayNew3(NULL, NULL, NULL, 0, NULL,
(cups_afree_func_t)free);
dinfo->resolvers = cupsArrayNew3((cups_array_func_t)cups_compare_dconstres,
NULL, NULL, 0, NULL,
(cups_afree_func_t)free);
if ((attr = ippFindAttribute(dinfo->attrs, "job-constraints-supported",
IPP_TAG_BEGIN_COLLECTION)) != NULL)
{
for (i = attr->num_values, val = attr->values; i > 0; i --, val ++)
cups_add_dconstres(dinfo->constraints, val->collection);
}
if ((attr = ippFindAttribute(dinfo->attrs, "job-resolvers-supported",
IPP_TAG_BEGIN_COLLECTION)) != NULL)
{
for (i = attr->num_values, val = attr->values; i > 0; i --, val ++)
cups_add_dconstres(dinfo->resolvers, val->collection);
}
}
/*
* 'cups_create_defaults()' - Create the -default option array.
*/
static void
cups_create_defaults(
cups_dinfo_t *dinfo) /* I - Destination information */
{
ipp_attribute_t *attr; /* Current attribute */
char name[IPP_MAX_NAME + 1],
/* Current name */
*nameptr, /* Pointer into current name */
value[2048]; /* Current value */
/*
* Iterate through the printer attributes looking for xxx-default and adding
* xxx=value to the defaults option array.
*/
for (attr = ippFirstAttribute(dinfo->attrs); attr; attr = ippNextAttribute(dinfo->attrs))
{
if (!ippGetName(attr) || ippGetGroupTag(attr) != IPP_TAG_PRINTER)
continue;
strlcpy(name, ippGetName(attr), sizeof(name));
if ((nameptr = name + strlen(name) - 8) <= name || strcmp(nameptr, "-default"))
continue;
*nameptr = '\0';
if (ippGetValueTag(attr) == IPP_TAG_BEGIN_COLLECTION)
{
if (cups_collection_string(attr, value, sizeof(value)) >= sizeof(value))
continue;
}
else if (ippAttributeString(attr, value, sizeof(value)) >= sizeof(value))
continue;
dinfo->num_defaults = cupsAddOption(name, value, dinfo->num_defaults, &dinfo->defaults);
}
}
/*
* 'cups_create_media_db()' - Create the media database.
*/
static void
cups_create_media_db(
cups_dinfo_t *dinfo, /* I - Destination information */
unsigned flags) /* I - Media flags */
{
int i; /* Looping var */
_ipp_value_t *val; /* Current value */
ipp_attribute_t *media_col_db, /* media-col-database */
*media_attr, /* media-xxx */
*x_dimension, /* x-dimension */
*y_dimension; /* y-dimension */
pwg_media_t *pwg; /* PWG media info */
cups_array_t *db; /* New media database array */
_cups_media_db_t mdb; /* Media entry */
char media_key[256]; /* Synthesized media-key value */
db = cupsArrayNew3((cups_array_func_t)cups_compare_media_db,
NULL, NULL, 0,
(cups_acopy_func_t)cups_copy_media_db,
(cups_afree_func_t)cups_free_media_db);
if (flags == CUPS_MEDIA_FLAGS_READY)
{
dinfo->ready_db = db;
media_col_db = ippFindAttribute(dinfo->ready_attrs, "media-col-ready",
IPP_TAG_BEGIN_COLLECTION);
media_attr = ippFindAttribute(dinfo->ready_attrs, "media-ready",
IPP_TAG_ZERO);
}
else
{
dinfo->media_db = db;
dinfo->min_size.width = INT_MAX;
dinfo->min_size.length = INT_MAX;
dinfo->max_size.width = 0;
dinfo->max_size.length = 0;
media_col_db = ippFindAttribute(dinfo->attrs, "media-col-database",
IPP_TAG_BEGIN_COLLECTION);
media_attr = ippFindAttribute(dinfo->attrs, "media-supported",
IPP_TAG_ZERO);
}
if (media_col_db)
{
_ipp_value_t *custom = NULL; /* Custom size range value */
for (i = media_col_db->num_values, val = media_col_db->values;
i > 0;
i --, val ++)
{
memset(&mdb, 0, sizeof(mdb));
if ((media_attr = ippFindAttribute(val->collection, "media-size",
IPP_TAG_BEGIN_COLLECTION)) != NULL)
{
ipp_t *media_size = media_attr->values[0].collection;
/* media-size collection value */
if ((x_dimension = ippFindAttribute(media_size, "x-dimension",
IPP_TAG_INTEGER)) != NULL &&
(y_dimension = ippFindAttribute(media_size, "y-dimension",
IPP_TAG_INTEGER)) != NULL)
{
/*
* Fixed size...
*/
mdb.width = x_dimension->values[0].integer;
mdb.length = y_dimension->values[0].integer;
}
else if ((x_dimension = ippFindAttribute(media_size, "x-dimension",
IPP_TAG_INTEGER)) != NULL &&
(y_dimension = ippFindAttribute(media_size, "y-dimension",
IPP_TAG_RANGE)) != NULL)
{
/*
* Roll limits...
*/
mdb.width = x_dimension->values[0].integer;
mdb.length = y_dimension->values[0].range.upper;
}
else if (flags != CUPS_MEDIA_FLAGS_READY &&
(x_dimension = ippFindAttribute(media_size, "x-dimension",
IPP_TAG_RANGE)) != NULL &&
(y_dimension = ippFindAttribute(media_size, "y-dimension",
IPP_TAG_RANGE)) != NULL)
{
/*
* Custom size range; save this as the custom size value with default
* margins, then continue; we'll capture the real margins below...
*/
custom = val;
dinfo->min_size.width = x_dimension->values[0].range.lower;
dinfo->min_size.length = y_dimension->values[0].range.lower;
dinfo->min_size.left =
dinfo->min_size.right = 635; /* Default 1/4" side margins */
dinfo->min_size.top =
dinfo->min_size.bottom = 1270; /* Default 1/2" top/bottom margins */
dinfo->max_size.width = x_dimension->values[0].range.upper;
dinfo->max_size.length = y_dimension->values[0].range.upper;
dinfo->max_size.left =
dinfo->max_size.right = 635; /* Default 1/4" side margins */
dinfo->max_size.top =
dinfo->max_size.bottom = 1270; /* Default 1/2" top/bottom margins */
continue;
}
}
if ((media_attr = ippFindAttribute(val->collection, "media-color", IPP_TAG_ZERO)) != NULL && (media_attr->value_tag == IPP_TAG_NAME || media_attr->value_tag == IPP_TAG_NAMELANG || media_attr->value_tag == IPP_TAG_KEYWORD))
mdb.color = media_attr->values[0].string.text;
if ((media_attr = ippFindAttribute(val->collection, "media-info", IPP_TAG_TEXT)) != NULL)
mdb.info = media_attr->values[0].string.text;
if ((media_attr = ippFindAttribute(val->collection, "media-key", IPP_TAG_ZERO)) != NULL && (media_attr->value_tag == IPP_TAG_NAME || media_attr->value_tag == IPP_TAG_NAMELANG || media_attr->value_tag == IPP_TAG_KEYWORD))
mdb.key = media_attr->values[0].string.text;
if ((media_attr = ippFindAttribute(val->collection, "media-size-name", IPP_TAG_ZERO)) != NULL && (media_attr->value_tag == IPP_TAG_NAME || media_attr->value_tag == IPP_TAG_NAMELANG || media_attr->value_tag == IPP_TAG_KEYWORD))
mdb.size_name = media_attr->values[0].string.text;
if ((media_attr = ippFindAttribute(val->collection, "media-source", IPP_TAG_ZERO)) != NULL && (media_attr->value_tag == IPP_TAG_NAME || media_attr->value_tag == IPP_TAG_NAMELANG || media_attr->value_tag == IPP_TAG_KEYWORD))
mdb.source = media_attr->values[0].string.text;
if ((media_attr = ippFindAttribute(val->collection, "media-type", IPP_TAG_ZERO)) != NULL && (media_attr->value_tag == IPP_TAG_NAME || media_attr->value_tag == IPP_TAG_NAMELANG || media_attr->value_tag == IPP_TAG_KEYWORD))
mdb.type = media_attr->values[0].string.text;
if ((media_attr = ippFindAttribute(val->collection, "media-bottom-margin", IPP_TAG_INTEGER)) != NULL)
mdb.bottom = media_attr->values[0].integer;
if ((media_attr = ippFindAttribute(val->collection, "media-left-margin", IPP_TAG_INTEGER)) != NULL)
mdb.left = media_attr->values[0].integer;
if ((media_attr = ippFindAttribute(val->collection, "media-right-margin", IPP_TAG_INTEGER)) != NULL)
mdb.right = media_attr->values[0].integer;
if ((media_attr = ippFindAttribute(val->collection, "media-top-margin", IPP_TAG_INTEGER)) != NULL)
mdb.top = media_attr->values[0].integer;
if (!mdb.key)
{
if (!mdb.size_name && (pwg = pwgMediaForSize(mdb.width, mdb.length)) != NULL)
mdb.size_name = (char *)pwg->pwg;
if (!mdb.size_name)
{
/*
* Use a CUPS-specific identifier if we don't have a size name...
*/
if (flags & CUPS_MEDIA_FLAGS_READY)
snprintf(media_key, sizeof(media_key), "cups-media-ready-%d", i + 1);
else
snprintf(media_key, sizeof(media_key), "cups-media-%d", i + 1);
}
else if (mdb.source)
{
/*
* Generate key using size name, source, and type (if set)...
*/
if (mdb.type)
snprintf(media_key, sizeof(media_key), "%s_%s_%s", mdb.size_name, mdb.source, mdb.type);
else
snprintf(media_key, sizeof(media_key), "%s_%s", mdb.size_name, mdb.source);
}
else if (mdb.type)
{
/*
* Generate key using size name and type...
*/
snprintf(media_key, sizeof(media_key), "%s_%s", mdb.size_name, mdb.type);
}
else
{
/*
* Key is just the size name...
*/
strlcpy(media_key, mdb.size_name, sizeof(media_key));
}
/*
* Append "_borderless" for borderless media...
*/
if (!mdb.bottom && !mdb.left && !mdb.right && !mdb.top)
strlcat(media_key, "_borderless", sizeof(media_key));
mdb.key = media_key;
}
DEBUG_printf(("1cups_create_media_db: Adding media: key=\"%s\", width=%d, length=%d, source=\"%s\", type=\"%s\".", mdb.key, mdb.width, mdb.length, mdb.source, mdb.type));
cupsArrayAdd(db, &mdb);
}
if (custom)
{
if ((media_attr = ippFindAttribute(custom->collection,
"media-bottom-margin",
IPP_TAG_INTEGER)) != NULL)
{
dinfo->min_size.top =
dinfo->max_size.top = media_attr->values[0].integer;
}
if ((media_attr = ippFindAttribute(custom->collection,
"media-left-margin",
IPP_TAG_INTEGER)) != NULL)
{
dinfo->min_size.left =
dinfo->max_size.left = media_attr->values[0].integer;
}
if ((media_attr = ippFindAttribute(custom->collection,
"media-right-margin",
IPP_TAG_INTEGER)) != NULL)
{
dinfo->min_size.right =
dinfo->max_size.right = media_attr->values[0].integer;
}
if ((media_attr = ippFindAttribute(custom->collection,
"media-top-margin",
IPP_TAG_INTEGER)) != NULL)
{
dinfo->min_size.top =
dinfo->max_size.top = media_attr->values[0].integer;
}
}
}
else if (media_attr &&
(media_attr->value_tag == IPP_TAG_NAME ||
media_attr->value_tag == IPP_TAG_NAMELANG ||
media_attr->value_tag == IPP_TAG_KEYWORD))
{
memset(&mdb, 0, sizeof(mdb));
mdb.left =
mdb.right = 635; /* Default 1/4" side margins */
mdb.top =
mdb.bottom = 1270; /* Default 1/2" top/bottom margins */
for (i = media_attr->num_values, val = media_attr->values;
i > 0;
i --, val ++)
{
if ((pwg = pwgMediaForPWG(val->string.text)) == NULL)
if ((pwg = pwgMediaForLegacy(val->string.text)) == NULL)
{
DEBUG_printf(("3cups_create_media_db: Ignoring unknown size '%s'.",
val->string.text));
continue;
}
mdb.width = pwg->width;
mdb.length = pwg->length;
if (flags != CUPS_MEDIA_FLAGS_READY &&
!strncmp(val->string.text, "custom_min_", 11))
{
mdb.size_name = NULL;
dinfo->min_size = mdb;
}
else if (flags != CUPS_MEDIA_FLAGS_READY &&
!strncmp(val->string.text, "custom_max_", 11))
{
mdb.size_name = NULL;
dinfo->max_size = mdb;
}
else
{
mdb.size_name = val->string.text;
cupsArrayAdd(db, &mdb);
}
}
}
}
/*
* 'cups_free_media_cb()' - Free a media entry.
*/
static void
cups_free_media_db(
_cups_media_db_t *mdb) /* I - Media entry to free */
{
if (mdb->color)
_cupsStrFree(mdb->color);
if (mdb->key)
_cupsStrFree(mdb->key);
if (mdb->info)
_cupsStrFree(mdb->info);
if (mdb->size_name)
_cupsStrFree(mdb->size_name);
if (mdb->source)
_cupsStrFree(mdb->source);
if (mdb->type)
_cupsStrFree(mdb->type);
free(mdb);
}
/*
* 'cups_get_media_db()' - Lookup the media entry for a given size.
*/
static int /* O - 1 on match, 0 on failure */
cups_get_media_db(http_t *http, /* I - Connection to destination */
cups_dinfo_t *dinfo, /* I - Destination information */
pwg_media_t *pwg, /* I - PWG media info */
unsigned flags, /* I - Media matching flags */
cups_size_t *size) /* O - Media size/margin/name info */
{
cups_array_t *db; /* Which media database to query */
_cups_media_db_t *mdb, /* Current media database entry */
*best = NULL, /* Best matching entry */
key; /* Search key */
/*
* Create the media database as needed...
*/
if (flags & CUPS_MEDIA_FLAGS_READY)
{
cups_update_ready(http, dinfo);
db = dinfo->ready_db;
}
else
{
if (!dinfo->media_db)
cups_create_media_db(dinfo, CUPS_MEDIA_FLAGS_DEFAULT);
db = dinfo->media_db;
}
/*
* Find a match...
*/
memset(&key, 0, sizeof(key));
key.width = pwg->width;
key.length = pwg->length;
if ((mdb = cupsArrayFind(db, &key)) != NULL)
{
/*
* Found an exact match, let's figure out the best margins for the flags
* supplied...
*/
best = mdb;
if (flags & CUPS_MEDIA_FLAGS_BORDERLESS)
{
/*
* Look for the smallest margins...
*/
if (best->left != 0 || best->right != 0 || best->top != 0 || best->bottom != 0)
{
for (mdb = (_cups_media_db_t *)cupsArrayNext(db);
mdb && !cups_compare_media_db(mdb, &key);
mdb = (_cups_media_db_t *)cupsArrayNext(db))
{
if (mdb->left <= best->left && mdb->right <= best->right &&
mdb->top <= best->top && mdb->bottom <= best->bottom)
{
best = mdb;
if (mdb->left == 0 && mdb->right == 0 && mdb->bottom == 0 &&
mdb->top == 0)
break;
}
}
}
/*
* If we need an exact match, return no-match if the size is not
* borderless.
*/
if ((flags & CUPS_MEDIA_FLAGS_EXACT) &&
(best->left || best->right || best->top || best->bottom))
return (0);
}
else if (flags & CUPS_MEDIA_FLAGS_DUPLEX)
{
/*
* Look for the largest margins...
*/
for (mdb = (_cups_media_db_t *)cupsArrayNext(db);
mdb && !cups_compare_media_db(mdb, &key);
mdb = (_cups_media_db_t *)cupsArrayNext(db))
{
if (mdb->left >= best->left && mdb->right >= best->right &&
mdb->top >= best->top && mdb->bottom >= best->bottom &&
(mdb->bottom != best->bottom || mdb->left != best->left || mdb->right != best->right || mdb->top != best->top))
best = mdb;
}
}
else
{
/*
* Look for the smallest non-zero margins...
*/
for (mdb = (_cups_media_db_t *)cupsArrayNext(db);
mdb && !cups_compare_media_db(mdb, &key);
mdb = (_cups_media_db_t *)cupsArrayNext(db))
{
if (((mdb->left > 0 && mdb->left <= best->left) || best->left == 0) &&
((mdb->right > 0 && mdb->right <= best->right) || best->right == 0) &&
((mdb->top > 0 && mdb->top <= best->top) || best->top == 0) &&
((mdb->bottom > 0 && mdb->bottom <= best->bottom) || best->bottom == 0) &&
(mdb->bottom != best->bottom || mdb->left != best->left || mdb->right != best->right || mdb->top != best->top))
best = mdb;
}
}
}
else if (flags & CUPS_MEDIA_FLAGS_EXACT)
{
/*
* See if we can do this as a custom size...
*/
if (pwg->width < dinfo->min_size.width ||
pwg->width > dinfo->max_size.width ||
pwg->length < dinfo->min_size.length ||
pwg->length > dinfo->max_size.length)
return (0); /* Out of range */
if ((flags & CUPS_MEDIA_FLAGS_BORDERLESS) &&
(dinfo->min_size.left > 0 || dinfo->min_size.right > 0 ||
dinfo->min_size.top > 0 || dinfo->min_size.bottom > 0))
return (0); /* Not borderless */
key.size_name = (char *)pwg->pwg;
key.bottom = dinfo->min_size.bottom;
key.left = dinfo->min_size.left;
key.right = dinfo->min_size.right;
key.top = dinfo->min_size.top;
best = &key;
}
else if (pwg->width >= dinfo->min_size.width &&
pwg->width <= dinfo->max_size.width &&
pwg->length >= dinfo->min_size.length &&
pwg->length <= dinfo->max_size.length)
{
/*
* Map to custom size...
*/
key.size_name = (char *)pwg->pwg;
key.bottom = dinfo->min_size.bottom;
key.left = dinfo->min_size.left;
key.right = dinfo->min_size.right;
key.top = dinfo->min_size.top;
best = &key;
}
else
{
/*
* Find a close size...
*/
for (mdb = (_cups_media_db_t *)cupsArrayFirst(db);
mdb;
mdb = (_cups_media_db_t *)cupsArrayNext(db))
if (cups_is_close_media_db(mdb, &key))
break;
if (!mdb)
return (0);
best = mdb;
if (flags & CUPS_MEDIA_FLAGS_BORDERLESS)
{
/*
* Look for the smallest margins...
*/
if (best->left != 0 || best->right != 0 || best->top != 0 ||
best->bottom != 0)
{
for (mdb = (_cups_media_db_t *)cupsArrayNext(db);
mdb && cups_is_close_media_db(mdb, &key);
mdb = (_cups_media_db_t *)cupsArrayNext(db))
{
if (mdb->left <= best->left && mdb->right <= best->right &&
mdb->top <= best->top && mdb->bottom <= best->bottom &&
(mdb->bottom != best->bottom || mdb->left != best->left || mdb->right != best->right || mdb->top != best->top))
{
best = mdb;
if (mdb->left == 0 && mdb->right == 0 && mdb->bottom == 0 &&
mdb->top == 0)
break;
}
}
}
}
else if (flags & CUPS_MEDIA_FLAGS_DUPLEX)
{
/*
* Look for the largest margins...
*/
for (mdb = (_cups_media_db_t *)cupsArrayNext(db);
mdb && cups_is_close_media_db(mdb, &key);
mdb = (_cups_media_db_t *)cupsArrayNext(db))
{
if (mdb->left >= best->left && mdb->right >= best->right &&
mdb->top >= best->top && mdb->bottom >= best->bottom &&
(mdb->bottom != best->bottom || mdb->left != best->left || mdb->right != best->right || mdb->top != best->top))
best = mdb;
}
}
else
{
/*
* Look for the smallest non-zero margins...
*/
for (mdb = (_cups_media_db_t *)cupsArrayNext(db);
mdb && cups_is_close_media_db(mdb, &key);
mdb = (_cups_media_db_t *)cupsArrayNext(db))
{
if (((mdb->left > 0 && mdb->left <= best->left) || best->left == 0) &&
((mdb->right > 0 && mdb->right <= best->right) ||
best->right == 0) &&
((mdb->top > 0 && mdb->top <= best->top) || best->top == 0) &&
((mdb->bottom > 0 && mdb->bottom <= best->bottom) ||
best->bottom == 0) &&
(mdb->bottom != best->bottom || mdb->left != best->left || mdb->right != best->right || mdb->top != best->top))
best = mdb;
}
}
}
if (best)
{
/*
* Return the matching size...
*/
if (best->key)
strlcpy(size->media, best->key, sizeof(size->media));
else if (best->size_name)
strlcpy(size->media, best->size_name, sizeof(size->media));
else if (pwg && pwg->pwg)
strlcpy(size->media, pwg->pwg, sizeof(size->media));
else
strlcpy(size->media, "unknown", sizeof(size->media));
size->width = best->width;
size->length = best->length;
size->bottom = best->bottom;
size->left = best->left;
size->right = best->right;
size->top = best->top;
return (1);
}
return (0);
}
/*
* 'cups_is_close_media_db()' - Compare two media entries to see if they are
* close to the same size.
*
* Currently we use 5 points (from PostScript) as the matching range...
*/
static int /* O - 1 if the sizes are close */
cups_is_close_media_db(
_cups_media_db_t *a, /* I - First media entries */
_cups_media_db_t *b) /* I - Second media entries */
{
int dwidth, /* Difference in width */
dlength; /* Difference in length */
dwidth = a->width - b->width;
dlength = a->length - b->length;
return (dwidth >= -176 && dwidth <= 176 &&
dlength >= -176 && dlength <= 176);
}
/*
* 'cups_test_constraints()' - Test constraints.
*/
static cups_array_t * /* O - Active constraints */
cups_test_constraints(
cups_dinfo_t *dinfo, /* I - Destination information */
const char *new_option, /* I - Newly selected option */
const char *new_value, /* I - Newly selected value */
int num_options, /* I - Number of options */
cups_option_t *options, /* I - Options */
int *num_conflicts, /* O - Number of conflicting options */
cups_option_t **conflicts) /* O - Conflicting options */
{
int i, /* Looping var */
count, /* Number of values */
match; /* Value matches? */
int num_matching; /* Number of matching options */
cups_option_t *matching; /* Matching options */
_cups_dconstres_t *c; /* Current constraint */
cups_array_t *active = NULL; /* Active constraints */
ipp_t *col; /* Collection value */
ipp_attribute_t *attr; /* Current attribute */
_ipp_value_t *attrval; /* Current attribute value */
const char *value; /* Current value */
char temp[1024]; /* Temporary string */
int int_value; /* Integer value */
int xres_value, /* Horizontal resolution */
yres_value; /* Vertical resolution */
ipp_res_t units_value; /* Resolution units */
for (c = (_cups_dconstres_t *)cupsArrayFirst(dinfo->constraints);
c;
c = (_cups_dconstres_t *)cupsArrayNext(dinfo->constraints))
{
num_matching = 0;
matching = NULL;
for (attr = ippFirstAttribute(c->collection);
attr;
attr = ippNextAttribute(c->collection))
{
/*
* Get the value for the current attribute in the constraint...
*/
if (new_option && new_value && !strcmp(attr->name, new_option))
value = new_value;
else if ((value = cupsGetOption(attr->name, num_options, options)) == NULL)
value = cupsGetOption(attr->name, dinfo->num_defaults, dinfo->defaults);
if (!value)
{
/*
* Not set so this constraint does not apply...
*/
break;
}
match = 0;
switch (attr->value_tag)
{
case IPP_TAG_INTEGER :
case IPP_TAG_ENUM :
int_value = atoi(value);
for (i = attr->num_values, attrval = attr->values;
i > 0;
i --, attrval ++)
{
if (attrval->integer == int_value)
{
match = 1;
break;
}
}
break;
case IPP_TAG_BOOLEAN :
int_value = !strcmp(value, "true");
for (i = attr->num_values, attrval = attr->values;
i > 0;
i --, attrval ++)
{
if (attrval->boolean == int_value)
{
match = 1;
break;
}
}
break;
case IPP_TAG_RANGE :
int_value = atoi(value);
for (i = attr->num_values, attrval = attr->values;
i > 0;
i --, attrval ++)
{
if (int_value >= attrval->range.lower &&
int_value <= attrval->range.upper)
{
match = 1;
break;
}
}
break;
case IPP_TAG_RESOLUTION :
if (sscanf(value, "%dx%d%15s", &xres_value, &yres_value, temp) != 3)
{
if (sscanf(value, "%d%15s", &xres_value, temp) != 2)
break;
yres_value = xres_value;
}
if (!strcmp(temp, "dpi"))
units_value = IPP_RES_PER_INCH;
else if (!strcmp(temp, "dpc") || !strcmp(temp, "dpcm"))
units_value = IPP_RES_PER_CM;
else
break;
for (i = attr->num_values, attrval = attr->values;
i > 0;
i --, attrval ++)
{
if (attrval->resolution.xres == xres_value &&
attrval->resolution.yres == yres_value &&
attrval->resolution.units == units_value)
{
match = 1;
break;
}
}
break;
case IPP_TAG_TEXT :
case IPP_TAG_NAME :
case IPP_TAG_KEYWORD :
case IPP_TAG_CHARSET :
case IPP_TAG_URI :
case IPP_TAG_URISCHEME :
case IPP_TAG_MIMETYPE :
case IPP_TAG_LANGUAGE :
case IPP_TAG_TEXTLANG :
case IPP_TAG_NAMELANG :
for (i = attr->num_values, attrval = attr->values;
i > 0;
i --, attrval ++)
{
if (!strcmp(attrval->string.text, value))
{
match = 1;
break;
}
}
break;
case IPP_TAG_BEGIN_COLLECTION :
col = ippNew();
_cupsEncodeOption(col, IPP_TAG_ZERO, NULL, ippGetName(attr), value);
for (i = 0, count = ippGetCount(attr); i < count; i ++)
{
if (cups_collection_contains(col, ippGetCollection(attr, i)))
{
match = 1;
break;
}
}
ippDelete(col);
break;
default :
break;
}
if (!match)
break;
num_matching = cupsAddOption(attr->name, value, num_matching, &matching);
}
if (!attr)
{
if (!active)
active = cupsArrayNew(NULL, NULL);
cupsArrayAdd(active, c);
if (num_conflicts && conflicts)
{
cups_option_t *moption; /* Matching option */
for (i = num_matching, moption = matching; i > 0; i --, moption ++)
*num_conflicts = cupsAddOption(moption->name, moption->value, *num_conflicts, conflicts);
}
}
cupsFreeOptions(num_matching, matching);
}
return (active);
}
/*
* 'cups_update_ready()' - Update xxx-ready attributes for the printer.
*/
static void
cups_update_ready(http_t *http, /* I - Connection to destination */
cups_dinfo_t *dinfo) /* I - Destination information */
{
ipp_t *request; /* Get-Printer-Attributes request */
static const char * const pattrs[] = /* Printer attributes we want */
{
"finishings-col-ready",
"finishings-ready",
"job-finishings-col-ready",
"job-finishings-ready",
"media-col-ready",
"media-ready"
};
/*
* Don't update more than once every 30 seconds...
*/
if ((time(NULL) - dinfo->ready_time) < _CUPS_MEDIA_READY_TTL)
return;
/*
* Free any previous results...
*/
if (dinfo->cached_flags & CUPS_MEDIA_FLAGS_READY)
{
cupsArrayDelete(dinfo->cached_db);
dinfo->cached_db = NULL;
dinfo->cached_flags = CUPS_MEDIA_FLAGS_DEFAULT;
}
ippDelete(dinfo->ready_attrs);
dinfo->ready_attrs = NULL;
cupsArrayDelete(dinfo->ready_db);
dinfo->ready_db = NULL;
/*
* Query the xxx-ready values...
*/
request = ippNewRequest(IPP_OP_GET_PRINTER_ATTRIBUTES);
ippSetVersion(request, dinfo->version / 10, dinfo->version % 10);
ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_URI, "printer-uri", NULL,
dinfo->uri);
ippAddString(request, IPP_TAG_OPERATION, IPP_TAG_NAME, "requesting-user-name",
NULL, cupsUser());
ippAddStrings(request, IPP_TAG_OPERATION, IPP_CONST_TAG(IPP_TAG_KEYWORD), "requested-attributes", (int)(sizeof(pattrs) / sizeof(pattrs[0])), NULL, pattrs);
dinfo->ready_attrs = cupsDoRequest(http, request, dinfo->resource);
/*
* Update the ready media database...
*/
cups_create_media_db(dinfo, CUPS_MEDIA_FLAGS_READY);
/*
* Update last lookup time and return...
*/
dinfo->ready_time = time(NULL);
}
| {
"pile_set_name": "Github"
} |
// #docplaster
// #docregion
import { Injectable } from '@angular/core';
import { LoggerService } from './logger.service';
import { UserService } from './user.service';
// #docregion injectables, injectable
@Injectable()
export class UserContextService {
// #enddocregion injectables, injectable
name: string;
role: string;
loggedInSince: Date;
// #docregion ctor, injectables
constructor(private userService: UserService, private loggerService: LoggerService) {
// #enddocregion ctor, injectables
this.loggedInSince = new Date();
// #docregion ctor, injectables
}
// #enddocregion ctor, injectables
loadUser(userId: number) {
let user = this.userService.getUserById(userId);
this.name = user.name;
this.role = user.role;
this.loggerService.logDebug('loaded User');
}
// #docregion injectables, injectable
}
// #enddocregion injectables, injectable
| {
"pile_set_name": "Github"
} |
#pragma once
#include <Scenario/Commands/Interval/SetMaxDuration.hpp>
#include <Scenario/Commands/Interval/SetMinDuration.hpp>
#include <Scenario/Commands/Scenario/Displacement/MoveEventMeta.hpp>
#include <Scenario/Commands/Scenario/Displacement/MoveInterval.hpp>
#include <Scenario/Palette/Tools/States/MoveAndMergeState.hpp>
#include <Scenario/Palette/Tools/States/MoveIntervalState.hpp>
#include <Scenario/Palette/Tools/States/MoveStates.hpp>
#include <Scenario/Palette/Transitions/EventTransitions.hpp>
#include <Scenario/Palette/Transitions/IntervalTransitions.hpp>
#include <Scenario/Palette/Transitions/StateTransitions.hpp>
#include <Scenario/Palette/Transitions/TimeSyncTransitions.hpp>
#include <score/statemachine/StateMachineTools.hpp>
namespace Scenario
{
class MoveIntervalInScenario_StateWrapper
{
public:
template <typename Scenario_T, typename ToolPalette_T>
static auto make(const ToolPalette_T& palette, QState* waitState, QState& parent)
{
/// Interval
/// //TODO remove useless arguments to ctor
auto moveInterval = new MoveIntervalState<ToolPalette_T>{
palette,
palette.model(),
palette.context().context.commandStack,
palette.context().context.objectLocker,
&parent};
score::make_transition<ClickOnInterval_Transition<Scenario_T>>(
waitState, moveInterval, *moveInterval);
moveInterval->addTransition(moveInterval, finishedState(), waitState);
return moveInterval;
}
};
class MoveLeftBraceInScenario_StateWrapper
{
public:
template <typename Scenario_T, typename ToolPalette_T>
static auto make(const ToolPalette_T& palette, QState* waitState, QState& parent)
{
auto moveBrace
= new MoveIntervalBraceState<Scenario::Command::SetMinDuration, Scenario_T, ToolPalette_T>{
palette,
palette.model(),
palette.context().context.commandStack,
palette.context().context.objectLocker,
&parent};
score::make_transition<ClickOnLeftBrace_Transition<Scenario_T>>(
waitState, moveBrace, *moveBrace);
moveBrace->addTransition(moveBrace, finishedState(), waitState);
return moveBrace;
}
};
class MoveRightBraceInScenario_StateWrapper
{
public:
template <typename Scenario_T, typename ToolPalette_T>
static auto make(const ToolPalette_T& palette, QState* waitState, QState& parent)
{
auto moveBrace
= new MoveIntervalBraceState<Scenario::Command::SetMaxDuration, Scenario_T, ToolPalette_T>{
palette,
palette.model(),
palette.context().context.commandStack,
palette.context().context.objectLocker,
&parent};
score::make_transition<ClickOnRightBrace_Transition<Scenario_T>>(
waitState, moveBrace, *moveBrace);
moveBrace->addTransition(moveBrace, finishedState(), waitState);
return moveBrace;
}
};
class MoveEventInScenario_StateWrapper
{
public:
template <typename Scenario_T, typename ToolPalette_T>
static auto make(const ToolPalette_T& palette, QState* waitState, QState& parent)
{
/// Event
auto moveEvent
= new MoveEventState<Scenario::Command::MoveEventMeta, Scenario_T, ToolPalette_T>{
palette,
palette.model(),
palette.context().context.commandStack,
palette.context().context.objectLocker,
&parent};
score::make_transition<ClickOnState_Transition<Scenario_T>>(waitState, moveEvent, *moveEvent);
score::make_transition<ClickOnEvent_Transition<Scenario_T>>(waitState, moveEvent, *moveEvent);
moveEvent->addTransition(moveEvent, finishedState(), waitState);
return moveEvent;
}
};
class MoveTimeSyncInScenario_StateWrapper
{
public:
template <typename Scenario_T, typename ToolPalette_T>
static auto make(const ToolPalette_T& palette, QState* waitState, QState& parent)
{
/// TimeSync
auto moveTimeSync
= new MoveTimeSyncState<Scenario::Command::MoveEventMeta, Scenario_T, ToolPalette_T>{
palette,
palette.model(),
palette.context().context.commandStack,
palette.context().context.objectLocker,
&parent};
score::make_transition<ClickOnTimeSync_Transition<Scenario_T>>(
waitState, moveTimeSync, *moveTimeSync);
moveTimeSync->addTransition(moveTimeSync, finishedState(), waitState);
return moveTimeSync;
}
};
class MoveEventInTopScenario_StateWrapper
{
public:
template <typename Scenario_T, typename ToolPalette_T>
static auto make(const ToolPalette_T& palette, QState* waitState, QState& parent)
{
/// Event
auto moveEvent
= new MoveEventState<Scenario::Command::MoveTopEventMeta, Scenario_T, ToolPalette_T>{
palette,
palette.model(),
palette.context().context.commandStack,
palette.context().context.objectLocker,
&parent};
score::make_transition<ClickOnState_Transition<Scenario_T>>(waitState, moveEvent, *moveEvent);
score::make_transition<ClickOnEvent_Transition<Scenario_T>>(waitState, moveEvent, *moveEvent);
moveEvent->addTransition(moveEvent, finishedState(), waitState);
return moveEvent;
}
};
class MoveTimeSyncInTopScenario_StateWrapper
{
public:
template <typename Scenario_T, typename ToolPalette_T>
static auto make(const ToolPalette_T& palette, QState* waitState, QState& parent)
{
/// TimeSync
auto moveTimeSync
= new MoveTimeSyncState<Scenario::Command::MoveTopEventMeta, Scenario_T, ToolPalette_T>{
palette,
palette.model(),
palette.context().context.commandStack,
palette.context().context.objectLocker,
&parent};
score::make_transition<ClickOnTimeSync_Transition<Scenario_T>>(
waitState, moveTimeSync, *moveTimeSync);
moveTimeSync->addTransition(moveTimeSync, finishedState(), waitState);
return moveTimeSync;
}
};
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* 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.android.locationtracker;
import com.android.locationtracker.data.TrackerDataHelper;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.telephony.CellLocation;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.telephony.cdma.CdmaCellLocation;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Location Tracking service
*
* Records location updates for all registered location providers, and cell
* location updates
*/
public class TrackerService extends Service {
private List<LocationTrackingListener> mListeners;
private static final String LOG_TAG = TrackerActivity.LOG_TAG;
// controls which location providers to track
private Set<String> mTrackedProviders;
private TrackerDataHelper mTrackerData;
private TelephonyManager mTelephonyManager;
private Location mNetworkLocation;
// Handlers and Receivers for phone and network state
private NetworkStateBroadcastReceiver mNetwork;
private static final String CELL_PROVIDER_TAG = "cell";
// signal strength updates
private static final String SIGNAL_PROVIDER_TAG = "signal";
private static final String WIFI_PROVIDER_TAG = "wifi";
// tracking tag for data connectivity issues
private static final String DATA_CONN_PROVIDER_TAG = "data";
// preference constants
private static final String MIN_TIME_PREF = "mintime_preference";
private static final String MIN_DIS_PREF = "mindistance_preference";
private static final String GPS_PREF = "gps_preference";
private static final String NETWORK_PREF = "network_preference";
private static final String SIGNAL_PREF = "signal_preference";
private static final String DEBUG_PREF = "advanced_log_preference";
private PreferenceListener mPrefListener;
public TrackerService() {
}
@Override
public IBinder onBind(Intent intent) {
// ignore - nothing to do
return null;
}
/**
* registers location listeners
*
* @param intent
* @param startId
*/
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
mNetworkLocation = null;
initLocationListeners();
Toast.makeText(this, "Tracking service started", Toast.LENGTH_SHORT);
}
private synchronized void initLocationListeners() {
mTrackerData = new TrackerDataHelper(this);
LocationManager lm = getLocationManager();
mTrackedProviders = getTrackedProviders();
List<String> locationProviders = lm.getAllProviders();
mListeners = new ArrayList<LocationTrackingListener>(
locationProviders.size());
long minUpdateTime = getLocationUpdateTime();
float minDistance = getLocationMinDistance();
for (String providerName : locationProviders) {
if (mTrackedProviders.contains(providerName)) {
Log.d(LOG_TAG, "Adding location listener for provider " +
providerName);
if (doDebugLogging()) {
mTrackerData.writeEntry("init", String.format(
"start listening to %s : %d ms; %f meters",
providerName, minUpdateTime, minDistance));
}
LocationTrackingListener listener =
new LocationTrackingListener();
lm.requestLocationUpdates(providerName, minUpdateTime,
minDistance, listener);
mListeners.add(listener);
}
}
mTelephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
if (doDebugLogging()) {
// register for cell location updates
mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CELL_LOCATION);
// Register for Network (Wifi or Mobile) updates
mNetwork = new NetworkStateBroadcastReceiver();
IntentFilter mIntentFilter;
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
mIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
mIntentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
Log.d(LOG_TAG, "registering receiver");
registerReceiver(mNetwork, mIntentFilter);
}
if (trackSignalStrength()) {
mTelephonyManager.listen(mPhoneStateListener,
PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
}
// register for preference changes, so we can restart listeners on
// pref changes
mPrefListener = new PreferenceListener();
getPreferences().registerOnSharedPreferenceChangeListener(mPrefListener);
}
private Set<String> getTrackedProviders() {
Set<String> providerSet = new HashSet<String>();
if (trackGPS()) {
providerSet.add(LocationManager.GPS_PROVIDER);
}
if (trackNetwork()) {
providerSet.add(LocationManager.NETWORK_PROVIDER);
}
return providerSet;
}
private SharedPreferences getPreferences() {
return PreferenceManager.getDefaultSharedPreferences(this);
}
private boolean trackNetwork() {
return getPreferences().getBoolean(NETWORK_PREF, true);
}
private boolean trackGPS() {
return getPreferences().getBoolean(GPS_PREF, true);
}
private boolean doDebugLogging() {
return getPreferences().getBoolean(DEBUG_PREF, false);
}
private boolean trackSignalStrength() {
return getPreferences().getBoolean(SIGNAL_PREF, false);
}
private float getLocationMinDistance() {
try {
String disString = getPreferences().getString(MIN_DIS_PREF, "0");
return Float.parseFloat(disString);
}
catch (NumberFormatException e) {
Log.e(LOG_TAG, "Invalid preference for location min distance", e);
}
return 0;
}
private long getLocationUpdateTime() {
try {
String timeString = getPreferences().getString(MIN_TIME_PREF, "0");
long secondsTime = Long.valueOf(timeString);
return secondsTime * 1000;
}
catch (NumberFormatException e) {
Log.e(LOG_TAG, "Invalid preference for location min time", e);
}
return 0;
}
/**
* Shuts down this service
*/
@Override
public void onDestroy() {
super.onDestroy();
Log.d(LOG_TAG, "Removing location listeners");
stopListeners();
Toast.makeText(this, "Tracking service stopped", Toast.LENGTH_SHORT);
}
/**
* De-registers all location listeners, closes persistent storage
*/
protected synchronized void stopListeners() {
LocationManager lm = getLocationManager();
if (mListeners != null) {
for (LocationTrackingListener listener : mListeners) {
lm.removeUpdates(listener);
}
mListeners.clear();
}
mListeners = null;
// stop cell state listener
if (mTelephonyManager != null) {
mTelephonyManager.listen(mPhoneStateListener, 0);
}
// stop network/wifi listener
if (mNetwork != null) {
unregisterReceiver(mNetwork);
}
mNetwork = null;
mTrackerData = null;
if (mPrefListener != null) {
getPreferences().unregisterOnSharedPreferenceChangeListener(mPrefListener);
mPrefListener = null;
}
}
private LocationManager getLocationManager() {
return (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
/**
* Determine the current distance from given location to the last
* approximated network location
*
* @param location - new location
*
* @return float distance in meters
*/
private synchronized float getDistanceFromNetwork(Location location) {
float value = 0;
if (mNetworkLocation != null) {
value = location.distanceTo(mNetworkLocation);
}
if (LocationManager.NETWORK_PROVIDER.equals(location.getProvider())) {
mNetworkLocation = location;
}
return value;
}
private class LocationTrackingListener implements LocationListener {
/**
* Writes details of location update to tracking file, including
* recording the distance between this location update and the last
* network location update
*
* @param location - new location
*/
public void onLocationChanged(Location location) {
if (location == null) {
return;
}
float distance = getDistanceFromNetwork(location);
mTrackerData.writeEntry(location, distance);
}
/**
* Writes update to tracking file
*
* @param provider - name of disabled provider
*/
public void onProviderDisabled(String provider) {
if (doDebugLogging()) {
mTrackerData.writeEntry(provider, "provider disabled");
}
}
/**
* Writes update to tracking file
*
* @param provider - name of enabled provider
*/
public void onProviderEnabled(String provider) {
if (doDebugLogging()) {
mTrackerData.writeEntry(provider, "provider enabled");
}
}
/**
* Writes update to tracking file
*
* @param provider - name of provider whose status changed
* @param status - new status
* @param extras - optional set of extra status messages
*/
public void onStatusChanged(String provider, int status, Bundle extras) {
if (doDebugLogging()) {
mTrackerData.writeEntry(provider, "status change: " + status);
}
}
}
PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
@Override
public void onCellLocationChanged(CellLocation location) {
try {
if (location instanceof GsmCellLocation) {
GsmCellLocation cellLocation = (GsmCellLocation)location;
String updateMsg = "cid=" + cellLocation.getCid() +
", lac=" + cellLocation.getLac();
mTrackerData.writeEntry(CELL_PROVIDER_TAG, updateMsg);
} else if (location instanceof CdmaCellLocation) {
CdmaCellLocation cellLocation = (CdmaCellLocation)location;
String updateMsg = "BID=" + cellLocation.getBaseStationId() +
", SID=" + cellLocation.getSystemId() +
", NID=" + cellLocation.getNetworkId() +
", lat=" + cellLocation.getBaseStationLatitude() +
", long=" + cellLocation.getBaseStationLongitude() +
", SID=" + cellLocation.getSystemId() +
", NID=" + cellLocation.getNetworkId();
mTrackerData.writeEntry(CELL_PROVIDER_TAG, updateMsg);
}
} catch (Exception e) {
Log.e(LOG_TAG, "Exception in CellStateHandler.handleMessage:", e);
}
}
public void onSignalStrengthsChanged(SignalStrength signalStrength) {
if (mTelephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
String updateMsg = "cdma dBM=" + signalStrength.getCdmaDbm();
mTrackerData.writeEntry(SIGNAL_PROVIDER_TAG, updateMsg);
} else if (mTelephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_GSM) {
String updateMsg = "gsm signal=" + signalStrength.getGsmSignalStrength();
mTrackerData.writeEntry(SIGNAL_PROVIDER_TAG, updateMsg);
}
}
};
/**
* Listener + recorder for mobile or wifi updates
*/
private class NetworkStateBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
WifiManager wifiManager =
(WifiManager) context.getSystemService(Context.WIFI_SERVICE);
List<ScanResult> wifiScanResults = wifiManager.getScanResults();
String updateMsg = "num scan results=" +
(wifiScanResults == null ? "0" : wifiScanResults.size());
mTrackerData.writeEntry(WIFI_PROVIDER_TAG, updateMsg);
} else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
String updateMsg;
boolean noConnectivity =
intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if (noConnectivity) {
updateMsg = "no connectivity";
}
else {
updateMsg = "connection available";
}
mTrackerData.writeEntry(DATA_CONN_PROVIDER_TAG, updateMsg);
} else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
WifiManager.WIFI_STATE_UNKNOWN);
String stateString = "unknown";
switch (state) {
case WifiManager.WIFI_STATE_DISABLED:
stateString = "disabled";
break;
case WifiManager.WIFI_STATE_DISABLING:
stateString = "disabling";
break;
case WifiManager.WIFI_STATE_ENABLED:
stateString = "enabled";
break;
case WifiManager.WIFI_STATE_ENABLING:
stateString = "enabling";
break;
}
mTrackerData.writeEntry(WIFI_PROVIDER_TAG,
"state = " + stateString);
}
}
}
private class PreferenceListener implements OnSharedPreferenceChangeListener {
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
Log.d(LOG_TAG, "restarting listeners due to preference change");
synchronized (TrackerService.this) {
stopListeners();
initLocationListeners();
}
}
}
}
| {
"pile_set_name": "Github"
} |
// Copyright 2015-2019 Espressif Systems (Shanghai) PTE LTD
//
// 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.
// The HAL layer for SPI (common part)
#include "hal/spi_hal.h"
static const char SPI_HAL_TAG[] = "spi_hal";
#define SPI_HAL_CHECK(a, str, ret_val, ...) \
if (!(a)) { \
HAL_LOGE(SPI_HAL_TAG,"%s(%d): "str, __FUNCTION__, __LINE__, ##__VA_ARGS__); \
return (ret_val); \
}
void spi_hal_init(spi_hal_context_t *hal, int host_id)
{
memset(hal, 0, sizeof(spi_hal_context_t));
spi_dev_t *hw = spi_periph_signal[host_id].hw;
hal->hw = hw;
spi_ll_master_init(hw);
//Force a transaction done interrupt. This interrupt won't fire yet because
//we initialized the SPI interrupt as disabled. This way, we can just
//enable the SPI interrupt and the interrupt handler will kick in, handling
//any transactions that are queued.
spi_ll_enable_int(hw);
spi_ll_set_int_stat(hw);
spi_ll_set_mosi_delay(hw, 0, 0);
}
void spi_hal_deinit(spi_hal_context_t *hal)
{
spi_dev_t *hw = hal->hw;
if (hw) {
spi_ll_disable_int(hw);
spi_ll_clear_int_stat(hw);
}
}
esp_err_t spi_hal_cal_clock_conf(const spi_hal_context_t *hal, int speed_hz, int duty_cycle, bool use_gpio, int input_delay_ns, int *out_freq, spi_hal_timing_conf_t *timing_conf)
{
spi_hal_timing_conf_t temp_conf;
int eff_clk_n = spi_ll_master_cal_clock(APB_CLK_FREQ, speed_hz, duty_cycle, &temp_conf.clock_reg);
//When the speed is too fast, we may need to use dummy cycles to compensate the reading.
//But these don't work for full-duplex connections.
spi_hal_cal_timing(eff_clk_n, use_gpio, input_delay_ns, &temp_conf.timing_dummy, &temp_conf.timing_miso_delay);
#ifdef CONFIG_IDF_TARGET_ESP32
const int freq_limit = spi_hal_get_freq_limit(use_gpio, input_delay_ns);
SPI_HAL_CHECK(hal->half_duplex || temp_conf.timing_dummy == 0 || hal->no_compensate,
"When work in full-duplex mode at frequency > %.1fMHz, device cannot read correct data.\n\
Try to use IOMUX pins to increase the frequency limit, or use the half duplex mode.\n\
Please note the SPI master can only work at divisors of 80MHz, and the driver always tries to find the closest frequency to your configuration.\n\
Specify ``SPI_DEVICE_NO_DUMMY`` to ignore this checking. Then you can output data at higher speed, or read data at your own risk.",
ESP_ERR_NOT_SUPPORTED, freq_limit / 1000. / 1000 );
#endif
if (timing_conf) {
*timing_conf = temp_conf;
}
if (out_freq) {
*out_freq = eff_clk_n;
}
return ESP_OK;
}
int spi_hal_master_cal_clock(int fapb, int hz, int duty_cycle)
{
return spi_ll_master_cal_clock(fapb, hz, duty_cycle, NULL);
}
void spi_hal_cal_timing(int eff_clk, bool gpio_is_used, int input_delay_ns, int *dummy_n, int *miso_delay_n)
{
const int apbclk_kHz = APB_CLK_FREQ / 1000;
//how many apb clocks a period has
const int spiclk_apb_n = APB_CLK_FREQ / eff_clk;
const int gpio_delay_ns = gpio_is_used ? GPIO_MATRIX_DELAY_NS : 0;
//how many apb clocks the delay is, the 1 is to compensate in case ``input_delay_ns`` is rounded off.
int delay_apb_n = (1 + input_delay_ns + gpio_delay_ns) * apbclk_kHz / 1000 / 1000;
if (delay_apb_n < 0) {
delay_apb_n = 0;
}
int dummy_required = delay_apb_n / spiclk_apb_n;
int miso_delay = 0;
if (dummy_required > 0) {
//due to the clock delay between master and slave, there's a range in which data is random
//give MISO a delay if needed to make sure we sample at the time MISO is stable
miso_delay = (dummy_required + 1) * spiclk_apb_n - delay_apb_n - 1;
} else {
//if the dummy is not required, maybe we should also delay half a SPI clock if the data comes too early
if (delay_apb_n * 4 <= spiclk_apb_n) {
miso_delay = -1;
}
}
*dummy_n = dummy_required;
*miso_delay_n = miso_delay;
HAL_LOGD(SPI_HAL_TAG, "eff: %d, limit: %dk(/%d), %d dummy, %d delay", eff_clk / 1000, apbclk_kHz / (delay_apb_n + 1), delay_apb_n, dummy_required, miso_delay);
}
int spi_hal_get_freq_limit(bool gpio_is_used, int input_delay_ns)
{
const int apbclk_kHz = APB_CLK_FREQ / 1000;
const int gpio_delay_ns = gpio_is_used ? GPIO_MATRIX_DELAY_NS : 0;
//how many apb clocks the delay is, the 1 is to compensate in case ``input_delay_ns`` is rounded off.
int delay_apb_n = (1 + input_delay_ns + gpio_delay_ns) * apbclk_kHz / 1000 / 1000;
if (delay_apb_n < 0) {
delay_apb_n = 0;
}
return APB_CLK_FREQ / (delay_apb_n + 1);
} | {
"pile_set_name": "Github"
} |
/// Copyright (c) 2012 Ecma International. All rights reserved.
/**
* This test is actually testing the [[Delete]] internal method (8.12.8). Since the
* language provides no way to directly exercise [[Delete]], the tests are placed here.
*
* @path ch11/11.4/11.4.1/11.4.1-4.a-11.js
* @description delete operator returns true on deleting arguments propterties(arguments.callee)
*/
function testcase() {
function foo(a,b)
{
return (delete arguments.callee);
}
var d = delete arguments.callee;
if(d === true && arguments.callee === undefined)
return true;
}
runTestCase(testcase);
| {
"pile_set_name": "Github"
} |
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule binaryToBase64
* @flow
*/
'use strict';
const base64 = require('base64-js');
function binaryToBase64(data: ArrayBuffer | $ArrayBufferView) {
if (data instanceof ArrayBuffer) {
data = new Uint8Array(data);
}
if (data instanceof Uint8Array) {
return base64.fromByteArray(data);
}
if (!ArrayBuffer.isView(data)) {
throw new Error('data must be ArrayBuffer or typed array');
}
const {buffer, byteOffset, byteLength} = data;
return base64.fromByteArray(new Uint8Array(buffer, byteOffset, byteLength));
}
module.exports = binaryToBase64;
| {
"pile_set_name": "Github"
} |
// =============================================================================
// Scilab ( http://www.scilab.org/ ) - This file is part of Scilab
// Copyright (C) 2012 - Scilab Enterprises - Alexandre HERISSE
//
// This file is distributed under the same license as the Scilab package.
// =============================================================================
// <-- XCOS TEST -->
//
// <-- Non-regression test for bug 11821 -->
//
// <-- Bugzilla URL -->
// http://bugzilla.scilab.org/show_bug.cgi?id=11821
//
// <-- Short Description -->
// Running XcosPalAdd example from help led to deadlock
pal = xcosPal();
pal = xcosPalAddBlock(pal, "SUM_f");
pal = xcosPalAddBlock(pal, "BIGSOM_f");
status = xcosPalAdd(pal, "my Summation blocks");
assert_checktrue (status);
| {
"pile_set_name": "Github"
} |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the viralAdvertising function below.
def viralAdvertising(n):
shared =5
cumulative=0
for i in range(1,n+1):
liked = shared//2
cumulative+=liked
shared = liked*3
return cumulative
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
result = viralAdvertising(n)
fptr.write(str(result) + '\n')
fptr.close()
| {
"pile_set_name": "Github"
} |
[[_events]]
= Events
Applications have the ability to publish events from time to time to communicate
that something of interest has happened at runtime. Events will be triggered by
the application during each of its life cycle phases, and also when MVC groups are
created and destroyed.
NOTE: All application event handlers are guaranteed to be called in the same thread
that originated the event.
:leveloffset: 2
include::events-publishing.adoc[]
include::events-consuming.adoc[]
include::events-application-events.adoc[]
include::events-lifecycle-events.adoc[]
include::events-miscellaneous-events.adoc[]
include::events-eventpublisher-transformation.adoc[]
:leveloffset: 1
| {
"pile_set_name": "Github"
} |
# Package Groups Used in Kubernetes Visibility Rules
## Background
`BUILD` rules define dependencies, answering the question:
on what packages does _foo_ depend?
The `BUILD` file in this package allows one to define
_allowed_ reverse dependencies, answering the question:
given a package _foo_, what other specific packages are
allowed to depend on it?
This is done via visibility rules.
Visibility rules discourage unintended, spurious
dependencies that blur code boundaries, slow CICD queues and
generally inhibit progress.
#### Facts
* A package is any directory that contains a `BUILD` file.
* A `package_group` is a `BUILD` file rule that defines a named
set of packages for use in other rules, e.g., given
```
package_group(
name = "database_CONSUMERS",
packages = [
"//foo/dbinitializer",
"//foo/backend/...", # `backend` and everything below it
],
)
```
one can specify the following visibility rule in any `BUILD` rule:
```
visibility = [ "//build/visible_to:database_CONSUMERS" ],
```
* A visibility rule takes a list of package groups as its
argument - or one of the pre-defined groups
`//visibility:private` or `//visibility:public`.
* If no visibility is explicitly defined, a package is
_private_ by default.
* Violations in visibility cause `make bazel-build` to fail,
which in turn causes the submit queue to fail - that's the
enforcement.
#### Why define all package groups meant for visibility here (in one file)?
* Ease discovery of appropriate groups for use in a rule.
* Ease reuse (inclusions) of commonly used groups.
* Consistent style:
* easy to read `//build/visible_to:math_library_CONSUMERS` rules,
* call out bad dependencies for eventual removal.
* Make it more obvious in code reviews when visibility is being
modified.
* One set of `OWNERS` to manage visibility.
The alternative is to use special [package literals] directly
in visibility rules, e.g.
```
visibility = [
"//foo/dbinitializer:__pkg__",
"//foo/backend:__subpackages__",
],
```
The difference in style is similar to the difference between
using a named static constant like `MAX_NODES` rather than a
literal like `12`. Names are preferable to literals for intent
documentation, search, changing one place rather than _n_,
associating usage in distant code blocks, etc.
## Rule Examples
#### Nobody outside this package can depend on me.
```
visibility = ["//visibility:private"],
```
Since this is the default, there's no reason to use this
rule except as a means to override, for some specific
target, some broader, whole-package visibility rule.
#### Anyone can depend on me (eschew this).
```
visibility = ["//visibility:public"],
```
#### Only some servers can depend on me.
Appropriate for, say, backend storage utilities.
```
visibility = ["//visible_to:server_foo","//visible_to:server_bar"].
```
#### Both some client and some server can see me.
Appropriate for shared API definition files and generated code:
```
visibility = ["//visible_to:client_foo,//visible_to:server_foo"],
```
## Handy commands
#### Quickly check for visibility violations
```
bazel build --check_visibility --nobuild \
//cmd/... //pkg/... //plugin/... \
//third_party/... //examples/... //test/... //vendor/k8s.io/...
```
#### Who depends on target _q_?
To create a seed set for a visibility group, one can ask what
packages currently depend on (must currently be able to see) a
given Go library target? It's a time consuming query.
```
q=//pkg/kubectl/cmd:go_default_library
bazel query "rdeps(...,${q})" | \
grep go_default_library | \
sed 's/\(.*\):go_default_library/ "\1",/'
```
#### What targets below _p_ are visible to anyone?
A means to look for things one missed when locking down _p_.
```
p=//pkg/kubectl/cmd
bazel query "visible(...,${p}/...)"
```
#### What packages below _p_ may target _q_ depend on without violating visibility rules?
A means to pinpoint unexpected visibility.
```
p=//pkg/kubectl
q=//cmd/kubelet:kubelet
bazel query "visible(${q},${p}/...)" | more
```
#### What packages does target _q_ need?
```
q=//cmd/kubectl:kubectl
bazel query "buildfiles(deps($q))" | \
grep -v @bazel_tools | \
grep -v @io_bazel_rules | \
grep -v @io_kubernetes_build | \
grep -v @local_config | \
grep -v @local_jdk | \
grep -v //visible_to: | \
sed 's/:BUILD//' | \
sort | uniq > ~/KUBECTL_BUILD.txt
```
or try
```
bazel query --nohost_deps --noimplicit_deps \
"kind('source file', deps($q))" | wc -
```
#### How does kubectl depend on pkg/util/parsers?
```
bazel query "somepath(cmd/kubectl:kubectl, pkg/util/parsers:go_default_library)"
```
[package literals]: https://bazel.build/versions/master/docs/be/common-definitions.html#common.visibility
| {
"pile_set_name": "Github"
} |
#LyX 2.2 created this file. For more info see http://www.lyx.org/
\lyxformat 508
\begin_document
\begin_header
\save_transient_properties true
\origin unavailable
\textclass paper
\use_default_options false
\begin_modules
theorems-ams
eqs-within-sections
figs-within-sections
\end_modules
\maintain_unincluded_children false
\language english
\language_package default
\inputencoding iso8859-1
\fontencoding global
\font_roman "default" "default"
\font_sans "default" "default"
\font_typewriter "default" "default"
\font_math "auto" "auto"
\font_default_family default
\use_non_tex_fonts false
\font_sc false
\font_osf false
\font_sf_scale 100 100
\font_tt_scale 100 100
\graphics default
\default_output_format default
\output_sync 0
\bibtex_command default
\index_command default
\paperfontsize 12
\spacing single
\use_hyperref false
\papersize letterpaper
\use_geometry false
\use_package amsmath 2
\use_package amssymb 2
\use_package cancel 1
\use_package esint 0
\use_package mathdots 1
\use_package mathtools 1
\use_package mhchem 1
\use_package stackrel 0
\use_package stmaryrd 1
\use_package undertilde 1
\cite_engine basic
\cite_engine_type default
\biblio_style plain
\use_bibtopic false
\use_indices false
\paperorientation portrait
\suppress_date false
\justification true
\use_refstyle 0
\index Index
\shortcut idx
\color #008000
\end_index
\secnumdepth 5
\tocdepth 5
\paragraph_separation indent
\paragraph_indentation default
\quotes_language english
\papercolumns 1
\papersides 2
\paperpagestyle default
\tracking_changes false
\output_changes false
\html_math_output 0
\html_css_as_file 0
\html_be_strict false
\end_header
\begin_body
\begin_layout Standard
\begin_inset FormulaMacro
\newcommand{\reals}{\mathbf{R}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\integers}{\mathbf{Z}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\naturals}{\mathbf{N}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\rationals}{\mathbf{Q}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\ca}{\mathcal{A}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\cb}{\mathcal{B}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\cc}{\mathcal{C}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\cd}{\mathcal{D}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\ce}{\mathcal{E}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\cf}{\mathcal{F}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\cg}{\mathcal{G}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\ch}{\mathcal{H}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\ci}{\mathcal{I}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\cj}{\mathcal{J}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\ck}{\mathcal{K}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\cl}{\mathcal{L}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\cm}{\mathcal{M}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\cn}{\mathcal{N}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\co}{\mathcal{O}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\cp}{\mathcal{P}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\cq}{\mathcal{Q}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\calr}{\mathcal{R}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\cs}{\mathcal{S}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\ct}{\mathcal{T}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\cu}{\mathcal{U}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\cv}{\mathcal{V}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\cw}{\mathcal{W}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\cx}{\mathcal{X}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\cy}{\mathcal{Y}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\cz}{\mathcal{Z}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\ind}[1]{1(#1)}
\end_inset
\begin_inset FormulaMacro
\newcommand{\pr}{\mathbb{P}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\predsp}{\cy}
\end_inset
\begin_inset FormulaMacro
\newcommand{\outsp}{\cy}
\end_inset
\begin_inset FormulaMacro
\newcommand{\prxy}{P_{\cx\times\cy}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\prx}{P_{\cx}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\prygivenx}{P_{\cy\mid\cx}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\ex}{\mathbb{E}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\var}{\textrm{Var}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\cov}{\textrm{Cov}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\sgn}{\textrm{sgn}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\sign}{\textrm{sign}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\kl}{\textrm{KL}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\law}{\mathcal{L}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\eps}{\varepsilon}
\end_inset
\begin_inset FormulaMacro
\newcommand{\as}{\textrm{ a.s.}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\io}{\textrm{ i.o.}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\ev}{\textrm{ ev.}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\convd}{\stackrel{d}{\to}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\eqd}{\stackrel{d}{=}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\del}{\nabla}
\end_inset
\begin_inset FormulaMacro
\newcommand{\loss}{V}
\end_inset
\begin_inset FormulaMacro
\newcommand{\risk}{R}
\end_inset
\begin_inset FormulaMacro
\newcommand{\emprisk}{\hat{R}_{\ell}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\lossfnl}{L}
\end_inset
\begin_inset FormulaMacro
\newcommand{\emplossfnl}{\hat{L}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\empminimizer}[1]{\hat{#1}_{\ell}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\minimizer}[1]{#1_{*}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\etal}{\textrm{et. al.}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\tr}{\operatorname{tr}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\trace}{\operatorname{trace}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\diag}{\text{diag}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\rank}{\text{rank}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\linspan}{\text{span}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\proj}{\text{Proj}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\argmax}{\operatornamewithlimits{arg\, max}}
{\mbox{argmax}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\argmin}{\operatornamewithlimits{arg\, min}}
{\mbox{argmin}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\bfx}{\mathbf{x}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\bfy}{\mathbf{y}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\bfl}{\mathbf{\lambda}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\bfm}{\mathbf{\mu}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\calL}{\mathcal{L}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\vw}{\boldsymbol{w}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\vx}{\boldsymbol{x}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\vxi}{\boldsymbol{\xi}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\valpha}{\boldsymbol{\alpha}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\vbeta}{\boldsymbol{\beta}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\vsigma}{\boldsymbol{\sigma}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\vmu}{\boldsymbol{\mu}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\vtheta}{\boldsymbol{\theta}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\vd}{\boldsymbol{d}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\vs}{\boldsymbol{s}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\vt}{\boldsymbol{t}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\vh}{\boldsymbol{h}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\ve}{\boldsymbol{e}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\vf}{\boldsymbol{f}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\vg}{\boldsymbol{g}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\vz}{\boldsymbol{z}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\vk}{\boldsymbol{k}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\va}{\boldsymbol{a}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\vb}{\boldsymbol{b}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\vv}{\boldsymbol{v}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\vy}{\boldsymbol{y}}
\end_inset
\begin_inset FormulaMacro
\newcommand{\hil}{\ch}
\end_inset
\begin_inset FormulaMacro
\newcommand{\rkhs}{\hil}
\end_inset
\end_layout
\begin_layout Title
Text for L1/L2
\end_layout
\begin_layout Author
David S.
Rosenberg
\end_layout
\begin_layout Date
\begin_inset ERT
status open
\begin_layout Plain Layout
\backslash
today
\end_layout
\end_inset
\end_layout
\begin_layout Standard
\begin_inset Formula
\begin{eqnarray*}
\hat{w}_{r} & = & \argmin_{\|w\|_{2}^{2}\le r^{2}}\frac{1}{n}\sum_{i=1}^{n}\left(w^{T}x_{i}-y_{i}\right)^{2}\\
\hat{w} & = & \hat{w}_{\infty}=\text{Unconstrained ERM}
\end{eqnarray*}
\end_inset
\end_layout
\begin_layout Standard
Consider the ratio
\begin_inset Formula $\|\hat{w}_{r}\|_{2}/\|\hat{w}\|_{2}$
\end_inset
\end_layout
\begin_layout Itemize
For
\begin_inset Formula $r=0$
\end_inset
,
\begin_inset Formula $\|\hat{w}_{r}\|_{2}/\|\hat{w}\|_{2}=0$
\end_inset
\end_layout
\begin_layout Itemize
For
\begin_inset Formula $r=\infty$
\end_inset
,
\begin_inset Formula $\|\hat{w}_{r}\|_{2}/\|\hat{w}\|_{2}=1$
\end_inset
\end_layout
\begin_layout Itemize
As
\begin_inset Formula $r$
\end_inset
ranges from
\begin_inset Formula $0$
\end_inset
to
\begin_inset Formula $\infty$
\end_inset
, move from left to right in chart.
\end_layout
\begin_layout Standard
\begin_inset Formula
\begin{eqnarray*}
\hat{w}_{r} & = & \argmin_{\|w\|_{1}\le r}\frac{1}{n}\sum_{i=1}^{n}\left(w^{T}x_{i}-y_{i}\right)^{2}\\
\hat{w} & = & \hat{w}_{\infty}=\text{Unconstrained ERM}
\end{eqnarray*}
\end_inset
\end_layout
\begin_layout Standard
Consider the ratio
\begin_inset Formula $\|\hat{w}_{r}\|_{1}/\|\hat{w}\|_{1}$
\end_inset
\end_layout
\begin_layout Itemize
For
\begin_inset Formula $r=0$
\end_inset
,
\begin_inset Formula $\|\hat{w}_{r}\|_{1}/\|\hat{w}\|_{1}=0$
\end_inset
\end_layout
\begin_layout Itemize
For
\begin_inset Formula $r=\infty$
\end_inset
,
\begin_inset Formula $\|\hat{w}_{r}\|_{1}/\|\hat{w}\|_{1}=1$
\end_inset
\end_layout
\begin_layout Itemize
As
\begin_inset Formula $r$
\end_inset
ranges from
\begin_inset Formula $0$
\end_inset
to
\begin_inset Formula $\infty$
\end_inset
, move from left to right in chart.
\end_layout
\end_body
\end_document
| {
"pile_set_name": "Github"
} |
#!/bin/bash
set -e
invoke-rc.d any_proxy stop
| {
"pile_set_name": "Github"
} |
// Copyright 2016 The etcd 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 mockstore provides mock structures for the etcd store package.
package mockstore
| {
"pile_set_name": "Github"
} |
/*
* Generated by class-dump 3.3.4 (64 bit).
*
* class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard.
*/
#import "NSObject.h"
#import "DVTInvalidation-Protocol.h"
#import "IDEDebugProcess-Protocol.h"
@class DBGDebugSession, DBGStackFrame, DBGThread, DVTObservingToken, DVTStackBacktrace, IDELaunchSession, NSArray, NSMutableArray, NSMutableDictionary, NSMutableSet, NSSet, NSString;
@interface DBGProcess : NSObject <IDEDebugProcess, DVTInvalidation>
{
DVTObservingToken *_codeModulesObserver;
DBGDebugSession *_parentDebugSession;
NSString *_associatedProcessUUID;
int _controlState;
NSArray *_threads;
BOOL _threadsAutoRefreshStackFramesDone;
NSMutableSet *_threadsAutoRefreshStackFrames;
NSMutableSet *_codeModules;
NSMutableDictionary *_codeModuleForPathTable;
DBGThread *_currentThread;
DBGStackFrame *_currentStackFrame;
NSString *_name;
int _PID;
NSMutableArray *_memoryDatas;
DVTObservingToken *_currentStackFrameValidityObserver;
DVTStackBacktrace *_currentStackFrameBacktraceWhenSet;
BOOL _usesPIDInName;
BOOL _nameConflictWithOtherRunningProcess;
BOOL _allSameSchemes;
}
+ (id)keyPathsForValuesAffectingName;
+ (id)keyPathsForValuesAffectingThreads;
+ (void)initialize;
@property(nonatomic) BOOL allSameSchemes; // @synthesize allSameSchemes=_allSameSchemes;
@property(nonatomic) BOOL nameConflictWithOtherRunningProcess; // @synthesize nameConflictWithOtherRunningProcess=_nameConflictWithOtherRunningProcess;
@property(nonatomic) BOOL usesPIDInName; // @synthesize usesPIDInName=_usesPIDInName;
@property BOOL threadsAutoRefreshStackFramesDone; // @synthesize threadsAutoRefreshStackFramesDone=_threadsAutoRefreshStackFramesDone;
@property(nonatomic) int PID; // @synthesize PID=_PID;
@property(copy, nonatomic) NSString *name; // @synthesize name=_name;
@property(copy, nonatomic) NSArray *threads; // @synthesize threads=_threads;
@property(nonatomic) int controlState; // @synthesize controlState=_controlState;
@property(readonly) NSString *associatedProcessUUID; // @synthesize associatedProcessUUID=_associatedProcessUUID;
@property(readonly) DBGDebugSession *parentDebugSession; // @synthesize parentDebugSession=_parentDebugSession;
- (void).cxx_destruct;
- (void)primitiveInvalidate;
@property(readonly) unsigned long long addressByteSize;
- (id)_stackFrameInThread:(id)arg1 frameID:(unsigned long long)arg2;
- (id)stackFrameForThreadID:(unsigned long long)arg1 frameID:(unsigned long long)arg2;
- (void)removeMemoryData:(id)arg1;
- (void)autoUpdateAllMemoryDatas;
- (id)readMemoryAtAddress:(unsigned long long)arg1 numberOfBytes:(unsigned long long)arg2 resultHandler:(id)arg3;
- (void)rawMemoryDataForAddressExpression:(id)arg1 numberOfBytes:(unsigned long long)arg2 resultHandler:(id)arg3;
- (id)memoryDataForUUID:(id)arg1;
- (id)memoryDataForAddressOfExpression:(id)arg1 numberOfBytes:(unsigned long long)arg2;
- (void)_handleCodeModuleChange:(id)arg1;
- (id)codeModuleForPath:(id)arg1;
- (BOOL)hasThreadsAutoRefreshStackFrames;
@property(retain, nonatomic) DBGStackFrame *currentStackFrame; // @synthesize currentStackFrame=_currentStackFrame;
@property(retain, nonatomic) DBGThread *currentThread; // @synthesize currentThread=_currentThread;
- (void)deregisterThreadAutoRefreshesStackFrames:(id)arg1;
- (void)registerThreadAutoRefreshesStackFrames:(id)arg1;
- (BOOL)_shouldSelectFirstSymbolFrame;
- (BOOL)_shouldLookForStackFrameWithDebugSymbols;
- (void)setInitialCurrentStackFrame;
- (BOOL)isPaused;
- (void)invalidateUnsuedThreadsAfterCallToSetThreads:(id)arg1;
- (void)_resetName;
@property(readonly) NSString *displayStatus;
@property(readonly) IDELaunchSession *launchSession;
- (id)initWithDebugSession:(id)arg1;
- (void)_detectNameConflict:(char *)arg1 sameScheme:(char *)arg2 forLaunchSession:(id)arg3 inLaunchSessions:(id)arg4 add:(BOOL)arg5;
- (void)_detectNameConflict:(char *)arg1 sameScheme:(char *)arg2 forLaunchSession:(id)arg3 otherLaunchSession:(id)arg4;
- (id)contentDelegateUIExtensionIdentifier;
// Remaining properties
@property(copy) NSSet *codeModules; // @dynamic codeModules;
@property(retain) DVTStackBacktrace *creationBacktrace;
@property(readonly) DVTStackBacktrace *invalidationBacktrace;
@property(readonly) NSArray *memoryDatas; // @dynamic memoryDatas;
@property(copy) NSMutableSet *mutableCodeModules; // @dynamic mutableCodeModules;
@property(retain) NSMutableArray *mutableMemoryDatas; // @dynamic mutableMemoryDatas;
@property(readonly, nonatomic, getter=isValid) BOOL valid;
@end
| {
"pile_set_name": "Github"
} |
from typing import Union, Optional
Buffer = Union[bytes, bytearray, memoryview]
class MD4Hash(object):
digest_size: int
block_size: int
oid: str
def __init__(self, data: Optional[Buffer] = ...) -> None: ...
def update(self, data: Buffer) -> None: ...
def digest(self) -> bytes: ...
def hexdigest(self) -> str: ...
def copy(self) -> MD4Hash: ...
def new(self, data: Optional[Buffer] = ...) -> MD4Hash: ...
def new(data: Optional[Buffer] = ...) -> MD4Hash: ...
digest_size: int
block_size: int
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.facebook.buck.core.toolchain.tool.impl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assume.assumeTrue;
import com.facebook.buck.core.rulekey.RuleKey;
import com.facebook.buck.core.rules.SourcePathRuleFinder;
import com.facebook.buck.core.rules.impl.FakeBuildRule;
import com.facebook.buck.core.rules.resolver.impl.TestActionGraphBuilder;
import com.facebook.buck.core.sourcepath.FakeSourcePath;
import com.facebook.buck.core.sourcepath.PathSourcePath;
import com.facebook.buck.core.toolchain.tool.Tool;
import com.facebook.buck.io.filesystem.impl.FakeProjectFilesystem;
import com.facebook.buck.rules.keys.DefaultRuleKeyFactory;
import com.facebook.buck.rules.keys.TestDefaultRuleKeyFactory;
import com.facebook.buck.testutil.FakeFileHashCache;
import com.facebook.buck.util.environment.Platform;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.hash.HashCode;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.Test;
public class ToolTest {
@Test
public void hashFileToolsCreatedWithTheSamePathAreEqual() {
SourcePathRuleFinder ruleFinder = new TestActionGraphBuilder();
DefaultRuleKeyFactory ruleKeyFactory =
new TestDefaultRuleKeyFactory(
FakeFileHashCache.createFromStrings(
ImmutableMap.<String, String>builder()
.put("path", Strings.repeat("a", 40))
.put("other-path", Strings.repeat("b", 40))
.put("same", Strings.repeat("a", 40))
.build()),
ruleFinder);
FakeProjectFilesystem filesystem = new FakeProjectFilesystem();
Path path = Paths.get("path");
Path otherPath = Paths.get("other-path");
Path same = Paths.get("same");
Tool tool1 = new HashedFileTool(PathSourcePath.of(filesystem, path));
RuleKey tool1RuleKey =
createRuleKeyBuilder(ruleKeyFactory).setReflectively("tool", tool1).build(RuleKey::new);
Tool tool2 = new HashedFileTool(PathSourcePath.of(filesystem, path));
RuleKey tool2RuleKey =
createRuleKeyBuilder(ruleKeyFactory).setReflectively("tool", tool2).build(RuleKey::new);
// Same name, same sha1
assertEquals(tool1RuleKey, tool2RuleKey);
Tool tool3 = new HashedFileTool(PathSourcePath.of(filesystem, otherPath));
RuleKey tool3RuleKey =
createRuleKeyBuilder(ruleKeyFactory).setReflectively("tool", tool3).build(RuleKey::new);
// Different name, different sha1
assertNotEquals(tool1RuleKey, tool3RuleKey);
Tool tool4 = new HashedFileTool(PathSourcePath.of(filesystem, same));
RuleKey tool4RuleKey =
createRuleKeyBuilder(ruleKeyFactory).setReflectively("tool", tool4).build(RuleKey::new);
// Different name, same sha1
assertNotEquals(tool1RuleKey, tool4RuleKey);
}
@Test
public void customVersion() {
SourcePathRuleFinder ruleFinder = new TestActionGraphBuilder();
DefaultRuleKeyFactory ruleKeyFactory =
new TestDefaultRuleKeyFactory(
FakeFileHashCache.createFromStrings(ImmutableMap.of()), ruleFinder);
String tool = "tool";
String version = "version";
Tool tool1 = VersionedTool.of(tool, FakeSourcePath.of("something"), version);
RuleKey tool1RuleKey =
createRuleKeyBuilder(ruleKeyFactory).setReflectively("tool", tool1).build(RuleKey::new);
Tool tool2 = VersionedTool.of(tool, FakeSourcePath.of("something-else"), version);
RuleKey tool2RuleKey =
createRuleKeyBuilder(ruleKeyFactory).setReflectively("tool", tool2).build(RuleKey::new);
assertEquals(tool1RuleKey, tool2RuleKey);
}
@Test
public void shouldAssumeThatToolsInDifferentAbsoluteLocationsWithTheSameNameAreTheSame() {
assumeTrue(Platform.detect() == Platform.MACOS || Platform.detect() == Platform.LINUX);
FakeProjectFilesystem filesystem = new FakeProjectFilesystem();
// Note: both file names are the same
HashedFileTool tool1 =
new HashedFileTool(PathSourcePath.of(filesystem, Paths.get("/usr/local/bin/python2.7")));
HashedFileTool tool2 =
new HashedFileTool(PathSourcePath.of(filesystem, Paths.get("/usr/local/bin/python2.7")));
SourcePathRuleFinder ruleFinder = new TestActionGraphBuilder();
DefaultRuleKeyFactory ruleKeyFactory =
new TestDefaultRuleKeyFactory(
FakeFileHashCache.createFromStrings(
ImmutableMap.<String, String>builder()
// Note: the hashes of both files are the same
.put("/usr/local/bin/python2.7", Strings.repeat("a", 40))
.put("/opt/bin/python2.7", Strings.repeat("a", 40))
.build()),
ruleFinder);
RuleKey tool1RuleKey =
createRuleKeyBuilder(ruleKeyFactory).setReflectively("tool", tool1).build(RuleKey::new);
RuleKey tool2RuleKey =
createRuleKeyBuilder(ruleKeyFactory).setReflectively("tool", tool2).build(RuleKey::new);
assertEquals(tool1RuleKey, tool2RuleKey);
}
private DefaultRuleKeyFactory.Builder<HashCode> createRuleKeyBuilder(
DefaultRuleKeyFactory factory) {
return factory.newBuilderForTesting(new FakeBuildRule("//:test"));
}
}
| {
"pile_set_name": "Github"
} |
{% from "shuup/admin/macros/multilanguage.jinja" import language_dependent_content_tabs %}
{% set product_form = form["base"] %}
<p class="section-description">{% trans %}All the required product information.{% endtrans %}</p>
<div class="row">
<div class="col-lg-12">
{% call(form, language, map) language_dependent_content_tabs(product_form, tab_id_prefix="language") %}
{{ bs3.field(product_form[map.name]) }}
{{ bs3.field(product_form[map.short_description]) }}
{{ bs3.field(product_form[map.description]) }}
{% endcall %}
</div>
</div>
<div class="row">
<div class="col-lg-12">
{{ bs3.field(product_form.file) }}
{{ bs3.field(product_form.type) }}
{{ bs3.field(product_form.sku) }}
</div>
</div>
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html> <html> <head> <title>THREEx.PlasmaShader.js</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <link rel="stylesheet" media="all" href="docco.css" /> </head> <body> <div id="container"> <div id="background"></div> <div id="jump_to"> Jump To … <div id="jump_wrapper"> <div id="jump_page"> <a class="source" href="THREEx.CelShader.html"> THREEx.CelShader.js </a> <a class="source" href="THREEx.DeviceOrientationState.html"> THREEx.DeviceOrientationState.js </a> <a class="source" href="THREEx.FullScreen.html"> THREEx.FullScreen.js </a> <a class="source" href="THREEx.GeometryUtils.html"> THREEx.GeometryUtils.js </a> <a class="source" href="THREEx.GeometryWobble.html"> THREEx.GeometryWobble.js </a> <a class="source" href="THREEx.KeyboardState.html"> THREEx.KeyboardState.js </a> <a class="source" href="THREEx.LogoTurtle.html"> THREEx.LogoTurtle.js </a> <a class="source" href="THREEx.PlasmaShader.html"> THREEx.PlasmaShader.js </a> <a class="source" href="THREEx.SkyMap.html"> THREEx.SkyMap.js </a> <a class="source" href="THREEx.WindowResize.html"> THREEx.WindowResize.js </a> <a class="source" href="THREEx.glCapability.html"> THREEx.glCapability.js </a> <a class="source" href="THREEx.requestAnimationFrame.html"> THREEx.requestAnimationFrame.js </a> <a class="source" href="THREEx.screenshot.html"> THREEx.screenshot.js </a> <a class="source" href="threex.embedded.html"> threex.embedded.js </a> </div> </div> </div> <table cellpadding="0" cellspacing="0"> <thead> <tr> <th class="docs"> <h1> THREEx.PlasmaShader.js </h1> </th> <th class="code"> </th> </tr> </thead> <tbody> <tr id="section-1"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-1">¶</a> </div> <p>define namespaces</p> </td> <td class="code"> <div class="highlight"><pre><span class="kd">var</span> <span class="nx">THREEx</span> <span class="o">=</span> <span class="nx">THREEx</span> <span class="o">||</span> <span class="p">{};</span>
<span class="nx">THREEx</span><span class="p">.</span><span class="nx">ShaderLib</span> <span class="o">=</span> <span class="nx">THREEx</span><span class="p">.</span><span class="nx">ShaderLib</span> <span class="o">||</span> <span class="p">{};</span>
<span class="nx">THREEx</span><span class="p">.</span><span class="nx">UniformsLib</span> <span class="o">=</span> <span class="nx">THREEx</span><span class="p">.</span><span class="nx">UniformsLib</span> <span class="o">||</span> <span class="p">{};</span>
<span class="nx">THREEx</span><span class="p">.</span><span class="nx">UniformsLib</span><span class="p">[</span><span class="s1">'plasma'</span><span class="p">]</span> <span class="o">=</span> <span class="p">{</span>
<span class="nx">time</span> <span class="o">:</span> <span class="p">{</span> <span class="nx">type</span> <span class="o">:</span> <span class="s2">"f"</span><span class="p">,</span> <span class="nx">value</span><span class="o">:</span> <span class="mf">0.0</span> <span class="p">},</span>
<span class="nx">scale</span> <span class="o">:</span> <span class="p">{</span> <span class="nx">type</span> <span class="o">:</span> <span class="s2">"f"</span><span class="p">,</span> <span class="nx">value</span><span class="o">:</span> <span class="mf">1.0</span> <span class="p">},</span>
<span class="nx">rotation</span><span class="o">:</span> <span class="p">{</span> <span class="nx">type</span> <span class="o">:</span> <span class="s2">"f"</span><span class="p">,</span> <span class="nx">value</span><span class="o">:</span> <span class="mf">0.0</span> <span class="p">},</span>
<span class="nx">opacity</span> <span class="o">:</span> <span class="p">{</span> <span class="nx">type</span> <span class="o">:</span> <span class="s2">"f"</span><span class="p">,</span> <span class="nx">value</span><span class="o">:</span> <span class="mf">1.0</span> <span class="p">},</span>
<span class="nx">c0</span> <span class="o">:</span> <span class="p">{</span> <span class="nx">type</span> <span class="o">:</span> <span class="s2">"f"</span><span class="p">,</span> <span class="nx">value</span><span class="o">:</span> <span class="mf">5.0</span> <span class="p">},</span>
<span class="nx">c1</span> <span class="o">:</span> <span class="p">{</span> <span class="nx">type</span> <span class="o">:</span> <span class="s2">"f"</span><span class="p">,</span> <span class="nx">value</span><span class="o">:</span> <span class="mf">3.0</span> <span class="p">},</span>
<span class="nx">c2</span> <span class="o">:</span> <span class="p">{</span> <span class="nx">type</span> <span class="o">:</span> <span class="s2">"f"</span><span class="p">,</span> <span class="nx">value</span><span class="o">:</span> <span class="mf">11.0</span> <span class="p">},</span>
<span class="nx">c3</span> <span class="o">:</span> <span class="p">{</span> <span class="nx">type</span> <span class="o">:</span> <span class="s2">"f"</span><span class="p">,</span> <span class="nx">value</span><span class="o">:</span> <span class="mf">7.0</span> <span class="p">},</span>
<span class="nx">c4</span> <span class="o">:</span> <span class="p">{</span> <span class="nx">type</span> <span class="o">:</span> <span class="s2">"f"</span><span class="p">,</span> <span class="nx">value</span><span class="o">:</span> <span class="mf">9.0</span> <span class="p">},</span>
<span class="nx">c5</span> <span class="o">:</span> <span class="p">{</span> <span class="nx">type</span> <span class="o">:</span> <span class="s2">"f"</span><span class="p">,</span> <span class="nx">value</span><span class="o">:</span> <span class="mf">3.0</span> <span class="p">}</span>
<span class="p">};</span>
<span class="nx">THREEx</span><span class="p">.</span><span class="nx">ShaderLib</span><span class="p">[</span><span class="s1">'plasma'</span><span class="p">]</span> <span class="o">=</span> <span class="p">{</span>
<span class="nx">vertexShader</span><span class="o">:</span> <span class="p">[</span>
<span class="s2">"#ifdef GL_ES"</span><span class="p">,</span>
<span class="s2">"precision highp float;"</span><span class="p">,</span>
<span class="s2">"#endif"</span><span class="p">,</span>
<span class="s2">"varying vec2 vUv;"</span><span class="p">,</span>
<span class="s2">"void main(){"</span><span class="p">,</span>
<span class="s2">"vUv = uv;"</span><span class="p">,</span>
<span class="s2">"gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);"</span><span class="p">,</span>
<span class="s2">"}"</span>
<span class="p">].</span><span class="nx">join</span><span class="p">(</span> <span class="s2">"\n"</span> <span class="p">),</span>
<span class="nx">fragmentShader</span><span class="o">:</span> <span class="p">[</span>
<span class="s2">"#ifdef GL_ES"</span><span class="p">,</span>
<span class="s2">"precision highp float;"</span><span class="p">,</span>
<span class="s2">"#endif"</span><span class="p">,</span>
<span class="s2">"varying vec2 vUv;"</span><span class="p">,</span>
<span class="s2">"uniform float time;"</span><span class="p">,</span>
<span class="s2">"uniform float scale;"</span><span class="p">,</span>
<span class="s2">"uniform float rotation;"</span><span class="p">,</span>
<span class="s2">"uniform float opacity;"</span><span class="p">,</span>
<span class="s2">"uniform float c0, c1, c2, c3, c4, c5;"</span><span class="p">,</span></pre></div> </td> </tr> <tr id="section-2"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-2">¶</a> </div> <p>todo zoom and rotation of vec2 point</p> </td> <td class="code"> <div class="highlight"><pre> <span class="s2">"vec2 rotoZoom(const vec2 point, const float scale, const float rotation){"</span><span class="p">,</span>
<span class="s2">"vec2 tmp;"</span><span class="p">,</span>
<span class="s2">"tmp.x = point.x * cos(rotation) - point.y * sin(rotation);"</span><span class="p">,</span>
<span class="s2">"tmp.y = point.x * sin(rotation) + point.y * cos(rotation);"</span><span class="p">,</span>
<span class="s2">"tmp = tmp * scale;"</span><span class="p">,</span>
<span class="s2">"return tmp;"</span><span class="p">,</span>
<span class="s2">"}"</span><span class="p">,</span>
</pre></div> </td> </tr> <tr id="section-3"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-3">¶</a> </div> <p>based on THREE.Color.setHSV()
based on Mads Elvheim / Madsy http://code.google.com/p/opengl3-freenode/wiki/ColorSpaceConversions</p> </td> <td class="code"> <div class="highlight"><pre> <span class="s2">"vec3 HSVtoRGB(const vec3 color){"</span><span class="p">,</span>
<span class="s2">"float h = color.r;"</span><span class="p">,</span>
<span class="s2">"float s = color.g;"</span><span class="p">,</span>
<span class="s2">"float v = color.b;"</span><span class="p">,</span>
<span class="s2">"float i = floor(h * 6.0);"</span><span class="p">,</span>
<span class="s2">"float f = (h * 6.0) - i;"</span><span class="p">,</span>
<span class="s2">"float p = v * (1.0 - s);"</span><span class="p">,</span>
<span class="s2">"float q = v * (1.0 - f * s);"</span><span class="p">,</span>
<span class="s2">"float t = v * (1.0 - (1.0 - f) * s);"</span><span class="p">,</span>
<span class="s2">"vec3 result;"</span><span class="p">,</span>
<span class="s2">"if( i < 1.0 ) result = vec3(v,t,p);"</span><span class="p">,</span>
<span class="s2">"else if( i < 2.0 ) result = vec3(q,v,p);"</span><span class="p">,</span>
<span class="s2">"else if( i < 3.0 ) result = vec3(p,v,t);"</span><span class="p">,</span>
<span class="s2">"else if( i < 4.0 ) result = vec3(p,q,v);"</span><span class="p">,</span>
<span class="s2">"else if( i < 5.0 ) result = vec3(t,p,v);"</span><span class="p">,</span>
<span class="s2">"else if( i < 6.0 ) result = vec3(v,p,q);"</span><span class="p">,</span>
<span class="s2">"else result = vec3(v,t,p);"</span><span class="p">,</span>
<span class="s2">"return result;"</span><span class="p">,</span>
<span class="s2">"}"</span><span class="p">,</span></pre></div> </td> </tr> <tr id="section-4"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-4">¶</a> </div> <p>default value</p> </td> <td class="code"> <div class="highlight"><pre> <span class="s2">"#ifndef ROTOZOOM"</span><span class="p">,</span>
<span class="s2">"#define ROTOZOOM 1"</span><span class="p">,</span>
<span class="s2">"#endif"</span><span class="p">,</span>
<span class="s2">"#ifndef USEHSV"</span><span class="p">,</span>
<span class="s2">"#define USEHSV 1"</span><span class="p">,</span>
<span class="s2">"#endif"</span><span class="p">,</span>
<span class="s2">"void main(){"</span><span class="p">,</span>
<span class="s2">"vec2 p = -1.0 + 2.0 * vUv;"</span><span class="p">,</span>
<span class="s2">"#if ROTOZOOM"</span><span class="p">,</span>
<span class="s2">"p = rotoZoom(p, scale, rotation);"</span><span class="p">,</span>
<span class="s2">"#endif"</span><span class="p">,</span>
<span class="s2">"float cossin1 = cos(p.x*c0+sin(time*1.3)) - sin(p.y*c3-cos(time)) + sin(time);"</span><span class="p">,</span>
<span class="s2">"float cossin2 = cos(p.y*c1+cos(c1*time/c4)) * sin(p.x*c4*sin(time)) - cos(time);"</span><span class="p">,</span>
<span class="s2">"float cossin3 = cos(p.x*c2+sin(c2*time/c5)) + sin(p.y*c5+cos(time)) + cos(time);"</span><span class="p">,</span></pre></div> </td> </tr> <tr id="section-5"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-5">¶</a> </div> <p>"vec3 color = vec3(abs(cossin1<em>sin(p.x)), cossin2</em>sin(p.y), cossin3*sin(p.x));",</p> </td> <td class="code"> <div class="highlight"><pre> <span class="s2">"vec3 color = vec3(abs(cossin1*sin(p.x)), 0.6 - 0.4* abs(cossin2*sin(p.y)), 0.5 - 0.3*(cossin3*sin(p.x)));"</span><span class="p">,</span>
<span class="s2">"#if USEHSV"</span><span class="p">,</span>
<span class="s2">"color = HSVtoRGB(color);"</span><span class="p">,</span>
<span class="s2">"#endif"</span><span class="p">,</span>
<span class="s2">"gl_FragColor = vec4(color, opacity);"</span><span class="p">,</span></pre></div> </td> </tr> <tr id="section-6"> <td class="docs"> <div class="pilwrap"> <a class="pilcrow" href="#section-6">¶</a> </div> <p>"gl_FragColor = vec4(cossin1<em>sin(p.x), cossin2</em>sin(p.y), cossin3*sin(p.x), opacity);",</p> </td> <td class="code"> <div class="highlight"><pre> <span class="s2">"}"</span>
<span class="p">].</span><span class="nx">join</span><span class="p">(</span> <span class="s2">"\n"</span> <span class="p">)</span>
<span class="p">};</span>
</pre></div> </td> </tr> </tbody> </table> </div> </body> </html> | {
"pile_set_name": "Github"
} |
<?xml version="1.0"?>
<component name="org.nuxeo.ecm.core.io.avro.tests" version="1.0.0">
<extension target="org.nuxeo.runtime.avro" point="replacement">
<replacement forbidden="__" replacement="____" priority="400" />
</extension>
</component>
| {
"pile_set_name": "Github"
} |
python-digitalocean
===================
This library provides easy access to Digital Ocean APIs to deploy
droplets, images and more.
|image0|
| |image1|
| |image2|
| |image3|
How to install
--------------
You can install python-digitalocean using **pip**
::
pip install -U python-digitalocean
or via sources:
::
python setup.py install
Features
--------
python-digitalocean support all the features provided via
digitalocean.com APIs, such as:
- Get user's Droplets
- Get user's Images (Snapshot and Backups)
- Get public Images
- Get Droplet's event status
- Create and Remove a Droplet
- Resize a Droplet
- Shutdown, restart and boot a Droplet
- Power off, power on and "power cycle" a Droplet
- Perform Snapshot
- Enable/Disable automatic Backups
- Restore root password of a Droplet
Examples
---------
Listing the droplets
~~~~~~~~~~~~~~~~~~~~
This example shows how to list all the active droplets:
.. code:: python
import digitalocean
manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
print(manager.get_all_droplets())
Shutdown all droplets
~~~~~~~~~~~~~~~~~~~~~
This example shows how to shutdown all the active droplets:
.. code:: python
import digitalocean
manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
my_droplets = manager.get_all_droplets()
for droplet in my_droplets:
droplet.shutdown()
Creating a Droplet and checking its status
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This example shows how to create a droplet and how to check its status
.. code:: python
import digitalocean
droplet = digitalocean.Droplet(token="secretspecialuniquesnowflake",
name='Example',
region='nyc2', # New York 2
image='ubuntu-14-04-x64', # Ubuntu 14.04 x64
size_slug='512mb', # 512MB
backups=True)
droplet.create()
Checking the status of the droplet
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. code:: python
actions = droplet.get_actions()
for action in actions:
action.load()
# Once it shows complete, droplet is up and running
print action.status
Add SSHKey into DigitalOcean Account
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. code:: python
from digitalocean import SSHKey
user_ssh_key = open('/home/<$USER>/.ssh/id_rsa.pub').read()
key = SSHKey(token='secretspecialuniquesnowflake',
name='uniquehostname',
public_key=user_ssh_key)
key.create()
Creating a new droplet with all your SSH keys
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. code:: python
manager = digitalocean.Manager(token="secretspecialuniquesnowflake")
keys = manager.get_all_sshkeys()
droplet = digitalocean.Droplet(token="secretspecialuniquesnowflake",
name='DropletWithSSHKeys',
region='ams3', # Amster
image='ubuntu-14-04-x64', # Ubuntu 14.04 x64
size_slug='512mb', # 512MB
ssh_keys=keys, #Automatic conversion
backups=False)
droplet.create()
Testing
-------
Test using Docker
~~~~~~~~~~~~~~~~~
To test this python-digitalocean you can use
`docker <https://www.docker.com>`__ to have a **clean environment
automatically**. First you have to build the container by running in
your shell on the repository directory:
::
docker build -t "pdo-tests" .
Then you can run all the tests (for both python 2 and python 3)
::
docker run pdo-tests
**Note**: This will use Ubuntu 14.04 as base and use your repository to
run tests. So every time you edit some files, please run these commands
to perform tests on your changes.
Testing using pytest manually
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Use `pytest <http://pytest.org/>`__ to perform testing. It is
recommended to use a dedicated virtualenv to perform tests, using these
commands:
::
$ virtualenv /tmp/digitalocean_env
$ source /tmp/digitalocean_env/bin/activate
$ pip install -r requirements.txt
To run all the tests manually use py.test command:
::
$ python -m pytest
Links
-----
- GitHub: https://github.com/koalalorenzo/python-digitalocean
- PyPI page: https://pypi.python.org/pypi/python-digitalocean/
- Author Website:
`http://who.is.lorenzo.setale.me/? <http://setale.me/>`__
- Author Blog: http://blog.setale.me/
.. |image0| image:: https://travis-ci.org/koalalorenzo/python-digitalocean.svg
:target: https://travis-ci.org/koalalorenzo/python-digitalocean
.. |image1| image:: https://img.shields.io/github/forks/badges/shields.svg?style=social&label=Fork
:target: https://travis-ci.org/koalalorenzo/python-digitalocean
.. |image2| image:: https://img.shields.io/github/stars/badges/shields.svg?style=social&label=Star
:target: https://travis-ci.org/koalalorenzo/python-digitalocean
.. |image3| image:: https://img.shields.io/github/watchers/badges/shields.svg?style=social&label=Watch
:target: https://travis-ci.org/koalalorenzo/python-digitalocean
| {
"pile_set_name": "Github"
} |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.models.extensions;
import com.microsoft.graph.serializer.ISerializer;
import com.microsoft.graph.serializer.IJsonBackedObject;
import com.microsoft.graph.serializer.AdditionalDataManager;
import java.util.EnumSet;
import com.microsoft.graph.models.generated.ScheduleEntityTheme;
import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Shift Activity.
*/
public class ShiftActivity implements IJsonBackedObject {
@SerializedName("@odata.type")
@Expose
public String oDataType;
private transient AdditionalDataManager additionalDataManager = new AdditionalDataManager(this);
@Override
public final AdditionalDataManager additionalDataManager() {
return additionalDataManager;
}
/**
* The Code.
* Customer defined code for the shiftActivity. Required.
*/
@SerializedName("code")
@Expose
public String code;
/**
* The Display Name.
* The name of the shiftActivity. Required.
*/
@SerializedName("displayName")
@Expose
public String displayName;
/**
* The End Date Time.
* The end date and time for the shiftActivity. The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 would look like this: '2014-01-01T00:00:00Z'. Required.
*/
@SerializedName("endDateTime")
@Expose
public java.util.Calendar endDateTime;
/**
* The Is Paid.
* Indicates whether the microsoft.graph.user should be paid for the activity during their shift. Required.
*/
@SerializedName("isPaid")
@Expose
public Boolean isPaid;
/**
* The Start Date Time.
* The start date and time for the shiftActivity. The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 would look like this: '2014-01-01T00:00:00Z'. Required.
*/
@SerializedName("startDateTime")
@Expose
public java.util.Calendar startDateTime;
/**
* The Theme.
*
*/
@SerializedName("theme")
@Expose
public ScheduleEntityTheme theme;
/**
* The raw representation of this class
*/
private JsonObject rawObject;
/**
* The serializer
*/
private ISerializer serializer;
/**
* Gets the raw representation of this class
*
* @return the raw representation of this class
*/
public JsonObject getRawObject() {
return rawObject;
}
/**
* Gets serializer
*
* @return the serializer
*/
protected ISerializer getSerializer() {
return serializer;
}
/**
* Sets the raw JSON object
*
* @param serializer the serializer
* @param json the JSON object to set this object to
*/
public void setRawObject(final ISerializer serializer, final JsonObject json) {
this.serializer = serializer;
rawObject = json;
}
}
| {
"pile_set_name": "Github"
} |
#####################
SFML Game Development
License
#####################
This file describes the licenses for material accompanying the book "SFML Game Development".
Copyright (c) 2013 Artur Moreira, Henrik Vogelius Hansson, Jan Haller
===========
Source code
===========
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
excluding commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. Redistributions may not be sold, nor may they be used in a commercial
product or activity.
4. This notice may not be removed or altered from any source distribution.
======
Assets
======
Assets include: Images, sound effects and music, but not fonts. These assets
are licensed under Creative Commons BY-NC-SA:
http://creativecommons.org/licenses/by-nc-sa/3.0/
| {
"pile_set_name": "Github"
} |
using UnityEngine;
using UnityEngine.UI;
namespace uREPL
{
public class GameObjectComponentItem : MonoBehaviour
{
[HideInInspector]
public Component component;
[HideInInspector]
public System.Type type;
public Text nameText;
public Text detailText;
public Button button;
public string title
{
get { return nameText.text; }
set { nameText.text = value; }
}
public string detail
{
get { return detailText.text; }
set { detailText.text = value; }
}
void Start()
{
button.onClick.AddListener(OnClick);
}
void Destroy()
{
button.onClick.RemoveListener(OnClick);
}
void OnClick()
{
Inspector.Inspect(component, type);
}
}
}
| {
"pile_set_name": "Github"
} |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.broker;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ProducerBrokerExchangeTest {
@Test
public void testGetPercentageBlockedHandlesDivideByZero(){
ProducerBrokerExchange producerBrokerExchange = new ProducerBrokerExchange();
producerBrokerExchange.getPercentageBlocked();
}
@Test
public void testGetPercentageBlockedNonZero(){
ProducerBrokerExchange producerBrokerExchange = new ProducerBrokerExchange();
producerBrokerExchange.blockingOnFlowControl(true);
producerBrokerExchange.incrementSend();
assertEquals(100.0, producerBrokerExchange.getPercentageBlocked(), 0);
}
}
| {
"pile_set_name": "Github"
} |
<?php
namespace DeepCopy\Matcher\Doctrine;
use DeepCopy\Matcher\Matcher;
use Doctrine\Common\Persistence\Proxy;
/**
* @final
*/
class DoctrineProxyMatcher implements Matcher
{
/**
* Matches a Doctrine Proxy class.
*
* {@inheritdoc}
*/
public function matches($object, $property)
{
return $object instanceof Proxy;
}
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* ALIPAY API: alipay.offline.material.image.upload request
*
* @author auto create
*
* @since 1.0, 2018-05-09 13:39:20
*/
namespace Alipay\Request;
class AlipayOfflineMaterialImageUploadRequest extends AbstractAlipayRequest
{
/**
* 图片/视频二进制内容,图片/视频大小不能超过5M
**/
private $imageContent;
/**
* 图片/视频名称
**/
private $imageName;
/**
* 用于显示指定图片/视频所属的partnerId(支付宝内部使用,外部商户无需填写此字段)
**/
private $imagePid;
/**
* 图片/视频格式
**/
private $imageType;
public function setImageContent($imageContent)
{
$this->imageContent = $imageContent;
$this->apiParams['image_content'] = $imageContent;
}
public function getImageContent()
{
return $this->imageContent;
}
public function setImageName($imageName)
{
$this->imageName = $imageName;
$this->apiParams['image_name'] = $imageName;
}
public function getImageName()
{
return $this->imageName;
}
public function setImagePid($imagePid)
{
$this->imagePid = $imagePid;
$this->apiParams['image_pid'] = $imagePid;
}
public function getImagePid()
{
return $this->imagePid;
}
public function setImageType($imageType)
{
$this->imageType = $imageType;
$this->apiParams['image_type'] = $imageType;
}
public function getImageType()
{
return $this->imageType;
}
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.14"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>FabGL: DS3231.h File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(document).ready(initResizable);
/* @license-end */</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">FabGL
</div>
<div id="projectbrief">ESP32 Display Controller and Graphics Library</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.14 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
var searchBox = new SearchBox("searchBox", "search",false,'Search');
/* @license-end */
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
/* @license-end */</script>
<div id="main-nav"></div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(document).ready(function(){initNavTree('_d_s3231_8h.html','');});
/* @license-end */
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="summary">
<a href="#nested-classes">Classes</a> </div>
<div class="headertitle">
<div class="title">DS3231.h File Reference</div> </div>
</div><!--header-->
<div class="contents">
<p>This file contains the DS3231 (Real Time Clock) device driver.
<a href="#details">More...</a></p>
<div class="textblock"><code>#include <stdint.h></code><br />
<code>#include <stddef.h></code><br />
<code>#include "freertos/FreeRTOS.h"</code><br />
<code>#include "<a class="el" href="fabglconf_8h_source.html">fabglconf.h</a>"</code><br />
<code>#include "<a class="el" href="fabutils_8h_source.html">fabutils.h</a>"</code><br />
<code>#include "<a class="el" href="tsi2c_8h_source.html">comdrivers/tsi2c.h</a>"</code><br />
</div><div class="textblock"><div class="dynheader">
Include dependency graph for DS3231.h:</div>
<div class="dyncontent">
<div class="center"><img src="_d_s3231_8h__incl.png" border="0" usemap="#_d_s3231_8h" alt=""/></div>
<map name="_d_s3231_8h" id="_d_s3231_8h">
<area shape="rect" id="node5" href="fabglconf_8h.html" title="This file contains FabGL library configuration settings, like number of supported colors..." alt="" coords="878,152,965,177"/>
<area shape="rect" id="node7" href="fabutils_8h.html" title="This file contains some utility classes and functions. " alt="" coords="156,79,231,104"/>
<area shape="rect" id="node9" href="tsi2c_8h.html" title="This file contains fabgl::I2C definition. " alt="" coords="457,79,586,104"/>
</map>
</div>
</div><div class="textblock"><div class="dynheader">
This graph shows which files directly or indirectly include this file:</div>
<div class="dyncontent">
<div class="center"><img src="_d_s3231_8h__dep__incl.png" border="0" usemap="#_d_s3231_8hdep" alt=""/></div>
<map name="_d_s3231_8hdep" id="_d_s3231_8hdep">
<area shape="rect" id="node2" href="fabgl_8h.html" title="This file is the all in one include file. Application can just include this file to use FabGL library..." alt="" coords="15,79,76,104"/>
</map>
</div>
</div>
<p><a href="_d_s3231_8h_source.html">Go to the source code of this file.</a></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="nested-classes"></a>
Classes</h2></td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct  </td><td class="memItemRight" valign="bottom"><a class="el" href="structfabgl_1_1_date_time.html">fabgl::DateTime</a></td></tr>
<tr class="memdesc:"><td class="mdescLeft"> </td><td class="mdescRight">Represents date and time. <a href="structfabgl_1_1_date_time.html#details">More...</a><br /></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class  </td><td class="memItemRight" valign="bottom"><a class="el" href="classfabgl_1_1_d_s3231.html">fabgl::DS3231</a></td></tr>
<tr class="memdesc:"><td class="mdescLeft"> </td><td class="mdescRight"><a class="el" href="classfabgl_1_1_d_s3231.html" title="DS3231 Real Time Clock driver. ">DS3231</a> Real Time Clock driver. <a href="classfabgl_1_1_d_s3231.html#details">More...</a><br /></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><p>This file contains the DS3231 (Real Time Clock) device driver. </p>
</div></div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="navelem"><a class="el" href="dir_68267d1309a1af8e8297ef4c3efbcdba.html">src</a></li><li class="navelem"><a class="el" href="dir_82e8a5453e51b0b6168db3257bd0eaab.html">devdrivers</a></li><li class="navelem"><a class="el" href="_d_s3231_8h.html">DS3231.h</a></li>
<li class="footer">Generated by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.14 </li>
</ul>
</div>
</body>
</html>
| {
"pile_set_name": "Github"
} |
/*
* 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.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*/
package org.topbraid.shacl.validation.sparql;
import org.apache.jena.rdf.model.Resource;
import org.topbraid.shacl.model.SHParameterizableTarget;
import org.topbraid.shacl.targets.CustomTargetLanguage;
import org.topbraid.shacl.targets.Target;
import org.topbraid.shacl.util.ExecutionPlatform;
import org.topbraid.shacl.vocabulary.SH;
public class SPARQLTargetLanguage implements CustomTargetLanguage {
@Override
public boolean canHandle(Resource executable) {
return executable.hasProperty(SH.select) && ExecutionPlatform.canExecute(executable);
}
@Override
public Target createTarget(Resource executable, SHParameterizableTarget parameterizableTarget) {
return new SPARQLTarget(executable, parameterizableTarget);
}
}
| {
"pile_set_name": "Github"
} |
1.2.0 / 2016-06-01
==================
* Add `combine` option to combine overlapping ranges
1.1.0 / 2016-05-13
==================
* Fix incorrectly returning -1 when there is at least one valid range
* perf: remove internal function
1.0.3 / 2015-10-29
==================
* perf: enable strict mode
1.0.2 / 2014-09-08
==================
* Support Node.js 0.6
1.0.1 / 2014-09-07
==================
* Move repository to jshttp
1.0.0 / 2013-12-11
==================
* Add repository to package.json
* Add MIT license
0.0.4 / 2012-06-17
==================
* Change ret -1 for unsatisfiable and -2 when invalid
0.0.3 / 2012-06-17
==================
* Fix last-byte-pos default to len - 1
0.0.2 / 2012-06-14
==================
* Add `.type`
0.0.1 / 2012-06-11
==================
* Initial release
| {
"pile_set_name": "Github"
} |
! parizek_qmtp12.scl
!
12-tone quasi-meantone tuning with 1/9 Pyth. comma as basic tempering unit (F...A#)
12
!
77.19166
196.09000
268.06832
8192/6561
505.86500
583.05666
699.34833
771.32665
890.22500
967.41665
1083.70833
2/1
| {
"pile_set_name": "Github"
} |
/******************************************************************************
* Copyright (c) 2011, Duane Merrill. All rights reserved.
* Copyright (c) 2011-2018, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the NVIDIA CORPORATION nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************/
/**
* \file
* cub::AgentRle implements a stateful abstraction of CUDA thread blocks for participating in device-wide run-length-encode.
*/
#pragma once
#include <iterator>
#include "single_pass_scan_operators.cuh"
#include "../block/block_load.cuh"
#include "../block/block_store.cuh"
#include "../block/block_scan.cuh"
#include "../block/block_exchange.cuh"
#include "../block/block_discontinuity.cuh"
#include "../grid/grid_queue.cuh"
#include "../iterator/cache_modified_input_iterator.cuh"
#include "../iterator/constant_input_iterator.cuh"
#include "../util_namespace.cuh"
/// Optional outer namespace(s)
CUB_NS_PREFIX
/// CUB namespace
namespace cub {
/******************************************************************************
* Tuning policy types
******************************************************************************/
/**
* Parameterizable tuning policy type for AgentRle
*/
template <
int _BLOCK_THREADS, ///< Threads per thread block
int _ITEMS_PER_THREAD, ///< Items per thread (per tile of input)
BlockLoadAlgorithm _LOAD_ALGORITHM, ///< The BlockLoad algorithm to use
CacheLoadModifier _LOAD_MODIFIER, ///< Cache load modifier for reading input elements
bool _STORE_WARP_TIME_SLICING, ///< Whether or not only one warp's worth of shared memory should be allocated and time-sliced among block-warps during any store-related data transpositions (versus each warp having its own storage)
BlockScanAlgorithm _SCAN_ALGORITHM> ///< The BlockScan algorithm to use
struct AgentRlePolicy
{
enum
{
BLOCK_THREADS = _BLOCK_THREADS, ///< Threads per thread block
ITEMS_PER_THREAD = _ITEMS_PER_THREAD, ///< Items per thread (per tile of input)
STORE_WARP_TIME_SLICING = _STORE_WARP_TIME_SLICING, ///< Whether or not only one warp's worth of shared memory should be allocated and time-sliced among block-warps during any store-related data transpositions (versus each warp having its own storage)
};
static const BlockLoadAlgorithm LOAD_ALGORITHM = _LOAD_ALGORITHM; ///< The BlockLoad algorithm to use
static const CacheLoadModifier LOAD_MODIFIER = _LOAD_MODIFIER; ///< Cache load modifier for reading input elements
static const BlockScanAlgorithm SCAN_ALGORITHM = _SCAN_ALGORITHM; ///< The BlockScan algorithm to use
};
/******************************************************************************
* Thread block abstractions
******************************************************************************/
/**
* \brief AgentRle implements a stateful abstraction of CUDA thread blocks for participating in device-wide run-length-encode
*/
template <
typename AgentRlePolicyT, ///< Parameterized AgentRlePolicyT tuning policy type
typename InputIteratorT, ///< Random-access input iterator type for data
typename OffsetsOutputIteratorT, ///< Random-access output iterator type for offset values
typename LengthsOutputIteratorT, ///< Random-access output iterator type for length values
typename EqualityOpT, ///< T equality operator type
typename OffsetT> ///< Signed integer type for global offsets
struct AgentRle
{
//---------------------------------------------------------------------
// Types and constants
//---------------------------------------------------------------------
/// The input value type
typedef typename std::iterator_traits<InputIteratorT>::value_type T;
/// The lengths output value type
typedef typename If<(Equals<typename std::iterator_traits<LengthsOutputIteratorT>::value_type, void>::VALUE), // LengthT = (if output iterator's value type is void) ?
OffsetT, // ... then the OffsetT type,
typename std::iterator_traits<LengthsOutputIteratorT>::value_type>::Type LengthT; // ... else the output iterator's value type
/// Tuple type for scanning (pairs run-length and run-index)
typedef KeyValuePair<OffsetT, LengthT> LengthOffsetPair;
/// Tile status descriptor interface type
typedef ReduceByKeyScanTileState<LengthT, OffsetT> ScanTileStateT;
// Constants
enum
{
WARP_THREADS = CUB_WARP_THREADS(PTX_ARCH),
BLOCK_THREADS = AgentRlePolicyT::BLOCK_THREADS,
ITEMS_PER_THREAD = AgentRlePolicyT::ITEMS_PER_THREAD,
WARP_ITEMS = WARP_THREADS * ITEMS_PER_THREAD,
TILE_ITEMS = BLOCK_THREADS * ITEMS_PER_THREAD,
WARPS = (BLOCK_THREADS + WARP_THREADS - 1) / WARP_THREADS,
/// Whether or not to sync after loading data
SYNC_AFTER_LOAD = (AgentRlePolicyT::LOAD_ALGORITHM != BLOCK_LOAD_DIRECT),
/// Whether or not only one warp's worth of shared memory should be allocated and time-sliced among block-warps during any store-related data transpositions (versus each warp having its own storage)
STORE_WARP_TIME_SLICING = AgentRlePolicyT::STORE_WARP_TIME_SLICING,
ACTIVE_EXCHANGE_WARPS = (STORE_WARP_TIME_SLICING) ? 1 : WARPS,
};
/**
* Special operator that signals all out-of-bounds items are not equal to everything else,
* forcing both (1) the last item to be tail-flagged and (2) all oob items to be marked
* trivial.
*/
template <bool LAST_TILE>
struct OobInequalityOp
{
OffsetT num_remaining;
EqualityOpT equality_op;
__device__ __forceinline__ OobInequalityOp(
OffsetT num_remaining,
EqualityOpT equality_op)
:
num_remaining(num_remaining),
equality_op(equality_op)
{}
template <typename Index>
__host__ __device__ __forceinline__ bool operator()(T first, T second, Index idx)
{
if (!LAST_TILE || (idx < num_remaining))
return !equality_op(first, second);
else
return true;
}
};
// Cache-modified Input iterator wrapper type (for applying cache modifier) for data
typedef typename If<IsPointer<InputIteratorT>::VALUE,
CacheModifiedInputIterator<AgentRlePolicyT::LOAD_MODIFIER, T, OffsetT>, // Wrap the native input pointer with CacheModifiedVLengthnputIterator
InputIteratorT>::Type // Directly use the supplied input iterator type
WrappedInputIteratorT;
// Parameterized BlockLoad type for data
typedef BlockLoad<
T,
AgentRlePolicyT::BLOCK_THREADS,
AgentRlePolicyT::ITEMS_PER_THREAD,
AgentRlePolicyT::LOAD_ALGORITHM>
BlockLoadT;
// Parameterized BlockDiscontinuity type for data
typedef BlockDiscontinuity<T, BLOCK_THREADS> BlockDiscontinuityT;
// Parameterized WarpScan type
typedef WarpScan<LengthOffsetPair> WarpScanPairs;
// Reduce-length-by-run scan operator
typedef ReduceBySegmentOp<cub::Sum> ReduceBySegmentOpT;
// Callback type for obtaining tile prefix during block scan
typedef TilePrefixCallbackOp<
LengthOffsetPair,
ReduceBySegmentOpT,
ScanTileStateT>
TilePrefixCallbackOpT;
// Warp exchange types
typedef WarpExchange<LengthOffsetPair, ITEMS_PER_THREAD> WarpExchangePairs;
typedef typename If<STORE_WARP_TIME_SLICING, typename WarpExchangePairs::TempStorage, NullType>::Type WarpExchangePairsStorage;
typedef WarpExchange<OffsetT, ITEMS_PER_THREAD> WarpExchangeOffsets;
typedef WarpExchange<LengthT, ITEMS_PER_THREAD> WarpExchangeLengths;
typedef LengthOffsetPair WarpAggregates[WARPS];
// Shared memory type for this thread block
struct _TempStorage
{
// Aliasable storage layout
union Aliasable
{
struct
{
typename BlockDiscontinuityT::TempStorage discontinuity; // Smem needed for discontinuity detection
typename WarpScanPairs::TempStorage warp_scan[WARPS]; // Smem needed for warp-synchronous scans
Uninitialized<LengthOffsetPair[WARPS]> warp_aggregates; // Smem needed for sharing warp-wide aggregates
typename TilePrefixCallbackOpT::TempStorage prefix; // Smem needed for cooperative prefix callback
};
// Smem needed for input loading
typename BlockLoadT::TempStorage load;
// Aliasable layout needed for two-phase scatter
union ScatterAliasable
{
unsigned long long align;
WarpExchangePairsStorage exchange_pairs[ACTIVE_EXCHANGE_WARPS];
typename WarpExchangeOffsets::TempStorage exchange_offsets[ACTIVE_EXCHANGE_WARPS];
typename WarpExchangeLengths::TempStorage exchange_lengths[ACTIVE_EXCHANGE_WARPS];
} scatter_aliasable;
} aliasable;
OffsetT tile_idx; // Shared tile index
LengthOffsetPair tile_inclusive; // Inclusive tile prefix
LengthOffsetPair tile_exclusive; // Exclusive tile prefix
};
// Alias wrapper allowing storage to be unioned
struct TempStorage : Uninitialized<_TempStorage> {};
//---------------------------------------------------------------------
// Per-thread fields
//---------------------------------------------------------------------
_TempStorage& temp_storage; ///< Reference to temp_storage
WrappedInputIteratorT d_in; ///< Pointer to input sequence of data items
OffsetsOutputIteratorT d_offsets_out; ///< Input run offsets
LengthsOutputIteratorT d_lengths_out; ///< Output run lengths
EqualityOpT equality_op; ///< T equality operator
ReduceBySegmentOpT scan_op; ///< Reduce-length-by-flag scan operator
OffsetT num_items; ///< Total number of input items
//---------------------------------------------------------------------
// Constructor
//---------------------------------------------------------------------
// Constructor
__device__ __forceinline__
AgentRle(
TempStorage &temp_storage, ///< [in] Reference to temp_storage
InputIteratorT d_in, ///< [in] Pointer to input sequence of data items
OffsetsOutputIteratorT d_offsets_out, ///< [out] Pointer to output sequence of run offsets
LengthsOutputIteratorT d_lengths_out, ///< [out] Pointer to output sequence of run lengths
EqualityOpT equality_op, ///< [in] T equality operator
OffsetT num_items) ///< [in] Total number of input items
:
temp_storage(temp_storage.Alias()),
d_in(d_in),
d_offsets_out(d_offsets_out),
d_lengths_out(d_lengths_out),
equality_op(equality_op),
scan_op(cub::Sum()),
num_items(num_items)
{}
//---------------------------------------------------------------------
// Utility methods for initializing the selections
//---------------------------------------------------------------------
template <bool FIRST_TILE, bool LAST_TILE>
__device__ __forceinline__ void InitializeSelections(
OffsetT tile_offset,
OffsetT num_remaining,
T (&items)[ITEMS_PER_THREAD],
LengthOffsetPair (&lengths_and_num_runs)[ITEMS_PER_THREAD])
{
bool head_flags[ITEMS_PER_THREAD];
bool tail_flags[ITEMS_PER_THREAD];
OobInequalityOp<LAST_TILE> inequality_op(num_remaining, equality_op);
if (FIRST_TILE && LAST_TILE)
{
// First-and-last-tile always head-flags the first item and tail-flags the last item
BlockDiscontinuityT(temp_storage.aliasable.discontinuity).FlagHeadsAndTails(
head_flags, tail_flags, items, inequality_op);
}
else if (FIRST_TILE)
{
// First-tile always head-flags the first item
// Get the first item from the next tile
T tile_successor_item;
if (threadIdx.x == BLOCK_THREADS - 1)
tile_successor_item = d_in[tile_offset + TILE_ITEMS];
BlockDiscontinuityT(temp_storage.aliasable.discontinuity).FlagHeadsAndTails(
head_flags, tail_flags, tile_successor_item, items, inequality_op);
}
else if (LAST_TILE)
{
// Last-tile always flags the last item
// Get the last item from the previous tile
T tile_predecessor_item;
if (threadIdx.x == 0)
tile_predecessor_item = d_in[tile_offset - 1];
BlockDiscontinuityT(temp_storage.aliasable.discontinuity).FlagHeadsAndTails(
head_flags, tile_predecessor_item, tail_flags, items, inequality_op);
}
else
{
// Get the first item from the next tile
T tile_successor_item;
if (threadIdx.x == BLOCK_THREADS - 1)
tile_successor_item = d_in[tile_offset + TILE_ITEMS];
// Get the last item from the previous tile
T tile_predecessor_item;
if (threadIdx.x == 0)
tile_predecessor_item = d_in[tile_offset - 1];
BlockDiscontinuityT(temp_storage.aliasable.discontinuity).FlagHeadsAndTails(
head_flags, tile_predecessor_item, tail_flags, tile_successor_item, items, inequality_op);
}
// Zip counts and runs
#pragma unroll
for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM)
{
lengths_and_num_runs[ITEM].key = head_flags[ITEM] && (!tail_flags[ITEM]);
lengths_and_num_runs[ITEM].value = ((!head_flags[ITEM]) || (!tail_flags[ITEM]));
}
}
//---------------------------------------------------------------------
// Scan utility methods
//---------------------------------------------------------------------
/**
* Scan of allocations
*/
__device__ __forceinline__ void WarpScanAllocations(
LengthOffsetPair &tile_aggregate,
LengthOffsetPair &warp_aggregate,
LengthOffsetPair &warp_exclusive_in_tile,
LengthOffsetPair &thread_exclusive_in_warp,
LengthOffsetPair (&lengths_and_num_runs)[ITEMS_PER_THREAD])
{
// Perform warpscans
unsigned int warp_id = ((WARPS == 1) ? 0 : threadIdx.x / WARP_THREADS);
int lane_id = LaneId();
LengthOffsetPair identity;
identity.key = 0;
identity.value = 0;
LengthOffsetPair thread_inclusive;
LengthOffsetPair thread_aggregate = internal::ThreadReduce(lengths_and_num_runs, scan_op);
WarpScanPairs(temp_storage.aliasable.warp_scan[warp_id]).Scan(
thread_aggregate,
thread_inclusive,
thread_exclusive_in_warp,
identity,
scan_op);
// Last lane in each warp shares its warp-aggregate
if (lane_id == WARP_THREADS - 1)
temp_storage.aliasable.warp_aggregates.Alias()[warp_id] = thread_inclusive;
CTA_SYNC();
// Accumulate total selected and the warp-wide prefix
warp_exclusive_in_tile = identity;
warp_aggregate = temp_storage.aliasable.warp_aggregates.Alias()[warp_id];
tile_aggregate = temp_storage.aliasable.warp_aggregates.Alias()[0];
#pragma unroll
for (int WARP = 1; WARP < WARPS; ++WARP)
{
if (warp_id == WARP)
warp_exclusive_in_tile = tile_aggregate;
tile_aggregate = scan_op(tile_aggregate, temp_storage.aliasable.warp_aggregates.Alias()[WARP]);
}
}
//---------------------------------------------------------------------
// Utility methods for scattering selections
//---------------------------------------------------------------------
/**
* Two-phase scatter, specialized for warp time-slicing
*/
template <bool FIRST_TILE>
__device__ __forceinline__ void ScatterTwoPhase(
OffsetT tile_num_runs_exclusive_in_global,
OffsetT warp_num_runs_aggregate,
OffsetT warp_num_runs_exclusive_in_tile,
OffsetT (&thread_num_runs_exclusive_in_warp)[ITEMS_PER_THREAD],
LengthOffsetPair (&lengths_and_offsets)[ITEMS_PER_THREAD],
Int2Type<true> is_warp_time_slice)
{
unsigned int warp_id = ((WARPS == 1) ? 0 : threadIdx.x / WARP_THREADS);
int lane_id = LaneId();
// Locally compact items within the warp (first warp)
if (warp_id == 0)
{
WarpExchangePairs(temp_storage.aliasable.scatter_aliasable.exchange_pairs[0]).ScatterToStriped(
lengths_and_offsets, thread_num_runs_exclusive_in_warp);
}
// Locally compact items within the warp (remaining warps)
#pragma unroll
for (int SLICE = 1; SLICE < WARPS; ++SLICE)
{
CTA_SYNC();
if (warp_id == SLICE)
{
WarpExchangePairs(temp_storage.aliasable.scatter_aliasable.exchange_pairs[0]).ScatterToStriped(
lengths_and_offsets, thread_num_runs_exclusive_in_warp);
}
}
// Global scatter
#pragma unroll
for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++)
{
if ((ITEM * WARP_THREADS) < warp_num_runs_aggregate - lane_id)
{
OffsetT item_offset =
tile_num_runs_exclusive_in_global +
warp_num_runs_exclusive_in_tile +
(ITEM * WARP_THREADS) + lane_id;
// Scatter offset
d_offsets_out[item_offset] = lengths_and_offsets[ITEM].key;
// Scatter length if not the first (global) length
if ((!FIRST_TILE) || (ITEM != 0) || (threadIdx.x > 0))
{
d_lengths_out[item_offset - 1] = lengths_and_offsets[ITEM].value;
}
}
}
}
/**
* Two-phase scatter
*/
template <bool FIRST_TILE>
__device__ __forceinline__ void ScatterTwoPhase(
OffsetT tile_num_runs_exclusive_in_global,
OffsetT warp_num_runs_aggregate,
OffsetT warp_num_runs_exclusive_in_tile,
OffsetT (&thread_num_runs_exclusive_in_warp)[ITEMS_PER_THREAD],
LengthOffsetPair (&lengths_and_offsets)[ITEMS_PER_THREAD],
Int2Type<false> is_warp_time_slice)
{
unsigned int warp_id = ((WARPS == 1) ? 0 : threadIdx.x / WARP_THREADS);
int lane_id = LaneId();
// Unzip
OffsetT run_offsets[ITEMS_PER_THREAD];
LengthT run_lengths[ITEMS_PER_THREAD];
#pragma unroll
for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++)
{
run_offsets[ITEM] = lengths_and_offsets[ITEM].key;
run_lengths[ITEM] = lengths_and_offsets[ITEM].value;
}
WarpExchangeOffsets(temp_storage.aliasable.scatter_aliasable.exchange_offsets[warp_id]).ScatterToStriped(
run_offsets, thread_num_runs_exclusive_in_warp);
WARP_SYNC(0xffffffff);
WarpExchangeLengths(temp_storage.aliasable.scatter_aliasable.exchange_lengths[warp_id]).ScatterToStriped(
run_lengths, thread_num_runs_exclusive_in_warp);
// Global scatter
#pragma unroll
for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++)
{
if ((ITEM * WARP_THREADS) + lane_id < warp_num_runs_aggregate)
{
OffsetT item_offset =
tile_num_runs_exclusive_in_global +
warp_num_runs_exclusive_in_tile +
(ITEM * WARP_THREADS) + lane_id;
// Scatter offset
d_offsets_out[item_offset] = run_offsets[ITEM];
// Scatter length if not the first (global) length
if ((!FIRST_TILE) || (ITEM != 0) || (threadIdx.x > 0))
{
d_lengths_out[item_offset - 1] = run_lengths[ITEM];
}
}
}
}
/**
* Direct scatter
*/
template <bool FIRST_TILE>
__device__ __forceinline__ void ScatterDirect(
OffsetT tile_num_runs_exclusive_in_global,
OffsetT warp_num_runs_aggregate,
OffsetT warp_num_runs_exclusive_in_tile,
OffsetT (&thread_num_runs_exclusive_in_warp)[ITEMS_PER_THREAD],
LengthOffsetPair (&lengths_and_offsets)[ITEMS_PER_THREAD])
{
#pragma unroll
for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ++ITEM)
{
if (thread_num_runs_exclusive_in_warp[ITEM] < warp_num_runs_aggregate)
{
OffsetT item_offset =
tile_num_runs_exclusive_in_global +
warp_num_runs_exclusive_in_tile +
thread_num_runs_exclusive_in_warp[ITEM];
// Scatter offset
d_offsets_out[item_offset] = lengths_and_offsets[ITEM].key;
// Scatter length if not the first (global) length
if (item_offset >= 1)
{
d_lengths_out[item_offset - 1] = lengths_and_offsets[ITEM].value;
}
}
}
}
/**
* Scatter
*/
template <bool FIRST_TILE>
__device__ __forceinline__ void Scatter(
OffsetT tile_num_runs_aggregate,
OffsetT tile_num_runs_exclusive_in_global,
OffsetT warp_num_runs_aggregate,
OffsetT warp_num_runs_exclusive_in_tile,
OffsetT (&thread_num_runs_exclusive_in_warp)[ITEMS_PER_THREAD],
LengthOffsetPair (&lengths_and_offsets)[ITEMS_PER_THREAD])
{
if ((ITEMS_PER_THREAD == 1) || (tile_num_runs_aggregate < BLOCK_THREADS))
{
// Direct scatter if the warp has any items
if (warp_num_runs_aggregate)
{
ScatterDirect<FIRST_TILE>(
tile_num_runs_exclusive_in_global,
warp_num_runs_aggregate,
warp_num_runs_exclusive_in_tile,
thread_num_runs_exclusive_in_warp,
lengths_and_offsets);
}
}
else
{
// Scatter two phase
ScatterTwoPhase<FIRST_TILE>(
tile_num_runs_exclusive_in_global,
warp_num_runs_aggregate,
warp_num_runs_exclusive_in_tile,
thread_num_runs_exclusive_in_warp,
lengths_and_offsets,
Int2Type<STORE_WARP_TIME_SLICING>());
}
}
//---------------------------------------------------------------------
// Cooperatively scan a device-wide sequence of tiles with other CTAs
//---------------------------------------------------------------------
/**
* Process a tile of input (dynamic chained scan)
*/
template <
bool LAST_TILE>
__device__ __forceinline__ LengthOffsetPair ConsumeTile(
OffsetT num_items, ///< Total number of global input items
OffsetT num_remaining, ///< Number of global input items remaining (including this tile)
int tile_idx, ///< Tile index
OffsetT tile_offset, ///< Tile offset
ScanTileStateT &tile_status) ///< Global list of tile status
{
if (tile_idx == 0)
{
// First tile
// Load items
T items[ITEMS_PER_THREAD];
if (LAST_TILE)
BlockLoadT(temp_storage.aliasable.load).Load(d_in + tile_offset, items, num_remaining, T());
else
BlockLoadT(temp_storage.aliasable.load).Load(d_in + tile_offset, items);
if (SYNC_AFTER_LOAD)
CTA_SYNC();
// Set flags
LengthOffsetPair lengths_and_num_runs[ITEMS_PER_THREAD];
InitializeSelections<true, LAST_TILE>(
tile_offset,
num_remaining,
items,
lengths_and_num_runs);
// Exclusive scan of lengths and runs
LengthOffsetPair tile_aggregate;
LengthOffsetPair warp_aggregate;
LengthOffsetPair warp_exclusive_in_tile;
LengthOffsetPair thread_exclusive_in_warp;
WarpScanAllocations(
tile_aggregate,
warp_aggregate,
warp_exclusive_in_tile,
thread_exclusive_in_warp,
lengths_and_num_runs);
// Update tile status if this is not the last tile
if (!LAST_TILE && (threadIdx.x == 0))
tile_status.SetInclusive(0, tile_aggregate);
// Update thread_exclusive_in_warp to fold in warp run-length
if (thread_exclusive_in_warp.key == 0)
thread_exclusive_in_warp.value += warp_exclusive_in_tile.value;
LengthOffsetPair lengths_and_offsets[ITEMS_PER_THREAD];
OffsetT thread_num_runs_exclusive_in_warp[ITEMS_PER_THREAD];
LengthOffsetPair lengths_and_num_runs2[ITEMS_PER_THREAD];
// Downsweep scan through lengths_and_num_runs
internal::ThreadScanExclusive(lengths_and_num_runs, lengths_and_num_runs2, scan_op, thread_exclusive_in_warp);
// Zip
#pragma unroll
for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++)
{
lengths_and_offsets[ITEM].value = lengths_and_num_runs2[ITEM].value;
lengths_and_offsets[ITEM].key = tile_offset + (threadIdx.x * ITEMS_PER_THREAD) + ITEM;
thread_num_runs_exclusive_in_warp[ITEM] = (lengths_and_num_runs[ITEM].key) ?
lengths_and_num_runs2[ITEM].key : // keep
WARP_THREADS * ITEMS_PER_THREAD; // discard
}
OffsetT tile_num_runs_aggregate = tile_aggregate.key;
OffsetT tile_num_runs_exclusive_in_global = 0;
OffsetT warp_num_runs_aggregate = warp_aggregate.key;
OffsetT warp_num_runs_exclusive_in_tile = warp_exclusive_in_tile.key;
// Scatter
Scatter<true>(
tile_num_runs_aggregate,
tile_num_runs_exclusive_in_global,
warp_num_runs_aggregate,
warp_num_runs_exclusive_in_tile,
thread_num_runs_exclusive_in_warp,
lengths_and_offsets);
// Return running total (inclusive of this tile)
return tile_aggregate;
}
else
{
// Not first tile
// Load items
T items[ITEMS_PER_THREAD];
if (LAST_TILE)
BlockLoadT(temp_storage.aliasable.load).Load(d_in + tile_offset, items, num_remaining, T());
else
BlockLoadT(temp_storage.aliasable.load).Load(d_in + tile_offset, items);
if (SYNC_AFTER_LOAD)
CTA_SYNC();
// Set flags
LengthOffsetPair lengths_and_num_runs[ITEMS_PER_THREAD];
InitializeSelections<false, LAST_TILE>(
tile_offset,
num_remaining,
items,
lengths_and_num_runs);
// Exclusive scan of lengths and runs
LengthOffsetPair tile_aggregate;
LengthOffsetPair warp_aggregate;
LengthOffsetPair warp_exclusive_in_tile;
LengthOffsetPair thread_exclusive_in_warp;
WarpScanAllocations(
tile_aggregate,
warp_aggregate,
warp_exclusive_in_tile,
thread_exclusive_in_warp,
lengths_and_num_runs);
// First warp computes tile prefix in lane 0
TilePrefixCallbackOpT prefix_op(tile_status, temp_storage.aliasable.prefix, Sum(), tile_idx);
unsigned int warp_id = ((WARPS == 1) ? 0 : threadIdx.x / WARP_THREADS);
if (warp_id == 0)
{
prefix_op(tile_aggregate);
if (threadIdx.x == 0)
temp_storage.tile_exclusive = prefix_op.exclusive_prefix;
}
CTA_SYNC();
LengthOffsetPair tile_exclusive_in_global = temp_storage.tile_exclusive;
// Update thread_exclusive_in_warp to fold in warp and tile run-lengths
LengthOffsetPair thread_exclusive = scan_op(tile_exclusive_in_global, warp_exclusive_in_tile);
if (thread_exclusive_in_warp.key == 0)
thread_exclusive_in_warp.value += thread_exclusive.value;
// Downsweep scan through lengths_and_num_runs
LengthOffsetPair lengths_and_num_runs2[ITEMS_PER_THREAD];
LengthOffsetPair lengths_and_offsets[ITEMS_PER_THREAD];
OffsetT thread_num_runs_exclusive_in_warp[ITEMS_PER_THREAD];
internal::ThreadScanExclusive(lengths_and_num_runs, lengths_and_num_runs2, scan_op, thread_exclusive_in_warp);
// Zip
#pragma unroll
for (int ITEM = 0; ITEM < ITEMS_PER_THREAD; ITEM++)
{
lengths_and_offsets[ITEM].value = lengths_and_num_runs2[ITEM].value;
lengths_and_offsets[ITEM].key = tile_offset + (threadIdx.x * ITEMS_PER_THREAD) + ITEM;
thread_num_runs_exclusive_in_warp[ITEM] = (lengths_and_num_runs[ITEM].key) ?
lengths_and_num_runs2[ITEM].key : // keep
WARP_THREADS * ITEMS_PER_THREAD; // discard
}
OffsetT tile_num_runs_aggregate = tile_aggregate.key;
OffsetT tile_num_runs_exclusive_in_global = tile_exclusive_in_global.key;
OffsetT warp_num_runs_aggregate = warp_aggregate.key;
OffsetT warp_num_runs_exclusive_in_tile = warp_exclusive_in_tile.key;
// Scatter
Scatter<false>(
tile_num_runs_aggregate,
tile_num_runs_exclusive_in_global,
warp_num_runs_aggregate,
warp_num_runs_exclusive_in_tile,
thread_num_runs_exclusive_in_warp,
lengths_and_offsets);
// Return running total (inclusive of this tile)
return prefix_op.inclusive_prefix;
}
}
/**
* Scan tiles of items as part of a dynamic chained scan
*/
template <typename NumRunsIteratorT> ///< Output iterator type for recording number of items selected
__device__ __forceinline__ void ConsumeRange(
int num_tiles, ///< Total number of input tiles
ScanTileStateT& tile_status, ///< Global list of tile status
NumRunsIteratorT d_num_runs_out) ///< Output pointer for total number of runs identified
{
// Blocks are launched in increasing order, so just assign one tile per block
int tile_idx = (blockIdx.x * gridDim.y) + blockIdx.y; // Current tile index
OffsetT tile_offset = tile_idx * TILE_ITEMS; // Global offset for the current tile
OffsetT num_remaining = num_items - tile_offset; // Remaining items (including this tile)
if (tile_idx < num_tiles - 1)
{
// Not the last tile (full)
ConsumeTile<false>(num_items, num_remaining, tile_idx, tile_offset, tile_status);
}
else if (num_remaining > 0)
{
// The last tile (possibly partially-full)
LengthOffsetPair running_total = ConsumeTile<true>(num_items, num_remaining, tile_idx, tile_offset, tile_status);
if (threadIdx.x == 0)
{
// Output the total number of items selected
*d_num_runs_out = running_total.key;
// The inclusive prefix contains accumulated length reduction for the last run
if (running_total.key > 0)
d_lengths_out[running_total.key - 1] = running_total.value;
}
}
}
};
} // CUB namespace
CUB_NS_POSTFIX // Optional outer namespace(s)
| {
"pile_set_name": "Github"
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.internal.cache.tier.sockets;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.geode.DataSerializable;
import org.apache.geode.DataSerializer;
import org.apache.geode.Delta;
import org.apache.geode.InvalidDeltaException;
import org.apache.geode.internal.cache.GemFireCacheImpl;
/**
* Faulty delta implementation, raising ArrayIndexOutOfBound exception as fromDelta reads incorrect
* sequence then wrote by toDelta
*
* @since GemFire 6.1
*/
public class FaultyDelta implements Delta, DataSerializable {
public static final byte INT_MASK = 0x1;
public static final byte BIG_OBJECT_MASK = 0x2;
public static final byte COMPLETE_MASK = 0x3;
protected int intVal = 0;
protected boolean hasDelta = false;
protected byte[] bigObj = new byte[2];
public static boolean isPatternMatched = false;
protected byte deltaBits = 0x0;
@Override
public void fromDelta(DataInput in) throws IOException, InvalidDeltaException {
try {
byte deltaBits = DataSerializer.readByte(in);
GemFireCacheImpl.getInstance().getLogger().fine("Applying delta on " + this.toString());
if (deltaBits != 0) {
// we should read here int, but we are reading byte array. Its is done
// intentionly to produce faulty fromDelta implementation
if ((deltaBits & INT_MASK) == INT_MASK) {
this.bigObj = DataSerializer.readByteArray(in);
GemFireCacheImpl.getInstance().getLogger()
.fine(" Applied delta on DeltaImpl's field 'bigObj' = {" + this.bigObj[0] + " "
+ this.bigObj[1] + "}");
}
if ((deltaBits & BIG_OBJECT_MASK) == BIG_OBJECT_MASK) {
this.intVal = DataSerializer.readPrimitiveInt(in);
GemFireCacheImpl.getInstance().getLogger()
.fine(" Applied delta on DeltaImpl's field 'intVal' = " + this.intVal);
}
if ((deltaBits | COMPLETE_MASK) != COMPLETE_MASK) {
GemFireCacheImpl.getInstance().getLogger().fine(" <unknown field code>");
throw new IllegalArgumentException(
"DeltaImpl.fromDelta(): Unknown field code, " + deltaBits);
}
}
} catch (IOException ioe) {
GemFireCacheImpl.getInstance().getLogger().warning("DeltaObj.fromDelta(): " + ioe);
throw ioe;
} catch (IllegalArgumentException iae) {
GemFireCacheImpl.getInstance().getLogger().warning("DeltaObj.fromDelta(): " + iae);
throw new InvalidDeltaException(iae);
}
}
@Override
public boolean hasDelta() {
return this.hasDelta;
}
@Override
public void toDelta(DataOutput out) throws IOException {
try {
DataSerializer.writeByte(this.deltaBits, out);
GemFireCacheImpl.getInstance().getLogger().fine("Extracting delta from " + this.toString());
if ((deltaBits & INT_MASK) == INT_MASK) {
GemFireCacheImpl.getInstance().getLogger()
.fine(" Extracted delta from DeltaObj's field 'intVal' = " + this.intVal);
DataSerializer.writePrimitiveInt(this.intVal, out);
}
if ((deltaBits & BIG_OBJECT_MASK) == BIG_OBJECT_MASK) {
GemFireCacheImpl.getInstance().getLogger()
.fine(" Extracted delta from DeltaObj's field 'bigObj' = {" + this.bigObj[0] + " "
+ this.bigObj[1] + "}");
DataSerializer.writeByteArray(this.bigObj, out);
}
if ((deltaBits | COMPLETE_MASK) != COMPLETE_MASK) {
GemFireCacheImpl.getInstance().getLogger().fine(" <unknown field code>");
throw new IllegalArgumentException("DeltaImpl.toDelta(): Unknown field code, " + deltaBits);
}
DataSerializer.writeByte((byte) 255, out);
GemFireCacheImpl.getInstance().getLogger()
.fine(" Writing extra DeltaObj's field 'byte' = " + 255);
GemFireCacheImpl.getInstance().getLogger().fine("-----------");
resetDeltaStatus();
} catch (IOException ioe) {
GemFireCacheImpl.getInstance().getLogger().warning("DeltaObj.toDelta(): " + ioe);
throw ioe;
} catch (IllegalArgumentException iae) {
GemFireCacheImpl.getInstance().getLogger().warning("DeltaObj.toDelta(): " + iae);
throw new InvalidDeltaException(iae);
}
}
@Override
public void fromData(DataInput in) throws IOException, ClassNotFoundException {
this.intVal = DataSerializer.readPrimitiveInt(in);
this.bigObj = DataSerializer.readByteArray(in);
}
@Override
public void toData(DataOutput out) throws IOException {
DataSerializer.writePrimitiveInt(this.intVal, out);
DataSerializer.writeByteArray(this.bigObj, out);
}
public byte[] getBigObj() {
return bigObj;
}
public void setBigObj(byte[] bigObj) {
this.hasDelta = true;
this.deltaBits |= BIG_OBJECT_MASK;
this.bigObj = bigObj;
}
public void resetDeltaStatus() {
this.deltaBits = 0x0;
this.hasDelta = false;
}
public int getIntVal() {
return intVal;
}
public void setIntVal(int intVal) {
this.hasDelta = true;
this.deltaBits |= INT_MASK;
this.intVal = intVal;
}
public String toString() {
return "DeltaObj[hasDelta=" + this.hasDelta + ",intVal=" + this.intVal + ",bigObj={"
+ this.bigObj[0] + "," + this.bigObj[1] + "}]";
}
}
| {
"pile_set_name": "Github"
} |
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Preprocessed version of "boost/mpl/greater.hpp" header
// -- DO NOT modify by hand!
namespace boost { namespace mpl {
template<
typename Tag1
, typename Tag2
>
struct greater_impl
: if_c<
( BOOST_MPL_AUX_NESTED_VALUE_WKND(int, Tag1)
> BOOST_MPL_AUX_NESTED_VALUE_WKND(int, Tag2)
)
, aux::cast2nd_impl< greater_impl< Tag1,Tag1 >,Tag1, Tag2 >
, aux::cast1st_impl< greater_impl< Tag2,Tag2 >,Tag1, Tag2 >
>::type
{
};
/// for Digital Mars C++/compilers with no CTPS/TTP support
template<> struct greater_impl< na,na >
{
template< typename U1, typename U2 > struct apply
{
typedef apply type;
BOOST_STATIC_CONSTANT(int, value = 0);
};
};
template< typename Tag > struct greater_impl< na,Tag >
{
template< typename U1, typename U2 > struct apply
{
typedef apply type;
BOOST_STATIC_CONSTANT(int, value = 0);
};
};
template< typename Tag > struct greater_impl< Tag,na >
{
template< typename U1, typename U2 > struct apply
{
typedef apply type;
BOOST_STATIC_CONSTANT(int, value = 0);
};
};
template< typename T > struct greater_tag
{
typedef typename T::tag type;
};
template<
typename BOOST_MPL_AUX_NA_PARAM(N1)
, typename BOOST_MPL_AUX_NA_PARAM(N2)
>
struct greater
: greater_impl<
typename greater_tag<N1>::type
, typename greater_tag<N2>::type
>::template apply< N1,N2 >::type
{
BOOST_MPL_AUX_LAMBDA_SUPPORT(2, greater, (N1, N2))
};
BOOST_MPL_AUX_NA_SPEC2(2, 2, greater)
}}
namespace boost { namespace mpl {
template<>
struct greater_impl< integral_c_tag,integral_c_tag >
{
template< typename N1, typename N2 > struct apply
: bool_< ( BOOST_MPL_AUX_VALUE_WKND(N1)::value > BOOST_MPL_AUX_VALUE_WKND(N2)::value ) >
{
};
};
}}
| {
"pile_set_name": "Github"
} |
package gw.specContrib.controlFlow
class Errant_SwitchInsideEnum {
enum Relop1 {
GreaterThan, LessThan
}
private enum InvoiceItemAmountSignum {
POSITIVE,
NEGATIVE
property get OperatorToUseForFiltering() : Relop1 {
switch (this) {
case POSITIVE:
return Relop1.GreaterThan
case NEGATIVE:
return Relop1.LessThan
}
return null //## issuekeys: UNREACHABLE STATEMENT
}
}
} | {
"pile_set_name": "Github"
} |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 28 15:34:18 2012
Author: Josef Perktold
"""
from io import StringIO
import numpy as np
from numpy.testing import assert_almost_equal, assert_equal
from scipy import stats
from statsmodels.stats.libqsturng import qsturng
from statsmodels.stats.multicomp import tukeyhsd
import statsmodels.stats.multicomp as multi
ss = '''\
43.9 1 1
39.0 1 2
46.7 1 3
43.8 1 4
44.2 1 5
47.7 1 6
43.6 1 7
38.9 1 8
43.6 1 9
40.0 1 10
89.8 2 1
87.1 2 2
92.7 2 3
90.6 2 4
87.7 2 5
92.4 2 6
86.1 2 7
88.1 2 8
90.8 2 9
89.1 2 10
68.4 3 1
69.3 3 2
68.5 3 3
66.4 3 4
70.0 3 5
68.1 3 6
70.6 3 7
65.2 3 8
63.8 3 9
69.2 3 10
36.2 4 1
45.2 4 2
40.7 4 3
40.5 4 4
39.3 4 5
40.3 4 6
43.2 4 7
38.7 4 8
40.9 4 9
39.7 4 10'''
#idx Treatment StressReduction
ss2 = '''\
1 mental 2
2 mental 2
3 mental 3
4 mental 4
5 mental 4
6 mental 5
7 mental 3
8 mental 4
9 mental 4
10 mental 4
11 physical 4
12 physical 4
13 physical 3
14 physical 5
15 physical 4
16 physical 1
17 physical 1
18 physical 2
19 physical 3
20 physical 3
21 medical 1
22 medical 2
23 medical 2
24 medical 2
25 medical 3
26 medical 2
27 medical 3
28 medical 1
29 medical 3
30 medical 1'''
ss3 = '''\
1 24.5
1 23.5
1 26.4
1 27.1
1 29.9
2 28.4
2 34.2
2 29.5
2 32.2
2 30.1
3 26.1
3 28.3
3 24.3
3 26.2
3 27.8'''
cylinders = np.array([8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 4, 8, 8, 8, 8, 8, 8, 8, 8, 8, 4, 6, 6, 6, 4, 4,
4, 4, 4, 4, 6, 8, 8, 8, 8, 4, 4, 4, 4, 8, 8, 8, 8, 6, 6, 6, 6, 4, 4, 4, 4, 6, 6,
6, 6, 4, 4, 4, 4, 4, 8, 4, 6, 6, 8, 8, 8, 8, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 6, 6, 4, 6, 4, 4, 4, 4, 4, 4, 4, 4])
cyl_labels = np.array(['USA', 'USA', 'USA', 'USA', 'USA', 'USA', 'USA', 'USA', 'USA', 'USA', 'France',
'USA', 'USA', 'USA', 'USA', 'USA', 'USA', 'USA', 'USA', 'USA', 'Japan', 'USA', 'USA', 'USA', 'Japan',
'Germany', 'France', 'Germany', 'Sweden', 'Germany', 'USA', 'USA', 'USA', 'USA', 'USA', 'Germany',
'USA', 'USA', 'France', 'USA', 'USA', 'USA', 'USA', 'USA', 'USA', 'USA', 'USA', 'USA', 'USA', 'Germany',
'Japan', 'USA', 'USA', 'USA', 'USA', 'Germany', 'Japan', 'Japan', 'USA', 'Sweden', 'USA', 'France',
'Japan', 'Germany', 'USA', 'USA', 'USA', 'USA', 'USA', 'USA', 'USA', 'USA', 'USA', 'USA', 'USA', 'USA',
'Germany', 'Japan', 'Japan', 'USA', 'USA', 'Japan', 'Japan', 'Japan', 'Japan', 'Japan', 'Japan', 'USA',
'USA', 'USA', 'USA', 'Japan', 'USA', 'USA', 'USA', 'Germany', 'USA', 'USA', 'USA'])
dta = np.recfromtxt(StringIO(ss), names=("Rust","Brand","Replication"))
dta2 = np.recfromtxt(StringIO(ss2), names = ("idx", "Treatment", "StressReduction"))
dta3 = np.recfromtxt(StringIO(ss3), names = ("Brand", "Relief"))
#print tukeyhsd(dta['Brand'], dta['Rust'])
def get_thsd(mci):
var_ = np.var(mci.groupstats.groupdemean(), ddof=len(mci.groupsunique))
means = mci.groupstats.groupmean
nobs = mci.groupstats.groupnobs
resi = tukeyhsd(means, nobs, var_, df=None, alpha=0.05, q_crit=qsturng(0.95, len(means), (nobs-1).sum()))
print(resi[4])
var2 = (mci.groupstats.groupvarwithin() * (nobs - 1)).sum() \
/ (nobs - 1).sum()
assert_almost_equal(var_, var2, decimal=14)
return resi
mc = multi.MultiComparison(dta['Rust'], dta['Brand'])
res = mc.tukeyhsd()
print(res)
mc2 = multi.MultiComparison(dta2['StressReduction'], dta2['Treatment'])
res2 = mc2.tukeyhsd()
print(res2)
mc2s = multi.MultiComparison(dta2['StressReduction'][3:29], dta2['Treatment'][3:29])
res2s = mc2s.tukeyhsd()
print(res2s)
res2s_001 = mc2s.tukeyhsd(alpha=0.01)
#R result
tukeyhsd2s = np.array([1.888889,0.8888889,-1,0.2658549,-0.5908785,-2.587133,3.511923,2.368656,0.5871331,0.002837638,0.150456,0.1266072]).reshape(3,4, order='F')
assert_almost_equal(res2s_001.confint, tukeyhsd2s[:,1:3], decimal=3)
mc3 = multi.MultiComparison(dta3['Relief'], dta3['Brand'])
res3 = mc3.tukeyhsd()
print(res3)
tukeyhsd4 = multi.MultiComparison(cylinders, cyl_labels, group_order=["Sweden", "Japan", "Germany", "France", "USA"])
res4 = tukeyhsd4.tukeyhsd()
print(res4)
try:
import matplotlib.pyplot as plt
fig = res4.plot_simultaneous("USA")
plt.show()
except Exception as e:
print(e)
for mci in [mc, mc2, mc3]:
get_thsd(mci)
print(mc2.allpairtest(stats.ttest_ind, method='b')[0])
'''same as SAS:
>>> np.var(mci.groupstats.groupdemean(), ddof=3)
4.6773333333333351
>>> var_ = np.var(mci.groupstats.groupdemean(), ddof=3)
>>> tukeyhsd(means, nobs, var_, df=None, alpha=0.05, q_crit=qsturng(0.95, 3, 12))[4]
array([[ 0.95263648, 8.24736352],
[-3.38736352, 3.90736352],
[-7.98736352, -0.69263648]])
>>> tukeyhsd(means, nobs, var_, df=None, alpha=0.05, q_crit=3.77278)[4]
array([[ 0.95098508, 8.24901492],
[-3.38901492, 3.90901492],
[-7.98901492, -0.69098508]])
'''
ss5 = '''\
Comparisons significant at the 0.05 level are indicated by ***.
BRAND
Comparison Difference
Between
Means Simultaneous 95% Confidence Limits Sign.
2 - 3 4.340 0.691 7.989 ***
2 - 1 4.600 0.951 8.249 ***
3 - 2 -4.340 -7.989 -0.691 ***
3 - 1 0.260 -3.389 3.909 -
1 - 2 -4.600 -8.249 -0.951 ***
1 - 3 -0.260 -3.909 3.389 '''
ss5 = '''\
2 - 3 4.340 0.691 7.989 ***
2 - 1 4.600 0.951 8.249 ***
3 - 2 -4.340 -7.989 -0.691 ***
3 - 1 0.260 -3.389 3.909 -
1 - 2 -4.600 -8.249 -0.951 ***
1 - 3 -0.260 -3.909 3.389 '''
dta5 = np.recfromtxt(StringIO(ss5), names = ('pair', 'mean', 'lower', 'upper', 'sig'), delimiter='\t')
sas_ = dta5[[1,3,2]]
confint1 = res3.confint
confint2 = sas_[['lower','upper']].view(float).reshape((3,2))
assert_almost_equal(confint1, confint2, decimal=2)
reject1 = res3.reject
reject2 = sas_['sig'] == '***'
assert_equal(reject1, reject2)
meandiff1 = res3.meandiffs
meandiff2 = sas_['mean']
assert_almost_equal(meandiff1, meandiff2, decimal=14)
| {
"pile_set_name": "Github"
} |
STATISTICS
Problem name : data/j301_2.sm
Variables : 32 (0 binary, 32 integer, 0 implicit integer, 0 continuous)
Constraints : 0 initial, 52 maximal
OBJECTIVE
Sense : minimize
VARIABLES
[integer] <start_0>: obj=0, original bounds=[0,16000]
[integer] <start_1>: obj=0, original bounds=[0,16000]
[integer] <start_2>: obj=0, original bounds=[0,16000]
[integer] <start_3>: obj=0, original bounds=[0,16000]
[integer] <start_4>: obj=0, original bounds=[0,16000]
[integer] <start_5>: obj=0, original bounds=[0,16000]
[integer] <start_6>: obj=0, original bounds=[0,16000]
[integer] <start_7>: obj=0, original bounds=[0,16000]
[integer] <start_8>: obj=0, original bounds=[0,16000]
[integer] <start_9>: obj=0, original bounds=[0,16000]
[integer] <start_10>: obj=0, original bounds=[0,16000]
[integer] <start_11>: obj=0, original bounds=[0,16000]
[integer] <start_12>: obj=0, original bounds=[0,16000]
[integer] <start_13>: obj=0, original bounds=[0,16000]
[integer] <start_14>: obj=0, original bounds=[0,16000]
[integer] <start_15>: obj=0, original bounds=[0,16000]
[integer] <start_16>: obj=0, original bounds=[0,16000]
[integer] <start_17>: obj=0, original bounds=[0,16000]
[integer] <start_18>: obj=0, original bounds=[0,16000]
[integer] <start_19>: obj=0, original bounds=[0,16000]
[integer] <start_20>: obj=0, original bounds=[0,16000]
[integer] <start_21>: obj=0, original bounds=[0,16000]
[integer] <start_22>: obj=0, original bounds=[0,16000]
[integer] <start_23>: obj=0, original bounds=[0,16000]
[integer] <start_24>: obj=0, original bounds=[0,16000]
[integer] <start_25>: obj=0, original bounds=[0,16000]
[integer] <start_26>: obj=0, original bounds=[0,16000]
[integer] <start_27>: obj=0, original bounds=[0,16000]
[integer] <start_28>: obj=0, original bounds=[0,16000]
[integer] <start_29>: obj=0, original bounds=[0,16000]
[integer] <start_30>: obj=0, original bounds=[0,16000]
[integer] <makespan>: obj=1, original bounds=[0,16000]
CONSTRAINTS
[varbound] <precedences_(0,1)>: <start_0>[I] -1<start_1>[I] <= 0;
[varbound] <precedences_(0,2)>: <start_0>[I] -1<start_2>[I] <= 0;
[varbound] <precedences_(0,3)>: <start_0>[I] -1<start_3>[I] <= 0;
[varbound] <precedences_(1,9)>: <start_1>[I] -1<start_9>[I] <= -2;
[varbound] <precedences_(2,4)>: <start_2>[I] -1<start_4>[I] <= -10;
[varbound] <precedences_(2,8)>: <start_2>[I] -1<start_8>[I] <= -10;
[varbound] <precedences_(2,14)>: <start_2>[I] -1<start_14>[I] <= -10;
[varbound] <precedences_(3,6)>: <start_3>[I] -1<start_6>[I] <= -7;
[varbound] <precedences_(3,12)>: <start_3>[I] -1<start_12>[I] <= -7;
[varbound] <precedences_(4,5)>: <start_4>[I] -1<start_5>[I] <= -1;
[varbound] <precedences_(4,16)>: <start_4>[I] -1<start_16>[I] <= -1;
[varbound] <precedences_(5,12)>: <start_5>[I] -1<start_12>[I] <= -3;
[varbound] <precedences_(5,15)>: <start_5>[I] -1<start_15>[I] <= -3;
[varbound] <precedences_(5,17)>: <start_5>[I] -1<start_17>[I] <= -3;
[varbound] <precedences_(6,7)>: <start_6>[I] -1<start_7>[I] <= -6;
[varbound] <precedences_(6,10)>: <start_6>[I] -1<start_10>[I] <= -6;
[varbound] <precedences_(6,18)>: <start_6>[I] -1<start_18>[I] <= -6;
[varbound] <precedences_(7,26)>: <start_7>[I] -1<start_26>[I] <= -2;
[varbound] <precedences_(8,13)>: <start_8>[I] -1<start_13>[I] <= -10;
[varbound] <precedences_(8,27)>: <start_8>[I] -1<start_27>[I] <= -10;
[varbound] <precedences_(9,11)>: <start_9>[I] -1<start_11>[I] <= -5;
[varbound] <precedences_(9,21)>: <start_9>[I] -1<start_21>[I] <= -5;
[varbound] <precedences_(10,20)>: <start_10>[I] -1<start_20>[I] <= -9;
[varbound] <precedences_(10,25)>: <start_10>[I] -1<start_25>[I] <= -9;
[varbound] <precedences_(11,23)>: <start_11>[I] -1<start_23>[I] <= -4;
[varbound] <precedences_(12,24)>: <start_12>[I] -1<start_24>[I] <= -4;
[varbound] <precedences_(13,24)>: <start_13>[I] -1<start_24>[I] <= -2;
[varbound] <precedences_(14,20)>: <start_14>[I] -1<start_20>[I] <= -4;
[varbound] <precedences_(15,19)>: <start_15>[I] -1<start_19>[I] <= -10;
[varbound] <precedences_(15,25)>: <start_15>[I] -1<start_25>[I] <= -10;
[varbound] <precedences_(16,20)>: <start_16>[I] -1<start_20>[I] <= -10;
[varbound] <precedences_(16,25)>: <start_16>[I] -1<start_25>[I] <= -10;
[varbound] <precedences_(16,28)>: <start_16>[I] -1<start_28>[I] <= -10;
[varbound] <precedences_(17,22)>: <start_17>[I] -1<start_22>[I] <= -7;
[varbound] <precedences_(18,24)>: <start_18>[I] -1<start_24>[I] <= -10;
[varbound] <precedences_(19,30)>: <start_19>[I] -1<start_30>[I] <= -7;
[varbound] <precedences_(20,30)>: <start_20>[I] -1<start_30>[I] <= -2;
[varbound] <precedences_(21,26)>: <start_21>[I] -1<start_26>[I] <= -1;
[varbound] <precedences_(21,28)>: <start_21>[I] -1<start_28>[I] <= -1;
[varbound] <precedences_(22,30)>: <start_22>[I] -1<start_30>[I] <= -2;
[varbound] <precedences_(23,28)>: <start_23>[I] -1<start_28>[I] <= -2;
[varbound] <precedences_(24,29)>: <start_24>[I] -1<start_29>[I] <= -2;
[varbound] <precedences_(25,26)>: <start_25>[I] -1<start_26>[I] <= -9;
[varbound] <precedences_(26,29)>: <start_26>[I] -1<start_29>[I] <= -1;
[varbound] <precedences_(27,29)>: <start_27>[I] -1<start_29>[I] <= -4;
[varbound] <precedences_(28,31)>: <start_28>[I] -1<makespan>[I] <= -7;
[varbound] <precedences_(29,31)>: <start_29>[I] -1<makespan>[I] <= -8;
[varbound] <precedences_(30,31)>: <start_30>[I] -1<makespan>[I] <= -9;
[cumulative] <R1 >: cumulative(<start_4>(1)[8], <start_9>(5)[1], <start_10>(9)[2], <start_15>(10)[10], <start_17>(7)[5], <start_21>(1)[10], <start_22>(2)[8], <start_25>(9)[7], <start_27>(4)[8])[0,2147483647) <= 14;
[cumulative] <R2 >: cumulative(<start_2>(10)[8], <start_7>(2)[9], <start_12>(4)[5], <start_20>(2)[7], <start_28>(7)[3], <start_30>(9)[6])[0,2147483647) <= 10;
[cumulative] <R3 >: cumulative(<start_1>(2)[2], <start_3>(7)[7], <start_6>(6)[5], <start_11>(4)[6], <start_13>(2)[10], <start_16>(10)[7], <start_19>(7)[3], <start_29>(8)[8])[0,2147483647) <= 11;
[cumulative] <R4>: cumulative(<start_5>(3)[8], <start_8>(10)[2], <start_14>(4)[10], <start_18>(10)[7], <start_23>(2)[8], <start_24>(2)[7], <start_26>(1)[1])[0,2147483647) <= 14;
END
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<meta name="keywords" content="日期控件 datepicker calendar 日历控件 javascript js日历控件 带时间 自定义格式 月历控件 日期时间 日期选择" />
<title>My97日期控件 功能演示 自定义事件 My97 Datepicker Demo</title>
<link href="../../css/base.css" tppabs="http://www.my97.net/dp/css/base.css" rel="stylesheet" type="text/css" />
<link href="demo.css" tppabs="http://www.my97.net/dp/demo/resource/demo.css" rel="stylesheet" type="text/css" />
</head>
<body>
<iframe src="../../head.asp" tppabs="http://www.my97.net/dp/head.asp" scrolling="no" frameborder="0" height="100px" width="100%"></iframe>
<script language="JavaScript" type="text/javascript" src="../../../WdatePicker.js" tppabs="http://www.my97.net/dp/My97DatePicker/WdatePicker.js"></script>
<div class="dCenter dBody">
<div id="content">
<h2>二. 功能及示例<a name="m2" id="m2"></a></h2>
<h3>5. 自定义事件<a name="m25" id="m25"></a></h3>
<ol>
<li>自定义事件
<a name="m251" id="m251"></a>
<p>如果你需要做一些附加的操作,你也不必担心,日期控件自带的自定义事件可以满足你的需求.此外,你还可以在自定义事件中调用提供的API库来做更多的运算和扩展,绝对可以通过很少的代码满足你及其个性化的需求.<br />
<br />
注意下面几个重要的指针,将对你的编程带来很多便利<br />
<span class="STYLE1">this: 指向文本框<br />
dp: 指向$dp<br />
dp.cal: 指向日期控件对象</span><br />
注意:函数原型必须使用类似 <span class="STYLE1">function(dp){} </span>的模式,这样子,在函数内部才可以使用dp</p>
</li>
<li>onpicking 和 onpicked 事件
<a name="m252" id="m252"></a>
<div>
<h4>示例5-2-1 onpicking事件演示</h4>
<p>
<input type="text" id="5421" onFocus="WdatePicker({onpicking:function(dp){if(!confirm('日期框原来的值为: '+dp.cal.getDateStr()+', 要用新选择的值:' + dp.cal.getNewDateStr() + '覆盖吗?')) return true;}})" class="Wdate"/>
<br />
<input type="text" id="5421" onFocus="WdatePicker({<span class="STYLE2">onpicking:</span><span class="STYLE1">function(dp){if(!confirm('日期框原来的值为: '+dp.cal.getDateStr()+', 要用新选择的值:' + dp.cal.getNewDateStr() + '覆盖吗?')) return true;}</span>})" class="Wdate"/><br />
<br />
<span class="STYLE1">注意:</span>你注意到dp.cal.getDateStr和dp.cal.getNewDateStr的用法了嘛? 详见<a href="999.asp-.htm#m5" tppabs="http://www.my97.net/dp/demo/resource/999.asp?#m5">内置函数和属性</a></p>
</div>
<div>
<h4>示例5-2-2 使用onpicked实现日期选择联动</h4>
<p>选择第一个日期的时候,第二个日期选择框自动弹出<br />
日期从:
<input id="d5221" class="Wdate" type="text" onFocus="var d5222=$dp.$('d5222');WdatePicker({onpicked:function(){d5222.focus();},maxDate:'#F{$dp.$D(\'d5222\')}'})"/>
至
<input id="d5222" class="Wdate" type="text" onFocus="WdatePicker({minDate:'#F{$dp.$D(\'d5221\')}'})"/>
<br />
<span class="STYLE1">注意:</span>下面第一个控件代码的写法<br />
<input id="<span class="STYLE1">d5221</span>" class="Wdate" type="text" onFocus="var d5222=$dp.$('d5222');WdatePicker({<span class="STYLE2">onpicked:</span><span class="STYLE1">function(){d5222.focus();}</span>,maxDate:'#F{$dp.$D(\'d5222\')}'})"/><br />
至<br />
<input id="<span class="STYLE1">d5222</span>" class="Wdate" type="text" onFocus="WdatePicker({minDate:'#F{$dp.$D(\'d5221\')}'})"/><br />
<br />
<span class="STYLE1">注意:</span>$dp.$是一个<a href="999.asp-.htm#m5" tppabs="http://www.my97.net/dp/demo/resource/999.asp?#m5">内置函数</a>,相当于document.getElementById</p>
</div>
<div>
<h4>示例5-2-3 将选择的值拆分到文本框 </h4>
<p>
<input type="text" id="d523_y" size="5"/>
年
<input type="text" id="d523_M" size="3"/>
月
<input type="text" id="d523_d" size="3"/>
日
<input type="text" id="d523_HH" size="3"/>
时
<input type="text" id="d523_mm" size="3"/>
分
<input type="text" id="d523_ss" size="3"/>
秒
<input type="text" id="d523"/>
<img onclick="WdatePicker({el:'d523',dateFmt:'yyyy-MM-dd HH:mm:ss',onpicked:pickedFunc})" src="../../../skin/datePicker.gif" tppabs="http://www.my97.net/dp/My97DatePicker/skin/datePicker.gif" width="16" height="22" align="absmiddle" style="cursor:pointer"/>
<script>
function pickedFunc(){
$dp.$('d523_y').value=$dp.cal.getP('y');
$dp.$('d523_M').value=$dp.cal.getP('M');
$dp.$('d523_d').value=$dp.cal.getP('d');
$dp.$('d523_HH').value=$dp.cal.getP('H');
$dp.$('d523_mm').value=$dp.cal.getP('m');
$dp.$('d523_ss').value=$dp.cal.getP('s');
}
</script>
<br />
<input type="text" id="d523_y" size="5"/>
年<br />
<input type="text" id="d523_M" size="3"/>
月<br />
<input type="text" id="d523_d" size="3"/>
日<br />
<input type="text" id="d523_HH" size="3"/>
时<br />
<input type="text" id="d523_mm" size="3"/>
分<br />
<input type="text" id="d523_ss" size="3"/>
秒 <br />
<img onclick="WdatePicker({<span class="STYLE2">el:</span><span class="STYLE1">'d523'</span>,dateFmt:'yyyy-MM-dd HH:mm:ss',<span class="STYLE2">onpicked:</span><span class="STYLE1">pickedFunc</span>})" src="../../../skin/datePicker.gif" width="16" height="22" align="absmiddle" style="cursor:pointer"/><br />
<span class="STYLE1"><script></span><br />
<span class="STYLE2">function</span> pickedFunc(){<br />
$dp.$('d523_y').value=$dp.cal.getP('y');<br />
$dp.$('d523_M').value=$dp.cal.getP('M');<br />
$dp.$('d523_d').value=$dp.cal.getP('d');<br />
$dp.$('d523_HH').value=$dp.cal.getP('H');<br />
$dp.$('d523_mm').value=$dp.cal.getP('m');<br />
$dp.$('d523_ss').value=$dp.cal.getP('s');<br />
}<br />
<span class="STYLE1"></script></span><br />
<br />
<span class="STYLE1">注意:</span>el:'d523'中,如果你不需要d523这个框,你可以把他改成hidden,但是el属性必须指定<br />
$dp.$和$dp.cal.getP都是<a href="999.asp-.htm#m5" tppabs="http://www.my97.net/dp/demo/resource/999.asp?#m5">内置函数</a> </p>
</div>
</li>
<li>onclearing 和 oncleared 事件
<a name="m253" id="m253"></a>
<div>
<h4>示例5-3-1 使用onclearing事件取消清空操作</h4>
<p>
<input type="text" class="Wdate" id="d531" onFocus="WdatePicker({onclearing:function(){if(!confirm('日期框的值为:'+this.value+', 确实要清空吗?'))return true;}})"/>
<br />
<input type="text" class="Wdate" id="d531" onFocus="WdatePicker({<span class="STYLE2">onclearing:</span><span class="STYLE1">function(){if(!confirm('日期框的值为:'+this.value+', 确实要清空吗?'))return true;}</span>})"/><br />
<br />
<span class="STYLE1">注意:</span>当onclearing函数返回true时,系统的清空事件将被取消,<br />
函数体里面没有引用$dp,所以函数原型里面可以省略参数dp </p>
</div>
<div>
<h4>示例5-3-2 使用cal对象取得当前日期所选择的月份(使用了 dp.cal)</h4>
<p>
<input type="text" class="Wdate" id="d532" onFocus="WdatePicker({oncleared:function(dp){alert('当前日期所选择的月份为:'+dp.cal.date.M);}})"/>
<br />
<input type="text" class="Wdate" id="d532" onFocus="WdatePicker({<span class="STYLE2">oncleared:</span><span class="STYLE1">function(dp){alert('当前日期所选择的月份为:'+dp.cal.date.M);}</span>})"/></p>
</div>
<div>
<h4>示例5-3-3 综合使用两个事件</h4>
<p>
<input type="text" class="Wdate" id="d533" onFocus="d533_focus(this)" value="2000-04-09"/>
<script>
function d533_focus(element){
var clearingFunc = function(){ if(!confirm('日期框的值为:'+this.value+', 确实要清空吗?')) return true; }
var clearedFunc = function(){ alert('日期框已被清空'); }
WdatePicker({el:element,onclearing:clearingFunc,oncleared:clearedFunc})
}
</script>
<br />
<span class="STYLE1"><script></span><br />
<span class="STYLE2">function</span> d533_focus(element){<br />
var clearingFunc = function(){
if(!confirm('日期框的值为:'+this.value+', 确实要清空吗?')) return true;
}<br />
var clearedFunc = function(){
alert('日期框已被清空');
}<br />
WdatePicker({el:element,onclearing:clearingFunc,oncleared:clearedFunc})<br />
}<br />
<span class="STYLE1"></script></span><br />
<input type="text" class="Wdate" id="d533" onFocus="<span class="STYLE1">d533_focus(this)</span>"/></p>
</div>
</li>
<li>年月日时分秒的 changing和changed <a name="m254" id="m254"></a> <p>年月日时分秒都有对应的changing和changed事件,分别是:<br />
ychanging ychanged <br />
Mchanging Mchanged<br />
dchanging dchanged<br />
Hchanging Hchanged<br />
mchanging mchanged<br />
schanging schanged <br />
</p>
<div>
<h4>示例5-4-1 年月日改变时弹出信息</h4>
<p>
<input type="text" class="Wdate" id="d" onFocus="WdatePicker({dchanging:cDayFunc,Mchanging:cMonthFunc,ychanging:cYearFunc,dchanged:cDayFunc,Mchanged:cMonthFunc,ychanged:cYearFunc})"/>
<script>
function cDayFunc(){
cFunc('d');
}
function cMonthFunc(){
cFunc('M');
}
function cYearFunc(){
cFunc('y');
}
function cFunc(who){
var str,p,c = $dp.cal;
if(who=='y'){
str='年份';
p='y';
}
else if(who=='M'){
str='月份';
p='M';
}
else if(who=='d'){
str='日期';
p='d';
}
alert(str+'发生改变了!\n$dp.cal.date.'+p+'='+c.date[p]+'\n$dp.cal.newdate.'+p+'='+c.newdate[p]);
}
</script>
<br />
<input type="text" class="Wdate" onFocus="WdatePicker({<span class="STYLE2">dchanging:<span class="STYLE1">cDayFunc</span>, Mchanging:</span><span class="STYLE1">cMonthFunc</span>,<span class="STYLE2"> ychanging:</span><span class="STYLE1">cYearFunc</span>,<span class="STYLE2"> dchanged:<span class="STYLE1">cDayFunc</span>, Mchanged:</span><span class="STYLE1">cMonthFunc</span>, <span class="STYLE2">ychanged:</span><span class="STYLE1">cYearFunc</span>})"/><br />
<span class="STYLE1"><script></span><br />
<span class="STYLE2">function</span> cDayFunc(){<br />
cFunc('d');<br />
}<br />
<span class="STYLE2">function</span> cMonthFunc(){<br />
cFunc('M');<br />
}<br />
<span class="STYLE2">function</span> cYearFunc(){<br />
cFunc('y');<br />
}<br />
<span class="STYLE2">function</span> cFunc(who){<br />
var str,p,c = $dp.cal;<br />
if(who=='y'){<br />
str='年份';<br />
p='y';<br />
}<br />
else if(who=='M'){<br />
str='月份';<br />
p='M';<br />
}<br />
else if(who=='d'){<br />
str='日期';<br />
p='d';<br />
}<br />
alert(str+'发生改变了!\n$dp.cal.date.'+p+'='+c.date[p]+'\n$dp.cal.newdate.'+p+'='+c.newdate[p]);<br />
}<span class="STYLE1"><br />
</script></span><br />
<br />
这个例子用到了 $dp.cal.date 和 $dp.cal.newdate 属性,你能从这里发现他们的不同之处吗?<br />
下面是有关这两个属性的描述详见<a href="999.asp.htm#m5" tppabs="http://www.my97.net/dp/demo/resource/999.asp#m5">内置函数和属性</a>
</p>
</div>
<p><br />
</p>
</li>
</ol>
<h3><a href="2.6.asp.htm" tppabs="http://www.my97.net/dp/demo/resource/2.6.asp">6. 快速选择功能</a> <a name="m26" id="m26"></a></h3>
<h2><a href="3.asp.htm" tppabs="http://www.my97.net/dp/demo/resource/3.asp">三. 配置说明</a><a name="m3" id="m3"></a></h2>
<h2><a href="999.asp.htm" tppabs="http://www.my97.net/dp/demo/resource/999.asp">四. 如何使用</a><a name="m4" id="m4"></a></h2>
<br />
<br />
</div>
<div style="clear:both"></div>
</div>
<div class="dCenter dBody" style="padding-left:72px">
<script type="text/javascript"><!--
google_ad_client = "ca-pub-6343250634002651";
/* 底部 */
google_ad_slot = "0599809152";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript">
</script>
</div>
<div id="footer" class="dCenter">© 2010 <a href="mailto:[email protected]">My97</a> All Rights Reserved. <script type="text/javascript">
var _bdhmProtocol = (("https:" == document.location.protocol) ? " https://" : " http://");
document.write(unescape("%3Cscript src='" + _bdhmProtocol + "hm.baidu.com/h.js%3F489957c212e14340592fb2e4921b2f1d' type='text/javascript'%3E%3C/script%3E"));
</script> 浙ICP备11060275号
</div>
</body>
</html>
| {
"pile_set_name": "Github"
} |
<html>
<head>
<link href="/static/css/bootstrap-2.3.2.min.css" rel="stylesheet">
<link href="/static/css/bootstrap-responsive-2.3.2.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h3>Fluxtream privacy policy and terms of use</h3>
<h4>1. Your data belongs to you</h4>
<p>Your data belongs to you. It doesn’t belong to us, and it doesn’t belong to any third parties either.
Fluxtream’s mission is to help you organize and understand your data, and in service of this mission, we will store and perform computations on your data.
We will never share your data with third parties without your explicit permission.
And we will never lock you in: you can download your data and/or delete your account at any time.
(As of October 2013, we’re still working on adding a download button inside Fluxtream.
In the meantime please send email to [email protected] and we’ll arrange to give you a snapshot of your data.)</p>
<h4>2. We will protect your data</h4>
We will secure and protect your data. While our servers are located in the United States and we’re subject to the laws of the U.S., we’ll push back as strongly as we legally can on any governmental requests for data from our servers. (And we’re prepared to move operations to a country that better respects privacy if the climate in the U.S. doesn’t improve.)
<h4>3. We carefully use third-party tools, in limited circumstances</h4>
Like other websites, we stand on the shoulders of giants by using some great tools to help us scale, debug, and analyze how well Fluxtream is working for you. To perform these tasks, some of these third-party tools will have access to very limited information: traffic patterns and visits. Never your personal data. We’ll also be very careful in the selection of these tools to make sure any traffic patterns and visit information are used solely in service of Fluxtream and you, and not further utilized or distributed.
<h4>4. We’re not perfect</h4>
We’ll do our best to grow and maintain Fluxtream for you, and to respond to problems you let us know about. But we can’t promise you that Fluxtream will always be available, and that we’ll never lose data or make other mistakes. In using this service, you agree that the only remedies for problems resulting from your use of Fluxtream are (1) a sincere and personal apology, and (2) a refund of whatever amount you might have paid to Fluxtream. Which at the moment (good news and bad news) is zero, since Fluxtream’s service is free of charge, at least until/if we ever roll out any paid services in the future.
<h4> 5. Fluxtream is not a medical service</h4>
In using Fluxtream, you agree that Fluxtream isn’t a medical service.
</div>
</body>
</html> | {
"pile_set_name": "Github"
} |
/* Bulgarian initialisation for the jQuery UI date picker plugin. */
/* Written by Stoyan Kyosev (http://svest.org). */
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define([ "../datepicker" ], factory );
} else {
// Browser globals
factory( jQuery.datepicker );
}
}(function( datepicker ) {
datepicker.regional['bg'] = {
closeText: 'затвори',
prevText: '<назад',
nextText: 'напред>',
nextBigText: '>>',
currentText: 'днес',
monthNames: ['Януари','Февруари','Март','Април','Май','Юни',
'Юли','Август','Септември','Октомври','Ноември','Декември'],
monthNamesShort: ['Яну','Фев','Мар','Апр','Май','Юни',
'Юли','Авг','Сеп','Окт','Нов','Дек'],
dayNames: ['Неделя','Понеделник','Вторник','Сряда','Четвъртък','Петък','Събота'],
dayNamesShort: ['Нед','Пон','Вто','Сря','Чет','Пет','Съб'],
dayNamesMin: ['Не','По','Вт','Ср','Че','Пе','Съ'],
weekHeader: 'Wk',
dateFormat: 'dd.mm.yy',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ''};
datepicker.setDefaults(datepicker.regional['bg']);
return datepicker.regional['bg'];
}));
| {
"pile_set_name": "Github"
} |
/**
* @file
* @brief Reaction fire code
*
* Note that in a turn-based game, reaction fire is a design bug in the first place,
* causing several logic problems. But we want it and we need it, so we'll have to
* work around those problems.
*
* Imagine the following situations:
* One of your soldiers is standing next to a house by a street. There is an alien down
* the street with a gun in snap shot mode (8 TUs). The soldier steps out on street, trying
* to cross it (and entering the line of sight of that alien). After 4 more paces or spending
* 8 TUs, your soldier is shot by the alien. Sounds reasonable? Fine. That's the basic idea
* of reaction fire.
*
* Now assume you have 5 soldiers next to that house. They all step out on the street. Nothing
* happens because they all just entered the line of sight of the alien. The first soldier
* starts walking and gets shot after 4 paces like above. The second soldier will walk 7 paces
* unharmed and get shot after 8 paces and the third soldier will be shot after 12 paces/24 TUs.
* This is because when the alien shoots at one target, all his other targets will receive a
* bonus equal to the amount of TUs the alien used for his shot. Still sounds reasonable? Fine.
*
* A slight modification: only one of the 5 soldiers steps out and gets shot after 4 paces.
* Then the 2nd steps out and gets shot after 4 paces as well. Likewise the 3rd soldier.
* That's because the soldiers hidden behind the house are not among the targets of the alien
* and thus don't receive the bonus when the alien shoots,
*
* There is also a problem at end of turn. Imagine your sniper is set to react with an aimed
* shot (18 Tus). An alien steps into his line of sight and fires two snap shots, totaling
* 16 TUs. Then the alien decides to do nothing for the rest of his round. You would love to
* see your sniper do his aimed shot, right ? But reaction fire rules don't allow that.
* On the other hand: if you (were stupid enough to) move one of your soldiers with his last
* 2 TUs out from cover and into the sight of an alien on RF with all his TUs still available,
* your soldier will receive no RF, due to the same RF rules. You love that, right ?
*
* Reaction fire is involved in the following situations:
* 1. G_ReactionFireOnMovement()
* calls G_ReactionFireCheckExecution()
* calls G_ReactionFireTryToShoot()
* calls G_ReactionFireTargetsUpdateAll()
* 2. G_ClientShoot()
* calls G_ReactionFirePreShot()
* calls G_ReactionFireTargetsUpdateAll()
* calls G_ReactionFireTryToShoot()
* calls G_ReactionFirePostShot()
* calls G_ReactionFireCheckExecution()
* calls G_ReactionFireTryToShoot()
* 3. G_ClientEndRound()
* calls G_ReactionFireOnEndTurn()
* calls G_ReactionFireTryToShoot()
* calls G_ReactionFireReset()
*/
/*
Copyright (C) 2002-2020 UFO: Alien Invasion.
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.
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, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "g_reaction.h"
#include "g_actor.h"
#include "g_client.h"
#include "g_combat.h"
#include "g_edicts.h"
#include "g_match.h"
#include "g_vis.h"
#define MAX_RF_TARGETS 10
#define MAX_RF_DATA 128
#define DEBUG_RF 0
/** @brief A single relation between a shooter and his target. */
class ReactionFireTarget
{
public:
Edict const* target;
int triggerTUs; /* the amount of TUS of the target(!) at which the reaction takes place */
};
#define RF_NO_ENTNUM -1
/** @brief A list of relations between a shooter and all his targets. */
class ReactionFireTargetList
{
public:
int entnum;
int count;
ReactionFireTarget targets[MAX_RF_TARGETS];
ReactionFireTargetList () {
OBJZERO(targets);
init();
}
inline void init (void) {
entnum = RF_NO_ENTNUM;
count = 0;
}
inline void reset (void) {
count = 0;
}
};
/** @brief A table with all the relations between all shooters and all their targets. */
class ReactionFireTargets
{
public:
void init();
void add(const Edict* shooter, const Edict* target, const int tusForShot);
void remove(const Edict* shooter, const Edict* target);
bool hasExpired(const Edict* shooter, const Edict* target, const int tusTarget);
int getTriggerTUs(const Edict* shooter, const Edict* target);
void advance(const Edict* shooter, const int tusShot);
void reset();
void notifyClientMove(const Edict* target, int step, bool startMove);
void notifyClientOnStep(const Edict* target, int step);
void create(const Edict* shooter);
void destroy(const Edict* shooter);
void resetTargetList(const Edict* shooter);
void notifyClientOnShot(const Edict* target, int step);
void notifyClientRFAborted(const Edict* shooter, const Edict* target, int step);
private:
ReactionFireTargetList rfData[MAX_RF_DATA];
ReactionFireTargetList* find (const Edict* shooter);
};
static ReactionFireTargets rft;
/**
* @brief Initialize the reaction fire table for all entities.
*/
void ReactionFireTargets::init (void)
{
for (int i = 0; i < MAX_RF_DATA; i++) {
rfData[i].init();
}
}
/**
* @brief Reset the target count in the reaction fire table for all entities.
*/
void ReactionFireTargets::reset (void)
{
for (int i = 0; i < MAX_RF_DATA; i++) {
rfData[i].reset();
}
}
void ReactionFireTargets::notifyClientOnStep (const Edict* target, int step)
{
for (int i = 0; i < MAX_RF_DATA; i++) {
ReactionFireTargetList* rfts = &rfData[i];
if (rfts->entnum == RF_NO_ENTNUM)
continue;
const Edict* shooter = G_EdictsGetByNum(rfts->entnum);
for (int j = 0; j < rfts->count; j++) {
ReactionFireTarget& t = rfts->targets[j];
if (t.target != target)
continue;
const int tus = std::max(0, target->TU - t.triggerTUs);
G_EventReactionFireTargetUpdate(*shooter, *target, tus, step);
}
}
}
void ReactionFireTargets::notifyClientOnShot (const Edict* target, int tusTarget)
{
for (int i = 0; i < MAX_RF_DATA; i++) {
ReactionFireTargetList* rfts = &rfData[i];
if (rfts->entnum == RF_NO_ENTNUM)
continue;
const Edict* shooter = G_EdictsGetByNum(rfts->entnum);
for (int j = 0; j < rfts->count; j++) {
ReactionFireTarget& t = rfts->targets[j];
if (t.target != target)
continue;
const int tus = std::max(0, target->TU - tusTarget - t.triggerTUs);
G_EventReactionFireTargetUpdate(*shooter, *target, tus, MAX_ROUTE);
}
}
}
void ReactionFireTargets::notifyClientMove (const Edict* target, int step, bool startMove)
{
for (int i = 0; i < MAX_RF_DATA; i++) {
ReactionFireTargetList* rfts = &rfData[i];
if (rfts->entnum == RF_NO_ENTNUM)
continue;
const Edict* shooter = G_EdictsGetByNum(rfts->entnum);
for (int j = 0; j < rfts->count; j++) {
if (rfts->targets[j].target != target)
continue;
if (startMove) {
const int tus = std::max(0, target->TU - rfts->targets[j].triggerTUs);
G_EventReactionFireAddTarget(*shooter, *target, tus, step);
} else {
G_EventReactionFireRemoveTarget(*shooter, *target, step);
}
}
}
}
void ReactionFireTargets::notifyClientRFAborted (const Edict* shooter, const Edict* target, int step)
{
ReactionFireTargetList* rfts = find(shooter);
assert(rfts);
for (int i = 0; i < rfts->count; i++) {
ReactionFireTarget& t = rfts->targets[i];
if (t.target != target)
continue;
G_EventReactionFireAbortShot(*shooter, *target, step);
}
}
/**
* @brief Find the given edict's table of reaction fire targets.
* @param[in] shooter The reaction firing actor
*/
ReactionFireTargetList* ReactionFireTargets::find (const Edict* shooter)
{
for (int i = 0; i < MAX_RF_DATA; i++) {
ReactionFireTargetList* rfts = &rfData[i];
if (rfts->entnum == shooter->getIdNum()) {
return rfts;
}
}
return nullptr;
}
/**
* @brief Create a table of reaction fire targets for the given edict.
* @param[in] shooter The reaction firing actor
*/
void ReactionFireTargets::create (const Edict* shooter)
{
const ReactionFireTargetList* rfts = find(shooter);
if (rfts)
gi.Error("Entity already has rfData");
for (int i = 0; i < MAX_RF_DATA; i++) {
ReactionFireTargetList& data = rfData[i];
if (data.entnum != RF_NO_ENTNUM)
continue;
data.entnum = shooter->getIdNum();
return;
}
gi.Error("Not enough rfData");
}
/**
* @brief Destroys the table of reaction fire targets for the given edict.
* @param[in] shooter The reaction firing actor
*/
void ReactionFireTargets::destroy (const Edict* shooter)
{
ReactionFireTargetList* rfts = find(shooter);
if (!rfts) {
gi.DPrintf("Entity doesn't have rfData");
return;
}
rfts->init();
}
/**
* @brief Add a reaction fire target for the given shooter.
* @param[in] shooter The reaction firing actor
* @param[in] target The potential reaction fire victim
* @param[in] tusForShot The TUs needed for the shot
*/
void ReactionFireTargets::add (const Edict* shooter, const Edict* target, const int tusForShot)
{
int i;
ReactionFireTargetList* rfts = find(shooter);
assert(rfts);
assert(target);
for (i = 0; i < rfts->count; i++) {
/* check if shooter already knows that target */
if (rfts->targets[i].target == target)
return;
}
if (i >= MAX_RF_TARGETS)
return;
rfts->targets[i].target = target;
rfts->targets[i].triggerTUs = target->TU - tusForShot;
rfts->count++;
G_EventReactionFireAddTarget(*shooter, *target, tusForShot, target->moveinfo.steps - 1);
#if DEBUG_RF
if (!(G_IsAlien(shooter) || G_IsCivilian(shooter)))
Com_Printf("S%i: added\n", shooter->number);
#endif
}
/**
* @brief Remove a reaction fire target for the given shooter.
* @param[in] shooter The reaction firing actor
* @param[in] target The potential reaction fire victim
*/
void ReactionFireTargets::remove (const Edict* shooter, const Edict* target)
{
ReactionFireTargetList* rfts = find(shooter);
assert(rfts);
assert(target);
for (int i = 0; i < rfts->count; i++) {
ReactionFireTarget& t = rfts->targets[i];
if (t.target != target)
continue;
/* not the last one? */
if (i != rfts->count - 1) {
t.target = rfts->targets[rfts->count - 1].target;
t.triggerTUs = rfts->targets[rfts->count - 1].triggerTUs;
}
rfts->count--;
G_EventReactionFireRemoveTarget(*shooter, *target, target->moveinfo.steps - 1);
#if DEBUG_RF
if (!(G_IsAlien(shooter) || G_IsCivilian(shooter)))
Com_Printf("S%i: removed\n", shooter->number);
#endif
}
}
void ReactionFireTargets::resetTargetList (const Edict* shooter)
{
ReactionFireTargetList* rfts = find(shooter);
for (int i = rfts->count - 1; i >= 0; --i)
remove(shooter, rfts->targets[i].target);
rfts->reset();
}
/**
* @brief Check if the given shooter is ready to reaction fire at the given target.
* @param[in] shooter The reaction firing actor
* @param[in] target The potential reaction fire victim
* @return The TUs the target will need to reach until the RF shot goes off.
*/
int ReactionFireTargets::getTriggerTUs (const Edict* shooter, const Edict* target)
{
const ReactionFireTargetList* rfts = find(shooter);
if (!rfts)
return -2; /* the shooter doesn't aim at anything */
assert(target);
for (int i = 0; i < rfts->count; i++) {
const ReactionFireTarget& t = rfts->targets[i];
if (t.target == target)
return t.triggerTUs;
}
return -1; /* the shooter doesn't aim at this target */
}
/**
* @brief Check if the given shooter is ready to reaction fire at the given target.
* @param[in] shooter The reaction firing actor
* @param[in] target The potential reaction fire victim
* @param[in] tusTarget The TUs the target will need for the shot, 0 for just moving
*/
bool ReactionFireTargets::hasExpired (const Edict* shooter, const Edict* target, const int tusTarget)
{
const ReactionFireTargetList* rfts = find(shooter);
if (!rfts)
return false; /* the shooter doesn't aim at anything */
assert(target);
for (int i = 0; i < rfts->count; i++) {
const ReactionFireTarget& t = rfts->targets[i];
if (t.target == target)
return t.triggerTUs >= target->TU - tusTarget;
}
return false; /* the shooter doesn't aim at this target */
}
/**
* @brief Increase the triggertime for the next RF shot for all targets of the shooter (after a reaction fire).
* @param[in] shooter The reaction firing actor
* @param[in] tusShot The TUs the shooter will need for the next shot
*/
void ReactionFireTargets::advance (const Edict* shooter, const int tusShot)
{
ReactionFireTargetList* rfts = find(shooter);
assert(rfts);
for (int i = 0; i < rfts->count; i++) {
ReactionFireTarget& t = rfts->targets[i];
t.triggerTUs -= tusShot;
}
}
/**
* @brief free function to initialize the reaction fire table for all entities.
*/
void G_ReactionFireTargetsInit (void)
{
rft.init();
}
/**
* @brief free function to create a table of reaction fire targets for the given edict.
* @param[in] shooter The reaction firing actor
*/
void G_ReactionFireTargetsCreate (const Edict* shooter)
{
rft.create(shooter);
}
/**
* @brief free function to destroy the table of reaction fire targets for the given edict.
* @param[in] shooter The reaction firing actor
*/
void G_ReactionFireTargetsDestroy (const Edict* shooter)
{
rft.destroy(shooter);
}
class ReactionFire
{
private:
bool isEnemy(const Actor* shooter, const Edict* target) const;
bool canReact(Actor* shooter, const Edict* target) const;
bool canSee(const Actor* shooter, const Edict* target) const;
bool shoot(Actor* shooter, const pos3_t at, shoot_types_t type, fireDefIndex_t firemode);
bool isPossible(Actor* shooter, const Edict* target) const;
public:
void notifyClientOnStep(const Edict* target, int step);
bool checkExecution(const Edict* target, int step);
void updateAllTargets(const Edict* target);
bool tryToShoot(Actor* shooter, const Edict* target);
bool isInWeaponRange(const Actor* shooter, const Edict* target, const fireDef_t* fd) const;
const fireDef_t* getFireDef(const Actor* shooter) const;
void resetTargets(const Edict* shooter);
void notifyClientOnShot(const Edict* target, int tusTarget);
};
static ReactionFire rf;
/**
* @brief Get the fireDef for the RF settings of the shooter.
* @param[in] shooter The reaction firing actor
* @return nullptr if something is wrong
*/
const fireDef_t* ReactionFire::getFireDef (const Actor* shooter) const
{
const FiremodeSettings* fmSetting = &shooter->chr.RFmode;
if (!fmSetting->isSaneFiremode())
return nullptr;
const Item* weapon = shooter->getHandItem(fmSetting->getHand());
if (weapon && weapon->ammoDef() && weapon->isWeapon() && !weapon->mustReload()) {
const fireDef_t* fdArray = weapon->getFiredefs();
if (fdArray == nullptr)
return nullptr;
const fireDefIndex_t fmIdx = fmSetting->getFmIdx();
return &fdArray[fmIdx];
}
return nullptr;
}
bool ReactionFire::isInWeaponRange (const Actor* shooter, const Edict* target, const fireDef_t* fd) const
{
assert(fd);
return fd->range >= VectorDist(shooter->origin, target->origin);
}
/**
* @brief Get the weapon firing TUs of the item in the hand of the shooter.
* @return -1 if no firedef was found for the item or the reaction fire mode is not activated.
* @param[in] shooter The reaction firing actor
* @param[in] target The target to check reaction fire for (e.g. check whether the weapon that was marked for
* using in reaction fire situations can handle the distance between the shooter and the target)
*/
static int G_ReactionFireGetTUsForItem (const Actor* shooter, const Edict* target)
{
const fireDef_t* fd = rf.getFireDef(shooter);
if (!fd)
return -1;
const int tus = G_ActorGetModifiedTimeForFiredef(shooter, fd, true);
if (tus <= shooter->TU && rf.isInWeaponRange(shooter, target, fd)) {
return tus;
}
return -1;
}
/**
* @brief Checks if the currently selected firemode is usable with the defined weapon.
* @param[in] actor The actor to check the firemode for.
*/
static bool G_ActorHasWorkingFireModeSet (const Edict* actor)
{
const FiremodeSettings* fmSettings = &actor->chr.RFmode;
if (!fmSettings->isSaneFiremode()) /* just checks for valid values */
return false;
const Item* weapon = actor->getHandItem(fmSettings->getHand());
if (!weapon)
return false;
const fireDef_t* fd = weapon->getFiredefs();
if (fd == nullptr)
return false;
if (fd->obj->weapons[fd->weapFdsIdx] == fmSettings->getWeapon()
&& fmSettings->getFmIdx() < fd->obj->numFiredefs[fd->weapFdsIdx]) {
return true;
}
return false;
}
/**
* @brief Updates the reaction fire settings in case something was moved into a hand or from a hand
* that would make the current settings invalid
* @param[in,out] actor The actor edict to check the settings for
* @param[in] fmIdx The fire mode index that should be used for reaction fire
* @param[in] hand The hand that should be used for reaction fire
* @param[in] od The object/weapon for the reaction fire
*/
void G_ReactionFireSettingsUpdate (Actor* actor, fireDefIndex_t fmIdx, actorHands_t hand, const objDef_t* od)
{
actor->chr.RFmode.set(hand, fmIdx, od); /* FiremodeSettings */
if (!G_ActorHasWorkingFireModeSet(actor)) {
/* Disable reaction fire if no valid firemode was found. */
G_ClientStateChange(actor->getPlayer(), actor, ~STATE_REACTION, false);
G_EventReactionFireChange(*actor);
G_EventSendState(G_VisToPM(actor->visflags), *actor);
return;
}
G_EventReactionFireChange(*actor);
/* If reaction fire is active, update the reserved TUs */
if (actor->isReaction()) {
G_ReactionFireSettingsReserveTUs(actor);
}
}
/**
* @brief Checks whether an actor has enough TUs left to activate reaction fire.
* @param[in] ent The actors edict to check for TUs for
* @return @c true if the given actor has enough TUs left to activate reaction fire, @c false otherwise.
*/
static bool G_ActorHasEnoughTUsReactionFire (const Edict* ent)
{
const int TUs = G_ActorGetTUForReactionFire(ent);
const chrReservations_t* res = &ent->chr.reservedTus;
return ent->TU - TUs >= res->shot + res->crouch;
}
/**
* @param ent The actor to set the reaction fire for
* @return @c true if the needed settings could have been made or settings are
* already valid, @c false otherwise.
*/
static bool G_ReactionFireSettingsSetDefault (Edict* ent)
{
if (G_ActorHasWorkingFireModeSet(ent))
return true;
actorHands_t hand = ACTOR_HAND_RIGHT;
const Item* item = ent->getHandItem(hand);
if (!item) {
hand = ACTOR_HAND_LEFT;
item = ent->getHandItem(hand);
}
if (!item)
return false;
const objDef_t* weapon = item->getReactionFireWeaponType();
if (!weapon)
return false;
ent->chr.RFmode.set(hand, 0, weapon); /* no special firemode */
if (!G_ActorHasWorkingFireModeSet(ent))
return false;
if (!G_IsAI(ent))
G_EventReactionFireChange(*ent);
return true;
}
/**
* @brief Checks whether the actor is allowed to activate reaction fire and will informs the player about
* the reason if this would not work.
* @param[in] ent The actor to check
* @return @c true if the actor is allowed to activate it, @c false otherwise
*/
static bool G_ReactionFireCanBeEnabled (const Edict* ent)
{
/* check ent is a suitable shooter */
if (!ent->inuse || !G_IsLivingActor(ent))
return false;
if (G_MatchIsRunning() && ent->getTeam() != level.activeTeam)
return false;
/* actor may not carry weapons at all - so no further checking is needed */
if (!ent->chr.teamDef->weapons && !ent->chr.teamDef->onlyWeapon)
return false;
if (!ent->chr.inv.holdsReactionFireWeapon()) {
G_ClientPrintf(ent->getPlayer(), PRINT_HUD, _("No reaction fire enabled weapon."));
return false;
}
if (!G_ActorHasWorkingFireModeSet(ent)) {
G_ClientPrintf(ent->getPlayer(), PRINT_HUD, _("No fire mode selected for reaction fire."));
return false;
}
if (!G_ActorHasEnoughTUsReactionFire(ent)) {
G_ClientPrintf(ent->getPlayer(), PRINT_HUD, _("Not enough TUs left for activating reaction fire."));
return false;
}
return true;
}
/**
* @brief Set the reaction fire TU reservation for an actor
* @param[in,out] ent The actor edict to set the TUs for
* @return @c true if TUs for reaction fire were reserved, @c false if the reservation was set
* back to @c 0
*/
bool G_ReactionFireSettingsReserveTUs (Actor* ent)
{
if (G_ReactionFireSettingsSetDefault(ent) && G_ReactionFireCanBeEnabled(ent)) {
const int TUs = G_ActorGetTUForReactionFire(ent);
/* Enable requested reaction fire. */
G_ActorReserveTUs(ent, TUs, ent->chr.reservedTus.shot, ent->chr.reservedTus.crouch);
return true;
}
G_ActorReserveTUs(ent, 0, ent->chr.reservedTus.shot, ent->chr.reservedTus.crouch);
return false;
}
inline bool ReactionFire::isPossible (Actor* shooter, const Edict* target) const
{
return isEnemy(shooter, target) && canReact(shooter, target) && canSee(shooter, target);
}
/**
* @brief Check whether we want to shoot at the target.
* @param[in] shooter The entity that might be firing
* @param[in] target The entity that might be fired at
*/
bool ReactionFire::isEnemy (const Actor* shooter, const Edict* target) const
{
/* an entity can't reaction fire at itself */
if (shooter == target)
return false;
/* Don't react in your own turn */
if (shooter->getTeam() == level.activeTeam)
return false;
if (G_IsDead(target))
return false;
/* If reaction fire is triggered by a friendly unit
* and the shooter is still sane, don't shoot;
* well, if the shooter isn't sane anymore... */
if (G_IsCivilian(target) || target->isSameTeamAs(shooter))
if (!shooter->isShaken() || (float) shooter->morale / mor_shaken->value > frand())
return false;
return true;
}
/**
* @brief Check whether shooter can reaction fire at target at all.
* @param[in] shooter The entity that might be firing
* @param[in] target The entity that might be fired at
*/
bool ReactionFire::canReact (Actor* shooter, const Edict* target) const
{
/* shooter can't use RF if is in STATE_DAZED (flashbang impact) */
if (shooter->isDazed())
return false;
/* check shooter has reaction fire enabled */
if (!shooter->isReaction())
return false;
/* check shooter has weapon in RF hand */
if (!shooter->getHandItem(shooter->chr.RFmode.getHand())) {
/* print character info if this happens, for now */
gi.DPrintf("Reaction fire enabled but no weapon for hand (name=%s,entnum=%i,hand=%i,fmIdx=%i)\n",
shooter->chr.name, shooter->getIdNum(), shooter->chr.RFmode.getHand(), shooter->chr.RFmode.getFmIdx());
shooter->removeReaction();
return false;
}
return true;
}
/**
* @brief Check whether shooter can see his target well enough
* @param[in] shooter The entity that might be firing
* @param[in] target The entity that might be fired at
*/
bool ReactionFire::canSee (const Actor* shooter, const Edict* target) const
{
if (!G_IsVisibleForTeam(target, shooter->getTeam()))
return false;
/* check in range and visible */
const int spotDist = G_VisCheckDist(shooter);
if (VectorDistSqr(shooter->origin, target->origin) > spotDist * spotDist)
return false;
const bool frustum = G_FrustumVis(shooter, target->origin);
if (!frustum)
return false;
const float actorVis = G_ActorVis(shooter, target, true);
if (actorVis < ACTOR_VIS_10)
return false;
return true;
}
/**
* @brief Check whether 'target' has just triggered any new reaction fire
* @param[in] target The entity triggering fire
*/
void ReactionFire::updateAllTargets (const Edict* target)
{
Actor* shooter = nullptr;
/* check all possible shooters */
while ((shooter = G_EdictsGetNextLivingActor(shooter))) {
/* check whether reaction fire is possible (friend/foe, LoS) */
if (isPossible(shooter, target)) {
const int TUs = G_ReactionFireGetTUsForItem(shooter, target);
if (TUs < 0)
continue; /* no suitable weapon */
rft.add(shooter, target, TUs);
} else {
rft.remove(shooter, target);
}
}
}
void ReactionFire::resetTargets (const Edict* shooter)
{
rft.resetTargetList(shooter);
}
/**
* @brief Perform the reaction fire shot
* @param[in] shooter The actor that is trying to shoot
* @param[in] at Position to fire on.
* @param[in] type What type of shot this is (left, right reaction-left etc...).
* @param[in] firemode The firemode index of the ammo for the used weapon (objDef.fd[][x]) .
* @return true if everything went ok (i.e. the shot(s) where fired ok), otherwise false.
* @sa G_ClientShoot
*/
bool ReactionFire::shoot (Actor* shooter, const pos3_t at, shoot_types_t type, fireDefIndex_t firemode)
{
const Item* weapon = nullptr;
if (IS_SHOT_RIGHT(type)) {
weapon = shooter->getRightHandItem();
if (!weapon)
return false;
} else {
weapon = shooter->getLeftHandItem();
if (!weapon)
return false;
}
const fireDef_t* fdArray = weapon->getFiredefs();
if (!fdArray)
return false;
/* Adjust the number of samples we take so that we don't end firing thousands of shots
* in case the fire mode is multi-shot */
const int shotsPerFD = fdArray[firemode].shots;
const int samples = std::max(1, 100 / shotsPerFD);
const Player& player = shooter->getPlayer();
shot_mock_t mock;
for (int i = 0; i < samples; ++i)
if (!G_ClientShoot(player, shooter, at, type, firemode, &mock, false, 0))
break;
/* this is the max amount of friendly units that were hit during the mock calculation */
const int maxShots = samples * shotsPerFD;
int maxff;
if (shooter->isInsane())
maxff = maxShots;
else if (shooter->isRaged())
maxff = maxShots * 2 / 3;
else if (shooter->isPanicked())
maxff = maxShots / 3;
else if (shooter->isShaken())
maxff = maxShots / 6;
else
maxff = maxShots / 20;
/* calculate the mock values - e.g. how many friendly units we would hit
* when opening the reaction fire */
const int ff = mock.friendCount + (G_IsAlien(shooter) ? 0 : mock.civilian);
const int hits = shooter->isInsane() ? ff + mock.enemyCount : mock.enemyCount;
if (ff <= maxff && hits > 0)
return G_ClientShoot(player, shooter, at, type, firemode, nullptr, false, 0);
return false;
}
/**
* @brief Resolve the reaction fire for an entity, this checks that the entity can fire and then takes the shot
* @param[in] shooter The entity using reaction fire
* @param[in] target The victim of the reaction fire
* @return true if the entity fired, false otherwise
*/
bool ReactionFire::tryToShoot (Actor* shooter, const Edict* target)
{
/* check for valid target */
assert(target);
/* shooter can't take a reaction shot if it's not possible - and check that
* the target is still alive */
if (!isPossible(shooter, target)) {
rft.remove(shooter, target);
return false;
}
/* take the shot */
const actorHands_t hand = shooter->chr.RFmode.getHand();
const shoot_types_t type = (hand == ACTOR_HAND_RIGHT ? ST_RIGHT_REACTION
: (hand == ACTOR_HAND_LEFT ? ST_LEFT_REACTION : ST_NUM_SHOOT_TYPES));
const bool tookShot = rf.shoot(shooter, target->pos, type, shooter->chr.RFmode.getFmIdx());
if (tookShot) {
/* clear any shakenness */
shooter->removeShaken();
}
return tookShot;
}
void ReactionFire::notifyClientOnShot (const Edict* target, int tusTarget)
{
rft.notifyClientOnShot(target, tusTarget);
}
void ReactionFire::notifyClientOnStep (const Edict* target, int step)
{
rft.notifyClientOnStep(target, step);
}
/**
* @brief Check all entities to see whether target has caused reaction fire to resolve.
* @param[in] target The entity that might be resolving reaction fire
* @param[in] step The number of the step in the move we are checking reactions for
* @returns whether any entity fired (or would fire) upon target
* @sa G_ReactionFireOnMovement
* @sa G_ReactionFirePostShot
*/
bool ReactionFire::checkExecution (const Edict* target, int step)
{
Actor* shooter = nullptr;
bool fired = false;
/* check all possible shooters */
while ((shooter = G_EdictsGetNextLivingActor(shooter))) {
const int tus = G_ReactionFireGetTUsForItem(shooter, target);
/* indicates an RF weapon is there */
if (tus <= 1)
continue;
if (!rft.hasExpired(shooter, target, 0))
continue;
if (!rf.tryToShoot(shooter, target)) {
G_ReactionFireNotifyClientRFAborted(shooter, target, step);
continue;
}
rft.advance(shooter, tus);
fired |= true;
}
return fired;
}
#if DEBUG_RF
/**
* @brief Prints some reaction fire data to the console
* @param[in] target The target entity
*/
static void G_ReactionFirePrintSituation (Edict* target)
{
if (!G_IsAlien(target))
return;
Com_Printf("Alien %i at %i/%i/%i TU:%i\n", target->number, target->pos[0], target->pos[1], target->pos[2], target->TU);
Actor* shooter = nullptr;
/* check all possible shooters */
while ((shooter = G_EdictsGetNextLivingActor(shooter))) {
if (G_IsAlien(shooter) || G_IsCivilian(shooter))
continue;
char msgHdr[100];
Com_sprintf(msgHdr, sizeof(msgHdr), "S%i: at %i/%i/%i RF: ", shooter->number, shooter->pos[0], shooter->pos[1], shooter->pos[2]);
int ttus = rft.getTriggerTUs(shooter, target);
if (ttus == -2)
Com_Printf("%s not initialized\n", msgHdr);
if (ttus == -1)
Com_Printf("%s not aiming\n", msgHdr);
else if (rft.hasExpired(shooter, target, 0))
Com_Printf("expired\n", msgHdr);
else
Com_Printf("%s not yet: %i\n", msgHdr, ttus);
}
}
#endif
/**
* @brief Called when 'target' moves, possibly triggering or resolving reaction fire
* @param[in] target The target entity
* @param[in] step The number of the step in the move we are checking reactions for
* @return true If any shots were (or would be) taken
* @sa G_ClientMove
*/
bool G_ReactionFireOnMovement (Actor* target, int step)
{
#if DEBUG_RF
G_ReactionFirePrintSituation(target);
#endif
rf.notifyClientOnStep(target, step);
/* Check to see whether this resolves any reaction fire */
const bool fired = rf.checkExecution(target, step);
/* Check to see whether this triggers any reaction fire */
rf.updateAllTargets(target);
return fired;
}
static void G_ReactionFireNotifyClientStartShot (const Edict* target)
{
rft.notifyClientMove(target, MAX_ROUTE, true);
}
static void G_ReactionFireNotifyClientEndShot (const Edict* target)
{
rft.notifyClientMove(target, MAX_ROUTE, false);
}
/**
* @brief Called when 'target' is about to shoot, this forces a 'draw' to decide who gets the first shot
* @param[in] target The entity about to shoot
* @param[in] fdTime The TU of the shot
* @sa G_ClientShoot
*/
void G_ReactionFirePreShot (const Actor* target, const int fdTime)
{
bool repeat = true;
/* Check to see whether this triggers any reaction fire */
G_ReactionFireNotifyClientStartShot(target);
rf.updateAllTargets(target);
rf.notifyClientOnShot(target, fdTime);
/* if any reaction fire occurs, we have to loop through all entities again to allow
* multiple (fast) RF snap shots before a (slow) aimed shot from the target occurs. */
while (repeat) {
Actor* shooter = nullptr;
repeat = false;
/* check all ents to see who wins and who loses a draw */
while ((shooter = G_EdictsGetNextLivingActor(shooter))) {
const int entTUs = G_ReactionFireGetTUsForItem(shooter, target);
/* indicates an RF weapon is there */
if (entTUs < 1)
continue;
if (!rft.hasExpired(shooter, target, fdTime))
continue;
if (!rf.tryToShoot(shooter, target)) {
G_ReactionFireNotifyClientRFAborted(shooter, target, MAX_ROUTE);
continue;
}
repeat = true;
rft.advance(shooter, entTUs);
}
}
}
/**
* @brief Removes the given target from the reaction fire lists
* @param[in] target The target to remove from the lists
*/
void G_ReactionFireOnDead (const Actor* target)
{
assert(G_IsDead(target));
rf.updateAllTargets(target);
rf.resetTargets(target);
}
/**
* @brief Called after 'target' has fired, this might trigger more reaction fire or resolve outstanding reaction fire (because target is out of time)
* @param[in] target The entity that has just fired
* @sa G_ClientShoot
*/
void G_ReactionFirePostShot (Actor* target)
{
/* Check to see whether this resolves any reaction fire */
rf.notifyClientOnShot(target, 0);
rf.checkExecution(target, MAX_ROUTE);
G_ReactionFireNotifyClientEndShot(target);
}
/**
* @brief Called at the end of turn, all outstanding reaction fire is resolved
* @sa G_ClientEndRound
*/
void G_ReactionFireOnEndTurn (void)
{
/* we explicitly do nothing at end of turn, just reset the table */
rft.reset();
}
/**
* @brief Guess! Reset all "shaken" states on end of turn?
* @note Normally called on end of turn.
* @sa G_ClientStateChange
* @param[in] team Index of team to loop through.
*/
void G_ReactionFireReset (int team)
{
Actor* actor = nullptr;
while ((actor = G_EdictsGetNextLivingActorOfTeam(actor, team))) {
actor->removeShaken();
}
}
void G_ReactionFireNotifyClientStartMove (const Actor* target)
{
/* note that this is sent _before_ the actual move event, so we can't use the step number */
rft.notifyClientMove(target, MAX_ROUTE, true);
}
void G_ReactionFireNotifyClientEndMove (const Actor* target)
{
rft.notifyClientMove(target, target->moveinfo.steps - 1, false);
}
void G_ReactionFireNotifyClientRFAborted (const Actor* shooter, const Edict* target, int step)
{
rft.notifyClientRFAborted(shooter, target, step);
}
| {
"pile_set_name": "Github"
} |
//===--- Range.h - From And Length ------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines range-like structures, to hold what needs to be redrawn
// or which parts of a text have been changed by the editor.
//
// Axel Naumann <[email protected]>, 2011-05-12
//===----------------------------------------------------------------------===//
#include "textinput/Range.h"
namespace textinput {
Range&
Range::Extend(const Range& with) {
if (IsEmpty()) {
*this = with;
return *this;
}
if (with.IsEmpty()) return *this;
size_t wEnd = with.fStart + with.fLength;
if (with.fLength == (size_t) -1) wEnd = (size_t) -1;
size_t end = fStart + fLength;
if (fLength == (size_t) -1) end = (size_t) -1;
fStart = PMin(fStart, with.fStart);
end = PMax(end, wEnd);
if (end == (size_t) -1) {
fLength = (size_t) -1;
} else {
fLength = end - fStart;
}
fPromptUpdate = (EPromptUpdate) (fPromptUpdate | with.fPromptUpdate);
return *this;
}
Range&
Range::Intersect(const Range& with) {
if (IsEmpty()) {
return *this;
}
if (with.IsEmpty()) {
*this = Empty();
return *this;
}
size_t wEnd = with.fStart + with.fLength;
if (with.fLength == (size_t) -1) wEnd = (size_t) -1;
size_t end = fStart + fLength;
if (fLength == (size_t) -1) end = (size_t) -1;
fStart = PMax(fStart, with.fStart);
end = PMin(end, wEnd);
if (end == (size_t) -1) {
fLength = (size_t) -1;
} else {
fLength = end - fStart;
}
return *this;
}
}
| {
"pile_set_name": "Github"
} |
// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2016 The Go Authors. All rights reserved.
// https://github.com/golang/protobuf
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package proto
import (
"errors"
"fmt"
"math"
"reflect"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"unicode/utf8"
)
// a sizer takes a pointer to a field and the size of its tag, computes the size of
// the encoded data.
type sizer func(pointer, int) int
// a marshaler takes a byte slice, a pointer to a field, and its tag (in wire format),
// marshals the field to the end of the slice, returns the slice and error (if any).
type marshaler func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error)
// marshalInfo is the information used for marshaling a message.
type marshalInfo struct {
typ reflect.Type
fields []*marshalFieldInfo
unrecognized field // offset of XXX_unrecognized
extensions field // offset of XXX_InternalExtensions
v1extensions field // offset of XXX_extensions
sizecache field // offset of XXX_sizecache
initialized int32 // 0 -- only typ is set, 1 -- fully initialized
messageset bool // uses message set wire format
hasmarshaler bool // has custom marshaler
sync.RWMutex // protect extElems map, also for initialization
extElems map[int32]*marshalElemInfo // info of extension elements
hassizer bool // has custom sizer
hasprotosizer bool // has custom protosizer
bytesExtensions field // offset of XXX_extensions where the field type is []byte
}
// marshalFieldInfo is the information used for marshaling a field of a message.
type marshalFieldInfo struct {
field field
wiretag uint64 // tag in wire format
tagsize int // size of tag in wire format
sizer sizer
marshaler marshaler
isPointer bool
required bool // field is required
name string // name of the field, for error reporting
oneofElems map[reflect.Type]*marshalElemInfo // info of oneof elements
}
// marshalElemInfo is the information used for marshaling an extension or oneof element.
type marshalElemInfo struct {
wiretag uint64 // tag in wire format
tagsize int // size of tag in wire format
sizer sizer
marshaler marshaler
isptr bool // elem is pointer typed, thus interface of this type is a direct interface (extension only)
}
var (
marshalInfoMap = map[reflect.Type]*marshalInfo{}
marshalInfoLock sync.Mutex
uint8SliceType = reflect.TypeOf(([]uint8)(nil)).Kind()
)
// getMarshalInfo returns the information to marshal a given type of message.
// The info it returns may not necessarily initialized.
// t is the type of the message (NOT the pointer to it).
func getMarshalInfo(t reflect.Type) *marshalInfo {
marshalInfoLock.Lock()
u, ok := marshalInfoMap[t]
if !ok {
u = &marshalInfo{typ: t}
marshalInfoMap[t] = u
}
marshalInfoLock.Unlock()
return u
}
// Size is the entry point from generated code,
// and should be ONLY called by generated code.
// It computes the size of encoded data of msg.
// a is a pointer to a place to store cached marshal info.
func (a *InternalMessageInfo) Size(msg Message) int {
u := getMessageMarshalInfo(msg, a)
ptr := toPointer(&msg)
if ptr.isNil() {
// We get here if msg is a typed nil ((*SomeMessage)(nil)),
// so it satisfies the interface, and msg == nil wouldn't
// catch it. We don't want crash in this case.
return 0
}
return u.size(ptr)
}
// Marshal is the entry point from generated code,
// and should be ONLY called by generated code.
// It marshals msg to the end of b.
// a is a pointer to a place to store cached marshal info.
func (a *InternalMessageInfo) Marshal(b []byte, msg Message, deterministic bool) ([]byte, error) {
u := getMessageMarshalInfo(msg, a)
ptr := toPointer(&msg)
if ptr.isNil() {
// We get here if msg is a typed nil ((*SomeMessage)(nil)),
// so it satisfies the interface, and msg == nil wouldn't
// catch it. We don't want crash in this case.
return b, ErrNil
}
return u.marshal(b, ptr, deterministic)
}
func getMessageMarshalInfo(msg interface{}, a *InternalMessageInfo) *marshalInfo {
// u := a.marshal, but atomically.
// We use an atomic here to ensure memory consistency.
u := atomicLoadMarshalInfo(&a.marshal)
if u == nil {
// Get marshal information from type of message.
t := reflect.ValueOf(msg).Type()
if t.Kind() != reflect.Ptr {
panic(fmt.Sprintf("cannot handle non-pointer message type %v", t))
}
u = getMarshalInfo(t.Elem())
// Store it in the cache for later users.
// a.marshal = u, but atomically.
atomicStoreMarshalInfo(&a.marshal, u)
}
return u
}
// size is the main function to compute the size of the encoded data of a message.
// ptr is the pointer to the message.
func (u *marshalInfo) size(ptr pointer) int {
if atomic.LoadInt32(&u.initialized) == 0 {
u.computeMarshalInfo()
}
// If the message can marshal itself, let it do it, for compatibility.
// NOTE: This is not efficient.
if u.hasmarshaler {
// Uses the message's Size method if available
if u.hassizer {
s := ptr.asPointerTo(u.typ).Interface().(Sizer)
return s.Size()
}
// Uses the message's ProtoSize method if available
if u.hasprotosizer {
s := ptr.asPointerTo(u.typ).Interface().(ProtoSizer)
return s.ProtoSize()
}
m := ptr.asPointerTo(u.typ).Interface().(Marshaler)
b, _ := m.Marshal()
return len(b)
}
n := 0
for _, f := range u.fields {
if f.isPointer && ptr.offset(f.field).getPointer().isNil() {
// nil pointer always marshals to nothing
continue
}
n += f.sizer(ptr.offset(f.field), f.tagsize)
}
if u.extensions.IsValid() {
e := ptr.offset(u.extensions).toExtensions()
if u.messageset {
n += u.sizeMessageSet(e)
} else {
n += u.sizeExtensions(e)
}
}
if u.v1extensions.IsValid() {
m := *ptr.offset(u.v1extensions).toOldExtensions()
n += u.sizeV1Extensions(m)
}
if u.bytesExtensions.IsValid() {
s := *ptr.offset(u.bytesExtensions).toBytes()
n += len(s)
}
if u.unrecognized.IsValid() {
s := *ptr.offset(u.unrecognized).toBytes()
n += len(s)
}
// cache the result for use in marshal
if u.sizecache.IsValid() {
atomic.StoreInt32(ptr.offset(u.sizecache).toInt32(), int32(n))
}
return n
}
// cachedsize gets the size from cache. If there is no cache (i.e. message is not generated),
// fall back to compute the size.
func (u *marshalInfo) cachedsize(ptr pointer) int {
if u.sizecache.IsValid() {
return int(atomic.LoadInt32(ptr.offset(u.sizecache).toInt32()))
}
return u.size(ptr)
}
// marshal is the main function to marshal a message. It takes a byte slice and appends
// the encoded data to the end of the slice, returns the slice and error (if any).
// ptr is the pointer to the message.
// If deterministic is true, map is marshaled in deterministic order.
func (u *marshalInfo) marshal(b []byte, ptr pointer, deterministic bool) ([]byte, error) {
if atomic.LoadInt32(&u.initialized) == 0 {
u.computeMarshalInfo()
}
// If the message can marshal itself, let it do it, for compatibility.
// NOTE: This is not efficient.
if u.hasmarshaler {
m := ptr.asPointerTo(u.typ).Interface().(Marshaler)
b1, err := m.Marshal()
b = append(b, b1...)
return b, err
}
var err, errLater error
// The old marshaler encodes extensions at beginning.
if u.extensions.IsValid() {
e := ptr.offset(u.extensions).toExtensions()
if u.messageset {
b, err = u.appendMessageSet(b, e, deterministic)
} else {
b, err = u.appendExtensions(b, e, deterministic)
}
if err != nil {
return b, err
}
}
if u.v1extensions.IsValid() {
m := *ptr.offset(u.v1extensions).toOldExtensions()
b, err = u.appendV1Extensions(b, m, deterministic)
if err != nil {
return b, err
}
}
if u.bytesExtensions.IsValid() {
s := *ptr.offset(u.bytesExtensions).toBytes()
b = append(b, s...)
}
for _, f := range u.fields {
if f.required {
if f.isPointer && ptr.offset(f.field).getPointer().isNil() {
// Required field is not set.
// We record the error but keep going, to give a complete marshaling.
if errLater == nil {
errLater = &RequiredNotSetError{f.name}
}
continue
}
}
if f.isPointer && ptr.offset(f.field).getPointer().isNil() {
// nil pointer always marshals to nothing
continue
}
b, err = f.marshaler(b, ptr.offset(f.field), f.wiretag, deterministic)
if err != nil {
if err1, ok := err.(*RequiredNotSetError); ok {
// Required field in submessage is not set.
// We record the error but keep going, to give a complete marshaling.
if errLater == nil {
errLater = &RequiredNotSetError{f.name + "." + err1.field}
}
continue
}
if err == errRepeatedHasNil {
err = errors.New("proto: repeated field " + f.name + " has nil element")
}
if err == errInvalidUTF8 {
if errLater == nil {
fullName := revProtoTypes[reflect.PtrTo(u.typ)] + "." + f.name
errLater = &invalidUTF8Error{fullName}
}
continue
}
return b, err
}
}
if u.unrecognized.IsValid() {
s := *ptr.offset(u.unrecognized).toBytes()
b = append(b, s...)
}
return b, errLater
}
// computeMarshalInfo initializes the marshal info.
func (u *marshalInfo) computeMarshalInfo() {
u.Lock()
defer u.Unlock()
if u.initialized != 0 { // non-atomic read is ok as it is protected by the lock
return
}
t := u.typ
u.unrecognized = invalidField
u.extensions = invalidField
u.v1extensions = invalidField
u.bytesExtensions = invalidField
u.sizecache = invalidField
isOneofMessage := false
if reflect.PtrTo(t).Implements(sizerType) {
u.hassizer = true
}
if reflect.PtrTo(t).Implements(protosizerType) {
u.hasprotosizer = true
}
// If the message can marshal itself, let it do it, for compatibility.
// NOTE: This is not efficient.
if reflect.PtrTo(t).Implements(marshalerType) {
u.hasmarshaler = true
atomic.StoreInt32(&u.initialized, 1)
return
}
n := t.NumField()
// deal with XXX fields first
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if f.Tag.Get("protobuf_oneof") != "" {
isOneofMessage = true
}
if !strings.HasPrefix(f.Name, "XXX_") {
continue
}
switch f.Name {
case "XXX_sizecache":
u.sizecache = toField(&f)
case "XXX_unrecognized":
u.unrecognized = toField(&f)
case "XXX_InternalExtensions":
u.extensions = toField(&f)
u.messageset = f.Tag.Get("protobuf_messageset") == "1"
case "XXX_extensions":
if f.Type.Kind() == reflect.Map {
u.v1extensions = toField(&f)
} else {
u.bytesExtensions = toField(&f)
}
case "XXX_NoUnkeyedLiteral":
// nothing to do
default:
panic("unknown XXX field: " + f.Name)
}
n--
}
// get oneof implementers
var oneofImplementers []interface{}
// gogo: isOneofMessage is needed for embedded oneof messages, without a marshaler and unmarshaler
if isOneofMessage {
switch m := reflect.Zero(reflect.PtrTo(t)).Interface().(type) {
case oneofFuncsIface:
_, _, _, oneofImplementers = m.XXX_OneofFuncs()
case oneofWrappersIface:
oneofImplementers = m.XXX_OneofWrappers()
}
}
// normal fields
fields := make([]marshalFieldInfo, n) // batch allocation
u.fields = make([]*marshalFieldInfo, 0, n)
for i, j := 0, 0; i < t.NumField(); i++ {
f := t.Field(i)
if strings.HasPrefix(f.Name, "XXX_") {
continue
}
field := &fields[j]
j++
field.name = f.Name
u.fields = append(u.fields, field)
if f.Tag.Get("protobuf_oneof") != "" {
field.computeOneofFieldInfo(&f, oneofImplementers)
continue
}
if f.Tag.Get("protobuf") == "" {
// field has no tag (not in generated message), ignore it
u.fields = u.fields[:len(u.fields)-1]
j--
continue
}
field.computeMarshalFieldInfo(&f)
}
// fields are marshaled in tag order on the wire.
sort.Sort(byTag(u.fields))
atomic.StoreInt32(&u.initialized, 1)
}
// helper for sorting fields by tag
type byTag []*marshalFieldInfo
func (a byTag) Len() int { return len(a) }
func (a byTag) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a byTag) Less(i, j int) bool { return a[i].wiretag < a[j].wiretag }
// getExtElemInfo returns the information to marshal an extension element.
// The info it returns is initialized.
func (u *marshalInfo) getExtElemInfo(desc *ExtensionDesc) *marshalElemInfo {
// get from cache first
u.RLock()
e, ok := u.extElems[desc.Field]
u.RUnlock()
if ok {
return e
}
t := reflect.TypeOf(desc.ExtensionType) // pointer or slice to basic type or struct
tags := strings.Split(desc.Tag, ",")
tag, err := strconv.Atoi(tags[1])
if err != nil {
panic("tag is not an integer")
}
wt := wiretype(tags[0])
sizr, marshalr := typeMarshaler(t, tags, false, false)
e = &marshalElemInfo{
wiretag: uint64(tag)<<3 | wt,
tagsize: SizeVarint(uint64(tag) << 3),
sizer: sizr,
marshaler: marshalr,
isptr: t.Kind() == reflect.Ptr,
}
// update cache
u.Lock()
if u.extElems == nil {
u.extElems = make(map[int32]*marshalElemInfo)
}
u.extElems[desc.Field] = e
u.Unlock()
return e
}
// computeMarshalFieldInfo fills up the information to marshal a field.
func (fi *marshalFieldInfo) computeMarshalFieldInfo(f *reflect.StructField) {
// parse protobuf tag of the field.
// tag has format of "bytes,49,opt,name=foo,def=hello!"
tags := strings.Split(f.Tag.Get("protobuf"), ",")
if tags[0] == "" {
return
}
tag, err := strconv.Atoi(tags[1])
if err != nil {
panic("tag is not an integer")
}
wt := wiretype(tags[0])
if tags[2] == "req" {
fi.required = true
}
fi.setTag(f, tag, wt)
fi.setMarshaler(f, tags)
}
func (fi *marshalFieldInfo) computeOneofFieldInfo(f *reflect.StructField, oneofImplementers []interface{}) {
fi.field = toField(f)
fi.wiretag = math.MaxInt32 // Use a large tag number, make oneofs sorted at the end. This tag will not appear on the wire.
fi.isPointer = true
fi.sizer, fi.marshaler = makeOneOfMarshaler(fi, f)
fi.oneofElems = make(map[reflect.Type]*marshalElemInfo)
ityp := f.Type // interface type
for _, o := range oneofImplementers {
t := reflect.TypeOf(o)
if !t.Implements(ityp) {
continue
}
sf := t.Elem().Field(0) // oneof implementer is a struct with a single field
tags := strings.Split(sf.Tag.Get("protobuf"), ",")
tag, err := strconv.Atoi(tags[1])
if err != nil {
panic("tag is not an integer")
}
wt := wiretype(tags[0])
sizr, marshalr := typeMarshaler(sf.Type, tags, false, true) // oneof should not omit any zero value
fi.oneofElems[t.Elem()] = &marshalElemInfo{
wiretag: uint64(tag)<<3 | wt,
tagsize: SizeVarint(uint64(tag) << 3),
sizer: sizr,
marshaler: marshalr,
}
}
}
// wiretype returns the wire encoding of the type.
func wiretype(encoding string) uint64 {
switch encoding {
case "fixed32":
return WireFixed32
case "fixed64":
return WireFixed64
case "varint", "zigzag32", "zigzag64":
return WireVarint
case "bytes":
return WireBytes
case "group":
return WireStartGroup
}
panic("unknown wire type " + encoding)
}
// setTag fills up the tag (in wire format) and its size in the info of a field.
func (fi *marshalFieldInfo) setTag(f *reflect.StructField, tag int, wt uint64) {
fi.field = toField(f)
fi.wiretag = uint64(tag)<<3 | wt
fi.tagsize = SizeVarint(uint64(tag) << 3)
}
// setMarshaler fills up the sizer and marshaler in the info of a field.
func (fi *marshalFieldInfo) setMarshaler(f *reflect.StructField, tags []string) {
switch f.Type.Kind() {
case reflect.Map:
// map field
fi.isPointer = true
fi.sizer, fi.marshaler = makeMapMarshaler(f)
return
case reflect.Ptr, reflect.Slice:
fi.isPointer = true
}
fi.sizer, fi.marshaler = typeMarshaler(f.Type, tags, true, false)
}
// typeMarshaler returns the sizer and marshaler of a given field.
// t is the type of the field.
// tags is the generated "protobuf" tag of the field.
// If nozero is true, zero value is not marshaled to the wire.
// If oneof is true, it is a oneof field.
func typeMarshaler(t reflect.Type, tags []string, nozero, oneof bool) (sizer, marshaler) {
encoding := tags[0]
pointer := false
slice := false
if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 {
slice = true
t = t.Elem()
}
if t.Kind() == reflect.Ptr {
pointer = true
t = t.Elem()
}
packed := false
proto3 := false
ctype := false
isTime := false
isDuration := false
isWktPointer := false
validateUTF8 := true
for i := 2; i < len(tags); i++ {
if tags[i] == "packed" {
packed = true
}
if tags[i] == "proto3" {
proto3 = true
}
if strings.HasPrefix(tags[i], "customtype=") {
ctype = true
}
if tags[i] == "stdtime" {
isTime = true
}
if tags[i] == "stdduration" {
isDuration = true
}
if tags[i] == "wktptr" {
isWktPointer = true
}
}
validateUTF8 = validateUTF8 && proto3
if !proto3 && !pointer && !slice {
nozero = false
}
if ctype {
if reflect.PtrTo(t).Implements(customType) {
if slice {
return makeMessageRefSliceMarshaler(getMarshalInfo(t))
}
if pointer {
return makeCustomPtrMarshaler(getMarshalInfo(t))
}
return makeCustomMarshaler(getMarshalInfo(t))
} else {
panic(fmt.Sprintf("custom type: type: %v, does not implement the proto.custom interface", t))
}
}
if isTime {
if pointer {
if slice {
return makeTimePtrSliceMarshaler(getMarshalInfo(t))
}
return makeTimePtrMarshaler(getMarshalInfo(t))
}
if slice {
return makeTimeSliceMarshaler(getMarshalInfo(t))
}
return makeTimeMarshaler(getMarshalInfo(t))
}
if isDuration {
if pointer {
if slice {
return makeDurationPtrSliceMarshaler(getMarshalInfo(t))
}
return makeDurationPtrMarshaler(getMarshalInfo(t))
}
if slice {
return makeDurationSliceMarshaler(getMarshalInfo(t))
}
return makeDurationMarshaler(getMarshalInfo(t))
}
if isWktPointer {
switch t.Kind() {
case reflect.Float64:
if pointer {
if slice {
return makeStdDoubleValuePtrSliceMarshaler(getMarshalInfo(t))
}
return makeStdDoubleValuePtrMarshaler(getMarshalInfo(t))
}
if slice {
return makeStdDoubleValueSliceMarshaler(getMarshalInfo(t))
}
return makeStdDoubleValueMarshaler(getMarshalInfo(t))
case reflect.Float32:
if pointer {
if slice {
return makeStdFloatValuePtrSliceMarshaler(getMarshalInfo(t))
}
return makeStdFloatValuePtrMarshaler(getMarshalInfo(t))
}
if slice {
return makeStdFloatValueSliceMarshaler(getMarshalInfo(t))
}
return makeStdFloatValueMarshaler(getMarshalInfo(t))
case reflect.Int64:
if pointer {
if slice {
return makeStdInt64ValuePtrSliceMarshaler(getMarshalInfo(t))
}
return makeStdInt64ValuePtrMarshaler(getMarshalInfo(t))
}
if slice {
return makeStdInt64ValueSliceMarshaler(getMarshalInfo(t))
}
return makeStdInt64ValueMarshaler(getMarshalInfo(t))
case reflect.Uint64:
if pointer {
if slice {
return makeStdUInt64ValuePtrSliceMarshaler(getMarshalInfo(t))
}
return makeStdUInt64ValuePtrMarshaler(getMarshalInfo(t))
}
if slice {
return makeStdUInt64ValueSliceMarshaler(getMarshalInfo(t))
}
return makeStdUInt64ValueMarshaler(getMarshalInfo(t))
case reflect.Int32:
if pointer {
if slice {
return makeStdInt32ValuePtrSliceMarshaler(getMarshalInfo(t))
}
return makeStdInt32ValuePtrMarshaler(getMarshalInfo(t))
}
if slice {
return makeStdInt32ValueSliceMarshaler(getMarshalInfo(t))
}
return makeStdInt32ValueMarshaler(getMarshalInfo(t))
case reflect.Uint32:
if pointer {
if slice {
return makeStdUInt32ValuePtrSliceMarshaler(getMarshalInfo(t))
}
return makeStdUInt32ValuePtrMarshaler(getMarshalInfo(t))
}
if slice {
return makeStdUInt32ValueSliceMarshaler(getMarshalInfo(t))
}
return makeStdUInt32ValueMarshaler(getMarshalInfo(t))
case reflect.Bool:
if pointer {
if slice {
return makeStdBoolValuePtrSliceMarshaler(getMarshalInfo(t))
}
return makeStdBoolValuePtrMarshaler(getMarshalInfo(t))
}
if slice {
return makeStdBoolValueSliceMarshaler(getMarshalInfo(t))
}
return makeStdBoolValueMarshaler(getMarshalInfo(t))
case reflect.String:
if pointer {
if slice {
return makeStdStringValuePtrSliceMarshaler(getMarshalInfo(t))
}
return makeStdStringValuePtrMarshaler(getMarshalInfo(t))
}
if slice {
return makeStdStringValueSliceMarshaler(getMarshalInfo(t))
}
return makeStdStringValueMarshaler(getMarshalInfo(t))
case uint8SliceType:
if pointer {
if slice {
return makeStdBytesValuePtrSliceMarshaler(getMarshalInfo(t))
}
return makeStdBytesValuePtrMarshaler(getMarshalInfo(t))
}
if slice {
return makeStdBytesValueSliceMarshaler(getMarshalInfo(t))
}
return makeStdBytesValueMarshaler(getMarshalInfo(t))
default:
panic(fmt.Sprintf("unknown wktpointer type %#v", t))
}
}
switch t.Kind() {
case reflect.Bool:
if pointer {
return sizeBoolPtr, appendBoolPtr
}
if slice {
if packed {
return sizeBoolPackedSlice, appendBoolPackedSlice
}
return sizeBoolSlice, appendBoolSlice
}
if nozero {
return sizeBoolValueNoZero, appendBoolValueNoZero
}
return sizeBoolValue, appendBoolValue
case reflect.Uint32:
switch encoding {
case "fixed32":
if pointer {
return sizeFixed32Ptr, appendFixed32Ptr
}
if slice {
if packed {
return sizeFixed32PackedSlice, appendFixed32PackedSlice
}
return sizeFixed32Slice, appendFixed32Slice
}
if nozero {
return sizeFixed32ValueNoZero, appendFixed32ValueNoZero
}
return sizeFixed32Value, appendFixed32Value
case "varint":
if pointer {
return sizeVarint32Ptr, appendVarint32Ptr
}
if slice {
if packed {
return sizeVarint32PackedSlice, appendVarint32PackedSlice
}
return sizeVarint32Slice, appendVarint32Slice
}
if nozero {
return sizeVarint32ValueNoZero, appendVarint32ValueNoZero
}
return sizeVarint32Value, appendVarint32Value
}
case reflect.Int32:
switch encoding {
case "fixed32":
if pointer {
return sizeFixedS32Ptr, appendFixedS32Ptr
}
if slice {
if packed {
return sizeFixedS32PackedSlice, appendFixedS32PackedSlice
}
return sizeFixedS32Slice, appendFixedS32Slice
}
if nozero {
return sizeFixedS32ValueNoZero, appendFixedS32ValueNoZero
}
return sizeFixedS32Value, appendFixedS32Value
case "varint":
if pointer {
return sizeVarintS32Ptr, appendVarintS32Ptr
}
if slice {
if packed {
return sizeVarintS32PackedSlice, appendVarintS32PackedSlice
}
return sizeVarintS32Slice, appendVarintS32Slice
}
if nozero {
return sizeVarintS32ValueNoZero, appendVarintS32ValueNoZero
}
return sizeVarintS32Value, appendVarintS32Value
case "zigzag32":
if pointer {
return sizeZigzag32Ptr, appendZigzag32Ptr
}
if slice {
if packed {
return sizeZigzag32PackedSlice, appendZigzag32PackedSlice
}
return sizeZigzag32Slice, appendZigzag32Slice
}
if nozero {
return sizeZigzag32ValueNoZero, appendZigzag32ValueNoZero
}
return sizeZigzag32Value, appendZigzag32Value
}
case reflect.Uint64:
switch encoding {
case "fixed64":
if pointer {
return sizeFixed64Ptr, appendFixed64Ptr
}
if slice {
if packed {
return sizeFixed64PackedSlice, appendFixed64PackedSlice
}
return sizeFixed64Slice, appendFixed64Slice
}
if nozero {
return sizeFixed64ValueNoZero, appendFixed64ValueNoZero
}
return sizeFixed64Value, appendFixed64Value
case "varint":
if pointer {
return sizeVarint64Ptr, appendVarint64Ptr
}
if slice {
if packed {
return sizeVarint64PackedSlice, appendVarint64PackedSlice
}
return sizeVarint64Slice, appendVarint64Slice
}
if nozero {
return sizeVarint64ValueNoZero, appendVarint64ValueNoZero
}
return sizeVarint64Value, appendVarint64Value
}
case reflect.Int64:
switch encoding {
case "fixed64":
if pointer {
return sizeFixedS64Ptr, appendFixedS64Ptr
}
if slice {
if packed {
return sizeFixedS64PackedSlice, appendFixedS64PackedSlice
}
return sizeFixedS64Slice, appendFixedS64Slice
}
if nozero {
return sizeFixedS64ValueNoZero, appendFixedS64ValueNoZero
}
return sizeFixedS64Value, appendFixedS64Value
case "varint":
if pointer {
return sizeVarintS64Ptr, appendVarintS64Ptr
}
if slice {
if packed {
return sizeVarintS64PackedSlice, appendVarintS64PackedSlice
}
return sizeVarintS64Slice, appendVarintS64Slice
}
if nozero {
return sizeVarintS64ValueNoZero, appendVarintS64ValueNoZero
}
return sizeVarintS64Value, appendVarintS64Value
case "zigzag64":
if pointer {
return sizeZigzag64Ptr, appendZigzag64Ptr
}
if slice {
if packed {
return sizeZigzag64PackedSlice, appendZigzag64PackedSlice
}
return sizeZigzag64Slice, appendZigzag64Slice
}
if nozero {
return sizeZigzag64ValueNoZero, appendZigzag64ValueNoZero
}
return sizeZigzag64Value, appendZigzag64Value
}
case reflect.Float32:
if pointer {
return sizeFloat32Ptr, appendFloat32Ptr
}
if slice {
if packed {
return sizeFloat32PackedSlice, appendFloat32PackedSlice
}
return sizeFloat32Slice, appendFloat32Slice
}
if nozero {
return sizeFloat32ValueNoZero, appendFloat32ValueNoZero
}
return sizeFloat32Value, appendFloat32Value
case reflect.Float64:
if pointer {
return sizeFloat64Ptr, appendFloat64Ptr
}
if slice {
if packed {
return sizeFloat64PackedSlice, appendFloat64PackedSlice
}
return sizeFloat64Slice, appendFloat64Slice
}
if nozero {
return sizeFloat64ValueNoZero, appendFloat64ValueNoZero
}
return sizeFloat64Value, appendFloat64Value
case reflect.String:
if validateUTF8 {
if pointer {
return sizeStringPtr, appendUTF8StringPtr
}
if slice {
return sizeStringSlice, appendUTF8StringSlice
}
if nozero {
return sizeStringValueNoZero, appendUTF8StringValueNoZero
}
return sizeStringValue, appendUTF8StringValue
}
if pointer {
return sizeStringPtr, appendStringPtr
}
if slice {
return sizeStringSlice, appendStringSlice
}
if nozero {
return sizeStringValueNoZero, appendStringValueNoZero
}
return sizeStringValue, appendStringValue
case reflect.Slice:
if slice {
return sizeBytesSlice, appendBytesSlice
}
if oneof {
// Oneof bytes field may also have "proto3" tag.
// We want to marshal it as a oneof field. Do this
// check before the proto3 check.
return sizeBytesOneof, appendBytesOneof
}
if proto3 {
return sizeBytes3, appendBytes3
}
return sizeBytes, appendBytes
case reflect.Struct:
switch encoding {
case "group":
if slice {
return makeGroupSliceMarshaler(getMarshalInfo(t))
}
return makeGroupMarshaler(getMarshalInfo(t))
case "bytes":
if pointer {
if slice {
return makeMessageSliceMarshaler(getMarshalInfo(t))
}
return makeMessageMarshaler(getMarshalInfo(t))
} else {
if slice {
return makeMessageRefSliceMarshaler(getMarshalInfo(t))
}
return makeMessageRefMarshaler(getMarshalInfo(t))
}
}
}
panic(fmt.Sprintf("unknown or mismatched type: type: %v, wire type: %v", t, encoding))
}
// Below are functions to size/marshal a specific type of a field.
// They are stored in the field's info, and called by function pointers.
// They have type sizer or marshaler.
func sizeFixed32Value(_ pointer, tagsize int) int {
return 4 + tagsize
}
func sizeFixed32ValueNoZero(ptr pointer, tagsize int) int {
v := *ptr.toUint32()
if v == 0 {
return 0
}
return 4 + tagsize
}
func sizeFixed32Ptr(ptr pointer, tagsize int) int {
p := *ptr.toUint32Ptr()
if p == nil {
return 0
}
return 4 + tagsize
}
func sizeFixed32Slice(ptr pointer, tagsize int) int {
s := *ptr.toUint32Slice()
return (4 + tagsize) * len(s)
}
func sizeFixed32PackedSlice(ptr pointer, tagsize int) int {
s := *ptr.toUint32Slice()
if len(s) == 0 {
return 0
}
return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize
}
func sizeFixedS32Value(_ pointer, tagsize int) int {
return 4 + tagsize
}
func sizeFixedS32ValueNoZero(ptr pointer, tagsize int) int {
v := *ptr.toInt32()
if v == 0 {
return 0
}
return 4 + tagsize
}
func sizeFixedS32Ptr(ptr pointer, tagsize int) int {
p := ptr.getInt32Ptr()
if p == nil {
return 0
}
return 4 + tagsize
}
func sizeFixedS32Slice(ptr pointer, tagsize int) int {
s := ptr.getInt32Slice()
return (4 + tagsize) * len(s)
}
func sizeFixedS32PackedSlice(ptr pointer, tagsize int) int {
s := ptr.getInt32Slice()
if len(s) == 0 {
return 0
}
return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize
}
func sizeFloat32Value(_ pointer, tagsize int) int {
return 4 + tagsize
}
func sizeFloat32ValueNoZero(ptr pointer, tagsize int) int {
v := math.Float32bits(*ptr.toFloat32())
if v == 0 {
return 0
}
return 4 + tagsize
}
func sizeFloat32Ptr(ptr pointer, tagsize int) int {
p := *ptr.toFloat32Ptr()
if p == nil {
return 0
}
return 4 + tagsize
}
func sizeFloat32Slice(ptr pointer, tagsize int) int {
s := *ptr.toFloat32Slice()
return (4 + tagsize) * len(s)
}
func sizeFloat32PackedSlice(ptr pointer, tagsize int) int {
s := *ptr.toFloat32Slice()
if len(s) == 0 {
return 0
}
return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize
}
func sizeFixed64Value(_ pointer, tagsize int) int {
return 8 + tagsize
}
func sizeFixed64ValueNoZero(ptr pointer, tagsize int) int {
v := *ptr.toUint64()
if v == 0 {
return 0
}
return 8 + tagsize
}
func sizeFixed64Ptr(ptr pointer, tagsize int) int {
p := *ptr.toUint64Ptr()
if p == nil {
return 0
}
return 8 + tagsize
}
func sizeFixed64Slice(ptr pointer, tagsize int) int {
s := *ptr.toUint64Slice()
return (8 + tagsize) * len(s)
}
func sizeFixed64PackedSlice(ptr pointer, tagsize int) int {
s := *ptr.toUint64Slice()
if len(s) == 0 {
return 0
}
return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize
}
func sizeFixedS64Value(_ pointer, tagsize int) int {
return 8 + tagsize
}
func sizeFixedS64ValueNoZero(ptr pointer, tagsize int) int {
v := *ptr.toInt64()
if v == 0 {
return 0
}
return 8 + tagsize
}
func sizeFixedS64Ptr(ptr pointer, tagsize int) int {
p := *ptr.toInt64Ptr()
if p == nil {
return 0
}
return 8 + tagsize
}
func sizeFixedS64Slice(ptr pointer, tagsize int) int {
s := *ptr.toInt64Slice()
return (8 + tagsize) * len(s)
}
func sizeFixedS64PackedSlice(ptr pointer, tagsize int) int {
s := *ptr.toInt64Slice()
if len(s) == 0 {
return 0
}
return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize
}
func sizeFloat64Value(_ pointer, tagsize int) int {
return 8 + tagsize
}
func sizeFloat64ValueNoZero(ptr pointer, tagsize int) int {
v := math.Float64bits(*ptr.toFloat64())
if v == 0 {
return 0
}
return 8 + tagsize
}
func sizeFloat64Ptr(ptr pointer, tagsize int) int {
p := *ptr.toFloat64Ptr()
if p == nil {
return 0
}
return 8 + tagsize
}
func sizeFloat64Slice(ptr pointer, tagsize int) int {
s := *ptr.toFloat64Slice()
return (8 + tagsize) * len(s)
}
func sizeFloat64PackedSlice(ptr pointer, tagsize int) int {
s := *ptr.toFloat64Slice()
if len(s) == 0 {
return 0
}
return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize
}
func sizeVarint32Value(ptr pointer, tagsize int) int {
v := *ptr.toUint32()
return SizeVarint(uint64(v)) + tagsize
}
func sizeVarint32ValueNoZero(ptr pointer, tagsize int) int {
v := *ptr.toUint32()
if v == 0 {
return 0
}
return SizeVarint(uint64(v)) + tagsize
}
func sizeVarint32Ptr(ptr pointer, tagsize int) int {
p := *ptr.toUint32Ptr()
if p == nil {
return 0
}
return SizeVarint(uint64(*p)) + tagsize
}
func sizeVarint32Slice(ptr pointer, tagsize int) int {
s := *ptr.toUint32Slice()
n := 0
for _, v := range s {
n += SizeVarint(uint64(v)) + tagsize
}
return n
}
func sizeVarint32PackedSlice(ptr pointer, tagsize int) int {
s := *ptr.toUint32Slice()
if len(s) == 0 {
return 0
}
n := 0
for _, v := range s {
n += SizeVarint(uint64(v))
}
return n + SizeVarint(uint64(n)) + tagsize
}
func sizeVarintS32Value(ptr pointer, tagsize int) int {
v := *ptr.toInt32()
return SizeVarint(uint64(v)) + tagsize
}
func sizeVarintS32ValueNoZero(ptr pointer, tagsize int) int {
v := *ptr.toInt32()
if v == 0 {
return 0
}
return SizeVarint(uint64(v)) + tagsize
}
func sizeVarintS32Ptr(ptr pointer, tagsize int) int {
p := ptr.getInt32Ptr()
if p == nil {
return 0
}
return SizeVarint(uint64(*p)) + tagsize
}
func sizeVarintS32Slice(ptr pointer, tagsize int) int {
s := ptr.getInt32Slice()
n := 0
for _, v := range s {
n += SizeVarint(uint64(v)) + tagsize
}
return n
}
func sizeVarintS32PackedSlice(ptr pointer, tagsize int) int {
s := ptr.getInt32Slice()
if len(s) == 0 {
return 0
}
n := 0
for _, v := range s {
n += SizeVarint(uint64(v))
}
return n + SizeVarint(uint64(n)) + tagsize
}
func sizeVarint64Value(ptr pointer, tagsize int) int {
v := *ptr.toUint64()
return SizeVarint(v) + tagsize
}
func sizeVarint64ValueNoZero(ptr pointer, tagsize int) int {
v := *ptr.toUint64()
if v == 0 {
return 0
}
return SizeVarint(v) + tagsize
}
func sizeVarint64Ptr(ptr pointer, tagsize int) int {
p := *ptr.toUint64Ptr()
if p == nil {
return 0
}
return SizeVarint(*p) + tagsize
}
func sizeVarint64Slice(ptr pointer, tagsize int) int {
s := *ptr.toUint64Slice()
n := 0
for _, v := range s {
n += SizeVarint(v) + tagsize
}
return n
}
func sizeVarint64PackedSlice(ptr pointer, tagsize int) int {
s := *ptr.toUint64Slice()
if len(s) == 0 {
return 0
}
n := 0
for _, v := range s {
n += SizeVarint(v)
}
return n + SizeVarint(uint64(n)) + tagsize
}
func sizeVarintS64Value(ptr pointer, tagsize int) int {
v := *ptr.toInt64()
return SizeVarint(uint64(v)) + tagsize
}
func sizeVarintS64ValueNoZero(ptr pointer, tagsize int) int {
v := *ptr.toInt64()
if v == 0 {
return 0
}
return SizeVarint(uint64(v)) + tagsize
}
func sizeVarintS64Ptr(ptr pointer, tagsize int) int {
p := *ptr.toInt64Ptr()
if p == nil {
return 0
}
return SizeVarint(uint64(*p)) + tagsize
}
func sizeVarintS64Slice(ptr pointer, tagsize int) int {
s := *ptr.toInt64Slice()
n := 0
for _, v := range s {
n += SizeVarint(uint64(v)) + tagsize
}
return n
}
func sizeVarintS64PackedSlice(ptr pointer, tagsize int) int {
s := *ptr.toInt64Slice()
if len(s) == 0 {
return 0
}
n := 0
for _, v := range s {
n += SizeVarint(uint64(v))
}
return n + SizeVarint(uint64(n)) + tagsize
}
func sizeZigzag32Value(ptr pointer, tagsize int) int {
v := *ptr.toInt32()
return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize
}
func sizeZigzag32ValueNoZero(ptr pointer, tagsize int) int {
v := *ptr.toInt32()
if v == 0 {
return 0
}
return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize
}
func sizeZigzag32Ptr(ptr pointer, tagsize int) int {
p := ptr.getInt32Ptr()
if p == nil {
return 0
}
v := *p
return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize
}
func sizeZigzag32Slice(ptr pointer, tagsize int) int {
s := ptr.getInt32Slice()
n := 0
for _, v := range s {
n += SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize
}
return n
}
func sizeZigzag32PackedSlice(ptr pointer, tagsize int) int {
s := ptr.getInt32Slice()
if len(s) == 0 {
return 0
}
n := 0
for _, v := range s {
n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31))))
}
return n + SizeVarint(uint64(n)) + tagsize
}
func sizeZigzag64Value(ptr pointer, tagsize int) int {
v := *ptr.toInt64()
return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize
}
func sizeZigzag64ValueNoZero(ptr pointer, tagsize int) int {
v := *ptr.toInt64()
if v == 0 {
return 0
}
return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize
}
func sizeZigzag64Ptr(ptr pointer, tagsize int) int {
p := *ptr.toInt64Ptr()
if p == nil {
return 0
}
v := *p
return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize
}
func sizeZigzag64Slice(ptr pointer, tagsize int) int {
s := *ptr.toInt64Slice()
n := 0
for _, v := range s {
n += SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize
}
return n
}
func sizeZigzag64PackedSlice(ptr pointer, tagsize int) int {
s := *ptr.toInt64Slice()
if len(s) == 0 {
return 0
}
n := 0
for _, v := range s {
n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63)))
}
return n + SizeVarint(uint64(n)) + tagsize
}
func sizeBoolValue(_ pointer, tagsize int) int {
return 1 + tagsize
}
func sizeBoolValueNoZero(ptr pointer, tagsize int) int {
v := *ptr.toBool()
if !v {
return 0
}
return 1 + tagsize
}
func sizeBoolPtr(ptr pointer, tagsize int) int {
p := *ptr.toBoolPtr()
if p == nil {
return 0
}
return 1 + tagsize
}
func sizeBoolSlice(ptr pointer, tagsize int) int {
s := *ptr.toBoolSlice()
return (1 + tagsize) * len(s)
}
func sizeBoolPackedSlice(ptr pointer, tagsize int) int {
s := *ptr.toBoolSlice()
if len(s) == 0 {
return 0
}
return len(s) + SizeVarint(uint64(len(s))) + tagsize
}
func sizeStringValue(ptr pointer, tagsize int) int {
v := *ptr.toString()
return len(v) + SizeVarint(uint64(len(v))) + tagsize
}
func sizeStringValueNoZero(ptr pointer, tagsize int) int {
v := *ptr.toString()
if v == "" {
return 0
}
return len(v) + SizeVarint(uint64(len(v))) + tagsize
}
func sizeStringPtr(ptr pointer, tagsize int) int {
p := *ptr.toStringPtr()
if p == nil {
return 0
}
v := *p
return len(v) + SizeVarint(uint64(len(v))) + tagsize
}
func sizeStringSlice(ptr pointer, tagsize int) int {
s := *ptr.toStringSlice()
n := 0
for _, v := range s {
n += len(v) + SizeVarint(uint64(len(v))) + tagsize
}
return n
}
func sizeBytes(ptr pointer, tagsize int) int {
v := *ptr.toBytes()
if v == nil {
return 0
}
return len(v) + SizeVarint(uint64(len(v))) + tagsize
}
func sizeBytes3(ptr pointer, tagsize int) int {
v := *ptr.toBytes()
if len(v) == 0 {
return 0
}
return len(v) + SizeVarint(uint64(len(v))) + tagsize
}
func sizeBytesOneof(ptr pointer, tagsize int) int {
v := *ptr.toBytes()
return len(v) + SizeVarint(uint64(len(v))) + tagsize
}
func sizeBytesSlice(ptr pointer, tagsize int) int {
s := *ptr.toBytesSlice()
n := 0
for _, v := range s {
n += len(v) + SizeVarint(uint64(len(v))) + tagsize
}
return n
}
// appendFixed32 appends an encoded fixed32 to b.
func appendFixed32(b []byte, v uint32) []byte {
b = append(b,
byte(v),
byte(v>>8),
byte(v>>16),
byte(v>>24))
return b
}
// appendFixed64 appends an encoded fixed64 to b.
func appendFixed64(b []byte, v uint64) []byte {
b = append(b,
byte(v),
byte(v>>8),
byte(v>>16),
byte(v>>24),
byte(v>>32),
byte(v>>40),
byte(v>>48),
byte(v>>56))
return b
}
// appendVarint appends an encoded varint to b.
func appendVarint(b []byte, v uint64) []byte {
// TODO: make 1-byte (maybe 2-byte) case inline-able, once we
// have non-leaf inliner.
switch {
case v < 1<<7:
b = append(b, byte(v))
case v < 1<<14:
b = append(b,
byte(v&0x7f|0x80),
byte(v>>7))
case v < 1<<21:
b = append(b,
byte(v&0x7f|0x80),
byte((v>>7)&0x7f|0x80),
byte(v>>14))
case v < 1<<28:
b = append(b,
byte(v&0x7f|0x80),
byte((v>>7)&0x7f|0x80),
byte((v>>14)&0x7f|0x80),
byte(v>>21))
case v < 1<<35:
b = append(b,
byte(v&0x7f|0x80),
byte((v>>7)&0x7f|0x80),
byte((v>>14)&0x7f|0x80),
byte((v>>21)&0x7f|0x80),
byte(v>>28))
case v < 1<<42:
b = append(b,
byte(v&0x7f|0x80),
byte((v>>7)&0x7f|0x80),
byte((v>>14)&0x7f|0x80),
byte((v>>21)&0x7f|0x80),
byte((v>>28)&0x7f|0x80),
byte(v>>35))
case v < 1<<49:
b = append(b,
byte(v&0x7f|0x80),
byte((v>>7)&0x7f|0x80),
byte((v>>14)&0x7f|0x80),
byte((v>>21)&0x7f|0x80),
byte((v>>28)&0x7f|0x80),
byte((v>>35)&0x7f|0x80),
byte(v>>42))
case v < 1<<56:
b = append(b,
byte(v&0x7f|0x80),
byte((v>>7)&0x7f|0x80),
byte((v>>14)&0x7f|0x80),
byte((v>>21)&0x7f|0x80),
byte((v>>28)&0x7f|0x80),
byte((v>>35)&0x7f|0x80),
byte((v>>42)&0x7f|0x80),
byte(v>>49))
case v < 1<<63:
b = append(b,
byte(v&0x7f|0x80),
byte((v>>7)&0x7f|0x80),
byte((v>>14)&0x7f|0x80),
byte((v>>21)&0x7f|0x80),
byte((v>>28)&0x7f|0x80),
byte((v>>35)&0x7f|0x80),
byte((v>>42)&0x7f|0x80),
byte((v>>49)&0x7f|0x80),
byte(v>>56))
default:
b = append(b,
byte(v&0x7f|0x80),
byte((v>>7)&0x7f|0x80),
byte((v>>14)&0x7f|0x80),
byte((v>>21)&0x7f|0x80),
byte((v>>28)&0x7f|0x80),
byte((v>>35)&0x7f|0x80),
byte((v>>42)&0x7f|0x80),
byte((v>>49)&0x7f|0x80),
byte((v>>56)&0x7f|0x80),
1)
}
return b
}
func appendFixed32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := *ptr.toUint32()
b = appendVarint(b, wiretag)
b = appendFixed32(b, v)
return b, nil
}
func appendFixed32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := *ptr.toUint32()
if v == 0 {
return b, nil
}
b = appendVarint(b, wiretag)
b = appendFixed32(b, v)
return b, nil
}
func appendFixed32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
p := *ptr.toUint32Ptr()
if p == nil {
return b, nil
}
b = appendVarint(b, wiretag)
b = appendFixed32(b, *p)
return b, nil
}
func appendFixed32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
s := *ptr.toUint32Slice()
for _, v := range s {
b = appendVarint(b, wiretag)
b = appendFixed32(b, v)
}
return b, nil
}
func appendFixed32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
s := *ptr.toUint32Slice()
if len(s) == 0 {
return b, nil
}
b = appendVarint(b, wiretag&^7|WireBytes)
b = appendVarint(b, uint64(4*len(s)))
for _, v := range s {
b = appendFixed32(b, v)
}
return b, nil
}
func appendFixedS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := *ptr.toInt32()
b = appendVarint(b, wiretag)
b = appendFixed32(b, uint32(v))
return b, nil
}
func appendFixedS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := *ptr.toInt32()
if v == 0 {
return b, nil
}
b = appendVarint(b, wiretag)
b = appendFixed32(b, uint32(v))
return b, nil
}
func appendFixedS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
p := ptr.getInt32Ptr()
if p == nil {
return b, nil
}
b = appendVarint(b, wiretag)
b = appendFixed32(b, uint32(*p))
return b, nil
}
func appendFixedS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
s := ptr.getInt32Slice()
for _, v := range s {
b = appendVarint(b, wiretag)
b = appendFixed32(b, uint32(v))
}
return b, nil
}
func appendFixedS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
s := ptr.getInt32Slice()
if len(s) == 0 {
return b, nil
}
b = appendVarint(b, wiretag&^7|WireBytes)
b = appendVarint(b, uint64(4*len(s)))
for _, v := range s {
b = appendFixed32(b, uint32(v))
}
return b, nil
}
func appendFloat32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := math.Float32bits(*ptr.toFloat32())
b = appendVarint(b, wiretag)
b = appendFixed32(b, v)
return b, nil
}
func appendFloat32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := math.Float32bits(*ptr.toFloat32())
if v == 0 {
return b, nil
}
b = appendVarint(b, wiretag)
b = appendFixed32(b, v)
return b, nil
}
func appendFloat32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
p := *ptr.toFloat32Ptr()
if p == nil {
return b, nil
}
b = appendVarint(b, wiretag)
b = appendFixed32(b, math.Float32bits(*p))
return b, nil
}
func appendFloat32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
s := *ptr.toFloat32Slice()
for _, v := range s {
b = appendVarint(b, wiretag)
b = appendFixed32(b, math.Float32bits(v))
}
return b, nil
}
func appendFloat32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
s := *ptr.toFloat32Slice()
if len(s) == 0 {
return b, nil
}
b = appendVarint(b, wiretag&^7|WireBytes)
b = appendVarint(b, uint64(4*len(s)))
for _, v := range s {
b = appendFixed32(b, math.Float32bits(v))
}
return b, nil
}
func appendFixed64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := *ptr.toUint64()
b = appendVarint(b, wiretag)
b = appendFixed64(b, v)
return b, nil
}
func appendFixed64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := *ptr.toUint64()
if v == 0 {
return b, nil
}
b = appendVarint(b, wiretag)
b = appendFixed64(b, v)
return b, nil
}
func appendFixed64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
p := *ptr.toUint64Ptr()
if p == nil {
return b, nil
}
b = appendVarint(b, wiretag)
b = appendFixed64(b, *p)
return b, nil
}
func appendFixed64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
s := *ptr.toUint64Slice()
for _, v := range s {
b = appendVarint(b, wiretag)
b = appendFixed64(b, v)
}
return b, nil
}
func appendFixed64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
s := *ptr.toUint64Slice()
if len(s) == 0 {
return b, nil
}
b = appendVarint(b, wiretag&^7|WireBytes)
b = appendVarint(b, uint64(8*len(s)))
for _, v := range s {
b = appendFixed64(b, v)
}
return b, nil
}
func appendFixedS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := *ptr.toInt64()
b = appendVarint(b, wiretag)
b = appendFixed64(b, uint64(v))
return b, nil
}
func appendFixedS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := *ptr.toInt64()
if v == 0 {
return b, nil
}
b = appendVarint(b, wiretag)
b = appendFixed64(b, uint64(v))
return b, nil
}
func appendFixedS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
p := *ptr.toInt64Ptr()
if p == nil {
return b, nil
}
b = appendVarint(b, wiretag)
b = appendFixed64(b, uint64(*p))
return b, nil
}
func appendFixedS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
s := *ptr.toInt64Slice()
for _, v := range s {
b = appendVarint(b, wiretag)
b = appendFixed64(b, uint64(v))
}
return b, nil
}
func appendFixedS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
s := *ptr.toInt64Slice()
if len(s) == 0 {
return b, nil
}
b = appendVarint(b, wiretag&^7|WireBytes)
b = appendVarint(b, uint64(8*len(s)))
for _, v := range s {
b = appendFixed64(b, uint64(v))
}
return b, nil
}
func appendFloat64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := math.Float64bits(*ptr.toFloat64())
b = appendVarint(b, wiretag)
b = appendFixed64(b, v)
return b, nil
}
func appendFloat64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := math.Float64bits(*ptr.toFloat64())
if v == 0 {
return b, nil
}
b = appendVarint(b, wiretag)
b = appendFixed64(b, v)
return b, nil
}
func appendFloat64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
p := *ptr.toFloat64Ptr()
if p == nil {
return b, nil
}
b = appendVarint(b, wiretag)
b = appendFixed64(b, math.Float64bits(*p))
return b, nil
}
func appendFloat64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
s := *ptr.toFloat64Slice()
for _, v := range s {
b = appendVarint(b, wiretag)
b = appendFixed64(b, math.Float64bits(v))
}
return b, nil
}
func appendFloat64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
s := *ptr.toFloat64Slice()
if len(s) == 0 {
return b, nil
}
b = appendVarint(b, wiretag&^7|WireBytes)
b = appendVarint(b, uint64(8*len(s)))
for _, v := range s {
b = appendFixed64(b, math.Float64bits(v))
}
return b, nil
}
func appendVarint32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := *ptr.toUint32()
b = appendVarint(b, wiretag)
b = appendVarint(b, uint64(v))
return b, nil
}
func appendVarint32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := *ptr.toUint32()
if v == 0 {
return b, nil
}
b = appendVarint(b, wiretag)
b = appendVarint(b, uint64(v))
return b, nil
}
func appendVarint32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
p := *ptr.toUint32Ptr()
if p == nil {
return b, nil
}
b = appendVarint(b, wiretag)
b = appendVarint(b, uint64(*p))
return b, nil
}
func appendVarint32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
s := *ptr.toUint32Slice()
for _, v := range s {
b = appendVarint(b, wiretag)
b = appendVarint(b, uint64(v))
}
return b, nil
}
func appendVarint32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
s := *ptr.toUint32Slice()
if len(s) == 0 {
return b, nil
}
b = appendVarint(b, wiretag&^7|WireBytes)
// compute size
n := 0
for _, v := range s {
n += SizeVarint(uint64(v))
}
b = appendVarint(b, uint64(n))
for _, v := range s {
b = appendVarint(b, uint64(v))
}
return b, nil
}
func appendVarintS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := *ptr.toInt32()
b = appendVarint(b, wiretag)
b = appendVarint(b, uint64(v))
return b, nil
}
func appendVarintS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := *ptr.toInt32()
if v == 0 {
return b, nil
}
b = appendVarint(b, wiretag)
b = appendVarint(b, uint64(v))
return b, nil
}
func appendVarintS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
p := ptr.getInt32Ptr()
if p == nil {
return b, nil
}
b = appendVarint(b, wiretag)
b = appendVarint(b, uint64(*p))
return b, nil
}
func appendVarintS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
s := ptr.getInt32Slice()
for _, v := range s {
b = appendVarint(b, wiretag)
b = appendVarint(b, uint64(v))
}
return b, nil
}
func appendVarintS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
s := ptr.getInt32Slice()
if len(s) == 0 {
return b, nil
}
b = appendVarint(b, wiretag&^7|WireBytes)
// compute size
n := 0
for _, v := range s {
n += SizeVarint(uint64(v))
}
b = appendVarint(b, uint64(n))
for _, v := range s {
b = appendVarint(b, uint64(v))
}
return b, nil
}
func appendVarint64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := *ptr.toUint64()
b = appendVarint(b, wiretag)
b = appendVarint(b, v)
return b, nil
}
func appendVarint64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := *ptr.toUint64()
if v == 0 {
return b, nil
}
b = appendVarint(b, wiretag)
b = appendVarint(b, v)
return b, nil
}
func appendVarint64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
p := *ptr.toUint64Ptr()
if p == nil {
return b, nil
}
b = appendVarint(b, wiretag)
b = appendVarint(b, *p)
return b, nil
}
func appendVarint64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
s := *ptr.toUint64Slice()
for _, v := range s {
b = appendVarint(b, wiretag)
b = appendVarint(b, v)
}
return b, nil
}
func appendVarint64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
s := *ptr.toUint64Slice()
if len(s) == 0 {
return b, nil
}
b = appendVarint(b, wiretag&^7|WireBytes)
// compute size
n := 0
for _, v := range s {
n += SizeVarint(v)
}
b = appendVarint(b, uint64(n))
for _, v := range s {
b = appendVarint(b, v)
}
return b, nil
}
func appendVarintS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := *ptr.toInt64()
b = appendVarint(b, wiretag)
b = appendVarint(b, uint64(v))
return b, nil
}
func appendVarintS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := *ptr.toInt64()
if v == 0 {
return b, nil
}
b = appendVarint(b, wiretag)
b = appendVarint(b, uint64(v))
return b, nil
}
func appendVarintS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
p := *ptr.toInt64Ptr()
if p == nil {
return b, nil
}
b = appendVarint(b, wiretag)
b = appendVarint(b, uint64(*p))
return b, nil
}
func appendVarintS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
s := *ptr.toInt64Slice()
for _, v := range s {
b = appendVarint(b, wiretag)
b = appendVarint(b, uint64(v))
}
return b, nil
}
func appendVarintS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
s := *ptr.toInt64Slice()
if len(s) == 0 {
return b, nil
}
b = appendVarint(b, wiretag&^7|WireBytes)
// compute size
n := 0
for _, v := range s {
n += SizeVarint(uint64(v))
}
b = appendVarint(b, uint64(n))
for _, v := range s {
b = appendVarint(b, uint64(v))
}
return b, nil
}
func appendZigzag32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := *ptr.toInt32()
b = appendVarint(b, wiretag)
b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31))))
return b, nil
}
func appendZigzag32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := *ptr.toInt32()
if v == 0 {
return b, nil
}
b = appendVarint(b, wiretag)
b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31))))
return b, nil
}
func appendZigzag32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
p := ptr.getInt32Ptr()
if p == nil {
return b, nil
}
b = appendVarint(b, wiretag)
v := *p
b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31))))
return b, nil
}
func appendZigzag32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
s := ptr.getInt32Slice()
for _, v := range s {
b = appendVarint(b, wiretag)
b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31))))
}
return b, nil
}
func appendZigzag32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
s := ptr.getInt32Slice()
if len(s) == 0 {
return b, nil
}
b = appendVarint(b, wiretag&^7|WireBytes)
// compute size
n := 0
for _, v := range s {
n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31))))
}
b = appendVarint(b, uint64(n))
for _, v := range s {
b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31))))
}
return b, nil
}
func appendZigzag64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := *ptr.toInt64()
b = appendVarint(b, wiretag)
b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63)))
return b, nil
}
func appendZigzag64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := *ptr.toInt64()
if v == 0 {
return b, nil
}
b = appendVarint(b, wiretag)
b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63)))
return b, nil
}
func appendZigzag64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
p := *ptr.toInt64Ptr()
if p == nil {
return b, nil
}
b = appendVarint(b, wiretag)
v := *p
b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63)))
return b, nil
}
func appendZigzag64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
s := *ptr.toInt64Slice()
for _, v := range s {
b = appendVarint(b, wiretag)
b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63)))
}
return b, nil
}
func appendZigzag64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
s := *ptr.toInt64Slice()
if len(s) == 0 {
return b, nil
}
b = appendVarint(b, wiretag&^7|WireBytes)
// compute size
n := 0
for _, v := range s {
n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63)))
}
b = appendVarint(b, uint64(n))
for _, v := range s {
b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63)))
}
return b, nil
}
func appendBoolValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := *ptr.toBool()
b = appendVarint(b, wiretag)
if v {
b = append(b, 1)
} else {
b = append(b, 0)
}
return b, nil
}
func appendBoolValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := *ptr.toBool()
if !v {
return b, nil
}
b = appendVarint(b, wiretag)
b = append(b, 1)
return b, nil
}
func appendBoolPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
p := *ptr.toBoolPtr()
if p == nil {
return b, nil
}
b = appendVarint(b, wiretag)
if *p {
b = append(b, 1)
} else {
b = append(b, 0)
}
return b, nil
}
func appendBoolSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
s := *ptr.toBoolSlice()
for _, v := range s {
b = appendVarint(b, wiretag)
if v {
b = append(b, 1)
} else {
b = append(b, 0)
}
}
return b, nil
}
func appendBoolPackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
s := *ptr.toBoolSlice()
if len(s) == 0 {
return b, nil
}
b = appendVarint(b, wiretag&^7|WireBytes)
b = appendVarint(b, uint64(len(s)))
for _, v := range s {
if v {
b = append(b, 1)
} else {
b = append(b, 0)
}
}
return b, nil
}
func appendStringValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := *ptr.toString()
b = appendVarint(b, wiretag)
b = appendVarint(b, uint64(len(v)))
b = append(b, v...)
return b, nil
}
func appendStringValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := *ptr.toString()
if v == "" {
return b, nil
}
b = appendVarint(b, wiretag)
b = appendVarint(b, uint64(len(v)))
b = append(b, v...)
return b, nil
}
func appendStringPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
p := *ptr.toStringPtr()
if p == nil {
return b, nil
}
v := *p
b = appendVarint(b, wiretag)
b = appendVarint(b, uint64(len(v)))
b = append(b, v...)
return b, nil
}
func appendStringSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
s := *ptr.toStringSlice()
for _, v := range s {
b = appendVarint(b, wiretag)
b = appendVarint(b, uint64(len(v)))
b = append(b, v...)
}
return b, nil
}
func appendUTF8StringValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
var invalidUTF8 bool
v := *ptr.toString()
if !utf8.ValidString(v) {
invalidUTF8 = true
}
b = appendVarint(b, wiretag)
b = appendVarint(b, uint64(len(v)))
b = append(b, v...)
if invalidUTF8 {
return b, errInvalidUTF8
}
return b, nil
}
func appendUTF8StringValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
var invalidUTF8 bool
v := *ptr.toString()
if v == "" {
return b, nil
}
if !utf8.ValidString(v) {
invalidUTF8 = true
}
b = appendVarint(b, wiretag)
b = appendVarint(b, uint64(len(v)))
b = append(b, v...)
if invalidUTF8 {
return b, errInvalidUTF8
}
return b, nil
}
func appendUTF8StringPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
var invalidUTF8 bool
p := *ptr.toStringPtr()
if p == nil {
return b, nil
}
v := *p
if !utf8.ValidString(v) {
invalidUTF8 = true
}
b = appendVarint(b, wiretag)
b = appendVarint(b, uint64(len(v)))
b = append(b, v...)
if invalidUTF8 {
return b, errInvalidUTF8
}
return b, nil
}
func appendUTF8StringSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
var invalidUTF8 bool
s := *ptr.toStringSlice()
for _, v := range s {
if !utf8.ValidString(v) {
invalidUTF8 = true
}
b = appendVarint(b, wiretag)
b = appendVarint(b, uint64(len(v)))
b = append(b, v...)
}
if invalidUTF8 {
return b, errInvalidUTF8
}
return b, nil
}
func appendBytes(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := *ptr.toBytes()
if v == nil {
return b, nil
}
b = appendVarint(b, wiretag)
b = appendVarint(b, uint64(len(v)))
b = append(b, v...)
return b, nil
}
func appendBytes3(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := *ptr.toBytes()
if len(v) == 0 {
return b, nil
}
b = appendVarint(b, wiretag)
b = appendVarint(b, uint64(len(v)))
b = append(b, v...)
return b, nil
}
func appendBytesOneof(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
v := *ptr.toBytes()
b = appendVarint(b, wiretag)
b = appendVarint(b, uint64(len(v)))
b = append(b, v...)
return b, nil
}
func appendBytesSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
s := *ptr.toBytesSlice()
for _, v := range s {
b = appendVarint(b, wiretag)
b = appendVarint(b, uint64(len(v)))
b = append(b, v...)
}
return b, nil
}
// makeGroupMarshaler returns the sizer and marshaler for a group.
// u is the marshal info of the underlying message.
func makeGroupMarshaler(u *marshalInfo) (sizer, marshaler) {
return func(ptr pointer, tagsize int) int {
p := ptr.getPointer()
if p.isNil() {
return 0
}
return u.size(p) + 2*tagsize
},
func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
p := ptr.getPointer()
if p.isNil() {
return b, nil
}
var err error
b = appendVarint(b, wiretag) // start group
b, err = u.marshal(b, p, deterministic)
b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group
return b, err
}
}
// makeGroupSliceMarshaler returns the sizer and marshaler for a group slice.
// u is the marshal info of the underlying message.
func makeGroupSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
return func(ptr pointer, tagsize int) int {
s := ptr.getPointerSlice()
n := 0
for _, v := range s {
if v.isNil() {
continue
}
n += u.size(v) + 2*tagsize
}
return n
},
func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
s := ptr.getPointerSlice()
var err error
var nerr nonFatal
for _, v := range s {
if v.isNil() {
return b, errRepeatedHasNil
}
b = appendVarint(b, wiretag) // start group
b, err = u.marshal(b, v, deterministic)
b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group
if !nerr.Merge(err) {
if err == ErrNil {
err = errRepeatedHasNil
}
return b, err
}
}
return b, nerr.E
}
}
// makeMessageMarshaler returns the sizer and marshaler for a message field.
// u is the marshal info of the message.
func makeMessageMarshaler(u *marshalInfo) (sizer, marshaler) {
return func(ptr pointer, tagsize int) int {
p := ptr.getPointer()
if p.isNil() {
return 0
}
siz := u.size(p)
return siz + SizeVarint(uint64(siz)) + tagsize
},
func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
p := ptr.getPointer()
if p.isNil() {
return b, nil
}
b = appendVarint(b, wiretag)
siz := u.cachedsize(p)
b = appendVarint(b, uint64(siz))
return u.marshal(b, p, deterministic)
}
}
// makeMessageSliceMarshaler returns the sizer and marshaler for a message slice.
// u is the marshal info of the message.
func makeMessageSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
return func(ptr pointer, tagsize int) int {
s := ptr.getPointerSlice()
n := 0
for _, v := range s {
if v.isNil() {
continue
}
siz := u.size(v)
n += siz + SizeVarint(uint64(siz)) + tagsize
}
return n
},
func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
s := ptr.getPointerSlice()
var err error
var nerr nonFatal
for _, v := range s {
if v.isNil() {
return b, errRepeatedHasNil
}
b = appendVarint(b, wiretag)
siz := u.cachedsize(v)
b = appendVarint(b, uint64(siz))
b, err = u.marshal(b, v, deterministic)
if !nerr.Merge(err) {
if err == ErrNil {
err = errRepeatedHasNil
}
return b, err
}
}
return b, nerr.E
}
}
// makeMapMarshaler returns the sizer and marshaler for a map field.
// f is the pointer to the reflect data structure of the field.
func makeMapMarshaler(f *reflect.StructField) (sizer, marshaler) {
// figure out key and value type
t := f.Type
keyType := t.Key()
valType := t.Elem()
tags := strings.Split(f.Tag.Get("protobuf"), ",")
keyTags := strings.Split(f.Tag.Get("protobuf_key"), ",")
valTags := strings.Split(f.Tag.Get("protobuf_val"), ",")
stdOptions := false
for _, t := range tags {
if strings.HasPrefix(t, "customtype=") {
valTags = append(valTags, t)
}
if t == "stdtime" {
valTags = append(valTags, t)
stdOptions = true
}
if t == "stdduration" {
valTags = append(valTags, t)
stdOptions = true
}
if t == "wktptr" {
valTags = append(valTags, t)
}
}
keySizer, keyMarshaler := typeMarshaler(keyType, keyTags, false, false) // don't omit zero value in map
valSizer, valMarshaler := typeMarshaler(valType, valTags, false, false) // don't omit zero value in map
keyWireTag := 1<<3 | wiretype(keyTags[0])
valWireTag := 2<<3 | wiretype(valTags[0])
// We create an interface to get the addresses of the map key and value.
// If value is pointer-typed, the interface is a direct interface, the
// idata itself is the value. Otherwise, the idata is the pointer to the
// value.
// Key cannot be pointer-typed.
valIsPtr := valType.Kind() == reflect.Ptr
// If value is a message with nested maps, calling
// valSizer in marshal may be quadratic. We should use
// cached version in marshal (but not in size).
// If value is not message type, we don't have size cache,
// but it cannot be nested either. Just use valSizer.
valCachedSizer := valSizer
if valIsPtr && !stdOptions && valType.Elem().Kind() == reflect.Struct {
u := getMarshalInfo(valType.Elem())
valCachedSizer = func(ptr pointer, tagsize int) int {
// Same as message sizer, but use cache.
p := ptr.getPointer()
if p.isNil() {
return 0
}
siz := u.cachedsize(p)
return siz + SizeVarint(uint64(siz)) + tagsize
}
}
return func(ptr pointer, tagsize int) int {
m := ptr.asPointerTo(t).Elem() // the map
n := 0
for _, k := range m.MapKeys() {
ki := k.Interface()
vi := m.MapIndex(k).Interface()
kaddr := toAddrPointer(&ki, false) // pointer to key
vaddr := toAddrPointer(&vi, valIsPtr) // pointer to value
siz := keySizer(kaddr, 1) + valSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1)
n += siz + SizeVarint(uint64(siz)) + tagsize
}
return n
},
func(b []byte, ptr pointer, tag uint64, deterministic bool) ([]byte, error) {
m := ptr.asPointerTo(t).Elem() // the map
var err error
keys := m.MapKeys()
if len(keys) > 1 && deterministic {
sort.Sort(mapKeys(keys))
}
var nerr nonFatal
for _, k := range keys {
ki := k.Interface()
vi := m.MapIndex(k).Interface()
kaddr := toAddrPointer(&ki, false) // pointer to key
vaddr := toAddrPointer(&vi, valIsPtr) // pointer to value
b = appendVarint(b, tag)
siz := keySizer(kaddr, 1) + valCachedSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1)
b = appendVarint(b, uint64(siz))
b, err = keyMarshaler(b, kaddr, keyWireTag, deterministic)
if !nerr.Merge(err) {
return b, err
}
b, err = valMarshaler(b, vaddr, valWireTag, deterministic)
if err != ErrNil && !nerr.Merge(err) { // allow nil value in map
return b, err
}
}
return b, nerr.E
}
}
// makeOneOfMarshaler returns the sizer and marshaler for a oneof field.
// fi is the marshal info of the field.
// f is the pointer to the reflect data structure of the field.
func makeOneOfMarshaler(fi *marshalFieldInfo, f *reflect.StructField) (sizer, marshaler) {
// Oneof field is an interface. We need to get the actual data type on the fly.
t := f.Type
return func(ptr pointer, _ int) int {
p := ptr.getInterfacePointer()
if p.isNil() {
return 0
}
v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct
telem := v.Type()
e := fi.oneofElems[telem]
return e.sizer(p, e.tagsize)
},
func(b []byte, ptr pointer, _ uint64, deterministic bool) ([]byte, error) {
p := ptr.getInterfacePointer()
if p.isNil() {
return b, nil
}
v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct
telem := v.Type()
if telem.Field(0).Type.Kind() == reflect.Ptr && p.getPointer().isNil() {
return b, errOneofHasNil
}
e := fi.oneofElems[telem]
return e.marshaler(b, p, e.wiretag, deterministic)
}
}
// sizeExtensions computes the size of encoded data for a XXX_InternalExtensions field.
func (u *marshalInfo) sizeExtensions(ext *XXX_InternalExtensions) int {
m, mu := ext.extensionsRead()
if m == nil {
return 0
}
mu.Lock()
n := 0
for _, e := range m {
if e.value == nil || e.desc == nil {
// Extension is only in its encoded form.
n += len(e.enc)
continue
}
// We don't skip extensions that have an encoded form set,
// because the extension value may have been mutated after
// the last time this function was called.
ei := u.getExtElemInfo(e.desc)
v := e.value
p := toAddrPointer(&v, ei.isptr)
n += ei.sizer(p, ei.tagsize)
}
mu.Unlock()
return n
}
// appendExtensions marshals a XXX_InternalExtensions field to the end of byte slice b.
func (u *marshalInfo) appendExtensions(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) {
m, mu := ext.extensionsRead()
if m == nil {
return b, nil
}
mu.Lock()
defer mu.Unlock()
var err error
var nerr nonFatal
// Fast-path for common cases: zero or one extensions.
// Don't bother sorting the keys.
if len(m) <= 1 {
for _, e := range m {
if e.value == nil || e.desc == nil {
// Extension is only in its encoded form.
b = append(b, e.enc...)
continue
}
// We don't skip extensions that have an encoded form set,
// because the extension value may have been mutated after
// the last time this function was called.
ei := u.getExtElemInfo(e.desc)
v := e.value
p := toAddrPointer(&v, ei.isptr)
b, err = ei.marshaler(b, p, ei.wiretag, deterministic)
if !nerr.Merge(err) {
return b, err
}
}
return b, nerr.E
}
// Sort the keys to provide a deterministic encoding.
// Not sure this is required, but the old code does it.
keys := make([]int, 0, len(m))
for k := range m {
keys = append(keys, int(k))
}
sort.Ints(keys)
for _, k := range keys {
e := m[int32(k)]
if e.value == nil || e.desc == nil {
// Extension is only in its encoded form.
b = append(b, e.enc...)
continue
}
// We don't skip extensions that have an encoded form set,
// because the extension value may have been mutated after
// the last time this function was called.
ei := u.getExtElemInfo(e.desc)
v := e.value
p := toAddrPointer(&v, ei.isptr)
b, err = ei.marshaler(b, p, ei.wiretag, deterministic)
if !nerr.Merge(err) {
return b, err
}
}
return b, nerr.E
}
// message set format is:
// message MessageSet {
// repeated group Item = 1 {
// required int32 type_id = 2;
// required string message = 3;
// };
// }
// sizeMessageSet computes the size of encoded data for a XXX_InternalExtensions field
// in message set format (above).
func (u *marshalInfo) sizeMessageSet(ext *XXX_InternalExtensions) int {
m, mu := ext.extensionsRead()
if m == nil {
return 0
}
mu.Lock()
n := 0
for id, e := range m {
n += 2 // start group, end group. tag = 1 (size=1)
n += SizeVarint(uint64(id)) + 1 // type_id, tag = 2 (size=1)
if e.value == nil || e.desc == nil {
// Extension is only in its encoded form.
msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint
siz := len(msgWithLen)
n += siz + 1 // message, tag = 3 (size=1)
continue
}
// We don't skip extensions that have an encoded form set,
// because the extension value may have been mutated after
// the last time this function was called.
ei := u.getExtElemInfo(e.desc)
v := e.value
p := toAddrPointer(&v, ei.isptr)
n += ei.sizer(p, 1) // message, tag = 3 (size=1)
}
mu.Unlock()
return n
}
// appendMessageSet marshals a XXX_InternalExtensions field in message set format (above)
// to the end of byte slice b.
func (u *marshalInfo) appendMessageSet(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) {
m, mu := ext.extensionsRead()
if m == nil {
return b, nil
}
mu.Lock()
defer mu.Unlock()
var err error
var nerr nonFatal
// Fast-path for common cases: zero or one extensions.
// Don't bother sorting the keys.
if len(m) <= 1 {
for id, e := range m {
b = append(b, 1<<3|WireStartGroup)
b = append(b, 2<<3|WireVarint)
b = appendVarint(b, uint64(id))
if e.value == nil || e.desc == nil {
// Extension is only in its encoded form.
msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint
b = append(b, 3<<3|WireBytes)
b = append(b, msgWithLen...)
b = append(b, 1<<3|WireEndGroup)
continue
}
// We don't skip extensions that have an encoded form set,
// because the extension value may have been mutated after
// the last time this function was called.
ei := u.getExtElemInfo(e.desc)
v := e.value
p := toAddrPointer(&v, ei.isptr)
b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic)
if !nerr.Merge(err) {
return b, err
}
b = append(b, 1<<3|WireEndGroup)
}
return b, nerr.E
}
// Sort the keys to provide a deterministic encoding.
keys := make([]int, 0, len(m))
for k := range m {
keys = append(keys, int(k))
}
sort.Ints(keys)
for _, id := range keys {
e := m[int32(id)]
b = append(b, 1<<3|WireStartGroup)
b = append(b, 2<<3|WireVarint)
b = appendVarint(b, uint64(id))
if e.value == nil || e.desc == nil {
// Extension is only in its encoded form.
msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint
b = append(b, 3<<3|WireBytes)
b = append(b, msgWithLen...)
b = append(b, 1<<3|WireEndGroup)
continue
}
// We don't skip extensions that have an encoded form set,
// because the extension value may have been mutated after
// the last time this function was called.
ei := u.getExtElemInfo(e.desc)
v := e.value
p := toAddrPointer(&v, ei.isptr)
b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic)
b = append(b, 1<<3|WireEndGroup)
if !nerr.Merge(err) {
return b, err
}
}
return b, nerr.E
}
// sizeV1Extensions computes the size of encoded data for a V1-API extension field.
func (u *marshalInfo) sizeV1Extensions(m map[int32]Extension) int {
if m == nil {
return 0
}
n := 0
for _, e := range m {
if e.value == nil || e.desc == nil {
// Extension is only in its encoded form.
n += len(e.enc)
continue
}
// We don't skip extensions that have an encoded form set,
// because the extension value may have been mutated after
// the last time this function was called.
ei := u.getExtElemInfo(e.desc)
v := e.value
p := toAddrPointer(&v, ei.isptr)
n += ei.sizer(p, ei.tagsize)
}
return n
}
// appendV1Extensions marshals a V1-API extension field to the end of byte slice b.
func (u *marshalInfo) appendV1Extensions(b []byte, m map[int32]Extension, deterministic bool) ([]byte, error) {
if m == nil {
return b, nil
}
// Sort the keys to provide a deterministic encoding.
keys := make([]int, 0, len(m))
for k := range m {
keys = append(keys, int(k))
}
sort.Ints(keys)
var err error
var nerr nonFatal
for _, k := range keys {
e := m[int32(k)]
if e.value == nil || e.desc == nil {
// Extension is only in its encoded form.
b = append(b, e.enc...)
continue
}
// We don't skip extensions that have an encoded form set,
// because the extension value may have been mutated after
// the last time this function was called.
ei := u.getExtElemInfo(e.desc)
v := e.value
p := toAddrPointer(&v, ei.isptr)
b, err = ei.marshaler(b, p, ei.wiretag, deterministic)
if !nerr.Merge(err) {
return b, err
}
}
return b, nerr.E
}
// newMarshaler is the interface representing objects that can marshal themselves.
//
// This exists to support protoc-gen-go generated messages.
// The proto package will stop type-asserting to this interface in the future.
//
// DO NOT DEPEND ON THIS.
type newMarshaler interface {
XXX_Size() int
XXX_Marshal(b []byte, deterministic bool) ([]byte, error)
}
// Size returns the encoded size of a protocol buffer message.
// This is the main entry point.
func Size(pb Message) int {
if m, ok := pb.(newMarshaler); ok {
return m.XXX_Size()
}
if m, ok := pb.(Marshaler); ok {
// If the message can marshal itself, let it do it, for compatibility.
// NOTE: This is not efficient.
b, _ := m.Marshal()
return len(b)
}
// in case somehow we didn't generate the wrapper
if pb == nil {
return 0
}
var info InternalMessageInfo
return info.Size(pb)
}
// Marshal takes a protocol buffer message
// and encodes it into the wire format, returning the data.
// This is the main entry point.
func Marshal(pb Message) ([]byte, error) {
if m, ok := pb.(newMarshaler); ok {
siz := m.XXX_Size()
b := make([]byte, 0, siz)
return m.XXX_Marshal(b, false)
}
if m, ok := pb.(Marshaler); ok {
// If the message can marshal itself, let it do it, for compatibility.
// NOTE: This is not efficient.
return m.Marshal()
}
// in case somehow we didn't generate the wrapper
if pb == nil {
return nil, ErrNil
}
var info InternalMessageInfo
siz := info.Size(pb)
b := make([]byte, 0, siz)
return info.Marshal(b, pb, false)
}
// Marshal takes a protocol buffer message
// and encodes it into the wire format, writing the result to the
// Buffer.
// This is an alternative entry point. It is not necessary to use
// a Buffer for most applications.
func (p *Buffer) Marshal(pb Message) error {
var err error
if p.deterministic {
if _, ok := pb.(Marshaler); ok {
return fmt.Errorf("proto: deterministic not supported by the Marshal method of %T", pb)
}
}
if m, ok := pb.(newMarshaler); ok {
siz := m.XXX_Size()
p.grow(siz) // make sure buf has enough capacity
pp := p.buf[len(p.buf) : len(p.buf) : len(p.buf)+siz]
pp, err = m.XXX_Marshal(pp, p.deterministic)
p.buf = append(p.buf, pp...)
return err
}
if m, ok := pb.(Marshaler); ok {
// If the message can marshal itself, let it do it, for compatibility.
// NOTE: This is not efficient.
var b []byte
b, err = m.Marshal()
p.buf = append(p.buf, b...)
return err
}
// in case somehow we didn't generate the wrapper
if pb == nil {
return ErrNil
}
var info InternalMessageInfo
siz := info.Size(pb)
p.grow(siz) // make sure buf has enough capacity
p.buf, err = info.Marshal(p.buf, pb, p.deterministic)
return err
}
// grow grows the buffer's capacity, if necessary, to guarantee space for
// another n bytes. After grow(n), at least n bytes can be written to the
// buffer without another allocation.
func (p *Buffer) grow(n int) {
need := len(p.buf) + n
if need <= cap(p.buf) {
return
}
newCap := len(p.buf) * 2
if newCap < need {
newCap = need
}
p.buf = append(make([]byte, 0, newCap), p.buf...)
}
| {
"pile_set_name": "Github"
} |
<!doctype html>
<html ⚡>
<head>
<!-- Standard AMP markup -->
<meta charset="utf-8">
<script async src="https://cdn.ampproject.org/v0.js"></script>
<title>Bucket List: Yosemite</title>
<link rel="canonical" href="http://choumx.github.io/amp-pwa/content/13.amp.html" />
<meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
<style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
<!-- AMP extensions -->
<script async custom-element="amp-ad" src="https://cdn.ampproject.org/v0/amp-ad-0.1.js"></script>
<script async custom-element="amp-carousel" src="https://cdn.ampproject.org/v0/amp-carousel-0.1.js"></script>
<script async custom-element="amp-social-share" src="https://cdn.ampproject.org/v0/amp-social-share-0.1.js"></script>
<script async custom-element="amp-analytics" src="https://cdn.ampproject.org/v0/amp-analytics-0.1.js"></script>
<script async custom-element="amp-install-serviceworker" src="https://cdn.ampproject.org/v0/amp-install-serviceworker-0.1.js"></script>
<!-- Custom fonts -->
<link href="https://fonts.googleapis.com/css?family=Playfair+Display" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Muli" rel="stylesheet">
<!-- Custom styles -->
<style amp-custom>
h1, h2, p, body, figure, ul {
margin: 0;
padding: 0;
}
body {
background: #ffffff;
font-family: 'Muli', sans-serif;
font-size: 40px;
line-height: 22px;
color: #333;
}
.hr {
background-color: #37dc8c;
width: 15%;
height: 2px;
margin: 0.5em 0;
}
.carousel .slide > amp-img > img {
object-fit: contain;
}
.banner {
background-position: center center;
background-repeat: no-repeat;
background-image: url(./header_logo.svg);
background-color: #37dc8c;
padding: 18px;
height: 24px;
box-shadow: 0 2px 2px 0 rgba(0, 0, 0, .14), 0 3px 1px -2px rgba(0, 0, 0, .2), 0 1px 5px 0 rgba(0, 0, 0, .12);
}
.container {
max-width: 600px;
margin: 0 auto;
margin-top: 15px;
padding: 0px 20px;
}
h1 {
font-family: 'Playfair Display', serif;
}
.heading {
font-size: 27pt;
font-weight: 700;
margin-bottom: 0.3em;
letter-spacing: .33pt;
line-height: 30pt;
}
h1.related {
font-size: 18pt;
line-height: 20pt;
margin-bottom: 1em;
}
ul.related {
list-style-type: none;
padding: 0;
}
ul.related li {
margin-top: 10px;
border-bottom: solid 1px #8c8c8c;
height: 90px;
}
ul.related li:last-child {
border: none;
}
ul.related p {
font-size: 12pt;
padding-left: 110px;
padding-top: 26px;
}
ul.related div {
height: 100%;
}
ul.related a {
text-decoration: none;
color: #777;
}
ul.related amp-img {
float: left;
}
.category {
color: #777;
font-size: 10pt;
line-height: 18pt;
letter-spacing: 0.6pt;
text-transform: uppercase;
}
.kicker {
color: #666;
font-size: 16pt;
line-height: 24pt;
letter-spacing: .3pt;
vertical-align: top;
margin-bottom: 0.2em;
}
.text {
font-size: 20px;
line-height: 30px;
letter-spacing: .3px;
color: #4A4A4A;
vertical-align: top;
margin-bottom: 16px;
}
.byline {
font-size: 10pt;
line-height: 18pt;
color: black;
margin-bottom: 12px;
}
.caption {
font-size: 14px;
line-height: 30px;
color: #8c8c8c;
letter-spacing: .3px;
text-align: left;
}
.bottom {
background-color: black;
color: #37dc8c;
font-size: 8pt;
text-align: center;
margin-top: 40px;
padding-top: 20px;
padding-bottom: 30px;
}
.amp-ad-container {
background: #eee;
float: right;
width: 300px;
min-height: 300px;
margin: 16px;
padding-top: 32px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center
}
.amp-ad-container>span {
position: relative;
font-size: 12px;
top: -4px;
left: 8px;
color: #666
}
@media (max-width: 600px) {
article {
top: 0;
margin-bottom: 0
}
.amp-ad-container {
background: #eee;
float: none;
width: 100%;
margin: 16px 0;
}
.amp-user-notification {
padding: 8px;
background: #bbb;
text-align: center;
color: white;
}
figure.article-image {
margin: 24px 0 16px 0;
}
}
amp-carousel {
margin: 16px -20px 24px -20px;
}
</style>
</head>
<body>
<div class="banner">
<amp-img width=24 height=24 src="./ic_menu_white_24dp.svg"></amp-img>
</div>
<amp-img src="hero/13.jpeg" width=1200 height=720 layout=responsive></amp-img>
<div class="container">
<h2 class="category">Bucket List Adventures</h2>
<h1 class="heading">Bucket List: Yosemite</h1>
<p class="kicker">From Mariposa Grove to Glacier Point, beautiful waterfalls and rock formations await you</p>
<p class="byline">By Carol R. Wright on Aug 28 at 11:12 AM</p>
<div>
<amp-social-share type="twitter" width="45" height="33"></amp-social-share>
<amp-social-share type="facebook" width="45" height="33" data-attribution=254325784911610></amp-social-share>
<amp-social-share type="pinterest" width="45" height="33"></amp-social-share>
<amp-social-share type="email" width="45" height="33"></amp-social-share>
</div>
<div class="hr"></div>
<p class="text">
Jelly jujubes marshmallow donut. Wafer cheesecake lollipop fruitcake danish powder. Pudding croissant biscuit icing. Gummi bears fruitcake cake wafer cake cookie caramels marshmallow bonbon.
</p>
<p class="text">
Gingerbread biscuit gummies cupcake. Powder sugar plum chocolate cake chocolate cake cake. Marzipan brownie halvah. Marzipan soufflé bear claw gummi bears muffin.
</p>
<p class="text">
Muffin jelly-o wafer ice cream brownie dessert chocolate bar. Candy canes cotton candy apple pie cake. Chupa chups bonbon dragée bear claw dessert. Oat cake croissant sweet roll apple pie pie.
</p>
<div class="amp-ad-container">
<amp-ad width=300 height=250
type="a9"
data-aax_size="300x250"
data-aax_pubname="test123"
data-aax_src="302">
</amp-ad>
<figcaption class="caption">Advertisement</figcaption>
</div>
<p class="text">
Cookie fruitcake toffee lemon drops. Gummies caramels topping wafer tootsie roll cake. Halvah pastry gingerbread liquorice. Dragée topping toffee chupa chups.
</p>
<p class="text">
Halvah bear claw cake fruitcake chocolate topping. Cookie topping chocolate cake chocolate topping biscuit caramels lollipop danish. Jelly-o pastry topping candy. Cotton candy oat cake pastry lemon drops chocolate.
</p>
<p class="text">
Pastry cupcake icing. Gummies lollipop sweet carrot cake tootsie roll. Brownie apple pie sweet roll soufflé.
</p>
<amp-carousel width=1200 height=720 layout="responsive" type="slides">
<figure>
<amp-img src="hero/2.jpeg" width=1200 height=720 layout=responsive></amp-img>
<figcaption class="caption">This is an image gallery.</figcaption>
</figure>
<figure>
<amp-img src="hero/3.jpeg" width=1200 height=720 layout=responsive></amp-img>
<figcaption class="caption">A new sentance.</figcaption>
</figure>
<figure>
<amp-img src="hero/4.jpeg" width=1200 height=720 layout=responsive></amp-img>
<figcaption class="caption">Each image has a different caption.</figcaption>
</figure>
<figure>
<amp-img src="hero/5.jpeg" width=1200 height=720 layout=responsive></amp-img>
<figcaption class="caption">Happy birthday.</figcaption>
</figure>
<figure>
<amp-img src="hero/6.jpeg" width=1200 height=720 layout=responsive></amp-img>
<figcaption class="caption">Green eggs and ham.</figcaption>
</figure>
</amp-carousel>
<p class="text">
Tart donut sweet pudding dragée sweet chocolate bar. Croissant tootsie roll cookie lollipop jelly topping apple pie. Danish bear claw sesame snaps toffee. Biscuit brownie brownie.
</p>
<p class="text">
Lemon drops macaroon liquorice tart. Gummi bears dragée donut. Cheesecake chocolate bar candy canes candy tart cotton candy chocolate cake croissant cake. Oat cake cheesecake ice cream cotton candy marzipan pastry.
</p>
<p class="text">
Dragée toffee cupcake pudding oat cake. Cupcake croissant cake jelly powder apple pie lemon drops cupcake bear claw. Tiramisu jelly sweet roll gummies pie muffin gummi bears oat cake.
</p>
<p class="text">
Chupa chups danish fruitcake jelly pastry jelly beans marzipan. Jelly wafer candy sweet. Croissant gummies apple pie.
</p>
<div class="hr"></div>
<h1 class="related">Related articles</h2>
<ul class="related">
<li>
<a href="2.amp.html">
<div>
<amp-img width=100 height=80 src="hero/2.jpeg"></amp-img>
<p>Melbourne in 48 Hours</p>
</div>
</a>
</li>
<li>
<a href="3.amp.html">
<div>
<amp-img width=100 height=80 src="hero/3.jpeg"></amp-img>
<p>Paris in 48 Hours</p>
</div>
</a>
</li>
<li>
<a href="4.amp.html">
<div>
<amp-img width=100 height=80 src="hero/4.jpeg"></amp-img>
<p>Montreal in 48 Hours</p>
</div>
</a>
</li>
</ul>
</div>
<div class="bottom">
<p>"To travel is to take a journey into yourself." - Danny Kaye</p>
<p>The Scenic • No Rights Reserved</p>
</div>
<!-- Sample amp-analytics request with fake GA account -->
<amp-analytics type="googleanalytics" id="analytics">
<script type="application/json">
{
"vars": {
"account": "XX-YYYYYYYY-Z"
},
"triggers": {
"default pageview": {
"on": "visible",
"request": "pageview",
"vars": {
"title": "Bucket List: Yosemite"
}
}
}
}
</script>
</amp-analytics>
<amp-install-serviceworker src="/amp-pwa/service-worker.js" layout="nodisplay"></amp-install-serviceworker>
</body>
</html>
| {
"pile_set_name": "Github"
} |
<div id="think_page_trace" style="position: fixed;bottom:0;right:0;font-size:14px;width:100%;z-index: 999999;color: #000;text-align:left;font-family:'微软雅黑';">
<div id="think_page_trace_tab" style="display: none;background:white;margin:0;height: 250px;">
<div id="think_page_trace_tab_tit" style="height:30px;padding: 6px 12px 0;border-bottom:1px solid #ececec;border-top:1px solid #ececec;font-size:16px">
<?php foreach ($trace as $key => $value) {?>
<span style="color:#000;padding-right:12px;height:30px;line-height:30px;display:inline-block;margin-right:3px;cursor:pointer;font-weight:700"><?php echo $key ?></span>
<?php }?>
</div>
<div id="think_page_trace_tab_cont" style="overflow:auto;height:212px;padding:0;line-height: 24px">
<?php foreach ($trace as $info) {?>
<div style="display:none;">
<ol style="padding: 0; margin:0">
<?php
if (is_array($info)) {
foreach ($info as $k => $val) {
echo '<li style="border-bottom:1px solid #EEE;font-size:14px;padding:0 12px">' . (is_numeric($k) ? '' : $k.' : ') . htmlentities(print_r($val,true), ENT_COMPAT, 'utf-8') . '</li>';
}
}
?>
</ol>
</div>
<?php }?>
</div>
</div>
<div id="think_page_trace_close" style="display:none;text-align:right;height:15px;position:absolute;top:10px;right:12px;cursor:pointer;"><img style="vertical-align:top;" src="data:image/gif;base64,R0lGODlhDwAPAJEAAAAAAAMDA////wAAACH/C1hNUCBEYXRhWE1QPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgNS4wLWMwNjAgNjEuMTM0Nzc3LCAyMDEwLzAyLzEyLTE3OjMyOjAwICAgICAgICAiPiA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPiA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtbG5zOnhtcE1NPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvbW0vIiB4bWxuczpzdFJlZj0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL3NUeXBlL1Jlc291cmNlUmVmIyIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ1M1IFdpbmRvd3MiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6MUQxMjc1MUJCQUJDMTFFMTk0OUVGRjc3QzU4RURFNkEiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6MUQxMjc1MUNCQUJDMTFFMTk0OUVGRjc3QzU4RURFNkEiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDoxRDEyNzUxOUJBQkMxMUUxOTQ5RUZGNzdDNThFREU2QSIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDoxRDEyNzUxQUJBQkMxMUUxOTQ5RUZGNzdDNThFREU2QSIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PgH//v38+/r5+Pf29fTz8vHw7+7t7Ovq6ejn5uXk4+Lh4N/e3dzb2tnY19bV1NPS0dDPzs3My8rJyMfGxcTDwsHAv769vLu6ubi3trW0s7KxsK+urayrqqmop6alpKOioaCfnp2cm5qZmJeWlZSTkpGQj46NjIuKiYiHhoWEg4KBgH9+fXx7enl4d3Z1dHNycXBvbm1sa2ppaGdmZWRjYmFgX15dXFtaWVhXVlVUU1JRUE9OTUxLSklIR0ZFRENCQUA/Pj08Ozo5ODc2NTQzMjEwLy4tLCsqKSgnJiUkIyIhIB8eHRwbGhkYFxYVFBMSERAPDg0MCwoJCAcGBQQDAgEAACH5BAAAAAAALAAAAAAPAA8AAAIdjI6JZqotoJPR1fnsgRR3C2jZl3Ai9aWZZooV+RQAOw==" /></div>
</div>
<div id="think_page_trace_open" style="height:30px;float:right;text-align:right;overflow:hidden;position:fixed;bottom:0;right:0;color:#000;line-height:30px;cursor:pointer;">
<div style="background:#232323;color:#FFF;padding:0 6px;float:right;line-height:30px;font-size:14px"><?php echo \think\Container::get('debug')->getUseTime().'s ';?></div>
<img width="30" style="" title="ShowPageTrace" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyBpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNSBXaW5kb3dzIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjVERDVENkZGQjkyNDExRTE5REY3RDQ5RTQ2RTRDQUJCIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjVERDVENzAwQjkyNDExRTE5REY3RDQ5RTQ2RTRDQUJCIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6NURENUQ2RkRCOTI0MTFFMTlERjdENDlFNDZFNENBQkIiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6NURENUQ2RkVCOTI0MTFFMTlERjdENDlFNDZFNENBQkIiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz5fx6IRAAAMCElEQVR42sxae3BU1Rk/9+69+8xuNtkHJAFCSIAkhMgjCCJQUi0GtEIVbP8Qq9LH2No6TmfaztjO2OnUdvqHFMfOVFTqIK0vUEEeqUBARCsEeYQkEPJoEvIiELLvvc9z+p27u2F3s5tsBB1OZiebu5dzf7/v/L7f952zMM8cWIwY+Mk2ulCp92Fnq3XvnzArr2NZnYNldDp0Gw+/OEQ4+obQn5D+4Ubb22+YOGsWi/Todh8AHglKEGkEsnHBQ162511GZFgW6ZCBM9/W4H3iNSQqIe09O196dLKX7d1O39OViP/wthtkND62if/wj/DbMpph8BY/m9xy8BoBmQk+mHqZQGNy4JYRwCoRbwa8l4JXw6M+orJxpU0U6ToKy/5bQsAiTeokGKkTx46RRxxEUgrwGgF4MWNNEJCGgYTvpgnY1IJWg5RzfqLgvcIgktX0i8dmMlFA8qCQ5L0Z/WObPLUxT1i4lWSYDISoEfBYGvM+LlMQQdkLHoWRRZ8zYQI62Thswe5WTORGwNXDcGjqeOA9AF7B8rhzsxMBEoJ8oJKaqPu4hblHMCMPwl9XeNWyb8xkB/DDGYKfMAE6aFL7xesZ389JlgG3XHEMI6UPDOP6JHHu67T2pwNPI69mCP4rEaBDUAJaKc/AOuXiwH07VCS3w5+UQMAuF/WqGI+yFIwVNBwemBD4r0wgQiKoFZa00sEYTwss32lA1tPwVxtc8jQ5/gWCwmGCyUD8vRT0sHBFW4GJDvZmrJFWRY1EkrGA6ZB8/10fOZSSj0E6F+BSP7xidiIzhBmKB09lEwHPkG+UQIyEN44EBiT5vrv2uJXyPQqSqO930fxvcvwbR/+JAkD9EfASgI9EHlp6YiHO4W+cAB20SnrFqxBbNljiXf1Pl1K2S0HCWfiog3YlAD5RGwwxK6oUjTweuVigLjyB0mX410mAFnMoVK1lvvUvgt8fUJH0JVyjuvcmg4dE5mUiFtD24AZ4qBVELxXKS+pMxN43kSdzNwudJ+bQbLlmnxvPOQoCugSap1GnSRoG8KOiKbH+rIA0lEeSAg3y6eeQ6XI2nrYnrPM89bUTgI0Pdqvl50vlNbtZxDUBcLBK0kPd5jPziyLdojJIN0pq5/mdzwL4UVvVInV5ncQEPNOUxa9d0TU+CW5l+FoI0GSDKHVVSOs+0KOsZoxwOzSZNFGv0mQ9avyLCh2Hpm+70Y0YJoJVgmQv822wnDC8Miq6VjJ5IFed0QD1YiAbT+nQE8v/RMZfmgmcCRHIIu7Bmcp39oM9fqEychcA747KxQ/AEyqQonl7hATtJmnhO2XYtgcia01aSbVMenAXrIomPcLgEBA4liGBzFZAT8zBYqW6brI67wg8sFVhxBhwLwBP2+tqBQqqK7VJKGh/BRrfTr6nWL7nYBaZdBJHqrX3kPEPap56xwE/GvjJTRMADeMCdcGpGXL1Xh4ZL8BDOlWkUpegfi0CeDzeA5YITzEnddv+IXL+UYCmqIvqC9UlUC/ki9FipwVjunL3yX7dOTLeXmVMAhbsGporPfyOBTm/BJ23gTVehsvXRnSewagUfpBXF3p5pygKS7OceqTjb7h2vjr/XKm0ZofKSI2Q/J102wHzatZkJPYQ5JoKsuK+EoHJakVzubzuLQDepCKllTZi9AG0DYg9ZLxhFaZsOu7bvlmVI5oPXJMQJcHxHClSln1apFTvAimeg48u0RWFeZW4lVcjbQWZuIQK1KozZfIDO6CSQmQQXdpBaiKZyEWThVK1uEc6v7V7uK0ysduExPZx4vysDR+4SelhBYm0R6LBuR4PXts8MYMcJPsINo4YZCDLj0sgB0/vLpPXvA2Tn42Cv5rsLulGubzW0sEd3d4W/mJt2Kck+DzDMijfPLOjyrDhXSh852B+OvflqAkoyXO1cYfujtc/i3jJSAwhgfFlp20laMLOku/bC7prgqW7lCn4auE5NhcXPd3M7x70+IceSgZvNljCd9k3fLjYsPElqLR14PXQZqD2ZNkkrAB79UeJUebFQmXpf8ZcAQt2XrMQdyNUVBqZoUzAFyp3V3xi/MubUA/mCT4Fhf038PC8XplhWnCmnK/ZzyC2BSTRSqKVOuY2kB8Jia0lvvRIVoP+vVWJbYarf6p655E2/nANBMCWkgD49DA0VAMyI1OLFMYCXiU9bmzi9/y5i/vsaTpHPHidTofzLbM65vMPva9HlovgXp0AvjtaqYMfDD0/4mAsYE92pxa+9k1QgCnRVObCpojpzsKTPvayPetTEgBdwnssjuc0kOBFX+q3HwRQxdrOLAqeYRjkMk/trTSu2Z9Lik7CfF0AvjtqAhS4NHobGXUnB5DQs8hG8p/wMX1r4+8xkmyvQ50JVq72TVeXbz3HvpWaQJi57hJYTw4kGbtS+C2TigQUtZUX+X27QQq2ePBZBru/0lxTm8fOOQ5yaZOZMAV+he4FqIMB+LQB0UgMSajANX29j+vbmly8ipRvHeSQoQOkM5iFXcPQCVwDMs5RBCQmaPOyvbNd6uwvQJ183BZQG3Zc+Eiv7vQOKu8YeDmMcJlt2ckyftVeMIGLBCmdMHl/tFILYwGPjXWO3zOfSq/+om+oa7Mlh2fpSsRGLp7RAW3FUVjNHgiMhyE6zBFjM2BdkdJGO7nP1kJXWAtBuBpPIAu7f+hhu7bFXIuC5xWrf0X2xreykOsUyKkF2gwadbrXDcXrfKxR43zGcSj4t/cCgr+a1iy6EjE5GYktUCl9fwfMeylyooGF48bN2IGLTw8x7StS7sj8TF9FmPGWQhm3rRR+o9lhvjJvSYAdfDUevI1M6bnX/OwWaDMOQ8RPgKRo0eulBTdT8AW2kl8e9L7UHghHwMfLiZPNoSpx0yugpQZaFqKWqxVSM3a2pN1SAhC2jf94I7ybBI7EL5A2Wvu5ht3xsoEt4+Ay/abXgCQAxyOeDsDlTCQzy75ohcGgv9Tra9uiymRUYTLrswOLlCdfAQf7HPDQQ4ErAH5EDXB9cMxWYpjtXApRncojS0sbV/cCgHTHwGNBJy+1PQE2x56FpaVR7wfQGZ37V+V+19EiHNvR6q1fRUjqvbjbMq1/qfHxbTrE10ePY2gPFk48D2CVMTf1AF4PXvyYR9dV6Wf7H413m3xTWQvYGhQ7mfYwA5mAX+18Vue05v/8jG/fZX/IW5MKPKtjSYlt0ellxh+/BOCPAwYaeVr0QofZFxJWVWC8znG70au6llVmktsF0bfHF6k8fvZ5esZJbwHwwnjg59tXz6sL/P0NUZDuSNu1mnJ8Vab17+cy005A9wtOpp3i0bZdpJLUil00semAwN45LgEViZYe3amNye0B6A9chviSlzXVsFtyN5/1H3gaNmMpn8Fz0GpYFp6Zw615H/LpUuRQQDMCL82n5DpBSawkvzIdN2ypiT8nSLth8Pk9jnjwdFzH3W4XW6KMBfwB569NdcGX93mC16tTflcArcYUc/mFuYbV+8zY0SAjAVoNErNgWjtwumJ3wbn/HlBFYdxHvSkJJEc+Ngal9opSwyo9YlITX2C/P/+gf8sxURSLR+mcZUmeqaS9wrh6vxW5zxFCOqFi90RbDWq/YwZmnu1+a6OvdpvRqkNxxe44lyl4OobEnpKA6Uox5EfH9xzPs/HRKrTPWdIQrK1VZDU7ETiD3Obpl+8wPPCRBbkbwNtpW9AbBe5L1SMlj3tdTxk/9W47JUmqS5HU+JzYymUKXjtWVmT9RenIhgXc+nroWLyxXJhmL112OdB8GCsk4f8oZJucnvmmtR85mBn10GZ0EKSCMUSAR3ukcXd5s7LvLD3me61WkuTCpJzYAyRurMB44EdEJzTfU271lUJC03YjXJXzYOGZwN4D8eB5jlfLrdWfzGRW7icMPfiSO6Oe7s20bmhdgLX4Z23B+s3JgQESzUDiMboSzDMHFpNMwccGePauhfwjzwnI2wu9zKGgEFg80jcZ7MHllk07s1H+5yojtUQTlH4nFdLKTGwDmPbIklOb1L1zO4T6N8NCuDLFLS/C63c0eNRimZ++s5BMBHxU11jHchI9oFVUxRh/eMDzHEzGYu0Lg8gJ7oS/tFCwoic44fyUtix0n/46vP4bf+//BRgAYwDDar4ncHIAAAAASUVORK5CYII=">
</div>
<script type="text/javascript">
(function(){
var tab_tit = document.getElementById('think_page_trace_tab_tit').getElementsByTagName('span');
var tab_cont = document.getElementById('think_page_trace_tab_cont').getElementsByTagName('div');
var open = document.getElementById('think_page_trace_open');
var close = document.getElementById('think_page_trace_close').children[0];
var trace = document.getElementById('think_page_trace_tab');
var cookie = document.cookie.match(/thinkphp_show_page_trace=(\d\|\d)/);
var history = (cookie && typeof cookie[1] != 'undefined' && cookie[1].split('|')) || [0,0];
open.onclick = function(){
trace.style.display = 'block';
this.style.display = 'none';
close.parentNode.style.display = 'block';
history[0] = 1;
document.cookie = 'thinkphp_show_page_trace='+history.join('|')
}
close.onclick = function(){
trace.style.display = 'none';
this.parentNode.style.display = 'none';
open.style.display = 'block';
history[0] = 0;
document.cookie = 'thinkphp_show_page_trace='+history.join('|')
}
for(var i = 0; i < tab_tit.length; i++){
tab_tit[i].onclick = (function(i){
return function(){
for(var j = 0; j < tab_cont.length; j++){
tab_cont[j].style.display = 'none';
tab_tit[j].style.color = '#999';
}
tab_cont[i].style.display = 'block';
tab_tit[i].style.color = '#000';
history[1] = i;
document.cookie = 'thinkphp_show_page_trace='+history.join('|')
}
})(i)
}
parseInt(history[0]) && open.click();
tab_tit[history[1]].click();
})();
</script>
| {
"pile_set_name": "Github"
} |
#version 450
out gl_PerVertex
{
vec4 gl_Position;
};
invariant gl_Position;
void main()
{
gl_Position = vec4(1.0);
}
| {
"pile_set_name": "Github"
} |
# micropolisevaluationview.py
#
# Micropolis, Unix Version. This game was released for the Unix platform
# in or about 1990 and has been modified for inclusion in the One Laptop
# Per Child program. Copyright (C) 1989 - 2007 Electronic Arts Inc. If
# you need assistance with this program, you may contact:
# http://wiki.laptop.org/go/Micropolis or email [email protected].
#
# 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/>.
#
# ADDITIONAL TERMS per GNU GPL Section 7
#
# No trademark or publicity rights are granted. This license does NOT
# give you any right, title or interest in the trademark SimCity or any
# other Electronic Arts trademark. You may not distribute any
# modification of this program using the trademark SimCity or claim any
# affliation or association with Electronic Arts Inc. or its employees.
#
# Any propagation or conveyance of this program must include this
# copyright notice and these terms.
#
# If you convey this program (or any modifications of it) and assume
# contractual liability for the program to recipients of it, you agree
# to indemnify Electronic Arts for any liability that those contractual
# assumptions impose on Electronic Arts.
#
# You may not misrepresent the origins of this program; modified
# versions of the program must be marked as such and not identified as
# the original program.
#
# This disclaimer supplements the one included in the General Public
# License. TO THE FULLEST EXTENT PERMISSIBLE UNDER APPLICABLE LAW, THIS
# PROGRAM IS PROVIDED TO YOU "AS IS," WITH ALL FAULTS, WITHOUT WARRANTY
# OF ANY KIND, AND YOUR USE IS AT YOUR SOLE RISK. THE ENTIRE RISK OF
# SATISFACTORY QUALITY AND PERFORMANCE RESIDES WITH YOU. ELECTRONIC ARTS
# DISCLAIMS ANY AND ALL EXPRESS, IMPLIED OR STATUTORY WARRANTIES,
# INCLUDING IMPLIED WARRANTIES OF MERCHANTABILITY, SATISFACTORY QUALITY,
# FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT OF THIRD PARTY
# RIGHTS, AND WARRANTIES (IF ANY) ARISING FROM A COURSE OF DEALING,
# USAGE, OR TRADE PRACTICE. ELECTRONIC ARTS DOES NOT WARRANT AGAINST
# INTERFERENCE WITH YOUR ENJOYMENT OF THE PROGRAM; THAT THE PROGRAM WILL
# MEET YOUR REQUIREMENTS; THAT OPERATION OF THE PROGRAM WILL BE
# UNINTERRUPTED OR ERROR-FREE, OR THAT THE PROGRAM WILL BE COMPATIBLE
# WITH THIRD PARTY SOFTWARE OR THAT ANY ERRORS IN THE PROGRAM WILL BE
# CORRECTED. NO ORAL OR WRITTEN ADVICE PROVIDED BY ELECTRONIC ARTS OR
# ANY AUTHORIZED REPRESENTATIVE SHALL CREATE A WARRANTY. SOME
# JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF OR LIMITATIONS ON IMPLIED
# WARRANTIES OR THE LIMITATIONS ON THE APPLICABLE STATUTORY RIGHTS OF A
# CONSUMER, SO SOME OR ALL OF THE ABOVE EXCLUSIONS AND LIMITATIONS MAY
# NOT APPLY TO YOU.
########################################################################
# Micropolis Evaluation View
# Don Hopkins
# Is The Mayor Doing a Good Job?
# Yes: XX%
# No: XX%
# What are the Worst Problems?
# Problem 1: XXX%
# Problem 2: XXX%
# Problem 3: XXX%
# Problem 4: XXX%
# Statistics
# Population: XXX
# Net Migration: XXX (last year)
# Assessed Value: XXX
# Category: XXX
# Game Level: XXX
# Overall City Score (0 - 1000)
# Current Score: XXX
# Annual Change: XXX
########################################################################
# Import stuff
from gi.repository import Gtk as gtk
import cairo
import pango
import micropolisengine
import micropolisview
########################################################################
# MicropolisEvaluationView
class MicropolisEvaluationView(micropolisview.MicropolisView):
problemNames = (
'Crime',
'Pollution',
'Housing',
'Taxes',
'Traffic',
'Unemployment',
'Fire',
)
categoryNames = (
'Village',
'Town',
'City',
'Capital',
'Metropolis',
'Megalopolis',
)
levelNames = (
'Easy',
'Medium',
'Hard',
)
viewWidth = 150
viewHeight = 150
def __init__(
self,
**args):
micropolisview.MicropolisView.__init__(
self,
aspect='evaluation',
interests=('city', 'evaluation',),
**args)
self.zoomable = False
self.set_size_request(self.viewWidth, self.viewHeight)
def update(
self,
name,
*args):
#print "EVALUATION UPDATE", self, name, args
self.queue_draw()
def drawContent(
self,
ctx,
playout):
#print "==== MicropolisEvaluationView DRAWCONTENT", self
engine = self.engine
winRect = self.get_allocation()
winWidth = winRect.width
winHeight = winRect.height
ctx.save()
ctx.set_source_rgb(1.0, 1.0, 1.0)
ctx.rectangle(0, 0, winWidth, winHeight)
ctx.fill()
yesPercent = engine.cityYes
noPercent = 100 - yesPercent
problems = []
for problem in range(0, 4):
problemNumber = engine.getProblemNumber(problem)
if problemNumber == -1:
txt = ''
else:
txt = self.problemNames[problemNumber] + ': ' + str(engine.getProblemVotes(problem)) + '%'
problems.append(txt)
population = engine.formatNumber(engine.cityPop)
netMigration = engine.formatDelta(engine.cityPopDelta)
assessedValue = engine.formatMoney(engine.cityAssessedValue)
category = self.categoryNames[engine.cityClass]
gameLevel = self.levelNames[engine.gameLevel]
currentScore = engine.formatNumber(engine.cityScore)
annualChange = engine.formatDelta(engine.cityScoreDelta)
paragraphs = [
"""<b>Population:</b>
%s""" % (
population,
),
"""<b>Net Migration:</b>
%s""" % (
netMigration,
),
"""<b>Assessed Value:</b>
%s""" % (
assessedValue,
),
"""<b>Category:</b>
%s""" % (
category,
),
"""<b>Game Level:</b>
%s""" % (
gameLevel,
),
"""<b>Current Score:</b>
%s""" % (
currentScore
),
"""<b>Annual Change:</b>
%s""" % (
annualChange,
),
"""<b>Is The Mayor doing
a Good Job?</b>
Yes: %s%%
No: %s%%""" % (
yesPercent,
noPercent,
),
"""<b>What are the
Worst Problems?</b>
%s
%s
%s
%s""" % (
problems[0],
problems[1],
problems[2],
problems[3],
),
]
margin = 10
hgap = 10
vgap = 5
x = margin
y = margin
colWidth = 0
firstRow = True
bottom = winHeight - margin
ctx.set_source_rgb(0.0, 0.0, 0.0)
playout.set_font_description(self.labelFont)
for paragraph in paragraphs:
playout.set_markup(paragraph)
width, height = playout.get_pixel_size()
if firstRow:
firstRow = False
else:
if y + height > bottom:
x += colWidth + hgap
y = margin
firstRow = True
if width > colWidth:
colWidth = width
ctx.move_to(x, y)
ctx.show_layout(playout)
y += height + vgap
########################################################################
| {
"pile_set_name": "Github"
} |
webcore_test_database.localstorage - This is a sample local storage database
generated by Chromium 17.0.963.38 beta (using the WebCore DOM Storage
backend). It is used in webkit/dom_storage/dom_storage_database_unittest.cc
to verify that the Chromium backend can read a WebCore generated database.
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: 2a3fc194bfcecfa408c8e335530b4ea1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
/* xxstod.h -- _[W]Sto[d f ld] common functionality */
#pragma warning(disable: 4210)
/* macros */
#define ACSIZE 4 /* size of extended-precision accumulators */
#define D16TO7 FLIT(268435456.0) /* 16^7 */
#define D10TO9 FLIT(1e9) /* 10^9 */
#if FBITS <= 24
#define NLONG 1 /* 7 * NLONG == max hexadecimal digits */
#elif FBITS <= 64
#define NLONG 3
#else /* NLONG */
#define NLONG 5
#endif /* NLONG */
/*
FTYPE _Stodx(const CTYPE *s, CTYPE **endptr, long pten, int *perr)
*/
{ /* convert string to FTYPE, with checking */
FTYPE x;
long lo[NLONG + 1];
const CTYPE *s0 = s;
int code = CNAME(Stopfx)(&s, endptr);
const int neg = code & FL_NEG;
extern FTYPE FNAME(Dtento)(FTYPE *, long, int *);
if (perr != 0)
*perr = 0;
if ((code &= ~FL_NEG) == FL_DEC)
{ /* parse decimal format */
const int nlo = CNAME(Stoflt)(s0, s, endptr, lo, NLONG);
FTYPE xpx[ACSIZE], xpf[ACSIZE];
int i;
FNAME(Xp_setw)(xpf, ACSIZE, D10TO9);
if (nlo == 0)
FNAME(Xp_setw)(xpx, ACSIZE, 0.0);
else
for (i = 1, FNAME(Xp_setn)(xpx, ACSIZE, lo[1]); i < nlo; )
{ /* x = x * D10TO9 + (FTYPE)lo[++i] */
FTYPE xpa[ACSIZE];
FTYPE xpt[ACSIZE * 2];
FNAME(Xp_mulx)(xpx, ACSIZE, xpf, ACSIZE, xpt);
FNAME(Xp_setn)(xpa, ACSIZE, lo[++i]);
FNAME(Xp_addx)(xpx, ACSIZE, xpa, ACSIZE);
}
pten += lo[0];
x = FNAME(Dtento)(xpx, pten, perr);
}
else if (code == FL_HEX)
{ /* parse hexadecimal format */
const int nlo = CNAME(Stoxflt)(s0, s, endptr, lo, NLONG);
FTYPE xpx[ACSIZE], xpf[ACSIZE];
int i;
FNAME(Xp_setw)(xpf, ACSIZE, D16TO7);
if (nlo == 0)
FNAME(Xp_setw)(xpx, ACSIZE, 0.0);
else
for (i = 1, FNAME(Xp_setn)(xpx, ACSIZE, lo[1]); i < nlo; )
{ /* x = x * D16TO7 + (FTYPE)lo[++i] */
FTYPE xpa[ACSIZE];
FTYPE xpt[ACSIZE * 2];
FNAME(Xp_mulx)(xpx, ACSIZE, xpf, ACSIZE, xpt);
FNAME(Xp_setn)(xpa, ACSIZE, lo[++i]);
FNAME(Xp_addx)(xpx, ACSIZE, xpa, ACSIZE);
}
x = FNAME(Dtento)(xpx, pten, perr);
FNAME(Dscale)(&x, lo[0]);
}
else if (code == FL_INF)
x = FCONST(Inf);
else if (code == FL_NAN)
x = FCONST(Nan);
else
x = FLIT(0.0); /* code == FL_ERR */
if (neg)
FNEGATE(x);
return (x);
}
/*
* Copyright (c) by P.J. Plauger. All rights reserved.
* Consult your license regarding permissions and restrictions.
V6.50:0009 */
| {
"pile_set_name": "Github"
} |
/* Copyright (C) 2007, 2009 Free Software Foundation, Inc.
This file is part of GCC.
GCC 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, or (at your option)
any later version.
GCC 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.
Under Section 7 of GPL version 3, you are granted additional
permissions described in the GCC Runtime Library Exception, version
3.1, as published by the Free Software Foundation.
You should have received a copy of the GNU General Public License and
a copy of the GCC Runtime Library Exception along with this program;
see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
<http://www.gnu.org/licenses/>.
/* Implemented from the specification included in the Intel C++ Compiler
User Guide and Reference, version 10.0. */
#ifndef _NMMINTRIN_H_INCLUDED
#define _NMMINTRIN_H_INCLUDED
#ifndef __SSE4_2__
# error "SSE4.2 instruction set not enabled"
#else
/* We just include SSE4.1 header file. */
#include <smmintrin.h>
#endif /* __SSE4_2__ */
#endif /* _NMMINTRIN_H_INCLUDED */
| {
"pile_set_name": "Github"
} |
/**
* Parses a TM formatted string into a javascript object with properties for hours, minutes, seconds and fractionalSeconds
* @param {string} time - a string in the TM VR format
* @param {boolean} [validate] - true if an exception should be thrown if the date is invalid
* @returns {*} javascript object with properties for hours, minutes, seconds and fractionalSeconds or undefined if no element or data. Missing fields are set to undefined
*/
export default function parseTM (time, validate) {
if (time.length >= 2) { // must at least have HH
// 0123456789
// HHMMSS.FFFFFF
const hh = parseInt(time.substring(0, 2), 10);
const mm = time.length >= 4 ? parseInt(time.substring(2, 4), 10) : undefined;
const ss = time.length >= 6 ? parseInt(time.substring(4, 6), 10) : undefined;
const fractionalStr = time.length >= 8 ? time.substring(7, 13) : undefined;
const ffffff = fractionalStr ? (parseInt(fractionalStr, 10) * Math.pow(10, 6 - fractionalStr.length)) : undefined;
if (validate) {
if ((isNaN(hh)) ||
(mm !== undefined && isNaN(mm)) ||
(ss !== undefined && isNaN(ss)) ||
(ffffff !== undefined && isNaN(ffffff)) ||
(hh < 0 || hh > 23) ||
(mm && (mm < 0 || mm > 59)) ||
(ss && (ss < 0 || ss > 59)) ||
(ffffff && (ffffff < 0 || ffffff > 999999))) {
throw `invalid TM '${time}'`;
}
}
return {
hours: hh,
minutes: mm,
seconds: ss,
fractionalSeconds: ffffff
};
}
if (validate) {
throw `invalid TM '${time}'`;
}
return undefined;
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2012 - 2020 Splice Machine, Inc.
*
* This file is part of Splice Machine.
* Splice Machine is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either
* version 3, or (at your option) any later version.
* Splice Machine 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 Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License along with Splice Machine.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.splicemachine.tools.version;
import splice.com.google.common.collect.ImmutableMap;
import splice.com.google.common.collect.Maps;
import com.splicemachine.si.testenv.ArchitectureIndependent;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.util.Map;
import static org.junit.Assert.*;
@Category(ArchitectureIndependent.class)
public class SimpleDatabaseVersionTest{
@Test
public void release() {
Map<String, String> map = Maps.newHashMap();
map.put("Build-Time", "2014-05-27");
map.put("Implementation-Version", "1d073ed3f6");
map.put("Release", "1.2.3");
map.put("URL", "http://www.splicemachine.com");
SimpleDatabaseVersion version = new SimpleDatabaseVersion(map);
assertEquals("2014-05-27", version.getBuildTime());
assertEquals("1d073ed3f6", version.getImplementationVersion());
assertEquals("1.2.3", version.getRelease());
assertEquals("http://www.splicemachine.com", version.getURL());
assertEquals(1, version.getMajorVersionNumber());
assertEquals(2, version.getMinorVersionNumber());
assertEquals(3, version.getPatchVersionNumber());
assertFalse(version.isUnknown());
}
@Test
public void snapshot() {
Map<String, String> map = ImmutableMap.of("Release", "2.3.4-SNAPSHOT");
SimpleDatabaseVersion version = new SimpleDatabaseVersion(map);
assertEquals("2.3.4-SNAPSHOT", version.getRelease());
assertEquals(2, version.getMajorVersionNumber());
assertEquals(3, version.getMinorVersionNumber());
assertEquals(4, version.getPatchVersionNumber());
assertFalse(version.isUnknown());
}
@Test
public void releaseCandidate() {
Map<String, String> map = ImmutableMap.of("Release", "4.5.55RC01");
SimpleDatabaseVersion version = new SimpleDatabaseVersion(map);
assertEquals("4.5.55RC01", version.getRelease());
assertEquals(4, version.getMajorVersionNumber());
assertEquals(5, version.getMinorVersionNumber());
assertEquals(55, version.getPatchVersionNumber());
assertFalse(version.isUnknown());
}
@Test
public void releaseCandidateSnapshot() {
Map<String, String> map = ImmutableMap.of("Release", "88.99.23004RC76-SNAPSHOT");
SimpleDatabaseVersion version = new SimpleDatabaseVersion(map);
assertEquals("88.99.23004RC76-SNAPSHOT", version.getRelease());
assertEquals(88, version.getMajorVersionNumber());
assertEquals(99, version.getMinorVersionNumber());
assertEquals(23004, version.getPatchVersionNumber());
assertFalse(version.isUnknown());
}
@Test
public void fourDigitVersion() {
Map<String, String> map = ImmutableMap.of("Release", "1.2.3.4");
SimpleDatabaseVersion version = new SimpleDatabaseVersion(map);
assertEquals("1.2.3.4", version.getRelease());
assertEquals(1, version.getMajorVersionNumber());
assertEquals(2, version.getMinorVersionNumber());
assertEquals(3, version.getPatchVersionNumber());
assertFalse(version.isUnknown());
}
@Test
public void twoDigitVersion() {
Map<String, String> map = ImmutableMap.of("Release", "1.2");
SimpleDatabaseVersion version = new SimpleDatabaseVersion(map);
assertEquals("1.2", version.getRelease());
assertEquals(1, version.getMajorVersionNumber());
assertEquals(2, version.getMinorVersionNumber());
assertEquals(-1, version.getPatchVersionNumber());
assertFalse(version.isUnknown());
}
@Test
public void oneDigitVersion() {
Map<String, String> map = ImmutableMap.of("Release", "1");
SimpleDatabaseVersion version = new SimpleDatabaseVersion(map);
assertEquals("1", version.getRelease());
assertEquals(1, version.getMajorVersionNumber());
assertEquals(-1, version.getMinorVersionNumber());
assertEquals(-1, version.getPatchVersionNumber());
assertFalse(version.isUnknown());
}
@Test
public void emptyVersion() {
Map<String, String> map = ImmutableMap.of("Release", "");
SimpleDatabaseVersion version = new SimpleDatabaseVersion(map);
assertEquals(SimpleDatabaseVersion.UNKNOWN_VERSION, version.getRelease());
assertEquals(-1, version.getMajorVersionNumber());
assertEquals(-1, version.getMinorVersionNumber());
assertEquals(-1, version.getPatchVersionNumber());
assertTrue(version.isUnknown());
}
@Test
public void missingVersion() {
Map<String, String> map = Maps.newTreeMap();
SimpleDatabaseVersion version = new SimpleDatabaseVersion(map);
assertEquals(SimpleDatabaseVersion.UNKNOWN_VERSION, version.getRelease());
assertEquals(-1, version.getMajorVersionNumber());
assertEquals(-1, version.getMinorVersionNumber());
assertEquals(-1, version.getPatchVersionNumber());
assertTrue(version.isUnknown());
}
@Test
public void nullVersion() {
SimpleDatabaseVersion version = new SimpleDatabaseVersion(null);
assertEquals(SimpleDatabaseVersion.UNKNOWN_VERSION, version.getRelease());
assertEquals(-1, version.getMajorVersionNumber());
assertEquals(-1, version.getMinorVersionNumber());
assertEquals(-1, version.getPatchVersionNumber());
assertTrue(version.isUnknown());
}
@Test
public void crazyVersion() {
Map<String, String> map = ImmutableMap.of("Release", "a1a.b2b.c3c");
SimpleDatabaseVersion version = new SimpleDatabaseVersion(map);
assertEquals("a1a.b2b.c3c", version.getRelease());
assertEquals(1, version.getMajorVersionNumber());
assertEquals(2, version.getMinorVersionNumber());
assertEquals(3, version.getPatchVersionNumber());
assertFalse(version.isUnknown());
}
}
| {
"pile_set_name": "Github"
} |
; RUN: llvm-link -o - %s | llvm-dis | FileCheck %s
; CHECK: !named = !{!0, !2}
!named = !{!0, !2}
; CHECK: !0 = !{!1}
; CHECK-NEXT: !1 = distinct !{!0}
!0 = !{!1}
!1 = distinct !{!0}
; CHECK-NEXT: !2 = distinct !{!3}
; CHECK-NEXT: !3 = !{!2}
!2 = distinct !{!3}
!3 = !{!2}
| {
"pile_set_name": "Github"
} |
<?php
namespace A17\Twill\Http\Middleware;
use Closure;
class Localization
{
/**
* Handles an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($request->user()->language) {
config(['twill.locale' => $request->user()->language]);
}
return $next($request);
}
}
| {
"pile_set_name": "Github"
} |
# Generated by Django 2.2.1 on 2019-10-18 11:35
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('api', '0004_auto_20190125_0517'),
]
operations = [
migrations.AlterModelOptions(
name='team',
options={},
),
migrations.CreateModel(
name='ODKToken',
fields=[
('key', models.CharField(max_length=150, primary_key=True, serialize=False)),
('status', models.CharField(choices=[('1', 'Active'), ('2', 'Inactive')], default='1', max_length=1, verbose_name='Status')),
('created', models.DateTimeField(auto_now_add=True)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='odk_token', to=settings.AUTH_USER_MODEL)),
],
),
]
| {
"pile_set_name": "Github"
} |
const path = require('path');
const puppeteer = require('puppeteer');
const CRX_PATH = path.join(__dirname, '../fixtures');
const args = [
'--no-sandbox',
'--disable-setuid-sandbox',
];
const launchBrowserWithoutExtension = async () => {
return await puppeteer.launch({
headless: false,
args: [...args, '--user-agent=PuppeteerAgentFast']
});
};
const launchBrowserWithExtension = async () => {
return await puppeteer.launch({
headless: false,
args: [
...args,
`--disable-extensions-except=${CRX_PATH}`,
`--load-extension=${CRX_PATH}`,
'--user-agent=PuppeteerAgentSlow'
]
});
};
module.exports = { launchBrowserWithoutExtension, launchBrowserWithExtension };
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<DelphiIDETheme modified="2013-04-24 20:49:18" author="Delphi IDE Theme Editor" versionapp="1.1.18.1">
<AdditionalSearchMatchHighlight>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>True</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>$00FFFFFF</ForegroundColorNew>
<BackgroundColorNew>$00757575</BackgroundColorNew>
</AdditionalSearchMatchHighlight>
<Assembler>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>$00FF9300</ForegroundColorNew>
<BackgroundColorNew>$00000000</BackgroundColorNew>
</Assembler>
<AttributeNames>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>$00CECD3B</ForegroundColorNew>
<BackgroundColorNew>$00000000</BackgroundColorNew>
</AttributeNames>
<AttributeValues>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>$0044FF0A</ForegroundColorNew>
<BackgroundColorNew>$00000000</BackgroundColorNew>
</AttributeValues>
<BraceHighlight>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>$00FFFFFF</ForegroundColorNew>
<BackgroundColorNew>$00070BB6</BackgroundColorNew>
</BraceHighlight>
<Character>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>$0044FF0A</ForegroundColorNew>
<BackgroundColorNew>$00000000</BackgroundColorNew>
</Character>
<CodeFoldingTree>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>$00FFFFFF</ForegroundColorNew>
<BackgroundColorNew>$00000000</BackgroundColorNew>
</CodeFoldingTree>
<Comment>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>$0000AEC7</ForegroundColorNew>
<BackgroundColorNew>$00000000</BackgroundColorNew>
</Comment>
<DiffAddition>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>True</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>clBlack</ForegroundColorNew>
<BackgroundColorNew>$00CCFFCC</BackgroundColorNew>
</DiffAddition>
<DiffDeletion>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>True</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>clBlack</ForegroundColorNew>
<BackgroundColorNew>$00FFC7C7</BackgroundColorNew>
</DiffDeletion>
<DiffMove>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>True</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>clBlack</ForegroundColorNew>
<BackgroundColorNew>$00AAFFFF</BackgroundColorNew>
</DiffMove>
<DisabledBreak>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>clGray</ForegroundColorNew>
<BackgroundColorNew>$00FFC7C7</BackgroundColorNew>
</DisabledBreak>
<EnabledBreak>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>clBlack</ForegroundColorNew>
<BackgroundColorNew>$00FFC7C7</BackgroundColorNew>
</EnabledBreak>
<ErrorLine>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>clWhite</ForegroundColorNew>
<BackgroundColorNew>clRed</BackgroundColorNew>
</ErrorLine>
<ExecutionPoint>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>clBlack</ForegroundColorNew>
<BackgroundColorNew>$009999CC</BackgroundColorNew>
</ExecutionPoint>
<Float>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>$00FFFFFF</ForegroundColorNew>
<BackgroundColorNew>$00000000</BackgroundColorNew>
</Float>
<FoldedCode>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>$00CC9999</ForegroundColorNew>
<BackgroundColorNew>clWhite</BackgroundColorNew>
</FoldedCode>
<Hex>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>$00FFFFFF</ForegroundColorNew>
<BackgroundColorNew>$00000000</BackgroundColorNew>
</Hex>
<HotLink>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>$00FF9300</ForegroundColorNew>
<BackgroundColorNew>$00000000</BackgroundColorNew>
</HotLink>
<Identifier>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>$00FFFFFF</ForegroundColorNew>
<BackgroundColorNew>$00000000</BackgroundColorNew>
</Identifier>
<IllegalChar>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>$000000FF</ForegroundColorNew>
<BackgroundColorNew>$00000000</BackgroundColorNew>
</IllegalChar>
<InvalidBreak>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>clWhite</ForegroundColorNew>
<BackgroundColorNew>clGreen</BackgroundColorNew>
</InvalidBreak>
<LineHighlight>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>True</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>$00FFFFFF</ForegroundColorNew>
<BackgroundColorNew>$00757575</BackgroundColorNew>
</LineHighlight>
<LineNumber>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>$00FFFFFF</ForegroundColorNew>
<BackgroundColorNew>$00000000</BackgroundColorNew>
</LineNumber>
<MarkedBlock>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>True</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>$00FFFFFF</ForegroundColorNew>
<BackgroundColorNew>$00757575</BackgroundColorNew>
</MarkedBlock>
<ModifiedLine>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>clLime</ForegroundColorNew>
<BackgroundColorNew>clYellow</BackgroundColorNew>
</ModifiedLine>
<Number>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>$00FFFFFF</ForegroundColorNew>
<BackgroundColorNew>$00000000</BackgroundColorNew>
</Number>
<Octal>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>$00FFFFFF</ForegroundColorNew>
<BackgroundColorNew>$00000000</BackgroundColorNew>
</Octal>
<PlainText>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>$00FFFFFF</ForegroundColorNew>
<BackgroundColorNew>$00000000</BackgroundColorNew>
</PlainText>
<Preprocessor>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>$00FF9300</ForegroundColorNew>
<BackgroundColorNew>$00000000</BackgroundColorNew>
</Preprocessor>
<ReservedWord>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>$00FF9300</ForegroundColorNew>
<BackgroundColorNew>$00000000</BackgroundColorNew>
</ReservedWord>
<RightMargin>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>$00FFFFFF</ForegroundColorNew>
<BackgroundColorNew>$00424242</BackgroundColorNew>
</RightMargin>
<Scripts>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>True</DefaultBackground>
<ForegroundColorNew>clPurple</ForegroundColorNew>
<BackgroundColorNew>clWhite</BackgroundColorNew>
</Scripts>
<SearchMatch>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>$00FFFFFF</ForegroundColorNew>
<BackgroundColorNew>$00757575</BackgroundColorNew>
</SearchMatch>
<String>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>$0044FF0A</ForegroundColorNew>
<BackgroundColorNew>$00000000</BackgroundColorNew>
</String>
<Symbol>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>$00FFFFFF</ForegroundColorNew>
<BackgroundColorNew>$00000000</BackgroundColorNew>
</Symbol>
<SyncEditBackground>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>True</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>clBlack</ForegroundColorNew>
<BackgroundColorNew>$00FAFFE6</BackgroundColorNew>
</SyncEditBackground>
<SyncEditHighlight>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>clBlue</ForegroundColorNew>
<BackgroundColorNew>clWhite</BackgroundColorNew>
</SyncEditHighlight>
<Tags>
<Bold>True</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>True</DefaultBackground>
<ForegroundColorNew>clNavy</ForegroundColorNew>
<BackgroundColorNew>clWhite</BackgroundColorNew>
</Tags>
<Whitespace>
<Bold>False</Bold>
<Italic>False</Italic>
<Underline>False</Underline>
<DefaultForeground>False</DefaultForeground>
<DefaultBackground>False</DefaultBackground>
<ForegroundColorNew>$00FFFFFF</ForegroundColorNew>
<BackgroundColorNew>$00000000</BackgroundColorNew>
</Whitespace>
</DelphiIDETheme>
| {
"pile_set_name": "Github"
} |
<?php
/**
* TOP API: taobao.topats.task.delete request
*
* @author auto create
* @since 1.0, 2014.03.27
*/
class TopatsTaskDeleteRequest
{
/**
* 需要取消的任务ID
**/
private $taskId;
private $apiParas = array();
public function setTaskId($taskId)
{
$this->taskId = $taskId;
$this->apiParas["task_id"] = $taskId;
}
public function getTaskId()
{
return $this->taskId;
}
public function getApiMethodName()
{
return "taobao.topats.task.delete";
}
public function getApiParas()
{
return $this->apiParas;
}
public function check()
{
RequestCheckUtil::checkNotNull($this->taskId,"taskId");
}
public function putOtherTextParam($key, $value) {
$this->apiParas[$key] = $value;
$this->$key = $value;
}
}
| {
"pile_set_name": "Github"
} |
defaultNamespace: jx
applications:
- name: velero
repository: https://kubernetes-charts.storage.googleapis.com
namespace: velero
phase: foo | {
"pile_set_name": "Github"
} |
/* Copyright (C) 2019, 2020 Monomax Software Pty Ltd
*
* This file is part of Dnote.
*
* Dnote is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Dnote 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Dnote. If not, see <https://www.gnu.org/licenses/>.
*/
@import '../App/responsive';
@import '../App/theme';
@import '../App/rem';
@import '../App/font';
.wrapper {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: rem(20px) rem(16px);
background: $first;
z-index: 3;
position: relative;
@include breakpoint(lg) {
flex-direction: row;
justify-content: center;
}
}
.content {
}
.left {
display: flex;
flex-direction: column;
align-items: flex-start;
width: 100%;
@include breakpoint(md) {
flex-direction: row;
width: auto;
}
@include breakpoint(lg) {
align-items: center;
}
}
.right {
width: 100%;
display: flex;
align-items: center;
margin-top: rem(16px);
@include breakpoint(md) {
width: auto;
}
@include breakpoint(lg) {
margin-top: 0;
}
}
.heading {
@include font-size('medium');
font-weight: 600;
color: $white;
}
.subheading {
@include font-size('regular');
font-weight: 400;
color: $white;
@include breakpoint(md) {
margin-left: rem(8px);
}
}
.colon {
margin-right: rem(8px);
}
.support {
display: block;
@include breakpoint(md) {
display: inline-block;
}
}
.cta {
width: 100%;
flex: 1;
@include breakpoint(lg) {
width: auto;
flex: auto;
margin-left: rem(16px);
}
}
.quit {
color: $white;
@include font-size('small');
display: none;
&:hover {
color: #e3e3e3;
}
@include breakpoint(lg) {
display: block;
position: absolute;
right: rem(16px);
}
}
a.quit-mobile {
color: white;
font-size: 1.4rem;
flex: 1;
padding: 5px 14px;
@include breakpoint(lg) {
display: none;
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2017 The Android Open Source Project
*
* 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.android.settings.notification;
import static android.provider.Settings.Secure.NOTIFICATION_BADGING;
import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Handler;
import android.provider.Settings;
import android.text.TextUtils;
import androidx.annotation.VisibleForTesting;
import androidx.preference.Preference;
import androidx.preference.PreferenceScreen;
import com.android.settings.core.PreferenceControllerMixin;
import com.android.settings.core.TogglePreferenceController;
import com.android.settingslib.core.lifecycle.LifecycleObserver;
import com.android.settingslib.core.lifecycle.events.OnPause;
import com.android.settingslib.core.lifecycle.events.OnResume;
public class BadgingNotificationPreferenceController extends TogglePreferenceController
implements PreferenceControllerMixin, Preference.OnPreferenceChangeListener,
LifecycleObserver, OnResume, OnPause {
private static final String TAG = "BadgeNotifPrefContr";
@VisibleForTesting
static final int ON = 1;
@VisibleForTesting
static final int OFF = 0;
private SettingObserver mSettingObserver;
public BadgingNotificationPreferenceController(Context context, String preferenceKey) {
super(context, preferenceKey);
}
@Override
public void displayPreference(PreferenceScreen screen) {
super.displayPreference(screen);
Preference preference = screen.findPreference(NOTIFICATION_BADGING);
if (preference != null) {
mSettingObserver = new SettingObserver(preference);
}
}
@Override
public void onResume() {
if (mSettingObserver != null) {
mSettingObserver.register(mContext.getContentResolver(), true /* register */);
}
}
@Override
public void onPause() {
if (mSettingObserver != null) {
mSettingObserver.register(mContext.getContentResolver(), false /* register */);
}
}
@Override
public int getAvailabilityStatus() {
return mContext.getResources()
.getBoolean(com.android.internal.R.bool.config_notificationBadging)
? AVAILABLE : UNSUPPORTED_ON_DEVICE;
}
@Override
public boolean isSliceable() {
return TextUtils.equals(getPreferenceKey(), "notification_badging");
}
@Override
public boolean isChecked() {
return Settings.Secure.getInt(mContext.getContentResolver(),
NOTIFICATION_BADGING, ON) == ON;
}
@Override
public boolean setChecked(boolean isChecked) {
return Settings.Secure.putInt(mContext.getContentResolver(),
NOTIFICATION_BADGING, isChecked ? ON : OFF);
}
class SettingObserver extends ContentObserver {
private final Uri NOTIFICATION_BADGING_URI =
Settings.Secure.getUriFor(NOTIFICATION_BADGING);
private final Preference mPreference;
public SettingObserver(Preference preference) {
super(new Handler());
mPreference = preference;
}
public void register(ContentResolver cr, boolean register) {
if (register) {
cr.registerContentObserver(NOTIFICATION_BADGING_URI, false, this);
} else {
cr.unregisterContentObserver(this);
}
}
@Override
public void onChange(boolean selfChange, Uri uri) {
super.onChange(selfChange, uri);
if (NOTIFICATION_BADGING_URI.equals(uri)) {
updateState(mPreference);
}
}
}
}
| {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: fb6d9d718acd94542b76c06f8d30f345
ModelImporter:
serializedVersion: 23
fileIDToRecycleName:
100000: Bag1
100002: Camera
100004: Cord1
100006: Directional Light
100008: Handle1
100010: Handle2
100012: Vacuum1
100014: Vacuum2
100016: //RootNode
100018: Weels2
100020: Mesh
100022: Vacuum3
100024: GlassCover
100026: GlassTube
100028: Handle
100030: Cord2
100032: Bag
100034: Vacuum4
100036: Bag4
100038: Cord3
100040: Cord4
100042: Handle4
400000: Bag1
400002: Camera
400004: Cord1
400006: Directional Light
400008: Handle1
400010: Handle2
400012: Vacuum1
400014: Vacuum2
400016: //RootNode
400018: Weels2
400020: Mesh
400022: Vacuum3
400024: GlassCover
400026: GlassTube
400028: Handle
400030: Cord2
400032: Bag
400034: Vacuum4
400036: Bag4
400038: Cord3
400040: Cord4
400042: Handle4
2300000: Bag1
2300002: Cord1
2300004: Handle1
2300006: Handle2
2300008: Vacuum1
2300010: Vacuum2
2300012: Weels2
2300014: Mesh
2300016: Vacuum3
2300018: GlassCover
2300020: GlassTube
2300022: Handle
2300024: Cord2
2300026: Bag
2300028: Vacuum4
2300030: Bag4
2300032: Cord3
2300034: Cord4
2300036: Handle4
3300000: Bag1
3300002: Cord1
3300004: Handle1
3300006: Handle2
3300008: Vacuum1
3300010: Vacuum2
3300012: Weels2
3300014: Mesh
3300016: Vacuum3
3300018: GlassCover
3300020: GlassTube
3300022: Handle
3300024: Cord2
3300026: Bag
3300028: Vacuum4
3300030: Bag4
3300032: Cord3
3300034: Cord4
3300036: Handle4
4300000: Vacuum1
4300002: Handle1
4300004: Bag1
4300006: Cord1
4300008: Vacuum2
4300010: Handle2
4300012: Weels2
4300014: Vacuum3
4300016: Mesh
4300018: GlassCover
4300020: GlassTube
4300022: Handle
4300024: Cord2
4300026: Vacuum4
4300028: Bag
4300030: Cord3
4300032: Handle4
4300034: Cord4
4300036: Bag4
7400000: Take 001
9500000: //RootNode
2186277476908879412: ImportLogs
externalObjects:
- first:
type: UnityEngine:Material
assembly: UnityEngine.CoreModule
name: BagMat
second: {fileID: 2100000, guid: b839877126f66414da24ef926da099de, type: 2}
- first:
type: UnityEngine:Material
assembly: UnityEngine.CoreModule
name: GlassMat
second: {fileID: 2100000, guid: 6f34f29e6bf039a42bb008efb137ffc5, type: 2}
- first:
type: UnityEngine:Material
assembly: UnityEngine.CoreModule
name: MetalMat
second: {fileID: 2100000, guid: 263a050ff19a3294a8ec697180ce630e, type: 2}
- first:
type: UnityEngine:Material
assembly: UnityEngine.CoreModule
name: PlasticMat
second: {fileID: 2100000, guid: 24ec335dad2ea61469e95d17577ae5ed, type: 2}
- first:
type: UnityEngine:Material
assembly: UnityEngine.CoreModule
name: RubberMat
second: {fileID: 2100000, guid: f6ec25c62736619449110ad0c81025de, type: 2}
materials:
importMaterials: 1
materialName: 0
materialSearch: 1
materialLocation: 0
animations:
legacyGenerateAnimations: 4
bakeSimulation: 0
resampleCurves: 1
optimizeGameObjects: 0
motionNodeName:
rigImportErrors:
rigImportWarnings:
animationImportErrors:
animationImportWarnings:
animationRetargetingWarnings:
animationDoRetargetingWarnings: 0
importAnimatedCustomProperties: 0
importConstraints: 0
animationCompression: 1
animationRotationError: 0.5
animationPositionError: 0.5
animationScaleError: 0.5
animationWrapMode: 0
extraExposedTransformPaths: []
extraUserProperties: []
clipAnimations: []
isReadable: 1
meshes:
lODScreenPercentages: []
globalScale: 1
meshCompression: 0
addColliders: 0
useSRGBMaterialColor: 1
importVisibility: 0
importBlendShapes: 1
importCameras: 0
importLights: 0
swapUVChannels: 0
generateSecondaryUV: 0
useFileUnits: 1
optimizeMeshForGPU: 1
keepQuads: 0
weldVertices: 1
preserveHierarchy: 0
indexFormat: 1
secondaryUVAngleDistortion: 8
secondaryUVAreaDistortion: 15.000001
secondaryUVHardAngle: 88
secondaryUVPackMargin: 4
useFileScale: 1
previousCalculatedGlobalScale: 1
hasPreviousCalculatedGlobalScale: 0
tangentSpace:
normalSmoothAngle: 60
normalImportMode: 0
tangentImportMode: 3
normalCalculationMode: 0
legacyComputeAllNormalsFromSmoothingGroupsWhenMeshHasBlendShapes: 1
blendShapeNormalImportMode: 1
normalSmoothingSource: 0
importAnimation: 0
copyAvatar: 0
humanDescription:
serializedVersion: 2
human: []
skeleton: []
armTwist: 0.5
foreArmTwist: 0.5
upperLegTwist: 0.5
legTwist: 0.5
armStretch: 0.05
legStretch: 0.05
feetSpacing: 0
rootMotionBoneName:
hasTranslationDoF: 0
hasExtraRoot: 0
skeletonHasParents: 0
lastHumanDescriptionAvatarSource: {instanceID: 0}
animationType: 0
humanoidOversampling: 1
additionalBone: 0
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
/**
* Copyright 2019 VMware, Inc.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 io.micrometer.core.instrument.binder.mongodb;
import com.mongodb.MongoClient;
import com.mongodb.connection.ServerId;
import com.mongodb.event.*;
import io.micrometer.core.annotation.Incubating;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.lang.NonNullApi;
import io.micrometer.core.lang.NonNullFields;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
/**
* {@link ConnectionPoolListener} for collecting connection pool metrics from {@link MongoClient}.
*
* @author Christophe Bornet
* @since 1.2.0
*/
@NonNullApi
@NonNullFields
@Incubating(since = "1.2.0")
public class MongoMetricsConnectionPoolListener extends ConnectionPoolListenerAdapter {
private static final String METRIC_PREFIX = "mongodb.driver.pool.";
private final Map<ServerId, AtomicInteger> poolSize = new ConcurrentHashMap<>();
private final Map<ServerId, AtomicInteger> checkedOutCount = new ConcurrentHashMap<>();
private final Map<ServerId, AtomicInteger> waitQueueSize = new ConcurrentHashMap<>();
private final Map<ServerId, List<Meter>> meters = new ConcurrentHashMap<>();
private final MeterRegistry registry;
public MongoMetricsConnectionPoolListener(MeterRegistry registry) {
this.registry = registry;
}
@Override
public void connectionPoolOpened(ConnectionPoolOpenedEvent event) {
List<Meter> connectionMeters = new ArrayList<>();
connectionMeters.add(registerGauge(event.getServerId(), METRIC_PREFIX + "size",
"the current size of the connection pool, including idle and and in-use members", poolSize));
connectionMeters.add(registerGauge(event.getServerId(), METRIC_PREFIX + "checkedout",
"the count of connections that are currently in use", checkedOutCount));
connectionMeters.add(registerGauge(event.getServerId(), METRIC_PREFIX + "waitqueuesize",
"the current size of the wait queue for a connection from the pool", waitQueueSize));
meters.put(event.getServerId(), connectionMeters);
}
@Override
public void connectionPoolClosed(ConnectionPoolClosedEvent event) {
ServerId serverId = event.getServerId();
for (Meter meter : meters.get(serverId)) {
registry.remove(meter);
}
meters.remove(serverId);
poolSize.remove(serverId);
checkedOutCount.remove(serverId);
waitQueueSize.remove(serverId);
}
@Override
public void connectionCheckedOut(ConnectionCheckedOutEvent event) {
checkedOutCount.get(event.getConnectionId().getServerId())
.incrementAndGet();
}
@Override
public void connectionCheckedIn(ConnectionCheckedInEvent event) {
checkedOutCount.get(event.getConnectionId().getServerId())
.decrementAndGet();
}
@SuppressWarnings("deprecation")
@Override
public void waitQueueEntered(ConnectionPoolWaitQueueEnteredEvent event) {
waitQueueSize.get(event.getServerId())
.incrementAndGet();
}
@SuppressWarnings("deprecation")
@Override
public void waitQueueExited(ConnectionPoolWaitQueueExitedEvent event) {
waitQueueSize.get(event.getServerId())
.decrementAndGet();
}
@Override
public void connectionAdded(ConnectionAddedEvent event) {
poolSize.get(event.getConnectionId().getServerId())
.incrementAndGet();
}
@Override
public void connectionRemoved(ConnectionRemovedEvent event) {
poolSize.get(event.getConnectionId().getServerId())
.decrementAndGet();
}
private Gauge registerGauge(ServerId serverId, String metricName, String description, Map<ServerId, AtomicInteger> metrics) {
AtomicInteger value = new AtomicInteger();
metrics.put(serverId, value);
return Gauge.builder(metricName, value, AtomicInteger::doubleValue)
.description(description)
.tag("cluster.id", serverId.getClusterId().getValue())
.tag("server.address", serverId.getAddress().toString())
.register(registry);
}
}
| {
"pile_set_name": "Github"
} |
/*
* =====================================================================================
*
* Filename: xRenderToFile.cpp
*
* Description: render pixelbuffer to a .ppm file
*
* Version: 1.0
* Created: 03/25/2015 10:26:14
* Revision: none
* Compiler: gcc
*
* Author: Pablo Colapinto (), gmail->wolftype
* Organization: wolftype
*
* =====================================================================================
*/
#include "vsr_cga3D_app.h"
#include "gfx/gfx_file.h"
using namespace vsr;
using namespace vsr::cga3D;
struct MyApp : App {
//Some Variables
bool bReset = false;
float amt = 0;
gfx::File file;
/*-----------------------------------------------------------------------------
* Setup Variables
*-----------------------------------------------------------------------------*/
void setup(){
///Bind Gui
bindGLV();
///Add Variables to GUI
gui(amt,"amt",-100,100)(bReset,"bReset");
}
/*-----------------------------------------------------------------------------
* Draw Routines
*-----------------------------------------------------------------------------*/
void onDraw(){
Draw(CXY(1), 0,1,0);
if (bReset){
bReset = false;
cout << windowData().width() << " " << windowData().height() << endl;
file.write( windowData().width(), windowData().height(), "/Volumes/Medico/vsr_tmp_output/render/");
}
}
void onResize(int w, int h){
App::onResize(w,h);
printf("resize\n");
if (file.pixels) delete[] file.pixels;
file.pixels = new unsigned char[ int(w*h*4) ];
}
};
int main(){
MyApp app;
app.start();
return 0;
}
| {
"pile_set_name": "Github"
} |
// Copyright 2017 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 unix
import (
"os"
"syscall"
)
// FIXME: unexported function from os
// syscallMode returns the syscall-specific mode bits from Go's portable mode bits.
func syscallMode(i os.FileMode) (o uint32) {
o |= uint32(i.Perm())
if i&os.ModeSetuid != 0 {
o |= syscall.S_ISUID
}
if i&os.ModeSetgid != 0 {
o |= syscall.S_ISGID
}
if i&os.ModeSticky != 0 {
o |= syscall.S_ISVTX
}
// No mapping for Go's ModeTemporary (plan9 only).
return
}
| {
"pile_set_name": "Github"
} |
from neat.graphs import feed_forward_layers
class FeedForwardNetwork(object):
def __init__(self, inputs, outputs, node_evals):
self.input_nodes = inputs
self.output_nodes = outputs
self.node_evals = node_evals
self.values = dict((key, 0.0) for key in inputs + outputs)
def activate(self, inputs):
if len(self.input_nodes) != len(inputs):
raise RuntimeError("Expected {0:n} inputs, got {1:n}".format(len(self.input_nodes), len(inputs)))
for k, v in zip(self.input_nodes, inputs):
self.values[k] = v
for node, act_func, agg_func, bias, response, links in self.node_evals:
node_inputs = []
for i, w in links:
node_inputs.append(self.values[i] * w)
s = agg_func(node_inputs)
self.values[node] = act_func(bias + response * s)
return [self.values[i] for i in self.output_nodes]
@staticmethod
def create(genome, config):
""" Receives a genome and returns its phenotype (a FeedForwardNetwork). """
# Gather expressed connections.
connections = [cg.key for cg in genome.connections.values() if cg.enabled]
layers = feed_forward_layers(config.genome_config.input_keys, config.genome_config.output_keys, connections)
node_evals = []
for layer in layers:
for node in layer:
inputs = []
node_expr = [] # currently unused
for conn_key in connections:
inode, onode = conn_key
if onode == node:
cg = genome.connections[conn_key]
inputs.append((inode, cg.weight))
node_expr.append("v[{}] * {:.7e}".format(inode, cg.weight))
ng = genome.nodes[node]
aggregation_function = config.genome_config.aggregation_function_defs.get(ng.aggregation)
activation_function = config.genome_config.activation_defs.get(ng.activation)
node_evals.append((node, activation_function, aggregation_function, ng.bias, ng.response, inputs))
return FeedForwardNetwork(config.genome_config.input_keys, config.genome_config.output_keys, node_evals)
| {
"pile_set_name": "Github"
} |
/*
Name: AGM_Interaction_fnc_GetActions
Author:
commy2
Garth de Wet (LH)
Description:
Parameters:
0: OBJECT - target
1: ARRAY - Parents of the target object
2: ARRAY - Actions
3: ARRAY - Patches
4: CONFIG - Parent config (ConfigFile >> "CfgVehicles"/MissionConfigFile >> "CfgVehicles")
5: BOOL - Is mission config file?
6: STRING - Classname ("AGM_Actions"/"AGM_SelfActions")
7: STRING - Sub-class
Returns:
Nothing
Example:
[player, [configfile >> "CfgVehicles" >> typeOf player, true] call BIS_fnc_returnParents, [], [],configfile >> "CfgVehicles", false, "AGM_Actions"] call AGM_Interaction_fnc_GetActions;
[player, [configfile >> "CfgVehicles" >> typeOf player, true] call BIS_fnc_returnParents, [], [],configfile >> "CfgVehicles", false, "AGM_SelfActions"] call AGM_Interaction_fnc_GetActions;
*/
#define DEFAULT_ICON "\AGM_Interaction\UI\dot_ca.paa"
private ["_target", "_parents", "_actions", "_patches", "_baseConfig", "_actionType", "_i","_index", "_missionConfig", "_stdConfig"];
_target = _this select 0;
_parents = _this select 1;
_actions = _this select 2;
_patches = _this select 3;
_baseConfig = _this select 4;
_missionConfig = _this select 5;
_actionType = _this select 6;
_subClass = _this select 7;
_stdConfig = (configFile >> "CfgVehicles" >> typeOf _target >> _actionType);
if (_subClass != "") then {
_stdConfig = _stdConfig >> _subClass;
};
_count = count _parents;
for "_i" from 0 to (_count - 1) do {
_config = _baseConfig >> _parents select _i >> _actionType;
if (_subClass != "") then {
_config = _config >> _subClass;
};
_count = count _config;
if (_count > 0) then {
for "_index" from 0 to (_count - 1) do {
private ["_action", "_displayName", "_distance","_condition","_statement","_showDisabled", "_priority", "_tooltip", "_hotkey",
"_subMenu", "_conditionShow", "_exceptions", "_icon", "_actionToCache", "_cacheActions", "_cache", "_indexCache", "_configName"];
_action = if (_missionConfig) then {_config select _index} else {_stdConfig >> configName (_config select _index)};
_cache = missionNamespace getVariable ["AGM_Interaction_MenuCache", [[], [], []]];
if (count _action > 0) then {
_configName = configName _action;
_cacheConfigs = _cache select 0;
_cacheActions = _cache select 1;
_cacheIndices = _cache select 2;
_indexCache = _cacheConfigs find _action;
if (_indexCache == -1) then {
_displayName = getText (_action >> "displayName");
_distance = getNumber (_action >> "distance");
_priority = getNumber (_action >> "priority");
_subMenu = getArray (_action >> "subMenu");
_tooltip = getText (_action >> "tooltip");
_hotkey = getText (_action >> "hotkey");
_enableInside = getNumber (_action >> "enableInside");
// Condition
_condition = getText (_action >> "condition");
if (_condition == "") then {_condition = "true"};
_condition = _condition + format [" && {%1 call AGM_Core_canInteract} && {[AGM_player, AGM_Interaction_Target] call AGM_Core_fnc_canInteractWith}", getArray (_action >> "exceptions")];
if (_enableInside != 1) then {_condition = _condition + " && {_player == _vehicle}"};
_condition = compile _condition;
// Condition to show the action
_conditionShow = getText (_action >> "conditionShow");
_conditionShow = if (_conditionShow == "") then {{true}} else {compile _conditionShow};
_showDisabled = getNumber (_action >> "showDisabled") == 1;
if (isText (_action >> "conditionShow")) then {
_showDisabled = [_object, _player] call _conditionShow;
};
// Exceptions to the general conditions that have to be true
_exceptions = getArray (_action >> "exceptions");
// statement
_statement = getText (_action >> "statement");
_statement = compile _statement;
if (profileNamespace getVariable ["AGM_Interaction_FlowMenu", false]) then {
_statement = if (getText (_action >> "statement") == "" && {count _subMenu > 1}) then {
compile format ["call AGM_Interaction_fnc_hideMenu;if(%2 == 1)then{['%1'] call AGM_Interaction_fnc_openSubMenuSelf;}else{['%1'] call AGM_Interaction_fnc_openSubMenu;};", _subMenu select 0, _subMenu select 1];
} else {
compile ("call AGM_Interaction_fnc_hideMenu;" + getText (_action >> "statement"));
};
};
// icon
_icon = getText (_action >> "Icon");
if (_icon == "") then {
_icon = DEFAULT_ICON;
};
_actionToCache = [_displayName, _statement, _condition, _priority, _subMenu, _icon, _tooltip, _conditionShow, _exceptions, _distance, _hotkey];
if (!(_configName in _patches) && {_showDisabled || {[_object, _player] call _condition}} && {_distance == 0 || {[_object, _distance] call AGM_Interaction_fnc_isInRange}}) then {
_actions pushBack _actionToCache;
_patches pushBack _configName;
};
_indexCache = _cacheActions find _actionToCache;
if (_indexCache == -1) then {
_indexCache = count _cacheActions;
_cacheActions pushBack _actionToCache;
};
_cacheConfigs pushBack _action;
_cacheIndices pushBack _indexCache;
_cache = [_cacheConfigs, _cacheActions, _cacheIndices];
["InteractionMenu", _action, {format ["%1 loaded into cache", _this]}] call AGM_Debug_fnc_log;
} else {
["InteractionMenu", _action, {format ["%1 loaded from cache", _this]}] call AGM_Debug_fnc_log;
_cachedAction = _cacheActions select (_cacheIndices select _indexCache);
_showDisabled = getNumber (_action >> "showDisabled") == 1;
if (isText (_action >> "conditionShow")) then {
_showDisabled = [_object, _player] call (_cachedAction select 7);
};
if (!(_configName in _patches) && {_showDisabled || {[_object, _player] call (_cachedAction select 2)}} && {[_object, (_cachedAction select 9)] call AGM_Interaction_fnc_isInRange || {(_cachedAction select 9) == 0}}) then {
_actions pushBack _cachedAction;
_patches pushBack _configName;
};
};
};
AGM_Interaction_MenuCache = _cache;
};
};
};
[_actions, _patches]
| {
"pile_set_name": "Github"
} |
[
{
"BriefDescription": "This category represents fraction of slots where the processor's Frontend undersupplies its Backend",
"MetricExpr": "IDQ_UOPS_NOT_DELIVERED.CORE / (4 * cycles)",
"MetricGroup": "TopdownL1",
"MetricName": "Frontend_Bound",
"PublicDescription": "This category represents fraction of slots where the processor's Frontend undersupplies its Backend. Frontend denotes the first part of the processor core responsible to fetch operations that are executed later on by the Backend part. Within the Frontend; a branch predictor predicts the next address to fetch; cache-lines are fetched from the memory subsystem; parsed into instructions; and lastly decoded into micro-ops (uops). Ideally the Frontend can issue 4 uops every cycle to the Backend. Frontend Bound denotes unutilized issue-slots when there is no Backend stall; i.e. bubbles where Frontend delivered no uops while Backend could have accepted them. For example; stalls due to instruction-cache misses would be categorized under Frontend Bound."
},
{
"BriefDescription": "This category represents fraction of slots where the processor's Frontend undersupplies its Backend. SMT version; use when SMT is enabled and measuring per logical CPU.",
"MetricExpr": "IDQ_UOPS_NOT_DELIVERED.CORE / (4 * (( ( CPU_CLK_UNHALTED.THREAD / 2 ) * ( 1 + CPU_CLK_UNHALTED.ONE_THREAD_ACTIVE / CPU_CLK_UNHALTED.REF_XCLK ) )))",
"MetricGroup": "TopdownL1_SMT",
"MetricName": "Frontend_Bound_SMT",
"PublicDescription": "This category represents fraction of slots where the processor's Frontend undersupplies its Backend. Frontend denotes the first part of the processor core responsible to fetch operations that are executed later on by the Backend part. Within the Frontend; a branch predictor predicts the next address to fetch; cache-lines are fetched from the memory subsystem; parsed into instructions; and lastly decoded into micro-ops (uops). Ideally the Frontend can issue 4 uops every cycle to the Backend. Frontend Bound denotes unutilized issue-slots when there is no Backend stall; i.e. bubbles where Frontend delivered no uops while Backend could have accepted them. For example; stalls due to instruction-cache misses would be categorized under Frontend Bound. SMT version; use when SMT is enabled and measuring per logical CPU."
},
{
"BriefDescription": "This category represents fraction of slots wasted due to incorrect speculations",
"MetricExpr": "( UOPS_ISSUED.ANY - UOPS_RETIRED.RETIRE_SLOTS + 4 * INT_MISC.RECOVERY_CYCLES ) / (4 * cycles)",
"MetricGroup": "TopdownL1",
"MetricName": "Bad_Speculation",
"PublicDescription": "This category represents fraction of slots wasted due to incorrect speculations. This include slots used to issue uops that do not eventually get retired and slots for which the issue-pipeline was blocked due to recovery from earlier incorrect speculation. For example; wasted work due to miss-predicted branches are categorized under Bad Speculation category. Incorrect data speculation followed by Memory Ordering Nukes is another example."
},
{
"BriefDescription": "This category represents fraction of slots wasted due to incorrect speculations. SMT version; use when SMT is enabled and measuring per logical CPU.",
"MetricExpr": "( UOPS_ISSUED.ANY - UOPS_RETIRED.RETIRE_SLOTS + 4 * (( INT_MISC.RECOVERY_CYCLES_ANY / 2 )) ) / (4 * (( ( CPU_CLK_UNHALTED.THREAD / 2 ) * ( 1 + CPU_CLK_UNHALTED.ONE_THREAD_ACTIVE / CPU_CLK_UNHALTED.REF_XCLK ) )))",
"MetricGroup": "TopdownL1_SMT",
"MetricName": "Bad_Speculation_SMT",
"PublicDescription": "This category represents fraction of slots wasted due to incorrect speculations. This include slots used to issue uops that do not eventually get retired and slots for which the issue-pipeline was blocked due to recovery from earlier incorrect speculation. For example; wasted work due to miss-predicted branches are categorized under Bad Speculation category. Incorrect data speculation followed by Memory Ordering Nukes is another example. SMT version; use when SMT is enabled and measuring per logical CPU."
},
{
"BriefDescription": "This category represents fraction of slots where no uops are being delivered due to a lack of required resources for accepting new uops in the Backend",
"MetricExpr": "1 - ( (IDQ_UOPS_NOT_DELIVERED.CORE / (4 * cycles)) + (( UOPS_ISSUED.ANY - UOPS_RETIRED.RETIRE_SLOTS + 4 * INT_MISC.RECOVERY_CYCLES ) / (4 * cycles)) + (UOPS_RETIRED.RETIRE_SLOTS / (4 * cycles)) )",
"MetricGroup": "TopdownL1",
"MetricName": "Backend_Bound",
"PublicDescription": "This category represents fraction of slots where no uops are being delivered due to a lack of required resources for accepting new uops in the Backend. Backend is the portion of the processor core where the out-of-order scheduler dispatches ready uops into their respective execution units; and once completed these uops get retired according to program order. For example; stalls due to data-cache misses or stalls due to the divider unit being overloaded are both categorized under Backend Bound. Backend Bound is further divided into two main categories: Memory Bound and Core Bound."
},
{
"BriefDescription": "This category represents fraction of slots where no uops are being delivered due to a lack of required resources for accepting new uops in the Backend. SMT version; use when SMT is enabled and measuring per logical CPU.",
"MetricExpr": "1 - ( (IDQ_UOPS_NOT_DELIVERED.CORE / (4 * (( ( CPU_CLK_UNHALTED.THREAD / 2 ) * ( 1 + CPU_CLK_UNHALTED.ONE_THREAD_ACTIVE / CPU_CLK_UNHALTED.REF_XCLK ) )))) + (( UOPS_ISSUED.ANY - UOPS_RETIRED.RETIRE_SLOTS + 4 * (( INT_MISC.RECOVERY_CYCLES_ANY / 2 )) ) / (4 * (( ( CPU_CLK_UNHALTED.THREAD / 2 ) * ( 1 + CPU_CLK_UNHALTED.ONE_THREAD_ACTIVE / CPU_CLK_UNHALTED.REF_XCLK ) )))) + (UOPS_RETIRED.RETIRE_SLOTS / (4 * (( ( CPU_CLK_UNHALTED.THREAD / 2 ) * ( 1 + CPU_CLK_UNHALTED.ONE_THREAD_ACTIVE / CPU_CLK_UNHALTED.REF_XCLK ) )))) )",
"MetricGroup": "TopdownL1_SMT",
"MetricName": "Backend_Bound_SMT",
"PublicDescription": "This category represents fraction of slots where no uops are being delivered due to a lack of required resources for accepting new uops in the Backend. Backend is the portion of the processor core where the out-of-order scheduler dispatches ready uops into their respective execution units; and once completed these uops get retired according to program order. For example; stalls due to data-cache misses or stalls due to the divider unit being overloaded are both categorized under Backend Bound. Backend Bound is further divided into two main categories: Memory Bound and Core Bound. SMT version; use when SMT is enabled and measuring per logical CPU."
},
{
"BriefDescription": "This category represents fraction of slots utilized by useful work i.e. issued uops that eventually get retired",
"MetricExpr": "UOPS_RETIRED.RETIRE_SLOTS / (4 * cycles)",
"MetricGroup": "TopdownL1",
"MetricName": "Retiring",
"PublicDescription": "This category represents fraction of slots utilized by useful work i.e. issued uops that eventually get retired. Ideally; all pipeline slots would be attributed to the Retiring category. Retiring of 100% would indicate the maximum 4 uops retired per cycle has been achieved. Maximizing Retiring typically increases the Instruction-Per-Cycle metric. Note that a high Retiring value does not necessary mean there is no room for more performance. For example; Microcode assists are categorized under Retiring. They hurt performance and can often be avoided. "
},
{
"BriefDescription": "This category represents fraction of slots utilized by useful work i.e. issued uops that eventually get retired. SMT version; use when SMT is enabled and measuring per logical CPU.",
"MetricExpr": "UOPS_RETIRED.RETIRE_SLOTS / (4 * (( ( CPU_CLK_UNHALTED.THREAD / 2 ) * ( 1 + CPU_CLK_UNHALTED.ONE_THREAD_ACTIVE / CPU_CLK_UNHALTED.REF_XCLK ) )))",
"MetricGroup": "TopdownL1_SMT",
"MetricName": "Retiring_SMT",
"PublicDescription": "This category represents fraction of slots utilized by useful work i.e. issued uops that eventually get retired. Ideally; all pipeline slots would be attributed to the Retiring category. Retiring of 100% would indicate the maximum 4 uops retired per cycle has been achieved. Maximizing Retiring typically increases the Instruction-Per-Cycle metric. Note that a high Retiring value does not necessary mean there is no room for more performance. For example; Microcode assists are categorized under Retiring. They hurt performance and can often be avoided. SMT version; use when SMT is enabled and measuring per logical CPU."
},
{
"BriefDescription": "Instructions Per Cycle (per Logical Processor)",
"MetricExpr": "INST_RETIRED.ANY / CPU_CLK_UNHALTED.THREAD",
"MetricGroup": "TopDownL1",
"MetricName": "IPC"
},
{
"BriefDescription": "Uops Per Instruction",
"MetricExpr": "UOPS_RETIRED.RETIRE_SLOTS / INST_RETIRED.ANY",
"MetricGroup": "Pipeline;Retire",
"MetricName": "UPI"
},
{
"BriefDescription": "Rough Estimation of fraction of fetched lines bytes that were likely (includes speculatively fetches) consumed by program instructions",
"MetricExpr": "min( 1 , UOPS_ISSUED.ANY / ( (UOPS_RETIRED.RETIRE_SLOTS / INST_RETIRED.ANY) * 32 * ( ICACHE.HIT + ICACHE.MISSES ) / 4 ) )",
"MetricGroup": "PGO;IcMiss",
"MetricName": "IFetch_Line_Utilization"
},
{
"BriefDescription": "Fraction of Uops delivered by the DSB (aka Decoded ICache; or Uop Cache)",
"MetricExpr": "IDQ.DSB_UOPS / (( IDQ.DSB_UOPS + LSD.UOPS + IDQ.MITE_UOPS + IDQ.MS_UOPS ) )",
"MetricGroup": "DSB;Fetch_BW",
"MetricName": "DSB_Coverage"
},
{
"BriefDescription": "Cycles Per Instruction (per Logical Processor)",
"MetricExpr": "1 / (INST_RETIRED.ANY / cycles)",
"MetricGroup": "Pipeline;Summary",
"MetricName": "CPI"
},
{
"BriefDescription": "Per-Logical Processor actual clocks when the Logical Processor is active.",
"MetricExpr": "CPU_CLK_UNHALTED.THREAD",
"MetricGroup": "Summary",
"MetricName": "CLKS"
},
{
"BriefDescription": "Total issue-pipeline slots (per-Physical Core)",
"MetricExpr": "4 * cycles",
"MetricGroup": "TopDownL1",
"MetricName": "SLOTS"
},
{
"BriefDescription": "Total issue-pipeline slots (per-Physical Core)",
"MetricExpr": "4 * (( ( CPU_CLK_UNHALTED.THREAD / 2 ) * ( 1 + CPU_CLK_UNHALTED.ONE_THREAD_ACTIVE / CPU_CLK_UNHALTED.REF_XCLK ) ))",
"MetricGroup": "TopDownL1_SMT",
"MetricName": "SLOTS_SMT"
},
{
"BriefDescription": "Total number of retired Instructions",
"MetricExpr": "INST_RETIRED.ANY",
"MetricGroup": "Summary",
"MetricName": "Instructions"
},
{
"BriefDescription": "Instructions Per Cycle (per physical core)",
"MetricExpr": "INST_RETIRED.ANY / cycles",
"MetricGroup": "SMT",
"MetricName": "CoreIPC"
},
{
"BriefDescription": "Instructions Per Cycle (per physical core)",
"MetricExpr": "INST_RETIRED.ANY / (( ( CPU_CLK_UNHALTED.THREAD / 2 ) * ( 1 + CPU_CLK_UNHALTED.ONE_THREAD_ACTIVE / CPU_CLK_UNHALTED.REF_XCLK ) ))",
"MetricGroup": "SMT",
"MetricName": "CoreIPC_SMT"
},
{
"BriefDescription": "Floating Point Operations Per Cycle",
"MetricExpr": "(( 1 * ( FP_COMP_OPS_EXE.SSE_SCALAR_SINGLE + FP_COMP_OPS_EXE.SSE_SCALAR_DOUBLE ) + 2 * FP_COMP_OPS_EXE.SSE_PACKED_DOUBLE + 4 * ( FP_COMP_OPS_EXE.SSE_PACKED_SINGLE + SIMD_FP_256.PACKED_DOUBLE ) + 8 * SIMD_FP_256.PACKED_SINGLE )) / cycles",
"MetricGroup": "FLOPS",
"MetricName": "FLOPc"
},
{
"BriefDescription": "Floating Point Operations Per Cycle",
"MetricExpr": "(( 1 * ( FP_COMP_OPS_EXE.SSE_SCALAR_SINGLE + FP_COMP_OPS_EXE.SSE_SCALAR_DOUBLE ) + 2 * FP_COMP_OPS_EXE.SSE_PACKED_DOUBLE + 4 * ( FP_COMP_OPS_EXE.SSE_PACKED_SINGLE + SIMD_FP_256.PACKED_DOUBLE ) + 8 * SIMD_FP_256.PACKED_SINGLE )) / (( ( CPU_CLK_UNHALTED.THREAD / 2 ) * ( 1 + CPU_CLK_UNHALTED.ONE_THREAD_ACTIVE / CPU_CLK_UNHALTED.REF_XCLK ) ))",
"MetricGroup": "FLOPS_SMT",
"MetricName": "FLOPc_SMT"
},
{
"BriefDescription": "Instruction-Level-Parallelism (average number of uops executed when there is at least 1 uop executed)",
"MetricExpr": "UOPS_DISPATCHED.THREAD / (( cpu@UOPS_DISPATCHED.CORE\\,cmask\\=1@ / 2 ) if #SMT_on else cpu@UOPS_DISPATCHED.CORE\\,cmask\\=1@)",
"MetricGroup": "Pipeline",
"MetricName": "ILP"
},
{
"BriefDescription": "Core actual clocks when any Logical Processor is active on the Physical Core",
"MetricExpr": "( ( CPU_CLK_UNHALTED.THREAD / 2 ) * ( 1 + CPU_CLK_UNHALTED.ONE_THREAD_ACTIVE / CPU_CLK_UNHALTED.REF_XCLK ) )",
"MetricGroup": "SMT",
"MetricName": "CORE_CLKS"
},
{
"BriefDescription": "Average CPU Utilization",
"MetricExpr": "CPU_CLK_UNHALTED.REF_TSC / msr@tsc@",
"MetricGroup": "Summary",
"MetricName": "CPU_Utilization"
},
{
"BriefDescription": "Giga Floating Point Operations Per Second",
"MetricExpr": "( (( 1 * ( FP_COMP_OPS_EXE.SSE_SCALAR_SINGLE + FP_COMP_OPS_EXE.SSE_SCALAR_DOUBLE ) + 2 * FP_COMP_OPS_EXE.SSE_PACKED_DOUBLE + 4 * ( FP_COMP_OPS_EXE.SSE_PACKED_SINGLE + SIMD_FP_256.PACKED_DOUBLE ) + 8 * SIMD_FP_256.PACKED_SINGLE )) / 1000000000 ) / duration_time",
"MetricGroup": "FLOPS;Summary",
"MetricName": "GFLOPs"
},
{
"BriefDescription": "Average Frequency Utilization relative nominal frequency",
"MetricExpr": "CPU_CLK_UNHALTED.THREAD / CPU_CLK_UNHALTED.REF_TSC",
"MetricGroup": "Power",
"MetricName": "Turbo_Utilization"
},
{
"BriefDescription": "Fraction of cycles where both hardware Logical Processors were active",
"MetricExpr": "1 - CPU_CLK_THREAD_UNHALTED.ONE_THREAD_ACTIVE / ( CPU_CLK_THREAD_UNHALTED.REF_XCLK_ANY / 2 ) if #SMT_on else 0",
"MetricGroup": "SMT;Summary",
"MetricName": "SMT_2T_Utilization"
},
{
"BriefDescription": "Fraction of cycles spent in Kernel mode",
"MetricExpr": "CPU_CLK_UNHALTED.THREAD:k / CPU_CLK_UNHALTED.THREAD",
"MetricGroup": "Summary",
"MetricName": "Kernel_Utilization"
},
{
"BriefDescription": "Average external Memory Bandwidth Use for reads and writes [GB / sec]",
"MetricExpr": "64 * ( arb@event\\=0x81\\,umask\\=0x1@ + arb@event\\=0x84\\,umask\\=0x1@ ) / 1000000 / duration_time / 1000",
"MetricGroup": "Memory_BW",
"MetricName": "DRAM_BW_Use"
},
{
"BriefDescription": "C3 residency percent per core",
"MetricExpr": "(cstate_core@c3\\-residency@ / msr@tsc@) * 100",
"MetricGroup": "Power",
"MetricName": "C3_Core_Residency"
},
{
"BriefDescription": "C6 residency percent per core",
"MetricExpr": "(cstate_core@c6\\-residency@ / msr@tsc@) * 100",
"MetricGroup": "Power",
"MetricName": "C6_Core_Residency"
},
{
"BriefDescription": "C7 residency percent per core",
"MetricExpr": "(cstate_core@c7\\-residency@ / msr@tsc@) * 100",
"MetricGroup": "Power",
"MetricName": "C7_Core_Residency"
},
{
"BriefDescription": "C2 residency percent per package",
"MetricExpr": "(cstate_pkg@c2\\-residency@ / msr@tsc@) * 100",
"MetricGroup": "Power",
"MetricName": "C2_Pkg_Residency"
},
{
"BriefDescription": "C3 residency percent per package",
"MetricExpr": "(cstate_pkg@c3\\-residency@ / msr@tsc@) * 100",
"MetricGroup": "Power",
"MetricName": "C3_Pkg_Residency"
},
{
"BriefDescription": "C6 residency percent per package",
"MetricExpr": "(cstate_pkg@c6\\-residency@ / msr@tsc@) * 100",
"MetricGroup": "Power",
"MetricName": "C6_Pkg_Residency"
},
{
"BriefDescription": "C7 residency percent per package",
"MetricExpr": "(cstate_pkg@c7\\-residency@ / msr@tsc@) * 100",
"MetricGroup": "Power",
"MetricName": "C7_Pkg_Residency"
}
]
| {
"pile_set_name": "Github"
} |
#!/bin/sh
DOCROOT=../../objc2swift-gh-pages/doc
if [ ! -e "${DOCROOT}" ] ; then
echo ${DOCROOT} does not exists.
exit 1
fi
for F in *.spec ; do
echo $F
./spec2doc.js $F -o ${DOCROOT} ${F%.spec}.html
done
| {
"pile_set_name": "Github"
} |
using System.Collections.Generic;
namespace Nimbus.Tests.Integration.TestScenarioGeneration.ScenarioComposition
{
public interface IScenarioFilter
{
IEnumerable<IConfigurationScenario<T>> Filter<T>(IEnumerable<IConfigurationScenario<T>> scenarios);
}
} | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<!-- Automatically generated file. Do not edit. -->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Impostare il punto zero relativo</title>
<link rel="stylesheet" type="text/css" href="../../../../style.css" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" /></head>
<body style="font-family:Arial, Helvetica, sans-serif">
<p style="text-align:right;"><a href="/doc/qcad/latest/reference/pt/index.php?page=scripts/Snap/SetRelativeZero/doc/SetRelativeZero">      </a></p>
<p style="font-style: italic;">Esta é uma tradução automática.</p>
<div class="nobreak">
<h2>Impostare il punto zero relativo</h2>
<p class="toolinfo">
<b>Barra de Ferramenta / Ícone:</b>
<br /><img src="../../doc/Snap.png" width="40" height="40" />
   
<img src="../doc/SetRelativeZero.png" width="40" height="40" />
   
<br/>
<b>Menu:</b> <font face="courier new">Snap > Impostare il punto zero relativo</font>
<br /><b>Atalho:</b> <font face="courier new">R, Z</font>
<br /><b>Comandos:</b> <font face="courier new">setrelativezero | rz</font>
</p>
</div>
<h3>Descrição</h3>
<p>Permite definir uma nova localização para o ponto zero relativo.</p>
<h3>Utilização</h3>
<ul>
<li>Clique na nova localização do ponto zero relativo.</li>
</ul>
</body>
</html>
| {
"pile_set_name": "Github"
} |
/*
* Licensed to GraphHopper GmbH under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper GmbH licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.graphhopper.jsprit.core.algorithm.recreate;
import com.graphhopper.jsprit.core.algorithm.state.StateManager;
import com.graphhopper.jsprit.core.problem.AbstractActivity;
import com.graphhopper.jsprit.core.problem.JobActivityFactory;
import com.graphhopper.jsprit.core.problem.Location;
import com.graphhopper.jsprit.core.problem.VehicleRoutingProblem;
import com.graphhopper.jsprit.core.problem.constraint.ConstraintManager;
import com.graphhopper.jsprit.core.problem.cost.AbstractForwardVehicleRoutingTransportCosts;
import com.graphhopper.jsprit.core.problem.cost.VehicleRoutingActivityCosts;
import com.graphhopper.jsprit.core.problem.cost.VehicleRoutingTransportCosts;
import com.graphhopper.jsprit.core.problem.driver.Driver;
import com.graphhopper.jsprit.core.problem.driver.DriverImpl;
import com.graphhopper.jsprit.core.problem.job.Job;
import com.graphhopper.jsprit.core.problem.job.Service;
import com.graphhopper.jsprit.core.problem.misc.JobInsertionContext;
import com.graphhopper.jsprit.core.problem.solution.route.VehicleRoute;
import com.graphhopper.jsprit.core.problem.solution.route.activity.TimeWindow;
import com.graphhopper.jsprit.core.problem.vehicle.Vehicle;
import com.graphhopper.jsprit.core.problem.vehicle.VehicleImpl;
import com.graphhopper.jsprit.core.problem.vehicle.VehicleType;
import com.graphhopper.jsprit.core.problem.vehicle.VehicleTypeImpl;
import com.graphhopper.jsprit.core.util.Coordinate;
import com.graphhopper.jsprit.core.util.EuclideanDistanceCalculator;
import com.graphhopper.jsprit.core.util.Locations;
import com.graphhopper.jsprit.core.util.ManhattanDistanceCalculator;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
public class TestCalculatesServiceInsertion {
ServiceInsertionCalculator serviceInsertion;
VehicleRoutingTransportCosts costs;
VehicleImpl vehicle;
VehicleImpl newVehicle;
private Service first;
private Service third;
private Service second;
private StateManager states;
private DriverImpl.NoDriver driver;
private VehicleRoutingProblem vrp;
@Before
public void setup() {
VehicleType t1 = VehicleTypeImpl.Builder.newInstance("t1").addCapacityDimension(0, 1000).setCostPerDistance(1.0).build();
vehicle = VehicleImpl.Builder.newInstance("vehicle").setLatestArrival(100.0).setStartLocation(Location.newInstance("0,0")).setType(t1).build();
VehicleType t2 = VehicleTypeImpl.Builder.newInstance("t2").addCapacityDimension(0, 1000).setCostPerDistance(2.0).build();
newVehicle = VehicleImpl.Builder.newInstance("newVehicle").setLatestArrival(100.0).setStartLocation(Location.newInstance("0,0")).setType(t2).build();
driver = DriverImpl.noDriver();
final Locations locations = new Locations() {
@Override
public Coordinate getCoord(String id) {
//assume: locationId="x,y"
String[] splitted = id.split(",");
return Coordinate.newInstance(Double.parseDouble(splitted[0]),
Double.parseDouble(splitted[1]));
}
};
costs = new AbstractForwardVehicleRoutingTransportCosts() {
@Override
public double getDistance(Location from, Location to, double departureTime, Vehicle vehicle) {
return ManhattanDistanceCalculator.calculateDistance(locations.getCoord(from.getId()), locations.getCoord(to.getId()));
}
@Override
public double getTransportTime(Location from, Location to, double departureTime, Driver driver, Vehicle vehicle) {
return ManhattanDistanceCalculator.calculateDistance(locations.getCoord(from.getId()), locations.getCoord(to.getId()));
}
@Override
public double getTransportCost(Location from, Location to, double departureTime, Driver driver, Vehicle vehicle) {
return vehicle.getType().getVehicleCostParams().perDistanceUnit * ManhattanDistanceCalculator.calculateDistance(locations.getCoord(from.getId()), locations.getCoord(to.getId()));
}
};
first = Service.Builder.newInstance("1").addSizeDimension(0, 0).setLocation(Location.newInstance("0,10")).setTimeWindow(TimeWindow.newInstance(0.0, 100.0)).build();
second = Service.Builder.newInstance("2").addSizeDimension(0, 0).setLocation(Location.newInstance("10,10")).setTimeWindow(TimeWindow.newInstance(0.0, 100.0)).build();
third = Service.Builder.newInstance("3").addSizeDimension(0, 0).setLocation(Location.newInstance("10,0")).setTimeWindow(TimeWindow.newInstance(0.0, 100.0)).build();
Collection<Job> jobs = new ArrayList<Job>();
jobs.add(first);
jobs.add(third);
jobs.add(second);
vrp = VehicleRoutingProblem.Builder.newInstance().addAllJobs(jobs)
.addVehicle(vehicle).setRoutingCost(costs).build();
states = new StateManager(vrp);
states.updateLoadStates();
states.updateTimeWindowStates();
ConstraintManager cManager = new ConstraintManager(vrp, states);
cManager.addLoadConstraint();
cManager.addTimeWindowConstraint();
VehicleRoutingActivityCosts actCosts = mock(VehicleRoutingActivityCosts.class);
serviceInsertion = new ServiceInsertionCalculator(costs, vrp.getActivityCosts(), new LocalActivityInsertionCostsCalculator(costs, actCosts, states), cManager, new JobActivityFactory() {
@Override
public List<AbstractActivity> createActivities(Job job) {
return vrp.copyAndGetActivities(job);
}
});
}
@Test
public void whenInsertingTheFirstJobInAnEmptyTourWithVehicle_itCalculatesMarginalCostChanges() {
VehicleRoute route = VehicleRoute.Builder.newInstance(vehicle, driver).build();
states.informInsertionStarts(Arrays.asList(route), null);
InsertionData iData = serviceInsertion.getInsertionData(route, first, vehicle, vehicle.getEarliestDeparture(), null, Double.MAX_VALUE);
assertEquals(20.0, iData.getInsertionCost(), 0.2);
assertEquals(0, iData.getDeliveryInsertionIndex());
}
@Test
public void whenInsertingTheSecondJobInAnNonEmptyTourWithVehicle_itCalculatesMarginalCostChanges() {
VehicleRoute route = VehicleRoute.Builder.newInstance(vehicle, driver).setJobActivityFactory(vrp.getJobActivityFactory()).addService(first).build();
states.informInsertionStarts(Arrays.asList(route), null);
InsertionData iData = serviceInsertion.getInsertionData(route, third, vehicle, vehicle.getEarliestDeparture(), null, Double.MAX_VALUE);
assertEquals(20.0, iData.getInsertionCost(), 0.2);
assertEquals(0, iData.getDeliveryInsertionIndex());
}
@Test
public void whenInsertingThirdJobWithVehicle_itCalculatesMarginalCostChanges() {
VehicleRoute route = VehicleRoute.Builder.newInstance(vehicle, driver).setJobActivityFactory(vrp.getJobActivityFactory()).addService(first).addService(third).build();
states.informInsertionStarts(Arrays.asList(route), null);
InsertionData iData = serviceInsertion.getInsertionData(route, second, vehicle, vehicle.getEarliestDeparture(), null, Double.MAX_VALUE);
assertEquals(0.0, iData.getInsertionCost(), 0.2);
assertEquals(1, iData.getDeliveryInsertionIndex());
}
@Test
public void whenInsertingThirdJobWithNewVehicle_itCalculatesMarginalCostChanges() {
VehicleRoute route = VehicleRoute.Builder.newInstance(vehicle, driver).setJobActivityFactory(vrp.getJobActivityFactory()).addService(first).addService(third).build();
states.informInsertionStarts(Arrays.asList(route), null);
InsertionData iData = serviceInsertion.getInsertionData(route, second, newVehicle, newVehicle.getEarliestDeparture(), null, Double.MAX_VALUE);
assertEquals(40.0, iData.getInsertionCost(), 0.2);
assertEquals(1, iData.getDeliveryInsertionIndex());
}
@Test
public void whenInsertingASecondJobWithAVehicle_itCalculatesLocalMarginalCostChanges() {
VehicleRoute route = VehicleRoute.Builder.newInstance(vehicle, driver).setJobActivityFactory(vrp.getJobActivityFactory()).addService(first).addService(second).build();
states.informInsertionStarts(Arrays.asList(route), null);
InsertionData iData = serviceInsertion.getInsertionData(route, third, vehicle, vehicle.getEarliestDeparture(), null, Double.MAX_VALUE);
assertEquals(0.0, iData.getInsertionCost(), 0.2);
assertEquals(2, iData.getDeliveryInsertionIndex());
}
@Test
public void whenInsertingASecondJobWithANewVehicle_itCalculatesLocalMarginalCostChanges() {
VehicleRoute route = VehicleRoute.Builder.newInstance(vehicle, driver).setJobActivityFactory(vrp.getJobActivityFactory()).addService(first).addService(second).build();
states.informInsertionStarts(Arrays.asList(route), null);
InsertionData iData = serviceInsertion.getInsertionData(route, third, newVehicle, newVehicle.getEarliestDeparture(), null, Double.MAX_VALUE);
assertEquals(50.0, iData.getInsertionCost(), 0.2);
assertEquals(2, iData.getDeliveryInsertionIndex());
}
@Test
public void whenInsertingJobAndCurrRouteIsEmpty_accessEggressCalcShouldReturnZero() {
VehicleRoute route = VehicleRoute.Builder.newInstance(VehicleImpl.createNoVehicle(), DriverImpl.noDriver()).build();
AdditionalAccessEgressCalculator accessEgressCalc = new AdditionalAccessEgressCalculator(costs);
Job job = Service.Builder.newInstance("1").addSizeDimension(0, 0).setLocation(Location.newInstance("1")).setTimeWindow(TimeWindow.newInstance(0.0, 100.0)).build();
JobInsertionContext iContex = new JobInsertionContext(route, job, newVehicle, mock(Driver.class), 0.0);
assertEquals(0.0, accessEgressCalc.getCosts(iContex), 0.01);
}
@Test
public void whenInsertingJobAndCurrRouteAndVehicleHaveTheSameLocation_accessEggressCalcShouldReturnZero() {
VehicleRoute route = VehicleRoute.Builder.newInstance(newVehicle, DriverImpl.noDriver())
.addService(first)
.build();
AdditionalAccessEgressCalculator accessEgressCalc = new AdditionalAccessEgressCalculator(costs);
JobInsertionContext iContex = new JobInsertionContext(route, first, newVehicle, mock(Driver.class), 0.0);
assertEquals(0.0, accessEgressCalc.getCosts(iContex), 0.01);
}
@Test
public void whenInsertingJobAndCurrRouteAndNewVehicleHaveDifferentLocations_accessEggressCostsMustBeCorrect() {
final Map<String, Coordinate> coords = new HashMap<String, Coordinate>();
coords.put("oldV", Coordinate.newInstance(1, 0));
coords.put("newV", Coordinate.newInstance(5, 0));
coords.put("service", Coordinate.newInstance(0, 0));
AbstractForwardVehicleRoutingTransportCosts routingCosts = new AbstractForwardVehicleRoutingTransportCosts() {
@Override
public double getDistance(Location from, Location to, double departureTime, Vehicle vehicle) {
return EuclideanDistanceCalculator.calculateDistance(coords.get(from.getId()), coords.get(to.getId()));
}
@Override
public double getTransportTime(Location from, Location to, double departureTime, Driver driver, Vehicle vehicle) {
return getTransportCost(from, to, departureTime, driver, vehicle);
}
@Override
public double getTransportCost(Location from, Location to, double departureTime, Driver driver, Vehicle vehicle) {
return EuclideanDistanceCalculator.calculateDistance(coords.get(from.getId()), coords.get(to.getId()));
}
};
Vehicle oldVehicle = VehicleImpl.Builder.newInstance("oldV").setStartLocation(Location.newInstance("oldV")).build();
VehicleRoute route = VehicleRoute.Builder.newInstance(oldVehicle, DriverImpl.noDriver())
.addService(Service.Builder.newInstance("service").addSizeDimension(0, 0).setLocation(Location.newInstance("service")).build())
.build();
Vehicle newVehicle = VehicleImpl.Builder.newInstance("newV").setStartLocation(Location.newInstance("newV")).build();
AdditionalAccessEgressCalculator accessEgressCalc = new AdditionalAccessEgressCalculator(routingCosts);
Job job = Service.Builder.newInstance("service2").addSizeDimension(0, 0).setLocation(Location.newInstance("service")).build();
JobInsertionContext iContex = new JobInsertionContext(route, job, newVehicle, mock(Driver.class), 0.0);
assertEquals(8.0, accessEgressCalc.getCosts(iContex), 0.01);
}
}
| {
"pile_set_name": "Github"
} |
//==========================================================================
// CNEDNETWORKBUILDER.H - part of
//
// OMNeT++/OMNEST
// Discrete System Simulation in C++
//
//==========================================================================
/*--------------------------------------------------------------*
Copyright (C) 2002-2017 Andras Varga
Copyright (C) 2006-2017 OpenSim Ltd.
This file is distributed WITHOUT ANY WARRANTY. See the file
`terms' for details on this and other legal matters.
*--------------------------------------------------------------*/
#ifndef __OMNETPP_CNETWORKBUILDER_H
#define __OMNETPP_CNETWORKBUILDER_H
#include <string>
#include <map>
#include <vector>
#include "nedxml/nedelements.h"
#include "nedxml/nedresourcecache.h"
#include "omnetpp/globals.h"
#include "omnetpp/cpar.h"
#include "cneddeclaration.h"
#include "cnedloader.h"
namespace omnetpp {
using namespace omnetpp::nedxml;
class cModule;
class cGate;
class cChannel;
#define MAX_LOOP_NESTING 32
/**
* @brief Stateless object to assist in building the network, based on NED files.
*
* @ingroup NetworkBuilder
*/
class SIM_API cNedNetworkBuilder
{
protected:
class ComponentTypeNames : public NedResourceCache::INedTypeNames {
public:
virtual bool contains(const char *qname) const override {return componentTypes.getInstance()->lookup(qname)!=nullptr;}
virtual int size() const override {return componentTypes.getInstance()->size();}
virtual const char *get(int k) const override {return componentTypes.getInstance()->get(k)->getFullName();}
};
typedef cNedDeclaration::PatternData PatternData; // abbreviation
protected:
// the current NED declaration we're working with. Stored here to
// avoid having to pass it around as a parameter.
cNedDeclaration *currentDecl = nullptr;
// submodule pointers. This is an optimization because cModule::getSubmodule()
// is slow if there are very large submodule vectors.
typedef std::vector<cModule*> ModulePtrVector;
typedef std::map<std::string,ModulePtrVector> SubmodMap;
SubmodMap submodMap;
protected:
cModule *_submodule(cModule *parentmodp, const char *submodName, int idx=-1);
void addSubmodulesAndConnections(cModule *modp);
bool superTypeAllowsUnconnected(cNedDeclaration *decl) const;
void buildRecursively(cModule *modp, cNedDeclaration *decl);
std::string resolveComponentType(const NedLookupContext& context, const char *nedTypeName);
cModuleType *findAndCheckModuleType(const char *modtypename, cModule *modp, const char *submodName);
cModuleType *findAndCheckModuleTypeLike(const char *modTypeName, const char *likeType, cModule *modp, const char *submodName);
std::vector<std::string> findTypeWithInterface(const char *nedTypeName, const char *interfaceQName);
std::string getSubmoduleTypeName(cModule *modp, SubmoduleElement *submod, int index = -1);
bool getSubmoduleOrChannelTypeNameFromDeepAssignments(cModule *modp, const std::string& submodOrChannelKey, std::string& outTypeName, bool& outIsDefault);
void addSubmodule(cModule *modp, SubmoduleElement *submod);
void doAddParametersAndGatesTo(cComponent *component, cNedDeclaration *decl);
void doAssignParametersFromPatterns(cComponent *component, const std::string& prefix, const std::vector<PatternData>& patterns, bool isInSubcomponent, cComponent *evalContext);
void doAssignParameterFromPattern(cPar& par, ParamElement *patternNode, bool isInSubcomponent, cComponent *evalContext);
static cPar::Type translateParamType(int t);
static cGate::Type translateGateType(int t);
void doParams(cComponent *component, ParametersElement *paramsNode, bool isSubcomponent);
void doParam(cComponent *component, ParamElement *paramNode, bool isSubcomponent);
void doGates(cModule *component, GatesElement *gatesNode, bool isSubcomponent);
void doGate(cModule *component, GateElement *gateNode, bool isSubcomponent);
void doGateSizes(cModule *component, GatesElement *gatesNode, bool isSubcomponent);
void doGateSize(cModule *component, GateElement *gateNode, bool isSubcomponent);
void assignSubcomponentParams(cComponent *subcomponent, NedElement *subcomponentNode);
void setupSubmoduleGateVectors(cModule *submodule, NedElement *submoduleNode);
void addConnectionOrConnectionGroup(cModule *modp, NedElement *connOrConnGroup);
void doConnOrConnGroupBody(cModule *modp, NedElement *connOrConnGroup, NedElement *loopOrCondition);
void doLoopOrCondition(cModule *modp, NedElement *loopOrCondition);
void doAddConnOrConnGroup(cModule *modp, NedElement *connOrConnGroup);
void doAddConnection(cModule *modp, ConnectionElement *conn);
void doConnectGates(cModule *modp, cGate *srcg, cGate *destg, ConnectionElement *conn);
cGate *resolveGate(cModule *parentmodp, const char *modname, const ExprRef& modindexp,
const char *gatename, const ExprRef& gateindexp, int subg, bool isplusplus);
void resolveInoutGate(cModule *parentmodp, const char *modname, const ExprRef& modindexp,
const char *gatename, const ExprRef& gateindexp, bool isplusplus,
cGate *&gate1, cGate *&gate2);
cModule *resolveModuleForConnection(cModule *parentmodp, const char *modname, const ExprRef& modindexp);
std::string getChannelTypeName(cModule *modp, cGate *srcgate, ConnectionElement *conn, const char *channelName);
cChannel *createChannel(ConnectionElement *conn, cModule *parentmodp, cGate *srcgate);
cChannelType *findAndCheckChannelType(const char *channelTypeName, cModule *modp);
cChannelType *findAndCheckChannelTypeLike(const char *channelTypeName, const char *likeType, cModule *modp);
cDynamicExpression *getOrCreateExpression(const ExprRef& exprRef, bool inSubcomponentScope);
long evaluateAsLong(const ExprRef& exprRef, cComponent *contextComponent, bool inSubcomponentScope);
bool evaluateAsBool(const ExprRef& exprRef, cComponent *contextComponent, bool inSubcomponentScope);
std::string evaluateAsString(const ExprRef& exprRef, cComponent *contextComponent, bool inSubcomponentScope);
long evaluateAsLong(const ExprRef& exprRef, cExpression::Context *context, bool inSubcomponentScope);
bool evaluateAsBool(const ExprRef& exprRef, cExpression::Context *context, bool inSubcomponentScope);
std::string evaluateAsString(const ExprRef& exprRef, cExpression::Context *context, bool inSubcomponentScope);
bool getBooleanProperty(NedElement *componentNode, const char *name);
public:
/** Constructor */
cNedNetworkBuilder() {}
/**
* Adds parameters and gates from the given NED declaration. Gate vectors
* will be created with zero size, and a further call to setupGateVectors()
* will be needed once parameter values have been finalized. (This method is
* also used with channels, with the "gates" part being a no-op then.)
* Invoked from cDynamicModule.
*/
void addParametersAndGatesTo(cComponent *component, cNedDeclaration *decl);
/**
* Applies NED pattern (a.k.a. deep) parameter assignments to parameters of
* the component.
*/
void assignParametersFromPatterns(cComponent *component);
/**
* Sets gate vector sizes on the module, using the given NED declaration.
* This should be called AFTER all parameters have been set, because gate
* vector sizes may depend on parameter values. Invoked from cDynamicModule.
*/
void setupGateVectors(cModule *module, cNedDeclaration *decl);
/**
* Builds submodules and internal connections, based on the info in the
* passed NedElement tree. Invoked from cDynamicModule.
*/
void buildInside(cModule *module, cNedDeclaration *decl);
};
} // namespace omnetpp
#endif
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{477CDA26-9A44-4BC6-8B66-3B869139BF7B}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>crypter</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>Use</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<None Include="..\..\..\..\..\Downloads\crypter.ico" />
<None Include="..\..\..\..\..\Downloads\small.ico" />
<None Include="ReadMe.txt" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="crypter.h" />
<ClInclude Include="Resource.h" />
<ClInclude Include="stdafx.h" />
<ClInclude Include="targetver.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="crypter.cpp" />
<ClCompile Include="stdafx.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="crypter.rc" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project> | {
"pile_set_name": "Github"
} |
---
title: Callouts and Lists
description: Composing callouts and lists.
skip_sitemap: true
---
1. Warning
{{< warning >}}
This is a warning
{{< /warning >}}
{{< warning >}}
This is a warning
with two paragraphs
{{< /warning >}}
{{< warning >}}
This is a warning
with two paragraphs
{{< text plain >}}
A nested text block
{{< /text >}}
{{< /warning >}}
1. Tip
{{< tip >}}
This is a tip
{{< /tip >}}
{{< tip >}}
This is a tip
with two paragraphs
{{< /tip >}}
1. Idea
{{< idea >}}
This is an idea
{{< /idea >}}
{{< idea >}}
This is an idea
with two paragraphs
{{< /idea >}}
1. Quote
{{< quote >}}
This is a quote
{{< /quote >}}
{{< quote >}}
This is a quote
with two paragraphs
{{< /quote >}}
| {
"pile_set_name": "Github"
} |
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $Workfile: $
// $Date: $
//
//-----------------------------------------------------------------------------
// $Log: $
//
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#include "basetempentity.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
//-----------------------------------------------------------------------------
// Purpose: Dispatches footprint decal tempentity
//-----------------------------------------------------------------------------
#define FOOTPRINT_DECAY_TIME 3.0f
class CTEFootprintDecal : public CBaseTempEntity
{
public:
DECLARE_CLASS( CTEFootprintDecal, CBaseTempEntity );
CTEFootprintDecal( const char *name );
virtual ~CTEFootprintDecal( void );
DECLARE_SERVERCLASS();
public:
CNetworkVector( m_vecOrigin );
CNetworkVector( m_vecDirection );
CNetworkVar( int, m_nEntity );
CNetworkVar( int, m_nIndex );
CNetworkVar( unsigned char, m_chMaterialType );
};
IMPLEMENT_SERVERCLASS_ST(CTEFootprintDecal, DT_TEFootprintDecal)
SendPropVector( SENDINFO(m_vecOrigin), -1, SPROP_COORD),
SendPropVector( SENDINFO(m_vecDirection), -1, SPROP_COORD),
SendPropInt( SENDINFO(m_nEntity), 11, SPROP_UNSIGNED ),
SendPropInt( SENDINFO(m_nIndex), 8, SPROP_UNSIGNED ),
SendPropInt( SENDINFO(m_chMaterialType), 8, SPROP_UNSIGNED ),
END_SEND_TABLE()
// Singleton to fire TEFootprintDecal objects
static CTEFootprintDecal g_TEFootprintDecal( "Footprint Decal" );
//-----------------------------------------------------------------------------
// constructor, destructor
//-----------------------------------------------------------------------------
CTEFootprintDecal::CTEFootprintDecal( const char *name ) :
CBaseTempEntity( name )
{
m_vecOrigin.Init();
m_nEntity = 0;
m_nIndex = 0;
m_chMaterialType = 'C';
}
CTEFootprintDecal::~CTEFootprintDecal( void )
{
}
//-----------------------------------------------------------------------------
// places a footprint decal
//-----------------------------------------------------------------------------
void TE_FootprintDecal( IRecipientFilter& filter, float delay,
const Vector *origin, const Vector *right, int entity, int index,
unsigned char materialType )
{
Assert( origin );
g_TEFootprintDecal.m_vecOrigin = *origin;
g_TEFootprintDecal.m_vecDirection = *right;
g_TEFootprintDecal.m_nEntity = entity;
g_TEFootprintDecal.m_nIndex = index;
g_TEFootprintDecal.m_chMaterialType = materialType;
VectorNormalize(g_TEFootprintDecal.m_vecDirection.GetForModify());
// Send it over the wire
g_TEFootprintDecal.Create( filter, delay );
} | {
"pile_set_name": "Github"
} |
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2015 Gael Guennebaud <[email protected]>
// Copyright (C) 2007-2009 Benoit Jacob <[email protected]>
//
// 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/.
#ifndef EIGEN_CONSTANTS_H
#define EIGEN_CONSTANTS_H
namespace Eigen {
/** This value means that a positive quantity (e.g., a size) is not known at compile-time, and that instead the value is
* stored in some runtime variable.
*
* Changing the value of Dynamic breaks the ABI, as Dynamic is often used as a template parameter for Matrix.
*/
const int Dynamic = -1;
/** This value means that a signed quantity (e.g., a signed index) is not known at compile-time, and that instead its value
* has to be specified at runtime.
*/
const int DynamicIndex = 0xffffff;
/** This value means +Infinity; it is currently used only as the p parameter to MatrixBase::lpNorm<int>().
* The value Infinity there means the L-infinity norm.
*/
const int Infinity = -1;
/** This value means that the cost to evaluate an expression coefficient is either very expensive or
* cannot be known at compile time.
*
* This value has to be positive to (1) simplify cost computation, and (2) allow to distinguish between a very expensive and very very expensive expressions.
* It thus must also be large enough to make sure unrolling won't happen and that sub expressions will be evaluated, but not too large to avoid overflow.
*/
const int HugeCost = 10000;
/** \defgroup flags Flags
* \ingroup Core_Module
*
* These are the possible bits which can be OR'ed to constitute the flags of a matrix or
* expression.
*
* It is important to note that these flags are a purely compile-time notion. They are a compile-time property of
* an expression type, implemented as enum's. They are not stored in memory at runtime, and they do not incur any
* runtime overhead.
*
* \sa MatrixBase::Flags
*/
/** \ingroup flags
*
* for a matrix, this means that the storage order is row-major.
* If this bit is not set, the storage order is column-major.
* For an expression, this determines the storage order of
* the matrix created by evaluation of that expression.
* \sa \ref TopicStorageOrders */
const unsigned int RowMajorBit = 0x1;
/** \ingroup flags
* means the expression should be evaluated by the calling expression */
const unsigned int EvalBeforeNestingBit = 0x2;
/** \ingroup flags
* \deprecated
* means the expression should be evaluated before any assignment */
const unsigned int EvalBeforeAssigningBit = 0x4; // FIXME deprecated
/** \ingroup flags
*
* Short version: means the expression might be vectorized
*
* Long version: means that the coefficients can be handled by packets
* and start at a memory location whose alignment meets the requirements
* of the present CPU architecture for optimized packet access. In the fixed-size
* case, there is the additional condition that it be possible to access all the
* coefficients by packets (this implies the requirement that the size be a multiple of 16 bytes,
* and that any nontrivial strides don't break the alignment). In the dynamic-size case,
* there is no such condition on the total size and strides, so it might not be possible to access
* all coeffs by packets.
*
* \note This bit can be set regardless of whether vectorization is actually enabled.
* To check for actual vectorizability, see \a ActualPacketAccessBit.
*/
const unsigned int PacketAccessBit = 0x8;
#ifdef EIGEN_VECTORIZE
/** \ingroup flags
*
* If vectorization is enabled (EIGEN_VECTORIZE is defined) this constant
* is set to the value \a PacketAccessBit.
*
* If vectorization is not enabled (EIGEN_VECTORIZE is not defined) this constant
* is set to the value 0.
*/
const unsigned int ActualPacketAccessBit = PacketAccessBit;
#else
const unsigned int ActualPacketAccessBit = 0x0;
#endif
/** \ingroup flags
*
* Short version: means the expression can be seen as 1D vector.
*
* Long version: means that one can access the coefficients
* of this expression by coeff(int), and coeffRef(int) in the case of a lvalue expression. These
* index-based access methods are guaranteed
* to not have to do any runtime computation of a (row, col)-pair from the index, so that it
* is guaranteed that whenever it is available, index-based access is at least as fast as
* (row,col)-based access. Expressions for which that isn't possible don't have the LinearAccessBit.
*
* If both PacketAccessBit and LinearAccessBit are set, then the
* packets of this expression can be accessed by packet(int), and writePacket(int) in the case of a
* lvalue expression.
*
* Typically, all vector expressions have the LinearAccessBit, but there is one exception:
* Product expressions don't have it, because it would be troublesome for vectorization, even when the
* Product is a vector expression. Thus, vector Product expressions allow index-based coefficient access but
* not index-based packet access, so they don't have the LinearAccessBit.
*/
const unsigned int LinearAccessBit = 0x10;
/** \ingroup flags
*
* Means the expression has a coeffRef() method, i.e. is writable as its individual coefficients are directly addressable.
* This rules out read-only expressions.
*
* Note that DirectAccessBit and LvalueBit are mutually orthogonal, as there are examples of expression having one but note
* the other:
* \li writable expressions that don't have a very simple memory layout as a strided array, have LvalueBit but not DirectAccessBit
* \li Map-to-const expressions, for example Map<const Matrix>, have DirectAccessBit but not LvalueBit
*
* Expressions having LvalueBit also have their coeff() method returning a const reference instead of returning a new value.
*/
const unsigned int LvalueBit = 0x20;
/** \ingroup flags
*
* Means that the underlying array of coefficients can be directly accessed as a plain strided array. The memory layout
* of the array of coefficients must be exactly the natural one suggested by rows(), cols(),
* outerStride(), innerStride(), and the RowMajorBit. This rules out expressions such as Diagonal, whose coefficients,
* though referencable, do not have such a regular memory layout.
*
* See the comment on LvalueBit for an explanation of how LvalueBit and DirectAccessBit are mutually orthogonal.
*/
const unsigned int DirectAccessBit = 0x40;
/** \deprecated \ingroup flags
*
* means the first coefficient packet is guaranteed to be aligned.
* An expression cannot has the AlignedBit without the PacketAccessBit flag.
* In other words, this means we are allow to perform an aligned packet access to the first element regardless
* of the expression kind:
* \code
* expression.packet<Aligned>(0);
* \endcode
*/
const unsigned int AlignedBit = 0x80;
const unsigned int NestByRefBit = 0x100;
/** \ingroup flags
*
* for an expression, this means that the storage order
* can be either row-major or column-major.
* The precise choice will be decided at evaluation time or when
* combined with other expressions.
* \sa \ref RowMajorBit, \ref TopicStorageOrders */
const unsigned int NoPreferredStorageOrderBit = 0x200;
/** \ingroup flags
*
* Means that the underlying coefficients can be accessed through pointers to the sparse (un)compressed storage format,
* that is, the expression provides:
* \code
inline const Scalar* valuePtr() const;
inline const Index* innerIndexPtr() const;
inline const Index* outerIndexPtr() const;
inline const Index* innerNonZeroPtr() const;
\endcode
*/
const unsigned int CompressedAccessBit = 0x400;
// list of flags that are inherited by default
const unsigned int HereditaryBits = RowMajorBit
| EvalBeforeNestingBit
| EvalBeforeAssigningBit;
/** \defgroup enums Enumerations
* \ingroup Core_Module
*
* Various enumerations used in %Eigen. Many of these are used as template parameters.
*/
/** \ingroup enums
* Enum containing possible values for the \c Mode or \c UpLo parameter of
* MatrixBase::selfadjointView() and MatrixBase::triangularView(), and selfadjoint solvers. */
enum {
/** View matrix as a lower triangular matrix. */
Lower=0x1,
/** View matrix as an upper triangular matrix. */
Upper=0x2,
/** %Matrix has ones on the diagonal; to be used in combination with #Lower or #Upper. */
UnitDiag=0x4,
/** %Matrix has zeros on the diagonal; to be used in combination with #Lower or #Upper. */
ZeroDiag=0x8,
/** View matrix as a lower triangular matrix with ones on the diagonal. */
UnitLower=UnitDiag|Lower,
/** View matrix as an upper triangular matrix with ones on the diagonal. */
UnitUpper=UnitDiag|Upper,
/** View matrix as a lower triangular matrix with zeros on the diagonal. */
StrictlyLower=ZeroDiag|Lower,
/** View matrix as an upper triangular matrix with zeros on the diagonal. */
StrictlyUpper=ZeroDiag|Upper,
/** Used in BandMatrix and SelfAdjointView to indicate that the matrix is self-adjoint. */
SelfAdjoint=0x10,
/** Used to support symmetric, non-selfadjoint, complex matrices. */
Symmetric=0x20
};
/** \ingroup enums
* Enum for indicating whether a buffer is aligned or not. */
enum {
Unaligned=0, /**< Data pointer has no specific alignment. */
Aligned8=8, /**< Data pointer is aligned on a 8 bytes boundary. */
Aligned16=16, /**< Data pointer is aligned on a 16 bytes boundary. */
Aligned32=32, /**< Data pointer is aligned on a 32 bytes boundary. */
Aligned64=64, /**< Data pointer is aligned on a 64 bytes boundary. */
Aligned128=128, /**< Data pointer is aligned on a 128 bytes boundary. */
AlignedMask=255,
Aligned=16, /**< \deprecated Synonym for Aligned16. */
#if EIGEN_MAX_ALIGN_BYTES==128
AlignedMax = Aligned128
#elif EIGEN_MAX_ALIGN_BYTES==64
AlignedMax = Aligned64
#elif EIGEN_MAX_ALIGN_BYTES==32
AlignedMax = Aligned32
#elif EIGEN_MAX_ALIGN_BYTES==16
AlignedMax = Aligned16
#elif EIGEN_MAX_ALIGN_BYTES==8
AlignedMax = Aligned8
#elif EIGEN_MAX_ALIGN_BYTES==0
AlignedMax = Unaligned
#else
#error Invalid value for EIGEN_MAX_ALIGN_BYTES
#endif
};
/** \ingroup enums
* Enum used by DenseBase::corner() in Eigen2 compatibility mode. */
// FIXME after the corner() API change, this was not needed anymore, except by AlignedBox
// TODO: find out what to do with that. Adapt the AlignedBox API ?
enum CornerType { TopLeft, TopRight, BottomLeft, BottomRight };
/** \ingroup enums
* Enum containing possible values for the \p Direction parameter of
* Reverse, PartialReduxExpr and VectorwiseOp. */
enum DirectionType {
/** For Reverse, all columns are reversed;
* for PartialReduxExpr and VectorwiseOp, act on columns. */
Vertical,
/** For Reverse, all rows are reversed;
* for PartialReduxExpr and VectorwiseOp, act on rows. */
Horizontal,
/** For Reverse, both rows and columns are reversed;
* not used for PartialReduxExpr and VectorwiseOp. */
BothDirections
};
/** \internal \ingroup enums
* Enum to specify how to traverse the entries of a matrix. */
enum {
/** \internal Default traversal, no vectorization, no index-based access */
DefaultTraversal,
/** \internal No vectorization, use index-based access to have only one for loop instead of 2 nested loops */
LinearTraversal,
/** \internal Equivalent to a slice vectorization for fixed-size matrices having good alignment
* and good size */
InnerVectorizedTraversal,
/** \internal Vectorization path using a single loop plus scalar loops for the
* unaligned boundaries */
LinearVectorizedTraversal,
/** \internal Generic vectorization path using one vectorized loop per row/column with some
* scalar loops to handle the unaligned boundaries */
SliceVectorizedTraversal,
/** \internal Special case to properly handle incompatible scalar types or other defecting cases*/
InvalidTraversal,
/** \internal Evaluate all entries at once */
AllAtOnceTraversal
};
/** \internal \ingroup enums
* Enum to specify whether to unroll loops when traversing over the entries of a matrix. */
enum {
/** \internal Do not unroll loops. */
NoUnrolling,
/** \internal Unroll only the inner loop, but not the outer loop. */
InnerUnrolling,
/** \internal Unroll both the inner and the outer loop. If there is only one loop,
* because linear traversal is used, then unroll that loop. */
CompleteUnrolling
};
/** \internal \ingroup enums
* Enum to specify whether to use the default (built-in) implementation or the specialization. */
enum {
Specialized,
BuiltIn
};
/** \ingroup enums
* Enum containing possible values for the \p _Options template parameter of
* Matrix, Array and BandMatrix. */
enum {
/** Storage order is column major (see \ref TopicStorageOrders). */
ColMajor = 0,
/** Storage order is row major (see \ref TopicStorageOrders). */
RowMajor = 0x1, // it is only a coincidence that this is equal to RowMajorBit -- don't rely on that
/** Align the matrix itself if it is vectorizable fixed-size */
AutoAlign = 0,
/** Don't require alignment for the matrix itself (the array of coefficients, if dynamically allocated, may still be requested to be aligned) */ // FIXME --- clarify the situation
DontAlign = 0x2
};
/** \ingroup enums
* Enum for specifying whether to apply or solve on the left or right. */
enum {
/** Apply transformation on the left. */
OnTheLeft = 1,
/** Apply transformation on the right. */
OnTheRight = 2
};
/* the following used to be written as:
*
* struct NoChange_t {};
* namespace {
* EIGEN_UNUSED NoChange_t NoChange;
* }
*
* on the ground that it feels dangerous to disambiguate overloaded functions on enum/integer types.
* However, this leads to "variable declared but never referenced" warnings on Intel Composer XE,
* and we do not know how to get rid of them (bug 450).
*/
enum NoChange_t { NoChange };
enum Sequential_t { Sequential };
enum Default_t { Default };
/** \internal \ingroup enums
* Used in AmbiVector. */
enum {
IsDense = 0,
IsSparse
};
/** \ingroup enums
* Used as template parameter in DenseCoeffBase and MapBase to indicate
* which accessors should be provided. */
enum AccessorLevels {
/** Read-only access via a member function. */
ReadOnlyAccessors,
/** Read/write access via member functions. */
WriteAccessors,
/** Direct read-only access to the coefficients. */
DirectAccessors,
/** Direct read/write access to the coefficients. */
DirectWriteAccessors
};
/** \ingroup enums
* Enum with options to give to various decompositions. */
enum DecompositionOptions {
/** \internal Not used (meant for LDLT?). */
Pivoting = 0x01,
/** \internal Not used (meant for LDLT?). */
NoPivoting = 0x02,
/** Used in JacobiSVD to indicate that the square matrix U is to be computed. */
ComputeFullU = 0x04,
/** Used in JacobiSVD to indicate that the thin matrix U is to be computed. */
ComputeThinU = 0x08,
/** Used in JacobiSVD to indicate that the square matrix V is to be computed. */
ComputeFullV = 0x10,
/** Used in JacobiSVD to indicate that the thin matrix V is to be computed. */
ComputeThinV = 0x20,
/** Used in SelfAdjointEigenSolver and GeneralizedSelfAdjointEigenSolver to specify
* that only the eigenvalues are to be computed and not the eigenvectors. */
EigenvaluesOnly = 0x40,
/** Used in SelfAdjointEigenSolver and GeneralizedSelfAdjointEigenSolver to specify
* that both the eigenvalues and the eigenvectors are to be computed. */
ComputeEigenvectors = 0x80,
/** \internal */
EigVecMask = EigenvaluesOnly | ComputeEigenvectors,
/** Used in GeneralizedSelfAdjointEigenSolver to indicate that it should
* solve the generalized eigenproblem \f$ Ax = \lambda B x \f$. */
Ax_lBx = 0x100,
/** Used in GeneralizedSelfAdjointEigenSolver to indicate that it should
* solve the generalized eigenproblem \f$ ABx = \lambda x \f$. */
ABx_lx = 0x200,
/** Used in GeneralizedSelfAdjointEigenSolver to indicate that it should
* solve the generalized eigenproblem \f$ BAx = \lambda x \f$. */
BAx_lx = 0x400,
/** \internal */
GenEigMask = Ax_lBx | ABx_lx | BAx_lx
};
/** \ingroup enums
* Possible values for the \p QRPreconditioner template parameter of JacobiSVD. */
enum QRPreconditioners {
/** Do not specify what is to be done if the SVD of a non-square matrix is asked for. */
NoQRPreconditioner,
/** Use a QR decomposition without pivoting as the first step. */
HouseholderQRPreconditioner,
/** Use a QR decomposition with column pivoting as the first step. */
ColPivHouseholderQRPreconditioner,
/** Use a QR decomposition with full pivoting as the first step. */
FullPivHouseholderQRPreconditioner
};
#ifdef Success
#error The preprocessor symbol 'Success' is defined, possibly by the X11 header file X.h
#endif
/** \ingroup enums
* Enum for reporting the status of a computation. */
enum ComputationInfo {
/** Computation was successful. */
Success = 0,
/** The provided data did not satisfy the prerequisites. */
NumericalIssue = 1,
/** Iterative procedure did not converge. */
NoConvergence = 2,
/** The inputs are invalid, or the algorithm has been improperly called.
* When assertions are enabled, such errors trigger an assert. */
InvalidInput = 3
};
/** \ingroup enums
* Enum used to specify how a particular transformation is stored in a matrix.
* \sa Transform, Hyperplane::transform(). */
enum TransformTraits {
/** Transformation is an isometry. */
Isometry = 0x1,
/** Transformation is an affine transformation stored as a (Dim+1)^2 matrix whose last row is
* assumed to be [0 ... 0 1]. */
Affine = 0x2,
/** Transformation is an affine transformation stored as a (Dim) x (Dim+1) matrix. */
AffineCompact = 0x10 | Affine,
/** Transformation is a general projective transformation stored as a (Dim+1)^2 matrix. */
Projective = 0x20
};
/** \internal \ingroup enums
* Enum used to choose between implementation depending on the computer architecture. */
namespace Architecture
{
enum Type {
Generic = 0x0,
SSE = 0x1,
AltiVec = 0x2,
VSX = 0x3,
NEON = 0x4,
#if defined EIGEN_VECTORIZE_SSE
Target = SSE
#elif defined EIGEN_VECTORIZE_ALTIVEC
Target = AltiVec
#elif defined EIGEN_VECTORIZE_VSX
Target = VSX
#elif defined EIGEN_VECTORIZE_NEON
Target = NEON
#else
Target = Generic
#endif
};
}
/** \internal \ingroup enums
* Enum used as template parameter in Product and product evalautors. */
enum { DefaultProduct=0, LazyProduct, AliasFreeProduct, CoeffBasedProductMode, LazyCoeffBasedProductMode, OuterProduct, InnerProduct, GemvProduct, GemmProduct };
/** \internal \ingroup enums
* Enum used in experimental parallel implementation. */
enum Action {GetAction, SetAction};
/** The type used to identify a dense storage. */
struct Dense {};
/** The type used to identify a general sparse storage. */
struct Sparse {};
/** The type used to identify a general solver (foctored) storage. */
struct SolverStorage {};
/** The type used to identify a permutation storage. */
struct PermutationStorage {};
/** The type used to identify a permutation storage. */
struct TranspositionsStorage {};
/** The type used to identify a matrix expression */
struct MatrixXpr {};
/** The type used to identify an array expression */
struct ArrayXpr {};
// An evaluator must define its shape. By default, it can be one of the following:
struct DenseShape { static std::string debugName() { return "DenseShape"; } };
struct SolverShape { static std::string debugName() { return "SolverShape"; } };
struct HomogeneousShape { static std::string debugName() { return "HomogeneousShape"; } };
struct DiagonalShape { static std::string debugName() { return "DiagonalShape"; } };
struct BandShape { static std::string debugName() { return "BandShape"; } };
struct TriangularShape { static std::string debugName() { return "TriangularShape"; } };
struct SelfAdjointShape { static std::string debugName() { return "SelfAdjointShape"; } };
struct PermutationShape { static std::string debugName() { return "PermutationShape"; } };
struct TranspositionsShape { static std::string debugName() { return "TranspositionsShape"; } };
struct SparseShape { static std::string debugName() { return "SparseShape"; } };
namespace internal {
// random access iterators based on coeff*() accessors.
struct IndexBased {};
// evaluator based on iterators to access coefficients.
struct IteratorBased {};
/** \internal
* Constants for comparison functors
*/
enum ComparisonName {
cmp_EQ = 0,
cmp_LT = 1,
cmp_LE = 2,
cmp_UNORD = 3,
cmp_NEQ = 4,
cmp_GT = 5,
cmp_GE = 6
};
} // end namespace internal
} // end namespace Eigen
#endif // EIGEN_CONSTANTS_H
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.