text
stringlengths
2
100k
meta
dict
// Copyright 2011 the V8 project authors. 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 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. // Flags: --allow-natives-syntax var a = new Array(10); function test_load_set_smi(a) { return a[0] = a[0] = 1; } test_load_set_smi(a); test_load_set_smi(a); test_load_set_smi(123); function test_load_set_smi_2(a) { return a[0] = a[0] = 1; } test_load_set_smi_2(a); %OptimizeFunctionOnNextCall(test_load_set_smi_2); test_load_set_smi_2(a); test_load_set_smi_2(0); %DeoptimizeFunction(test_load_set_smi_2); %ClearFunctionFeedback(test_load_set_smi_2); var b = new Object(); function test_load_set_smi_3(b) { return b[0] = b[0] = 1; } test_load_set_smi_3(b); test_load_set_smi_3(b); test_load_set_smi_3(123); function test_load_set_smi_4(b) { return b[0] = b[0] = 1; } test_load_set_smi_4(b); %OptimizeFunctionOnNextCall(test_load_set_smi_4); test_load_set_smi_4(b); test_load_set_smi_4(0); %DeoptimizeFunction(test_load_set_smi_4); %ClearFunctionFeedback(test_load_set_smi_4);
{ "pile_set_name": "Github" }
msgid "" msgstr "" "Project-Id-Version: plugin-update-checker\n" "POT-Creation-Date: 2017-11-24 17:02+0200\n" "PO-Revision-Date: 2020-03-21 15:14-0400\n" "Language-Team: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "X-Generator: Poedit 2.3\n" "X-Poedit-Basepath: ..\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" "X-Poedit-SourceCharset: UTF-8\n" "X-Poedit-KeywordsList: __;_e;_x:1,2c;_x\n" "Last-Translator: \n" "Language: es_ES\n" "X-Poedit-SearchPath-0: .\n" #: Puc/v4p3/Plugin/UpdateChecker.php:395 msgid "Check for updates" msgstr "Comprobar si hay actualizaciones" #: Puc/v4p3/Plugin/UpdateChecker.php:548 #, php-format msgctxt "the plugin title" msgid "The %s plugin is up to date." msgstr "El plugin %s está actualizado." #: Puc/v4p3/Plugin/UpdateChecker.php:550 #, php-format msgctxt "the plugin title" msgid "A new version of the %s plugin is available." msgstr "Una nueva versión del %s plugin está disponible." #: Puc/v4p3/Plugin/UpdateChecker.php:552 #, php-format msgctxt "the plugin title" msgid "Could not determine if updates are available for %s." msgstr "No se pudo determinar si hay actualizaciones disponibles para %s." #: Puc/v4p3/Plugin/UpdateChecker.php:558 #, php-format msgid "Unknown update checker status \"%s\"" msgstr "Estado del comprobador de actualización desconocido «%s»" #: Puc/v4p3/Vcs/PluginUpdateChecker.php:95 msgid "There is no changelog available." msgstr "No hay un registro de cambios disponible."
{ "pile_set_name": "Github" }
// go run mksysnum.go https://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master // Code generated by the command above; see README.md. DO NOT EDIT. // +build amd64,dragonfly package unix const ( // SYS_NOSYS = 0; // { int nosys(void); } syscall nosys_args int SYS_EXIT = 1 // { void exit(int rval); } SYS_FORK = 2 // { int fork(void); } SYS_READ = 3 // { ssize_t read(int fd, void *buf, size_t nbyte); } SYS_WRITE = 4 // { ssize_t write(int fd, const void *buf, size_t nbyte); } SYS_OPEN = 5 // { int open(char *path, int flags, int mode); } SYS_CLOSE = 6 // { int close(int fd); } SYS_WAIT4 = 7 // { int wait4(int pid, int *status, int options, struct rusage *rusage); } wait4 wait_args int SYS_LINK = 9 // { int link(char *path, char *link); } SYS_UNLINK = 10 // { int unlink(char *path); } SYS_CHDIR = 12 // { int chdir(char *path); } SYS_FCHDIR = 13 // { int fchdir(int fd); } SYS_MKNOD = 14 // { int mknod(char *path, int mode, int dev); } SYS_CHMOD = 15 // { int chmod(char *path, int mode); } SYS_CHOWN = 16 // { int chown(char *path, int uid, int gid); } SYS_OBREAK = 17 // { int obreak(char *nsize); } break obreak_args int SYS_GETFSSTAT = 18 // { int getfsstat(struct statfs *buf, long bufsize, int flags); } SYS_GETPID = 20 // { pid_t getpid(void); } SYS_MOUNT = 21 // { int mount(char *type, char *path, int flags, caddr_t data); } SYS_UNMOUNT = 22 // { int unmount(char *path, int flags); } SYS_SETUID = 23 // { int setuid(uid_t uid); } SYS_GETUID = 24 // { uid_t getuid(void); } SYS_GETEUID = 25 // { uid_t geteuid(void); } SYS_PTRACE = 26 // { int ptrace(int req, pid_t pid, caddr_t addr, int data); } SYS_RECVMSG = 27 // { int recvmsg(int s, struct msghdr *msg, int flags); } SYS_SENDMSG = 28 // { int sendmsg(int s, caddr_t msg, int flags); } SYS_RECVFROM = 29 // { int recvfrom(int s, caddr_t buf, size_t len, int flags, caddr_t from, int *fromlenaddr); } SYS_ACCEPT = 30 // { int accept(int s, caddr_t name, int *anamelen); } SYS_GETPEERNAME = 31 // { int getpeername(int fdes, caddr_t asa, int *alen); } SYS_GETSOCKNAME = 32 // { int getsockname(int fdes, caddr_t asa, int *alen); } SYS_ACCESS = 33 // { int access(char *path, int flags); } SYS_CHFLAGS = 34 // { int chflags(char *path, int flags); } SYS_FCHFLAGS = 35 // { int fchflags(int fd, int flags); } SYS_SYNC = 36 // { int sync(void); } SYS_KILL = 37 // { int kill(int pid, int signum); } SYS_GETPPID = 39 // { pid_t getppid(void); } SYS_DUP = 41 // { int dup(int fd); } SYS_PIPE = 42 // { int pipe(void); } SYS_GETEGID = 43 // { gid_t getegid(void); } SYS_PROFIL = 44 // { int profil(caddr_t samples, size_t size, size_t offset, u_int scale); } SYS_KTRACE = 45 // { int ktrace(const char *fname, int ops, int facs, int pid); } SYS_GETGID = 47 // { gid_t getgid(void); } SYS_GETLOGIN = 49 // { int getlogin(char *namebuf, u_int namelen); } SYS_SETLOGIN = 50 // { int setlogin(char *namebuf); } SYS_ACCT = 51 // { int acct(char *path); } SYS_SIGALTSTACK = 53 // { int sigaltstack(stack_t *ss, stack_t *oss); } SYS_IOCTL = 54 // { int ioctl(int fd, u_long com, caddr_t data); } SYS_REBOOT = 55 // { int reboot(int opt); } SYS_REVOKE = 56 // { int revoke(char *path); } SYS_SYMLINK = 57 // { int symlink(char *path, char *link); } SYS_READLINK = 58 // { int readlink(char *path, char *buf, int count); } SYS_EXECVE = 59 // { int execve(char *fname, char **argv, char **envv); } SYS_UMASK = 60 // { int umask(int newmask); } umask umask_args int SYS_CHROOT = 61 // { int chroot(char *path); } SYS_MSYNC = 65 // { int msync(void *addr, size_t len, int flags); } SYS_VFORK = 66 // { pid_t vfork(void); } SYS_SBRK = 69 // { int sbrk(int incr); } SYS_SSTK = 70 // { int sstk(int incr); } SYS_MUNMAP = 73 // { int munmap(void *addr, size_t len); } SYS_MPROTECT = 74 // { int mprotect(void *addr, size_t len, int prot); } SYS_MADVISE = 75 // { int madvise(void *addr, size_t len, int behav); } SYS_MINCORE = 78 // { int mincore(const void *addr, size_t len, char *vec); } SYS_GETGROUPS = 79 // { int getgroups(u_int gidsetsize, gid_t *gidset); } SYS_SETGROUPS = 80 // { int setgroups(u_int gidsetsize, gid_t *gidset); } SYS_GETPGRP = 81 // { int getpgrp(void); } SYS_SETPGID = 82 // { int setpgid(int pid, int pgid); } SYS_SETITIMER = 83 // { int setitimer(u_int which, struct itimerval *itv, struct itimerval *oitv); } SYS_SWAPON = 85 // { int swapon(char *name); } SYS_GETITIMER = 86 // { int getitimer(u_int which, struct itimerval *itv); } SYS_GETDTABLESIZE = 89 // { int getdtablesize(void); } SYS_DUP2 = 90 // { int dup2(int from, int to); } SYS_FCNTL = 92 // { int fcntl(int fd, int cmd, long arg); } SYS_SELECT = 93 // { int select(int nd, fd_set *in, fd_set *ou, fd_set *ex, struct timeval *tv); } SYS_FSYNC = 95 // { int fsync(int fd); } SYS_SETPRIORITY = 96 // { int setpriority(int which, int who, int prio); } SYS_SOCKET = 97 // { int socket(int domain, int type, int protocol); } SYS_CONNECT = 98 // { int connect(int s, caddr_t name, int namelen); } SYS_GETPRIORITY = 100 // { int getpriority(int which, int who); } SYS_BIND = 104 // { int bind(int s, caddr_t name, int namelen); } SYS_SETSOCKOPT = 105 // { int setsockopt(int s, int level, int name, caddr_t val, int valsize); } SYS_LISTEN = 106 // { int listen(int s, int backlog); } SYS_GETTIMEOFDAY = 116 // { int gettimeofday(struct timeval *tp, struct timezone *tzp); } SYS_GETRUSAGE = 117 // { int getrusage(int who, struct rusage *rusage); } SYS_GETSOCKOPT = 118 // { int getsockopt(int s, int level, int name, caddr_t val, int *avalsize); } SYS_READV = 120 // { int readv(int fd, struct iovec *iovp, u_int iovcnt); } SYS_WRITEV = 121 // { int writev(int fd, struct iovec *iovp, u_int iovcnt); } SYS_SETTIMEOFDAY = 122 // { int settimeofday(struct timeval *tv, struct timezone *tzp); } SYS_FCHOWN = 123 // { int fchown(int fd, int uid, int gid); } SYS_FCHMOD = 124 // { int fchmod(int fd, int mode); } SYS_SETREUID = 126 // { int setreuid(int ruid, int euid); } SYS_SETREGID = 127 // { int setregid(int rgid, int egid); } SYS_RENAME = 128 // { int rename(char *from, char *to); } SYS_FLOCK = 131 // { int flock(int fd, int how); } SYS_MKFIFO = 132 // { int mkfifo(char *path, int mode); } SYS_SENDTO = 133 // { int sendto(int s, caddr_t buf, size_t len, int flags, caddr_t to, int tolen); } SYS_SHUTDOWN = 134 // { int shutdown(int s, int how); } SYS_SOCKETPAIR = 135 // { int socketpair(int domain, int type, int protocol, int *rsv); } SYS_MKDIR = 136 // { int mkdir(char *path, int mode); } SYS_RMDIR = 137 // { int rmdir(char *path); } SYS_UTIMES = 138 // { int utimes(char *path, struct timeval *tptr); } SYS_ADJTIME = 140 // { int adjtime(struct timeval *delta, struct timeval *olddelta); } SYS_SETSID = 147 // { int setsid(void); } SYS_QUOTACTL = 148 // { int quotactl(char *path, int cmd, int uid, caddr_t arg); } SYS_STATFS = 157 // { int statfs(char *path, struct statfs *buf); } SYS_FSTATFS = 158 // { int fstatfs(int fd, struct statfs *buf); } SYS_GETFH = 161 // { int getfh(char *fname, struct fhandle *fhp); } SYS_GETDOMAINNAME = 162 // { int getdomainname(char *domainname, int len); } SYS_SETDOMAINNAME = 163 // { int setdomainname(char *domainname, int len); } SYS_UNAME = 164 // { int uname(struct utsname *name); } SYS_SYSARCH = 165 // { int sysarch(int op, char *parms); } SYS_RTPRIO = 166 // { int rtprio(int function, pid_t pid, struct rtprio *rtp); } SYS_EXTPREAD = 173 // { ssize_t extpread(int fd, void *buf, size_t nbyte, int flags, off_t offset); } SYS_EXTPWRITE = 174 // { ssize_t extpwrite(int fd, const void *buf, size_t nbyte, int flags, off_t offset); } SYS_NTP_ADJTIME = 176 // { int ntp_adjtime(struct timex *tp); } SYS_SETGID = 181 // { int setgid(gid_t gid); } SYS_SETEGID = 182 // { int setegid(gid_t egid); } SYS_SETEUID = 183 // { int seteuid(uid_t euid); } SYS_PATHCONF = 191 // { int pathconf(char *path, int name); } SYS_FPATHCONF = 192 // { int fpathconf(int fd, int name); } SYS_GETRLIMIT = 194 // { int getrlimit(u_int which, struct rlimit *rlp); } getrlimit __getrlimit_args int SYS_SETRLIMIT = 195 // { int setrlimit(u_int which, struct rlimit *rlp); } setrlimit __setrlimit_args int SYS_MMAP = 197 // { caddr_t mmap(caddr_t addr, size_t len, int prot, int flags, int fd, int pad, off_t pos); } // SYS_NOSYS = 198; // { int nosys(void); } __syscall __syscall_args int SYS_LSEEK = 199 // { off_t lseek(int fd, int pad, off_t offset, int whence); } SYS_TRUNCATE = 200 // { int truncate(char *path, int pad, off_t length); } SYS_FTRUNCATE = 201 // { int ftruncate(int fd, int pad, off_t length); } SYS___SYSCTL = 202 // { int __sysctl(int *name, u_int namelen, void *old, size_t *oldlenp, void *new, size_t newlen); } __sysctl sysctl_args int SYS_MLOCK = 203 // { int mlock(const void *addr, size_t len); } SYS_MUNLOCK = 204 // { int munlock(const void *addr, size_t len); } SYS_UNDELETE = 205 // { int undelete(char *path); } SYS_FUTIMES = 206 // { int futimes(int fd, struct timeval *tptr); } SYS_GETPGID = 207 // { int getpgid(pid_t pid); } SYS_POLL = 209 // { int poll(struct pollfd *fds, u_int nfds, int timeout); } SYS___SEMCTL = 220 // { int __semctl(int semid, int semnum, int cmd, union semun *arg); } SYS_SEMGET = 221 // { int semget(key_t key, int nsems, int semflg); } SYS_SEMOP = 222 // { int semop(int semid, struct sembuf *sops, u_int nsops); } SYS_MSGCTL = 224 // { int msgctl(int msqid, int cmd, struct msqid_ds *buf); } SYS_MSGGET = 225 // { int msgget(key_t key, int msgflg); } SYS_MSGSND = 226 // { int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg); } SYS_MSGRCV = 227 // { int msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg); } SYS_SHMAT = 228 // { caddr_t shmat(int shmid, const void *shmaddr, int shmflg); } SYS_SHMCTL = 229 // { int shmctl(int shmid, int cmd, struct shmid_ds *buf); } SYS_SHMDT = 230 // { int shmdt(const void *shmaddr); } SYS_SHMGET = 231 // { int shmget(key_t key, size_t size, int shmflg); } SYS_CLOCK_GETTIME = 232 // { int clock_gettime(clockid_t clock_id, struct timespec *tp); } SYS_CLOCK_SETTIME = 233 // { int clock_settime(clockid_t clock_id, const struct timespec *tp); } SYS_CLOCK_GETRES = 234 // { int clock_getres(clockid_t clock_id, struct timespec *tp); } SYS_NANOSLEEP = 240 // { int nanosleep(const struct timespec *rqtp, struct timespec *rmtp); } SYS_MINHERIT = 250 // { int minherit(void *addr, size_t len, int inherit); } SYS_RFORK = 251 // { int rfork(int flags); } SYS_OPENBSD_POLL = 252 // { int openbsd_poll(struct pollfd *fds, u_int nfds, int timeout); } SYS_ISSETUGID = 253 // { int issetugid(void); } SYS_LCHOWN = 254 // { int lchown(char *path, int uid, int gid); } SYS_LCHMOD = 274 // { int lchmod(char *path, mode_t mode); } SYS_LUTIMES = 276 // { int lutimes(char *path, struct timeval *tptr); } SYS_EXTPREADV = 289 // { ssize_t extpreadv(int fd, struct iovec *iovp, u_int iovcnt, int flags, off_t offset); } SYS_EXTPWRITEV = 290 // { ssize_t extpwritev(int fd, struct iovec *iovp,u_int iovcnt, int flags, off_t offset); } SYS_FHSTATFS = 297 // { int fhstatfs(const struct fhandle *u_fhp, struct statfs *buf); } SYS_FHOPEN = 298 // { int fhopen(const struct fhandle *u_fhp, int flags); } SYS_MODNEXT = 300 // { int modnext(int modid); } SYS_MODSTAT = 301 // { int modstat(int modid, struct module_stat* stat); } SYS_MODFNEXT = 302 // { int modfnext(int modid); } SYS_MODFIND = 303 // { int modfind(const char *name); } SYS_KLDLOAD = 304 // { int kldload(const char *file); } SYS_KLDUNLOAD = 305 // { int kldunload(int fileid); } SYS_KLDFIND = 306 // { int kldfind(const char *file); } SYS_KLDNEXT = 307 // { int kldnext(int fileid); } SYS_KLDSTAT = 308 // { int kldstat(int fileid, struct kld_file_stat* stat); } SYS_KLDFIRSTMOD = 309 // { int kldfirstmod(int fileid); } SYS_GETSID = 310 // { int getsid(pid_t pid); } SYS_SETRESUID = 311 // { int setresuid(uid_t ruid, uid_t euid, uid_t suid); } SYS_SETRESGID = 312 // { int setresgid(gid_t rgid, gid_t egid, gid_t sgid); } SYS_AIO_RETURN = 314 // { int aio_return(struct aiocb *aiocbp); } SYS_AIO_SUSPEND = 315 // { int aio_suspend(struct aiocb * const * aiocbp, int nent, const struct timespec *timeout); } SYS_AIO_CANCEL = 316 // { int aio_cancel(int fd, struct aiocb *aiocbp); } SYS_AIO_ERROR = 317 // { int aio_error(struct aiocb *aiocbp); } SYS_AIO_READ = 318 // { int aio_read(struct aiocb *aiocbp); } SYS_AIO_WRITE = 319 // { int aio_write(struct aiocb *aiocbp); } SYS_LIO_LISTIO = 320 // { int lio_listio(int mode, struct aiocb * const *acb_list, int nent, struct sigevent *sig); } SYS_YIELD = 321 // { int yield(void); } SYS_MLOCKALL = 324 // { int mlockall(int how); } SYS_MUNLOCKALL = 325 // { int munlockall(void); } SYS___GETCWD = 326 // { int __getcwd(u_char *buf, u_int buflen); } SYS_SCHED_SETPARAM = 327 // { int sched_setparam (pid_t pid, const struct sched_param *param); } SYS_SCHED_GETPARAM = 328 // { int sched_getparam (pid_t pid, struct sched_param *param); } SYS_SCHED_SETSCHEDULER = 329 // { int sched_setscheduler (pid_t pid, int policy, const struct sched_param *param); } SYS_SCHED_GETSCHEDULER = 330 // { int sched_getscheduler (pid_t pid); } SYS_SCHED_YIELD = 331 // { int sched_yield (void); } SYS_SCHED_GET_PRIORITY_MAX = 332 // { int sched_get_priority_max (int policy); } SYS_SCHED_GET_PRIORITY_MIN = 333 // { int sched_get_priority_min (int policy); } SYS_SCHED_RR_GET_INTERVAL = 334 // { int sched_rr_get_interval (pid_t pid, struct timespec *interval); } SYS_UTRACE = 335 // { int utrace(const void *addr, size_t len); } SYS_KLDSYM = 337 // { int kldsym(int fileid, int cmd, void *data); } SYS_JAIL = 338 // { int jail(struct jail *jail); } SYS_SIGPROCMASK = 340 // { int sigprocmask(int how, const sigset_t *set, sigset_t *oset); } SYS_SIGSUSPEND = 341 // { int sigsuspend(const sigset_t *sigmask); } SYS_SIGACTION = 342 // { int sigaction(int sig, const struct sigaction *act, struct sigaction *oact); } SYS_SIGPENDING = 343 // { int sigpending(sigset_t *set); } SYS_SIGRETURN = 344 // { int sigreturn(ucontext_t *sigcntxp); } SYS_SIGTIMEDWAIT = 345 // { int sigtimedwait(const sigset_t *set,siginfo_t *info, const struct timespec *timeout); } SYS_SIGWAITINFO = 346 // { int sigwaitinfo(const sigset_t *set,siginfo_t *info); } SYS___ACL_GET_FILE = 347 // { int __acl_get_file(const char *path, acl_type_t type, struct acl *aclp); } SYS___ACL_SET_FILE = 348 // { int __acl_set_file(const char *path, acl_type_t type, struct acl *aclp); } SYS___ACL_GET_FD = 349 // { int __acl_get_fd(int filedes, acl_type_t type, struct acl *aclp); } SYS___ACL_SET_FD = 350 // { int __acl_set_fd(int filedes, acl_type_t type, struct acl *aclp); } SYS___ACL_DELETE_FILE = 351 // { int __acl_delete_file(const char *path, acl_type_t type); } SYS___ACL_DELETE_FD = 352 // { int __acl_delete_fd(int filedes, acl_type_t type); } SYS___ACL_ACLCHECK_FILE = 353 // { int __acl_aclcheck_file(const char *path, acl_type_t type, struct acl *aclp); } SYS___ACL_ACLCHECK_FD = 354 // { int __acl_aclcheck_fd(int filedes, acl_type_t type, struct acl *aclp); } SYS_EXTATTRCTL = 355 // { int extattrctl(const char *path, int cmd, const char *filename, int attrnamespace, const char *attrname); } SYS_EXTATTR_SET_FILE = 356 // { int extattr_set_file(const char *path, int attrnamespace, const char *attrname, void *data, size_t nbytes); } SYS_EXTATTR_GET_FILE = 357 // { int extattr_get_file(const char *path, int attrnamespace, const char *attrname, void *data, size_t nbytes); } SYS_EXTATTR_DELETE_FILE = 358 // { int extattr_delete_file(const char *path, int attrnamespace, const char *attrname); } SYS_AIO_WAITCOMPLETE = 359 // { int aio_waitcomplete(struct aiocb **aiocbp, struct timespec *timeout); } SYS_GETRESUID = 360 // { int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid); } SYS_GETRESGID = 361 // { int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid); } SYS_KQUEUE = 362 // { int kqueue(void); } SYS_KEVENT = 363 // { int kevent(int fd, const struct kevent *changelist, int nchanges, struct kevent *eventlist, int nevents, const struct timespec *timeout); } SYS_KENV = 390 // { int kenv(int what, const char *name, char *value, int len); } SYS_LCHFLAGS = 391 // { int lchflags(char *path, int flags); } SYS_UUIDGEN = 392 // { int uuidgen(struct uuid *store, int count); } SYS_SENDFILE = 393 // { int sendfile(int fd, int s, off_t offset, size_t nbytes, struct sf_hdtr *hdtr, off_t *sbytes, int flags); } SYS_VARSYM_SET = 450 // { int varsym_set(int level, const char *name, const char *data); } SYS_VARSYM_GET = 451 // { int varsym_get(int mask, const char *wild, char *buf, int bufsize); } SYS_VARSYM_LIST = 452 // { int varsym_list(int level, char *buf, int maxsize, int *marker); } SYS_EXEC_SYS_REGISTER = 465 // { int exec_sys_register(void *entry); } SYS_EXEC_SYS_UNREGISTER = 466 // { int exec_sys_unregister(int id); } SYS_SYS_CHECKPOINT = 467 // { int sys_checkpoint(int type, int fd, pid_t pid, int retval); } SYS_MOUNTCTL = 468 // { int mountctl(const char *path, int op, int fd, const void *ctl, int ctllen, void *buf, int buflen); } SYS_UMTX_SLEEP = 469 // { int umtx_sleep(volatile const int *ptr, int value, int timeout); } SYS_UMTX_WAKEUP = 470 // { int umtx_wakeup(volatile const int *ptr, int count); } SYS_JAIL_ATTACH = 471 // { int jail_attach(int jid); } SYS_SET_TLS_AREA = 472 // { int set_tls_area(int which, struct tls_info *info, size_t infosize); } SYS_GET_TLS_AREA = 473 // { int get_tls_area(int which, struct tls_info *info, size_t infosize); } SYS_CLOSEFROM = 474 // { int closefrom(int fd); } SYS_STAT = 475 // { int stat(const char *path, struct stat *ub); } SYS_FSTAT = 476 // { int fstat(int fd, struct stat *sb); } SYS_LSTAT = 477 // { int lstat(const char *path, struct stat *ub); } SYS_FHSTAT = 478 // { int fhstat(const struct fhandle *u_fhp, struct stat *sb); } SYS_GETDIRENTRIES = 479 // { int getdirentries(int fd, char *buf, u_int count, long *basep); } SYS_GETDENTS = 480 // { int getdents(int fd, char *buf, size_t count); } SYS_USCHED_SET = 481 // { int usched_set(pid_t pid, int cmd, void *data, int bytes); } SYS_EXTACCEPT = 482 // { int extaccept(int s, int flags, caddr_t name, int *anamelen); } SYS_EXTCONNECT = 483 // { int extconnect(int s, int flags, caddr_t name, int namelen); } SYS_MCONTROL = 485 // { int mcontrol(void *addr, size_t len, int behav, off_t value); } SYS_VMSPACE_CREATE = 486 // { int vmspace_create(void *id, int type, void *data); } SYS_VMSPACE_DESTROY = 487 // { int vmspace_destroy(void *id); } SYS_VMSPACE_CTL = 488 // { int vmspace_ctl(void *id, int cmd, struct trapframe *tframe, struct vextframe *vframe); } SYS_VMSPACE_MMAP = 489 // { int vmspace_mmap(void *id, void *addr, size_t len, int prot, int flags, int fd, off_t offset); } SYS_VMSPACE_MUNMAP = 490 // { int vmspace_munmap(void *id, void *addr, size_t len); } SYS_VMSPACE_MCONTROL = 491 // { int vmspace_mcontrol(void *id, void *addr, size_t len, int behav, off_t value); } SYS_VMSPACE_PREAD = 492 // { ssize_t vmspace_pread(void *id, void *buf, size_t nbyte, int flags, off_t offset); } SYS_VMSPACE_PWRITE = 493 // { ssize_t vmspace_pwrite(void *id, const void *buf, size_t nbyte, int flags, off_t offset); } SYS_EXTEXIT = 494 // { void extexit(int how, int status, void *addr); } SYS_LWP_CREATE = 495 // { int lwp_create(struct lwp_params *params); } SYS_LWP_GETTID = 496 // { lwpid_t lwp_gettid(void); } SYS_LWP_KILL = 497 // { int lwp_kill(pid_t pid, lwpid_t tid, int signum); } SYS_LWP_RTPRIO = 498 // { int lwp_rtprio(int function, pid_t pid, lwpid_t tid, struct rtprio *rtp); } SYS_PSELECT = 499 // { int pselect(int nd, fd_set *in, fd_set *ou, fd_set *ex, const struct timespec *ts, const sigset_t *sigmask); } SYS_STATVFS = 500 // { int statvfs(const char *path, struct statvfs *buf); } SYS_FSTATVFS = 501 // { int fstatvfs(int fd, struct statvfs *buf); } SYS_FHSTATVFS = 502 // { int fhstatvfs(const struct fhandle *u_fhp, struct statvfs *buf); } SYS_GETVFSSTAT = 503 // { int getvfsstat(struct statfs *buf, struct statvfs *vbuf, long vbufsize, int flags); } SYS_OPENAT = 504 // { int openat(int fd, char *path, int flags, int mode); } SYS_FSTATAT = 505 // { int fstatat(int fd, char *path, struct stat *sb, int flags); } SYS_FCHMODAT = 506 // { int fchmodat(int fd, char *path, int mode, int flags); } SYS_FCHOWNAT = 507 // { int fchownat(int fd, char *path, int uid, int gid, int flags); } SYS_UNLINKAT = 508 // { int unlinkat(int fd, char *path, int flags); } SYS_FACCESSAT = 509 // { int faccessat(int fd, char *path, int amode, int flags); } SYS_MQ_OPEN = 510 // { mqd_t mq_open(const char * name, int oflag, mode_t mode, struct mq_attr *attr); } SYS_MQ_CLOSE = 511 // { int mq_close(mqd_t mqdes); } SYS_MQ_UNLINK = 512 // { int mq_unlink(const char *name); } SYS_MQ_GETATTR = 513 // { int mq_getattr(mqd_t mqdes, struct mq_attr *mqstat); } SYS_MQ_SETATTR = 514 // { int mq_setattr(mqd_t mqdes, const struct mq_attr *mqstat, struct mq_attr *omqstat); } SYS_MQ_NOTIFY = 515 // { int mq_notify(mqd_t mqdes, const struct sigevent *notification); } SYS_MQ_SEND = 516 // { int mq_send(mqd_t mqdes, const char *msg_ptr, size_t msg_len, unsigned msg_prio); } SYS_MQ_RECEIVE = 517 // { ssize_t mq_receive(mqd_t mqdes, char *msg_ptr, size_t msg_len, unsigned *msg_prio); } SYS_MQ_TIMEDSEND = 518 // { int mq_timedsend(mqd_t mqdes, const char *msg_ptr, size_t msg_len, unsigned msg_prio, const struct timespec *abs_timeout); } SYS_MQ_TIMEDRECEIVE = 519 // { ssize_t mq_timedreceive(mqd_t mqdes, char *msg_ptr, size_t msg_len, unsigned *msg_prio, const struct timespec *abs_timeout); } SYS_IOPRIO_SET = 520 // { int ioprio_set(int which, int who, int prio); } SYS_IOPRIO_GET = 521 // { int ioprio_get(int which, int who); } SYS_CHROOT_KERNEL = 522 // { int chroot_kernel(char *path); } SYS_RENAMEAT = 523 // { int renameat(int oldfd, char *old, int newfd, char *new); } SYS_MKDIRAT = 524 // { int mkdirat(int fd, char *path, mode_t mode); } SYS_MKFIFOAT = 525 // { int mkfifoat(int fd, char *path, mode_t mode); } SYS_MKNODAT = 526 // { int mknodat(int fd, char *path, mode_t mode, dev_t dev); } SYS_READLINKAT = 527 // { int readlinkat(int fd, char *path, char *buf, size_t bufsize); } SYS_SYMLINKAT = 528 // { int symlinkat(char *path1, int fd, char *path2); } SYS_SWAPOFF = 529 // { int swapoff(char *name); } SYS_VQUOTACTL = 530 // { int vquotactl(const char *path, struct plistref *pref); } SYS_LINKAT = 531 // { int linkat(int fd1, char *path1, int fd2, char *path2, int flags); } SYS_EACCESS = 532 // { int eaccess(char *path, int flags); } SYS_LPATHCONF = 533 // { int lpathconf(char *path, int name); } SYS_VMM_GUEST_CTL = 534 // { int vmm_guest_ctl(int op, struct vmm_guest_options *options); } SYS_VMM_GUEST_SYNC_ADDR = 535 // { int vmm_guest_sync_addr(long *dstaddr, long *srcaddr); } SYS_PROCCTL = 536 // { int procctl(idtype_t idtype, id_t id, int cmd, void *data); } SYS_CHFLAGSAT = 537 // { int chflagsat(int fd, const char *path, int flags, int atflags);} SYS_PIPE2 = 538 // { int pipe2(int *fildes, int flags); } SYS_UTIMENSAT = 539 // { int utimensat(int fd, const char *path, const struct timespec *ts, int flags); } SYS_FUTIMENS = 540 // { int futimens(int fd, const struct timespec *ts); } SYS_ACCEPT4 = 541 // { int accept4(int s, caddr_t name, int *anamelen, int flags); } SYS_LWP_SETNAME = 542 // { int lwp_setname(lwpid_t tid, const char *name); } SYS_PPOLL = 543 // { int ppoll(struct pollfd *fds, u_int nfds, const struct timespec *ts, const sigset_t *sigmask); } SYS_LWP_SETAFFINITY = 544 // { int lwp_setaffinity(pid_t pid, lwpid_t tid, const cpumask_t *mask); } SYS_LWP_GETAFFINITY = 545 // { int lwp_getaffinity(pid_t pid, lwpid_t tid, cpumask_t *mask); } SYS_LWP_CREATE2 = 546 // { int lwp_create2(struct lwp_params *params, const cpumask_t *mask); } )
{ "pile_set_name": "Github" }
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2016, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * 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 SimplePie Team 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 HOLDERS * AND 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 SimplePie * @copyright 2004-2016 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * Date Parser * * @package SimplePie * @subpackage Parsing */ class SimplePie_Parse_Date { /** * Input data * * @access protected * @var string */ var $date; /** * List of days, calendar day name => ordinal day number in the week * * @access protected * @var array */ var $day = array( // English 'mon' => 1, 'monday' => 1, 'tue' => 2, 'tuesday' => 2, 'wed' => 3, 'wednesday' => 3, 'thu' => 4, 'thursday' => 4, 'fri' => 5, 'friday' => 5, 'sat' => 6, 'saturday' => 6, 'sun' => 7, 'sunday' => 7, // Dutch 'maandag' => 1, 'dinsdag' => 2, 'woensdag' => 3, 'donderdag' => 4, 'vrijdag' => 5, 'zaterdag' => 6, 'zondag' => 7, // French 'lundi' => 1, 'mardi' => 2, 'mercredi' => 3, 'jeudi' => 4, 'vendredi' => 5, 'samedi' => 6, 'dimanche' => 7, // German 'montag' => 1, 'dienstag' => 2, 'mittwoch' => 3, 'donnerstag' => 4, 'freitag' => 5, 'samstag' => 6, 'sonnabend' => 6, 'sonntag' => 7, // Italian 'lunedì' => 1, 'martedì' => 2, 'mercoledì' => 3, 'giovedì' => 4, 'venerdì' => 5, 'sabato' => 6, 'domenica' => 7, // Spanish 'lunes' => 1, 'martes' => 2, 'miércoles' => 3, 'jueves' => 4, 'viernes' => 5, 'sábado' => 6, 'domingo' => 7, // Finnish 'maanantai' => 1, 'tiistai' => 2, 'keskiviikko' => 3, 'torstai' => 4, 'perjantai' => 5, 'lauantai' => 6, 'sunnuntai' => 7, // Hungarian 'hétfő' => 1, 'kedd' => 2, 'szerda' => 3, 'csütörtok' => 4, 'péntek' => 5, 'szombat' => 6, 'vasárnap' => 7, // Greek 'Δευ' => 1, 'Τρι' => 2, 'Τετ' => 3, 'Πεμ' => 4, 'Παρ' => 5, 'Σαβ' => 6, 'Κυρ' => 7, ); /** * List of months, calendar month name => calendar month number * * @access protected * @var array */ var $month = array( // English 'jan' => 1, 'january' => 1, 'feb' => 2, 'february' => 2, 'mar' => 3, 'march' => 3, 'apr' => 4, 'april' => 4, 'may' => 5, // No long form of May 'jun' => 6, 'june' => 6, 'jul' => 7, 'july' => 7, 'aug' => 8, 'august' => 8, 'sep' => 9, 'september' => 9, 'oct' => 10, 'october' => 10, 'nov' => 11, 'november' => 11, 'dec' => 12, 'december' => 12, // Dutch 'januari' => 1, 'februari' => 2, 'maart' => 3, 'april' => 4, 'mei' => 5, 'juni' => 6, 'juli' => 7, 'augustus' => 8, 'september' => 9, 'oktober' => 10, 'november' => 11, 'december' => 12, // French 'janvier' => 1, 'février' => 2, 'mars' => 3, 'avril' => 4, 'mai' => 5, 'juin' => 6, 'juillet' => 7, 'août' => 8, 'septembre' => 9, 'octobre' => 10, 'novembre' => 11, 'décembre' => 12, // German 'januar' => 1, 'februar' => 2, 'märz' => 3, 'april' => 4, 'mai' => 5, 'juni' => 6, 'juli' => 7, 'august' => 8, 'september' => 9, 'oktober' => 10, 'november' => 11, 'dezember' => 12, // Italian 'gennaio' => 1, 'febbraio' => 2, 'marzo' => 3, 'aprile' => 4, 'maggio' => 5, 'giugno' => 6, 'luglio' => 7, 'agosto' => 8, 'settembre' => 9, 'ottobre' => 10, 'novembre' => 11, 'dicembre' => 12, // Spanish 'enero' => 1, 'febrero' => 2, 'marzo' => 3, 'abril' => 4, 'mayo' => 5, 'junio' => 6, 'julio' => 7, 'agosto' => 8, 'septiembre' => 9, 'setiembre' => 9, 'octubre' => 10, 'noviembre' => 11, 'diciembre' => 12, // Finnish 'tammikuu' => 1, 'helmikuu' => 2, 'maaliskuu' => 3, 'huhtikuu' => 4, 'toukokuu' => 5, 'kesäkuu' => 6, 'heinäkuu' => 7, 'elokuu' => 8, 'suuskuu' => 9, 'lokakuu' => 10, 'marras' => 11, 'joulukuu' => 12, // Hungarian 'január' => 1, 'február' => 2, 'március' => 3, 'április' => 4, 'május' => 5, 'június' => 6, 'július' => 7, 'augusztus' => 8, 'szeptember' => 9, 'október' => 10, 'november' => 11, 'december' => 12, // Greek 'Ιαν' => 1, 'Φεβ' => 2, 'Μάώ' => 3, 'Μαώ' => 3, 'Απρ' => 4, 'Μάι' => 5, 'Μαϊ' => 5, 'Μαι' => 5, 'Ιούν' => 6, 'Ιον' => 6, 'Ιούλ' => 7, 'Ιολ' => 7, 'Αύγ' => 8, 'Αυγ' => 8, 'Σεπ' => 9, 'Οκτ' => 10, 'Νοέ' => 11, 'Δεκ' => 12, ); /** * List of timezones, abbreviation => offset from UTC * * @access protected * @var array */ var $timezone = array( 'ACDT' => 37800, 'ACIT' => 28800, 'ACST' => 34200, 'ACT' => -18000, 'ACWDT' => 35100, 'ACWST' => 31500, 'AEDT' => 39600, 'AEST' => 36000, 'AFT' => 16200, 'AKDT' => -28800, 'AKST' => -32400, 'AMDT' => 18000, 'AMT' => -14400, 'ANAST' => 46800, 'ANAT' => 43200, 'ART' => -10800, 'AZOST' => -3600, 'AZST' => 18000, 'AZT' => 14400, 'BIOT' => 21600, 'BIT' => -43200, 'BOT' => -14400, 'BRST' => -7200, 'BRT' => -10800, 'BST' => 3600, 'BTT' => 21600, 'CAST' => 18000, 'CAT' => 7200, 'CCT' => 23400, 'CDT' => -18000, 'CEDT' => 7200, 'CEST' => 7200, 'CET' => 3600, 'CGST' => -7200, 'CGT' => -10800, 'CHADT' => 49500, 'CHAST' => 45900, 'CIST' => -28800, 'CKT' => -36000, 'CLDT' => -10800, 'CLST' => -14400, 'COT' => -18000, 'CST' => -21600, 'CVT' => -3600, 'CXT' => 25200, 'DAVT' => 25200, 'DTAT' => 36000, 'EADT' => -18000, 'EAST' => -21600, 'EAT' => 10800, 'ECT' => -18000, 'EDT' => -14400, 'EEST' => 10800, 'EET' => 7200, 'EGT' => -3600, 'EKST' => 21600, 'EST' => -18000, 'FJT' => 43200, 'FKDT' => -10800, 'FKST' => -14400, 'FNT' => -7200, 'GALT' => -21600, 'GEDT' => 14400, 'GEST' => 10800, 'GFT' => -10800, 'GILT' => 43200, 'GIT' => -32400, 'GST' => 14400, 'GST' => -7200, 'GYT' => -14400, 'HAA' => -10800, 'HAC' => -18000, 'HADT' => -32400, 'HAE' => -14400, 'HAP' => -25200, 'HAR' => -21600, 'HAST' => -36000, 'HAT' => -9000, 'HAY' => -28800, 'HKST' => 28800, 'HMT' => 18000, 'HNA' => -14400, 'HNC' => -21600, 'HNE' => -18000, 'HNP' => -28800, 'HNR' => -25200, 'HNT' => -12600, 'HNY' => -32400, 'IRDT' => 16200, 'IRKST' => 32400, 'IRKT' => 28800, 'IRST' => 12600, 'JFDT' => -10800, 'JFST' => -14400, 'JST' => 32400, 'KGST' => 21600, 'KGT' => 18000, 'KOST' => 39600, 'KOVST' => 28800, 'KOVT' => 25200, 'KRAST' => 28800, 'KRAT' => 25200, 'KST' => 32400, 'LHDT' => 39600, 'LHST' => 37800, 'LINT' => 50400, 'LKT' => 21600, 'MAGST' => 43200, 'MAGT' => 39600, 'MAWT' => 21600, 'MDT' => -21600, 'MESZ' => 7200, 'MEZ' => 3600, 'MHT' => 43200, 'MIT' => -34200, 'MNST' => 32400, 'MSDT' => 14400, 'MSST' => 10800, 'MST' => -25200, 'MUT' => 14400, 'MVT' => 18000, 'MYT' => 28800, 'NCT' => 39600, 'NDT' => -9000, 'NFT' => 41400, 'NMIT' => 36000, 'NOVST' => 25200, 'NOVT' => 21600, 'NPT' => 20700, 'NRT' => 43200, 'NST' => -12600, 'NUT' => -39600, 'NZDT' => 46800, 'NZST' => 43200, 'OMSST' => 25200, 'OMST' => 21600, 'PDT' => -25200, 'PET' => -18000, 'PETST' => 46800, 'PETT' => 43200, 'PGT' => 36000, 'PHOT' => 46800, 'PHT' => 28800, 'PKT' => 18000, 'PMDT' => -7200, 'PMST' => -10800, 'PONT' => 39600, 'PST' => -28800, 'PWT' => 32400, 'PYST' => -10800, 'PYT' => -14400, 'RET' => 14400, 'ROTT' => -10800, 'SAMST' => 18000, 'SAMT' => 14400, 'SAST' => 7200, 'SBT' => 39600, 'SCDT' => 46800, 'SCST' => 43200, 'SCT' => 14400, 'SEST' => 3600, 'SGT' => 28800, 'SIT' => 28800, 'SRT' => -10800, 'SST' => -39600, 'SYST' => 10800, 'SYT' => 7200, 'TFT' => 18000, 'THAT' => -36000, 'TJT' => 18000, 'TKT' => -36000, 'TMT' => 18000, 'TOT' => 46800, 'TPT' => 32400, 'TRUT' => 36000, 'TVT' => 43200, 'TWT' => 28800, 'UYST' => -7200, 'UYT' => -10800, 'UZT' => 18000, 'VET' => -14400, 'VLAST' => 39600, 'VLAT' => 36000, 'VOST' => 21600, 'VUT' => 39600, 'WAST' => 7200, 'WAT' => 3600, 'WDT' => 32400, 'WEST' => 3600, 'WFT' => 43200, 'WIB' => 25200, 'WIT' => 32400, 'WITA' => 28800, 'WKST' => 18000, 'WST' => 28800, 'YAKST' => 36000, 'YAKT' => 32400, 'YAPT' => 36000, 'YEKST' => 21600, 'YEKT' => 18000, ); /** * Cached PCRE for SimplePie_Parse_Date::$day * * @access protected * @var string */ var $day_pcre; /** * Cached PCRE for SimplePie_Parse_Date::$month * * @access protected * @var string */ var $month_pcre; /** * Array of user-added callback methods * * @access private * @var array */ var $built_in = array(); /** * Array of user-added callback methods * * @access private * @var array */ var $user = array(); /** * Create new SimplePie_Parse_Date object, and set self::day_pcre, * self::month_pcre, and self::built_in * * @access private */ public function __construct() { $this->day_pcre = '(' . implode(array_keys($this->day), '|') . ')'; $this->month_pcre = '(' . implode(array_keys($this->month), '|') . ')'; static $cache; if (!isset($cache[get_class($this)])) { $all_methods = get_class_methods($this); foreach ($all_methods as $method) { if (strtolower(substr($method, 0, 5)) === 'date_') { $cache[get_class($this)][] = $method; } } } foreach ($cache[get_class($this)] as $method) { $this->built_in[] = $method; } } /** * Get the object * * @access public */ public static function get() { static $object; if (!$object) { $object = new SimplePie_Parse_Date; } return $object; } /** * Parse a date * * @final * @access public * @param string $date Date to parse * @return int Timestamp corresponding to date string, or false on failure */ public function parse($date) { foreach ($this->user as $method) { if (($returned = call_user_func($method, $date)) !== false) { return $returned; } } foreach ($this->built_in as $method) { if (($returned = call_user_func(array($this, $method), $date)) !== false) { return $returned; } } return false; } /** * Add a callback method to parse a date * * @final * @access public * @param callback $callback */ public function add_callback($callback) { if (is_callable($callback)) { $this->user[] = $callback; } else { trigger_error('User-supplied function must be a valid callback', E_USER_WARNING); } } /** * Parse a superset of W3C-DTF (allows hyphens and colons to be omitted, as * well as allowing any of upper or lower case "T", horizontal tabs, or * spaces to be used as the time separator (including more than one)) * * @access protected * @return int Timestamp */ public function date_w3cdtf($date) { static $pcre; if (!$pcre) { $year = '([0-9]{4})'; $month = $day = $hour = $minute = $second = '([0-9]{2})'; $decimal = '([0-9]*)'; $zone = '(?:(Z)|([+\-])([0-9]{1,2}):?([0-9]{1,2}))'; $pcre = '/^' . $year . '(?:-?' . $month . '(?:-?' . $day . '(?:[Tt\x09\x20]+' . $hour . '(?::?' . $minute . '(?::?' . $second . '(?:.' . $decimal . ')?)?)?' . $zone . ')?)?)?$/'; } if (preg_match($pcre, $date, $match)) { /* Capturing subpatterns: 1: Year 2: Month 3: Day 4: Hour 5: Minute 6: Second 7: Decimal fraction of a second 8: Zulu 9: Timezone ± 10: Timezone hours 11: Timezone minutes */ // Fill in empty matches for ($i = count($match); $i <= 3; $i++) { $match[$i] = '1'; } for ($i = count($match); $i <= 7; $i++) { $match[$i] = '0'; } // Numeric timezone if (isset($match[9]) && $match[9] !== '') { $timezone = $match[10] * 3600; $timezone += $match[11] * 60; if ($match[9] === '-') { $timezone = 0 - $timezone; } } else { $timezone = 0; } // Convert the number of seconds to an integer, taking decimals into account $second = round((int)$match[6] + (int)$match[7] / pow(10, strlen($match[7]))); return gmmktime($match[4], $match[5], $second, $match[2], $match[3], $match[1]) - $timezone; } else { return false; } } /** * Remove RFC822 comments * * @access protected * @param string $data Data to strip comments from * @return string Comment stripped string */ public function remove_rfc2822_comments($string) { $string = (string) $string; $position = 0; $length = strlen($string); $depth = 0; $output = ''; while ($position < $length && ($pos = strpos($string, '(', $position)) !== false) { $output .= substr($string, $position, $pos - $position); $position = $pos + 1; if ($pos === 0 || $string[$pos - 1] !== '\\') { $depth++; while ($depth && $position < $length) { $position += strcspn($string, '()', $position); if ($string[$position - 1] === '\\') { $position++; continue; } elseif (isset($string[$position])) { switch ($string[$position]) { case '(': $depth++; break; case ')': $depth--; break; } $position++; } else { break; } } } else { $output .= '('; } } $output .= substr($string, $position); return $output; } /** * Parse RFC2822's date format * * @access protected * @return int Timestamp */ public function date_rfc2822($date) { static $pcre; if (!$pcre) { $wsp = '[\x09\x20]'; $fws = '(?:' . $wsp . '+|' . $wsp . '*(?:\x0D\x0A' . $wsp . '+)+)'; $optional_fws = $fws . '?'; $day_name = $this->day_pcre; $month = $this->month_pcre; $day = '([0-9]{1,2})'; $hour = $minute = $second = '([0-9]{2})'; $year = '([0-9]{2,4})'; $num_zone = '([+\-])([0-9]{2})([0-9]{2})'; $character_zone = '([A-Z]{1,5})'; $zone = '(?:' . $num_zone . '|' . $character_zone . ')'; $pcre = '/(?:' . $optional_fws . $day_name . $optional_fws . ',)?' . $optional_fws . $day . $fws . $month . $fws . $year . $fws . $hour . $optional_fws . ':' . $optional_fws . $minute . '(?:' . $optional_fws . ':' . $optional_fws . $second . ')?' . $fws . $zone . '/i'; } if (preg_match($pcre, $this->remove_rfc2822_comments($date), $match)) { /* Capturing subpatterns: 1: Day name 2: Day 3: Month 4: Year 5: Hour 6: Minute 7: Second 8: Timezone ± 9: Timezone hours 10: Timezone minutes 11: Alphabetic timezone */ // Find the month number $month = $this->month[strtolower($match[3])]; // Numeric timezone if ($match[8] !== '') { $timezone = $match[9] * 3600; $timezone += $match[10] * 60; if ($match[8] === '-') { $timezone = 0 - $timezone; } } // Character timezone elseif (isset($this->timezone[strtoupper($match[11])])) { $timezone = $this->timezone[strtoupper($match[11])]; } // Assume everything else to be -0000 else { $timezone = 0; } // Deal with 2/3 digit years if ($match[4] < 50) { $match[4] += 2000; } elseif ($match[4] < 1000) { $match[4] += 1900; } // Second is optional, if it is empty set it to zero if ($match[7] !== '') { $second = $match[7]; } else { $second = 0; } return gmmktime($match[5], $match[6], $second, $month, $match[2], $match[4]) - $timezone; } else { return false; } } /** * Parse RFC850's date format * * @access protected * @return int Timestamp */ public function date_rfc850($date) { static $pcre; if (!$pcre) { $space = '[\x09\x20]+'; $day_name = $this->day_pcre; $month = $this->month_pcre; $day = '([0-9]{1,2})'; $year = $hour = $minute = $second = '([0-9]{2})'; $zone = '([A-Z]{1,5})'; $pcre = '/^' . $day_name . ',' . $space . $day . '-' . $month . '-' . $year . $space . $hour . ':' . $minute . ':' . $second . $space . $zone . '$/i'; } if (preg_match($pcre, $date, $match)) { /* Capturing subpatterns: 1: Day name 2: Day 3: Month 4: Year 5: Hour 6: Minute 7: Second 8: Timezone */ // Month $month = $this->month[strtolower($match[3])]; // Character timezone if (isset($this->timezone[strtoupper($match[8])])) { $timezone = $this->timezone[strtoupper($match[8])]; } // Assume everything else to be -0000 else { $timezone = 0; } // Deal with 2 digit year if ($match[4] < 50) { $match[4] += 2000; } else { $match[4] += 1900; } return gmmktime($match[5], $match[6], $match[7], $month, $match[2], $match[4]) - $timezone; } else { return false; } } /** * Parse C99's asctime()'s date format * * @access protected * @return int Timestamp */ public function date_asctime($date) { static $pcre; if (!$pcre) { $space = '[\x09\x20]+'; $wday_name = $this->day_pcre; $mon_name = $this->month_pcre; $day = '([0-9]{1,2})'; $hour = $sec = $min = '([0-9]{2})'; $year = '([0-9]{4})'; $terminator = '\x0A?\x00?'; $pcre = '/^' . $wday_name . $space . $mon_name . $space . $day . $space . $hour . ':' . $min . ':' . $sec . $space . $year . $terminator . '$/i'; } if (preg_match($pcre, $date, $match)) { /* Capturing subpatterns: 1: Day name 2: Month 3: Day 4: Hour 5: Minute 6: Second 7: Year */ $month = $this->month[strtolower($match[2])]; return gmmktime($match[4], $match[5], $match[6], $month, $match[3], $match[7]); } else { return false; } } /** * Parse dates using strtotime() * * @access protected * @return int Timestamp */ public function date_strtotime($date) { $strtotime = strtotime($date); if ($strtotime === -1 || $strtotime === false) { return false; } else { return $strtotime; } } }
{ "pile_set_name": "Github" }
// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv4 const ( sysIP_TOS = 0x1 sysIP_TTL = 0x2 sysIP_HDRINCL = 0x3 sysIP_OPTIONS = 0x4 sysIP_ROUTER_ALERT = 0x5 sysIP_RECVOPTS = 0x6 sysIP_RETOPTS = 0x7 sysIP_PKTINFO = 0x8 sysIP_PKTOPTIONS = 0x9 sysIP_MTU_DISCOVER = 0xa sysIP_RECVERR = 0xb sysIP_RECVTTL = 0xc sysIP_RECVTOS = 0xd sysIP_MTU = 0xe sysIP_FREEBIND = 0xf sysIP_TRANSPARENT = 0x13 sysIP_RECVRETOPTS = 0x7 sysIP_ORIGDSTADDR = 0x14 sysIP_RECVORIGDSTADDR = 0x14 sysIP_MINTTL = 0x15 sysIP_NODEFRAG = 0x16 sysIP_UNICAST_IF = 0x32 sysIP_MULTICAST_IF = 0x20 sysIP_MULTICAST_TTL = 0x21 sysIP_MULTICAST_LOOP = 0x22 sysIP_ADD_MEMBERSHIP = 0x23 sysIP_DROP_MEMBERSHIP = 0x24 sysIP_UNBLOCK_SOURCE = 0x25 sysIP_BLOCK_SOURCE = 0x26 sysIP_ADD_SOURCE_MEMBERSHIP = 0x27 sysIP_DROP_SOURCE_MEMBERSHIP = 0x28 sysIP_MSFILTER = 0x29 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIP_MULTICAST_ALL = 0x31 sysICMP_FILTER = 0x1 sysSO_EE_ORIGIN_NONE = 0x0 sysSO_EE_ORIGIN_LOCAL = 0x1 sysSO_EE_ORIGIN_ICMP = 0x2 sysSO_EE_ORIGIN_ICMP6 = 0x3 sysSO_EE_ORIGIN_TXSTATUS = 0x4 sysSO_EE_ORIGIN_TIMESTAMPING = 0x4 sysSOL_SOCKET = 0x1 sysSO_ATTACH_FILTER = 0x1a sizeofKernelSockaddrStorage = 0x80 sizeofSockaddrInet = 0x10 sizeofInetPktinfo = 0xc sizeofSockExtendedErr = 0x10 sizeofIPMreq = 0x8 sizeofIPMreqn = 0xc sizeofIPMreqSource = 0xc sizeofGroupReq = 0x88 sizeofGroupSourceReq = 0x108 sizeofICMPFilter = 0x4 sizeofSockFprog = 0x10 ) type kernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type inetPktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type sockExtendedErr struct { Errno uint32 Origin uint8 Type uint8 Code uint8 Pad uint8 Info uint32 Data uint32 } type ipMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type ipMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type ipMreqSource struct { Multiaddr uint32 Interface uint32 Sourceaddr uint32 } type groupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage } type groupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group kernelSockaddrStorage Source kernelSockaddrStorage } type icmpFilter struct { Data uint32 } type sockFProg struct { Len uint16 Pad_cgo_0 [6]byte Filter *sockFilter } type sockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 }
{ "pile_set_name": "Github" }
using Engine.Exceptions; using Engine.Model.Client; using Engine.Model.Common.Entities; using OpenAL; using System; using System.Collections.Generic; using System.Security; using System.Threading; namespace Engine.Audio.OpenAL { public sealed class OpenALPlayer : MarshalByRefObject, IPlayer { #region fields private readonly object _syncObject = new object(); private bool _disposed; private AudioContext _context; private Dictionary<UserId, SourceDescription> _sources; #endregion #region nested types private class SourceDescription { public int Id { get; private set; } public long LastPlayedNumber { get; set; } [SecurityCritical] public SourceDescription(int soueceId) { Id = soueceId; } [SecurityCritical] public ALFormat GetFormat(SoundPack pack) { if (pack.Channels != 2 && pack.Channels != 1) throw new ArgumentException("channels"); if (pack.BitPerChannel != 8 && pack.BitPerChannel != 16) throw new ArgumentException("bitPerChannel"); if (pack.Channels == 1) return pack.BitPerChannel == 8 ? ALFormat.Mono8 : ALFormat.Mono16; else return pack.BitPerChannel == 8 ? ALFormat.Stereo8 : ALFormat.Stereo16; } } #endregion #region constructor [SecurityCritical] public OpenALPlayer(string deviceName = null) { if (string.IsNullOrEmpty(deviceName) || IsInited) return; Initialize(deviceName); } #endregion #region properties public bool IsInited { [SecuritySafeCritical] get { return Interlocked.CompareExchange(ref _context, null, null) != null; } } public IList<string> Devices { [SecuritySafeCritical] get { try { return AudioContext.AvailableDevices; } catch (Exception) { return new List<string>(); } } } #endregion #region methods [SecurityCritical] private void Initialize(string deviceName) { try { lock (_syncObject) { _sources = new Dictionary<UserId, SourceDescription>(); if (string.IsNullOrEmpty(deviceName)) deviceName = AudioContext.DefaultDevice; if (!AudioContext.AvailableDevices.Contains(deviceName)) deviceName = AudioContext.DefaultDevice; _context = new AudioContext(deviceName); } } catch (Exception e) { if (_context != null) _context.Dispose(); _context = null; ClientModel.Logger.Write(e); throw new ModelException(ErrorCode.AudioNotEnabled, "Audio player do not initialized.", e, deviceName); } } [SecuritySafeCritical] public void SetOptions(string deviceName) { if (IsInited) { Stop(); _context.Dispose(); } Initialize(deviceName); } [SecuritySafeCritical] public void Enqueue(UserId id, long packNumber, SoundPack pack) { if (!IsInited) return; lock (_syncObject) { SourceDescription source; if (!_sources.TryGetValue(id, out source)) { int sourceId = AL.GenSource(); source = new SourceDescription(sourceId); _sources.Add(id, source); } if (source.LastPlayedNumber > packNumber) return; source.LastPlayedNumber = packNumber; int bufferId = AL.GenBuffer(); AL.BufferData(bufferId, source.GetFormat(pack), pack.Data, pack.Data.Length, pack.Frequency); AL.SourceQueueBuffer(source.Id, bufferId); if (AL.GetSourceState(source.Id) != ALSourceState.Playing) AL.SourcePlay(source.Id); ClearBuffers(source, 0); } } [SecuritySafeCritical] public void Stop(UserId id) { if (!IsInited) return; lock (_syncObject) { SourceDescription source; if (!_sources.TryGetValue(id, out source)) return; Stop(source); _sources.Remove(id); } } [SecuritySafeCritical] public void Stop() { if (!IsInited) return; lock (_syncObject) { foreach (SourceDescription source in _sources.Values) Stop(source); _sources.Clear(); } } [SecurityCritical] private void Stop(SourceDescription source) { int count; AL.GetSource(source.Id, ALGetSourcei.BuffersQueued, out count); ClearBuffers(source, count); AL.DeleteSource(source.Id); } [SecurityCritical] private void ClearBuffers(UserId id, int input) { SourceDescription source; if (!_sources.TryGetValue(id, out source)) return; ClearBuffers(source, input); } [SecurityCritical] private void ClearBuffers(SourceDescription source, int count) { if (_context == null) return; int[] freedbuffers; if (count == 0) { int buffersProcessed; AL.GetSource(source.Id, ALGetSourcei.BuffersProcessed, out buffersProcessed); if (buffersProcessed == 0) return; freedbuffers = AL.SourceUnqueueBuffers(source.Id, buffersProcessed); } else freedbuffers = AL.SourceUnqueueBuffers(source.Id, count); AL.DeleteBuffers(freedbuffers); } #endregion #region IDisposable [SecuritySafeCritical] public void Dispose() { if (_disposed) return; _disposed = true; if (_context != null) { Stop(); _context.Dispose(); } } #endregion } }
{ "pile_set_name": "Github" }
#ifndef __CONCRETE_PRODUCT_1_H__ #define __CONCRETE_PRODUCT_1_H__ #include "product.h" struct concrete_product_1 { struct product product; }; void concrete_product_1_init(struct concrete_product_1 *); #endif /* __CONCRETE_PRODUCT_1_H__ */
{ "pile_set_name": "Github" }
p edge 30 30 e 0 8 e 1 6 e 2 7 e 3 26 e 4 27 e 5 23 e 6 20 e 7 16 e 8 12 e 9 10 e 10 3 e 11 5 e 12 22 e 13 18 e 14 2 e 15 29 e 16 15 e 17 11 e 18 17 e 19 28 e 20 21 e 21 24 e 22 9 e 23 14 e 24 0 e 25 19 e 26 25 e 27 13 e 28 4 e 29 1
{ "pile_set_name": "Github" }
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // +k8s:deepcopy-gen=package // +k8s:protobuf-gen=package // +k8s:openapi-gen=true // +k8s:prerelease-lifecycle-gen=true // +groupName=certificates.k8s.io package v1beta1 // import "k8s.io/api/certificates/v1beta1"
{ "pile_set_name": "Github" }
#import <Foundation/Foundation.h> /** * MurmurHash2 was written by Austin Appleby, and is placed in the public domain. * http://code.google.com/p/smhasher **/ #ifndef YapDatabase_YapMurmurHash_h #define YapDatabase_YapMurmurHash_h NSUInteger YapMurmurHash2(NSUInteger hash1, NSUInteger hash2); NSUInteger YapMurmurHash3(NSUInteger hash1, NSUInteger hash2, NSUInteger hash3); NSUInteger YapMurmurHashData(NSData *data); int32_t YapMurmurHashData_32(NSData *data); int64_t YapMurmurHashData_64(NSData *data); #endif
{ "pile_set_name": "Github" }
/** * Thai translation for bootstrap-datetimepicker * Suchau Jiraprapot <[email protected]> */ ;(function($){ $.fn.datetimepicker.dates['th'] = { days: ["อาทิตย์", "จันทร์", "อังคาร", "พุธ", "พฤหัส", "ศุกร์", "เสาร์", "อาทิตย์"], daysShort: ["อา", "จ", "อ", "พ", "พฤ", "ศ", "ส", "อา"], daysMin: ["อา", "จ", "อ", "พ", "พฤ", "ศ", "ส", "อา"], months: ["มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน", "กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม"], monthsShort: ["ม.ค.", "ก.พ.", "มี.ค.", "เม.ย.", "พ.ค.", "มิ.ย.", "ก.ค.", "ส.ค.", "ก.ย.", "ต.ค.", "พ.ย.", "ธ.ค."], today: "วันนี้", suffix: [], meridiem: [] }; }(jQuery));
{ "pile_set_name": "Github" }
classes=80 train=./data/coco_1000img.txt valid=./data/coco_1000val.txt names=data/coco.names backup=backup/ eval=coco
{ "pile_set_name": "Github" }
/**************************************************************************** * net/socket/socket.c * * 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. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <sys/socket.h> #include <errno.h> #include <assert.h> #include <debug.h> #include "usrsock/usrsock.h" #include "socket/socket.h" #ifdef CONFIG_NET /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: psock_socket * * Description: * socket() creates an endpoint for communication and returns a socket * structure. * * Input Parameters: * domain (see sys/socket.h) * type (see sys/socket.h) * protocol (see sys/socket.h) * psock A pointer to a user allocated socket structure to be * initialized. * * Returned Value: * Returns zero (OK) on success. On failure, it returns a negated errno * value to indicate the nature of the error: * * EACCES * Permission to create a socket of the specified type and/or protocol * is denied. * EAFNOSUPPORT * The implementation does not support the specified address family. * EINVAL * Unknown protocol, or protocol family not available. * EMFILE * Process file table overflow. * ENFILE * The system limit on the total number of open files has been reached. * ENOBUFS or ENOMEM * Insufficient memory is available. The socket cannot be created until * sufficient resources are freed. * EPROTONOSUPPORT * The protocol type or the specified protocol is not supported within * this domain. * ****************************************************************************/ int psock_socket(int domain, int type, int protocol, FAR struct socket *psock) { FAR const struct sock_intf_s *sockif = NULL; int ret; /* Initialize the socket structure */ psock->s_crefs = 1; psock->s_domain = domain; psock->s_conn = NULL; #if defined(CONFIG_NET_TCP_WRITE_BUFFERS) || defined(CONFIG_NET_UDP_WRITE_BUFFERS) psock->s_sndcb = NULL; #endif if (type & SOCK_CLOEXEC) { psock->s_flags |= _SF_CLOEXEC; } if (type & SOCK_NONBLOCK) { psock->s_flags |= _SF_NONBLOCK; } type &= SOCK_TYPE_MASK; psock->s_type = type; #ifdef CONFIG_NET_USRSOCK if (domain != PF_LOCAL && domain != PF_UNSPEC) { /* Handle special setup for USRSOCK sockets (user-space networking * stack). */ ret = g_usrsock_sockif.si_setup(psock, protocol); psock->s_sockif = &g_usrsock_sockif; return ret; } #endif /* CONFIG_NET_USRSOCK */ /* Get the socket interface */ sockif = net_sockif(domain, type, protocol); if (sockif == NULL) { nerr("ERROR: socket address family unsupported: %d\n", domain); return -EAFNOSUPPORT; } /* The remaining of the socket initialization depends on the address * family. */ DEBUGASSERT(sockif->si_setup != NULL); psock->s_sockif = sockif; ret = sockif->si_setup(psock, protocol); if (ret < 0) { nerr("ERROR: socket si_setup() failed: %d\n", ret); return ret; } return OK; } /**************************************************************************** * Name: socket * * Description: * socket() creates an endpoint for communication and returns a descriptor. * * Input Parameters: * domain (see sys/socket.h) * type (see sys/socket.h) * protocol (see sys/socket.h) * * Returned Value: * A non-negative socket descriptor on success; -1 on error with errno set * appropriately. * * EACCES * Permission to create a socket of the specified type and/or protocol * is denied. * EAFNOSUPPORT * The implementation does not support the specified address family. * EINVAL * Unknown protocol, or protocol family not available. * EMFILE * Process file table overflow. * ENFILE * The system limit on the total number of open files has been reached. * ENOBUFS or ENOMEM * Insufficient memory is available. The socket cannot be created until * sufficient resources are freed. * EPROTONOSUPPORT * The protocol type or the specified protocol is not supported within * this domain. * * Assumptions: * ****************************************************************************/ int socket(int domain, int type, int protocol) { FAR struct socket *psock; int errcode; int sockfd; int ret; /* Allocate a socket descriptor */ sockfd = sockfd_allocate(0); if (sockfd < 0) { nerr("ERROR: Failed to allocate a socket descriptor\n"); errcode = ENFILE; goto errout; } /* Get the underlying socket structure */ psock = sockfd_socket(sockfd); if (!psock) { errcode = ENOSYS; /* should not happen */ goto errout_with_sockfd; } /* Initialize the socket structure */ ret = psock_socket(domain, type, protocol, psock); if (ret < 0) { nerr("ERROR: psock_socket() failed: %d\n", ret); errcode = -ret; goto errout_with_sockfd; } /* The socket has been successfully initialized */ psock->s_flags |= _SF_INITD; return sockfd; errout_with_sockfd: sockfd_release(sockfd); errout: set_errno(errcode); return ERROR; } #endif /* CONFIG_NET */
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 326628f9cad8d714e999eaf89d7f9041 folderAsset: yes DefaultImporter: externalObjects: {} userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
/* * Copyright (C) 2016 - 2018 ExoMedia Contributors * * 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.devbrackets.android.exomedia.core.video.mp; import android.content.Context; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.PlaybackParams; import android.net.Uri; import android.os.Build; import android.support.annotation.FloatRange; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.view.Surface; import com.devbrackets.android.exomedia.core.ListenerMux; import com.devbrackets.android.exomedia.core.exoplayer.WindowInfo; import com.devbrackets.android.exomedia.core.video.ClearableSurface; import java.io.IOException; import java.util.Map; import static android.content.ContentValues.TAG; /** * A delegated object used to handle the majority of the * functionality for the "Native" video view implementation * to simplify support for both the {@link android.view.TextureView} * and {@link android.view.SurfaceView} implementations */ @SuppressWarnings("WeakerAccess") public class NativeVideoDelegate { public interface Callback { void videoSizeChanged(int width, int height); } public enum State { ERROR, IDLE, PREPARING, PREPARED, PLAYING, PAUSED, COMPLETED } protected Map<String, String> headers; protected State currentState = State.IDLE; protected Context context; protected Callback callback; protected ClearableSurface clearableSurface; protected MediaPlayer mediaPlayer; protected boolean playRequested = false; protected long requestedSeek; protected int currentBufferPercent; @FloatRange(from = 0.0, to = 1.0) protected float requestedVolume = 1.0f; protected ListenerMux listenerMux; @NonNull protected InternalListeners internalListeners = new InternalListeners(); @Nullable protected MediaPlayer.OnCompletionListener onCompletionListener; @Nullable protected MediaPlayer.OnPreparedListener onPreparedListener; @Nullable protected MediaPlayer.OnBufferingUpdateListener onBufferingUpdateListener; @Nullable protected MediaPlayer.OnSeekCompleteListener onSeekCompleteListener; @Nullable protected MediaPlayer.OnErrorListener onErrorListener; @Nullable protected MediaPlayer.OnInfoListener onInfoListener; public NativeVideoDelegate(@NonNull Context context, @NonNull Callback callback, @NonNull ClearableSurface clearableSurface) { this.context = context; this.callback = callback; this.clearableSurface = clearableSurface; initMediaPlayer(); currentState = State.IDLE; } public void start() { if (isReady()) { mediaPlayer.start(); currentState = State.PLAYING; } playRequested = true; listenerMux.setNotifiedCompleted(false); } public void pause() { if (isReady() && mediaPlayer.isPlaying()) { mediaPlayer.pause(); currentState = State.PAUSED; } playRequested = false; } public long getDuration() { if (!listenerMux.isPrepared() || !isReady()) { return 0; } return mediaPlayer.getDuration(); } public long getCurrentPosition() { if (!listenerMux.isPrepared() || !isReady()) { return 0; } return mediaPlayer.getCurrentPosition(); } @FloatRange(from = 0.0, to = 1.0) public float getVolume() { return requestedVolume; } public boolean setVolume(@FloatRange(from = 0.0, to = 1.0) float volume) { requestedVolume = volume; mediaPlayer.setVolume(volume, volume); return true; } public void seekTo(long milliseconds) { if (isReady()) { mediaPlayer.seekTo((int) milliseconds); requestedSeek = 0; } else { requestedSeek = milliseconds; } } public boolean isPlaying() { return isReady() && mediaPlayer.isPlaying(); } public int getBufferPercentage() { if (mediaPlayer != null) { return currentBufferPercent; } return 0; } @Nullable public WindowInfo getWindowInfo() { return null; } public boolean setPlaybackSpeed(float speed) { // Marshmallow+ support setting the playback speed natively if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { PlaybackParams params = new PlaybackParams(); params.setSpeed(speed); mediaPlayer.setPlaybackParams(params); return true; } return false; } public float getPlaybackSpeed() { // Marshmallow+ support setting the playback speed natively if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return mediaPlayer.getPlaybackParams().getSpeed(); } return 1F; } /** * Performs the functionality to stop the video in playback * * @param clearSurface <code>true</code> if the surface should be cleared */ public void stopPlayback(boolean clearSurface) { currentState = State.IDLE; if (isReady()) { try { mediaPlayer.stop(); } catch (Exception e) { Log.d(TAG, "stopPlayback: error calling mediaPlayer.stop()", e); } } playRequested = false; if (clearSurface) { listenerMux.clearSurfaceWhenReady(clearableSurface); } } /** * Cleans up the resources being held. This should only be called when * destroying the video view */ public void suspend() { currentState = State.IDLE; try { mediaPlayer.reset(); mediaPlayer.release(); } catch (Exception e) { Log.d(TAG, "stopPlayback: error calling mediaPlayer.reset() or mediaPlayer.release()", e); } playRequested = false; } public boolean restart() { if (currentState != State.COMPLETED) { return false; } seekTo(0); start(); //Makes sure the listeners get the onPrepared callback listenerMux.setNotifiedPrepared(false); listenerMux.setNotifiedCompleted(false); return true; } /** * Sets video URI using specific headers. * * @param uri The Uri for the video to play * @param headers The headers for the URI request. * Note that the cross domain redirection is allowed by default, but that can be * changed with key/value pairs through the headers parameter with * "android-allow-cross-domain-redirect" as the key and "0" or "1" as the value * to disallow or allow cross domain redirection. */ public void setVideoURI(Uri uri, @Nullable Map<String, String> headers) { this.headers = headers; requestedSeek = 0; playRequested = false; openVideo(uri); } public void setListenerMux(ListenerMux listenerMux) { this.listenerMux = listenerMux; setOnCompletionListener(listenerMux); setOnPreparedListener(listenerMux); setOnBufferingUpdateListener(listenerMux); setOnSeekCompleteListener(listenerMux); setOnErrorListener(listenerMux); } /** * Register a callback to be invoked when the media file * is loaded and ready to go. * * @param listener The callback that will be run */ public void setOnPreparedListener(@Nullable MediaPlayer.OnPreparedListener listener) { onPreparedListener = listener; } /** * Register a callback to be invoked when the end of a media file * has been reached during playback. * * @param listener The callback that will be run */ public void setOnCompletionListener(@Nullable MediaPlayer.OnCompletionListener listener) { onCompletionListener = listener; } /** * Register a callback to be invoked when the status of a network * stream's buffer has changed. * * @param listener the callback that will be run. */ public void setOnBufferingUpdateListener(@Nullable MediaPlayer.OnBufferingUpdateListener listener) { onBufferingUpdateListener = listener; } /** * Register a callback to be invoked when a seek operation has been * completed. * * @param listener the callback that will be run */ public void setOnSeekCompleteListener(@Nullable MediaPlayer.OnSeekCompleteListener listener) { onSeekCompleteListener = listener; } /** * Register a callback to be invoked when an error occurs * during playback or setup. If no listener is specified, * or if the listener returned false, TextureVideoView will inform * the user of any errors. * * @param listener The callback that will be run */ public void setOnErrorListener(@Nullable MediaPlayer.OnErrorListener listener) { onErrorListener = listener; } /** * Register a callback to be invoked when an informational event * occurs during playback or setup. * * @param listener The callback that will be run */ public void setOnInfoListener(@Nullable MediaPlayer.OnInfoListener listener) { onInfoListener = listener; } public void onSurfaceSizeChanged(int width, int height) { if (mediaPlayer == null || width <= 0 || height <= 0) { return; } if (requestedSeek != 0) { seekTo(requestedSeek); } if (playRequested) { start(); } } public void onSurfaceReady(Surface surface) { mediaPlayer.setSurface(surface); if (playRequested) { start(); } } protected void initMediaPlayer() { mediaPlayer = new MediaPlayer(); mediaPlayer.setOnInfoListener(internalListeners); mediaPlayer.setOnErrorListener(internalListeners); mediaPlayer.setOnPreparedListener(internalListeners); mediaPlayer.setOnCompletionListener(internalListeners); mediaPlayer.setOnSeekCompleteListener(internalListeners); mediaPlayer.setOnBufferingUpdateListener(internalListeners); mediaPlayer.setOnVideoSizeChangedListener(internalListeners); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.setScreenOnWhilePlaying(true); } protected boolean isReady() { return currentState != State.ERROR && currentState != State.IDLE && currentState != State.PREPARING; } protected void openVideo(@Nullable Uri uri) { if (uri == null) { return; } currentBufferPercent = 0; try { mediaPlayer.reset(); mediaPlayer.setDataSource(context.getApplicationContext(), uri, headers); mediaPlayer.prepareAsync(); currentState = State.PREPARING; } catch (IOException | IllegalArgumentException ex) { Log.w(TAG, "Unable to open content: " + uri, ex); currentState = State.ERROR; internalListeners.onError(mediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0); } } public class InternalListeners implements MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnErrorListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnSeekCompleteListener, MediaPlayer.OnInfoListener, MediaPlayer.OnVideoSizeChangedListener { @Override public void onBufferingUpdate(MediaPlayer mp, int percent) { currentBufferPercent = percent; if (onBufferingUpdateListener != null) { onBufferingUpdateListener.onBufferingUpdate(mp, percent); } } @Override public void onCompletion(MediaPlayer mp) { currentState = State.COMPLETED; if (onCompletionListener != null) { onCompletionListener.onCompletion(mediaPlayer); } } @Override public void onSeekComplete(MediaPlayer mp) { if (onSeekCompleteListener != null) { onSeekCompleteListener.onSeekComplete(mp); } } @Override public boolean onError(MediaPlayer mp, int what, int extra) { Log.d(TAG, "Error: " + what + "," + extra); currentState = State.ERROR; return onErrorListener == null || onErrorListener.onError(mediaPlayer, what, extra); } @Override public void onPrepared(MediaPlayer mp) { currentState = State.PREPARED; if (onPreparedListener != null) { onPreparedListener.onPrepared(mediaPlayer); } callback.videoSizeChanged(mp.getVideoWidth(), mp.getVideoHeight()); if (requestedSeek != 0) { seekTo(requestedSeek); } if (playRequested) { start(); } } @Override public boolean onInfo(MediaPlayer mp, int what, int extra) { return onInfoListener == null || onInfoListener.onInfo(mp, what, extra); } @Override public void onVideoSizeChanged(MediaPlayer mp, int width, int height) { callback.videoSizeChanged(mp.getVideoWidth(), mp.getVideoHeight()); } } }
{ "pile_set_name": "Github" }
using System; using UIKit; namespace Xamarin.Forms.Platform.iOS.UnitTests { internal static class ColorComparison { public static bool ARGBEquivalent(UIColor color1, UIColor color2) { color1.GetRGBA(out nfloat red1, out nfloat green1, out nfloat blue1, out nfloat alpha1); color2.GetRGBA(out nfloat red2, out nfloat green2, out nfloat blue2, out nfloat alpha2); const double tolerance = 0.000001; return Equal(red1, red2, tolerance) && Equal(green1, green2, tolerance) && Equal(blue1, blue2, tolerance) && Equal(alpha1, alpha2, tolerance); } static bool Equal(nfloat v1, nfloat v2, double tolerance) { return Math.Abs(v1 - v2) <= tolerance; } } }
{ "pile_set_name": "Github" }
/******************************************************************************/ #ifdef JEMALLOC_H_TYPES #endif /* JEMALLOC_H_TYPES */ /******************************************************************************/ #ifdef JEMALLOC_H_STRUCTS #endif /* JEMALLOC_H_STRUCTS */ /******************************************************************************/ #ifdef JEMALLOC_H_EXTERNS void *pages_map(void *addr, size_t size); void pages_unmap(void *addr, size_t size); void *pages_trim(void *addr, size_t alloc_size, size_t leadsize, size_t size); bool pages_commit(void *addr, size_t size); bool pages_decommit(void *addr, size_t size); bool pages_purge(void *addr, size_t size); #endif /* JEMALLOC_H_EXTERNS */ /******************************************************************************/ #ifdef JEMALLOC_H_INLINES #endif /* JEMALLOC_H_INLINES */ /******************************************************************************/
{ "pile_set_name": "Github" }
#ifndef VP8_RTCD_H_ #define VP8_RTCD_H_ #ifdef RTCD_C #define RTCD_EXTERN #else #define RTCD_EXTERN extern #endif /* * VP8 */ struct blockd; struct macroblockd; struct loop_filter_info; /* Encoder forward decls */ struct block; struct macroblock; struct variance_vtable; union int_mv; struct yv12_buffer_config; #ifdef __cplusplus extern "C" { #endif void vp8_bilinear_predict16x16_c(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch); void vp8_bilinear_predict16x16_sse2(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch); void vp8_bilinear_predict16x16_ssse3(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch); RTCD_EXTERN void (*vp8_bilinear_predict16x16)(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch); void vp8_bilinear_predict4x4_c(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch); void vp8_bilinear_predict4x4_mmx(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch); #define vp8_bilinear_predict4x4 vp8_bilinear_predict4x4_mmx void vp8_bilinear_predict8x4_c(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch); void vp8_bilinear_predict8x4_mmx(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch); #define vp8_bilinear_predict8x4 vp8_bilinear_predict8x4_mmx void vp8_bilinear_predict8x8_c(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch); void vp8_bilinear_predict8x8_sse2(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch); void vp8_bilinear_predict8x8_ssse3(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch); RTCD_EXTERN void (*vp8_bilinear_predict8x8)(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch); void vp8_blend_b_c(unsigned char *y, unsigned char *u, unsigned char *v, int y1, int u1, int v1, int alpha, int stride); #define vp8_blend_b vp8_blend_b_c void vp8_blend_mb_inner_c(unsigned char *y, unsigned char *u, unsigned char *v, int y1, int u1, int v1, int alpha, int stride); #define vp8_blend_mb_inner vp8_blend_mb_inner_c void vp8_blend_mb_outer_c(unsigned char *y, unsigned char *u, unsigned char *v, int y1, int u1, int v1, int alpha, int stride); #define vp8_blend_mb_outer vp8_blend_mb_outer_c int vp8_block_error_c(short *coeff, short *dqcoeff); int vp8_block_error_sse2(short *coeff, short *dqcoeff); #define vp8_block_error vp8_block_error_sse2 void vp8_copy32xn_c(const unsigned char *src_ptr, int source_stride, unsigned char *dst_ptr, int dst_stride, int n); void vp8_copy32xn_sse2(const unsigned char *src_ptr, int source_stride, unsigned char *dst_ptr, int dst_stride, int n); void vp8_copy32xn_sse3(const unsigned char *src_ptr, int source_stride, unsigned char *dst_ptr, int dst_stride, int n); RTCD_EXTERN void (*vp8_copy32xn)(const unsigned char *src_ptr, int source_stride, unsigned char *dst_ptr, int dst_stride, int n); void vp8_copy_mem16x16_c(unsigned char *src, int src_pitch, unsigned char *dst, int dst_pitch); void vp8_copy_mem16x16_sse2(unsigned char *src, int src_pitch, unsigned char *dst, int dst_pitch); #define vp8_copy_mem16x16 vp8_copy_mem16x16_sse2 void vp8_copy_mem8x4_c(unsigned char *src, int src_pitch, unsigned char *dst, int dst_pitch); void vp8_copy_mem8x4_mmx(unsigned char *src, int src_pitch, unsigned char *dst, int dst_pitch); #define vp8_copy_mem8x4 vp8_copy_mem8x4_mmx void vp8_copy_mem8x8_c(unsigned char *src, int src_pitch, unsigned char *dst, int dst_pitch); void vp8_copy_mem8x8_mmx(unsigned char *src, int src_pitch, unsigned char *dst, int dst_pitch); #define vp8_copy_mem8x8 vp8_copy_mem8x8_mmx void vp8_dc_only_idct_add_c(short input, unsigned char *pred, int pred_stride, unsigned char *dst, int dst_stride); void vp8_dc_only_idct_add_mmx(short input, unsigned char *pred, int pred_stride, unsigned char *dst, int dst_stride); #define vp8_dc_only_idct_add vp8_dc_only_idct_add_mmx int vp8_denoiser_filter_c(unsigned char *mc_running_avg_y, int mc_avg_y_stride, unsigned char *running_avg_y, int avg_y_stride, unsigned char *sig, int sig_stride, unsigned int motion_magnitude, int increase_denoising); int vp8_denoiser_filter_sse2(unsigned char *mc_running_avg_y, int mc_avg_y_stride, unsigned char *running_avg_y, int avg_y_stride, unsigned char *sig, int sig_stride, unsigned int motion_magnitude, int increase_denoising); #define vp8_denoiser_filter vp8_denoiser_filter_sse2 int vp8_denoiser_filter_uv_c(unsigned char *mc_running_avg, int mc_avg_stride, unsigned char *running_avg, int avg_stride, unsigned char *sig, int sig_stride, unsigned int motion_magnitude, int increase_denoising); int vp8_denoiser_filter_uv_sse2(unsigned char *mc_running_avg, int mc_avg_stride, unsigned char *running_avg, int avg_stride, unsigned char *sig, int sig_stride, unsigned int motion_magnitude, int increase_denoising); #define vp8_denoiser_filter_uv vp8_denoiser_filter_uv_sse2 void vp8_dequant_idct_add_c(short *input, short *dq, unsigned char *output, int stride); void vp8_dequant_idct_add_mmx(short *input, short *dq, unsigned char *output, int stride); #define vp8_dequant_idct_add vp8_dequant_idct_add_mmx void vp8_dequant_idct_add_uv_block_c(short *q, short *dq, unsigned char *dst_u, unsigned char *dst_v, int stride, char *eobs); void vp8_dequant_idct_add_uv_block_sse2(short *q, short *dq, unsigned char *dst_u, unsigned char *dst_v, int stride, char *eobs); #define vp8_dequant_idct_add_uv_block vp8_dequant_idct_add_uv_block_sse2 void vp8_dequant_idct_add_y_block_c(short *q, short *dq, unsigned char *dst, int stride, char *eobs); void vp8_dequant_idct_add_y_block_sse2(short *q, short *dq, unsigned char *dst, int stride, char *eobs); #define vp8_dequant_idct_add_y_block vp8_dequant_idct_add_y_block_sse2 void vp8_dequantize_b_c(struct blockd*, short *dqc); void vp8_dequantize_b_mmx(struct blockd*, short *dqc); #define vp8_dequantize_b vp8_dequantize_b_mmx int vp8_diamond_search_sad_c(struct macroblock *x, struct block *b, struct blockd *d, union int_mv *ref_mv, union int_mv *best_mv, int search_param, int sad_per_bit, int *num00, struct variance_vtable *fn_ptr, int *mvcost[2], union int_mv *center_mv); int vp8_diamond_search_sadx4(struct macroblock *x, struct block *b, struct blockd *d, union int_mv *ref_mv, union int_mv *best_mv, int search_param, int sad_per_bit, int *num00, struct variance_vtable *fn_ptr, int *mvcost[2], union int_mv *center_mv); #define vp8_diamond_search_sad vp8_diamond_search_sadx4 void vp8_fast_quantize_b_c(struct block *, struct blockd *); void vp8_fast_quantize_b_sse2(struct block *, struct blockd *); void vp8_fast_quantize_b_ssse3(struct block *, struct blockd *); RTCD_EXTERN void (*vp8_fast_quantize_b)(struct block *, struct blockd *); void vp8_filter_by_weight16x16_c(unsigned char *src, int src_stride, unsigned char *dst, int dst_stride, int src_weight); void vp8_filter_by_weight16x16_sse2(unsigned char *src, int src_stride, unsigned char *dst, int dst_stride, int src_weight); #define vp8_filter_by_weight16x16 vp8_filter_by_weight16x16_sse2 void vp8_filter_by_weight4x4_c(unsigned char *src, int src_stride, unsigned char *dst, int dst_stride, int src_weight); #define vp8_filter_by_weight4x4 vp8_filter_by_weight4x4_c void vp8_filter_by_weight8x8_c(unsigned char *src, int src_stride, unsigned char *dst, int dst_stride, int src_weight); void vp8_filter_by_weight8x8_sse2(unsigned char *src, int src_stride, unsigned char *dst, int dst_stride, int src_weight); #define vp8_filter_by_weight8x8 vp8_filter_by_weight8x8_sse2 int vp8_full_search_sad_c(struct macroblock *x, struct block *b, struct blockd *d, union int_mv *ref_mv, int sad_per_bit, int distance, struct variance_vtable *fn_ptr, int *mvcost[2], union int_mv *center_mv); int vp8_full_search_sadx3(struct macroblock *x, struct block *b, struct blockd *d, union int_mv *ref_mv, int sad_per_bit, int distance, struct variance_vtable *fn_ptr, int *mvcost[2], union int_mv *center_mv); int vp8_full_search_sadx8(struct macroblock *x, struct block *b, struct blockd *d, union int_mv *ref_mv, int sad_per_bit, int distance, struct variance_vtable *fn_ptr, int *mvcost[2], union int_mv *center_mv); RTCD_EXTERN int (*vp8_full_search_sad)(struct macroblock *x, struct block *b, struct blockd *d, union int_mv *ref_mv, int sad_per_bit, int distance, struct variance_vtable *fn_ptr, int *mvcost[2], union int_mv *center_mv); void vp8_loop_filter_bh_c(unsigned char *y, unsigned char *u, unsigned char *v, int ystride, int uv_stride, struct loop_filter_info *lfi); void vp8_loop_filter_bh_sse2(unsigned char *y, unsigned char *u, unsigned char *v, int ystride, int uv_stride, struct loop_filter_info *lfi); #define vp8_loop_filter_bh vp8_loop_filter_bh_sse2 void vp8_loop_filter_bv_c(unsigned char *y, unsigned char *u, unsigned char *v, int ystride, int uv_stride, struct loop_filter_info *lfi); void vp8_loop_filter_bv_sse2(unsigned char *y, unsigned char *u, unsigned char *v, int ystride, int uv_stride, struct loop_filter_info *lfi); #define vp8_loop_filter_bv vp8_loop_filter_bv_sse2 void vp8_loop_filter_mbh_c(unsigned char *y, unsigned char *u, unsigned char *v, int ystride, int uv_stride, struct loop_filter_info *lfi); void vp8_loop_filter_mbh_sse2(unsigned char *y, unsigned char *u, unsigned char *v, int ystride, int uv_stride, struct loop_filter_info *lfi); #define vp8_loop_filter_mbh vp8_loop_filter_mbh_sse2 void vp8_loop_filter_mbv_c(unsigned char *y, unsigned char *u, unsigned char *v, int ystride, int uv_stride, struct loop_filter_info *lfi); void vp8_loop_filter_mbv_sse2(unsigned char *y, unsigned char *u, unsigned char *v, int ystride, int uv_stride, struct loop_filter_info *lfi); #define vp8_loop_filter_mbv vp8_loop_filter_mbv_sse2 void vp8_loop_filter_bhs_c(unsigned char *y, int ystride, const unsigned char *blimit); void vp8_loop_filter_bhs_sse2(unsigned char *y, int ystride, const unsigned char *blimit); #define vp8_loop_filter_simple_bh vp8_loop_filter_bhs_sse2 void vp8_loop_filter_bvs_c(unsigned char *y, int ystride, const unsigned char *blimit); void vp8_loop_filter_bvs_sse2(unsigned char *y, int ystride, const unsigned char *blimit); #define vp8_loop_filter_simple_bv vp8_loop_filter_bvs_sse2 void vp8_loop_filter_simple_horizontal_edge_c(unsigned char *y, int ystride, const unsigned char *blimit); void vp8_loop_filter_simple_horizontal_edge_sse2(unsigned char *y, int ystride, const unsigned char *blimit); #define vp8_loop_filter_simple_mbh vp8_loop_filter_simple_horizontal_edge_sse2 void vp8_loop_filter_simple_vertical_edge_c(unsigned char *y, int ystride, const unsigned char *blimit); void vp8_loop_filter_simple_vertical_edge_sse2(unsigned char *y, int ystride, const unsigned char *blimit); #define vp8_loop_filter_simple_mbv vp8_loop_filter_simple_vertical_edge_sse2 int vp8_mbblock_error_c(struct macroblock *mb, int dc); int vp8_mbblock_error_sse2(struct macroblock *mb, int dc); #define vp8_mbblock_error vp8_mbblock_error_sse2 int vp8_mbuverror_c(struct macroblock *mb); int vp8_mbuverror_sse2(struct macroblock *mb); #define vp8_mbuverror vp8_mbuverror_sse2 int vp8_refining_search_sad_c(struct macroblock *x, struct block *b, struct blockd *d, union int_mv *ref_mv, int sad_per_bit, int distance, struct variance_vtable *fn_ptr, int *mvcost[2], union int_mv *center_mv); int vp8_refining_search_sadx4(struct macroblock *x, struct block *b, struct blockd *d, union int_mv *ref_mv, int sad_per_bit, int distance, struct variance_vtable *fn_ptr, int *mvcost[2], union int_mv *center_mv); #define vp8_refining_search_sad vp8_refining_search_sadx4 void vp8_regular_quantize_b_c(struct block *, struct blockd *); void vp8_regular_quantize_b_sse2(struct block *, struct blockd *); void vp8_regular_quantize_b_sse4_1(struct block *, struct blockd *); RTCD_EXTERN void (*vp8_regular_quantize_b)(struct block *, struct blockd *); void vp8_short_fdct4x4_c(short *input, short *output, int pitch); void vp8_short_fdct4x4_sse2(short *input, short *output, int pitch); #define vp8_short_fdct4x4 vp8_short_fdct4x4_sse2 void vp8_short_fdct8x4_c(short *input, short *output, int pitch); void vp8_short_fdct8x4_sse2(short *input, short *output, int pitch); #define vp8_short_fdct8x4 vp8_short_fdct8x4_sse2 void vp8_short_idct4x4llm_c(short *input, unsigned char *pred, int pitch, unsigned char *dst, int dst_stride); void vp8_short_idct4x4llm_mmx(short *input, unsigned char *pred, int pitch, unsigned char *dst, int dst_stride); #define vp8_short_idct4x4llm vp8_short_idct4x4llm_mmx void vp8_short_inv_walsh4x4_c(short *input, short *output); void vp8_short_inv_walsh4x4_sse2(short *input, short *output); #define vp8_short_inv_walsh4x4 vp8_short_inv_walsh4x4_sse2 void vp8_short_inv_walsh4x4_1_c(short *input, short *output); #define vp8_short_inv_walsh4x4_1 vp8_short_inv_walsh4x4_1_c void vp8_short_walsh4x4_c(short *input, short *output, int pitch); void vp8_short_walsh4x4_sse2(short *input, short *output, int pitch); #define vp8_short_walsh4x4 vp8_short_walsh4x4_sse2 void vp8_sixtap_predict16x16_c(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch); void vp8_sixtap_predict16x16_sse2(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch); void vp8_sixtap_predict16x16_ssse3(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch); RTCD_EXTERN void (*vp8_sixtap_predict16x16)(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch); void vp8_sixtap_predict4x4_c(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch); void vp8_sixtap_predict4x4_mmx(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch); void vp8_sixtap_predict4x4_ssse3(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch); RTCD_EXTERN void (*vp8_sixtap_predict4x4)(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch); void vp8_sixtap_predict8x4_c(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch); void vp8_sixtap_predict8x4_sse2(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch); void vp8_sixtap_predict8x4_ssse3(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch); RTCD_EXTERN void (*vp8_sixtap_predict8x4)(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch); void vp8_sixtap_predict8x8_c(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch); void vp8_sixtap_predict8x8_sse2(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch); void vp8_sixtap_predict8x8_ssse3(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch); RTCD_EXTERN void (*vp8_sixtap_predict8x8)(unsigned char *src, int src_pitch, int xofst, int yofst, unsigned char *dst, int dst_pitch); void vp8_rtcd(void); #ifdef RTCD_C #include "vpx_ports/x86.h" static void setup_rtcd_internal(void) { int flags = x86_simd_caps(); (void)flags; vp8_bilinear_predict16x16 = vp8_bilinear_predict16x16_sse2; if (flags & HAS_SSSE3) vp8_bilinear_predict16x16 = vp8_bilinear_predict16x16_ssse3; vp8_bilinear_predict8x8 = vp8_bilinear_predict8x8_sse2; if (flags & HAS_SSSE3) vp8_bilinear_predict8x8 = vp8_bilinear_predict8x8_ssse3; vp8_copy32xn = vp8_copy32xn_sse2; if (flags & HAS_SSE3) vp8_copy32xn = vp8_copy32xn_sse3; vp8_fast_quantize_b = vp8_fast_quantize_b_sse2; if (flags & HAS_SSSE3) vp8_fast_quantize_b = vp8_fast_quantize_b_ssse3; vp8_full_search_sad = vp8_full_search_sad_c; if (flags & HAS_SSE3) vp8_full_search_sad = vp8_full_search_sadx3; if (flags & HAS_SSE4_1) vp8_full_search_sad = vp8_full_search_sadx8; vp8_regular_quantize_b = vp8_regular_quantize_b_sse2; if (flags & HAS_SSE4_1) vp8_regular_quantize_b = vp8_regular_quantize_b_sse4_1; vp8_sixtap_predict16x16 = vp8_sixtap_predict16x16_sse2; if (flags & HAS_SSSE3) vp8_sixtap_predict16x16 = vp8_sixtap_predict16x16_ssse3; vp8_sixtap_predict4x4 = vp8_sixtap_predict4x4_mmx; if (flags & HAS_SSSE3) vp8_sixtap_predict4x4 = vp8_sixtap_predict4x4_ssse3; vp8_sixtap_predict8x4 = vp8_sixtap_predict8x4_sse2; if (flags & HAS_SSSE3) vp8_sixtap_predict8x4 = vp8_sixtap_predict8x4_ssse3; vp8_sixtap_predict8x8 = vp8_sixtap_predict8x8_sse2; if (flags & HAS_SSSE3) vp8_sixtap_predict8x8 = vp8_sixtap_predict8x8_ssse3; } #endif #ifdef __cplusplus } // extern "C" #endif #endif
{ "pile_set_name": "Github" }
<template> <div> <base-title title="Classes" /> <base-table :columns="columns" :rows="rows" /> </div> </template> <script> import BaseTable from '../base/Table' import BaseTitle from '../BaseTitle' export default { components: { BaseTable, BaseTitle }, data () { return { columns: [ { attr: 'name', name: 'Name' }, { attr: 'description', name: 'Description' } ], rows: [ { name: 'vsm-mob-hide', description: 'Hide HTML elements in mobile design' }, { name: 'vsm-mob-full', description: 'Add flex-grow: 1, see Demo example' } ] } } } </script>
{ "pile_set_name": "Github" }
.page-body-wrapper { flex-grow: 1; } .animation-element-wrapper { display: block; margin-bottom: 100rpx; } .animation-element { width: 200rpx; height: 200rpx; background-color: #1AAD19; } .animation-buttons { padding: 50rpx 50rpx 10rpx; border-top: 1px solid #ccc; display: flex; flex-grow: 1; overflow-y: scroll; flex-direction: row; flex-wrap: wrap; width: 100%; height: 400rpx; box-sizing: border-box; } .animation-button { width: 290rpx; margin: 20rpx auto; } .animation-button-reset { width: 610rpx; margin: 20rpx auto; } page { background-color: #fbf9fe; height: 100%; } .container { display: flex; flex-direction: column; min-height: 100%; justify-content: space-between; } .page-header { display: flex; font-size: 32rpx; color: #aaa; margin-top: 50rpx; flex-direction: column; align-items: center; } .page-header-text { padding: 20rpx 40rpx; } .page-header-line { width: 150rpx; height: 1px; border-bottom: 1px solid #ccc; } .page-body { width: 100%; display: flex; flex-direction: column; align-items: center; flex-grow: 1; overflow-x: hidden; } .page-body-wrapper { margin-top: 100rpx; display: flex; flex-direction: column; align-items: center; width: 100%; } .page-body-wrapper form { width: 100%; } .page-body-wording { text-align: center; padding: 200rpx 100rpx; } .page-body-info { display: flex; flex-direction: column; align-items: center; background-color: #fff; margin-bottom: 50rpx; width: 100%; padding: 50rpx 0 150rpx 0; } .page-body-title { margin-bottom: 100rpx; font-size: 32rpx; } .page-body-text { font-size: 30rpx; line-height: 26px; color: #ccc; } .page-body-text-small { font-size: 24rpx; color: #000; margin-bottom: 100rpx; } .page-body-form { width: 100%; background-color: #fff; display: flex; flex-direction: column; width: 100%; border: 1px solid #eee; } .page-body-form-item { display: flex; align-items: center; margin-left: 30rpx; border-bottom: 1px solid #eee; height: 88rpx; font-size: 34rpx; } .page-body-form-key { width: 180rpx; color: #000; } .page-body-form-value { flex-grow: 1; } .page-body-form-value .input-placeholder { color: #b2b2b2; } .page-body-form-picker { display: flex; justify-content: space-between; height: 100rpx; align-items: center; font-size: 36rpx; margin-left: 20rpx; padding-right: 20rpx; border-bottom: 1px solid #eee; } .page-body-form-picker-value { color: #ccc; } .page-body-buttons { width: 100%; } .page-body-button { margin: 25rpx; } .page-body-button image { width: 150rpx; height: 150rpx; } .page-footer { text-align: center; color: #1aad19; font-size: 24rpx; margin: 20rpx 0; } .green{ color: #09BB07; } .red{ color: #F76260; } .blue{ color: #10AEFF; } .yellow{ color: #FFBE00; } .gray{ color: #C9C9C9; } .strong{ font-weight: bold; } .bc_green{ background-color: #09BB07; } .bc_red{ background-color: #F76260; } .bc_blue{ background-color: #10AEFF; } .bc_yellow{ background-color: #FFBE00; } .bc_gray{ background-color: #C9C9C9; } .tc{ text-align: center; } .page input{ padding: 20rpx 30rpx; background-color: #fff; } checkbox, radio{ margin-right: 10rpx; } .btn-area{ padding: 0 30px; } .btn-area button{ margin-top: 20rpx; margin-bottom: 20rpx; } .page { min-height: 100%; flex: 1; background-color: #FBF9FE; font-size: 32rpx; font-family: -apple-system-font,Helvetica Neue,Helvetica,sans-serif; overflow: hidden; } .page__hd{ padding: 50rpx 50rpx 100rpx 50rpx; text-align: center; } .page__title{ display: inline-block; padding: 20rpx 40rpx; font-size: 32rpx; color: #AAAAAA; border-bottom: 1px solid #CCCCCC; } .page__desc{ display: none; margin-top: 20rpx; font-size: 26rpx; color: #BBBBBB; } .section{ margin-bottom: 80rpx; } .section_gap{ padding: 0 30rpx; } .section__title{ margin-bottom: 16rpx; padding-left: 30rpx; padding-right: 30rpx; } .section_gap .section__title{ padding-left: 0; padding-right: 0; } .section__ctn{ }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2009-2020 Lightbend Inc. <https://www.lightbend.com> */ package akka.io import java.lang.{ Iterable => JIterable } import java.net.InetSocketAddress import scala.collection.immutable import com.github.ghik.silencer.silent import akka.actor._ import akka.io.Inet.SocketOption import akka.io.Udp.UdpSettings import akka.util.ByteString import akka.util.ccompat._ /** * UDP Extension for Akka’s IO layer. * * This extension implements the connectionless UDP protocol with * calling `connect` on the underlying sockets, i.e. with restricting * from whom data can be received. For “unconnected” UDP mode see [[Udp]]. * * For a full description of the design and philosophy behind this IO * implementation please refer to <a href="http://doc.akka.io/">the Akka online documentation</a>. * * The Java API for generating UDP commands is available at [[UdpConnectedMessage]]. */ @ccompatUsedUntil213 object UdpConnected extends ExtensionId[UdpConnectedExt] with ExtensionIdProvider { override def lookup = UdpConnected override def createExtension(system: ExtendedActorSystem): UdpConnectedExt = new UdpConnectedExt(system) /** * Java API: retrieve the UdpConnected extension for the given system. */ override def get(system: ActorSystem): UdpConnectedExt = super.get(system) override def get(system: ClassicActorSystemProvider): UdpConnectedExt = super.get(system) /** * The common interface for [[Command]] and [[Event]]. */ sealed trait Message /** * The common type of all commands supported by the UDP implementation. */ trait Command extends SelectionHandler.HasFailureMessage with Message { def failureMessage = CommandFailed(this) } /** * Each [[Send]] can optionally request a positive acknowledgment to be sent * to the commanding actor. If such notification is not desired the [[Send#ack]] * must be set to an instance of this class. The token contained within can be used * to recognize which write failed when receiving a [[CommandFailed]] message. */ case class NoAck(token: Any) extends Event /** * Default [[NoAck]] instance which is used when no acknowledgment information is * explicitly provided. Its “token” is `null`. */ object NoAck extends NoAck(null) /** * This message is understood by the connection actors to send data to their * designated destination. The connection actor will respond with * [[CommandFailed]] if the send could not be enqueued to the O/S kernel * because the send buffer was full. If the given `ack` is not of type [[NoAck]] * the connection actor will reply with the given object as soon as the datagram * has been successfully enqueued to the O/S kernel. */ final case class Send(payload: ByteString, ack: Any) extends Command { require( ack != null, "ack must be non-null. Use NoAck if you don't want acks.") def wantsAck: Boolean = !ack.isInstanceOf[NoAck] } object Send { def apply(data: ByteString): Send = Send(data, NoAck) } /** * Send this message to the [[UdpExt#manager]] in order to bind to a local * port (optionally with the chosen `localAddress`) and create a UDP socket * which is restricted to sending to and receiving from the given `remoteAddress`. * All received datagrams will be sent to the designated `handler` actor. */ @silent("deprecated") final case class Connect( handler: ActorRef, remoteAddress: InetSocketAddress, localAddress: Option[InetSocketAddress] = None, options: immutable.Traversable[SocketOption] = Nil) extends Command /** * Send this message to a connection actor (which had previously sent the * [[Connected]] message) in order to close the socket. The connection actor * will reply with a [[Disconnected]] message. */ case object Disconnect extends Command /** * Send this message to a listener actor (which sent a [[Udp.Bound]] message) to * have it stop reading datagrams from the network. If the O/S kernel’s receive * buffer runs full then subsequent datagrams will be silently discarded. * Re-enable reading from the socket using the `ResumeReading` command. */ case object SuspendReading extends Command /** * This message must be sent to the listener actor to re-enable reading from * the socket after a `SuspendReading` command. */ case object ResumeReading extends Command /** * The common type of all events emitted by the UDP implementation. */ trait Event extends Message /** * When a connection actor receives a datagram from its socket it will send * it to the handler designated in the [[Udp.Bind]] message using this message type. */ final case class Received(data: ByteString) extends Event /** * When a command fails it will be replied to with this message type, * wrapping the failing command object. */ final case class CommandFailed(cmd: Command) extends Event /** * This message is sent by the connection actor to the actor which sent the * [[Connect]] message when the UDP socket has been bound to the local and * remote addresses given. */ sealed trait Connected extends Event case object Connected extends Connected /** * This message is sent by the connection actor to the actor which sent the * `Disconnect` message when the UDP socket has been closed. */ sealed trait Disconnected extends Event case object Disconnected extends Disconnected } class UdpConnectedExt(system: ExtendedActorSystem) extends IO.Extension { val settings: UdpSettings = new UdpSettings(system.settings.config.getConfig("akka.io.udp-connected")) val manager: ActorRef = { system.systemActorOf( props = Props(classOf[UdpConnectedManager], this) .withDispatcher(settings.ManagementDispatcher) .withDeploy(Deploy.local), name = "IO-UDP-CONN") } /** * Java API: retrieve the UDP manager actor’s reference. */ def getManager: ActorRef = manager val bufferPool: BufferPool = new DirectByteBufferPool(settings.DirectBufferSize, settings.MaxDirectBufferPoolSize) } /** * Java API: factory methods for the message types used when communicating with the UdpConnected service. */ object UdpConnectedMessage { import UdpConnected._ import language.implicitConversions /** * Send this message to the [[UdpExt#manager]] in order to bind to a local * port (optionally with the chosen `localAddress`) and create a UDP socket * which is restricted to sending to and receiving from the given `remoteAddress`. * All received datagrams will be sent to the designated `handler` actor. */ def connect( handler: ActorRef, remoteAddress: InetSocketAddress, localAddress: InetSocketAddress, options: JIterable[SocketOption]): Command = Connect(handler, remoteAddress, Some(localAddress), options) /** * Connect without specifying the `localAddress`. */ def connect(handler: ActorRef, remoteAddress: InetSocketAddress, options: JIterable[SocketOption]): Command = Connect(handler, remoteAddress, None, options) /** * Connect without specifying the `localAddress` or `options`. */ def connect(handler: ActorRef, remoteAddress: InetSocketAddress): Command = Connect(handler, remoteAddress, None, Nil) /** * This message is understood by the connection actors to send data to their * designated destination. The connection actor will respond with * [[UdpConnected.CommandFailed]] if the send could not be enqueued to the O/S kernel * because the send buffer was full. If the given `ack` is not of type [[UdpConnected.NoAck]] * the connection actor will reply with the given object as soon as the datagram * has been successfully enqueued to the O/S kernel. */ def send(data: ByteString, ack: AnyRef): Command = Send(data, ack) /** * Send without requesting acknowledgment. */ def send(data: ByteString): Command = Send(data) /** * Send this message to a connection actor (which had previously sent the * [[UdpConnected.Connected]] message) in order to close the socket. The connection actor * will reply with a [[UdpConnected.Disconnected]] message. */ def disconnect: Command = Disconnect /** * Each [[UdpConnected.Send]] can optionally request a positive acknowledgment to be sent * to the commanding actor. If such notification is not desired the [[UdpConnected.Send#ack]] * must be set to an instance of this class. The token contained within can be used * to recognize which write failed when receiving a [[UdpConnected.CommandFailed]] message. */ def noAck(token: AnyRef): NoAck = NoAck(token) /** * Default [[UdpConnected.NoAck]] instance which is used when no acknowledgment information is * explicitly provided. Its “token” is `null`. */ def noAck: NoAck = NoAck /** * Send this message to a listener actor (which sent a [[Udp.Bound]] message) to * have it stop reading datagrams from the network. If the O/S kernel’s receive * buffer runs full then subsequent datagrams will be silently discarded. * Re-enable reading from the socket using the `UdpConnected.ResumeReading` command. */ def suspendReading: Command = SuspendReading /** * This message must be sent to the listener actor to re-enable reading from * the socket after a `UdpConnected.SuspendReading` command. */ def resumeReading: Command = ResumeReading implicit private def fromJava[T](coll: JIterable[T]): immutable.Iterable[T] = { import akka.util.ccompat.JavaConverters._ coll.asScala.to(immutable.Iterable) } }
{ "pile_set_name": "Github" }
var falafel = require('falafel'); var test = require('../'); test('array', function (t) { t.plan(8); var src = '(' + function () { var xs = [ 1, 2, [ 3, 4 ] ]; var ys = [ 5, 6 ]; g([ xs, ys ]); } + ')()'; var output = falafel(src, function (node) { if (node.type === 'ArrayExpression') { node.update('fn(' + node.source() + ')'); } }); var arrays = [ [ 3, 4 ], [ 1, 2, [ 3, 4 ] ], [ 5, 6 ], [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ], ]; Function(['fn','g'], output)( function (xs) { t.same(arrays.shift(), xs); return xs; }, function (xs) { t.same(xs, [ [ 1, 2, [ 3, 4 ] ], [ 5, 6 ] ]); } ); });
{ "pile_set_name": "Github" }
<?php /** * Hoa * * * @license * * New BSD License * * Copyright © 2007-2017, Hoa community. 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 Hoa 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 HOLDERS AND 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. */ namespace Hoa\Realdom\IRealdom; /** * Interface \Hoa\Realdom\IRealdom\Interval. * * Represent domain with bounds. * * @copyright Copyright © 2007-2017 Hoa community * @license New BSD License */ interface Interval { /** * Get lower bound of the domain. * * @return \Hoa\Realdom */ public function getLowerBound(); /** * Get upper bound of the domain. * * @return \Hoa\Realdom */ public function getUpperBound(); /** * Reduce the lower bound. * * @param mixed $value Value. * @return bool */ public function reduceRightTo($value); /** * Reduce the upper bound. * * @param mixed $value Value. * @return bool */ public function reduceLeftTo($value); }
{ "pile_set_name": "Github" }
/* This Software is provided under the Zope Public License (ZPL) Version 2.1. Copyright (c) 2009, 2010 by the mingw-w64 project See the AUTHORS file for the list of contributors to the mingw-w64 project. This license has been certified as open source. It has also been designated as GPL compatible by the Free Software Foundation (FSF). Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions in source code must retain the accompanying copyright notice, this list of conditions, and the following disclaimer. 2. Redistributions in binary form must reproduce the accompanying copyright notice, this list of conditions, and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Names of the copyright holders must not be used to endorse or promote products derived from this software without prior written permission from the copyright holders. 4. The right to distribute this software or to use it for any purpose does not give you the right to use Servicemarks (sm) or Trademarks (tm) of the copyright holders. Use of them is covered by separate agreement with the copyright holders. 5. If any files are modified, you must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED 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 HOLDERS 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. */ /* double version of the functions. */ #define _NEW_COMPLEX_DOUBLE 1 #include "complex_internal.h" #include "csinh.def.h" #include "csin.def.h"
{ "pile_set_name": "Github" }
<?php // Page créé par Shepard [Fabian Pijcke] <[email protected]> // Arno Esterhuizen <[email protected]> // et Romain Bourdon <[email protected]> // et Hervé Leclerc <[email protected]> // // Mise à jour par Herve Leclerc [email protected] // Icônes par Mark James <http://www.famfamfam.com/lab/icons/silk/> //------ //[modif oto] Modifications Dominique Ottello (Otomatic) //Suppression des vhosts, le dossier n'étant plus créé à l'installation //Affichage des Outils, Projets et Alias sur trois colonnes // - Recodage en utf-8 // - Modification des styles : ajout .third .left et .right // - Ajouts d'index dans $langues['en'] et ['fr'] : // 'locale' pour set_locale // 'docp' url des documentations PHP // 'docm' url des documentations MySQL // 'doca2.2' url de la documentation Apache 2.2 // 'doca2.4' url de la documentation Apache 2.4 // 'server' Server Software // - Classement alphabétique des extensions PHP en fonction de la localisation // - Liens sur les documentations Apache, PHP et MySQL // - Ajout variable $suppress_localhost = true; // - Conformité W3C par ajout de <li>...</li> sur les variables // $aliasContents et $projectContents si vides //[modif oto] - Pour supprimer niveau localhost dans les url $suppress_localhost = true; // avec modification de la ligne //$projectContents .= '<li><a href="'.$file.'">'.$file.'</a></li>'; //Par : //$projectContents .= '<li><a href="'.($suppress_localhost ? 'http://' : '').$file.'">'.$file.'</a></li>'; //----- //[modif oto] Ajout $server_dir pour un seul remplacement // si déplacement www hors de Wamp et pas d'utilisation des jonctions //Par défaut la valeur est "../" //$server_dir = "WAMPROOT/"; $server_dir = "../"; //Fonctionne à condition d'avoir ServerSignature On et ServerTokens Full dans httpd.conf $server_software = $_SERVER['SERVER_SOFTWARE']; $wampConfFile = $server_dir.'wampmanager.conf'; //chemin jusqu'aux fichiers alias $aliasDir = $server_dir.'alias/'; // on charge le fichier de conf locale if (!is_file($wampConfFile)) die ('Unable to open WampServer\'s config file, please change path in index.php file'); $fp = fopen($wampConfFile,'r'); $wampConfFileContents = fread ($fp, filesize ($wampConfFile)); fclose ($fp); // on récupère les versions des applis preg_match('|phpVersion = (.*)\n|',$wampConfFileContents,$result); $phpVersion = str_replace('"','',$result[1]); preg_match('|apacheVersion = (.*)\n|',$wampConfFileContents,$result); $apacheVersion = str_replace('"','',$result[1]); $doca_version = 'doca'.substr($apacheVersion,0,3); preg_match('|mysqlVersion = (.*)\n|',$wampConfFileContents,$result); $mysqlVersion = str_replace('"','',$result[1]); preg_match('|wampserverVersion = (.*)\n|',$wampConfFileContents,$result); $wampserverVersion = str_replace('"','',$result[1]); // répertoires à ignorer dans les projets $projectsListIgnore = array ('.','..'); // textes $langues = array( 'en' => array( 'langue' => 'English', 'locale' => 'english', 'autreLangue' => 'Version Française', 'autreLangueLien' => 'fr', 'titreHtml' => 'WAMPSERVER Homepage', 'titreConf' => 'Server Configuration', 'versa' => 'Apache Version :', 'doca2.2' => 'httpd.apache.org/docs/2.2/en/', 'doca2.4' => 'httpd.apache.org/docs/2.4/en/', 'versp' => 'PHP Version :', 'server' => 'Server Software:', 'docp' => 'www.php.net/manual/en/', 'versm' => 'MySQL Version :', 'docm' => 'dev.mysql.com/doc/index.html', 'phpExt' => 'Loaded Extensions : ', 'titrePage' => 'Tools', 'txtProjet' => 'Your Projects', 'txtNoProjet' => 'No projects yet.<br />To create a new one, just create a directory in \'www\'.', 'txtAlias' => 'Your Aliases', 'txtNoAlias' => 'No Alias yet.<br />To create a new one, use the WAMPSERVER menu.', 'faq' => 'http://www.en.wampserver.com/faq.php' ), 'fr' => array( 'langue' => 'Français', 'locale' => 'french', 'autreLangue' => 'English Version', 'autreLangueLien' => 'en', 'titreHtml' => 'Accueil WAMPSERVER', 'titreConf' => 'Configuration Serveur', 'versa' => 'Version Apache:', 'doca2.2' => 'httpd.apache.org/docs/2.2/fr/', 'doca2.4' => 'httpd.apache.org/docs/2.4/fr/', 'versp' => 'Version de PHP:', 'server' => 'Server Software:', 'docp' => 'www.php.net/manual/fr/', 'versm' => 'Version de MySQL:', 'docm' => 'dev.mysql.com/doc/index.html', 'phpExt' => 'Extensions Chargées: ', 'titrePage' => 'Outils', 'txtProjet' => 'Vos Projets', 'txtNoProjet' => 'Aucun projet.<br /> Pour en ajouter un nouveau, créez simplement un répertoire dans \'www\'.', 'txtAlias' => 'Vos Alias', 'txtNoAlias' => 'Aucun alias.<br /> Pour en ajouter un nouveau, utilisez le menu de WAMPSERVER.', 'faq' => 'http://www.wampserver.com/faq.php' ) ); // images $pngFolder = <<< EOFILE iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAA3NCSVQICAjb4U/gAAABhlBMVEX//v7//v3///7//fr//fj+/v3//fb+/fT+/Pf//PX+/Pb+/PP+/PL+/PH+/PD+++/+++7++u/9+vL9+vH79+r79+n79uj89tj89Nf889D88sj78sz78sr58N3u7u7u7ev777j67bL67Kv46sHt6uP26cns6d356aP56aD56Jv45pT45pP45ZD45I324av344r344T14J734oT34YD13pD24Hv03af13pP233X025303JL23nX23nHz2pX23Gvn2a7122fz2I3122T12mLz14Xv1JPy1YD12Vz02Fvy1H7v04T011Py03j011b01k7v0n/x0nHz1Ejv0Hnuz3Xx0Gvz00buzofz00Pxz2juz3Hy0TrmznzmzoHy0Djqy2vtymnxzS3xzi/kyG3jyG7wyyXkwJjpwHLiw2Liw2HhwmDdvlXevVPduVThsX7btDrbsj/gq3DbsDzbrT7brDvaqzjapjrbpTraojnboTrbmzrbmjrbl0Tbljrakz3ajzzZjTfZijLZiTJdVmhqAAAAgnRSTlP///////////////////////////////////////8A////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////9XzUpQAAAAlwSFlzAAALEgAACxIB0t1+/AAAAB90RVh0U29mdHdhcmUATWFjcm9tZWRpYSBGaXJld29ya3MgOLVo0ngAAACqSURBVBiVY5BDAwxECGRlpgNBtpoKCMjLM8jnsYKASFJycnJ0tD1QRT6HromhHj8YMOcABYqEzc3d4uO9vIKCIkULgQIlYq5haao8YMBUDBQoZWIBAnFtAwsHD4kyoEA5l5SCkqa+qZ27X7hkBVCgUkhRXcvI2sk3MCpRugooUCOooWNs4+wdGpuQIlMDFKiWNbO0dXTx9AwICVGuBQqkFtQ1wEB9LhGeAwDSdzMEmZfC0wAAAABJRU5ErkJggg== EOFILE; $pngFolderGo = <<< EOFILE iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAJISURBVDjLpZPLS5RhFIef93NmnMIRSynvgRF5KWhRlmWbbotwU9sWLupfCBeBEYhQm2iVq1oF0TKIILIkMgosxBaBkpFDmpo549y+772dFl5bBIG/5eGch9+5KRFhOwrYpmIAk8+OjScr29uV2soTotzXtLOZLiD6q0oBUDjY89nGAJQErU3dD+NKKZDVYpTChr9a5sdvpWUtClCWqBRxZiE/9+o68CQGgJUQr8ujn/dxugyCSpRKkaw/S33n7QQigAfxgKCCitqpp939mwCjAvEapxOIF3xpBlOYJ78wQjxZB2LAa0QsYEm19iUQv29jBihJeltCF0F0AZNbIdXaS7K6ba3hdQey6iBWBS6IbQJMQGzHHqrarm0kCh6vf2AzLxGX5eboc5ZLBe52dZBsvAGRsAUgIi7EFycQl0VcDrEZvFlGXBZshtCGNNa0cXVkjEdXIjBb1kiEiLd4s4jYLOKy9L1+DGLQ3qKtpW7XAdpqj5MLC/Q8uMi98oYtAC2icIj9jdgMYjNYrznf0YsTj/MOjzCbTXO48RR5XaJ35k2yMBCoGIBov2yLSztNPpHCpwKROKHVOPF8X5rCeIv1BuMMK1GOI02nyZsiH769DVcBYXRneuhSJ8I5FCmAsNomrbPsrWzGeocTz1x2ht0VtXxKj/Jl+v1y0dCg/vVMl4daXKg12mtCq9lf0xGcaLnA2Mw7hidfTGhL5+ygROp/v/HQQLB4tPlMzcjk8EftOTk7KHr1hP4T0NKvFp0vqyl5F18YFLse/wPLHlqRZqo3CAAAAABJRU5ErkJggg== EOFILE; $gifLogo = <<< EOFILE iVBORw0KGgoAAAANSUhEUgAAAGAAAABTCAYAAABgdgI7AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJ bWFnZVJlYWR5ccllPAAAA2RpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdp bj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6 eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEz NDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJo dHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlw dGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEu MC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVz b3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1N Ok9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDo1ODg0QkM3NUZBMDhFMDExODkyQ0U2NkE5ODVB M0Q2OSIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDoyMEQ2RDU5MDA5M0UxMUUwOUUwRkYwRTg2 NjQyMzQzQyIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDoyMEQ2RDU4RjA5M0UxMUUwOUUwRkYw RTg2NjQyMzQzQyIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ1M1IFdpbmRvd3Mi PiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDo1ODg0QkM3NUZB MDhFMDExODkyQ0U2NkE5ODVBM0Q2OSIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDo1ODg0QkM3 NUZBMDhFMDExODkyQ0U2NkE5ODVBM0Q2OSIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRG PiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/Pgv54A4AAA33SURBVHja7F0JmBTVEa7Z XXZhuc9FiCIICVf8PIKA3EQIAkbJh5AImARERDFAVKIoikc+TEwCSVDBRBRkvygGScIRjoAhCiyC EORQlCMBIiIIy7mw7O6kavp/zNvHTHfPTM+1UN9X3053v+5+XVWvrlfvrc/v99NlSB5kXCZBciHr wi/fK8nuy9cYb2Jsx9gGx3UZq8XwTBneJxkPMe5h3MS4lnEzY1HSvtR/bwgGJAdyGW9jHMrYhbFm HN4hTLyasT3jD3BuN+MixjcYP7wUVZC8dwQ+/k3G/nEifji4hnEs43rGv4A5lwwDvsm4kvGPjC2T PAIzGW9nfJ9xOmPtis6AQYzvMXZPQVv4AOMaxq4VlQEPQN3UpNSFVozLGe+paAwYjiHuSwPPMIfx D4yPJNYNjR90Y3w5hvtLGYvx1y0D/dDvOTEI2S8Zj8FWpS0DxAWczZgdwT37GN+Fh/Ix41eMpxnP R8iASozVGRsgrugMYagXQV9eZNyB2CEtGfA8YxOXbTcyToN/ftzjfqzAsxsy3sk4hvHrLu4TwXkV AeLJdLMBHaD7nUDUy6OMnRjz40B8Hb5g/D3jtxinMJa5uKdlPO1BPBnwtIvnH0Mk/AswIlEg0jyR cSDUmxM8yNgonRggkWUvhzZnQYDlIa6JqzqE8aUY3VZJdfyO8T7GK0JcX4DYxIn5tRhHphMDRrow mKJ2VoU4P4qspNlcPCcWOyV9GAovbAvjk/CMdFiCvjjBkBD3piQDaiK3YwcFkEwdqjLOY5zB2Azn TsCjiVXdCNSHWlzKmGe0mYZ0hB20oDjkjOLBgI4hPtCE5wzCimS9DQ8l3iBpkPlQT7rb+pSLe3um AwO6OVz/FG6hDpMZb02gEe6E0aCDqMMNLjy7lGfAjQ7X/24YPfHHxych5SC5qebGufkO90hfK6cy A0SVNHVo8y/j+MfxMG4uoArebfbNzubkIbJOWQbUgrGzy+t8Zry/NyUP+hg02A3Db8e0+qnOgCo2 1yXoOWzkipomkQHNDYkW4h9xcGtrpDIDshyeeQaooA7FNukeK1SFEOhpEaecjy+VGeDks5+DGtIZ lsw5gkzDHS1DHxMGiZ6S9EXIsGT0yZfuDPAlavgmiCFpxYAMDGs7NzXVITuRNPN6QmYvwvVwUnQW GC3UQLBUw8bNHYJ+RAv3OHg6m1OZAeJmvhtH6ayENEIVB88mFthYkY2wF16WXU1nCbmb5UoZuFwd nWTwWgVJVJsfxhCLXTjI+H1KZmWyM8xibBvGRZZvuN9LNeU1A0T/drS5fjgNRp1kc6+1ue5p/ajX xCiDHg4HRWmgFZy8tNJ0tgH+KNr7I7zfb3N/ygWHiWZApLmfLMOrKXXos8+Q0DKH4E+YU5xMmnj9 MifiSuJLn1GSzOM5h8BrkHYsv+3KVMT46/MLd5D9BIoQ/4QRZ+QmcsR4bYRP4aOybIy0GDGVc/+S rPVbzWw+diZZM1fyu70LAvyWrFKUErS3E7JD8MwUVHZhZItSmQFHySotzLXJs0itqJoVE+lfb8MA xYSOEY5qt+UjUh6jz09I9Vs9h0DvaCqrIBkBnzu0uck4nptEGzjHOL4eaigcHMOoSVkGiFHb7tDG nAOW0sS1SSC+LJVaapzr53DPfxkLU90LcqowE3XSyhjWP6HYsqSRgqidBw2PSUrXnSr6/k0eTyLF gwGryb7YVezAWOOcLFe9L0HEF6JLynmLcV4YUsvhXs8zvfFgwKcwrHYgXk0745yspBlMVg2/W5AV NB9F0H4/4wDGPxnnW4cQChPEXV0VRwZke/nc1xyuq5UnpsTNA2NkZc3OMGG/qKxtjJPIKhUUlSbV zTvCtC8Fo54la2HGQuN6NRhjp3mEpREKh7vASe2WUuB7lL+mLV1cuBAVVAeRrnJoJwb4TgpdDCVM +gbcVuUaSjJvL0aZmXMS76Wl0f4IDOcnZK0xCxWXvOXC+Ap0h3r1wFW592IG5Pgq0QTqQz9lJ6V2 oF8lsb5Gai+nu2j3AXTy1gR7QVLnKSsgu7hou4ysKjqKGwN8Ph98xNb8tocxCmKaXJIczDr41k4g KYlfk7U24FCcCS+lhbJPhaz7quOifTFily2xvzrTGqj+u8Mb4eWsSkfT6xjR2YjOM6N5m+iyMS6H kqisyfjIl6ESGjsERW5BniFb39xGwZUyU1wSn7R+xaLpSaaxC9n7fZr+HNoGqBGgoAs1555nUVdq QeN4XNQMqKXz0bxdFsP9PIr7xC4cgN4/CUmMZJ1wNhibB2ZWj6IP82Gj/NETPpsl8Dy9TRuZ+H9l z+IL0ncpC8sAHdpTU1rEbKgXSESWoD8RqSeZpryL0gtWIzA7Fb2DmUVLOHZ7jN5hX3l/UDoiZYBi Qj6NYgNdmWqwes8KjIhzbhlRGdLUN02Iv5is+qIo1ixnXtDsozm0mRHCcYqKAZbPls2kz2aFWouj lltoKDuu2YGR7ko1qU0whqU48WXB3oTI9K0PGq+M9fwJvtFHT7CufyWQbiLvGGBCZ7YPC9jO1gvM m7heZz0Bhq1KihF+NzyjBZHbeFn0tpV97lXs9u1hBpQwI8JPG3jGgPL2ISImSOXBc5761tGDZDdl 0ucFsjYGcSnxGQGp30n7OHZ6i3W9+zDGUwYoJixkpVQ/EIAWRWKgv0NWnc0t5DwV6DXILopvIhjb 657wOQFBO8rfuY2dtIH0ErtpkdlpzxlAgZxBHuuWvrALORThOofmYEIPBG6N48CQQqiZdcjrrI7M w7EKv1cw2V/g2z9kyT9OpzlcjdxDjQsDFHSgZvQis+GGAE2jmj4V7l0BJjQg5xSxUzzwFaLrfZEn 03zQ8ZmBzIAEqDM8SAfFlQECddlfWswqqX1g3qUE0lNM6VM3q7yaEtrAg+Yk9zuf3qdZgT39KPUZ IFCTnZwb2TbIrP9gasdj4mb+pFzyKNsaJ8hC5FpEH7BZmMyR64pAlttbSAgDQqmmR+hW6sR/8wL5 MFVJ7o9hZFQKkS7y49lu3fhMSLufZf1/7INupjeogLazgS2N0xK2pDBAQR67q9+l6zh66MkBXW0+ koxTrqamSjXdG25+JTtAuG20i2V0C5O7rNzI60NtqWVgWqAMz8ykYFFehnY+h43DYSb4Opb0T1jd 7KFj5apUqOIxIDjYM5j4udSQqjMj6lIvJtkw6sgMEvt7hjaxCmjE9jc7QDg//JAMPlOTCb+fptJy 1ssFrNBKQuQ9KtFdbIHGU29mxVVshY+yRB+kI6zNt7KUX09XUjdqw0/YGvDhDwSqTRIH5f5lgByk yv8QkBExiW7n4KDNBWmuwwZdYQNmVieOviu7zFJLu750beA+ExrF5FzFzgCFSRsBlzLoAq+XJt4P v/tvZG0ZRsjXPERWNcFsre33yFrEICtFFiX5e64ja7/nOvD1ZceTXWnFDXBkIZTtDO1yF5yTKLK6 FhJ+jPPjk9z9pzRXSqG4P+PSgeYBumsMGI4P2EjBmadntA/rgXNXk1XFJtavVRK/QwlHERJ7PyJr l0WpgOiWLgzQVdBa+HitkQaQ6UB960n5LZVhNyBdIKPgM/iEPXFeRoeUoyzT8hDi1vRB8kuk89tk 1fxIDZBUJvQja8JGip7WG4k6ubcABK2P96twVBFZanqewO/X8ayzF9l3a044DwK2mILTjKp/u3Cf 1K5+DnXWFfkjVcQram4MvmMq2kf6bCmHnxVKBYmzvB03y8fXJquGUo0ARZzf4Hgmjn9lqADB97Qc Ti+cO2e0WYFkmDpWq9wVrMN5vQ+ibn6I6w/hnJS1tKHwW4l1QA5If/c7WnvVv9NGm8e1fqs6o7tx rgDCFtWzw6kggv5XL++P35J9+g84eCWO/WSVESoj+CqkRaRyC66PwPWeWnj6MxBOMWMTiD4Hxzu0 0HYlzklBrCxtzcfxZqhI2UbypPZhe8DUsRQs86uEd8h1qf1sj5Emx6OM/okATIL9UNeUNA/E8Xwc q/ntaJ492o4Bg3CDbKz3mvaymfg9CRwXAjYJkcUUfB5tnzE6oZegr9FGmhraorJOUHCFyirj4xtj 6Eu1m9rLoTOIdNCQQrVdfiscb0V6W/o3AOeU99YDx+tCjJ4huDYHHmGh5pBcE+2z7RjQhIK7Wp3Q ht9gPOgw/m7QDPUdkMpitD+PNpMNBvxD64OS7u44FnV1PAwDul7IMlhtTlH5Xa4IBBF7MhHSJkO+ GhikPKOzRv+24d7uIfpHmmAUQgOMRLt8g7gRPzucESYYHrlZVS6vh8StAVOULlRqqLHWoYkYHQMQ J5iQYeR79XMZFL7mJ7dcqtL6WJUkyqbgNmOCsgn4YyB+HQpOuAgBn0T78yBWUZi+6HAUcdEwbUSr 7z0b47NDXvBT+W0ll+HvASq/PF/VyTcEgXbBGM8l77b8UsNyOIb7CBi3LzFS+mAkykR6RxjEqSD+ frTbi1GTB+GajXtEXSwxiBQO8rVvlULff+J4pwfPDpkL6qfpUn1x3OOa362WflaFDvRjpBzR7p1i eALrQng4ys2tC6kupWDJ4MoQ3pUfPj/B5w91XSRT3wJ5nHatUPvd26Z/OlQBgaWNud91VM+2U0FK 7awAd/XNiRZAn++AdBF0rfwfroeRmtiK673gvRCYsko7VjHHGQouVy2G4Sctke/TGN8GTJe53Ola 6mQJBKYFPvQjSOwm7V3T4CGJMW+KUTGPgostQvVPhyKMrP7l/Hdvnp1a2VAD1C62N1fEZJzCVN65 5BiMYCZVYPBd/n/CyYXLO2ZdZsClDf8XYACcVJnoRcTY2AAAAABJRU5ErkJggg== EOFILE; $pngPlugin = <<< EOFILE iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAAsSAAALEgHS3X78AAAABGdBTUEAALGOfPtRkwAAACBjSFJNAAB6JQAAgIMAAPn/AACA6QAAdTAAAOpgAAA6mAAAF2+SX8VGAAABmklEQVR42mL4//8/AyUYIIDAxK5du1BwXEb3/9D4FjBOzZ/wH10ehkF6AQIIw4B1G7b+D09o/h+X3gXG4YmteA0ACCCsLghPbPkfm9b5PzK5439Sdg9eAwACCEyANMBwaFwTGIMMAOEQIBuGA6Mb/qMbABBAEAOQnIyMo1M74Tgiqf2/b3gVhgEAAQQmQuKa/8ekdYMxyLCgmEYMHJXc9t87FNMAgACCGgBxIkgzyDaQU5FxQGQN2AUBUXX/vULKwdgjsOQ/SC9AAKEEYlB03f+oFJABdSjYP6L6P0guIqkVjt0DisEGAAQQigEgG0AhHxBVi4L9wqvBBiEHtqs/xACAAAIbEBBd/x+Eg2ObwH4FORmGfYCaQRikCUS7B5YBNReBMUgvQABBDADaAtIIwsEx9f/Dk9pQsH9kHTh8XANKMAIRIIDAhF9ELTiQQH4FaQAZCAsskPNhyRpkK7oBAAEEMSC8GsVGkEaYIlBghcU3gbGzL6YBAAEEJnzCgP6EYs/gcjCGKQI5G4Z9QiswDAAIIAZKszNAgAEAHgFgGSNMTwgAAAAASUVORK5CYII= EOFILE; $pngWrench = <<< EOFILE iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAA3NCSVQICAjb4U/gAAABO1BMVEXu7u7n5+fk5OTi4uLg4ODd3d3X19fV1dXU1NTS0tLPz8+7z+/MzMy6zu65ze65zu7Kysq3zO62zO3IyMjHx8e1yOiyyO2yyOzFxcXExMSyxue0xuexxefDw8OtxeuwxOXCwsLBwcGuxOWsw+q/v7+qweqqwuqrwuq+vr6nv+qmv+m7u7ukvumkvemivOi5ubm4uLicuOebuOeat+e0tLSYtuabtuaatuaXteaZteaatN6Xs+aVs+WTsuaTsuWRsOSrq6uLreKoqKinp6elpaWLqNijo6OFpt2CpNyAo92BotyAo9+dnZ18oNqbm5t4nt57nth7ntp4nt15ndp3nd6ZmZmYmJhym956mtJzm96WlpaVlZVwmNyTk5Nvl9lultuSkpKNjY2Li4uKioqIiIiHh4eGhoZQgtVKfNFdha6iAAAAaXRSTlMA//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////914ivwAAAACXBIWXMAAAsSAAALEgHS3X78AAAAH3RFWHRTb2Z0d2FyZQBNYWNyb21lZGlhIEZpcmV3b3JrcyA4tWjSeAAAAKFJREFUGJVjYIABASc/PwYkIODDxBCNLODEzGiQgCwQxsTlzJCYmAgXiGKVdHFxYEuB8dkTOIS1tRUVocaIWiWI8IiIKKikaoD50kYWrpwmKSkpsRC+lBk3t2NEMgtMu4wpr5aeuHcAjC9vzadjYyjn7w7lK9kK6tqZK4d4wBQECenZW6pHesEdFC9mbK0W7otwsqenqmpMILIn4tIzgpG4ADUpGMOpkOiuAAAAAElFTkSuQmCC EOFILE; $favicon = <<< EOFILE iVBORw0KGgoAAAANSUhEUgAAAB8AAAAfCAYAAAAfrhY5AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJ bWFnZVJlYWR5ccllPAAAA2RpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdp bj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6 eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEz NDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJo dHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlw dGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEu MC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVz b3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1N Ok9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDo1ODg0QkM3NUZBMDhFMDExODkyQ0U2NkE5ODVB M0Q2OSIgeG1wTU06RG9jdW1lbnRJRD0ieG1wLmRpZDoxRkI1ODNGRTA5MDMxMUUwQjAwNEEwODc0 OTk5N0ZEOCIgeG1wTU06SW5zdGFuY2VJRD0ieG1wLmlpZDoxRkI1ODNGRDA5MDMxMUUwQjAwNEEw ODc0OTk5N0ZEOCIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ1M1IFdpbmRvd3Mi PiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDo1ODg0QkM3NUZB MDhFMDExODkyQ0U2NkE5ODVBM0Q2OSIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDo1ODg0QkM3 NUZBMDhFMDExODkyQ0U2NkE5ODVBM0Q2OSIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRG PiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PiUukzAAAAHHSURBVHja5FfRccIwDLVz /W+7QdggbJBM0HQCwg+/LRNwTJDymx9ggmYDsgEZwRuUDVI5ET1XyE5CuIa76k7ABVtPluQnRVZV JcYST4woD85/ZRbC5wxUf/sdbZagBehGVAvlNM+GXWYaaIugQ+QDdA1OnLqByyyAzwPo042iqyMx BwdKN7jMNODREWKFyonv2KdPPqERoDlPGQMKQ7drPWPjfAy6Inb080/QiK/2Js8JMacBpzWwzGIs QFdxhujkFMNtSkj3m1ftjTnxEg0f0XNXAYb1mmatwFPSFM1s4NTwuUp18QU9CiyonWj2rhkHWXAK kNeh7gdMQ5wzRdnKcAo9DwZcsRBtqL70qm7Ior3B/5zbI0IKrvv8mxarhXSsXtrY8m5OfjB+F5SN BkhKrpi8635uaxAvkO9HpgZSB/v57f2cFpEQzz+UeZ28Yvq+bMXpkb5rSgwLc+Z5Fylwb+y68x4p MlNW2CLnPUmnrE/d7F1dOGXJ+Qb0neQqre9ptZiAscTI38ng7YTQ8g6Budlg75pktkxPV9idctss 1mGYOKciupsxatQB8pJkmkUTpgCvHZ0jDtg+t4/60vAf3tVGBf8WYAC3Rq8Ub3mHyQAAAABJRU5E rkJggg== EOFILE; //affichage du phpinfo if (isset($_GET['phpinfo'])) { phpinfo(); exit(); } //affichage des images if (isset($_GET['img'])) { switch ($_GET['img']) { case 'pngFolder' : header("Content-type: image/png"); echo base64_decode($pngFolder); exit(); case 'pngFolderGo' : header("Content-type: image/png"); echo base64_decode($pngFolderGo); exit(); case 'gifLogo' : header("Content-type: image/gif"); echo base64_decode($gifLogo); exit(); case 'pngPlugin' : header("Content-type: image/png"); echo base64_decode($pngPlugin); exit(); case 'pngWrench' : header("Content-type: image/png"); echo base64_decode($pngWrench); exit(); case 'favicon' : header("Content-type: image/x-icon"); echo base64_decode($favicon); exit(); } } // Définition de la langue et des textes if (isset ($_GET['lang'])) { $langue = htmlspecialchars($_GET['lang'],ENT_QUOTES); if ($langue != 'en' && $langue != 'fr' ) { $langue = 'fr'; } } elseif (isset ($_SERVER['HTTP_ACCEPT_LANGUAGE']) AND preg_match("/^fr/", $_SERVER['HTTP_ACCEPT_LANGUAGE'])) { $langue = 'fr'; } else { $langue = 'en'; } //initialisation $aliasContents = ''; // récupération des alias if (is_dir($aliasDir)) { $handle=opendir($aliasDir); while (($file = readdir($handle))!==false) { //echo($file); if (is_file($aliasDir.$file) && strstr($file, '.conf')) { $msg = ''; $aliasContents .= '<li><a href="'.str_replace('.conf','',$file).'/">'.str_replace('.conf','',$file).'</a></li>'; } } closedir($handle); } if (empty($aliasContents)) $aliasContents = "<li>".$langues[$langue]['txtNoAlias']."</li>\n"; // récupération des projets $handle=opendir("."); $projectContents = ''; while (($file = readdir($handle))!==false) { if (is_dir($file) && !in_array($file,$projectsListIgnore)) { //[modif oto] Ajout éventuel de http:// pour éviter le niveau localhost dans les url $projectContents .= '<li><a href="'.($suppress_localhost ? 'http://localhost/' : '').$file.'">'.$file.'</a></li>'; } } closedir($handle); if (empty($projectContents)) $projectContents = "<li>".$langues[$langue]['txtNoProjet']."</li>\n";; //initialisation $phpExtContents = ''; // récupération des extensions PHP $loaded_extensions = get_loaded_extensions(); // [modif oto] classement alphabétique des extensions setlocale(LC_ALL,"{$langues[$langue]['locale']}"); sort($loaded_extensions,SORT_LOCALE_STRING); foreach ($loaded_extensions as $extension) $phpExtContents .= "<li>${extension}</li>"; //header('Status: 301 Moved Permanently', false, 301); //header('Location: /aviatechno/index.php'); //exit(); $pageContents = <<< EOPAGE <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html lang="en" xml:lang="en"> <head> <title>{$langues[$langue]['titreHtml']}</title> <meta http-equiv="Content-Type" content="txt/html; charset=utf-8" /> <style type="text/css"> * { margin: 0; padding: 0; } html { background: #ddd; } body { margin: 1em 10%; padding: 1em 3em; font: 80%/1.4 tahoma, arial, helvetica, lucida sans, sans-serif; border: 1px solid #999; background: #eee; position: relative; } #head { margin-bottom: 1.8em; margin-top: 1.8em; padding-bottom: 0em; border-bottom: 1px solid #999; letter-spacing: -500em; text-indent: -500em; height: 125px; background: url(index.php?img=gifLogo) 0 0 no-repeat; } .utility { position: absolute; right: 4em; top: 145px; font-size: 0.85em; } .utility li { display: inline; } h2 { margin: 0.8em 0 0 0; } ul { list-style: none; margin: 0; padding: 0; } #head ul li, dl ul li, #foot li { list-style: none; display: inline; margin: 0; padding: 0 0.4em; } ul.aliases, ul.projects, ul.tools { list-style: none; line-height: 24px; } ul.aliases a, ul.projects a, ul.tools a { padding-left: 22px; background: url(index.php?img=pngFolder) 0 100% no-repeat; } ul.tools a { background: url(index.php?img=pngWrench) 0 100% no-repeat; } ul.aliases a { background: url(index.php?img=pngFolderGo) 0 100% no-repeat; } dl { margin: 0; padding: 0; } dt { font-weight: bold; text-align: right; width: 11em; clear: both; } dd { margin: -1.35em 0 0 12em; padding-bottom: 0.4em; overflow: auto; } dd ul li { float: left; display: block; width: 16.5%; margin: 0; padding: 0 0 0 20px; background: url(index.php?img=pngPlugin) 2px 50% no-repeat; line-height: 1.6; } a { color: #024378; font-weight: bold; text-decoration: none; } a:hover { color: #04569A; text-decoration: underline; } #foot { text-align: center; margin-top: 1.8em; border-top: 1px solid #999; padding-top: 1em; font-size: 0.85em; } .third { width:32%; float:left; } .left {float:left;} .right {float:right;} </style> <link rel="shortcut icon" href="index.php?img=favicon" type="image/ico" /> </head> <body> <div id="head"> <h1><abbr title="Windows">W</abbr><abbr title="Apache">A</abbr><abbr title="MySQL">M</abbr><abbr title="PHP">P</abbr></h1> <ul> <li>PHP 5</li> <li>Apache 2</li> <li>MySQL 5</li> </ul> </div> <ul class="utility"> <li>Version ${wampserverVersion}</li> <li><a href="?lang={$langues[$langue]['autreLangueLien']}">{$langues[$langue]['autreLangue']}</a></li> </ul> <h2> {$langues[$langue]['titreConf']} </h2> <dl class="content"> <dt>{$langues[$langue]['versa']}</dt> <dd>${apacheVersion}&nbsp;&nbsp;-&nbsp;<a href='http://{$langues[$langue][$doca_version]}'>Documentation</a></dd> <dt>{$langues[$langue]['versp']}</dt> <dd>${phpVersion}&nbsp;&nbsp;-&nbsp;<a href='http://{$langues[$langue]['docp']}'>Documentation</a></dd> <dt>{$langues[$langue]['server']}</dt> <dd>${server_software}</dd> <dt>{$langues[$langue]['phpExt']}</dt> <dd> <ul> ${phpExtContents} </ul> </dd> <dt>{$langues[$langue]['versm']}</dt> <dd>${mysqlVersion} &nbsp;-&nbsp; <a href='http://{$langues[$langue]['docm']}'>Documentation</a></dd> </dl> <div style="margin-top:5px;border-top:1px solid #999;"></div> <div class="third left"> <h2>{$langues[$langue]['titrePage']}</h2> <ul class="tools"> <li><a href="?phpinfo=1">phpinfo()</a></li> <li><a href="phpmyadmin/">phpmyadmin</a></li> </ul> </div> <div class="third left"> <h2>{$langues[$langue]['txtProjet']}</h2> <ul class="projects"> $projectContents </ul> </div> <div class="third right"> <h2>{$langues[$langue]['txtAlias']}</h2> <ul class="aliases"> ${aliasContents} </ul> </div> <div style="clear:both;"></div> <ul id="foot"> <li><a href="http://www.wampserver.com">WampServer</a></li> <li><a href="http://www.wampserver.com/en/donations.php">Donate</a></li> <li><a href="http://www.alterway.fr">Alter Way</a></li> </ul> </body> </html> EOPAGE; echo $pageContents; ?>
{ "pile_set_name": "Github" }
<?php require_once("provider.php"); class StockProvider implements ServiceProvider { // Widget properties static $widgetName = "Stock Price"; static $widgetIcon = "stock.svg"; public $cpair; public $width; public $height; function StockProvider() { $this->stock = "GOOG"; $this->width = 800; $this->height = 100; $this->font_size = 1; $this->font_family = "Verdana"; } public function getTunables() { return array( "stock" => array("type" => "text", "display" => "Stock Name", "value" => $this->stock), "font_family" => array("type" => "text", "display" => "Font Family", "value" => $this->font_family), "font_size" => array("type" => "fnum", "display" => "Font Size", "value" => $this->font_size) ); } public function setTunables($v) { $this->stock = strtoupper($v["stock"]["value"]); $this->font_family = $v["font_family"]["value"]; $this->font_size = $v["font_size"]["value"]; } public function shape() { // Return default width/height return array( "width" => $this->width, "height" => $this->height, "resizable" => true, "keep_aspect" => false, ); } public function render() { // Gather information from yahoo $raw = file_get_contents("http://finance.google.com/finance/info?client=ig&q=".$this->stock); $raw = str_replace("//", "", $raw); $info = json_decode($raw, true); $name = $info[0]["t"]; $price = $info[0]["l"]; // Generate an SVG image out of this return sprintf( '<svg width="%d" height="%d" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <text text-anchor="middle" x="50%%" y="80%%" fill="black" style="font-size: %dpx; font-family: %s;"> %s %0.3f </text> </svg>', $this->width, $this->height, $this->font_size * $this->height, $this->font_family, $name, $price ); } }; ?>
{ "pile_set_name": "Github" }
#!/bin/sh mkdir colors cp SublimeMonokai.xml colors touch IntelliJ\ IDEA\ Global\ Settings jar cfM SublimeMonoKai.jar IntelliJ\ IDEA\ Global\ Settings colors rm -r colors rm IntelliJ\ IDEA\ Global\ Settings
{ "pile_set_name": "Github" }
;;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- ;;;; Code from Paradigms of AI Programming ;;;; Copyright (c) 1991 Peter Norvig ;;;; File unifgram.lisp: The DCG parser from Chapter 20. (requires "prologcp") (defmacro rule (head &optional (arrow ':-) &body body) "Expand one of several types of logic rules into pure Prolog." ;; This is data-driven, dispatching on the arrow (funcall (get arrow 'rule-function) head body)) (setf (get ':- 'rule-function) #'(lambda (head body) `(<- ,head .,body))) (defun dcg-normal-goal-p (x) (or (starts-with x :test) (eq x '!))) (defun dcg-word-list-p (x) (starts-with x ':word)) (setf (get '--> 'rule-function) 'make-dcg) (defun make-dcg (head body) (let ((n (count-if (complement #'dcg-normal-goal-p) body))) `(<- (,@head ?s0 ,(symbol '?s n)) .,(make-dcg-body body 0)))) (defun make-dcg-body (body n) "Make the body of a Definite Clause Grammar (DCG) clause. Add ?string-in and -out variables to each constituent. Goals like (:test goal) are ordinary Prolog goals, and goals like (:word hello) are literal words to be parsed." (if (null body) nil (let ((goal (first body))) (cond ((eq goal '!) (cons '! (make-dcg-body (rest body) n))) ((dcg-normal-goal-p goal) (append (rest goal) (make-dcg-body (rest body) n))) ((dcg-word-list-p goal) (cons `(= ,(symbol '?s n) (,@(rest goal) .,(symbol '?s (+ n 1)))) (make-dcg-body (rest body) (+ n 1)))) (t (cons (append goal (list (symbol '?s n) (symbol '?s (+ n 1)))) (make-dcg-body (rest body) (+ n 1)))))))) (setf (get '==> 'rule-function) 'make-augmented-dcg) (defun make-augmented-dcg (head body) "Build an augmented DCG rule that handles :sem, :ex, and automatic conjunctiontive constituents." (if (eq (last1 head) :sem) ;; Handle :sem (let* ((?sem (gensym "?SEM"))) (make-augmented-dcg `(,@(butlast head) ,?sem) `(,@(remove :sem body :key #'first-or-nil) (:test ,(collect-sems body ?sem))))) ;; Separate out examples from body (multiple-value-bind (exs new-body) (partition-if #'(lambda (x) (starts-with x :ex)) body) ;; Handle conjunctions (let ((rule `(rule ,(handle-conj head) --> ,@new-body))) (if (null exs) rule `(progn (:ex ,head .,(mappend #'rest exs)) ,rule)))))) (defun collect-sems (body ?sem) "Get the semantics out of each constituent in body, and combine them together into ?sem." (let ((sems (loop for goal in body unless (or (dcg-normal-goal-p goal) (dcg-word-list-p goal) (starts-with goal :ex) (atom goal)) collect (last1 goal)))) (case (length sems) (0 `(= ,?sem t)) (1 `(= ,?sem ,(first sems))) (t `(and* ,sems ,?sem))))) (defun and*/2 (in out cont) "IN is a list of conjuncts that are conjoined into OUT." ;; E.g.: (and* (t (and a b) t (and c d) t) ?x) ==> ;; ?x = (and a b c d) (if (unify! out (maybe-add 'and (conjuncts (cons 'and in)) t)) (funcall cont))) (defun conjuncts (exp) "Get all the conjuncts from an expression." (deref exp) (cond ((eq exp t) nil) ((atom exp) (list exp)) ((eq (deref (first exp)) 'nil) nil) ((eq (first exp) 'and) (mappend #'conjuncts (rest exp))) (t (list exp)))) (defmacro :ex ((category . args) &body examples) "Add some example phrases, indexed under the category." `(add-examples ',category ',args ',examples)) (defvar *examples* (make-hash-table :test #'eq)) (defun get-examples (category) (gethash category *examples*)) (defun clear-examples () (clrhash *examples*)) (defun add-examples (category args examples) "Add these example strings to this category, and when it comes time to run them, use the args." (dolist (example examples) (when (stringp example) (let ((ex `(,example (,category ,@args ,(string->list (remove-punctuation example)) ())))) (unless (member ex (get-examples category) :test #'equal) (setf (gethash category *examples*) (nconc (get-examples category) (list ex)))))))) (defun run-examples (&optional category) "Run all the example phrases stored under a category. With no category, run ALL the examples." (prolog-compile-symbols) (if (null category) (maphash #'(lambda (cat val) (declare (ignore val)) (format t "~2&Examples of ~a:~&" cat) (run-examples cat)) *examples*) (dolist (example (get-examples category)) (format t "~2&EXAMPLE: ~{~a~&~9T~a~}" example) (top-level-prove (cdr example))))) (defun remove-punctuation (string) "Replace punctuation with spaces in string." (substitute-if #\space #'punctuation-p string)) (defun string->list (string) "Convert a string to a list of words." (read-from-string (concatenate 'string "(" string ")"))) (defun punctuation-p (char) (find char "*_.,;:`!?#-()\\\"")) (defmacro conj-rule ((conj-cat sem1 combined-sem) ==> conj (cat . args)) "Define this category as an automatic conjunction." (assert (eq ==> '==>)) `(progn (setf (get ',cat 'conj-cat) ',(symbol cat '_)) (rule (,cat ,@(butlast args) ?combined-sem) ==> (,(symbol cat '_) ,@(butlast args) ,sem1) (,conj-cat ,sem1 ?combined-sem)) (rule (,conj-cat ,sem1 ,combined-sem) ==> ,conj (,cat ,@args)) (rule (,conj-cat ?sem1 ?sem1) ==>))) (defun handle-conj (head) "Replace (Cat ...) with (Cat_ ...) if Cat is declared as a conjunctive category." (if (and (listp head) (conj-category (predicate head))) (cons (conj-category (predicate head)) (args head)) head)) (defun conj-category (predicate) "If this is a conjunctive predicate, return the Cat_ symbol." (get predicate 'conj-category))
{ "pile_set_name": "Github" }
# 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/. # This script is used to capture the content of config.status-generated # files and subsequently restore their timestamp if they haven't changed. import argparse import errno import itertools import os import re import subprocess import sys import pickle import mozpack.path as mozpath class Pool(object): def __new__(cls, size): try: import multiprocessing size = min(size, multiprocessing.cpu_count()) return multiprocessing.Pool(size) except: return super(Pool, cls).__new__(cls) def imap_unordered(self, fn, iterable): return itertools.imap(fn, iterable) def close(self): pass def join(self): pass class File(object): def __init__(self, path): self._path = path self._content = open(path, 'rb').read() stat = os.stat(path) self._times = (stat.st_atime, stat.st_mtime) @property def path(self): return self._path @property def mtime(self): return self._times[1] @property def modified(self): '''Returns whether the file was modified since the instance was created. Result is memoized.''' if hasattr(self, '_modified'): return self._modified modified = True if os.path.exists(self._path): if open(self._path, 'rb').read() == self._content: modified = False self._modified = modified return modified def update_time(self): '''If the file hasn't changed since the instance was created, restore its old modification time.''' if not self.modified: os.utime(self._path, self._times) # As defined in the various sub-configures in the tree PRECIOUS_VARS = set([ 'build_alias', 'host_alias', 'target_alias', 'CC', 'CFLAGS', 'LDFLAGS', 'LIBS', 'CPPFLAGS', 'CPP', 'CCC', 'CXXFLAGS', 'CXX', 'CCASFLAGS', 'CCAS', ]) CONFIGURE_DATA = 'configure.pkl' # Autoconf, in some of the sub-configures used in the tree, likes to error # out when "precious" variables change in value. The solution it gives to # straighten things is to either run make distclean or remove config.cache. # There's no reason not to do the latter automatically instead of failing, # doing the cleanup (which, on buildbots means a full clobber), and # restarting from scratch. def maybe_clear_cache(data): env = dict(data['env']) for kind in ('target', 'host', 'build'): arg = data[kind] if arg is not None: env['%s_alias' % kind] = arg # configure can take variables assignments in its arguments, and that # overrides whatever is in the environment. for arg in data['args']: if arg[:1] != '-' and '=' in arg: key, value = arg.split('=', 1) env[key] = value comment = re.compile(r'^\s+#') cache = {} with open(data['cache-file']) as f: for line in f: if not comment.match(line) and '=' in line: key, value = line.rstrip(os.linesep).split('=', 1) # If the value is quoted, unquote it if value[:1] == "'": value = value[1:-1].replace("'\\''", "'") cache[key] = value for precious in PRECIOUS_VARS: # If there is no entry at all for that precious variable, then # its value is not precious for that particular configure. if 'ac_cv_env_%s_set' % precious not in cache: continue is_set = cache.get('ac_cv_env_%s_set' % precious) == 'set' value = cache.get('ac_cv_env_%s_value' % precious) if is_set else None if value != env.get(precious): print 'Removing %s because of %s value change from:' \ % (data['cache-file'], precious) print ' %s' % (value if value is not None else 'undefined') print 'to:' print ' %s' % env.get(precious, 'undefined') os.remove(data['cache-file']) return True return False def split_template(s): """Given a "file:template" string, returns "file", "template". If the string is of the form "file" (without a template), returns "file", "file.in".""" if ':' in s: return s.split(':', 1) return s, '%s.in' % s def get_config_files(data): config_status = mozpath.join(data['objdir'], 'config.status') if not os.path.exists(config_status): return [], [] configure = mozpath.join(data['srcdir'], 'configure') config_files = [] command_files = [] # Scan the config.status output for information about configuration files # it generates. config_status_output = subprocess.check_output( [data['shell'], '-c', '%s --help' % config_status], stderr=subprocess.STDOUT).splitlines() state = None for line in config_status_output: if line.startswith('Configuration') and line.endswith(':'): if line.endswith('commands:'): state = 'commands' else: state = 'config' elif not line.strip(): state = None elif state: for f, t in (split_template(couple) for couple in line.split()): f = mozpath.join(data['objdir'], f) t = mozpath.join(data['srcdir'], t) if state == 'commands': command_files.append(f) else: config_files.append((f, t)) return config_files, command_files def prepare(srcdir, objdir, shell, args): parser = argparse.ArgumentParser() parser.add_argument('--target', type=str) parser.add_argument('--host', type=str) parser.add_argument('--build', type=str) parser.add_argument('--cache-file', type=str) # The --srcdir argument is simply ignored. It's a useless autoconf feature # that we don't support well anyways. This makes it stripped from `others` # and allows to skip setting it when calling the subconfigure (configure # will take it from the configure path anyways). parser.add_argument('--srcdir', type=str) data_file = os.path.join(objdir, CONFIGURE_DATA) previous_args = None if os.path.exists(data_file): with open(data_file, 'rb') as f: data = pickle.load(f) previous_args = data['args'] # Msys likes to break environment variables and command line arguments, # so read those from stdin, as they are passed from the configure script # when necessary (on windows). # However, for some reason, $PATH is not handled like other environment # variables, and msys remangles it even when giving it is already a msys # $PATH. Fortunately, the mangling/demangling is just find for $PATH, so # we can just take the value from the environment. Msys will convert it # back properly when calling subconfigure. input = sys.stdin.read() if input: data = {a: b for [a, b] in eval(input)} environ = {a: b for a, b in data['env']} environ['PATH'] = os.environ['PATH'] args = data['args'] else: environ = os.environ args, others = parser.parse_known_args(args) data = { 'target': args.target, 'host': args.host, 'build': args.build, 'args': others, 'shell': shell, 'srcdir': srcdir, 'env': environ, } if args.cache_file: data['cache-file'] = mozpath.normpath(mozpath.join(os.getcwd(), args.cache_file)) else: data['cache-file'] = mozpath.join(objdir, 'config.cache') if previous_args is not None: data['previous-args'] = previous_args try: os.makedirs(objdir) except OSError as e: if e.errno != errno.EEXIST: raise with open(data_file, 'wb') as f: pickle.dump(data, f) def prefix_lines(text, prefix): return ''.join('%s> %s' % (prefix, line) for line in text.splitlines(True)) def run(objdir): ret = 0 output = '' with open(os.path.join(objdir, CONFIGURE_DATA), 'rb') as f: data = pickle.load(f) data['objdir'] = objdir cache_file = data['cache-file'] cleared_cache = True if os.path.exists(cache_file): cleared_cache = maybe_clear_cache(data) config_files, command_files = get_config_files(data) contents = [] for f, t in config_files: contents.append(File(f)) # AC_CONFIG_COMMANDS actually only registers tags, not file names # but most commands are tagged with the file name they create. # However, a few don't, or are tagged with a directory name (and their # command is just to create that directory) for f in command_files: if os.path.isfile(f): contents.append(File(f)) # Only run configure if one of the following is true: # - config.status doesn't exist # - config.status is older than configure # - the configure arguments changed # - the environment changed in a way that requires a cache clear. configure = mozpath.join(data['srcdir'], 'configure') config_status_path = mozpath.join(objdir, 'config.status') skip_configure = True if not os.path.exists(config_status_path): skip_configure = False config_status = None else: config_status = File(config_status_path) if config_status.mtime < os.path.getmtime(configure) or \ data.get('previous-args', data['args']) != data['args'] or \ cleared_cache: skip_configure = False relobjdir = os.path.relpath(objdir, os.getcwd()) if not skip_configure: command = [data['shell'], configure] for kind in ('target', 'build', 'host'): if data.get(kind) is not None: command += ['--%s=%s' % (kind, data[kind])] command += data['args'] command += ['--cache-file=%s' % cache_file] # Pass --no-create to configure so that it doesn't run config.status. # We're going to run it ourselves. command += ['--no-create'] print prefix_lines('configuring', relobjdir) print prefix_lines('running %s' % ' '.join(command[:-1]), relobjdir) sys.stdout.flush() try: output += subprocess.check_output(command, stderr=subprocess.STDOUT, cwd=objdir, env=data['env']) except subprocess.CalledProcessError as e: return relobjdir, e.returncode, e.output # Leave config.status with a new timestamp if configure is newer than # its original mtime. if config_status and os.path.getmtime(configure) <= config_status.mtime: config_status.update_time() # Only run config.status if one of the following is true: # - config.status changed or did not exist # - one of the templates for config files is newer than the corresponding # config file. skip_config_status = True if not config_status or config_status.modified: # If config.status doesn't exist after configure (because it's not # an autoconf configure), skip it. if os.path.exists(config_status_path): skip_config_status = False else: # config.status changed or was created, so we need to update the # list of config and command files. config_files, command_files = get_config_files(data) for f, t in config_files: if not os.path.exists(t) or \ os.path.getmtime(f) < os.path.getmtime(t): skip_config_status = False if not skip_config_status: if skip_configure: print prefix_lines('running config.status', relobjdir) sys.stdout.flush() try: output += subprocess.check_output([data['shell'], '-c', './config.status'], stderr=subprocess.STDOUT, cwd=objdir, env=data['env']) except subprocess.CalledProcessError as e: ret = e.returncode output += e.output for f in contents: f.update_time() return relobjdir, ret, output def subconfigure(args): parser = argparse.ArgumentParser() parser.add_argument('--list', type=str, help='File containing a list of subconfigures to run') parser.add_argument('--skip', type=str, help='File containing a list of Subconfigures to skip') parser.add_argument('subconfigures', type=str, nargs='*', help='Subconfigures to run if no list file is given') args, others = parser.parse_known_args(args) subconfigures = args.subconfigures if args.list: subconfigures.extend(open(args.list, 'rb').read().splitlines()) if args.skip: skips = set(open(args.skip, 'rb').read().splitlines()) subconfigures = [s for s in subconfigures if s not in skips] if not subconfigures: return 0 ret = 0 # One would think using a ThreadPool would be faster, considering # everything happens in subprocesses anyways, but no, it's actually # slower on Windows. (20s difference overall!) pool = Pool(len(subconfigures)) for relobjdir, returncode, output in \ pool.imap_unordered(run, subconfigures): print prefix_lines(output, relobjdir) sys.stdout.flush() ret = max(returncode, ret) if ret: break pool.close() pool.join() return ret def main(args): if args[0] != '--prepare': return subconfigure(args) topsrcdir = os.path.abspath(args[1]) subdir = args[2] # subdir can be of the form srcdir:objdir if ':' in subdir: srcdir, subdir = subdir.split(':', 1) else: srcdir = subdir srcdir = os.path.join(topsrcdir, srcdir) objdir = os.path.abspath(subdir) return prepare(srcdir, objdir, args[3], args[4:]) if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
{ "pile_set_name": "Github" }
(defpackage :roswell.delete.git (:use :cl :roswell.util)) (in-package :roswell.delete.git) (defun git (&rest argv) (if (rest argv) (dolist (x (rest argv) (roswell:quit 0)) (let* ((* (loop for v being the hash-values in (roswell.util::local-project-build-hash) for .git/ = (merge-pathnames ".git/" (make-pathname :defaults v :name nil :type nil)) when (and (equal (pathname-name v) (first (last (pathname-directory v)))) (uiop:directory-exists-p .git/)) collect v)) (* (sort * #'string< :key #'pathname-name)) (* (mapcar (lambda (x) (truename (make-pathname :defaults x :type nil :name nil))) *))) (loop for x in * with a = (namestring (truename (homedir))) for b = (namestring x) do (and (string= a b :end2 (min (length a) (length b))) (probe-file b) (progn (format t "delete ~S~%" x) (uiop/filesystem:delete-directory-tree x :validate t)))))) `(,(roswell:opt "wargv0") "help" ,(format nil "delete-git"))))
{ "pile_set_name": "Github" }
.CodeMirror-hints { position: absolute; z-index: 10; overflow: hidden; list-style: none; margin: 0; padding: 2px; -webkit-box-shadow: 2px 3px 5px rgba(0,0,0,.2); -moz-box-shadow: 2px 3px 5px rgba(0,0,0,.2); box-shadow: 2px 3px 5px rgba(0,0,0,.2); border-radius: 3px; border: 1px solid silver; background: white; font-size: 90%; font-family: monospace; max-height: 20em; overflow-y: auto; } .CodeMirror-hint { margin: 0; padding: 0 4px; border-radius: 2px; max-width: 19em; overflow: hidden; white-space: pre; color: black; cursor: pointer; } li.CodeMirror-hint-active { background: #08f; color: white; }
{ "pile_set_name": "Github" }
-----BEGIN RSA PRIVATE KEY----- MIICXAIBAAKBgQDBV1Z/Q5gPF7lojc8pKUdyz5+Jf2B3vs4he6egekugWnoJduki 9Lnae/JchB/soIX0co3nLc11NuFFlnAWJNMDJr08l5AHAJLYNHevF5l/f9oDQwvZ speKh1xpIAJNqCTzVeQ/ZLx6/GccIXV/xDuKIiovqJTPgR5WPkYKaw++lQIDAQAB AoGALXnUj5SflJU4+B2652ydMKUjWl0KnL/VjkyejgGV/j6py8Ybaixz9q8Gv7oY JDlRqMC1HfZJCFQDQrHy5VJ+CywA/H9WrqKo/Ch9U4tJAZtkig1Cmay/BAYixVu0 xBeim10aKF6hxHH4Chg9We+OCuzWBWJhqveNjuDedL/i7JUCQQDlejovcwBUCbhJ U12qKOwlaboolWbl7yF3XdckTJZg7+1UqQHZH5jYZlLZyZxiaC92SNV0SyTLJZnS Jh5CO+VDAkEA16/pPcuVtMMz/R6SSPpRSIAa1stLs0mFSs3NpR4pdm0n42mu05pO 1tJEt3a1g7zkreQBf53+Dwb+lA841EkjRwJBAIFmt0DifKDnCkBu/jZh9SfzwsH3 3Zpzik+hXxxdA7+ODCrdUul449vDd5zQD5t+XKU61QNLDGhxv5e9XvrCg7kCQH/a 3ldsVF0oDaxxL+QkxoREtCQ5tLEd1u7F2q6Tl56FDE0pe6Ih6bQ8RtG+g9EI60IN U7oTrOO5kLWx5E0q4ccCQAZVgoenn9MhRU1agKOCuM6LT2DxReTu4XztJzynej+8 0J93n3ebanB1MlRpn1XJwhQ7gAC8ImaQKLJK5jdJzFc= -----END RSA PRIVATE KEY----- -----BEGIN CERTIFICATE----- MIICaTCCAdKgAwIBAgIJAP6VN47boiXRMA0GCSqGSIb3DQEBBQUAMEQxCzAJBgNV BAYTAlVLMRYwFAYDVQQKEw1PcGVuU1NMIEdyb3VwMR0wGwYDVQQDExRUZXN0IFMv TUlNRSBSU0EgUm9vdDAeFw0wODAyMjIxMzUzMDdaFw0xNjA1MTExMzUzMDdaMEQx CzAJBgNVBAYTAlVLMRYwFAYDVQQKEw1PcGVuU1NMIEdyb3VwMR0wGwYDVQQDExRU ZXN0IFMvTUlNRSBSU0EgUm9vdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA wVdWf0OYDxe5aI3PKSlHcs+fiX9gd77OIXunoHpLoFp6CXbpIvS52nvyXIQf7KCF 9HKN5y3NdTbhRZZwFiTTAya9PJeQBwCS2DR3rxeZf3/aA0ML2bKXiodcaSACTagk 81XkP2S8evxnHCF1f8Q7iiIqL6iUz4EeVj5GCmsPvpUCAwEAAaNjMGEwHQYDVR0O BBYEFBPPS6e7iS6zOFcXdsabrWhb5e0XMB8GA1UdIwQYMBaAFBPPS6e7iS6zOFcX dsabrWhb5e0XMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMA0GCSqG SIb3DQEBBQUAA4GBAIECprq5viDvnDbkyOaiSr9ubMUmWqvycfAJMdPZRKcOZczS l+L9R9lF3JSqbt3knOe9u6bGDBOTY2285PdCCuHRVMk2Af1f6El1fqAlRUwNqipp r68sWFuRqrcRNtk6QQvXfkOhrqQBuDa7te/OVQLa2lGN9Dr2mQsD8ijctatG -----END CERTIFICATE-----
{ "pile_set_name": "Github" }
// File: platform.cpp // See Copyright Notice and license at the end of include/lzham.h #include "lzham_core.h" #include "lzham_timer.h" #include <assert.h> #if LZHAM_PLATFORM_X360 #include <xbdm.h> #endif #define LZHAM_FORCE_DEBUGGER_PRESENT 1 #ifndef _MSC_VER int sprintf_s(char *buffer, size_t sizeOfBuffer, const char *format, ...) { if (!sizeOfBuffer) return 0; va_list args; va_start(args, format); int c = vsnprintf(buffer, sizeOfBuffer, format, args); va_end(args); buffer[sizeOfBuffer - 1] = '\0'; if (c < 0) return static_cast<int>(sizeOfBuffer - 1); return LZHAM_MIN(c, (int)sizeOfBuffer - 1); } int vsprintf_s(char *buffer, size_t sizeOfBuffer, const char *format, va_list args) { if (!sizeOfBuffer) return 0; int c = vsnprintf(buffer, sizeOfBuffer, format, args); buffer[sizeOfBuffer - 1] = '\0'; if (c < 0) return static_cast<int>(sizeOfBuffer - 1); return LZHAM_MIN(c, (int)sizeOfBuffer - 1); } #endif // __GNUC__ bool lzham_is_debugger_present(void) { #if LZHAM_PLATFORM_X360 return DmIsDebuggerPresent() != 0; #elif LZHAM_USE_WIN32_API return IsDebuggerPresent() != 0; #elif LZHAM_FORCE_DEBUGGER_PRESENT return true; #else return false; #endif } void lzham_debug_break(void) { #if LZHAM_USE_WIN32_API __debugbreak(); // ESENTHEL CHANGED #elif (TARGET_OS_MAC == 1) && (TARGET_IPHONE_SIMULATOR == 0) && (TARGET_OS_IPHONE == 0) __asm {int 3} #else assert(0); #endif } void lzham_output_debug_string(const char* p) { LZHAM_NOTE_UNUSED(p); #if LZHAM_USE_WIN32_API OutputDebugStringA(p); #else fputs(p, stderr); #endif } #if LZHAM_BUFFERED_PRINTF // This stuff was a quick hack only intended for debugging/development. namespace lzham { struct buffered_str { enum { cBufSize = 256 }; char m_buf[cBufSize]; }; static lzham::vector<buffered_str> g_buffered_strings; static volatile long g_buffered_string_locked; static void lock_buffered_strings() { while (atomic_exchange32(&g_buffered_string_locked, 1) == 1) { lzham_yield_processor(); lzham_yield_processor(); lzham_yield_processor(); lzham_yield_processor(); } LZHAM_MEMORY_IMPORT_BARRIER } static void unlock_buffered_strings() { LZHAM_MEMORY_EXPORT_BARRIER atomic_exchange32(&g_buffered_string_locked, 0); } } // namespace lzham void lzham_buffered_printf(const char *format, ...) { format; char buf[lzham::buffered_str::cBufSize]; va_list args; va_start(args, format); vsnprintf_s(buf, sizeof(buf), sizeof(buf), format, args); va_end(args); buf[sizeof(buf) - 1] = '\0'; lzham::lock_buffered_strings(); if (!lzham::g_buffered_strings.capacity()) { lzham::g_buffered_strings.try_reserve(2048); } if (lzham::g_buffered_strings.try_resize(lzham::g_buffered_strings.size() + 1)) { memcpy(lzham::g_buffered_strings.back().m_buf, buf, sizeof(buf)); } lzham::unlock_buffered_strings(); } void lzham_flush_buffered_printf() { lzham::lock_buffered_strings(); for (lzham::uint i = 0; i < lzham::g_buffered_strings.size(); i++) { printf("%s", lzham::g_buffered_strings[i].m_buf); } lzham::g_buffered_strings.try_resize(0); lzham::unlock_buffered_strings(); } #endif
{ "pile_set_name": "Github" }
/* alphagrad.c This frei0r plugin fills alpha channel with a gradient Version 0.1 aug 2010 Copyright (C) 2010 Marko Cebokli http://lea.hamradio.si/~s57uuu 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ //compile: gcc -c -fPIC -Wall alphagrad.c -o alphagrad.o //link: gcc -shared -o alphagrad.so alphagrad.o #include <stdio.h> #include <frei0r.h> #include <stdlib.h> #include <math.h> #include <assert.h> //---------------------------------------- //struktura za instanco efekta typedef struct { int h; int w; float poz,wdt,tilt,min,max; uint32_t *gr8; int op; } inst; //----------------------------------------------------- //RGBA8888 little endian void fill_grad(inst *in) { int i,j; float st,ct,po,wd,d,a; st=sinf(in->tilt); ct=cosf(in->tilt); po=(-in->w/2.0+in->poz*in->w)*1.5; wd=in->wdt*in->w; if (in->min==in->max) { for (i=0;i<in->h*in->w;i++) in->gr8[i]=(((uint32_t)(in->min*255.0))<<24)&0xFF000000; return; } for (i=0;i<in->h;i++) for (j=0;j<in->w;j++) { d=(i-in->h/2)*ct+(j-in->w/2)*st-po; if (fabsf(d)>wd/2.0) { if (d>0.0) a=in->min; else a=in->max; } else { if (d>wd/2.0) d=wd/2.0; a = in->min+(wd/2.0-d) / wd*(in->max-in->min); } a=255.0*a; in->gr8[i*in->w+j] = (((uint32_t)a)<<24)&0xFF000000; } } //----------------------------------------------------- //stretch [0...1] to parameter range [min...max] linear float map_value_forward(double v, float min, float max) { return min+(max-min)*v; } //----------------------------------------------------- //collapse from parameter range [min...max] to [0...1] linear double map_value_backward(float v, float min, float max) { return (v-min)/(max-min); } //*********************************************** // OBVEZNE FREI0R FUNKCIJE //----------------------------------------------- int f0r_init() { return 1; } //------------------------------------------------ void f0r_deinit() { } //----------------------------------------------- void f0r_get_plugin_info(f0r_plugin_info_t* info) { info->name="alphagrad"; info->author="Marko Cebokli"; info->plugin_type=F0R_PLUGIN_TYPE_FILTER; info->color_model=F0R_COLOR_MODEL_RGBA8888; info->frei0r_version=FREI0R_MAJOR_VERSION; info->major_version=0; info->minor_version=2; info->num_params=6; info->explanation="Fills alpha channel with a gradient"; } //-------------------------------------------------- void f0r_get_param_info(f0r_param_info_t* info, int param_index) { switch(param_index) { case 0: info->name = "Position"; info->type = F0R_PARAM_DOUBLE; info->explanation = ""; break; case 1: info->name = "Transition width"; info->type = F0R_PARAM_DOUBLE; info->explanation = ""; break; case 2: info->name = "Tilt"; info->type = F0R_PARAM_DOUBLE; info->explanation = ""; break; case 3: info->name = "Min"; info->type = F0R_PARAM_DOUBLE; info->explanation = ""; break; case 4: info->name = "Max"; info->type = F0R_PARAM_DOUBLE; info->explanation = ""; break; case 5: info->name = "Operation"; info->type = F0R_PARAM_DOUBLE; info->explanation = ""; break; } } //---------------------------------------------- f0r_instance_t f0r_construct(unsigned int width, unsigned int height) { inst *in; in=calloc(1,sizeof(inst)); in->w=width; in->h=height; in->poz=0.5; in->wdt=0.5; in->tilt=0.0; in->min=0.0; in->max=1.0; in->op=0; in->gr8 = (uint32_t*)calloc(in->w*in->h, sizeof(uint32_t)); fill_grad(in); return (f0r_instance_t)in; } //--------------------------------------------------- void f0r_destruct(f0r_instance_t instance) { inst *in; in=(inst*)instance; free(in->gr8); free(instance); } //----------------------------------------------------- void f0r_set_param_value(f0r_instance_t instance, f0r_param_t parm, int param_index) { inst *p; double tmpf; int tmpi,chg; p=(inst*)instance; chg=0; switch(param_index) { case 0: tmpf=*((double*)parm); if (tmpf!=p->poz) chg=1; p->poz=tmpf; break; case 1: tmpf=*((double*)parm); if (tmpf!=p->wdt) chg=1; p->wdt=tmpf; break; case 2: tmpf=map_value_forward(*((double*)parm), -3.15, 3.15); if (tmpf!=p->tilt) chg=1; p->tilt=tmpf; break; case 3: tmpf=*((double*)parm); if (tmpf!=p->min) chg=1; p->min=tmpf; break; case 4: tmpf=*((double*)parm); if (tmpf!=p->max) chg=1; p->max=tmpf; break; case 5: tmpi=map_value_forward(*((double*)parm), 0.0, 4.9999); if (p->op != tmpi) chg=1; p->op=tmpi; break; } if (chg==0) return; fill_grad(p); } //-------------------------------------------------- void f0r_get_param_value(f0r_instance_t instance, f0r_param_t param, int param_index) { inst *p; p=(inst*)instance; switch(param_index) { case 0: *((double*)param)=p->poz; break; case 1: *((double*)param)=p->wdt; break; case 2: *((double*)param)=map_value_backward(p->tilt, -3.15, 3.15); break; case 3: *((double*)param)=p->min; break; case 4: *((double*)param)=p->max; break; case 5: *((double*)param)=map_value_backward(p->op, 0.0, 4.9999); break; } } //------------------------------------------------- //RGBA8888 little endian void f0r_update(f0r_instance_t instance, double time, const uint32_t* inframe, uint32_t* outframe) { inst *in; int i; uint32_t t; assert(instance); in=(inst*)instance; switch (in->op) { case 0: //write on clear for (i=0;i<in->h*in->w;i++) outframe[i] = (inframe[i]&0x00FFFFFF) | in->gr8[i]; break; case 1: //max for (i=0;i<in->h*in->w;i++) { t=((inframe[i]&0xFF000000)>in->gr8[i]) ? inframe[i]&0xFF000000 : in->gr8[i]; outframe[i] = (inframe[i]&0x00FFFFFF) | t; } break; case 2: //min for (i=0;i<in->h*in->w;i++) { t=((inframe[i]&0xFF000000)<in->gr8[i]) ? inframe[i]&0xFF000000 : in->gr8[i]; outframe[i] = (inframe[i]&0x00FFFFFF) | t; } break; case 3: //add for (i=0;i<in->h*in->w;i++) { t=((inframe[i]&0xFF000000)>>1)+(in->gr8[i]>>1); t = (t>0x7F800000) ? 0xFF000000 : t<<1; outframe[i] = (inframe[i]&0x00FFFFFF) | t; } break; case 4: //subtract for (i=0;i<in->h*in->w;i++) { t= ((inframe[i]&0xFF000000)>in->gr8[i]) ? (inframe[i]&0xFF000000)-in->gr8[i] : 0; outframe[i] = (inframe[i]&0x00FFFFFF) | t; } break; default: break; } } //**********************************************************
{ "pile_set_name": "Github" }
Filter 1: ON PK Fc 31 Hz Gain -9.4 dB Q 1.41 Filter 2: ON PK Fc 62 Hz Gain -7.4 dB Q 1.41 Filter 3: ON PK Fc 125 Hz Gain -6.5 dB Q 1.41 Filter 4: ON PK Fc 250 Hz Gain -6.8 dB Q 1.41 Filter 5: ON PK Fc 500 Hz Gain -5.5 dB Q 1.41 Filter 6: ON PK Fc 1000 Hz Gain -2.1 dB Q 1.41 Filter 7: ON PK Fc 2000 Hz Gain 4.7 dB Q 1.41 Filter 8: ON PK Fc 4000 Hz Gain 5.0 dB Q 1.41 Filter 9: ON PK Fc 8000 Hz Gain 5.9 dB Q 1.41 Filter 10: ON PK Fc 16000 Hz Gain 8.7 dB Q 1.41
{ "pile_set_name": "Github" }
/* * Copyright (C) 2010 Michael Brown <[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 2 of the * License, or 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., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * You can also choose to distribute this program under the terms of * the Unmodified Binary Distribution Licence (as given in the file * COPYING.UBDL), provided that you have satisfied its requirements. */ #include <string.h> #include <stdio.h> #include <ipxe/command.h> #include <ipxe/parseopt.h> #include <ipxe/login_ui.h> FILE_LICENCE ( GPL2_OR_LATER_OR_UBDL ); /** @file * * Login commands * */ /** "login" options */ struct login_options {}; /** "login" option list */ static struct option_descriptor login_opts[] = {}; /** "login" command descriptor */ static struct command_descriptor login_cmd = COMMAND_DESC ( struct login_options, login_opts, 0, 0, NULL ); /** * "login" command * * @v argc Argument count * @v argv Argument list * @ret rc Return status code */ static int login_exec ( int argc, char **argv ) { struct login_options opts; int rc; /* Parse options */ if ( ( rc = parse_options ( argc, argv, &login_cmd, &opts ) ) != 0 ) return rc; /* Show login UI */ if ( ( rc = login_ui() ) != 0 ) { printf ( "Could not set credentials: %s\n", strerror ( rc ) ); return rc; } return 0; } /** Login commands */ struct command login_command __command = { .name = "login", .exec = login_exec, };
{ "pile_set_name": "Github" }
//===------------------------ __refstring ---------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef _LIBCPP_REFSTRING_H #define _LIBCPP_REFSTRING_H #include <__config> #include <stdexcept> #include <cstddef> #include <cstring> #ifdef __APPLE__ #include <dlfcn.h> #include <mach-o/dyld.h> #endif #include "atomic_support.h" _LIBCPP_BEGIN_NAMESPACE_STD namespace __refstring_imp { namespace { typedef int count_t; struct _Rep_base { std::size_t len; std::size_t cap; count_t count; }; inline _Rep_base* rep_from_data(const char *data_) noexcept { char *data = const_cast<char *>(data_); return reinterpret_cast<_Rep_base *>(data - sizeof(_Rep_base)); } inline char * data_from_rep(_Rep_base *rep) noexcept { char *data = reinterpret_cast<char *>(rep); return data + sizeof(*rep); } #if defined(__APPLE__) inline const char* compute_gcc_empty_string_storage() _NOEXCEPT { void* handle = dlopen("/usr/lib/libstdc++.6.dylib", RTLD_NOLOAD); if (handle == nullptr) return nullptr; void* sym = dlsym(handle, "_ZNSs4_Rep20_S_empty_rep_storageE"); if (sym == nullptr) return nullptr; return data_from_rep(reinterpret_cast<_Rep_base *>(sym)); } inline const char* get_gcc_empty_string_storage() _NOEXCEPT { static const char* p = compute_gcc_empty_string_storage(); return p; } #endif }} // namespace __refstring_imp using namespace __refstring_imp; inline __libcpp_refstring::__libcpp_refstring(const char* msg) { std::size_t len = strlen(msg); _Rep_base* rep = static_cast<_Rep_base *>(::operator new(sizeof(*rep) + len + 1)); rep->len = len; rep->cap = len; rep->count = 0; char *data = data_from_rep(rep); std::memcpy(data, msg, len + 1); __imp_ = data; } inline __libcpp_refstring::__libcpp_refstring(const __libcpp_refstring &s) _NOEXCEPT : __imp_(s.__imp_) { if (__uses_refcount()) __libcpp_atomic_add(&rep_from_data(__imp_)->count, 1); } inline __libcpp_refstring& __libcpp_refstring::operator=(__libcpp_refstring const& s) _NOEXCEPT { bool adjust_old_count = __uses_refcount(); struct _Rep_base *old_rep = rep_from_data(__imp_); __imp_ = s.__imp_; if (__uses_refcount()) __libcpp_atomic_add(&rep_from_data(__imp_)->count, 1); if (adjust_old_count) { if (__libcpp_atomic_add(&old_rep->count, count_t(-1)) < 0) { ::operator delete(old_rep); } } return *this; } inline __libcpp_refstring::~__libcpp_refstring() { if (__uses_refcount()) { _Rep_base* rep = rep_from_data(__imp_); if (__libcpp_atomic_add(&rep->count, count_t(-1)) < 0) { ::operator delete(rep); } } } inline bool __libcpp_refstring::__uses_refcount() const { #ifdef __APPLE__ return __imp_ != get_gcc_empty_string_storage(); #else return true; #endif } _LIBCPP_END_NAMESPACE_STD #endif //_LIBCPP_REFSTRING_H
{ "pile_set_name": "Github" }
find_package(Git REQUIRED) set(neko_debian_dir ${bin_dir}/neko-debian) # format SNAPSHOT_VERSION execute_process( COMMAND ${GIT_EXECUTABLE} rev-parse --short HEAD OUTPUT_VARIABLE COMMIT_SHA OUTPUT_STRIP_TRAILING_WHITESPACE ) execute_process( COMMAND ${GIT_EXECUTABLE} show -s --format=%ct HEAD OUTPUT_VARIABLE COMMIT_TIME OUTPUT_STRIP_TRAILING_WHITESPACE ) execute_process( COMMAND date -u -d @${COMMIT_TIME} +%Y%m%d%H%M%S OUTPUT_VARIABLE COMMIT_TIME OUTPUT_STRIP_TRAILING_WHITESPACE ) set(SNAPSHOT_VERSION ${NEKO_VERSION}+1SNAPSHOT${COMMIT_TIME}+${COMMIT_SHA}) message(STATUS "building source package version ${SNAPSHOT_VERSION}") message(STATUS "setting up neko-debian repo") if (EXISTS ${neko_debian_dir}) execute_process( COMMAND ${GIT_EXECUTABLE} fetch --all WORKING_DIRECTORY ${neko_debian_dir} ) execute_process( COMMAND ${GIT_EXECUTABLE} clean -fx WORKING_DIRECTORY ${neko_debian_dir} ) execute_process( COMMAND ${GIT_EXECUTABLE} reset --hard HEAD WORKING_DIRECTORY ${neko_debian_dir} ) execute_process( COMMAND ${GIT_EXECUTABLE} tag -d upstream/${SNAPSHOT_VERSION} WORKING_DIRECTORY ${neko_debian_dir} ) else() execute_process( COMMAND ${GIT_EXECUTABLE} clone https://github.com/HaxeFoundation/neko-debian.git ${neko_debian_dir} ) endif() foreach(branch upstream next) execute_process( COMMAND ${GIT_EXECUTABLE} checkout ${branch} WORKING_DIRECTORY ${neko_debian_dir} ) execute_process( COMMAND ${GIT_EXECUTABLE} reset --hard origin/${branch} WORKING_DIRECTORY ${neko_debian_dir} ) endforeach() message(STATUS "import changes from source archive to neko-debian") get_filename_component(source_archive_name ${source_archive} NAME) file(COPY ${source_archive} DESTINATION ${bin_dir}) file(RENAME ${bin_dir}/${source_archive_name} ${bin_dir}/neko_${SNAPSHOT_VERSION}.orig.tar.gz) execute_process( COMMAND gbp import-orig ${bin_dir}/neko_${SNAPSHOT_VERSION}.orig.tar.gz -u ${SNAPSHOT_VERSION} --debian-branch=next WORKING_DIRECTORY ${neko_debian_dir} ) set(distros trusty xenial zesty artful bionic ) if (DEFINED ENV{PPA}) set(PPA $ENV{PPA}) else() set(PPA "ppa:haxe/snapshots") endif() foreach(distro ${distros}) message(STATUS "backporting to ${distro} and will upload to ${PPA}") execute_process( COMMAND ${GIT_EXECUTABLE} checkout . WORKING_DIRECTORY ${neko_debian_dir} ) execute_process( COMMAND ${GIT_EXECUTABLE} checkout next-${distro} WORKING_DIRECTORY ${neko_debian_dir} ) execute_process( COMMAND ${GIT_EXECUTABLE} clean -fx WORKING_DIRECTORY ${neko_debian_dir} ) execute_process( COMMAND ${GIT_EXECUTABLE} reset --hard origin/next-${distro} WORKING_DIRECTORY ${neko_debian_dir} ) execute_process( COMMAND ${GIT_EXECUTABLE} merge next -m "merge" WORKING_DIRECTORY ${neko_debian_dir} ) execute_process( COMMAND dch -v "${SNAPSHOT_VERSION}-1" --urgency low "snapshot build" WORKING_DIRECTORY ${neko_debian_dir} ) execute_process( COMMAND debuild -S -sa WORKING_DIRECTORY ${neko_debian_dir} ) execute_process( COMMAND backportpackage -d ${distro} --upload ${PPA} --yes neko_${SNAPSHOT_VERSION}-1.dsc WORKING_DIRECTORY ${bin_dir} ) endforeach()
{ "pile_set_name": "Github" }
package freenet.clients.http.updateableelements; import java.util.Timer; import java.util.TimerTask; import freenet.clients.http.SimpleToadletServer; import freenet.clients.http.ToadletContext; import freenet.support.Base64; import freenet.support.HTMLNode; /** A pushed element that counts up every second. Only for testing purposes. */ public class TesterElement extends BaseUpdateableElement { private int status = 0; private int maxStatus; ToadletContext ctx; Timer t; final String id; public TesterElement(ToadletContext ctx, String id, int max) { super("div","style","float:left;", ctx); this.id = id; this.ctx = ctx; this.maxStatus = max; init(true); t = new Timer(true); t.scheduleAtFixedRate(new TimerTask() { @Override public void run() { update(); } }, 0, 1000); } public void update() { status++; if (status >= maxStatus) { t.cancel(); } ((SimpleToadletServer) ctx.getContainer()).pushDataManager.updateElement(getUpdaterId(ctx.getUniqueId())); } @Override public void dispose() { t.cancel(); } @Override public String getUpdaterId(String requestId) { return getId(requestId,id); } public static String getId(String requestId,String id){ return Base64.encodeStandardUTF8(("test:" + requestId + "id:" + id+"gndfjkghghdfukggherugbdfkutg54ibngjkdfgyisdhiterbyjhuyfghdightw7i4tfgsdgo;dfnghsdbfuiyfgfoinfsdbufvwte4785tu4kgjdfnzukfbyfhe48e54gjfdjgbdruserigbfdnvbxdio;fherigtuseofjuodsvbyfhsd8ofghfio;")); } @Override public String getUpdaterType() { return UpdaterConstants.REPLACER_UPDATER; } @Override public void updateState(boolean initial) { children.clear(); addChild(new HTMLNode("img", "src","/imagecreator/?text="+status+"&width="+Math.min(status+30,300)+"&height="+Math.min(status+30,300))); } }
{ "pile_set_name": "Github" }
/* //@HEADER // ************************************************************************ // // Kokkos v. 3.0 // Copyright (2020) National Technology & Engineering // Solutions of Sandia, LLC (NTESS). // // Under the terms of Contract DE-NA0003525 with NTESS, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. 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. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY NTESS "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 NTESS OR THE // 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. // // Questions? Contact Christian R. Trott ([email protected]) // // ************************************************************************ //@HEADER */ #if defined(KOKKOS_ENABLE_RFO_PREFETCH) #include <xmmintrin.h> #endif #include <Kokkos_Macros.hpp> #if defined(KOKKOS_ATOMIC_HPP) && !defined(KOKKOS_ATOMIC_FETCH_SUB_HPP) #define KOKKOS_ATOMIC_FETCH_SUB_HPP #if defined(KOKKOS_ENABLE_CUDA) #include <Cuda/Kokkos_Cuda_Version_9_8_Compatibility.hpp> #endif namespace Kokkos { //---------------------------------------------------------------------------- #if defined(KOKKOS_ENABLE_CUDA) #if defined(__CUDA_ARCH__) || defined(KOKKOS_IMPL_CUDA_CLANG_WORKAROUND) // Support for int, unsigned int, unsigned long long int, and float __inline__ __device__ int atomic_fetch_sub(volatile int* const dest, const int val) { return atomicSub((int*)dest, val); } __inline__ __device__ unsigned int atomic_fetch_sub( volatile unsigned int* const dest, const unsigned int val) { return atomicSub((unsigned int*)dest, val); } __inline__ __device__ unsigned int atomic_fetch_sub( volatile int64_t* const dest, const int64_t val) { return atomic_fetch_add(dest, -val); } __inline__ __device__ unsigned int atomic_fetch_sub(volatile float* const dest, const float val) { return atomicAdd((float*)dest, -val); } #if (600 <= __CUDA_ARCH__) __inline__ __device__ unsigned int atomic_fetch_sub(volatile double* const dest, const double val) { return atomicAdd((double*)dest, -val); } #endif template <typename T> __inline__ __device__ T atomic_fetch_sub( volatile T* const dest, typename std::enable_if<sizeof(T) == sizeof(int), const T>::type val) { union U { int i; T t; KOKKOS_INLINE_FUNCTION U() {} } oldval, assume, newval; oldval.t = *dest; do { assume.i = oldval.i; newval.t = assume.t - val; oldval.i = atomicCAS((int*)dest, assume.i, newval.i); } while (assume.i != oldval.i); return oldval.t; } template <typename T> __inline__ __device__ T atomic_fetch_sub( volatile T* const dest, typename std::enable_if<sizeof(T) != sizeof(int) && sizeof(T) == sizeof(unsigned long long int), const T>::type val) { union U { unsigned long long int i; T t; KOKKOS_INLINE_FUNCTION U() {} } oldval, assume, newval; oldval.t = *dest; do { assume.i = oldval.i; newval.t = assume.t - val; oldval.i = atomicCAS((unsigned long long int*)dest, assume.i, newval.i); } while (assume.i != oldval.i); return oldval.t; } //---------------------------------------------------------------------------- template <typename T> __inline__ __device__ T atomic_fetch_sub(volatile T* const dest, typename std::enable_if<(sizeof(T) != 4) && (sizeof(T) != 8), const T>::type& val) { T return_val; // This is a way to (hopefully) avoid dead lock in a warp int done = 0; #ifdef KOKKOS_IMPL_CUDA_SYNCWARP_NEEDS_MASK unsigned int mask = KOKKOS_IMPL_CUDA_ACTIVEMASK; unsigned int active = KOKKOS_IMPL_CUDA_BALLOT_MASK(mask, 1); #else unsigned int active = KOKKOS_IMPL_CUDA_BALLOT(1); #endif unsigned int done_active = 0; while (active != done_active) { if (!done) { if (Impl::lock_address_cuda_space((void*)dest)) { Kokkos::memory_fence(); return_val = *dest; *dest = return_val - val; Kokkos::memory_fence(); Impl::unlock_address_cuda_space((void*)dest); done = 1; } } #ifdef KOKKOS_IMPL_CUDA_SYNCWARP_NEEDS_MASK done_active = KOKKOS_IMPL_CUDA_BALLOT_MASK(mask, done); #else done_active = KOKKOS_IMPL_CUDA_BALLOT(done); #endif } return return_val; } #endif #endif //---------------------------------------------------------------------------- #if !defined(KOKKOS_ENABLE_ROCM_ATOMICS) || !defined(KOKKOS_ENABLE_HIP_ATOMICS) #if !defined(__CUDA_ARCH__) || defined(KOKKOS_IMPL_CUDA_CLANG_WORKAROUND) #if defined(KOKKOS_ENABLE_GNU_ATOMICS) || defined(KOKKOS_ENABLE_INTEL_ATOMICS) inline int atomic_fetch_sub(volatile int* const dest, const int val) { #if defined(KOKKOS_ENABLE_RFO_PREFETCH) _mm_prefetch((const char*)dest, _MM_HINT_ET0); #endif return __sync_fetch_and_sub(dest, val); } inline long int atomic_fetch_sub(volatile long int* const dest, const long int val) { #if defined(KOKKOS_ENABLE_RFO_PREFETCH) _mm_prefetch((const char*)dest, _MM_HINT_ET0); #endif return __sync_fetch_and_sub(dest, val); } #if defined(KOKKOS_ENABLE_GNU_ATOMICS) inline unsigned int atomic_fetch_sub(volatile unsigned int* const dest, const unsigned int val) { #if defined(KOKKOS_ENABLE_RFO_PREFETCH) _mm_prefetch((const char*)dest, _MM_HINT_ET0); #endif return __sync_fetch_and_sub(dest, val); } inline unsigned long int atomic_fetch_sub( volatile unsigned long int* const dest, const unsigned long int val) { #if defined(KOKKOS_ENABLE_RFO_PREFETCH) _mm_prefetch((const char*)dest, _MM_HINT_ET0); #endif return __sync_fetch_and_sub(dest, val); } #endif template <typename T> inline T atomic_fetch_sub( volatile T* const dest, typename std::enable_if<sizeof(T) == sizeof(int), const T>::type val) { union U { int i; T t; KOKKOS_INLINE_FUNCTION U() {} } oldval, assume, newval; #if defined(KOKKOS_ENABLE_RFO_PREFETCH) _mm_prefetch((const char*)dest, _MM_HINT_ET0); #endif oldval.t = *dest; do { assume.i = oldval.i; newval.t = assume.t - val; oldval.i = __sync_val_compare_and_swap((int*)dest, assume.i, newval.i); } while (assume.i != oldval.i); return oldval.t; } template <typename T> inline T atomic_fetch_sub(volatile T* const dest, typename std::enable_if<sizeof(T) != sizeof(int) && sizeof(T) == sizeof(long), const T>::type val) { #if defined(KOKKOS_ENABLE_RFO_PREFETCH) _mm_prefetch((const char*)dest, _MM_HINT_ET0); #endif union U { long i; T t; KOKKOS_INLINE_FUNCTION U() {} } oldval, assume, newval; oldval.t = *dest; do { assume.i = oldval.i; newval.t = assume.t - val; oldval.i = __sync_val_compare_and_swap((long*)dest, assume.i, newval.i); } while (assume.i != oldval.i); return oldval.t; } //---------------------------------------------------------------------------- template <typename T> inline T atomic_fetch_sub( volatile T* const dest, typename std::enable_if<(sizeof(T) != 4) && (sizeof(T) != 8), const T>::type& val) { #if defined(KOKKOS_ENABLE_RFO_PREFETCH) _mm_prefetch((const char*)dest, _MM_HINT_ET0); #endif while (!Impl::lock_address_host_space((void*)dest)) ; Kokkos::memory_fence(); T return_val = *dest; *dest = return_val - val; Kokkos::memory_fence(); Impl::unlock_address_host_space((void*)dest); return return_val; } //---------------------------------------------------------------------------- #elif defined(KOKKOS_ENABLE_OPENMP_ATOMICS) template <typename T> T atomic_fetch_sub(volatile T* const dest, const T val) { T retval; #pragma omp atomic capture { retval = dest[0]; dest[0] -= val; } return retval; } #elif defined(KOKKOS_ENABLE_SERIAL_ATOMICS) template <typename T> T atomic_fetch_sub(volatile T* const dest_v, const T val) { T* dest = const_cast<T*>(dest_v); T retval = *dest; *dest -= val; return retval; } #endif #endif #endif // !defined ROCM_ATOMICS // dummy for non-CUDA Kokkos headers being processed by NVCC #if defined(__CUDA_ARCH__) && !defined(KOKKOS_ENABLE_CUDA) template <typename T> __inline__ __device__ T atomic_fetch_sub(volatile T* const, Kokkos::Impl::identity_t<T>) { return T(); } #endif } // namespace Kokkos #include <impl/Kokkos_Atomic_Assembly.hpp> #endif
{ "pile_set_name": "Github" }
{ "name": "helloxz/imgurl", "description": "ImgURL is a simple, pure graph bed program, simple installation, powerful.", "type": "project", "license": "GPL-3.0", "authors": [ { "name": "xiaoz", "email": "[email protected]" } ], "minimum-stability": "stable", "require": {} }
{ "pile_set_name": "Github" }
package com.blogcode.after; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * Created by [email protected] on 2017. 2. 6. * Blog : http://jojoldu.tistory.com * Github : http://github.com/jojoldu */ @Configuration public class AppConfig { @Bean public EnumMapper enumMapper() { EnumMapper enumMapper = new EnumMapper(); enumMapper.put("commissionType", EnumContract.CommissionType.class); enumMapper.put("commissionCutting", EnumContract.CommissionCutting.class); return enumMapper; } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>microcks</artifactId> <groupId>io.github.microcks</groupId> <version>1.0.1-SNAPSHOT</version> <relativePath>../../pom.xml</relativePath> </parent> <modelVersion>4.0.0</modelVersion> <name>Microcks Async Minion</name> <artifactId>microcks-async-minion</artifactId> <properties> <compiler-plugin.version>3.8.1</compiler-plugin.version> <maven.compiler.parameters>true</maven.compiler.parameters> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <quarkus-plugin.version>1.5.2.Final</quarkus-plugin.version> <quarkus.platform.artifact-id>quarkus-universe-bom</quarkus.platform.artifact-id> <quarkus.platform.group-id>io.quarkus</quarkus.platform.group-id> <quarkus.platform.version>1.5.2.Final</quarkus.platform.version> <surefire-plugin.version>2.22.1</surefire-plugin.version> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>${quarkus.platform.group-id}</groupId> <artifactId>${quarkus.platform.artifact-id}</artifactId> <version>${quarkus.platform.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-rest-client</artifactId> </dependency> <dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-resteasy-jackson</artifactId> </dependency> <dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-smallrye-reactive-messaging-kafka</artifactId> </dependency> <dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-smallrye-health</artifactId> </dependency> <dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-quartz</artifactId> </dependency> <dependency> <groupId>io.github.microcks</groupId> <artifactId>microcks-model</artifactId> <version>${project.version}</version> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>io.github.microcks</groupId> <artifactId>microcks-util</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>io.github.microcks</groupId> <artifactId>microcks-el</artifactId> <version>${project.version}</version> </dependency> <!-- Test related dependencies --> <dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-junit5</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>io.quarkus</groupId> <artifactId>quarkus-maven-plugin</artifactId> <version>${quarkus-plugin.version}</version> <executions> <execution> <goals> <goal>build</goal> </goals> </execution> </executions> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>${compiler-plugin.version}</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>${surefire-plugin.version}</version> <configuration> <systemProperties> <java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager> </systemProperties> </configuration> </plugin> </plugins> </build> <profiles> <profile> <id>native</id> <activation> <property> <name>native</name> </property> </activation> <build> <plugins> <plugin> <artifactId>maven-failsafe-plugin</artifactId> <version>${surefire-plugin.version}</version> <executions> <execution> <goals> <goal>integration-test</goal> <goal>verify</goal> </goals> <configuration> <systemProperties> <native.image.path>${project.build.directory}/${project.build.finalName}-runner</native.image.path> </systemProperties> </configuration> </execution> </executions> </plugin> </plugins> </build> <properties> <quarkus.package.type>native</quarkus.package.type> </properties> </profile> </profiles> </project>
{ "pile_set_name": "Github" }
/* Copyright 2019 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package version // Base version information. // // This is the fallback data used when version information from git is not // provided via go ldflags. It provides an approximation of the Kubernetes // version for ad-hoc builds (e.g. `go build`) that cannot get the version // information from git. // // If you are looking at these fields in the git tree, they look // strange. They are modified on the fly by the build process. The // in-tree values are dummy values used for "git archive", which also // works for GitHub tar downloads. // // When releasing a new Kubernetes version, this file is updated by // build/mark_new_version.sh to reflect the new version, and then a // git annotated tag (using format vX.Y where X == Major version and Y // == Minor version) is created to point to the commit that updates // component-base/version/base.go var ( // TODO: Deprecate gitMajor and gitMinor, use only gitVersion // instead. First step in deprecation, keep the fields but make // them irrelevant. (Next we'll take it out, which may muck with // scripts consuming the kubectl version output - but most of // these should be looking at gitVersion already anyways.) gitMajor string // major version, always numeric gitMinor string // minor version, numeric possibly followed by "+" // semantic version, derived by build scripts (see // https://github.com/kubernetes/community/blob/master/contributors/design-proposals/release/versioning.md // for a detailed discussion of this field) // // TODO: This field is still called "gitVersion" for legacy // reasons. For prerelease versions, the build metadata on the // semantic version is a git hash, but the version itself is no // longer the direct output of "git describe", but a slight // translation to be semver compliant. // NOTE: The $Format strings are replaced during 'git archive' thanks to the // companion .gitattributes file containing 'export-subst' in this same // directory. See also https://git-scm.com/docs/gitattributes gitVersion = "v0.0.0-master+$Format:%h$" gitCommit = "$Format:%H$" // sha1 from git, output of $(git rev-parse HEAD) gitTreeState = "" // state of git tree, either "clean" or "dirty" buildDate = "1970-01-01T00:00:00Z" // build date in ISO8601 format, output of $(date -u +'%Y-%m-%dT%H:%M:%SZ') )
{ "pile_set_name": "Github" }
package com.ifmvo.togetherad.core.helper import android.app.Activity import org.jetbrains.annotations.NotNull import android.view.ViewGroup import com.ifmvo.togetherad.core.R import com.ifmvo.togetherad.core.TogetherAd import com.ifmvo.togetherad.core.config.AdProviderLoader import com.ifmvo.togetherad.core.custom.flow.BaseNativeTemplate import com.ifmvo.togetherad.core.listener.NativeListener import com.ifmvo.togetherad.core.listener.NativeViewListener import com.ifmvo.togetherad.core.utils.AdRandomUtil import com.ifmvo.togetherad.core.utils.loge import org.jetbrains.annotations.Nullable /** * 原生自渲染广告 * * Created by Matthew Chen on 2020-04-20. */ @Deprecated(message = "设计上考虑不周全,使用单例导致无法同时请求多次", replaceWith = ReplaceWith(expression = "AdHelperNativePro", imports = ["com.ifmvo.togetherad.core.helper"])) object AdHelperNative : BaseHelper() { private const val defaultMaxCount = 4 //为了照顾 Java 调用的同学 fun getList(@NotNull activity: Activity, @NotNull alias: String, maxCount: Int = defaultMaxCount, listener: NativeListener? = null) { getList(activity, alias, null, maxCount, listener) } fun getList(@NotNull activity: Activity, @NotNull alias: String, radioMap: Map<String, Int>? = null, maxCount: Int = defaultMaxCount, listener: NativeListener? = null) { val currentMaxCount = if (maxCount <= 0) defaultMaxCount else maxCount val currentRadioMap = if (radioMap?.isEmpty() != false) TogetherAd.getPublicProviderRadio() else radioMap val adProviderType = AdRandomUtil.getRandomAdProvider(currentRadioMap) if (adProviderType?.isEmpty() != false) { listener?.onAdFailedAll() return } val adProvider = AdProviderLoader.loadAdProvider(adProviderType) if (adProvider == null) { "$adProviderType ${activity.getString(R.string.no_init)}".loge() val newRadioMap = filterType(radioMap = currentRadioMap, adProviderType = adProviderType) getList(activity = activity, alias = alias, radioMap = newRadioMap, maxCount = maxCount, listener = listener) return } adProvider.getNativeAdList(activity = activity, adProviderType = adProviderType, alias = alias, maxCount = currentMaxCount, listener = object : NativeListener { override fun onAdStartRequest(providerType: String) { listener?.onAdStartRequest(providerType) } override fun onAdLoaded(providerType: String, adList: List<Any>) { listener?.onAdLoaded(providerType, adList) } override fun onAdFailed(providerType: String, failedMsg: String?) { listener?.onAdFailed(providerType, failedMsg) val newRadioMap = filterType(radioMap = currentRadioMap, adProviderType = adProviderType) getList(activity = activity, alias = alias, radioMap = newRadioMap, maxCount = maxCount, listener = listener) } }) } fun show(@NotNull adObject: Any, @NotNull container: ViewGroup, @NotNull nativeTemplate: BaseNativeTemplate, @Nullable listener: NativeViewListener? = null) { TogetherAd.mProviders.entries.forEach { entry -> val adProvider = AdProviderLoader.loadAdProvider(entry.key) if (adProvider?.nativeAdIsBelongTheProvider(adObject) == true) { val nativeView = nativeTemplate.getNativeView(entry.key) nativeView?.showNative(entry.key, adObject, container, listener) return@forEach } } } }
{ "pile_set_name": "Github" }
/*$ Copyright (C) 2013-2020 Azel. This file is part of AzPainter. AzPainter 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. AzPainter 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/>. $*/ /***************************************** * 中間色グラデーションバー *****************************************/ /* * [notify] * type : 0-色選択 1-左の色変更 2-右の色変更 * param1 : 色 */ #include "mDef.h" #include "mWidgetDef.h" #include "mWidget.h" #include "mSysCol.h" #include "mPixbuf.h" #include "mEvent.h" #include "defDraw.h" //--------------------- typedef struct { mWidget wg; uint32_t col[2]; int rgb[2][3], //左右の RGB 値 rgb_diff[3], //左右の RGB 色差 rgb_diff_step[3], //左右の RGB 色差 (段階有効時) step, //段階数 fdrag, curx, //ドラッグ時のカーソル位置 last_gradx; //ドラッグ時、前回のグラデーション部分X位置 (-1 で最初) }GradBar; //--------------------- #define _BAR_H 13 #define _BETWEEN 4 //端の色とグラデーションの間 //--------------------- //======================== // sub //======================== /** 色から RGB 値取得してセット */ static void _set_rgb(GradBar *p) { int i,j,sf; uint32_t c; //R,G,B for(i = 0; i < 2; i++) { c = p->col[i]; for(j = 0, sf = 16; j < 3; j++, sf -= 8) p->rgb[i][j] = (c >> sf) & 255; } //色差 for(i = 0; i < 3; i++) { j = p->rgb[1][i] - p->rgb[0][i]; p->rgb_diff[i] = j; if((j & 1) && j > 0) j++; p->rgb_diff_step[i] = j; } } /** ドラッグ移動時、色を取得して通知 */ static void _on_motion(GradBar *p,int curx) { int i,x,w,c[3],step,stepno; double d; x = curx - (_BAR_H + _BETWEEN + 1); //グラデーション部分を先頭とした位置 w = p->wg.w - (_BAR_H + _BETWEEN) * 2 - 2; if(x < 0) x = 0; else if(x >= w) x = w - 1; //前回位置と比較 if(p->last_gradx == x) return; p->last_gradx = x; p->curx = x + _BAR_H + _BETWEEN + 1; //色取得 step = p->step; if(step < 3) { //通常 d = (double)x / (w - 1); for(i = 0; i < 3; i++) c[i] = (int)(p->rgb_diff[i] * d + p->rgb[0][i] + 0.5); } else { //段階あり stepno = x * step / w; if(stepno == step - 1) { //終端の色 for(i = 0; i < 3; i++) c[i] = p->rgb[1][i]; } else { for(i = 0; i < 3; i++) c[i] = stepno * p->rgb_diff_step[i] / (step - 1) + p->rgb[0][i]; } } //通知 mWidgetAppendEvent_notify(NULL, M_WIDGET(p), 0, M_RGB(c[0], c[1], c[2]), 0); mWidgetUpdate(M_WIDGET(p)); } //======================== // ハンドラ //======================== /** 押し時 */ static void _event_press(GradBar *p,int x) { int w = p->wg.w,no; if(x < _BAR_H || x >= w - _BAR_H) { //左右の色 : 描画色セット no = (x >= w - _BAR_H); p->col[no] = APP_DRAW->col.drawcol; _set_rgb(p); mWidgetUpdate(M_WIDGET(p)); mWidgetAppendEvent_notify(NULL, M_WIDGET(p), 1 + no, APP_DRAW->col.drawcol, 0); } else if(x >= _BAR_H + _BETWEEN + 1 && x < w - _BAR_H - _BETWEEN) { //グラデーション部分 (枠は含まない) p->fdrag = 1; p->last_gradx = -1; _on_motion(p, x); mWidgetGrabPointer(M_WIDGET(p)); } } /** グラブ解除 */ static void _grab_release(GradBar *p) { if(p->fdrag) { p->fdrag = 0; mWidgetUngrabPointer(M_WIDGET(p)); mWidgetUpdate(M_WIDGET(p)); } } /** イベント */ static int _event_handle(mWidget *wg,mEvent *ev) { GradBar *p = (GradBar *)wg; switch(ev->type) { case MEVENT_POINTER: if(ev->pt.type == MEVENT_POINTER_TYPE_MOTION) { //移動 if(p->fdrag) _on_motion(p, ev->pt.x); } else if(ev->pt.type == MEVENT_POINTER_TYPE_PRESS) { //押し if(ev->pt.btt == M_BTT_LEFT && !p->fdrag) _event_press(p, ev->pt.x); } else if(ev->pt.type == MEVENT_POINTER_TYPE_RELEASE) { //離し if(ev->pt.btt == M_BTT_LEFT) _grab_release(p); } break; case MEVENT_FOCUS: if(ev->focus.bOut) _grab_release(p); break; } return 1; } /** 描画 */ static void _draw_handle(mWidget *wg,mPixbuf *pixbuf) { GradBar *p = (GradBar *)wg; int i,j,x,w,c[3],step,stepno; uint32_t col; uint8_t *pd,*pd_y; mBox box; w = wg->w; //背景色 mPixbufFillBox(pixbuf, 0, 0, wg->w, _BAR_H, MSYSCOL(FACE)); //端の色 for(i = 0, x = 0; i < 2; i++) { mPixbufBox(pixbuf, x, 0, _BAR_H, _BAR_H, 0); mPixbufFillBox(pixbuf, x + 1, 1, _BAR_H - 2, _BAR_H - 2, mRGBtoPix(p->col[i])); x = w - _BAR_H; } //グラデーション w -= (_BAR_H + _BETWEEN) * 2; mPixbufBox(pixbuf, _BAR_H + _BETWEEN, 0, w, _BAR_H, 0); if(mPixbufGetClipBox_d(pixbuf, &box, _BAR_H + _BETWEEN + 1, 1, w - 2, _BAR_H - 2)) { pd = mPixbufGetBufPtFast(pixbuf, box.x, box.y); x = box.x - (_BAR_H + _BETWEEN + 1); w -= 2; step = p->step; if(step < 3) w--; for(i = 0; i < box.w; i++, x++, pd += pixbuf->bpp) { if(step < 3) { //通常 for(j = 0; j < 3; j++) c[j] = p->rgb_diff[j] * x / w + p->rgb[0][j]; } else { //段階あり stepno = x * step / w; if(stepno == step - 1) { //終端 for(j = 0; j < 3; j++) c[j] = p->rgb[1][j]; } else { for(j = 0; j < 3; j++) c[j] = stepno * p->rgb_diff_step[j] / (step - 1) + p->rgb[0][j]; } } col = mRGBtoPix2(c[0], c[1], c[2]); //Y を同じ色で埋める for(j = _BAR_H - 2, pd_y = pd; j; j--, pd_y += pixbuf->pitch_dir) (pixbuf->setbuf)(pd_y, col); } } //カーソル if(p->fdrag) mPixbufLineV(pixbuf, p->curx, 0, _BAR_H, MPIXBUF_COL_XOR); } //======================== /** 作成 */ mWidget *DockColorPalette_GradationBar_new(mWidget *parent, int id,uint32_t colL,uint32_t colR,int step) { GradBar *p; p = (GradBar *)mWidgetNew(sizeof(GradBar), parent); p->col[0] = colL; p->col[1] = colR; p->step = step; p->wg.id = id; p->wg.fEventFilter |= MWIDGET_EVENTFILTER_POINTER; p->wg.fLayout = MLF_EXPAND_W; p->wg.hintH = _BAR_H; p->wg.hintW = 80; p->wg.draw = _draw_handle; p->wg.event = _event_handle; _set_rgb(p); return (mWidget *)p; } /** 段階数変更 */ void DockColorPalette_GradationBar_setStep(mWidget *wg,int step) { ((GradBar *)wg)->step = step; mWidgetUpdate(wg); }
{ "pile_set_name": "Github" }
<accessControl> <resource uri="/axis2/*"> <clients> <ip>192.168.2.*</ip> </clients> </resource> </accessControl>
{ "pile_set_name": "Github" }
// Copyright 2015 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 linux // +build arm64 // +build !gccgo #include "textflag.h" // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. TEXT ·Syscall(SB),NOSPLIT,$0-56 B syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-80 B syscall·Syscall6(SB) TEXT ·RawSyscall(SB),NOSPLIT,$0-56 B syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 B syscall·RawSyscall6(SB)
{ "pile_set_name": "Github" }
{ "title":"matchMedia", "description":"API for finding out whether or not a media query applies to the document.", "spec":"https://www.w3.org/TR/cssom-view/#dom-window-matchmedia", "status":"wd", "links":[ { "url":"https://github.com/paulirish/matchMedia.js/", "title":"matchMedia.js polyfill" }, { "url":"https://developer.mozilla.org/en/DOM/window.matchMedia", "title":"MDN Web Docs - matchMedia" }, { "url":"https://developer.mozilla.org/en/CSS/Using_media_queries_from_code", "title":"MDN Web Docs - Using matchMedia" }, { "url":"https://www.webplatform.org/docs/css/media_queries/apis/matchMedia", "title":"WebPlatform Docs" } ], "bugs":[ { "description":"MediaQueryList.addEventListener [doesn't work in Safari and IE](https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList#Browser_compatibility)" } ], "categories":[ "DOM", "JS API" ], "stats":{ "ie":{ "5.5":"n", "6":"n", "7":"n", "8":"n", "9":"n", "10":"y", "11":"y" }, "edge":{ "12":"y", "13":"y", "14":"y", "15":"y", "16":"y", "17":"y", "18":"y", "79":"y", "80":"y", "81":"y", "83":"y", "84":"y", "85":"y" }, "firefox":{ "2":"n", "3":"n", "3.5":"n", "3.6":"n", "4":"n", "5":"n", "6":"y", "7":"y", "8":"y", "9":"y", "10":"y", "11":"y", "12":"y", "13":"y", "14":"y", "15":"y", "16":"y", "17":"y", "18":"y", "19":"y", "20":"y", "21":"y", "22":"y", "23":"y", "24":"y", "25":"y", "26":"y", "27":"y", "28":"y", "29":"y", "30":"y", "31":"y", "32":"y", "33":"y", "34":"y", "35":"y", "36":"y", "37":"y", "38":"y", "39":"y", "40":"y", "41":"y", "42":"y", "43":"y", "44":"y", "45":"y", "46":"y", "47":"y", "48":"y", "49":"y", "50":"y", "51":"y", "52":"y", "53":"y", "54":"y", "55":"y", "56":"y", "57":"y", "58":"y", "59":"y", "60":"y", "61":"y", "62":"y", "63":"y", "64":"y", "65":"y", "66":"y", "67":"y", "68":"y", "69":"y", "70":"y", "71":"y", "72":"y", "73":"y", "74":"y", "75":"y", "76":"y", "77":"y", "78":"y", "79":"y", "80":"y", "81":"y", "82":"y" }, "chrome":{ "4":"n", "5":"n", "6":"n", "7":"n", "8":"n", "9":"y", "10":"y", "11":"y", "12":"y", "13":"y", "14":"y", "15":"y", "16":"y", "17":"y", "18":"y", "19":"y", "20":"y", "21":"y", "22":"y", "23":"y", "24":"y", "25":"y", "26":"y", "27":"y", "28":"y", "29":"y", "30":"y", "31":"y", "32":"y", "33":"y", "34":"y", "35":"y", "36":"y", "37":"y", "38":"y", "39":"y", "40":"y", "41":"y", "42":"y", "43":"y", "44":"y", "45":"y", "46":"y", "47":"y", "48":"y", "49":"y", "50":"y", "51":"y", "52":"y", "53":"y", "54":"y", "55":"y", "56":"y", "57":"y", "58":"y", "59":"y", "60":"y", "61":"y", "62":"y", "63":"y", "64":"y", "65":"y", "66":"y", "67":"y", "68":"y", "69":"y", "70":"y", "71":"y", "72":"y", "73":"y", "74":"y", "75":"y", "76":"y", "77":"y", "78":"y", "79":"y", "80":"y", "81":"y", "83":"y", "84":"y", "85":"y", "86":"y", "87":"y", "88":"y" }, "safari":{ "3.1":"n", "3.2":"n", "4":"n", "5":"n", "5.1":"y", "6":"y", "6.1":"y", "7":"y", "7.1":"y", "8":"y", "9":"y", "9.1":"y", "10":"y", "10.1":"y", "11":"y", "11.1":"y", "12":"y", "12.1":"y", "13":"y", "13.1":"y", "14":"y", "TP":"y" }, "opera":{ "9":"n", "9.5-9.6":"n", "10.0-10.1":"n", "10.5":"n", "10.6":"n", "11":"n", "11.1":"n", "11.5":"n", "11.6":"n", "12":"n", "12.1":"y", "15":"y", "16":"y", "17":"y", "18":"y", "19":"y", "20":"y", "21":"y", "22":"y", "23":"y", "24":"y", "25":"y", "26":"y", "27":"y", "28":"y", "29":"y", "30":"y", "31":"y", "32":"y", "33":"y", "34":"y", "35":"y", "36":"y", "37":"y", "38":"y", "39":"y", "40":"y", "41":"y", "42":"y", "43":"y", "44":"y", "45":"y", "46":"y", "47":"y", "48":"y", "49":"y", "50":"y", "51":"y", "52":"y", "53":"y", "54":"y", "55":"y", "56":"y", "57":"y", "58":"y", "60":"y", "62":"y", "63":"y", "64":"y", "65":"y", "66":"y", "67":"y", "68":"y", "69":"y", "70":"y" }, "ios_saf":{ "3.2":"n", "4.0-4.1":"n", "4.2-4.3":"n", "5.0-5.1":"y", "6.0-6.1":"y", "7.0-7.1":"y", "8":"y", "8.1-8.4":"y", "9.0-9.2":"y", "9.3":"y", "10.0-10.2":"y", "10.3":"y", "11.0-11.2":"y", "11.3-11.4":"y", "12.0-12.1":"y", "12.2-12.4":"y", "13.0-13.1":"y", "13.2":"y", "13.3":"y", "13.4-13.7":"y", "14.0":"y" }, "op_mini":{ "all":"y" }, "android":{ "2.1":"n", "2.2":"n", "2.3":"n", "3":"y", "4":"y", "4.1":"y", "4.2-4.3":"y", "4.4":"y", "4.4.3-4.4.4":"y", "81":"y" }, "bb":{ "7":"n", "10":"y" }, "op_mob":{ "10":"n", "11":"n", "11.1":"n", "11.5":"n", "12":"n", "12.1":"y", "59":"y" }, "and_chr":{ "85":"y" }, "and_ff":{ "79":"y" }, "ie_mob":{ "10":"y", "11":"y" }, "and_uc":{ "12.12":"y" }, "samsung":{ "4":"y", "5.0-5.4":"y", "6.2-6.4":"y", "7.2-7.4":"y", "8.2":"y", "9.2":"y", "10.1":"y", "11.1-11.2":"y", "12.0":"y" }, "and_qq":{ "10.4":"y" }, "baidu":{ "7.12":"y" }, "kaios":{ "2.5":"y" } }, "notes":"", "notes_by_num":{ }, "usage_perc_y":98.4, "usage_perc_a":0, "ucprefix":false, "parent":"", "keywords":"mediaquerylist", "ie_id":"matchmedia", "chrome_id":"4677872220372992", "firefox_id":"", "webkit_id":"", "shown":true }
{ "pile_set_name": "Github" }
// +build go1.3 package stack import ( "sync" ) var pcStackPool = sync.Pool{ New: func() interface{} { return make([]uintptr, 1000) }, } func poolBuf() []uintptr { return pcStackPool.Get().([]uintptr) } func putPoolBuf(p []uintptr) { pcStackPool.Put(p) }
{ "pile_set_name": "Github" }
// Copyright 2011 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package packet import ( "bytes" "encoding/hex" "io" "testing" ) // Test packet.Read error handling in OpaquePacket.Parse, // which attempts to re-read an OpaquePacket as a supported // Packet type. func TestOpaqueParseReason(t *testing.T) { buf, err := hex.DecodeString(UnsupportedKeyHex) if err != nil { t.Fatal(err) } or := NewOpaqueReader(bytes.NewBuffer(buf)) count := 0 badPackets := 0 var uid *UserId for { op, err := or.Next() if err == io.EOF { break } else if err != nil { t.Errorf("#%d: opaque read error: %v", count, err) break } // try to parse opaque packet p, err := op.Parse() switch pkt := p.(type) { case *UserId: uid = pkt case *OpaquePacket: // If an OpaquePacket can't re-parse, packet.Read // certainly had its reasons. if pkt.Reason == nil { t.Errorf("#%d: opaque packet, no reason", count) } else { badPackets++ } } count++ } const expectedBad = 3 // Test post-conditions, make sure we actually parsed packets as expected. if badPackets != expectedBad { t.Errorf("unexpected # unparseable packets: %d (want %d)", badPackets, expectedBad) } if uid == nil { t.Errorf("failed to find expected UID in unsupported keyring") } else if uid.Id != "Armin M. Warda <[email protected]>" { t.Errorf("unexpected UID: %v", uid.Id) } } // This key material has public key and signature packet versions modified to // an unsupported value (1), so that trying to parse the OpaquePacket to // a typed packet will get an error. It also contains a GnuPG trust packet. // (Created with: od -An -t x1 pubring.gpg | xargs | sed 's/ //g') const UnsupportedKeyHex = `988d012e7a18a20000010400d6ac00d92b89c1f4396c243abb9b76d2e9673ad63483291fed88e22b82e255e441c078c6abbbf7d2d195e50b62eeaa915b85b0ec20c225ce2c64c167cacb6e711daf2e45da4a8356a059b8160e3b3628ac0dd8437b31f06d53d6e8ea4214d4a26406a6b63e1001406ef23e0bb3069fac9a99a91f77dfafd5de0f188a5da5e3c9000511b42741726d696e204d2e205761726461203c7761726461406e657068696c696d2e727568722e64653e8900950105102e8936c705d1eb399e58489901013f0e03ff5a0c4f421e34fcfa388129166420c08cd76987bcdec6f01bd0271459a85cc22048820dd4e44ac2c7d23908d540f54facf1b36b0d9c20488781ce9dca856531e76e2e846826e9951338020a03a09b57aa5faa82e9267458bd76105399885ac35af7dc1cbb6aaed7c39e1039f3b5beda2c0e916bd38560509bab81235d1a0ead83b0020000`
{ "pile_set_name": "Github" }
/* * MACE decoder * Copyright (c) 2002 Laszlo Torok <[email protected]> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * MACE decoder. */ #include "avcodec.h" #include "internal.h" #include "libavutil/common.h" /* * Adapted to libavcodec by Francois Revol <[email protected]> * (removed 68k REG stuff, changed types, added some statics and consts, * libavcodec api, context stuff, interlaced stereo out). */ static const int16_t MACEtab1[] = {-13, 8, 76, 222, 222, 76, 8, -13}; static const int16_t MACEtab3[] = {-18, 140, 140, -18}; static const int16_t MACEtab2[][4] = { { 37, 116, 206, 330}, { 39, 121, 216, 346}, { 41, 127, 225, 361}, { 42, 132, 235, 377}, { 44, 137, 245, 392}, { 46, 144, 256, 410}, { 48, 150, 267, 428}, { 51, 157, 280, 449}, { 53, 165, 293, 470}, { 55, 172, 306, 490}, { 58, 179, 319, 511}, { 60, 187, 333, 534}, { 63, 195, 348, 557}, { 66, 205, 364, 583}, { 69, 214, 380, 609}, { 72, 223, 396, 635}, { 75, 233, 414, 663}, { 79, 244, 433, 694}, { 82, 254, 453, 725}, { 86, 265, 472, 756}, { 90, 278, 495, 792}, { 94, 290, 516, 826}, { 98, 303, 538, 862}, { 102, 316, 562, 901}, { 107, 331, 588, 942}, { 112, 345, 614, 983}, { 117, 361, 641, 1027}, { 122, 377, 670, 1074}, { 127, 394, 701, 1123}, { 133, 411, 732, 1172}, { 139, 430, 764, 1224}, { 145, 449, 799, 1280}, { 152, 469, 835, 1337}, { 159, 490, 872, 1397}, { 166, 512, 911, 1459}, { 173, 535, 951, 1523}, { 181, 558, 993, 1590}, { 189, 584, 1038, 1663}, { 197, 610, 1085, 1738}, { 206, 637, 1133, 1815}, { 215, 665, 1183, 1895}, { 225, 695, 1237, 1980}, { 235, 726, 1291, 2068}, { 246, 759, 1349, 2161}, { 257, 792, 1409, 2257}, { 268, 828, 1472, 2357}, { 280, 865, 1538, 2463}, { 293, 903, 1606, 2572}, { 306, 944, 1678, 2688}, { 319, 986, 1753, 2807}, { 334, 1030, 1832, 2933}, { 349, 1076, 1914, 3065}, { 364, 1124, 1999, 3202}, { 380, 1174, 2088, 3344}, { 398, 1227, 2182, 3494}, { 415, 1281, 2278, 3649}, { 434, 1339, 2380, 3811}, { 453, 1398, 2486, 3982}, { 473, 1461, 2598, 4160}, { 495, 1526, 2714, 4346}, { 517, 1594, 2835, 4540}, { 540, 1665, 2961, 4741}, { 564, 1740, 3093, 4953}, { 589, 1818, 3232, 5175}, { 615, 1898, 3375, 5405}, { 643, 1984, 3527, 5647}, { 671, 2072, 3683, 5898}, { 701, 2164, 3848, 6161}, { 733, 2261, 4020, 6438}, { 766, 2362, 4199, 6724}, { 800, 2467, 4386, 7024}, { 836, 2578, 4583, 7339}, { 873, 2692, 4786, 7664}, { 912, 2813, 5001, 8008}, { 952, 2938, 5223, 8364}, { 995, 3070, 5457, 8739}, { 1039, 3207, 5701, 9129}, { 1086, 3350, 5956, 9537}, { 1134, 3499, 6220, 9960}, { 1185, 3655, 6497, 10404}, { 1238, 3818, 6788, 10869}, { 1293, 3989, 7091, 11355}, { 1351, 4166, 7407, 11861}, { 1411, 4352, 7738, 12390}, { 1474, 4547, 8084, 12946}, { 1540, 4750, 8444, 13522}, { 1609, 4962, 8821, 14126}, { 1680, 5183, 9215, 14756}, { 1756, 5415, 9626, 15415}, { 1834, 5657, 10057, 16104}, { 1916, 5909, 10505, 16822}, { 2001, 6173, 10975, 17574}, { 2091, 6448, 11463, 18356}, { 2184, 6736, 11974, 19175}, { 2282, 7037, 12510, 20032}, { 2383, 7351, 13068, 20926}, { 2490, 7679, 13652, 21861}, { 2601, 8021, 14260, 22834}, { 2717, 8380, 14897, 23854}, { 2838, 8753, 15561, 24918}, { 2965, 9144, 16256, 26031}, { 3097, 9553, 16982, 27193}, { 3236, 9979, 17740, 28407}, { 3380, 10424, 18532, 29675}, { 3531, 10890, 19359, 31000}, { 3688, 11375, 20222, 32382}, { 3853, 11883, 21125, 32767}, { 4025, 12414, 22069, 32767}, { 4205, 12967, 23053, 32767}, { 4392, 13546, 24082, 32767}, { 4589, 14151, 25157, 32767}, { 4793, 14783, 26280, 32767}, { 5007, 15442, 27452, 32767}, { 5231, 16132, 28678, 32767}, { 5464, 16851, 29957, 32767}, { 5708, 17603, 31294, 32767}, { 5963, 18389, 32691, 32767}, { 6229, 19210, 32767, 32767}, { 6507, 20067, 32767, 32767}, { 6797, 20963, 32767, 32767}, { 7101, 21899, 32767, 32767}, { 7418, 22876, 32767, 32767}, { 7749, 23897, 32767, 32767}, { 8095, 24964, 32767, 32767}, { 8456, 26078, 32767, 32767}, { 8833, 27242, 32767, 32767}, { 9228, 28457, 32767, 32767}, { 9639, 29727, 32767, 32767} }; static const int16_t MACEtab4[][2] = { { 64, 216}, { 67, 226}, { 70, 236}, { 74, 246}, { 77, 257}, { 80, 268}, { 84, 280}, { 88, 294}, { 92, 307}, { 96, 321}, { 100, 334}, { 104, 350}, { 109, 365}, { 114, 382}, { 119, 399}, { 124, 416}, { 130, 434}, { 136, 454}, { 142, 475}, { 148, 495}, { 155, 519}, { 162, 541}, { 169, 564}, { 176, 590}, { 185, 617}, { 193, 644}, { 201, 673}, { 210, 703}, { 220, 735}, { 230, 767}, { 240, 801}, { 251, 838}, { 262, 876}, { 274, 914}, { 286, 955}, { 299, 997}, { 312, 1041}, { 326, 1089}, { 341, 1138}, { 356, 1188}, { 372, 1241}, { 388, 1297}, { 406, 1354}, { 424, 1415}, { 443, 1478}, { 462, 1544}, { 483, 1613}, { 505, 1684}, { 527, 1760}, { 551, 1838}, { 576, 1921}, { 601, 2007}, { 628, 2097}, { 656, 2190}, { 686, 2288}, { 716, 2389}, { 748, 2496}, { 781, 2607}, { 816, 2724}, { 853, 2846}, { 891, 2973}, { 930, 3104}, { 972, 3243}, { 1016, 3389}, { 1061, 3539}, { 1108, 3698}, { 1158, 3862}, { 1209, 4035}, { 1264, 4216}, { 1320, 4403}, { 1379, 4599}, { 1441, 4806}, { 1505, 5019}, { 1572, 5244}, { 1642, 5477}, { 1715, 5722}, { 1792, 5978}, { 1872, 6245}, { 1955, 6522}, { 2043, 6813}, { 2134, 7118}, { 2229, 7436}, { 2329, 7767}, { 2432, 8114}, { 2541, 8477}, { 2655, 8854}, { 2773, 9250}, { 2897, 9663}, { 3026, 10094}, { 3162, 10546}, { 3303, 11016}, { 3450, 11508}, { 3604, 12020}, { 3765, 12556}, { 3933, 13118}, { 4108, 13703}, { 4292, 14315}, { 4483, 14953}, { 4683, 15621}, { 4892, 16318}, { 5111, 17046}, { 5339, 17807}, { 5577, 18602}, { 5826, 19433}, { 6086, 20300}, { 6358, 21205}, { 6642, 22152}, { 6938, 23141}, { 7248, 24173}, { 7571, 25252}, { 7909, 26380}, { 8262, 27557}, { 8631, 28786}, { 9016, 30072}, { 9419, 31413}, { 9839, 32767}, { 10278, 32767}, { 10737, 32767}, { 11216, 32767}, { 11717, 32767}, { 12240, 32767}, { 12786, 32767}, { 13356, 32767}, { 13953, 32767}, { 14576, 32767}, { 15226, 32767}, { 15906, 32767}, { 16615, 32767} }; static const struct { const int16_t *tab1; const int16_t *tab2; int stride; } tabs[] = { {MACEtab1, &MACEtab2[0][0], 4}, {MACEtab3, &MACEtab4[0][0], 2}, {MACEtab1, &MACEtab2[0][0], 4} }; #define QT_8S_2_16S(x) (((x) & 0xFF00) | (((x) >> 8) & 0xFF)) typedef struct ChannelData { int16_t index, factor, prev2, previous, level; } ChannelData; typedef struct MACEContext { ChannelData chd[2]; } MACEContext; /** * MACE version of av_clip_int16(). We have to do this to keep binary * identical output to the binary decoder. */ static inline int16_t mace_broken_clip_int16(int n) { if (n > 32767) return 32767; else if (n < -32768) return -32767; else return n; } static int16_t read_table(ChannelData *chd, uint8_t val, int tab_idx) { int16_t current; if (val < tabs[tab_idx].stride) current = tabs[tab_idx].tab2[((chd->index & 0x7f0) >> 4) * tabs[tab_idx].stride + val]; else current = - 1 - tabs[tab_idx].tab2[((chd->index & 0x7f0) >> 4)*tabs[tab_idx].stride + 2*tabs[tab_idx].stride-val-1]; if (( chd->index += tabs[tab_idx].tab1[val]-(chd->index >> 5) ) < 0) chd->index = 0; return current; } static void chomp3(ChannelData *chd, int16_t *output, uint8_t val, int tab_idx) { int16_t current = read_table(chd, val, tab_idx); current = mace_broken_clip_int16(current + chd->level); chd->level = current - (current >> 3); *output = QT_8S_2_16S(current); } static void chomp6(ChannelData *chd, int16_t *output, uint8_t val, int tab_idx) { int16_t current = read_table(chd, val, tab_idx); if ((chd->previous ^ current) >= 0) { chd->factor = FFMIN(chd->factor + 506, 32767); } else { if (chd->factor - 314 < -32768) chd->factor = -32767; else chd->factor -= 314; } current = mace_broken_clip_int16(current + chd->level); chd->level = (current*chd->factor) >> 15; current >>= 1; output[0] = QT_8S_2_16S(chd->previous + chd->prev2 - ((chd->prev2-current) >> 2)); output[1] = QT_8S_2_16S(chd->previous + current + ((chd->prev2-current) >> 2)); chd->prev2 = chd->previous; chd->previous = current; } static av_cold int mace_decode_init(AVCodecContext * avctx) { if (avctx->channels > 2 || avctx->channels < 1) return AVERROR(EINVAL); avctx->sample_fmt = AV_SAMPLE_FMT_S16P; return 0; } static int mace_decode_frame(AVCodecContext *avctx, void *data, int *got_frame_ptr, AVPacket *avpkt) { AVFrame *frame = data; const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; int16_t **samples; MACEContext *ctx = avctx->priv_data; int i, j, k, l, ret; int is_mace3 = (avctx->codec_id == AV_CODEC_ID_MACE3); if (buf_size % (avctx->channels << is_mace3)) { av_log(avctx, AV_LOG_ERROR, "buffer size %d is odd\n", buf_size); buf_size -= buf_size % (avctx->channels << is_mace3); if (!buf_size) return AVERROR_INVALIDDATA; } /* get output buffer */ frame->nb_samples = 3 * (buf_size << (1 - is_mace3)) / avctx->channels; if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) return ret; samples = (int16_t **)frame->extended_data; for(i = 0; i < avctx->channels; i++) { int16_t *output = samples[i]; for (j=0; j < buf_size / (avctx->channels << is_mace3); j++) for (k=0; k < (1 << is_mace3); k++) { uint8_t pkt = buf[(i << is_mace3) + (j*avctx->channels << is_mace3) + k]; uint8_t val[2][3] = {{pkt >> 5, (pkt >> 3) & 3, pkt & 7 }, {pkt & 7 , (pkt >> 3) & 3, pkt >> 5}}; for (l=0; l < 3; l++) { if (is_mace3) chomp3(&ctx->chd[i], output, val[1][l], l); else chomp6(&ctx->chd[i], output, val[0][l], l); output += 1 << (1-is_mace3); } } } *got_frame_ptr = 1; return buf_size; } AVCodec ff_mace3_decoder = { .name = "mace3", .long_name = NULL_IF_CONFIG_SMALL("MACE (Macintosh Audio Compression/Expansion) 3:1"), .type = AVMEDIA_TYPE_AUDIO, .id = AV_CODEC_ID_MACE3, .priv_data_size = sizeof(MACEContext), .init = mace_decode_init, .decode = mace_decode_frame, .capabilities = CODEC_CAP_DR1, .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_NONE }, }; AVCodec ff_mace6_decoder = { .name = "mace6", .long_name = NULL_IF_CONFIG_SMALL("MACE (Macintosh Audio Compression/Expansion) 6:1"), .type = AVMEDIA_TYPE_AUDIO, .id = AV_CODEC_ID_MACE6, .priv_data_size = sizeof(MACEContext), .init = mace_decode_init, .decode = mace_decode_frame, .capabilities = CODEC_CAP_DR1, .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_NONE }, };
{ "pile_set_name": "Github" }
/* * isph3a.h * * TI OMAP3 ISP - H3A AF module * * Copyright (C) 2010 Nokia Corporation * Copyright (C) 2009 Texas Instruments, Inc. * * Contacts: David Cohen <[email protected]> * Laurent Pinchart <[email protected]> * Sakari Ailus <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #ifndef OMAP3_ISP_H3A_H #define OMAP3_ISP_H3A_H #include <linux/omap3isp.h> /* * ---------- * -H3A AEWB- * ---------- */ #define AEWB_PACKET_SIZE 16 #define AEWB_SATURATION_LIMIT 0x3ff /* Flags for changed registers */ #define PCR_CHNG (1 << 0) #define AEWWIN1_CHNG (1 << 1) #define AEWINSTART_CHNG (1 << 2) #define AEWINBLK_CHNG (1 << 3) #define AEWSUBWIN_CHNG (1 << 4) #define PRV_WBDGAIN_CHNG (1 << 5) #define PRV_WBGAIN_CHNG (1 << 6) /* ISPH3A REGISTERS bits */ #define ISPH3A_PCR_AF_EN (1 << 0) #define ISPH3A_PCR_AF_ALAW_EN (1 << 1) #define ISPH3A_PCR_AF_MED_EN (1 << 2) #define ISPH3A_PCR_AF_BUSY (1 << 15) #define ISPH3A_PCR_AEW_EN (1 << 16) #define ISPH3A_PCR_AEW_ALAW_EN (1 << 17) #define ISPH3A_PCR_AEW_BUSY (1 << 18) #define ISPH3A_PCR_AEW_MASK (ISPH3A_PCR_AEW_ALAW_EN | \ ISPH3A_PCR_AEW_AVE2LMT_MASK) /* * -------- * -H3A AF- * -------- */ /* Peripheral Revision */ #define AFPID 0x0 #define AFCOEF_OFFSET 0x00000004 /* COEF base address */ /* PCR fields */ #define AF_BUSYAF (1 << 15) #define AF_FVMODE (1 << 14) #define AF_RGBPOS (0x7 << 11) #define AF_MED_TH (0xFF << 3) #define AF_MED_EN (1 << 2) #define AF_ALAW_EN (1 << 1) #define AF_EN (1 << 0) #define AF_PCR_MASK (AF_FVMODE | AF_RGBPOS | AF_MED_TH | \ AF_MED_EN | AF_ALAW_EN) /* AFPAX1 fields */ #define AF_PAXW (0x7F << 16) #define AF_PAXH 0x7F /* AFPAX2 fields */ #define AF_AFINCV (0xF << 13) #define AF_PAXVC (0x7F << 6) #define AF_PAXHC 0x3F /* AFPAXSTART fields */ #define AF_PAXSH (0xFFF<<16) #define AF_PAXSV 0xFFF /* COEFFICIENT MASK */ #define AF_COEF_MASK0 0xFFF #define AF_COEF_MASK1 (0xFFF<<16) /* BIT SHIFTS */ #define AF_RGBPOS_SHIFT 11 #define AF_MED_TH_SHIFT 3 #define AF_PAXW_SHIFT 16 #define AF_LINE_INCR_SHIFT 13 #define AF_VT_COUNT_SHIFT 6 #define AF_HZ_START_SHIFT 16 #define AF_COEF_SHIFT 16 /* Init and cleanup functions */ int omap3isp_h3a_aewb_init(struct isp_device *isp); int omap3isp_h3a_af_init(struct isp_device *isp); void omap3isp_h3a_aewb_cleanup(struct isp_device *isp); void omap3isp_h3a_af_cleanup(struct isp_device *isp); #endif /* OMAP3_ISP_H3A_H */
{ "pile_set_name": "Github" }
/* Kikoo */ /** * Kikoo */
{ "pile_set_name": "Github" }
<?php // $Header: /cvsroot/tikiwiki/tiki/parse_tiki.php,v 1.5 2004/06/16 01:24:10 teedog Exp $ // heaviled modified get_strings.php // dedicated as a tool for use in an eventual test suite // [email protected] require_once('tiki-setup.php'); if($tiki_p_admin != 'y') die("You need to be admin to run this script"); $logfile = 'temp/tiki_parsed.txt'; $logfilehtml = 'temp/tiki_parsed.html'; function collect($dir) { global $dirs; if (is_dir($dir) and is_dir("$dir/CVS")) { $list = file("$dir/CVS/Entries"); foreach ($list as $l) { // if (count($dirs) > 20) return true; if (strstr($l,'/')) { $s = split('/',rtrim($l)); $filepath = $dir.'/'.$s[1]; if ($s[0] == 'D') { collect($filepath); $dirs["$dir"][] = $s[1]; $dirs["$dir"]['FILES'] = array(); } else { if (is_file($filepath)) { $stat = stat($filepath); $files["$filepath"]["mtime"] = $stat['mtime']; $files["$filepath"]["ctime"] = $stat['ctime']; $files["$filepath"]["atime"] = $stat['atime']; $files["$filepath"]["size"] = $stat['size']; $files["$filepath"]["rev"] = $s[2]; $files["$filepath"]["date"] = $s[3]; $files["$filepath"]["flags"] = $s[4]; $files["$filepath"]["tag"] = $s[5]; clearstatcache(); $dirs["$dir"]['FILES'] = $files; } } } } } } function echoline($fd, $fx, $outstring, $style='', $mod='', $br=true) { if ($br) { $br = "\n"; } else { $br = ''; } fwrite ($fd, $outstring.$br); if ($mod == 'd') { $outstring = date('D M d H:m:s Y',trim($outstring)); } if ($style == 'eob') { $htmlstring = "</div>"; } elseif ($style) { if ($style == 'dir') { $htmlstring = "<span class='$style' onclick=\"javascript:toggle('".$outstring."');\">". sprintf(" %-16s : ",$style). htmlspecialchars($outstring)."</span>"; $htmlstring.= "<div class='box' id='".$outstring."'>"; $br = ''; } else { $htmlstring = "<span class='$style'>". sprintf(" %-16s : ",$style). htmlspecialchars($outstring)."</span>"; } } else { $htmlstring = htmlspecialchars($outstring); } fwrite ($fx, $htmlstring.$br); } $display = 'none'; if (isset($_REQUEST['all'])) $display = 'block'; ?> <html><head><style> pre { padding : 10px; border: 1px solid #666666; background-color: #efefef; } .dir { font-weight : bold; background-color: #ffffff; cursor : pointer; } .box { padding : 10px; border : 1px solid #999999; background-color: #f6f6f6; display : <?php echo $display ?>; } .file { font-weight : bold; } .php { background-color: #AACCFF; } .smarty { background-color: #FFccAA; } .other { background-color: #cccccc; } .image { background-color: #aaffcc; } .sub { padding-left : 20px; font-size : 80%; } .var { background-color: #FFFFAA; } .url { background-color: #FFAAAA; } .action { background-color: #AACCFF; } .form { background-color: #AABBFF; } .atime, .ctime, .mtime, .date { background-color: #dedede; } .size, .rev, .tag { background-color: #ededed; } </style><script type="text/javascript" src="lib/tiki-js.js"></script></head> <body><form action="parse_tiki.php" method="post"><input type="submit" name="action" value="process" /></form> <a href="<?php echo $logfile; ?>">raw report</a> <pre> <?php if (isset($_POST['action'])) { $files = $dirs = array(); collect('.'); @unlink ($logfile); $fw = fopen($logfile,'w'); $fx = fopen($logfilehtml,'w'); foreach ($dirs as $dir=>$params) { $dirname = basename($dir); $path = dirname($dir); echoline($fw,$fx,$dir,'dir'); echoline($fw,$fx,''); if (isset($dirs["$dir"]['FILES'])) { foreach ($dirs["$dir"]['FILES'] as $file=>$params) { $fp = fopen ($file, "r"); $data = fread ($fp, filesize ($file)); fclose ($fp); $requests = array(); $urls = array(); if (preg_match("/\.(tpl|ph(p|tml))$/", $file)) { if (preg_match("/\.ph(p|tml)$/", $file)) { echoline($fw,$fx, $file,"file php"); $data = preg_replace ("/(?s)\/\*.*?\*\//", "", $data); // C comments $data = preg_replace ("/(?m)^\s*\/\/.*\$/", "", $data); // C++ comments $data = preg_replace ("/(?m)^\s*\#.*\$/", "", $data); // shell comments $data = preg_replace('/(\r|\n)/', '', $data); // all one line preg_match_all('/\$_(REQUEST|POST|GET|COOKIE|SESSION)\[([^\]]*)\]/', $data, $requests); // requests uses $max = count($requests[0]); for ($i=0;$i<$max;$i++) { echoline($fw,$fx,$requests[1][$i]." = ".$requests[2][$i],'sub var'); } } elseif (preg_match ("/\.tpl$/", $file)) { echoline($fw,$fx,$file,'file smarty'); $data = preg_replace('/(?s)\{\*.*?\*\}/', '', $data); // Smarty comment $data = preg_replace('/(\r|\n)/', '', $data); // all one line } preg_match_all('/<(a[^>]*)>[^<]*<\/a>/im', $data, $urls); // href links foreach ($urls[1] as $u) { echoline($fw,$fx,$u,'sub url'); } preg_match_all('/<(form[^>]*)>/', $data, $forms); // form uses foreach ($forms[1] as $f) { echoline($fw,$fx,$f,'sub action'); } preg_match_all('/<((input|textarea|select)[^>]*)>/', $data, $elements); // form elements uses $max = count($elements[0]); for ($i=0;$i<$max;$i++) { echoline($fw,$fx,$elements[1][$i],'sub form'); } echoline($fw,$fx,trim($params['atime']),'sub atime','d'); echoline($fw,$fx,trim($params['mtime']),'sub mtime','d'); echoline($fw,$fx,trim($params['ctime']),'sub ctime','d'); echoline($fw,$fx,trim($params['date']),'sub date'); echoline($fw,$fx,trim($params['size']),'sub size'); echoline($fw,$fx,trim($params['rev']),'sub rev'); echoline($fw,$fx,substr(trim($params['tag']),1),'sub tag'); } elseif (preg_match ("/\.(gif|jpg|png)$/i", $file)) { echoline($fw,$fx,$file,'file image'); } else { echoline($fw,$fx,$file,'file other'); } echoline($fw,$fx,''); flush(); } } echoline($fw,$fx,'end of box','eob'); } fclose($fw); fclose($fx); } if (is_file($logfilehtml)) { readfile($logfilehtml); } ?> </pre> </body></html>
{ "pile_set_name": "Github" }
/******************************************************************************* * Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file 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. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.CloudFormation; using Amazon.CloudFormation.Model; namespace Amazon.PowerShell.Cmdlets.CFN { /// <summary> /// Updates a stack as specified in the template. After the call completes successfully, /// the stack update starts. You can check the status of the stack via the <a>DescribeStacks</a> /// action. /// /// /// <para> /// To get a copy of the template for an existing stack, you can use the <a>GetTemplate</a> /// action. /// </para><para> /// For more information about creating an update template, updating a stack, and monitoring /// the progress of the update, see <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks.html">Updating /// a Stack</a>. /// </para> /// </summary> [Cmdlet("Update", "CFNStack", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)] [OutputType("System.String")] [AWSCmdlet("Calls the AWS CloudFormation UpdateStack API operation.", Operation = new[] {"UpdateStack"}, SelectReturnType = typeof(Amazon.CloudFormation.Model.UpdateStackResponse))] [AWSCmdletOutput("System.String or Amazon.CloudFormation.Model.UpdateStackResponse", "This cmdlet returns a System.String object.", "The service call response (type Amazon.CloudFormation.Model.UpdateStackResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class UpdateCFNStackCmdlet : AmazonCloudFormationClientCmdlet, IExecutor { #region Parameter Capability /// <summary> /// <para> /// <para>In some cases, you must explicitly acknowledge that your stack template contains certain /// capabilities in order for AWS CloudFormation to update the stack.</para><ul><li><para><code>CAPABILITY_IAM</code> and <code>CAPABILITY_NAMED_IAM</code></para><para>Some stack templates might include resources that can affect permissions in your AWS /// account; for example, by creating new AWS Identity and Access Management (IAM) users. /// For those stacks, you must explicitly acknowledge this by specifying one of these /// capabilities.</para><para>The following IAM resources require you to specify either the <code>CAPABILITY_IAM</code> /// or <code>CAPABILITY_NAMED_IAM</code> capability.</para><ul><li><para>If you have IAM resources, you can specify either capability. </para></li><li><para>If you have IAM resources with custom names, you <i>must</i> specify <code>CAPABILITY_NAMED_IAM</code>. /// </para></li><li><para>If you don't specify either of these capabilities, AWS CloudFormation returns an <code>InsufficientCapabilities</code> /// error.</para></li></ul><para>If your stack template contains these resources, we recommend that you review all /// permissions associated with them and edit their permissions if necessary.</para><ul><li><para><a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-accesskey.html"> /// AWS::IAM::AccessKey</a></para></li><li><para><a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-group.html"> /// AWS::IAM::Group</a></para></li><li><para><a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-instanceprofile.html"> /// AWS::IAM::InstanceProfile</a></para></li><li><para><a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-policy.html"> /// AWS::IAM::Policy</a></para></li><li><para><a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html"> /// AWS::IAM::Role</a></para></li><li><para><a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-user.html"> /// AWS::IAM::User</a></para></li><li><para><a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-addusertogroup.html"> /// AWS::IAM::UserToGroupAddition</a></para></li></ul><para>For more information, see <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities">Acknowledging /// IAM Resources in AWS CloudFormation Templates</a>.</para></li><li><para><code>CAPABILITY_AUTO_EXPAND</code></para><para>Some template contain macros. Macros perform custom processing on templates; this /// can include simple actions like find-and-replace operations, all the way to extensive /// transformations of entire templates. Because of this, users typically create a change /// set from the processed template, so that they can review the changes resulting from /// the macros before actually updating the stack. If your stack template contains one /// or more macros, and you choose to update a stack directly from the processed template, /// without first reviewing the resulting changes in a change set, you must acknowledge /// this capability. This includes the <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/create-reusable-transform-function-snippets-and-add-to-your-template-with-aws-include-transform.html">AWS::Include</a> /// and <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/transform-aws-serverless.html">AWS::Serverless</a> /// transforms, which are macros hosted by AWS CloudFormation.</para><para>Change sets do not currently support nested stacks. If you want to update a stack /// from a stack template that contains macros <i>and</i> nested stacks, you must update /// the stack directly from the template using this capability.</para><important><para>You should only update stacks directly from a stack template that contains macros /// if you know what processing the macro performs.</para><para>Each macro relies on an underlying Lambda service function for processing stack templates. /// Be aware that the Lambda function owner can update the function operation without /// AWS CloudFormation being notified.</para></important><para>For more information, see <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-macros.html">Using /// AWS CloudFormation Macros to Perform Custom Processing on Templates</a>.</para></li></ul> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("Capabilities")] public System.String[] Capability { get; set; } #endregion #region Parameter ClientRequestToken /// <summary> /// <para> /// <para>A unique identifier for this <code>UpdateStack</code> request. Specify this token /// if you plan to retry requests so that AWS CloudFormation knows that you're not attempting /// to update a stack with the same name. You might retry <code>UpdateStack</code> requests /// to ensure that AWS CloudFormation successfully received them.</para><para>All events triggered by a given stack operation are assigned the same client request /// token, which you can use to track operations. For example, if you execute a <code>CreateStack</code> /// operation with the token <code>token1</code>, then all the <code>StackEvents</code> /// generated by that operation will have <code>ClientRequestToken</code> set as <code>token1</code>.</para><para>In the console, stack operations display the client request token on the Events tab. /// Stack operations that are initiated from the console use the token format <i>Console-StackOperation-ID</i>, /// which helps you easily identify the stack operation . For example, if you create a /// stack using the console, each stack event would be assigned the same token in the /// following format: <code>Console-CreateStack-7f59c3cf-00d2-40c7-b2ff-e75db0987002</code>. /// </para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String ClientRequestToken { get; set; } #endregion #region Parameter RollbackConfiguration_MonitoringTimeInMinute /// <summary> /// <para> /// <para>The amount of time, in minutes, during which CloudFormation should monitor all the /// rollback triggers after the stack creation or update operation deploys all necessary /// resources.</para><para>The default is 0 minutes.</para><para>If you specify a monitoring period but do not specify any rollback triggers, CloudFormation /// still waits the specified period of time before cleaning up old resources after update /// operations. You can use this monitoring period to perform any manual stack validation /// desired, and manually cancel the stack creation or update (using <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_CancelUpdateStack.html">CancelUpdateStack</a>, /// for example) as necessary.</para><para>If you specify 0 for this parameter, CloudFormation still monitors the specified rollback /// triggers during stack creation and update operations. Then, for update operations, /// it begins disposing of old resources immediately once the operation completes.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("RollbackConfiguration_MonitoringTimeInMinutes")] public System.Int32? RollbackConfiguration_MonitoringTimeInMinute { get; set; } #endregion #region Parameter NotificationARNs /// <summary> /// <para> /// <para>Amazon Simple Notification Service topic Amazon Resource Names (ARNs) that AWS CloudFormation /// associates with the stack. Specify an empty list to remove all notification topics.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String[] NotificationARNs { get; set; } #endregion #region Parameter Parameter /// <summary> /// <para> /// <para>A list of <code>Parameter</code> structures that specify input parameters for the /// stack. For more information, see the <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_Parameter.html">Parameter</a> /// data type.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("Parameters")] public Amazon.CloudFormation.Model.Parameter[] Parameter { get; set; } #endregion #region Parameter ResourceType /// <summary> /// <para> /// <para>The template resource types that you have permissions to work with for this update /// stack action, such as <code>AWS::EC2::Instance</code>, <code>AWS::EC2::*</code>, or /// <code>Custom::MyCustomInstance</code>.</para><para>If the list of resource types doesn't include a resource that you're updating, the /// stack update fails. By default, AWS CloudFormation grants permissions to all resource /// types. AWS Identity and Access Management (IAM) uses this parameter for AWS CloudFormation-specific /// condition keys in IAM policies. For more information, see <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html">Controlling /// Access with AWS Identity and Access Management</a>.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("ResourceTypes")] public System.String[] ResourceType { get; set; } #endregion #region Parameter RoleARN /// <summary> /// <para> /// <para>The Amazon Resource Name (ARN) of an AWS Identity and Access Management (IAM) role /// that AWS CloudFormation assumes to update the stack. AWS CloudFormation uses the role's /// credentials to make calls on your behalf. AWS CloudFormation always uses this role /// for all future operations on the stack. As long as users have permission to operate /// on the stack, AWS CloudFormation uses this role even if the users don't have permission /// to pass it. Ensure that the role grants least privilege.</para><para>If you don't specify a value, AWS CloudFormation uses the role that was previously /// associated with the stack. If no role is available, AWS CloudFormation uses a temporary /// session that is generated from your user credentials.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String RoleARN { get; set; } #endregion #region Parameter RollbackConfiguration_RollbackTrigger /// <summary> /// <para> /// <para>The triggers to monitor during stack creation or update actions. </para><para>By default, AWS CloudFormation saves the rollback triggers specified for a stack and /// applies them to any subsequent update operations for the stack, unless you specify /// otherwise. If you do specify rollback triggers for this parameter, those triggers /// replace any list of triggers previously specified for the stack. This means:</para><ul><li><para>To use the rollback triggers previously specified for this stack, if any, don't specify /// this parameter.</para></li><li><para>To specify new or updated rollback triggers, you must specify <i>all</i> the triggers /// that you want used for this stack, even triggers you've specifed before (for example, /// when creating the stack or during a previous stack update). Any triggers that you /// don't include in the updated list of triggers are no longer applied to the stack.</para></li><li><para>To remove all currently specified triggers, specify an empty list for this parameter.</para></li></ul><para>If a specified trigger is missing, the entire stack operation fails and is rolled /// back. </para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("RollbackConfiguration_RollbackTriggers")] public Amazon.CloudFormation.Model.RollbackTrigger[] RollbackConfiguration_RollbackTrigger { get; set; } #endregion #region Parameter StackName /// <summary> /// <para> /// <para>The name or unique stack ID of the stack to update.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] #else [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String StackName { get; set; } #endregion #region Parameter StackPolicyBody /// <summary> /// <para> /// <para>Structure containing a new stack policy body. You can specify either the <code>StackPolicyBody</code> /// or the <code>StackPolicyURL</code> parameter, but not both.</para><para>You might update the stack policy, for example, in order to protect a new resource /// that you created during a stack update. If you do not specify a stack policy, the /// current policy that is associated with the stack is unchanged.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String StackPolicyBody { get; set; } #endregion #region Parameter StackPolicyDuringUpdateBody /// <summary> /// <para> /// <para>Structure containing the temporary overriding stack policy body. You can specify either /// the <code>StackPolicyDuringUpdateBody</code> or the <code>StackPolicyDuringUpdateURL</code> /// parameter, but not both.</para><para>If you want to update protected resources, specify a temporary overriding stack policy /// during this update. If you do not specify a stack policy, the current policy that /// is associated with the stack will be used.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String StackPolicyDuringUpdateBody { get; set; } #endregion #region Parameter StackPolicyDuringUpdateURL /// <summary> /// <para> /// <para>Location of a file containing the temporary overriding stack policy. The URL must /// point to a policy (max size: 16KB) located in an S3 bucket in the same Region as the /// stack. You can specify either the <code>StackPolicyDuringUpdateBody</code> or the /// <code>StackPolicyDuringUpdateURL</code> parameter, but not both.</para><para>If you want to update protected resources, specify a temporary overriding stack policy /// during this update. If you do not specify a stack policy, the current policy that /// is associated with the stack will be used.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String StackPolicyDuringUpdateURL { get; set; } #endregion #region Parameter StackPolicyURL /// <summary> /// <para> /// <para>Location of a file containing the updated stack policy. The URL must point to a policy /// (max size: 16KB) located in an S3 bucket in the same Region as the stack. You can /// specify either the <code>StackPolicyBody</code> or the <code>StackPolicyURL</code> /// parameter, but not both.</para><para>You might update the stack policy, for example, in order to protect a new resource /// that you created during a stack update. If you do not specify a stack policy, the /// current policy that is associated with the stack is unchanged.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String StackPolicyURL { get; set; } #endregion #region Parameter Tag /// <summary> /// <para> /// <para>Key-value pairs to associate with this stack. AWS CloudFormation also propagates these /// tags to supported resources in the stack. You can specify a maximum number of 50 tags.</para><para>If you don't specify this parameter, AWS CloudFormation doesn't modify the stack's /// tags. If you specify an empty value, AWS CloudFormation removes all associated tags.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("Tags")] public Amazon.CloudFormation.Model.Tag[] Tag { get; set; } #endregion #region Parameter TemplateBody /// <summary> /// <para> /// <para>Structure containing the template body with a minimum length of 1 byte and a maximum /// length of 51,200 bytes. (For more information, go to <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-anatomy.html">Template /// Anatomy</a> in the AWS CloudFormation User Guide.)</para><para>Conditional: You must specify only one of the following parameters: <code>TemplateBody</code>, /// <code>TemplateURL</code>, or set the <code>UsePreviousTemplate</code> to <code>true</code>.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String TemplateBody { get; set; } #endregion #region Parameter TemplateURL /// <summary> /// <para> /// <para>Location of file containing the template body. The URL must point to a template that /// is located in an Amazon S3 bucket. For more information, go to <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-anatomy.html">Template /// Anatomy</a> in the AWS CloudFormation User Guide.</para><para>Conditional: You must specify only one of the following parameters: <code>TemplateBody</code>, /// <code>TemplateURL</code>, or set the <code>UsePreviousTemplate</code> to <code>true</code>.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String TemplateURL { get; set; } #endregion #region Parameter UsePreviousTemplate /// <summary> /// <para> /// <para>Reuse the existing template that is associated with the stack that you are updating.</para><para>Conditional: You must specify only one of the following parameters: <code>TemplateBody</code>, /// <code>TemplateURL</code>, or set the <code>UsePreviousTemplate</code> to <code>true</code>.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.Boolean? UsePreviousTemplate { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The default value is 'StackId'. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.CloudFormation.Model.UpdateStackResponse). /// Specifying the name of a property of type Amazon.CloudFormation.Model.UpdateStackResponse will result in that property being returned. /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "StackId"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the StackName parameter. /// The -PassThru parameter is deprecated, use -Select '^StackName' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^StackName' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter Force /// <summary> /// This parameter overrides confirmation prompts to force /// the cmdlet to continue its operation. This parameter should always /// be used with caution. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter Force { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.StackName), MyInvocation.BoundParameters); if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Update-CFNStack (UpdateStack)")) { return; } var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.CloudFormation.Model.UpdateStackResponse, UpdateCFNStackCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.StackName; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute if (this.Capability != null) { context.Capability = new List<System.String>(this.Capability); } context.ClientRequestToken = this.ClientRequestToken; if (this.NotificationARNs != null) { context.NotificationARNs = new List<System.String>(this.NotificationARNs); } if (this.Parameter != null) { context.Parameter = new List<Amazon.CloudFormation.Model.Parameter>(this.Parameter); } if (this.ResourceType != null) { context.ResourceType = new List<System.String>(this.ResourceType); } context.RoleARN = this.RoleARN; context.RollbackConfiguration_MonitoringTimeInMinute = this.RollbackConfiguration_MonitoringTimeInMinute; if (this.RollbackConfiguration_RollbackTrigger != null) { context.RollbackConfiguration_RollbackTrigger = new List<Amazon.CloudFormation.Model.RollbackTrigger>(this.RollbackConfiguration_RollbackTrigger); } context.StackName = this.StackName; #if MODULAR if (this.StackName == null && ParameterWasBound(nameof(this.StackName))) { WriteWarning("You are passing $null as a value for parameter StackName which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif context.StackPolicyBody = this.StackPolicyBody; context.StackPolicyDuringUpdateBody = this.StackPolicyDuringUpdateBody; context.StackPolicyDuringUpdateURL = this.StackPolicyDuringUpdateURL; context.StackPolicyURL = this.StackPolicyURL; if (this.Tag != null) { context.Tag = new List<Amazon.CloudFormation.Model.Tag>(this.Tag); } context.TemplateBody = this.TemplateBody; context.TemplateURL = this.TemplateURL; context.UsePreviousTemplate = this.UsePreviousTemplate; // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.CloudFormation.Model.UpdateStackRequest(); if (cmdletContext.Capability != null) { request.Capabilities = cmdletContext.Capability; } if (cmdletContext.ClientRequestToken != null) { request.ClientRequestToken = cmdletContext.ClientRequestToken; } if (cmdletContext.NotificationARNs != null) { request.NotificationARNs = cmdletContext.NotificationARNs; } if (cmdletContext.Parameter != null) { request.Parameters = cmdletContext.Parameter; } if (cmdletContext.ResourceType != null) { request.ResourceTypes = cmdletContext.ResourceType; } if (cmdletContext.RoleARN != null) { request.RoleARN = cmdletContext.RoleARN; } // populate RollbackConfiguration var requestRollbackConfigurationIsNull = true; request.RollbackConfiguration = new Amazon.CloudFormation.Model.RollbackConfiguration(); System.Int32? requestRollbackConfiguration_rollbackConfiguration_MonitoringTimeInMinute = null; if (cmdletContext.RollbackConfiguration_MonitoringTimeInMinute != null) { requestRollbackConfiguration_rollbackConfiguration_MonitoringTimeInMinute = cmdletContext.RollbackConfiguration_MonitoringTimeInMinute.Value; } if (requestRollbackConfiguration_rollbackConfiguration_MonitoringTimeInMinute != null) { request.RollbackConfiguration.MonitoringTimeInMinutes = requestRollbackConfiguration_rollbackConfiguration_MonitoringTimeInMinute.Value; requestRollbackConfigurationIsNull = false; } List<Amazon.CloudFormation.Model.RollbackTrigger> requestRollbackConfiguration_rollbackConfiguration_RollbackTrigger = null; if (cmdletContext.RollbackConfiguration_RollbackTrigger != null) { requestRollbackConfiguration_rollbackConfiguration_RollbackTrigger = cmdletContext.RollbackConfiguration_RollbackTrigger; } if (requestRollbackConfiguration_rollbackConfiguration_RollbackTrigger != null) { request.RollbackConfiguration.RollbackTriggers = requestRollbackConfiguration_rollbackConfiguration_RollbackTrigger; requestRollbackConfigurationIsNull = false; } // determine if request.RollbackConfiguration should be set to null if (requestRollbackConfigurationIsNull) { request.RollbackConfiguration = null; } if (cmdletContext.StackName != null) { request.StackName = cmdletContext.StackName; } if (cmdletContext.StackPolicyBody != null) { request.StackPolicyBody = cmdletContext.StackPolicyBody; } if (cmdletContext.StackPolicyDuringUpdateBody != null) { request.StackPolicyDuringUpdateBody = cmdletContext.StackPolicyDuringUpdateBody; } if (cmdletContext.StackPolicyDuringUpdateURL != null) { request.StackPolicyDuringUpdateURL = cmdletContext.StackPolicyDuringUpdateURL; } if (cmdletContext.StackPolicyURL != null) { request.StackPolicyURL = cmdletContext.StackPolicyURL; } if (cmdletContext.Tag != null) { request.Tags = cmdletContext.Tag; } if (cmdletContext.TemplateBody != null) { request.TemplateBody = cmdletContext.TemplateBody; } if (cmdletContext.TemplateURL != null) { request.TemplateURL = cmdletContext.TemplateURL; } if (cmdletContext.UsePreviousTemplate != null) { request.UsePreviousTemplate = cmdletContext.UsePreviousTemplate.Value; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return output; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.CloudFormation.Model.UpdateStackResponse CallAWSServiceOperation(IAmazonCloudFormation client, Amazon.CloudFormation.Model.UpdateStackRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS CloudFormation", "UpdateStack"); try { #if DESKTOP return client.UpdateStack(request); #elif CORECLR return client.UpdateStackAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public List<System.String> Capability { get; set; } public System.String ClientRequestToken { get; set; } public List<System.String> NotificationARNs { get; set; } public List<Amazon.CloudFormation.Model.Parameter> Parameter { get; set; } public List<System.String> ResourceType { get; set; } public System.String RoleARN { get; set; } public System.Int32? RollbackConfiguration_MonitoringTimeInMinute { get; set; } public List<Amazon.CloudFormation.Model.RollbackTrigger> RollbackConfiguration_RollbackTrigger { get; set; } public System.String StackName { get; set; } public System.String StackPolicyBody { get; set; } public System.String StackPolicyDuringUpdateBody { get; set; } public System.String StackPolicyDuringUpdateURL { get; set; } public System.String StackPolicyURL { get; set; } public List<Amazon.CloudFormation.Model.Tag> Tag { get; set; } public System.String TemplateBody { get; set; } public System.String TemplateURL { get; set; } public System.Boolean? UsePreviousTemplate { get; set; } public System.Func<Amazon.CloudFormation.Model.UpdateStackResponse, UpdateCFNStackCmdlet, object> Select { get; set; } = (response, cmdlet) => response.StackId; } } }
{ "pile_set_name": "Github" }
// // YLController.h // MacBlueTelnet // // Created by Yung-Luen Lan on 9/11/07. // Copyright 2007 yllan.org. All rights reserved. // #import <Cocoa/Cocoa.h> #import "WLSitesPanelController.h" #define scrollTimerInterval 0.12 @class WLTabView; @class WLFeedGenerator; @class WLTabBarControl; @class WLPresentationController; @class RemoteControl; @class MultiClickRemoteBehavior; #if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_5 @protocol NSTabViewDelegate @end #endif @interface WLMainFrameController : NSObject <NSTabViewDelegate, WLSitesObserver> { /* composeWindow */ IBOutlet NSTextView *_composeText; IBOutlet NSPanel *_composeWindow; IBOutlet NSWindow *_mainWindow; IBOutlet NSPanel *_messageWindow; IBOutlet id _addressBar; IBOutlet id _detectDoubleByteButton; IBOutlet id _autoReplyButton; IBOutlet id _mouseButton; IBOutlet WLTabView *_tabView; IBOutlet WLTabBarControl *_tabBarControl; /* Menus */ IBOutlet NSMenuItem *_detectDoubleByteMenuItem; IBOutlet NSMenuItem *_closeWindowMenuItem; IBOutlet NSMenuItem *_closeTabMenuItem; IBOutlet NSMenuItem *_autoReplyMenuItem; IBOutlet NSMenuItem *_showHiddenTextMenuItem; IBOutlet NSMenuItem *_encodingMenuItem; IBOutlet NSMenuItem *_presentationModeMenuItem; IBOutlet NSMenuItem *_sitesMenu; /* Message */ IBOutlet NSTextView *_unreadMessageTextView; // Remote Control RemoteControl *_remoteControl; MultiClickRemoteBehavior *_remoteControlBehavior; NSTimer* _scrollTimer; // Full Screen WLPresentationController *_presentationModeController; // RSS feed NSThread *_rssThread; // 10.7 Full Screen @private NSRect _originalFrame; NSRect _originalMainFrame; CGFloat _screenRatio; NSColor *_originalWindowBackgroundColor; NSDictionary *_originalSizeParameters; } @property (readonly) WLTabView *tabView; + (WLMainFrameController *)sharedInstance; - (IBAction)toggleAutoReply:(id)sender; - (IBAction)toggleMouseAction:(id)sender; - (IBAction)connectLocation:(id)sender; - (IBAction)openLocation:(id)sender; - (IBAction)reconnect:(id)sender; - (IBAction)openPreferencesWindow:(id)sender; - (void)newConnectionWithSite:(WLSite *)site; - (IBAction)openSitePanel:(id)sender; - (IBAction)addCurrentSite:(id)sender; - (IBAction)openEmoticonsPanel:(id)sender; - (IBAction)openComposePanel:(id)sender; - (IBAction)downloadPost:(id)sender; // Message - (IBAction)closeMessageWindow:(id)sender; #pragma mark - #pragma mark Menu:View - (IBAction)toggleShowsHiddenText:(id)sender; - (IBAction)toggleDetectDoubleByte:(id)sender; - (IBAction)increaseFontSize:(id)sender; - (IBAction)decreaseFontSize:(id)sender; - (IBAction)togglePresentationMode:(id)sender; - (IBAction)setEncoding:(id)sender; /* // for portal - (IBAction)browseImage:(id)sender; - (IBAction)removeSiteImage:(id)sender; - (void)openPanelDidEnd:(NSOpenPanel *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo; */ // for resotre - (IBAction)restoreSettings:(id)sender; // for RSS feed - (IBAction)openRSS:(id)sender; @end
{ "pile_set_name": "Github" }
/* * Copyright 2011-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://aws.amazon.com/apache2.0 * * This file 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.amazonaws.services.s3.model.analytics; import java.io.Serializable; /** * The StorageClassAnalysisDataExport class. */ public class StorageClassAnalysisDataExport implements Serializable { private String outputSchemaVersion; private AnalyticsExportDestination destination; /** * Sets the version of the output schema to use when exporting data. * @param outputSchemaVersion the output schema version. */ public void setOutputSchemaVersion(StorageClassAnalysisSchemaVersion outputSchemaVersion) { if (outputSchemaVersion == null) { setOutputSchemaVersion((String) null); } else { setOutputSchemaVersion(outputSchemaVersion.toString()); } } /** * Sets the version of the output schema to use when exporting data. * @param outputSchemaVersion the output schema version. * @return this object for method chaining. */ @SuppressWarnings("checkstyle:hiddenfield") public StorageClassAnalysisDataExport withOutputSchemaVersion(StorageClassAnalysisSchemaVersion outputSchemaVersion) { setOutputSchemaVersion(outputSchemaVersion); return this; } /** * @return the version of the output schema to use when exporting data. */ public String getOutputSchemaVersion() { return outputSchemaVersion; } /** * Sets the version of the output schema to use when exporting data. * @param outputSchemaVersion the output schema version. */ public void setOutputSchemaVersion(String outputSchemaVersion) { this.outputSchemaVersion = outputSchemaVersion; } /** * Sets the version of the output schema to use when exporting data * @param outputSchemaVersion the output schema version. * @return this object for method chaining. */ @SuppressWarnings("checkstyle:hiddenfield") public StorageClassAnalysisDataExport withOutputSchemaVersion(String outputSchemaVersion) { setOutputSchemaVersion(outputSchemaVersion); return this; } /** * @return the place to store the data for an analysis. */ public AnalyticsExportDestination getDestination() { return destination; } /** * Sets the place to store the data for an analysis. * @param destination the destination to store the data. */ public void setDestination(AnalyticsExportDestination destination) { this.destination = destination; } /** * Sets the place to store the data for an analysis * @param destination the destination to store the data. * @return this object for method chaining. */ @SuppressWarnings("checkstyle:hiddenfield") public StorageClassAnalysisDataExport withDestination(AnalyticsExportDestination destination) { setDestination(destination); return this; } }
{ "pile_set_name": "Github" }
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software GmbH & Co. KG, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.workplace.tools.searchindex; import org.opencms.configuration.CmsSearchConfiguration; import org.opencms.i18n.CmsMessageContainer; import org.opencms.jsp.CmsJspActionElement; import org.opencms.main.CmsLog; import org.opencms.main.OpenCms; import org.opencms.search.CmsSearchManager; import org.opencms.search.fields.CmsLuceneField; import org.opencms.search.fields.CmsSearchField; import org.opencms.search.fields.CmsSearchFieldMapping; import org.opencms.search.fields.I_CmsSearchFieldConfiguration; import org.opencms.search.fields.I_CmsSearchFieldMapping; import org.opencms.util.CmsStringUtil; import org.opencms.workplace.list.CmsListColumnAlignEnum; import org.opencms.workplace.list.CmsListColumnDefinition; import org.opencms.workplace.list.CmsListDefaultAction; import org.opencms.workplace.list.CmsListDirectAction; import org.opencms.workplace.list.CmsListItem; import org.opencms.workplace.list.CmsListItemDetails; import org.opencms.workplace.list.CmsListItemDetailsFormatter; import org.opencms.workplace.list.CmsListMetadata; import org.opencms.workplace.list.CmsListMultiAction; import org.opencms.workplace.list.CmsListOrderEnum; import org.opencms.workplace.tools.CmsToolDialog; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import org.apache.commons.logging.Log; /** * A list that displays the fields of a request parameter given * <code>{@link org.opencms.search.fields.CmsLuceneFieldConfiguration}</code> ("fieldconfiguration"). * * This list is no stand-alone page but has to be embedded in another dialog * (see <code> {@link org.opencms.workplace.tools.searchindex.A_CmsEmbeddedListDialog}</code>. <p> * * @since 6.5.5 */ public class CmsFieldsList extends A_CmsEmbeddedListDialog { /** Standard list button location. */ public static final String ICON_FALSE = "list/multi_deactivate.png"; /** Standard list button location. */ public static final String ICON_TRUE = "list/multi_activate.png"; /** list action id constant. */ public static final String LIST_ACTION_EDIT = "ae"; /** list action id constant. */ public static final String LIST_ACTION_EXCERPT_FALSE = "aef"; /** list action id constant. */ public static final String LIST_ACTION_EXCERPT_TRUE = "aet"; /** list action id constant. */ public static final String LIST_ACTION_INDEX_FALSE = "aif"; /** list action id constant. */ public static final String LIST_ACTION_INDEX_TRUE = "ait"; /** list action id constant. */ public static final String LIST_ACTION_MAPPING = "am"; /** list action id constant. */ public static final String LIST_ACTION_OVERVIEW_FIELD = "aof"; /** list action id constant. */ public static final String LIST_ACTION_STORE_FALSE = "asf"; /** list action id constant. */ public static final String LIST_ACTION_STORE_TRUE = "ast"; /** list column id constant. */ public static final String LIST_COLUMN_BOOST = "cb"; /** list column id constant. */ public static final String LIST_COLUMN_DEFAULT = "cd"; /** list column id constant. */ public static final String LIST_COLUMN_DISPLAY = "cdi"; /** list column id constant. */ public static final String LIST_COLUMN_EDIT = "ced"; /** list column id constant. */ public static final String LIST_COLUMN_EXCERPT = "ce"; /** list column id constant. */ public static final String LIST_COLUMN_EXCERPT_HIDE = "ceh"; /** list column id constant. */ public static final String LIST_COLUMN_ICON = "ci"; /** list column id constant. */ public static final String LIST_COLUMN_INDEX = "cx"; /** list column id constant. */ public static final String LIST_COLUMN_MAPPING = "cm"; /** list column id constant. */ public static final String LIST_COLUMN_NAME = "cn"; /** list column id constant. */ public static final String LIST_COLUMN_STORE = "cs"; /** list column id constant. */ public static final String LIST_COLUMN_STORE_HIDE = "csh"; /** list item detail id constant. */ public static final String LIST_DETAIL_FIELD = "df"; /** list id constant. */ public static final String LIST_ID = "lsfcf"; /** list action id constant. */ public static final String LIST_MACTION_DELETEFIELD = "mad"; /** The path to the fieldconfiguration list icon. */ protected static final String LIST_ICON_FIELD_EDIT = "tools/searchindex/icons/small/fieldconfiguration-editfield.png"; /** The log object for this class. */ private static final Log LOG = CmsLog.getLog(CmsFieldsList.class); /** Stores the value of the request parameter for the search index source name. */ private String m_paramFieldconfiguration; /** * Public constructor.<p> * * @param jsp an initialized JSP action element */ public CmsFieldsList(CmsJspActionElement jsp) { this(jsp, LIST_ID, Messages.get().container(Messages.GUI_LIST_FIELDS_NAME_0)); } /** * Public constructor.<p> * * @param jsp an initialized JSP action element * @param listId the id of the list * @param listName the list name */ public CmsFieldsList(CmsJspActionElement jsp, String listId, CmsMessageContainer listName) { this(jsp, listId, listName, LIST_COLUMN_NAME, CmsListOrderEnum.ORDER_ASCENDING, null); } /** * Public constructor.<p> * * @param jsp an initialized JSP action element * @param listId the id of the displayed list * @param listName the name of the list * @param sortedColId the a priory sorted column * @param sortOrder the order of the sorted column * @param searchableColId the column to search into */ public CmsFieldsList( CmsJspActionElement jsp, String listId, CmsMessageContainer listName, String sortedColId, CmsListOrderEnum sortOrder, String searchableColId) { super(jsp, listId, listName, sortedColId, sortOrder, searchableColId); } /** * @see org.opencms.workplace.list.A_CmsListDialog#executeListMultiActions() */ @Override public void executeListMultiActions() { CmsSearchManager searchManager = OpenCms.getSearchManager(); if (getParamListAction().equals(LIST_MACTION_DELETEFIELD)) { // execute the delete multiaction Iterator<CmsListItem> itItems = getSelectedItems().iterator(); CmsListItem listItem; CmsLuceneField field; List<CmsSearchField> deleteFields = new ArrayList<CmsSearchField>(); List<CmsSearchField> fields = searchManager.getFieldConfiguration(m_paramFieldconfiguration).getFields(); Iterator<CmsSearchField> itFields; while (itItems.hasNext()) { listItem = itItems.next(); itFields = fields.iterator(); while (itFields.hasNext()) { String item = (String)listItem.get(LIST_COLUMN_NAME); CmsLuceneField curField = (CmsLuceneField)itFields.next(); String fieldName = curField.getName(); if (item.equals(fieldName)) { deleteFields.add(curField); } } } itFields = deleteFields.iterator(); while (itFields.hasNext()) { field = (CmsLuceneField)itFields.next(); searchManager.removeSearchFieldConfigurationField( searchManager.getFieldConfiguration(m_paramFieldconfiguration), field); } refreshList(); if (checkWriteConfiguration(fields)) { writeConfiguration(false); } } listSave(); } /** * @see org.opencms.workplace.list.A_CmsListDialog#executeListSingleActions() */ @Override public void executeListSingleActions() throws ServletException, IOException { String field = getSelectedItem().getId(); Map<String, String[]> params = new HashMap<String, String[]>(); String action = getParamListAction(); I_CmsSearchFieldConfiguration fieldConfig = OpenCms.getSearchManager().getFieldConfiguration( m_paramFieldconfiguration); Iterator<CmsSearchField> itFields = fieldConfig.getFields().iterator(); CmsLuceneField fieldObject = null; while (itFields.hasNext()) { CmsLuceneField curField = (CmsLuceneField)itFields.next(); if (curField.getName().equals(field)) { fieldObject = curField; } } params.put(A_CmsFieldDialog.PARAM_FIELD, new String[] {field}); params.put(A_CmsFieldDialog.PARAM_FIELDCONFIGURATION, new String[] {m_paramFieldconfiguration}); params.put(PARAM_ACTION, new String[] {DIALOG_INITIAL}); params.put(PARAM_STYLE, new String[] {CmsToolDialog.STYLE_NEW}); if (action.equals(LIST_ACTION_EDIT)) { // forward to the edit indexsource screen getToolManager().jspForwardTool( this, "/searchindex/fieldconfigurations/fieldconfiguration/field/edit", params); } else if (action.equals(LIST_ACTION_MAPPING)) { // forward to the new mapping screen getToolManager().jspForwardTool( this, "/searchindex/fieldconfigurations/fieldconfiguration/field/newmapping", params); } else if (action.equals(LIST_ACTION_OVERVIEW_FIELD)) { // forward to the field configuration overview screen getToolManager().jspForwardTool(this, "/searchindex/fieldconfigurations/fieldconfiguration/field", params); } else if (action.equals(LIST_ACTION_EXCERPT_FALSE)) { // execute the excerpt false action if (fieldObject != null) { fieldObject.setInExcerpt(true); writeConfiguration(true); } } else if (action.equals(LIST_ACTION_INDEX_FALSE)) { // execute the excerpt false action if (fieldObject != null) { fieldObject.setIndexed(true); writeConfiguration(true); } } else if (action.equals(LIST_ACTION_STORE_FALSE)) { // execute the excerpt false action if (fieldObject != null) { fieldObject.setStored(true); writeConfiguration(true); } } else if (action.equals(LIST_ACTION_EXCERPT_TRUE)) { // execute the excerpt false action if (fieldObject != null) { fieldObject.setInExcerpt(false); writeConfiguration(true); } } else if (action.equals(LIST_ACTION_INDEX_TRUE)) { // execute the excerpt false action if (fieldObject != null) { fieldObject.setIndexed(false); writeConfiguration(true); } } else if (action.equals(LIST_ACTION_STORE_TRUE)) { // execute the excerpt false action if (fieldObject != null) { fieldObject.setStored(false); writeConfiguration(true); } } listSave(); } /** * Returns the request parameter "fieldconfiguration".<p> * * @return the request parameter "fieldconfiguration" */ public String getParamFieldconfiguration() { return m_paramFieldconfiguration; } /** * Sets the request parameter "fieldconfiguration". <p> * * Method intended for workplace-properietary automatic filling of * request parameter values to dialogs, not for manual invocation. <p> * * @param fieldconfiguration the request parameter "fieldconfiguration" to set */ public void setParamFieldconfiguration(String fieldconfiguration) { m_paramFieldconfiguration = fieldconfiguration; } /** * @see org.opencms.workplace.list.A_CmsListDialog#fillDetails(java.lang.String) */ @Override protected void fillDetails(String detailId) { // get content List<CmsListItem> items = getList().getAllContent(); Iterator<CmsListItem> itItems = items.iterator(); CmsListItem item; while (itItems.hasNext()) { item = itItems.next(); if (detailId.equals(LIST_DETAIL_FIELD)) { fillDetailField(item, detailId); } } } /** * @see org.opencms.workplace.list.A_CmsListDialog#getListItems() */ @Override protected List<CmsListItem> getListItems() { List<CmsListItem> result = new ArrayList<CmsListItem>(); // get content List<CmsSearchField> fields = getFields(); Iterator<CmsSearchField> itFields = fields.iterator(); CmsLuceneField field; while (itFields.hasNext()) { field = (CmsLuceneField)itFields.next(); CmsListItem item = getList().newItem(field.getName()); String defaultValue = field.getDefaultValue(); if (defaultValue == null) { defaultValue = "-"; } item.set(LIST_COLUMN_NAME, field.getName()); item.set(LIST_COLUMN_DISPLAY, resolveMacros(field.getDisplayName())); item.set(LIST_COLUMN_INDEX, field.getIndexed()); item.set(LIST_COLUMN_EXCERPT_HIDE, Boolean.valueOf(field.isInExcerpt())); item.set(LIST_COLUMN_STORE_HIDE, Boolean.valueOf(field.isStored())); item.set(LIST_COLUMN_DEFAULT, defaultValue); result.add(item); } return result; } /** * @see org.opencms.workplace.list.A_CmsListDialog#setColumns(org.opencms.workplace.list.CmsListMetadata) */ @Override protected void setColumns(CmsListMetadata metadata) { // create column for edit CmsListColumnDefinition editCol = new CmsListColumnDefinition(LIST_COLUMN_EDIT); editCol.setName(Messages.get().container(Messages.GUI_LIST_FIELD_COL_EDIT_NAME_0)); editCol.setHelpText(Messages.get().container(Messages.GUI_LIST_FIELD_COL_EDIT_NAME_HELP_0)); editCol.setWidth("20"); editCol.setAlign(CmsListColumnAlignEnum.ALIGN_LEFT); editCol.setSorteable(false); // add dummy icon CmsListDirectAction editAction = new CmsListDirectAction(LIST_ACTION_EDIT); editAction.setName(Messages.get().container(Messages.GUI_LIST_FIELD_ACTION_EDIT_NAME_0)); editAction.setHelpText(Messages.get().container(Messages.GUI_LIST_FIELD_COL_EDIT_NAME_HELP_0)); editAction.setIconPath(LIST_ICON_FIELD_EDIT); editCol.addDirectAction(editAction); // add it to the list definition metadata.addColumn(editCol); // create column for new mapping CmsListColumnDefinition mappingCol = new CmsListColumnDefinition(LIST_COLUMN_MAPPING); mappingCol.setName(Messages.get().container(Messages.GUI_LIST_FIELD_COL_MAPPING_0)); mappingCol.setHelpText(Messages.get().container(Messages.GUI_LIST_FIELD_COL_MAPPING_HELP_0)); mappingCol.setWidth("20"); mappingCol.setAlign(CmsListColumnAlignEnum.ALIGN_LEFT); mappingCol.setSorteable(false); // add mapping action CmsListDirectAction mappingAction = new CmsListDirectAction(LIST_ACTION_MAPPING); mappingAction.setName(Messages.get().container(Messages.GUI_LIST_FIELD_ACTION_MAPPING_0)); mappingAction.setHelpText(Messages.get().container(Messages.GUI_LIST_FIELD_COL_MAPPING_HELP_0)); mappingAction.setIconPath(ICON_ADD); mappingCol.addDirectAction(mappingAction); // add it to the list definition metadata.addColumn(mappingCol); // add column for name CmsListColumnDefinition nameCol = new CmsListColumnDefinition(LIST_COLUMN_NAME); nameCol.setAlign(CmsListColumnAlignEnum.ALIGN_LEFT); nameCol.setName(Messages.get().container(Messages.GUI_LIST_SEARCHINDEX_COL_NAME_0)); nameCol.setSorteable(true); nameCol.setWidth("45%"); // add overview action CmsListDefaultAction overviewAction = new CmsListDefaultAction(LIST_ACTION_OVERVIEW_FIELD); overviewAction.setName(Messages.get().container(Messages.GUI_LIST_FIELD_COL_OVERVIEW_NAME_0)); overviewAction.setHelpText(Messages.get().container(Messages.GUI_LIST_FIELD_COL_OVERVIEW_NAME_HELP_0)); nameCol.addDefaultAction(overviewAction); metadata.addColumn(nameCol); // add column for display CmsListColumnDefinition displayCol = new CmsListColumnDefinition(LIST_COLUMN_DISPLAY); displayCol.setAlign(CmsListColumnAlignEnum.ALIGN_LEFT); displayCol.setName(Messages.get().container(Messages.GUI_LIST_FIELD_COL_DISPLAY_0)); displayCol.setWidth("35%"); metadata.addColumn(displayCol); // add hide column for store CmsListColumnDefinition storeHideCol = new CmsListColumnDefinition(LIST_COLUMN_STORE_HIDE); storeHideCol.setVisible(false); metadata.addColumn(storeHideCol); // add hide column for excerpt CmsListColumnDefinition excerptHideCol = new CmsListColumnDefinition(LIST_COLUMN_EXCERPT_HIDE); excerptHideCol.setVisible(false); metadata.addColumn(excerptHideCol); // add column for store CmsListColumnDefinition storeCol = new CmsListColumnDefinition(LIST_COLUMN_STORE); storeCol.setAlign(CmsListColumnAlignEnum.ALIGN_CENTER); storeCol.setName(Messages.get().container(Messages.GUI_LIST_FIELD_COL_STORE_0)); // true action CmsListDirectAction storeTrueAction = new CmsListDirectAction(LIST_ACTION_STORE_TRUE) { /** * @see org.opencms.workplace.tools.A_CmsHtmlIconButton#isVisible() */ @Override public boolean isVisible() { if (getItem() != null) { return ((Boolean)getItem().get(LIST_COLUMN_STORE_HIDE)).booleanValue(); } return super.isVisible(); } }; storeTrueAction.setName(Messages.get().container(Messages.GUI_LIST_FIELD_ACTION_TRUE_NAME_0)); storeTrueAction.setHelpText(Messages.get().container(Messages.GUI_LIST_FIELD_ACTION_TRUE_HELP_0)); storeTrueAction.setConfirmationMessage(Messages.get().container(Messages.GUI_LIST_FIELD_ACTION_TRUE_CONF_0)); storeTrueAction.setIconPath(ICON_TRUE); // false action CmsListDirectAction storeFalseAction = new CmsListDirectAction(LIST_ACTION_STORE_FALSE) { /** * @see org.opencms.workplace.tools.A_CmsHtmlIconButton#isVisible() */ @Override public boolean isVisible() { if (getItem() != null) { return !((Boolean)getItem().get(LIST_COLUMN_STORE_HIDE)).booleanValue(); } return super.isVisible(); } }; storeFalseAction.setName(Messages.get().container(Messages.GUI_LIST_FIELD_ACTION_FALSE_NAME_0)); storeFalseAction.setHelpText(Messages.get().container(Messages.GUI_LIST_FIELD_ACTION_FALSE_HELP_0)); storeFalseAction.setConfirmationMessage(Messages.get().container(Messages.GUI_LIST_FIELD_ACTION_FALSE_CONF_0)); storeFalseAction.setIconPath(ICON_FALSE); storeCol.addDirectAction(storeTrueAction); storeCol.addDirectAction(storeFalseAction); metadata.addColumn(storeCol); // add colum for excerpt CmsListColumnDefinition excerptCol = new CmsListColumnDefinition(LIST_COLUMN_EXCERPT); excerptCol.setAlign(CmsListColumnAlignEnum.ALIGN_CENTER); excerptCol.setName(Messages.get().container(Messages.GUI_LIST_FIELD_COL_EXCERPT_0)); // true action CmsListDirectAction excerptTrueAction = new CmsListDirectAction(LIST_ACTION_EXCERPT_TRUE) { /** * @see org.opencms.workplace.tools.A_CmsHtmlIconButton#isVisible() */ @Override public boolean isVisible() { if (getItem() != null) { return ((Boolean)getItem().get(LIST_COLUMN_EXCERPT_HIDE)).booleanValue(); } return super.isVisible(); } }; excerptTrueAction.setName(Messages.get().container(Messages.GUI_LIST_FIELD_ACTION_TRUE_NAME_0)); excerptTrueAction.setHelpText(Messages.get().container(Messages.GUI_LIST_FIELD_ACTION_TRUE_HELP_0)); excerptTrueAction.setConfirmationMessage(Messages.get().container(Messages.GUI_LIST_FIELD_ACTION_TRUE_CONF_0)); excerptTrueAction.setIconPath(ICON_TRUE); // false action CmsListDirectAction excerptFalseAction = new CmsListDirectAction(LIST_ACTION_EXCERPT_FALSE) { /** * @see org.opencms.workplace.tools.A_CmsHtmlIconButton#isVisible() */ @Override public boolean isVisible() { if (getItem() != null) { return !((Boolean)getItem().get(LIST_COLUMN_EXCERPT_HIDE)).booleanValue(); } return super.isVisible(); } }; excerptFalseAction.setName(Messages.get().container(Messages.GUI_LIST_FIELD_ACTION_FALSE_NAME_0)); excerptFalseAction.setHelpText(Messages.get().container(Messages.GUI_LIST_FIELD_ACTION_FALSE_HELP_0)); excerptFalseAction.setConfirmationMessage( Messages.get().container(Messages.GUI_LIST_FIELD_ACTION_FALSE_CONF_0)); excerptFalseAction.setIconPath(ICON_FALSE); excerptCol.addDirectAction(excerptTrueAction); excerptCol.addDirectAction(excerptFalseAction); metadata.addColumn(excerptCol); // add column for index CmsListColumnDefinition indexCol = new CmsListColumnDefinition(LIST_COLUMN_INDEX); indexCol.setAlign(CmsListColumnAlignEnum.ALIGN_CENTER); indexCol.setName(Messages.get().container(Messages.GUI_LIST_FIELD_COL_INDEX_0)); indexCol.setWidth("10%"); metadata.addColumn(indexCol); // add column for boost CmsListColumnDefinition boostCol = new CmsListColumnDefinition(LIST_COLUMN_BOOST); boostCol.setAlign(CmsListColumnAlignEnum.ALIGN_CENTER); boostCol.setName(Messages.get().container(Messages.GUI_LIST_FIELD_COL_BOOST_0)); boostCol.setWidth("5%"); metadata.addColumn(boostCol); // add column for default CmsListColumnDefinition defaultCol = new CmsListColumnDefinition(LIST_COLUMN_DEFAULT); defaultCol.setAlign(CmsListColumnAlignEnum.ALIGN_CENTER); defaultCol.setName(Messages.get().container(Messages.GUI_LIST_FIELD_COL_DEFAULT_0)); defaultCol.setWidth("5%"); metadata.addColumn(defaultCol); } /** * @see org.opencms.workplace.list.A_CmsListDialog#setIndependentActions(org.opencms.workplace.list.CmsListMetadata) */ @Override protected void setIndependentActions(CmsListMetadata metadata) { // add field configuration details CmsListItemDetails configDetails = new CmsListItemDetails(LIST_DETAIL_FIELD); configDetails.setAtColumn(LIST_COLUMN_NAME); configDetails.setVisible(false); configDetails.setShowActionName(Messages.get().container(Messages.GUI_LIST_FIELD_DETAIL_MAPPINGS_SHOW_0)); configDetails.setShowActionHelpText( Messages.get().container(Messages.GUI_LIST_FIELD_DETAIL_MAPPINGS_SHOW_HELP_0)); configDetails.setHideActionName(Messages.get().container(Messages.GUI_LIST_FIELD_DETAIL_MAPPINGS_HIDE_0)); configDetails.setHideActionHelpText( Messages.get().container(Messages.GUI_LIST_FIELD_DETAIL_MAPPINGS_HIDE_HELP_0)); configDetails.setName(Messages.get().container(Messages.GUI_LIST_FIELD_DETAIL_MAPPINGS_NAME_0)); configDetails.setFormatter( new CmsListItemDetailsFormatter(Messages.get().container(Messages.GUI_LIST_FIELD_DETAIL_MAPPINGS_NAME_0))); metadata.addItemDetails(configDetails); } /** * @see org.opencms.workplace.list.A_CmsListDialog#setMultiActions(org.opencms.workplace.list.CmsListMetadata) */ @Override protected void setMultiActions(CmsListMetadata metadata) { // add add multi action CmsListMultiAction deleteMultiAction = new CmsListMultiAction(LIST_MACTION_DELETEFIELD); deleteMultiAction.setName(Messages.get().container(Messages.GUI_LIST_FIELD_MACTION_DELETEFIELD_NAME_0)); deleteMultiAction.setHelpText( Messages.get().container(Messages.GUI_LIST_FIELD_MACTION_DELETEFIELD_NAME_HELP_0)); deleteMultiAction.setConfirmationMessage( Messages.get().container(Messages.GUI_LIST_FIELD_MACTION_DELETEFIELD_CONF_0)); deleteMultiAction.setIconPath(ICON_MULTI_DELETE); metadata.addMultiAction(deleteMultiAction); } /** * @see org.opencms.workplace.list.A_CmsListDialog#validateParamaters() */ @Override protected void validateParamaters() throws Exception { // will throw NPE if something wrong OpenCms.getSearchManager().getFieldConfiguration(getParamFieldconfiguration()).getFields(); } /** * Writes the updated search configuration back to the XML * configuration file and refreshes the complete list.<p> * * @param refresh if true, the list items are refreshed */ protected void writeConfiguration(boolean refresh) { // update the XML configuration OpenCms.writeConfiguration(CmsSearchConfiguration.class); if (refresh) { refreshList(); } } /** * Checks the configuration to write.<p> * * @param fields list of fields of the current field configuration * @return true if configuration is valid, otherwise false */ private boolean checkWriteConfiguration(List<CmsSearchField> fields) { if (fields == null) { return false; } Iterator<CmsSearchField> itFields = fields.iterator(); while (itFields.hasNext()) { CmsLuceneField curField = (CmsLuceneField)itFields.next(); if (curField.getMappings().isEmpty()) { return false; } } return true; } /** * Fills details of the field into the given item. <p> * * @param item the list item to fill * @param detailId the id for the detail to fill */ private void fillDetailField(CmsListItem item, String detailId) { StringBuffer html = new StringBuffer(); // search for the corresponding A_CmsSearchIndex: String idxFieldName = (String)item.get(LIST_COLUMN_NAME); List<CmsSearchField> fields = OpenCms.getSearchManager().getFieldConfiguration( m_paramFieldconfiguration).getFields(); Iterator<CmsSearchField> itFields = fields.iterator(); CmsLuceneField idxField = null; while (itFields.hasNext()) { CmsLuceneField curField = (CmsLuceneField)itFields.next(); if (curField.getName().equals(idxFieldName)) { idxField = curField; } } if (idxField != null) { html.append("<ul>\n"); Iterator<I_CmsSearchFieldMapping> itMappings = idxField.getMappings().iterator(); while (itMappings.hasNext()) { CmsSearchFieldMapping mapping = (CmsSearchFieldMapping)itMappings.next(); html.append(" <li>\n").append(" "); html.append(mapping.getType().toString()); if (CmsStringUtil.isNotEmpty(mapping.getParam())) { html.append("=").append(mapping.getParam()).append("\n"); } html.append(" </li>"); } html.append("</ul>\n"); } item.set(detailId, html.toString()); } /** * Returns the configured fields of the current field configuration. * * @return the configured fields of the current field configuration */ private List<CmsSearchField> getFields() { CmsSearchManager manager = OpenCms.getSearchManager(); I_CmsSearchFieldConfiguration fieldConfig = manager.getFieldConfiguration(getParamFieldconfiguration()); List<CmsSearchField> result; if (fieldConfig != null) { result = fieldConfig.getFields(); } else { result = Collections.emptyList(); if (LOG.isErrorEnabled()) { LOG.error( Messages.get().getBundle().key( Messages.ERR_SEARCHINDEX_EDIT_MISSING_PARAM_1, A_CmsFieldConfigurationDialog.PARAM_FIELDCONFIGURATION)); } } return result; } }
{ "pile_set_name": "Github" }
/** * Copyright (c) 2013-present, Facebook, Inc. All rights reserved. * * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ 'use strict'; import {EditorState, Modifier, SelectionState} from 'draft-js'; export default function removeMediaBlock(editorState, blockKey) { var content = editorState.getCurrentContent(); var block = content.getBlockForKey(blockKey); var targetRange = new SelectionState({ anchorKey: blockKey, anchorOffset: 0, focusKey: blockKey, focusOffset: block.getLength(), }); var withoutTeX = Modifier.removeRange(content, targetRange, 'backward'); var resetBlock = Modifier.setBlockType( withoutTeX, withoutTeX.getSelectionAfter(), 'unstyled' ); var newState = EditorState.push(editorState, resetBlock, 'remove-range'); return EditorState.forceSelection(newState, resetBlock.getSelectionAfter()); }
{ "pile_set_name": "Github" }
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <LangVersion>8.0</LangVersion> <OutputPath>..\..\bin\</OutputPath> <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath> </PropertyGroup> <ItemGroup> <Compile Remove="Properties\AssemblyInfo.cs" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\Mosa.Compiler.Common\Mosa.Compiler.Common.csproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="dnlib" Version="3.3.2" /> </ItemGroup> </Project>
{ "pile_set_name": "Github" }
"""Utilities for writing code that runs on Python 2 and 3""" # Copyright (c) 2010-2015 Benjamin Peterson # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from __future__ import absolute_import import functools import itertools import operator import sys import types __author__ = "Benjamin Peterson <[email protected]>" __version__ = "1.10.0" # Useful for very coarse version differentiation. PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 PY34 = sys.version_info[0:2] >= (3, 4) if PY3: string_types = str, integer_types = int, class_types = type, text_type = str binary_type = bytes MAXSIZE = sys.maxsize else: string_types = basestring, integer_types = (int, long) class_types = (type, types.ClassType) text_type = unicode binary_type = str if sys.platform.startswith("java"): # Jython always uses 32 bits. MAXSIZE = int((1 << 31) - 1) else: # It's possible to have sizeof(long) != sizeof(Py_ssize_t). class X(object): def __len__(self): return 1 << 31 try: len(X()) except OverflowError: # 32-bit MAXSIZE = int((1 << 31) - 1) else: # 64-bit MAXSIZE = int((1 << 63) - 1) del X def _add_doc(func, doc): """Add documentation to a function.""" func.__doc__ = doc def _import_module(name): """Import module, returning the module after the last dot.""" __import__(name) return sys.modules[name] class _LazyDescr(object): def __init__(self, name): self.name = name def __get__(self, obj, tp): result = self._resolve() setattr(obj, self.name, result) # Invokes __set__. try: # This is a bit ugly, but it avoids running this again by # removing this descriptor. delattr(obj.__class__, self.name) except AttributeError: pass return result class MovedModule(_LazyDescr): def __init__(self, name, old, new=None): super(MovedModule, self).__init__(name) if PY3: if new is None: new = name self.mod = new else: self.mod = old def _resolve(self): return _import_module(self.mod) def __getattr__(self, attr): _module = self._resolve() value = getattr(_module, attr) setattr(self, attr, value) return value class _LazyModule(types.ModuleType): def __init__(self, name): super(_LazyModule, self).__init__(name) self.__doc__ = self.__class__.__doc__ def __dir__(self): attrs = ["__doc__", "__name__"] attrs += [attr.name for attr in self._moved_attributes] return attrs # Subclasses should override this _moved_attributes = [] class MovedAttribute(_LazyDescr): def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): super(MovedAttribute, self).__init__(name) if PY3: if new_mod is None: new_mod = name self.mod = new_mod if new_attr is None: if old_attr is None: new_attr = name else: new_attr = old_attr self.attr = new_attr else: self.mod = old_mod if old_attr is None: old_attr = name self.attr = old_attr def _resolve(self): module = _import_module(self.mod) return getattr(module, self.attr) class _SixMetaPathImporter(object): """ A meta path importer to import six.moves and its submodules. This class implements a PEP302 finder and loader. It should be compatible with Python 2.5 and all existing versions of Python3 """ def __init__(self, six_module_name): self.name = six_module_name self.known_modules = {} def _add_module(self, mod, *fullnames): for fullname in fullnames: self.known_modules[self.name + "." + fullname] = mod def _get_module(self, fullname): return self.known_modules[self.name + "." + fullname] def find_module(self, fullname, path=None): if fullname in self.known_modules: return self return None def __get_module(self, fullname): try: return self.known_modules[fullname] except KeyError: raise ImportError("This loader does not know module " + fullname) def load_module(self, fullname): try: # in case of a reload return sys.modules[fullname] except KeyError: pass mod = self.__get_module(fullname) if isinstance(mod, MovedModule): mod = mod._resolve() else: mod.__loader__ = self sys.modules[fullname] = mod return mod def is_package(self, fullname): """ Return true, if the named module is a package. We need this method to get correct spec objects with Python 3.4 (see PEP451) """ return hasattr(self.__get_module(fullname), "__path__") def get_code(self, fullname): """Return None Required, if is_package is implemented""" self.__get_module(fullname) # eventually raises ImportError return None get_source = get_code # same as get_code _importer = _SixMetaPathImporter(__name__) class _MovedItems(_LazyModule): """Lazy loading of moved objects""" __path__ = [] # mark as package _moved_attributes = [ MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"), MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), MovedAttribute("intern", "__builtin__", "sys"), MovedAttribute("map", "itertools", "builtins", "imap", "map"), MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"), MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"), MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), MovedAttribute("reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload"), MovedAttribute("reduce", "__builtin__", "functools"), MovedAttribute("shlex_quote", "pipes", "shlex", "quote"), MovedAttribute("StringIO", "StringIO", "io"), MovedAttribute("UserDict", "UserDict", "collections"), MovedAttribute("UserList", "UserList", "collections"), MovedAttribute("UserString", "UserString", "collections"), MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), MovedModule("builtins", "__builtin__"), MovedModule("configparser", "ConfigParser"), MovedModule("copyreg", "copy_reg"), MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"), MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), MovedModule("http_cookies", "Cookie", "http.cookies"), MovedModule("html_entities", "htmlentitydefs", "html.entities"), MovedModule("html_parser", "HTMLParser", "html.parser"), MovedModule("http_client", "httplib", "http.client"), MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"), MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), MovedModule("cPickle", "cPickle", "pickle"), MovedModule("queue", "Queue"), MovedModule("reprlib", "repr"), MovedModule("socketserver", "SocketServer"), MovedModule("_thread", "thread", "_thread"), MovedModule("tkinter", "Tkinter"), MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), MovedModule("tkinter_tix", "Tix", "tkinter.tix"), MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"), MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), MovedModule("tkinter_colorchooser", "tkColorChooser", "tkinter.colorchooser"), MovedModule("tkinter_commondialog", "tkCommonDialog", "tkinter.commondialog"), MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), MovedModule("tkinter_font", "tkFont", "tkinter.font"), MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", "tkinter.simpledialog"), MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"), MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"), ] # Add windows specific modules. if sys.platform == "win32": _moved_attributes += [ MovedModule("winreg", "_winreg"), ] for attr in _moved_attributes: setattr(_MovedItems, attr.name, attr) if isinstance(attr, MovedModule): _importer._add_module(attr, "moves." + attr.name) del attr _MovedItems._moved_attributes = _moved_attributes moves = _MovedItems(__name__ + ".moves") _importer._add_module(moves, "moves") class Module_six_moves_urllib_parse(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_parse""" _urllib_parse_moved_attributes = [ MovedAttribute("ParseResult", "urlparse", "urllib.parse"), MovedAttribute("SplitResult", "urlparse", "urllib.parse"), MovedAttribute("parse_qs", "urlparse", "urllib.parse"), MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), MovedAttribute("urldefrag", "urlparse", "urllib.parse"), MovedAttribute("urljoin", "urlparse", "urllib.parse"), MovedAttribute("urlparse", "urlparse", "urllib.parse"), MovedAttribute("urlsplit", "urlparse", "urllib.parse"), MovedAttribute("urlunparse", "urlparse", "urllib.parse"), MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), MovedAttribute("quote", "urllib", "urllib.parse"), MovedAttribute("quote_plus", "urllib", "urllib.parse"), MovedAttribute("unquote", "urllib", "urllib.parse"), MovedAttribute("unquote_plus", "urllib", "urllib.parse"), MovedAttribute("urlencode", "urllib", "urllib.parse"), MovedAttribute("splitquery", "urllib", "urllib.parse"), MovedAttribute("splittag", "urllib", "urllib.parse"), MovedAttribute("splituser", "urllib", "urllib.parse"), MovedAttribute("uses_fragment", "urlparse", "urllib.parse"), MovedAttribute("uses_netloc", "urlparse", "urllib.parse"), MovedAttribute("uses_params", "urlparse", "urllib.parse"), MovedAttribute("uses_query", "urlparse", "urllib.parse"), MovedAttribute("uses_relative", "urlparse", "urllib.parse"), ] for attr in _urllib_parse_moved_attributes: setattr(Module_six_moves_urllib_parse, attr.name, attr) del attr Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes _importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"), "moves.urllib_parse", "moves.urllib.parse") class Module_six_moves_urllib_error(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_error""" _urllib_error_moved_attributes = [ MovedAttribute("URLError", "urllib2", "urllib.error"), MovedAttribute("HTTPError", "urllib2", "urllib.error"), MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), ] for attr in _urllib_error_moved_attributes: setattr(Module_six_moves_urllib_error, attr.name, attr) del attr Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes _importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"), "moves.urllib_error", "moves.urllib.error") class Module_six_moves_urllib_request(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_request""" _urllib_request_moved_attributes = [ MovedAttribute("urlopen", "urllib2", "urllib.request"), MovedAttribute("install_opener", "urllib2", "urllib.request"), MovedAttribute("build_opener", "urllib2", "urllib.request"), MovedAttribute("pathname2url", "urllib", "urllib.request"), MovedAttribute("url2pathname", "urllib", "urllib.request"), MovedAttribute("getproxies", "urllib", "urllib.request"), MovedAttribute("Request", "urllib2", "urllib.request"), MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), MovedAttribute("BaseHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), MovedAttribute("FileHandler", "urllib2", "urllib.request"), MovedAttribute("FTPHandler", "urllib2", "urllib.request"), MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), MovedAttribute("urlretrieve", "urllib", "urllib.request"), MovedAttribute("urlcleanup", "urllib", "urllib.request"), MovedAttribute("URLopener", "urllib", "urllib.request"), MovedAttribute("FancyURLopener", "urllib", "urllib.request"), MovedAttribute("proxy_bypass", "urllib", "urllib.request"), ] for attr in _urllib_request_moved_attributes: setattr(Module_six_moves_urllib_request, attr.name, attr) del attr Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes _importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"), "moves.urllib_request", "moves.urllib.request") class Module_six_moves_urllib_response(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_response""" _urllib_response_moved_attributes = [ MovedAttribute("addbase", "urllib", "urllib.response"), MovedAttribute("addclosehook", "urllib", "urllib.response"), MovedAttribute("addinfo", "urllib", "urllib.response"), MovedAttribute("addinfourl", "urllib", "urllib.response"), ] for attr in _urllib_response_moved_attributes: setattr(Module_six_moves_urllib_response, attr.name, attr) del attr Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes _importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"), "moves.urllib_response", "moves.urllib.response") class Module_six_moves_urllib_robotparser(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_robotparser""" _urllib_robotparser_moved_attributes = [ MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), ] for attr in _urllib_robotparser_moved_attributes: setattr(Module_six_moves_urllib_robotparser, attr.name, attr) del attr Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes _importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"), "moves.urllib_robotparser", "moves.urllib.robotparser") class Module_six_moves_urllib(types.ModuleType): """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" __path__ = [] # mark as package parse = _importer._get_module("moves.urllib_parse") error = _importer._get_module("moves.urllib_error") request = _importer._get_module("moves.urllib_request") response = _importer._get_module("moves.urllib_response") robotparser = _importer._get_module("moves.urllib_robotparser") def __dir__(self): return ['parse', 'error', 'request', 'response', 'robotparser'] _importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"), "moves.urllib") def add_move(move): """Add an item to six.moves.""" setattr(_MovedItems, move.name, move) def remove_move(name): """Remove item from six.moves.""" try: delattr(_MovedItems, name) except AttributeError: try: del moves.__dict__[name] except KeyError: raise AttributeError("no such move, %r" % (name,)) if PY3: _meth_func = "__func__" _meth_self = "__self__" _func_closure = "__closure__" _func_code = "__code__" _func_defaults = "__defaults__" _func_globals = "__globals__" else: _meth_func = "im_func" _meth_self = "im_self" _func_closure = "func_closure" _func_code = "func_code" _func_defaults = "func_defaults" _func_globals = "func_globals" try: advance_iterator = next except NameError: def advance_iterator(it): return it.next() next = advance_iterator try: callable = callable except NameError: def callable(obj): return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) if PY3: def get_unbound_function(unbound): return unbound create_bound_method = types.MethodType def create_unbound_method(func, cls): return func Iterator = object else: def get_unbound_function(unbound): return unbound.im_func def create_bound_method(func, obj): return types.MethodType(func, obj, obj.__class__) def create_unbound_method(func, cls): return types.MethodType(func, None, cls) class Iterator(object): def next(self): return type(self).__next__(self) callable = callable _add_doc(get_unbound_function, """Get the function out of a possibly unbound function""") get_method_function = operator.attrgetter(_meth_func) get_method_self = operator.attrgetter(_meth_self) get_function_closure = operator.attrgetter(_func_closure) get_function_code = operator.attrgetter(_func_code) get_function_defaults = operator.attrgetter(_func_defaults) get_function_globals = operator.attrgetter(_func_globals) if PY3: def iterkeys(d, **kw): return iter(d.keys(**kw)) def itervalues(d, **kw): return iter(d.values(**kw)) def iteritems(d, **kw): return iter(d.items(**kw)) def iterlists(d, **kw): return iter(d.lists(**kw)) viewkeys = operator.methodcaller("keys") viewvalues = operator.methodcaller("values") viewitems = operator.methodcaller("items") else: def iterkeys(d, **kw): return d.iterkeys(**kw) def itervalues(d, **kw): return d.itervalues(**kw) def iteritems(d, **kw): return d.iteritems(**kw) def iterlists(d, **kw): return d.iterlists(**kw) viewkeys = operator.methodcaller("viewkeys") viewvalues = operator.methodcaller("viewvalues") viewitems = operator.methodcaller("viewitems") _add_doc(iterkeys, "Return an iterator over the keys of a dictionary.") _add_doc(itervalues, "Return an iterator over the values of a dictionary.") _add_doc(iteritems, "Return an iterator over the (key, value) pairs of a dictionary.") _add_doc(iterlists, "Return an iterator over the (key, [values]) pairs of a dictionary.") if PY3: def b(s): return s.encode("latin-1") def u(s): return s unichr = chr import struct int2byte = struct.Struct(">B").pack del struct byte2int = operator.itemgetter(0) indexbytes = operator.getitem iterbytes = iter import io StringIO = io.StringIO BytesIO = io.BytesIO _assertCountEqual = "assertCountEqual" if sys.version_info[1] <= 1: _assertRaisesRegex = "assertRaisesRegexp" _assertRegex = "assertRegexpMatches" else: _assertRaisesRegex = "assertRaisesRegex" _assertRegex = "assertRegex" else: def b(s): return s # Workaround for standalone backslash def u(s): return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape") unichr = unichr int2byte = chr def byte2int(bs): return ord(bs[0]) def indexbytes(buf, i): return ord(buf[i]) iterbytes = functools.partial(itertools.imap, ord) import StringIO StringIO = BytesIO = StringIO.StringIO _assertCountEqual = "assertItemsEqual" _assertRaisesRegex = "assertRaisesRegexp" _assertRegex = "assertRegexpMatches" _add_doc(b, """Byte literal""") _add_doc(u, """Text literal""") def assertCountEqual(self, *args, **kwargs): return getattr(self, _assertCountEqual)(*args, **kwargs) def assertRaisesRegex(self, *args, **kwargs): return getattr(self, _assertRaisesRegex)(*args, **kwargs) def assertRegex(self, *args, **kwargs): return getattr(self, _assertRegex)(*args, **kwargs) if PY3: exec_ = getattr(moves.builtins, "exec") def reraise(tp, value, tb=None): if value is None: value = tp() if value.__traceback__ is not tb: raise value.with_traceback(tb) raise value else: def exec_(_code_, _globs_=None, _locs_=None): """Execute code in a namespace.""" if _globs_ is None: frame = sys._getframe(1) _globs_ = frame.f_globals if _locs_ is None: _locs_ = frame.f_locals del frame elif _locs_ is None: _locs_ = _globs_ exec("""exec _code_ in _globs_, _locs_""") exec_("""def reraise(tp, value, tb=None): raise tp, value, tb """) if sys.version_info[:2] == (3, 2): exec_("""def raise_from(value, from_value): if from_value is None: raise value raise value from from_value """) elif sys.version_info[:2] > (3, 2): exec_("""def raise_from(value, from_value): raise value from from_value """) else: def raise_from(value, from_value): raise value print_ = getattr(moves.builtins, "print", None) if print_ is None: def print_(*args, **kwargs): """The new-style print function for Python 2.4 and 2.5.""" fp = kwargs.pop("file", sys.stdout) if fp is None: return def write(data): if not isinstance(data, basestring): data = str(data) # If the file has an encoding, encode unicode with it. if (isinstance(fp, file) and isinstance(data, unicode) and fp.encoding is not None): errors = getattr(fp, "errors", None) if errors is None: errors = "strict" data = data.encode(fp.encoding, errors) fp.write(data) want_unicode = False sep = kwargs.pop("sep", None) if sep is not None: if isinstance(sep, unicode): want_unicode = True elif not isinstance(sep, str): raise TypeError("sep must be None or a string") end = kwargs.pop("end", None) if end is not None: if isinstance(end, unicode): want_unicode = True elif not isinstance(end, str): raise TypeError("end must be None or a string") if kwargs: raise TypeError("invalid keyword arguments to print()") if not want_unicode: for arg in args: if isinstance(arg, unicode): want_unicode = True break if want_unicode: newline = unicode("\n") space = unicode(" ") else: newline = "\n" space = " " if sep is None: sep = space if end is None: end = newline for i, arg in enumerate(args): if i: write(sep) write(arg) write(end) if sys.version_info[:2] < (3, 3): _print = print_ def print_(*args, **kwargs): fp = kwargs.get("file", sys.stdout) flush = kwargs.pop("flush", False) _print(*args, **kwargs) if flush and fp is not None: fp.flush() _add_doc(reraise, """Reraise an exception.""") if sys.version_info[0:2] < (3, 4): def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, updated=functools.WRAPPER_UPDATES): def wrapper(f): f = functools.wraps(wrapped, assigned, updated)(f) f.__wrapped__ = wrapped return f return wrapper else: wraps = functools.wraps def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(meta): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {}) def add_metaclass(metaclass): """Class decorator for creating a class with a metaclass.""" def wrapper(cls): orig_vars = cls.__dict__.copy() slots = orig_vars.get('__slots__') if slots is not None: if isinstance(slots, str): slots = [slots] for slots_var in slots: orig_vars.pop(slots_var) orig_vars.pop('__dict__', None) orig_vars.pop('__weakref__', None) return metaclass(cls.__name__, cls.__bases__, orig_vars) return wrapper def python_2_unicode_compatible(klass): """ A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. """ if PY2: if '__str__' not in klass.__dict__: raise ValueError("@python_2_unicode_compatible cannot be applied " "to %s because it doesn't define __str__()." % klass.__name__) klass.__unicode__ = klass.__str__ klass.__str__ = lambda self: self.__unicode__().encode('utf-8') return klass # Complete the moves implementation. # This code is at the end of this module to speed up module loading. # Turn this module into a package. __path__ = [] # required for PEP 302 and PEP 451 __package__ = __name__ # see PEP 366 @ReservedAssignment if globals().get("__spec__") is not None: __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable # Remove other six meta path importers, since they cause problems. This can # happen if six is removed from sys.modules and then reloaded. (Setuptools does # this for some reason.) if sys.meta_path: for i, importer in enumerate(sys.meta_path): # Here's some real nastiness: Another "instance" of the six module might # be floating around. Therefore, we can't use isinstance() to check for # the six meta path importer, since the other six instance will have # inserted an importer with different class. if (type(importer).__name__ == "_SixMetaPathImporter" and importer.name == __name__): del sys.meta_path[i] break del i, importer # Finally, add the importer to the meta path import hook. sys.meta_path.append(_importer)
{ "pile_set_name": "Github" }
#include <assert.h> /* Test of reduction on both parallel and loop directives (workers and vectors in gang-partitioned mode, int type with XOR). */ int main (int argc, char *argv[]) { int i, j, arr[32768], res = 0, hres = 0; for (i = 0; i < 32768; i++) arr[i] = i; #pragma acc parallel num_gangs(32) num_workers(32) vector_length(32) \ reduction(^:res) { #pragma acc loop gang /* { dg-warning "nested loop in reduction needs reduction clause for 'res'" "TODO" } */ for (j = 0; j < 32; j++) { #pragma acc loop worker vector reduction(^:res) for (i = 0; i < 1024; i++) res ^= 3 * arr[j * 1024 + i]; #pragma acc loop worker vector reduction(^:res) for (i = 0; i < 1024; i++) res ^= arr[j * 1024 + (1023 - i)]; } } for (j = 0; j < 32; j++) for (i = 0; i < 1024; i++) { hres ^= 3 * arr[j * 1024 + i]; hres ^= arr[j * 1024 + (1023 - i)]; } assert (res == hres); return 0; }
{ "pile_set_name": "Github" }
<div class="gf-form-group"> <div class="grafana-info-box"> <h4>BigQuery Authentication</h4> <p>There are two ways to authenticate the BigQuery plugin - either by uploading a Service Account key file, or by automatically retrieving credentials from the Google metadata server. The latter option is only available when running Grafana on a GCE virtual machine.</p> <h5>Uploading a Service Account Key File</h5> <p> First you need to create a Google Cloud Platform (GCP) Service Account for the Project you want to show data for. A Grafana datasource integrates with one GCP Project. If you want to visualize data from multiple GCP Projects then you need to create one datasource per GCP Project. </p> <p> The <strong>BigQuery Data Viewer</strong> role provides all the permissions that Grafana needs. The following API needs to be enabled on GCP for the datasource to work: <a class="external-link" target="_blank" href="https://console.cloud.google.com/apis/library/bigquery.googleapis.com">BigQuery API</a> </p> <h5>GCE Default Service Account</h5> <p> If Grafana is running on a Google Compute Engine (GCE) virtual machine, it is possible for Grafana to automatically retrieve the default project id and authentication token from the metadata server. In order for this to work, you need to make sure that you have a service account that is setup as the default account for the virtual machine and that the service account has been given read access to the BigQuery API. </p> <!-- TDOD docs --> <p>Detailed instructions on how to create a Service Account can be found <a class="external-link" target="_blank" href="https://doitintl.github.io/bigquery-grafana/">in the documentation.</a> </p> </div> </div> <div class="gf-form-group"> <div class="gf-form"> <h3>Authentication</h3> <info-popover mode="header">Upload your Service Account key file or paste in the contents of the file. The file contents will be encrypted and saved in the Grafana database.</info-popover> </div> <div class="gf-form-inline"> <div class="gf-form max-width-30"> <span class="gf-form-label width-13">Authentication Type</span> <div class="gf-form-select-wrapper max-width-24"> <select class="gf-form-input" ng-model="ctrl.current.jsonData.authenticationType" ng-options="f.key as f.value for f in ctrl.authenticationTypes"></select> </div> </div> </div> <div ng-if="ctrl.current.jsonData.authenticationType === ctrl.defaultAuthenticationType && !ctrl.current.jsonData.clientEmail && !ctrl.inputDataValid"> <div class="gf-form-group" ng-if="!ctrl.inputDataValid"> <div class="gf-form"> <form> <dash-upload on-upload="ctrl.onUpload(dash)" btn-text="Upload Service Account key file"></dash-upload> </form> </div> </div> <div class="gf-form-group"> <h5 class="section-heading" ng-if="!ctrl.inputDataValid">Or paste Service Account key JSON</h5> <div class="gf-form" ng-if="!ctrl.inputDataValid"> <textarea rows="10" data-share-panel-url="" class="gf-form-input" ng-model="ctrl.jsonText" ng-paste="ctrl.onPasteJwt($event)"></textarea> </div> <div ng-repeat="valError in ctrl.validationErrors" class="text-error p-l-1"> <i class="fa fa-warning"></i> {{valError}} </div> </div> </div> </div> <div class="gf-form-group" ng-if="ctrl.current.jsonData.authenticationType === ctrl.defaultAuthenticationType && (ctrl.inputDataValid || ctrl.current.jsonData.clientEmail)"> <h6>Uploaded Key Details</h6> <div class="gf-form"> <span class="gf-form-label width-13">Project</span> <input class="gf-form-input width-40" disabled type="text" ng-model="ctrl.current.jsonData.defaultProject" /> </div> <div class="gf-form"> <span class="gf-form-label width-13">Client Email</span> <input class="gf-form-input width-40" disabled type="text" ng-model="ctrl.current.jsonData.clientEmail" /> </div> <div class="gf-form"> <span class="gf-form-label width-13">Token URI</span> <input class="gf-form-input width-40" disabled type="text" ng-model='ctrl.current.jsonData.tokenUri' /> </div> <div class="gf-form" ng-if="ctrl.current.secureJsonFields.privateKey"> <span class="gf-form-label width-13">Private Key</span> <input type="text" class="gf-form-input max-width-12" disabled="disabled" value="configured"> </div> <div class="gf-form width-18"> <a class="btn btn-secondary gf-form-btn" href="#" ng-click="ctrl.resetValidationMessages()">Reset Service Account Key </a> <info-popover mode="right-normal"> Reset to clear the uploaded key and upload a new file. </info-popover> </div> </div> <p class="gf-form-label" ng-hide="ctrl.current.secureJsonFields.privateKey || ctrl.current.jsonData.authenticationType !== ctrl.defaultAuthenticationType"><i class="fa fa-save"></i> Do not forget to save your changes after uploading a file.</p> <div class="gf-form max-width-30"> <span class="gf-form-label width-13">Flat Rate Project</span> <input type="text" class="gf-form-input" ng-model='ctrl.current.jsonData.flatRateProject'></input> <info-popover mode="right-absolute"> The project that the Queries will be run in if you are using a flat-rate pricing model. </info-popover> </div> <div class="gf-form"> <label class="gf-form-label width-13">Processing Location</label> <div class="gf-form-select-wrapper"> <select class="gf-form-input gf-size-auto" ng-model="ctrl.current.jsonData.processingLocation" ng-options="f.value as f.text for f in ctrl.locations" ng-change="ctrl.refresh()"></select> </div> </div> <div class="gf-form"> <span class="gf-form-label width-13">Query Priority</span> <div class="gf-form-select-wrapper"> <select class="gf-form-select-wrapper gf-form-input gf-size-auto" ng-model="ctrl.current.jsonData.queryPriority" ng-options="f.value as f.text for f in ctrl.queryPriority" ng-change="ctrl.refresh()"></select> </div> </div> <gf-form-switch class="gf-form" label="Send anonymous usage data" label-class="width-13" checked="ctrl.current.jsonData.sendUsageData" switch-class="max-width-6"></gf-form-switch> <!-- <label class="gf-form-label query-keyword pointer"> </label> --> <p class="gf-form-label" ng-show="ctrl.current.jsonData.authenticationType !== ctrl.defaultAuthenticationType"><i class="fa fa-save"></i> Verify GCE default service account by clicking Save & Test</p>
{ "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.flink.statefun.flink.io.kinesis.polyglot; import com.google.protobuf.Any; import com.google.protobuf.InvalidProtocolBufferException; import org.apache.flink.statefun.flink.io.generated.KinesisEgressRecord; import org.apache.flink.statefun.sdk.kinesis.egress.EgressRecord; import org.apache.flink.statefun.sdk.kinesis.egress.KinesisEgressSerializer; public final class GenericKinesisEgressSerializer implements KinesisEgressSerializer<Any> { private static final long serialVersionUID = 1L; @Override public EgressRecord serialize(Any value) { final KinesisEgressRecord kinesisEgressRecord = asKinesisEgressRecord(value); final EgressRecord.Builder builder = EgressRecord.newBuilder() .withData(kinesisEgressRecord.getValueBytes().toByteArray()) .withStream(kinesisEgressRecord.getStream()) .withPartitionKey(kinesisEgressRecord.getPartitionKey()); final String explicitHashKey = kinesisEgressRecord.getExplicitHashKey(); if (explicitHashKey != null && !explicitHashKey.isEmpty()) { builder.withExplicitHashKey(explicitHashKey); } return builder.build(); } private static KinesisEgressRecord asKinesisEgressRecord(Any message) { if (!message.is(KinesisEgressRecord.class)) { throw new IllegalStateException( "The generic Kinesis egress expects only messages of type " + KinesisEgressRecord.class.getName()); } try { return message.unpack(KinesisEgressRecord.class); } catch (InvalidProtocolBufferException e) { throw new RuntimeException( "Unable to unpack message as a " + KinesisEgressRecord.class.getName(), e); } } }
{ "pile_set_name": "Github" }
input_driver = "xinput" input_device = "Controller (Xbox One For Windows)" input_device_display_name = "XBOX One Controller" input_vendor_id = "1118" input_product_id = "767" input_b_btn = "0" input_y_btn = "2" input_select_btn = "7" input_start_btn = "6" input_up_btn = "h0up" input_down_btn = "h0down" input_left_btn = "h0left" input_right_btn = "h0right" input_a_btn = "1" input_x_btn = "3" input_l_btn = "4" input_r_btn = "5" input_l2_axis = "+4" input_r2_axis = "+5" input_l3_btn = "8" input_r3_btn = "9" input_l_x_plus_axis = "+0" input_l_x_minus_axis = "-0" input_l_y_plus_axis = "-1" input_l_y_minus_axis = "+1" input_r_x_plus_axis = "+2" input_r_x_minus_axis = "-2" input_r_y_plus_axis = "-3" input_r_y_minus_axis = "+3" input_menu_toggle_btn = "10" input_b_btn_label = "A" input_y_btn_label = "X" input_select_btn_label = "View" input_start_btn_label = "Menu" input_up_btn_label = "D-Pad Up" input_down_btn_label = "D-Pad Down" input_left_btn_label = "D-Pad Left" input_right_btn_label = "D-Pad Right" input_a_btn_label = "B" input_x_btn_label = "Y" input_l_btn_label = "Left Bumper" input_r_btn_label = "Right Bumper" input_l2_axis_label = "Left Trigger" input_r2_axis_label = "Right Trigger" input_l3_btn_label = "Left Thumb" input_r3_btn_label = "Right Thumb" input_l_x_plus_axis_label = "Left Analog X+" input_l_x_minus_axis_label = "Left Analog X-" input_l_y_plus_axis_label = "Left Analog Y+" input_l_y_minus_axis_label = "Left Analog Y-" input_r_x_plus_axis_label = "Right Analog X+" input_r_x_minus_axis_label = "Right Analog X-" input_r_y_plus_axis_label = "Right Analog Y+" input_r_y_minus_axis_label = "Right Analog Y-" input_menu_toggle_btn_label = "Guide"
{ "pile_set_name": "Github" }
<!doctype html> <title>CodeMirror: HTML mixed mode</title> <meta charset="utf-8"/> <link rel=stylesheet href="../../doc/docs.css"> <link rel="stylesheet" href="../../lib/codemirror.css"> <script src="../../lib/codemirror.js"></script> <script src="../../addon/selection/selection-pointer.js"></script> <script src="../xml/xml.js"></script> <script src="../javascript/javascript.js"></script> <script src="../css/css.js"></script> <script src="../vbscript/vbscript.js"></script> <script src="htmlmixed.js"></script> <style>.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style> <div id=nav> <a href="https://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../../doc/logo.png" alt=""></a> <ul> <li><a href="../../index.html">Home</a> <li><a href="../../doc/manual.html">Manual</a> <li><a href="https://github.com/codemirror/codemirror">Code</a> </ul> <ul> <li><a href="../index.html">Language modes</a> <li><a class=active href="#">HTML mixed</a> </ul> </div> <article> <h2>HTML mixed mode</h2> <form><textarea id="code" name="code"> <html style="color: green"> <!-- this is a comment --> <head> <title>Mixed HTML Example</title> <style> h1 {font-family: comic sans; color: #f0f;} div {background: yellow !important;} body { max-width: 50em; margin: 1em 2em 1em 5em; } </style> </head> <body> <h1>Mixed HTML Example</h1> <script> function jsFunc(arg1, arg2) { if (arg1 && arg2) document.body.innerHTML = "achoo"; } </script> </body> </html> </textarea></form> <script> // Define an extended mixed-mode that understands vbscript and // leaves mustache/handlebars embedded templates in html mode var mixedMode = { name: "htmlmixed", scriptTypes: [{matches: /\/x-handlebars-template|\/x-mustache/i, mode: null}, {matches: /(text|application)\/(x-)?vb(a|script)/i, mode: "vbscript"}] }; var editor = CodeMirror.fromTextArea(document.getElementById("code"), { mode: mixedMode, selectionPointer: true }); </script> <p>The HTML mixed mode depends on the XML, JavaScript, and CSS modes.</p> <p>It takes an optional mode configuration option, <code>tags</code>, which can be used to add custom behavior for specific tags. When given, it should be an object mapping tag names (for example <code>script</code>) to arrays or three-element arrays. Those inner arrays indicate [attributeName, valueRegexp, <a href="../../doc/manual.html#option_mode">modeSpec</a>] specifications. For example, you could use <code>["type", /^foo$/, "foo"]</code> to map the attribute <code>type="foo"</code> to the <code>foo</code> mode. When the first two fields are null (<code>[null, null, "mode"]</code>), the given mode is used for any such tag that doesn't match any of the previously given attributes. For example:</p> <pre>var myModeSpec = { name: "htmlmixed", tags: { style: [["type", /^text\/(x-)?scss$/, "text/x-scss"], [null, null, "css"]], custom: [[null, null, "customMode"]] } }</pre> <p><strong>MIME types defined:</strong> <code>text/html</code> (redefined, only takes effect if you load this parser after the XML parser).</p> </article>
{ "pile_set_name": "Github" }
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <utility> // template <class T1, class T2> struct pair // struct piecewise_construct_t { }; // constexpr piecewise_construct_t piecewise_construct = piecewise_construct_t(); #include <utility> #include <tuple> #include <cassert> class A { int i_; char c_; public: A(int i, char c) : i_(i), c_(c) {} int get_i() const {return i_;} char get_c() const {return c_;} }; class B { double d_; unsigned u1_; unsigned u2_; public: B(double d, unsigned u1, unsigned u2) : d_(d), u1_(u1), u2_(u2) {} double get_d() const {return d_;} unsigned get_u1() const {return u1_;} unsigned get_u2() const {return u2_;} }; int main() { #ifndef _LIBCPP_HAS_NO_VARIADICS std::pair<A, B> p(std::piecewise_construct, std::make_tuple(4, 'a'), std::make_tuple(3.5, 6u, 2u)); assert(p.first.get_i() == 4); assert(p.first.get_c() == 'a'); assert(p.second.get_d() == 3.5); assert(p.second.get_u1() == 6u); assert(p.second.get_u2() == 2u); #endif }
{ "pile_set_name": "Github" }
// Copyright 2012-present Oliver Eilhard. All rights reserved. // Use of this source code is governed by a MIT-license. // See http://olivere.mit-license.org/license.txt for details. package elastic import "testing" func TestIngestPutPipelineURL(t *testing.T) { client := setupTestClientAndCreateIndex(t) tests := []struct { Id string Expected string }{ { "my-pipeline-id", "/_ingest/pipeline/my-pipeline-id", }, } for _, test := range tests { path, _, err := client.IngestPutPipeline(test.Id).buildURL() if err != nil { t.Fatal(err) } if path != test.Expected { t.Errorf("expected %q; got: %q", test.Expected, path) } } }
{ "pile_set_name": "Github" }
@XmlSchema(namespace="${datawave.webservice.namespace}", elementFormDefault=XmlNsForm.QUALIFIED, xmlns={@XmlNs(prefix = "", namespaceURI = "${datawave.webservice.namespace}")}) package datawave.webservice.common.result; import javax.xml.bind.annotation.XmlNs; import javax.xml.bind.annotation.XmlNsForm; import javax.xml.bind.annotation.XmlSchema;
{ "pile_set_name": "Github" }
<?xml version="1.0" ?> <!DOCTYPE translationbundle> <translationbundle lang="es-419"> <translation id="1185134272377778587">Acerca de Chromium</translation> <translation id="1472013873724362412">Tu cuenta no funciona en Chromium. Comunícate con tu administrador de dominio o utiliza una cuenta común de Google para acceder.</translation> <translation id="2195025571279539885">¿Quieres que Google Chrome te ofrezca traducir las páginas de este sitio que estén en <ph name="LANGUAGE_NAME" /> la próxima vez?</translation> <translation id="3805899903892079518">Chromium no tiene acceso a tus fotos o videos. Habilita el acceso en Configuración de iOS &gt; Privacidad &gt; Fotos.</translation> <translation id="6068866989048414399">Condiciones del servicio de Chromium</translation> <translation id="6268381023930128611">¿Salir de Chromium?</translation> <translation id="6424492062988593837">¡Chromium mejoró! Hay una nueva versión disponible.</translation> <translation id="6600954340915313787">Se copió en Chrome.</translation> <translation id="7337881442233988129">Chromium</translation> <translation id="8252885722420466166">Obtén una mejor experiencia de Google en Chromium según tu ubicación.</translation> <translation id="8353224596138547809">¿Quieres que Chromium guarde tu contraseña para este sitio?</translation> <translation id="8586442755830160949">Copyright <ph name="YEAR" /> Los autores de Chromium. Todos los derechos reservados.</translation> <translation id="985602178874221306">Los creadores de Chromium</translation> </translationbundle>
{ "pile_set_name": "Github" }
# frozen_string_literal: true require "spec_helper" require "decidim/api/test/type_context" require "decidim/core/test/shared_examples/traceable_interface_examples" require "decidim/core/test/shared_examples/scopable_interface_examples" module Decidim module Budgets describe BudgetType, type: :graphql do include_context "with a graphql type" let(:model) { create(:budget) } include_examples "scopable interface" it_behaves_like "traceable interface" do let(:author) { create(:user, :admin, organization: model.component.organization) } end describe "id" do let(:query) { "{ id }" } it "returns all the required fields" do expect(response).to include("id" => model.id.to_s) end end describe "title" do let(:query) { '{ title { translation(locale: "en")}}' } it "returns all the required fields" do expect(response["title"]["translation"]).to eq(model.title["en"]) end end describe "description" do let(:query) { '{ description { translation(locale: "en")}}' } it "returns all the required fields" do expect(response["description"]["translation"]).to eq(model.description["en"]) end end describe "total_budget" do let(:query) { "{ total_budget }" } it "returns the total budget" do expect(response["total_budget"]).to eq(model.total_budget) end end describe "projects" do let!(:budget2) { create(:budget) } let(:query) { "{ projects { id } }" } it "returns the budget projects" do ids = response["projects"].map { |project| project["id"] } expect(ids).to include(*model.projects.map(&:id).map(&:to_s)) expect(ids).not_to include(*budget2.projects.map(&:id).map(&:to_s)) end end end end end
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: be3c3a084f7b29b4880b42b4cfbf4d8f MonoImporter: serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName:
{ "pile_set_name": "Github" }
wlxt.jxie.edu.cn jw.jxie.edu.cn xxfw.jxie.edu.cn xlzx.jxie.edu.cn portal.jxie.edu.cn www.jxie.edu.cn jpkc.jxie.edu.cn
{ "pile_set_name": "Github" }
# AVAILABLE NOW: [Front-End Developer Handbook 2017](https://frontendmasters.com/books/front-end-handbook/2017/) *** ## Learn Internet/Web > The Internet is a global system of interconnected computer networks that use the Internet protocol suite (TCP/IP) to link several billion devices worldwide. It is a network of networks that consists of millions of private, public, academic, business, and government networks of local to global scope, linked by a broad array of electronic, wireless, and optical networking technologies. The Internet carries an extensive range of information resources and services, such as the inter-linked hypertext documents and applications of the World Wide Web (WWW), electronic mail, telephony, and peer-to-peer networks for file sharing. ><cite>&#8212; [Wikipedia](https://en.wikipedia.org/wiki/Internet)</cite> * [How Does the Internet work](http://www.w3.org/wiki/How_does_the_Internet_work) - W3C [read] * [How Does the Internet Work?](http://web.stanford.edu/class/msande91si/www-spr04/readings/week1/InternetWhitepaper.htm) - Stanford Paper [read] * [How the Internet Works](https://www.khanacademy.org/partner-content/code-org/internet-works) [watch] * [How the Internet Works in 5 Minutes](https://www.youtube.com/watch?v=7_LPdttKXPc) [watch] * [How the Web Works](https://www.eventedmind.com/classes/how-the-web-works-7f40254c) [watch][$] * [What Is the Internet? Or, "You Say Tomato, I Say TCP/IP"](http://www.20thingsilearned.com/en-US/what-is-the-internet/1) [read]
{ "pile_set_name": "Github" }
/* * Copyright (C) 2015 Karumi. * * 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.byl.qrobot.menu; import android.view.View; /** * Interface used to notify click events performed in ExpandableItems inside an ExpandableSelector * widget. */ public interface OnExpandableItemClickListener { void onExpandableItemClickListener(int index, View view); }
{ "pile_set_name": "Github" }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. #include "pch.h" #include "XamlUiaTextRange.h" #include "../types/TermControlUiaTextRange.hpp" #include <UIAutomationClient.h> // the same as COR_E_NOTSUPPORTED // we don't want to import the CLR headers to get it #define XAML_E_NOT_SUPPORTED 0x80131515L namespace UIA { using ::ITextRangeProvider; using ::SupportedTextSelection; using ::TextPatternRangeEndpoint; using ::TextUnit; } namespace XamlAutomation { using winrt::Windows::UI::Xaml::Automation::SupportedTextSelection; using winrt::Windows::UI::Xaml::Automation::Provider::IRawElementProviderSimple; using winrt::Windows::UI::Xaml::Automation::Provider::ITextRangeProvider; using winrt::Windows::UI::Xaml::Automation::Text::TextPatternRangeEndpoint; using winrt::Windows::UI::Xaml::Automation::Text::TextUnit; } namespace winrt::Microsoft::Terminal::TerminalControl::implementation { XamlAutomation::ITextRangeProvider XamlUiaTextRange::Clone() const { UIA::ITextRangeProvider* pReturn; THROW_IF_FAILED(_uiaProvider->Clone(&pReturn)); auto xutr = winrt::make_self<XamlUiaTextRange>(pReturn, _parentProvider); return xutr.as<XamlAutomation::ITextRangeProvider>(); } bool XamlUiaTextRange::Compare(XamlAutomation::ITextRangeProvider pRange) const { auto self = winrt::get_self<XamlUiaTextRange>(pRange); BOOL returnVal; THROW_IF_FAILED(_uiaProvider->Compare(self->_uiaProvider.get(), &returnVal)); return returnVal; } int32_t XamlUiaTextRange::CompareEndpoints(XamlAutomation::TextPatternRangeEndpoint endpoint, XamlAutomation::ITextRangeProvider pTargetRange, XamlAutomation::TextPatternRangeEndpoint targetEndpoint) { auto self = winrt::get_self<XamlUiaTextRange>(pTargetRange); int32_t returnVal; THROW_IF_FAILED(_uiaProvider->CompareEndpoints(static_cast<UIA::TextPatternRangeEndpoint>(endpoint), self->_uiaProvider.get(), static_cast<UIA::TextPatternRangeEndpoint>(targetEndpoint), &returnVal)); return returnVal; } void XamlUiaTextRange::ExpandToEnclosingUnit(XamlAutomation::TextUnit unit) const { THROW_IF_FAILED(_uiaProvider->ExpandToEnclosingUnit(static_cast<UIA::TextUnit>(unit))); } XamlAutomation::ITextRangeProvider XamlUiaTextRange::FindAttribute(int32_t /*textAttributeId*/, winrt::Windows::Foundation::IInspectable /*val*/, bool /*searchBackward*/) { // TODO GitHub #2161: potential accessibility improvement // we don't support this currently throw winrt::hresult_not_implemented(); } XamlAutomation::ITextRangeProvider XamlUiaTextRange::FindText(winrt::hstring text, bool searchBackward, bool ignoreCase) { UIA::ITextRangeProvider* pReturn; const auto queryText = wil::make_bstr(text.c_str()); THROW_IF_FAILED(_uiaProvider->FindText(queryText.get(), searchBackward, ignoreCase, &pReturn)); auto xutr = winrt::make_self<XamlUiaTextRange>(pReturn, _parentProvider); return *xutr; } winrt::Windows::Foundation::IInspectable XamlUiaTextRange::GetAttributeValue(int32_t textAttributeId) const { // Copied functionality from Types::UiaTextRange.cpp if (textAttributeId == UIA_IsReadOnlyAttributeId) { return winrt::box_value(false); } else { // We _need_ to return XAML_E_NOT_SUPPORTED here. // Returning nullptr is an improper implementation of it being unsupported. // UIA Clients rely on this HRESULT to signify that the requested attribute is undefined. // Anything else will result in the UIA Client refusing to read when navigating by word // Magically, this doesn't affect other forms of navigation... winrt::throw_hresult(XAML_E_NOT_SUPPORTED); } } void XamlUiaTextRange::GetBoundingRectangles(com_array<double>& returnValue) const { returnValue = {}; try { SAFEARRAY* pReturnVal; THROW_IF_FAILED(_uiaProvider->GetBoundingRectangles(&pReturnVal)); double* pVals; THROW_IF_FAILED(SafeArrayAccessData(pReturnVal, (void**)&pVals)); long lBound, uBound; THROW_IF_FAILED(SafeArrayGetLBound(pReturnVal, 1, &lBound)); THROW_IF_FAILED(SafeArrayGetUBound(pReturnVal, 1, &uBound)); long count = uBound - lBound + 1; std::vector<double> vec; vec.reserve(count); for (int i = 0; i < count; i++) { double element = pVals[i]; vec.push_back(element); } winrt::com_array<double> result{ vec }; returnValue = std::move(result); } catch (...) { } } XamlAutomation::IRawElementProviderSimple XamlUiaTextRange::GetEnclosingElement() { return _parentProvider; } winrt::hstring XamlUiaTextRange::GetText(int32_t maxLength) const { BSTR returnVal; THROW_IF_FAILED(_uiaProvider->GetText(maxLength, &returnVal)); return winrt::to_hstring(returnVal); } int32_t XamlUiaTextRange::Move(XamlAutomation::TextUnit unit, int32_t count) { int returnVal; THROW_IF_FAILED(_uiaProvider->Move(static_cast<UIA::TextUnit>(unit), count, &returnVal)); return returnVal; } int32_t XamlUiaTextRange::MoveEndpointByUnit(XamlAutomation::TextPatternRangeEndpoint endpoint, XamlAutomation::TextUnit unit, int32_t count) const { int returnVal; THROW_IF_FAILED(_uiaProvider->MoveEndpointByUnit(static_cast<UIA::TextPatternRangeEndpoint>(endpoint), static_cast<UIA::TextUnit>(unit), count, &returnVal)); return returnVal; } void XamlUiaTextRange::MoveEndpointByRange(XamlAutomation::TextPatternRangeEndpoint endpoint, XamlAutomation::ITextRangeProvider pTargetRange, XamlAutomation::TextPatternRangeEndpoint targetEndpoint) const { auto self = winrt::get_self<XamlUiaTextRange>(pTargetRange); THROW_IF_FAILED(_uiaProvider->MoveEndpointByRange(static_cast<UIA::TextPatternRangeEndpoint>(endpoint), /*pTargetRange*/ self->_uiaProvider.get(), static_cast<UIA::TextPatternRangeEndpoint>(targetEndpoint))); } void XamlUiaTextRange::Select() const { THROW_IF_FAILED(_uiaProvider->Select()); } void XamlUiaTextRange::AddToSelection() const { // we don't support this throw winrt::hresult_not_implemented(); } void XamlUiaTextRange::RemoveFromSelection() const { // we don't support this throw winrt::hresult_not_implemented(); } void XamlUiaTextRange::ScrollIntoView(bool alignToTop) const { THROW_IF_FAILED(_uiaProvider->ScrollIntoView(alignToTop)); } winrt::com_array<XamlAutomation::IRawElementProviderSimple> XamlUiaTextRange::GetChildren() const { // we don't have any children return {}; } }
{ "pile_set_name": "Github" }
`CameraRoll`模块提供了访问本地相册的功能。 ### 截图 ![cameraroll](img/api/cameraroll.png) ### 方法 <div class="props"> <div class="prop"> <h4 class="propTitle"><a class="anchor" name="saveimagewithtag"></a><span class="propType">static </span>saveImageWithTag<span class="propType">(tag)</span> <a class="hash-link" href="#saveimagewithtag">#</a></h4> <div> <p>保存一个图片到相册。</p> <p>@param {string} tag 在安卓上,本参数是一个本地URI,例如<code>"file:///sdcard/img.png"</code>.</p> <p>在iOS设备上可能是以下之一:</p> <ul> <li>本地URI</li> <li>资源库的标签</li> <li>非以上两种类型,表示图片数据将会存储在内存中(并且在本进程持续的时候一直会占用内存)。</li> </ul> <p>返回一个Promise,操作成功时返回新的URI。</p> </div> </div> <div class="prop"> <h4 class="propTitle"><a class="anchor" name="getphotos"></a><span class="propType">static </span>getPhotos<span class="propType">(params: object)</span> <a class="hash-link" href="#getphotos">#</a></h4> <div> <p>返回一个带有图片标识符对象的Promise。返回的对象的结构参见<a href="https://github.com/facebook/react-native/blob/0.23-stable/Libraries/CameraRoll/CameraRoll.js#L83" target="_blank"><code>getPhotosReturnChecker</code></a>。</p> <p> @param {object} 要求的参数结构参见<a href="https://github.com/facebook/react-native/blob/0.23-stable/Libraries/CameraRoll/CameraRoll.js#L45" target="_blank"><code>getPhotosParamChecker</code></a>. </p> <p> 返回一个Promise,操作成功时返回符合<a href="https://github.com/facebook/react-native/blob/0.23-stable/Libraries/CameraRoll/CameraRoll.js#L83" target="_blank"><code>getPhotosReturnChecker</code></a>结构的对象。</p> </div> </div> </div> ### 例子 ```javascript 'use strict'; const React = require('react-native'); const { CameraRoll, Image, SliderIOS, StyleSheet, Switch, Text, View, TouchableOpacity } = React; const CameraRollView = require('./CameraRollView'); const AssetScaledImageExampleView = require('./AssetScaledImageExample'); const CAMERA_ROLL_VIEW = 'camera_roll_view'; const CameraRollExample = React.createClass({ getInitialState() { return { groupTypes: 'SavedPhotos', sliderValue: 1, bigImages: true, }; }, render() { return ( <View> <Switch onValueChange={this._onSwitchChange} value={this.state.bigImages} /> <Text>{(this.state.bigImages ? 'Big' : 'Small') + ' Images'}</Text> <SliderIOS value={this.state.sliderValue} onValueChange={this._onSliderChange} /> <Text>{'Group Type: ' + this.state.groupTypes}</Text> <CameraRollView ref={CAMERA_ROLL_VIEW} batchSize={20} groupTypes={this.state.groupTypes} renderImage={this._renderImage} /> </View> ); }, loadAsset(asset){ if (this.props.navigator) { this.props.navigator.push({ title: 'Camera Roll Image', component: AssetScaledImageExampleView, backButtonTitle: 'Back', passProps: { asset: asset }, }); } }, _renderImage(asset) { const imageSize = this.state.bigImages ? 150 : 75; const imageStyle = [styles.image, {width: imageSize, height: imageSize}]; const location = asset.node.location.longitude ? JSON.stringify(asset.node.location) : 'Unknown location'; return ( <TouchableOpacity key={asset} onPress={ this.loadAsset.bind( this, asset ) }> <View style={styles.row}> <Image source={asset.node.image} style={imageStyle} /> <View style={styles.info}> <Text style={styles.url}>{asset.node.image.uri}</Text> <Text>{location}</Text> <Text>{asset.node.group_name}</Text> <Text>{new Date(asset.node.timestamp).toString()}</Text> </View> </View> </TouchableOpacity> ); }, _onSliderChange(value) { const options = CameraRoll.GroupTypesOptions; const index = Math.floor(value * options.length * 0.99); const groupTypes = options[index]; if (groupTypes !== this.state.groupTypes) { this.setState({groupTypes: groupTypes}); } }, _onSwitchChange(value) { this.refs[CAMERA_ROLL_VIEW].rendererChanged(); this.setState({ bigImages: value }); } }); const styles = StyleSheet.create({ row: { flexDirection: 'row', flex: 1, }, url: { fontSize: 9, marginBottom: 14, }, image: { margin: 4, }, info: { flex: 1, }, }); exports.title = 'Camera Roll'; exports.description = 'Example component that uses CameraRoll to list user\'s photos'; exports.examples = [ { title: 'Photos', render(): ReactElement { return <CameraRollExample />; } } ]; ```
{ "pile_set_name": "Github" }
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # This is a Pester test suite to validate the Format-Hex cmdlet in the Microsoft.PowerShell.Utility module. <# Purpose: Verify Format-Hex displays the Hexadecimal value for the input data. Action: Run Format-Hex. Expected Result: Hexadecimal equivalent of the input data is displayed. #> Describe "FormatHex" -tags "CI" { BeforeAll { $newline = [Environment]::Newline Setup -d FormatHexDataDir $inputFile1 = New-Item -Path "$TestDrive/SourceFile-1.txt" $inputText1 = 'Hello World' Set-Content -LiteralPath $inputFile1.FullName -Value $inputText1 -NoNewline $inputFile2 = New-Item -Path "$TestDrive/SourceFile-2.txt" $inputText2 = 'More text' Set-Content -LiteralPath $inputFile2.FullName -Value $inputText2 -NoNewline $inputFile3 = New-Item -Path "$TestDrive/SourceFile literal [3].txt" $inputText3 = 'Literal path' Set-Content -LiteralPath $inputFile3.FullName -Value $inputText3 -NoNewline $inputFile4 = New-Item -Path "$TestDrive/SourceFile-4.txt" $inputText4 = 'Now is the winter of our discontent' Set-Content -LiteralPath $inputFile4.FullName -Value $inputText4 -NoNewline $certificateProvider = Get-ChildItem Cert:\CurrentUser\My\ -ErrorAction SilentlyContinue $thumbprint = $null $certProviderAvailable = $false if ($certificateProvider.Count -gt 0) { $thumbprint = $certificateProvider[0].Thumbprint $certProviderAvailable = $true } $skipTest = ([System.Management.Automation.Platform]::IsLinux -or [System.Management.Automation.Platform]::IsMacOS -or (-not $certProviderAvailable)) } Context "InputObject Paramater" { BeforeAll { enum TestEnum { TestOne = 1; TestTwo = 2; TestThree = 3; TestFour = 4 } Add-Type -TypeDefinition @' public enum TestSByteEnum : sbyte { One = -1, Two = -2, Three = -3, Four = -4 } '@ } $testCases = @( @{ Name = "Can process bool type 'fhx -InputObject `$true'" InputObject = $true Count = 1 ExpectedResult = "00000000 01 00 00 00" } @{ Name = "Can process byte type 'fhx -InputObject [byte]5'" InputObject = [byte]5 Count = 1 ExpectedResult = "00000000 05" } @{ Name = "Can process byte[] type 'fhx -InputObject [byte[]](1,2,3,4,5)'" InputObject = [byte[]](1, 2, 3, 4, 5) Count = 1 ExpectedResult = "00000000 01 02 03 04 05 ....." } @{ Name = "Can process int type 'fhx -InputObject 7'" InputObject = 7 Count = 1 ExpectedResult = "00000000 07 00 00 00 ...." } @{ Name = "Can process int[] type 'fhx -InputObject [int[]](5,6,7,8)'" InputObject = [int[]](5, 6, 7, 8) Count = 1 ExpectedResult = "00000000 05 00 00 00 06 00 00 00 07 00 00 00 08 00 00 00 ................" } @{ Name = "Can process int32 type 'fhx -InputObject [int32]2032'" InputObject = [int32]2032 Count = 1 ExpectedResult = "00000000 F0 07 00 00 ð..." } @{ Name = "Can process int32[] type 'fhx -InputObject [int32[]](2032, 2033, 2034)'" InputObject = [int32[]](2032, 2033, 2034) Count = 1 ExpectedResult = "0000000000000000 F0 07 00 00 F1 07 00 00 F2 07 00 00 ð...ñ...ò..." } @{ Name = "Can process Int64 type 'fhx -InputObject [Int64]9223372036854775807'" InputObject = [Int64]9223372036854775807 Count = 1 ExpectedResult = "0000000000000000 FF FF FF FF FF FF FF 7F ÿÿÿÿÿÿÿ�" } @{ Name = "Can process Int64[] type 'fhx -InputObject [Int64[]](9223372036852,9223372036853)'" InputObject = [Int64[]](9223372036852, 9223372036853) Count = 1 ExpectedResult = "0000000000000000 F4 5A D0 7B 63 08 00 00 F5 5A D0 7B 63 08 00 00 ôZÐ{c...õZÐ{c..." } @{ Name = "Can process string type 'fhx -InputObject hello world'" InputObject = "hello world" Count = 1 ExpectedResult = "0000000000000000 68 65 6C 6C 6F 20 77 6F 72 6C 64 hello world" } @{ Name = "Can process PS-native enum array '[TestEnum[]]('TestOne', 'TestTwo', 'TestThree', 'TestFour') | fhx'" InputObject = [TestEnum[]]('TestOne', 'TestTwo', 'TestThree', 'TestFour') Count = 1 ExpectedResult = "0000000000000000 01 00 00 00 02 00 00 00 03 00 00 00 04 00 00 00 ................" } @{ Name = "Can process C#-native sbyte enum array '[TestSByteEnum[]]('One', 'Two', 'Three', 'Four') | fhx'" InputObject = [TestSByteEnum[]]('One', 'Two', 'Three', 'Four') Count = 1 ExpectedResult = "0000000000000000 FF FE FD FC .þýü" } ) It "<Name>" -TestCase $testCases { param ($Name, $InputObject, $Count, $ExpectedResult) $result = Format-Hex -InputObject $InputObject $result.count | Should -Be $Count $result | Should -BeOfType Microsoft.PowerShell.Commands.ByteCollection $result.ToString() | Should -MatchExactly $ExpectedResult } } Context "InputObject From Pipeline" { BeforeAll { enum TestEnum { TestOne = 1; TestTwo = 2; TestThree = 3; TestFour = 4 } Add-Type -TypeDefinition @' public enum TestSByteEnum : sbyte { One = -1, Two = -2, Three = -3, Four = -4 } '@ } $testCases = @( @{ Name = "Can process bool type '`$true | fhx'" InputObject = $true Count = 1 ExpectedResult = "0000000000000000 01" } @{ Name = "Can process byte type '[byte]5 | fhx'" InputObject = [byte]5 Count = 1 ExpectedResult = "0000000000000000 05" } @{ Name = "Can process byte[] type '[byte[]](1,2) | fhx'" InputObject = [byte[]](1, 2) Count = 1 ExpectedResult = "0000000000000000 01 02 ��" } @{ Name = "Can process int type '7 | fhx'" InputObject = 7 Count = 1 ExpectedResult = "0000000000000000 07 00 00 00 � " } @{ Name = "Can process int[] type '[int[]](5,6) | fhx'" InputObject = [int[]](5, 6) Count = 1 ExpectedResult = "0000000000000000 05 00 00 00 06 00 00 00 � � " } @{ Name = "Can process int32 type '[int32]2032 | fhx'" InputObject = [int32]2032 Count = 1 ExpectedResult = "0000000000000000 F0 07 00 00 ð� " } @{ Name = "Can process int32[] type '[int32[]](2032, 2033) | fhx'" InputObject = [int32[]](2032, 2033) Count = 1 ExpectedResult = "0000000000000000 F0 07 00 00 F1 07 00 00 ð� ñ� " } @{ Name = "Can process Int64 type '[Int64]9223372036854775807 | fhx'" InputObject = [Int64]9223372036854775807 Count = 1 ExpectedResult = "0000000000000000 FF FF FF FF FF FF FF 7F ÿÿÿÿÿÿÿ�" } @{ Name = "Can process Int64[] type '[Int64[]](9223372036852,9223372036853) | fhx'" InputObject = [Int64[]](9223372036852, 9223372036853) Count = 1 ExpectedResult = "0000000000000000 F4 5A D0 7B 63 08 00 00 F5 5A D0 7B 63 08 00 00 ôZÐ{c� õZÐ{c� " } @{ Name = "Can process string type 'hello world | fhx'" InputObject = "hello world" Count = 1 ExpectedResult = "0000000000000000 68 65 6C 6C 6F 20 77 6F 72 6C 64 hello world" } @{ Name = "Can process string type amidst other types { 1, 2, 3, 'hello world' | fhx }" InputObject = 1, 2, 3, "hello world" Count = 2 ExpectedResult = "0000000000000000 01 00 00 00 02 00 00 00 03 00 00 00 � � � " ExpectedSecondResult = "0000000000000000 68 65 6C 6C 6F 20 77 6F 72 6C 64 hello world" } @{ Name = "Can process jagged array type '[sbyte[]](-15, 18, 21, -5), [byte[]](1, 2, 3, 4, 5, 6) | fhx'" InputObject = [sbyte[]](-15, 18, 21, -5), [byte[]](1, 2, 3, 4, 5, 6) Count = 2 ExpectedResult = "0000000000000000 F1 12 15 FB ñ��û" ExpectedSecondResult = "0000000000000000 01 02 03 04 05 06 ������" } @{ Name = "Can process jagged array type '[bool[]](`$true, `$false), [int[]](1, 2, 3, 4) | fhx'" InputObject = [bool[]]($true, $false), [int[]](1, 2, 3, 4) Count = 2 ExpectedResult = "0000000000000000 01 00 00 00 00 00 00 00 �" ExpectedSecondResult = "0000000000000000 01 00 00 00 02 00 00 00 03 00 00 00 04 00 00 00 � � � �" } @{ Name = "Can process PS-native enum array '[TestEnum[]]('TestOne', 'TestTwo', 'TestThree', 'TestFour') | fhx'" InputObject = [TestEnum[]]('TestOne', 'TestTwo', 'TestThree', 'TestFour') Count = 1 ExpectedResult = "0000000000000000 01 00 00 00 02 00 00 00 03 00 00 00 04 00 00 00 � � � � " } @{ Name = "Can process C#-native sbyte enum array '[TestSByteEnum[]]('One', 'Two', 'Three', 'Four') | fhx'" InputObject = [TestSByteEnum[]]('One', 'Two', 'Three', 'Four') Count = 1 ExpectedResult = "0000000000000000 FF FE FD FC ÿþýü" } ) It "<Name>" -TestCases $testCases { param ($Name, $InputObject, $Count, $ExpectedResult, $ExpectedSecondResult) $result = $InputObject | Format-Hex $result.Count | Should -Be $Count $result | Should -BeOfType Microsoft.PowerShell.Commands.ByteCollection $result[0].ToString() | Should -MatchExactly $ExpectedResult if ($result.count -gt 1) { $result[1].ToString() | Should -MatchExactly $ExpectedSecondResult } } $heterogenousInputCases = @( @{ InputScript = { [sbyte[]](-15, 18, 21, -5), "hello", [byte[]](1..6), 1, 2, 3, 4 } Count = 4 ExpectedResults = @( "0000000000000000 F1 12 15 FB ñ��û" "0000000000000000 68 65 6C 6C 6F hello" "0000000000000000 01 02 03 04 05 06 ������" "0000000000000000 01 00 00 00 02 00 00 00 03 00 00 00 04 00 00 00 � � � � " ) ExpectedLabels = @( "System.SByte[]" "System.String" "System.Byte" "System.Int32" ).ForEach{ [regex]::Escape($_) } -join '|' } @{ InputScript = { $inputFile1, "Mountains are merely mountains", 1, 4, 5, 3, [ushort[]](1..10) } Count = 6 ExpectedResults = @( "0000000000000000 48 65 6C 6C 6F 20 57 6F 72 6C 64 Hello World" "0000000000000000 4D 6F 75 6E 74 61 69 6E 73 20 61 72 65 20 6D 65 Mountains are me" "0000000000000010 72 65 6C 79 20 6D 6F 75 6E 74 61 69 6E 73 rely mountains" "0000000000000000 01 00 00 00 04 00 00 00 05 00 00 00 03 00 00 00 � � � � " "0000000000000000 01 00 02 00 03 00 04 00 05 00 06 00 07 00 08 00 � � � � � � � � " "0000000000000010 09 00 0A 00 � � " ) ExpectedLabels = @( $inputFile1.FullName "System.String" "System.Int32" "System.UInt16[]" ).ForEach{ [regex]::Escape($_) } -join '|' } @{ InputScript = { $true, $false, $true, 123, 100, 76, $true, $false } Count = 3 ExpectedResults = @( "0000000000000000 01 00 00 00 00 00 00 00 01 00 00 00 � �" "0000000000000000 7B 00 00 00 64 00 00 00 4C 00 00 00 { d L" "0000000000000000 01 00 00 00 00 00 00 00 �" ) ExpectedLabels = @( "System.Boolean" "System.Int32" ).ForEach{ [regex]::Escape($_) } -join '|' } ) It 'can process jagged input: <InputScript>' -TestCases $heterogenousInputCases { param($InputScript, $Count, $ExpectedResults, $ExpectedLabels) $Results = & $InputScript | Format-Hex $Results | Should -HaveCount $Count $ExpectedResults | Should -HaveCount $Count for ($Number = 0; $Number -lt $Results.Count; $Number++) { $Results[$Number] | Should -MatchExactly $ExpectedResults[$Number] $Results[$Number].Label | Should -MatchExactly $ExpectedLabels } } } Context "Path and LiteralPath Parameters" { $testDirectory = $inputFile1.DirectoryName $testCases = @( @{ Name = "Can process file content from given file path 'fhx -Path `$inputFile1'" PathCase = $true Path = $inputFile1 Count = 1 ExpectedResult = $inputText1 } @{ Name = "Can process file content from all files in array of file paths 'fhx -Path `$inputFile1, `$inputFile2'" PathCase = $true Path = @($inputFile1, $inputFile2) Count = 2 ExpectedResult = $inputText1 ExpectedSecondResult = $inputText2 } @{ Name = "Can process file content from all files when resolved to multiple paths 'fhx -Path '`$testDirectory\SourceFile-*''" PathCase = $true Path = "$testDirectory\SourceFile-*" Count = 2 ExpectedResult = $inputText1 ExpectedSecondResult = $inputText2 } @{ Name = "Can process file content from given file path 'fhx -LiteralPath `$inputFile3'" Path = $inputFile3 Count = 1 ExpectedResult = $inputText3 } @{ Name = "Can process file content from all files in array of file paths 'fhx -LiteralPath `$inputFile1, `$inputFile3'" Path = @($inputFile1, $inputFile3) Count = 2 ExpectedResult = $inputText1 ExpectedSecondResult = $inputText3 } ) It "<Name>" -TestCase $testCases { param ($Name, $PathCase, $Path, $ExpectedResult, $ExpectedSecondResult) if ($PathCase) { $result = Format-Hex -Path $Path } else { # LiteralPath $result = Format-Hex -LiteralPath $Path } $result | Should -BeOfType Microsoft.PowerShell.Commands.ByteCollection $result[0].ToString() | Should -MatchExactly $ExpectedResult if ($result.count -gt 1) { $result[1].ToString() | Should -MatchExactly $ExpectedSecondResult } } It 'properly accepts -LiteralPath input from a FileInfo object' { $FilePath = 'TestDrive:\FHX-LitPathTest.txt' "Hello World!" | Set-Content -Path $FilePath $FileObject = Get-Item -Path $FilePath $result = $FileObject | Format-Hex if ($IsWindows) { $Result.Bytes[-1] | Should -Be 0x0A $Result.Bytes[-2] | Should -Be 0x0D $Result.Bytes.Length | Should -Be 14 } else { $Result.Bytes[-1] | Should -Be 0x0A $Result.Bytes.Length | Should -Be 13 } } } Context "Encoding Parameter" { $testCases = @( @{ Name = "Can process ASCII encoding 'fhx -InputObject 'hello' -Encoding ASCII'" Encoding = "ASCII" Count = 1 ExpectedResult = "0000000000000000 68 65 6C 6C 6F hello" } @{ Name = "Can process BigEndianUnicode encoding 'fhx -InputObject 'hello' -Encoding BigEndianUnicode'" Encoding = "BigEndianUnicode" Count = 1 ExpectedResult = "0000000000000000 00 68 00 65 00 6C 00 6C 00 6F h e l l o" } @{ Name = "Can process BigEndianUTF32 encoding 'fhx -InputObject 'hello' -Encoding BigEndianUTF32'" Encoding = "BigEndianUTF32" Count = 2 ExpectedResult = "0000000000000000 00 00 00 68 00 00 00 65 00 00 00 6C 00 00 00 6C h e l l" ExpectedSecondResult = "0000000000000010 00 00 00 6F o" } @{ Name = "Can process Unicode encoding 'fhx -InputObject 'hello' -Encoding Unicode'" Encoding = "Unicode" Count = 1 ExpectedResult = "0000000000000000 68 00 65 00 6C 00 6C 00 6F 00 h e l l o " } @{ Name = "Can process UTF7 encoding 'fhx -InputObject 'hello' -Encoding UTF7'" Encoding = "UTF7" Count = 1 ExpectedResult = "0000000000000000 68 65 6C 6C 6F hello" } @{ Name = "Can process UTF8 encoding 'fhx -InputObject 'hello' -Encoding UTF8'" Encoding = "UTF8" Count = 1 ExpectedResult = "0000000000000000 68 65 6C 6C 6F hello" } @{ Name = "Can process UTF32 encoding 'fhx -InputObject 'hello' -Encoding UTF32'" Encoding = "UTF32" Count = 2 ExpectedResult = "0000000000000000 68 00 00 00 65 00 00 00 6C 00 00 00 6C 00 00 00 h e l l " ExpectedSecondResult = "0000000000000010 6F 00 00 00 o " } ) It "<Name>" -TestCase $testCases { param ($Name, $Encoding, $Count, $ExpectedResult) $result = Format-Hex -InputObject 'hello' -Encoding $Encoding $result.count | Should -Be $Count $result | Should -BeOfType Microsoft.PowerShell.Commands.ByteCollection $result[0].ToString() | Should -MatchExactly $ExpectedResult } } Context "Validate Error Scenarios" { $testDirectory = $inputFile1.DirectoryName $testCases = @( @{ Name = "Does not support non-FileSystem Provider paths 'fhx -Path 'Cert:\CurrentUser\My\`$thumbprint' -ErrorAction Stop'" PathParameterErrorCase = $true Path = "Cert:\CurrentUser\My\$thumbprint" ExpectedFullyQualifiedErrorId = "FormatHexOnlySupportsFileSystemPaths,Microsoft.PowerShell.Commands.FormatHex" } @{ Name = "Type Not Supported 'fhx -InputObject @{'hash' = 'table'} -ErrorAction Stop'" InputObjectErrorCase = $true Path = $inputFile1 InputObject = @{ "hash" = "table" } ExpectedFullyQualifiedErrorId = "FormatHexTypeNotSupported,Microsoft.PowerShell.Commands.FormatHex" } ) It "<Name>" -Skip:$skipTest -TestCase $testCases { param ($Name, $PathParameterErrorCase, $Path, $InputObject, $InputObjectErrorCase, $ExpectedFullyQualifiedErrorId) { if ($PathParameterErrorCase) { $result = Format-Hex -Path $Path -ErrorAction Stop } if ($InputObjectErrorCase) { $result = Format-Hex -InputObject $InputObject -ErrorAction Stop } } | Should -Throw -ErrorId $ExpectedFullyQualifiedErrorId } } Context "Continues to Process Valid Paths" { $testCases = @( @{ Name = "If given invalid path in array, continues to process valid paths 'fhx -Path `$invalidPath, `$inputFile1 -ErrorVariable e -ErrorAction SilentlyContinue'" PathCase = $true InvalidPath = "$($inputFile1.DirectoryName)\fakefile8888845345345348709.txt" ExpectedFullyQualifiedErrorId = "FileNotFound,Microsoft.PowerShell.Commands.FormatHex" } @{ Name = "If given a non FileSystem path in array, continues to process valid paths 'fhx -Path `$invalidPath, `$inputFile1 -ErrorVariable e -ErrorAction SilentlyContinue'" PathCase = $true InvalidPath = "Cert:\CurrentUser\My\$thumbprint" ExpectedFullyQualifiedErrorId = "FormatHexOnlySupportsFileSystemPaths,Microsoft.PowerShell.Commands.FormatHex" } @{ Name = "If given a non FileSystem path in array (with LiteralPath), continues to process valid paths 'fhx -Path `$invalidPath, `$inputFile1 -ErrorVariable e -ErrorAction SilentlyContinue'" InvalidPath = "Cert:\CurrentUser\My\$thumbprint" ExpectedFullyQualifiedErrorId = "FormatHexOnlySupportsFileSystemPaths,Microsoft.PowerShell.Commands.FormatHex" } ) It "<Name>" -Skip:$skipTest -TestCase $testCases { param ($Name, $PathCase, $InvalidPath, $ExpectedFullyQualifiedErrorId) $output = $null $errorThrown = $null if ($PathCase) { $output = Format-Hex -Path $InvalidPath, $inputFile1 -ErrorVariable errorThrown -ErrorAction SilentlyContinue } else { # LiteralPath $output = Format-Hex -LiteralPath $InvalidPath, $inputFile1 -ErrorVariable errorThrown -ErrorAction SilentlyContinue } $errorThrown.FullyQualifiedErrorId | Should -MatchExactly $ExpectedFullyQualifiedErrorId $output.Length | Should -Be 1 $output[0].ToString() | Should -MatchExactly $inputText1 } } Context "Cmdlet Functionality" { It "Path is default Parameter Set 'fhx `$inputFile1'" { $result = Format-Hex $inputFile1 $result | Should -Not -BeNullOrEmpty , $result | Should -BeOfType Microsoft.PowerShell.Commands.ByteCollection $actualResult = $result.ToString() $actualResult | Should -MatchExactly $inputText1 } It "Validate file input from Pipeline 'Get-ChildItem `$inputFile1 | Format-Hex'" { $result = Get-ChildItem $inputFile1 | Format-Hex $result | Should -Not -BeNullOrEmpty , $result | Should -BeOfType Microsoft.PowerShell.Commands.ByteCollection $actualResult = $result.ToString() $actualResult | Should -MatchExactly $inputText1 } It "Validate that streamed text does not have buffer underrun problems ''a' * 30 | Format-Hex'" { $result = "a" * 30 | Format-Hex $result | Should -Not -BeNullOrEmpty $result | Should -BeOfType Microsoft.PowerShell.Commands.ByteCollection $result[0].ToString() | Should -MatchExactly "0000000000000000 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 aaaaaaaaaaaaaaaa" $result[1].ToString() | Should -MatchExactly "0000000000000010 61 61 61 61 61 61 61 61 61 61 61 61 61 61 aaaaaaaaaaaaaa " } It "Validate that files do not have buffer underrun problems 'Format-Hex -Path `$InputFile4'" { $result = Format-Hex -Path $InputFile4 $result | Should -Not -BeNullOrEmpty $result.Count | Should -Be 3 $result[0].ToString() | Should -MatchExactly "0000000000000000 4E 6F 77 20 69 73 20 74 68 65 20 77 69 6E 74 65 Now is the winte" $result[1].ToString() | Should -MatchExactly "0000000000000010 72 20 6F 66 20 6F 75 72 20 64 69 73 63 6F 6E 74 r of our discont" $result[2].ToString() | Should -MatchExactly "0000000000000020 65 6E 74 ent " } } Context "Count and Offset parameters" { It "Count = length" { $result = Format-Hex -Path $InputFile4 -Count $inputText4.Length $result | Should -Not -BeNullOrEmpty $result.Count | Should -Be 3 $result[0].ToString() | Should -MatchExactly "0000000000000000 4E 6F 77 20 69 73 20 74 68 65 20 77 69 6E 74 65 Now is the winte" $result[1].ToString() | Should -MatchExactly "0000000000000010 72 20 6F 66 20 6F 75 72 20 64 69 73 63 6F 6E 74 r of our discont" $result[2].ToString() | Should -MatchExactly "0000000000000020 65 6E 74 ent " } It "Count = 1" { $result = Format-Hex -Path $inputFile4 -Count 1 $result.ToString() | Should -MatchExactly "0000000000000000 4E N " } It "Offset = length" { $result = Format-Hex -Path $InputFile4 -Offset $inputText4.Length $result | Should -BeNullOrEmpty $result = Format-Hex -InputObject $inputText4 -Offset $inputText4.Length $result | Should -BeNullOrEmpty } It "Offset = 1" { $result = Format-Hex -Path $InputFile4 -Offset 1 $result | Should -Not -BeNullOrEmpty $result.Count | Should -Be 3 $result[0].ToString() | Should -MatchExactly "0000000000000001 6F 77 20 69 73 20 74 68 65 20 77 69 6E 74 65 72 ow is the winter" $result[1].ToString() | Should -MatchExactly "0000000000000011 20 6F 66 20 6F 75 72 20 64 69 73 63 6F 6E 74 65 of our disconte" $result[2].ToString() | Should -MatchExactly "0000000000000021 6E 74 nt " } It "Count = 1 and Offset = 1" { $result = Format-Hex -Path $inputFile4 -Count 1 -Offset 1 $result.ToString() | Should -MatchExactly "0000000000000001 6F o " } It "Count should be > 0" { { Format-Hex -Path $inputFile4 -Count 0 } | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.FormatHex" } It "Offset should be >= 0" { { Format-Hex -Path $inputFile4 -Offset -1 } | Should -Throw -ErrorId "ParameterArgumentValidationError,Microsoft.PowerShell.Commands.FormatHex" } It "Offset = 0" { $result = Format-Hex -Path $InputFile4 -Offset 0 $result | Should -Not -BeNullOrEmpty $result.Count | Should -Be 3 $result[0].ToString() | Should -MatchExactly "0000000000000000 4E 6F 77 20 69 73 20 74 68 65 20 77 69 6E 74 65 Now is the winte" $result[1].ToString() | Should -MatchExactly "0000000000000010 72 20 6F 66 20 6F 75 72 20 64 69 73 63 6F 6E 74 r of our discont" $result[2].ToString() | Should -MatchExactly "0000000000000020 65 6E 74 ent " } } }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2018 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas 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, version 3 of the License. * * Canvas 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 this program. If not, see <http://www.gnu.org/licenses/>. */ import React, {Component} from 'react' import {string, func} from 'prop-types' import {Badge} from '@instructure/ui-elements' import {ScreenReaderContent} from '@instructure/ui-a11y' export default class Indicator extends Component { static propTypes = { title: string.isRequired, variant: string.isRequired, indicatorRef: func } static defaultProps = { indicatorRef: () => {} } render() { return ( <div ref={this.props.indicatorRef}> <Badge standalone type="notification" variant={this.props.variant} /> <ScreenReaderContent>{this.props.title}</ScreenReaderContent> </div> ) } }
{ "pile_set_name": "Github" }
// Carousels .carousel { .carousel-control-prev-icon, .carousel-control-next-icon { width: $carousel-control-icon-width; height: $carousel-control-icon-height; } .carousel-control-prev-icon { background-image: $carousel-control-prev-icon; } .carousel-control-next-icon { background-image: $carousel-control-next-icon; } .carousel-indicators { li { width: $carousel-indicators-width; height: $carousel-indicators-height; cursor: pointer; border-radius: $carousel-indicators-border-radius; } } } .carousel-fade { .carousel-item { opacity: 0; transition-duration: $carousel-transition-duration; transition-property: opacity; } .carousel-item.active, .carousel-item-next.carousel-item-left, .carousel-item-prev.carousel-item-right { opacity: 1; } .carousel-item-left, .carousel-item-right { &.active { opacity: 0; } } .carousel-item-next, .carousel-item-prev, .carousel-item.active, .carousel-item-left.active, .carousel-item-prev.active { transform: $carousel-item-transform; @supports (transform-style: preserve-3d) { transform: $carousel-item-transform-2; } } }
{ "pile_set_name": "Github" }
const merge = require('webpack-merge') const common = require('./webpack.common.js') const WebpackCopyPlugin = require('copy-webpack-plugin') module.exports = merge(common, { plugins: [ new WebpackCopyPlugin([{ from: 'README.md', to: 'README.md' }, { from: 'LICENSE', to: 'LICENSE' }, { from: 'CHANGELOG.md', to: 'CHANGELOG.md' }, { from: 'manifest.json', to: 'manifest.json' }, { from: 'oidc-callback.html', to: 'oidc-callback.html' }, { from: 'oidc-silent-redirect.html', to: 'oidc-silent-redirect.html' }]) ], mode: 'production', devtool: 'none', resolve: { alias: { vue: 'vue/dist/vue.min.js' } } })
{ "pile_set_name": "Github" }
"steam/cached/InstallSubChooseApps_SingleApp.res" { "InstallSubChooseApps" { "ControlName" "CInstallSubChooseApps" "fieldName" "InstallSubChooseApps" "xpos" "8" "ypos" "48" "wide" "388" "tall" "300" "AutoResize" "0" "PinCorner" "0" "visible" "1" "enabled" "1" "tabPosition" "1" "paintbackground" "1" "WizardWide" "0" "WizardTall" "0" } "Label1" { "ControlName" "Label" "fieldName" "Label1" "xpos" "10" "ypos" "24" "wide" "340" "tall" "24" "AutoResize" "0" "PinCorner" "0" "visible" "1" "enabled" "1" "tabPosition" "0" "paintbackground" "1" "labelText" "#Steam_InstallGameInfo" "textAlignment" "north-west" "wrap" "1" } "CreateShortcutCheck" { "ControlName" "CheckButton" "fieldName" "CreateShortcutCheck" "xpos" "16" "ypos" "60" "wide" "390" "tall" "24" "AutoResize" "0" "PinCorner" "0" "visible" "1" "enabled" "1" "tabPosition" "0" "paintbackground" "1" "labelText" "#Steam_Install_CreateDesktopShortcut" "textAlignment" "west" "wrap" "0" "Default" "0" } "CreateStartMenuShortcutCheck" { "ControlName" "CheckButton" "fieldName" "CreateStartMenuShortcutCheck" "xpos" "16" "ypos" "84" "wide" "390" "tall" "24" "AutoResize" "0" "PinCorner" "0" "visible" "1" "enabled" "1" "tabPosition" "0" "paintbackground" "1" "labelText" "#Steam_Install_CreateStartMenuShortcut" "textAlignment" "west" "wrap" "0" "Default" "0" } "InstallSize" { "ControlName" "Label" "fieldName" "InstallSize" "xpos" "10" "ypos" "128" "wide" "186" "tall" "24" "AutoResize" "0" "PinCorner" "0" "visible" "1" "enabled" "1" "tabPosition" "0" "paintbackground" "1" "labelText" "#Steam_ScanCDKey_SpaceRequired" "textAlignment" "west" "wrap" "0" } "InstallSizeLabel" { "ControlName" "Label" "fieldName" "InstallSizeLabel" "xpos" "200" "ypos" "128" "wide" "80" "tall" "24" "AutoResize" "0" "PinCorner" "0" "visible" "1" "enabled" "1" "tabPosition" "0" "paintbackground" "1" "labelText" "42 MB" "textAlignment" "west" "wrap" "0" } "DriveSpace" { "ControlName" "Label" "fieldName" "DriveSpace" "xpos" "10" "ypos" "152" "wide" "186" "tall" "24" "AutoResize" "0" "PinCorner" "0" "visible" "1" "enabled" "1" "tabPosition" "0" "paintbackground" "1" "labelText" "#Steam_ScanCDKey_SpaceAvailable" "textAlignment" "west" "wrap" "0" } "DriveSpaceLabel" { "ControlName" "Label" "fieldName" "DriveSpaceLabel" "xpos" "200" "ypos" "152" "wide" "80" "tall" "24" "AutoResize" "0" "PinCorner" "0" "visible" "1" "enabled" "1" "tabPosition" "0" "paintbackground" "1" "labelText" "148805 MB" "textAlignment" "west" "wrap" "0" } "DownloadTimeLabel" { "ControlName" "Label" "fieldName" "DownloadTimeLabel" "xpos" "10" "ypos" "176" "wide" "189" "tall" "24" "AutoResize" "0" "PinCorner" "0" "visible" "1" "enabled" "1" "tabPosition" "0" "paintbackground" "1" "labelText" "#Steam_InstallDownloadTime" "textAlignment" "west" "wrap" "0" } "DownloadTimeInfo" { "ControlName" "Label" "fieldName" "DownloadTimeInfo" "xpos" "200" "ypos" "176" "wide" "200" "tall" "24" "AutoResize" "0" "PinCorner" "0" "visible" "1" "enabled" "1" "tabPosition" "0" "paintbackground" "1" "labelText" "#Steam_InstallDownloadTime_Info" "textAlignment" "west" "wrap" "0" } "InstallFolderLabel" { "ControlName" "Label" "fieldName" "InstallFolderLabel" "xpos" "10" "ypos" "200" "wide" "200" "tall" "24" "AutoResize" "0" "PinCorner" "0" "visible" "1" "enabled" "1" "tabPosition" "0" "paintbackground" "1" "labelText" "#SteamUI_ChooseInstallFolder" "textAlignment" "west" "wrap" "0" } "InstallFolderCombo" { "ControlName" "ComboBox" "fieldName" "InstallFolderCombo" "xpos" "10" "ypos" "232" "wide" "432" "tall" "24" "AutoResize" "0" "PinCorner" "0" "visible" "1" "enabled" "1" "tabPosition" "0" "paintbackground" "1" "textAlignment" "west" "wrap" "0" } styles { Label { minimum-width=200 } } layout { place { control=Label1 x=16 y=16 margin-right=16 width=max } place { start=Label1 y=16 control=CreateShortcutCheck,CreateStartMenuShortcutCheck width=max height=24 dir=down margin-right=200 } place { start=CreateStartMenuShortcutCheck y=16 control=InstallSize height=24 dir=down end-right=InstallSizeLabel } place { start=InstallSize control=InstallSizeLabel height=24 margin-right=16 } place { start=InstallSize control=DriveSpace height=24 dir=down end-right=DriveSpaceLabel } place { start=DriveSpace control=DriveSpaceLabel height=24 margin-right=16 } place { start=DriveSpace control=DownloadTimeLabel height=24 dir=down end-right=DownloadTimeInfo } place { start=DownloadTimeLabel control=DownloadTimeInfo height=24 margin-right=16 } } }
{ "pile_set_name": "Github" }
#if !defined(CYGWIN) /** * @file ir_linux.cpp * */ /* Copyright (C) 2017 by Arjan van Vught mailto:[email protected] * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/un.h> #include <unistd.h> #include <fcntl.h> #include "ir_linux.h" #include "input.h" IrLinux::IrLinux(void) : m_nFd(-1) { } IrLinux::~IrLinux(void) { if (m_nFd != -1) { close(m_nFd); } m_nFd = -1; } bool IrLinux::Start(void) { memset(&m_Addr, '\0', sizeof(m_Addr)); strcpy(m_Addr.sun_path, "/var/run/lirc/lircd"); m_nFd = socket(AF_UNIX, SOCK_STREAM, 0); if (m_nFd == -1) { perror("socket"); return false; } int flags = fcntl(m_nFd, F_GETFL, 0); if (flags < 0) { perror("fcntl"); return false; } flags |= O_NONBLOCK; if (fcntl(m_nFd, F_SETFL, flags) != 0) { perror("fcntl"); return false; } m_Addr.sun_family=AF_UNIX; if (connect(m_nFd, reinterpret_cast<struct sockaddr*>(&m_Addr), sizeof(m_Addr)) == -1) { perror("connect"); return false; } return true; } bool IrLinux::IsAvailable(void) { const bool b = read(m_nFd, m_Buffer, sizeof(m_Buffer)) > 0 ? true : false; if (b) { int sequence; char prefix[32]; if (sscanf(m_Buffer, "%s %x %s", prefix, reinterpret_cast<unsigned int*>(&sequence), m_Code) != 3) { return false; } // demping if (sequence % 2 != 0) { return false; } } return b; } int IrLinux::GetChar(void) { int ch; char *p = strchr(m_Code, '_'); if (p == NULL) { return INPUT_KEY_NOT_DEFINED; } if (strcmp(p, "_OK") == 0) { ch = INPUT_KEY_ENTER; } else if (strcmp(p, "_NUMERIC_POUND") == 0) { ch = INPUT_KEY_ESC; } else if (strcmp(p, "_DOWN") == 0) { ch = INPUT_KEY_DOWN; } else if (strcmp(p, "_UP") == 0) { ch = INPUT_KEY_UP; } else if (strcmp(p, "_LEFT") == 0) { ch = INPUT_KEY_LEFT; } else if (strcmp(p, "_RIGHT") == 0) { ch = INPUT_KEY_RIGHT; } else { ch = INPUT_KEY_NOT_DEFINED; } return ch; } #endif
{ "pile_set_name": "Github" }
""" print_autoconf_hint(state::WizardState) Print a hint for projects that use autoconf to have a good `./configure` line. """ function print_autoconf_hint(state::WizardState) println(state.outs, " The recommended options for GNU Autoconf are:") println(state.outs) printstyled(state.outs, " ./configure --prefix=\${prefix} --build=\${MACHTYPE} --host=\${target}", bold=true) println(state.outs) println(state.outs) println(state.outs, " followed by `make` and `make install`. Since the prefix environment") println(state.outs, " variable is set already, this will automatically perform the installation") println(state.outs, " into the correct directory.") end """ provide_hints(state::WizardState, path::AbstractString) Given an unpacked source directory, provide hints on how a user might go about building the binary bounty they so richly desire. """ function provide_hints(state::WizardState, path::AbstractString) files = readdir(path) println(state.outs, "You have the following contents in your working directory:") println(state.outs, join(map(x->string(" - ", x),files),'\n')) printed = false function start_hints() printed || printstyled(state.outs, "Hints:\n", color=:yellow) printed = true end # Avoid providing duplicate hints (even for files in separate directories) # As long as the hint is the same, people will get the idea hints_provided = Set{Symbol}() function already_hinted(sym) start_hints() (sym in hints_provided) && return true push!(hints_provided, sym) return false end for (root, dirs, files) in walkdir(path) for file in files file_path = joinpath(root, file) # Helper function to try to read the given path's contents, but # returning an empty string on error (for e.g. broken symlinks) read_contents(path) = try String(read(path)) catch "" end if file == "configure" && occursin("Generated by GNU Autoconf", read_contents(file_path)) already_hinted(:autoconf) && continue println(state.outs, " - ", replace(file_path, "$path/" => ""), "\n") println(state.outs, " This file is a configure file generated by GNU Autoconf. ") print_autoconf_hint(state) elseif file == "configure.in" || file == "configure.ac" already_hinted(:autoconf) && continue println(state.outs, " - ", replace(file_path, "$path/" => ""), "\n") println(state.outs, " This file is likely input to GNU Autoconf. ") print_autoconf_hint(state) elseif file == "CMakeLists.txt" already_hinted(:CMake) && continue println(state.outs, " - ", replace(file_path, "$path/" => ""), "\n") print(state.outs, " This file is likely input to CMake. ") println(state.outs, "The recommended options for CMake are") println(state.outs) printstyled(state.outs, " cmake -DCMAKE_INSTALL_PREFIX=\$prefix -DCMAKE_TOOLCHAIN_FILE=\${CMAKE_TARGET_TOOLCHAIN} -DCMAKE_BUILD_TYPE=Release", bold=true) println(state.outs) println(state.outs) println(state.outs, " followed by `make` and `make install`. Since the prefix environment") println(state.outs, " variable is set already, this will automatically perform the installation") println(state.outs, " into the correct directory.\n") elseif file == "meson.build" already_hinted(:Meson) && continue println(state.outs, " - ", replace(file_path, "$path/" => ""), "\n") print(state.outs, " This file is likely input to Meson. ") println(state.outs, "The recommended option for Meson is") println(state.outs) printstyled(state.outs, " meson --cross-file=\${MESON_TARGET_TOOLCHAIN}", bold=true) println(state.outs) println(state.outs) println(state.outs, " followed by `ninja` and `ninja install`. Since the prefix variable") println(state.outs, " is set already, this will automatically perform the installation") println(state.outs, " into the correct directory.\n") end end end println(state.outs) end
{ "pile_set_name": "Github" }
import { TransactionStateT, TransationKindT } from 'entities/Transaction'; const { Transfer } = TransationKindT; export interface AccountMutationT { accountId: string; currency: string; amount: number; } /** * Get all necessary accounts balance mutations for given transaction change. */ export default function getAccountsMutations( prev?: TransactionStateT, next?: TransactionStateT ): AccountMutationT[] { if (!prev && next) { return createTransaction(next); } else if (prev && !next) { return removeTransaction(prev); } else if (prev && next) { return [...removeTransaction(prev), ...createTransaction(next)]; } else { return []; } } function createTransaction(transaction: TransactionStateT): AccountMutationT[] { const mutations: AccountMutationT[] = []; if ( transaction.kind === Transfer && transaction.accountId === transaction.linkedAccountId && transaction.currency === transaction.linkedCurrency ) { return mutations; } mutations.push({ accountId: transaction.accountId, currency: transaction.currency, amount: transaction.amount * (transaction.kind === Transfer ? -1 : 1) }); if ( transaction.kind === Transfer && transaction.linkedAccountId && transaction.linkedCurrency && transaction.linkedAmount ) { mutations.push({ accountId: transaction.linkedAccountId, currency: transaction.linkedCurrency, amount: transaction.linkedAmount }); } return mutations; } function removeTransaction(transaction: TransactionStateT): AccountMutationT[] { const mutations = []; mutations.push({ accountId: transaction.accountId, currency: transaction.currency, amount: transaction.amount * (transaction.kind === Transfer ? 1 : -1) }); if ( transaction.kind === Transfer && transaction.linkedAccountId && transaction.linkedCurrency && transaction.linkedAmount ) { mutations.push({ accountId: transaction.linkedAccountId, currency: transaction.linkedCurrency, amount: transaction.linkedAmount * -1 }); } return mutations; }
{ "pile_set_name": "Github" }
<?php /* * Copyright 2014 Google Inc. * * 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. */ class Google_Service_Compute_UsableSubnetworksAggregatedListWarningData extends Google_Model { public $key; public $value; public function setKey($key) { $this->key = $key; } public function getKey() { return $this->key; } public function setValue($value) { $this->value = $value; } public function getValue() { return $this->value; } }
{ "pile_set_name": "Github" }
var baseKeys = require('./_baseKeys'), getTag = require('./_getTag'), isArrayLike = require('./isArrayLike'), isString = require('./isString'), stringSize = require('./_stringSize'); /** `Object#toString` result references. */ var mapTag = '[object Map]', setTag = '[object Set]'; /** * Gets the size of `collection` by returning its length for array-like * values or the number of own enumerable string keyed properties for objects. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @returns {number} Returns the collection size. * @example * * _.size([1, 2, 3]); * // => 3 * * _.size({ 'a': 1, 'b': 2 }); * // => 2 * * _.size('pebbles'); * // => 7 */ function size(collection) { if (collection == null) { return 0; } if (isArrayLike(collection)) { return isString(collection) ? stringSize(collection) : collection.length; } var tag = getTag(collection); if (tag == mapTag || tag == setTag) { return collection.size; } return baseKeys(collection).length; } module.exports = size;
{ "pile_set_name": "Github" }
<?php namespace Symfony\Component\HttpKernel\Tests\Exception; use Symfony\Component\HttpKernel\Exception\PreconditionFailedHttpException; class PreconditionFailedHttpExceptionTest extends HttpExceptionTest { protected function createException() { return new PreconditionFailedHttpException(); } }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2003-2006 Gabest * http://www.gabest.org * * 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, 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 GNU Make; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * http://www.gnu.org/copyleft/gpl.html * */ #pragma once #include <atlbase.h> #include <atlcoll.h> #include "OggFile.h" #include "..\BaseSplitter\BaseSplitter.h" class OggPacket : public Packet { public: OggPacket() {fSkip = false;} bool fSkip; }; class COggSplitterOutputPin : public CBaseSplitterOutputPin { class CComment { public: CStringW m_key, m_value; CComment(CStringW key, CStringW value) : m_key(key), m_value(value) {m_key.MakeUpper();} }; CAutoPtrList<CComment> m_pComments; protected: CCritSec m_csPackets; CAutoPtrList<OggPacket> m_packets; CAutoPtr<OggPacket> m_lastpacket; int m_lastseqnum; REFERENCE_TIME m_rtLast; bool m_fSkip; void ResetState(DWORD seqnum = -1); public: COggSplitterOutputPin(LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr); void AddComment(BYTE* p, int len); CStringW GetComment(CStringW key); HRESULT UnpackPage(OggPage& page); virtual HRESULT UnpackPacket(CAutoPtr<OggPacket>& p, BYTE* pData, int len) = 0; virtual REFERENCE_TIME GetRefTime(__int64 granule_position) = 0; CAutoPtr<OggPacket> GetPacket(); HRESULT DeliverEndFlush(); HRESULT DeliverNewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate); }; class COggVorbisOutputPin : public COggSplitterOutputPin { CAutoPtrList<OggPacket> m_initpackets; DWORD m_audio_sample_rate; DWORD m_blocksize[2], m_lastblocksize; CAtlArray<bool> m_blockflags; virtual HRESULT UnpackPacket(CAutoPtr<OggPacket>& p, BYTE* pData, int len); virtual REFERENCE_TIME GetRefTime(__int64 granule_position); HRESULT DeliverPacket(CAutoPtr<OggPacket> p); HRESULT DeliverNewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate); public: COggVorbisOutputPin(OggVorbisIdHeader* h, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr); HRESULT UnpackInitPage(OggPage& page); bool IsInitialized() {return m_initpackets.GetCount() >= 3;} }; class COggDirectShowOutputPin : public COggSplitterOutputPin { virtual HRESULT UnpackPacket(CAutoPtr<OggPacket>& p, BYTE* pData, int len); virtual REFERENCE_TIME GetRefTime(__int64 granule_position); public: COggDirectShowOutputPin(AM_MEDIA_TYPE* pmt, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr); }; class COggStreamOutputPin : public COggSplitterOutputPin { __int64 m_time_unit, m_samples_per_unit; DWORD m_default_len; virtual HRESULT UnpackPacket(CAutoPtr<OggPacket>& p, BYTE* pData, int len); virtual REFERENCE_TIME GetRefTime(__int64 granule_position); public: COggStreamOutputPin(OggStreamHeader* h, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr); }; class COggVideoOutputPin : public COggStreamOutputPin { public: COggVideoOutputPin(OggStreamHeader* h, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr); }; class COggAudioOutputPin : public COggStreamOutputPin { public: COggAudioOutputPin(OggStreamHeader* h, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr); }; class COggTextOutputPin : public COggStreamOutputPin { public: COggTextOutputPin(OggStreamHeader* h, LPCWSTR pName, CBaseFilter* pFilter, CCritSec* pLock, HRESULT* phr); }; class __declspec(uuid("9FF48807-E133-40AA-826F-9B2959E5232D")) COggSplitterFilter : public CBaseSplitterFilter { protected: CAutoPtr<COggFile> m_pFile; HRESULT CreateOutputs(IAsyncReader* pAsyncReader); bool DemuxInit(); void DemuxSeek(REFERENCE_TIME rt); bool DemuxLoop(); public: COggSplitterFilter(LPUNKNOWN pUnk, HRESULT* phr); virtual ~COggSplitterFilter(); }; class __declspec(uuid("6D3688CE-3E9D-42F4-92CA-8A11119D25CD")) COggSourceFilter : public COggSplitterFilter { public: COggSourceFilter(LPUNKNOWN pUnk, HRESULT* phr); };
{ "pile_set_name": "Github" }
""" Multi-part parsing for file uploads. Exposes one class, ``MultiPartParser``, which feeds chunks of uploaded data to file upload handlers for processing. """ from __future__ import unicode_literals import base64 import cgi from django.conf import settings from django.core.exceptions import SuspiciousOperation from django.utils.datastructures import MultiValueDict from django.utils.encoding import force_text from django.utils import six from django.utils.text import unescape_entities from django.core.files.uploadhandler import StopUpload, SkipFile, StopFutureHandlers __all__ = ('MultiPartParser', 'MultiPartParserError', 'InputStreamExhausted') class MultiPartParserError(Exception): pass class InputStreamExhausted(Exception): """ No more reads are allowed from this device. """ pass RAW = "raw" FILE = "file" FIELD = "field" class MultiPartParser(object): """ A rfc2388 multipart/form-data parser. ``MultiValueDict.parse()`` reads the input stream in ``chunk_size`` chunks and returns a tuple of ``(MultiValueDict(POST), MultiValueDict(FILES))``. """ def __init__(self, META, input_data, upload_handlers, encoding=None): """ Initialize the MultiPartParser object. :META: The standard ``META`` dictionary in Django request objects. :input_data: The raw post data, as a file-like object. :upload_handler: An UploadHandler instance that performs operations on the uploaded data. :encoding: The encoding with which to treat the incoming data. """ # # Content-Type should containt multipart and the boundary information. # content_type = META.get('HTTP_CONTENT_TYPE', META.get('CONTENT_TYPE', '')) if not content_type.startswith('multipart/'): raise MultiPartParserError('Invalid Content-Type: %s' % content_type) # Parse the header to get the boundary to split the parts. ctypes, opts = parse_header(content_type.encode('ascii')) boundary = opts.get('boundary') if not boundary or not cgi.valid_boundary(boundary): raise MultiPartParserError('Invalid boundary in multipart: %s' % boundary) # Content-Length should contain the length of the body we are about # to receive. try: content_length = int(META.get('HTTP_CONTENT_LENGTH', META.get('CONTENT_LENGTH', 0))) except (ValueError, TypeError): content_length = 0 if content_length < 0: # This means we shouldn't continue...raise an error. raise MultiPartParserError("Invalid content length: %r" % content_length) if isinstance(boundary, six.text_type): boundary = boundary.encode('ascii') self._boundary = boundary self._input_data = input_data # For compatibility with low-level network APIs (with 32-bit integers), # the chunk size should be < 2^31, but still divisible by 4. possible_sizes = [x.chunk_size for x in upload_handlers if x.chunk_size] self._chunk_size = min([2**31-4] + possible_sizes) self._meta = META self._encoding = encoding or settings.DEFAULT_CHARSET self._content_length = content_length self._upload_handlers = upload_handlers def parse(self): """ Parse the POST data and break it into a FILES MultiValueDict and a POST MultiValueDict. Returns a tuple containing the POST and FILES dictionary, respectively. """ # We have to import QueryDict down here to avoid a circular import. from django.http import QueryDict encoding = self._encoding handlers = self._upload_handlers # HTTP spec says that Content-Length >= 0 is valid # handling content-length == 0 before continuing if self._content_length == 0: return QueryDict('', encoding=self._encoding), MultiValueDict() # See if the handler will want to take care of the parsing. # This allows overriding everything if somebody wants it. for handler in handlers: result = handler.handle_raw_input(self._input_data, self._meta, self._content_length, self._boundary, encoding) if result is not None: return result[0], result[1] # Create the data structures to be used later. self._post = QueryDict('', mutable=True) self._files = MultiValueDict() # Instantiate the parser and stream: stream = LazyStream(ChunkIter(self._input_data, self._chunk_size)) # Whether or not to signal a file-completion at the beginning of the loop. old_field_name = None counters = [0] * len(handlers) try: for item_type, meta_data, field_stream in Parser(stream, self._boundary): if old_field_name: # We run this at the beginning of the next loop # since we cannot be sure a file is complete until # we hit the next boundary/part of the multipart content. self.handle_file_complete(old_field_name, counters) old_field_name = None try: disposition = meta_data['content-disposition'][1] field_name = disposition['name'].strip() except (KeyError, IndexError, AttributeError): continue transfer_encoding = meta_data.get('content-transfer-encoding') if transfer_encoding is not None: transfer_encoding = transfer_encoding[0].strip() field_name = force_text(field_name, encoding, errors='replace') if item_type == FIELD: # This is a post field, we can just set it in the post if transfer_encoding == 'base64': raw_data = field_stream.read() try: data = str(raw_data).decode('base64') except: data = raw_data else: data = field_stream.read() self._post.appendlist(field_name, force_text(data, encoding, errors='replace')) elif item_type == FILE: # This is a file, use the handler... file_name = disposition.get('filename') if not file_name: continue file_name = force_text(file_name, encoding, errors='replace') file_name = self.IE_sanitize(unescape_entities(file_name)) content_type = meta_data.get('content-type', ('',))[0].strip() try: charset = meta_data.get('content-type', (0, {}))[1].get('charset', None) except: charset = None try: content_length = int(meta_data.get('content-length')[0]) except (IndexError, TypeError, ValueError): content_length = None counters = [0] * len(handlers) try: for handler in handlers: try: handler.new_file(field_name, file_name, content_type, content_length, charset) except StopFutureHandlers: break for chunk in field_stream: if transfer_encoding == 'base64': # We only special-case base64 transfer encoding # We should always read base64 streams by multiple of 4 over_bytes = len(chunk) % 4 if over_bytes: over_chunk = field_stream.read(4 - over_bytes) chunk += over_chunk try: chunk = base64.b64decode(chunk) except Exception as e: # Since this is only a chunk, any error is an unfixable error. raise MultiPartParserError("Could not decode base64 data: %r" % e) for i, handler in enumerate(handlers): chunk_length = len(chunk) chunk = handler.receive_data_chunk(chunk, counters[i]) counters[i] += chunk_length if chunk is None: # If the chunk received by the handler is None, then don't continue. break except SkipFile: # Just use up the rest of this file... exhaust(field_stream) else: # Handle file upload completions on next iteration. old_field_name = field_name else: # If this is neither a FIELD or a FILE, just exhaust the stream. exhaust(stream) except StopUpload as e: if not e.connection_reset: exhaust(self._input_data) else: # Make sure that the request data is all fed exhaust(self._input_data) # Signal that the upload has completed. for handler in handlers: retval = handler.upload_complete() if retval: break return self._post, self._files def handle_file_complete(self, old_field_name, counters): """ Handle all the signalling that takes place when a file is complete. """ for i, handler in enumerate(self._upload_handlers): file_obj = handler.file_complete(counters[i]) if file_obj: # If it returns a file object, then set the files dict. self._files.appendlist(force_text(old_field_name, self._encoding, errors='replace'), file_obj) break def IE_sanitize(self, filename): """Cleanup filename from Internet Explorer full paths.""" return filename and filename[filename.rfind("\\")+1:].strip() class LazyStream(six.Iterator): """ The LazyStream wrapper allows one to get and "unget" bytes from a stream. Given a producer object (an iterator that yields bytestrings), the LazyStream object will support iteration, reading, and keeping a "look-back" variable in case you need to "unget" some bytes. """ def __init__(self, producer, length=None): """ Every LazyStream must have a producer when instantiated. A producer is an iterable that returns a string each time it is called. """ self._producer = producer self._empty = False self._leftover = b'' self.length = length self.position = 0 self._remaining = length self._unget_history = [] def tell(self): return self.position def read(self, size=None): def parts(): remaining = (size is not None and [size] or [self._remaining])[0] # do the whole thing in one shot if no limit was provided. if remaining is None: yield b''.join(self) return # otherwise do some bookkeeping to return exactly enough # of the stream and stashing any extra content we get from # the producer while remaining != 0: assert remaining > 0, 'remaining bytes to read should never go negative' chunk = next(self) emitting = chunk[:remaining] self.unget(chunk[remaining:]) remaining -= len(emitting) yield emitting out = b''.join(parts()) return out def __next__(self): """ Used when the exact number of bytes to read is unimportant. This procedure just returns whatever is chunk is conveniently returned from the iterator instead. Useful to avoid unnecessary bookkeeping if performance is an issue. """ if self._leftover: output = self._leftover self._leftover = b'' else: output = next(self._producer) self._unget_history = [] self.position += len(output) return output def close(self): """ Used to invalidate/disable this lazy stream. Replaces the producer with an empty list. Any leftover bytes that have already been read will still be reported upon read() and/or next(). """ self._producer = [] def __iter__(self): return self def unget(self, bytes): """ Places bytes back onto the front of the lazy stream. Future calls to read() will return those bytes first. The stream position and thus tell() will be rewound. """ if not bytes: return self._update_unget_history(len(bytes)) self.position -= len(bytes) self._leftover = b''.join([bytes, self._leftover]) def _update_unget_history(self, num_bytes): """ Updates the unget history as a sanity check to see if we've pushed back the same number of bytes in one chunk. If we keep ungetting the same number of bytes many times (here, 50), we're mostly likely in an infinite loop of some sort. This is usually caused by a maliciously-malformed MIME request. """ self._unget_history = [num_bytes] + self._unget_history[:49] number_equal = len([current_number for current_number in self._unget_history if current_number == num_bytes]) if number_equal > 40: raise SuspiciousOperation( "The multipart parser got stuck, which shouldn't happen with" " normal uploaded files. Check for malicious upload activity;" " if there is none, report this to the Django developers." ) class ChunkIter(six.Iterator): """ An iterable that will yield chunks of data. Given a file-like object as the constructor, this object will yield chunks of read operations from that object. """ def __init__(self, flo, chunk_size=64 * 1024): self.flo = flo self.chunk_size = chunk_size def __next__(self): try: data = self.flo.read(self.chunk_size) except InputStreamExhausted: raise StopIteration() if data: return data else: raise StopIteration() def __iter__(self): return self class InterBoundaryIter(six.Iterator): """ A Producer that will iterate over boundaries. """ def __init__(self, stream, boundary): self._stream = stream self._boundary = boundary def __iter__(self): return self def __next__(self): try: return LazyStream(BoundaryIter(self._stream, self._boundary)) except InputStreamExhausted: raise StopIteration() class BoundaryIter(six.Iterator): """ A Producer that is sensitive to boundaries. Will happily yield bytes until a boundary is found. Will yield the bytes before the boundary, throw away the boundary bytes themselves, and push the post-boundary bytes back on the stream. The future calls to next() after locating the boundary will raise a StopIteration exception. """ def __init__(self, stream, boundary): self._stream = stream self._boundary = boundary self._done = False # rollback an additional six bytes because the format is like # this: CRLF<boundary>[--CRLF] self._rollback = len(boundary) + 6 # Try to use mx fast string search if available. Otherwise # use Python find. Wrap the latter for consistency. unused_char = self._stream.read(1) if not unused_char: raise InputStreamExhausted() self._stream.unget(unused_char) try: from mx.TextTools import FS self._fs = FS(boundary).find except ImportError: self._fs = lambda data: data.find(boundary) def __iter__(self): return self def __next__(self): if self._done: raise StopIteration() stream = self._stream rollback = self._rollback bytes_read = 0 chunks = [] for bytes in stream: bytes_read += len(bytes) chunks.append(bytes) if bytes_read > rollback: break if not bytes: break else: self._done = True if not chunks: raise StopIteration() chunk = b''.join(chunks) boundary = self._find_boundary(chunk, len(chunk) < self._rollback) if boundary: end, next = boundary stream.unget(chunk[next:]) self._done = True return chunk[:end] else: # make sure we dont treat a partial boundary (and # its separators) as data if not chunk[:-rollback]:# and len(chunk) >= (len(self._boundary) + 6): # There's nothing left, we should just return and mark as done. self._done = True return chunk else: stream.unget(chunk[-rollback:]) return chunk[:-rollback] def _find_boundary(self, data, eof = False): """ Finds a multipart boundary in data. Should no boundry exist in the data None is returned instead. Otherwise a tuple containing the indices of the following are returned: * the end of current encapsulation * the start of the next encapsulation """ index = self._fs(data) if index < 0: return None else: end = index next = index + len(self._boundary) # backup over CRLF last = max(0, end-1) if data[last:last+1] == b'\n': end -= 1 last = max(0, end-1) if data[last:last+1] == b'\r': end -= 1 return end, next def exhaust(stream_or_iterable): """ Completely exhausts an iterator or stream. Raise a MultiPartParserError if the argument is not a stream or an iterable. """ iterator = None try: iterator = iter(stream_or_iterable) except TypeError: iterator = ChunkIter(stream_or_iterable, 16384) if iterator is None: raise MultiPartParserError('multipartparser.exhaust() was passed a non-iterable or stream parameter') for __ in iterator: pass def parse_boundary_stream(stream, max_header_size): """ Parses one and exactly one stream that encapsulates a boundary. """ # Stream at beginning of header, look for end of header # and parse it if found. The header must fit within one # chunk. chunk = stream.read(max_header_size) # 'find' returns the top of these four bytes, so we'll # need to munch them later to prevent them from polluting # the payload. header_end = chunk.find(b'\r\n\r\n') def _parse_header(line): main_value_pair, params = parse_header(line) try: name, value = main_value_pair.split(':', 1) except: raise ValueError("Invalid header: %r" % line) return name, (value, params) if header_end == -1: # we find no header, so we just mark this fact and pass on # the stream verbatim stream.unget(chunk) return (RAW, {}, stream) header = chunk[:header_end] # here we place any excess chunk back onto the stream, as # well as throwing away the CRLFCRLF bytes from above. stream.unget(chunk[header_end + 4:]) TYPE = RAW outdict = {} # Eliminate blank lines for line in header.split(b'\r\n'): # This terminology ("main value" and "dictionary of # parameters") is from the Python docs. try: name, (value, params) = _parse_header(line) except: continue if name == 'content-disposition': TYPE = FIELD if params.get('filename'): TYPE = FILE outdict[name] = value, params if TYPE == RAW: stream.unget(chunk) return (TYPE, outdict, stream) class Parser(object): def __init__(self, stream, boundary): self._stream = stream self._separator = b'--' + boundary def __iter__(self): boundarystream = InterBoundaryIter(self._stream, self._separator) for sub_stream in boundarystream: # Iterate over each part yield parse_boundary_stream(sub_stream, 1024) def parse_header(line): """ Parse the header into a key-value. Input (line): bytes, output: unicode for key/name, bytes for value which will be decoded later """ plist = _parse_header_params(b';' + line) key = plist.pop(0).lower().decode('ascii') pdict = {} for p in plist: i = p.find(b'=') if i >= 0: name = p[:i].strip().lower().decode('ascii') value = p[i+1:].strip() if len(value) >= 2 and value[:1] == value[-1:] == b'"': value = value[1:-1] value = value.replace(b'\\\\', b'\\').replace(b'\\"', b'"') pdict[name] = value return key, pdict def _parse_header_params(s): plist = [] while s[:1] == b';': s = s[1:] end = s.find(b';') while end > 0 and s.count(b'"', 0, end) % 2: end = s.find(b';', end + 1) if end < 0: end = len(s) f = s[:end] plist.append(f.strip()) s = s[end:] return plist
{ "pile_set_name": "Github" }
require(["gitbook", "jQuery"], function(gitbook, $) { gitbook.events.bind('start', function (e, config) { var conf = config['edit-link']; var label = conf.label; var base = conf.base; var lang = gitbook.state.innerLanguage; if (lang) { // label can be a unique string for multi-languages site if (typeof label === 'object') label = label[lang]; lang = lang + '/'; } // Add slash at the end if not present if (base.slice(-1) != "/") { base = base + "/"; } gitbook.toolbar.createButton({ icon: 'fa fa-edit', text: label, onClick: function() { var filepath = gitbook.state.filepath; window.open(base + lang + filepath); } }); }); });
{ "pile_set_name": "Github" }
#!/bin/bash # 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, 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., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. # Author/Copyright(c): 2009, Thomas Renninger <[email protected]>, Novell Inc. # Ondemand up_threshold and sampling rate test script for cpufreq-bench # mircobenchmark. # Modify the general variables at the top or extend or copy out parts # if you want to test other things # # Default with latest kernels is 95, before micro account patches # it was 80, cmp. with git commit 808009131046b62ac434dbc796 UP_THRESHOLD="60 80 95" # Depending on the kernel and the HW sampling rate could be restricted # and cannot be set that low... # E.g. before git commit cef9615a853ebc4972084f7 one could only set # min sampling rate of 80000 if CONFIG_HZ=250 SAMPLING_RATE="20000 80000" function measure() { local -i up_threshold_set local -i sampling_rate_set for up_threshold in $UP_THRESHOLD;do for sampling_rate in $SAMPLING_RATE;do # Set values in sysfs echo $up_threshold >/sys/devices/system/cpu/cpu0/cpufreq/ondemand/up_threshold echo $sampling_rate >/sys/devices/system/cpu/cpu0/cpufreq/ondemand/sampling_rate up_threshold_set=$(cat /sys/devices/system/cpu/cpu0/cpufreq/ondemand/up_threshold) sampling_rate_set=$(cat /sys/devices/system/cpu/cpu0/cpufreq/ondemand/sampling_rate) # Verify set values in sysfs if [ ${up_threshold_set} -eq ${up_threshold} ];then echo "up_threshold: $up_threshold, set in sysfs: ${up_threshold_set}" else echo "WARNING: Tried to set up_threshold: $up_threshold, set in sysfs: ${up_threshold_set}" fi if [ ${sampling_rate_set} -eq ${sampling_rate} ];then echo "sampling_rate: $sampling_rate, set in sysfs: ${sampling_rate_set}" else echo "WARNING: Tried to set sampling_rate: $sampling_rate, set in sysfs: ${sampling_rate_set}" fi # Benchmark cpufreq-bench -o /var/log/cpufreq-bench/up_threshold_${up_threshold}_sampling_rate_${sampling_rate} done done } function create_plots() { local command for up_threshold in $UP_THRESHOLD;do command="cpufreq-bench_plot.sh -o \"sampling_rate_${SAMPLING_RATE}_up_threshold_${up_threshold}\" -t \"Ondemand sampling_rate: ${SAMPLING_RATE} comparison - Up_threshold: $up_threshold %\"" for sampling_rate in $SAMPLING_RATE;do command="${command} /var/log/cpufreq-bench/up_threshold_${up_threshold}_sampling_rate_${sampling_rate}/* \"sampling_rate = $sampling_rate\"" done echo $command eval "$command" echo done for sampling_rate in $SAMPLING_RATE;do command="cpufreq-bench_plot.sh -o \"up_threshold_${UP_THRESHOLD}_sampling_rate_${sampling_rate}\" -t \"Ondemand up_threshold: ${UP_THRESHOLD} % comparison - sampling_rate: $sampling_rate\"" for up_threshold in $UP_THRESHOLD;do command="${command} /var/log/cpufreq-bench/up_threshold_${up_threshold}_sampling_rate_${sampling_rate}/* \"up_threshold = $up_threshold\"" done echo $command eval "$command" echo done command="cpufreq-bench_plot.sh -o \"up_threshold_${UP_THRESHOLD}_sampling_rate_${SAMPLING_RATE}\" -t \"Ondemand up_threshold: ${UP_THRESHOLD} and sampling_rate ${SAMPLING_RATE} comparison\"" for sampling_rate in $SAMPLING_RATE;do for up_threshold in $UP_THRESHOLD;do command="${command} /var/log/cpufreq-bench/up_threshold_${up_threshold}_sampling_rate_${sampling_rate}/* \"up_threshold = $up_threshold - sampling_rate = $sampling_rate\"" done done echo "$command" eval "$command" } measure create_plots
{ "pile_set_name": "Github" }
#include "gpio.h" #include "mem_map.h" #include "portmux.h" #include "ports.h" #define CONFIG_BF52x 1 /* Linux glue */
{ "pile_set_name": "Github" }
/* * The MIT License (MIT) * * Copyright (c) 2017-2020 Yegor Bugayenko * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.cactoos.scalar; import java.util.stream.Collectors; import org.cactoos.Scalar; import org.cactoos.iterable.IterableOf; import org.cactoos.list.ListOf; /** * Make a scalar which is sum of scalar's values. * * <p>This class implements {@link Scalar}, which throws a checked * {@link Exception}. Despite that this class does NOT throw a checked * exception.</p> * * <p>There is no thread-safety guarantee. * <p>Note this class is for internal usage only * * @since 0.30 */ final class SumOfScalar implements Scalar<SumOf> { /** * Varargs of Scalar to sum up values from. */ private final Scalar<? extends Number>[] scalars; /** * Ctor. * @param src Varargs of Scalar to sum up values from * @since 0.30 */ @SafeVarargs SumOfScalar(final Scalar<? extends Number>... src) { this.scalars = src; } @Override public SumOf value() { return new SumOf( new IterableOf<>( new ListOf<>(this.scalars) .stream() .map( scalar -> new Unchecked<>(scalar).value() ).collect(Collectors.toList()) ) ); } }
{ "pile_set_name": "Github" }
// <copyright file="AssemblyInfo.cs" company="ConfigR contributors"> // Copyright (c) ConfigR contributors. ([email protected]) // </copyright> using Xunit; [assembly: CollectionBehavior(DisableTestParallelization = true)]
{ "pile_set_name": "Github" }
var sanitize = require('mongo-sanitize'); module.exports = function (app) { var Contato = app.models.contato; var controller = {} controller.listaContatos = function(req, res) { Contato.find().populate('emergencia').exec() .then( function(contatos) { res.json(contatos); }, function(erro) { console.error(erro) res.status(500).json(erro); } ); }; controller.obtemContato = function(req, res) { var _id = req.params.id; Contato.findById(_id).exec() .then( function(contato) { if (!contato) throw new Error("Contato não encontrado"); res.json(contato) }, function(erro) { console.log(erro); res.status(404).json(erro) } ); }; controller.removeContato = function(req, res) { var _id = sanitize(req.params.id); Contato.remove({"_id" : _id}).exec() .then( function() { res.end(); }, function(erro) { return console.error(erro); } ); }; controller.salvaContato = function(req, res) { var _id = req.body._id; var dados = { "nome" : req.body.nome, "email" : req.body.email, "emergencia" : req.body.emergencia || null }; if(_id) { Contato.findByIdAndUpdate(_id, dados).exec() .then( function(contato) { res.json(contato); }, function(erro) { console.error(erro) res.status(500).json(erro); } ); } else { Contato.create(dados) .then( function(contato) { res.status(201).json(contato); }, function(erro) { console.log(erro); res.status(500).json(erro); } ); } }; return controller; };
{ "pile_set_name": "Github" }
/* * serchan.cxx * * Asynchronous serial I/O channel class implementation. * * Portable Windows Library * * Copyright (c) 1993-1998 Equivalence Pty. Ltd. * * The contents of this file are subject to the Mozilla Public License * Version 1.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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See * the License for the specific language governing rights and limitations * under the License. * * The Original Code is Portable Windows Library. * * The Initial Developer of the Original Code is Equivalence Pty. Ltd. * * Portions are Copyright (C) 1993 Free Software Foundation, Inc. * All Rights Reserved. * * Contributor(s): ______________________________________. * * $Log: serchan.cxx,v $ * Revision 1.32 2005/11/30 12:47:42 csoutheren * Removed tabs, reformatted some code, and changed tags for Doxygen * * Revision 1.31 2005/03/10 03:27:30 dereksmithies * Fix an address typo. * * Revision 1.30 2005/01/03 02:52:52 csoutheren * Fixed problem with default speed of serial ports * Fixed problem with using obsolete lock directory for serial ports * * Revision 1.29 2004/07/11 07:56:36 csoutheren * Applied jumbo VxWorks patch, thanks to Eize Slange * * Revision 1.28 2004/02/22 04:06:47 ykiryanov * ifdef'd all functions because BeOS don't support it * * Revision 1.27 2002/11/02 00:32:21 robertj * Further fixes to VxWorks (Tornado) port, thanks Andreas Sikkema. * * Revision 1.26 2002/10/17 13:44:27 robertj * Port to RTEMS, thanks Vladimir Nesic. * * Revision 1.25 2002/10/10 04:43:44 robertj * VxWorks port, thanks Martijn Roest * * Revision 1.24 2002/03/27 06:42:16 robertj * Implemented the DTR etc functions and ttya/ttyb strings for sunos, * thanks [email protected] & Raimo Ruokonen <[email protected]> * * Revision 1.23 2001/09/10 03:03:36 robertj * Major change to fix problem with error codes being corrupted in a * PChannel when have simultaneous reads and writes in threads. * * Revision 1.22 2001/08/11 15:38:43 rogerh * Add Mac OS Carbon changes from John Woods <[email protected]> * * Revision 1.21 2001/01/04 17:57:41 rogerh * Fix a cut and past error in my previous commit * * Revision 1.20 2001/01/04 10:28:07 rogerh * FreeBSD does not set the Baud Rate with c_cflags. Add the 'BSD' way * * Revision 1.19 2001/01/03 10:56:01 rogerh * CBAUD is not defined on FreeBSD. * * Revision 1.18 2000/12/29 07:36:18 craigs * Finally got working correctly! * * Revision 1.17 2000/11/14 14:56:24 rogerh * Fix #define parameters (fd should be just f) * * Revision 1.16 2000/11/14 14:52:32 rogerh * Fix SET/GET typo error * * Revision 1.15 2000/11/12 23:30:41 craigs * Fixed problems with serial port configuration * * Revision 1.14 2000/06/21 01:01:22 robertj * AIX port, thanks Wolfgang Platzer ([email protected]). * * Revision 1.13 2000/04/09 18:19:23 rogerh * Add my changes for NetBSD support. * * Revision 1.12 2000/04/06 12:11:32 rogerh * MacOS X support submitted by Kevin Packard * * Revision 1.11 2000/03/08 12:17:09 rogerh * Add OpenBSD support * * Revision 1.10 1998/12/21 06:08:08 robertj * Fixed warning on solaris x86 GNU system. * * Revision 1.9 1998/11/30 21:51:54 robertj * New directory structure. * * Revision 1.8 1998/11/24 09:39:14 robertj * FreeBSD port. * * Revision 1.7 1998/09/24 04:12:17 robertj * Added open software license. * */ #pragma implementation "serchan.h" #pragma implementation "modem.h" #include <ptlib.h> #include <fcntl.h> #include <signal.h> #include <sys/ioctl.h> #if defined(P_LINUX) #define TCSETATTR(f,t) tcsetattr(f,TCSANOW,t) #define TCGETATTR(f,t) tcgetattr(f,t) #elif defined(P_FREEBSD) || defined(P_OPENBSD) || defined (P_NETBSD) || defined(P_MACOSX) || defined(P_MACOS) || defined(P_RTEMS) #include <sys/ttycom.h> #define TCGETA TIOCGETA #define TCSETAW TIOCSETAW #elif defined(P_SUN4) #include <sys/termio.h> extern "C" int ioctl(int, int, void *); #elif defined (P_AIX) #include <sys/termio.h> #endif #ifndef TCSETATTR #define TCSETATTR(f,t) ::ioctl(f,TCSETAW,t) #endif #ifndef TCGETATTR #define TCGETATTR(f,t) ::ioctl(f,TCGETA,t) #endif //#define BINARY_LOCK 1 //#define LOCK_PREFIX "/var/spool/uucp/LCK.." #define LOCK_PREFIX "/var/lock/LCK.." #define DEV_PREFIX "/dev/" #define PORTLISTENV "PWLIB_SERIALPORTS" #define DEV_PREFIX "/dev/" #include "../common/serial.cxx" //////////////////////////////////////////////////////////////// // // PSerialChannel // void PSerialChannel::Construct() { // set control modes: 9600, N, 8, 1, local line baudRate = 9600; dataBits = 8; parityBits = NoParity; stopBits = 1; #if defined(P_VXWORKS) || defined (__BEOS__) PAssertAlways(PUnimplementedFunction); #else // set input mode: ignore breaks, ignore parity errors, do not strip chars, // no CR/NL conversion, no case conversion, no XON/XOFF control, // no start/stop Termio.c_iflag = IGNBRK | IGNPAR; Termio.c_cflag = CS8 | CSTOPB | CREAD | CLOCAL; #if defined(P_FREEBSD) || defined(P_OPENBSD) || defined (P_NETBSD) || defined(P_MACOSX) || defined(P_MACOS) Termio.c_ispeed = Termio.c_ospeed = B9600; #else Termio.c_cflag |= B9600; #endif // set output mode: no post process output, Termio.c_oflag = 0; // set line discipline Termio.c_lflag = 0; #endif // P_VXWORKS } BOOL PSerialChannel::Close() { #if defined(P_VXWORKS) || defined (__BEOS__) PAssertAlways(PUnimplementedFunction); return FALSE; #else if (os_handle >= 0) { // delete the lockfile PFile::Remove(PString(LOCK_PREFIX) + channelName); // restore the original terminal settings TCSETATTR(os_handle, &oldTermio); } return PChannel::Close(); #endif // P_VXWORKS } BOOL PSerialChannel::Open(const PString & port, DWORD speed, BYTE data, Parity parity, BYTE stop, FlowControl inputFlow, FlowControl outputFlow) { // if the port is already open, close it if (IsOpen()) Close(); // // check prefix of name // if (port.Left(PORT_PREFIX_LEN) != PORT_PREFIX) { // lastError = BadParameter; // return FALSE; // } // // check suffix // int portnum = (port.Right(port.GetLength()-PORT_PREFIX_LEN)).AsInteger(); // if ((portnum < PORT_START) || (portnum >= (PORT_START + PORT_COUNT))) { // lastError = BadParameter; // return FALSE; // } // save the port name channelName = port; #if defined(P_VXWORKS) || defined (__BEOS__) PAssertAlways(PUnimplementedFunction); return FALSE; #else // construct lock filename PString lockfilename = PString(LOCK_PREFIX) + port; // if the file exists, probe the process to see if it is still running if (PFile::Exists(lockfilename)) { PFile lockfile(lockfilename, PFile::ReadOnly); int lock_pid; #ifdef BINARY_LOCK lockfile.Read(&lock_pid, sizeof(lock_pid)); #else char lock_pid_str[20]; lockfile.Read(lock_pid_str, 20); lock_pid = atoi(lock_pid_str); #endif // if kill returns 0, then the port is in use if (kill(lock_pid, 0) == 0) return SetErrorValues(DeviceInUse, EBUSY); // remove the lock file lockfile.Remove(); } // create new lockfile with our PID PFile lockfile(lockfilename, PFile::WriteOnly, PFile::Create); int pid = getpid(); #ifdef BINARY_LOCK lockfile.Write(&pid, sizeof(pid)); #else lockfile << pid; #endif lockfile.Close(); // attempt to open the device PString device_name = PString(DEV_PREFIX) + port; if ((os_handle = ::open((const char *)device_name, O_RDWR|O_NONBLOCK|O_NOCTTY)) < 0) { ConvertOSError(os_handle); Close(); return FALSE; } // save the channel name channelName = port; // save the current port setup TCGETATTR(os_handle, &oldTermio); // set the default paramaters TCSETATTR(os_handle, &Termio); // now set the mode that was passed in if (!SetSpeed(speed) || !SetDataBits(data) || !SetParity(parity) || !SetStopBits(stop) || !SetInputFlowControl(inputFlow) || !SetOutputFlowControl(outputFlow)) { errno = EINVAL; ConvertOSError(-1); return FALSE; } ::fcntl(os_handle, F_SETFD, 1); #endif // P_VXWORKS return TRUE; } BOOL PSerialChannel::SetSpeed(DWORD newBaudRate) { if (newBaudRate == baudRate) return TRUE; if (os_handle < 0) return TRUE; #if defined(P_VXWORKS) || defined (__BEOS__) PAssertAlways(PUnimplementedFunction); return FALSE; #else int baud; switch(newBaudRate) { #ifdef B50 case 50: baud = B50; break; #endif #ifdef B75 case 75: baud = B75; break; #endif #ifdef B110 case 110: baud = B110; break; #endif #ifdef B134 case 134: baud = B134; break; #endif #ifdef B150 case 150: baud = B150; break; #endif #ifdef B200 case 200: baud = B200; break; #endif #ifdef B300 case 300: baud = B300; break; #endif #ifdef B600 case 600: baud = B600; break; #endif #ifdef B1200 case 1200: baud = B1200; break; #endif #ifdef B1800 case 1800: baud = B1800; break; #endif #ifdef B2400 case 2400: baud = B2400; break; #endif #ifdef B4800 case 4800: baud = B4800; break; #endif #ifdef B9600 case 9600: case 0: // default baud = B9600; break; #endif #ifdef B19200 case 19200: baud = B19200; break; #endif #ifdef B38400 case 38400: baud = B38400; break; #endif #ifdef B57600 case 57600: baud = B57600; break; #endif #ifdef B115200 case 115200: baud = B115200; break; #endif #ifdef B230400 case 230400: baud = B230400; break; #endif default: baud = -1; }; if (baud == -1) { errno = EINVAL; ConvertOSError(-1); return FALSE; } // save new baud rate baudRate = newBaudRate; #if defined(P_FREEBSD) || defined(P_OPENBSD) || defined (P_NETBSD) || defined(P_MACOSX) || defined(P_MACOS) // The BSD way Termio.c_ispeed = baud; Termio.c_ospeed = baud; #else // The Linux way Termio.c_cflag &= ~CBAUD; Termio.c_cflag |= baud; #endif if (os_handle < 0) return TRUE; // initialise the port return ConvertOSError(TCSETATTR(os_handle, &Termio)); #endif // P_VXWORKS } BOOL PSerialChannel::SetDataBits(BYTE data) { if (data == dataBits) return TRUE; #if defined(P_VXWORKS) || defined (__BEOS__) PAssertAlways(PUnimplementedFunction); return FALSE; #else int flags; switch (data) { #ifdef CS5 case 5: flags = CS5; break; #endif #ifdef CS6 case 6: flags = CS6; break; #endif #ifdef CS7 case 7: flags = CS7; break; #endif #ifdef CS8 case 8: case 0: // default flags = CS8; break; #endif default: flags = -1; break; } if (flags == 0) { errno = EINVAL; ConvertOSError(-1); return FALSE; } // set the new number of data bits dataBits = data; Termio.c_cflag &= ~CSIZE; Termio.c_cflag |= flags; if (os_handle < 0) return TRUE; return ConvertOSError(TCSETATTR(os_handle, &Termio)); #endif // P_VXWORKS } BOOL PSerialChannel::SetParity(Parity parity) { if (parity == parityBits) return TRUE; #if defined(P_VXWORKS) || defined (__BEOS__) PAssertAlways(PUnimplementedFunction); return FALSE; #else int flags; switch (parity) { case OddParity: flags = PARODD | PARENB; break; case EvenParity: flags = PARENB; case NoParity: case DefaultParity: flags = IGNPAR; break; case MarkParity: case SpaceParity: default: flags = -1; } if (flags < 0) { errno = EINVAL; ConvertOSError(-1); return FALSE; } if (os_handle < 0) return TRUE; // set the new parity parityBits = parity; Termio.c_cflag &= ~(PARENB|PARODD); Termio.c_cflag |= flags; return ConvertOSError(TCSETATTR(os_handle, &Termio)); #endif // P_VXWORKS } BOOL PSerialChannel::SetStopBits(BYTE stop) { if (stop == stopBits) return TRUE; #if defined(P_VXWORKS) || defined (__BEOS__) PAssertAlways(PUnimplementedFunction); return FALSE; #else int flags; switch (stop) { case 2: flags = CSTOPB; break; default: case 1: flags = 0; break; } if (flags < 0) { errno = EINVAL; ConvertOSError(-1); return FALSE; } if (os_handle < 0) return TRUE; // set the new number of stop bits stopBits = stop; Termio.c_cflag &= ~CSTOPB; Termio.c_cflag |= flags; return ConvertOSError(TCSETATTR(os_handle, &Termio)); #endif // P_VXWORKS } DWORD PSerialChannel::GetSpeed() const { return baudRate; } BYTE PSerialChannel::GetStopBits() const { return stopBits; } BYTE PSerialChannel::GetDataBits() const { return dataBits; } PSerialChannel::Parity PSerialChannel::GetParity() const { return parityBits; } BOOL PSerialChannel::SetInputFlowControl(FlowControl) { return TRUE; } PSerialChannel::FlowControl PSerialChannel::GetInputFlowControl() const { return NoFlowControl; } BOOL PSerialChannel::SetOutputFlowControl(FlowControl) { return TRUE; } PSerialChannel::FlowControl PSerialChannel::GetOutputFlowControl() const { return NoFlowControl; } void PSerialChannel::SetDTR(BOOL mode) { #if defined(P_VXWORKS) || defined (__BEOS__) PAssertAlways(PUnimplementedFunction); #else int flags = 0; ioctl(os_handle,TIOCMGET,&flags); // get the bits flags &= ~TIOCM_DTR; if ( mode == TRUE ) flags |= TIOCM_DTR; ioctl(os_handle,TIOCMSET,&flags); // set back /* ALTERNATE IMPLEMENTATION? Uses "Local Mode" bits? if ( mode TRUE ) ioctl(os_handle, TIOCSDTR, 0); else ioctl(os_handle, TIOCCDTR, 0); */ #endif // P_VXWORKS } void PSerialChannel::SetRTS(BOOL mode) { #if defined(P_VXWORKS) || defined (__BEOS__) PAssertAlways(PUnimplementedFunction); #else int flags = 0; ioctl(os_handle,TIOCMGET,&flags); // get the bits flags &= ~TIOCM_RTS; if ( mode == TRUE ) flags |= TIOCM_RTS; ioctl(os_handle,TIOCMSET,&flags); // set back #endif // P_VXWORKS } void PSerialChannel::SetBreak(BOOL mode) { #if defined(P_VXWORKS) || defined (__BEOS__) PAssertAlways(PUnimplementedFunction); #else if (mode) ioctl(os_handle, TIOCSBRK, 0); else ioctl(os_handle, TIOCCBRK, 0); #endif // P_VXWORKS } BOOL PSerialChannel::GetCTS() { #if defined(P_VXWORKS) || defined (__BEOS__) PAssertAlways(PUnimplementedFunction); return FALSE; #else int flags = 0; ioctl(os_handle,TIOCMGET,&flags); // get the bits return (flags&TIOCM_CTS)?TRUE:FALSE; #endif // P_VXWORKS } BOOL PSerialChannel::GetDSR() { #if defined(P_VXWORKS) || defined (__BEOS__) PAssertAlways(PUnimplementedFunction); return FALSE; #else int flags = 0; ioctl(os_handle,TIOCMGET,&flags); // get the bits return (flags&TIOCM_DSR)?TRUE:FALSE; #endif // P_VXWORKS } BOOL PSerialChannel::GetDCD() { #if defined(P_VXWORKS) || defined (__BEOS__) PAssertAlways(PUnimplementedFunction); return FALSE; #else int flags = 0; ioctl(os_handle,TIOCMGET,&flags); // get the bits return (flags&TIOCM_CD)?TRUE:FALSE; #endif // P_VXWORKS } BOOL PSerialChannel::GetRing() { #if defined(P_VXWORKS) || defined (__BEOS__) PAssertAlways(PUnimplementedFunction); return FALSE; #else int flags = 0; ioctl(os_handle,TIOCMGET,&flags); // get the bits return (flags&TIOCM_RNG)?TRUE:FALSE; #endif // P_VXWORKS } PStringList PSerialChannel::GetPortNames() { PStringList ports; char * env = getenv(PORTLISTENV); if (env != NULL) { PString str(env); PStringArray tokens = str.Tokenise(" ,\t", FALSE); PINDEX i; for (i = 0; i < tokens.GetSize(); i++) ports.AppendString(tokens[i]); } else { #if defined(__sun) && defined (__sparc) ports.AppendString(PString("ttya")); ports.AppendString(PString("ttyb")); #else ports.AppendString(PString("ttyS0")); ports.AppendString(PString("ttyS1")); ports.AppendString(PString("ttyS2")); ports.AppendString(PString("ttyS3")); #endif } return ports; } // End of File ///////////////////////////////////////////////////////////////
{ "pile_set_name": "Github" }
import * as React from 'react'; import {StyletronComponent} from 'styletron-react'; import {Override} from '../overrides'; export interface KEY_STRINGS { ArrowUp: 'ArrowUp'; ArrowDown: 'ArrowDown'; ArrowLeft: 'ArrowLeft'; ArrowRight: 'ArrowRight'; Enter: 'Enter'; Space: ' '; Escape: 'Escape'; Backspace: 'Backspace'; } export interface STATE_CHANGE_TYPES { click: 'click'; moveUp: 'moveUp'; moveDown: 'moveDown'; mouseEnter: 'mouseEnter'; focus: 'focus'; reset: 'reset'; character: 'character'; enter: 'enter'; } export interface OPTION_LIST_SIZE { default: 'default'; compact: 'compact'; } export type BaseMenuPropsT = { renderAll?: boolean; }; export interface MenuOverrides { EmptyState?: Override<any>; List?: Override<any>; Option?: Override<any>; ListItem?: Override<any>; OptgroupHeader?: Override<any>; } export interface MenuProps extends BaseMenuPropsT { size?: keyof OPTION_LIST_SIZE; overrides?: MenuOverrides; } export type ItemT = any; export type ArrayItemsT = ItemT[]; export type GroupedItemsT = { __ungrouped: ArrayItemsT; [key: string]: ArrayItemsT; }; export type ItemsT = ArrayItemsT | GroupedItemsT; export type StatefulMenuProps = StatefulContainerProps & MenuProps; export class StatefulMenu extends React.PureComponent<StatefulMenuProps> {} export interface RenderItemProps { disabled?: boolean; ref?: React.Ref<any>; id?: string; isFocused?: boolean; isHighlighted?: boolean; resetMenu?: () => any; } export type OnItemSelect = (args: { item: any; event?: React.SyntheticEvent<HTMLElement> | KeyboardEvent; }) => any; export type StateReducer = ( changeType: STATE_CHANGE_TYPES[keyof STATE_CHANGE_TYPES], changes: StatefulContainerState, currentState: StatefulContainerState, ) => StatefulContainerState; export type GetRequiredItemProps = ( item: any, index: number, ) => RenderItemProps; export type RenderProps = StatefulContainerState & { items: ItemsT; getRequiredItemProps: GetRequiredItemProps; }; export interface StatefulContainerProps { items: ItemsT; initialState?: StatefulContainerState; stateReducer?: StateReducer; getRequiredItemProps?: GetRequiredItemProps; onActiveDescendantChange?: (id?: string) => void; onItemSelect?: OnItemSelect; rootRef?: React.Ref<any>; keyboardControlNode?: React.Ref<any>; typeAhead?: boolean; children?: (args: RenderProps) => React.ReactNode; addMenuToNesting?: (ref: React.Ref<HTMLElement>) => void; removeMenuFromNesting?: (ref: React.Ref<HTMLElement>) => void; getParentMenu?: (ref: React.Ref<HTMLElement>) => void; getChildMenu?: (ref: React.Ref<HTMLElement>) => void; } export interface StatefulContainerState { activedescendantId?: string; highlightedIndex: number; isFocused: boolean; } export class StatefulContainer extends React.Component< StatefulContainerProps, StatefulContainerState > {} export interface OptionListProps extends BaseMenuPropsT { item: any; getItemLabel: (item: any) => React.ReactNode; getChildMenu?: (item: any) => React.ReactNode; onMouseEnter?: (event: MouseEvent) => any; size?: OPTION_LIST_SIZE[keyof OPTION_LIST_SIZE]; overrides?: { ListItem?: Override<any>; ChildMenuPopover?: Override<any>; }; renderHrefAsAnchor?: boolean; resetMenu?: () => void; $isHighlighted?: boolean; $isFocused?: boolean; } export const OptionList: React.FC<OptionListProps>; export interface OptionProfileProps extends BaseMenuPropsT { item: any; getChildMenu?: (item: any) => React.ReactNode; getProfileItemLabels: ( item: any, ) => {title?: string; subtitle?: string; body?: string}; getProfileItemImg: (item: any) => string | React.ComponentType<any>; getProfileItemImgText: (item: any) => string; overrides?: { ListItemProfile?: Override<any>; ProfileImgContainer?: Override<any>; ProfileImg?: Override<any>; ProfileLabelsContainer?: Override<any>; ProfileTitle?: Override<any>; ProfileSubtitle?: Override<any>; ProfileBody?: Override<any>; ChildMenuPopover?: Override<any>; }; resetMenu?: () => void; $isHighlighted?: boolean; } export const OptionProfile: React.FC<OptionProfileProps>; export interface SharedStatelessProps { activedescendantId?: string; getRequiredItemProps?: (item: any, index: number) => RenderItemProps; highlightedIndex?: number; items: ItemsT; isFocused?: boolean; noResultsMsg?: React.ReactNode; onBlur?: (event: React.FocusEvent<HTMLElement>) => any; onFocus?: (event: React.FocusEvent<HTMLElement>) => any; rootRef?: React.Ref<any>; focusMenu?: (event: FocusEvent | MouseEvent | KeyboardEvent) => any; unfocusMenu?: () => any; handleKeyDown?: (event: KeyboardEvent) => any; } export type StatelessMenuProps = SharedStatelessProps & MenuProps; export const Menu: React.FC<StatelessMenuProps>; export interface NestedMenuProps { children: React.ReactNode; } export interface NestedMenuState { menus: Array<React.Ref<HTMLElement>>; } export class NestedMenus extends React.Component< NestedMenuProps, NestedMenuState > { addMenuToNesting(ref: React.Ref<HTMLElement>): void; removeMenuFromNesting(ref: React.Ref<HTMLElement>): void; findMenuIndexByRef(ref: React.Ref<HTMLElement>): number; getParentMenu(ref: React.Ref<HTMLElement>): React.Ref<HTMLElement>; getChildMenu(ref: React.Ref<HTMLElement>): React.Ref<HTMLElement>; } export const StyledEmptyState: StyletronComponent<any>; export const StyledList: StyletronComponent<any>; export const StyledListItem: StyletronComponent<any>; export const StyledListItemProfile: StyletronComponent<any>; export const StyledProfileImgContainer: StyletronComponent<any>; export const StyledProfileImg: StyletronComponent<any>; export const StyledProfileLabelsContainer: StyletronComponent<any>; export const StyledProfileTitle: StyletronComponent<any>; export const StyledProfileSubtitle: StyletronComponent<any>; export const StyledProfileBody: StyletronComponent<any>; export const KEY_STRINGS: KEY_STRINGS; export const STATE_CHANGE_TYPES: STATE_CHANGE_TYPES; export const OPTION_LIST_SIZE: OPTION_LIST_SIZE;
{ "pile_set_name": "Github" }
#!/usr/bin/env bash if [[ "$1" == "" ]]; then echo ./`basename "$0"` file.apk exit 1 fi APKPATH=$1 APKFILE=$(basename -- "$APKPATH") APPNAME="${APKFILE%.*}" # apktool apktool -f d $APKPATH -o 10_apktool-output/$APPNAME.out # jadx #jadx $APKPATH -d 11_jadx-output/$APPNAME.out # extract certinfo keytool -printcert -file 10_apktool-output/$APPNAME.out/original/META-INF/*.RSA > $APPNAME.certinfo.txt
{ "pile_set_name": "Github" }