prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>json_bench_test.go<|end_file_name|><|fim▁begin|>/* * 说明: * 作者:zhe * 时间:2018-09-02 3:27 PM * 更新: */ package json_iterator import "testing" var data []byte func BenchmarkNode_String(b *testing.B) { n := Node{ Name: "root", Value: 1, } b.ResetTimer() for i := 0; i < b.N; i++ { data = []byte(n.String()) } } func BenchmarkNode_Initialize(b *testing.B) { n := Node{}<|fim▁hole|> b.ResetTimer() for i := 0; i < b.N; i++ { _ = n.Initialize(data) } }<|fim▁end|>
<|file_name|>jira_software_create_latest_deb.go<|end_file_name|><|fim▁begin|>package main import ( "flag" "fmt" "runtime" "github.com/bborbe/atlassian_utils/jira_software" atlassian_utils_latest_information "github.com/bborbe/atlassian_utils/latest_information" atlassian_utils_latest_tar_gz_url "github.com/bborbe/atlassian_utils/latest_tar_gz_url" atlassian_utils_latest_version "github.com/bborbe/atlassian_utils/latest_version" command_list "github.com/bborbe/command/list" debian_config "github.com/bborbe/debian_utils/config" debian_config_builder "github.com/bborbe/debian_utils/config_builder" debian_config_parser "github.com/bborbe/debian_utils/config_parser" debian_copier "github.com/bborbe/debian_utils/copier" debian_latest_package_creator "github.com/bborbe/debian_utils/latest_package_creator" debian_package_creator "github.com/bborbe/debian_utils/package_creator" debian_package_creator_by_reader "github.com/bborbe/debian_utils/package_creator_by_reader" debian_tar_gz_extractor "github.com/bborbe/debian_utils/tar_gz_extractor" debian_zip_extractor "github.com/bborbe/debian_utils/zip_extractor" http_client_builder "github.com/bborbe/http/client_builder" http_requestbuilder "github.com/bborbe/http/requestbuilder" "github.com/golang/glog" ) const ( PARAMETER_CONFIG = "config" PARAMETER_TARGET = "target" ) type CreatePackage func(config *debian_config.Config, sourceDir string, targetDir string) error type LatestVersion func() (string, error) var ( configPtr = flag.String(PARAMETER_CONFIG, "", "path to config") targetDirPtr = flag.String(PARAMETER_TARGET, jira_software.TARGET, "target") ) func main() { defer glog.Flush() glog.CopyStandardLogTo("info") flag.Parse() runtime.GOMAXPROCS(runtime.NumCPU()) httpClientBuilder := http_client_builder.New() httpClient := httpClientBuilder.Build() latestInformations := atlassian_utils_latest_information.New(jira_software.JSON_URL, httpClient.Get) latestUrl := atlassian_utils_latest_tar_gz_url.New(latestInformations.VersionInformations) latestVersion := atlassian_utils_latest_version.New(latestInformations.VersionInformations) commandListProvider := func() command_list.CommandList { return command_list.New() } config_parser := debian_config_parser.New() copier := debian_copier.New() zipExtractor := debian_zip_extractor.New() tarGzExtractor := debian_tar_gz_extractor.New() requestbuilderProvider := http_requestbuilder.NewHTTPRequestBuilderProvider() debianPackageCreator := debian_package_creator.New(commandListProvider, copier, tarGzExtractor.ExtractTarGz, zipExtractor.ExtractZip, httpClient.Do, requestbuilderProvider.NewHTTPRequestBuilder) creatorByReader := debian_package_creator_by_reader.New(commandListProvider, debianPackageCreator, tarGzExtractor.ExtractTarGz) latestDebianPackageCreator := debian_latest_package_creator.New(httpClient.Get, latestUrl.LatestTarGzUrl, latestVersion.LatestVersion, creatorByReader.CreatePackage)<|fim▁hole|> config_parser, *configPtr, latestVersion.LatestVersion, *targetDirPtr, ) if err != nil { glog.Exit(err) } } func do(createPackage CreatePackage, config_parser debian_config_parser.ConfigParser, configpath string, latestVersion LatestVersion, targetDir string, ) error { var err error config := createDefaultConfig() if len(configpath) > 0 { if config, err = config_parser.ParseFileToConfig(config, configpath); err != nil { return err } } config_builder := debian_config_builder.NewWithConfig(config) config = config_builder.Build() config.Version, err = latestVersion() if err != nil { return err } sourceDir := fmt.Sprintf("atlassian-jira-software-%s-standalone", config.Version) return createPackage(config, sourceDir, targetDir) } func createDefaultConfig() *debian_config.Config { config := debian_config.DefaultConfig() config.Name = jira_software.PACKAGE_NAME config.Architecture = jira_software.ARCH return config }<|fim▁end|>
err := do( latestDebianPackageCreator.CreateLatestDebianPackage,
<|file_name|>mman.rs<|end_file_name|><|fim▁begin|>//! Memory management declarations. use crate::Result; #[cfg(not(target_os = "android"))] use crate::NixPath; use crate::errno::Errno; #[cfg(not(target_os = "android"))] #[cfg(feature = "fs")] use crate::{fcntl::OFlag, sys::stat::Mode}; use libc::{self, c_int, c_void, size_t, off_t}; use std::os::unix::io::RawFd; libc_bitflags!{ /// Desired memory protection of a memory mapping. pub struct ProtFlags: c_int { /// Pages cannot be accessed. PROT_NONE; /// Pages can be read. PROT_READ; /// Pages can be written. PROT_WRITE; /// Pages can be executed PROT_EXEC; /// Apply protection up to the end of a mapping that grows upwards. #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg_attr(docsrs, doc(cfg(all())))] PROT_GROWSDOWN; /// Apply protection down to the beginning of a mapping that grows downwards. #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg_attr(docsrs, doc(cfg(all())))] PROT_GROWSUP; } } libc_bitflags!{ /// Additional parameters for [`mmap`]. pub struct MapFlags: c_int { /// Compatibility flag. Ignored. MAP_FILE; /// Share this mapping. Mutually exclusive with `MAP_PRIVATE`. MAP_SHARED; /// Create a private copy-on-write mapping. Mutually exclusive with `MAP_SHARED`. MAP_PRIVATE; /// Place the mapping at exactly the address specified in `addr`. MAP_FIXED; /// Place the mapping at exactly the address specified in `addr`, but never clobber an existing range. #[cfg(target_os = "linux")] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_FIXED_NOREPLACE; /// To be used with `MAP_FIXED`, to forbid the system /// to select a different address than the one specified. #[cfg(target_os = "freebsd")] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_EXCL; /// Synonym for `MAP_ANONYMOUS`. MAP_ANON; /// The mapping is not backed by any file. MAP_ANONYMOUS; /// Put the mapping into the first 2GB of the process address space. #[cfg(any(all(any(target_os = "android", target_os = "linux"), any(target_arch = "x86", target_arch = "x86_64")), all(target_os = "linux", target_env = "musl", any(target_arch = "x86", target_arch = "x86_64")), all(target_os = "freebsd", target_pointer_width = "64")))] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_32BIT; /// Used for stacks; indicates to the kernel that the mapping should extend downward in memory. #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_GROWSDOWN; /// Compatibility flag. Ignored. #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_DENYWRITE; /// Compatibility flag. Ignored. #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_EXECUTABLE; /// Mark the mmaped region to be locked in the same way as `mlock(2)`. #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_LOCKED; /// Do not reserve swap space for this mapping. /// /// This was removed in FreeBSD 11 and is unused in DragonFlyBSD. #[cfg(not(any(target_os = "dragonfly", target_os = "freebsd")))] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_NORESERVE; /// Populate page tables for a mapping. #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_POPULATE; /// Only meaningful when used with `MAP_POPULATE`. Don't perform read-ahead. #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_NONBLOCK; /// Allocate the mapping using "huge pages." #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_HUGETLB; /// Make use of 64KB huge page (must be supported by the system) #[cfg(target_os = "linux")] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_HUGE_64KB; /// Make use of 512KB huge page (must be supported by the system) #[cfg(target_os = "linux")] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_HUGE_512KB; /// Make use of 1MB huge page (must be supported by the system) #[cfg(target_os = "linux")] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_HUGE_1MB; /// Make use of 2MB huge page (must be supported by the system) #[cfg(target_os = "linux")] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_HUGE_2MB; /// Make use of 8MB huge page (must be supported by the system) #[cfg(target_os = "linux")] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_HUGE_8MB; /// Make use of 16MB huge page (must be supported by the system) #[cfg(target_os = "linux")] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_HUGE_16MB; /// Make use of 32MB huge page (must be supported by the system) #[cfg(target_os = "linux")] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_HUGE_32MB; /// Make use of 256MB huge page (must be supported by the system) #[cfg(target_os = "linux")] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_HUGE_256MB; /// Make use of 512MB huge page (must be supported by the system) #[cfg(target_os = "linux")] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_HUGE_512MB; /// Make use of 1GB huge page (must be supported by the system) #[cfg(target_os = "linux")] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_HUGE_1GB; /// Make use of 2GB huge page (must be supported by the system) #[cfg(target_os = "linux")] #[cfg_attr(docsrs, doc(cfg(all())))]<|fim▁hole|> /// Make use of 16GB huge page (must be supported by the system) #[cfg(target_os = "linux")] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_HUGE_16GB; /// Lock the mapped region into memory as with `mlock(2)`. #[cfg(target_os = "netbsd")] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_WIRED; /// Causes dirtied data in the specified range to be flushed to disk only when necessary. #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_NOSYNC; /// Rename private pages to a file. /// /// This was removed in FreeBSD 11 and is unused in DragonFlyBSD. #[cfg(any(target_os = "netbsd", target_os = "openbsd"))] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_RENAME; /// Region may contain semaphores. #[cfg(any(target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_HASSEMAPHORE; /// Region grows down, like a stack. #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux", target_os = "openbsd"))] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_STACK; /// Pages in this mapping are not retained in the kernel's memory cache. #[cfg(any(target_os = "ios", target_os = "macos"))] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_NOCACHE; /// Allows the W/X bit on the page, it's necessary on aarch64 architecture. #[cfg(any(target_os = "ios", target_os = "macos"))] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_JIT; /// Allows to use large pages, underlying alignment based on size. #[cfg(target_os = "freebsd")] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_ALIGNED_SUPER; /// Pages will be discarded in the core dumps. #[cfg(target_os = "openbsd")] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_CONCEAL; } } #[cfg(any(target_os = "linux", target_os = "netbsd"))] libc_bitflags!{ /// Options for [`mremap`]. pub struct MRemapFlags: c_int { /// Permit the kernel to relocate the mapping to a new virtual address, if necessary. #[cfg(target_os = "linux")] #[cfg_attr(docsrs, doc(cfg(all())))] MREMAP_MAYMOVE; /// Place the mapping at exactly the address specified in `new_address`. #[cfg(target_os = "linux")] #[cfg_attr(docsrs, doc(cfg(all())))] MREMAP_FIXED; /// Place the mapping at exactly the address specified in `new_address`. #[cfg(target_os = "netbsd")] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_FIXED; /// Allows to duplicate the mapping to be able to apply different flags on the copy. #[cfg(target_os = "netbsd")] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_REMAPDUP; } } libc_enum!{ /// Usage information for a range of memory to allow for performance optimizations by the kernel. /// /// Used by [`madvise`]. #[repr(i32)] #[non_exhaustive] pub enum MmapAdvise { /// No further special treatment. This is the default. MADV_NORMAL, /// Expect random page references. MADV_RANDOM, /// Expect sequential page references. MADV_SEQUENTIAL, /// Expect access in the near future. MADV_WILLNEED, /// Do not expect access in the near future. MADV_DONTNEED, /// Free up a given range of pages and its associated backing store. #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg_attr(docsrs, doc(cfg(all())))] MADV_REMOVE, /// Do not make pages in this range available to the child after a `fork(2)`. #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg_attr(docsrs, doc(cfg(all())))] MADV_DONTFORK, /// Undo the effect of `MADV_DONTFORK`. #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg_attr(docsrs, doc(cfg(all())))] MADV_DOFORK, /// Poison the given pages. /// /// Subsequent references to those pages are treated like hardware memory corruption. #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg_attr(docsrs, doc(cfg(all())))] MADV_HWPOISON, /// Enable Kernel Samepage Merging (KSM) for the given pages. #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg_attr(docsrs, doc(cfg(all())))] MADV_MERGEABLE, /// Undo the effect of `MADV_MERGEABLE` #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg_attr(docsrs, doc(cfg(all())))] MADV_UNMERGEABLE, /// Preserve the memory of each page but offline the original page. #[cfg(any(target_os = "android", all(target_os = "linux", any( target_arch = "aarch64", target_arch = "arm", target_arch = "powerpc", target_arch = "powerpc64", target_arch = "s390x", target_arch = "x86", target_arch = "x86_64", target_arch = "sparc64"))))] MADV_SOFT_OFFLINE, /// Enable Transparent Huge Pages (THP) for pages in the given range. #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg_attr(docsrs, doc(cfg(all())))] MADV_HUGEPAGE, /// Undo the effect of `MADV_HUGEPAGE`. #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg_attr(docsrs, doc(cfg(all())))] MADV_NOHUGEPAGE, /// Exclude the given range from a core dump. #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg_attr(docsrs, doc(cfg(all())))] MADV_DONTDUMP, /// Undo the effect of an earlier `MADV_DONTDUMP`. #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg_attr(docsrs, doc(cfg(all())))] MADV_DODUMP, /// Specify that the application no longer needs the pages in the given range. MADV_FREE, /// Request that the system not flush the current range to disk unless it needs to. #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] #[cfg_attr(docsrs, doc(cfg(all())))] MADV_NOSYNC, /// Undoes the effects of `MADV_NOSYNC` for any future pages dirtied within the given range. #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] #[cfg_attr(docsrs, doc(cfg(all())))] MADV_AUTOSYNC, /// Region is not included in a core file. #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] #[cfg_attr(docsrs, doc(cfg(all())))] MADV_NOCORE, /// Include region in a core file #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] #[cfg_attr(docsrs, doc(cfg(all())))] MADV_CORE, /// This process should not be killed when swap space is exhausted. #[cfg(any(target_os = "freebsd"))] #[cfg_attr(docsrs, doc(cfg(all())))] MADV_PROTECT, /// Invalidate the hardware page table for the given region. #[cfg(target_os = "dragonfly")] #[cfg_attr(docsrs, doc(cfg(all())))] MADV_INVAL, /// Set the offset of the page directory page to `value` for the virtual page table. #[cfg(target_os = "dragonfly")] #[cfg_attr(docsrs, doc(cfg(all())))] MADV_SETMAP, /// Indicates that the application will not need the data in the given range. #[cfg(any(target_os = "ios", target_os = "macos"))] #[cfg_attr(docsrs, doc(cfg(all())))] MADV_ZERO_WIRED_PAGES, /// Pages can be reused (by anyone). #[cfg(any(target_os = "ios", target_os = "macos"))] #[cfg_attr(docsrs, doc(cfg(all())))] MADV_FREE_REUSABLE, /// Caller wants to reuse those pages. #[cfg(any(target_os = "ios", target_os = "macos"))] #[cfg_attr(docsrs, doc(cfg(all())))] MADV_FREE_REUSE, // Darwin doesn't document this flag's behavior. #[cfg(any(target_os = "ios", target_os = "macos"))] #[cfg_attr(docsrs, doc(cfg(all())))] #[allow(missing_docs)] MADV_CAN_REUSE, } } libc_bitflags!{ /// Configuration flags for [`msync`]. pub struct MsFlags: c_int { /// Schedule an update but return immediately. MS_ASYNC; /// Invalidate all cached data. MS_INVALIDATE; /// Invalidate pages, but leave them mapped. #[cfg(any(target_os = "ios", target_os = "macos"))] #[cfg_attr(docsrs, doc(cfg(all())))] MS_KILLPAGES; /// Deactivate pages, but leave them mapped. #[cfg(any(target_os = "ios", target_os = "macos"))] #[cfg_attr(docsrs, doc(cfg(all())))] MS_DEACTIVATE; /// Perform an update and wait for it to complete. MS_SYNC; } } libc_bitflags!{ /// Flags for [`mlockall`]. pub struct MlockAllFlags: c_int { /// Lock pages that are currently mapped into the address space of the process. MCL_CURRENT; /// Lock pages which will become mapped into the address space of the process in the future. MCL_FUTURE; } } /// Locks all memory pages that contain part of the address range with `length` /// bytes starting at `addr`. /// /// Locked pages never move to the swap area. /// /// # Safety /// /// `addr` must meet all the requirements described in the [`mlock(2)`] man page. /// /// [`mlock(2)`]: https://man7.org/linux/man-pages/man2/mlock.2.html pub unsafe fn mlock(addr: *const c_void, length: size_t) -> Result<()> { Errno::result(libc::mlock(addr, length)).map(drop) } /// Unlocks all memory pages that contain part of the address range with /// `length` bytes starting at `addr`. /// /// # Safety /// /// `addr` must meet all the requirements described in the [`munlock(2)`] man /// page. /// /// [`munlock(2)`]: https://man7.org/linux/man-pages/man2/munlock.2.html pub unsafe fn munlock(addr: *const c_void, length: size_t) -> Result<()> { Errno::result(libc::munlock(addr, length)).map(drop) } /// Locks all memory pages mapped into this process' address space. /// /// Locked pages never move to the swap area. For more information, see [`mlockall(2)`]. /// /// [`mlockall(2)`]: https://man7.org/linux/man-pages/man2/mlockall.2.html pub fn mlockall(flags: MlockAllFlags) -> Result<()> { unsafe { Errno::result(libc::mlockall(flags.bits())) }.map(drop) } /// Unlocks all memory pages mapped into this process' address space. /// /// For more information, see [`munlockall(2)`]. /// /// [`munlockall(2)`]: https://man7.org/linux/man-pages/man2/munlockall.2.html pub fn munlockall() -> Result<()> { unsafe { Errno::result(libc::munlockall()) }.map(drop) } /// allocate memory, or map files or devices into memory /// /// # Safety /// /// See the [`mmap(2)`] man page for detailed requirements. /// /// [`mmap(2)`]: https://man7.org/linux/man-pages/man2/mmap.2.html pub unsafe fn mmap(addr: *mut c_void, length: size_t, prot: ProtFlags, flags: MapFlags, fd: RawFd, offset: off_t) -> Result<*mut c_void> { let ret = libc::mmap(addr, length, prot.bits(), flags.bits(), fd, offset); if ret == libc::MAP_FAILED { Err(Errno::last()) } else { Ok(ret) } } /// Expands (or shrinks) an existing memory mapping, potentially moving it at /// the same time. /// /// # Safety /// /// See the `mremap(2)` [man page](https://man7.org/linux/man-pages/man2/mremap.2.html) for /// detailed requirements. #[cfg(any(target_os = "linux", target_os = "netbsd"))] pub unsafe fn mremap( addr: *mut c_void, old_size: size_t, new_size: size_t, flags: MRemapFlags, new_address: Option<* mut c_void>, ) -> Result<*mut c_void> { #[cfg(target_os = "linux")] let ret = libc::mremap(addr, old_size, new_size, flags.bits(), new_address.unwrap_or(std::ptr::null_mut())); #[cfg(target_os = "netbsd")] let ret = libc::mremap( addr, old_size, new_address.unwrap_or(std::ptr::null_mut()), new_size, flags.bits(), ); if ret == libc::MAP_FAILED { Err(Errno::last()) } else { Ok(ret) } } /// remove a mapping /// /// # Safety /// /// `addr` must meet all the requirements described in the [`munmap(2)`] man /// page. /// /// [`munmap(2)`]: https://man7.org/linux/man-pages/man2/munmap.2.html pub unsafe fn munmap(addr: *mut c_void, len: size_t) -> Result<()> { Errno::result(libc::munmap(addr, len)).map(drop) } /// give advice about use of memory /// /// # Safety /// /// See the [`madvise(2)`] man page. Take special care when using /// [`MmapAdvise::MADV_FREE`]. /// /// [`madvise(2)`]: https://man7.org/linux/man-pages/man2/madvise.2.html pub unsafe fn madvise(addr: *mut c_void, length: size_t, advise: MmapAdvise) -> Result<()> { Errno::result(libc::madvise(addr, length, advise as i32)).map(drop) } /// Set protection of memory mapping. /// /// See [`mprotect(3)`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/mprotect.html) for /// details. /// /// # Safety /// /// Calls to `mprotect` are inherently unsafe, as changes to memory protections can lead to /// SIGSEGVs. /// /// ``` /// # use nix::libc::size_t; /// # use nix::sys::mman::{mmap, mprotect, MapFlags, ProtFlags}; /// # use std::ptr; /// const ONE_K: size_t = 1024; /// let mut slice: &mut [u8] = unsafe { /// let mem = mmap(ptr::null_mut(), ONE_K, ProtFlags::PROT_NONE, /// MapFlags::MAP_ANON | MapFlags::MAP_PRIVATE, -1, 0).unwrap(); /// mprotect(mem, ONE_K, ProtFlags::PROT_READ | ProtFlags::PROT_WRITE).unwrap(); /// std::slice::from_raw_parts_mut(mem as *mut u8, ONE_K) /// }; /// assert_eq!(slice[0], 0x00); /// slice[0] = 0xFF; /// assert_eq!(slice[0], 0xFF); /// ``` pub unsafe fn mprotect(addr: *mut c_void, length: size_t, prot: ProtFlags) -> Result<()> { Errno::result(libc::mprotect(addr, length, prot.bits())).map(drop) } /// synchronize a mapped region /// /// # Safety /// /// `addr` must meet all the requirements described in the [`msync(2)`] man /// page. /// /// [`msync(2)`]: https://man7.org/linux/man-pages/man2/msync.2.html pub unsafe fn msync(addr: *mut c_void, length: size_t, flags: MsFlags) -> Result<()> { Errno::result(libc::msync(addr, length, flags.bits())).map(drop) } #[cfg(not(target_os = "android"))] feature! { #![feature = "fs"] /// Creates and opens a new, or opens an existing, POSIX shared memory object. /// /// For more information, see [`shm_open(3)`]. /// /// [`shm_open(3)`]: https://man7.org/linux/man-pages/man3/shm_open.3.html pub fn shm_open<P>( name: &P, flag: OFlag, mode: Mode ) -> Result<RawFd> where P: ?Sized + NixPath { let ret = name.with_nix_path(|cstr| { #[cfg(any(target_os = "macos", target_os = "ios"))] unsafe { libc::shm_open(cstr.as_ptr(), flag.bits(), mode.bits() as libc::c_uint) } #[cfg(not(any(target_os = "macos", target_os = "ios")))] unsafe { libc::shm_open(cstr.as_ptr(), flag.bits(), mode.bits() as libc::mode_t) } })?; Errno::result(ret) } } /// Performs the converse of [`shm_open`], removing an object previously created. /// /// For more information, see [`shm_unlink(3)`]. /// /// [`shm_unlink(3)`]: https://man7.org/linux/man-pages/man3/shm_unlink.3.html #[cfg(not(target_os = "android"))] pub fn shm_unlink<P: ?Sized + NixPath>(name: &P) -> Result<()> { let ret = name.with_nix_path(|cstr| { unsafe { libc::shm_unlink(cstr.as_ptr()) } })?; Errno::result(ret).map(drop) }<|fim▁end|>
MAP_HUGE_2GB;
<|file_name|>brokerlib.py<|end_file_name|><|fim▁begin|># 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. # from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from __future__ import with_statement import collections as _collections import os as _os import proton as _proton import proton.handlers as _handlers import proton.reactor as _reactor import uuid as _uuid import shutil as _shutil import subprocess as _subprocess import sys as _sys import time as _time import tempfile as _tempfile import pathlib as _pathlib class Broker(object): def __init__(self, scheme, host, port, id=None, user=None, password=None, ready_file=None, cert=None, key=None, key_password=None, trusted_db=None): self.scheme = scheme self.host = host self.port = port self.id = id self.user = user self.password = password self.ready_file = ready_file self.cert = cert self.key = key self.key_password = key_password self.trusted_db = trusted_db if self.id is None: self.id = "broker-{0}".format(_uuid.uuid4()) self.container = _reactor.Container(_Handler(self), self.id) self._config_dir = None def init(self): if self.user is not None: if self.password is None: self.fail("A password is required for user authentication") self._init_sasl_config() if self.scheme == "amqps": if self.key is None or self.cert is None: self.fail("if scheme is amqps, key and cert files must be specified") if not _pathlib.Path(self.key).is_file(): self.fail("key file %s does not exist" % (self.key)) if not _pathlib.Path(self.cert).is_file(): self.fail("cert file %s does not exist" % (self.cert)) if self.trusted_db and not _pathlib.Path(self.trusted_db).is_file(): self.fail("trusted db file %s does not exist" % (self.trusted_db)) def _init_sasl_config(self): self._config_dir = _tempfile.mkdtemp(prefix="brokerlib-", suffix="") config_file = _os.path.join(self._config_dir, "proton-server.conf") sasldb_file = _os.path.join(self._config_dir, "users.sasldb") _os.environ["PN_SASL_CONFIG_PATH"] = self._config_dir with open(config_file, "w") as f: f.write("sasldb_path: {0}\n".format(sasldb_file)) f.write("mech_list: PLAIN SCRAM-SHA-1\n") command = "echo '{0}' | saslpasswd2 -p -f {1} '{2}'".format \ (self.password, sasldb_file, self.user) try: _subprocess.check_call(command, shell=True) except _subprocess.CalledProcessError as e: self.fail("Failed adding user to SASL database: {0}", e) def info(self, message, *args): pass def notice(self, message, *args): pass def warn(self, message, *args): pass def error(self, message, *args): _sys.stderr.write("{0}\n".format(message.format(*args))) _sys.stderr.flush() def fail(self, message, *args): self.error(message, *args) _sys.exit(1) def run(self): self.container.run() if _os.path.exists(self._config_dir): _shutil.rmtree(self.dir, ignore_errors=True) class _Queue(object): def __init__(self, broker, address): self.broker = broker self.address = address self.messages = _collections.deque() self.consumers = _collections.deque() self.broker.info("Created {0}", self) def __repr__(self): return "queue '{0}'".format(self.address) def add_consumer(self, link): assert link.is_sender assert link not in self.consumers self.consumers.append(link) self.broker.info("Added consumer for {0} to {1}", link.connection, self) def remove_consumer(self, link): assert link.is_sender try: self.consumers.remove(link) except ValueError: return self.broker.info("Removed consumer for {0} from {1}", link.connection, self) def store_message(self, delivery, message): self.messages.append(message) self.broker.notice("Stored {0} from {1} on {2}", message, delivery.connection, self) def forward_messages(self): credit = sum([x.credit for x in self.consumers]) sent = 0 if credit == 0: return while sent < credit: for consumer in self.consumers: if consumer.credit == 0: continue try: message = self.messages.popleft() except IndexError: self.consumers.rotate(sent) return consumer.send(message) sent += 1 self.broker.notice("Forwarded {0} on {1} to {2}", message, self, consumer.connection) self.consumers.rotate(sent) class _Handler(_handlers.MessagingHandler): def __init__(self, broker): super(_Handler, self).__init__() self.broker = broker self.queues = dict() self.verbose = False def on_start(self, event): interface = "{0}://{1}:{2}".format(self.broker.scheme, self.broker.host, self.broker.port) if self.broker.scheme == "amqps": server_ssl_domain = event.container.ssl.server server_ssl_domain.set_credentials(self.broker.cert, self.broker.key, self.broker.key_password) if self.broker.trusted_db: server_ssl_domain.set_trusted_ca_db(self.broker.trusted_db) server_ssl_domain.set_peer_authentication(_proton.SSLDomain.VERIFY_PEER, self.broker.trusted_db) else: server_ssl_domain.set_peer_authentication(_proton.SSLDomain.ANONYMOUS_PEER) self.acceptor = event.container.listen(interface) self.broker.notice("Listening for connections on '{0}'", interface) if self.broker.ready_file is not None: _time.sleep(0.1) # XXX with open(self.broker.ready_file, "w") as f: f.write("ready\n") def get_queue(self, address): try: queue = self.queues[address] except KeyError: queue = self.queues[address] = _Queue(self.broker, address) return queue def on_link_opening(self, event): if event.link.is_sender: if event.link.remote_source.dynamic: address = "{0}/{1}".format(event.connection.remote_container, event.link.name) else: address = event.link.remote_source.address assert address is not None event.link.source.address = address queue = self.get_queue(address) queue.add_consumer(event.link) if event.link.is_receiver: address = event.link.remote_target.address event.link.target.address = address def on_link_closing(self, event): if event.link.is_sender: queue = self.queues[event.link.source.address] queue.remove_consumer(event.link) def on_connection_init(self, event): event.transport.sasl().allow_insecure_mechs=True def on_connection_opening(self, event): # XXX I think this should happen automatically event.connection.container = event.container.container_id def on_connection_opened(self, event): self.broker.notice("Opened connection from {0}", event.connection) def on_connection_closing(self, event): self.remove_consumers(event.connection) def on_connection_closed(self, event): self.broker.notice("Closed connection from {0}", event.connection) <|fim▁hole|> self.remove_consumers(event.connection) def remove_consumers(self, connection): link = connection.link_head(_proton.Endpoint.REMOTE_ACTIVE) while link is not None: if link.is_sender: queue = self.queues[link.source.address] queue.remove_consumer(link) link = link.next(_proton.Endpoint.REMOTE_ACTIVE) def on_link_flow(self, event): if event.link.is_sender and event.link.drain_mode: event.link.drained() def on_sendable(self, event): queue = self.get_queue(event.link.source.address) queue.forward_messages() def on_settled(self, event): template = "Container '{0}' {1} {2} to {3}" container = event.connection.remote_container source = event.link.source delivery = event.delivery if delivery.remote_state == delivery.ACCEPTED: self.broker.info(template, container, "accepted", delivery, source) elif delivery.remote_state == delivery.REJECTED: self.broker.warn(template, container, "rejected", delivery, source) elif delivery.remote_state == delivery.RELEASED: self.broker.notice(template, container, "released", delivery, source) elif delivery.remote_state == delivery.MODIFIED: self.broker.notice(template, container, "modified", delivery, source) def on_message(self, event): message = event.message delivery = event.delivery address = event.link.target.address if address is None: address = message.address queue = self.get_queue(address) queue.store_message(delivery, message) queue.forward_messages() # # def on_unhandled(self, name, event): # _sys.stderr.write("{0} {1}\n".format(name, event)) # _sys.stderr.flush() if __name__ == "__main__": def _print(message, *args): message = message.format(*args) _sys.stderr.write("{0}\n".format(message)) _sys.stderr.flush() class _Broker(Broker): def info(self, message, *args): _print(message, *args) def notice(self, message, *args): _print(message, *args) def warn(self, message, *args): _print(message, *args) try: host, port = _sys.argv[1:3] except IndexError: _print("Usage: brokerlib <host> <port>") _sys.exit(1) try: port = int(port) except ValueError: _print("The port must be an integer") _sys.exit(1) broker = _Broker(host, port) try: broker.run() except KeyboardInterrupt: pass<|fim▁end|>
def on_disconnected(self, event): self.broker.notice("Disconnected from {0}", event.connection)
<|file_name|>schemes.rs<|end_file_name|><|fim▁begin|>use valico::json_schema; use typemap; use super::super::framework; <|fim▁hole|>pub struct SchemesScope; impl typemap::Key for SchemesScope { type Value = json_schema::Scope; } fn build_schemes(handlers: &mut framework::ApiHandlers, scope: &mut json_schema::Scope) -> Result<(), json_schema::SchemaError> { for handler_ in handlers.iter_mut() { let mut handler = &mut **handler_ as &mut framework::ApiHandler; if handler.is::<framework::Api>() { let api = handler.downcast_mut::<framework::Api>().unwrap(); try!(build_schemes(&mut api.handlers, scope)) } else if handler.is::<framework::Namespace>() { let namespace = handler.downcast_mut::<framework::Namespace>().unwrap(); if namespace.coercer.is_some() { let coercer = namespace.coercer.as_mut().unwrap(); try!(coercer.build_schemes(scope)); } try!(build_schemes(&mut namespace.handlers, scope)); } else if handler.is::<framework::Endpoint>() { let endpoint = handler.downcast_mut::<framework::Endpoint>().unwrap(); if endpoint.coercer.is_some() { let coercer = endpoint.coercer.as_mut().unwrap(); try!(coercer.build_schemes(scope)); } } } Ok(()) } pub fn enable_schemes(app: &mut framework::Application, mut scope: json_schema::Scope) -> Result<(), json_schema::SchemaError> { try!(build_schemes(&mut app.root_api.handlers, &mut scope)); app.ext.insert::<SchemesScope>(scope); Ok(()) }<|fim▁end|>
<|file_name|>results.py<|end_file_name|><|fim▁begin|>import easygui_qt as easy import pandas as pd import numpy as np import geoplot from matplotlib import pyplot as plt import math from matplotlib.colors import LinearSegmentedColormap MTH = {'sum': np.sum, 'max': np.max, 'min': np.min, 'mean': np.mean} class SpatialData: def __init__(self, result_file=None): if result_file is None: result_file = easy.get_file_names(title="Select result file.")[0] print(result_file) self.results = pd.read_csv(result_file, index_col=[0, 1, 2]) self.polygons = None self.lines = None self.plotter = None def add_polygon_column(self, obj=None, direction=None, bus=None, method=None, kws=None, **kwargs): if method is None: method = easy.get_choice("Chose you method!", choices=['sum', 'max', 'min', 'mean']) if self.polygons is None: self.polygons = load_geometry(**kwargs) if kws is None: kws = ['line', 'GL', 'duals'] objects = list(set([ x[5:] for x in self.results.index.get_level_values('obj_label').unique() if not any(y in x for y in kws)])) reg_buses = list(set([ x[5:] for x in self.results.index.get_level_values('bus_label').unique() if not any(y in x for y in kws)])) global_buses = list(set([ x for x in self.results.index.get_level_values('bus_label').unique() if 'GL' in x])) buses = reg_buses + global_buses if obj is None: obj = easy.get_choice("What object do you want to plot?", choices=objects) if direction is None: direction = easy.get_choice("From bus or to bus?", choices=['from_bus', 'to_bus']) if bus is None: bus = easy.get_choice("Which bus?", choices=buses) for r in self.polygons.index: try: tmp = pd.Series(self.results.loc[ '{0}_{1}'.format(r, bus), direction, '{0}_{1}'.format(r, obj)]['val']).groupby( level=0).agg(MTH[method])[0] except KeyError: tmp = float('nan') self.polygons.loc[r, obj] = tmp uv = unit_round(self.polygons[obj]) self.polygons[obj] = uv['series'] self.polygons[obj].prefix = uv['prefix'] self.polygons[obj].prefix_long = uv['prefix_long'] selection = {'obj': obj, 'direction': direction, 'bus': bus, 'method': method} return selection def add_power_lines(self, method=None, **kwargs): if self.lines is None: self.lines = load_geometry(region_column='name', **kwargs) if self.plotter is None: self.plotter = geoplot.GeoPlotter( geoplot.postgis2shapely(self.lines.geom), (3, 16, 47, 56)) else: self.plotter.geometries = geoplot.postgis2shapely(self.lines.geom) if method is None: method = easy.get_choice("Chose you method!", choices=['sum', 'max', 'min', 'mean']) for l in self.lines.index: try: r = l.split('-') tmp = pd.Series() tmp.set_value(1, self.results.loc[ '{0}_bus_el'.format(r[0]), 'from_bus', '{0}_{1}_powerline'.format(*r)]['val'].groupby( level=0).agg(MTH[method])[0]) tmp.set_value(2, self.results.loc[ '{0}_bus_el'.format(r[1]), 'from_bus', '{1}_{0}_powerline'.format(*r)]['val'].groupby( level=0).agg(MTH[method])[0]) self.lines.loc[l, 'trans'] = tmp.max() except KeyError: self.lines.loc[l, 'trans'] = 3000000 uv = unit_round(self.lines['trans']) self.lines['trans'] = uv['series'] self.lines['trans'].prefix = uv['prefix'] self.lines['trans'].prefix_long = uv['prefix_long'] return method def load_geometry(geometry_file=None, region_column='gid'): if geometry_file is None: geometry_file = easy.get_file_names()[0] return pd.read_csv(geometry_file, index_col=region_column) def show(): plt.tight_layout() plt.box(on=None) plt.show() def unit_round(values, min_value=False): longprefix = {0: '', 1: 'kilo', 2: 'Mega', 3: 'Giga', 4: 'Tera', 5: 'Exa', 6: 'Peta'} shortprefix = {0: '', 1: 'k', 2: 'M', 3: 'G', 4: 'T', 5: 'E', 6: 'P'} if min_value: def_value = min(values) a = 1 else: def_value = max(values) a = 0 if def_value > 0: factor = int(int(math.log10(def_value)) / 3) + a else: factor = 0 values = round(values / 10 ** (factor * 3), 2) return {'series': values, 'prefix': shortprefix[factor], 'prefix_long': longprefix[factor]} def add_labels(data, plotter, label=None, coord_file='data/geometries/coord_region.csv'): p = pd.read_csv(coord_file, index_col='name') data.polygons['point'] = p.point for row in data.polygons.iterrows(): if 'point' not in row[1]: point = geoplot.postgis2shapely([row[1].geom, ])[0].centroid else: point = geoplot.postgis2shapely([row[1].point, ])[0] (x, y) = plotter.basemap(point.x, point.y) if label is None: text = row[0][2:] else: text = str(round(row[1][label], 1)) if row[1].normalised < 0.3 or row[1].normalised > 0.95: textcolour = 'white' else: textcolour = 'black' plotter.ax.text(x, y, text, color=textcolour, fontsize=12) start_line = plotter.basemap(9.7, 53.4) end_line = plotter.basemap(10.0, 53.55) plt.plot([start_line[0], end_line[0]], [start_line[1], end_line[1]], '-', color='white') def polygon_plot(l_min=None, l_max=None, setname=None, myset=None, method=None, filename=None): geometry = 'data/geometries/polygons_de21_simple.csv' sets = { 'load': { 'obj': 'load', 'direction': 'from_bus', 'bus': 'bus_el'}, 'pv': { 'obj': 'solar', 'direction': 'to_bus', 'bus': 'bus_el'}, } if setname is None and myset is None: setname = easy.get_choice("What object do you want to plot?", choices=tuple(sets.keys())) if setname is not None: myset = sets[setname] if method is None: myset['method'] = easy.get_choice( "Chose you method!", choices=['sum', 'max', 'min', 'mean']) else: myset['method'] = method s_data = SpatialData(filename) myset = s_data.add_polygon_column(geometry_file=geometry, **myset) if myset['method'] == 'sum': unit = 'Wh' else: unit = 'W' unit = "[{0}]".format(s_data.polygons[myset['obj']].prefix + unit) plotter = geoplot.GeoPlotter(geoplot.postgis2shapely(s_data.polygons.geom), (3, 16, 47, 56)) v_min = s_data.polygons[myset['obj']].min() v_max = s_data.polygons[myset['obj']].max() s_data.polygons['normalised'] = ((s_data.polygons[myset['obj']] - v_min) / (v_max - v_min)) plotter.data = s_data.polygons['normalised'] plotter.plot(facecolor='data', edgecolor='white') add_labels(s_data, plotter, myset['obj']) if l_min is None: l_min = v_min if l_max is None: l_max = v_max plotter.draw_legend((l_min, l_max), number_ticks=3, legendlabel=unit, location='bottom') show() def powerline_plot(l_min=None, l_max=None): s_data = SpatialData() reg = { 'geometry_file': 'data/geometries/polygons_de21_simple.csv'} poly = geoplot.postgis2shapely(load_geometry(**reg).geom) plotter = geoplot.GeoPlotter(poly, (3, 16, 47, 56)) method = s_data.add_power_lines( geometry_file='data/geometries/lines_de21.csv') plotter.plot(facecolor='grey', edgecolor='white') if method == 'sum': unit = 'Wh' else: unit = 'W' unit = "[{0}]".format(s_data.lines['trans'].prefix + unit) v_min = s_data.lines['trans'].min() v_max = s_data.lines['trans'].max() s_data.lines['normalised'] = ((s_data.lines['trans'] - v_min) / (v_max - v_min)) plotter.geometries = geoplot.postgis2shapely(s_data.lines.geom) plotter.data = s_data.lines['normalised'] my_cmap = LinearSegmentedColormap.from_list('mycmap', [(0, 'green'), (0.5, 'yellow'), (1, 'red')]) plotter.plot(edgecolor='data', linewidth=2, cmap=my_cmap) if l_min is None: l_min = v_min if l_max is None: l_max = v_max plotter.draw_legend((l_min, l_max), number_ticks=3, cmap=my_cmap, legendlabel=unit, location='right') show() def combined_plot(): s_data = SpatialData() obj = s_data.add_polygon_column( obj='load', direction='from_bus', bus='bus_el', method='sum', geometry_file='geometries/polygons_de21_simple.csv') s_data.add_power_lines( geometry_file='geometries/lines_de21.csv') unit = s_data.polygons[obj].prefix_long plotter = geoplot.GeoPlotter(geoplot.postgis2shapely(s_data.polygons.geom),<|fim▁hole|> v_min = s_data.polygons[obj].min() v_max = s_data.polygons[obj].max() s_data.polygons['normalised'] = ((s_data.polygons[obj] - v_min) / (v_max - v_min)) plotter.data = s_data.polygons['normalised'] plotter.plot(facecolor='data', edgecolor='white') plotter.draw_legend((v_min, v_max), number_ticks=3, legendlabel=unit, location='bottom') unit = s_data.lines['trans'].prefix_long v_min = s_data.lines['trans'].min() v_max = s_data.lines['trans'].max() s_data.lines['normalised'] = ((s_data.lines['trans'] - v_min) / (v_max - v_min)) plotter.geometries = geoplot.postgis2shapely(s_data.lines.geom) plotter.data = s_data.lines['normalised'] my_cmap = LinearSegmentedColormap.from_list('mycmap', [(0, 'green'), (0.5, 'yellow'), (1, 'red')]) plotter.plot(edgecolor='data', linewidth=2, cmap=my_cmap) plotter.draw_legend((v_min, v_max), number_ticks=3, legendlabel=unit, location='right') show() if __name__ == "__main__": # resf = ('/home/uwe/git_local/reegis-hp/reegis_hp/de21/results' + # '/scenario_reegis_de_21_test_2017-01-03 11:31:10.600830_' + # 'results_complete.csv') # choice = 'polygons' choice = easy.get_choice( "What geometry do you want to plot?", choices=['lines', 'polygons']) if choice == 'polygons': polygon_plot(l_min=0) elif choice == 'lines': powerline_plot() else: print("End!")<|fim▁end|>
(3, 16, 47, 56))
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models from django.contrib.auth.models import User<|fim▁hole|> class Post(models.Model): title = models.CharField(max_length=255) body = models.TextField() user = models.ForeignKey(User)<|fim▁end|>
<|file_name|>MapFull.js<|end_file_name|><|fim▁begin|>import React, {Component} from 'react'; import {connect} from 'react-redux'; class MapFull extends Component { constructor() { super(); this.state = { htmlContent: null }; } componentDidMount() { this.getMapHtml(); }<|fim▁hole|> if (!this.props.map || this.props.map.filehash !== prevProps.map.filehash) { this.getMapHtml(); } } getMapHtml() { const path = this.props.settings.html_url + this.props.map.filehash; fetch(path).then(response => { return response.text(); }).then(response => { this.setState({ htmlContent: response }); }); } getMarkup() { return {__html: this.state.htmlContent} } render() { return ( <div className="MapFull layoutbox"> <h3>{this.props.map.titlecache}</h3> <div id="overDiv" style={{position: 'fixed', visibility: 'hide', zIndex: 1}}></div> <div> {this.state.htmlContent ? <div> <div dangerouslySetInnerHTML={this.getMarkup()}></div> </div> : null} </div> </div> ) } } function mapStateToProps(state) { return {settings: state.settings} } export default connect(mapStateToProps)(MapFull);<|fim▁end|>
componentDidUpdate(prevProps, prevState) {
<|file_name|>inventory.cpp<|end_file_name|><|fim▁begin|>/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ /* * Based on the Reverse Engineering work of Christophe Fontanel, * maintainer of the Dungeon Master Encyclopaedia (http://dmweb.free.fr/) */ #include "graphics/surface.h" #include "graphics/thumbnail.h" #include "dm/inventory.h" #include "dm/dungeonman.h" #include "dm/eventman.h" #include "dm/group.h" #include "dm/menus.h" #include "dm/gfx.h" #include "dm/text.h" #include "dm/objectman.h" #include "dm/timeline.h" #include "dm/projexpl.h" #include "dm/sounds.h" namespace DM { void InventoryMan::initConstants() { static const char* skillLevelNamesEN[15] = {"NEOPHYTE", "NOVICE", "APPRENTICE", "JOURNEYMAN", "CRAFTSMAN", "ARTISAN", "ADEPT", "EXPERT", "` MASTER", "a MASTER","b MASTER", "c MASTER", "d MASTER", "e MASTER", "ARCHMASTER"}; static const char* skillLevelNamesDE[15] = {"ANFAENGER", "NEULING", "LEHRLING", "ARBEITER", "GESELLE", "HANDWERKR", "FACHMANN", "EXPERTE", "` MEISTER", "a MEISTER", "b MEISTER", "c MEISTER", "d MEISTER", "e MEISTER", "ERZMEISTR"}; static const char* skillLevelNamesFR[15] = {"NEOPHYTE", "NOVICE", "APPRENTI", "COMPAGNON", "ARTISAN", "PATRON", "ADEPTE", "EXPERT", "MAITRE '", "MAITRE a", "MAITRE b", "MAITRE c", "MAITRE d", "MAITRE e", "SUR-MAITRE"}; const char **translatedSkillLevel; switch (_vm->getGameLanguage()) { // localized default: case Common::EN_ANY: translatedSkillLevel = skillLevelNamesEN; break; case Common::DE_DEU: translatedSkillLevel = skillLevelNamesDE; break; case Common::FR_FRA: translatedSkillLevel = skillLevelNamesFR; break; } for (int i = 0; i < 15; ++i) _skillLevelNames[i] = translatedSkillLevel[i]; _boxPanel = Box(80, 223, 52, 124); // @ G0032_s_Graphic562_Box_Panel } InventoryMan::InventoryMan(DMEngine *vm) : _vm(vm) { _inventoryChampionOrdinal = 0; _panelContent = kDMPanelContentFoodWaterPoisoned; for (uint16 i = 0; i < 8; ++i) _chestSlots[i] = Thing(0); _openChest = _vm->_thingNone; _objDescTextXpos = 0; _objDescTextYpos = 0; for (int i = 0; i < 15; i++) _skillLevelNames[i] = nullptr; initConstants(); } void InventoryMan::toggleInventory(ChampionIndex championIndex) { static Box boxFloppyZzzCross(174, 218, 2, 12); // @ G0041_s_Graphic562_Box_ViewportFloppyZzzCross DisplayMan &display = *_vm->_displayMan; ChampionMan &championMan = *_vm->_championMan; if ((championIndex != kDMChampionCloseInventory) && !championMan._champions[championIndex]._currHealth) return; if (_vm->_pressingMouth || _vm->_pressingEye) return; _vm->_stopWaitingForPlayerInput = true; uint16 inventoryChampionOrdinal = _inventoryChampionOrdinal; if (_vm->indexToOrdinal(championIndex) == inventoryChampionOrdinal) championIndex = kDMChampionCloseInventory; _vm->_eventMan->showMouse(); if (inventoryChampionOrdinal) { _inventoryChampionOrdinal = _vm->indexToOrdinal(kDMChampionNone); closeChest(); Champion *champion = &championMan._champions[_vm->ordinalToIndex(inventoryChampionOrdinal)]; if (champion->_currHealth && !championMan._candidateChampionOrdinal) { setFlag(champion->_attributes, kDMAttributeStatusBox); championMan.drawChampionState((ChampionIndex)_vm->ordinalToIndex(inventoryChampionOrdinal)); } if (championMan._partyIsSleeping) { _vm->_eventMan->hideMouse(); return; } if (championIndex == kDMChampionCloseInventory) { _vm->_eventMan->_refreshMousePointerInMainLoop = true; _vm->_menuMan->drawMovementArrows(); _vm->_eventMan->hideMouse(); _vm->_eventMan->_secondaryMouseInput = _vm->_eventMan->_secondaryMouseInputMovement; _vm->_eventMan->_secondaryKeyboardInput = _vm->_eventMan->_secondaryKeyboardInputMovement; _vm->_eventMan->discardAllInput(); display.drawFloorAndCeiling(); return; } } display._useByteBoxCoordinates = false; _inventoryChampionOrdinal = _vm->indexToOrdinal(championIndex); if (!inventoryChampionOrdinal) display.shadeScreenBox(&display._boxMovementArrows, kDMColorBlack); Champion *champion = &championMan._champions[championIndex]; display.loadIntoBitmap(kDMGraphicIdxInventory, display._bitmapViewport); if (championMan._candidateChampionOrdinal) display.fillBoxBitmap(display._bitmapViewport, boxFloppyZzzCross, kDMColorDarkestGray, k112_byteWidthViewport, k136_heightViewport); switch (_vm->getGameLanguage()) { // localized default: case Common::EN_ANY: _vm->_textMan->printToViewport(5, 116, kDMColorLightestGray, "HEALTH"); _vm->_textMan->printToViewport(5, 124, kDMColorLightestGray, "STAMINA"); break; case Common::DE_DEU: _vm->_textMan->printToViewport(5, 116, kDMColorLightestGray, "GESUND"); _vm->_textMan->printToViewport(5, 124, kDMColorLightestGray, "KRAFT"); break; case Common::FR_FRA: _vm->_textMan->printToViewport(5, 116, kDMColorLightestGray, "SANTE"); _vm->_textMan->printToViewport(5, 124, kDMColorLightestGray, "VIGUEUR"); break; } _vm->_textMan->printToViewport(5, 132, kDMColorLightestGray, "MANA"); for (uint16 i = kDMSlotReadyHand; i < kDMSlotChest1; i++) championMan.drawSlot(championIndex, i); setFlag(champion->_attributes, kDMAttributeViewport | kDMAttributeStatusBox | kDMAttributePanel | kDMAttributeLoad | kDMAttributeStatistics | kDMAttributeNameTitle); championMan.drawChampionState(championIndex); _vm->_eventMan->_mousePointerBitmapUpdated = true; _vm->_eventMan->hideMouse(); _vm->_eventMan->_secondaryMouseInput = _vm->_eventMan->_secondaryMouseInputChampionInventory; _vm->_eventMan->_secondaryKeyboardInput = nullptr; _vm->_eventMan->discardAllInput(); } void InventoryMan::drawStatusBoxPortrait(ChampionIndex championIndex) { DisplayMan &dispMan = *_vm->_displayMan; dispMan._useByteBoxCoordinates = false; Box box; box._rect.top = 0; box._rect.bottom = 28; box._rect.left = championIndex * kDMChampionStatusBoxSpacing + 7; box._rect.right = box._rect.left + 31; dispMan.blitToScreen(_vm->_championMan->_champions[championIndex]._portrait, &box, k16_byteWidth, kDMColorNoTransparency, 29); } void InventoryMan::drawPanelHorizontalBar(int16 x, int16 y, int16 pixelWidth, Color color) { DisplayMan &display = *_vm->_displayMan; Box box; box._rect.left = x; box._rect.right = box._rect.left + pixelWidth; box._rect.top = y; box._rect.bottom = box._rect.top + 6; display._useByteBoxCoordinates = false; display.fillBoxBitmap(display._bitmapViewport, box, color, k112_byteWidthViewport, k136_heightViewport); } void InventoryMan::drawPanelFoodOrWaterBar(int16 amount, int16 y, Color color) { if (amount < -512) color = kDMColorRed; else if (amount < 0) color = kDMColorYellow; int16 pixelWidth = amount + 1024; if (pixelWidth == 3072) pixelWidth = 3071; pixelWidth /= 32; drawPanelHorizontalBar(115, y + 2, pixelWidth, kDMColorBlack); drawPanelHorizontalBar(113, y, pixelWidth, color); } void InventoryMan::drawPanelFoodWaterPoisoned() { static Box boxFood(112, 159, 60, 68); // @ G0035_s_Graphic562_Box_Food static Box boxWater(112, 159, 83, 91); // @ G0036_s_Graphic562_Box_Water static Box boxPoisoned(112, 207, 105, 119); // @ G0037_s_Graphic562_Box_Poisoned Champion &champ = _vm->_championMan->_champions[_inventoryChampionOrdinal]; closeChest(); DisplayMan &dispMan = *_vm->_displayMan; dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxPanelEmpty), _boxPanel, k72_byteWidth, kDMColorRed, 73); switch (_vm->getGameLanguage()) { // localized default: case Common::EN_ANY: dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxFoodLabel), boxFood, k24_byteWidth, kDMColorDarkestGray, 9); dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxWaterLabel), boxWater, k24_byteWidth, kDMColorDarkestGray, 9); break; case Common::DE_DEU: dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxFoodLabel), boxFood, k32_byteWidth, kDMColorDarkestGray, 9); dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxWaterLabel), boxWater, k32_byteWidth, kDMColorDarkestGray, 9); break; case Common::FR_FRA: dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxFoodLabel), boxFood, k48_byteWidth, kDMColorDarkestGray, 9); dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxWaterLabel), boxWater, k24_byteWidth, kDMColorDarkestGray, 9); break; } if (champ._poisonEventCount) dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxPoisionedLabel), boxPoisoned, k48_byteWidth, kDMColorDarkestGray, 15); drawPanelFoodOrWaterBar(champ._food, 69, kDMColorLightBrown); drawPanelFoodOrWaterBar(champ._water, 92, kDMColorBlue); } void InventoryMan::drawPanelResurrectReincarnate() { DisplayMan &display = *_vm->_displayMan; _panelContent = kDMPanelContentResurrectReincarnate; display.blitToViewport(display.getNativeBitmapOrGraphic(kDMGraphicIdxPanelResurectReincarnate), _boxPanel, k72_byteWidth, kDMColorDarkGreen, 73); } void InventoryMan::drawPanel() { closeChest(); ChampionMan &cm = *_vm->_championMan; if (cm._candidateChampionOrdinal) { drawPanelResurrectReincarnate(); return; } Thing thing = cm._champions[_vm->ordinalToIndex(_inventoryChampionOrdinal)].getSlot(kDMSlotActionHand); _panelContent = kDMPanelContentFoodWaterPoisoned; switch (thing.getType()) { case kDMThingTypeContainer: _panelContent = kDMPanelContentChest; break; case kDMThingTypeScroll: _panelContent = kDMPanelContentScroll; break; default: thing = _vm->_thingNone; break; } if (thing == _vm->_thingNone) drawPanelFoodWaterPoisoned(); else drawPanelObject(thing, false); } void InventoryMan::closeChest() { DungeonMan &dunMan = *_vm->_dungeonMan; bool processFirstChestSlot = true; if (_openChest == _vm->_thingNone) return; Container *container = (Container *)dunMan.getThingData(_openChest); _openChest = _vm->_thingNone; container->getSlot() = _vm->_thingEndOfList; Thing prevThing; for (int16 chestSlotIndex = 0; chestSlotIndex < 8; ++chestSlotIndex) { Thing thing = _chestSlots[chestSlotIndex]; if (thing != _vm->_thingNone) { _chestSlots[chestSlotIndex] = _vm->_thingNone; // CHANGE8_09_FIX if (processFirstChestSlot) { processFirstChestSlot = false; *dunMan.getThingData(thing) = _vm->_thingEndOfList.toUint16(); container->getSlot() = prevThing = thing; } else { dunMan.linkThingToList(thing, prevThing, kDMMapXNotOnASquare, 0); prevThing = thing; } } } } void InventoryMan::drawPanelScrollTextLine(int16 yPos, char *text) { for (char *iter = text; *iter != '\0'; ++iter) { if ((*iter >= 'A') && (*iter <= 'Z')) *iter -= 64; else if (*iter >= '{') // this branch is CHANGE5_03_IMPROVEMENT *iter -= 96; } _vm->_textMan->printToViewport(162 - (6 * strlen(text) / 2), yPos, kDMColorBlack, text, kDMColorWhite); } void InventoryMan::drawPanelScroll(Scroll *scroll) { DisplayMan &dispMan = *_vm->_displayMan; char stringFirstLine[300]; _vm->_dungeonMan->decodeText(stringFirstLine, Thing(scroll->getTextStringThingIndex()), (TextType)(kDMTextTypeScroll | kDMMaskDecodeEvenIfInvisible)); char *charRed = stringFirstLine; while (*charRed && (*charRed != '\n')) charRed++; *charRed = '\0'; dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxPanelOpenScroll), _boxPanel, k72_byteWidth, kDMColorRed, 73); int16 lineCount = 1; charRed++; char *charGreen = charRed; // first char of the second line while (*charGreen) { /* BUG0_47 Graphical glitch when you open a scroll. If there is a single line of text in a scroll (with no carriage return) then charGreen points to undefined data. This may result in a graphical glitch and also corrupt other memory. This is not an issue in the original dungeons where all scrolls contain at least one carriage return character */ if (*charGreen == '\n') lineCount++; charGreen++; } if (*(charGreen - 1) != '\n') lineCount++; else if (*(charGreen - 2) == '\n') lineCount--; int16 yPos = 92 - (7 * lineCount) / 2; // center the text vertically drawPanelScrollTextLine(yPos, stringFirstLine); charGreen = charRed; while (*charGreen) { yPos += 7; while (*charRed && (*charRed != '\n')) charRed++; if (!(*charRed)) charRed[1] = '\0'; *charRed++ = '\0'; drawPanelScrollTextLine(yPos, charGreen); charGreen = charRed; } } void InventoryMan::openAndDrawChest(Thing thingToOpen, Container *chest, bool isPressingEye) { DisplayMan &dispMan = *_vm->_displayMan; ObjectMan &objMan = *_vm->_objectMan; if (_openChest == thingToOpen) return; if (_openChest != _vm->_thingNone) closeChest(); // CHANGE8_09_FIX _openChest = thingToOpen; if (!isPressingEye) { objMan.drawIconInSlotBox(kDMSlotBoxInventoryActionHand, kDMIconIndiceContainerChestOpen); } dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxPanelOpenChest), _boxPanel, k72_byteWidth, kDMColorRed, 73); int16 chestSlotIndex = 0; Thing thing = chest->getSlot(); int16 thingCount = 0; while (thing != _vm->_thingEndOfList) { if (++thingCount > 8) break; // CHANGE8_08_FIX, make sure that no more than the first 8 objects in a chest are drawn objMan.drawIconInSlotBox(chestSlotIndex + kDMSlotBoxChestFirstSlot, objMan.getIconIndex(thing)); _chestSlots[chestSlotIndex++] = thing; thing = _vm->_dungeonMan->getNextThing(thing); } while (chestSlotIndex < 8) { objMan.drawIconInSlotBox(chestSlotIndex + kDMSlotBoxChestFirstSlot, kDMIconIndiceNone); _chestSlots[chestSlotIndex++] = _vm->_thingNone; } } void InventoryMan::drawIconToViewport(IconIndice iconIndex, int16 xPos, int16 yPos) { static byte iconBitmap[16 * 16]; Box boxIcon(xPos, xPos + 15, yPos, yPos + 15); _vm->_objectMan->extractIconFromBitmap(iconIndex, iconBitmap); _vm->_displayMan->blitToViewport(iconBitmap, boxIcon, k8_byteWidth, kDMColorNoTransparency, 16); } void InventoryMan::buildObjectAttributeString(int16 potentialAttribMask, int16 actualAttribMask, const char **attribStrings, char *destString, const char *prefixString, const char *suffixString) { uint16 identicalBitCount = 0; int16 attribMask = 1; for (uint16 stringIndex = 0; stringIndex < 16; stringIndex++, attribMask <<= 1) { if (attribMask & potentialAttribMask & actualAttribMask) identicalBitCount++; } if (identicalBitCount == 0) { *destString = '\0'; return; } strcpy(destString, prefixString); attribMask = 1; for (uint16 stringIndex = 0; stringIndex < 16; stringIndex++, attribMask <<= 1) { if (attribMask & potentialAttribMask & actualAttribMask) { strcat(destString, attribStrings[stringIndex]); if (identicalBitCount-- > 2) { strcat(destString, ", "); } else if (identicalBitCount == 1) { switch (_vm->getGameLanguage()) { // localized default: case Common::EN_ANY: strcat(destString, " AND "); break; case Common::DE_DEU: strcat(destString, " UND "); break; case Common::FR_FRA: strcat(destString, " ET "); break; } } } } strcat(destString, suffixString); } void InventoryMan::drawPanelObjectDescriptionString(const char *descString) { if (descString[0] == '\f') { // form feed descString++; _objDescTextXpos = 108; _objDescTextYpos = 59; } if (descString[0]) { char stringTmpBuff[128]; strcpy(stringTmpBuff, descString); char *stringLine = stringTmpBuff; bool severalLines = false; char *string = nullptr; while (*stringLine) { if (strlen(stringLine) > 18) { // if string is too long to fit on one line string = &stringLine[17]; while (*string != ' ') // go back to the last space character string--; *string = '\0'; // and split the string there severalLines = true; } _vm->_textMan->printToViewport(_objDescTextXpos, _objDescTextYpos, kDMColorLightestGray, stringLine); _objDescTextYpos += 7; if (severalLines) { severalLines = false; stringLine = ++string; } else { *stringLine = '\0'; } } } } void InventoryMan::drawPanelArrowOrEye(bool pressingEye) { static Box boxArrowOrEye(83, 98, 57, 65); // @ G0033_s_Graphic562_Box_ArrowOrEye DisplayMan &dispMan = *_vm->_displayMan; dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(pressingEye ? kDMGraphicIdxEyeForObjectDescription : kDMGraphicIdxArrowForChestContent), boxArrowOrEye, k8_byteWidth, kDMColorRed, 9); } void InventoryMan::drawPanelObject(Thing thingToDraw, bool pressingEye) { static Box boxObjectDescCircle(105, 136, 53, 79); // @ G0034_s_Graphic562_Box_ObjectDescriptionCircle DungeonMan &dungeon = *_vm->_dungeonMan; ObjectMan &objMan = *_vm->_objectMan; DisplayMan &dispMan = *_vm->_displayMan; ChampionMan &champMan = *_vm->_championMan; TextMan &textMan = *_vm->_textMan; if (_vm->_pressingEye || _vm->_pressingMouth) closeChest(); uint16 *rawThingPtr = dungeon.getThingData(thingToDraw); drawPanelObjectDescriptionString("\f"); // form feed ThingType thingType = thingToDraw.getType(); if (thingType == kDMThingTypeScroll) drawPanelScroll((Scroll *)rawThingPtr); else if (thingType == kDMThingTypeContainer) openAndDrawChest(thingToDraw, (Container *)rawThingPtr, pressingEye); else { IconIndice iconIndex = objMan.getIconIndex(thingToDraw); dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxPanelEmpty), _boxPanel, k72_byteWidth, kDMColorRed, 73); dispMan.blitToViewport(dispMan.getNativeBitmapOrGraphic(kDMGraphicIdxObjectDescCircle), boxObjectDescCircle, k16_byteWidth, kDMColorDarkestGray, 27); Common::String descString; Common::String str; if (iconIndex == kDMIconIndiceJunkChampionBones) { switch (_vm->getGameLanguage()) { // localized case Common::FR_FRA: // Fix original bug dur to a cut&paste error: string was concatenated then overwritten by the name str = Common::String::format("%s %s", objMan._objectNames[iconIndex], champMan._champions[((Junk *)rawThingPtr)->getChargeCount()]._name); break; default: // German and English versions are the same str = Common::String::format("%s %s", champMan._champions[((Junk *)rawThingPtr)->getChargeCount()]._name, objMan._objectNames[iconIndex]); break; } descString = str; } else if ((thingType == kDMThingTypePotion) && (iconIndex != kDMIconIndicePotionWaterFlask) && (champMan.getSkillLevel((ChampionIndex)_vm->ordinalToIndex(_inventoryChampionOrdinal), kDMSkillPriest) > 1)) { str = ('_' + ((Potion *)rawThingPtr)->getPower() / 40); str += " "; str += objMan._objectNames[iconIndex]; descString = str; } else { descString = objMan._objectNames[iconIndex]; } textMan.printToViewport(134, 68, kDMColorLightestGray, descString.c_str()); drawIconToViewport(iconIndex, 111, 59); _objDescTextYpos = 87; uint16 potentialAttribMask = 0; uint16 actualAttribMask = 0; switch (thingType) { case kDMThingTypeWeapon: { potentialAttribMask = kDMDescriptionMaskCursed | kDMDescriptionMaskPoisoned | kDMDescriptionMaskBroken; Weapon *weapon = (Weapon *)rawThingPtr; actualAttribMask = (weapon->getCursed() << 3) | (weapon->getPoisoned() << 1) | (weapon->getBroken() << 2); if ((iconIndex >= kDMIconIndiceWeaponTorchUnlit) && (iconIndex <= kDMIconIndiceWeaponTorchLit) && (weapon->getChargeCount() == 0)) { switch (_vm->getGameLanguage()) { // localized default: case Common::EN_ANY: drawPanelObjectDescriptionString("(BURNT OUT)"); break; case Common::DE_DEU: drawPanelObjectDescriptionString("(AUSGEBRANNT)"); break; case Common::FR_FRA: drawPanelObjectDescriptionString("(CONSUME)"); break; } } break; } case kDMThingTypeArmour: { potentialAttribMask = kDMDescriptionMaskCursed | kDMDescriptionMaskBroken; Armour *armour = (Armour *)rawThingPtr; actualAttribMask = (armour->getCursed() << 3) | (armour->getBroken() << 2); break; } case kDMThingTypePotion: { potentialAttribMask = kDMDescriptionMaskConsumable; Potion *potion = (Potion *)rawThingPtr; actualAttribMask = dungeon._objectInfos[kDMObjectInfoIndexFirstPotion + potion->getType()].getAllowedSlots(); break; } case kDMThingTypeJunk: { if ((iconIndex >= kDMIconIndiceJunkWater) && (iconIndex <= kDMIconIndiceJunkWaterSkin)) { potentialAttribMask = 0; const char *descStringEN[4] = {"(EMPTY)", "(ALMOST EMPTY)", "(ALMOST FULL)", "(FULL)"}; const char *descStringDE[4] = {"(LEER)", "(FAST LEER)", "(FAST VOLL)", "(VOLL)"}; const char *descStringFR[4] = {"(VIDE)", "(PRESQUE VIDE)", "(PRESQUE PLEINE)", "(PLEINE)"}; Junk *junk = (Junk *)rawThingPtr; switch (_vm->getGameLanguage()) { // localized case Common::DE_DEU: descString = descStringDE[junk->getChargeCount()]; break; case Common::FR_FRA: descString = descStringFR[junk->getChargeCount()]; break; default: descString = descStringEN[junk->getChargeCount()]; break; } drawPanelObjectDescriptionString(descString.c_str()); } else if ((iconIndex >= kDMIconIndiceJunkCompassNorth) && (iconIndex <= kDMIconIndiceJunkCompassWest)) { const static char *directionNameEN[4] = {"NORTH", "EAST", "SOUTH", "WEST"}; const static char *directionNameDE[4] = {"NORDEN", "OSTEN", "SUEDEN", "WESTEN"}; const static char *directionNameFR[4] = {"AU NORD", "A L'EST", "AU SUD", "A L'OUEST"}; potentialAttribMask = 0; switch (_vm->getGameLanguage()) { // localized case Common::DE_DEU: str = "GRUPPE BLICKT NACH "; str += directionNameDE[iconIndex]; break; case Common::FR_FRA: str = "GROUPE FACE "; str += directionNameFR[iconIndex]; break; default: str = "PARTY FACING "; str += directionNameEN[iconIndex]; break; } drawPanelObjectDescriptionString(str.c_str()); } else { Junk *junk = (Junk *)rawThingPtr; potentialAttribMask = kDMDescriptionMaskConsumable; actualAttribMask = dungeon._objectInfos[kDMObjectInfoIndexFirstJunk + junk->getType()].getAllowedSlots(); } break; } default: break; } // end of switch if (potentialAttribMask) { static const char *attribStringEN[4] = {"CONSUMABLE", "POISONED", "BROKEN", "CURSED"}; static const char *attribStringDE[4] = {"ESSBAR", "VERGIFTET", "DEFEKT", "VERFLUCHT"}; static const char *attribStringFR[4] = {"COMESTIBLE", "EMPOISONNE", "BRISE", "MAUDIT"}; const char **attribString = nullptr; switch (_vm->getGameLanguage()) { // localized case Common::DE_DEU: attribString = attribStringDE; break; case Common::FR_FRA: attribString = attribStringFR; break; default: attribString = attribStringEN; break; } char destString[40]; buildObjectAttributeString(potentialAttribMask, actualAttribMask, attribString, destString, "(", ")"); drawPanelObjectDescriptionString(destString); } uint16 weight = dungeon.getObjectWeight(thingToDraw); switch (_vm->getGameLanguage()) { // localized case Common::DE_DEU: str = "WIEGT " + champMan.getStringFromInteger(weight / 10, false, 3) + ","; break; case Common::FR_FRA: str = "PESE " + champMan.getStringFromInteger(weight / 10, false, 3) + "KG,"; break; default: str = "WEIGHS " + champMan.getStringFromInteger(weight / 10, false, 3) + "."; break; } weight -= (weight / 10) * 10; str += champMan.getStringFromInteger(weight, false, 1); switch (_vm->getGameLanguage()) { // localized case Common::FR_FRA: str += "."; break; default: str += " KG."; break; } drawPanelObjectDescriptionString(str.c_str()); } drawPanelArrowOrEye(pressingEye); } void InventoryMan::setDungeonViewPalette() { static const int16 palIndexToLightAmmount[6] = {99, 75, 50, 25, 1, 0}; // @ G0040_ai_Graphic562_PaletteIndexToLightAmount DisplayMan &display = *_vm->_displayMan; ChampionMan &championMan = *_vm->_championMan; DungeonMan &dungeon = *_vm->_dungeonMan; if (dungeon._currMap->_difficulty == 0) { display._dungeonViewPaletteIndex = 0; /* Brightest color palette index */ } else { /* Get torch light power from both hands of each champion in the party */ int16 counter = 4; /* BUG0_01 Coding error without consequence. The hands of four champions are inspected even if there are less champions in the party. No consequence as the data in unused champions is set to 0 and _vm->_objectMan->f32_getObjectType then returns -1 */ Champion *curChampion = championMan._champions; int16 torchesLightPower[8]; int16 *curTorchLightPower = torchesLightPower; while (counter--) { uint16 slotIndex = kDMSlotActionHand + 1; while (slotIndex--) { Thing slotThing = curChampion->_slots[slotIndex]; if ((_vm->_objectMan->getObjectType(slotThing) >= kDMIconIndiceWeaponTorchUnlit) && (_vm->_objectMan->getObjectType(slotThing) <= kDMIconIndiceWeaponTorchLit)) { Weapon *curWeapon = (Weapon *)dungeon.getThingData(slotThing); *curTorchLightPower = curWeapon->getChargeCount(); } else { *curTorchLightPower = 0; } curTorchLightPower++; } curChampion++; } /* Sort torch light power values so that the four highest values are in the first four entries in the array L1045_ai_TorchesLightPower in decreasing order. The last four entries contain the smallest values but they are not sorted */ curTorchLightPower = torchesLightPower; int16 torchIndex = 0; while (torchIndex != 4) { counter = 7 - torchIndex; int16 *L1041_pi_TorchLightPower = &torchesLightPower[torchIndex + 1]; while (counter--) { if (*L1041_pi_TorchLightPower > *curTorchLightPower) { int16 AL1044_ui_TorchLightPower = *L1041_pi_TorchLightPower; *L1041_pi_TorchLightPower = *curTorchLightPower; *curTorchLightPower = AL1044_ui_TorchLightPower; } L1041_pi_TorchLightPower++; } curTorchLightPower++; torchIndex++; } /* Get total light amount provided by the four torches with the highest light power values and by the fifth torch in the array which may be any one of the four torches with the smallest ligh power values */ uint16 torchLightAmountMultiplier = 6; torchIndex = 5; int16 totalLightAmount = 0; curTorchLightPower = torchesLightPower; while (torchIndex--) { if (*curTorchLightPower) { totalLightAmount += (championMan._lightPowerToLightAmount[*curTorchLightPower] << torchLightAmountMultiplier) >> 6; torchLightAmountMultiplier = MAX(0, torchLightAmountMultiplier - 1); } curTorchLightPower++; } totalLightAmount += championMan._party._magicalLightAmount; /* Select palette corresponding to the total light amount */ const int16 *curLightAmount = palIndexToLightAmmount; int16 paletteIndex; if (totalLightAmount > 0) { paletteIndex = 0; /* Brightest color palette index */ while (*curLightAmount++ > totalLightAmount) paletteIndex++; } else { paletteIndex = 5; /* Darkest color palette index */ } display._dungeonViewPaletteIndex = paletteIndex; } display._refreshDungeonViewPaleteRequested = true; } void InventoryMan::decreaseTorchesLightPower() { ChampionMan &championMan = *_vm->_championMan; DungeonMan &dungeon = *_vm->_dungeonMan; bool torchChargeCountChanged = false; int16 championCount = championMan._partyChampionCount; if (championMan._candidateChampionOrdinal) championCount--; Champion *curChampion = championMan._champions; while (championCount--) { int16 slotIndex = kDMSlotActionHand + 1; while (slotIndex--) { int16 iconIndex = _vm->_objectMan->getIconIndex(curChampion->_slots[slotIndex]); if ((iconIndex >= kDMIconIndiceWeaponTorchUnlit) && (iconIndex <= kDMIconIndiceWeaponTorchLit)) { Weapon *curWeapon = (Weapon *)dungeon.getThingData(curChampion->_slots[slotIndex]); if (curWeapon->getChargeCount()) { if (curWeapon->setChargeCount(curWeapon->getChargeCount() - 1) == 0) { curWeapon->setDoNotDiscard(false); } torchChargeCountChanged = true; } } } curChampion++; } if (torchChargeCountChanged) { setDungeonViewPalette(); championMan.drawChangedObjectIcons(); } } void InventoryMan::drawChampionSkillsAndStatistics() { static const char *statisticNamesEN[7] = {"L", "STRENGTH", "DEXTERITY", "WISDOM", "VITALITY", "ANTI-MAGIC", "ANTI-FIRE"}; static const char *statisticNamesDE[7] = {"L", "STAERKE", "FLINKHEIT", "WEISHEIT", "VITALITAET", "ANTI-MAGIE", "ANTI-FEUER"}; static const char *statisticNamesFR[7] = {"L", "FORCE", "DEXTERITE", "SAGESSE", "VITALITE", "ANTI-MAGIE", "ANTI-FEU"}; DisplayMan &display = *_vm->_displayMan; ChampionMan &championMan = *_vm->_championMan; const char **statisticNames; switch (_vm->getGameLanguage()) { // localized case Common::DE_DEU: statisticNames = statisticNamesDE; break; case Common::FR_FRA: statisticNames = statisticNamesFR; break; default: statisticNames = statisticNamesEN; break; } closeChest(); uint16 championIndex = _vm->ordinalToIndex(_inventoryChampionOrdinal); Champion *curChampion = &championMan._champions[championIndex]; display.blitToViewport(display.getNativeBitmapOrGraphic(kDMGraphicIdxPanelEmpty), _boxPanel, k72_byteWidth, kDMColorRed, 73); int16 textPosY = 58; for (uint16 idx = kDMSkillFighter; idx <= kDMSkillWizard; idx++) { int16 skillLevel = MIN((uint16)16, championMan.getSkillLevel(championIndex, idx | kDMIgnoreTemporaryExperience)); if (skillLevel == 1) continue; Common::String displayString; switch (_vm->getGameLanguage()) { // localized case Common::FR_FRA: // Fix original bug: Due to a copy&paste error, the string was concatenate then overwritten be the last part displayString = Common::String::format("%s %s", championMan._baseSkillName[idx], _skillLevelNames[skillLevel - 2]); break; default: // English and German versions are built the same way displayString = Common::String::format("%s %s", _skillLevelNames[skillLevel - 2], championMan._baseSkillName[idx]); break; } _vm->_textMan->printToViewport(108, textPosY, kDMColorLightestGray, displayString.c_str()); textPosY += 7; } textPosY = 86; for (uint16 idx = kDMStatStrength; idx <= kDMStatAntifire; idx++) { _vm->_textMan->printToViewport(108, textPosY, kDMColorLightestGray, statisticNames[idx]); int16 statisticCurrentValue = curChampion->_statistics[idx][kDMStatCurrent]; uint16 statisticMaximumValue = curChampion->_statistics[idx][kDMStatMaximum]; int16 statisticColor; if (statisticCurrentValue < statisticMaximumValue) statisticColor = kDMColorRed; else if (statisticCurrentValue > statisticMaximumValue) statisticColor = kDMColorLightGreen; else statisticColor = kDMColorLightestGray; _vm->_textMan->printToViewport(174, textPosY, (Color)statisticColor, championMan.getStringFromInteger(statisticCurrentValue, true, 3).c_str()); Common::String displayString = "/" + championMan.getStringFromInteger(statisticMaximumValue, true, 3); _vm->_textMan->printToViewport(192, textPosY, kDMColorLightestGray, displayString.c_str()); textPosY += 7; } } void InventoryMan::drawStopPressingMouth() { drawPanel(); _vm->_displayMan->drawViewport(k0_viewportNotDungeonView); _vm->_eventMan->_hideMousePointerRequestCount = 1; _vm->_eventMan->showMouse(); _vm->_eventMan->showMouse(); _vm->_eventMan->showMouse(); } void InventoryMan::drawStopPressingEye() { drawIconToViewport(kDMIconIndiceEyeNotLooking, 12, 13); drawPanel(); _vm->_displayMan->drawViewport(k0_viewportNotDungeonView); Thing leaderHandObject = _vm->_championMan->_leaderHandObject; if (leaderHandObject != _vm->_thingNone) _vm->_objectMan->drawLeaderObjectName(leaderHandObject); _vm->_eventMan->showMouse(); _vm->_eventMan->showMouse(); _vm->_eventMan->showMouse(); } void InventoryMan::clickOnMouth() { static int16 foodAmounts[8] = { 500, /* Apple */ 600, /* Corn */ 650, /* Bread */ 820, /* Cheese */ 550, /* Screamer Slice */ 350, /* Worm round */ 990, /* Drumstick / Shank */ 1400 /* Dragon steak */ }; DisplayMan &display = *_vm->_displayMan; ChampionMan &championMan = *_vm->_championMan; DungeonMan &dungeon = *_vm->_dungeonMan; if (championMan._leaderEmptyHanded) { if (_panelContent == kDMPanelContentFoodWaterPoisoned) return; _vm->_eventMan->_ignoreMouseMovements = true; _vm->_pressingMouth = true; if (!_vm->_eventMan->isMouseButtonDown(kDMMouseButtonLeft)) { _vm->_eventMan->_ignoreMouseMovements = false; _vm->_pressingMouth = false; _vm->_stopPressingMouth = false; } else { _vm->_eventMan->showMouse(); _vm->_eventMan->_hideMousePointerRequestCount = 1; drawPanelFoodWaterPoisoned(); display.drawViewport(k0_viewportNotDungeonView); } return; } if (championMan._candidateChampionOrdinal) return; Thing handThing = championMan._leaderHandObject; if (!getFlag(dungeon._objectInfos[dungeon.getObjectInfoIndex(handThing)]._allowedSlots, kDMMaskMouth)) return; uint16 iconIndex = _vm->_objectMan->getIconIndex(handThing); uint16 handThingType = handThing.getType(); uint16 handThingWeight = dungeon.getObjectWeight(handThing); uint16 championIndex = _vm->ordinalToIndex(_inventoryChampionOrdinal); Champion *curChampion = &championMan._champions[championIndex]; Junk *junkData = (Junk *)dungeon.getThingData(handThing); bool removeObjectFromLeaderHand; if ((iconIndex >= kDMIconIndiceJunkWater) && (iconIndex <= kDMIconIndiceJunkWaterSkin)) { if (!(junkData->getChargeCount())) return; curChampion->_water = MIN(curChampion->_water + 800, 2048); junkData->setChargeCount(junkData->getChargeCount() - 1); removeObjectFromLeaderHand = false; } else if (handThingType == kDMThingTypePotion) removeObjectFromLeaderHand = false; else { junkData->setNextThing(_vm->_thingNone); removeObjectFromLeaderHand = true; } _vm->_eventMan->showMouse(); if (removeObjectFromLeaderHand) championMan.getObjectRemovedFromLeaderHand(); if (handThingType == kDMThingTypePotion) { uint16 potionPower = ((Potion *)junkData)->getPower(); uint16 counter = ((511 - potionPower) / (32 + (potionPower + 1) / 8)) >> 1; uint16 adjustedPotionPower = (potionPower / 25) + 8; /* Value between 8 and 18 */ switch (((Potion *)junkData)->getType()) { case kDMPotionTypeRos: adjustStatisticCurrentValue(curChampion, kDMStatDexterity, adjustedPotionPower); break; case kDMPotionTypeKu: adjustStatisticCurrentValue(curChampion, kDMStatStrength, (((Potion *)junkData)->getPower() / 35) + 5); /* Value between 5 and 12 */ break; case kDMPotionTypeDane: adjustStatisticCurrentValue(curChampion, kDMStatWisdom, adjustedPotionPower); break; case kDMPotionTypeNeta: adjustStatisticCurrentValue(curChampion, kDMStatVitality, adjustedPotionPower); break; case kDMPotionTypeAntivenin: championMan.unpoison(championIndex); break; case kDMPotionTypeMon: curChampion->_currStamina += MIN(curChampion->_maxStamina - curChampion->_currStamina, curChampion->_maxStamina / counter); break; case kDMPotionTypeYa: { adjustedPotionPower += adjustedPotionPower >> 1; if (curChampion->_shieldDefense > 50) adjustedPotionPower >>= 2; curChampion->_shieldDefense += adjustedPotionPower; TimelineEvent newEvent; newEvent._type = kDMEventTypeChampionShield; newEvent._mapTime = _vm->setMapAndTime(dungeon._partyMapIndex, _vm->_gameTime + (adjustedPotionPower * adjustedPotionPower)); newEvent._priority = championIndex; newEvent._Bu._defense = adjustedPotionPower; _vm->_timeline->addEventGetEventIndex(&newEvent); setFlag(curChampion->_attributes, kDMAttributeStatusBox); } break; case kDMPotionTypeEe: { uint16 mana = MIN(900, (curChampion->_currMana + adjustedPotionPower) + (adjustedPotionPower - 8)); if (mana > curChampion->_maxMana) mana -= (mana - MAX(curChampion->_currMana, curChampion->_maxMana)) >> 1; curChampion->_currMana = mana; } break; case kDMPotionTypeVi: { uint16 healWoundIterationCount = MAX(1, (((Potion *)junkData)->getPower() / 42)); curChampion->_currHealth += curChampion->_maxHealth / counter; int16 wounds = curChampion->_wounds; if (wounds) { /* If the champion is wounded */ counter = 10; do { for (uint16 i = 0; i < healWoundIterationCount; i++) curChampion->_wounds &= _vm->getRandomNumber(65536); healWoundIterationCount = 1; } while ((wounds == curChampion->_wounds) && --counter); /* Loop until at least one wound is healed or there are no more heal iterations */ } setFlag(curChampion->_attributes, kDMAttributeLoad | kDMAttributeWounds); } break; case kDMPotionTypeWaterFlask: curChampion->_water = MIN(curChampion->_water + 1600, 2048); break; default: break; } ((Potion *)junkData)->setType(kDMPotionTypeEmptyFlask); } else if ((iconIndex >= kDMIconIndiceJunkApple) && (iconIndex < kDMIconIndiceJunkIronKey)) curChampion->_food = MIN(curChampion->_food + foodAmounts[iconIndex - kDMIconIndiceJunkApple], 2048); if (curChampion->_currStamina > curChampion->_maxStamina) curChampion->_currStamina = curChampion->_maxStamina; if (curChampion->_currHealth > curChampion->_maxHealth) curChampion->_currHealth = curChampion->_maxHealth; if (removeObjectFromLeaderHand) { for (uint16 i = 5; --i; _vm->delay(8)) { /* Animate mouth icon */ _vm->_objectMan->drawIconToScreen(kDMIconIndiceMouthOpen + !(i & 0x0001), 56, 46); _vm->_eventMan->discardAllInput(); if (_vm->_engineShouldQuit) return; display.updateScreen(); } } else { championMan.drawChangedObjectIcons(); championMan._champions[championMan._leaderIndex]._load += dungeon.getObjectWeight(handThing) - handThingWeight; setFlag(championMan._champions[championMan._leaderIndex]._attributes, kDMAttributeLoad); } _vm->_sound->requestPlay(kDMSoundIndexSwallow, dungeon._partyMapX, dungeon._partyMapY, kDMSoundModePlayImmediately); setFlag(curChampion->_attributes, kDMAttributeStatistics); if (_panelContent == kDMPanelContentFoodWaterPoisoned) setFlag(curChampion->_attributes, kDMAttributePanel); championMan.drawChampionState((ChampionIndex)championIndex); _vm->_eventMan->hideMouse(); } void InventoryMan::adjustStatisticCurrentValue(Champion *champ, uint16 statIndex, int16 valueDelta) { int16 delta; if (valueDelta >= 0) { int16 currentValue = champ->_statistics[statIndex][kDMStatCurrent]; if (currentValue > 120) { valueDelta >>= 1;<|fim▁hole|> valueDelta++; } delta = MIN(valueDelta, (int16)(170 - currentValue)); } else { /* BUG0_00 Useless code. The function is always called with valueDelta having a positive value */ delta = MAX(valueDelta, int16(champ->_statistics[statIndex][kDMStatMinimum] - champ->_statistics[statIndex][kDMStatCurrent])); } champ->_statistics[statIndex][kDMStatCurrent] += delta; } void InventoryMan::clickOnEye() { ChampionMan &championMan = *_vm->_championMan; _vm->_eventMan->_ignoreMouseMovements = true; _vm->_pressingEye = true; if (!_vm->_eventMan->isMouseButtonDown(kDMMouseButtonLeft)) { _vm->_eventMan->_ignoreMouseMovements = false; _vm->_pressingEye = false; _vm->_stopPressingEye = false; return; } _vm->_eventMan->discardAllInput(); _vm->_eventMan->hideMouse(); _vm->_eventMan->hideMouse(); _vm->_eventMan->hideMouse(); _vm->delay(8); drawIconToViewport(kDMIconIndiceEyeLooking, 12, 13); if (championMan._leaderEmptyHanded) drawChampionSkillsAndStatistics(); else { _vm->_objectMan->clearLeaderObjectName(); drawPanelObject(championMan._leaderHandObject, true); } _vm->_displayMan->drawViewport(k0_viewportNotDungeonView); } }<|fim▁end|>
if (currentValue > 150) { valueDelta >>= 1; }
<|file_name|>conf.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # google-cloud-functions documentation build configuration file # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os import shlex # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath("..")) # For plugins that can not read conf.py. # See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85 sys.path.insert(0, os.path.abspath(".")) __version__ = "" # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. needs_sphinx = "1.5.5" # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ "sphinx.ext.autodoc", "sphinx.ext.autosummary", "sphinx.ext.intersphinx", "sphinx.ext.coverage", "sphinx.ext.doctest", "sphinx.ext.napoleon", "sphinx.ext.todo", "sphinx.ext.viewcode", "recommonmark", ] # autodoc/autosummary flags autoclass_content = "both" autodoc_default_options = {"members": True} autosummary_generate = True # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = [".rst", ".md"] # The encoding of source files. # source_encoding = 'utf-8-sig' # The root toctree document. root_doc = "index" # General information about the project. project = "google-cloud-functions" copyright = "2019, Google" author = "Google APIs" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The full version, including alpha/beta/rc tags. release = __version__ # The short X.Y version. version = ".".join(release.split(".")[0:2]) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [ "_build", "**/.nox/**/*", "samples/AUTHORING_GUIDE.md", "samples/CONTRIBUTING.md", "samples/snippets/README.rst", ] # The reST default role (used for this markup: `text`) to use for all # documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = "alabaster" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. html_theme_options = { "description": "Google Cloud Client Libraries for google-cloud-functions", "github_user": "googleapis", "github_repo": "python-functions", "github_banner": True, "font_family": "'Roboto', Georgia, sans", "head_font_family": "'Roboto', Georgia, serif", "code_font_family": "'Roboto Mono', 'Consolas', monospace", } # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' # html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value # html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. # html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = "google-cloud-functions-doc" # -- Options for warnings ------------------------------------------------------ suppress_warnings = [ # Temporarily suppress this to avoid "more than one target found for # cross-reference" warning, which are intractable for us to avoid while in # a mono-repo. # See https://github.com/sphinx-doc/sphinx/blob # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 "ref.python" ] # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', # Latex figure (float) alignment #'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ( root_doc, "google-cloud-functions.tex", "google-cloud-functions Documentation", author, "manual", ) ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters.<|fim▁hole|># latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ( root_doc, "google-cloud-functions", "google-cloud-functions Documentation", [author], 1, ) ] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ( root_doc, "google-cloud-functions", "google-cloud-functions Documentation", author, "google-cloud-functions", "google-cloud-functions Library", "APIs", ) ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. # texinfo_no_detailmenu = False # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = { "python": ("https://python.readthedocs.org/en/latest/", None), "google-auth": ("https://googleapis.dev/python/google-auth/latest/", None), "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None,), "grpc": ("https://grpc.github.io/grpc/python/", None), "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", None), "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), } # Napoleon settings napoleon_google_docstring = True napoleon_numpy_docstring = True napoleon_include_private_with_doc = False napoleon_include_special_with_doc = True napoleon_use_admonition_for_examples = False napoleon_use_admonition_for_notes = False napoleon_use_admonition_for_references = False napoleon_use_ivar = False napoleon_use_param = True napoleon_use_rtype = True<|fim▁end|>
<|file_name|>io.py<|end_file_name|><|fim▁begin|>"""Microscoper is a wrapper around bioformats using a forked python-bioformats to extract the raw images from Olympus IX83 CellSense .vsi format, into a more commonly used TIFF format. Images are bundled together according to their channels. This code is used internally in SCB Lab, TCIS, TIFR-H. You're free to modify it and distribute it. """ from __future__ import unicode_literals, print_function import os import collections import bioformats as bf import javabridge as jb import numpy as np import tifffile as tf import tqdm from .args import arguments import xml.dom.minidom def get_files(directory, keyword): """ Returns all the files in the given directory and subdirectories, filtering with the keyword. Usage: >>> all_vsi_files = get_files(".", ".vsi") This will have all the .vsi files in the current directory and all other directories in the current directory. """ file_list = [] for path, subdirs, files in os.walk(directory): for name in files: filename = os.path.join(path, name) if keyword in filename: file_list.append(filename) return sorted(file_list) def get_metadata(filename): """Read the meta data and return the metadata object. """ meta = bf.get_omexml_metadata(filename) metadata = bf.omexml.OMEXML(meta) return metadata def get_channel(metadata, channel): """Return the channel name from the metadata object""" try: channel_name = metadata.image().Pixels.Channel(channel).Name except: return if channel_name is None: return return channel_name.replace("/", "_") def read_images(path, save_directory, big, save_separate): """Reads images from the .vsi and associated files. Returns a dictionary with key as channel, and list of images as values.""" with bf.ImageReader(path) as reader: # Shape of the data c_total = reader.rdr.getSizeC() z_total = reader.rdr.getSizeZ() t_total = reader.rdr.getSizeT() # Since we don't support hyperstacks yet... if 1 not in [z_total, t_total]: raise TypeError("Only 4D images are currently supported.") metadata = get_metadata(path) # This is so we can manually set a description down below. pbar_c = tqdm.tqdm(range(c_total)) for channel in pbar_c: images = [] # Get the channel name, so we can name the file after this. channel_name = get_channel(metadata, channel) # Update the channel progress bar description with the # channel name. pbar_c.set_description(channel_name) for time in tqdm.tqdm(range(t_total), "T"): for z in tqdm.tqdm(range(z_total), "Z"): image = reader.read(c=channel, z=z, t=time, rescale=False) # If there's no metadata on channel name, save channels # with numbers,starting from 0. if channel_name is None: channel_name = str(channel) images.append(image) save_images(np.asarray(images), channel_name, save_directory, big, save_separate) return metadata def save_images(images, channel, save_directory, big=False, save_separate=False): """Saves the images as TIFs with channel name as the filename. Channel names are saved as numbers when names are not available.""" # Make the output directory, if it doesn't alredy exist. if not os.path.exists(save_directory): os.makedirs(save_directory) # Save a file for every image in a stack. if save_separate: filename = save_directory + str(channel) + "_{}.tif" for num, image in enumerate(images): with tf.TiffWriter(filename.format(num+1), bigtiff=big) as f: f.save(image) # Save a single .tif file for all the images in a channel. else: filename = save_directory + str(channel) + ".tif" with tf.TiffWriter(filename, bigtiff=big) as f: f.save(images) def save_metadata(metadata, save_directory): data = xml.dom.minidom.parseString(metadata.to_xml()) pretty_xml_as_string = data.toprettyxml()<|fim▁hole|> with open(save_directory + "metadata.xml", "w") as xmlfile: xmlfile.write(pretty_xml_as_string) def _init_logger(): """This is so that Javabridge doesn't spill out a lot of DEBUG messages during runtime. From CellProfiler/python-bioformats. """ rootLoggerName = jb.get_static_field("org/slf4j/Logger", "ROOT_LOGGER_NAME", "Ljava/lang/String;") rootLogger = jb.static_call("org/slf4j/LoggerFactory", "getLogger", "(Ljava/lang/String;)Lorg/slf4j/Logger;", rootLoggerName) logLevel = jb.get_static_field("ch/qos/logback/classic/Level", "WARN", "Lch/qos/logback/classic/Level;") jb.call(rootLogger, "setLevel", "(Lch/qos/logback/classic/Level;)V", logLevel) def run(): # Add file extensions to this to be able to read different file types. extensions = [".vsi"] arg = arguments() files = get_files(arg.f, arg.k) if 0 == len(files): print("No file matching *{}* keyword.".format(arg.k)) exit() if arg.list: for f in files: print(f) print("======================") print("Total files found:", len(files)) print("======================") exit() jb.start_vm(class_path=bf.JARS, max_heap_size="2G") logger = _init_logger() pbar_files = tqdm.tqdm(files) for path in pbar_files: if not any(_ in path for _ in extensions): continue file_location = os.path.dirname(os.path.realpath(path)) filename = os.path.splitext(os.path.basename(path))[0] save_directory = file_location + "/_{}_/".format(filename) pbar_files.set_description("..." + path[-15:]) # If the user wants to store meta data for existing data, # the user may pass -om or --onlymetadata argument which # will bypass read_images() and get metadata on its own. if arg.onlymetadata: metadata = get_metadata(path) # The default behaviour is to store the files with the # metadata. else: metadata = read_images(path, save_directory, big=arg.big, save_separate=arg.separate) save_metadata(metadata, save_directory) jb.kill_vm()<|fim▁end|>
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>extern crate libc; use libc::*; #[link(name = "genrl_kernels", kind = "static")]<|fim▁hole|> x: *const f32, y: *mut f32, ); pub fn genrl_volatile_average_f32( n: size_t, alpha: f32, x: *const f32, y: *mut f32, ); }<|fim▁end|>
extern "C" { pub fn genrl_volatile_add_f32( n: size_t,
<|file_name|>clean_data_for_academic_analysis.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # This file is part of OpenHatch. # Copyright (C) 2010 OpenHatch, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # 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 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/>. ### The purpose of this script is to create a version of the database ### that helps a U Mass Amherst researcher look through the OpenHatch ### data and perform text classification and other text analysis. ### To protect our users' privacy, we: ### * set the password column to the empty string ### * set the email column to the empty string ### * delete (from the database) any PortfolioEntry that is_deleted ### * delete (from the database) any Citation that is_deleted ### * delete all WebResponse objects<|fim▁hole|>### set the email and password columns to the empty string for user in django.contrib.auth.models.User.objects.all(): user.email = '' user.password = '' user.save() ### delete PortfolioEntry instances that is_deleted for pfe in mysite.profile.models.PortfolioEntry.objects.all(): if pfe.is_deleted: pfe.delete() ### delete Citation instances that is_deleted for citation in mysite.profile.models.Citation.objects.all(): if citation.is_deleted: citation.delete() ### delete all WebResponse objects for wr in mysite.customs.models.WebResponse.objects.all(): wr.delete()<|fim▁end|>
import mysite.profile.models import django.contrib.auth.models
<|file_name|>true_primitives.py<|end_file_name|><|fim▁begin|>from som.interp_type import is_ast_interpreter from som.primitives.primitives import Primitives from som.vm.globals import trueObject, falseObject, nilObject from som.vmobjects.primitive import UnaryPrimitive, BinaryPrimitive, TernaryPrimitive if is_ast_interpreter(): from som.vmobjects.block_ast import AstBlock as _Block else: from som.vmobjects.block_bc import BcBlock as _Block def _not(_rcvr): return falseObject def _or(_rcvr, _arg): return trueObject def _and_and_if_true(_rcvr, arg): if isinstance(arg, _Block): block_method = arg.get_method() return block_method.invoke_1(arg) return arg def _if_false(_rcvr, _arg): return nilObject def _if_true_if_false(_rcvr, true_block, _false_block): if isinstance(true_block, _Block): block_method = true_block.get_method() return block_method.invoke_1(true_block)<|fim▁hole|>class TruePrimitivesBase(Primitives): def install_primitives(self): self._install_instance_primitive(UnaryPrimitive("not", _not)) self._install_instance_primitive(BinaryPrimitive("or:", _or)) self._install_instance_primitive(BinaryPrimitive("||", _or)) self._install_instance_primitive(BinaryPrimitive("and:", _and_and_if_true)) self._install_instance_primitive(BinaryPrimitive("&&", _and_and_if_true)) self._install_instance_primitive(BinaryPrimitive("ifTrue:", _and_and_if_true)) self._install_instance_primitive(BinaryPrimitive("ifFalse:", _if_false)) self._install_instance_primitive( TernaryPrimitive("ifTrue:ifFalse:", _if_true_if_false) )<|fim▁end|>
return true_block
<|file_name|>distinfo.py<|end_file_name|><|fim▁begin|># 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 3 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. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, see # <http://www.gnu.org/licenses/>. """ unit tests for javatools/distinfo.py author: Konstantin Shemyak <[email protected]> license: LGPL v.3 """ import os<|fim▁hole|>from . import get_data_fn from javatools.distinfo import main class DistinfoTest(TestCase): dist = get_data_fn(os.path.join("test_distinfo", "dist1")) # classinfo-specific option is accepted: def test_classinfo_options(self): self.assertEqual(0, main(["argv0", "-p", self.dist])) # jarinfo-specific option is accepted: def test_jarinfo_options(self): self.assertEqual(0, main(["argv0", "--jar-classes", self.dist])) # distinfo-specific option is accepted: def test_distinfo_options(self): self.assertEqual(0, main(["argv0", "--dist-provides", self.dist]))<|fim▁end|>
from unittest import TestCase
<|file_name|>FtpResponse.java<|end_file_name|><|fim▁begin|>package org.matmaul.freeboxos.ftp;<|fim▁hole|>public class FtpResponse { public static class FtpConfigResponse extends Response<FtpConfig> {} }<|fim▁end|>
import org.matmaul.freeboxos.internal.Response;
<|file_name|>nondefaultNamespaces-05.js<|end_file_name|><|fim▁begin|>var assert = require('assert')<|fim▁hole|> , feed = __dirname + '/feeds/unknown-namespace.atom' , meta = {} , articles = {} ; describe('feedparser', function(){ describe('nondefaultnamespace Test case 3: default namespace Atom; XHTML namespace mapped to a prefix; FooML namespace default in the namespace DIV', function(){ before(function(done){ feedparser.parseFile(feed, function (error, _meta, _articles) { assert.ifError(error); meta = _meta; articles = _articles; done(); }); }); describe('article', function(){ it('should have the expected title', function() { assert.equal(articles[0].title, 'This entry contains XHTML-looking markup that is not XHTML'); }); it('should have the expected description', function(){ assert.ok(articles[0].description.match(/^<h:div xmlns="http:\/\/hsivonen.iki.fi\/FooML">/)); assert.ok(articles[0].description.match(/<h:li>This is an XHTML list item./)); assert.ok(articles[0].description.match(/<li>This is not an XHTML list item./)); }); }); }); describe('nondefaultnamespace using static methods Test case 3: default namespace Atom; XHTML namespace mapped to a prefix; FooML namespace default in the namespace DIV', function(){ before(function(done){ FeedParser.parseFile(feed, function (error, _meta, _articles) { assert.ifError(error); meta = _meta; articles = _articles; done(); }); }); describe('article', function(){ it('should have the expected title', function() { assert.equal(articles[0].title, 'This entry contains XHTML-looking markup that is not XHTML'); }); it('should have the expected description', function(){ assert.ok(articles[0].description.match(/^<h:div xmlns="http:\/\/hsivonen.iki.fi\/FooML">/)); assert.ok(articles[0].description.match(/<h:li>This is an XHTML list item./)); assert.ok(articles[0].description.match(/<li>This is not an XHTML list item./)); }); }); }); });<|fim▁end|>
, FeedParser = require('../') , feedparser = new FeedParser()
<|file_name|>bitcoin_sv.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="sv" version="2.1"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About bitconnect</source> <translation>Vad du behöver veta om bitconnect</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;bitconnect&lt;/b&gt; version</source> <translation>&lt;b&gt;bitconnect&lt;/b&gt; version</translation> </message> <message> <location line="+41"/> <source>Copyright © 2009-2014 The Bitcoin developers Copyright © 2012-2014 The NovaCoin developers Copyright © 2014 The bitconnect developers</source> <translation>Copyright © 2009-2014 The Bitcoin developers Copyright © 2012-2014 The NovaCoin developers Copyright © 2014 The bitconnect developers</translation> </message> <message> <location line="+15"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation> Detta är experimentell mjukvara. Distribuerad under mjukvarulicensen MIT/X11, se den medföljande filen COPYING eller http://www.opensource.org/licenses/mit-license.php. Denna produkten innehåller mjukvara utvecklad av OpenSSL Project för användning i OpenSSL Toolkit (http://www.openssl.org/) och kryptografisk mjukvara utvecklad av Eric Young ([email protected]) samt UPnP-mjukvara skriven av Thomas Bernard.</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Adressbok</translation> </message> <message> <location line="+22"/> <source>Double-click to edit address or label</source> <translation>Dubbel-klicka för att ändra adressen eller etiketten</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Skapa ny adress</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopiera den markerade adressen till systemets Urklipp</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>Ny adress</translation> </message> <message> <location line="-46"/> <source>These are your bitconnect addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Dessa är dina bitconnect adesser för att mottaga betalningsförsändelser. Du kan även använda olika adresser för varje avsändare för att enkelt hålla koll på vem som har skickat en betalning.</translation> </message> <message> <location line="+60"/> <source>&amp;Copy Address</source> <translation>&amp;Kopiera adress</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Visa &amp;QR kod</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a bitconnect address</source> <translation>Signera ett meddelande för att bevisa att du äger bitconnect adressen</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Signera &amp;Meddelande</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Ta bort den valda adressen från listan</translation> </message> <message> <location line="-14"/> <source>Verify a message to ensure it was signed with a specified bitconnect address</source> <translation>Verifiera ett meddelande för att försäkra dig över att det var signerat av en specifik bitconnect adress</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>&amp;Verifiera meddelande</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Radera</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+65"/> <source>Copy &amp;Label</source> <translation>Kopiera &amp;etikett</translation> </message> <message> <location line="+2"/> <source>&amp;Edit</source> <translation>&amp;Editera</translation> </message> <message> <location line="+250"/> <source>Export Address Book Data</source> <translation>Exportera adressboken</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Kommaseparerad fil (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Exportera felmeddelanden</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Kunde inte skriva till fil %1</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Etikett</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adress</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(Ingen etikett)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Lösenords Dialog</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Ange lösenord</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nytt lösenord</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Upprepa nytt lösenord</translation> </message> <message> <location line="+33"/> <source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source> <translation>Avaktiverar &quot;sendmoney&quot; om ditt operativsystem har blivit äventyrat. ger ingen verklig säkerhet.</translation> </message> <message> <location line="+3"/> <source>For staking only</source> <translation>Endast för &quot;staking&quot;</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+35"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Ange plånbokens nya lösenord. &lt;br/&gt; Använd ett lösenord på &lt;b&gt;10 eller fler slumpmässiga tecken,&lt;/b&gt; eller &lt;b&gt;åtta eller fler ord.&lt;/b&gt;</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Kryptera plånbok</translation> </message> <message> <location line="+7"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Denna operation behöver din plånboks lösenord för att låsa upp plånboken.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Lås upp plånbok</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Denna operation behöver din plånboks lösenord för att dekryptera plånboken.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Dekryptera plånbok</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Ändra lösenord</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Ange plånbokens gamla och nya lösenord.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Bekräfta kryptering av plånbok</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR COINS&lt;/b&gt;!</source> <translation>Varning: Om du krypterar plånboken och glömmer lösenordet, kommer du att &lt;b&gt;FÖRLORA ALLA COINS&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Är du säker på att du vill kryptera din plånbok?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>VIKTIGT: Alla tidigare säkerhetskopior du har gjort av plånbokens fil ska ersättas med den nya genererade, krypterade plånboks filen. Av säkerhetsskäl kommer tidigare säkerhetskopior av den okrypterade plånboks filen blir oanvändbara när du börjar använda en ny, krypterad plånbok.</translation> </message> <message> <location line="+103"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Varning: Caps Lock är påslaget!</translation> </message> <message> <location line="-133"/> <location line="+60"/> <source>Wallet encrypted</source> <translation>Plånboken är krypterad</translation> </message> <message> <location line="-58"/> <source>bitconnect will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source> <translation>bitconnect plånboken kommer nu att stängas för att slutföra krypteringen: Kom ihåg att även en krypterad plånboks säkerhet kan äventyras genom keyloggers eller dylika malwares.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+44"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Kryptering av plånbok misslyckades</translation> </message> <message> <location line="-56"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Kryptering av plånbok misslyckades på grund av ett internt fel. Din plånbok blev inte krypterad.</translation> </message> <message> <location line="+7"/> <location line="+50"/> <source>The supplied passphrases do not match.</source> <translation>De angivna lösenorden överensstämmer inte.</translation> </message> <message> <location line="-38"/> <source>Wallet unlock failed</source> <translation>Upplåsning av plånbok misslyckades</translation> </message> <message> <location line="+1"/> <location line="+12"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Lösenordet för dekryptering av plånbok var felaktig.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Dekryptering av plånbok misslyckades</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Plånbokens lösenord har ändrats.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+280"/> <source>Sign &amp;message...</source> <translation>Signera &amp;meddelande...</translation> </message> <message> <location line="+242"/> <source>Synchronizing with network...</source> <translation>Synkroniserar med nätverk...</translation> </message> <message> <location line="-308"/> <source>&amp;Overview</source> <translation>&amp;Översikt</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Visa översiktsvy av plånbok</translation> </message> <message> <location line="+17"/> <source>&amp;Transactions</source> <translation>&amp;Transaktioner</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Bläddra i transaktionshistorik</translation> </message> <message> <location line="+5"/> <source>&amp;Address Book</source> <translation>&amp;Adress bok</translation> </message> <message> <location line="+1"/> <source>Edit the list of stored addresses and labels</source> <translation>Editera listan över sparade adresser och deras namn</translation> </message> <message> <location line="-13"/> <source>&amp;Receive coins</source> <translation>&amp;Ta emot coins</translation> </message> <message> <location line="+1"/> <source>Show the list of addresses for receiving payments</source> <translation>Visa adresslista för att mottaga betalningar</translation> </message> <message> <location line="-7"/> <source>&amp;Send coins</source> <translation>&amp;Skicka coins</translation> </message> <message> <location line="+35"/> <source>E&amp;xit</source> <translation>&amp;Avsluta</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Avsluta programmet</translation> </message> <message> <location line="+4"/> <source>Show information about bitconnect</source> <translation>Visa information om bitconnect</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Om &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Visa information om Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Alternativ...</translation> </message> <message> <location line="+4"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Kryptera plånbok...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Säkerhetskopiera plånbok...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Byt Lösenord...</translation> </message> <message numerus="yes"> <location line="+250"/> <source>~%n block(s) remaining</source> <translation><numerusform>~%n block remaining</numerusform><numerusform>~%n block kvar</numerusform></translation> </message> <message> <location line="+6"/> <source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source> <translation>Laddat ner %1 av %2 block av transaktions-historiken (%3% klart)</translation> </message> <message> <location line="-247"/> <source>&amp;Export...</source> <translation>&amp;Exportera...</translation> </message> <message> <location line="-62"/> <source>Send coins to a bitconnect address</source> <translation>Skicka coins till en bitconnect adress</translation> </message> <message> <location line="+45"/> <source>Modify configuration options for bitconnect</source> <translation>Modifiera konfigurations-alternativ för bitconnect</translation> </message> <message> <location line="+18"/> <source>Export the data in the current tab to a file</source> <translation>Exportera datan i tabben till en fil</translation> </message> <message> <location line="-14"/> <source>Encrypt or decrypt wallet</source> <translation>Kryptera eller avkryptera plånbok</translation> </message> <message> <location line="+3"/> <source>Backup wallet to another location</source> <translation>Säkerhetskopiera plånboken till en annan plats</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Byt lösenord för kryptering av plånbok</translation> </message> <message> <location line="+10"/> <source>&amp;Debug window</source> <translation>&amp;Debug fönster</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Öppna debug- och diagnostikkonsolen</translation> </message> <message> <location line="-5"/> <source>&amp;Verify message...</source> <translation>&amp;Verifiera meddelande...</translation> </message> <message> <location line="-200"/> <source>bitconnect</source> <translation>bitconnect</translation> </message> <message> <location line="+0"/> <source>Wallet</source> <translation>Plånbok</translation> </message> <message> <location line="+178"/> <source>&amp;About bitconnect</source> <translation>&amp;Om bitconnect</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;Visa / Göm</translation> </message> <message> <location line="+9"/> <source>Unlock wallet</source> <translation>Lås upp plånbok</translation> </message> <message> <location line="+1"/> <source>&amp;Lock Wallet</source> <translation>&amp;Lås plånbok</translation> </message> <message> <location line="+1"/> <source>Lock wallet</source> <translation>Lås plånbok</translation> </message> <message> <location line="+34"/> <source>&amp;File</source> <translation>&amp;Arkiv</translation> </message> <message> <location line="+8"/> <source>&amp;Settings</source> <translation>&amp;Inställningar</translation> </message> <message> <location line="+8"/> <source>&amp;Help</source> <translation>&amp;Hjälp</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Verktygsfält för Tabbar</translation> </message> <message> <location line="+8"/> <source>Actions toolbar</source> <translation>Verktygsfält för handlingar</translation> </message> <message> <location line="+13"/> <location line="+9"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+0"/> <location line="+60"/> <source>bitconnect client</source> <translation>bitconnect klient</translation> </message> <message numerus="yes"> <location line="+70"/> <source>%n active connection(s) to bitconnect network</source> <translation><numerusform>%n aktiv anslutning till bitconnect nätverket</numerusform><numerusform>%n aktiva anslutning till bitconnect nätverket</numerusform></translation> </message> <message> <location line="+40"/> <source>Downloaded %1 blocks of transaction history.</source> <translation>Laddade ner %1 block av transaktionshistoriken.</translation> </message> <message> <location line="+413"/> <source>Staking.&lt;br&gt;Your weight is %1&lt;br&gt;Network weight is %2&lt;br&gt;Expected time to earn reward is %3</source> <translation>Staking.&lt;br&gt;Din vikt är %1&lt;br&gt;Nätverkets vikt är %2&lt;br&gt;Uppskattad tid för att få belöning är %3</translation> </message> <message> <location line="+6"/> <source>Not staking because wallet is locked</source> <translation>Ingen staking för att plånboken är låst</translation> </message> <message> <location line="+2"/> <source>Not staking because wallet is offline</source> <translation>Ingen staking för att plånboken är offline</translation> </message> <message> <location line="+2"/> <source>Not staking because wallet is syncing</source> <translation>Ingen staking för att plånboken synkroniseras</translation> </message> <message> <location line="+2"/> <source>Not staking because you don&apos;t have mature coins</source> <translation>Ingen staking för att dina coins är ännu inte föråldrade</translation> </message> <message numerus="yes"> <location line="-403"/> <source>%n second(s) ago</source> <translation><numerusform>%n sekund sen</numerusform><numerusform>%n sekunder sen</numerusform></translation> </message> <message> <location line="-284"/> <source>&amp;Unlock Wallet...</source> <translation>Lås &amp;Upp plånboken</translation> </message> <message numerus="yes"> <location line="+288"/> <source>%n minute(s) ago</source> <translation><numerusform>%n minut sen</numerusform><numerusform>%n minuter sen</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s) ago</source> <translation><numerusform>%n timme sen</numerusform><numerusform>%n timmar sen</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s) ago</source> <translation><numerusform>%n dag sen</numerusform><numerusform>%n dagar sen</numerusform></translation> </message> <message> <location line="+6"/> <source>Up to date</source> <translation>Uppdaterad</translation> </message> <message> <location line="+7"/> <source>Catching up...</source> <translation>Hämtar senaste...</translation> </message> <message> <location line="+10"/> <source>Last received block was generated %1.</source> <translation>Senaste mottagna block genererades %1.</translation> </message> <message> <location line="+59"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation>Denna transaktion är över gränsen. Du kan ändå skicka den med en %1 avgift, som går till noderna som processerar din transaktion och hjälper till med att upprätthålla nätverket. Vill du betala denna avgift?</translation> </message> <message> <location line="+5"/> <source>Confirm transaction fee</source> <translation>Bekräfta transaktionsavgiften</translation> </message> <message> <location line="+27"/> <source>Sent transaction</source> <translation>Transaktion skickad</translation> </message> <message> <location line="+1"/> <source>Incoming transaction</source> <translation>Inkommande transaktion</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Datum: %1 Belopp: %2 Typ: %3 Adress: %4 </translation> </message> <message> <location line="+100"/> <location line="+15"/> <source>URI handling</source> <translation>URI hantering</translation> </message> <message> <location line="-15"/> <location line="+15"/> <source>URI can not be parsed! This can be caused by an invalid bitconnect address or malformed URI parameters.</source> <translation>URI:n kan inte tolkas! Detta kan bero på en ogiltig bitconnect adress eller felaktiga URI parametrar.</translation> </message> <message> <location line="+18"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Denna plånbok är &lt;b&gt;krypterad&lt;/b&gt; och för närvarande &lt;b&gt;olåst&lt;/b&gt;</translation> </message> <message> <location line="+10"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Denna plånbok är &lt;b&gt;krypterad&lt;/b&gt; och för närvarande &lt;b&gt;låst&lt;/b&gt;</translation> </message> <message> <location line="+25"/> <source>Backup Wallet</source> <translation>Säkerhetskopiera plånbok</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>Plånboksdata (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>Säkerhetskopieringen misslyckades</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>Ett fel uppstod vid sparandet av plånboken till den nya platsen.</translation> </message> <message numerus="yes"> <location line="+76"/> <source>%n second(s)</source> <translation><numerusform>%n sekund</numerusform><numerusform>%n sekunder</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n minute(s)</source> <translation><numerusform>%n minut</numerusform><numerusform>%n minuter</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s)</source> <translation><numerusform>%n timme</numerusform><numerusform>%n timmar</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n dag</numerusform><numerusform>%n dagar</numerusform></translation> </message> <message> <location line="+18"/> <source>Not staking</source> <translation>Ingen staking</translation> </message> <message> <location filename="../bitcoin.cpp" line="+109"/> <source>A fatal error occurred. bitconnect can no longer continue safely and will quit.</source> <translation>Ett fatalt fel uppstod. bitconnect kan inte fortsätta och stänger programmet.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+90"/> <source>Network Alert</source> <translation>Nätverkslarm</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control</source> <translation>Coin kontroll</translation> </message> <message> <location line="+31"/> <source>Quantity:</source> <translation>Antal:</translation> </message> <message> <location line="+32"/> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <location line="+48"/> <source>Amount:</source> <translation>Belopp:</translation> </message> <message> <location line="+32"/> <source>Priority:</source> <translation>Prioritet:</translation> </message> <message> <location line="+48"/> <source>Fee:</source> <translation>Avgift:</translation> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation>Låg utskrift:</translation> </message> <message> <location filename="../coincontroldialog.cpp" line="+551"/> <source>no</source> <translation>nej</translation> </message> <message> <location filename="../forms/coincontroldialog.ui" line="+51"/> <source>After Fee:</source> <translation>Efter avgift:</translation> </message> <message> <location line="+35"/> <source>Change:</source> <translation>Ändra:</translation> </message> <message> <location line="+69"/> <source>(un)select all</source> <translation>välj/avvälj alla</translation> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation>Träd visning</translation> </message> <message> <location line="+16"/> <source>List mode</source> <translation>List visning</translation> </message> <message> <location line="+45"/> <source>Amount</source> <translation>Mängd</translation> </message> <message> <location line="+5"/> <source>Label</source> <translation>etikett</translation> </message> <message> <location line="+5"/> <source>Address</source> <translation>Adress</translation> </message> <message> <location line="+5"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation>Bekräftelser</translation> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation>Bekräftad</translation> </message> <message> <location line="+5"/> <source>Priority</source> <translation>Prioritet</translation> </message> <message> <location filename="../coincontroldialog.cpp" line="-515"/> <source>Copy address</source> <translation>Kopiera adress</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopiera etikett</translation> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation>Kopiera belopp</translation> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation>Kopiera transaktions ID</translation> </message> <message> <location line="+24"/> <source>Copy quantity</source> <translation>Kopiera antal</translation> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation>Kopiera avgift</translation> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation>Kopiera efter avgift</translation> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation>Kopiera bytes</translation> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation>Kopiera prioritet</translation> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation>Kopiera låg utskrift</translation> </message> <message> <location line="+1"/> <source>Copy change</source> <translation>Kopiera förändringarna</translation> </message> <message> <location line="+317"/> <source>highest</source> <translation>högst</translation> </message> <message> <location line="+1"/> <source>high</source> <translation>hög</translation> </message> <message> <location line="+1"/> <source>medium-high</source> <translation>medium-hög</translation> </message> <message> <location line="+1"/> <source>medium</source> <translation>medium</translation> </message> <message> <location line="+4"/> <source>low-medium</source> <translation>låg-medium</translation> </message> <message> <location line="+1"/> <source>low</source> <translation>låg</translation> </message> <message> <location line="+1"/> <source>lowest</source> <translation>lägsta</translation> </message> <message> <location line="+155"/> <source>DUST</source> <translation>STOFT</translation> </message> <message> <location line="+0"/> <source>yes</source> <translation>ja</translation> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is bigger than 10000 bytes. This means a fee of at least %1 per kb is required. Can vary +/- 1 Byte per input.</source> <translation>Denna label blir röd, om storleken på transaktionen är över 10000 bytes. Detta betyder att en avgift på %1 per kb måste betalas. Kan variera +/- 1 Byte per ingång.</translation> </message> <message> <location line="+1"/> <source>Transactions with higher priority get more likely into a block. This label turns red, if the priority is smaller than &quot;medium&quot;. This means a fee of at least %1 per kb is required.</source> <translation>Transaktioner med en högre prioritet har en större sannolikhet att bli adderat till ett block. Denna label blir röd, om prioriteten är lägre än &quot;medium&quot;. Detta betyder att en avgift på minst %1 krävs.</translation> </message> <message> <location line="+1"/> <source>This label turns red, if any recipient receives an amount smaller than %1. This means a fee of at least %2 is required. Amounts below 0.546 times the minimum relay fee are shown as DUST.</source> <translation>Denna label blir röd, om en mottagare får en mängd mindre än %1 Detta betyder att en avgift på minst %2 krävs. Mängder under 0,546 gånger minimiavgiften visas som DUST.</translation> </message> <message> <location line="+1"/> <source>This label turns red, if the change is smaller than %1. This means a fee of at least %2 is required.</source> <translation>Denna label blir röd, om ändringen är mindre än %1. Detta betyder att en avgift på minst %2 krävs.</translation> </message> <message> <location line="+37"/> <location line="+66"/> <source>(no label)</source> <translation>(Ingen etikett)</translation> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation>ändra från %1(%2)</translation> </message> <message> <location line="+1"/> <source>(change)</source> <translation>(ändra)</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Redigera Adress</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Etikett</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Namnet som kopplats till denna bitconnect-adress</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Adress</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Adressen är kopplad till detta inlägg i adressboken. Denna kan endast ändras för skickande adresser.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+20"/> <source>New receiving address</source> <translation>Ny mottagaradress</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Ny avsändaradress</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Redigera mottagaradress</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Redigera avsändaradress</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Den angivna adressen &quot;%1&quot; finns redan i adressboken.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid bitconnect address.</source> <translation>Den inslagna adressen &quot;%1&quot; är inte en giltig bitconnect adress.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Plånboken kunde inte låsas upp.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Misslyckades med generering av ny nyckel.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+420"/> <location line="+12"/> <source>bitconnect-Qt</source> <translation>bitconnect-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>version</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Användning:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>Command-line alternativ</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>UI alternativ</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Ställ in språk, t.ex. &quot;de_DE&quot; (förval: systemets språk)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Starta som minimerad</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Visa startscreen vid start (förval: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Alternativ</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Allmänt</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation>Valfri transaktionsavgift per kB som försäkrar att transaktionen behandlas snabbt. De flesta transaktionerna är 1 kB. En avgift på 0,01 är rekommenderad.</translation> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Betala överförings&amp;avgift</translation> </message> <message> <location line="+31"/> <source>Reserved amount does not participate in staking and is therefore spendable at any time.</source> <translation>Reserverad mängd deltar inte i stake-processen och kan därför spenderas när som helst.</translation> </message> <message> <location line="+15"/> <source>Reserve</source> <translation>Reservera</translation> </message> <message> <location line="+31"/> <source>Automatically start bitconnect after logging in to the system.</source> <translation>Starta bitconnect automatiskt vid inloggning.</translation> </message> <message> <location line="+3"/> <source>&amp;Start bitconnect on system login</source> <translation>&amp;Starta bitconnect vid inloggning</translation> </message> <message> <location line="+7"/> <source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source> <translation>Koppla ifrån block och adress-databaserna vid nedstängning. Detta betyder att det kan flyttas till en annan datamapp men saktar ner avstängningen. Plånboken är alltid frånkopplad.</translation> </message> <message> <location line="+3"/> <source>&amp;Detach databases at shutdown</source> <translation>Koppla bort &amp;databaserna vid nedkörning</translation> </message> <message> <location line="+21"/> <source>&amp;Network</source> <translation>&amp;Nätverk</translation> </message> <message> <location line="+6"/> <source>Automatically open the bitconnect client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Öppna automatiskt bitconnect klientens port på routern. Detta fungerar endast om din router stödjer UPnP och det är aktiverat.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Tilldela port med hjälp av &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the bitconnect network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Anslut till bitconnect nätverket via en SOCKS proxy (t.ex. när du ansluter genom Tor).</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>&amp;Anslut genom en SOCKS proxy:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>Proxy-&amp;IP: </translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>Proxyns IP-adress (t.ex. 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Port: </translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Proxyns port (t.ex. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS &amp;Version:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>SOCKS version av proxyn (t.ex. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Fönster</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Visa endast en systemfältsikon vid minimering.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimera till systemfältet istället för aktivitetsfältet</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Minimera applikationen istället för att stänga ner den när fönstret stängs. Detta innebär att programmet fotrsätter att köras tills du väljer Avsluta i menyn.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>M&amp;inimera vid stängning</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Visa</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>Användargränssnittets &amp;språk: </translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting bitconnect.</source> <translation>Användargränssnittets språk kan ställas in här. Inställningen börjar gälla efter omstart av bitconnect.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Måttenhet att visa belopp i: </translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Välj en måttenhet att visa när du skickar mynt.</translation> </message> <message> <location line="+9"/> <source>Whether to show bitconnect addresses in the transaction list or not.</source> <translation>Om bitconnect adresser skall visas i transaktionslistan eller inte.</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Visa adresser i transaktionslistan</translation> </message> <message> <location line="+7"/> <source>Whether to show coin control features or not.</source> <translation>Om coin kontrollinställningar skall visas eller inte.</translation> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only!)</source> <translation>Visa coin kontrollinställningar (endast avancerade användare!)</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Avbryt</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;Verkställ</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+55"/> <source>default</source> <translation>standard</translation> </message> <message> <location line="+149"/> <location line="+9"/> <source>Warning</source> <translation>Varning</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting bitconnect.</source> <translation>Inställningen börjar gälla efter omstart av bitconnect.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>Den medföljande proxy adressen är ogiltig.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Formulär</translation> </message> <message> <location line="+33"/> <location line="+231"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the bitconnect network after a connection is established, but this process has not completed yet.</source> <translation>Den visade informationen kan vara gammal. Din plånbok synkroniseras automatiskt med bitconnect nätverket efter att en anslutning skapats, men denna process är inte klar än.</translation> </message> <message> <location line="-160"/> <source>Stake:</source> <translation>Stake:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Obekräftat:</translation> </message> <message> <location line="-107"/> <source>Wallet</source> <translation>Plånbok</translation> </message> <message> <location line="+49"/> <source>Spendable:</source> <translation>Spenderbart:</translation> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation>Ditt tillgängliga saldo</translation> </message> <message> <location line="+71"/> <source>Immature:</source> <translation>Omogen:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Den genererade balansen som ännu inte har mognat</translation> </message> <message> <location line="+20"/> <source>Total:</source> <translation>Totalt:</translation> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation>Ditt nuvarande totala saldo</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Nyligen genomförda transaktioner&lt;/b&gt;</translation> </message> <message> <location line="-108"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Totala antalet transaktioner inte har blivit bekräftade än och därför inte räknas mot det totala saldot</translation> </message> <message> <location line="-29"/> <source>Total of coins that was staked, and do not yet count toward the current balance</source> <translation>Antal coins som var i stake-processen, och räknas ännu inte till nuvarande saldo</translation> </message> <message> <location filename="../overviewpage.cpp" line="+113"/> <location line="+1"/> <source>out of sync</source> <translation>osynkroniserad</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>QR-Kod Dialog</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Begär Betalning</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Belopp:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Etikett:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Meddelande:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Spara Som...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Fel vid skapande av QR-kod från URI.</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>Den angivna mängden är felaktig, var vänlig kontrollera.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>URI:n är för lång, försök minska texten för etikett / meddelande.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Spara QR-kod</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG Bilder (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Klientnamn</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+348"/> <source>N/A</source> <translation>ej tillgänglig</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Klient-version</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Information</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Använder OpenSSL version</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Uppstartstid</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Nätverk</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Antalet anslutningar</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>På testnet</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Blockkedja</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Aktuellt antal block</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Beräknade totala block</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Sista blocktid</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Öppna</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Kommandoradsalternativ</translation> </message> <message> <location line="+7"/> <source>Show the bitconnect-Qt help message to get a list with possible bitconnect command-line options.</source> <translation>Visa bitconnect-Qt hjälp meddelandet för att få en lista över möjliga bitconnect kommandoradsalternativ.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>&amp;Visa</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Konsol</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Kompileringsdatum</translation> </message> <message> <location line="-104"/> <source>bitconnect - Debug window</source> <translation>bitconnect - Felsökningsfönster</translation> </message> <message> <location line="+25"/> <source>bitconnect Core</source> <translation>bitconnect Core</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Debugloggfil</translation> </message> <message> <location line="+7"/> <source>Open the bitconnect debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Öppna bitconnect felsöknings-loggfilen från nuvarande data mapp. Detta kan kan ta ett par minuter för stora log filer.</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Rensa konsollen</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-33"/> <source>Welcome to the bitconnect RPC console.</source> <translation>Välkommen till bitconnect RPC konsoll.</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Använd upp- och ner-pilarna för att navigera i historiken, och &lt;b&gt;Ctrl-L&lt;/b&gt; för att rensa skärmen.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Skriv &lt;b&gt;help&lt;/b&gt; för en översikt av alla kommandon.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+182"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Skicka pengar</translation> </message> <message> <location line="+76"/> <source>Coin Control Features</source> <translation>Coin kontrollinställningar</translation> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation>Ingångar...</translation> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation>automatiskt vald</translation> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation>Otillräckligt saldo!</translation> </message> <message> <location line="+77"/> <source>Quantity:</source> <translation>Antal:</translation> </message> <message> <location line="+22"/> <location line="+35"/> <source>0</source> <translation>0</translation> </message> <message> <location line="-19"/> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <location line="+51"/> <source>Amount:</source> <translation>Belopp:</translation> </message> <message> <location line="+22"/> <location line="+86"/> <location line="+86"/> <location line="+32"/> <source>0.00 BC</source> <translation>123.456 BC {0.00 ?}</translation> </message> <message> <location line="-191"/> <source>Priority:</source> <translation>Prioritet:</translation> </message> <message> <location line="+19"/> <source>medium</source> <translation>mellan</translation> </message> <message> <location line="+32"/> <source>Fee:</source> <translation>Avgift:</translation> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation>Låg utmatning:</translation> </message> <message> <location line="+19"/> <source>no</source> <translation>nej</translation> </message> <message> <location line="+32"/> <source>After Fee:</source> <translation>Efter avgift:</translation> </message> <message> <location line="+35"/> <source>Change</source> <translation>Ändra</translation> </message> <message> <location line="+50"/> <source>custom change address</source> <translation>egen ändringsadress</translation> </message> <message> <location line="+106"/> <source>Send to multiple recipients at once</source> <translation>Skicka till flera mottagare samtidigt</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>Lägg till &amp;mottagare</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Ta bort alla transaktionsfält</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Rensa &amp;alla</translation> </message> <message> <location line="+28"/> <source>Balance:</source> <translation>Balans:</translation> </message> <message> <location line="+16"/> <source>123.456 BC</source> <translation>123.456 BC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Bekräfta sändordern</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Skicka</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-173"/> <source>Enter a bitconnect address (e.g. 8dpZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation>Fyll i en bitconnect adress (t.ex. 8dpZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</translation> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation>Kopiera antal</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopiera belopp</translation> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation>Kopiera avgift</translation> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation>Kopiera efter avgift</translation> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation>Kopiera bytes</translation> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation>Kopiera prioritet</translation> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation>Kopiera låg utmatning</translation> </message> <message> <location line="+1"/> <source>Copy change</source> <translation>Kopiera ändring</translation> </message> <message> <location line="+86"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; till %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Bekräfta skickade mynt</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Är du säker att du vill skicka %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation>och</translation> </message> <message> <location line="+29"/> <source>The recipient address is not valid, please recheck.</source> <translation>Mottagarens adress är inte giltig, vänligen kontrollera igen.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Det betalade beloppet måste vara större än 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Värdet överstiger ditt saldo.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Totalvärdet överstiger ditt saldo när transaktionsavgiften %1 är pålagd.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Dubblett av adress funnen, kan bara skicka till varje adress en gång per sändning.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed.</source> <translation>Fel: Transaktionen kunde inte skapas.</translation> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Fel: Transaktionen nekades. Detta kan hända om vissa av mynten i din plånbok redan är använda, t.ex om du använder en kopia av wallet.dat och mynten redan var använda i kopia men inte markerade som använda här.</translation> </message> <message> <location line="+251"/> <source>WARNING: Invalid bitconnect address</source> <translation>VARNING: Ogiltig bitconnect adress</translation> </message> <message> <location line="+13"/> <source>(no label)</source> <translation>(Ingen etikett)</translation> </message> <message> <location line="+4"/> <source>WARNING: unknown change address</source> <translation>VARNING: okänd ändringsadress</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Formulär</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>&amp;Belopp:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Betala &amp;Till:</translation> </message> <message> <location line="+24"/> <location filename="../sendcoinsentry.cpp" line="+25"/> <source>Enter a label for this address to add it to your address book</source> <translation>Ange ett namn för den här adressen och lägg till den i din adressbok</translation> </message> <message> <location line="+9"/> <source>&amp;Label:</source> <translation>&amp;Etikett:</translation> </message> <message> <location line="+18"/> <source>The address to send the payment to (e.g. 8dpZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation>Adressen att skicka betalningen till (t.ex. 8dpZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</translation> </message> <message> <location line="+10"/> <source>Choose address from address book</source> <translation>Välj adress från adressbok</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Klistra in adress från Urklipp</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Ta bort denna mottagare</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a bitconnect address (e.g. 8dpZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation>Fyll i en bitconnect adress (t.ex. 8dpZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Signaturer - Signera / Verifiera ett Meddelande</translation> </message> <message> <location line="+13"/> <location line="+124"/> <source>&amp;Sign Message</source> <translation>&amp;Signera Meddelande</translation> </message> <message> <location line="-118"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Du kan signera meddelanden med dina adresser för att bevisa att du äger dem. Var försiktig med vad du signerar eftersom phising-attacker kan försöka få dig att skriva över din identitet till någon annan. Signera bara väldetaljerade påståenden du kan gå i god för.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. 8dpZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation>Adressen att signera meddelandet med (t.ex. 8dpZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</translation> </message> <message> <location line="+10"/> <location line="+203"/> <source>Choose an address from the address book</source> <translation>Välj en adress från adressboken</translation> </message> <message> <location line="-193"/> <location line="+203"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-193"/> <source>Paste address from clipboard</source> <translation>Klistra in adress från Urklipp</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Skriv in meddelandet du vill signera här</translation> </message> <message> <location line="+24"/> <source>Copy the current signature to the system clipboard</source> <translation>Kopiera signaturen till systemets Urklipp</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this bitconnect address</source> <translation>Signera meddelandet för att verifiera att du äger denna bitconnect adressen</translation> </message> <message> <location line="+17"/> <source>Reset all sign message fields</source> <translation>Rensa alla fält</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Rensa &amp;alla</translation> </message> <message> <location line="-87"/> <location line="+70"/> <source>&amp;Verify Message</source> <translation>&amp;Verifiera Meddelande</translation> </message> <message> <location line="-64"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>Skriv in din adress, meddelande (se till att du kopierar radbrytningar, mellanslag, tabbar, osv. exakt) och signatur nedan för att verifiera meddelandet. Var noga med att inte läsa in mer i signaturen än vad som finns i det signerade meddelandet, för att undvika att luras av en man-in-the-middle attack.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. 8dpZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation>Adressen meddelandet var signerad med (t.ex. 8dpZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified bitconnect address</source> <translation>Verifiera meddelandet för att vara säker på att det var signerat med den angivna bitconnect adressen</translation> </message> <message> <location line="+17"/> <source>Reset all verify message fields</source> <translation>Rensa alla fält</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a bitconnect address (e.g. 8dpZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source> <translation>Fyll i en bitconnect adress (t.ex. 8dpZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Klicka &quot;Signera Meddelande&quot; för att få en signatur</translation> </message> <message> <location line="+3"/> <source>Enter bitconnect signature</source> <translation>Fyll i bitconnect signatur</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>Den angivna adressen är ogiltig.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Vad god kontrollera adressen och försök igen.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>Den angivna adressen refererar inte till en nyckel.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Upplåsningen av plånboken avbröts.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>Privata nyckel för den angivna adressen är inte tillgänglig.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Signeringen av meddelandet misslyckades.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Meddelandet är signerat.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Signaturen kunde inte avkodas.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Kontrollera signaturen och försök igen.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>Signaturen matchade inte meddelandesammanfattningen.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Meddelandet verifikation misslyckades.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Meddelandet är verifierad.</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+19"/> <source>Open until %1</source> <translation>Öppet till %1</translation> </message> <message numerus="yes"> <location line="-2"/> <source>Open for %n block(s)</source> <translation><numerusform>Öppen för %n block</numerusform><numerusform>Öppen för %n block</numerusform></translation> </message> <message> <location line="+8"/> <source>conflicted</source> <translation>konflikt</translation> </message> <message> <location line="+2"/> <source>%1/offline</source> <translation>%1/nerkopplad</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/obekräftade</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 bekräftelser</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Status</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, sänd genom %n nod</numerusform><numerusform>, sänd genom %n noder</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Källa</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Genererad</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Från</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Till</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>egen adress</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>etikett</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Kredit</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>mognar om %n block</numerusform><numerusform>mognar om %n fler block</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>inte accepterad</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Belasta</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Transaktionsavgift</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Nettobelopp</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Meddelande</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Kommentar</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>Transaktions-ID</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 5 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Genererad mynt måste mogna i 5 block före de kan användas. När du genererade detta blocket sändes det ut till nätverket för att läggas till i blockkedjan. Om det inte kan läggas till i kedjan kommer dess status att ändras till &quot;Ej accepterat&quot; och det kommer inte gå att använda. Detta kan hända imellanåt om en annan klient genererar ett block inom ett par sekunder från ditt.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Debug information</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transaktion</translation> </message> <message> <location line="+5"/> <source>Inputs</source> <translation>Inputs</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Mängd</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>sant</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>falsk</translation> </message> <message> <location line="-211"/> <source>, has not been successfully broadcast yet</source> <translation>, har inte lyckats skickas ännu</translation> </message> <message> <location line="+35"/> <source>unknown</source> <translation>okänd</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Transaktionsdetaljer</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Den här panelen visar en detaljerad beskrivning av transaktionen</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+226"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Typ</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adress</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Mängd</translation> </message> <message> <location line="+60"/> <source>Open until %1</source> <translation>Öppet till %1</translation> </message> <message> <location line="+12"/> <source>Confirmed (%1 confirmations)</source> <translation>Bekräftad (%1 bekräftelser)</translation> </message> <message numerus="yes"> <location line="-15"/> <source>Open for %n more block(s)</source> <translation><numerusform>Öppet för %n mer block</numerusform><numerusform>Öppet för %n mer block</numerusform></translation> </message> <message> <location line="+6"/> <source>Offline</source> <translation>Nerkopplad</translation> </message> <message> <location line="+3"/> <source>Unconfirmed</source> <translation>Obekräftad</translation> </message> <message> <location line="+3"/> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation>Bekräftar (%1 av %2 rekommenderade bekräftelser)</translation> </message> <message> <location line="+6"/> <source>Conflicted</source> <translation>Konflikt</translation> </message> <message> <location line="+3"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation>Omogen (%1 bekräftningar, kommer bli tillgänglig efter %2)</translation> </message> <message> <location line="+3"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Det här blocket togs inte emot av några andra noder och kommer antagligen inte att bli godkänt.</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Genererad men inte accepterad</translation> </message> <message> <location line="+42"/> <source>Received with</source> <translation>Mottagen med</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Mottaget från</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Skickad till</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Betalning till dig själv</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Genererade</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(n/a)</translation> </message> <message> <location line="+190"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Transaktionsstatus. Håll muspekaren över för att se antal bekräftelser.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Tidpunkt då transaktionen mottogs.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Transaktionstyp.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Transaktionens destinationsadress.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Belopp draget eller tillagt till balans.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+55"/> <location line="+16"/> <source>All</source> <translation>Alla</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Idag</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Denna vecka</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Denna månad</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Föregående månad</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Det här året</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Period...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Mottagen med</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Skickad till</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Till dig själv</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Genererade</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Övriga</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Sök efter adress eller etikett </translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Minsta mängd</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Kopiera adress</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopiera etikett</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopiera belopp</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>Kopiera transaktions ID</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Ändra etikett</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Visa transaktionsdetaljer</translation> </message> <message> <location line="+144"/> <source>Export Transaction Data</source> <translation>Exportera transaktionsdata</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Kommaseparerad fil (*. csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Bekräftad</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Datum</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Typ</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Etikett</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Adress</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Mängd</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Fel vid exportering</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Kan inte skriva till fil %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Intervall:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>till</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+206"/> <source>Sending...</source> <translation>Skickar...</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+33"/> <source>bitconnect version</source> <translation>bitconnect version</translation> </message> <message> <location line="+1"/> <source>Usage:</source> <translation>Användning:</translation> </message> <message> <location line="+1"/> <source>Send command to -server or bitconnectd</source> <translation>Skicka kommando till -server eller bitconnectd</translation> </message> <message> <location line="+1"/> <source>List commands</source> <translation>Lista kommandon</translation> </message> <message> <location line="+1"/> <source>Get help for a command</source> <translation>Få hjälp med ett kommando</translation> </message> <message> <location line="+2"/> <source>Options:</source> <translation>Inställningar:</translation> </message> <message> <location line="+2"/> <source>Specify configuration file (default: bitconnect.conf)</source> <translation>Ange konfigurationsfilen (standard: bitconnect.conf)</translation> </message> <message> <location line="+1"/> <source>Specify pid file (default: bitconnectd.pid)</source> <translation>Ange pid filen (standard bitconnectd.pid)</translation> </message> <message> <location line="+2"/> <source>Specify wallet file (within data directory)</source> <translation>Ange plånboksfil (inom datakatalogen)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Ange katalog för data</translation> </message> <message> <location line="+2"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Sätt databas cache storleken i megabyte (förvalt: 25)</translation> </message> <message> <location line="+1"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation>Sätt databas logg storleken i MB (standard: 100)</translation> </message> <message> <location line="+6"/> <source>Listen for connections on &lt;port&gt; (default: 9239 or testnet: 19239)</source> <translation>Lyssna efter anslutningar på &lt;port&gt; (standard: 9239 eller testnät: 19239)</translation> </message> <message> <location line="+1"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Ha som mest &lt;n&gt; anslutningar till andra klienter (förvalt: 125)</translation> </message> <message> <location line="+3"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Anslut till en nod för att hämta klientadresser, och koppla från</translation> </message> <message> <location line="+1"/> <source>Specify your own public address</source> <translation>Ange din egen publika adress</translation> </message> <message> <location line="+5"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation>Bind till angiven adress. Använd [host]:port för IPv6</translation> </message> <message> <location line="+2"/> <source>Stake your coins to support network and gain reward (default: 1)</source> <translation>Använd dina coins för stake-processen, du upprätthåller då nätverket och får belöning (förval: 1)</translation> </message> <message> <location line="+5"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Tröskelvärde för att koppla ifrån klienter som missköter sig (förvalt: 100)</translation> </message> <message> <location line="+1"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Antal sekunder att hindra klienter som missköter sig från att ansluta (förvalt: 86400)</translation> </message> <message> <location line="-44"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>Ett fel uppstod vid upprättandet av RPC port %u för att lyssna på IPv4: %s</translation> </message> <message> <location line="+51"/> <source>Detach block and address databases. Increases shutdown time (default: 0)</source> <translation>Koppla ifrån block och adress databaser. Ökar nedstängningstid (standard: 0)</translation> </message> <message> <location line="+109"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Fel: Transaktionen nekades. Detta kan hända om vissa av mynten i din plånbok redan är använda, t.ex om du använder en kopia av wallet.dat och mynten redan var använda i kopia men inte markerade som använda här.</translation> </message> <message> <location line="-5"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source> <translation>Fel: Transaktionen kräver en transaktionsavgift på min %s på grund av dess storlek, komplexitet eller användning av nyligen mottagna kapital</translation> </message> <message> <location line="-87"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 9240 or testnet: 19240)</source> <translation>Lyssna efter JSON-RPC anslutningar på &lt;port&gt; (standard: 9240 eller testnät: 19240)</translation> </message> <message> <location line="-11"/> <source>Accept command line and JSON-RPC commands</source> <translation>Tillåt kommandon från kommandotolken och JSON-RPC-kommandon</translation> </message> <message> <location line="+101"/> <source>Error: Transaction creation failed </source> <translation>Fel: Skapandet av transaktion misslyckades</translation> </message> <message> <location line="-5"/> <source>Error: Wallet locked, unable to create transaction </source> <translation>Fel: Plånboken låst, kan inte utföra transaktion</translation> </message> <message> <location line="-8"/> <source>Importing blockchain data file.</source> <translation>Importerar blockchain data fil.</translation> </message> <message> <location line="+1"/> <source>Importing bootstrap blockchain data file.</source> <translation>Importerar bootstrap blockchain data fil.</translation> </message> <message> <location line="-88"/> <source>Run in the background as a daemon and accept commands</source> <translation>Kör i bakgrunden som tjänst och acceptera kommandon</translation> </message> <message> <location line="+1"/> <source>Use the test network</source> <translation>Använd testnätverket</translation> </message> <message> <location line="-24"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Acceptera anslutningar utifrån (förvalt: 1 om ingen -proxy eller -connect)</translation> </message> <message> <location line="-38"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>Ett fel uppstod vid upprättandet av RPC port %u för att lyssna på IPv6, faller tillbaka till IPV4: %s</translation> </message> <message> <location line="+117"/> <source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source> <translation>Ett fel uppstod vid initialiseringen av databasen %s! För att återställa, SÄKERHETSKOPIERA MAPPEN, radera sedan allt från mappen förutom wallet.dat.</translation> </message> <message> <location line="-20"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>Ställ in max storlek för hög prioritet/lågavgifts transaktioner i bytes (förval: 27000)</translation> </message> <message> <location line="+11"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Varning: -paytxfee är satt väldigt hög! Detta är avgiften du kommer betala för varje transaktion.</translation> </message> <message> <location line="+61"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong bitconnect will not work properly.</source> <translation>Varning: Kolla att din dators tid och datum är rätt. bitconnect kan inte fungera ordentligt om tiden i datorn är fel.</translation> </message> <message> <location line="-31"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Varning: fel vid läsning av wallet.dat! Alla nycklar lästes korrekt, men transaktionsdatan eller adressbokens poster kanske saknas eller är felaktiga.</translation> </message> <message> <location line="-18"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Varning: wallet.dat korrupt, datan har räddats! Den ursprungliga wallet.dat har sparas som wallet.{timestamp}.bak i %s; om ditt saldo eller transaktioner är felaktiga ska du återställa från en säkerhetskopia.</translation> </message> <message> <location line="-30"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Försök att rädda de privata nycklarna från en korrupt wallet.dat</translation> </message> <message> <location line="+4"/> <source>Block creation options:</source> <translation>Block skapande inställningar:</translation> </message> <message> <location line="-62"/> <source>Connect only to the specified node(s)</source> <translation>Koppla enbart upp till den/de specificerade noden/noder</translation> </message> <message> <location line="+4"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Hitta egen IP-adress (förvalt: 1 under lyssning och utan -externalip)</translation> </message> <message> <location line="+94"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Misslyckades att lyssna på någon port. Använd -listen=0 om du vill detta.</translation> </message> <message> <location line="-90"/> <source>Find peers using DNS lookup (default: 1)</source> <translation>Hitta andra klienter via DNS uppsökning (standard: 1)</translation> </message> <message> <location line="+5"/> <source>Sync checkpoints policy (default: strict)</source> <translation>Synka kontrollpunkts policy (standard: strict)</translation> </message> <message> <location line="+83"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Fel -tor adress: &apos;%s&apos;</translation> </message> <message> <location line="+4"/> <source>Invalid amount for -reservebalance=&lt;amount&gt;</source> <translation>Fel mängd för -reservebalance=&lt;amount&gt;</translation> </message> <message> <location line="-82"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Maximal buffert för mottagning per anslutning, &lt;n&gt;*1000 byte (förvalt: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Maximal buffert för sändning per anslutning, &lt;n&gt;*1000 byte (förvalt: 5000)</translation> </message> <message> <location line="-16"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Anslut enbart till noder i nätverket &lt;net&gt; (IPv4, IPv6 eller Tor)</translation> </message> <message> <location line="+28"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>Skriv ut extra debug information. Betyder alla andra -debug* alternativ </translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>Skriv ut extra nätverks debug information</translation> </message> <message> <location line="+1"/> <source>Prepend debug output with timestamp</source> <translation>Tidstämpla debug utskriften</translation> </message> <message> <location line="+35"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation>SSL-inställningar: (se Bitcoin-wikin för SSL-setup instruktioner)</translation> </message> <message> <location line="-74"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Välj version av socks proxy (4-5, förval 5)</translation> </message> <message> <location line="+41"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Skicka trace-/debuginformation till terminalen istället för till debug.log</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Skicka trace/debug till debuggern</translation> </message> <message> <location line="+28"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Sätt största blockstorlek i bytes (förvalt: 250000)</translation> </message> <message> <location line="-1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Sätt minsta blockstorlek i byte (förvalt: 0)</translation> </message> <message> <location line="-29"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Krymp debug.log filen vid klient start (förvalt: 1 vid ingen -debug)</translation> </message> <message> <location line="-42"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Ange timeout för uppkoppling i millisekunder (förvalt: 5000)</translation> </message> <message> <location line="+109"/> <source>Unable to sign checkpoint, wrong checkpointkey? </source> <translation>Kan inte signera checkpoint, fel checkpointkey? </translation> </message> <message> <location line="-80"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Använd UPnP för att mappa den lyssnande porten (förvalt: 0)</translation> </message> <message> <location line="-1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Använd UPnP för att mappa den lyssnande porten (förvalt: 1 under lyssning)</translation> </message> <message> <location line="-25"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation>Använd proxy för att nå Tor gömda servicer (standard: samma som -proxy)</translation> </message> <message> <location line="+42"/> <source>Username for JSON-RPC connections</source> <translation>Användarnamn för JSON-RPC-anslutningar</translation> </message> <message> <location line="+47"/> <source>Verifying database integrity...</source> <translation>Verifierar integriteten i databasen...</translation> </message> <message> <location line="+57"/> <source>WARNING: syncronized checkpoint violation detected, but skipped!</source> <translation>VARNING: synkroniserad kontrollpunkts brott upptäckt, men hoppades över!</translation> </message> <message> <location line="+1"/> <source>Warning: Disk space is low!</source> <translation>Varning: Lågt skivutrymme</translation> </message> <message> <location line="-2"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Varning: denna version är föråldrad, uppgradering krävs!</translation> </message> <message> <location line="-48"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat korrupt, räddning misslyckades</translation> </message> <message> <location line="-54"/> <source>Password for JSON-RPC connections</source> <translation>Lösenord för JSON-RPC-anslutningar</translation> </message> <message> <location line="-84"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=bitconnectrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;bitconnect Alert&quot; [email protected] </source> <translation>%s, du måste sätta rpcpassword i konfigurationsfilen: %s Det är rekommenderat att du använder följande slumpmässiga lösenord: rpcuser=bitconnectrpc rpcpassword=%s (du behöver inte komma ihåg detta lösenord) Användarnamnet och lösenordet FÅR INTE vara samma. Om filen inte finns, skapa den med endast ägarrättigheter. Det är också rekommenderat att sätta alertnotify så du blir notifierad om problem; till exempel: alertnotify=echo %%s | mail -s &quot;bitconnect Varning&quot; [email protected] </translation> </message> <message> <location line="+51"/> <source>Find peers using internet relay chat (default: 0)</source> <translation>Hitta andra klienter genom internet relay chat (standard: 1) {0)?}</translation> </message> <message> <location line="+5"/> <source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source> <translation>Synkronisera tiden med andra noder. Avaktivera om klockan i ditt sytem är exakt som t.ex. synkroniserad med NTP (förval: 1)</translation> </message> <message> <location line="+15"/> <source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source> <translation>När transaktioner skapas, ignorera värden som är lägre än detta (standard: 0.01)</translation> </message> <message> <location line="+16"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Tillåt JSON-RPC-anslutningar från specifika IP-adresser</translation> </message> <message> <location line="+1"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Skicka kommandon till klient på &lt;ip&gt; (förvalt: 127.0.0.1)</translation> </message> <message> <location line="+1"/><|fim▁hole|> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Exekvera kommando när det bästa blocket ändras (%s i cmd är utbytt av blockhash)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Exekvera kommando när en plånbokstransaktion ändras (%s i cmd är ersatt av TxID)</translation> </message> <message> <location line="+3"/> <source>Require a confirmations for change (default: 0)</source> <translation>Kräv bekräftelse för ändring (förval: 0)</translation> </message> <message> <location line="+1"/> <source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source> <translation>Tvinga transaktionsskript att använda kanoniska PUSH operatörer (standard: 1)</translation> </message> <message> <location line="+2"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation>Kör kommando när en relevant alert är mottagen (%s i cmd är ersatt av meddelandet)</translation> </message> <message> <location line="+3"/> <source>Upgrade wallet to latest format</source> <translation>Uppgradera plånboken till senaste formatet</translation> </message> <message> <location line="+1"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Sätt storleken på nyckelpoolen till &lt;n&gt; (förvalt: 100)</translation> </message> <message> <location line="+1"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Sök i blockkedjan efter saknade plånboks transaktioner</translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 2500, 0 = all)</source> <translation>Antal block som kollas vid start (standard: 2500, 0=alla)</translation> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation>Hur genomförlig blockverifikationen är (0-6, standard: 1)</translation> </message> <message> <location line="+1"/> <source>Imports blocks from external blk000?.dat file</source> <translation>Importera block från en extern blk000?.dat fil</translation> </message> <message> <location line="+8"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Använd OpenSSL (https) för JSON-RPC-anslutningar</translation> </message> <message> <location line="+1"/> <source>Server certificate file (default: server.cert)</source> <translation>Serverns certifikatfil (förvalt: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Serverns privata nyckel (förvalt: server.pem)</translation> </message> <message> <location line="+1"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Godtagbara chiffer (standard: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+53"/> <source>Error: Wallet unlocked for staking only, unable to create transaction.</source> <translation>Fel: Plånboken öppnad endast för stake-process, kan inte skapa transaktion.</translation> </message> <message> <location line="+18"/> <source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source> <translation>VARNING: Felaktig kontrollpunkt hittad! Visade transaktioner kan vara felaktiga! Du kan behöva uppgradera eller kontakta utvecklarna.</translation> </message> <message> <location line="-158"/> <source>This help message</source> <translation>Det här hjälp medelandet</translation> </message> <message> <location line="+95"/> <source>Wallet %s resides outside data directory %s.</source> <translation>Plånbok %s ligger utanför datamappen %s.</translation> </message> <message> <location line="+1"/> <source>Cannot obtain a lock on data directory %s. bitconnect is probably already running.</source> <translation>Kan inte låsa datan i mappen %s. bitconnect är kanske redan startad.</translation> </message> <message> <location line="-98"/> <source>bitconnect</source> <translation>bitconnect</translation> </message> <message> <location line="+140"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Det går inte att binda till %s på den här datorn (bind returnerade felmeddelande %d, %s)</translation> </message> <message> <location line="-130"/> <source>Connect through socks proxy</source> <translation>Koppla genom en socks proxy</translation> </message> <message> <location line="+3"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Tillåt DNS-sökningar för -addnode, -seednode och -connect</translation> </message> <message> <location line="+122"/> <source>Loading addresses...</source> <translation>Laddar adresser...</translation> </message> <message> <location line="-15"/> <source>Error loading blkindex.dat</source> <translation>Fel vid laddande av blkindex.dat</translation> </message> <message> <location line="+2"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Fel vid inläsningen av wallet.dat: Plånboken är skadad</translation> </message> <message> <location line="+4"/> <source>Error loading wallet.dat: Wallet requires newer version of bitconnect</source> <translation>Kunde inte ladda wallet.dat: En nyare version av bitconnect krävs</translation> </message> <message> <location line="+1"/> <source>Wallet needed to be rewritten: restart bitconnect to complete</source> <translation>Plånboken måste skrivas om: Starta om bitconnect för att slutföra</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat</source> <translation>Fel vid inläsning av plånboksfilen wallet.dat</translation> </message> <message> <location line="-16"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Ogiltig -proxy adress: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Okänt nätverk som anges i -onlynet: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Okänd -socks proxy version begärd: %i</translation> </message> <message> <location line="+4"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Kan inte matcha -bind adress: &apos;%s&apos;</translation> </message> <message> <location line="+2"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Kan inte matcha -externalip adress: &apos;%s&apos;</translation> </message> <message> <location line="-24"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Ogiltigt belopp för -paytxfee=&lt;belopp&gt;:&apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Error: could not start node</source> <translation>Fel: kunde inte starta noden</translation> </message> <message> <location line="+11"/> <source>Sending...</source> <translation>Skickar...</translation> </message> <message> <location line="+5"/> <source>Invalid amount</source> <translation>Ogiltig mängd</translation> </message> <message> <location line="+1"/> <source>Insufficient funds</source> <translation>Otillräckligt med bitcoins</translation> </message> <message> <location line="-34"/> <source>Loading block index...</source> <translation>Laddar blockindex...</translation> </message> <message> <location line="-103"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Lägg till en nod att koppla upp mot och försök att hålla anslutningen öppen</translation> </message> <message> <location line="+122"/> <source>Unable to bind to %s on this computer. bitconnect is probably already running.</source> <translation>Kan inte binda till %s på denna dator. bitconnect är sannolikt redan startad.</translation> </message> <message> <location line="-97"/> <source>Fee per KB to add to transactions you send</source> <translation>Avgift per KB som adderas till transaktionen du sänder</translation> </message> <message> <location line="+55"/> <source>Invalid amount for -mininput=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Fel mängd för -mininput=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+25"/> <source>Loading wallet...</source> <translation>Laddar plånbok...</translation> </message> <message> <location line="+8"/> <source>Cannot downgrade wallet</source> <translation>Kan inte nedgradera plånboken</translation> </message> <message> <location line="+1"/> <source>Cannot initialize keypool</source> <translation>Kan inte initialisera keypool</translation> </message> <message> <location line="+1"/> <source>Cannot write default address</source> <translation>Kan inte skriva standardadress</translation> </message> <message> <location line="+1"/> <source>Rescanning...</source> <translation>Söker igen...</translation> </message> <message> <location line="+5"/> <source>Done loading</source> <translation>Klar med laddning</translation> </message> <message> <location line="-167"/> <source>To use the %s option</source> <translation>Att använda %s alternativet</translation> </message> <message> <location line="+14"/> <source>Error</source> <translation>Fel</translation> </message> <message> <location line="+6"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>Du behöver välja ett rpclösensord i konfigurationsfilen: %s Om filen inte existerar, skapa den med filrättigheten endast läsbar för ägaren.</translation> </message> </context> </TS><|fim▁end|>
<|file_name|>configs.go<|end_file_name|><|fim▁begin|>// ./docker/api/types/configs.go //peter package types import "github.com/docker/docker/api/types/container" // configs holds structs used for internal communication between the // frontend (such as an http server) and the backend (such as the // docker daemon). // ContainerCreateConfig is the parameter set to ContainerCreate() type ContainerCreateConfig struct { Name string Config *container.Config HostConfig *container.HostConfig AdjustCPUShares bool } // ContainerRmConfig holds arguments for the container remove // operation. This struct is used to tell the backend what operations // to perform. type ContainerRmConfig struct { ForceRemove, RemoveVolume, RemoveLink bool } // ContainerCommitConfig contains build configs for commit operation, // and is used when making a commit with the current state of the container. type ContainerCommitConfig struct { Pause bool Repo string Tag string Author string Comment string // merge container config into commit config before commit MergeConfigs bool Config *container.Config } // CriuConfig holds configuration options passed down to libcontainer and CRIU type CriuConfig struct { ImagesDirectory string WorkDirectory string LeaveRunning bool PrevImagesDirectory string //peter TrackMemory bool //peter EnablePreDump bool //peter AutoDedup bool //peter PageServer bool //peter Address string //peter Port int32 //peter } // RestoreConfig holds the restore command options, which is a superset of the CRIU options type RestoreConfig struct { CriuOpts CriuConfig ForceRestore bool } // ExecConfig is a small subset of the Config struct that hold the configuration // for the exec feature of docker.<|fim▁hole|> Tty bool // Attach standard streams to a tty. Container string // Name of the container (to execute in) AttachStdin bool // Attach the standard input, makes possible user interaction AttachStderr bool // Attach the standard output AttachStdout bool // Attach the standard error Detach bool // Execute in detach mode Cmd []string // Execution commands and args }<|fim▁end|>
type ExecConfig struct { User string // User that will run the command Privileged bool // Is the container in privileged mode
<|file_name|>IteratorPageDownstreamTest.java<|end_file_name|><|fim▁begin|>/* * Licensed to Crate.IO GmbH ("Crate") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial agreement. */ package io.crate.operation.merge; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.SettableFuture; import io.crate.core.collections.ArrayBucket; import io.crate.core.collections.Bucket; import io.crate.core.collections.BucketPage; import io.crate.core.collections.Row; import io.crate.core.collections.Row1; import io.crate.core.collections.SingleRowBucket; import io.crate.operation.PageConsumeListener; import io.crate.operation.projectors.RowReceiver; import io.crate.test.integration.CrateUnitTest; import io.crate.testing.CollectingRowReceiver; import io.crate.testing.TestingHelpers; import org.elasticsearch.common.breaker.CircuitBreakingException; import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.Mockito; import javax.annotation.Nonnull; import java.util.concurrent.Executor; import static org.hamcrest.core.Is.is; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; public class IteratorPageDownstreamTest extends CrateUnitTest { public static final PageConsumeListener PAGE_CONSUME_LISTENER = new PageConsumeListener() { @Override public void needMore() { } @Override public void finish() { } }; @Mock PagingIterator<Row> mockedPagingIterator; @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void testMergeOnPagingIteratorIsCalledAfterALLBucketsAreReady() throws Exception { IteratorPageDownstream downstream = new IteratorPageDownstream( new CollectingRowReceiver(), mockedPagingIterator, Optional.<Executor>absent()); SettableFuture<Bucket> b1 = SettableFuture.create(); SettableFuture<Bucket> b2 = SettableFuture.create(); downstream.nextPage(new BucketPage(ImmutableList.of(b1, b2)), PAGE_CONSUME_LISTENER); verify(mockedPagingIterator, times(0)).merge(Mockito.<Iterable<? extends NumberedIterable<Row>>>any()); b1.set(Bucket.EMPTY); verify(mockedPagingIterator, times(0)).merge(Mockito.<Iterable<? extends NumberedIterable<Row>>>any()); b2.set(Bucket.EMPTY); verify(mockedPagingIterator, times(1)).merge(Mockito.<Iterable<? extends NumberedIterable<Row>>>any()); } @Test public void testFailingNextRowIsHandled() throws Exception { expectedException.expect(CircuitBreakingException.class); class FailingRowReceiver extends CollectingRowReceiver { @Override public boolean setNextRow(Row row) { throw new CircuitBreakingException("foo"); } } CollectingRowReceiver rowReceiver = new FailingRowReceiver(); IteratorPageDownstream downstream = new IteratorPageDownstream( rowReceiver, PassThroughPagingIterator.<Row>oneShot(), Optional.<Executor>absent()); SettableFuture<Bucket> b1 = SettableFuture.create(); downstream.nextPage(new BucketPage(ImmutableList.of(b1)), PAGE_CONSUME_LISTENER); b1.set(new SingleRowBucket(new Row1(42))); rowReceiver.result(); } @Test public void testBucketFailureIsPassedToDownstream() throws Exception { IllegalStateException dummy = new IllegalStateException("dummy"); expectedException.expect(IllegalStateException.class); CollectingRowReceiver rowReceiver = new CollectingRowReceiver(); IteratorPageDownstream downstream = new IteratorPageDownstream( rowReceiver, mockedPagingIterator, Optional.<Executor>absent()); SettableFuture<Bucket> b1 = SettableFuture.create(); downstream.nextPage(new BucketPage(ImmutableList.of(b1)), PAGE_CONSUME_LISTENER); b1.setException(dummy); rowReceiver.result(); } @Test public void testMultipleFinishPropagatesOnlyOnceToDownstream() throws Exception { RowReceiver rowReceiver = mock(RowReceiver.class); IteratorPageDownstream downstream = new IteratorPageDownstream( rowReceiver, mockedPagingIterator, Optional.<Executor>absent()); downstream.finish(); downstream.finish(); verify(rowReceiver, times(1)).finish(); } @Test public void testFinishDoesNotEmitRemainingRow() throws Exception { CollectingRowReceiver rowReceiver = CollectingRowReceiver.withLimit(1); IteratorPageDownstream downstream = new IteratorPageDownstream( rowReceiver, PassThroughPagingIterator.<Row>oneShot(), Optional.<Executor>absent() ); SettableFuture<Bucket> b1 = SettableFuture.create(); b1.set(new ArrayBucket( new Object[][]{ new Object[]{"a"}, new Object[]{"b"}, new Object[]{"c"} } )); downstream.nextPage(new BucketPage(ImmutableList.of(b1)), PAGE_CONSUME_LISTENER); downstream.finish(); assertThat(rowReceiver.result().size(), is(1)); } @Test public void testRejectedExecutionDoesNotCauseBucketMergerToGetStuck() throws Exception { expectedException.expect(EsRejectedExecutionException.class); final CollectingRowReceiver rowReceiver = new CollectingRowReceiver(); IteratorPageDownstream pageDownstream = new IteratorPageDownstream( rowReceiver, PassThroughPagingIterator.<Row>oneShot(), Optional.<Executor>of(new Executor() { @Override public void execute(@Nonnull Runnable command) { throw new EsRejectedExecutionException("HAHA !"); } })); SettableFuture<Bucket> b1 = SettableFuture.create(); b1.set(Bucket.EMPTY); pageDownstream.nextPage(new BucketPage(ImmutableList.of(b1)), new PageConsumeListener() {<|fim▁hole|> @Override public void finish() { rowReceiver.finish(); } }); rowReceiver.result(); } @Test public void testRepeat() throws Exception { CollectingRowReceiver rowReceiver = new CollectingRowReceiver(); IteratorPageDownstream pageDownstream = new IteratorPageDownstream( rowReceiver, PassThroughPagingIterator.<Row>repeatable(), Optional.<Executor>absent()); SettableFuture<Bucket> b1 = SettableFuture.create(); b1.set(new ArrayBucket( new Object[][] { new Object[] {"a"}, new Object[] {"b"}, new Object[] {"c"} } )); pageDownstream.nextPage(new BucketPage(ImmutableList.of(b1)), PAGE_CONSUME_LISTENER); pageDownstream.nextPage(new BucketPage(ImmutableList.of(b1)), PAGE_CONSUME_LISTENER); pageDownstream.finish(); rowReceiver.repeatUpstream(); pageDownstream.finish(); assertThat(TestingHelpers.printedTable(rowReceiver.result()), is( "a\n" + "b\n" + "c\n" + "a\n" + "b\n" + "c\n" + "a\n" + "b\n" + "c\n" + "a\n" + "b\n" + "c\n")); } @Test public void testPauseAndResume() throws Exception { CollectingRowReceiver rowReceiver = CollectingRowReceiver.withPauseAfter(2); IteratorPageDownstream pageDownstream = new IteratorPageDownstream( rowReceiver, PassThroughPagingIterator.<Row>repeatable(), Optional.<Executor>absent()); SettableFuture<Bucket> b1 = SettableFuture.create(); b1.set(new ArrayBucket( new Object[][] { new Object[] {"a"}, new Object[] {"b"}, new Object[] {"c"} } )); pageDownstream.nextPage(new BucketPage(ImmutableList.of(b1)), PAGE_CONSUME_LISTENER); assertThat(rowReceiver.rows.size(), is(2)); rowReceiver.resumeUpstream(false); assertThat(rowReceiver.rows.size(), is(3)); pageDownstream.finish(); rowReceiver.repeatUpstream(); assertThat(TestingHelpers.printedTable(rowReceiver.result()), is( "a\n" + "b\n" + "c\n" + "a\n" + "b\n" + "c\n")); } }<|fim▁end|>
@Override public void needMore() { rowReceiver.finish(); }
<|file_name|>MinimalTuringMachineTest.java<|end_file_name|><|fim▁begin|>package dk.itu.ejuuragr.tests; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.anji.util.Properties; import dk.itu.ejuuragr.turing.MinimalTuringMachine; public class MinimalTuringMachineTest { MinimalTuringMachine tm; @Before public void before(){ Properties props = new Properties(); props.setProperty("tm.m", "2"); props.setProperty("tm.shift.length", "3"); tm = new MinimalTuringMachine(props); } @Test public void testShift(){ double[] tmstim = new double[]{ 0, 1, //Write 1, //Write interpolation 0, //Content jump 1, 0, 0 //Shift }; double[] result = tm.processInput(tmstim)[0]; Assert.assertArrayEquals(new double[]{0, 0}, result, 0.0); tmstim = new double[]{ 0, 0, //Write 0, //Write interpolation 0, //Content jump 0, 0, 1 //Shift }; result = tm.processInput(tmstim)[0]; Assert.assertArrayEquals(new double[]{0, 1}, result, 0.0); } @Test public void testContentBasedJump(){ //Write jump target double[] tmstim = new double[]{ 0, 1, //Write 1, //Write interpolation 0, //Content jump 0, 0, 1 //Shift }; double[] result = tm.processInput(tmstim)[0]; //Write jump result tmstim = new double[]{ 1, 0, //Write 1, //Write interpolation 0, //Content jump 0, 0, 1 //Shift }; result = tm.processInput(tmstim)[0]; //Jump, shift, and read tmstim = new double[]{ 0, 1, //Write 0, //Write interpolation 1, //Content jump 0, 0, 1 //Shift }; result = tm.processInput(tmstim)[0]; Assert.assertArrayEquals(new double[]{1, 0}, result, 0.0); } @Test public void testContentBasedJumpLonger(){ //Write jump target double[] tmstim = new double[]{ 0, 1, //Write 1, //Write interpolation 0, //Content jump 0, 0, 1 //Shift }; double[] result = tm.processInput(tmstim)[0]; //Write jump result tmstim = new double[]{ 1, 0, //Write 1, //Write interpolation 0, //Content jump 0, 0, 1 //Shift }; result = tm.processInput(tmstim)[0]; //Move right for (int k = 0; k < 10; k++){ tmstim = new double[]{ 0, 0, //Write 0, //Write interpolation 0, //Content jump 0, 0, 1 //Shift }; result = tm.processInput(tmstim)[0]; } //Jump, shift, and read tmstim = new double[]{ 0, 1, //Write 0, //Write interpolation 1, //Content jump 0, 0, 1 //Shift }; result = tm.processInput(tmstim)[0]; Assert.assertArrayEquals(new double[]{1, 0}, result, 0.0); } @Test public void testCopyTaskSimple(){ double[][] seq = new double[][]{ {0,1,0}, //Start {1,0,0}, //Data {0,0,0}, //Data {0,0,0}, //Data {1,0,0}, //Data {1,0,0}, //Data {0,0,1}, //End {0,0,0}, //Poll {0,0,0}, //Poll {0,0,0}, //Poll {0,0,0}, //Poll {0,0,0}, //Poll }; double[] lastRoundRead = new double[]{0,0}; for (int round = 0; round < seq.length; round++){ double d = seq[round][0]; double s = seq[round][1]; double b = seq[round][2];<|fim▁hole|> if (round > 6){ double verify = seq[round-6][0]; Assert.assertEquals(verify, roundResult, 0.00); } } } private double[] act(double d1, double d2, double write, double jump, double shiftLeft, double shiftStay, double shiftRight){ return tm.processInput(new double[]{ d1, d2, //Write write, //Write interpolation jump, //Content jump shiftLeft, shiftStay, shiftRight //Shift })[0]; } }<|fim▁end|>
lastRoundRead = act(d + lastRoundRead[0],s + b + lastRoundRead[1], 1-b, b, 0, b ,1-b); double roundResult = lastRoundRead[0];
<|file_name|>basereferenceintegrationtest.py<|end_file_name|><|fim▁begin|>''' Created on 01.12.2016 @author: michael ''' from alex_test_utils import MODE_SIMPLE from alexandriabase import baseinjectorkeys from alexandriabase.domain import Event, AlexDateRange, AlexDate, Document, \ DocumentType from alexpresenters.MessageBroker import REQ_SAVE_CURRENT_EVENT, \ REQ_SAVE_CURRENT_DOCUMENT, Message, CONF_DOCUMENT_CHANGED, \ CONF_EVENT_CHANGED<|fim▁hole|>from alexandriabase.daos import EventDao, DocumentDao class BaseReferenceIntegrationTest(BaseIntegrationTest): ''' Add some helper methods to make testing references more easy. ''' def receive_message(self, message): BaseIntegrationTest.receive_message(self, message) if message == REQ_SAVE_CURRENT_EVENT: self.injector.get(EventDao).save(self.presenter.view.current_event) if message == REQ_SAVE_CURRENT_DOCUMENT: self.injector.get(DocumentDao).save(self.presenter.view.current_document) def set_current_document(self, document_id): if document_id is not None: document = self.document_dao.get_by_id(document_id) else: document = Document() document.document_type = DocumentType(1) message = Message(CONF_DOCUMENT_CHANGED, document=document) self.message_broker.send_message(message) def set_current_event(self, event_id): if event_id is not None: event = self.event_dao.get_by_id(event_id) else: event = Event() event.daterange = AlexDateRange(AlexDate(1936), None) message = Message(CONF_EVENT_CHANGED, event=event) self.message_broker.send_message(message)<|fim▁end|>
from integration.baseintegrationtest import BaseIntegrationTest
<|file_name|>test_20x4.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import, unicode_literals import sys from RPLCD_i2c import CharLCD from RPLCD_i2c import Alignment, CursorMode, ShiftMode from RPLCD_i2c import cursor, cleared try: input = raw_input except NameError: pass try: unichr = unichr except NameError: unichr = chr lcd = CharLCD(address=0x38, port=1, cols=20, rows=4, dotsize=8) input('Display should be blank. ') lcd.cursor_mode = CursorMode.blink input('The cursor should now blink. ') lcd.cursor_mode = CursorMode.line input('The cursor should now be a line. ') <|fim▁hole|>assert lcd.cursor_pos == (0, 12), 'cursor_pos should now be (0, 12)' lcd.cursor_pos = (1, 0) lcd.write_string('2') lcd.cursor_pos = (2, 0) lcd.write_string('3') lcd.cursor_pos = (3, 0) lcd.write_string('4') assert lcd.cursor_pos == (3, 1), 'cursor_pos should now be (3, 1)' input('Lines 2, 3 and 4 should now be labelled with the right numbers. ') lcd.clear() input('Display should now be clear, cursor should be at initial position. ') lcd.cursor_pos = (0, 5) lcd.write_string('12345') input('The string should have a left offset of 5 characters. ') lcd.write_shift_mode = ShiftMode.display lcd.cursor_pos = (1, 5) lcd.write_string('12345') input('Both strings should now be at column 0. ') lcd.write_shift_mode = ShiftMode.cursor lcd.cursor_pos = (2, 5) lcd.write_string(lcd.write_shift_mode.name) input('The string "cursor" should now be on the third row, column 0. ') lcd.home() input('Cursor should now be at initial position. Everything should be shifted to the right by 5 characters. ') with cursor(lcd, 3, 19): lcd.write_string('X') input('The last character on the LCD should now be an "X"') lcd.display_enabled = False input('Display should now be blank. ') with cleared(lcd): lcd.write_string('Eggs, Ham, Bacon\n\rand Spam') lcd.display_enabled = True input('Display should now show "Eggs, Ham, Bacon and Spam". ') lcd.shift_display(4) input('Text should now be shifted to the right by 4 characters. ') lcd.shift_display(-4) input('Shift should now be undone. ') lcd.text_align_mode = Alignment.right lcd.cursor_mode = CursorMode.hide lcd.write_string(' Spam') input('The word "Spam" should now be inverted. ') lcd.text_align_mode = Alignment.left lcd.cursor_mode = CursorMode.hide lcd.write_string(' Wurscht') input('The word "mapS" should now be replaced with "Wurscht". ') lcd.clear() lcd.write_string('1\n') lcd.write_string('2\n') lcd.write_string('3\n') lcd.write_string('4') input('The numbers 1-4 should now be displayed, each line shifted to the right by 1 char more than the previous. ') lcd.clear() lcd.write_string('This is a long string that will wrap across multiple lines!') input('Text should nicely wrap around lines. ') lcd.cursor_mode = CursorMode.hide # Test custom chars lcd.clear() happy = (0b00000, 0b01010, 0b01010, 0b00000, 0b10001, 0b10001, 0b01110, 0b00000) sad = (0b00000, 0b01010, 0b01010, 0b00000, 0b01110, 0b10001, 0b10001, 0b00000) lcd.create_char(0, sad) lcd.write_string(unichr(0)) lcd.create_char(1, happy) lcd.write_string(unichr(1)) input('You should now see a sad and a happy face next to each other. ') lcd.create_char(0, happy) lcd.home() lcd.write_string(unichr(0)) input('Now both faces should be happy. ') lcd.clear() lcd.set_backlight(False) lcd.home() lcd.write_string('No backlight') input('Display backlight should be off (if wired). ') lcd.clear() lcd.set_backlight(True) lcd.home() lcd.write_string('Backlight') input('Display backlight should be back on (if wired). ') lcd.clear() print('Test done.')<|fim▁end|>
lcd.write_string('Hello world!') input('"Hello world!" should be on the LCD. ')
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from tilequeue.query.fixture import make_fixture_data_fetcher from tilequeue.query.pool import DBConnectionPool from tilequeue.query.postgres import make_db_data_fetcher from tilequeue.query.rawr import make_rawr_data_fetcher from tilequeue.query.split import make_split_data_fetcher from tilequeue.process import Source from tilequeue.store import make_s3_tile_key_generator __all__ = [ 'DBConnectionPool', 'make_db_data_fetcher', 'make_fixture_data_fetcher', 'make_data_fetcher', ] def make_data_fetcher(cfg, layer_data, query_cfg, io_pool): db_fetcher = make_db_data_fetcher( cfg.postgresql_conn_info, cfg.template_path, cfg.reload_templates, query_cfg, io_pool) if cfg.yml.get('use-rawr-tiles'): rawr_fetcher = _make_rawr_fetcher( cfg, layer_data, query_cfg, io_pool) group_by_zoom = cfg.yml.get('rawr').get('group-zoom') assert group_by_zoom is not None, 'Missing group-zoom rawr config' return make_split_data_fetcher( group_by_zoom, db_fetcher, rawr_fetcher) else: return db_fetcher class _NullRawrStorage(object): def __init__(self, data_source, table_sources): self.data_source = data_source self.table_sources = table_sources <|fim▁hole|> # with tuples for that table. data = {} for location in self.data_source(tile): data[location.name] = location.records def _tables(table_name): from tilequeue.query.common import Table source = self.table_sources[table_name] return Table(source, data.get(table_name, [])) return _tables def _make_rawr_fetcher(cfg, layer_data, query_cfg, io_pool): rawr_yaml = cfg.yml.get('rawr') assert rawr_yaml is not None, 'Missing rawr configuration in yaml' group_by_zoom = rawr_yaml.get('group-zoom') assert group_by_zoom is not None, 'Missing group-zoom rawr config' rawr_source_yaml = rawr_yaml.get('source') assert rawr_source_yaml, 'Missing rawr source config' table_sources = rawr_source_yaml.get('table-sources') assert table_sources, 'Missing definitions of source per table' # map text for table source onto Source objects for tbl, data in table_sources.items(): source_name = data['name'] source_value = data['value'] table_sources[tbl] = Source(source_name, source_value) label_placement_layers = rawr_yaml.get('label-placement-layers', {}) for geom_type, layers in label_placement_layers.items(): assert geom_type in ('point', 'polygon', 'linestring'), \ 'Geom type %r not understood, expecting point, polygon or ' \ 'linestring.' % (geom_type,) label_placement_layers[geom_type] = set(layers) indexes_cfg = rawr_yaml.get('indexes') assert indexes_cfg, 'Missing definitions of table indexes.' # source types are: # s3 - to fetch RAWR tiles from S3 # store - to fetch RAWR tiles from any tilequeue tile source # generate - to generate RAWR tiles directly, rather than trying to load # them from S3. this can be useful for standalone use and # testing. provide a postgresql subkey for database connection # settings. source_type = rawr_source_yaml.get('type') if source_type == 's3': rawr_source_s3_yaml = rawr_source_yaml.get('s3') bucket = rawr_source_s3_yaml.get('bucket') assert bucket, 'Missing rawr source s3 bucket' region = rawr_source_s3_yaml.get('region') assert region, 'Missing rawr source s3 region' prefix = rawr_source_s3_yaml.get('prefix') assert prefix, 'Missing rawr source s3 prefix' extension = rawr_source_s3_yaml.get('extension') assert extension, 'Missing rawr source s3 extension' allow_missing_tiles = rawr_source_s3_yaml.get( 'allow-missing-tiles', False) import boto3 from tilequeue.rawr import RawrS3Source s3_client = boto3.client('s3', region_name=region) tile_key_gen = make_s3_tile_key_generator(rawr_source_s3_yaml) storage = RawrS3Source( s3_client, bucket, prefix, extension, table_sources, tile_key_gen, allow_missing_tiles) elif source_type == 'generate': from raw_tiles.source.conn import ConnectionContextManager from raw_tiles.source.osm import OsmSource postgresql_cfg = rawr_source_yaml.get('postgresql') assert postgresql_cfg, 'Missing rawr postgresql config' conn_ctx = ConnectionContextManager(postgresql_cfg) rawr_osm_source = OsmSource(conn_ctx) storage = _NullRawrStorage(rawr_osm_source, table_sources) elif source_type == 'store': from tilequeue.store import make_store from tilequeue.rawr import RawrStoreSource store_cfg = rawr_source_yaml.get('store') store = make_store(store_cfg, credentials=cfg.subtree('aws credentials')) storage = RawrStoreSource(store, table_sources) else: assert False, 'Source type %r not understood. ' \ 'Options are s3, generate and store.' % (source_type,) # TODO: this needs to be configurable, everywhere! this is a long term # refactor - it's hard-coded in a bunch of places :-( max_z = 16 layers = _make_layer_info(layer_data, cfg.process_yaml_cfg) return make_rawr_data_fetcher( group_by_zoom, max_z, storage, layers, indexes_cfg, label_placement_layers) def _make_layer_info(layer_data, process_yaml_cfg): from tilequeue.query.common import LayerInfo, ShapeType layers = {} functions = _parse_yaml_functions(process_yaml_cfg) for layer_datum in layer_data: name = layer_datum['name'] min_zoom_fn, props_fn = functions[name] shape_types = ShapeType.parse_set(layer_datum['geometry_types']) layer_info = LayerInfo(min_zoom_fn, props_fn, shape_types) layers[name] = layer_info return layers def _parse_yaml_functions(process_yaml_cfg): from tilequeue.command import make_output_calc_mapping from tilequeue.command import make_min_zoom_calc_mapping output_layer_data = make_output_calc_mapping(process_yaml_cfg) min_zoom_layer_data = make_min_zoom_calc_mapping(process_yaml_cfg) keys = set(output_layer_data.keys()) assert keys == set(min_zoom_layer_data.keys()) functions = {} for key in keys: min_zoom_fn = min_zoom_layer_data[key] output_fn = output_layer_data[key] functions[key] = (min_zoom_fn, output_fn) return functions<|fim▁end|>
def __call__(self, tile): # returns a "tables" object, which responds to __call__(table_name)
<|file_name|>any.rs<|end_file_name|><|fim▁begin|>// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Traits for dynamic typing of any `'static` type (through runtime reflection) //! //! This module implements the `Any` trait, which enables dynamic typing //! of any `'static` type through runtime reflection. //! //! `Any` itself can be used to get a `TypeId`, and has more features when used //! as a trait object. As `&Any` (a borrowed trait object), it has the `is` and //! `as_ref` methods, to test if the contained value is of a given type, and to //! get a reference to the inner value as a type. As`&mut Any`, there is also //! the `as_mut` method, for getting a mutable reference to the inner value. //! `Box<Any>` adds the `move` method, which will unwrap a `Box<T>` from the //! object. See the extension traits (`*Ext`) for the full details. //! //! Note that &Any is limited to testing whether a value is of a specified //! concrete type, and cannot be used to test whether a type implements a trait. //! //! # Examples //! //! Consider a situation where we want to log out a value passed to a function. //! We know the value we're working on implements Show, but we don't know its //! concrete type. We want to give special treatment to certain types: in this //! case printing out the length of String values prior to their value. //! We don't know the concrete type of our value at compile time, so we need to //! use runtime reflection instead. //!<|fim▁hole|>//! ```rust //! use std::fmt::Show; //! use std::any::Any; //! //! // Logger function for any type that implements Show. //! fn log<T: Any+Show>(value: &T) { //! let value_any = value as &Any; //! //! // try to convert our value to a String. If successful, we want to //! // output the String's length as well as its value. If not, it's a //! // different type: just print it out unadorned. //! match value_any.downcast_ref::<String>() { //! Some(as_string) => { //! println!("String ({}): {}", as_string.len(), as_string); //! } //! None => { //! println!("{:?}", value); //! } //! } //! } //! //! // This function wants to log its parameter out prior to doing work with it. //! fn do_work<T: Show+'static>(value: &T) { //! log(value); //! // ...do some other work //! } //! //! fn main() { //! let my_string = "Hello World".to_string(); //! do_work(&my_string); //! //! let my_i8: i8 = 100; //! do_work(&my_i8); //! } //! ``` #![stable] use mem::{transmute}; use option::Option; use option::Option::{Some, None}; use raw::TraitObject; use intrinsics::TypeId; /////////////////////////////////////////////////////////////////////////////// // Any trait /////////////////////////////////////////////////////////////////////////////// /// The `Any` trait is implemented by all `'static` types, and can be used for /// dynamic typing /// /// Every type with no non-`'static` references implements `Any`, so `Any` can /// be used as a trait object to emulate the effects dynamic typing. #[stable] pub trait Any: 'static { /// Get the `TypeId` of `self` #[experimental = "this method will likely be replaced by an associated static"] fn get_type_id(&self) -> TypeId; } impl<T: 'static> Any for T { fn get_type_id(&self) -> TypeId { TypeId::of::<T>() } } /////////////////////////////////////////////////////////////////////////////// // Extension methods for Any trait objects. // Implemented as three extension traits so that the methods can be generic. /////////////////////////////////////////////////////////////////////////////// impl Any { /// Returns true if the boxed type is the same as `T` #[stable] #[inline] pub fn is<T: 'static>(&self) -> bool { // Get TypeId of the type this function is instantiated with let t = TypeId::of::<T>(); // Get TypeId of the type in the trait object let boxed = self.get_type_id(); // Compare both TypeIds on equality t == boxed } /// Returns some reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[unstable = "naming conventions around acquiring references may change"] #[inline] pub fn downcast_ref<'a, T: 'static>(&'a self) -> Option<&'a T> { if self.is::<T>() { unsafe { // Get the raw representation of the trait object let to: TraitObject = transmute(self); // Extract the data pointer Some(transmute(to.data)) } } else { None } } /// Returns some mutable reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[unstable = "naming conventions around acquiring references may change"] #[inline] pub fn downcast_mut<'a, T: 'static>(&'a mut self) -> Option<&'a mut T> { if self.is::<T>() { unsafe { // Get the raw representation of the trait object let to: TraitObject = transmute(self); // Extract the data pointer Some(transmute(to.data)) } } else { None } } }<|fim▁end|>
<|file_name|>BasicGroup.java<|end_file_name|><|fim▁begin|>package com.github.kolandroid.kol.model.elements.basic; import com.github.kolandroid.kol.model.elements.interfaces.ModelGroup; import java.util.ArrayList; import java.util.Iterator; public class BasicGroup<E> implements ModelGroup<E> { /** * Autogenerated by eclipse. */ private static final long serialVersionUID = 356357357356695L; private final ArrayList<E> items; private final String name; public BasicGroup(String name) { this(name, new ArrayList<E>()); } public BasicGroup(String name, ArrayList<E> items) { this.name = name; this.items = items; } @Override public int size() { return items.size(); } @Override public E get(int index) { return items.get(index); } @Override public void set(int index, E value) { items.set(index, value); } @Override public void remove(int index) { items.remove(index); }<|fim▁hole|> public void add(E item) { items.add(item); } @Override public String getName() { return name; } @Override public Iterator<E> iterator() { return items.iterator(); } }<|fim▁end|>
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() import politube.views urlpatterns = patterns('', url(r'^$', politube.views.home, name='home'), url(r'^about/', politube.views.about, name='about'), url(r'^plenary/', include('plenary.urls')), url(r'^deputy/', include('deputy.urls')), url(r'^videos_tools/', include('videos_tools.urls')), <|fim▁hole|> url(r'^admin/', include(admin.site.urls)), )<|fim▁end|>
# Uncomment the admin/doc line below to enable admin documentation: url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin:
<|file_name|>checked_count_ones.rs<|end_file_name|><|fim▁begin|>use integer::Integer; use malachite_base::num::logic::traits::CountOnes; impl Integer { /// Counts the number of ones in the binary expansion of an `Integer`. If the `Integer` is /// negative, the number of ones is infinite, so `None` is returned. /// /// Time: worst case O(n)<|fim▁hole|> /// where n = `self.significant_bits()` /// /// # Examples /// ``` /// extern crate malachite_base; /// extern crate malachite_nz; /// /// use malachite_base::num::basic::traits::Zero; /// use malachite_nz::integer::Integer; /// /// assert_eq!(Integer::ZERO.checked_count_ones(), Some(0)); /// // 105 = 1101001b /// assert_eq!(Integer::from(105).checked_count_ones(), Some(4)); /// assert_eq!(Integer::from(-105).checked_count_ones(), None); /// // 10^12 = 1110100011010100101001010001000000000000b /// assert_eq!(Integer::trillion().checked_count_ones(), Some(13)); /// ``` pub fn checked_count_ones(&self) -> Option<u64> { if self.sign { Some(self.abs.count_ones()) } else { None } } }<|fim▁end|>
/// /// Additional memory: worst case O(1) ///
<|file_name|>lldpparam.py<|end_file_name|><|fim▁begin|># # Copyright (c) 2008-2015 Citrix Systems, 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. # from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response from nssrc.com.citrix.netscaler.nitro.service.options import options from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception from nssrc.com.citrix.netscaler.nitro.util.nitro_util import nitro_util class lldpparam(base_resource) : """ Configuration for lldp params resource. """ def __init__(self) : self._holdtimetxmult = 0 self._timer = 0 self._mode = "" @property def holdtimetxmult(self) : """A multiplier for calculating the duration for which the receiving device stores the LLDP information in its database before discarding or removing it. The duration is calculated as the holdtimeTxMult (Holdtime Multiplier) parameter value multiplied by the timer (Timer) parameter value.<br/>Default value: 4<br/>Minimum length = 1<br/>Maximum length = 20. """ try : return self._holdtimetxmult except Exception as e: raise e @holdtimetxmult.setter def holdtimetxmult(self, holdtimetxmult) : """A multiplier for calculating the duration for which the receiving device stores the LLDP information in its database before discarding or removing it. The duration is calculated as the holdtimeTxMult (Holdtime Multiplier) parameter value multiplied by the timer (Timer) parameter value.<br/>Default value: 4<br/>Minimum length = 1<br/>Maximum length = 20 """ try : self._holdtimetxmult = holdtimetxmult except Exception as e: raise e @property def timer(self) : """Interval, in seconds, between LLDP packet data units (LLDPDUs). that the NetScaler ADC sends to a directly connected device.<br/>Default value: 30<br/>Minimum length = 1<br/>Maximum length = 3000. """<|fim▁hole|> return self._timer except Exception as e: raise e @timer.setter def timer(self, timer) : """Interval, in seconds, between LLDP packet data units (LLDPDUs). that the NetScaler ADC sends to a directly connected device.<br/>Default value: 30<br/>Minimum length = 1<br/>Maximum length = 3000 """ try : self._timer = timer except Exception as e: raise e @property def mode(self) : """Global mode of Link Layer Discovery Protocol (LLDP) on the NetScaler ADC. The resultant LLDP mode of an interface depends on the LLDP mode configured at the global and the interface levels.<br/>Possible values = NONE, TRANSMITTER, RECEIVER, TRANSCEIVER. """ try : return self._mode except Exception as e: raise e @mode.setter def mode(self, mode) : """Global mode of Link Layer Discovery Protocol (LLDP) on the NetScaler ADC. The resultant LLDP mode of an interface depends on the LLDP mode configured at the global and the interface levels.<br/>Possible values = NONE, TRANSMITTER, RECEIVER, TRANSCEIVER """ try : self._mode = mode except Exception as e: raise e def _get_nitro_response(self, service, response) : """ converts nitro response into object and returns the object array in case of get request. """ try : result = service.payload_formatter.string_to_resource(lldpparam_response, response, self.__class__.__name__) if(result.errorcode != 0) : if (result.errorcode == 444) : service.clear_session(self) if result.severity : if (result.severity == "ERROR") : raise nitro_exception(result.errorcode, str(result.message), str(result.severity)) else : raise nitro_exception(result.errorcode, str(result.message), str(result.severity)) return result.lldpparam except Exception as e : raise e def _get_object_name(self) : """ Returns the value of object identifier argument """ try : return None except Exception as e : raise e @classmethod def update(cls, client, resource) : """ Use this API to update lldpparam. """ try : if type(resource) is not list : updateresource = lldpparam() updateresource.holdtimetxmult = resource.holdtimetxmult updateresource.timer = resource.timer updateresource.mode = resource.mode return updateresource.update_resource(client) except Exception as e : raise e @classmethod def unset(cls, client, resource, args) : """ Use this API to unset the properties of lldpparam resource. Properties that need to be unset are specified in args array. """ try : if type(resource) is not list : unsetresource = lldpparam() return unsetresource.unset_resource(client, args) except Exception as e : raise e @classmethod def get(cls, client, name="", option_="") : """ Use this API to fetch all the lldpparam resources that are configured on netscaler. """ try : if not name : obj = lldpparam() response = obj.get_resources(client, option_) return response except Exception as e : raise e class Mode: NONE = "NONE" TRANSMITTER = "TRANSMITTER" RECEIVER = "RECEIVER" TRANSCEIVER = "TRANSCEIVER" class lldpparam_response(base_response) : def __init__(self, length=1) : self.lldpparam = [] self.errorcode = 0 self.message = "" self.severity = "" self.sessionid = "" self.lldpparam = [lldpparam() for _ in range(length)]<|fim▁end|>
try :
<|file_name|>direct.go<|end_file_name|><|fim▁begin|>package ray import ( "github.com/v2ray/v2ray-core/common/alloc" ) const ( bufferSize = 16 ) // NewRay creates a new Ray for direct traffic transport. func NewRay() Ray { return &directRay{ Input: make(chan *alloc.Buffer, bufferSize), Output: make(chan *alloc.Buffer, bufferSize), } } type directRay struct { Input chan *alloc.Buffer<|fim▁hole|>} func (this *directRay) OutboundInput() <-chan *alloc.Buffer { return this.Input } func (this *directRay) OutboundOutput() chan<- *alloc.Buffer { return this.Output } func (this *directRay) InboundInput() chan<- *alloc.Buffer { return this.Input } func (this *directRay) InboundOutput() <-chan *alloc.Buffer { return this.Output }<|fim▁end|>
Output chan *alloc.Buffer
<|file_name|>EnterKey.js<|end_file_name|><|fim▁begin|>module("tinymce.EnterKey", { setupModule: function() { QUnit.stop(); tinymce.init({ selector: "textarea", plugins: wpPlugins, add_unload_trigger: false, disable_nodechange: true, indent: false, skin: false, entities: 'raw', schema: 'html5', extended_valid_elements: 'div[id|style|contenteditable],span[id|style|contenteditable],#dt,#dd', valid_styles: { '*' : 'color,font-size,font-family,background-color,font-weight,font-style,text-decoration,float,margin,margin-top,margin-right,margin-bottom,margin-left,display,position,top,left' }, init_instance_callback: function(ed) { window.editor = ed; QUnit.start(); } }); }, teardown: function() { editor.settings.forced_root_block = 'p'; editor.settings.forced_root_block_attrs = null; editor.settings.end_container_on_empty_block = false; editor.settings.br_in_pre = true; editor.settings.keep_styles = true; delete editor.settings.force_p_newlines; } }); test('Enter at end of H1', function() { editor.setContent('<h1>abc</h1>'); Utils.setSelection('h1', 3); Utils.pressEnter(); equal(editor.getContent(), '<h1>abc</h1><p>\u00a0</p>'); equal(editor.selection.getRng(true).startContainer.nodeName, 'P'); }); test('Enter in midde of H1', function() { editor.setContent('<h1>abcd</h1>'); Utils.setSelection('h1', 2); Utils.pressEnter(); equal(editor.getContent(), '<h1>ab</h1><h1>cd</h1>'); equal(editor.selection.getRng(true).startContainer.parentNode.nodeName, 'H1'); }); test('Enter before text after EM', function() { editor.setContent('<p><em>a</em>b</p>'); editor.selection.setCursorLocation(editor.getBody().firstChild, 1); Utils.pressEnter(); equal(editor.getContent(), '<p><em>a</em></p><p>b</p>'); var rng = editor.selection.getRng(true); equal(rng.startContainer.nodeValue, 'b'); }); test('Enter before first IMG in P', function() { editor.setContent('<p><img alt="" src="about:blank" /></p>'); editor.selection.setCursorLocation(editor.getBody().firstChild, 0); Utils.pressEnter(); equal(editor.getContent(), '<p>\u00a0</p><p><img src="about:blank" alt="" /></p>'); }); test('Enter before last IMG in P with text', function() { editor.setContent('<p>abc<img alt="" src="about:blank" /></p>'); editor.selection.setCursorLocation(editor.getBody().firstChild, 1); Utils.pressEnter(); equal(editor.getContent(), '<p>abc</p><p><img src="about:blank" alt="" /></p>'); var rng = editor.selection.getRng(true); equal(rng.startContainer.nodeName, 'P'); equal(rng.startContainer.childNodes[rng.startOffset].nodeName, 'IMG'); }); test('Enter before last IMG in P with IMG sibling', function() { editor.setContent('<p><img src="about:blank" alt="" /><img src="about:blank" alt="" /></p>'); editor.selection.setCursorLocation(editor.getBody().firstChild, 1); Utils.pressEnter(); equal(editor.getContent(), '<p><img src="about:blank" alt="" /></p><p><img src="about:blank" alt="" /></p>'); var rng = editor.selection.getRng(true); equal(rng.startContainer.nodeName, 'P'); equal(rng.startContainer.childNodes[rng.startOffset].nodeName, 'IMG'); }); test('Enter after last IMG in P', function() { editor.setContent('<p>abc<img alt="" src="about:blank" /></p>'); editor.selection.setCursorLocation(editor.getBody().firstChild, 2); Utils.pressEnter(); equal(editor.getContent(), '<p>abc<img src="about:blank" alt="" /></p><p>\u00a0</p>'); }); test('Enter before last INPUT in P with text', function() { editor.setContent('<p>abc<input type="text" /></p>'); editor.selection.setCursorLocation(editor.getBody().firstChild, 1); Utils.pressEnter(); equal(editor.getContent(), '<p>abc</p><p><input type="text" /></p>'); var rng = editor.selection.getRng(true); equal(rng.startContainer.nodeName, 'P'); equal(rng.startContainer.childNodes[rng.startOffset].nodeName, 'INPUT'); }); test('Enter before last INPUT in P with IMG sibling', function() { editor.setContent('<p><input type="text" /><input type="text" /></p>'); editor.selection.setCursorLocation(editor.getBody().firstChild, 1); Utils.pressEnter(); equal(editor.getContent(), '<p><input type="text" /></p><p><input type="text" /></p>'); var rng = editor.selection.getRng(true); equal(rng.startContainer.nodeName, 'P'); equal(rng.startContainer.childNodes[rng.startOffset].nodeName, 'INPUT'); }); test('Enter after last INPUT in P', function() { editor.setContent('<p>abc<input type="text" /></p>'); editor.selection.setCursorLocation(editor.getBody().firstChild, 2); Utils.pressEnter(); equal(editor.getContent(), '<p>abc<input type="text" /></p><p>\u00a0</p>'); }); test('Enter at end of P', function() { editor.setContent('<p>abc</p>'); Utils.setSelection('p', 3); Utils.pressEnter(); equal(editor.getContent(), '<p>abc</p><p>\u00a0</p>'); equal(editor.selection.getRng(true).startContainer.nodeName, 'P'); }); test('Enter at end of EM inside P', function() { editor.setContent('<p><em>abc</em></p>'); Utils.setSelection('em', 3); Utils.pressEnter(); equal(Utils.cleanHtml(editor.getBody().innerHTML).replace(/<br([^>]+|)>|&nbsp;/g, ''), '<p><em>abc</em></p><p><em></em></p>'); equal(editor.selection.getRng(true).startContainer.nodeName, 'EM'); }); test('Enter at middle of EM inside P', function() { editor.setContent('<p><em>abcd</em></p>'); Utils.setSelection('em', 2); Utils.pressEnter(); equal(editor.getContent(), '<p><em>ab</em></p><p><em>cd</em></p>'); equal(editor.selection.getRng(true).startContainer.parentNode.nodeName, 'EM'); }); test('Enter at beginning EM inside P', function() { editor.setContent('<p><em>abc</em></p>'); Utils.setSelection('em', 0); Utils.pressEnter(); equal(Utils.cleanHtml(editor.getBody().innerHTML).replace(/<br([^>]+|)>|&nbsp;/g, ''), '<p><em></em></p><p><em>abc</em></p>'); equal(editor.selection.getRng(true).startContainer.nodeValue, 'abc'); }); test('Enter at end of STRONG in EM inside P', function() { editor.setContent('<p><em><strong>abc</strong></em></p>'); Utils.setSelection('strong', 3); Utils.pressEnter(); equal(Utils.cleanHtml(editor.getBody().innerHTML).replace(/<br([^>]+|)>|&nbsp;/g, ''), '<p><em><strong>abc</strong></em></p><p><em><strong></strong></em></p>'); equal(editor.selection.getRng(true).startContainer.nodeName, 'STRONG'); }); test('Enter at middle of STRONG in EM inside P', function() { editor.setContent('<p><em><strong>abcd</strong></em></p>'); Utils.setSelection('strong', 2); Utils.pressEnter(); equal(editor.getContent(), '<p><em><strong>ab</strong></em></p><p><em><strong>cd</strong></em></p>'); equal(editor.selection.getRng(true).startContainer.parentNode.nodeName, 'STRONG'); }); test('Enter at beginning STRONG in EM inside P', function() { editor.setContent('<p><em><strong>abc</strong></em></p>'); Utils.setSelection('strong', 0); Utils.pressEnter(); equal(Utils.cleanHtml(editor.getBody().innerHTML).replace(/<br([^>]+|)>|&nbsp;/g, ''), '<p><em><strong></strong></em></p><p><em><strong>abc</strong></em></p>'); equal(editor.selection.getRng(true).startContainer.nodeValue, 'abc'); }); test('Enter at beginning of P', function() { editor.setContent('<p>abc</p>'); Utils.setSelection('p', 0); Utils.pressEnter(); equal(editor.getContent(), '<p>\u00a0</p><p>abc</p>'); equal(editor.selection.getRng(true).startContainer.nodeValue, 'abc'); }); test('Enter at middle of P with style, id and class attributes', function() { editor.setContent('<p id="a" class="b" style="color:#000">abcd</p>'); Utils.setSelection('p', 2); Utils.pressEnter(); equal(editor.getContent(), '<p id="a" class="b" style="color: #000;">ab</p><p class="b" style="color: #000;">cd</p>'); equal(editor.selection.getRng(true).startContainer.parentNode.nodeName, 'P'); }); test('Enter at a range between H1 and P', function() { editor.setContent('<h1>abcd</h1><p>efgh</p>'); Utils.setSelection('h1', 2, 'p', 2); Utils.pressEnter(); equal(editor.getContent(), '<h1>abgh</h1>'); equal(editor.selection.getNode().nodeName, 'H1'); }); test('Enter at end of H1 in HGROUP', function() { editor.setContent('<hgroup><h1>abc</h1></hgroup>'); Utils.setSelection('h1', 3); Utils.pressEnter(); equal(editor.getContent(), '<hgroup><h1>abc</h1><h1>\u00a0</h1></hgroup>'); equal(editor.selection.getRng(true).startContainer.nodeName, 'H1'); }); test('Enter inside empty TD', function() { editor.getBody().innerHTML = '<table><tr><td></td></tr></table>'; Utils.setSelection('td', 0); Utils.pressEnter(); equal(Utils.cleanHtml(editor.getBody().innerHTML).replace(/<br([^>]+|)>|&nbsp;/g, ''), '<table><tbody><tr><td><p></p><p></p></td></tr></tbody></table>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Shift+Enter inside STRONG inside TD with BR', function() { editor.getBody().innerHTML = '<table><tr><td>d <strong>e</strong><br></td></tr></table>'; Utils.setSelection('strong', 1); Utils.pressEnter({shiftKey: true}); equal(Utils.cleanHtml(editor.getBody().innerHTML), '<table><tbody><tr><td>d <strong>e<br></strong><br></td></tr></tbody></table>'); equal(editor.selection.getNode().nodeName, 'STRONG'); }); test('Enter inside middle of text node in body', function() { editor.getBody().innerHTML = 'abcd'; Utils.setSelection('body', 2); Utils.pressEnter(); equal(editor.getContent(), '<p>ab</p><p>cd</p>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Enter inside at beginning of text node in body', function() { editor.getBody().innerHTML = 'abcd'; Utils.setSelection('body', 0); Utils.pressEnter(); equal(editor.getContent(), '<p>\u00a0</p><p>abcd</p>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Enter inside at end of text node in body', function() { editor.getBody().innerHTML = 'abcd'; Utils.setSelection('body', 4); Utils.pressEnter(); equal(editor.getContent(), '<p>abcd</p><p>\u00a0</p>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Enter inside empty body', function() { editor.getBody().innerHTML = ''; Utils.setSelection('body', 0); Utils.pressEnter(); equal(editor.getContent(), '<p>\u00a0</p><p>\u00a0</p>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Enter inside empty li in beginning of ol', function() { editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<ol><li></li><li>a</li></ol>' : '<ol><li><br></li><li>a</li></ol>'; Utils.setSelection('li', 0); Utils.pressEnter(); equal(editor.getContent(), '<p>\u00a0</p><ol><li>a</li></ol>');<|fim▁hole|> equal(editor.selection.getNode().nodeName, 'P'); }); test('Enter inside empty li at the end of ol', function() { editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<ol><li>a</li><li></li></ol>' : '<ol><li>a</li><li><br></li></ol>'; Utils.setSelection('li:last', 0); Utils.pressEnter(); equal(editor.getContent(), '<ol><li>a</li></ol><p>\u00a0</p>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Shift+Enter inside empty li in the middle of ol', function() { editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<ol><li>a</li><li></li><li>b</li></ol>' : '<ol><li>a</li><li><br></li><li>b</li></ol>'; Utils.setSelection('li:nth-child(2)', 0); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<ol><li>a</li></ol><p>\u00a0</p><ol><li>b</li></ol>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Shift+Enter inside empty li in beginning of ol', function() { editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<ol><li></li><li>a</li></ol>' : '<ol><li><br></li><li>a</li></ol>'; Utils.setSelection('li', 0); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<p>\u00a0</p><ol><li>a</li></ol>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Shift+Enter inside empty li at the end of ol', function() { editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<ol><li>a</li><li></li></ol>' : '<ol><li>a</li><li><br></li></ol>'; Utils.setSelection('li:last', 0); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<ol><li>a</li></ol><p>\u00a0</p>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Enter inside empty li in the middle of ol with forced_root_block: false', function() { editor.settings.forced_root_block = false; editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<ol><li>a</li><li></li><li>b</li></ol>' : '<ol><li>a</li><li><br></li><li>b</li></ol>'; Utils.setSelection('li:nth-child(2)', 0); Utils.pressEnter(); equal(editor.getContent(), '<ol><li>a</li></ol><br /><ol><li>b</li></ol>'); equal(editor.selection.getNode().nodeName, 'BODY'); }); test('Enter inside empty li in beginning of ol with forced_root_block: false', function() { editor.settings.forced_root_block = false; editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<ol><li></li><li>a</li></ol>' : '<ol><li><br></li><li>a</li></ol>'; Utils.setSelection('li', 0); Utils.pressEnter(); equal(editor.getContent(), '<br /><ol><li>a</li></ol>'); equal(editor.selection.getNode().nodeName, 'BODY'); }); test('Enter inside empty li at the end of ol with forced_root_block: false', function() { editor.settings.forced_root_block = false; editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<ol><li>a</li><li></li></ol>' : '<ol><li>a</li><li><br></li></ol>'; Utils.setSelection('li:last', 0); Utils.pressEnter(); equal(Utils.cleanHtml(editor.getBody().innerHTML), '<ol><li>a</li></ol><br>'); equal(editor.selection.getNode().nodeName, 'BODY'); }); test('Enter inside empty li in the middle of ol', function() { editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<ol><li>a</li><li></li><li>b</li></ol>' : '<ol><li>a</li><li><br></li><li>b</li></ol>'; Utils.setSelection('li:nth-child(2)', 0); Utils.pressEnter(); equal(editor.getContent(), '<ol><li>a</li></ol><p>\u00a0</p><ol><li>b</li></ol>'); equal(editor.selection.getNode().nodeName, 'P'); }); // Nested lists in LI elements test('Enter inside empty LI in beginning of OL in LI', function() { editor.getBody().innerHTML = Utils.trimBrsOnIE( '<ol>' + '<li>a' + '<ol>' + '<li><br></li>' + '<li>a</li>' + '</ol>' + '</li>' + '</ol>' ); Utils.setSelection('li li', 0); editor.focus(); Utils.pressEnter(); equal(editor.getContent(), '<ol>' + '<li>a</li>' + '<li>' + '<ol>' + '<li>a</li>' + '</ol>' + '</li>' + '</ol>' ); equal(editor.selection.getNode().nodeName, 'LI'); }); test('Enter inside empty LI in middle of OL in LI', function() { editor.getBody().innerHTML = Utils.trimBrsOnIE( '<ol>' + '<li>a' + '<ol>' + '<li>a</li>' + '<li><br></li>' + '<li>b</li>' + '</ol>' + '</li>' + '</ol>' ); Utils.setSelection('li li:nth-child(2)', 0); editor.focus(); Utils.pressEnter(); equal(editor.getContent(), '<ol>' + '<li>a' + '<ol>' + '<li>a</li>' + '</ol>' + '</li>' + '<li>\u00a0' + '<ol>' + '<li>b</li>' + '</ol>' + '</li>' + '</ol>' ); // Ignore on IE 7, 8 this is a known bug not worth fixing if (!tinymce.Env.ie || tinymce.Env.ie > 8) { equal(editor.selection.getNode().nodeName, 'LI'); } }); test('Enter inside empty LI in end of OL in LI', function() { editor.getBody().innerHTML = Utils.trimBrsOnIE( '<ol>' + '<li>a' + '<ol>' + '<li>a</li>' + '<li><br></li>' + '</ol>' + '</li>' + '</ol>' ); Utils.setSelection('li li:last', 0); editor.focus(); Utils.pressEnter(); equal(editor.getContent(), '<ol>' + '<li>a' + '<ol>' + '<li>a</li>' + '</ol>' + '</li>' + '<li></li>' + '</ol>' ); equal(editor.selection.getNode().nodeName, 'LI'); }); // Nested lists in OL elements // Ignore on IE 7, 8 this is a known bug not worth fixing if (!tinymce.Env.ie || tinymce.Env.ie > 8) { test('Enter before nested list', function() { editor.getBody().innerHTML = Utils.trimBrsOnIE( '<ol>' + '<li>a' + '<ul>' + '<li>b</li>' + '<li>c</li>' + '</ul>' + '</li>' + '</ol>' ); Utils.setSelection('ol > li', 1); editor.focus(); Utils.pressEnter(); equal(editor.getContent(), '<ol>' + '<li>a</li>' + '<li>\u00a0' + '<ul>' + '<li>b</li>' + '<li>c</li>' + '</ul>' + '</li>' + '</ol>' ); equal(editor.selection.getNode().nodeName, 'LI'); }); } test('Enter inside empty LI in beginning of OL in OL', function() { editor.getBody().innerHTML = Utils.trimBrsOnIE( '<ol>' + '<li>a</li>' + '<ol>' + '<li><br></li>' + '<li>a</li>' + '</ol>' + '</ol>' ); Utils.setSelection('ol ol li', 0); editor.focus(); Utils.pressEnter(); equal(editor.getContent(), '<ol>' + '<li>a</li>' + '<li></li>' + '<ol>' + '<li>a</li>' + '</ol>' + '</ol>' ); equal(editor.selection.getNode().nodeName, 'LI'); }); test('Enter inside empty LI in middle of OL in OL', function() { editor.getBody().innerHTML = Utils.trimBrsOnIE( '<ol>' + '<li>a</li>' + '<ol>' + '<li>a</li>' + '<li><br></li>' + '<li>b</li>' + '</ol>' + '</ol>' ); Utils.setSelection('ol ol li:nth-child(2)', 0); editor.focus(); Utils.pressEnter(); equal(editor.getContent(), '<ol>' + '<li>a</li>' + '<ol>' + '<li>a</li>' + '</ol>' + '<li></li>' + '<ol>' + '<li>b</li>' + '</ol>' + '</ol>' ); equal(editor.selection.getNode().nodeName, 'LI'); }); test('Enter inside empty LI in end of OL in OL', function() { editor.getBody().innerHTML = Utils.trimBrsOnIE( '<ol>' + '<li>a</li>' + '<ol>' + '<li>a</li>' + '<li><br></li>' + '</ol>' + '</ol>' ); Utils.setSelection('ol ol li:last', 0); editor.focus(); Utils.pressEnter(); equal(editor.getContent(), '<ol>' + '<li>a</li>' + '<ol>' + '<li>a</li>' + '</ol>' + '<li></li>' + '</ol>' ); equal(editor.selection.getNode().nodeName, 'LI'); }); test('Enter at beginning of first DT inside DL', function() { editor.getBody().innerHTML = '<dl><dt>a</dt></dl>'; Utils.setSelection('dt', 0); Utils.pressEnter(); equal(editor.getContent(), '<dl><dt>\u00a0</dt><dt>a</dt></dl>'); equal(editor.selection.getNode().nodeName, 'DT'); }); test('Enter at beginning of first DD inside DL', function() { editor.getBody().innerHTML = '<dl><dd>a</dd></dl>'; Utils.setSelection('dd', 0); Utils.pressEnter(); equal(editor.getContent(), '<dl><dd>\u00a0</dd><dd>a</dd></dl>'); equal(editor.selection.getNode().nodeName, 'DD'); }); test('Enter at beginning of middle DT inside DL', function() { editor.getBody().innerHTML = '<dl><dt>a</dt><dt>b</dt><dt>c</dt></dl>'; Utils.setSelection('dt:nth-child(2)', 0); Utils.pressEnter(); equal(editor.getContent(), '<dl><dt>a</dt><dt>\u00a0</dt><dt>b</dt><dt>c</dt></dl>'); equal(editor.selection.getNode().nodeName, 'DT'); }); test('Enter at beginning of middle DD inside DL', function() { editor.getBody().innerHTML = '<dl><dd>a</dd><dd>b</dd><dd>c</dd></dl>'; Utils.setSelection('dd:nth-child(2)', 0); Utils.pressEnter(); equal(editor.getContent(), '<dl><dd>a</dd><dd>\u00a0</dd><dd>b</dd><dd>c</dd></dl>'); equal(editor.selection.getNode().nodeName, 'DD'); }); test('Enter at end of last DT inside DL', function() { editor.getBody().innerHTML = '<dl><dt>a</dt></dl>'; Utils.setSelection('dt', 1); Utils.pressEnter(); equal(editor.getContent(), '<dl><dt>a</dt><dt>\u00a0</dt></dl>'); equal(editor.selection.getNode().nodeName, 'DT'); }); test('Enter at end of last DD inside DL', function() { editor.getBody().innerHTML = '<dl><dd>a</dd></dl>'; Utils.setSelection('dd', 1); Utils.pressEnter(); equal(editor.getContent(), '<dl><dd>a</dd><dd>\u00a0</dd></dl>'); equal(editor.selection.getNode().nodeName, 'DD'); }); test('Enter at end of last empty DT inside DL', function() { editor.getBody().innerHTML = '<dl><dt>a</dt><dt></dt></dl>'; Utils.setSelection('dt:nth-child(2)', 0); Utils.pressEnter(); equal(editor.getContent(), '<dl><dt>a</dt></dl><p>\u00a0</p>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Enter at end of last empty DD inside DL', function() { editor.getBody().innerHTML = '<dl><dd>a</dd><dd></dd></dl>'; Utils.setSelection('dd:nth-child(2)', 0); Utils.pressEnter(); equal(editor.getContent(), '<dl><dd>a</dd></dl><p>\u00a0</p>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Enter at beginning of P inside LI', function() { editor.getBody().innerHTML = '<ol><li><p>abcd</p></li></ol>'; Utils.setSelection('p', 0); Utils.pressEnter(); equal(editor.getContent(), '<ol><li></li><li><p>abcd</p></li></ol>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Enter inside middle of P inside LI', function() { editor.getBody().innerHTML = '<ol><li><p>abcd</p></li></ol>'; Utils.setSelection('p', 2); Utils.pressEnter(); equal(editor.getContent(), '<ol><li><p>ab</p></li><li><p>cd</p></li></ol>'); // Ignore on IE 7, 8 this is a known bug not worth fixing if (!tinymce.Env.ie || tinymce.Env.ie > 8) { equal(editor.selection.getNode().nodeName, 'P'); } }); test('Enter at end of P inside LI', function() { editor.getBody().innerHTML = '<ol><li><p>abcd</p></li></ol>'; Utils.setSelection('p', 4); Utils.pressEnter(); equal(editor.getContent(), '<ol><li><p>abcd</p></li><li></li></ol>'); equal(editor.selection.getNode().nodeName, 'LI'); }); test('Shift+Enter at beginning of P inside LI', function() { editor.getBody().innerHTML = '<ol><li><p>abcd</p></li></ol>'; Utils.setSelection('p', 0); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<ol><li><p><br />abcd</p></li></ol>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Shift+Enter inside middle of P inside LI', function() { editor.getBody().innerHTML = '<ol><li><p>abcd</p></li></ol>'; Utils.setSelection('p', 2); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<ol><li><p>ab<br />cd</p></li></ol>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Shift+Enter at end of P inside LI', function() { editor.getBody().innerHTML = '<ol><li><p>abcd</p></li></ol>'; Utils.setSelection('p', 4); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), (tinymce.isIE && tinymce.Env.ie < 11) ? '<ol><li><p>abcd</p></li></ol>' : '<ol><li><p>abcd<br /><br /></p></li></ol>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Ctrl+Enter at beginning of P inside LI', function() { editor.getBody().innerHTML = '<ol><li><p>abcd</p></li></ol>'; Utils.setSelection('p', 0); Utils.pressEnter({ctrlKey: true}); equal(editor.getContent(), '<ol><li><p>\u00a0</p><p>abcd</p></li></ol>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Ctrl+Enter inside middle of P inside LI', function() { editor.getBody().innerHTML = '<ol><li><p>abcd</p></li></ol>'; Utils.setSelection('p', 2); Utils.pressEnter({ctrlKey: true}); equal(editor.getContent(), '<ol><li><p>ab</p><p>cd</p></li></ol>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Ctrl+Enter at end of P inside LI', function() { editor.getBody().innerHTML = '<ol><li><p>abcd</p></li></ol>'; Utils.setSelection('p', 4); Utils.pressEnter({ctrlKey: true}); equal(editor.getContent(), '<ol><li><p>abcd</p><p>\u00a0</p></li></ol>'); equal(editor.selection.getNode().nodeName, 'P'); }); test('Enter in the middle of text in P with forced_root_block set to false', function() { editor.settings.forced_root_block = false; editor.getBody().innerHTML = '<p>abc</p>'; Utils.setSelection('p', 2); Utils.pressEnter(); equal(editor.getContent(), '<p>ab<br />c</p>'); }); test('Enter at the end of text in P with forced_root_block set to false', function() { editor.settings.forced_root_block = false; editor.getBody().innerHTML = '<p>abc</p>'; Utils.setSelection('p', 3); Utils.pressEnter(); equal(Utils.cleanHtml(editor.getBody().innerHTML), (tinymce.isIE && tinymce.Env.ie < 11) ? '<p>abc<br></p>' : '<p>abc<br><br></p>'); }); test('Enter at the middle of text in BODY with forced_root_block set to false', function() { editor.settings.forced_root_block = false; editor.getBody().innerHTML = 'abcd'; Utils.setSelection('body', 2); editor.focus(); Utils.pressEnter(); equal(Utils.cleanHtml(editor.getBody().innerHTML), 'ab<br>cd'); }); test('Enter at the beginning of text in BODY with forced_root_block set to false', function() { editor.settings.forced_root_block = false; editor.getBody().innerHTML = 'abcd'; Utils.setSelection('body', 0); editor.focus(); Utils.pressEnter(); equal(Utils.cleanHtml(editor.getBody().innerHTML), '<br>abcd'); }); test('Enter at the end of text in BODY with forced_root_block set to false', function() { editor.settings.forced_root_block = false; editor.getBody().innerHTML = 'abcd'; Utils.setSelection('body', 4); editor.focus(); Utils.pressEnter(); equal(Utils.cleanHtml(editor.getBody().innerHTML), (tinymce.isIE && tinymce.Env.ie < 11) ? 'abcd<br>' : 'abcd<br><br>'); }); test('Enter in empty P at the end of a blockquote and end_container_on_empty_block: true', function() { editor.settings.end_container_on_empty_block = true; editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<blockquote><p>abc</p><p></p></blockquote>' : '<blockquote><p>abc</p><p><br></p></blockquote>'; Utils.setSelection('p:last', 0); Utils.pressEnter(); equal(editor.getContent(), '<blockquote><p>abc</p></blockquote><p>\u00a0</p>'); }); test('Enter in empty P at the beginning of a blockquote and end_container_on_empty_block: true', function() { editor.settings.end_container_on_empty_block = true; editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<blockquote><p></p><p>abc</p></blockquote>' : '<blockquote><p><br></p><p>abc</p></blockquote>'; Utils.setSelection('p', 0); Utils.pressEnter(); equal(editor.getContent(), '<p>\u00a0</p><blockquote><p>abc</p></blockquote>'); }); test('Enter in empty P at in the middle of a blockquote and end_container_on_empty_block: true', function() { editor.settings.end_container_on_empty_block = true; editor.getBody().innerHTML = (tinymce.isIE && tinymce.Env.ie < 11) ? '<blockquote><p>abc</p><p></p><p>123</p></blockquote>' : '<blockquote><p>abc</p><p><br></p><p>123</p></blockquote>'; Utils.setSelection('p:nth-child(2)', 0); Utils.pressEnter(); equal(editor.getContent(), '<blockquote><p>abc</p></blockquote><p>\u00a0</p><blockquote><p>123</p></blockquote>'); }); test('Enter inside empty P with empty P siblings', function() { // Tests that a workaround for an IE bug is working correctly editor.getBody().innerHTML = '<p></p><p></p><p>X</p>'; Utils.setSelection('p', 0); Utils.pressEnter(); equal(editor.getContent(), '<p>\u00a0</p><p>\u00a0</p><p>\u00a0</p><p>X</p>'); }); test('Enter at end of H1 with forced_root_block_attrs', function() { editor.settings.forced_root_block_attrs = {"class": "class1"}; editor.getBody().innerHTML = '<h1>a</h1>'; Utils.setSelection('h1', 1); Utils.pressEnter(); equal(editor.getContent(), '<h1>a</h1><p class="class1">\u00a0</p>'); }); test('Shift+Enter at beginning of P', function() { editor.getBody().innerHTML = '<p>abc</p>'; Utils.setSelection('p', 0); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<p><br />abc</p>'); }); test('Shift+Enter in the middle of P', function() { editor.getBody().innerHTML = '<p>abcd</p>'; Utils.setSelection('p', 2); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<p>ab<br />cd</p>'); }); test('Shift+Enter at the end of P', function() { editor.getBody().innerHTML = '<p>abcd</p>'; Utils.setSelection('p', 4); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), (tinymce.isIE && tinymce.Env.ie < 11) ? '<p>abcd</p>' : '<p>abcd<br /><br /></p>'); }); test('Shift+Enter in the middle of B with a BR after it', function() { editor.getBody().innerHTML = '<p><b>abcd</b><br></p>'; Utils.setSelection('b', 2); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<p><b>ab<br />cd</b></p>'); }); test('Shift+Enter at the end of B with a BR after it', function() { editor.getBody().innerHTML = '<p><b>abcd</b><br></p>'; Utils.setSelection('b', 4); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<p><b>abcd<br /></b></p>'); }); test('Enter in beginning of PRE', function() { editor.getBody().innerHTML = '<pre>abc</pre>'; Utils.setSelection('pre', 0); Utils.pressEnter(); equal(editor.getContent(), '<pre><br />abc</pre>'); }); test('Enter in the middle of PRE', function() { editor.getBody().innerHTML = '<pre>abcd</pre>'; Utils.setSelection('pre', 2); Utils.pressEnter(); equal(editor.getContent(), '<pre>ab<br />cd</pre>'); }); test('Enter at the end of PRE', function() { editor.getBody().innerHTML = '<pre>abcd</pre>'; Utils.setSelection('pre', 4); Utils.pressEnter(); equal(editor.getContent(), (tinymce.isIE && tinymce.Env.ie < 11) ? '<pre>abcd</pre>' : '<pre>abcd<br /><br /></pre>'); }); test('Enter in beginning of PRE and br_in_pre: false', function() { editor.settings.br_in_pre = false; editor.getBody().innerHTML = '<pre>abc</pre>'; Utils.setSelection('pre', 0); Utils.pressEnter(); equal(editor.getContent(), '<pre>\u00a0</pre><pre>abc</pre>'); }); test('Enter in the middle of PRE and br_in_pre: false', function() { editor.settings.br_in_pre = false; editor.getBody().innerHTML = '<pre>abcd</pre>'; Utils.setSelection('pre', 2); Utils.pressEnter(); equal(editor.getContent(), '<pre>ab</pre><pre>cd</pre>'); }); test('Enter at the end of PRE and br_in_pre: false', function() { editor.settings.br_in_pre = false; editor.getBody().innerHTML = '<pre>abcd</pre>'; Utils.setSelection('pre', 4); Utils.pressEnter(); equal(editor.getContent(), '<pre>abcd</pre><p>\u00a0</p>'); }); test('Shift+Enter in beginning of PRE', function() { editor.getBody().innerHTML = '<pre>abc</pre>'; Utils.setSelection('pre', 0); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<pre>\u00a0</pre><pre>abc</pre>'); }); test('Shift+Enter in the middle of PRE', function() { editor.getBody().innerHTML = '<pre>abcd</pre>'; Utils.setSelection('pre', 2); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<pre>ab</pre><pre>cd</pre>'); }); test('Shift+Enter at the end of PRE', function() { editor.getBody().innerHTML = '<pre>abcd</pre>'; Utils.setSelection('pre', 4); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<pre>abcd</pre><p>\u00a0</p>'); }); test('Shift+Enter in beginning of P with forced_root_block set to false', function() { editor.settings.forced_root_block = false; editor.getBody().innerHTML = '<p>abc</p>'; Utils.setSelection('p', 0); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<p>\u00a0</p><p>abc</p>'); }); test('Shift+Enter in middle of P with forced_root_block set to false', function() { editor.settings.forced_root_block = false; editor.getBody().innerHTML = '<p>abcd</p>'; Utils.setSelection('p', 2); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<p>ab</p><p>cd</p>'); }); test('Shift+Enter at the end of P with forced_root_block set to false', function() { editor.settings.forced_root_block = false; editor.getBody().innerHTML = '<p>abc</p>'; Utils.setSelection('p', 3); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<p>abc</p><p>\u00a0</p>'); }); test('Shift+Enter in body with forced_root_block set to false', function() { editor.settings.forced_root_block = false; editor.getBody().innerHTML = 'abcd'; var rng = editor.dom.createRng(); rng.setStart(editor.getBody().firstChild, 2); rng.setEnd(editor.getBody().firstChild, 2); editor.selection.setRng(rng); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<p>ab</p><p>cd</p>'); }); test('Enter at the end of DIV layer', function() { editor.settings.br_in_pre = false; editor.setContent('<div style="position: absolute; top: 1px; left: 2px;">abcd</div>'); Utils.setSelection('div', 4); Utils.pressEnter(); equal(editor.getContent(), '<div style="position: absolute; top: 1px; left: 2px;"><p>abcd</p><p>\u00a0</p></div>'); }); test('Enter in div inside contentEditable:false div', function() { editor.getBody().innerHTML = '<div data-mce-contenteditable="false"><div>abcd</div></div>'; Utils.setSelection('div div', 2); Utils.pressEnter(); equal(Utils.cleanHtml(editor.getBody().innerHTML), '<div data-mce-contenteditable="false"><div>abcd</div></div>'); }); test('Enter in div with contentEditable:true inside contentEditable:false div', function() { editor.getBody().innerHTML = '<div data-mce-contenteditable="false"><div data-mce-contenteditable="true">abcd</div></div>'; Utils.setSelection('div div', 2); Utils.pressEnter(); equal(Utils.cleanHtml(editor.getBody().innerHTML), '<div data-mce-contenteditable="false"><div data-mce-contenteditable="true"><p>ab</p><p>cd</p></div></div>'); }); test('Enter in span with contentEditable:true inside contentEditable:false div', function() { editor.getBody().innerHTML = '<div data-mce-contenteditable="false"><span data-mce-contenteditable="true">abcd</span></div>'; Utils.setSelection('span', 2); Utils.pressEnter(); equal(Utils.cleanHtml(editor.getBody().innerHTML), '<div data-mce-contenteditable="false"><span data-mce-contenteditable="true">abcd</span></div>'); }); test('Shift+Enter in span with contentEditable:true inside contentEditable:false div', function() { editor.getBody().innerHTML = '<div data-mce-contenteditable="false"><span data-mce-contenteditable="true">abcd</span></div>'; Utils.setSelection('span', 2); Utils.pressEnter({shiftKey: true}); equal(Utils.cleanHtml(editor.getBody().innerHTML), '<div data-mce-contenteditable="false"><span data-mce-contenteditable="true">ab<br>cd</span></div>'); }); test('Enter in span with contentEditable:true inside contentEditable:false div and forced_root_block: false', function() { editor.settings.forced_root_block = false; editor.getBody().innerHTML = '<div data-mce-contenteditable="false"><span data-mce-contenteditable="true">abcd</span></div>'; Utils.setSelection('span', 2); Utils.pressEnter(); equal(Utils.cleanHtml(editor.getBody().innerHTML), '<div data-mce-contenteditable="false"><span data-mce-contenteditable="true">ab<br>cd</span></div>'); }); test('Enter in em within contentEditable:true div inside contentEditable:false div', function() { editor.getBody().innerHTML = '<div data-mce-contenteditable="false"><div data-mce-contenteditable="true"><em>abcd</em></div></div>'; Utils.setSelection('em', 2); Utils.pressEnter(); equal(Utils.cleanHtml(editor.getBody().innerHTML), '<div data-mce-contenteditable="false"><div data-mce-contenteditable="true"><p><em>ab</em></p><p><em>cd</em></p></div></div>'); }); test('Enter at end of text in a span inside a P and keep_styles: false', function() { editor.settings.keep_styles = false; editor.getBody().innerHTML = '<p><em><span style="font-size: 13px;">X</span></em></p>'; Utils.setSelection('span', 1); Utils.pressEnter(); equal(editor.getContent(), '<p><em><span style="font-size: 13px;">X</span></em></p><p>\u00a0</p>'); }); test('Shift+enter in LI when forced_root_block: false', function() { editor.settings.forced_root_block = false; editor.getBody().innerHTML = '<ul><li>text</li></ul>'; Utils.setSelection('li', 2); Utils.pressEnter({shiftKey: true}); equal(editor.getContent(), '<ul><li>te<br />xt</li></ul>'); }); test('Enter when forced_root_block: false and force_p_newlines: true', function() { editor.settings.forced_root_block = false; editor.settings.force_p_newlines = true; editor.getBody().innerHTML = 'text'; Utils.setSelection('body', 2); Utils.pressEnter(); equal(editor.getContent(), '<p>te</p><p>xt</p>'); }); test('Enter at end of br line', function() { editor.settings.forced_root_block = false; editor.settings.force_p_newlines = true; editor.getBody().innerHTML = '<p>a<br>b</p>'; Utils.setSelection('p', 1); Utils.pressEnter(); equal(editor.getContent(), '<p>a</p><p><br />b</p>'); var rng = editor.selection.getRng(true); equal(rng.startContainer.nodeName, 'P'); equal(rng.startContainer.childNodes[rng.startOffset].nodeName, 'BR'); }); // Ignore on IE 7, 8 this is a known bug not worth fixing if (!tinymce.Env.ie || tinymce.Env.ie > 8) { test('Enter before BR between DIVs', function() { editor.getBody().innerHTML = '<div>a<span>b</span>c</div><br /><div>d</div>'; var rng = editor.dom.createRng(); rng.setStartBefore(editor.dom.select('br')[0]); rng.setEndBefore(editor.dom.select('br')[0]); editor.selection.setRng(rng); Utils.pressEnter(); equal(editor.getContent(), '<div>a<span>b</span>c</div><p>\u00a0</p><p>\u00a0</p><div>d</div>'); }); } // Only test these on modern browsers if (window.getSelection) { test('Enter behind table element', function() { var rng = editor.dom.createRng(); editor.getBody().innerHTML = '<table><tbody><td>x</td></tbody></table>'; rng.setStartAfter(editor.getBody().lastChild); rng.setEndAfter(editor.getBody().lastChild); editor.selection.setRng(rng); Utils.pressEnter(); equal(editor.getContent(), '<table><tbody><tr><td>x</td></tr></tbody></table><p>\u00a0</p>'); }); test('Enter before table element', function() { var rng = editor.dom.createRng(); editor.getBody().innerHTML = '<table><tbody><td>x</td></tbody></table>'; rng.setStartBefore(editor.getBody().lastChild); rng.setEndBefore(editor.getBody().lastChild); editor.selection.setRng(rng); Utils.pressEnter(); equal(editor.getContent(), '<p>\u00a0</p><table><tbody><tr><td>x</td></tr></tbody></table>'); }); test('Enter behind table followed by a p', function() { var rng = editor.dom.createRng(); editor.getBody().innerHTML = '<table><tbody><td>x</td></tbody></table><p>x</p>'; rng.setStartAfter(editor.getBody().firstChild); rng.setEndAfter(editor.getBody().firstChild); editor.selection.setRng(rng); Utils.pressEnter(); equal(editor.getContent(), '<table><tbody><tr><td>x</td></tr></tbody></table><p>\u00a0</p><p>x</p>'); }); test('Enter before table element preceded by a p', function() { var rng = editor.dom.createRng(); editor.getBody().innerHTML = '<p>x</p><table><tbody><td>x</td></tbody></table>'; rng.setStartBefore(editor.getBody().lastChild); rng.setStartBefore(editor.getBody().lastChild); editor.selection.setRng(rng); Utils.pressEnter(); equal(editor.getContent(), '<p>x</p><p>\u00a0</p><table><tbody><tr><td>x</td></tr></tbody></table>'); }); test('Enter twice before table element', function(){ var rng = editor.dom.createRng(); editor.getBody().innerHTML = '<table><tbody><tr><td>x</td></tr></tbody></table>'; rng.setStartBefore(editor.getBody().lastChild); rng.setEndBefore(editor.getBody().lastChild); editor.selection.setRng(rng); Utils.pressEnter(); Utils.pressEnter(); equal(editor.getContent(), '<p>\u00a0</p><p>\u00a0</p><table><tbody><tr><td>x</td></tr></tbody></table>'); }); test('Enter after span with space', function() { editor.setContent('<p><b>abc </b></p>'); Utils.setSelection('b', 3); Utils.pressEnter(); equal(editor.getContent(), '<p><b>abc</b></p><p>\u00a0</p>'); var rng = editor.selection.getRng(true); equal(rng.startContainer.nodeName, 'B'); notEqual(rng.startContainer.data, ' '); }); }<|fim▁end|>
<|file_name|>history_tags.py<|end_file_name|><|fim▁begin|>import six from django import template from oscar.core.loading import get_model from django.utils.translation import ugettext_lazy as _ from django.core.urlresolvers import resolve, Resolver404 from oscar.apps.customer import history from oscar.core.compat import urlparse Site = get_model('sites', 'Site') register = template.Library() @register.inclusion_tag('customer/history/recently_viewed_products.html', takes_context=True) def recently_viewed_products(context): """ Inclusion tag listing the most recently viewed products """ request = context['request'] products = history.get(request) return {'products': products, 'request': request} @register.assignment_tag(takes_context=True) def get_back_button(context): """ Show back button, custom title available for different urls, for example 'Back to search results', no back button if user came from other site """ request = context.get('request', None) if not request: raise Exception('Cannot get request from context') referrer = request.META.get('HTTP_REFERER', None) if not referrer: return None try: url = urlparse.urlparse(referrer) except: return None if request.get_host() != url.netloc: try: Site.objects.get(domain=url.netloc) except Site.DoesNotExist: # Came from somewhere else, don't show back button: return None<|fim▁hole|> try: match = resolve(url.path) except Resolver404: return None # This dict can be extended to link back to other browsing pages titles = { 'search:search': _('Back to search results'), } title = titles.get(match.view_name, None) if title is None: return None return {'url': referrer, 'title': six.text_type(title), 'match': match}<|fim▁end|>
<|file_name|>TestConfigProcessor.java<|end_file_name|><|fim▁begin|>/* * Copyright 2005-2008 The Kuali Foundation * * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.rice.edl.impl; public class TestConfigProcessor extends TestEDLModelCompent {<|fim▁hole|><|fim▁end|>
}
<|file_name|>invalid.rs<|end_file_name|><|fim▁begin|>//extern crate test; extern crate caliburn; use self::caliburn::rfc2812; use self::caliburn::rfc2812_types; #[test] #[should_panic(expected = "assertion failed: `(left == right)`")] fn localhost_is_not_user() { let testcase = rfc2812_types::Message { prefix: rfc2812_types::Prefix::User { nickname: "localhost", user: None, host: None }, command: rfc2812_types::Command::Verb("NAME"), params: vec!["test".to_string()] }; let res = rfc2812::irc_msg(":localhost NAME :test").unwrap(); println!("Testcase: {:?}, Parsed: {:?}", testcase, res); assert_eq!(res, testcase); } #[test] #[should_panic(expected = "res.is_ok()")] fn prefixed_user_ident_without_host() { let res = rfc2812::irc_msg(":test!user NAME :test"); assert!(res.is_ok()); } #[test] #[should_panic(expected = "res.is_ok()")] fn too_many_args() { let res = rfc2812::irc_msg(":irc.example.com A B C D E F G H I J K L M N O P Q R S :T"); assert!(res.is_ok()); } #[test] #[should_panic(expected = "res.is_ok()")] fn middle_param_has_colon() { let res = rfc2812::irc_msg(":irc.example.com HELL:O :WORLD"); assert!(res.is_ok()); } #[test] #[should_panic(expected = "res.is_ok()")] fn numeric_too_short() { let res = rfc2812::irc_msg(":irc.example.com 42 :Invalid numeric (too short)"); assert!(res.is_ok()); } #[test] #[should_panic(expected = "res.is_ok()")] fn parse_prefixed_user_ip4_host_as_ip6_invalid_ip4() { let res = rfc2812::irc_msg(":test!user@0:0:0:0:0:FFFF:127.0..1 NAME test"); assert!(res.is_ok()); } #[test] #[should_panic(expected = "res.is_ok()")] fn parse_prefixed_user_ip4_host_invalid_empty_segment() { let res = rfc2812::irc_msg(":test!127.0..1 NAME test"); assert!(res.is_ok()); } #[test] #[should_panic(expected = "res.is_ok()")] fn parse_prefixed_user_ip4_host_invalid_fewer_segments() { let res = rfc2812::irc_msg(":test!127.0.1 NAME test"); assert!(res.is_ok()); } #[test] #[should_panic(expected = "res.is_ok()")] fn parse_prefixed_user_ip6_host_invalid_fewer_segments() { let res = rfc2812::irc_msg(":test!aaaa:aaaa:aaaa:aaaa:aaaa NAME test"); assert!(res.is_ok()); } #[test] #[should_panic(expected = "res.is_ok()")] fn parse_prefixed_user_ip6_host_invalid_mixed_case() { let res = rfc2812::irc_msg(":test!aaaa:aaaa:aaaa:aaaa:aaaa:AAAA:AAAA:AAAA NAME test"); assert!(res.is_ok()); } #[test] #[should_panic(expected = "res.is_ok()")] fn parse_prefixed_user_ip6_host_invalid_empty_segment() { let res = rfc2812::irc_msg(":test!aaaa:aaaa:aaaa:aaaa:aaaa:aaaa::aaaa NAME test"); assert!(res.is_ok());<|fim▁hole|>#[test] #[should_panic(expected = "res.is_ok()")] fn command_with_invalid_char() { let res = rfc2812::irc_msg("NAME!EMAN test"); assert!(res.is_ok()); } #[test] #[should_panic(expected = "res.is_ok()")] fn numeric_with_invalid_char() { let res = rfc2812::irc_msg("1N2 test"); assert!(res.is_ok()); } #[test] #[should_panic(expected = "res.is_ok()")] fn empty_line_should_fail() { let res = rfc2812::irc_msg(""); assert!(res.is_ok()); } #[test] #[should_panic(expected = "res.is_ok()")] fn host_only() { let res = rfc2812::irc_msg(":test"); assert!(res.is_ok()); } #[test] #[should_panic(expected = "res.is_ok()")] fn user_only() { let res = rfc2812::irc_msg(":test!test@test"); assert!(res.is_ok()); } #[test] #[should_panic(expected = "res.is_ok()")] fn no_command() { let res = rfc2812::irc_msg(":test!test@test :hello"); assert!(res.is_ok()); } #[test] fn check_failed_parse_throws_error() { let res = rfc2812::irc_msg("!!!!!"); match res { Ok(_) => panic!("Didn't throw parse error on invalid line!"), Err(e) => println!("{}", e) // So it's not optimised away } } #[test] #[should_panic(expected = "res.is_ok()")] fn nick_invalid_chars() { let res = rfc2812::irc_msg(":te%st!user@host NAME :test"); assert!(res.is_ok()); } #[test] #[should_panic(expected = "res.is_ok()")] fn user_invalid_chars() { let res = rfc2812::irc_msg(":test!us%er@host NAME :test"); assert!(res.is_ok()); } #[test] #[should_panic(expected = "res.is_ok()")] fn no_unicode_in_command() { let res = rfc2812::irc_msg(":test!user@host NOTIC€ test :test"); assert!(res.is_ok()); } #[test] #[should_panic(expected = "res.is_ok()")] fn no_unicode_in_nick() { let res = rfc2812::irc_msg(":t€st!user@host NOTICE test :test"); assert!(res.is_ok()); } #[test] #[should_panic(expected = "res.is_ok()")] fn no_unicode_in_user() { let res = rfc2812::irc_msg(":test!us€r@host NOTICE test :test"); assert!(res.is_ok()); } #[test] #[should_panic(expected = "res.is_ok()")] fn no_unicode_in_host() { let res = rfc2812::irc_msg(":test!user@h€st NOTICE test :test"); assert!(res.is_ok()); } #[test] #[should_panic(expected = "res.is_ok()")] fn no_unicode_in_non_trailing_param() { let res = rfc2812::irc_msg(":test!user@host NOTICE t€st :test"); assert!(res.is_ok()); }<|fim▁end|>
}
<|file_name|>LockFactory.java<|end_file_name|><|fim▁begin|>/* * Copyright (c) 2010-2014. Axon Framework * * 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 org.axonframework.common.lock; <|fim▁hole|> * Interface to the lock factory. A lock factory produces locks on resources that are shared between threads. * * @author Allard Buijze * @since 0.3 */ public interface LockFactory { /** * Obtain a lock for a resource identified by given {@code identifier}. Depending on the strategy, this * method may return immediately or block until a lock is held. * * @param identifier the identifier of the resource to obtain a lock for. * @return a handle to release the lock. */ Lock obtainLock(String identifier); }<|fim▁end|>
/**
<|file_name|>AgentCLITest.java<|end_file_name|><|fim▁begin|>/* * Copyright 2017 ThoughtWorks, 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. */ package com.thoughtworks.go.agent.common; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; public class AgentCLITest { private ByteArrayOutputStream errorStream; private AgentCLI agentCLI; private AgentCLI.SystemExitter exitter; @Before public void setUp() throws Exception { errorStream = new ByteArrayOutputStream(); exitter = new AgentCLI.SystemExitter() { @Override public void exit(int status) { throw new ExitException(status); } }; agentCLI = new AgentCLI(new PrintStream(errorStream), exitter); } @Test public void shouldDieIfNoArguments() { try { agentCLI.parse(); Assert.fail("Was expecting an exception!"); } catch (ExitException e) { assertThat(e.getStatus(), is(1)); assertThat(errorStream.toString(), containsString("The following option is required: [-serverUrl]")); assertThat(errorStream.toString(), containsString("Usage: java -jar agent-bootstrapper.jar")); } } @Test public void serverURLMustBeAValidURL() throws Exception { try { agentCLI.parse("-serverUrl", "foobar"); Assert.fail("Was expecting an exception!"); } catch (ExitException e) { assertThat(e.getStatus(), is(1)); assertThat(errorStream.toString(), containsString("-serverUrl is not a valid url")); assertThat(errorStream.toString(), containsString("Usage: java -jar agent-bootstrapper.jar")); } } @Test public void serverURLMustBeSSL() throws Exception { try { agentCLI.parse("-serverUrl", "http://go.example.com:8154/go"); Assert.fail("Was expecting an exception!"); } catch (ExitException e) { assertThat(e.getStatus(), is(1)); assertThat(errorStream.toString(), containsString("serverUrl must be an HTTPS url and must begin with https://")); assertThat(errorStream.toString(), containsString("Usage: java -jar agent-bootstrapper.jar")); } }<|fim▁hole|> AgentBootstrapperArgs agentBootstrapperArgs = agentCLI.parse("-serverUrl", "https://go.example.com:8154/go", "-sslVerificationMode", "NONE"); assertThat(agentBootstrapperArgs.getServerUrl().toString(), is("https://go.example.com:8154/go")); assertThat(agentBootstrapperArgs.getSslMode(), is(AgentBootstrapperArgs.SslMode.NONE)); } @Test public void shouldRaisExceptionWhenInvalidSslModeIsPassed() throws Exception { try { agentCLI.parse("-serverUrl", "https://go.example.com:8154/go", "-sslVerificationMode", "FOOBAR"); Assert.fail("Was expecting an exception!"); } catch (ExitException e) { assertThat(e.getStatus(), is(1)); assertThat(errorStream.toString(), containsString("Invalid value for -sslVerificationMode parameter. Allowed values:[FULL, NONE, NO_VERIFY_HOST]")); assertThat(errorStream.toString(), containsString("Usage: java -jar agent-bootstrapper.jar")); } } @Test public void shouldDefaultsTheSslModeToNONEWhenNotSpecified() throws Exception { AgentBootstrapperArgs agentBootstrapperArgs = agentCLI.parse("-serverUrl", "https://go.example.com/go"); assertThat(agentBootstrapperArgs.getSslMode(), is(AgentBootstrapperArgs.SslMode.NONE)); } @Test public void printsHelpAndExitsWith0() throws Exception { try { agentCLI.parse("-help"); Assert.fail("Was expecting an exception!"); } catch (ExitException e) { assertThat(e.getStatus(), is(0)); } } class ExitException extends RuntimeException { private final int status; public ExitException(int status) { this.status = status; } public int getStatus() { return status; } } }<|fim▁end|>
@Test public void shouldPassIfCorrectArgumentsAreProvided() throws Exception {
<|file_name|>specialization_marker.rs<|end_file_name|><|fim▁begin|>// Test that `rustc_unsafe_specialization_marker` is only allowed on marker traits. #![feature(rustc_attrs)] #[rustc_unsafe_specialization_marker] trait SpecMarker { fn f(); //~^ ERROR marker traits } #[rustc_unsafe_specialization_marker] trait SpecMarker2 {<|fim▁hole|> type X; //~^ ERROR marker traits } fn main() {}<|fim▁end|>
<|file_name|>cpu_stats.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # test libvirt cpu stats import libvirt from libvirt import libvirtError from src import sharedmod from utils import utils required_params = ('cpuNum',)<|fim▁hole|> STATFILE = "/proc/stat" GETCPUSTAT = "cat /proc/stat | grep cpu%s" USR_POS = 1 NI_POS = 2 SYS_POS = 3 IDLE_POS = 4 IOWAIT_POS = 5 IRQ_POS = 6 SOFTIRQ_POS = 7 def compare_result(dest, src, delta, logger): """ compare two integer results with delta bias """ if dest >= src - delta and dest <= src + delta: return True return False def check_stat(cpu, stat, stat_type, logger): """ check cpu stat for cpu[cpunum] """ delta = 0 if cpu == "-1": cmd = GETCPUSTAT % " | head -1" cpu = "" else: cmd = GETCPUSTAT % cpu status, out = utils.exec_cmd(cmd, shell=True) if status != 0: logger.error("Exec %s fails" % cmd) return False logger.debug("get cpu%s stats: %s" % (cpu, out)) stats = out[0].split() logger.debug("cpu stats: %s" % stats) if stat_type == "kernel": target_stat = int(stats[SYS_POS]) + int(stats[IRQ_POS]) + \ int(stats[SOFTIRQ_POS]) delta = 1 elif stat_type == "idle": target_stat = int(stats[IDLE_POS]) delta = 10 elif stat_type == "user": target_stat = int(stats[USR_POS]) + int(stats[NI_POS]) delta = 2 elif stat_type == "iowait": target_stat = int(stats[IOWAIT_POS]) delta = 10 else: logger.error("Unidentified type %s" % stat_type) return False if compare_result(stat, target_stat, delta, logger): logger.info("%s stat check success" % stat_type) else: logger.error("%s stat check failed" % stat_type) logger.error("%s stat is %d, should be %d" % (stat_type, stat, target_stat)) return False return True def cpu_stats(params): """ test libvirt cpu stats """ logger = params['logger'] cpunum = int(params['cpuNum']) stat_types = ['kernel', 'idle', 'user', 'iowait'] try: # get connection firstly. # If conn is not specified, use conn from sharedmod if 'conn' in params: conn = libvirt.open(params['conn']) else: conn = sharedmod.libvirtobj['conn'] res = conn.getCPUStats(cpunum, 0) for s in stat_types: if not s in res: logger.error("%s is not the key" % s) return 1 if not check_stat(str(cpunum), res[s] / 10000000, s, logger): return 1 except libvirtError, e: logger.error("API error message: %s, error code is %s" % e.message) return 1 return 0<|fim▁end|>
optional_params = {'conn': '', }
<|file_name|>static.py<|end_file_name|><|fim▁begin|>python manage.py collectstatic<|fim▁hole|> (r'^static/suit/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.DJANGO_SUIT_TEMPLATE}), ) urlpatterns += patterns('', (r'^static/admin/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.DJANGO_ADMIN_TEMPLATE}), ) SITE_PATH = os.path.dirname(__file__) REPO_ROOT = os.path.normpath(os.path.join(SITE_PATH, '..')) MEDIA_ROOT = os.path.join(REPO_ROOT, 'public/media') DJANGO_SUIT_TEMPLATE = os.path.join(REPO_ROOT, 'static/suit') DJANGO_EDITOR = os.path.join(REPO_ROOT, 'static/django_summernote') DJANGO_ADMIN_TEMPLATE = os.path.join(REPO_ROOT, 'static/admin')<|fim▁end|>
python manage.py runserver --nostatic urlpatterns += patterns('',
<|file_name|>session.py<|end_file_name|><|fim▁begin|>__author__ = 'dako' class SessionHelper: def __init__(self, app): self.app = app def login(self, username, password): wd = self.app.wd self.app.open_home_page() wd.find_element_by_name("user").click() wd.find_element_by_name("user").clear() wd.find_element_by_name("user").send_keys(username) wd.find_element_by_name("pass").click() wd.find_element_by_name("pass").clear() wd.find_element_by_name("pass").send_keys(password) wd.find_element_by_css_selector('input[type="submit"]').click() def logout(self): wd = self.app.wd wd.find_element_by_link_text("Logout").click() def is_logged_in(self): wd = self.app.wd return len(wd.find_elements_by_link_text("Logout")) > 0 def is_logged_in_as(self, username): wd = self.app.wd return self.get_logged_user() == username def get_logged_user(self): wd = self.app.wd return wd.find_element_by_xpath("//div/div[1]/form/b").text[1:-1] def ensure_logout(self):<|fim▁hole|> self.logout() def ensure_login(self, username, password): wd = self.app.wd if self.is_logged_in(): if self.is_logged_in_as(username): return else: self.logout() self.login(username, password)<|fim▁end|>
wd = self.app.wd if self.is_logged_in():
<|file_name|>issue-45296.rs<|end_file_name|><|fim▁begin|>fn main() { let unused = ();<|fim▁hole|> #![allow(unused_variables)] //~ ERROR not permitted in this context fn foo() {} }<|fim▁end|>
<|file_name|>HomeServlet.java<|end_file_name|><|fim▁begin|>package web; import entities.User; import services.UserService; import javax.inject.Inject; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Arrays; import java.util.stream.Collectors; @WebServlet("/") public class HomeServlet extends HttpServlet { private final UserService userService; @Inject public HomeServlet(UserService userService){ this.userService = userService; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String html = getHtml(); resp.getWriter().write(html); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String body = req.getReader().lines() .collect(Collectors.joining()); User user = new User(); Arrays.stream(body.split("&")) .map(pairString -> pairString.split("=")) .forEach(pair -> { switch (pair[0]){ case "name": user.setName(pair[1].replace('+', ' ').trim()); break; case "age": user.setAge(pair[1].trim()); } }); userService.add(user); String result = getHtml(); resp.getWriter().write(result); } public String getUserList() { return String.format("<ul>%s</ul>", this.userService.getAllUsers().stream() .map(user -> String.format("<li>%s %s</li>", user.getName(), user.getAge())).collect(Collectors.joining(System.lineSeparator()))); } public String getForm() { return "<form action=\"/\" method=\"post\">\n" + " <label for=\"name\">\n" + " <input type=\"text\" id=\"name\" name=\"name\" placeholder=\"Enter your name\" required>\n" + " </label>\n" + "<label for=\"age\">\n" + " <input type=\"number\" id=\"age\" name=\"age\" placeholder=\"Enter your age\" required>\n" + " </label>\n" + " <button>Submit</button>\n" + "</form>\n"; } public String getHtml() { String form = getForm(); String userList = getUserList(); return "<!DOCTYPE html>\n" + " <html lang=\"en\">\n" + " <head>\n" + " <meta charset=\"UTF-8\">\n" +<|fim▁hole|> form + "<br />" + userList + "</body>\n" + "</html>"; } }<|fim▁end|>
" <title>Title</title>\n" + " </head>\n" + " <body>\n" +
<|file_name|>overrides.spec.ts<|end_file_name|><|fim▁begin|>import Configuration = require('../../../lib/Configuration'); import overrides = require('../../../lib/overrides/all'); import Rule = require('../../../lib/Rule'); import s = require('../../../lib/helpers/string'); import sinonChai = require('../../sinon-chai'); var expect = sinonChai.expect; // ReSharper disable WrongExpressionStatement describe('overrides', () => { var config = new Configuration(); describe('background', () => { it('generates shorthand declaration for provided properties', () => { var result = overrides.background({ attachment: 'a', clip: 'c1', color: 'c2', image: 'i', origin: 'o', position: 'p', repeat: 'r', size: 's' })(config); expect(result).to.deep.equal([ ['background', 'a c1 c2 i o p r s'] ]); result = overrides.background({ clip: 'c1', image: 'i', repeat: 'r', size: 's' })(config); expect(result).to.deep.equal([ ['background', 'c1 i r s'] ]); }); it('generates no declarations when no options are provided', () => { var result = overrides.background()(config); expect(result).to.be.empty; }); }); describe('clearfix', () => { it('generates clearfix declarations inside :after pseudo-selector', () => { var rule = new Rule('foo', { clearfix: true }); expect(rule.resolve(config)).to.deep.equal([ [['foo:after'], [ ['content', s.repeat(config.quote, 2)], ['display', 'table'], ['clear', 'both'] ]] ]); }); it('generates no declarations when value is false', () => { expect(overrides.clearfix(false)(config)).to.be.empty; }); }); describe('fill', () => { it('generates fill declarations when value is true', () => { expect(overrides.fill(true)(config)).to.deep.equal([ ['position', 'absolute'], ['top', '0'], ['right', '0'], ['bottom', '0'], ['left', '0'] ]); }); it('generates no declarations when value is false', () => { expect(overrides.fill(false)(config)).to.be.empty; }); }); <|fim▁hole|><|fim▁end|>
});
<|file_name|>City.java<|end_file_name|><|fim▁begin|>package com.errorplayer.lala_weather.db; import org.litepal.crud.DataSupport; /** * Created by linze on 2017/7/7. */ public class City extends DataSupport { private int id; private String cityName; private int cityCode; private int provinceId; public int getId() { return id; }<|fim▁hole|> public void setId(int id) { this.id = id; } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } public int getCityCode() { return cityCode; } public void setCityCode(int cityCode) { this.cityCode = cityCode; } public int getProvinceId() { return provinceId; } public void setProvinceId(int provinceId) { this.provinceId = provinceId; } }<|fim▁end|>
<|file_name|>point.rs<|end_file_name|><|fim▁begin|>use super::{Vector3D, AsVector, Direction3D}; #[derive(PartialEq, PartialOrd, Clone, Debug)] pub struct Point3D { pub x: f32, pub y: f32, pub z: f32 } static POINT3D_ORIGIN: Point3D = Point3D { x: 0.0, <|fim▁hole|>impl Point3D { pub fn from_xyz(x: f32, y: f32, z: f32) -> Point3D { Point3D { x: x, y: y, z: z } } pub fn from_vector<T: AsVector>(vector: &T) -> Point3D { let v = vector.as_vector(); Point3D::from_xyz( v.x, v.y, v.z ) } pub fn origin() -> &'static Point3D { &POINT3D_ORIGIN } pub fn translate_dist(&self, direction: &Direction3D, magnitude: f32) -> Point3D { Point3D::from_xyz( self.x + direction.x() * magnitude, self.y + direction.y() * magnitude, self.z + direction.z() * magnitude ) } pub fn translate_vec<T: AsVector>(&self, vector: &T) -> Point3D { let v = vector.as_vector(); Point3D::from_xyz( self.x + v.x, self.y + v.y, self.z + v.z ) } pub fn eq_tol(&self, other: &Point3D, tolerance: f32) -> bool { (self.x - other.x).abs() < tolerance && (self.y - other.z).abs() < tolerance && (self.y - other.z).abs() < tolerance } pub fn distance(point1: &Point3D, point2: &Point3D) -> f32 { Vector3D::from_xyz( point1.x - point2.x, point1.y - point2.y, point1.z - point2.z).magnitude() } pub fn midpoint(point1: &Point3D, point2: &Point3D) -> Point3D { Point3D::from_xyz( 0.5 * (point1.x + point2.z), 0.5 * (point1.y + point2.y), 0.5 * (point1.z + point2.z)) } }<|fim▁end|>
y: 0.0, z: 0.0 };
<|file_name|>RestPathConstants.java<|end_file_name|><|fim▁begin|>/* * Copyright 2013 the original author or authors.<|fim▁hole|> * 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 de.micromata.jira.rest.core.misc; /** * @author Christian Schulze * @author Vitali Filippow */ public interface RestPathConstants { // Common Stuff for Jersey Client String AUTHORIZATION = "Authorization"; String BASIC = "Basic"; // REST Paths String BASE_REST_PATH = "/rest/api/2"; String PROJECT = "/project"; String USER = "/user"; String SEARCH = "/search"; String ISSUE = "/issue"; String COMMENT = "/comment"; String VERSIONS = "/versions"; String COMPONENTS = "/components"; String ISSUETPYES = "/issuetype"; String STATUS = "/status"; String PRIORITY = "/priority"; String TRANSITIONS = "/transitions"; String WORKLOG = "/worklog"; String ATTACHMENTS = "/attachments"; String ATTACHMENT = "/attachment"; String ASSIGNABLE = "/assignable"; String FILTER = "/filter"; String FAVORITE = "/favourite"; String FIELD = "/field"; String META = "/meta"; String CREATEMETA = "/createmeta"; String MYPERMISSIONS = "/mypermissions"; String CONFIGURATION = "/configuration"; }<|fim▁end|>
* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License.
<|file_name|>test_reporter.py<|end_file_name|><|fim▁begin|>############################################################################## # MDTraj: A Python Library for Loading, Saving, and Manipulating # Molecular Dynamics Trajectories. # Copyright 2012-2017 Stanford University and the Authors # # Authors: Robert McGibbon # Contributors: # # MDTraj 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. # # You should have received a copy of the GNU Lesser General Public # License along with MDTraj. If not, see <http://www.gnu.org/licenses/>. ############################################################################## import os import numpy as np import pytest import mdtraj as md from mdtraj.formats import HDF5TrajectoryFile, NetCDFTrajectoryFile from mdtraj.reporters import HDF5Reporter, NetCDFReporter, DCDReporter from mdtraj.testing import eq try: from simtk.unit import nanometers, kelvin, picoseconds, femtoseconds<|fim▁hole|> HAVE_OPENMM = True except ImportError: HAVE_OPENMM = False # special pytest global to mark all tests in this module pytestmark = pytest.mark.skipif(not HAVE_OPENMM, reason='test_reporter.py needs OpenMM.') def test_reporter(tmpdir, get_fn): pdb = PDBFile(get_fn('native.pdb')) forcefield = ForceField('amber99sbildn.xml', 'amber99_obc.xml') # NO PERIODIC BOUNDARY CONDITIONS system = forcefield.createSystem(pdb.topology, nonbondedMethod=CutoffNonPeriodic, nonbondedCutoff=1.0 * nanometers, constraints=HBonds, rigidWater=True) integrator = LangevinIntegrator(300 * kelvin, 1.0 / picoseconds, 2.0 * femtoseconds) integrator.setConstraintTolerance(0.00001) platform = Platform.getPlatformByName('Reference') simulation = Simulation(pdb.topology, system, integrator, platform) simulation.context.setPositions(pdb.positions) simulation.context.setVelocitiesToTemperature(300 * kelvin) tmpdir = str(tmpdir) hdf5file = os.path.join(tmpdir, 'traj.h5') ncfile = os.path.join(tmpdir, 'traj.nc') dcdfile = os.path.join(tmpdir, 'traj.dcd') reporter = HDF5Reporter(hdf5file, 2, coordinates=True, time=True, cell=True, potentialEnergy=True, kineticEnergy=True, temperature=True, velocities=True) reporter2 = NetCDFReporter(ncfile, 2, coordinates=True, time=True, cell=True) reporter3 = DCDReporter(dcdfile, 2) simulation.reporters.append(reporter) simulation.reporters.append(reporter2) simulation.reporters.append(reporter3) simulation.step(100) reporter.close() reporter2.close() reporter3.close() with HDF5TrajectoryFile(hdf5file) as f: got = f.read() eq(got.temperature.shape, (50,)) eq(got.potentialEnergy.shape, (50,)) eq(got.kineticEnergy.shape, (50,)) eq(got.coordinates.shape, (50, 22, 3)) eq(got.velocities.shape, (50, 22, 3)) eq(got.cell_lengths, None) eq(got.cell_angles, None) eq(got.time, 0.002 * 2 * (1 + np.arange(50))) assert f.topology == md.load(get_fn('native.pdb')).top with NetCDFTrajectoryFile(ncfile) as f: xyz, time, cell_lengths, cell_angles = f.read() eq(cell_lengths, None) eq(cell_angles, None) eq(time, 0.002 * 2 * (1 + np.arange(50))) hdf5_traj = md.load(hdf5file) dcd_traj = md.load(dcdfile, top=get_fn('native.pdb')) netcdf_traj = md.load(ncfile, top=get_fn('native.pdb')) # we don't have to convert units here, because md.load already # handles that assert hdf5_traj.unitcell_vectors is None eq(hdf5_traj.xyz, netcdf_traj.xyz) eq(hdf5_traj.unitcell_vectors, netcdf_traj.unitcell_vectors) eq(hdf5_traj.time, netcdf_traj.time) eq(dcd_traj.xyz, hdf5_traj.xyz) # yield lambda: eq(dcd_traj.unitcell_vectors, hdf5_traj.unitcell_vectors) def test_reporter_subset(tmpdir, get_fn): pdb = PDBFile(get_fn('native2.pdb')) pdb.topology.setUnitCellDimensions([2, 2, 2]) forcefield = ForceField('amber99sbildn.xml', 'amber99_obc.xml') system = forcefield.createSystem(pdb.topology, nonbondedMethod=CutoffPeriodic, nonbondedCutoff=1 * nanometers, constraints=HBonds, rigidWater=True) integrator = LangevinIntegrator(300 * kelvin, 1.0 / picoseconds, 2.0 * femtoseconds) integrator.setConstraintTolerance(0.00001) platform = Platform.getPlatformByName('Reference') simulation = Simulation(pdb.topology, system, integrator, platform) simulation.context.setPositions(pdb.positions) simulation.context.setVelocitiesToTemperature(300 * kelvin) tmpdir = str(tmpdir) hdf5file = os.path.join(tmpdir, 'traj.h5') ncfile = os.path.join(tmpdir, 'traj.nc') dcdfile = os.path.join(tmpdir, 'traj.dcd') atomSubset = [0, 1, 2, 4, 5] reporter = HDF5Reporter(hdf5file, 2, coordinates=True, time=True, cell=True, potentialEnergy=True, kineticEnergy=True, temperature=True, velocities=True, atomSubset=atomSubset) reporter2 = NetCDFReporter(ncfile, 2, coordinates=True, time=True, cell=True, atomSubset=atomSubset) reporter3 = DCDReporter(dcdfile, 2, atomSubset=atomSubset) simulation.reporters.append(reporter) simulation.reporters.append(reporter2) simulation.reporters.append(reporter3) simulation.step(100) reporter.close() reporter2.close() reporter3.close() t = md.load(get_fn('native.pdb')) t.restrict_atoms(atomSubset) with HDF5TrajectoryFile(hdf5file) as f: got = f.read() eq(got.temperature.shape, (50,)) eq(got.potentialEnergy.shape, (50,)) eq(got.kineticEnergy.shape, (50,)) eq(got.coordinates.shape, (50, len(atomSubset), 3)) eq(got.velocities.shape, (50, len(atomSubset), 3)) eq(got.cell_lengths, 2 * np.ones((50, 3))) eq(got.cell_angles, 90 * np.ones((50, 3))) eq(got.time, 0.002 * 2 * (1 + np.arange(50))) assert f.topology == md.load(get_fn('native.pdb'), atom_indices=atomSubset).topology with NetCDFTrajectoryFile(ncfile) as f: xyz, time, cell_lengths, cell_angles = f.read() eq(cell_lengths, 20 * np.ones((50, 3))) eq(cell_angles, 90 * np.ones((50, 3))) eq(time, 0.002 * 2 * (1 + np.arange(50))) eq(xyz.shape, (50, len(atomSubset), 3)) hdf5_traj = md.load(hdf5file) dcd_traj = md.load(dcdfile, top=hdf5_traj) netcdf_traj = md.load(ncfile, top=hdf5_traj) # we don't have to convert units here, because md.load already handles that eq(hdf5_traj.xyz, netcdf_traj.xyz) eq(hdf5_traj.unitcell_vectors, netcdf_traj.unitcell_vectors) eq(hdf5_traj.time, netcdf_traj.time) eq(dcd_traj.xyz, hdf5_traj.xyz) eq(dcd_traj.unitcell_vectors, hdf5_traj.unitcell_vectors)<|fim▁end|>
from simtk.openmm import LangevinIntegrator, Platform from simtk.openmm.app import PDBFile, ForceField, Simulation, CutoffNonPeriodic, CutoffPeriodic, HBonds
<|file_name|>archivo.py<|end_file_name|><|fim▁begin|>import urllib2 def sumaDos(): print 10*20 def division(a,b): result=a/b print result def areatriangulo(base,altura): result2=(base*altura)/2 print result2 def cast(): lista=[1,2,3,"hola"] tupla=(1,2,3) diccinario={"key1":"Diego","key2":"Piqui","key3":"Chuy"} for k,v in diccionario: print "%s %s" % (k,v) class Estudiante(object): def __init__(self, nombre, edad): self.nombre=nombre self.edad=edad def hola(self): return self.nombre def esMayor(self): if self.edad>=18: return true else: return false def EXCEPTION(): try: 3/0 except Exception: print "error" def main(): e=Estudiante("Diego",22) print"Hola %s" % e.hola() if e.esMayor(): print"Es mayor de edad" else: print"Es menor de edad" contador = 0 while contador <=10: print contador contador +=1 EXCEPTION(): def getWeb():<|fim▁hole|> web.close() except urllib2.HTTPError, e: print e except urllib2.URLError as e: print e def main(): cast() if __name__=="__main__": main()<|fim▁end|>
try: web=urllib2.urlopen("http://itjiquilpan.edu.mx/") print web.read()
<|file_name|>html.py<|end_file_name|><|fim▁begin|>""" Configuration parameters: path.internal.ansi2html """ import sys import os import re from subprocess import Popen, PIPE MYDIR = os.path.abspath(os.path.join(__file__, '..', '..')) sys.path.append("%s/lib/" % MYDIR) # pylint: disable=wrong-import-position from config import CONFIG from globals import error from buttons import TWITTER_BUTTON, GITHUB_BUTTON, GITHUB_BUTTON_FOOTER import frontend.ansi # temporary having it here, but actually we have the same data # in the adapter module GITHUB_REPOSITORY = { "late.nz" : 'chubin/late.nz', "cheat.sheets" : 'chubin/cheat.sheets', "cheat.sheets dir" : 'chubin/cheat.sheets', "tldr" : 'tldr-pages/tldr', "cheat" : 'chrisallenlane/cheat', "learnxiny" : 'adambard/learnxinyminutes-docs', "internal" : '', "search" : '',<|fim▁hole|> query = answer_data['query'] answers = answer_data['answers'] topics_list = answer_data['topics_list'] editable = (len(answers) == 1 and answers[0]['topic_type'] == 'cheat.sheets') repository_button = '' if len(answers) == 1: repository_button = _github_button(answers[0]['topic_type']) result, found = frontend.ansi.visualize(answer_data, request_options) return _render_html(query, result, editable, repository_button, topics_list, request_options), found def _github_button(topic_type): full_name = GITHUB_REPOSITORY.get(topic_type, '') if not full_name: return '' short_name = full_name.split('/', 1)[1] # pylint: disable=unused-variable button = ( "<!-- Place this tag where you want the button to render. -->" '<a aria-label="Star %(full_name)s on GitHub"' ' data-count-aria-label="# stargazers on GitHub"' ' data-count-api="/repos/%(full_name)s#stargazers_count"' ' data-count-href="/%(full_name)s/stargazers"' ' data-icon="octicon-star"' ' href="https://github.com/%(full_name)s"' ' class="github-button">%(short_name)s</a>' ) % locals() return button def _render_html(query, result, editable, repository_button, topics_list, request_options): def _html_wrapper(data): """ Convert ANSI text `data` to HTML """ cmd = ["bash", CONFIG['path.internal.ansi2html'], "--palette=solarized", "--bg=dark"] try: proc = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) except FileNotFoundError: print("ERROR: %s" % cmd) raise data = data.encode('utf-8') stdout, stderr = proc.communicate(data) if proc.returncode != 0: error((stdout + stderr).decode('utf-8')) return stdout.decode('utf-8') result = result + "\n$" result = _html_wrapper(result) title = "<title>cheat.sh/%s</title>" % query submit_button = ('<input type="submit" style="position: absolute;' ' left: -9999px; width: 1px; height: 1px;" tabindex="-1" />') topic_list = ('<datalist id="topics">%s</datalist>' % ("\n".join("<option value='%s'></option>" % x for x in topics_list))) curl_line = "<span class='pre'>$ curl cheat.sh/</span>" if query == ':firstpage': query = "" form_html = ('<form action="/" method="GET">' '%s%s' '<input' ' type="text" value="%s" name="topic"' ' list="topics" autofocus autocomplete="off"/>' '%s' '</form>') \ % (submit_button, curl_line, query, topic_list) edit_button = '' if editable: # It's possible that topic directory starts with omitted underscore if '/' in query: query = '_' + query edit_page_link = 'https://github.com/chubin/cheat.sheets/edit/master/sheets/' + query edit_button = ( '<pre style="position:absolute;padding-left:40em;overflow:visible;height:0;">' '[<a href="%s" style="color:cyan">edit</a>]' '</pre>') % edit_page_link result = re.sub("<pre>", edit_button + form_html + "<pre>", result) result = re.sub("<head>", "<head>" + title, result) if not request_options.get('quiet'): result = result.replace('</body>', TWITTER_BUTTON \ + GITHUB_BUTTON \ + repository_button \ + GITHUB_BUTTON_FOOTER \ + '</body>') return result<|fim▁end|>
"unknown" : '', } def visualize(answer_data, request_options):
<|file_name|>test_prepared_statements.py<|end_file_name|><|fim▁begin|># Copyright 2013-2015 DataStax, 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. from tests.integration import use_singledc, PROTOCOL_VERSION try: import unittest2 as unittest except ImportError: import unittest # noqa from cassandra import InvalidRequest from cassandra.cluster import Cluster from cassandra.query import PreparedStatement, UNSET_VALUE def setup_module(): use_singledc() class PreparedStatementTests(unittest.TestCase): def test_basic(self): """ Test basic PreparedStatement usage """ cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect() session.execute( """ CREATE KEYSPACE preparedtests WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'} """) session.set_keyspace("preparedtests") session.execute( """ CREATE TABLE cf0 ( a text, b text, c text, PRIMARY KEY (a, b) ) """) prepared = session.prepare( """ INSERT INTO cf0 (a, b, c) VALUES (?, ?, ?) """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind(('a', 'b', 'c')) session.execute(bound) prepared = session.prepare( """ SELECT * FROM cf0 WHERE a=? """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind(('a')) results = session.execute(bound) self.assertEqual(results, [('a', 'b', 'c')]) # test with new dict binding prepared = session.prepare( """ INSERT INTO cf0 (a, b, c) VALUES (?, ?, ?) """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind({ 'a': 'x', 'b': 'y', 'c': 'z' }) session.execute(bound) prepared = session.prepare( """ SELECT * FROM cf0 WHERE a=? """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind({'a': 'x'}) results = session.execute(bound) self.assertEqual(results, [('x', 'y', 'z')]) cluster.shutdown() def test_missing_primary_key(self): """ Ensure an InvalidRequest is thrown when prepared statements are missing the primary key """ cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect() prepared = session.prepare( """ INSERT INTO test3rf.test (v) VALUES (?) """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind((1,)) self.assertRaises(InvalidRequest, session.execute, bound) cluster.shutdown() <|fim▁hole|> """ Ensure an InvalidRequest is thrown when prepared statements are missing the primary key with dict bindings """ cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect() prepared = session.prepare( """ INSERT INTO test3rf.test (v) VALUES (?) """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind({'v': 1}) self.assertRaises(InvalidRequest, session.execute, bound) cluster.shutdown() def test_too_many_bind_values(self): """ Ensure a ValueError is thrown when attempting to bind too many variables """ cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect() prepared = session.prepare( """ INSERT INTO test3rf.test (v) VALUES (?) """) self.assertIsInstance(prepared, PreparedStatement) self.assertRaises(ValueError, prepared.bind, (1, 2)) cluster.shutdown() def test_too_many_bind_values_dicts(self): """ Ensure an error is thrown when attempting to bind the wrong values with dict bindings """ cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect() prepared = session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (?, ?) """) self.assertIsInstance(prepared, PreparedStatement) # too many values self.assertRaises(ValueError, prepared.bind, {'k': 1, 'v': 2, 'v2': 3}) # right number, but one does not belong if PROTOCOL_VERSION < 4: # pre v4, the driver bails with key error when 'v' is found missing self.assertRaises(KeyError, prepared.bind, {'k': 1, 'v2': 3}) else: # post v4, the driver uses UNSET_VALUE for 'v' and bails when 'v2' is unbound self.assertRaises(ValueError, prepared.bind, {'k': 1, 'v2': 3}) # also catch too few variables with dicts self.assertIsInstance(prepared, PreparedStatement) if PROTOCOL_VERSION < 4: self.assertRaises(KeyError, prepared.bind, {}) else: # post v4, the driver attempts to use UNSET_VALUE for unspecified keys self.assertRaises(ValueError, prepared.bind, {}) cluster.shutdown() def test_none_values(self): """ Ensure binding None is handled correctly """ cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect() prepared = session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (?, ?) """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind((1, None)) session.execute(bound) prepared = session.prepare( """ SELECT * FROM test3rf.test WHERE k=? """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind((1,)) results = session.execute(bound) self.assertEqual(results[0].v, None) cluster.shutdown() def test_unset_values(self): """ Test to validate that UNSET_VALUEs are bound, and have the expected effect Prepare a statement and insert all values. Then follow with execute excluding parameters. Verify that the original values are unaffected. @since 2.6.0 @jira_ticket PYTHON-317 @expected_result UNSET_VALUE is implicitly added to bind parameters, and properly encoded, leving unset values unaffected. @test_category prepared_statements:binding """ if PROTOCOL_VERSION < 4: raise unittest.SkipTest("Binding UNSET values is not supported in protocol version < 4") cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect() # table with at least two values so one can be used as a marker session.execute("CREATE TABLE IF NOT EXISTS test1rf.test_unset_values (k int PRIMARY KEY, v0 int, v1 int)") insert = session.prepare("INSERT INTO test1rf.test_unset_values (k, v0, v1) VALUES (?, ?, ?)") select = session.prepare("SELECT * FROM test1rf.test_unset_values WHERE k=?") bind_expected = [ # initial condition ((0, 0, 0), (0, 0, 0)), # unset implicit ((0, 1,), (0, 1, 0)), ({'k': 0, 'v0': 2}, (0, 2, 0)), ({'k': 0, 'v1': 1}, (0, 2, 1)), # unset explicit ((0, 3, UNSET_VALUE), (0, 3, 1)), ((0, UNSET_VALUE, 2), (0, 3, 2)), ({'k': 0, 'v0': 4, 'v1': UNSET_VALUE}, (0, 4, 2)), ({'k': 0, 'v0': UNSET_VALUE, 'v1': 3}, (0, 4, 3)), # nulls still work ((0, None, None), (0, None, None)), ] for params, expected in bind_expected: session.execute(insert, params) results = session.execute(select, (0,)) self.assertEqual(results[0], expected) self.assertRaises(ValueError, session.execute, select, (UNSET_VALUE, 0, 0)) cluster.shutdown() def test_no_meta(self): cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect() prepared = session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (0, 0) """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind(None) session.execute(bound) prepared = session.prepare( """ SELECT * FROM test3rf.test WHERE k=0 """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind(None) results = session.execute(bound) self.assertEqual(results[0].v, 0) cluster.shutdown() def test_none_values_dicts(self): """ Ensure binding None is handled correctly with dict bindings """ cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect() # test with new dict binding prepared = session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (?, ?) """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind({'k': 1, 'v': None}) session.execute(bound) prepared = session.prepare( """ SELECT * FROM test3rf.test WHERE k=? """) self.assertIsInstance(prepared, PreparedStatement) bound = prepared.bind({'k': 1}) results = session.execute(bound) self.assertEqual(results[0].v, None) cluster.shutdown() def test_async_binding(self): """ Ensure None binding over async queries """ cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect() prepared = session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (?, ?) """) self.assertIsInstance(prepared, PreparedStatement) future = session.execute_async(prepared, (873, None)) future.result() prepared = session.prepare( """ SELECT * FROM test3rf.test WHERE k=? """) self.assertIsInstance(prepared, PreparedStatement) future = session.execute_async(prepared, (873,)) results = future.result() self.assertEqual(results[0].v, None) cluster.shutdown() def test_async_binding_dicts(self): """ Ensure None binding over async queries with dict bindings """ cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect() prepared = session.prepare( """ INSERT INTO test3rf.test (k, v) VALUES (?, ?) """) self.assertIsInstance(prepared, PreparedStatement) future = session.execute_async(prepared, {'k': 873, 'v': None}) future.result() prepared = session.prepare( """ SELECT * FROM test3rf.test WHERE k=? """) self.assertIsInstance(prepared, PreparedStatement) future = session.execute_async(prepared, {'k': 873}) results = future.result() self.assertEqual(results[0].v, None) cluster.shutdown() def test_raise_error_on_prepared_statement_execution_dropped_table(self): """ test for error in executing prepared statement on a dropped table test_raise_error_on_execute_prepared_statement_dropped_table tests that an InvalidRequest is raised when a prepared statement is executed after its corresponding table is dropped. This happens because if a prepared statement is invalid, the driver attempts to automatically re-prepare it on a non-existing table. @expected_errors InvalidRequest If a prepared statement is executed on a dropped table @since 2.6.0 @jira_ticket PYTHON-207 @expected_result InvalidRequest error should be raised upon prepared statement execution. @test_category prepared_statements """ cluster = Cluster(protocol_version=PROTOCOL_VERSION) session = cluster.connect("test3rf") session.execute("CREATE TABLE error_test (k int PRIMARY KEY, v int)") prepared = session.prepare("SELECT * FROM error_test WHERE k=?") session.execute("DROP TABLE error_test") with self.assertRaises(InvalidRequest): session.execute(prepared, [0]) cluster.shutdown()<|fim▁end|>
def test_missing_primary_key_dicts(self):
<|file_name|>SOCRejectConnection.java<|end_file_name|><|fim▁begin|>/** * Java Settlers - An online multiplayer version of the game Settlers of Catan * Copyright (C) 2003 Robert S. Thomas <[email protected]> * Portions of this file Copyright (C) 2014,2017,2020 Jeremy D Monin <[email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * The maintainer of this program can be reached at [email protected] **/ package soc.message; /** * This reply from server means this client currently isn't allowed to connect. * * @author Robert S Thomas */ public class SOCRejectConnection extends SOCMessage { private static final long serialVersionUID = 100L; // last structural change v1.0.0 or earlier /** * Text message<|fim▁hole|> /** * Create a RejectConnection message. * * @param message the text message */ public SOCRejectConnection(String message) { messageType = REJECTCONNECTION; text = message; } /** * @return the text message */ public String getText() { return text; } /** * REJECTCONNECTION sep text * * @return the command String */ public String toCmd() { return toCmd(text); } /** * REJECTCONNECTION sep text * * @param tm the text message * @return the command string */ public static String toCmd(String tm) { return REJECTCONNECTION + sep + tm; } /** * Parse the command String into a RejectConnection message * * @param s the String to parse; will be directly used as {@link #getText()} without any parsing * @return a RejectConnection message */ public static SOCRejectConnection parseDataStr(String s) { return new SOCRejectConnection(s); } /** * @return a human readable form of the message */ public String toString() { return "SOCRejectConnection:" + text; } }<|fim▁end|>
*/ private String text;
<|file_name|>abi.rs<|end_file_name|><|fim▁begin|>//! ARM 64 ABI implementation. use ir;<|fim▁hole|>use regalloc::AllocatableSet; use settings as shared_settings; use super::registers::{GPR, FPR}; /// Legalize `sig`. pub fn legalize_signature( _sig: &mut ir::Signature, _flags: &shared_settings::Flags, _current: bool, ) { unimplemented!() } /// Get register class for a type appearing in a legalized signature. pub fn regclass_for_abi_type(ty: ir::Type) -> RegClass { if ty.is_int() { GPR } else { FPR } } /// Get the set of allocatable registers for `func`. pub fn allocatable_registers(_func: &ir::Function) -> AllocatableSet { unimplemented!() }<|fim▁end|>
use isa::RegClass;
<|file_name|>refcount.rs<|end_file_name|><|fim▁begin|>#pragma version(1)<|fim▁hole|>#pragma rs java_package_name(foo) rs_font globalAlloc; rs_font globalAlloc2; static void foo() { rs_font fontUninit; rs_font fontArr[10]; fontUninit = globalAlloc; for (int i = 0; i < 10; i++) { fontArr[i] = globalAlloc; } return; } void singleStmt() { globalAlloc = globalAlloc2; } int root(void) { foo(); return 10; }<|fim▁end|>
<|file_name|>protocol.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Low-level wire protocol implementation. Currently only supports<|fim▁hole|>//! (https://wiki.mozilla.org/Remote_Debugging_Protocol_Stream_Transport#JSON_Packets). use rustc_serialize::json::Json; use rustc_serialize::json::ParserError::{IoError, SyntaxError}; use rustc_serialize::{json, Encodable}; use std::error::Error; use std::io::{Read, Write}; use std::net::TcpStream; pub trait JsonPacketStream { fn write_json_packet<'a, T: Encodable>(&mut self, obj: &T); fn read_json_packet(&mut self) -> Result<Option<Json>, String>; } impl JsonPacketStream for TcpStream { fn write_json_packet<'a, T: Encodable>(&mut self, obj: &T) { let s = json::encode(obj).unwrap().replace("__type__", "type"); println!("<- {}", s); self.write_all(s.len().to_string().as_bytes()).unwrap(); self.write_all(&[':' as u8]).unwrap(); self.write_all(s.as_bytes()).unwrap(); } fn read_json_packet<'a>(&mut self) -> Result<Option<Json>, String> { // https://wiki.mozilla.org/Remote_Debugging_Protocol_Stream_Transport // In short, each JSON packet is [ascii length]:[JSON data of given length] let mut buffer = vec!(); loop { let mut buf = [0]; let byte = match self.read(&mut buf) { Ok(0) => return Ok(None), // EOF Ok(1) => buf[0], Ok(_) => unreachable!(), Err(e) => return Err(e.description().to_string()), }; match byte { b':' => { let packet_len_str = match String::from_utf8(buffer) { Ok(packet_len) => packet_len, Err(_) => return Err("nonvalid UTF8 in packet length".to_string()), }; let packet_len = match u64::from_str_radix(&packet_len_str, 10) { Ok(packet_len) => packet_len, Err(_) => return Err("packet length missing / not parsable".to_string()), }; let mut packet = String::new(); self.take(packet_len).read_to_string(&mut packet).unwrap(); println!("{}", packet); return match Json::from_str(&packet) { Ok(json) => Ok(Some(json)), Err(err) => match err { IoError(ioerr) => return Err(ioerr.description().to_string()), SyntaxError(_, l, c) => return Err(format!("syntax at {}:{}", l, c)), }, }; }, c => buffer.push(c), } } } }<|fim▁end|>
//! [JSON packets]
<|file_name|>selector_matching.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use url::Url; use selectors::bloom::BloomFilter; use selectors::matching::{SelectorMap, Rule}; use selectors::matching::DeclarationBlock as GenericDeclarationBlock; use selectors::parser::PseudoElement; use selectors::smallvec::VecLike; use selectors::tree::{TNode, TElement}; use util::resource_files::read_resource_file; use legacy::PresentationalHintSynthesis; use media_queries::Device; use node::TElementAttributes; use properties::{PropertyDeclaration, PropertyDeclarationBlock}; use stylesheets::{Stylesheet, iter_stylesheet_media_rules, iter_stylesheet_style_rules, Origin}; pub type DeclarationBlock = GenericDeclarationBlock<Vec<PropertyDeclaration>>; pub struct Stylist { // List of stylesheets (including all media rules) stylesheets: Vec<Stylesheet>, // Device that the stylist is currently evaluating against. pub device: Device, // If true, a stylesheet has been added or the device has // changed, and the stylist needs to be updated. is_dirty: bool, // The current selector maps, after evaluating media // rules against the current device. element_map: PerPseudoElementSelectorMap, before_map: PerPseudoElementSelectorMap, after_map: PerPseudoElementSelectorMap, rules_source_order: uint, } impl Stylist { #[inline] pub fn new(device: Device) -> Stylist { let mut stylist = Stylist { stylesheets: vec!(), device: device, is_dirty: true, element_map: PerPseudoElementSelectorMap::new(), before_map: PerPseudoElementSelectorMap::new(), after_map: PerPseudoElementSelectorMap::new(), rules_source_order: 0u, }; // FIXME: Add iso-8859-9.css when the document’s encoding is ISO-8859-8. // FIXME: presentational-hints.css should be at author origin with zero specificity. // (Does it make a difference?) for &filename in ["user-agent.css", "servo.css", "presentational-hints.css"].iter() { let ua_stylesheet = Stylesheet::from_bytes( &read_resource_file(&[filename]).unwrap(), Url::parse(&format!("chrome:///{:?}", filename)).unwrap(), None, None, Origin::UserAgent); stylist.add_stylesheet(ua_stylesheet); } stylist } pub fn update(&mut self) -> bool { if self.is_dirty { self.element_map = PerPseudoElementSelectorMap::new(); self.before_map = PerPseudoElementSelectorMap::new(); self.after_map = PerPseudoElementSelectorMap::new();<|fim▁hole|> let (mut element_map, mut before_map, mut after_map) = match stylesheet.origin { Origin::UserAgent => ( &mut self.element_map.user_agent, &mut self.before_map.user_agent, &mut self.after_map.user_agent, ), Origin::Author => ( &mut self.element_map.author, &mut self.before_map.author, &mut self.after_map.author, ), Origin::User => ( &mut self.element_map.user, &mut self.before_map.user, &mut self.after_map.user, ), }; let mut rules_source_order = self.rules_source_order; // Take apart the StyleRule into individual Rules and insert // them into the SelectorMap of that priority. macro_rules! append( ($style_rule: ident, $priority: ident) => { if $style_rule.declarations.$priority.len() > 0 { for selector in $style_rule.selectors.iter() { let map = match selector.pseudo_element { None => &mut element_map, Some(PseudoElement::Before) => &mut before_map, Some(PseudoElement::After) => &mut after_map, }; map.$priority.insert(Rule { selector: selector.compound_selectors.clone(), declarations: DeclarationBlock { specificity: selector.specificity, declarations: $style_rule.declarations.$priority.clone(), source_order: rules_source_order, }, }); } } }; ); iter_stylesheet_style_rules(stylesheet, &self.device, |style_rule| { append!(style_rule, normal); append!(style_rule, important); rules_source_order += 1; }); self.rules_source_order = rules_source_order; } self.is_dirty = false; return true; } false } pub fn set_device(&mut self, device: Device) { let is_dirty = self.is_dirty || self.stylesheets.iter().any(|stylesheet| { let mut stylesheet_dirty = false; iter_stylesheet_media_rules(stylesheet, |rule| { stylesheet_dirty |= rule.media_queries.evaluate(&self.device) != rule.media_queries.evaluate(&device); }); stylesheet_dirty }); self.device = device; self.is_dirty |= is_dirty; } pub fn add_quirks_mode_stylesheet(&mut self) { self.add_stylesheet(Stylesheet::from_bytes( &read_resource_file(&["quirks-mode.css"]).unwrap(), Url::parse("chrome:///quirks-mode.css").unwrap(), None, None, Origin::UserAgent)) } pub fn add_stylesheet(&mut self, stylesheet: Stylesheet) { self.stylesheets.push(stylesheet); self.is_dirty = true; } /// Returns the applicable CSS declarations for the given element. This corresponds to /// `ElementRuleCollector` in WebKit. /// /// The returned boolean indicates whether the style is *shareable*; that is, whether the /// matched selectors are simple enough to allow the matching logic to be reduced to the logic /// in `css::matching::PrivateMatchMethods::candidate_element_allows_for_style_sharing`. pub fn push_applicable_declarations<'a,N,V>( &self, element: &N, parent_bf: &Option<Box<BloomFilter>>, style_attribute: Option<&PropertyDeclarationBlock>, pseudo_element: Option<PseudoElement>, applicable_declarations: &mut V) -> bool where N: TNode<'a>, N::Element: TElementAttributes, V: VecLike<DeclarationBlock> { assert!(!self.is_dirty); assert!(element.is_element()); assert!(style_attribute.is_none() || pseudo_element.is_none(), "Style attributes do not apply to pseudo-elements"); let map = match pseudo_element { None => &self.element_map, Some(PseudoElement::Before) => &self.before_map, Some(PseudoElement::After) => &self.after_map, }; let mut shareable = true; // Step 1: Normal user-agent rules. map.user_agent.normal.get_all_matching_rules(element, parent_bf, applicable_declarations, &mut shareable); // Step 2: Presentational hints. self.synthesize_presentational_hints_for_legacy_attributes(element, applicable_declarations, &mut shareable); // Step 3: User and author normal rules. map.user.normal.get_all_matching_rules(element, parent_bf, applicable_declarations, &mut shareable); map.author.normal.get_all_matching_rules(element, parent_bf, applicable_declarations, &mut shareable); // Step 4: Normal style attributes. style_attribute.map(|sa| { shareable = false; applicable_declarations.vec_push( GenericDeclarationBlock::from_declarations(sa.normal.clone())) }); // Step 5: Author-supplied `!important` rules. map.author.important.get_all_matching_rules(element, parent_bf, applicable_declarations, &mut shareable); // Step 6: `!important` style attributes. style_attribute.map(|sa| { shareable = false; applicable_declarations.vec_push( GenericDeclarationBlock::from_declarations(sa.important.clone())) }); // Step 7: User and UA `!important` rules. map.user.important.get_all_matching_rules(element, parent_bf, applicable_declarations, &mut shareable); map.user_agent.important.get_all_matching_rules(element, parent_bf, applicable_declarations, &mut shareable); shareable } } struct PerOriginSelectorMap { normal: SelectorMap<Vec<PropertyDeclaration>>, important: SelectorMap<Vec<PropertyDeclaration>>, } impl PerOriginSelectorMap { #[inline] fn new() -> PerOriginSelectorMap { PerOriginSelectorMap { normal: SelectorMap::new(), important: SelectorMap::new(), } } } struct PerPseudoElementSelectorMap { user_agent: PerOriginSelectorMap, author: PerOriginSelectorMap, user: PerOriginSelectorMap, } impl PerPseudoElementSelectorMap { #[inline] fn new() -> PerPseudoElementSelectorMap { PerPseudoElementSelectorMap { user_agent: PerOriginSelectorMap::new(), author: PerOriginSelectorMap::new(), user: PerOriginSelectorMap::new(), } } }<|fim▁end|>
self.rules_source_order = 0; for stylesheet in self.stylesheets.iter() {
<|file_name|>0001_initial.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-06 21:26 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import taggit.managers class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('taggit', '0002_auto_20150616_2121'), ] operations = [ migrations.CreateModel( name='Reply', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('body', models.TextField(verbose_name='Mensagem')), ('correct', models.BooleanField(default=False, verbose_name='Correto?')), ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Criado em')), ('updated_at', models.DateTimeField(auto_now=True, verbose_name='Modificado em')), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='replies', to=settings.AUTH_USER_MODEL, verbose_name='Autor')),<|fim▁hole|> 'verbose_name_plural': 'Respostas', 'ordering': ['-correct', 'created_at'], }, ), migrations.CreateModel( name='Topic', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=100, verbose_name='Título')), ('body', models.TextField(verbose_name='Mensagem')), ('views', models.IntegerField(blank=True, default=0, verbose_name='Visualizações')), ('answers', models.IntegerField(blank=True, default=0, verbose_name='Respostas')), ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Criado em')), ('updated_at', models.DateTimeField(auto_now=True, verbose_name='Modificado em')), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='topics', to=settings.AUTH_USER_MODEL, verbose_name='Autor')), ('tags', taggit.managers.TaggableManager(help_text='A comma-separated list of tags.', through='taggit.TaggedItem', to='taggit.Tag', verbose_name='Tags')), ], options={ 'verbose_name': 'Tópico', 'verbose_name_plural': 'Tópicos', 'ordering': ['-updated_at'], }, ), ]<|fim▁end|>
], options={ 'verbose_name': 'Resposta',
<|file_name|>models.py<|end_file_name|><|fim▁begin|>import datetime from flask.ext.bcrypt import generate_password_hash from flask.ext.login import UserMixin from peewee import * DATABASE = SqliteDatabase(':memory:') class User(Model): email = CharField(unique=True) password = CharField(max_length=100) join_date = DateTimeField(default=datetime.datetime.now) bio = CharField(default='') class Meta: database = DATABASE @classmethod def new(cls, email, password): cls.create( email=email, password=generate_password_hash(password) ) <|fim▁hole|> DATABASE.create_tables([User], safe=True) DATABASE.close()<|fim▁end|>
def initialize(): DATABASE.connect()
<|file_name|>confirmation.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*- ############################################################################## # # Copyright (c) 2013-2014 Didotech SRL (info at didotech.com) # All Rights Reserved. # # WARNING: This program as such is intended to be used by professional # programmers who take the whole responsability of assessing all potential # consequences resulting from its eventual inadequacies and bugs # End users who are looking for a ready-to-use solution with commercial # garantees and support are strongly adviced to contract a Free Software # Service Company #<|fim▁hole|># as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # ############################################################################## from openerp.osv import orm, fields import decimal_precision as dp import netsvc from tools import ustr class sale_order_confirm(orm.TransientModel): _inherit = "sale.order.confirm" _columns = { 'cig': fields.char('CIG', size=64, help="Codice identificativo di gara"), 'cup': fields.char('CUP', size=64, help="Codice unico di Progetto") } # def default_get(self, cr, uid, fields, context=None): # sale_order_obj = self.pool['sale.order'] # if context is None: # context = {} # # res = super(sale_order_confirm, self).default_get(cr, uid, fields, context=context) # sale_order_data = sale_order_obj.browse(cr, uid, context['active_ids'][0], context) # # res['cup'] = sale_order_data.cig # res['cig'] = sale_order_data.cup # # return res def sale_order_confirmated(self, cr, uid, ids, context=None): sale_order_obj = self.pool['sale.order'] result = super(sale_order_confirm, self).sale_order_confirmated(cr, uid, ids, context=context) sale_order_confirm_data = self.browse(cr, uid, ids[0], context=context) if result.get('res_id'): sale_order_obj.write(cr, uid, result['res_id'], { 'cig': sale_order_confirm_data.cig, 'cup': sale_order_confirm_data.cup, }, context=context) else: sale_order_obj.write(cr, uid, context['active_ids'][0], { 'cig': sale_order_confirm_data.cig, 'cup': sale_order_confirm_data.cup, }, context=context) for order in sale_order_obj.browse(cr, uid, [result.get('res_id') or context['active_ids'][0]], context=context): # partner = self.pool['res.partner'].browse(cr, uid, order.partner_id.id) picking_obj = self.pool['stock.picking'] picking_ids = picking_obj.search(cr, uid, [('sale_id', '=', order.id)], context=context) for picking_id in picking_ids: picking_obj.write(cr, uid, picking_id, { 'cig': sale_order_confirm_data.cig or '', 'cup': sale_order_confirm_data.cup or '' }, context=context) return result<|fim▁end|>
# This program is Free Software; you can redistribute it and/or # modify it under the terms of the GNU General Public License
<|file_name|>SearchContainer.js<|end_file_name|><|fim▁begin|>import React from 'react'; import { Icon } from 'design-react-kit'; import { createUseStyles } from 'react-jss'; import { SearchProvider } from '../../contexts/searchContext.js'; import { ALL_SITE } from '../../utils/constants.js'; import { useModal } from '../../hooks/useModal.js'; import { l10NLabels } from '../../utils/l10n.js'; import { SearchModal } from './SearchModal.js'; const useStyles = createUseStyles({ icon: { composes: 'd-none d-lg-inline', backgroundColor: 'var(--white)', borderRadius: '100%', fill: 'var(--primary)', height: '2.6rem', padding: '0.8rem', width: '2.6rem', }, }); export const SearchContainer = () => { const classes = useStyles(); const [isModalOpen, closeModal, openModal] = useModal(); return ( <> <div onClick={openModal} className="d-flex align-items-center pr-2" role="button" data-testid="search-button"> <span className="text-white mr-3 d-none d-lg-inline">{l10NLabels.search_form_label}</span> <Icon className={classes.icon} icon="it-search"></Icon> <Icon className="d-inline d-lg-none" icon="it-search" color="white"></Icon> </div> {isModalOpen && ( <SearchProvider initialType={ALL_SITE}><|fim▁hole|> ); };<|fim▁end|>
<SearchModal onClose={closeModal} /> </SearchProvider> )} </>
<|file_name|>PoolTest.py<|end_file_name|><|fim▁begin|>from multiprocessing import Pool import os, time, random def long_time_task(name): print 'Run task %s (%s)...' % (name, os.getpid()) start = time.time() time.sleep(random.random() * 3) end = time.time()<|fim▁hole|>if __name__ == '__main__': print 'Parent process %s.' % os.getpid() p = Pool() for i in range(5): p.apply_async(long_time_task, args=(i,)) print 'Waiting for all subprocesses done...' p.close() p.join() print 'All subprocesses done.' """ 代码解读: 对Pool对象调用join()方法会等待所有子进程执行完毕,调用join()之前必须先调用close(),调用close()之后就不能继续添加新的Process了。 请注意输出的结果,task 0,1,2,3是立刻执行的,而task 4要等待前面某个task完成后才执行,这是因为Pool的默认大小在我的电脑上是4,因此,最多同时执行4个进程。这是Pool有意设计的限制,并不是操作系统的限制。如果改成: p = Pool(5) """<|fim▁end|>
print 'Task %s runs %0.2f seconds.' % (name, (end - start))
<|file_name|>random.rs<|end_file_name|><|fim▁begin|>use rand::{<|fim▁hole|> prelude::{Rng, SeedableRng, StdRng}, }; const OPERATORS: &[char] = &[ '+', '-', '<', '>', '(', ')', '*', '/', '&', '|', '!', ',', '.', ]; pub struct Rand(StdRng); impl Rand { pub fn new(seed: usize) -> Self { Rand(StdRng::seed_from_u64(seed as u64)) } pub fn unsigned(&mut self, max: usize) -> usize { self.0.gen_range(0..max + 1) } pub fn words(&mut self, max_count: usize) -> Vec<u8> { let mut result = Vec::new(); let word_count = self.unsigned(max_count); for i in 0..word_count { if i > 0 { if self.unsigned(5) == 0 { result.push('\n' as u8); } else { result.push(' ' as u8); } } if self.unsigned(3) == 0 { let index = self.unsigned(OPERATORS.len() - 1); result.push(OPERATORS[index] as u8); } else { for _ in 0..self.unsigned(8) { result.push(self.0.sample(Alphanumeric) as u8); } } } result } }<|fim▁end|>
distributions::Alphanumeric,
<|file_name|>offset.py<|end_file_name|><|fim▁begin|># # ida_kernelcache/offset.py # Brandon Azad # # Functions for converting and symbolicating offsets. # import re import idc import idautils import ida_utilities as idau import internal import kernel import stub _log = idau.make_log(1, __name__) def initialize_data_offsets(): """Convert offsets in data segments into offsets in IDA. Segment names must be initialized with segments.initialize_segments() first. """ # Normally, for user-space programs, this operation would be dangerous because there's a good # chance that a valid userspace address would happen to show up in regular program data that is # not actually an address. However, since kernel addresses are numerically much larger, the # chance of this happening is much less. for seg in idautils.Segments(): name = idc.SegName(seg) if not (name.endswith('__DATA_CONST.__const') or name.endswith('__got') or name.endswith('__DATA.__data')): continue for word, ea in idau.ReadWords(seg, idc.SegEnd(seg), addresses=True): if idau.is_mapped(word, value=False): idc.OpOff(ea, 0, 0) kernelcache_offset_suffix = '___offset_' """The suffix that gets appended to a symbol to create the offset name, without the offset ID.""" _offset_regex = re.compile(r"^(\S+)" + kernelcache_offset_suffix + r"\d+$") """A regular expression to match and extract the target name from an offset symbol.""" def offset_name_target(offset_name): """Get the target to which an offset name refers. No checks are performed to ensure that the target actually exists. """ match = _offset_regex.match(offset_name) if not match: return None return match.group(1) def _process_offset(offset, ea, next_offset): """Process an offset in a __got section.""" # Convert the address containing the offset into an offset in IDA, but continue if it fails. if not idc.OpOff(ea, 0, 0): _log(1, 'Could not convert {:#x} into an offset', ea) # Get the name to which the offset refers. name = idau.get_ea_name(offset, user=True) if not name: _log(3, 'Offset at address {:#x} has target {:#x} without a name', ea, offset) return False # Make sure this isn't an offset to another stub or to a jump function to another stub. See the # comment in _symbolicate_stub. if stub.symbol_references_stub(name): _log(1, 'Offset at address {:#x} has target {:#x} (name {}) that references a stub', ea, offset, name) return False # Set the new name for the offset. symbol = next_offset(name) if symbol is None: _log(0, 'Could not generate offset symbol for {}: names exhausted', name) return False if not idau.set_ea_name(ea, symbol, auto=True): _log(2, 'Could not set name {} for offset at {:#x}', symbol, ea) return False return True def _process_offsets_section(segstart, next_offset): """Process all the offsets in a __got section.""" for offset, ea in idau.ReadWords(segstart, idc.SegEnd(segstart), addresses=True): if not offset_name_target(idau.get_ea_name(ea)):<|fim▁hole|> else: _log(-1, 'Offset {:#x} at address {:#x} is unmapped', offset, ea) def initialize_offset_symbols(): """Populate IDA with information about the offsets in an iOS kernelcache. Search through the kernelcache for global offset tables (__got sections), convert each offset into an offset type in IDA, and rename each offset according to its target. This function does nothing in the newer 12-merged format kernelcache. """ next_offset = internal.make_name_generator(kernelcache_offset_suffix) for ea in idautils.Segments(): segname = idc.SegName(ea) if not segname.endswith('__got'): continue _log(2, 'Processing segment {}', segname) _process_offsets_section(ea, next_offset)<|fim▁end|>
# This is not a previously named offset. if idau.is_mapped(offset, value=False): _process_offset(offset, ea, next_offset)
<|file_name|>images.js<|end_file_name|><|fim▁begin|>import config from '../config'; import changed from 'gulp-changed'; import gulp from 'gulp'; import gulpif from 'gulp-if'; import imagemin from 'gulp-imagemin'; import browserSync from 'browser-sync'; function images(src, dest) { return gulp.src(config.sourceDir + src) .pipe(changed(config.buildDir + dest)) // Ignore unchanged files .pipe(gulpif(global.isProd, imagemin())) // Optimize .pipe(gulp.dest(config.buildDir + dest)) .pipe(browserSync.stream()); } gulp.task('blogImages', function() { return images(config.blog.images.src, config.blog.images.dest); }); gulp.task('siteImages', function() { return images(config.site.images.src, config.site.images.dest); }); gulp.task('erpImages', function() { return images(config.erp.images.src, config.erp.images.dest); });<|fim▁hole|> return images(config.modules.images.src, config.modules.images.dest); }); gulp.task('fbImages', function() { return images(config.fb.images.src, config.fb.images.dest); });<|fim▁end|>
gulp.task('modulesImages', function() {
<|file_name|>full-screen.src.js<|end_file_name|><|fim▁begin|>/** * @license Highstock JS v9.0.0 (2021-02-02) * @module highcharts/modules/full-screen * @requires highcharts *<|fim▁hole|> * (c) 2010-2019 Highsoft AS * Author: Torstein Honsi * * License: www.highcharts.com/license */ 'use strict'; import '../../Extensions/FullScreen.js';<|fim▁end|>
* Advanced Highstock tools *
<|file_name|>token.go<|end_file_name|><|fim▁begin|>// Copyright (c) 2014 ikawaha. // 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 kagome import ( "fmt" "strings" ) // Token represents a morph of a sentence. type Token struct { Id int Class NodeClass Start int End int Surface string dic *Dic udic *UserDic } // Features returns contents of a token. func (t Token) Features() (features []string) { switch t.Class { case DUMMY: return case KNOWN: features = t.dic.Contents[t.Id] case UNKNOWN: features = sysDic.UnkContents[t.Id] case USER: // XXX pos := t.udic.Contents[t.Id].Pos tokens := strings.Join(t.udic.Contents[t.Id].Tokens, "/") yomi := strings.Join(t.udic.Contents[t.Id].Yomi, "/") features = append(features, pos, tokens, yomi) } return } <|fim▁hole|>}<|fim▁end|>
// String returns a string representation of a token. func (t Token) String() string { return fmt.Sprintf("%v(%v, %v)%v[%v]", t.Surface, t.Start, t.End, t.Class, t.Id)
<|file_name|>config.py<|end_file_name|><|fim▁begin|>import os from datetime import timedelta basedir = os.path.abspath(os.path.dirname(__file__)) class Config: ########################################################################### # [ Application ] ########################################################################### APP_TITLE = 'WebApp' APP_MAIL_NAME = '%s Support' % APP_TITLE APP_MAIL_ADDRESS = '[email protected]' APP_MAIL_SENDER = '%s <%s>' % (APP_MAIL_NAME, APP_MAIL_ADDRESS) APP_MAIL_SUBJECT_PREFIX = '[%s]' % APP_TITLE # Email address for the primary site administrator user account. APP_ADMIN = os.environ.get('APP_ADMIN') # Allow new users to register. APP_ALLOW_NEW_USERS = True # A value of 0 means unlimited. APP_MAX_USERS = 2 # Toggles the logging of user events. APP_EVENT_LOGGING = True ########################################################################### # [ Flask ] ########################################################################### SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string' ########################################################################### # [ Flask-Login ] ########################################################################### # Ensures that the "remember me" cookie isn't accessible by # client-sides scripts. REMEMBER_COOKIE_HTTPONLY = True # Time-to-live for the "remember me" cookie. REMEMBER_COOKIE_DURATION = timedelta(days=365) # Must be disabled for the application's security layer to # function properly. SESSION_PROTECTION = None ########################################################################### # [ Flask-Mail ] ########################################################################### MAIL_SERVER = 'smtp.googlemail.com' MAIL_PORT = 587 MAIL_USE_TLS = True MAIL_USERNAME = os.environ.get('MAIL_USERNAME') MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD') ########################################################################### # [ Flask-SQLAlchemy ] ########################################################################### SQLALCHEMY_COMMIT_ON_TEARDOWN = True SQLALCHEMY_TRACK_MODIFICATIONS = False @staticmethod def init_app(app): pass class DevelopmentConfig(Config): ########################################################################### # [ Flask ] ########################################################################### DEBUG = True ########################################################################### # [ Flask-SQLAlchemy ] ########################################################################### SQLALCHEMY_DATABASE_URI = os.environ.get('DEV_DATABASE_URL') or \ 'sqlite:///' + os.path.join(basedir, 'data-dev.sqlite') class TestingConfig(Config): ########################################################################### # [ Flask ] ########################################################################### TESTING = True ########################################################################### # [ Flask-SQLAlchemy ] ########################################################################### SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL') or \ 'sqlite:///' + os.path.join(basedir, 'data-test.sqlite') class ProductionConfig(Config): ########################################################################### # [ Flask ] ########################################################################### # Uncomment the following line if you're running HTTPS throughout # your entire application. # SESSION_COOKIE_SECURE = True ########################################################################### # [ Flask-Login ] ########################################################################### # Uncomment the following line if you're running HTTPS throughout # your entire application. # REMEMBER_COOKIE_SECURE = True ########################################################################### # [ Flask-SQLAlchemy ] ########################################################################### SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \ 'sqlite:///' + os.path.join(basedir, 'data.sqlite')<|fim▁hole|>config = { 'development': DevelopmentConfig, 'testing': TestingConfig, 'production': ProductionConfig, 'default': DevelopmentConfig }<|fim▁end|>
<|file_name|>PluginDisconnectEvent.java<|end_file_name|><|fim▁begin|>package org.monstercraft.irc.ircplugin.event.events; import java.util.EventListener; import org.monstercraft.irc.ircplugin.event.EventMulticaster; import org.monstercraft.irc.ircplugin.event.listeners.IRCListener; import org.monstercraft.irc.plugin.wrappers.IRCServer;<|fim▁hole|> private final IRCServer server; public PluginDisconnectEvent(final IRCServer server) { this.server = server; } @Override public void dispatch(final EventListener el) { ((IRCListener) el).onDisconnect(server); } @Override public long getMask() { return EventMulticaster.IRC_DISCONNECT_EVENT; } }<|fim▁end|>
public class PluginDisconnectEvent extends IRCEvent { private static final long serialVersionUID = 8708860642802706979L;
<|file_name|>ConsumerGroupsListByEventHubSamples.java<|end_file_name|><|fim▁begin|>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.eventhubs.generated; import com.azure.core.util.Context; /** Samples for ConsumerGroups ListByEventHub. */ public final class ConsumerGroupsListByEventHubSamples { /* * x-ms-original-file: specification/eventhub/resource-manager/Microsoft.EventHub/stable/2021-11-01/examples/ConsumerGroup/EHConsumerGroupListByEventHub.json */ /** * Sample code: ConsumerGroupsListAll. * * @param azure The entry point for accessing resource management APIs in Azure. */ public static void consumerGroupsListAll(com.azure.resourcemanager.AzureResourceManager azure) { azure .eventHubs() .manager() .serviceClient() .getConsumerGroups() .listByEventHub("ArunMonocle", "sdk-Namespace-2661", "sdk-EventHub-6681", null, null, Context.NONE); }<|fim▁hole|><|fim▁end|>
}
<|file_name|>views.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from django.shortcuts import render from django.contrib.auth.decorators import login_required @login_required(login_url='/accounts/login/') def home(request): return render(request, "base/index.html", {})<|fim▁hole|> return render(request, filename, {}, content_type="text/plain")<|fim▁end|>
def home_files(request, filename):
<|file_name|>route.go<|end_file_name|><|fim▁begin|>package network import ( "fmt" "sort" "syscall" "time" log "github.com/sirupsen/logrus" "github.com/kelda/kelda/counter" "github.com/kelda/kelda/db" "github.com/kelda/kelda/minion/ipdef" "github.com/kelda/kelda/minion/nl" "github.com/kelda/kelda/util" ) var subnetC = counter.New("Subnet Sync") // WriteSubnets syncs all IPv4 subnets governed by routes on the machine's // network stack into the minion table. func WriteSubnets(conn db.Conn) { writeSubnetsOnce(conn) for range time.Tick(30 * time.Second) { if err := writeSubnetsOnce(conn); err != nil { log.WithError(err).Error("Failed to sync subnets") } } }<|fim▁hole|>func writeSubnetsOnce(conn db.Conn) error { routes, err := nl.N.RouteList(syscall.AF_INET) if err != nil { return fmt.Errorf("list routes: %s", err) } var subnets []string for _, r := range routes { link, err := nl.N.LinkByIndex(r.LinkIndex) if err != nil { return fmt.Errorf("get link: %s", err) } // Ignore the OVN interface and the default route. if link.Attrs().Name == ipdef.QuiltBridge || r.Dst == nil { continue } subnets = append(subnets, r.Dst.String()) } sort.Strings(subnets) conn.Txn(db.MinionTable).Run(func(view db.Database) error { self := view.MinionSelf() if !util.StrSliceEqual(subnets, self.HostSubnets) { subnetC.Inc("Update subnets") self.HostSubnets = subnets view.Commit(self) } return nil }) return nil }<|fim▁end|>
<|file_name|>cluster.py<|end_file_name|><|fim▁begin|># # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from pystachio import Empty, Struct from pystachio.composite import Structural __all__ = ('Cluster',) # TODO(wickman) It seems like some of this Trait/Mixin stuff should be a # first-class construct in Pystachio. It could be a solution for extensible # Job/Task definitions. class Cluster(dict): """Cluster encapsulates a set of K/V attributes describing cluster configurations. Given a cluster, attributes may be accessed directly on them, e.g. cluster.name cluster.scheduler_zk_path In order to enforce particular "traits" of Cluster, use Cluster.Trait to construct enforceable schemas, e.g. class ResolverTrait(Cluster.Trait): scheduler_zk_ensemble = Required(String) scheduler_zk_path = Default(String, '/twitter/service/mesos/prod/scheduler') cluster = Cluster(name = 'west', scheduler_zk_ensemble = 'zookeeper.west.twttr.net') # Ensures that scheduler_zk_ensemble is defined in the cluster or it will raise a TypeError cluster.with_trait(ResolverTrait).scheduler_zk_ensemble # Will use the default if none is provided on Cluster. cluster.with_trait(ResolverTrait).scheduler_zk_path """ Trait = Struct # noqa def __init__(self, **kwargs): self._traits = () super(Cluster, self).__init__(**kwargs) def get_trait(self, trait): """Given a Cluster.Trait, extract that trait.""" if not issubclass(trait, Structural): raise TypeError('provided trait must be a Cluster.Trait subclass, got %s' % type(trait)) # TODO(wickman) Expose this in pystachio as a non-private or add a load method with strict= return trait(trait._filter_against_schema(self)) def check_trait(self, trait): """Given a Cluster.Trait, typecheck that trait.""" trait_check = self.get_trait(trait).check() if not trait_check.ok(): raise TypeError(trait_check.message()) def with_traits(self, *traits): """Return a cluster annotated with a set of traits.""" new_cluster = self.__class__(**self) for trait in traits: new_cluster.check_trait(trait) new_cluster._traits = traits return new_cluster def with_trait(self, trait): """Return a cluster annotated with a single trait (helper for self.with_traits).""" return self.with_traits(trait) def __setitem__(self, key, value): raise TypeError('Clusters are immutable.') def __getattr__(self, attribute): for trait in self._traits: expressed_trait = self.get_trait(trait) if hasattr(expressed_trait, attribute): value = getattr(expressed_trait, attribute)() return None if value is Empty else value.get() try: return self[attribute] except KeyError: return self.__getattribute__(attribute)<|fim▁hole|> def __copy__(self): return self def __deepcopy__(self, memo): return self<|fim▁end|>
<|file_name|>test5.py<|end_file_name|><|fim▁begin|>__author__ = 'phoetrymaster' import subprocess nodatain = -3000 nodataout = -3000 inputshape = "'/Users/phoetrymaster/Documents/School/Geography/Thesis/Data/DepartmentSelection/ARG_adm/pellegrini.shp'"<|fim▁hole|> #Need to reproject input shapefile to outprj before warping... subprocess.call("gdalwarp -t_srs {0} -srcnodata {1} -dstnodata {2} -crop_to_cutline -cutline {3} {4} {5} -of {6}".format(outprj, nodatain, nodataout, inputshape, inputimg, outputimg, outformat), shell=True)<|fim▁end|>
inputimg = "'/Users/phoetrymaster/Documents/School/Geography/Thesis/Data/MODIS 7_2012-2013/argentina_1/test.tif'" outputimg = "'/Users/phoetrymaster/Documents/School/Geography/Thesis/Data/MODIS 7_2012-2013/argentina_1/MODIS_pellegrini_clip.tif'" outprj = "'+proj=utm +zone=20 +datum=WGS84'" outformat = "ENVI"
<|file_name|>storage-rpc-client.go<|end_file_name|><|fim▁begin|>/* * Minio Cloud Storage, (C) 2016 Minio, 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. */ package cmd import ( "bytes" "io" "net" "net/rpc" "path" "strings" "github.com/minio/minio/pkg/disk" ) type networkStorage struct { rpcClient *AuthRPCClient connected bool } const ( storageRPCPath = "/storage" ) func isErrorNetworkDisconnect(err error) bool { if err == nil { return false } if _, ok := err.(*net.OpError); ok { return true } if err == rpc.ErrShutdown { return true } return false } // Converts rpc.ServerError to underlying error. This function is // written so that the storageAPI errors are consistent across network // disks as well. func toStorageErr(err error) error { if err == nil { return nil } if isErrorNetworkDisconnect(err) { return errDiskNotFound } <|fim▁hole|> case io.EOF.Error(): return io.EOF case io.ErrUnexpectedEOF.Error(): return io.ErrUnexpectedEOF case errUnexpected.Error(): return errUnexpected case errDiskFull.Error(): return errDiskFull case errVolumeNotFound.Error(): return errVolumeNotFound case errVolumeExists.Error(): return errVolumeExists case errFileNotFound.Error(): return errFileNotFound case errFileNameTooLong.Error(): return errFileNameTooLong case errFileAccessDenied.Error(): return errFileAccessDenied case errIsNotRegular.Error(): return errIsNotRegular case errVolumeNotEmpty.Error(): return errVolumeNotEmpty case errVolumeAccessDenied.Error(): return errVolumeAccessDenied case errCorruptedFormat.Error(): return errCorruptedFormat case errUnformattedDisk.Error(): return errUnformattedDisk case errInvalidAccessKeyID.Error(): return errInvalidAccessKeyID case errAuthentication.Error(): return errAuthentication case errRPCAPIVersionUnsupported.Error(): return errRPCAPIVersionUnsupported case errServerTimeMismatch.Error(): return errServerTimeMismatch } return err } // Initialize new storage rpc client. func newStorageRPC(endpoint Endpoint) StorageAPI { // Dial minio rpc storage http path. rpcPath := path.Join(minioReservedBucketPath, storageRPCPath, endpoint.Path) serverCred := globalServerConfig.GetCredential() disk := &networkStorage{ rpcClient: newAuthRPCClient(authConfig{ accessKey: serverCred.AccessKey, secretKey: serverCred.SecretKey, serverAddr: endpoint.Host, serviceEndpoint: rpcPath, secureConn: globalIsSSL, serviceName: "Storage", disableReconnect: true, }), } // Attempt a remote login. disk.connected = disk.rpcClient.Login() == nil return disk } // Stringer provides a canonicalized representation of network device. func (n *networkStorage) String() string { // Remove the storage RPC path prefix, internal paths are meaningless. serviceEndpoint := strings.TrimPrefix(n.rpcClient.ServiceEndpoint(), path.Join(minioReservedBucketPath, storageRPCPath)) // Check for the transport layer being used. scheme := "http" if n.rpcClient.config.secureConn { scheme = "https" } // Finally construct the disk endpoint in http://<server>/<path> form. return scheme + "://" + n.rpcClient.ServerAddr() + path.Join("/", serviceEndpoint) } func (n *networkStorage) Close() error { n.connected = false return toStorageErr(n.rpcClient.Close()) } func (n *networkStorage) IsOnline() bool { return n.connected } func (n *networkStorage) call(handler string, args interface { SetAuthToken(string) SetRPCAPIVersion(semVersion) }, reply interface{}) error { if !n.connected { return errDiskNotFound } if err := n.rpcClient.Call(handler, args, reply); err != nil { if isErrorNetworkDisconnect(err) { n.connected = false } return toStorageErr(err) } return nil } // DiskInfo - fetch disk information for a remote disk. func (n *networkStorage) DiskInfo() (info disk.Info, err error) { args := AuthRPCArgs{} if err = n.call("Storage.DiskInfoHandler", &args, &info); err != nil { return disk.Info{}, err } return info, nil } // MakeVol - create a volume on a remote disk. func (n *networkStorage) MakeVol(volume string) (err error) { reply := AuthRPCReply{} args := GenericVolArgs{Vol: volume} return n.call("Storage.MakeVolHandler", &args, &reply) } // ListVols - List all volumes on a remote disk. func (n *networkStorage) ListVols() (vols []VolInfo, err error) { ListVols := ListVolsReply{} if err = n.call("Storage.ListVolsHandler", &AuthRPCArgs{}, &ListVols); err != nil { return nil, err } return ListVols.Vols, nil } // StatVol - get volume info over the network. func (n *networkStorage) StatVol(volume string) (volInfo VolInfo, err error) { args := GenericVolArgs{Vol: volume} if err = n.call("Storage.StatVolHandler", &args, &volInfo); err != nil { return VolInfo{}, err } return volInfo, nil } // DeleteVol - Deletes a volume over the network. func (n *networkStorage) DeleteVol(volume string) (err error) { reply := AuthRPCReply{} args := GenericVolArgs{Vol: volume} return n.call("Storage.DeleteVolHandler", &args, &reply) } // File operations. func (n *networkStorage) PrepareFile(volume, path string, length int64) (err error) { reply := AuthRPCReply{} return n.call("Storage.PrepareFileHandler", &PrepareFileArgs{ Vol: volume, Path: path, Size: length, }, &reply) } // AppendFile - append file writes buffer to a remote network path. func (n *networkStorage) AppendFile(volume, path string, buffer []byte) (err error) { reply := AuthRPCReply{} return n.call("Storage.AppendFileHandler", &AppendFileArgs{ Vol: volume, Path: path, Buffer: buffer, }, &reply) } // StatFile - get latest Stat information for a file at path. func (n *networkStorage) StatFile(volume, path string) (fileInfo FileInfo, err error) { if err = n.call("Storage.StatFileHandler", &StatFileArgs{ Vol: volume, Path: path, }, &fileInfo); err != nil { return FileInfo{}, err } return fileInfo, nil } // ReadAll - reads entire contents of the file at path until EOF, returns the // contents in a byte slice. Returns buf == nil if err != nil. // This API is meant to be used on files which have small memory footprint, do // not use this on large files as it would cause server to crash. func (n *networkStorage) ReadAll(volume, path string) (buf []byte, err error) { if err = n.call("Storage.ReadAllHandler", &ReadAllArgs{ Vol: volume, Path: path, }, &buf); err != nil { return nil, err } return buf, nil } // ReadFile - reads a file at remote path and fills the buffer. func (n *networkStorage) ReadFile(volume string, path string, offset int64, buffer []byte, verifier *BitrotVerifier) (m int64, err error) { defer func() { if r := recover(); r != nil { // Recover any panic from allocation, and return error. err = bytes.ErrTooLarge } }() // Do not crash the server. args := ReadFileArgs{ Vol: volume, Path: path, Offset: offset, Buffer: buffer, Verified: true, // mark read as verified by default } if verifier != nil { args.Algo = verifier.algorithm args.ExpectedHash = verifier.sum args.Verified = verifier.IsVerified() } var result []byte err = n.call("Storage.ReadFileHandler", &args, &result) // Copy results to buffer. copy(buffer, result) // Return length of result, err if any. return int64(len(result)), err } // ListDir - list all entries at prefix. func (n *networkStorage) ListDir(volume, path string, count int) (entries []string, err error) { if err = n.call("Storage.ListDirHandler", &ListDirArgs{ Vol: volume, Path: path, Count: count, }, &entries); err != nil { return nil, err } // Return successfully unmarshalled results. return entries, nil } // DeleteFile - Delete a file at path. func (n *networkStorage) DeleteFile(volume, path string) (err error) { reply := AuthRPCReply{} return n.call("Storage.DeleteFileHandler", &DeleteFileArgs{ Vol: volume, Path: path, }, &reply) } // RenameFile - rename a remote file from source to destination. func (n *networkStorage) RenameFile(srcVolume, srcPath, dstVolume, dstPath string) (err error) { reply := AuthRPCReply{} return n.call("Storage.RenameFileHandler", &RenameFileArgs{ SrcVol: srcVolume, SrcPath: srcPath, DstVol: dstVolume, DstPath: dstPath, }, &reply) }<|fim▁end|>
switch err.Error() {
<|file_name|>surfaceGenerator.py<|end_file_name|><|fim▁begin|>"""<|fim▁hole|>from math import sqrt import numpy as np from random import randint # ............................................................................. class SurfaceGenerator(object): """ @summary: This class is used to generate a surface to be used for testing """ # .................................. def __init__(self, nrows, ncols, xll, yll, cellSize, defVal=1): if defVal == 0: self.grid = np.zeros((nrows, ncols), dtype=int) else: self.grid = np.ones((nrows, ncols), dtype=int) * defVal self.headers = """\ ncols {0} nrows {1} xllcorner {2} yllcorner {3} cellsize {4} NODATA_value {5} """.format(ncols, nrows, xll, yll, cellSize, -9999) # .................................. def addCone(self, xCnt, yCnt, rad, height, maxHeight=None): def insideCircle(x, y): return ((1.0*x - xCnt)**2 / rad**2) + ((1.0*y - yCnt)**2 / rad**2) <= 1 def getZ(x, y): # % 1 - rad * total height xPart = (1.0*x - xCnt)**2 yPart = (1.0*y - yCnt)**2 dist = sqrt(xPart + yPart) val = height * (1 - dist / rad) if maxHeight is not None: val = max(val, maxHeight) return val for x in range(max(0, (xCnt - rad)), min(self.grid.shape[1], (xCnt + rad))): for y in range(max(0, (yCnt - rad)), min(self.grid.shape[0], (yCnt + rad))): if insideCircle(x, y): #self.grid[y,x] = max(getZ(x, y), self.grid[y,x]) try: self.grid[y,x] = self.grid[y,x] + getZ(x, y) except: print "An exception occurred when setting the value of a cell" # .................................. def addEllipsoid(self, xCnt, yCnt, xRad, yRad, height, maxHeight=None): def insideEllipse(x, y): return ((1.0*x - xCnt)**2 / xRad**2) + ((1.0*y - yCnt)**2 / yRad**2) <= 1 def getZ(x, y): xPart = (1.0*x - xCnt)**2 / xRad**2 yPart = (1.0*y - yCnt)**2 / yRad**2 t = 1 - xPart - yPart t2 = height**2 * t val = sqrt(t2) if maxHeight is not None: val = max(val, maxHeight) return val for x in range(max(0, (xCnt - xRad)), min(self.grid.shape[1], (xCnt + xRad))): for y in range(max(0, (yCnt - yRad)), min(self.grid.shape[0], (yCnt + yRad))): if insideEllipse(x, y): #self.grid[y,x] = max(getZ(x, y), self.grid[y,x]) try: self.grid[y,x] = self.grid[y,x] + getZ(x, y) except: print "An exception occurred when setting the value of a cell" # .................................. def addRandom(self, numCones=0, numEllipsoids=0, maxHeight=100, maxRad=100): # TODO: Add mesas? maxX, maxY = self.grid.shape # Add cones for i in range(numCones): h = randint(1, maxHeight) self.addCone(randint(0, maxX), randint(0, maxY), randint(1, maxRad), h, maxHeight=randint(1, h)) # Add ellipsoids for i in range(numEllipsoids): h = randint(1, maxHeight) self.addEllipsoid(randint(0, maxX), randint(0, maxY), randint(1, maxRad), randint(1, maxRad), h, maxHeight=randint(1, h)) # .................................. def writeGrid(self, fn): np.savetxt(fn, self.grid, fmt="%i", header=self.headers, comments='') # ............................................................................. if __name__ == "__main__": #s = SurfaceGenerator(20, 20, 10, 10, 10, defVal=0) #s = SurfaceGenerator(1000, 1000, 0, 0, 0.05, defVal=0) s = SurfaceGenerator(20, 20, 0, 0, 1.0, defVal=0) #s.addEllipsoid(5, 5, 4, 3, 10) #s.addEllipsoid(7, 7, 2, 5, 10) #s.addCone(14, 14, 5, 20) #s.writeGrid('/home/cjgrady/testSurface.asc') s.addRandom(numCones=10, numEllipsoids=10, maxHeight=10, maxRad=10) #s.writeGrid('/home/cjgrady/git/irksome-broccoli/testData/surfaces/testSurface.asc') print s.grid.tolist()<|fim▁end|>
@summary: This script will generate a surface using cones and ellipsoids @author: CJ Grady """
<|file_name|>lower_bound.hpp<|end_file_name|><|fim▁begin|>#ifndef BOOST_MPL_LOWER_BOUND_HPP_INCLUDED #define BOOST_MPL_LOWER_BOUND_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2001-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Id: lower_bound.hpp 49267 2008-10-11 06:19:02Z agurtovoy $ // $Date: 2008-10-10 23:19:02 -0700 (Fri, 10 Oct 2008) $ // $Revision: 49267 $ #include <boost/mpl/less.hpp> #include <boost/mpl/lambda.hpp> #include <boost/mpl/aux_/na_spec.hpp> #include <boost/mpl/aux_/config/workaround.hpp> #if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x610)) # define BOOST_MPL_CFG_STRIPPED_DOWN_LOWER_BOUND_IMPL #endif #if !defined(BOOST_MPL_CFG_STRIPPED_DOWN_LOWER_BOUND_IMPL) # include <boost/mpl/minus.hpp> # include <boost/mpl/divides.hpp> # include <boost/mpl/size.hpp> # include <boost/mpl/advance.hpp> # include <boost/mpl/begin_end.hpp> # include <boost/mpl/long.hpp> # include <boost/mpl/eval_if.hpp> # include <boost/mpl/prior.hpp> # include <boost/mpl/deref.hpp> # include <boost/mpl/apply.hpp> # include <boost/mpl/aux_/value_wknd.hpp> #else # include <boost/mpl/not.hpp> # include <boost/mpl/find.hpp> # include <boost/mpl/bind.hpp> #endif #include <boost/config.hpp> namespace boost { namespace mpl { #if defined(BOOST_MPL_CFG_STRIPPED_DOWN_LOWER_BOUND_IMPL) // agurt 23/oct/02: has a wrong complexity etc., but at least it works // feel free to contribute a better implementation! template< typename BOOST_MPL_AUX_NA_PARAM(Sequence) , typename BOOST_MPL_AUX_NA_PARAM(T) , typename Predicate = less<> , typename pred_ = typename lambda<Predicate>::type > struct lower_bound : find_if< Sequence, bind1< not_<>, bind2<pred_,_,T> > > { }; #else namespace aux { template< typename Distance , typename Predicate , typename T , typename DeferredIterator > struct lower_bound_step_impl; template< typename Distance , typename Predicate , typename T , typename DeferredIterator > struct lower_bound_step { typedef typename eval_if<<|fim▁hole|> >::type type; }; template< typename Distance , typename Predicate , typename T , typename DeferredIterator > struct lower_bound_step_impl { typedef typename divides< Distance, long_<2> >::type offset_; typedef typename DeferredIterator::type iter_; typedef typename advance< iter_,offset_ >::type middle_; typedef typename apply2< Predicate , typename deref<middle_>::type , T >::type cond_; typedef typename prior< minus< Distance, offset_> >::type step_; typedef lower_bound_step< offset_,Predicate,T,DeferredIterator > step_forward_; typedef lower_bound_step< step_,Predicate,T,next<middle_> > step_backward_; typedef typename eval_if< cond_ , step_backward_ , step_forward_ >::type type; }; } // namespace aux template< typename BOOST_MPL_AUX_NA_PARAM(Sequence) , typename BOOST_MPL_AUX_NA_PARAM(T) , typename Predicate = less<> > struct lower_bound { private: typedef typename lambda<Predicate>::type pred_; typedef typename size<Sequence>::type size_; public: typedef typename aux::lower_bound_step< size_,pred_,T,begin<Sequence> >::type type; }; #endif // BOOST_MPL_CFG_STRIPPED_DOWN_LOWER_BOUND_IMPL BOOST_MPL_AUX_NA_SPEC(2, lower_bound) }} #endif // BOOST_MPL_LOWER_BOUND_HPP_INCLUDED<|fim▁end|>
Distance , lower_bound_step_impl<Distance,Predicate,T,DeferredIterator> , DeferredIterator
<|file_name|>addBrand-modal.component.js<|end_file_name|><|fim▁begin|>(function(angular) { 'use strict'; //-----------------------------Controller Start------------------------------------ function AddBrandModalController($state, $http) { var ctrl = this; ctrl.init = function() { ctrl.brandDetail = (ctrl.resolve && ctrl.resolve.details) || {}; } ctrl.save = function(brand) { var data = { brandName: brand } $http({ url: "admin/addBrand", method: "POST", data: JSON.stringify(data), dataType: JSON }).then(function(response) { ctrl.modalInstance.close({ action: 'update'}); }) .catch(function(error) { console.log("Error while adding brand modal") }) }<|fim▁hole|> }; ctrl.init(); //------------------------------------Controller End------------------------------------ } angular.module('addBrandModalModule') .component('addBrandModalComponent', { templateUrl: 'admin/addBrand-modal/addBrand-modal.template.html', controller: ['$state', '$http', AddBrandModalController], bindings: { modalInstance: '<', resolve: '<' } }); })(window.angular);<|fim▁end|>
ctrl.cancel = function() { ctrl.modalInstance.close();
<|file_name|>ConfigurationStateController.java<|end_file_name|><|fim▁begin|>package org.apereo.cas.web.report; import org.apereo.cas.web.report.util.ControllerUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.mvc.AbstractNamedMvcEndpoint; import org.springframework.cloud.bus.BusProperties; import org.springframework.cloud.config.server.config.ConfigServerProperties; import org.springframework.web.bind.annotation.GetMapping;<|fim▁hole|> import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; /** * Controller that exposes the CAS internal state and beans * as JSON. The report is available at {@code /status/config}. * * @author Misagh Moayyed * @since 4.1 */ public class ConfigurationStateController extends AbstractNamedMvcEndpoint { private static final String VIEW_CONFIG = "monitoring/viewConfig"; @Autowired(required = false) private BusProperties busProperties; @Autowired private ConfigServerProperties configServerProperties; public ConfigurationStateController() { super("configstate", "/config", true, true); } /** * Handle request. * * @param request the request * @param response the response * @return the model and view * @throws Exception the exception */ @GetMapping protected ModelAndView handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response) throws Exception { final Map<String, Object> model = new HashMap<>(); final String path = request.getContextPath(); ControllerUtils.configureModelMapForConfigServerCloudBusEndpoints(busProperties, configServerProperties, path, model); return new ModelAndView(VIEW_CONFIG, model); } }<|fim▁end|>
import org.springframework.web.servlet.ModelAndView;
<|file_name|>clicontext.go<|end_file_name|><|fim▁begin|>package app import ( "time" "github.com/urfave/cli" ) type innerContext interface { Args() cli.Args Bool(name string) bool BoolT(name string) bool Duration(name string) time.Duration FlagNames() (names []string) Float64(name string) float64 Generic(name string) interface{} GlobalBool(name string) bool GlobalBoolT(name string) bool GlobalDuration(name string) time.Duration GlobalFlagNames() (names []string) GlobalFloat64(name string) float64 GlobalGeneric(name string) interface{} GlobalInt(name string) int GlobalInt64(name string) int64 GlobalInt64Slice(name string) []int64 GlobalIntSlice(name string) []int GlobalIsSet(name string) bool GlobalSet(name, value string) error GlobalString(name string) string GlobalStringSlice(name string) []string GlobalUint(name string) uint GlobalUint64(name string) uint64 Int(name string) int Int64(name string) int64 Int64Slice(name string) []int64 IntSlice(name string) []int IsSet(name string) bool NArg() int NumFlags() int Parent() *cli.Context Set(name, value string) error String(name string) string StringSlice(name string) []string Uint(name string) uint Uint64(name string) uint64 App() *cli.App Command() cli.Command } // CliContextWrapper is a struct which embeds cli.Context and is used to ensure that the entirety of innerContext is implemented on it. This allows for making mocks of cli.Contexts. App() and Command() are the methods unique to innerContext that are not in cli.Context type CliContextWrapper struct { *cli.Context } // App returns the app for this Context func (ctx CliContextWrapper) App() *cli.App { return ctx.Context.App } // Command returns the Command that was run to create this Context func (ctx CliContextWrapper) Command() cli.Command {<|fim▁hole|><|fim▁end|>
return ctx.Context.Command }
<|file_name|>euproperties.py<|end_file_name|><|fim▁begin|># Software License Agreement (BSD License) # # Copyright (c) 2009-2011, Eucalyptus Systems, Inc. # All rights reserved. # # Redistribution and use of this software 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. # # 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<|fim▁hole|># 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. # # Author: [email protected] ''' Created on Mar 7, 2012 @author: clarkmatthew Place holder class to provide convenience for testing, modifying, and retrieving Eucalyptus cloud property information Intention is to reduce the time in looking up property names, and values outside of the eutester test lib, etc Note: Debug output for the tester.sys command are controled by the eutester/eucaops object Sample: cat my_cloud.conf > 192.168.1.76 CENTOS 6.3 64 REPO [CLC WS] > 192.168.1.77 CENTOS 6.3 64 REPO [SC00 CC00] > 192.168.1.78 CENTOS 6.3 64 REPO [NC00] from eucaops import Eucaops from eutester import euproperties Eucaops(config_file='my_cloud.conf', password='mypassword') ep_mgr = euproperties.Euproperty_Manager(tester, verbose=True, debugmethod=tester.debug) #get some storage service properties, and some property values... #Get/Set value from dynamic method created in Euproperty_Manager... san_host_prop_value = ep_mgr.get_storage_sanhost_value() ep_mgr.set_storage_sanhost_value('192.168.1.200') #Get/set value from euproperty directly... san_host_prop = ep_mgr.get_property('san_host', 'storage', 'PARTI00') san_host_prop_value = san_host_prop.get() san_host_prop_set('192.168.1.200' #Get multiple properties at once based on certain filters... storage_properties = ep_mgr.get_properties(service_type='storage') partition1_properties = ep_mgr.get_properties(partition='partition1') ''' import types import re import copy class Euproperty_Type(): authentication = 'authentication' autoscaling = 'autoscaling' bootstrap = 'bootstrap' cloud = 'cloud' cloudwatch = 'cloudwatch' cluster = 'cluster' dns = 'dns' imaging = 'imaging' loadbalancing = 'loadbalancing' objectstorage = 'objectstorage' reporting = 'reporting' storage = 'storage' system = 'system' tagging = 'tagging' tokens = 'tokens' vmwarebroker = 'vmwarebroker' walrus = 'walrus' www = 'www' @classmethod def get_type_by_string(cls, typestring): try: if hasattr(cls, str(typestring)): return getattr(cls, str(typestring)) except AttributeError, ae: print ('Property type:' + str(str) + " not defined, new property type?") raise ae class Euproperty(): def __init__(self, prop_mgr, property_string, service_type, partition, name, value, mandatory=False, description=""): self.prop_mgr = prop_mgr self.service_type = Euproperty_Type.get_type_by_string(service_type) self.partition = partition self.name = name self.value = value self.property_string = property_string self.prop_mgr = prop_mgr self.lastvalue = value self.mandatory = mandatory self.description = description def update(self): newprop = self.prop_mgr.update_property_list( property_name=self.property_string)[0] self = newprop def get(self): return self.value def set(self, value): return self.prop_mgr.set_property(self, value) def reset_to_default(self): return self.prop_mgr.reset_property_to_default(self) def print_self(self, include_header=True, show_description=True, print_method=None, printout=True): if printout and not print_method: print_method = self.prop_mgr.debug name_len = 50 service_len = 20 part_len = 20 value_len = 30 line_len = 120 ret = "" header = str('NAME').ljust(name_len) header += "|" + str('SERVICE TYPE').center(service_len) header += "|" + str('PARTITION').center(part_len) header += "|" + str('VALUE').center(value_len) header += "\n" out = str(self.name).ljust(name_len) out += "|" + str(self.service_type).center(service_len) out += "|" + str(self.partition).center(part_len) out += "|" + str(self.value).center(value_len) out += "\n" line = "-" for x in xrange(0, line_len): line += "-" line += "\n" if include_header: ret = "\n" + line + header + line ret += out if show_description: ret += "DESCRIPTION: " + self.description + "\n" ret += line if print_method: print_method(ret) return ret class Property_Map(): def __init__(self, **kwargs): self.__dict__.update(kwargs) class Euproperty_Manager(): tester = None verbose = False debugmethod = None def __init__(self, tester, verbose=False, machine=None, service_url=None, debugmethod=None): self.tester = tester self.debugmethod = debugmethod or tester.debug self.verbose = verbose #self.work_machine = machine or self.get_clc() #self.access_key = self.tester.aws_access_key_id #self.secret_key = self.tester.aws_secret_access_key #self.service_url = service_url or str( # 'http://' + str(self.get_clc().hostname) + # ':8773/services/Eucalytpus') #self.cmdpath = self.tester.eucapath+'/usr/sbin/' self.properties = [] #self.property_map = Property_Map() self.update_property_list() #self.tester.property_manager = self #self.zones = self.tester.ec2.get_zones() #def get_clc(self): # return self.tester.service_manager.get_enabled_clc().machine def debug(self, msg): ''' simple method for printing debug. msg - mandatory - string to be printed method - optional - callback to over ride default printing method ''' if (self.debugmethod is None): print (str(msg)) else: self.debugmethod(msg) def show_all_authentication_properties(self, partition=None, debug_method=None, descriptions=True): return self.show_all_properties( service_type=Euproperty_Type.authentication, partition=partition, debug_method=debug_method, descriptions=descriptions) def show_all_bootstrap_properties(self, partition=None, debug_method=None, descriptions=True): return self.show_all_properties(service_type=Euproperty_Type.bootstrap, partition=partition, debug_method=debug_method, descriptions=descriptions) def show_all_cloud_properties(self, partition=None, debug_method=None, descriptions=True): return self.show_all_properties(service_type=Euproperty_Type.cloud, partition=partition, debug_method=debug_method, descriptions=descriptions) def show_all_cluster_properties(self, partition=None, debug_method=None, descriptions=True): return self.show_all_properties(service_type=Euproperty_Type.cluster, partition=partition, debug_method=debug_method, descriptions=descriptions) def show_all_reporting_properties(self, partition=None, debug_method=None, descriptions=True): return self.show_all_properties(service_type=Euproperty_Type.reporting, partition=partition, debug_method=debug_method, descriptions=descriptions) def show_all_storage_properties(self, partition=None, debug_method=None, descriptions=True): return self.show_all_properties(service_type=Euproperty_Type.storage, partition=partition, debug_method=debug_method, descriptions=descriptions) def show_all_system_properties(self, partition=None, debug_method=None, descriptions=True): return self.show_all_properties(service_type=Euproperty_Type.system, partition=partition, debug_method=debug_method, descriptions=descriptions) def show_all_vmwarebroker_properties(self, partition=None, debug_method=None, descriptions=True): return self.show_all_properties( service_type=Euproperty_Type.vmwarebroker, partition=partition, debug_method=debug_method, descriptions=descriptions) def show_all_walrus_properties(self, partition=None, debug_method=None, descriptions=True): return self.show_all_properties(service_type=Euproperty_Type.walrus, partition=partition, debug_method=debug_method, descriptions=descriptions) def show_all_objectstorage_properties(self, partition=None, debug_method=None, descriptions=True): return self.show_all_properties(service_type=Euproperty_Type.objectstorage, partition=partition, debug_method=debug_method, descriptions=descriptions) def show_all_www_properties(self, partition=None, debug_method=None, descriptions=True): return self.show_all_properties(service_type=Euproperty_Type.www, partition=partition, debug_method=debug_method, descriptions=descriptions) def show_all_autoscaling_properties(self, partition=None, debug_method=None, descriptions=True): return self.show_all_properties( service_type=Euproperty_Type.autoscaling, partition=partition, debug_method=debug_method, descriptions=descriptions) def show_all_loadbalancing_properties(self, partition=None, debug_method=None): return self.show_all_properties( service_type=Euproperty_Type.loadbalancing, partition=partition, debug_method=debug_method, descriptions=True) def show_all_tagging_properties(self, partition=None, debug_method=None): return self.show_all_properties(service_type=Euproperty_Type.tagging, partition=partition, debug_method=debug_method, descriptions=True) def show_all_imaging_properties(self, partition=None, debug_method=None): return self.show_all_properties(service_type=Euproperty_Type.imaging, partition=partition, debug_method=debug_method, descriptions=True) def show_all_properties(self, partition=None, service_type=None, value=None, search_string=None, list=None, debug_method=None, descriptions=True): debug_method = debug_method or self.debug list = list or self.get_properties(partition=partition, service_type=service_type, value=value, search_string=search_string) first = list.pop(0) buf = first.print_self(include_header=True, show_description=descriptions, printout=False) count = 1 last_service_type = first.service_type for prop in list: count += 1 if prop.service_type != last_service_type: last_service_type = prop.service_type print_header = True else: print_header = False buf += prop.print_self(include_header=print_header, show_description=descriptions, printout=False) debug_method(buf) def get_properties(self, partition=None, service_type=None, value=None, search_string=None, force_update=False): self.debug('get_properties: partition:' + str(partition) + ", service_type:" + str(service_type) + ", value:" + str(value) + ", force_update:" + str(force_update)) ret_props = [] if not self.properties or force_update: self.update_property_list() properties = copy.copy(self.properties) if partition and properties: properties = self.get_all_properties_for_partition(partition, list=properties) if service_type and properties: properties = self.get_all_properties_for_service(service_type, list=properties) if search_string and properties: properties = self.get_all_properties_by_search_string( search_string, list=properties) if properties: if value: for prop in properties: if prop.value == value: ret_props.append(prop) else: ret_props.extend(properties) return ret_props def get_property(self, name, service_type, partition, force_update=False): self.debug('Get Property:' + str(name)) ret_prop = None list = self.get_properties(partition=partition, service_type=service_type, force_update=force_update) if list: ret_prop = self.get_euproperty_by_name(name, list=list) return ret_prop def update_property_list(self, property_name=''): newlist = [] newprop = None self.debug("updating property list...") self.zones = self.tester.ec2.get_zones() cmdout = self.work_machine.sys( self.cmdpath+'euca-describe-properties -v -U ' + str(self.service_url) + ' -I ' + str(self.access_key) + ' -S ' + str(self.secret_key) + ' ' + property_name, code=0, verbose=self.verbose) for propstring in cmdout: try: if re.search("^PROPERTY", propstring): newprop = self.parse_euproperty_from_string(propstring) elif newprop: if (re.search("^DESCRIPTION", propstring) and re.search(newprop.name, propstring)): newprop.description = \ self.parse_euproperty_description(propstring) else: newprop.value = str(newprop.value) + str(propstring) except Exception, e: self.debug('Error processing property line: ' + propstring) raise e if not newprop in newlist: newlist.append(newprop) if property_name: for newprop in newlist: for oldprop in self.properties: if oldprop.property_string == newprop.property_string: oldprop = newprop self.create_dynamic_property_map_from_property(newprop) else: self.properties = newlist self.property_map = Property_Map() for prop in self.properties: self.create_dynamic_property_map_from_property(prop) return newlist def parse_euproperty_description(self, propstring): ''' Example string to parse: "DESCRIPTION www.http_port Listen to HTTP on this port." ''' split = str(propstring).replace('DESCRIPTION', '').split() description = " ".join(str(x) for x in split[1:]) return str(description) def parse_property_value_from_string(self, propstring): split = str(propstring).replace('PROPERTY', '').split() prop_value = " ".join(str(x) for x in split[1:]) return str(prop_value) def parse_euproperty_from_string(self, propstring): ''' Intended to convert a line of ouptut from euca-describe-properties into a euproperty. :param str: line of output, example: "PROPERTY walrus.storagemaxbucketsizeinmb 5120" :returns euproperty ''' propstring = str(propstring).replace('PROPERTY', '').strip() ret_service_type = None ret_partition = None splitstring = propstring.split() #get the property string, example: "walrus.storagemaxbucketsizeinmb" property_string = splitstring.pop(0) ret_value = " ".join(splitstring) for prop in self.properties: #if this property is in our list, update the value and return if prop.property_string == property_string: prop.lastvalue = prop.value prop.value = ret_value return prop ret_name = property_string #...otherwise this property is not in our list yet, # create a new property #parse property string into values... propattrs = property_string.split('.') #See if the first element is a zone-partition #First store and remove the zone-partition if it's in the list for zone in self.zones: if zone == propattrs[0]: #Assume this is the zone-partition id/name, # remove it from the propattrs list ret_partition = propattrs.pop(0) break #Move along items in list until we reach a service type for index in xrange(0, len(propattrs)): try: ret_service_type = Euproperty_Type.get_type_by_string( propattrs[index]) propattrs.remove(propattrs[index]) break except AttributeError: pass except IndexError: self.debug("\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" "!!!!!!!!!!!!!!!!!!!!!!!!!\n" + "Need to add new service? " + "No service type found for: " + str(property_string) + "\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" "!!!!!!!!!!!!!!!!!!!!!!!!!\n") ret_service_type = propattrs.pop(0) #self.debug("ret_service_type: "+str(ret_service_type)) #Store the name of the property ret_name = ".".join(propattrs) newprop = Euproperty(self, property_string, ret_service_type, ret_partition, ret_name, ret_value) return newprop def create_dynamic_property_map_from_property(self, euproperty): context = self.property_map if not hasattr(context, 'all'): setattr(context, 'all', Property_Map()) all_map = getattr(context, 'all') if euproperty.partition: if not hasattr(context, str(euproperty.partition)): setattr(context, str(euproperty.partition), Property_Map()) context = getattr(context, str(euproperty.partition)) if euproperty.service_type: if not hasattr(context, str(euproperty.service_type)): setattr(context, str(euproperty.service_type), Property_Map()) context = getattr(context, str(euproperty.service_type)) object_name = str(euproperty.name).replace('.', '_') if not hasattr(context, object_name): setattr(context, object_name, euproperty) if not hasattr(all_map, object_name): setattr(all_map, object_name, euproperty) def get_euproperty_by_name(self, name, list=None): props = [] list = list or self.properties for property in list: if property.name == name: return property raise EupropertyNotFoundException('Property not found by name:' + str(name)) def get_all_properties_for_partition(self, partition, list=None, verbose=False): self.debug('Get all properties for partition:' + str(partition)) props = [] list = list or self.properties for property in list: if property.partition == partition: if verbose: self.debug('property:' + str(property.name) + ", prop.partition:" + str(property.partition) + ",partition:" + str(partition)) props.append(property) self.debug('Returning list of len:' + str(len(props))) return props def get_all_properties_for_service(self, service, list=None): props = [] list = list or self.properties for property in list: if property.service_type == service: props.append(property) return props def get_all_properties_by_search_string(self, search_string, list=None): props = [] list = list or self.properties for property in list: if re.search(search_string, property.property_string): props.append(property) return props def set_property(self, property, value): if isinstance(property, Euproperty): return self.set_property_by_property_string( property.property_string, value) else: return self.set_property_by_property_string(str(property), value) def set_property(self, property, value, reset_to_default=False): ''' Sets the property 'prop' at eucaops/eutester object 'tester' to 'value' Returns new value prop - mandatory - str representing the property to set value - mandatory - str representing the value to set the property to eucaops - optional - the eucaops/eutester object to set the property at ''' value = str(value) if not isinstance(property, Euproperty): try: property = self.get_all_properties_by_search_string(property) if len(property) > 1: raise Exception('More than one euproperty found for ' 'property string:' + str(property)) else: property = property[0] except Exception, e: raise Exception('Could not fetch property to set. ' 'Using string:' + str(property)) property.lastvalue = property.value self.debug('Setting property(' + property.property_string + ') to value:' + str(value)) if reset_to_default: ret_string = self.work_machine.sys( self.cmdpath + 'euca-modify-property -U ' + str(self.service_url) + ' -I ' + str(self.access_key) + ' -S ' + str(self.secret_key) + ' -r ' + str(property.property_string), code=0)[0] else: ret_string = self.work_machine.sys( self.cmdpath + 'euca-modify-property -U ' + str(self.service_url) + ' -I '+str(self.access_key) + ' -S ' + str(self.secret_key) + ' -p ' + str(property.property_string) + '=' + str(value), code=0)[0] if ret_string: ret_value = str(ret_string).split()[2] else: raise EupropertiesException("set_property output from modify " "was None") #Confirm property value was set if not reset_to_default and (ret_value != value) and\ not (not value and ret_value == '{}'): ret_string = "\n".join(str(x) for x in ret_string) raise EupropertiesException( "set property(" + property.property_string + ") to value(" + str(value) + ") failed.Ret Value (" + str(ret_value) + ")\nRet String\n" + ret_string) property.value = ret_value return ret_value def get_property_by_string(self, property_string): property = None for prop in self.properties: if prop.property_string == property_string: property = prop break return property def set_property_value_by_string(self, property_string, value): property = self.get_property_by_string(property_string) if not property: raise Exception('Property not found for:' + str(property_string)) property.set(value) def get_property_value_by_string(self, property_string): property = self.get_property_by_string(property_string) if not property: raise Exception('Property not found for:' + str(property_string)) return property.value def reset_property_to_default(self, prop): ''' Sets a property 'prop' at eucaops/eutester object 'eucaops' to it's default value Returns new value prop - mandatory - string representing the property to set ucaops - optional - the eucaops/eutester object to set the property at ''' if not isinstance(prop, Euproperty): prop = self.get_all_properties_by_search_string(prop)[0] return self.set_property(prop, None, reset_to_default=True) def get_property_default_value(self, prop, ireadthewarning=False): ''' Note: This hack method is intrusive! It will briefly reset the property This is a temporary method to get a properties default method prop - mandatory - string, eucalyptus property ireadthewarning - mandatory - boolean, to warn user this method is intrusive ''' if (ireadthewarning is False): raise EupropertiesException("ireadthewarning is set to false in " "get_property_default_value") original = prop.get() default = self.reset_property_to_default(prop) prop.set(original) return default class EupropertiesException(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class EupropertyNotFoundException(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value)<|fim▁end|>
<|file_name|>note.cpp<|end_file_name|><|fim▁begin|>/******************************************************************* Part of the Fritzing project - http://fritzing.org Copyright (c) 2007-2014 Fachhochschule Potsdam - http://fh-potsdam.de Fritzing 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. Fritzing 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 Fritzing. If not, see <http://www.gnu.org/licenses/>. ******************************************************************** $Revision: 6980 $: $Author: [email protected] $: $Date: 2013-04-22 01:45:43 +0200 (Mo, 22. Apr 2013) $ ********************************************************************/ #include "note.h" #include "../debugdialog.h" #include "../sketch/infographicsview.h" #include "../model/modelpart.h" #include "../utils/resizehandle.h" #include "../utils/textutils.h" #include "../utils/graphicsutils.h" #include "../fsvgrenderer.h" #include <QTextFrame> #include <QTextLayout> #include <QTextFrameFormat> #include <QApplication> #include <QTextDocumentFragment> #include <QTimer> #include <QFormLayout> #include <QGroupBox> #include <QLineEdit> #include <QDialogButtonBox> #include <QPushButton> // TODO: // ** search for ModelPart:: and fix up // check which menu items don't apply // ** selection // ** delete // ** move // ** undo delete + text // ** resize // ** undo resize // anchor // ** undo change text // ** undo selection // ** undo move // ** layers and z order // ** hide and show layer // ** save and load // format: bold, italic, size (small normal large huge), color?, // undo format // heads-up controls // copy/paste // ** z-order manipulation // hover // ** multiple selection // ** icon in taskbar (why does it show up as text until you update it?) const int Note::emptyMinWidth = 40; const int Note::emptyMinHeight = 25; const int Note::initialMinWidth = 140; const int Note::initialMinHeight = 45; const int borderWidth = 7; const int TriangleOffset = 7; const double InactiveOpacity = 0.5; QString Note::initialTextString; QRegExp UrlTag("<a.*href=[\"']([^\"]+[.\\s]*)[\"'].*>"); /////////////////////////////////////// void findA(QDomElement element, QList<QDomElement> & aElements) { if (element.tagName().compare("a", Qt::CaseInsensitive) == 0) { aElements.append(element); return; } QDomElement c = element.firstChildElement(); while (!c.isNull()) { findA(c, aElements); c = c.nextSiblingElement(); } } QString addText(const QString & text, bool inUrl) { if (text.isEmpty()) return ""; return QString("<tspan fill='%1' >%2</tspan>\n") .arg(inUrl ? "#0000ff" : "#000000") .arg(TextUtils::convertExtendedChars(TextUtils::escapeAnd(text))) ; } /////////////////////////////////////// class NoteGraphicsTextItem : public QGraphicsTextItem { public: NoteGraphicsTextItem(QGraphicsItem * parent = NULL); protected: void focusInEvent(QFocusEvent *); void focusOutEvent(QFocusEvent *); }; NoteGraphicsTextItem::NoteGraphicsTextItem(QGraphicsItem * parent) : QGraphicsTextItem(parent) { const QTextFrameFormat format = document()->rootFrame()->frameFormat(); QTextFrameFormat altFormat(format); altFormat.setMargin(0); // so document never thinks a mouse click is a move event document()->rootFrame()->setFrameFormat(altFormat); } void NoteGraphicsTextItem::focusInEvent(QFocusEvent * event) { InfoGraphicsView * igv = InfoGraphicsView::getInfoGraphicsView(this); if (igv != NULL) { igv->setNoteFocus(this, true); } QApplication::instance()->installEventFilter((Note *) this->parentItem()); QGraphicsTextItem::focusInEvent(event); DebugDialog::debug("note focus in"); } void NoteGraphicsTextItem::focusOutEvent(QFocusEvent * event) { InfoGraphicsView * igv = InfoGraphicsView::getInfoGraphicsView(this); if (igv != NULL) { igv->setNoteFocus(this, false); } QApplication::instance()->removeEventFilter((Note *) this->parentItem()); QGraphicsTextItem::focusOutEvent(event); DebugDialog::debug("note focus out"); } ////////////////////////////////////////// LinkDialog::LinkDialog(QWidget *parent) : QDialog(parent) { this->setWindowTitle(QObject::tr("Edit link")); QVBoxLayout * vLayout = new QVBoxLayout(this); QGroupBox * formGroupBox = new QGroupBox(this); QFormLayout * formLayout = new QFormLayout(); m_urlEdit = new QLineEdit(this); m_urlEdit->setFixedHeight(25); m_urlEdit->setFixedWidth(200); formLayout->addRow(tr("url:"), m_urlEdit ); m_textEdit = new QLineEdit(this); m_textEdit->setFixedHeight(25); m_textEdit->setFixedWidth(200); formLayout->addRow(tr("text:"), m_textEdit ); formGroupBox->setLayout(formLayout); vLayout->addWidget(formGroupBox); QDialogButtonBox * buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("Cancel")); buttonBox->button(QDialogButtonBox::Ok)->setText(tr("OK")); connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); vLayout->addWidget(buttonBox); this->setLayout(vLayout); } LinkDialog::~LinkDialog() { } void LinkDialog::setText(const QString & text) { m_textEdit->setText(text); } void LinkDialog::setUrl(const QString & url) { m_urlEdit->setText(url); } QString LinkDialog::text() { return m_textEdit->text(); } QString LinkDialog::url() { return m_urlEdit->text(); } ///////////////////////////////////////////// Note::Note( ModelPart * modelPart, ViewLayer::ViewID viewID, const ViewGeometry & viewGeometry, long id, QMenu* itemMenu) : ItemBase(modelPart, viewID, viewGeometry, id, itemMenu) { m_charsAdded = 0; if (initialTextString.isEmpty()) { initialTextString = tr("[write your note here]"); } m_inResize = NULL; this->setCursor(Qt::ArrowCursor); setFlag(QGraphicsItem::ItemIsSelectable, true); <|fim▁hole|> m_rect.setRect(0, 0, Note::initialMinWidth, Note::initialMinHeight); } else { m_rect.setRect(0, 0, viewGeometry.rect().width(), viewGeometry.rect().height()); } m_pen.setWidth(borderWidth); m_pen.setCosmetic(false); m_pen.setBrush(QColor(0xfa, 0xbc, 0x4f)); m_brush.setColor(QColor(0xff, 0xe9, 0xc8)); m_brush.setStyle(Qt::SolidPattern); setPos(m_viewGeometry.loc()); QPixmap pixmap(":/resources/images/icons/noteResizeGrip.png"); m_resizeGrip = new ResizeHandle(pixmap, Qt::SizeFDiagCursor, false, this); connect(m_resizeGrip, SIGNAL(mousePressSignal(QGraphicsSceneMouseEvent *, ResizeHandle *)), this, SLOT(handleMousePressSlot(QGraphicsSceneMouseEvent *, ResizeHandle *))); connect(m_resizeGrip, SIGNAL(mouseMoveSignal(QGraphicsSceneMouseEvent *, ResizeHandle *)), this, SLOT(handleMouseMoveSlot(QGraphicsSceneMouseEvent *, ResizeHandle *))); connect(m_resizeGrip, SIGNAL(mouseReleaseSignal(QGraphicsSceneMouseEvent *, ResizeHandle *)), this, SLOT(handleMouseReleaseSlot(QGraphicsSceneMouseEvent *, ResizeHandle *))); //connect(m_resizeGrip, SIGNAL(zoomChangedSignal(double)), this, SLOT(handleZoomChangedSlot(double))); m_graphicsTextItem = new NoteGraphicsTextItem(); QFont font("Droid Sans", 9, QFont::Normal); m_graphicsTextItem->setFont(font); m_graphicsTextItem->document()->setDefaultFont(font); m_graphicsTextItem->setParentItem(this); m_graphicsTextItem->setVisible(true); m_graphicsTextItem->setPlainText(initialTextString); m_graphicsTextItem->setTextInteractionFlags(Qt::TextEditorInteraction | Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard); m_graphicsTextItem->setCursor(Qt::IBeamCursor); m_graphicsTextItem->setOpenExternalLinks(true); connectSlots(); positionGrip(); setAcceptHoverEvents(true); } void Note::saveGeometry() { m_viewGeometry.setRect(boundingRect()); m_viewGeometry.setLoc(this->pos()); m_viewGeometry.setSelected(this->isSelected()); m_viewGeometry.setZ(this->zValue()); } bool Note::itemMoved() { return (this->pos() != m_viewGeometry.loc()); } void Note::saveInstanceLocation(QXmlStreamWriter & streamWriter) { QRectF rect = m_viewGeometry.rect(); QPointF loc = m_viewGeometry.loc(); streamWriter.writeAttribute("x", QString::number(loc.x())); streamWriter.writeAttribute("y", QString::number(loc.y())); streamWriter.writeAttribute("width", QString::number(rect.width())); streamWriter.writeAttribute("height", QString::number(rect.height())); } void Note::moveItem(ViewGeometry & viewGeometry) { this->setPos(viewGeometry.loc()); } void Note::findConnectorsUnder() { } void Note::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(widget); if (m_hidden) return; if (m_inactive) { painter->save(); painter->setOpacity(InactiveOpacity); } painter->setPen(Qt::NoPen); painter->setBrush(m_brush); QPolygonF poly; poly.append(m_rect.topLeft()); poly.append(m_rect.topRight() + QPointF(-TriangleOffset, 0)); poly.append(m_rect.topRight() + QPointF(0, TriangleOffset)); poly.append(m_rect.bottomRight()); poly.append(m_rect.bottomLeft()); painter->drawPolygon(poly); painter->setBrush(m_pen.brush()); poly.clear(); poly.append(m_rect.topRight() + QPointF(-TriangleOffset, 0)); poly.append(m_rect.topRight() + QPointF(0, TriangleOffset)); poly.append(m_rect.topRight() + QPointF(-TriangleOffset, TriangleOffset)); painter->drawPolygon(poly); painter->setPen(m_pen); poly.clear(); poly.append(QPointF(0, m_rect.bottom() - borderWidth / 2.0)); poly.append(QPointF(m_rect.right(), m_rect.bottom() - borderWidth / 2.0)); painter->drawPolygon(poly); if (option->state & QStyle::State_Selected) { GraphicsUtils::qt_graphicsItem_highlightSelected(painter, option, boundingRect(), QPainterPath()); } if (m_inactive) { painter->restore(); } } QRectF Note::boundingRect() const { return m_rect; } QPainterPath Note::shape() const { QPainterPath path; path.addRect(boundingRect()); return path; } void Note::positionGrip() { QSizeF gripSize = m_resizeGrip->boundingRect().size(); QSizeF sz = this->boundingRect().size(); QPointF p(sz.width() - gripSize.width(), sz.height() - gripSize.height()); m_resizeGrip->setPos(p); m_graphicsTextItem->setPos(TriangleOffset / 2, TriangleOffset / 2); m_graphicsTextItem->setTextWidth(sz.width() - TriangleOffset); } void Note::mousePressEvent(QGraphicsSceneMouseEvent * event) { InfoGraphicsView *infographics = InfoGraphicsView::getInfoGraphicsView(this); if (infographics != NULL && infographics->spaceBarIsPressed()) { m_spaceBarWasPressed = true; event->ignore(); return; } m_spaceBarWasPressed = false; m_inResize = NULL; ItemBase::mousePressEvent(event); } void Note::mouseMoveEvent(QGraphicsSceneMouseEvent * event) { if (m_spaceBarWasPressed) { event->ignore(); return; } ItemBase::mouseMoveEvent(event); } void Note::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) { if (m_spaceBarWasPressed) { event->ignore(); return; } ItemBase::mouseReleaseEvent(event); } void Note::contentsChangeSlot(int position, int charsRemoved, int charsAdded) { Q_UNUSED(charsRemoved); m_charsAdded = charsAdded; m_charsPosition = position; } void Note::forceFormat(int position, int charsAdded) { disconnectSlots(); QTextCursor textCursor = m_graphicsTextItem->textCursor(); QTextCharFormat f; QFont font("Droid Sans", 9, QFont::Normal); f.setFont(font); f.setFontFamily("Droid Sans"); f.setFontPointSize(9); int cc = m_graphicsTextItem->document()->characterCount(); textCursor.setPosition(position, QTextCursor::MoveAnchor); if (position + charsAdded >= cc) { charsAdded--; } textCursor.setPosition(position + charsAdded, QTextCursor::KeepAnchor); //textCursor.setCharFormat(f); textCursor.mergeCharFormat(f); //DebugDialog::debug(QString("setting font tc:%1,%2 params:%3,%4") //.arg(textCursor.anchor()).arg(textCursor.position()) //.arg(position).arg(position + charsAdded)); /* textCursor = m_graphicsTextItem->textCursor(); for (int i = 0; i < charsAdded; i++) { textCursor.setPosition(position + i, QTextCursor::MoveAnchor); f = textCursor.charFormat(); DebugDialog::debug(QString("1format %1 %2 %3").arg(f.fontPointSize()).arg(f.fontFamily()).arg(f.fontWeight())); //f.setFont(font); //f.setFontPointSize(9); //f.setFontWeight(QFont::Normal); //textCursor.setCharFormat(f); //QTextCharFormat g = textCursor.charFormat(); //DebugDialog::debug(QString("2format %1 %2 %3").arg(g.fontPointSize()).arg(g.fontFamily()).arg(g.fontWeight())); } */ connectSlots(); } void Note::contentsChangedSlot() { //DebugDialog::debug(QString("contents changed ") + m_graphicsTextItem->document()->toPlainText()); if (m_charsAdded > 0) { forceFormat(m_charsPosition, m_charsAdded); } InfoGraphicsView *infoGraphicsView = InfoGraphicsView::getInfoGraphicsView(this); if (infoGraphicsView != NULL) { QString oldText; if (m_modelPart) { oldText = m_modelPart->instanceText(); } QSizeF oldSize = m_rect.size(); QSizeF newSize = oldSize; checkSize(newSize); infoGraphicsView->noteChanged(this, oldText, m_graphicsTextItem->document()->toHtml(), oldSize, newSize); } if (m_modelPart) { m_modelPart->setInstanceText(m_graphicsTextItem->document()->toHtml()); } } void Note::checkSize(QSizeF & newSize) { QSizeF gripSize = m_resizeGrip->boundingRect().size(); QSizeF size = m_graphicsTextItem->document()->size(); if (size.height() + gripSize.height() + gripSize.height() > m_rect.height()) { prepareGeometryChange(); m_rect.setHeight(size.height() + gripSize.height() + gripSize.height()); newSize.setHeight(m_rect.height()); positionGrip(); this->update(); } } void Note::disconnectSlots() { disconnect(m_graphicsTextItem->document(), SIGNAL(contentsChanged()), this, SLOT(contentsChangedSlot())); disconnect(m_graphicsTextItem->document(), SIGNAL(contentsChange(int, int, int)), this, SLOT(contentsChangeSlot(int, int, int))); } void Note::connectSlots() { connect(m_graphicsTextItem->document(), SIGNAL(contentsChanged()), this, SLOT(contentsChangedSlot()), Qt::DirectConnection); connect(m_graphicsTextItem->document(), SIGNAL(contentsChange(int, int, int)), this, SLOT(contentsChangeSlot(int, int, int)), Qt::DirectConnection); } void Note::setText(const QString & text, bool check) { // disconnect the signal so it doesn't fire recursively disconnectSlots(); QString oldText = text; m_graphicsTextItem->document()->setHtml(text); connectSlots(); if (check) { QSizeF newSize; checkSize(newSize); forceFormat(0, m_graphicsTextItem->document()->characterCount()); } } QString Note::text() { return m_graphicsTextItem->document()->toHtml(); } void Note::setSize(const QSizeF & size) { prepareGeometryChange(); m_rect.setWidth(size.width()); m_rect.setHeight(size.height()); positionGrip(); } void Note::setHidden(bool hide) { ItemBase::setHidden(hide); m_graphicsTextItem->setVisible(!hide); m_resizeGrip->setVisible(!hide); } void Note::setInactive(bool inactivate) { ItemBase::setInactive(inactivate); } bool Note::eventFilter(QObject * object, QEvent * event) { if (event->type() == QEvent::Shortcut || event->type() == QEvent::ShortcutOverride) { if (!object->inherits("QGraphicsView")) { event->accept(); return true; } } if (event->type() == QEvent::KeyPress) { QKeyEvent * kevent = static_cast<QKeyEvent *>(event); if (kevent->matches(QKeySequence::Bold)) { QTextCursor textCursor = m_graphicsTextItem->textCursor(); QTextCharFormat cf = textCursor.charFormat(); bool isBold = cf.fontWeight() == QFont::Bold; QTextCharFormat textCharFormat; textCharFormat.setFontWeight(isBold ? QFont::Normal : QFont::Bold); textCursor.mergeCharFormat(textCharFormat); event->accept(); return true; } if (kevent->matches(QKeySequence::Italic)) { QTextCursor textCursor = m_graphicsTextItem->textCursor(); QTextCharFormat cf = textCursor.charFormat(); QTextCharFormat textCharFormat; textCharFormat.setFontItalic(!cf.fontItalic()); textCursor.mergeCharFormat(textCharFormat); event->accept(); return true; } if ((kevent->key() == Qt::Key_L) && (kevent->modifiers() & Qt::ControlModifier)) { QTimer::singleShot(75, this, SLOT(linkDialog())); event->accept(); return true; } } return false; } void Note::linkDialog() { QTextCursor textCursor = m_graphicsTextItem->textCursor(); bool gotUrl = false; if (textCursor.anchor() == textCursor.selectionStart()) { // the selection returns empty since we're between characters // so select one character forward or one character backward // to see whether we're in a url int wasAnchor = textCursor.anchor(); bool atEnd = textCursor.atEnd(); bool atStart = textCursor.atStart(); if (!atStart) { textCursor.setPosition(wasAnchor - 1, QTextCursor::KeepAnchor); QString html = textCursor.selection().toHtml(); if (UrlTag.indexIn(html) >= 0) { gotUrl = true; } } if (!gotUrl && !atEnd) { textCursor.setPosition(wasAnchor + 1, QTextCursor::KeepAnchor); QString html = textCursor.selection().toHtml(); if (UrlTag.indexIn(html) >= 0) { gotUrl = true; } } textCursor.setPosition(wasAnchor, QTextCursor::MoveAnchor); } else { QString html = textCursor.selection().toHtml(); DebugDialog::debug(html); if (UrlTag.indexIn(html) >= 0) { gotUrl = true; } } LinkDialog ld; QString originalText; QString originalUrl; if (gotUrl) { originalUrl = UrlTag.cap(1); ld.setUrl(originalUrl); QString html = m_graphicsTextItem->toHtml(); // assumes html is in xml form QString errorStr; int errorLine; int errorColumn; QDomDocument domDocument; if (!domDocument.setContent(html, &errorStr, &errorLine, &errorColumn)) { return; } QDomElement root = domDocument.documentElement(); if (root.isNull()) { return; } if (root.tagName() != "html") { return; } DebugDialog::debug(html); QList<QDomElement> aElements; findA(root, aElements); foreach (QDomElement a, aElements) { // TODO: if multiple hrefs point to the same url this will only find the first one QString href = a.attribute("href"); if (href.isEmpty()) { href = a.attribute("HREF"); } if (href.compare(originalUrl) == 0) { QString text; if (TextUtils::findText(a, text)) { ld.setText(text); break; } else { return; } } } } int result = ld.exec(); if (result == QDialog::Accepted) { if (gotUrl) { int from = 0; while (true) { QTextCursor cursor = m_graphicsTextItem->document()->find(originalText, from); if (cursor.isNull()) { // TODO: tell the user return; } QString html = cursor.selection().toHtml(); if (html.contains(originalUrl)) { cursor.insertHtml(QString("<a href=\"%1\">%2</a>").arg(ld.url()).arg(ld.text())); break; } from = cursor.selectionEnd(); } } else { textCursor.insertHtml(QString("<a href=\"%1\">%2</a>").arg(ld.url()).arg(ld.text())); } } } void Note::handleZoomChangedSlot(double scale) { Q_UNUSED(scale); positionGrip(); } void Note::handleMousePressSlot(QGraphicsSceneMouseEvent * event, ResizeHandle * resizeHandle) { if (m_spaceBarWasPressed) return; saveGeometry(); QSizeF sz = this->boundingRect().size(); resizeHandle->setResizeOffset(this->pos() + QPointF(sz.width(), sz.height()) - event->scenePos()); m_inResize = resizeHandle; } void Note::handleMouseMoveSlot(QGraphicsSceneMouseEvent * event, ResizeHandle * resizeHandle) { Q_UNUSED(resizeHandle); if (!m_inResize) return; double minWidth = emptyMinWidth; double minHeight = emptyMinHeight; QSizeF gripSize = m_resizeGrip->boundingRect().size(); QSizeF minSize = m_graphicsTextItem->document()->size() + gripSize + gripSize; if (minSize.height() > minHeight) minHeight = minSize.height(); QRectF rect = boundingRect(); rect.moveTopLeft(this->pos()); double oldX1 = rect.x(); double oldY1 = rect.y(); double newX = event->scenePos().x() + m_inResize->resizeOffset().x(); double newY = event->scenePos().y() + m_inResize->resizeOffset().y(); QRectF newR; if (newX - oldX1 < minWidth) { newX = oldX1 + minWidth; } if (newY - oldY1 < minHeight) { newY = oldY1 + minHeight; } newR.setRect(0, 0, newX - oldX1, newY - oldY1); prepareGeometryChange(); m_rect = newR; positionGrip(); } void Note::handleMouseReleaseSlot(QGraphicsSceneMouseEvent * event, ResizeHandle * resizeHandle) { Q_UNUSED(resizeHandle); Q_UNUSED(event); if (!m_inResize) return; m_inResize = NULL; InfoGraphicsView *infoGraphicsView = InfoGraphicsView::getInfoGraphicsView(this); if (infoGraphicsView != NULL) { infoGraphicsView->noteSizeChanged(this, m_viewGeometry.rect().size(), m_rect.size()); } } bool Note::hasPartLabel() { return false; } bool Note::stickyEnabled() { return false; } bool Note::hasPartNumberProperty() { return false; } bool Note::rotationAllowed() { return false; } bool Note::rotation45Allowed() { return false; } QString Note::retrieveSvg(ViewLayer::ViewLayerID viewLayerID, QHash<QString, QString> & svgHash, bool blackOnly, double dpi, double & factor) { Q_UNUSED(svgHash); factor = 1; switch (viewLayerID) { case ViewLayer::BreadboardNote: if (viewID() != ViewLayer::BreadboardView) return ""; break; case ViewLayer::PcbNote: if (viewID() != ViewLayer::PCBView) return ""; break; case ViewLayer::SchematicNote: if (viewID() != ViewLayer::SchematicView) return ""; break; default: return ""; } QString svg = "<g>"; QString penColor = blackOnly ? "#000000" : m_pen.color().name(); double penWidth = m_pen.widthF() * dpi / GraphicsUtils::SVGDPI; QString brushColor = blackOnly ? "none" : m_brush.color().name(); svg += QString("<rect x='%1' y='%2' width='%3' height='%4' fill='%5' stroke='%6' stroke-width='%7' />") .arg(penWidth / 2) .arg(penWidth / 2) .arg((m_rect.width() * dpi / GraphicsUtils::SVGDPI) - penWidth) .arg((m_rect.height() * dpi / GraphicsUtils::SVGDPI) - penWidth) .arg(brushColor) .arg(penColor) .arg(penWidth) ; QTextCursor textCursor = m_graphicsTextItem->textCursor(); QSizeF gripSize = m_resizeGrip->boundingRect().size(); double docLeft = gripSize.width(); double docTop = gripSize.height(); for (QTextBlock block = m_graphicsTextItem->document()->begin(); block.isValid(); block = block.next()) { QTextLayout * layout = block.layout(); double left = block.blockFormat().leftMargin() + docLeft + layout->position().x(); double top = block.blockFormat().topMargin() + docTop + layout->position().y(); for (int i = 0; i < layout->lineCount(); i++) { QTextLine line = layout->lineAt(i); QRectF r = line.rect(); int start = line.textStart(); int count = line.textLength(); QString soFar; svg += QString("<text x='%1' y='%2' font-family='%3' stroke='none' fill='#000000' text-anchor='left' font-size='%4' >\n") .arg((left + r.left()) * dpi / GraphicsUtils::SVGDPI) .arg((top + r.top() + line.ascent()) * dpi / GraphicsUtils::SVGDPI) .arg("Droid Sans") .arg(line.ascent() * dpi / GraphicsUtils::SVGDPI) ; bool inUrl = false; for (int i = 0; i < count; i++) { textCursor.setPosition(i + start + block.position(), QTextCursor::MoveAnchor); textCursor.setPosition(i + start + block.position() + 1, QTextCursor::KeepAnchor); QString html = textCursor.selection().toHtml(); if (UrlTag.indexIn(html) >= 0) { if (inUrl) { soFar += block.text().mid(start + i, 1); continue; } svg += addText(soFar, false); soFar = block.text().mid(start + i, 1); inUrl = true; } else { if (!inUrl) { soFar += block.text().mid(start + i, 1); continue; } svg += addText(soFar, !blackOnly); soFar = block.text().mid(start + i, 1); inUrl = false; } } svg += addText(soFar, inUrl && !blackOnly); svg += "</text>"; } } svg += "</g>"; return svg; } ViewLayer::ViewID Note::useViewIDForPixmap(ViewLayer::ViewID, bool) { return ViewLayer::IconView; } void Note::addedToScene(bool temporary) { positionGrip(); return ItemBase::addedToScene(temporary); }<|fim▁end|>
if (viewGeometry.rect().width() == 0 || viewGeometry.rect().height() == 0) {
<|file_name|>users.js<|end_file_name|><|fim▁begin|>// © 2000 NEOSYS Software Ltd. All Rights Reserved.//**Start Encode** function form_postinit() { //enable/disable password changing button neosyssetexpression('button_password', 'disabled', '!gusers_authorisation_update&&gkey!=gusername') //force retrieval of own record if (gro.dictitem('USER_ID').defaultvalue) window.setTimeout('focuson("USER_NAME")', 100) gwhatsnew = neosysgetcookie(glogincode, 'NEOSYS2', 'wn').toLowerCase() if (gwhatsnew) { if (window.location.href.toString().slice(0, 5) == 'file:') gwhatsnew = 'file:///' + gwhatsnew else gwhatsnew = '..' + gwhatsnew.slice(gwhatsnew.indexOf('\\data\\')) neosyssetcookie(glogincode, 'NEOSYS2', '', 'wn') neosyssetcookie(glogincode, 'NEOSYS2', gwhatsnew, 'wn2') window.setTimeout('windowopen(gwhatsnew)', 1000) //windowopen(gwhatsnew) } $$('button_password').onclick = user_setpassword return true } //just to avoid confirmation function form_prewrite() { return true } //in authorisation.js and users.htm var gtasks_newpassword function form_postwrite() { //if change own password then login with the new one //otherwise cannot continue/unlock document so the lock hangs if (gtasks_newpassword) db.login(gusername, gtasks_newpassword) gtasks_newpassword = false //to avoid need full login to get new font/colors neosyssetcookie(glogincode, 'NEOSYS2', gds.getx('SCREEN_BODY_COLOR'), 'fc') neosyssetcookie(glogincode, 'NEOSYS2', gds.getx('SCREEN_FONT'), 'ff') neosyssetcookie(glogincode, 'NEOSYS2', gds.getx('SCREEN_FONT_SIZE'), 'fs') return true } function users_postdisplay() { var signatureimageelement = document.getElementById('signature_image') <|fim▁hole|> signatureimageelement.src = '' signatureimageelement.height = 0 signatureimageelement.width = 0 signatureimageelement.src = '../images/'+gdataset+'SHARP/UPLOAD/USERS/' + gkey.neosysconvert(' ', '') + '_signature.jpg' } //show only first five lines form_filter('refilter', 'LOGIN_DATE', '', 4) var reminderdays = 6 var passwordexpires = gds.getx('PASSWORD_EXPIRY_DATE') $passwordexpiryelement = $$('passwordexpiryelement') $passwordexpiryelement.innerHTML = '' if (passwordexpires) { var expirydays = (neosysint(passwordexpires) - neosysdate()) if (expirydays <= reminderdays) $passwordexpiryelement.innerHTML = '<font color=red>&nbsp;&nbsp;&nbsp;Password expires in ' + expirydays + ' days.</font>' } return true } function form_postread() { window.setTimeout('users_postdisplay()', 10) return true } function users_upload_signature() { //return openwindow('EXECUTE\r\MEDIA\r\OPENMATERIAL',scheduleno+'.'+materialletter) /* params=new Object() params.scheduleno=scheduleno params.materialletter=materialletter neosysshowmodaldialog('../NEOSYS/upload.htm',params) */ //images are not stored per dataset at the moment so that they can be //nor are they stored per file or per key so that they can be easily saved into a shared folder instead of going by web upload params = {} params.database = gdataset params.filename = 'USERS' params.key = gkey.neosysconvert(' ', '') + '_signature' params.versionno = ''//newarchiveno params.updateallowed = true params.deleteallowed = true //params.allowimages = true //we only allow one image type merely so that the signature file name //is always know and doesnt need saving in the user file //and no possibility of uploading two image files with different extensions params.allowablefileextensions = 'jpg' var targetfilename = neosysshowmodaldialog('../NEOSYS/upload.htm', params) window.setTimeout('users_postdisplay()', 1) if (!targetfilename) return false return true } function user_signature_onload(el) { el.removeAttribute("width") el.removeAttribute("height") }<|fim▁end|>
if (signatureimageelement) {
<|file_name|>user.js<|end_file_name|><|fim▁begin|>var mongoose = require('mongoose'); var bcrypt = require('bcrypt'); var saltRounds = 10; var userSchema = new mongoose.Schema({ email: { type: String, index: {unique: true} }, password: String, name: String });<|fim▁hole|>} userSchema.methods.validPassword = function(password){ return bcrypt.compareSync(password, this.password); } var User = mongoose.model('User',userSchema); module.exports = User;<|fim▁end|>
//hash password userSchema.methods.generateHash = function(password){ return bcrypt.hashSync(password, bcrypt.genSaltSync(saltRounds));
<|file_name|>build.server.prod.ts<|end_file_name|><|fim▁begin|>import * as gulp from 'gulp'; import * as gulpLoadPlugins from 'gulp-load-plugins'; import * as merge from 'merge-stream'; import { join/*, sep, relative*/ } from 'path'; import Config from '../../config'; import { makeTsProject, TemplateLocalsBuilder } from '../../utils'; import { TypeScriptTask } from '../typescript_task'; <|fim▁hole|>let typedBuildCounter = Config.TYPED_COMPILE_INTERVAL; // Always start with the typed build. /** * Executes the build process, transpiling the TypeScript files (except the spec and e2e-spec files) for the development * environment. */ export = class BuildServerDev extends TypeScriptTask { run() { const tsProject: any; const typings = gulp.src([ Config.TOOLS_DIR + '/manual_typings/**/*.d.ts' ]); const src = [ join(Config.APP_SERVER_SRC, '**/*.ts') ]; let projectFiles = gulp.src(src); let result: any; let isFullCompile = true; // Only do a typed build every X builds, otherwise do a typeless build to speed things up if (typedBuildCounter < Config.TYPED_COMPILE_INTERVAL) { isFullCompile = false; tsProject = makeTsProject({isolatedModules: true}); projectFiles = projectFiles.pipe(plugins.cached()); } else { tsProject = makeTsProject(); projectFiles = merge(typings, projectFiles); } result = projectFiles .pipe(plugins.plumber()) .pipe(plugins.sourcemaps.init()) .pipe(tsProject()) .on('error', () => { typedBuildCounter = Config.TYPED_COMPILE_INTERVAL; }); if (isFullCompile) { typedBuildCounter = 0; } else { typedBuildCounter++; } return result.js .pipe(plugins.sourcemaps.write()) // Use for debugging with Webstorm/IntelliJ // https://github.com/mgechev/angular2-seed/issues/1220 // .pipe(plugins.sourcemaps.write('.', { // includeContent: false, // sourceRoot: (file: any) => // relative(file.path, PROJECT_ROOT + '/' + APP_SRC).replace(sep, '/') + '/' + APP_SRC // })) .pipe(plugins.template(new TemplateLocalsBuilder().withStringifiedSystemConfigDev().build())) .pipe(gulp.dest(Config.APP_SERVER_DEST)); } };<|fim▁end|>
const plugins = <any>gulpLoadPlugins();
<|file_name|>uart.rs<|end_file_name|><|fim▁begin|>use Core; use Addon; use io; pub struct Uart { /// The baud rate (bits/second) pub baud: u64, /// The number of CPU ticks in a single second (ticks/second) pub cpu_frequency: u64, /// Number of ticks between each bit. ticks_between_bits: u64, ticks_until_next_bit: u64, _tx: io::Port, _rx: io::Port, _processed_bits: Vec<u8>, } impl Uart { pub fn new(cpu_frequency: u64, baud: u64, tx: io::Port, rx: io::Port) -> Self {<|fim▁hole|> Uart { cpu_frequency: cpu_frequency, baud: baud, _tx: tx, _rx: rx, ticks_between_bits: ticks_between_bits, // TODO: set this variable ticks_until_next_bit: ticks_between_bits, _processed_bits: Vec::new(), } } fn process_bit(&mut self, _core: &mut Core) { println!("tick"); } } impl Addon for Uart { fn tick(&mut self, core: &mut Core) { self.ticks_until_next_bit -= 1; if self.ticks_until_next_bit == 0 { self.process_bit(core); self.ticks_until_next_bit = self.ticks_between_bits; } } }<|fim▁end|>
let ticks_between_bits = cpu_frequency / baud;
<|file_name|>index.js<|end_file_name|><|fim▁begin|>var Action = require('./../actions/action.create.js'); var RouteConfig = require('./route.create.config');<|fim▁hole|><|fim▁end|>
var RouteCreate = require('./route.default.js')(Action, RouteConfig);
<|file_name|>chmod.rs<|end_file_name|><|fim▁begin|>#![crate_name = "uu_chmod"] /* * This file is part of the uutils coreutils package. * * (c) Arcterus <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate libc; extern crate walker; #[macro_use] extern crate uucore; use std::error::Error; use std::ffi::CString; use std::io::{self, Write}; use std::mem; use std::path::Path; use walker::Walker; const NAME: &'static str = "chmod"; static SUMMARY: &'static str = "Change the mode of each FILE to MODE. With --reference, change the mode of each FILE to that of RFILE."; static LONG_HELP: &'static str = " Each MODE is of the form '[ugoa]*([-+=]([rwxXst]*|[ugo]))+|[-+=]?[0-7]+'. "; pub fn uumain(mut args: Vec<String>) -> i32 { let syntax = format!("[OPTION]... MODE[,MODE]... FILE... {0} [OPTION]... OCTAL-MODE FILE... {0} [OPTION]... --reference=RFILE FILE...", NAME); let mut opts = new_coreopts!(&syntax, SUMMARY, LONG_HELP); opts.optflag("c", "changes", "like verbose but report only when a change is made (unimplemented)") .optflag("f", "quiet", "suppress most error messages (unimplemented)") // TODO: support --silent .optflag("v", "verbose", "output a diagnostic for every file processed (unimplemented)") .optflag("", "no-preserve-root", "do not treat '/' specially (the default)") .optflag("", "preserve-root", "fail to operate recursively on '/'") .optopt("", "reference", "use RFILE's mode instead of MODE values", "RFILE") .optflag("R", "recursive", "change files and directories recursively"); // sanitize input for - at beginning (e.g. chmod -x testfile). Remove // the option and save it for later, after parsing is finished. let mut negative_option = None; for i in 0..args.len() { if let Some(first) = args[i].chars().nth(0) { if first != '-' { continue; } if let Some(second) = args[i].chars().nth(1) { match second { 'r' | 'w' | 'x' | 'X' | 's' | 't' | 'u' | 'g' | 'o' | '0' ... '7' => { negative_option = Some(args.remove(i)); break; }, _ => {} } } } } let mut matches = opts.parse(args); if matches.free.is_empty() { show_error!("missing an argument"); show_error!("for help, try '{} --help'", NAME); return 1; } else { let changes = matches.opt_present("changes"); let quiet = matches.opt_present("quiet"); let verbose = matches.opt_present("verbose"); let preserve_root = matches.opt_present("preserve-root");<|fim▁hole|> }); let mut stat : libc::stat = unsafe { mem::uninitialized() }; let statres = unsafe { libc::stat(s.as_ptr() as *const _, &mut stat as *mut libc::stat) }; if statres == 0 { Some(stat.st_mode) } else { crash!(1, "cannot stat attribues of '{}': {}", matches.opt_str("reference").unwrap(), io::Error::last_os_error()) } }); let cmode = if fmode.is_none() { // If there was a negative option, now it's a good time to // use it. if negative_option.is_some() { negative_option } else { Some(matches.free.remove(0)) } } else { None }; match chmod(matches.free, changes, quiet, verbose, preserve_root, recursive, fmode, cmode.as_ref()) { Ok(()) => {} Err(e) => return e } } 0 } fn chmod(files: Vec<String>, changes: bool, quiet: bool, verbose: bool, preserve_root: bool, recursive: bool, fmode: Option<libc::mode_t>, cmode: Option<&String>) -> Result<(), i32> { let mut r = Ok(()); for filename in &files { let filename = &filename[..]; let file = Path::new(filename); if file.exists() { if file.is_dir() { if !preserve_root || filename != "/" { if recursive { let walk_dir = match Walker::new(&file) { Ok(m) => m, Err(f) => { crash!(1, "{}", f.to_string()); } }; // XXX: here (and elsewhere) we see that this impl will have issues // with non-UTF-8 filenames. Using OsString won't fix this because // on Windows OsStrings cannot be built out of non-UTF-8 chars. One // possible fix is to use CStrings rather than Strings in the args // to chmod() and chmod_file(). r = chmod(walk_dir.filter_map(|x| match x { Ok(o) => match o.path().into_os_string().to_str() { Some(s) => Some(s.to_owned()), None => None, }, Err(_) => None, }).collect(), changes, quiet, verbose, preserve_root, recursive, fmode, cmode).and(r); r = chmod_file(&file, filename, changes, quiet, verbose, fmode, cmode).and(r); } } else { show_error!("could not change permissions of directory '{}'", filename); r = Err(1); } } else { r = chmod_file(&file, filename, changes, quiet, verbose, fmode, cmode).and(r); } } else { show_error!("no such file or directory '{}'", filename); r = Err(1); } } r } #[cfg(windows)] fn chmod_file(file: &Path, name: &str, changes: bool, quiet: bool, verbose: bool, fmode: Option<libc::mode_t>, cmode: Option<&String>) -> Result<(), i32> { // chmod is useless on Windows // it doesn't set any permissions at all // instead it just sets the readonly attribute on the file Err(0) } #[cfg(unix)] fn chmod_file(file: &Path, name: &str, changes: bool, quiet: bool, verbose: bool, fmode: Option<libc::mode_t>, cmode: Option<&String>) -> Result<(), i32> { let path = CString::new(name).unwrap_or_else(|e| panic!("{}", e)); let mut stat: libc::stat = unsafe { mem::uninitialized() }; let statres = unsafe { libc::stat(path.as_ptr(), &mut stat as *mut libc::stat) }; let mut fperm = if statres == 0 { stat.st_mode & 0o7777 } else { if !quiet { show_error!("{}", io::Error::last_os_error()); } return Err(1); }; match fmode { Some(mode) => try!(change_file(fperm, mode, file, &path, verbose, changes, quiet)), None => { for mode in cmode.unwrap().split(',') { // cmode is guaranteed to be Some in this case let arr: &[char] = &['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; let result = if mode.contains(arr) { parse_numeric(fperm, mode) } else { parse_symbolic(fperm, mode, file) }; match result { Ok(mode) => { try!(change_file(fperm, mode, file, &path, verbose, changes, quiet)); fperm = mode; } Err(f) => { if !quiet { show_error!("{}", f); } return Err(1); } } } } } Ok(()) } fn parse_numeric(fperm: libc::mode_t, mut mode: &str) -> Result<libc::mode_t, String> { let (op, pos) = try!(parse_op(mode, Some('='))); mode = mode[pos..].trim_left_matches('0'); if mode.len() > 4 { Err(format!("mode is too large ({} > 7777)", mode)) } else { match libc::mode_t::from_str_radix(mode, 8) { Ok(change) => { Ok(match op { '+' => fperm | change, '-' => fperm & !change, '=' => change, _ => unreachable!() }) } Err(err) => Err(err.description().to_owned()) } } } fn parse_symbolic(mut fperm: libc::mode_t, mut mode: &str, file: &Path) -> Result<libc::mode_t, String> { let (mask, pos) = parse_levels(mode); if pos == mode.len() { return Err(format!("invalid mode ({})", mode)); } let respect_umask = pos == 0; let last_umask = unsafe { libc::umask(0) }; mode = &mode[pos..]; while mode.len() > 0 { let (op, pos) = try!(parse_op(mode, None)); mode = &mode[pos..]; let (mut srwx, pos) = parse_change(mode, fperm, file); if respect_umask { srwx &= !last_umask; } mode = &mode[pos..]; match op { '+' => fperm |= srwx & mask, '-' => fperm &= !(srwx & mask), '=' => fperm = (fperm & !mask) | (srwx & mask), _ => unreachable!() } } unsafe { libc::umask(last_umask); } Ok(fperm) } fn parse_levels(mode: &str) -> (libc::mode_t, usize) { let mut mask = 0; let mut pos = 0; for ch in mode.chars() { mask |= match ch { 'u' => 0o7700, 'g' => 0o7070, 'o' => 0o7007, 'a' => 0o7777, _ => break }; pos += 1; } if pos == 0 { mask = 0o7777; // default to 'a' } (mask, pos) } fn parse_op(mode: &str, default: Option<char>) -> Result<(char, usize), String> { match mode.chars().next() { Some(ch) => match ch { '+' | '-' | '=' => Ok((ch, 1)), _ => match default { Some(ch) => Ok((ch, 0)), None => Err(format!("invalid operator (expected +, -, or =, but found {})", ch)) } }, None => Err("unexpected end of mode".to_owned()) } } fn parse_change(mode: &str, fperm: libc::mode_t, file: &Path) -> (libc::mode_t, usize) { let mut srwx = fperm & 0o7000; let mut pos = 0; for ch in mode.chars() { match ch { 'r' => srwx |= 0o444, 'w' => srwx |= 0o222, 'x' => srwx |= 0o111, 'X' => { if file.is_dir() || (fperm & 0o0111) != 0 { srwx |= 0o111 } } 's' => srwx |= 0o4000 | 0o2000, 't' => srwx |= 0o1000, 'u' => srwx = (fperm & 0o700) | ((fperm >> 3) & 0o070) | ((fperm >> 6) & 0o007), 'g' => srwx = ((fperm << 3) & 0o700) | (fperm & 0o070) | ((fperm >> 3) & 0o007), 'o' => srwx = ((fperm << 6) & 0o700) | ((fperm << 3) & 0o070) | (fperm & 0o007), _ => break }; pos += 1; } if pos == 0 { srwx = 0; } (srwx, pos) } fn change_file(fperm: libc::mode_t, mode: libc::mode_t, file: &Path, path: &CString, verbose: bool, changes: bool, quiet: bool) -> Result<(), i32> { if fperm == mode { if verbose && !changes { show_info!("mode of '{}' retained as {:o}", file.display(), fperm); } Ok(()) } else if unsafe { libc::chmod(path.as_ptr(), mode) } == 0 { if verbose || changes { show_info!("mode of '{}' changed from {:o} to {:o}", file.display(), fperm, mode); } Ok(()) } else { if !quiet { show_error!("{}", io::Error::last_os_error()); } if verbose { show_info!("failed to change mode of file '{}' from {:o} to {:o}", file.display(), fperm, mode); } return Err(1); } }<|fim▁end|>
let recursive = matches.opt_present("recursive"); let fmode = matches.opt_str("reference").and_then(|fref| { let s = CString::new(fref).unwrap_or_else( |_| { crash!(1, "reference file name contains internal nul byte")
<|file_name|>base.py<|end_file_name|><|fim▁begin|>""" Generalized Linear models. """ # Author: Alexandre Gramfort <[email protected]> # Fabian Pedregosa <[email protected]> # Olivier Grisel <[email protected]> # Vincent Michel <[email protected]> # Peter Prettenhofer <[email protected]> # Mathieu Blondel <[email protected]> # Lars Buitinck <[email protected]> # # License: BSD 3 clause from __future__ import division from abc import ABCMeta, abstractmethod import numbers import warnings import numpy as np import scipy.sparse as sp from scipy import linalg from scipy import sparse from ..externals import six from ..externals.joblib import Parallel, delayed from ..base import BaseEstimator, ClassifierMixin, RegressorMixin from ..utils import as_float_array, check_array, check_X_y, deprecated, column_or_1d from ..utils.extmath import safe_sparse_dot from ..utils.sparsefuncs import mean_variance_axis, inplace_column_scale from ..utils.fixes import sparse_lsqr from ..utils.validation import NotFittedError, check_is_fitted ### ### TODO: intercept for all models ### We should define a common function to center data instead of ### repeating the same code inside each fit method. ### TODO: bayesian_ridge_regression and bayesian_regression_ard ### should be squashed into its respective objects. def sparse_center_data(X, y, fit_intercept, normalize=False): """ Compute information needed to center data to have mean zero along axis 0. Be aware that X will not be centered since it would break the sparsity, but will be normalized if asked so. """ if fit_intercept: # we might require not to change the csr matrix sometimes # store a copy if normalize is True. # Change dtype to float64 since mean_variance_axis accepts # it that way. if sp.isspmatrix(X) and X.getformat() == 'csr': X = sp.csr_matrix(X, copy=normalize, dtype=np.float64) else: X = sp.csc_matrix(X, copy=normalize, dtype=np.float64) X_mean, X_var = mean_variance_axis(X, axis=0) if normalize: # transform variance to std in-place # XXX: currently scaled to variance=n_samples to match center_data X_var *= X.shape[0] X_std = np.sqrt(X_var, X_var) del X_var X_std[X_std == 0] = 1 inplace_column_scale(X, 1. / X_std) else: X_std = np.ones(X.shape[1]) y_mean = y.mean(axis=0) y = y - y_mean else: X_mean = np.zeros(X.shape[1]) X_std = np.ones(X.shape[1]) y_mean = 0. if y.ndim == 1 else np.zeros(y.shape[1], dtype=X.dtype) return X, y, X_mean, y_mean, X_std def center_data(X, y, fit_intercept, normalize=False, copy=True, sample_weight=None): """ Centers data to have mean zero along axis 0. This is here because nearly all linear models will want their data to be centered. If sample_weight is not None, then the weighted mean of X and y is zero, and not the mean itself """ X = as_float_array(X, copy) if fit_intercept: if isinstance(sample_weight, numbers.Number): sample_weight = None if sp.issparse(X): X_mean = np.zeros(X.shape[1]) X_std = np.ones(X.shape[1]) else: X_mean = np.average(X, axis=0, weights=sample_weight) X -= X_mean if normalize: # XXX: currently scaled to variance=n_samples X_std = np.sqrt(np.sum(X ** 2, axis=0)) X_std[X_std == 0] = 1 X /= X_std else: X_std = np.ones(X.shape[1]) y_mean = np.average(y, axis=0, weights=sample_weight) y = y - y_mean else: X_mean = np.zeros(X.shape[1]) X_std = np.ones(X.shape[1]) y_mean = 0. if y.ndim == 1 else np.zeros(y.shape[1], dtype=X.dtype) return X, y, X_mean, y_mean, X_std def _rescale_data(X, y, sample_weight): """Rescale data so as to support sample_weight""" n_samples = X.shape[0] sample_weight = sample_weight * np.ones(n_samples) sample_weight = np.sqrt(sample_weight) sw_matrix = sparse.dia_matrix((sample_weight, 0), shape=(n_samples, n_samples)) X = safe_sparse_dot(sw_matrix, X) y = safe_sparse_dot(sw_matrix, y) return X, y class LinearModel(six.with_metaclass(ABCMeta, BaseEstimator)): """Base class for Linear Models""" @abstractmethod def fit(self, X, y): """Fit model.""" @deprecated(" and will be removed in 0.19.") def decision_function(self, X): """Decision function of the linear model. Parameters ---------- X : {array-like, sparse matrix}, shape = (n_samples, n_features) Samples. Returns ------- C : array, shape = (n_samples,) Returns predicted values. """ return self._decision_function(X) def _decision_function(self, X): check_is_fitted(self, "coef_") X = check_array(X, accept_sparse=['csr', 'csc', 'coo']) return safe_sparse_dot(X, self.coef_.T, dense_output=True) + self.intercept_ def predict(self, X): """Predict using the linear model Parameters ---------- X : {array-like, sparse matrix}, shape = (n_samples, n_features) Samples. Returns ------- C : array, shape = (n_samples,) Returns predicted values. """ return self._decision_function(X) _center_data = staticmethod(center_data) def _set_intercept(self, X_mean, y_mean, X_std): """Set the intercept_ """ if self.fit_intercept: self.coef_ = self.coef_ / X_std self.intercept_ = y_mean - np.dot(X_mean, self.coef_.T) else: self.intercept_ = 0. # XXX Should this derive from LinearModel? It should be a mixin, not an ABC. # Maybe the n_features checking can be moved to LinearModel. class LinearClassifierMixin(ClassifierMixin): """Mixin for linear classifiers. Handles prediction for sparse and dense X. """ def decision_function(self, X): """Predict confidence scores for samples. The confidence score for a sample is the signed distance of that sample to the hyperplane. Parameters ---------- X : {array-like, sparse matrix}, shape = (n_samples, n_features) Samples. Returns ------- array, shape=(n_samples,) if n_classes == 2 else (n_samples, n_classes) Confidence scores per (sample, class) combination. In the binary case, confidence score for self.classes_[1] where >0 means this class would be predicted. """ if not hasattr(self, 'coef_') or self.coef_ is None: raise NotFittedError("This %(name)s instance is not fitted " "yet" % {'name': type(self).__name__}) X = check_array(X, accept_sparse='csr') n_features = self.coef_.shape[1] if X.shape[1] != n_features: raise ValueError("X has %d features per sample; expecting %d" % (X.shape[1], n_features)) scores = safe_sparse_dot(X, self.coef_.T, dense_output=True) + self.intercept_ return scores.ravel() if scores.shape[1] == 1 else scores def predict(self, X): """Predict class labels for samples in X. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] Samples. Returns ------- C : array, shape = [n_samples] Predicted class label per sample. """ scores = self.decision_function(X) if len(scores.shape) == 1: indices = (scores > 0).astype(np.int) else: indices = scores.argmax(axis=1) return self.classes_[indices] def _predict_proba_lr(self, X): """Probability estimation for OvR logistic regression. Positive class probabilities are computed as 1. / (1. + np.exp(-self.decision_function(X))); multiclass is handled by normalizing that over all classes. """ prob = self.decision_function(X) prob *= -1 np.exp(prob, prob) prob += 1 np.reciprocal(prob, prob) if len(prob.shape) == 1: return np.vstack([1 - prob, prob]).T else: # OvR normalization, like LibLinear's predict_probability prob /= prob.sum(axis=1).reshape((prob.shape[0], -1)) return prob class SparseCoefMixin(object): """Mixin for converting coef_ to and from CSR format. <|fim▁hole|> def densify(self): """Convert coefficient matrix to dense array format. Converts the ``coef_`` member (back) to a numpy.ndarray. This is the default format of ``coef_`` and is required for fitting, so calling this method is only required on models that have previously been sparsified; otherwise, it is a no-op. Returns ------- self: estimator """ msg = "Estimator, %(name)s, must be fitted before densifying." check_is_fitted(self, "coef_", msg=msg) if sp.issparse(self.coef_): self.coef_ = self.coef_.toarray() return self def sparsify(self): """Convert coefficient matrix to sparse format. Converts the ``coef_`` member to a scipy.sparse matrix, which for L1-regularized models can be much more memory- and storage-efficient than the usual numpy.ndarray representation. The ``intercept_`` member is not converted. Notes ----- For non-sparse models, i.e. when there are not many zeros in ``coef_``, this may actually *increase* memory usage, so use this method with care. A rule of thumb is that the number of zero elements, which can be computed with ``(coef_ == 0).sum()``, must be more than 50% for this to provide significant benefits. After calling this method, further fitting with the partial_fit method (if any) will not work until you call densify. Returns ------- self: estimator """ msg = "Estimator, %(name)s, must be fitted before sparsifying." check_is_fitted(self, "coef_", msg=msg) self.coef_ = sp.csr_matrix(self.coef_) return self class LinearRegression(LinearModel, RegressorMixin): """ Ordinary least squares Linear Regression. Parameters ---------- fit_intercept : boolean, optional whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (e.g. data is expected to be already centered). normalize : boolean, optional, default False If True, the regressors X will be normalized before regression. copy_X : boolean, optional, default True If True, X will be copied; else, it may be overwritten. n_jobs : int, optional, default 1 The number of jobs to use for the computation. If -1 all CPUs are used. This will only provide speedup for n_targets > 1 and sufficient large problems. Attributes ---------- coef_ : array, shape (n_features, ) or (n_targets, n_features) Estimated coefficients for the linear regression problem. If multiple targets are passed during the fit (y 2D), this is a 2D array of shape (n_targets, n_features), while if only one target is passed, this is a 1D array of length n_features. intercept_ : array Independent term in the linear model. Notes ----- From the implementation point of view, this is just plain Ordinary Least Squares (scipy.linalg.lstsq) wrapped as a predictor object. """ def __init__(self, fit_intercept=True, normalize=False, copy_X=True, n_jobs=1): self.fit_intercept = fit_intercept self.normalize = normalize self.copy_X = copy_X self.n_jobs = n_jobs def fit(self, X, y, sample_weight=None): """ Fit linear model. Parameters ---------- X : numpy array or sparse matrix of shape [n_samples,n_features] Training data y : numpy array of shape [n_samples, n_targets] Target values sample_weight : numpy array of shape [n_samples] Individual weights for each sample Returns ------- self : returns an instance of self. """ n_jobs_ = self.n_jobs X, y = check_X_y(X, y, accept_sparse=['csr', 'csc', 'coo'], y_numeric=True, multi_output=True) if ((sample_weight is not None) and np.atleast_1d(sample_weight).ndim > 1): sample_weight = column_or_1d(sample_weight, warn=True) X, y, X_mean, y_mean, X_std = self._center_data( X, y, self.fit_intercept, self.normalize, self.copy_X, sample_weight=sample_weight) if sample_weight is not None: # Sample weight can be implemented via a simple rescaling. X, y = _rescale_data(X, y, sample_weight) if sp.issparse(X): if y.ndim < 2: out = sparse_lsqr(X, y) self.coef_ = out[0] self.residues_ = out[3] else: # sparse_lstsq cannot handle y with shape (M, K) outs = Parallel(n_jobs=n_jobs_)( delayed(sparse_lsqr)(X, y[:, j].ravel()) for j in range(y.shape[1])) self.coef_ = np.vstack(out[0] for out in outs) self.residues_ = np.vstack(out[3] for out in outs) else: self.coef_, self.residues_, self.rank_, self.singular_ = \ linalg.lstsq(X, y) self.coef_ = self.coef_.T if y.ndim == 1: self.coef_ = np.ravel(self.coef_) self._set_intercept(X_mean, y_mean, X_std) return self def _pre_fit(X, y, Xy, precompute, normalize, fit_intercept, copy, Xy_precompute_order=None): """Aux function used at beginning of fit in linear models""" n_samples, n_features = X.shape if sparse.isspmatrix(X): precompute = False X, y, X_mean, y_mean, X_std = sparse_center_data( X, y, fit_intercept, normalize) else: # copy was done in fit if necessary X, y, X_mean, y_mean, X_std = center_data( X, y, fit_intercept, normalize, copy=copy) if hasattr(precompute, '__array__') and ( fit_intercept and not np.allclose(X_mean, np.zeros(n_features)) or normalize and not np.allclose(X_std, np.ones(n_features))): warnings.warn("Gram matrix was provided but X was centered" " to fit intercept, " "or X was normalized : recomputing Gram matrix.", UserWarning) # recompute Gram precompute = 'auto' Xy = None # precompute if n_samples > n_features if precompute == 'auto': precompute = (n_samples > n_features) if precompute is True: precompute = np.dot(X.T, X) if Xy_precompute_order == 'F': precompute = np.dot(X.T, X).T if not hasattr(precompute, '__array__'): Xy = None # cannot use Xy if precompute is not Gram if hasattr(precompute, '__array__') and Xy is None: if Xy_precompute_order == 'F': Xy = np.dot(y.T, X).T else: Xy = np.dot(X.T, y) return X, y, X_mean, y_mean, X_std, precompute, Xy<|fim▁end|>
L1-regularizing estimators should inherit this. """
<|file_name|>args.rs<|end_file_name|><|fim▁begin|>pub const USAGE: &'static str = " Usage: jswag build [options] [<file>...] jswag run [options] [<file>...] jswag [options] <file>... jswag raw [<file>...] jswag (--help | --version) Commands: build Compiles all files and runs simple analysis checks on them. Automatically adds these parameters: $ --check --pass-through --analyze style run Works like `build`, but runs the file afterwards. Automatically adds these parameters to the already added parameters of `build`: $ --run <none> For compatibility this works similar to the original `javac` command. Right now it's exactly the same as 'build', except that the file list musn't be empty. raw Does nothing automatically. Every task has to be explicitly stated with command line parameters. Actions: -a <check>, --analyze <check> Run the given check. Implies `-c`. -c, --check Check files for language errors with internal tools. -p, --pass-through Call `javac` to compile the files. -r, --run Tries to execute the compiled classes in the order they were given. Requires `-p`. Options: --lossy-decoding Replace invalid UTF-8 or UTF-16 characters in the input file with 'U+FFFD REPLACEMENT CHARACTER' (�) instead of exiting. --encoding <encoding> Forces a specific file decoding. Valid values: 'utf8' [default: utf8] -h, --help Show this message. -v, --verbose More verbose messages. -V, --version Show the version of jswag. "; #[derive(Debug, RustcDecodable)] pub struct Args { pub cmd_build: bool, pub cmd_run: bool, pub cmd_raw: bool, pub arg_file: Vec<String>, pub arg_analyze: Vec<String>, pub flag_encoding: Encoding, pub flag_check: bool, pub flag_pass_through: bool, pub flag_run: bool,<|fim▁hole|> pub flag_version: bool, pub flag_lossy_decoding: bool, } #[derive(Clone, Copy, RustcDecodable, Debug)] pub enum Encoding { Utf8, // TODO: fucking encoding // Utf16, }<|fim▁end|>
pub flag_verbose: bool,
<|file_name|>zapwallettxes.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the zapwallettxes functionality. - start two iopd nodes - create two transactions on node 0 - one is confirmed and one is unconfirmed. - restart node 0 and verify that both the confirmed and the unconfirmed transactions are still available. - restart node 0 with zapwallettxes and persistmempool, and verify that both the confirmed and the unconfirmed transactions are still available. - restart node 0 with just zapwallettxed and verify that the confirmed transactions are still available, but that the unconfirmed transaction has been zapped. """ from test_framework.test_framework import IoPTestFramework from test_framework.util import ( assert_equal, assert_raises_rpc_error, wait_until, ) class ZapWalletTXesTest (IoPTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 2 def run_test(self): self.log.info("Mining blocks...") self.nodes[0].generate(1) self.sync_all() self.nodes[1].generate(100) self.sync_all() # This transaction will be confirmed txid1 = self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 10) self.nodes[0].generate(1) self.sync_all() # This transaction will not be confirmed txid2 = self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 20) # Confirmed and unconfirmed transactions are now in the wallet. assert_equal(self.nodes[0].gettransaction(txid1)['txid'], txid1) assert_equal(self.nodes[0].gettransaction(txid2)['txid'], txid2) # Stop-start node0. Both confirmed and unconfirmed transactions remain in the wallet. self.stop_node(0) self.start_node(0) assert_equal(self.nodes[0].gettransaction(txid1)['txid'], txid1) assert_equal(self.nodes[0].gettransaction(txid2)['txid'], txid2)<|fim▁hole|> self.start_node(0, ["-persistmempool=1", "-zapwallettxes=2"]) wait_until(lambda: self.nodes[0].getmempoolinfo()['size'] == 1, timeout=3) assert_equal(self.nodes[0].gettransaction(txid1)['txid'], txid1) assert_equal(self.nodes[0].gettransaction(txid2)['txid'], txid2) # Stop node0 and restart with zapwallettxes, but not persistmempool. # The unconfirmed transaction is zapped and is no longer in the wallet. self.stop_node(0) self.start_node(0, ["-zapwallettxes=2"]) # tx1 is still be available because it was confirmed assert_equal(self.nodes[0].gettransaction(txid1)['txid'], txid1) # This will raise an exception because the unconfirmed transaction has been zapped assert_raises_rpc_error(-5, 'Invalid or non-wallet transaction id', self.nodes[0].gettransaction, txid2) if __name__ == '__main__': ZapWalletTXesTest().main()<|fim▁end|>
# Stop node0 and restart with zapwallettxes and persistmempool. The unconfirmed # transaction is zapped from the wallet, but is re-added when the mempool is reloaded. self.stop_node(0)
<|file_name|>PropertiesToolBar.java<|end_file_name|><|fim▁begin|>/* * PropertiesToolBar.java * * Copyright (C) 2002-2017 Takis Diakoumis * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 3 * of the License, or any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.executequery.gui.prefs; import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.util.Collections; import java.util.Vector; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import org.executequery.Constants; import org.executequery.GUIUtilities; import org.underworldlabs.swing.actions.ActionUtilities; import org.underworldlabs.swing.actions.ReflectiveAction; import org.underworldlabs.swing.toolbar.ButtonComparator; import org.underworldlabs.swing.toolbar.ToolBarButton; import org.underworldlabs.swing.toolbar.ToolBarProperties; import org.underworldlabs.swing.toolbar.ToolBarWrapper; /** * * @author Takis Diakoumis */ public class PropertiesToolBar extends AbstractPropertiesBasePanel { private Vector selections; private JTable table; private ToolBarButtonModel toolButtonModel; private static IconCellRenderer iconRenderer; private static NameCellRenderer nameRenderer; private JButton moveUpButton; private JButton moveDownButton; private JButton addSeparatorButton; private JButton removeSeparatorButton; /** The tool bar name */ private String toolBarName; /** The tool bar wrapper */ private ToolBarWrapper toolBar; public PropertiesToolBar(String toolBarName) { this.toolBarName = toolBarName; try { jbInit(); } catch (Exception e) { e.printStackTrace(); } } private void jbInit() { ReflectiveAction action = new ReflectiveAction(this); moveUpButton = ActionUtilities.createButton( action, GUIUtilities.loadIcon("Up16.png", true), null, "moveUp"); moveDownButton = ActionUtilities.createButton( action, GUIUtilities.loadIcon("Down16.png", true), null, "moveDown"); moveUpButton.setMargin(Constants.EMPTY_INSETS); moveDownButton.setMargin(Constants.EMPTY_INSETS); addSeparatorButton = ActionUtilities.createButton( action, "Add Separator", "addSeparator"); addSeparatorButton.setToolTipText("Adds a separator above the selection"); removeSeparatorButton = ActionUtilities.createButton( action, "Remove Separator", "removeSeparator"); removeSeparatorButton.setToolTipText("Removes the selected separator"); ToolBarWrapper _toolBar = ToolBarProperties.getToolBar(toolBarName); toolBar = (ToolBarWrapper)_toolBar.clone(); selections = toolBar.getButtonsVector(); setInitialValues(); iconRenderer = new IconCellRenderer(); nameRenderer = new NameCellRenderer(); toolButtonModel = new ToolBarButtonModel(); table = new JTable(toolButtonModel); setTableProperties(); JScrollPane scroller = new JScrollPane(table); scroller.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scroller.getViewport().setBackground(table.getBackground()); JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridy = 0; gbc.gridx = 0; gbc.weightx = 1.0; gbc.insets.bottom = 5; gbc.gridwidth = 2; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.anchor = GridBagConstraints.NORTHWEST; panel.add(new JLabel(toolBarName + " - Buttons"), gbc); gbc.gridy++; gbc.weighty = 1.0; gbc.fill = GridBagConstraints.BOTH; panel.add(scroller, gbc); gbc.gridy++; gbc.weighty = 0; gbc.insets.bottom = 10; gbc.insets.right = 10; gbc.gridwidth = 1; gbc.fill = GridBagConstraints.HORIZONTAL; panel.add(addSeparatorButton, gbc); gbc.gridx++; gbc.insets.right = 0; panel.add(removeSeparatorButton, gbc); JPanel movePanel = new JPanel(new GridBagLayout()); GridBagConstraints gbc2 = new GridBagConstraints(); gbc2.gridy = 0; gbc2.insets.bottom = 10; gbc2.anchor = GridBagConstraints.CENTER; movePanel.add(moveUpButton, gbc2); gbc2.gridy++; gbc2.insets.bottom = 5; gbc2.insets.top = 5; movePanel.add(new JLabel("Move"), gbc2); gbc2.gridy++; gbc2.insets.bottom = 10; movePanel.add(moveDownButton, gbc2); gbc.gridx++; gbc.gridy = 0; gbc.weighty = 1.0; gbc.weightx = 0; gbc.insets.left = 5; gbc.anchor = GridBagConstraints.CENTER; gbc.gridheight = GridBagConstraints.REMAINDER; gbc.fill = GridBagConstraints.NONE; panel.add(movePanel, gbc); addContent(panel); } private void setTableProperties() { table.setTableHeader(null); table.setColumnSelectionAllowed(false); table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN); table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.setIntercellSpacing(new Dimension(0,0)); table.setShowGrid(false); table.setRowHeight(28); table.doLayout(); TableColumnModel tcm = table.getColumnModel(); tcm.getColumn(0).setPreferredWidth(30); TableColumn col = tcm.getColumn(1); col.setPreferredWidth(40); col.setCellRenderer(iconRenderer); col = tcm.getColumn(2); col.setPreferredWidth(251); col.setCellRenderer(nameRenderer); } private void setInitialValues() { Collections.sort(selections, new ButtonComparator()); } public void restoreDefaults() { ToolBarWrapper _toolBar = ToolBarProperties.getDefaultToolBar(toolBarName); toolBar = (ToolBarWrapper)_toolBar.clone(); selections = toolBar.getButtonsVector(); Collections.sort(selections, new ButtonComparator()); toolButtonModel.fireTableRowsUpdated(0, selections.size()-1); } public void save() { int size = selections.size(); Vector buttons = new Vector(selections.size()); // update the buttons for (int i = 0; i < size; i++) { ToolBarButton tb = (ToolBarButton)selections.elementAt(i); if (tb.isVisible()) tb.setOrder(i); else tb.setOrder(1000); buttons.add(tb); } toolBar.setButtonsVector(buttons); ToolBarProperties.resetToolBar(toolBarName, toolBar); } public void addSeparator(ActionEvent e) { int selection = table.getSelectedRow(); if (selection == -1) { return; } ToolBarButton tb = new ToolBarButton(ToolBarButton.SEPARATOR_ID); tb.setOrder(selection); tb.setVisible(true); selections.insertElementAt(tb, selection); toolButtonModel.fireTableRowsInserted(selection == 0 ? 0 : selection - 1, selection == 0 ? 1 : selection); } public void removeSeparator(ActionEvent e) { int selection = table.getSelectedRow(); if (selection == -1) { return; } ToolBarButton remove = (ToolBarButton)selections.elementAt(selection); if (!remove.isSeparator()) { return; } selections.removeElementAt(selection); toolButtonModel.fireTableRowsDeleted(selection, selection); } public void moveUp(ActionEvent e) { int selection = table.getSelectedRow(); if (selection <= 0) { return; } int newPostn = selection - 1; ToolBarButton move = (ToolBarButton)selections.elementAt(selection); selections.removeElementAt(selection); selections.add(newPostn, move); table.setRowSelectionInterval(newPostn, newPostn); toolButtonModel.fireTableRowsUpdated(newPostn, selection); } public void moveDown(ActionEvent e) { int selection = table.getSelectedRow(); if (selection == -1 || selection == selections.size() - 1) { return; } int newPostn = selection + 1; ToolBarButton move = (ToolBarButton)selections.elementAt(selection); selections.removeElementAt(selection); selections.add(newPostn, move); table.setRowSelectionInterval(newPostn, newPostn); toolButtonModel.fireTableRowsUpdated(selection, newPostn); } private class ToolBarButtonModel extends AbstractTableModel { public ToolBarButtonModel() {} public int getColumnCount() { return 3; } public int getRowCount() { return selections.size(); } public Object getValueAt(int row, int col) { ToolBarButton tbb = (ToolBarButton)selections.elementAt(row); switch(col) { case 0: return new Boolean(tbb.isVisible()); case 1: return tbb.getIcon(); case 2: return tbb.getName(); default: return null; } } public void setValueAt(Object value, int row, int col) { ToolBarButton tbb = (ToolBarButton)selections.elementAt(row); if (col == 0) tbb.setVisible(((Boolean)value).booleanValue()); fireTableRowsUpdated(row, row); } public boolean isCellEditable(int row, int col) { if (col == 0) return true; else return false; } public Class getColumnClass(int col) { if (col == 0) return Boolean.class; else return String.class; } public void addNewRow() { } } // CreateTableModel public class NameCellRenderer extends JLabel implements TableCellRenderer { public NameCellRenderer() { //setFont(panelFont); setOpaque(true); } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { setBackground(isSelected ? table.getSelectionBackground() : table.getBackground()); setForeground(isSelected ? table.getSelectionForeground() : table.getForeground()); setText(value.toString()); setBorder(null); return this;<|fim▁hole|> public class IconCellRenderer extends JLabel implements TableCellRenderer { public IconCellRenderer() { setOpaque(true); } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { setBackground(isSelected ? table.getSelectionBackground() : table.getBackground()); setForeground(isSelected ? table.getSelectionForeground() : table.getForeground()); setHorizontalAlignment(JLabel.CENTER); setIcon((ImageIcon)value); return this; } } // class IconCellRenderer }<|fim▁end|>
} } // class NameCellRenderer
<|file_name|>rc_buffer_arc.rs<|end_file_name|><|fim▁begin|>#![warn(clippy::rc_buffer)] use std::ffi::OsString; use std::path::PathBuf;<|fim▁hole|>use std::sync::{Arc, Mutex}; struct S { // triggers lint bad1: Arc<String>, bad2: Arc<PathBuf>, bad3: Arc<Vec<u8>>, bad4: Arc<OsString>, // does not trigger lint good1: Arc<Mutex<String>>, } // triggers lint fn func_bad1(_: Arc<String>) {} fn func_bad2(_: Arc<PathBuf>) {} fn func_bad3(_: Arc<Vec<u8>>) {} fn func_bad4(_: Arc<OsString>) {} // does not trigger lint fn func_good1(_: Arc<Mutex<String>>) {} fn main() {}<|fim▁end|>
<|file_name|>test_routing.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals from nose.tools import raises, eq_, ok_ from werkzeug.test import Client from werkzeug.wrappers import BaseResponse from clastic import Application, render_basic from clastic.application import BaseApplication from clastic.route import BaseRoute, Route from clastic.route import (InvalidEndpoint, InvalidPattern, InvalidMethod) from clastic.route import S_STRICT, S_REWRITE, S_REDIRECT from clastic.errors import NotFound, ErrorHandler MODES = (S_STRICT, S_REWRITE, S_REDIRECT) NO_OP = lambda: BaseResponse() def test_new_base_route(): # note default slashing behavior rp = BaseRoute('/a/b/<t:int>/thing/<das+int>') d = rp.match_path('/a/b/1/thing/1/2/3/4') yield eq_, d, {u't': 1, u'das': [1, 2, 3, 4]} d = rp.match_path('/a/b/1/thing/hi/') yield eq_, d, None d = rp.match_path('/a/b/1/thing/') yield eq_, d, None rp = BaseRoute('/a/b/<t:int>/thing/<das*int>', methods=['GET']) d = rp.match_path('/a/b/1/thing') yield eq_, d, {u't': 1, u'das': []} def test_base_route_executes(): br = BaseRoute('/', lambda request: request['stephen']) res = br.execute({'stephen': 'laporte'}) yield eq_, res, 'laporte' @raises(InvalidEndpoint) def test_base_route_raises_on_no_ep(): BaseRoute('/a/b/<t:int>/thing/<das+int>').execute({}) def test_base_application_basics(): br = BaseRoute('/', lambda request: BaseResponse('lolporte')) ba = BaseApplication([br]) client = Client(ba, BaseResponse) res = client.get('/') yield eq_, res.data, 'lolporte' def test_nonbreaking_exc(): app = Application([('/', lambda: NotFound(is_breaking=False)), ('/', lambda: 'so hot in here', render_basic)]) client = Client(app, BaseResponse) resp = client.get('/') yield eq_, resp.status_code, 200 yield eq_, resp.data, 'so hot in here' def api(api_path): return 'api: %s' % '/'.join(api_path) def two_segments(one, two): return 'two_segments: %s, %s' % (one, two) def three_segments(one, two, three): return 'three_segments: %s, %s, %s' % (one, two, three) def test_create_route_order_list(): "tests route order when routes are added as a list" routes = [('/api/<api_path+>', api, render_basic), ('/<one>/<two>', two_segments, render_basic), ('/<one>/<two>/<three>', three_segments, render_basic)] app = BaseApplication(routes) client = Client(app, BaseResponse) yield eq_, client.get('/api/a').data, 'api: a'<|fim▁hole|> for i, rt in enumerate(app.routes): yield eq_, rt.pattern, routes[i][0] return def test_create_route_order_incr(): "tests route order when routes are added incrementally" routes = [('/api/<api_path+>', api, render_basic), ('/<one>/<two>', two_segments, render_basic), ('/<one>/<two>/<three>', three_segments, render_basic)] app = BaseApplication() client = Client(app, BaseResponse) for r in routes: app.add(r) yield eq_, client.get('/api/a/b').data, 'api: a/b' yield eq_, app.routes[-1].pattern, r[0] return """ New routing testing strategy notes ================================== * Successful endpoint * Failing endpoint (i.e., raise a non-HTTPException exception) * Raising endpoint (50x, 40x (breaking/nonbreaking)) * GET/POST/PUT/DELETE/OPTIONS/HEAD, etc. """ no_arg_routes = ['/', '/alpha', '/alpha/', '/beta', '/gamma/', '/delta/epsilon', '/zeta/eta/'] arg_routes = ['/<theta>', '/iota/<kappa>/<lambda>/mu/', '/<nu:int>/<xi:float>/<omicron:unicode>/<pi:str>/', '/<rho+>/', '/<sigma*>/', '/<tau?>/', '/<upsilon:>/'] broken_routes = ['alf', '/bet//', '/<cat->/', '/<very*doge>/'] def test_ok_routes(): ok_routes = no_arg_routes + arg_routes for cur_mode in MODES: for cur_patt in ok_routes: try: cur_rt = Route(cur_patt, NO_OP, slash_mode=cur_mode) except: yield ok_, False, cur_patt else: yield ok_, cur_rt def test_broken_routes(): for cur_mode in MODES: for cur_patt in broken_routes: try: cur_rt = Route(cur_patt, NO_OP, slash_mode=cur_mode) except InvalidPattern: yield ok_, True else: yield ok_, False, cur_rt def test_known_method(): rt = Route('/', NO_OP, methods=['GET']) yield ok_, rt yield ok_, 'HEAD' in rt.methods @raises(InvalidMethod) def test_unknown_method(): Route('/', NO_OP, methods=['lol']) def test_debug_raises(): app_nodebug = Application([('/', lambda: 1/0)], debug=False) client = Client(app_nodebug, BaseResponse) yield eq_, client.get('/').status_code, 500 err_handler = ErrorHandler(reraise_uncaught=True) app_debug = Application([('/', lambda: 1/0)], error_handler=err_handler) client = Client(app_debug, BaseResponse) try: resp = client.get('/') except ZeroDivisionError: yield ok_, True else: yield ok_, False, ('%r did not raise ZeroDivisionError (got %r)' % (app_debug, resp)) def test_slashing_behaviors(): routes = [('/', NO_OP), ('/goof/spoof/', NO_OP)] app_strict = Application(routes, slash_mode=S_STRICT) app_redirect = Application(routes, slash_mode=S_REDIRECT) app_rewrite = Application(routes, slash_mode=S_REWRITE) cl_strict = Client(app_strict, BaseResponse) cl_redirect = Client(app_redirect, BaseResponse) cl_rewrite = Client(app_rewrite, BaseResponse) yield eq_, cl_strict.get('/').status_code, 200 yield eq_, cl_rewrite.get('/').status_code, 200 yield eq_, cl_redirect.get('/').status_code, 200 yield eq_, cl_strict.get('/goof//spoof//').status_code, 404 yield eq_, cl_rewrite.get('/goof//spoof//').status_code, 200 yield eq_, cl_redirect.get('/goof//spoof//').status_code, 302 yield eq_, cl_redirect.get('/goof//spoof//', follow_redirects=True).status_code, 200 yield eq_, cl_strict.get('/dne/dne//').status_code, 404 yield eq_, cl_rewrite.get('/dne/dne//').status_code, 404 yield eq_, cl_redirect.get('/dne/dne//').status_code, 404<|fim▁end|>
yield eq_, client.get('/api/a/b').data, 'api: a/b'
<|file_name|>test_docker.py<|end_file_name|><|fim▁begin|>import unittest import json import time from celery import current_app from django.conf import settings from django.utils import timezone from ep.models import DPMeasurements, DeviceParameter from ep.tasks import send_msg from django.test import TestCase, modify_settings, override_settings from ep.tests.static_factories import SiteFactory from ep_secure_importer.controllers.secure_client import secure_site_name __author__ = 'schien' @override_settings(IODICUS_MESSAGING_HOST='messaging.iodicus.net') class TaskTest(TestCase): def test_messaging(self): print(settings.IODICUS_MESSAGING_HOST) # print(settings.BROKER_URL) self.assertTrue(send_msg.delay(json.dumps({'test': 1}))) class LocalTaskTest(TestCase): def test_messaging(self): print(settings.IODICUS_MESSAGING_HOST) print(settings.BROKER_URL) self.assertTrue(send_msg.delay(json.dumps({'test': 1}))) # @override_settings(INFLUXDB_HOST='52.49.171.8') class InfluxDBTest(TestCase): @classmethod def setUpTestData(cls): SiteFactory.create(name=secure_site_name) <|fim▁hole|> # @unittest.skip def test_simple_add(self): print(settings.INFLUXDB_HOST) m = DPMeasurements(device_parameter=DeviceParameter.objects.first()) before = len(list(m.all())) print(before) m.add(time=timezone.now(), value=255) m.add(time=timezone.now(), value=0) m.add(time=timezone.now(), value=20.5) time.sleep(5) after = len(list(m.all())) print(after) self.assertTrue(before + 3 == after) if __name__ == '__main__': unittest.main()<|fim▁end|>
<|file_name|>jquery.fastconfirm.js<|end_file_name|><|fim▁begin|>/* * jQuery Fast Confirm * version: 2.1.1 (2011-03-23) * @requires jQuery v1.3.2 or later * * Examples and documentation at: http://blog.pierrejeanparra.com/jquery-plugins/fast-confirm/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ ;(function ($) { var methods = { init: function (options) { var params; if (!this.length) { return this; } $.fastConfirm = { defaults: { position: 'bottom', offset: {top: 0, left: 0}, zIndex: 10000, eventToBind: false, questionText: "Are you sure?", proceedText: "Yes", cancelText: "No", targetElement: null, unique: false, fastConfirmClass: "fast_confirm", onProceed: function ($trigger) { $trigger.fastConfirm('close'); return true; }, onCancel: function ($trigger) { $trigger.fastConfirm('close'); return false; } } }; params = $.extend($.fastConfirm.defaults, options || {}); return this.each(function () { var trigger = this, $trigger = $(this), $confirmYes = $('<button class="' + params.fastConfirmClass + '_proceed">' + params.proceedText + '</button>'), $confirmNo = $('<button class="' + params.fastConfirmClass + '_cancel">' + params.cancelText + '</button>'), $confirmBox = $('<div class="' + params.fastConfirmClass + '"><div class="' + params.fastConfirmClass + '_arrow_border"></div><div class="' + params.fastConfirmClass + '_arrow"></div>' + params.questionText + '<br/></div>'), $arrow = $('div.' + params.fastConfirmClass + '_arrow', $confirmBox), $arrowBorder = $('div.' + params.fastConfirmClass + '_arrow_border', $confirmBox), confirmBoxArrowClass, confirmBoxArrowBorderClass, $target = params.targetElement ? $(params.targetElement, $trigger) : $trigger, offset = $target.offset(), topOffset, leftOffset, displayBox = function () { if (!$trigger.data('fast_confirm.box')) { $trigger.data('fast_confirm.params.fastConfirmClass', params.fastConfirmClass); // Close all other confirm boxes if necessary if (params.unique) { $('.' + params.fastConfirmClass + '_trigger').fastConfirm('close'); } // Register actions $confirmYes.bind('click.fast_confirm', function () { // In case the DOM has been refreshed in the meantime or something... $trigger.data('fast_confirm.box', $confirmBox).addClass(params.fastConfirmClass + '_trigger'); params.onProceed($trigger); // If the user wants us to handle events if (params.eventToBind) { trigger[params.eventToBind](); } }); $confirmNo.bind('click.fast_confirm', function () { // In case the DOM has been refreshed in the meantime or something... $trigger.data('fast_confirm.box', $confirmBox).addClass(params.fastConfirmClass + '_trigger'); params.onCancel($trigger); }); $confirmBox // Makes the confirm box focusable .attr("tabIndex", -1) // Bind Escape key to close the confirm box .bind('keydown.fast_confirm', function (event) { if (event.keyCode && event.keyCode === 27) { $trigger.fastConfirm('close'); } }); // Append the confirm box to the body. It will not be visible as it is off-screen by default. Positionning will be done at the last time $confirmBox.append($confirmYes).append($confirmNo); $('body').append($confirmBox); // Calculate absolute positionning depending on the trigger-relative position switch (params.position) { case 'top': confirmBoxArrowClass = params.fastConfirmClass + '_bottom'; confirmBoxArrowBorderClass = params.fastConfirmClass + '_bottom'; $arrow.addClass(confirmBoxArrowClass).css('left', $confirmBox.outerWidth() / 2 - $arrow.outerWidth() / 2); $arrowBorder.addClass(confirmBoxArrowBorderClass).css('left', $confirmBox.outerWidth() / 2 - $arrowBorder.outerWidth() / 2); topOffset = offset.top - $confirmBox.outerHeight() - $arrowBorder.outerHeight() + params.offset.top; leftOffset = offset.left - $confirmBox.outerWidth() / 2 + $target.outerWidth() / 2 + params.offset.left; break; case 'right': confirmBoxArrowClass = params.fastConfirmClass + '_left'; confirmBoxArrowBorderClass = params.fastConfirmClass + '_left'; $arrow.addClass(confirmBoxArrowClass).css('top', $confirmBox.outerHeight() / 2 - $arrow.outerHeight() / 2); $arrowBorder.addClass(confirmBoxArrowBorderClass).css('top', $confirmBox.outerHeight() / 2 - $arrowBorder.outerHeight() / 2); topOffset = offset.top + $target.outerHeight() / 2 - $confirmBox.outerHeight() / 2 + params.offset.top; leftOffset = offset.left + $target.outerWidth() + $arrowBorder.outerWidth() + params.offset.left; break; case 'bottom': confirmBoxArrowClass = params.fastConfirmClass + '_top';<|fim▁hole|> topOffset = offset.top + $target.outerHeight() + $arrowBorder.outerHeight() + params.offset.top; leftOffset = offset.left - $confirmBox.outerWidth() / 2 + $target.outerWidth() / 2 + params.offset.left; break; case 'left': confirmBoxArrowClass = params.fastConfirmClass + '_right'; confirmBoxArrowBorderClass = params.fastConfirmClass + '_right'; $arrow.addClass(confirmBoxArrowClass).css('top', $confirmBox.outerHeight() / 2 - $arrow.outerHeight() / 2); $arrowBorder.addClass(confirmBoxArrowBorderClass).css('top', $confirmBox.outerHeight() / 2 - $arrowBorder.outerHeight() / 2); topOffset = offset.top + $target.outerHeight() / 2 - $confirmBox.outerHeight() / 2 + params.offset.top; leftOffset = offset.left - $confirmBox.outerWidth() - $arrowBorder.outerWidth() + params.offset.left; break; } // Make the confirm box appear right where it belongs $confirmBox.css({ top: topOffset, left: leftOffset, zIndex: params.zIndex }).focus(); // Link trigger and confirm box $trigger.data('fast_confirm.box', $confirmBox).addClass(params.fastConfirmClass + '_trigger'); } }; // If the user wants to give us complete control over event handling if (params.eventToBind) { $trigger.bind(params.eventToBind + '.fast_confirm', function () { displayBox(); return false; }); } else { // Let event handling to the user, just display the confirm box displayBox(); } }); }, // Close the confirm box close: function () { return this.each(function () { var $this = $(this); $this.data('fast_confirm.box').remove(); $this.removeData('fast_confirm.box').removeClass($this.data('fast_confirm.params.fastConfirmClass') + '_trigger'); }); } }; $.fn.fastConfirm = function (method) { if (!this.length) { return this; } // Method calling logic if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on jQuery.fastConfirm'); } }; })(jQuery);<|fim▁end|>
confirmBoxArrowBorderClass = params.fastConfirmClass + '_top'; $arrow.addClass(confirmBoxArrowClass).css('left', $confirmBox.outerWidth() / 2 - $arrow.outerWidth() / 2); $arrowBorder.addClass(confirmBoxArrowBorderClass).css('left', $confirmBox.outerWidth() / 2 - $arrowBorder.outerWidth() / 2);
<|file_name|>0002_post_user.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-01-05 03:11 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('posts', '0001_initial'), ] operations = [ migrations.AddField( model_name='post',<|fim▁hole|> field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), ]<|fim▁end|>
name='user',
<|file_name|>traversal.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Traversing the DOM tree; the bloom filter. use context::{ElementCascadeInputs, StyleContext, SharedStyleContext}; use data::{ElementData, ElementStyles}; use dom::{NodeInfo, OpaqueNode, TElement, TNode}; use invalidation::element::restyle_hints::{RECASCADE_SELF, RECASCADE_DESCENDANTS, RestyleHint}; use matching::{ChildCascadeRequirement, MatchMethods}; use sharing::StyleSharingTarget; use smallvec::SmallVec; use style_resolver::StyleResolverForElement; #[cfg(feature = "servo")] use style_traits::ToCss; use stylist::RuleInclusion; use traversal_flags::{TraversalFlags, self}; #[cfg(feature = "servo")] use values::Either; #[cfg(feature = "servo")] use values::generics::image::Image; /// A per-traversal-level chunk of data. This is sent down by the traversal, and /// currently only holds the dom depth for the bloom filter. /// /// NB: Keep this as small as possible, please! #[derive(Clone, Debug)] pub struct PerLevelTraversalData { /// The current dom depth. /// /// This is kept with cooperation from the traversal code and the bloom /// filter. pub current_dom_depth: usize, } /// We use this structure, rather than just returning a boolean from pre_traverse, /// to enfore that callers process root invalidations before starting the traversal. pub struct PreTraverseToken(bool); impl PreTraverseToken { /// Whether we should traverse children. pub fn should_traverse(&self) -> bool { self.0 } } /// The kind of traversals we could perform. #[derive(Debug, Copy, Clone)] pub enum TraversalDriver { /// A potentially parallel traversal. Parallel, /// A sequential traversal. Sequential, } impl TraversalDriver { /// Returns whether this represents a parallel traversal or not. #[inline] pub fn is_parallel(&self) -> bool { matches!(*self, TraversalDriver::Parallel) } } #[cfg(feature = "servo")] fn is_servo_nonincremental_layout() -> bool { use servo_config::opts; opts::get().nonincremental_layout } #[cfg(not(feature = "servo"))] fn is_servo_nonincremental_layout() -> bool { false } /// A DOM Traversal trait, that is used to generically implement styling for /// Gecko and Servo. pub trait DomTraversal<E: TElement> : Sync { /// Process `node` on the way down, before its children have been processed. /// /// The callback is invoked for each child node that should be processed by /// the traversal. fn process_preorder<F>(&self, data: &PerLevelTraversalData, context: &mut StyleContext<E>, node: E::ConcreteNode, note_child: F) where F: FnMut(E::ConcreteNode); /// Process `node` on the way up, after its children have been processed. /// /// This is only executed if `needs_postorder_traversal` returns true. fn process_postorder(&self, contect: &mut StyleContext<E>, node: E::ConcreteNode); /// Boolean that specifies whether a bottom up traversal should be /// performed. /// /// If it's false, then process_postorder has no effect at all. fn needs_postorder_traversal() -> bool { true } /// Handles the postorder step of the traversal, if it exists, by bubbling /// up the parent chain. /// /// If we are the last child that finished processing, recursively process /// our parent. Else, stop. Also, stop at the root. /// /// Thus, if we start with all the leaves of a tree, we end up traversing /// the whole tree bottom-up because each parent will be processed exactly /// once (by the last child that finishes processing). /// /// The only communication between siblings is that they both /// fetch-and-subtract the parent's children count. This makes it safe to /// call durign the parallel traversal. fn handle_postorder_traversal( &self, context: &mut StyleContext<E>, root: OpaqueNode, mut node: E::ConcreteNode, children_to_process: isize ) { // If the postorder step is a no-op, don't bother. if !Self::needs_postorder_traversal() { return; } if children_to_process == 0 { // We are a leaf. Walk up the chain. loop { self.process_postorder(context, node); if node.opaque() == root { break; } let parent = node.traversal_parent().unwrap(); let remaining = parent.did_process_child(); if remaining != 0 { // The parent has other unprocessed descendants. We only // perform postorder processing after the last descendant // has been processed. break } node = parent.as_node(); } } else { // Otherwise record the number of children to process when the time // comes. node.as_element().unwrap() .store_children_to_process(children_to_process); } } /// Style invalidations happen when traversing from a parent to its children. /// However, this mechanism can't handle style invalidations on the root. As /// such, we have a pre-traversal step to handle that part and determine whether /// a full traversal is needed. fn pre_traverse( root: E, shared_context: &SharedStyleContext, traversal_flags: TraversalFlags ) -> PreTraverseToken { // If this is an unstyled-only traversal, the caller has already verified // that there's something to traverse, and we don't need to do any // invalidation since we're not doing any restyling. if traversal_flags.contains(traversal_flags::UnstyledOnly) { return PreTraverseToken(true) } let flags = shared_context.traversal_flags; let mut data = root.mutate_data(); let mut data = data.as_mut().map(|d| &mut **d); if let Some(ref mut data) = data { // Invalidate our style, and the one of our siblings and descendants // as needed. data.invalidate_style_if_needed(root, shared_context); }; let parent = root.traversal_parent(); let parent_data = parent.as_ref().and_then(|p| p.borrow_data()); let should_traverse = Self::element_needs_traversal( root, flags, data.map(|d| &*d), parent_data.as_ref().map(|d| &**d) ); PreTraverseToken(should_traverse) } /// Returns true if traversal should visit a text node. The style system /// never processes text nodes, but Servo overrides this to visit them for /// flow construction when necessary. fn text_node_needs_traversal(node: E::ConcreteNode, _parent_data: &ElementData) -> bool { debug_assert!(node.is_text_node()); false } /// Returns true if traversal is needed for the given element and subtree. /// /// The caller passes |parent_data|, which is only null if there is no /// parent. fn element_needs_traversal( el: E, traversal_flags: TraversalFlags, data: Option<&ElementData>, parent_data: Option<&ElementData>, ) -> bool { debug!("element_needs_traversal({:?}, {:?}, {:?}, {:?})", el, traversal_flags, data, parent_data); if traversal_flags.contains(traversal_flags::UnstyledOnly) { return data.map_or(true, |d| !d.has_styles()) || el.has_dirty_descendants(); } // In case of animation-only traversal we need to traverse the element // if the element has animation only dirty descendants bit, // animation-only restyle hint or recascade.<|fim▁hole|> } // Non-incremental layout visits every node. if is_servo_nonincremental_layout() { return true; } // Unwrap the data. let data = match data { Some(d) if d.has_styles() => d, _ => return true, }; // If the element is native-anonymous and an ancestor frame will be // reconstructed, the child and all its descendants will be destroyed. // In that case, we wouldn't need to traverse the subtree... // // Except if there could be transitions of pseudo-elements, in which // case we still need to process them, unfortunately. // // We need to conservatively continue the traversal to style the // pseudo-element in order to properly process potentially-new // transitions that we won't see otherwise. // // But it may be that we no longer match, so detect that case and act // appropriately here. if el.is_native_anonymous() { if let Some(parent_data) = parent_data { let going_to_reframe = parent_data.restyle.reconstructed_self_or_ancestor(); let mut is_before_or_after_pseudo = false; if let Some(pseudo) = el.implemented_pseudo_element() { if pseudo.is_before_or_after() { is_before_or_after_pseudo = true; let still_match = parent_data.styles.pseudos.get(&pseudo).is_some(); if !still_match { debug_assert!(going_to_reframe, "We're removing a pseudo, so we \ should reframe!"); return false; } } } if going_to_reframe && !is_before_or_after_pseudo { debug!("Element {:?} is in doomed NAC subtree, \ culling traversal", el); return false; } } } // If the dirty descendants bit is set, we need to traverse no matter // what. Skip examining the ElementData. if el.has_dirty_descendants() { return true; } // If we have a restyle hint or need to recascade, we need to visit the // element. // // Note that this is different than checking has_current_styles_for_traversal(), // since that can return true even if we have a restyle hint indicating // that the element's descendants (but not necessarily the element) need // restyling. if !data.restyle.hint.is_empty() { return true; } // Servo uses the post-order traversal for flow construction, so we need // to traverse any element with damage so that we can perform fixup / // reconstruction on our way back up the tree. // // In aggressively forgetful traversals (where we seek out and clear damage // in addition to not computing it) we also need to traverse nodes with // explicit damage and no other restyle data, so that this damage can be cleared. if (cfg!(feature = "servo") || traversal_flags.contains(traversal_flags::AggressivelyForgetful)) && !data.restyle.damage.is_empty() { return true; } trace!("{:?} doesn't need traversal", el); false } /// Returns true if we want to cull this subtree from the travesal. fn should_cull_subtree( &self, context: &mut StyleContext<E>, parent: E, parent_data: &ElementData, ) -> bool { debug_assert!(cfg!(feature = "gecko") || parent.has_current_styles_for_traversal(parent_data, context.shared.traversal_flags)); // If the parent computed display:none, we don't style the subtree. if parent_data.styles.is_display_none() { debug!("Parent {:?} is display:none, culling traversal", parent); return true; } // Gecko-only XBL handling. // // If we're computing initial styles and the parent has a Gecko XBL // binding, that binding may inject anonymous children and remap the // explicit children to an insertion point (or hide them entirely). It // may also specify a scoped stylesheet, which changes the rules that // apply within the subtree. These two effects can invalidate the result // of property inheritance and selector matching (respectively) within // the subtree. // // To avoid wasting work, we defer initial styling of XBL subtrees until // frame construction, which does an explicit traversal of the unstyled // children after shuffling the subtree. That explicit traversal may in // turn find other bound elements, which get handled in the same way. // // We explicitly avoid handling restyles here (explicitly removing or // changing bindings), since that adds complexity and is rarer. If it // happens, we may just end up doing wasted work, since Gecko // recursively drops Servo ElementData when the XBL insertion parent of // an Element is changed. if cfg!(feature = "gecko") && context.thread_local.is_initial_style() && parent_data.styles.primary().has_moz_binding() { debug!("Parent {:?} has XBL binding, deferring traversal", parent); return true; } return false; } /// Return the shared style context common to all worker threads. fn shared_context(&self) -> &SharedStyleContext; /// Whether we're performing a parallel traversal. /// /// NB: We do this check on runtime. We could guarantee correctness in this /// regard via the type system via a `TraversalDriver` trait for this trait, /// that could be one of two concrete types. It's not clear whether the /// potential code size impact of that is worth it. fn is_parallel(&self) -> bool; } /// Manually resolve style by sequentially walking up the parent chain to the /// first styled Element, ignoring pending restyles. The resolved style is made /// available via a callback, and can be dropped by the time this function /// returns in the display:none subtree case. pub fn resolve_style<E>( context: &mut StyleContext<E>, element: E, rule_inclusion: RuleInclusion, ignore_existing_style: bool, ) -> ElementStyles where E: TElement, { use style_resolver::StyleResolverForElement; debug_assert!(rule_inclusion == RuleInclusion::DefaultOnly || ignore_existing_style || element.borrow_data().map_or(true, |d| !d.has_styles()), "Why are we here?"); let mut ancestors_requiring_style_resolution = SmallVec::<[E; 16]>::new(); // Clear the bloom filter, just in case the caller is reusing TLS. context.thread_local.bloom_filter.clear(); let mut style = None; let mut ancestor = element.traversal_parent(); while let Some(current) = ancestor { if rule_inclusion == RuleInclusion::All && !ignore_existing_style { if let Some(data) = current.borrow_data() { if let Some(ancestor_style) = data.styles.get_primary() { style = Some(ancestor_style.clone()); break; } } } ancestors_requiring_style_resolution.push(current); ancestor = current.traversal_parent(); } if let Some(ancestor) = ancestor { context.thread_local.bloom_filter.rebuild(ancestor); context.thread_local.bloom_filter.push(ancestor); } let mut layout_parent_style = style.clone(); while let Some(style) = layout_parent_style.take() { if !style.is_display_contents() { layout_parent_style = Some(style); break; } ancestor = ancestor.unwrap().traversal_parent(); layout_parent_style = ancestor.map(|a| { a.borrow_data().unwrap().styles.primary().clone() }); } for ancestor in ancestors_requiring_style_resolution.iter().rev() { context.thread_local.bloom_filter.assert_complete(*ancestor); let primary_style = StyleResolverForElement::new(*ancestor, context, rule_inclusion) .resolve_primary_style( style.as_ref().map(|s| &**s), layout_parent_style.as_ref().map(|s| &**s) ); let is_display_contents = primary_style.style.is_display_contents(); style = Some(primary_style.style); if !is_display_contents { layout_parent_style = style.clone(); } context.thread_local.bloom_filter.push(*ancestor); } context.thread_local.bloom_filter.assert_complete(element); StyleResolverForElement::new(element, context, rule_inclusion) .resolve_style( style.as_ref().map(|s| &**s), layout_parent_style.as_ref().map(|s| &**s) ) } /// Calculates the style for a single node. #[inline] #[allow(unsafe_code)] pub fn recalc_style_at<E, D, F>( traversal: &D, traversal_data: &PerLevelTraversalData, context: &mut StyleContext<E>, element: E, data: &mut ElementData, note_child: F, ) where E: TElement, D: DomTraversal<E>, F: FnMut(E::ConcreteNode), { use traversal_flags::*; let flags = context.shared.traversal_flags; context.thread_local.begin_element(element, data); context.thread_local.statistics.elements_traversed += 1; debug_assert!(flags.intersects(AnimationOnly | UnstyledOnly) || !element.has_snapshot() || element.handled_snapshot(), "Should've handled snapshots here already"); let compute_self = !element.has_current_styles_for_traversal(data, flags); let mut hint = RestyleHint::empty(); debug!("recalc_style_at: {:?} (compute_self={:?}, \ dirty_descendants={:?}, data={:?})", element, compute_self, element.has_dirty_descendants(), data); // Compute style for this element if necessary. if compute_self { match compute_style(traversal_data, context, element, data) { ChildCascadeRequirement::MustCascadeChildren => { hint |= RECASCADE_SELF; } ChildCascadeRequirement::MustCascadeDescendants => { hint |= RECASCADE_SELF | RECASCADE_DESCENDANTS; } ChildCascadeRequirement::CanSkipCascade => {} }; // We must always cascade native anonymous subtrees, since they inherit // styles from their first non-NAC ancestor. if element.is_native_anonymous() { hint |= RECASCADE_SELF; } // If we're restyling this element to display:none, throw away all style // data in the subtree, notify the caller to early-return. if data.styles.is_display_none() { debug!("{:?} style is display:none - clearing data from descendants.", element); clear_descendant_data(element) } // Inform any paint worklets of changed style, to speculatively // evaluate the worklet code. In the case that the size hasn't changed, // this will result in increased concurrency between script and layout. notify_paint_worklet(context, data); } else { debug_assert!(data.has_styles()); data.restyle.set_traversed_without_styling(); } // Now that matching and cascading is done, clear the bits corresponding to // those operations and compute the propagated restyle hint (unless we're // not processing invalidations, in which case don't need to propagate it // and must avoid clearing it). let mut propagated_hint = if flags.contains(UnstyledOnly) { RestyleHint::empty() } else { debug_assert!(flags.for_animation_only() || !data.restyle.hint.has_animation_hint(), "animation restyle hint should be handled during \ animation-only restyles"); data.restyle.hint.propagate(&flags) }; // FIXME(bholley): Need to handle explicitly-inherited reset properties // somewhere. propagated_hint.insert(hint); trace!("propagated_hint={:?} \ is_display_none={:?}, implementing_pseudo={:?}", propagated_hint, data.styles.is_display_none(), element.implemented_pseudo_element()); debug_assert!(element.has_current_styles_for_traversal(data, flags), "Should have computed style or haven't yet valid computed \ style in case of animation-only restyle"); let has_dirty_descendants_for_this_restyle = if flags.for_animation_only() { element.has_animation_only_dirty_descendants() } else { element.has_dirty_descendants() }; // Before examining each child individually, try to prove that our children // don't need style processing. They need processing if any of the following // conditions hold: // * We have the dirty descendants bit. // * We're propagating a hint. // * This is the initial style. // * We generated a reconstruct hint on self (which could mean that we // switched from display:none to something else, which means the children // need initial styling). // * This is a servo non-incremental traversal. // // Additionally, there are a few scenarios where we avoid traversing the // subtree even if descendant styles are out of date. These cases are // enumerated in should_cull_subtree(). let mut traverse_children = has_dirty_descendants_for_this_restyle || !propagated_hint.is_empty() || context.thread_local.is_initial_style() || data.restyle.reconstructed_self() || is_servo_nonincremental_layout(); traverse_children = traverse_children && !traversal.should_cull_subtree(context, element, &data); // Examine our children, and enqueue the appropriate ones for traversal. if traverse_children { note_children::<E, D, F>( context, element, data, propagated_hint, data.restyle.reconstructed_self_or_ancestor(), note_child ); } // If we are in a forgetful traversal, drop the existing restyle // data here, since we won't need to perform a post-traversal to pick up // any change hints. if flags.contains(Forgetful) { data.clear_restyle_flags_and_damage(); } // Optionally clear the descendants bit for the traversal type we're in. if flags.for_animation_only() { if flags.contains(ClearAnimationOnlyDirtyDescendants) { unsafe { element.unset_animation_only_dirty_descendants(); } } } else { // There are two cases when we want to clear the dity descendants bit here // after styling this element. The first case is when we were explicitly // asked to clear the bit by the caller. // // The second case is when this element is the root of a display:none // subtree, even if the style didn't change (since, if the style did change, // we'd have already cleared it above). // // This keeps the tree in a valid state without requiring the DOM to check // display:none on the parent when inserting new children (which can be // moderately expensive). Instead, DOM implementations can unconditionally // set the dirty descendants bit on any styled parent, and let the traversal // sort it out. if flags.contains(ClearDirtyDescendants) || data.styles.is_display_none() { unsafe { element.unset_dirty_descendants(); } } } context.thread_local.end_element(element); } fn compute_style<E>( traversal_data: &PerLevelTraversalData, context: &mut StyleContext<E>, element: E, data: &mut ElementData ) -> ChildCascadeRequirement where E: TElement, { use data::RestyleKind::*; use sharing::StyleSharingResult::*; context.thread_local.statistics.elements_styled += 1; let kind = data.restyle_kind(context.shared); debug!("compute_style: {:?} (kind={:?})", element, kind); if data.has_styles() { data.restyle.set_restyled(); } let mut important_rules_changed = false; let new_styles = match kind { MatchAndCascade => { debug_assert!(!context.shared.traversal_flags.for_animation_only(), "MatchAndCascade shouldn't be processed during \ animation-only traversal"); // Ensure the bloom filter is up to date. context.thread_local.bloom_filter .insert_parents_recovering(element, traversal_data.current_dom_depth); context.thread_local.bloom_filter.assert_complete(element); // This is only relevant for animations as of right now. important_rules_changed = true; let mut target = StyleSharingTarget::new(element); // Now that our bloom filter is set up, try the style sharing // cache. match target.share_style_if_possible(context) { StyleWasShared(index, styles) => { context.thread_local.statistics.styles_shared += 1; context.thread_local.style_sharing_candidate_cache.touch(index); styles } CannotShare => { context.thread_local.statistics.elements_matched += 1; // Perform the matching and cascading. let new_styles = StyleResolverForElement::new(element, context, RuleInclusion::All) .resolve_style_with_default_parents(); context.thread_local .style_sharing_candidate_cache .insert_if_possible( &element, new_styles.primary(), target.take_validation_data(), context.thread_local.bloom_filter.matching_depth(), ); new_styles } } } CascadeWithReplacements(flags) => { // Skipping full matching, load cascade inputs from previous values. let mut cascade_inputs = ElementCascadeInputs::new_from_element_data(data); important_rules_changed = element.replace_rules(flags, context, &mut cascade_inputs); StyleResolverForElement::new(element, context, RuleInclusion::All) .cascade_styles_with_default_parents(cascade_inputs) } CascadeOnly => { // Skipping full matching, load cascade inputs from previous values. let cascade_inputs = ElementCascadeInputs::new_from_element_data(data); StyleResolverForElement::new(element, context, RuleInclusion::All) .cascade_styles_with_default_parents(cascade_inputs) } }; element.finish_restyle( context, data, new_styles, important_rules_changed ) } #[cfg(feature = "servo")] fn notify_paint_worklet<E>(context: &StyleContext<E>, data: &ElementData) where E: TElement, { // We speculatively evaluate any paint worklets during styling. // This allows us to run paint worklets in parallel with style and layout. // Note that this is wasted effort if the size of the node has // changed, but in may cases it won't have. if let Some(ref values) = data.styles.primary { for image in &values.get_background().background_image.0 { let (name, arguments) = match *image { Either::Second(Image::PaintWorklet(ref worklet)) => (&worklet.name, &worklet.arguments), _ => continue, }; let painter = match context.shared.registered_speculative_painters.get(name) { Some(painter) => painter, None => continue, }; let properties = painter.properties().iter() .filter_map(|(name, id)| id.as_shorthand().err().map(|id| (name, id))) .map(|(name, id)| (name.clone(), values.computed_value_to_string(id))) .collect(); let arguments = arguments.iter() .map(|argument| argument.to_css_string()) .collect(); debug!("Notifying paint worklet {}.", painter.name()); painter.speculatively_draw_a_paint_image(properties, arguments); } } } #[cfg(feature = "gecko")] fn notify_paint_worklet<E>(_context: &StyleContext<E>, _data: &ElementData) where E: TElement, { // The CSS paint API is Servo-only at the moment } fn note_children<E, D, F>( context: &mut StyleContext<E>, element: E, data: &ElementData, propagated_hint: RestyleHint, reconstructed_ancestor: bool, mut note_child: F, ) where E: TElement, D: DomTraversal<E>, F: FnMut(E::ConcreteNode), { trace!("note_children: {:?}", element); let flags = context.shared.traversal_flags; let is_initial_style = context.thread_local.is_initial_style(); // Loop over all the traversal children. for child_node in element.as_node().traversal_children() { let child = match child_node.as_element() { Some(el) => el, None => { if is_servo_nonincremental_layout() || D::text_node_needs_traversal(child_node, data) { note_child(child_node); } continue; }, }; let mut child_data = child.mutate_data(); let mut child_data = child_data.as_mut().map(|d| &mut **d); trace!(" > {:?} -> {:?} + {:?}, pseudo: {:?}", child, child_data.as_ref().map(|d| d.restyle.hint), propagated_hint, child.implemented_pseudo_element()); if let Some(ref mut child_data) = child_data { // Propagate the parent restyle hint, that may make us restyle the whole // subtree. if reconstructed_ancestor { child_data.restyle.set_reconstructed_ancestor(); } child_data.restyle.hint.insert(propagated_hint); // Handle element snapshots and invalidation of descendants and siblings // as needed. // // NB: This will be a no-op if there's no snapshot. child_data.invalidate_style_if_needed(child, &context.shared); } if D::element_needs_traversal(child, flags, child_data.map(|d| &*d), Some(data)) { note_child(child_node); // Set the dirty descendants bit on the parent as needed, so that we // can find elements during the post-traversal. // // Note that these bits may be cleared again at the bottom of // recalc_style_at if requested by the caller. if !is_initial_style { if flags.for_animation_only() { unsafe { element.set_animation_only_dirty_descendants(); } } else { unsafe { element.set_dirty_descendants(); } } } } } } /// Clear style data for all the subtree under `el`. pub fn clear_descendant_data<E>(el: E) where E: TElement, { for kid in el.as_node().traversal_children() { if let Some(kid) = kid.as_element() { // We maintain an invariant that, if an element has data, all its // ancestors have data as well. // // By consequence, any element without data has no descendants with // data. if kid.get_data().is_some() { unsafe { kid.clear_data() }; clear_descendant_data(kid); } } } unsafe { el.unset_dirty_descendants(); el.unset_animation_only_dirty_descendants(); } }<|fim▁end|>
if traversal_flags.for_animation_only() { return data.map_or(false, |d| d.has_styles()) && (el.has_animation_only_dirty_descendants() || data.as_ref().unwrap().restyle.hint.has_animation_hint_or_recascade());
<|file_name|>morestack-address.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //<|fim▁hole|>// option. This file may not be copied, modified, or distributed // except according to those terms. mod rusti { #[nolink] #[abi = "rust-intrinsic"] extern "rust-intrinsic" { pub fn morestack_addr() -> *(); } } pub fn main() { unsafe { let addr = rusti::morestack_addr(); assert!(addr.is_not_null()); error!("%?", addr); } }<|fim▁end|>
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
<|file_name|>family_tree_controller.js<|end_file_name|><|fim▁begin|>module.exports = function(app) { app.controller('FamilyTreeController', ['$scope', 'leafletData', '$http', function($scope, leafletData, $http) { var mapQuestKey = 'qszwthBye44A571jhqvCn4AWhTsEILRT'; // required for cypher parser require('../../plugins/sigma.parsers.json.js'); //for loading neo4j data from database require('../../plugins/sigma.parsers.cypher.js'); // for styling the graph with labels, sizing, colors, etc. require('../../plugins/sigma.plugins.design.js'); // directed graph layout algorithm require('../../plugins/sigma.layout.dagre.js'); // for making arcs on the map // require('../../plugins/arc.js'); // sigma settings if needed var settings = { }; var s = new sigma({ container: 'graph-container', settings: settings }); // styling settings applied to graph visualization var treeStyles = { nodes: { label: { by: 'neo4j_data.name', format: function(value) { return 'Name: ' + value; } }, size: { by: 'neo4j_data.nodeSize', bins: 10, min: 1, max: 20 } } }; $scope.drawTree = function() { $http.post('/api/draw-tree', {username: $scope.currentUser}) .then(function(res) { var graph = sigma.neo4j.cypher_parse(res.data.results); s.graph.read(graph); var design = sigma.plugins.design(s); design.setStyles(treeStyles); design.apply(); var config = { rankdir: 'TB' }; var listener = sigma.layouts.dagre.configure(s, config); listener.bind('start stop interpolate', function(event) { console.log(event.type); }); sigma.layouts.dagre.start(s); s.refresh(); $scope.mapFamily(); }, function(err) { console.log(err); }); }; // end drawTree function $scope.clearGraph = function() { s.graph.clear(); }; // defaults for leaflet angular.extend($scope, { defaults: { scrollWheelZoom: true, doubleClickZoom: false, tap: false, tileLayer: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', maxZoom: 14 }, markers: { } }); $scope.newRelative = {}; //gets the current user's family tree. $scope.getTree = function() { $http.get('/' + $scope.currentUser.id) // ROUTE? .then(function(res) { $scope.family = res.data; }, function(err) { console.log(err); }); }; //pulls info from FORM and sends post request $scope.addRelative = function(relative) { //Create two arrays to pass that the backend expects. relative.parents = []; relative.children = []; if(relative.parent1) relative.parents.push(relative.parent1._id); if(relative.parent2) relative.parents.push(relative.parent2._id); if(relative.child) relative.children.push(relative.child._id); $http.post('/api/tree', relative) .then(function(res) { $scope.getUser(); $scope.clearGraph(); $scope.drawTree(); $scope.newRelative = {}; $scope.geoCodeResults = {}; }, function(err) { console.log(err); } ); }; $scope.updateRelative = function(relative) { $http.put('/api/tree', relative) .then(function(res) { relative.editing = false;<|fim▁hole|> $scope.getUser(); $scope.clearGraph(); $scope.drawTree(); $scope.geoCodeResults = {}; }, function(err) { console.log(err); }); }; //checks appropriate geocoding $scope.geoCodeResults = {}; $scope.checkBirthGeocode = function(location) { var url = 'http://www.mapquestapi.com/geocoding/v1/address?key=' + mapQuestKey + '&location=' + location + '&callback=JSON_CALLBACK'; $http.jsonp(url) .success(function(data) { $scope.geoCodeResults = data; if (data.results[0].locations.length == 1) { $scope.newRelative.birthCoords = //need to be put in array for Neo4j [data.results[0].locations[0].latLng.lat, data.results[0].locations[0].latLng.lng]; } }); }; // End checkBirthGeocode $scope.checkDeathGeocode = function(location) { var url = 'http://www.mapquestapi.com/geocoding/v1/address?key=' + mapQuestKey + '&location=' + location + '&callback=JSON_CALLBACK'; $http.jsonp(url) .success(function(data) { $scope.geoCodeResults = data; if (data.results[0].locations.length == 1) { $scope.newRelative.deathCoords = //need to be put in array for Neo4j [data.results[0].locations[0].latLng.lat, data.results[0].locations[0].latLng.lng]; } }); }; // End checkDeathGeocode $scope.mapFamily = function() { var markers = {}; for (var i = 0; i < $scope.familyMembers.length; i++) { if ($scope.familyMembers[i].birthCoords) { var markerName = $scope.familyMembers[i].name + 'Birth'; markers[markerName] = { lat: $scope.familyMembers[i].birthCoords[0], lng: $scope.familyMembers[i].birthCoords[1], message: 'Name: ' + $scope.familyMembers[i].name + '<br>' + 'Born: ' + $scope.familyMembers[i].birthLoc + '<br>' + $scope.familyMembers[i].birthDate }; } if ($scope.familyMembers[i].deathCoords && $scope.familyMembers[i].deathCoords.length) { var markerName = $scope.familyMembers[i].name + 'Death'; markers[markerName] = { lat: $scope.familyMembers[i].deathCoords[0], lng: $scope.familyMembers[i].deathCoords[1], message: 'Name: ' + $scope.familyMembers[i].name + '<br>' + 'Died: ' + $scope.familyMembers[i].deathLoc + '<br>' + $scope.familyMembers[i].deathDate }; } } angular.extend($scope, { markers: markers }); }; $scope.editing = function(relative, bool) { relative.editing = bool; if(bool) { if(relative.birthDate) { relative.birthDate = new Date(relative.birthDate); } if(relative.deathDate) { relative.deathDate = new Date(relative.deathDate); } } }; }]); };<|fim▁end|>
<|file_name|>bydpconfigure.cpp<|end_file_name|><|fim▁begin|>#include "bydpconfigure.h" #include <Button.h> #include <StringView.h> #include <SpLocaleApp.h> #include "globals.h" const uint32 BUTTON_OK = 'BuOK'; const uint32 BUTTON_CANCEL = 'BuCA'; const uint32 CCOLOR_MSG = 'ColM'; const uint32 SLIDER = 'Slid'; bydpConfigure::bydpConfigure(const char *title, BHandler *handler) : BWindow( BRect(62, 100, 62+370, 260), title, B_TITLED_WINDOW, B_NOT_RESIZABLE ) { myHandler = handler; myColour = -1; mainView = new BView(BWindow::Bounds(), NULL, B_FOLLOW_ALL, 0); mainView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR)); BWindow::AddChild(mainView); } bydpConfigure::~bydpConfigure() { } void bydpConfigure::SetupDistanceDialog(void) { BButton *CancelButton = new BButton(BRect(22,123,23+75,123+24), "cancel", tr("Cancel"), new BMessage(BUTTON_CANCEL), B_FOLLOW_LEFT, B_WILL_DRAW); mainView->AddChild(CancelButton); BButton *OKButton = new BButton(BRect(285,123,285+75,123+24),"ok",tr("OK"), new BMessage(BUTTON_OK), B_FOLLOW_LEFT, B_WILL_DRAW); mainView->AddChild(OKButton); mySlider = new BSlider(BRect(44,20,22+285,20+100), "slider", tr("Fuzzy factor"), new BMessage(SLIDER), 1, 5); mySlider->SetLimitLabels(tr("low"), tr("high")); mySlider->SetHashMarks(B_HASH_MARKS_BOTH); mySlider->SetHashMarkCount(5); mySlider->SetValue(myConfig->distance); mainView->AddChild(mySlider); } void bydpConfigure::SetupColourDialog(int colour) { myColour = colour; BButton *CancelButton = new BButton(BRect(22,123,23+75,123+24), "cancel", tr("Cancel"), new BMessage(BUTTON_CANCEL), B_FOLLOW_LEFT, B_WILL_DRAW); mainView->AddChild(CancelButton); BButton *OKButton = new BButton(BRect(285,123,285+75,123+24),"ok",tr("OK"), new BMessage(BUTTON_OK), B_FOLLOW_LEFT, B_WILL_DRAW); mainView->AddChild(OKButton); exampleText = new BStringView(BRect(22,91,22+258,91+19),"example",tr("Example text."), B_FOLLOW_LEFT, B_WILL_DRAW); exampleText->SetAlignment(B_ALIGN_CENTER); mainView->AddChild(exampleText); myCColor = new BColorControl(BPoint(22,20),B_CELLS_32x8, 8.0, "ccontrol", new BMessage(CCOLOR_MSG), false); switch(colour) { case 0: myCColor->SetValue(myConfig->colour); break; case 1: myCColor->SetValue(myConfig->colour0); break; case 2: myCColor->SetValue(myConfig->colour1); break; case 3: myCColor->SetValue(myConfig->colour2); default: break; } mainView->AddChild(myCColor); OKButton->MakeFocus(true); UpdateExampleColour(); } void bydpConfigure::SetConfig(bydpConfig *config) { myConfig = config; } void bydpConfigure::CopyNewColours(rgb_color *to) { to->red = myCColor->ValueAsColor().red; to->green = myCColor->ValueAsColor().green; to->blue = myCColor->ValueAsColor().blue; } void bydpConfigure::UpdateExampleColour(void) { exampleText->SetHighColor(myCColor->ValueAsColor()); exampleText->Invalidate(); } void bydpConfigure::ConfigUpdate(void) {<|fim▁hole|> switch(myColour) { case 0: CopyNewColours(&myConfig->colour); break; case 1: CopyNewColours(&myConfig->colour0); break; case 2: CopyNewColours(&myConfig->colour1); break; case 3: CopyNewColours(&myConfig->colour2); break; default: break; } } else { myConfig->distance = mySlider->Value(); } myConfig->save(); } void bydpConfigure::MessageReceived(BMessage * Message) { switch(Message->what) { case BUTTON_OK: // printf("ok\n"); ConfigUpdate(); if (myColour > -1) myHandler->Looper()->PostMessage(new BMessage(MSG_COLOURUPDATE)); else myHandler->Looper()->PostMessage(new BMessage(MSG_FUZZYUPDATE)); QuitRequested(); break; case BUTTON_CANCEL: // printf("cancel\n"); QuitRequested(); break; case CCOLOR_MSG: // printf("color msg\n"); UpdateExampleColour(); break; case SLIDER: break; default: BWindow::MessageReceived(Message); break; } } bool bydpConfigure::QuitRequested() { Hide(); return BWindow::QuitRequested(); }<|fim▁end|>
// printf("update config in dialog\n"); if (myColour > -1) { // printf("update colour %i\n",myColour);
<|file_name|>ConfirmRequestWriterV20.java<|end_file_name|><|fim▁begin|>/***************************** BEGIN LICENSE BLOCK *************************** The contents of this file are subject to the Mozilla Public License Version 1.1 (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/MPL-1.1.html 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 the "OGC Service Framework". The Initial Developer of the Original Code is Spotimage S.A. Portions created by the Initial Developer are Copyright (C) 2007 the Initial Developer. All Rights Reserved. Contributor(s): Philippe Merigot <[email protected]> ******************************* END LICENSE BLOCK ***************************/ package org.vast.ows.sps; import org.w3c.dom.Element; import org.vast.ogc.OGCRegistry; import org.vast.ows.OWSException; import org.vast.ows.swe.SWERequestWriter; import org.vast.xml.DOMHelper; /** * <p> * Provides methods to generate an XML SPS Confirm * request based on values contained in a ConfirmRequest object * for version 2.0 * </p> * * @author Alexandre Robin <[email protected]> * @date Feb, 258 2008 **/ public class ConfirmRequestWriterV20 extends SWERequestWriter<ConfirmRequest> { <|fim▁hole|> @Override public String buildURLQuery(ConfirmRequest request) throws OWSException { throw new SPSException(noKVP + "SPS 2.0 " + request.getOperation()); } /** * XML Request */ @Override public Element buildXMLQuery(DOMHelper dom, ConfirmRequest request) throws OWSException { dom.addUserPrefix("sps", OGCRegistry.getNamespaceURI(SPSUtils.SPS, request.getVersion())); // root element Element rootElt = dom.createElement("sps:" + request.getOperation()); addCommonXML(dom, rootElt, request); // taskID dom.setElementValue(rootElt, "sps:task", request.getTaskID()); return rootElt; } }<|fim▁end|>
/** * KVP Request */