repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
gbif/gbif-api
src/main/java/org/gbif/api/model/occurrence/predicate/GeoDistancePredicate.java
<filename>src/main/java/org/gbif/api/model/occurrence/predicate/GeoDistancePredicate.java /* * 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.gbif.api.model.occurrence.predicate; import org.gbif.api.model.occurrence.geo.DistanceUnit; import org.gbif.api.util.SearchTypeValidator; import java.util.Objects; import java.util.StringJoiner; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; /** * This predicate checks if an occurrence location falls within the given WKT geometry {@code value}. */ public class GeoDistancePredicate implements Predicate { @NotNull private final DistanceUnit.GeoDistance geoDistance; @NotNull private final String latitude; @NotNull private final String longitude; @NotNull private final String distance; /** * Builds a new geodistance predicate that matches records within a given distance of a geopoint.. * * @param latitude * @param longitude * @param distance */ @JsonCreator public GeoDistancePredicate(@JsonProperty("latitude") String latitude, @JsonProperty("longitude") String longitude, @JsonProperty("distance") String distance) { Objects.requireNonNull(latitude, "<latitude> may not be null"); Objects.requireNonNull(longitude, "<longitude> may not be null"); Objects.requireNonNull(distance, "<distance> may not be null"); this.latitude = latitude; this.longitude = longitude; this.distance = distance; // test if it is a valid GeoDistance SearchTypeValidator.validateGeoDistance(latitude, longitude, distance); this.geoDistance = DistanceUnit.GeoDistance.parseGeoDistance(latitude, longitude, distance); } public GeoDistancePredicate(@NotNull DistanceUnit.GeoDistance geoDistance) { this.geoDistance = geoDistance; this.latitude = Double.toString(geoDistance.getLatitude()); this.longitude = Double.toString(geoDistance.getLongitude()); this.distance = geoDistance.getDistance().toString(); } public String getLatitude() { return latitude; } public String getLongitude() { return longitude; } public String getDistance() { return distance; } public DistanceUnit.GeoDistance getGeoDistance() { return geoDistance; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GeoDistancePredicate that = (GeoDistancePredicate) o; return Objects.equals(geoDistance, that.geoDistance); } @Override public int hashCode() { return Objects.hash(geoDistance); } @Override public String toString() { return new StringJoiner(", ", GeoDistancePredicate.class.getSimpleName() + "[", "]") .add("geoDistance=" + geoDistance).toString(); } }
rkorytkowski/teiid
engine/src/main/java/org/teiid/common/buffer/impl/PhysicalInfo.java
<gh_stars>0 /* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * 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.teiid.common.buffer.impl; import org.teiid.common.buffer.BaseCacheEntry; import org.teiid.common.buffer.CacheKey; import org.teiid.core.TeiidRuntimeException; import org.teiid.query.QueryPlugin; /** * Represents the memory buffer and storage state of an object. * It is important to minimize the amount of data held here. * Currently should be 60 bytes. */ final class PhysicalInfo extends BaseCacheEntry { static final Exception sizeChanged = new Exception(); final Long gid; //the memory inode and block count int inode = BufferFrontedFileStoreCache.EMPTY_ADDRESS; int memoryBlockCount; //the storage block and BlockStore index int block = BufferFrontedFileStoreCache.EMPTY_ADDRESS; byte sizeIndex = 0; //state flags boolean pinned; //indicates that the entry is being read boolean evicting; //indicates that the entry will be moved out of the memory buffer boolean loading; //used by tier 1 cache to prevent double loads boolean adding; //used to prevent double adds int sizeEstimate; PhysicalInfo(Long gid, Long id, int inode, long lastAccess, int sizeEstimate) { super(new CacheKey(id, lastAccess, 0)); this.inode = inode; this.gid = gid; this.sizeEstimate = sizeEstimate; } void setSize(int size) throws Exception { int newMemoryBlockCount = (size>>BufferFrontedFileStoreCache.LOG_BLOCK_SIZE) + ((size&BufferFrontedFileStoreCache.BLOCK_MASK)>0?1:0); if (this.memoryBlockCount != 0) { if (newMemoryBlockCount != memoryBlockCount) { throw sizeChanged; } return; //no changes } this.memoryBlockCount = newMemoryBlockCount; while (newMemoryBlockCount > 1) { this.sizeIndex++; newMemoryBlockCount = (newMemoryBlockCount>>1) + ((newMemoryBlockCount&0x01)==0?0:1); } } void await(boolean donePinning, boolean doneEvicting) { while ((donePinning && pinned) || (doneEvicting && evicting)) { try { wait(); } catch (InterruptedException e) { throw new TeiidRuntimeException(QueryPlugin.Event.TEIID30043, e); } } } synchronized void lockForLoad() { while (loading) { try { wait(); } catch (InterruptedException e) { throw new TeiidRuntimeException(QueryPlugin.Event.TEIID30044, e); } } loading = true; } synchronized void unlockForLoad() { assert loading; loading = false; notifyAll(); } }
strangelittlemonkey/DragonFlyBSD
sys/dev/disk/vn/vn.c
<reponame>strangelittlemonkey/DragonFlyBSD /* * Copyright (c) 1988 University of Utah. * Copyright (c) 1990, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * the Systems Programming Group of the University of Utah Computer * Science Department. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * from: Utah Hdr: vn.c 1.13 94/04/02 * * from: @(#)vn.c 8.6 (Berkeley) 4/1/94 * $FreeBSD: src/sys/dev/vn/vn.c,v 1.105.2.4 2001/11/18 07:11:00 dillon Exp $ */ /* * Vnode disk driver. * * Block/character interface to a vnode. Allows one to treat a file * as a disk (e.g. build a filesystem in it, mount it, etc.). * * NOTE 1: There is a security issue involved with this driver. * Once mounted all access to the contents of the "mapped" file via * the special file is controlled by the permissions on the special * file, the protection of the mapped file is ignored (effectively, * by using root credentials in all transactions). * * NOTE 2: Doesn't interact with leases, should it? */ #include "use_vn.h" #include <sys/param.h> #include <sys/systm.h> #include <sys/kernel.h> #include <sys/proc.h> #include <sys/priv.h> #include <sys/nlookup.h> #include <sys/buf.h> #include <sys/malloc.h> #include <sys/mount.h> #include <sys/vnode.h> #include <sys/fcntl.h> #include <sys/conf.h> #include <sys/diskslice.h> #include <sys/disk.h> #include <sys/stat.h> #include <sys/module.h> #include <sys/vnioctl.h> #include <vm/vm.h> #include <vm/vm_object.h> #include <vm/vm_page.h> #include <vm/vm_pager.h> #include <vm/vm_pageout.h> #include <vm/swap_pager.h> #include <vm/vm_extern.h> #include <vm/vm_zone.h> #include <sys/devfs.h> static d_ioctl_t vnioctl; static d_open_t vnopen; static d_close_t vnclose; static d_psize_t vnsize; static d_strategy_t vnstrategy; static d_clone_t vnclone; MALLOC_DEFINE(M_VN, "vn_softc", "vn driver structures"); DEVFS_DEFINE_CLONE_BITMAP(vn); #if NVN <= 1 #define VN_PREALLOCATED_UNITS 4 #else #define VN_PREALLOCATED_UNITS NVN #endif #define VN_BSIZE_BEST 8192 /* * dev_ops * D_DISK We want to look like a disk * D_CANFREE We support BUF_CMD_FREEBLKS * D_NOEMERGPGR Too complex for emergency pager */ static struct dev_ops vn_ops = { { "vn", 0, D_DISK | D_CANFREE | D_NOEMERGPGR }, .d_open = vnopen, .d_close = vnclose, .d_read = physread, .d_write = physwrite, .d_ioctl = vnioctl, .d_strategy = vnstrategy, .d_psize = vnsize }; struct vn_softc { int sc_unit; int sc_flags; /* flags */ u_int64_t sc_size; /* size of vn, sc_secsize scale */ int sc_secsize; /* sector size */ struct disk sc_disk; struct vnode *sc_vp; /* vnode if not NULL */ vm_object_t sc_object; /* backing object if not NULL */ struct ucred *sc_cred; /* credentials */ int sc_maxactive; /* max # of active requests */ struct buf sc_tab; /* transfer queue */ u_long sc_options; /* options */ cdev_t sc_dev; /* devices that refer to this unit */ SLIST_ENTRY(vn_softc) sc_list; }; static SLIST_HEAD(, vn_softc) vn_list; /* sc_flags */ #define VNF_INITED 0x01 #define VNF_READONLY 0x02 #define VNF_OPENED 0x10 #define VNF_DESTROY 0x20 static u_long vn_options; #define IFOPT(vn,opt) if (((vn)->sc_options|vn_options) & (opt)) #define TESTOPT(vn,opt) (((vn)->sc_options|vn_options) & (opt)) static int vnsetcred (struct vn_softc *vn, struct ucred *cred); static void vnclear (struct vn_softc *vn); static int vnget (cdev_t dev, struct vn_softc *vn , struct vn_user *vnu); static int vn_modevent (module_t, int, void *); static int vniocattach_file (struct vn_softc *, struct vn_ioctl *, cdev_t dev, int flag, struct ucred *cred); static int vniocattach_swap (struct vn_softc *, struct vn_ioctl *, cdev_t dev, int flag, struct ucred *cred); static cdev_t vn_create(int unit, struct devfs_bitmap *bitmap, int clone); static int vnclone(struct dev_clone_args *ap) { int unit; unit = devfs_clone_bitmap_get(&DEVFS_CLONE_BITMAP(vn), 0); ap->a_dev = vn_create(unit, &DEVFS_CLONE_BITMAP(vn), 1); return 0; } static int vnclose(struct dev_close_args *ap) { cdev_t dev = ap->a_head.a_dev; struct vn_softc *vn; vn = dev->si_drv1; KKASSERT(vn != NULL); vn->sc_flags &= ~VNF_OPENED; /* The disk has been detached and can now be safely destroyed */ if (vn->sc_flags & VNF_DESTROY) { KKASSERT(disk_getopencount(&vn->sc_disk) == 0); disk_destroy(&vn->sc_disk); devfs_clone_bitmap_put(&DEVFS_CLONE_BITMAP(vn), dkunit(dev)); SLIST_REMOVE(&vn_list, vn, vn_softc, sc_list); kfree(vn, M_VN); } return (0); } static struct vn_softc * vncreatevn(void) { struct vn_softc *vn; vn = kmalloc(sizeof *vn, M_VN, M_WAITOK | M_ZERO); return vn; } static void vninitvn(struct vn_softc *vn, cdev_t dev) { int unit; KKASSERT(vn != NULL); KKASSERT(dev != NULL); unit = dkunit(dev); vn->sc_unit = unit; dev->si_drv1 = vn; vn->sc_dev = dev; SLIST_INSERT_HEAD(&vn_list, vn, sc_list); } static int vnopen(struct dev_open_args *ap) { cdev_t dev = ap->a_head.a_dev; struct vn_softc *vn; /* * Locate preexisting device */ vn = dev->si_drv1; KKASSERT(vn != NULL); /* * Update si_bsize fields for device. This data will be overriden by * the slice/parition code for vn accesses through partitions, and * used directly if you open the 'whole disk' device. * * si_bsize_best must be reinitialized in case VN has been * reconfigured, plus make it at least VN_BSIZE_BEST for efficiency. */ dev->si_bsize_phys = vn->sc_secsize; dev->si_bsize_best = vn->sc_secsize; if (dev->si_bsize_best < VN_BSIZE_BEST) dev->si_bsize_best = VN_BSIZE_BEST; if ((ap->a_oflags & FWRITE) && (vn->sc_flags & VNF_READONLY)) return (EACCES); IFOPT(vn, VN_FOLLOW) kprintf("vnopen(%s, 0x%x, 0x%x)\n", devtoname(dev), ap->a_oflags, ap->a_devtype); vn->sc_flags |= VNF_OPENED; return(0); } /* * vnstrategy: * * Run strategy routine for VN device. We use VOP_READ/VOP_WRITE calls * for vnode-backed vn's, and the swap_pager_strategy() call for * vm_object-backed vn's. */ static int vnstrategy(struct dev_strategy_args *ap) { cdev_t dev = ap->a_head.a_dev; struct bio *bio = ap->a_bio; struct buf *bp; struct bio *nbio; int unit; struct vn_softc *vn; int error; unit = dkunit(dev); vn = dev->si_drv1; KKASSERT(vn != NULL); bp = bio->bio_buf; IFOPT(vn, VN_DEBUG) kprintf("vnstrategy(%p): unit %d\n", bp, unit); if ((vn->sc_flags & VNF_INITED) == 0) { bp->b_error = ENXIO; bp->b_flags |= B_ERROR; biodone(bio); return(0); } bp->b_resid = bp->b_bcount; /* * The vnode device is using disk/slice label support. * * The dscheck() function is called for validating the * slices that exist ON the vnode device itself, and * translate the "slice-relative" block number, again. * dscheck() will call biodone() and return NULL if * we are at EOF or beyond the device size. */ nbio = bio; /* * Use the translated nbio from this point on */ if (vn->sc_vp && bp->b_cmd == BUF_CMD_FREEBLKS) { /* * Freeblks is not handled for vnode-backed elements yet. */ bp->b_resid = 0; /* operation complete */ } else if (vn->sc_vp) { /* * VNODE I/O * * If an error occurs, we set B_ERROR but we do not set * B_INVAL because (for a write anyway), the buffer is * still valid. */ struct uio auio; struct iovec aiov; bzero(&auio, sizeof(auio)); aiov.iov_base = bp->b_data; aiov.iov_len = bp->b_bcount; auio.uio_iov = &aiov; auio.uio_iovcnt = 1; auio.uio_offset = nbio->bio_offset; auio.uio_segflg = UIO_SYSSPACE; if (bp->b_cmd == BUF_CMD_READ) auio.uio_rw = UIO_READ; else auio.uio_rw = UIO_WRITE; auio.uio_resid = bp->b_bcount; auio.uio_td = curthread; /* * Don't use IO_DIRECT here, it really gets in the way * due to typical blocksize differences between the * fs backing the VN device and whatever is running on * the VN device. */ switch (bp->b_cmd) { case (BUF_CMD_READ): vn_lock(vn->sc_vp, LK_SHARED | LK_RETRY); error = VOP_READ(vn->sc_vp, &auio, IO_RECURSE, vn->sc_cred); break; case (BUF_CMD_WRITE): vn_lock(vn->sc_vp, LK_EXCLUSIVE | LK_RETRY); error = VOP_WRITE(vn->sc_vp, &auio, IO_RECURSE, vn->sc_cred); break; case (BUF_CMD_FLUSH): auio.uio_resid = 0; vn_lock(vn->sc_vp, LK_EXCLUSIVE | LK_RETRY); error = VOP_FSYNC(vn->sc_vp, MNT_WAIT, 0); break; default: auio.uio_resid = 0; error = 0; goto breakunlocked; } vn_unlock(vn->sc_vp); breakunlocked: bp->b_resid = auio.uio_resid; if (error) { bp->b_error = error; bp->b_flags |= B_ERROR; } /* operation complete */ } else if (vn->sc_object) { /* * OBJT_SWAP I/O (handles read, write, freebuf) * * We have nothing to do if freeing blocks on a reserved * swap area, othrewise execute the op. */ if (bp->b_cmd == BUF_CMD_FREEBLKS && TESTOPT(vn, VN_RESERVE)) { bp->b_resid = 0; /* operation complete */ } else { swap_pager_strategy(vn->sc_object, nbio); return(0); /* NOT REACHED */ } } else { bp->b_resid = bp->b_bcount; bp->b_flags |= B_ERROR | B_INVAL; bp->b_error = EINVAL; /* operation complete */ } biodone(nbio); return(0); } /* ARGSUSED */ static int vnioctl(struct dev_ioctl_args *ap) { cdev_t dev = ap->a_head.a_dev; struct vn_softc *vn; struct vn_ioctl *vio; int error; u_long *f; vn = dev->si_drv1; IFOPT(vn,VN_FOLLOW) { kprintf("vnioctl(%s, 0x%lx, %p, 0x%x): unit %d\n", devtoname(dev), ap->a_cmd, ap->a_data, ap->a_fflag, dkunit(dev)); } switch (ap->a_cmd) { case VNIOCATTACH: case VNIOCDETACH: case VNIOCGSET: case VNIOCGCLEAR: case VNIOCGET: case VNIOCUSET: case VNIOCUCLEAR: goto vn_specific; } #if 0 if (dkslice(dev) != WHOLE_DISK_SLICE || dkpart(dev) != WHOLE_SLICE_PART) return (ENOTTY); #endif vn_specific: error = priv_check_cred(ap->a_cred, PRIV_ROOT, 0); if (error) return (error); vio = (struct vn_ioctl *)ap->a_data; f = (u_long*)ap->a_data; switch (ap->a_cmd) { case VNIOCATTACH: if (vn->sc_flags & VNF_INITED) return(EBUSY); if (vn->sc_flags & VNF_DESTROY) return(ENXIO); if (vio->vn_file == NULL) error = vniocattach_swap(vn, vio, dev, ap->a_fflag, ap->a_cred); else error = vniocattach_file(vn, vio, dev, ap->a_fflag, ap->a_cred); break; case VNIOCDETACH: if ((vn->sc_flags & VNF_INITED) == 0) return(ENXIO); /* * XXX handle i/o in progress. Return EBUSY, or wait, or * flush the i/o. * XXX handle multiple opens of the device. Return EBUSY, * or revoke the fd's. * How are these problems handled for removable and failing * hardware devices? (Hint: They are not) */ if ((disk_getopencount(&vn->sc_disk)) > 1) return (EBUSY); vnclear(vn); IFOPT(vn, VN_FOLLOW) kprintf("vnioctl: CLRed\n"); if (dkunit(dev) >= VN_PREALLOCATED_UNITS) { vn->sc_flags |= VNF_DESTROY; } break; case VNIOCGET: error = vnget(dev, vn, (struct vn_user *) ap->a_data); break; case VNIOCGSET: vn_options |= *f; *f = vn_options; break; case VNIOCGCLEAR: vn_options &= ~(*f); *f = vn_options; break; case VNIOCUSET: vn->sc_options |= *f; *f = vn->sc_options; break; case VNIOCUCLEAR: vn->sc_options &= ~(*f); *f = vn->sc_options; break; default: error = ENOTTY; break; } return(error); } /* * vniocattach_file: * * Attach a file to a VN partition. Return the size in the vn_size * field. */ static int vniocattach_file(struct vn_softc *vn, struct vn_ioctl *vio, cdev_t dev, int flag, struct ucred *cred) { struct vattr vattr; struct nlookupdata nd; int error, flags; struct vnode *vp; struct disk_info info; flags = FREAD|FWRITE; error = nlookup_init(&nd, vio->vn_file, UIO_USERSPACE, NLC_FOLLOW|NLC_LOCKVP); if (error) return (error); if ((error = vn_open(&nd, NULL, flags, 0)) != 0) { if (error != EACCES && error != EPERM && error != EROFS) goto done; flags &= ~FWRITE; nlookup_done(&nd); error = nlookup_init(&nd, vio->vn_file, UIO_USERSPACE, NLC_FOLLOW|NLC_LOCKVP); if (error) return (error); if ((error = vn_open(&nd, NULL, flags, 0)) != 0) goto done; } vp = nd.nl_open_vp; if (vp->v_type != VREG || (error = VOP_GETATTR(vp, &vattr))) { if (error == 0) error = EINVAL; goto done; } vn_unlock(vp); vn->sc_secsize = DEV_BSIZE; vn->sc_vp = vp; nd.nl_open_vp = NULL; /* * If the size is specified, override the file attributes. Note that * the vn_size argument is in PAGE_SIZE sized blocks. */ if (vio->vn_size) vn->sc_size = vio->vn_size * PAGE_SIZE / vn->sc_secsize; else vn->sc_size = vattr.va_size / vn->sc_secsize; error = vnsetcred(vn, cred); if (error) { vn->sc_vp = NULL; vn_close(vp, flags, NULL); goto done; } vn->sc_flags |= VNF_INITED; if (flags == FREAD) vn->sc_flags |= VNF_READONLY; /* * Set the disk info so that probing is triggered */ bzero(&info, sizeof(struct disk_info)); info.d_media_blksize = vn->sc_secsize; info.d_media_blocks = vn->sc_size; /* * reserve mbr sector for backwards compatibility * when no slices exist. */ info.d_dsflags = DSO_COMPATMBR | DSO_RAWPSIZE; info.d_secpertrack = 32; info.d_nheads = 64 / (vn->sc_secsize / DEV_BSIZE); info.d_secpercyl = info.d_secpertrack * info.d_nheads; info.d_ncylinders = vn->sc_size / info.d_secpercyl; disk_setdiskinfo_sync(&vn->sc_disk, &info); error = dev_dopen(dev, flag, S_IFCHR, cred, NULL); if (error) vnclear(vn); IFOPT(vn, VN_FOLLOW) kprintf("vnioctl: SET vp %p size %llx blks\n", vn->sc_vp, (long long)vn->sc_size); done: nlookup_done(&nd); return(error); } /* * vniocattach_swap: * * Attach swap backing store to a VN partition of the size specified * in vn_size. */ static int vniocattach_swap(struct vn_softc *vn, struct vn_ioctl *vio, cdev_t dev, int flag, struct ucred *cred) { int error; struct disk_info info; /* * Range check. Disallow negative sizes or any size less then the * size of a page. Then round to a page. */ if (vio->vn_size <= 0) return(EDOM); /* * Allocate an OBJT_SWAP object. * * sc_secsize is PAGE_SIZE'd * * vio->vn_size is in PAGE_SIZE'd chunks. * sc_size must be in PAGE_SIZE'd chunks. * Note the truncation. */ vn->sc_secsize = PAGE_SIZE; vn->sc_size = vio->vn_size; vn->sc_object = swap_pager_alloc(NULL, vn->sc_secsize * (off_t)vio->vn_size, VM_PROT_DEFAULT, 0); vm_object_set_flag(vn->sc_object, OBJ_NOPAGEIN); IFOPT(vn, VN_RESERVE) { if (swap_pager_reserve(vn->sc_object, 0, vn->sc_size) < 0) { vm_pager_deallocate(vn->sc_object); vn->sc_object = NULL; return(EDOM); } } vn->sc_flags |= VNF_INITED; error = vnsetcred(vn, cred); if (error == 0) { /* * Set the disk info so that probing is triggered */ bzero(&info, sizeof(struct disk_info)); info.d_media_blksize = vn->sc_secsize; info.d_media_blocks = vn->sc_size; /* * reserve mbr sector for backwards compatibility * when no slices exist. */ info.d_dsflags = DSO_COMPATMBR | DSO_RAWPSIZE; info.d_secpertrack = 32; info.d_nheads = 64 / (vn->sc_secsize / DEV_BSIZE); info.d_secpercyl = info.d_secpertrack * info.d_nheads; info.d_ncylinders = vn->sc_size / info.d_secpercyl; disk_setdiskinfo_sync(&vn->sc_disk, &info); error = dev_dopen(dev, flag, S_IFCHR, cred, NULL); } if (error == 0) { IFOPT(vn, VN_FOLLOW) { kprintf("vnioctl: SET vp %p size %llx\n", vn->sc_vp, (long long)vn->sc_size); } } if (error) vnclear(vn); return(error); } /* * Duplicate the current processes' credentials. Since we are called only * as the result of a SET ioctl and only root can do that, any future access * to this "disk" is essentially as root. Note that credentials may change * if some other uid can write directly to the mapped file (NFS). */ static int vnsetcred(struct vn_softc *vn, struct ucred *cred) { char *tmpbuf; int error = 0; /* * Set credits in our softc */ if (vn->sc_cred) crfree(vn->sc_cred); vn->sc_cred = crdup(cred); /* * Horrible kludge to establish credentials for NFS XXX. */ if (vn->sc_vp) { struct uio auio; struct iovec aiov; tmpbuf = kmalloc(vn->sc_secsize, M_TEMP, M_WAITOK); bzero(&auio, sizeof(auio)); aiov.iov_base = tmpbuf; aiov.iov_len = vn->sc_secsize; auio.uio_iov = &aiov; auio.uio_iovcnt = 1; auio.uio_offset = 0; auio.uio_rw = UIO_READ; auio.uio_segflg = UIO_SYSSPACE; auio.uio_resid = aiov.iov_len; vn_lock(vn->sc_vp, LK_EXCLUSIVE | LK_RETRY); error = VOP_READ(vn->sc_vp, &auio, 0, vn->sc_cred); vn_unlock(vn->sc_vp); kfree(tmpbuf, M_TEMP); } return (error); } static void vnclear(struct vn_softc *vn) { IFOPT(vn, VN_FOLLOW) kprintf("vnclear(%p): vp=%p\n", vn, vn->sc_vp); vn->sc_flags &= ~VNF_INITED; if (vn->sc_vp != NULL) { vn_close(vn->sc_vp, (vn->sc_flags & VNF_READONLY) ? FREAD : (FREAD|FWRITE), NULL); vn->sc_vp = NULL; } vn->sc_flags &= ~VNF_READONLY; if (vn->sc_cred) { crfree(vn->sc_cred); vn->sc_cred = NULL; } if (vn->sc_object != NULL) { vm_pager_deallocate(vn->sc_object); vn->sc_object = NULL; } disk_unprobe(&vn->sc_disk); vn->sc_size = 0; } /* * vnget: * * populate a struct vn_user for the VNIOCGET ioctl. * interface conventions defined in sys/sys/vnioctl.h. */ static int vnget(cdev_t dev, struct vn_softc *vn, struct vn_user *vnu) { int error, found = 0; char *freepath, *fullpath; struct vattr vattr; if (vnu->vnu_unit == -1) { vnu->vnu_unit = dkunit(dev); } else if (vnu->vnu_unit < 0) return (EINVAL); SLIST_FOREACH(vn, &vn_list, sc_list) { if(vn->sc_unit != vnu->vnu_unit) continue; found = 1; if (vn->sc_flags & VNF_INITED && vn->sc_vp != NULL) { /* note: u_cred checked in vnioctl above */ error = VOP_GETATTR(vn->sc_vp, &vattr); if (error) { kprintf("vnget: VOP_GETATTR for %p failed\n", vn->sc_vp); return (error); } error = vn_fullpath(curproc, vn->sc_vp, &fullpath, &freepath, 0); if (error) { kprintf("vnget: unable to resolve vp %p\n", vn->sc_vp); return(error); } strlcpy(vnu->vnu_file, fullpath, sizeof(vnu->vnu_file)); kfree(freepath, M_TEMP); vnu->vnu_dev = vattr.va_fsid; vnu->vnu_ino = vattr.va_fileid; } else if (vn->sc_flags & VNF_INITED && vn->sc_object != NULL){ strlcpy(vnu->vnu_file, _VN_USER_SWAP, sizeof(vnu->vnu_file)); vnu->vnu_size = vn->sc_size; vnu->vnu_secsize = vn->sc_secsize; } else { bzero(vnu->vnu_file, sizeof(vnu->vnu_file)); vnu->vnu_dev = 0; vnu->vnu_ino = 0; } break; } if (!found) return(ENXIO); return(0); } static int vnsize(struct dev_psize_args *ap) { cdev_t dev = ap->a_head.a_dev; struct vn_softc *vn; vn = dev->si_drv1; if (!vn) return(ENXIO); if ((vn->sc_flags & VNF_INITED) == 0) return(ENXIO); ap->a_result = (int64_t)vn->sc_size; return(0); } static cdev_t vn_create(int unit, struct devfs_bitmap *bitmap, int clone) { struct vn_softc *vn; struct disk_info info; cdev_t dev, ret_dev; vn = vncreatevn(); if (clone) { /* * For clone devices we need to return the top-level cdev, * not the raw dev we'd normally work with. */ dev = disk_create_clone(unit, &vn->sc_disk, &vn_ops); ret_dev = vn->sc_disk.d_cdev; } else { ret_dev = dev = disk_create(unit, &vn->sc_disk, &vn_ops); } vninitvn(vn, dev); bzero(&info, sizeof(struct disk_info)); info.d_media_blksize = 512; info.d_media_blocks = 0; info.d_dsflags = DSO_MBRQUIET | DSO_RAWPSIZE; info.d_secpertrack = 32; info.d_nheads = 64; info.d_secpercyl = info.d_secpertrack * info.d_nheads; info.d_ncylinders = 0; disk_setdiskinfo_sync(&vn->sc_disk, &info); if (bitmap != NULL) devfs_clone_bitmap_set(bitmap, unit); return ret_dev; } static int vn_modevent(module_t mod, int type, void *data) { struct vn_softc *vn; static cdev_t dev = NULL; int i; switch (type) { case MOD_LOAD: dev = make_autoclone_dev(&vn_ops, &DEVFS_CLONE_BITMAP(vn), vnclone, UID_ROOT, GID_OPERATOR, 0640, "vn"); for (i = 0; i < VN_PREALLOCATED_UNITS; i++) { vn_create(i, &DEVFS_CLONE_BITMAP(vn), 0); } break; case MOD_UNLOAD: case MOD_SHUTDOWN: while ((vn = SLIST_FIRST(&vn_list)) != NULL) { /* * XXX: no idea if we can return EBUSY even in the * shutdown case, so err on the side of caution * and just rip stuff out on shutdown. */ if (type != MOD_SHUTDOWN) { if (vn->sc_flags & VNF_OPENED) return (EBUSY); } disk_destroy(&vn->sc_disk); SLIST_REMOVE_HEAD(&vn_list, sc_list); if (vn->sc_flags & VNF_INITED) vnclear(vn); kfree(vn, M_VN); } destroy_autoclone_dev(dev, &DEVFS_CLONE_BITMAP(vn)); dev_ops_remove_all(&vn_ops); break; default: break; } return 0; } DEV_MODULE(vn, vn_modevent, 0);
navikt/spsak
felles/integrasjon/unleash-klient/src/main/java/no/nav/vedtak/felles/integrasjon/unleash/strategier/ByEnvironmentStrategy.java
<gh_stars>1-10 package no.nav.vedtak.felles.integrasjon.unleash.strategier; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import no.finn.unleash.strategy.Strategy; public class ByEnvironmentStrategy implements Strategy { public static final String ENV_KEY = "miljø"; private static final Logger LOGGER = LoggerFactory.getLogger(ByEnvironmentStrategy.class); @Override public String getName() { return "byEnvironment"; } @Override public boolean isEnabled(Map<String, String> parameters) { boolean enabled = EnvironmentService.isCurrentEnvironmentInMap(parameters, ENV_KEY); LOGGER.info("Strategy={} is enabled={}", getName(), enabled); return enabled; } }
ChristinGorman/baxter
src/main/java/no/gorman/database/Where.java
package no.gorman.database; public class Where { public final DatabaseColumns column; public final String operator; public final Object value; public Where(DatabaseColumns column, String operator) { this.column = column; this.operator = operator; this.value = null; } public Where(DatabaseColumns column, String operator, Object value) { this.column = column; this.operator = operator; this.value = value; } @Override public String toString() { return column.getTable() + "." + column.name() + " " + operator + " " + value; } }
cmbi/vase
src/main/webapp/jsmol/j2s/JS/ScriptException.js
<reponame>cmbi/vase<gh_stars>1-10 Clazz.declarePackage ("JS"); Clazz.load (["java.lang.Exception"], "JS.ScriptException", null, function () { c$ = Clazz.decorateAsClass (function () { this.eval = null; this.message = null; this.untranslated = null; this.isError = false; Clazz.instantialize (this, arguments); }, JS, "ScriptException", Exception); Clazz.makeConstructor (c$, function (se, msg, untranslated, isError) { Clazz.superConstructor (this, JS.ScriptException, []); this.eval = se; this.message = msg; this.isError = isError; if (!isError) return; this.eval.setException (this, msg, untranslated); }, "JS.ScriptError,~S,~S,~B"); Clazz.defineMethod (c$, "getErrorMessageUntranslated", function () { return this.untranslated; }); Clazz.overrideMethod (c$, "toString", function () { return this.message; }); });
marcopush/util-cpp
string.cc
<filename>string.cc #include "string.hh" namespace util::string { std::string_view ref_sv; }
SemyonSinchenko/jungrapht-visualization
jungrapht-visualization/src/test/java/org/jungrapht/visualization/layout/algorithms/sugiyama/TestSugiyamaFunctions.java
<gh_stars>10-100 package org.jungrapht.visualization.layout.algorithms.sugiyama; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.jgrapht.Graph; import org.jgrapht.graph.builder.GraphTypeBuilder; import org.jgrapht.util.SupplierUtil; import org.jungrapht.visualization.layout.util.synthetics.SE; import org.jungrapht.visualization.layout.util.synthetics.SV; import org.jungrapht.visualization.layout.util.synthetics.SVTransformedGraphSupplier; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestSugiyamaFunctions { private static final Logger log = LoggerFactory.getLogger(TestSugiyamaFunctions.class); Graph<String, Integer> graph; @Before public void setup() { // build a DAG graph = GraphTypeBuilder.<String, Integer>directed() .edgeSupplier(SupplierUtil.createIntegerSupplier()) .buildGraph(); graph.addVertex("00"); // rank 0 index 0 graph.addVertex("01"); // rank 0 index 1 graph.addVertex("10"); // rank 1 index 0 graph.addVertex("11"); // rank 1 index 1 graph.addVertex("20"); // rank 2 index 0 graph.addVertex("21"); // rank 2 index 1 graph.addEdge("00", "10"); // connect from rank 0 to rank 1 graph.addEdge("10", "20"); // connect from rank 1 to rank 2 graph.addEdge("00", "11"); // connect from rank 0 -> 1 graph.addEdge("11", "21"); // connect from rank 1 -> 2 graph.addEdge( "01", "20"); // connect from rank 1 -> 2 (this edge should be replaced with 2 synthetic edges) log.info( "graph has {} vertices and {} edges", graph.vertexSet().size(), graph.edgeSet().size()); log.info("graph: {}", graph); } @Test public void testTransformedGraph() { SVTransformedGraphSupplier<String, Integer> svTransformedGraphSupplier = new SVTransformedGraphSupplier(graph); Graph<SV<String>, SE<Integer>> sgraph = svTransformedGraphSupplier.get(); Assert.assertEquals(graph.vertexSet().size(), sgraph.vertexSet().size()); Assert.assertEquals(graph.edgeSet().size(), sgraph.edgeSet().size()); Set<String> verticesCopy = new HashSet<>(graph.vertexSet()); Set<Integer> edgesCopy = new HashSet<>(graph.edgeSet()); sgraph .vertexSet() .forEach( v -> { Assert.assertTrue(graph.containsVertex(v.getVertex())); verticesCopy.remove(v.getVertex()); }); Assert.assertTrue(verticesCopy.isEmpty()); sgraph .edgeSet() .forEach( e -> { Assert.assertTrue(graph.containsEdge(e.getEdge())); edgesCopy.remove(e.getEdge()); }); Assert.assertTrue(edgesCopy.isEmpty()); } @Test public void testAssignLayers() { TransformedGraphSupplier<String, Integer> svTransformedGraphSupplier = new TransformedGraphSupplier(graph); Graph<LV<String>, LE<String, Integer>> sgraph = svTransformedGraphSupplier.get(); List<List<LV<String>>> layers = GraphLayers.assign(sgraph); Assert.assertEquals(3, layers.size()); // this graph should have 3 layers this.checkLayers(layers); log.info("assign layers:"); for (List<LV<String>> layer : layers) { log.info("Layer: {}", layer); } log.info("virtual vertices and edges:"); Synthetics<String, Integer> synthetics = new Synthetics<>(sgraph); List<LE<String, Integer>> edges = new ArrayList<>(sgraph.edgeSet()); log.info("there are {} edges ", edges.size()); log.info("edges: {}", edges); LV<String>[][] layersArray = synthetics.createVirtualVerticesAndEdges(edges, layers); for (int i = 0; i < layersArray.length; i++) { // for (List<SugiyamaVertex<String>> layer : layers) { log.info("Layer: {}", Arrays.toString(layersArray[i])); } log.info("there are {} edges ", edges.size()); log.info("edges: {}", edges); Assert.assertEquals(graph.edgeSet().size(), edges.size() - 1); checkLayers(layers); } @Test public void testAssignLayersWithDoubleSkip() { graph.addVertex("30"); // rank 2 index 1 graph.addEdge("20", "30"); graph.addEdge("00", "30"); // connect from rank 0 to rank 3. should add 3, subtract 1 TransformedGraphSupplier<String, Integer> svTransformedGraphSupplier = new TransformedGraphSupplier(graph); Graph<LV<String>, LE<String, Integer>> sgraph = svTransformedGraphSupplier.get(); log.info("incoming dag: {}", sgraph); // AssignLayers<String, Integer> assignLayers = new AssignLayers<>(sgraph); List<List<LV<String>>> layers = GraphLayers.assign(sgraph); // assignLayers.assignLayers(); this.checkLayers(layers); log.info("assign layers:"); for (List<LV<String>> layer : layers) { log.info("Layer: {}", layer); } log.info("virtual vertices and edges:"); Synthetics<String, Integer> synthetics = new Synthetics<>(sgraph); List<LE<String, Integer>> edges = new ArrayList<>(sgraph.edgeSet()); log.info("there are {} edges ", edges.size()); log.info("edges: {}", edges); LV<String>[][] layersArray = synthetics.createVirtualVerticesAndEdges(edges, layers); for (int i = 0; i < layersArray.length; i++) { log.info("Layer: {}", Arrays.toString(layersArray[i])); } log.info("there are {} edges ", edges.size()); log.info("edges: {}", edges); log.info("graph.edgeSet(): {}", graph.edgeSet()); log.info("edges.size(): {}", edges.size()); Assert.assertEquals(graph.edgeSet().size(), edges.size() - 3); checkLayers(layers); log.info("outgoing dag: {}", sgraph.toString()); // should look like this: /* SV{vertex=00, rank=0, index=0}, SV{vertex=01, rank=0, index=1}, SV{vertex=10, rank=1, index=0}, SV{vertex=11, rank=1, index=1}, SV{vertex=20, rank=2, index=0}, SV{vertex=21, rank=2, index=1}, SV{vertex=30, rank=3, index=0}], [ SE{edge=0, source=SV{vertex=00, rank=0, index=0}, intermediateVertices=[], target=SV{vertex=10, rank=1, index=0}}=(SV{vertex=00, rank=0, index=0},SV{vertex=10, rank=1, index=0}), SE{edge=1, source=SV{vertex=10, rank=1, index=0}, intermediateVertices=[], target=SV{vertex=20, rank=2, index=0}}=(SV{vertex=10, rank=1, index=0},SV{vertex=20, rank=2, index=0}), SE{edge=2, source=SV{vertex=00, rank=0, index=0}, intermediateVertices=[], target=SV{vertex=11, rank=1, index=1}}=(SV{vertex=00, rank=0, index=0},SV{vertex=11, rank=1, index=1}), SE{edge=3, source=SV{vertex=11, rank=1, index=1}, intermediateVertices=[], target=SV{vertex=21, rank=2, index=1}}=(SV{vertex=11, rank=1, index=1},SV{vertex=21, rank=2, index=1}), SE{edge=4, source=SV{vertex=01, rank=0, index=1}, intermediateVertices=[SyntheticVertex{vertex=1048855692, rank=1, index=3}], target=SV{vertex=20, rank=2, index=0}}= (SV{vertex=01, rank=0, index=1},SV{vertex=20, rank=2, index=0}), SE{edge=5, source=SV{vertex=20, rank=2, index=0}, intermediateVertices=[], target=SV{vertex=30, rank=3, index=0}}=(SV{vertex=20, rank=2, index=0},SV{vertex=30, rank=3, index=0}), SE{edge=6, source=SV{vertex=00, rank=0, index=0}, intermediateVertices=[SyntheticVertex{vertex=702061917, rank=1, index=2}, SyntheticVertex{vertex=1409545055, rank=2, index=2}], target=SV{vertex=30, rank=3, index=0}}= (SV{vertex=00, rank=0, index=0},SV{vertex=30, rank=3, index=0})]) */ // all edges for no skipped layers sgraph.edgeSet().forEach(this::testEdgeHasCorrectRanks); // test that the graph has 3 virtualVertices List<SyntheticLV<String>> virtualVertices = sgraph .vertexSet() .stream() .filter(v -> v instanceof SyntheticLV) .map(v -> (SyntheticLV<String>) v) .collect(Collectors.toList()); Assert.assertEquals(3, virtualVertices.size()); synthetics.makeArticulatedEdges(); // test that one edge has 2 intermediate vertices List<ArticulatedEdge<String, Integer>> articulatedEdges = sgraph .edgeSet() .stream() .filter( e -> e instanceof ArticulatedEdge && ((ArticulatedEdge) e).getIntermediateVertices().size() == 2) .map(e -> (ArticulatedEdge<String, Integer>) e) .collect(Collectors.toList()); Assert.assertEquals(1, articulatedEdges.size()); ArticulatedEdge<String, Integer> bentEdge = articulatedEdges.get(0); List<Integer> ranks = new ArrayList<>(); ranks.add(bentEdge.source.getRank()); ranks.addAll( bentEdge.getIntermediateVertices().stream().map(LV::getRank).collect(Collectors.toList())); ranks.add(bentEdge.target.getRank()); Assert.assertEquals(ranks, List.of(0, 1, 2, 3)); // test that one edge has 1 intermediate vertex articulatedEdges = sgraph .edgeSet() .stream() .filter( e -> e instanceof ArticulatedEdge && ((ArticulatedEdge) e).getIntermediateVertices().size() == 1) .map(e -> (ArticulatedEdge<String, Integer>) e) .collect(Collectors.toList()); Assert.assertEquals(1, articulatedEdges.size()); bentEdge = articulatedEdges.get(0); ranks = new ArrayList<>(); ranks.add(bentEdge.source.getRank()); ranks.addAll( bentEdge.getIntermediateVertices().stream().map(LV::getRank).collect(Collectors.toList())); ranks.add(bentEdge.target.getRank()); Assert.assertEquals(ranks, List.of(0, 1, 2)); log.info("dag vertices: {}", sgraph.vertexSet()); log.info("dag edges: {}", sgraph.edgeSet()); } private void testEdgeHasCorrectRanks(LE<String, Integer> edge) { List<Integer> ranks = new ArrayList<>(); ranks.add(edge.getSource().getRank()); if (edge instanceof ArticulatedEdge) { ranks.addAll( ((ArticulatedEdge<String, Integer>) edge) .getIntermediateVertices() .stream() .map(LV::getRank) .collect(Collectors.toList())); } ranks.add(edge.getTarget().getRank()); testConsecutive(ranks.stream().mapToInt(Integer::intValue).toArray()); } /** * ensure that every SV vertex has the rank and index data assigned that matches that vertex's * actual rank (layer number) and index (position in layer) * * @param layers */ private void checkLayers(List<List<LV<String>>> layers) { for (int i = 0; i < layers.size(); i++) { List<LV<String>> layer = layers.get(i); log.info("layer: {}", layer); for (int j = 0; j < layer.size(); j++) { LV<String> LV = layer.get(j); log.info("sv {},{}: {}", i, j, LV); Assert.assertEquals(i, LV.getRank()); Assert.assertEquals(j, LV.getIndex()); } } } private void testConsecutive(int[] array) { for (int i = 0; i < array.length - 1; i++) { Assert.assertEquals(array[i] + 1, array[i + 1]); } } public int testCountEdges(int[] tree, int n, int last) { if (n == last) return 0; int base = tree.length / 2; int pos = n + base; int sum = 0; while (pos >= 0) { if (pos % 2 != 0) { // odd sum += tree[pos - 1]; } pos /= 2; } return tree[0] - sum; } @Test public void testInsertionSortCounter() { int[] array = new int[] {0, 1, 2, 3, 4, 5}; int count = insertionSortCounter(array); log.info("count is {}", count); Assert.assertEquals(0, count); array = new int[] {0, 1, 2, 0, 3, 4, 0, 2, 3, 2, 4}; count = insertionSortCounter(array); log.info("count is {}", count); Assert.assertEquals(12, count); array = new int[] {0, 1, 3, 1, 2}; count = insertionSortCounter(array); log.info("count is {}", count); Assert.assertEquals(2, count); array = new int[] {1, 2, 0, 1, 3}; count = insertionSortCounter(array); log.info("count is {}", count); Assert.assertEquals(3, count); List<Integer> list = Arrays.asList(0, 1, 2, 0, 3, 4, 0, 2, 3, 2, 4); count = insertionSortCounter(list); log.info("count is {}", count); Assert.assertEquals(12, count); list = Arrays.asList(0, 1, 3, 1, 2); count = insertionSortCounter(list); log.info("count is {}", count); Assert.assertEquals(2, count); list = Arrays.asList(1, 2, 0, 1, 3); count = insertionSortCounter(list); log.info("count is {}", count); Assert.assertEquals(3, count); } private int insertionSortCounter(List<Integer> list) { int counter = 0; for (int i = 1; i < list.size(); i++) { int value = list.get(i); //array[i]; int j = i - 1; while (j >= 0 && list.get(j) > value) { list.set(j + 1, list.get(j)); counter++; j--; } list.set(j + 1, value); } return counter; } private int insertionSortCounter(int[] array) { int counter = 0; for (int i = 1; i < array.length; i++) { int value = array[i]; int j = i - 1; while (j >= 0 && array[j] > value) { array[j + 1] = array[j]; counter++; j--; } array[j + 1] = value; } return counter; } @Test public void testRemoveCycles() { // add some cycles graph.addEdge("20", "10"); graph.addEdge("21", "11"); // connect from rank 0 to rank 3. should add 3, subtract 1 graph.addEdge("20", "00"); log.info("graph expanded to {}", graph); // //add a couple of unconnected vertices graph.addVertex("loner1"); graph.addVertex("loner2"); RemoveCycles<String, Integer> removeCycles = new RemoveCycles(graph); Graph<String, Integer> dag = removeCycles.removeCycles(); log.info("feedback arcs: {}", removeCycles.getFeedbackEdges()); // remove the cycles i know i put in graph.removeEdge("20", "10"); graph.removeEdge("21", "11"); graph.removeEdge("20", "00"); Assert.assertEquals(graph, dag); } }
cidermole/yaca
src/x86/yaca-c/Template.h
#ifndef _TEMPLATE_H_ #define _TEMPLATE_H_ #include <map> #include <string> #include "Utils.h" using namespace std; class Template { private: string m_file; map<string, string> m_replace; public: Template(string file): m_file(file) {} void addKey(string key, string value) { m_replace.insert(pair<string, string>(key, value)); } string parse(); // throws const char* }; #endif /* _TEMPLATE_H_ */
happymanx/Weather_FFI
dcmtk-master2/dcmdata/libsrc/dcvr.cc
/* * * Copyright (C) 1994-2022, OFFIS e.V. * All rights reserved. See COPYRIGHT file for details. * * This software and supporting documentation were developed by * * OFFIS e.V. * R&D Division Health * Escherweg 2 * D-26121 Oldenburg, Germany * * * Module: dcmdata * * Author: <NAME>, <NAME>, <NAME> * * Purpose: class DcmVR: Value Representation * * */ #include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */ #include "dcmtk/dcmdata/dcvr.h" #include "dcmtk/dcmdata/dctypes.h" /* ** global flags */ OFGlobal<OFBool> dcmEnableUnknownVRGeneration(OFTrue); OFGlobal<OFBool> dcmEnableUnlimitedTextVRGeneration(OFTrue); OFGlobal<OFBool> dcmEnableOtherFloatVRGeneration(OFTrue); OFGlobal<OFBool> dcmEnableOtherDoubleVRGeneration(OFTrue); OFGlobal<OFBool> dcmEnableOtherLongVRGeneration(OFTrue); OFGlobal<OFBool> dcmEnableUniversalResourceIdentifierOrLocatorVRGeneration(OFTrue); OFGlobal<OFBool> dcmEnableUnlimitedCharactersVRGeneration(OFTrue); OFGlobal<OFBool> dcmEnableOther64bitVeryLongVRGeneration(OFTrue); OFGlobal<OFBool> dcmEnableSigned64bitVeryLongVRGeneration(OFTrue); OFGlobal<OFBool> dcmEnableUnsigned64bitVeryLongVRGeneration(OFTrue); OFGlobal<OFBool> dcmEnableUnknownVRConversion(OFFalse); /* ** global functions */ void dcmEnableGenerationOfNewVRs() { dcmEnableUnknownVRGeneration.set(OFTrue); dcmEnableUnlimitedTextVRGeneration.set(OFTrue); dcmEnableOtherFloatVRGeneration.set(OFTrue); dcmEnableOtherDoubleVRGeneration.set(OFTrue); dcmEnableOtherLongVRGeneration.set(OFTrue); dcmEnableUniversalResourceIdentifierOrLocatorVRGeneration.set(OFTrue); dcmEnableUnlimitedCharactersVRGeneration.set(OFTrue); dcmEnableOther64bitVeryLongVRGeneration.set(OFTrue); dcmEnableSigned64bitVeryLongVRGeneration.set(OFTrue); dcmEnableUnsigned64bitVeryLongVRGeneration.set(OFTrue); } void dcmDisableGenerationOfNewVRs() { dcmEnableUnknownVRGeneration.set(OFFalse); dcmEnableUnlimitedTextVRGeneration.set(OFFalse); dcmEnableOtherFloatVRGeneration.set(OFFalse); dcmEnableOtherDoubleVRGeneration.set(OFFalse); dcmEnableOtherLongVRGeneration.set(OFFalse); dcmEnableUniversalResourceIdentifierOrLocatorVRGeneration.set(OFFalse); dcmEnableUnlimitedCharactersVRGeneration.set(OFFalse); dcmEnableOther64bitVeryLongVRGeneration.set(OFFalse); dcmEnableSigned64bitVeryLongVRGeneration.set(OFFalse); dcmEnableUnsigned64bitVeryLongVRGeneration.set(OFFalse); } /* ** VR property table */ #define DCMVR_PROP_NONE 0x00 #define DCMVR_PROP_NONSTANDARD 0x01 #define DCMVR_PROP_INTERNAL 0x02 #define DCMVR_PROP_EXTENDEDLENGTHENCODING 0x04 #define DCMVR_PROP_ISASTRING 0x08 #define DCMVR_PROP_ISAFFECTEDBYCHARSET 0x10 #define DCMVR_PROP_ISLENGTHINCHAR 0x20 #define DCMVR_PROP_UNDEFINEDLENGTH 0x40 struct DcmVREntry { DcmEVR vr; // Enumeration Value of Value representation const char* vrName; // Name of Value representation const OFString* delimiterChars; // Delimiter characters, switch to default charset size_t fValWidth; // Length of minimal unit, used for swapping int propertyFlags; // Normal, internal, non-standard VR, etc. Uint32 minValueLength; // Minimum length of a single value (bytes or characters) Uint32 maxValueLength; // Maximum length of a single value (bytes or characters) }; static const OFString noDelimiters; // none static const OFString bsDelimiter("\\"); // backslash static const OFString pnDelimiters("\\^="); // person name static const DcmVREntry DcmVRDict[] = { { EVR_AE, "AE", &noDelimiters, sizeof(char), DCMVR_PROP_ISASTRING, 0, 16 }, { EVR_AS, "AS", &noDelimiters, sizeof(char), DCMVR_PROP_ISASTRING, 4, 4 }, { EVR_AT, "AT", &noDelimiters, sizeof(Uint16), DCMVR_PROP_NONE, 4, 4 }, { EVR_CS, "CS", &noDelimiters, sizeof(char), DCMVR_PROP_ISASTRING, 0, 16 }, { EVR_DA, "DA", &noDelimiters, sizeof(char), DCMVR_PROP_ISASTRING, 8, 10 }, { EVR_DS, "DS", &noDelimiters, sizeof(char), DCMVR_PROP_ISASTRING, 0, 16 }, { EVR_DT, "DT", &noDelimiters, sizeof(char), DCMVR_PROP_ISASTRING, 0, 26 }, { EVR_FL, "FL", &noDelimiters, sizeof(Float32), DCMVR_PROP_NONE, 4, 4 }, { EVR_FD, "FD", &noDelimiters, sizeof(Float64), DCMVR_PROP_NONE, 8, 8 }, { EVR_IS, "IS", &noDelimiters, sizeof(char), DCMVR_PROP_ISASTRING, 0, 12 }, { EVR_LO, "LO", &bsDelimiter, sizeof(char), DCMVR_PROP_ISASTRING | DCMVR_PROP_ISAFFECTEDBYCHARSET | DCMVR_PROP_ISLENGTHINCHAR, 0, 64 }, { EVR_LT, "LT", &noDelimiters, sizeof(char), DCMVR_PROP_ISASTRING | DCMVR_PROP_ISAFFECTEDBYCHARSET | DCMVR_PROP_ISLENGTHINCHAR, 0, 10240 }, { EVR_OB, "OB", &noDelimiters, sizeof(Uint8), DCMVR_PROP_EXTENDEDLENGTHENCODING | DCMVR_PROP_UNDEFINEDLENGTH, 0, 4294967294U }, { EVR_OD, "OD", &noDelimiters, sizeof(Float64), DCMVR_PROP_EXTENDEDLENGTHENCODING | DCMVR_PROP_UNDEFINEDLENGTH, 0, 4294967288U }, { EVR_OF, "OF", &noDelimiters, sizeof(Float32), DCMVR_PROP_EXTENDEDLENGTHENCODING | DCMVR_PROP_UNDEFINEDLENGTH, 0, 4294967292U }, { EVR_OL, "OL", &noDelimiters, sizeof(Uint32), DCMVR_PROP_EXTENDEDLENGTHENCODING | DCMVR_PROP_UNDEFINEDLENGTH, 0, 4294967292U }, { EVR_OV, "OV", &noDelimiters, sizeof(Uint64), DCMVR_PROP_EXTENDEDLENGTHENCODING | DCMVR_PROP_UNDEFINEDLENGTH, 0, 4294967288U }, { EVR_OW, "OW", &noDelimiters, sizeof(Uint16), DCMVR_PROP_EXTENDEDLENGTHENCODING | DCMVR_PROP_UNDEFINEDLENGTH, 0, 4294967294U }, { EVR_PN, "PN", &pnDelimiters, sizeof(char), DCMVR_PROP_ISASTRING | DCMVR_PROP_ISAFFECTEDBYCHARSET | DCMVR_PROP_ISLENGTHINCHAR, 0, 64 }, { EVR_SH, "SH", &bsDelimiter, sizeof(char), DCMVR_PROP_ISASTRING | DCMVR_PROP_ISAFFECTEDBYCHARSET | DCMVR_PROP_ISLENGTHINCHAR, 0, 16 }, { EVR_SL, "SL", &noDelimiters, sizeof(Sint32), DCMVR_PROP_NONE, 4, 4 }, { EVR_SQ, "SQ", &noDelimiters, 0, DCMVR_PROP_EXTENDEDLENGTHENCODING | DCMVR_PROP_UNDEFINEDLENGTH, 0, 4294967294U }, { EVR_SS, "SS", &noDelimiters, sizeof(Sint16), DCMVR_PROP_NONE, 2, 2 }, { EVR_ST, "ST", &noDelimiters, sizeof(char), DCMVR_PROP_ISASTRING | DCMVR_PROP_ISAFFECTEDBYCHARSET | DCMVR_PROP_ISLENGTHINCHAR, 0, 1024 }, { EVR_SV, "SV", &noDelimiters, sizeof(Sint64), DCMVR_PROP_EXTENDEDLENGTHENCODING, 8, 8 }, { EVR_TM, "TM", &noDelimiters, sizeof(char), DCMVR_PROP_ISASTRING, 0, 16 }, { EVR_UC, "UC", &bsDelimiter, sizeof(char), DCMVR_PROP_ISASTRING | DCMVR_PROP_EXTENDEDLENGTHENCODING | DCMVR_PROP_ISAFFECTEDBYCHARSET, 0, 4294967294U }, { EVR_UI, "UI", &noDelimiters, sizeof(char), DCMVR_PROP_ISASTRING, 0, 64 }, { EVR_UL, "UL", &noDelimiters, sizeof(Uint32), DCMVR_PROP_NONE, 4, 4 }, { EVR_UR, "UR", &noDelimiters, sizeof(char), DCMVR_PROP_ISASTRING|DCMVR_PROP_EXTENDEDLENGTHENCODING, 0, 4294967294U }, { EVR_US, "US", &noDelimiters, sizeof(Uint16), DCMVR_PROP_NONE, 2, 2 }, { EVR_UT, "UT", &noDelimiters, sizeof(char), DCMVR_PROP_ISASTRING | DCMVR_PROP_EXTENDEDLENGTHENCODING | DCMVR_PROP_ISAFFECTEDBYCHARSET, 0, 4294967294U }, { EVR_UV, "UV", &noDelimiters, sizeof(Uint64), DCMVR_PROP_EXTENDEDLENGTHENCODING, 8, 8 }, { EVR_ox, "ox", &noDelimiters, sizeof(Uint8), DCMVR_PROP_NONSTANDARD | DCMVR_PROP_EXTENDEDLENGTHENCODING | DCMVR_PROP_UNDEFINEDLENGTH, 0, 4294967294U }, { EVR_px, "px", &noDelimiters, sizeof(Uint8), DCMVR_PROP_NONSTANDARD | DCMVR_PROP_EXTENDEDLENGTHENCODING | DCMVR_PROP_UNDEFINEDLENGTH, 0, 4294967294U }, { EVR_xs, "xs", &noDelimiters, sizeof(Uint16), DCMVR_PROP_NONSTANDARD, 2, 2 }, { EVR_lt, "lt", &noDelimiters, sizeof(Uint16), DCMVR_PROP_NONSTANDARD | DCMVR_PROP_EXTENDEDLENGTHENCODING, 0, 4294967294U }, { EVR_na, "na", &noDelimiters, 0, DCMVR_PROP_NONSTANDARD, 0, 0 }, { EVR_up, "up", &noDelimiters, sizeof(Uint32), DCMVR_PROP_NONSTANDARD, 4, 4 }, /* unique prefixes have been "invented" for the following internal VRs */ { EVR_item, "it_EVR_item", &noDelimiters, 0, DCMVR_PROP_NONSTANDARD | DCMVR_PROP_INTERNAL, 0, 0 }, { EVR_metainfo, "mi_EVR_metainfo", &noDelimiters, 0, DCMVR_PROP_NONSTANDARD | DCMVR_PROP_INTERNAL, 0, 0 }, { EVR_dataset, "ds_EVR_dataset", &noDelimiters, 0, DCMVR_PROP_NONSTANDARD | DCMVR_PROP_INTERNAL, 0, 0 }, { EVR_fileFormat, "ff_EVR_fileFormat", &noDelimiters, 0, DCMVR_PROP_NONSTANDARD | DCMVR_PROP_INTERNAL, 0, 0 }, { EVR_dicomDir, "dd_EVR_dicomDir", &noDelimiters, 0, DCMVR_PROP_NONSTANDARD | DCMVR_PROP_INTERNAL, 0, 0 }, { EVR_dirRecord, "dr_EVR_dirRecord", &noDelimiters, 0, DCMVR_PROP_NONSTANDARD | DCMVR_PROP_INTERNAL, 0, 0 }, { EVR_pixelSQ, "ps_EVR_pixelSQ", &noDelimiters, sizeof(Uint8), DCMVR_PROP_NONSTANDARD | DCMVR_PROP_INTERNAL, 0, DCM_UndefinedLength }, /* Moved from internal use to non standard only: necessary to distinguish from "normal" OB */ { EVR_pixelItem, "pi", &noDelimiters, sizeof(Uint8), DCMVR_PROP_NONSTANDARD, 0, DCM_UndefinedLength }, /* EVR_UNKNOWN (i.e. "future" VRs) should be mapped to UN or OB */ { EVR_UNKNOWN, "??", &noDelimiters, sizeof(Uint8), DCMVR_PROP_NONSTANDARD | DCMVR_PROP_INTERNAL | DCMVR_PROP_EXTENDEDLENGTHENCODING | DCMVR_PROP_UNDEFINEDLENGTH, 0, DCM_UndefinedLength }, /* Unknown Value Representation */ { EVR_UN, "UN", &noDelimiters, sizeof(Uint8), DCMVR_PROP_EXTENDEDLENGTHENCODING | DCMVR_PROP_UNDEFINEDLENGTH, 0, 4294967294U }, /* Pixel Data - only used in ident() */ { EVR_PixelData, "PixelData", &noDelimiters, 0, DCMVR_PROP_INTERNAL, 0, DCM_UndefinedLength }, /* Overlay Data - only used in ident() */ { EVR_OverlayData, "OverlayData", &noDelimiters, 0, DCMVR_PROP_INTERNAL, 0, DCM_UndefinedLength }, /* illegal VRs, we assume no extended length coding */ { EVR_UNKNOWN2B, "??", &noDelimiters, sizeof(Uint8), DCMVR_PROP_NONSTANDARD | DCMVR_PROP_INTERNAL, 0, DCM_UndefinedLength }, }; static const int DcmVRDict_DIM = OFstatic_cast(int, sizeof(DcmVRDict) / sizeof(DcmVREntry)); /* ** Check the consistency of the DcmVRDict */ #ifdef DEBUG #include "dcmtk/ofstd/ofstream.h" class DcmVRDict_checker { private: int error_found; public: DcmVRDict_checker(); }; DcmVRDict_checker::DcmVRDict_checker() : error_found(OFFalse) { for (int i = 0; i < DcmVRDict_DIM; i++) { if (DcmVRDict[i].vr != i) { error_found = OFTrue; DCMDATA_FATAL("DcmVRDict: Internal ERROR: inconsistent indexing: " << DcmVRDict[i].vrName); abort(); } } } const DcmVRDict_checker DcmVRDict_startup_check(); #endif /* ** DcmVR member functions */ void DcmVR::setVR(DcmEVR evr) { if ((OFstatic_cast(int, evr) >= 0) && (OFstatic_cast(int, evr) < DcmVRDict_DIM)) { vr = evr; } else { vr = EVR_UNKNOWN; } } void DcmVR::setVR(const char* vrName) { vr = EVR_UNKNOWN; /* default */ if (vrName != NULL) { int found = OFFalse; int i = 0; for (i = 0; (!found && (i < DcmVRDict_DIM)); i++) { /* We only compare the first two characters of the passed string and * never accept a VR that is labeled for internal use only. */ if ((strncmp(vrName, DcmVRDict[i].vrName, 2) == 0) && !(DcmVRDict[i].propertyFlags & DCMVR_PROP_INTERNAL)) { found = OFTrue; vr = DcmVRDict[i].vr; } } /* Workaround: There have been reports of systems transmitting * illegal VR strings in explicit VR (i.e. "??") without using * extended length fields. This is particularly bad because the * DICOM committee has announced that all future VRs will use * extended length. In order to distinguish between these two * variants, we treat all unknown VRs consisting of uppercase * letters as "real" future VRs (and thus assume extended length). * All other VR strings are treated as "illegal" VRs. */ char c1 = *vrName; char c2 = (c1) ? (*(vrName + 1)) : ('\0'); if ((c1 == '?') && (c2 == '?')) vr = EVR_UNKNOWN2B; if (!found && ((c1 < 'A') || (c1 > 'Z') || (c2 < 'A') || (c2 > 'Z'))) vr = EVR_UNKNOWN2B; } } DcmEVR DcmVR::getValidEVR() const { DcmEVR evr = EVR_UNKNOWN; if (isStandard()) { evr = vr; } else { switch (vr) { case EVR_up: evr = EVR_UL; break; case EVR_xs: evr = EVR_US; break; case EVR_lt: evr = EVR_OW; break; case EVR_ox: case EVR_px: case EVR_pixelSQ: evr = EVR_OB; break; default: evr = EVR_UN; /* handle as Unknown VR */ break; } } /* ** If the generation of post-1993 VRs is not globally enabled then use OB instead. ** We may not want to generate these "new" VRs if other software cannot handle it. */ DcmEVR oldVR = evr; switch (evr) { case EVR_UN: if (!dcmEnableUnknownVRGeneration.get()) evr = EVR_OB; /* handle UN as if OB */ break; case EVR_UT: if (!dcmEnableUnlimitedTextVRGeneration.get()) { if (dcmEnableUnknownVRGeneration.get()) evr = EVR_UN; /* handle UT as if UN */ else evr = EVR_OB; /* handle UT as if OB */ } break; case EVR_OF: if (!dcmEnableOtherFloatVRGeneration.get()) { if (dcmEnableUnknownVRGeneration.get()) evr = EVR_UN; /* handle OF as if UN */ else evr = EVR_OB; /* handle OF as if OB */ } break; case EVR_OD: if (!dcmEnableOtherDoubleVRGeneration.get()) { if (dcmEnableUnknownVRGeneration.get()) evr = EVR_UN; /* handle OD as if UN */ else evr = EVR_OB; /* handle OD as if OB */ } break; case EVR_OL: if (!dcmEnableOtherLongVRGeneration.get()) { if (dcmEnableUnknownVRGeneration.get()) evr = EVR_UN; /* handle OL as if UN */ else evr = EVR_OB; /* handle OL as if OB */ } break; case EVR_UR: if (!dcmEnableUniversalResourceIdentifierOrLocatorVRGeneration.get()) { if (dcmEnableUnlimitedTextVRGeneration.get()) evr = EVR_UT; /* handle UR as if UT */ else if (dcmEnableUnknownVRGeneration.get()) evr = EVR_UN; /* handle UR as if UN */ else evr = EVR_OB; /* handle UR as if OB */ } break; case EVR_UC: if (!dcmEnableUnlimitedCharactersVRGeneration.get()) { if (dcmEnableUnknownVRGeneration.get()) evr = EVR_UN; /* handle UC as if UN */ else evr = EVR_OB; /* handle UC as if OB */ } break; case EVR_OV: if (!dcmEnableOther64bitVeryLongVRGeneration.get()) { if (dcmEnableUnknownVRGeneration.get()) evr = EVR_UN; /* handle OV as if UN */ else evr = EVR_OB; /* handle OV as if OB */ } break; case EVR_SV: if (!dcmEnableSigned64bitVeryLongVRGeneration.get()) { if (dcmEnableUnknownVRGeneration.get()) evr = EVR_UN; /* handle SV as if UN */ else evr = EVR_OB; /* handle SV as if OB */ } break; case EVR_UV: if (!dcmEnableUnsigned64bitVeryLongVRGeneration.get()) { if (dcmEnableUnknownVRGeneration.get()) evr = EVR_UN; /* handle UV as if UN */ else evr = EVR_OB; /* handle UV as if OB */ } break; default: /* in all other cases, do nothing */ break; } if (oldVR != evr) { DCMDATA_TRACE("DcmVR::getValidEVR() VR=\"" << DcmVR(oldVR).getVRName() << "\" replaced by \"" << DcmVR(evr).getVRName() << "\" since support is disabled"); } return evr; } size_t DcmVR::getValueWidth(void) const { return DcmVRDict[vr].fValWidth; } const char* DcmVR::getVRName() const { return DcmVRDict[vr].vrName; } const char* DcmVR::getValidVRName() const { DcmVR avr(getValidEVR()); return avr.getVRName(); } OFBool DcmVR::isStandard() const { return (DcmVRDict[vr].propertyFlags & DCMVR_PROP_NONSTANDARD) ? OFFalse : OFTrue; } OFBool DcmVR::isForInternalUseOnly() const { return (DcmVRDict[vr].propertyFlags & DCMVR_PROP_INTERNAL) ? OFTrue : OFFalse; } /* returns true if VR represents a string */ OFBool DcmVR::isaString() const { return (DcmVRDict[vr].propertyFlags & DCMVR_PROP_ISASTRING) ? OFTrue : OFFalse; } /* * returns true if VR uses an extended length encoding * for explicit transfer syntaxes */ OFBool DcmVR::usesExtendedLengthEncoding() const { return (DcmVRDict[vr].propertyFlags & DCMVR_PROP_EXTENDEDLENGTHENCODING) ? OFTrue : OFFalse; } /* returns true if VR supports undefined length */ OFBool DcmVR::supportsUndefinedLength() const { return (DcmVRDict[vr].propertyFlags & DCMVR_PROP_UNDEFINEDLENGTH) ? OFTrue : OFFalse; } Uint32 DcmVR::getMinValueLength() const { return (DcmVRDict[vr].minValueLength); } Uint32 DcmVR::getMaxValueLength() const { return (DcmVRDict[vr].maxValueLength); } /* returns true if the VR is equivalent */ OFBool DcmVR::isEquivalent(const DcmVR& avr) const { DcmEVR evr = avr.getEVR(); if (vr == evr) return OFTrue; OFBool result = OFFalse; switch (vr) { case EVR_ox: case EVR_px: result = (evr == EVR_OB || evr == EVR_OW); break; case EVR_lt: result = (evr == EVR_OW || evr == EVR_US || evr == EVR_SS); break; case EVR_OB: result = (evr == EVR_ox || evr == EVR_px); break; case EVR_OW: result = (evr == EVR_ox || evr == EVR_px || evr == EVR_lt); break; case EVR_up: result = (evr == EVR_UL); break; case EVR_UL: result = (evr == EVR_up); break; case EVR_xs: result = (evr == EVR_SS || evr == EVR_US); break; case EVR_SS: case EVR_US: result = (evr == EVR_xs || evr == EVR_lt); break; default: break; } return result; } OFBool DcmVR::isAffectedBySpecificCharacterSet() const { return (DcmVRDict[vr].propertyFlags & DCMVR_PROP_ISAFFECTEDBYCHARSET) ? OFTrue : OFFalse; } const OFString& DcmVR::getDelimiterChars() const { return *DcmVRDict[vr].delimiterChars; } /* returns true if VR length is in char */ OFBool DcmVR::isLengthInChar() const { return (DcmVRDict[vr].propertyFlags & DCMVR_PROP_ISLENGTHINCHAR) ? OFTrue : OFFalse; }
dinvlad/jade-data-repo
src/test/java/bio/terra/common/FutureUtilsTest.java
package bio.terra.common; import bio.terra.common.category.Unit; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.IterableUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import java.util.stream.IntStream; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc @Category(Unit.class) public class FutureUtilsTest { private static Logger logger = LoggerFactory.getLogger(FutureUtilsTest.class); private ThreadPoolExecutor executorService; @Before public void setUp() throws Exception { executorService = new ThreadPoolExecutor( 3, 3, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(10) ); } @After public void afterClass() throws Exception { if (executorService != null) { executorService.shutdownNow(); } } @Test public void testWaitForTasks() { final AtomicInteger counter = new AtomicInteger(0); final Callable<Integer> action = () -> { try { TimeUnit.SECONDS.sleep(1); return counter.getAndIncrement(); } catch (InterruptedException e) { throw new RuntimeException(e); } }; final List<Future<Integer>> futures = new ArrayList<>(); for (int i = 0; i < 10; i++) { futures.add(executorService.submit(action)); } final List<Integer> resolved = FutureUtils.waitFor(futures); assertThat(resolved).containsAll(IntStream.range(0, 10).boxed().collect(Collectors.toList())); assertThat(executorService.getActiveCount()).isZero(); } @Test public void testWaitForTaskAcrossTwoBatches() throws InterruptedException { // Tests two batches of actions being submitted. The second batch should be shorter (note the sleep). Ensure // that it properly finishes before the first batch and that an exception doesn't cause the first batch to fail // Expand the thread queue for this particular test if (executorService != null) { executorService.shutdown(); } executorService = new ThreadPoolExecutor( 10, 10, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(10) ); final AtomicInteger counter1 = new AtomicInteger(0); final Callable<Integer> action1 = () -> { try { TimeUnit.SECONDS.sleep(10); return counter1.getAndIncrement(); } catch (InterruptedException e) { throw new RuntimeException(e); } }; final AtomicInteger counter2 = new AtomicInteger(0); final Callable<Integer> action2 = () -> { try { if (counter2.get() == 0) { throw new RuntimeException("Injected error"); } TimeUnit.MILLISECONDS.sleep(500); return counter2.getAndIncrement(); } catch (InterruptedException e) { throw new RuntimeException(e); } }; // Submit the two batches final List<Future<Integer>> batch1Futures = new ArrayList<>(); for (int i = 0; i < 3; i++) { batch1Futures.add(executorService.submit(action1)); } final List<Future<Integer>> batch2Futures = new ArrayList<>(); for (int i = 0; i < 5; i++) { batch2Futures.add(executorService.submit(action2)); } assertThatThrownBy(() -> FutureUtils.waitFor(batch2Futures)); // There should still be at least 3 services running (from the first batch) assertThat(executorService.getActiveCount()).isGreaterThanOrEqualTo(3); // Make sure that all tasks from the first batch are still running assertThat(CollectionUtils.collect(batch1Futures, Future::isDone)).doesNotContain(true); final List<Integer> resolved1 = FutureUtils.waitFor(batch1Futures); assertThat(resolved1).containsAll(IntStream.range(0, 3).boxed().collect(Collectors.toList())); assertThat(executorService.getActiveCount()).isZero(); } @Test public void testWaitForTasksSomeFail() throws InterruptedException { final AtomicInteger counter = new AtomicInteger(0); final Callable<Integer> action = () -> { try { final int count = counter.getAndIncrement(); if (count == 5) { throw new RuntimeException("Injected error"); } TimeUnit.SECONDS.sleep(1); return count; } catch (InterruptedException e) { throw new RuntimeException(e); } }; final List<Future<Integer>> futures = new ArrayList<>(); for (int i = 0; i < 10; i++) { futures.add(executorService.submit(action)); } assertThatThrownBy(() -> FutureUtils.waitFor(futures)).hasMessage("Error executing thread"); // Note: adding a sleep since getActiveCount represents an approximation of the number of threads active. // Pausing gives the thread executor a chance to learn that the thread has been canceled TimeUnit.MILLISECONDS.sleep(50); assertThat(executorService.getActiveCount()).isZero(); // Make sure that some tasks after the failure were cancelled assertThat(IterableUtils.countMatches(futures, Future::isCancelled)).isPositive(); } @Test public void testThreadTimeoutFailure() throws InterruptedException { final AtomicInteger counter = new AtomicInteger(0); // Note: Logging statements left in to make understanding test runs easier final Callable<Integer> action = () -> { try { // On the first iteration, to cause a failure final int count = counter.getAndIncrement(); logger.info("Launching {}", count); if (count == 0) { TimeUnit.SECONDS.sleep(1); } else { // This should allow all other threads to complete successfully TimeUnit.MILLISECONDS.sleep(10); } logger.info("Done with {}", count); return count; } catch (InterruptedException e) { throw new RuntimeException(e); } }; final List<Future<Integer>> futures = new ArrayList<>(); for (int i = 0; i < 5; i++) { futures.add(executorService.submit(action)); } assertThatThrownBy(() -> FutureUtils.waitFor(futures, Optional.of(Duration.ofMillis(100)))) .hasMessage("Thread timed out"); // Note: adding a sleep since getActiveCount represents an approximation of the number of threads active. // Pausing gives the thread executor a chance to learn that the thread has been canceled TimeUnit.MILLISECONDS.sleep(50); assertThat(executorService.getActiveCount()).isZero(); } @Test public void testMaxOutQueue() { final AtomicInteger counter = new AtomicInteger(0); final Callable<Integer> action = () -> { try { TimeUnit.MILLISECONDS.sleep(100); return counter.getAndIncrement(); } catch (InterruptedException e) { throw new RuntimeException(e); } }; final List<Future<Integer>> futures = new ArrayList<>(); // Note: we can submit up to 3 running + 10 queue tasks for (int i = 0; i < 13; i++) { futures.add(executorService.submit(action)); } // Can't accept new threads for now assertThatThrownBy(() -> futures.add(executorService.submit(action))); final List<Integer> resolved = FutureUtils.waitFor(futures); assertThat(resolved).containsAll(IntStream.range(0, 13).boxed().collect(Collectors.toList())); futures.clear(); // Now that queue is empty, we can for (int i = 0; i < 10; i++) { futures.add(executorService.submit(action)); } final List<Integer> resolvedSecondRound = FutureUtils.waitFor(futures); assertThat(resolvedSecondRound).containsAll(IntStream.range(13, 23).boxed().collect(Collectors.toList())); assertThat(executorService.getActiveCount()).isZero(); } }
becca-bailey/amphtml
3p/vendors/embedly.js
<reponame>becca-bailey/amphtml // src/polyfills.js must be the first import. import '#3p/polyfills'; import {register} from '#3p/3p'; import {embedly} from '#3p/embedly'; import {draw3p, init} from '#3p/integration-lib'; init(window); register('embedly', embedly); window.draw3p = draw3p;
albanoj2/robinhood-api
src/main/java/com/ampro/robinhood/endpoint/account/data/BasicAccountHolderInfoElement.java
<reponame>albanoj2/robinhood-api package com.ampro.robinhood.endpoint.account.data; import com.ampro.robinhood.endpoint.ApiElement; public class BasicAccountHolderInfoElement implements ApiElement { private String address; private String citizenship; private String city; private String country_of_residence; private String date_of_birth; private String marital_status; private int number_dependents; private long phone_number; private String state; private int tax_id_ssn; //TODO: updated_at private int zipcode; @Override public boolean requiresAuth() { return true; } /** * @return the address */ public String getAddress() { return address; } /** * @return the citizenship */ public String getCitizenship() { return citizenship; } /** * @return the city */ public String getCity() { return city; } /** * @return the country_of_residence */ public String getCountryOfResidence() { return country_of_residence; } /** * @return the date_of_birth */ public String getDateOfBirth() { return date_of_birth; } /** * @return the marital_status */ public String getMaritalStatus() { return marital_status; } /** * @return the number_dependents */ public int getNumberDependents() { return number_dependents; } /** * @return the phone_number */ public long getPhoneNumber() { return phone_number; } /** * @return the state */ public String getState() { return state; } /** * @return the tax_id_ssn */ public int getTaxIdSsn() { return tax_id_ssn; } /** * @return the zipcode */ public int getZipcode() { return zipcode; } }
bprevost/brad_demo
frc/network_tables/nt_driver_station_example.py
#!/usr/bin/env python3 '''This is a NetworkTables client (driver station or coprocessor side).''' import time from networktables import NetworkTables import logging # To see messages from networktables, you must setup logging logging.basicConfig(level=logging.DEBUG) NetworkTables.initialize(server='192.168.1.21') sd = NetworkTables.getTable("SmartDashboard") dsTime = 0 while True: sd.putNumber("dsTime", dsTime) dsTime += 1 robotTime = sd.getNumber("robotTime", "N/A") print("robotTime:", robotTime) time.sleep(1)
srinivasankavitha/js-graphql-intellij-plugin
src/main/com/intellij/lang/jsgraphql/ide/injection/GraphQLCommentBasedInjectionHelper.java
/* * Copyright (c) 2019-present, <NAME> * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.intellij.lang.jsgraphql.ide.injection; import com.intellij.openapi.application.ApplicationManager; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; public interface GraphQLCommentBasedInjectionHelper { static GraphQLCommentBasedInjectionHelper getInstance() { return ApplicationManager.getApplication().getService(GraphQLCommentBasedInjectionHelper.class); } /** * Gets whether the specified host element has a GraphQL injection based a language=GraphQL comment * * @param host the host to check * @return <code>true</code> if the host has an active GraphQL injection, <code>false</code> otherwise */ boolean isGraphQLInjectedUsingComment(@NotNull PsiElement host); }
meringu/terraform-private-registry
internal/api/v1/modules.go
<reponame>meringu/terraform-private-registry<filename>internal/api/v1/modules.go package v1 import "time" // ListMeta is the meta fielt for a list response type ListMeta struct { Limit int `json:"limit"` CurrentOffset int `json:"current_offset"` NextOffset int `json:"next_offset,omitempty"` NextURL string `json:"next_url,omitempty"` PrevOffset int `json:"prev_offset,omitempty"` PrevURL string `json:"prev_url,omitempty"` } // Module is is a Terraform Moudle type Module struct { ID string `json:"id"` Owner string `json:"owner"` Namespace string `json:"namespace"` Name string `json:"name"` Version string `json:"version"` Provider string `json:"provider"` Description string `json:"description"` Source string `json:"source"` Tag string `json:"tag,omitempty"` PublishedAt time.Time `json:"published_at"` Downloads int64 `json:"downloads"` Verified bool `json:"verified"` Root ModuleVersionDetailed `json:"root,omitmpty"` Submodules []ModuleVersionDetailed `json:"submodule,omitempty"` Examples []ModuleVersionDetailed `json:"examples,omitempty"` Providers []string `json:"providers,omitempty"` Versions []string `json:"versions,omitempty"` } // GetModuleVersionResponse is the response for getting a module type GetModuleVersionResponse struct { Module } // ListModulesResponse is the response for listing the modules type ListModulesResponse struct { Meta ListMeta `json:"meta"` Modules []Module `json:"modules"` } // ListModuleVersionsResponse is the response for listing a module's versions type ListModuleVersionsResponse struct { Modules []ModuleDetailed `json:"modules"` } // ModuleDetailed contians the module versions type ModuleDetailed struct { Source string `json:"source"` Versions []ModuleVersion `json:"versions"` } // ModuleVersion contains the module verion information type ModuleVersion struct { Version string `json:"version"` Root ModuleVersionDetailed `json:"root"` Submodules []ModuleVersionDetailed `json:"submodules"` } // ModuleVersionDetailed contains detailed infomation about just that module type ModuleVersionDetailed struct { Path string `json:"path,omitempty"` Name string `json:"name,omitempty"` Readme string `json:"readme,omitempty"` Providers []Provider `json:"providers"` Empty bool `json:"empty,omitempty"` Inputs []Input `json:"inputs,omitempty"` Outputs []Output `json:"outputs,omitempty"` Dependencies []Dependency `json:"dependencies"` Resources []Resource `json:"resources,omitempty"` } // Input of a Terraform module type Input struct { Name string `json:"name"` Type string `json:"type"` Description string `json:"description"` Default string `json:"default"` Required bool `json:"required"` } // Output of a Terraform module type Output struct { Name string `json:"name"` Description string `json:"description"` } // Resource of a Terraform module type Resource struct { Name string `json:"name"` Type string `json:"type"` } // Provider is information about the provider in a module type Provider struct { Name string `json:"name"` Version string `json:"string"` } // Dependency is a module that is used from another module type Dependency struct { Name string `json:"name"` Source string `json:"source"` Version string `json:"version"` }
zipated/src
third_party/mesa/src/src/gallium/drivers/softpipe/sp_tex_sample.h
<reponame>zipated/src /************************************************************************** * * Copyright 2007 Tungsten Graphics, Inc., <NAME>, Texas. * All Rights Reserved. * Copyright 2010 VMware, Inc. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sub license, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS BE LIABLE FOR * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * **************************************************************************/ #ifndef SP_TEX_SAMPLE_H #define SP_TEX_SAMPLE_H #include "tgsi/tgsi_exec.h" struct sp_sampler_variant; typedef void (*wrap_nearest_func)(float s, unsigned size, int *icoord); typedef void (*wrap_linear_func)(float s, unsigned size, int *icoord0, int *icoord1, float *w); typedef float (*compute_lambda_func)(const struct sp_sampler_variant *sampler, const float s[TGSI_QUAD_SIZE], const float t[TGSI_QUAD_SIZE], const float p[TGSI_QUAD_SIZE]); typedef void (*img_filter_func)(struct tgsi_sampler *tgsi_sampler, float s, float t, float p, unsigned level, unsigned face_id, enum tgsi_sampler_control control, float *rgba); typedef void (*filter_func)(struct tgsi_sampler *tgsi_sampler, const float s[TGSI_QUAD_SIZE], const float t[TGSI_QUAD_SIZE], const float p[TGSI_QUAD_SIZE], const float c0[TGSI_QUAD_SIZE], enum tgsi_sampler_control control, float rgba[TGSI_NUM_CHANNELS][TGSI_QUAD_SIZE]); union sp_sampler_key { struct { unsigned target:3; unsigned is_pot:1; unsigned processor:2; unsigned unit:4; unsigned swizzle_r:3; unsigned swizzle_g:3; unsigned swizzle_b:3; unsigned swizzle_a:3; unsigned pad:10; } bits; unsigned value; }; /** * Subclass of tgsi_sampler */ struct sp_sampler_variant { struct tgsi_sampler base; /**< base class */ union sp_sampler_key key; /* The owner of this struct: */ const struct pipe_sampler_state *sampler; /* Currently bound texture: */ const struct pipe_sampler_view *view; struct softpipe_tex_tile_cache *cache; unsigned processor; /* For sp_get_samples_2d_linear_POT: */ unsigned xpot; unsigned ypot; unsigned faces[TGSI_QUAD_SIZE]; wrap_nearest_func nearest_texcoord_s; wrap_nearest_func nearest_texcoord_t; wrap_nearest_func nearest_texcoord_p; wrap_linear_func linear_texcoord_s; wrap_linear_func linear_texcoord_t; wrap_linear_func linear_texcoord_p; img_filter_func min_img_filter; img_filter_func mag_img_filter; compute_lambda_func compute_lambda; filter_func mip_filter; filter_func compare; filter_func sample_target; /* Linked list: */ struct sp_sampler_variant *next; }; struct sp_sampler; /* Create a sampler variant for a given set of non-orthogonal state. Currently the */ struct sp_sampler_variant * sp_create_sampler_variant( const struct pipe_sampler_state *sampler, const union sp_sampler_key key ); void sp_sampler_variant_bind_view( struct sp_sampler_variant *variant, struct softpipe_tex_tile_cache *tex_cache, const struct pipe_sampler_view *view ); void sp_sampler_variant_destroy( struct sp_sampler_variant * ); static INLINE struct sp_sampler_variant * sp_sampler_variant(const struct tgsi_sampler *sampler) { return (struct sp_sampler_variant *) sampler; } extern void sp_get_samples(struct tgsi_sampler *tgsi_sampler, const float s[TGSI_QUAD_SIZE], const float t[TGSI_QUAD_SIZE], const float p[TGSI_QUAD_SIZE], float lodbias, float rgba[TGSI_NUM_CHANNELS][TGSI_QUAD_SIZE]); #endif /* SP_TEX_SAMPLE_H */
MarioA-PM/scrabble-MarioA-PM
src/main/java/cl/uchile/dcc/scrabble/types/number/TBinary.java
<reponame>MarioA-PM/scrabble-MarioA-PM package cl.uchile.dcc.scrabble.types.number; import cl.uchile.dcc.scrabble.flyweightFactory.*; import cl.uchile.dcc.scrabble.types.*; import cl.uchile.dcc.scrabble.Operations.*; import java.util.Objects; /** * Class that represents a binary number. */ public class TBinary extends AbstractType { private final String b; private final FlyweightTBinaryFactory binFac = FlyweightTBinaryFactory.getInstance(); private final FlyweightTIntFactory intFac = FlyweightTIntFactory.getInstance(); private final FlyweightTFloatFactory floatFac = FlyweightTFloatFactory.getInstance(); private final FlyweightTStringFactory stringFac = FlyweightTStringFactory.getInstance(); private final FlyweightTBoolFactory boolFac = FlyweightTBoolFactory.getInstance(); public TBinary(String b) { this.b = b; } public String getValue() { return b; } @Override public String toString() { return getValue(); } /** * The objects are equal if they represent the same number * Example: 0110 = 0000110 */ @Override public boolean equals(Object o) { if (!(o instanceof TBinary)) { return false; } TBinary bin = (TBinary) o; if (this.getValue().equals(bin.getValue())) { return true; } if (!((this.getValue()).charAt(0) == ((bin.getValue()).charAt(0)))) { return false; } return this.toInt(this.getValue()) == this.toInt(bin.getValue()); } @Override public int hashCode() { return Objects.hash(TBinary.class, this.toInt(getValue())); } @Override public TString toTString() { return stringFac.getTString(this.getValue()); } @Override public IType suma(IType n) { return n.sumarABin(this); } @Override public IType resta(IType n) { return n.restarABin(this); } @Override public IType mult(IType n) { return n.multABin(this); } @Override public IType div(IType n) { return n.divABin(this); } /** * Returns the integer representation of the binary. */ private int toInt(String binary) { if (bitToInt(binary.charAt(0)) == 0) { return positiveBinToInt(binary); } else { return negativeBinaryToInt(binary); } } /** * Converts the binary String representing a negative integer to integer. */ private int negativeBinaryToInt(String binary) { int n = binary.length() - 1; int w = (int) (-bitToInt(binary.charAt(0)) * Math.pow(2, n)); for (int i = n, j = 0; i > 0; i--, j++) { w += (int) Math.pow(2, j) * (binary.charAt(i) == '1' ? 1 : 0); } return w; } /** * Converts the binary String representing a positive integer to integer. */ private int positiveBinToInt(String binary) { int w = 0; for (int i = binary.length() - 1, j = 0; i > 0; i--, j++) { w += (int) Math.pow(2, j) * bitToInt(binary.charAt(i)); } return w; } /** * Converts the char value to int. */ private int bitToInt(char bit) { return bit == '0' ? 0 : 1; } @Override public TBinary sumarABin(TBinary n) { return (intFac.getTInt(n.toTInt().getValue() + this.toTInt().getValue())).toTBinary(); } @Override public TBinary restarABin(TBinary n) { return (intFac.getTInt(n.toTInt().getValue() - this.toTInt().getValue())).toTBinary(); } @Override public TBinary multABin(TBinary n) { return (intFac.getTInt(n.toTInt().getValue() * this.toTInt().getValue())).toTBinary(); } @Override public TBinary divABin(TBinary n) { return (intFac.getTInt(n.toTInt().getValue() / this.toTInt().getValue())).toTBinary(); } @Override public TInt toTInt(){ return intFac.getTInt(this.toInt(this.getValue())); } @Override public TFloat toTFloat(){ return floatFac.getTFloat(this.toTInt().getValue()); } @Override public TFloat sumarAFloat(TFloat n) { return floatFac.getTFloat(n.getValue() + this.toTInt().getValue()); } @Override public TFloat restarAFloat(TFloat n) { return floatFac.getTFloat(n.getValue() - this.toTInt().getValue()); } @Override public TFloat multAFloat(TFloat n) { return floatFac.getTFloat(n.toTFloat().getValue() * this.toTInt().getValue()); } @Override public TFloat divAFloat(TFloat n) { return floatFac.getTFloat(n.toTFloat().getValue() / this.toTInt().getValue()); } @Override public TInt sumarAInt(TInt n) { return intFac.getTInt(n.getValue() + this.toTInt().getValue()); } @Override public TInt restarAInt(TInt n) { return intFac.getTInt(n.getValue() - this.toTInt().getValue()); } @Override public TInt multAInt(TInt n) { return intFac.getTInt(n.getValue() * this.toTInt().getValue()); } @Override public TInt divAInt(TInt n) { return intFac.getTInt(n.getValue() / this.toTInt().getValue()); } /** * {@inheritDoc} * Implements the negation bit to bit. */ @Override public TBinary neg() { StringBuilder bin = new StringBuilder(this.getValue()); int l = this.getValue().length(); for (int j = 0; j < l; j++){ bin.replace(j, j + 1, String.valueOf((((int) bin.charAt(j))+1)%2)); } return binFac.getTBinary(bin.toString()); } @Override public IType and(IOpLogical p) { return p.andBinary(this); } /** * Implements the disjunction bit to bit between a binary String and the given boolean. */ private String orBoolean(boolean b){ if (!b){ return this.getValue(); } else{ int l = this.getValue().length(); return "1".repeat(l); } } /** * Implements the conjunction bit to bit between a binary String and the given boolean. */ private String andBoolean(boolean b){ if (b){ return this.getValue(); } else{ int l = this.getValue().length(); return "0".repeat(l); } } @Override public IType andBool(TBool p) { return binFac.getTBinary(this.andBoolean(p.getValue())); } /** * Implements the disjunction bit to bit between two binary strings with the same length. */ private String orSameLength(String b){ int l = this.getValue().length(); String a = this.getValue(); StringBuilder bin = new StringBuilder(l); for (int i = 0; i < l; i++){ if (a.charAt(i) == b.charAt(i) & a.charAt(i) == '0'){ bin.append("0"); } else{ bin.append("1"); } } return bin.toString(); } /** * Implements the conjunction bit to bit between two binary strings with the same length. */ private String andSameLength(String b){ int l = this.getValue().length(); String a = this.getValue(); StringBuilder bin = new StringBuilder(l); for (int i = 0; i < l; i++){ if (a.charAt(i) == b.charAt(i) & a.charAt(i) == '1'){ bin.append("1"); } else{ bin.append("0"); } } return bin.toString(); } /** * {@inheritDoc} * Implements the conjunction bit to bit. */ @Override public IType andBinary(TBinary p) { int l1 = p.getValue().length(); int l2 = this.getValue().length(); if (l1 == l2){ return binFac.getTBinary(this.andSameLength(p.getValue())); } else if(l2 > l1){ String a = this.getValue().substring(0,l2 - l1); String b = this.getValue().substring(l2 - l1, l2); String c = a.concat(p.andSameLength(b)); return binFac.getTBinary(c); } else { String a = p.getValue().substring(0,l1 - l2); String b = p.getValue().substring(l1 - l2, l1); String c = a.concat(this.andSameLength(b)); return binFac.getTBinary(c); } } @Override public IType or(IOpLogical p) { return p.orBinary(this); } @Override public IType orBool(TBool p) { return binFac.getTBinary(this.orBoolean(p.getValue())); } /** * {@inheritDoc} * Implements the disjunction bit to bit. */ @Override public IType orBinary(TBinary p) { int l1 = p.getValue().length(); int l2 = this.getValue().length(); if (l1 == l2){ return binFac.getTBinary(this.orSameLength(p.getValue())); } else if(l2 > l1){ String a = this.getValue().substring(0,l2 - l1); String b = this.getValue().substring(l2 - l1, l2); String c = a.concat(p.orSameLength(b)); return binFac.getTBinary(c); } else { String a = p.getValue().substring(0,l1 - l2); String b = p.getValue().substring(l1 - l2, l1); String c = a.concat(this.orSameLength(b)); return binFac.getTBinary(c); } } @Override public TBinary toTBinary() { return binFac.getTBinary(this.getValue()); } @Override public TBool compare(IType t, int n){ return t.compareTBin(this, -n); } @Override public TBool compareTInt(TInt t, int n) { int cp = Integer.compare(this.toInt(this.getValue()), t.getValue()); return boolFac.getTBool(cp*n > 0 | cp == n); } @Override public TBool compareTBin(TBinary t, int n) { int cp = Integer.compare(this.toInt(this.getValue()), t.toInt(t.getValue())); return boolFac.getTBool(cp*n > 0 | cp == n); } @Override public TBool compareTFloat(TFloat t, int n) { int cp = Double.compare(this.toInt(this.getValue()), t.getValue()); return boolFac.getTBool(cp*n > 0 | cp == n); } }
kazievab/scalajs-react-material-ui
demo/src/main/scala/io/kinoplan/demo/styles/demos/AppBar/BottomAppBarStyle.scala
<reponame>kazievab/scalajs-react-material-ui package io.kinoplan.demo.styles.demos.AppBar import io.kinoplan.demo.CssSettings._ import io.kinoplan.demo.styles.{CommonStyle, DefaultCommonStyle} case class BottomAppBarStyle(common: CommonStyle = DefaultCommonStyle) extends StyleSheet.Inline { import common.theme import dsl._ val root = style( backgroundColor :=! theme.palette.background.default, flexGrow(1), border.none, boxShadow := theme.shadows(1) ) val text = style( paddingTop((theme.spacing.unit * 2).px), paddingLeft((theme.spacing.unit * 2).px), paddingRight((theme.spacing.unit * 2).px) ) val paper = style( maxHeight(300.px), overflow.auto ) val list = style( paddingBottom((theme.spacing.unit * 2).px) ) val subHeader = common.paper val appBar = style( top.auto, bottom :=! 0.toString ) val toolbar = style( alignItems.center, justifyContent.spaceBetween ) val fabButton = style( position.absolute, zIndex :=! 1.toString, top :=! (-30).toString, left :=! 0.toString, right :=! 0.toString, margin :=! "0 auto" ) } object DefaultBottomAppBarStyle extends BottomAppBarStyle
Alipashaimani/Competitive-programming
Codeforces/777A.cpp
<reponame>Alipashaimani/Competitive-programming #include <bits/stdc++.h> using namespace std; int n, x; int arr[6][3]={{0, 1, 2}, {1, 0, 2}, {1, 2, 0}, {2, 1, 0}, {2, 0, 1}, {0, 2, 1}}; int main() { cin >> n >> x; cout << arr[n%6][x]; return 0; }
simonbirt/siesta
siesta/src/main/java/com/cadenzauk/core/tuple/Tuple.java
/* * Copyright (c) 2017, 2018 Cadenza United Kingdom Limited * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.cadenzauk.core.tuple; public interface Tuple { static <T1> Tuple1<T1> of(T1 item1) { return new Tuple1<>(item1); } static <T1, T2> Tuple2<T1,T2> of(T1 item1, T2 item2) { return new Tuple2<>(item1, item2); } static <T1, T2, T3> Tuple3<T1,T2,T3> of(T1 item1, T2 item2, T3 item3) { return new Tuple3<>(item1, item2, item3); } static <T1, T2, T3, T4> Tuple4<T1,T2,T3,T4> of(T1 item1, T2 item2, T3 item3, T4 item4) { return new Tuple4<>(item1, item2, item3, item4); } static <T1, T2, T3, T4, T5> Tuple5<T1,T2,T3,T4,T5> of(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) { return new Tuple5<>(item1, item2, item3, item4, item5); } static <T1, T2, T3, T4, T5, T6> Tuple6<T1,T2,T3,T4,T5,T6> of(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) { return new Tuple6<>(item1, item2, item3, item4, item5, item6); } static <T1, T2, T3, T4, T5, T6, T7> Tuple7<T1,T2,T3,T4,T5,T6,T7> of(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) { return new Tuple7<>(item1, item2, item3, item4, item5, item6, item7); } static <T1, T2, T3, T4, T5, T6, T7, T8> Tuple8<T1,T2,T3,T4,T5,T6,T7,T8> of(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8) { return new Tuple8<>(item1, item2, item3, item4, item5, item6, item7, item8); } static <T1, T2, T3, T4, T5, T6, T7, T8, T9> Tuple9<T1,T2,T3,T4,T5,T6,T7,T8,T9> of(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8, T9 item9) { return new Tuple9<>(item1, item2, item3, item4, item5, item6, item7, item8, item9); } static <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> Tuple10<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10> of(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8, T9 item9, T10 item10) { return new Tuple10<>(item1, item2, item3, item4, item5, item6, item7, item8, item9, item10); } static <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Tuple11<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11> of(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8, T9 item9, T10 item10, T11 item11) { return new Tuple11<>(item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11); } static <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> Tuple12<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12> of(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8, T9 item9, T10 item10, T11 item11, T12 item12) { return new Tuple12<>(item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12); } static <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> Tuple13<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13> of(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8, T9 item9, T10 item10, T11 item11, T12 item12, T13 item13) { return new Tuple13<>(item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13); } static <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> Tuple14<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14> of(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8, T9 item9, T10 item10, T11 item11, T12 item12, T13 item13, T14 item14) { return new Tuple14<>(item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14); } static <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15> Tuple15<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15> of(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8, T9 item9, T10 item10, T11 item11, T12 item12, T13 item13, T14 item14, T15 item15) { return new Tuple15<>(item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15); } static <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> Tuple16<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16> of(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8, T9 item9, T10 item10, T11 item11, T12 item12, T13 item13, T14 item14, T15 item15, T16 item16) { return new Tuple16<>(item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15, item16); } static <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17> Tuple17<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17> of(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8, T9 item9, T10 item10, T11 item11, T12 item12, T13 item13, T14 item14, T15 item15, T16 item16, T17 item17) { return new Tuple17<>(item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15, item16, item17); } static <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18> Tuple18<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18> of(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8, T9 item9, T10 item10, T11 item11, T12 item12, T13 item13, T14 item14, T15 item15, T16 item16, T17 item17, T18 item18) { return new Tuple18<>(item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15, item16, item17, item18); } static <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19> Tuple19<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18,T19> of(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8, T9 item9, T10 item10, T11 item11, T12 item12, T13 item13, T14 item14, T15 item15, T16 item16, T17 item17, T18 item18, T19 item19) { return new Tuple19<>(item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15, item16, item17, item18, item19); } static <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20> Tuple20<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18,T19,T20> of(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8, T9 item9, T10 item10, T11 item11, T12 item12, T13 item13, T14 item14, T15 item15, T16 item16, T17 item17, T18 item18, T19 item19, T20 item20) { return new Tuple20<>(item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15, item16, item17, item18, item19, item20); } }
joakim-ronning/sn-scatter-plot
src/services/plugin-service/__tests__/plugin-args.spec.js
<gh_stars>1-10 // eslint-disable-next-line no-unused-vars import getPluginArgs from '../plugin-args'; describe('plugin-args', () => { let sandbox; let create; let layoutService; let pluginArgs; beforeEach(() => { sandbox = sinon.createSandbox(); layoutService = { getLayout: sandbox.stub().returns('correct-layout') }; create = () => getPluginArgs(layoutService); pluginArgs = create(); }); afterEach(() => { sandbox.restore(); }); describe('pluginArgs', () => { it('should have all keys', () => { expect(pluginArgs).to.have.all.keys(['layout', 'keys']); }); describe('layout', () => { it('should get layout from layoutService', () => { expect(pluginArgs.layout).to.equal('correct-layout'); }); }); describe('keys', () => { it('should have all keys', () => { expect(pluginArgs.keys).to.have.all.keys(['SCALE', 'COMPONENT']); }); describe('SCALE', () => { it('should have all keys', () => { expect(pluginArgs.keys.SCALE).to.have.all.keys(['X', 'Y']); }); }); describe('COMPONENT', () => { it('should have all keys', () => { expect(pluginArgs.keys.COMPONENT).to.have.all.keys(['X_AXIS', 'Y_AXIS', 'POINT']); }); }); }); }); });
Softsimulation/siturmagdalena
public/js/encuestas/turismoReceptor/transporte.js
angular.module('receptor.transporte', ["checklist-model"]) .controller('transporte', ['$scope', 'receptorServi',function ($scope, receptorServi) { $scope.transporte = {}; $scope.$watch('id', function () { $("body").attr("class", "cbp-spmenu-push charging"); receptorServi.getDatosTransporte($scope.id).then(function (data) { if(data.success){ $("body").attr("class", "cbp-spmenu-push"); $scope.transportes = data.transporte_llegar; $scope.lugares = data.lugares; $scope.transporte.Id = $scope.id; if (data.mover != null && data.llegar != null) { $scope.transporte.Llegar = data.llegar; $scope.transporte.Mover = data.mover; $scope.transporte.Alquiler = data.opcion_lugar; $scope.transporte.Empresa = data.empresa; $scope.transporte.Calificacion = data.calificacion; $scope.controlSostenibilidad = data.controlSostenibilidad; } }else{ $("body").attr("class", "cbp-spmenu-push"); swal("Error", "Error en la carga, por favor recarga la pagina", "error"); } }).catch(function () { $("body").attr("class", "cbp-spmenu-push"); swal("Error", "No se realizo la solicitud, reinicie la página"); }) }) $scope.guardar = function () { if (!$scope.transForm.$valid) { swal("Error", "Formulario incompleto corrige los errores.", "error"); return; } $("body").attr("class", "cbp-spmenu-push charging"); receptorServi.guardarSeccionTransporte($scope.transporte).then(function (data) { if (data.success) { $("body").attr("class", "cbp-spmenu-push"); var msj; if (data.sw == 0) { msj = "guardado"; }else{ msj = "editado"; } swal({ title: "Realizado", text: "Se ha " + msj + " satisfactoriamente la sección.", type: "success", timer: 1000, showConfirmButton: false }); setTimeout(function () { window.location.href = "/turismoreceptor/secciongrupoviaje/" + $scope.id; }, 1000); } else { $("body").attr("class", "cbp-spmenu-push"); swal("Error", "Por favor corrija los errores", "error"); $scope.errores = data.errores; } }).catch(function () { $("body").attr("class", "cbp-spmenu-push"); swal("Error", "No se realizo la solicitud, reinicie la página"); }) } }]) .controller('viaje_grupo', ['$scope', 'receptorServi',function ($scope, receptorServi) { $scope.grupo = { Personas: [] } $scope.$watch('id', function () { $("body").attr("class", "cbp-spmenu-push charging"); receptorServi.getDatosSeccionViajeGrupo($scope.id).then(function (data) { if(data.success){ $("body").attr("class", "cbp-spmenu-push"); $scope.viaje_grupos = data.viaje_grupos; $scope.grupo.Id = $scope.id; if (data.tam_grupo != null && data.personas != null) { $scope.grupo.Numero = data.tam_grupo; $scope.grupo.Personas = data.personas; $scope.grupo.Otro = data.otro; $scope.grupo.Numero_otros = data.acompaniantes; } }else{ $("body").attr("class", "cbp-spmenu-push"); swal("Error", "Error en la carga, por favor recarga la pagina", "error"); } }).catch(function () { $("body").attr("class", "cbp-spmenu-push"); swal("Error", "No se realizo la solicitud, reinicie la página"); }) }) $scope.buscar = function (list, data) { if (list.indexOf(data) !== -1) { return true; } else { return false; } } $scope.verifica = function () { if($scope.grupo.Numero < 1 && $scope.grupo.Numero != null){ $scope.grupo.Personas = []; $scope.grupo.Otro = null; } else { if ($scope.grupo.Numero == 1) { $scope.grupo.Personas = [1]; $scope.grupo.Otro = null; } else { var i = $scope.grupo.Personas.indexOf(1); if (i != -1) { $scope.grupo.Personas.splice(i, 1); } } } } $scope.verificarOtro = function () { var i = $scope.grupo.Personas.indexOf(12); if ($scope.grupo.Otro != null && $scope.grupo.Otro != '') { if (i == -1) { $scope.grupo.Personas.push(12); } } } $scope.vchek = function (id) { if (id == 12) { var i = $scope.grupo.Personas.indexOf(12); if (i !== -1) { $scope.grupo.Otro = null; } } } $scope.guardar = function () { if (!$scope.grupoForm.$valid || $scope.grupo.Personas.length == 0) { return; } $("body").attr("class", "cbp-spmenu-push charging"); receptorServi.guardarSeccionViajeGrupo($scope.grupo).then(function (data) { if(data.success){ $("body").attr("class", "cbp-spmenu-push"); var msj; if (data.sw == 0) { msj = "guardado"; } else { msj = "editado"; } swal({ title: "Realizado", type: "success", text: "Se ha " + msj + " satisfactoriamente la sección.", type: "success", timer: 1000, showConfirmButton: false }); setTimeout(function () { window.location.href = "/turismoreceptor/secciongastos/" + $scope.id; }, 1000); }else{ $("body").attr("class", "cbp-spmenu-push"); swal("Error", "Por favor corrija los errores", "error"); } }).catch(function () { $("body").attr("class", "cbp-spmenu-push"); swal("Error", "No se realizo la solicitud, reinicie la página"); }) } }]) .controller('transporte_visitante', ['$scope', '$http',function ($scope, $http) { $scope.transporte = {}; $scope.$watch('id', function () { $("body").attr("class", "cbp-spmenu-push charging"); $http.get('/EncuestaReceptorVisitante/CargarTransporte/' + $scope.id) .success(function (data) { $("body").attr("class", "cbp-spmenu-push"); if (data.success) { $scope.transportes = data.transporte_llegar; $scope.lugares = data.lugares; $scope.transporte.Id = $scope.id; if (data.mover != null && data.llegar != null) { $scope.transporte.Llegar = data.llegar; $scope.transporte.Mover = data.mover; $scope.transporte.Alquiler = data.opcion_lugar; $scope.transporte.Empresa = data.empresa; } } else { swal("Error", "Error en la carga, por favor recarga la página", "error"); } }).error(function () { $("body").attr("class", "cbp-spmenu-push"); swal("Error", "Error en la carga, por favor recarga la página", "error"); }) }) $scope.guardar = function () { if (!$scope.transForm.$valid) { return; } $("body").attr("class", "cbp-spmenu-push charging"); $http.post('/EncuestaReceptorVisitante/GuardarTransporte', $scope.transporte) .success(function (data) { if (data.success) { $("body").attr("class", "cbp-spmenu-push"); var msj; if (data.sw == 0) { msj = "guardado"; } else { msj = "editado"; } swal({ title: "Realizado", text: "Se ha " + msj + " satisfactoriamente la sección.", type: "success", timer: 1000, showConfirmButton: false }); setTimeout(function () { window.location.href = "/EncuestaReceptorVisitante/SeccionViajeGrupo/" + $scope.id; }, 1000); } else { swal("Error", "Por favor corrija los errores", "error"); $scope.errores = data.errores; } }).error(function () { $("body").attr("class", "cbp-spmenu-push"); swal("Error", "Error en la carga, por favor recarga la pagina", "error"); }) } }]) .controller('viaje_grupo_visitante', ['$scope', '$http',function ($scope, $http) { $scope.grupo = { Personas: [] } $scope.$watch('id', function () { $("body").attr("class", "cbp-spmenu-push charging"); $http.get('/EncuestaReceptorVisitante/CargarViajeGrupo/' + $scope.id) .success(function (data) { $("body").attr("class", "cbp-spmenu-push"); if (data.success) { $scope.viaje_grupos = data.viaje_grupos; $scope.grupo.Id = $scope.id; if (data.tam_grupo != null && data.personas != null) { $scope.grupo.Numero = data.tam_grupo; $scope.grupo.Personas = data.personas; $scope.grupo.Otro = data.otro; $scope.grupo.Numero_otros = data.acompañantes; } } else { swal("Error", "Error en la carga, por favor recarga la página", "error"); } }).error(function () { $("body").attr("class", "cbp-spmenu-push"); swal("Error", "Error en la carga, por favor recarga la página", "error"); }) }) $scope.buscar = function (list, data) { if (list.indexOf(data) !== -1) { return true; } else { return false; } } $scope.verifica = function () { if ($scope.grupo.Numero < 1 && $scope.grupo.Numero != null) { $scope.grupo.Personas = []; $scope.grupo.Otro = null; } else { if ($scope.grupo.Numero == 1) { $scope.grupo.Personas = [1] $scope.grupo.Otro = null; } else { var i = $scope.grupo.Personas.indexOf(1); if (i != -1) { $scope.grupo.Personas.splice(i, 1); } } } } $scope.verificarOtro = function () { var i = $scope.grupo.Personas.indexOf(12); if ($scope.grupo.Otro != null && $scope.grupo.Otro != '') { if (i == -1) { $scope.grupo.Personas.push(12); } } } $scope.vchek = function (id) { if (id == 12) { var i = $scope.grupo.Personas.indexOf(12); if (i !== -1) { $scope.grupo.Otro = null; } } } $scope.guardar = function () { if (!$scope.grupoForm.$valid) { return; } if ($scope.grupo.Personas.length == 0) { return; } if ($scope.grupo.Personas.indexOf(9) == -1) { $scope.grupo.Numero_otros = null; } if ($scope.grupo.Personas.indexOf(12) == -1) { $scope.grupo.Otro = null; } $("body").attr("class", "cbp-spmenu-push charging"); $http.post('/EncuestaReceptorVisitante/GuardarViajeGrupo', $scope.grupo) .success(function (data) { $("body").attr("class", "cbp-spmenu-push"); if (data.success) { var msj; if (data.sw == 0) { msj = "guardado"; } else { msj = "editado"; } swal({ title: "Realizado", text: "Se ha " + msj + " satisfactoriamente la sección.", type: "success", timer: 1000, showConfirmButton: false }); setTimeout(function () { window.location.href = "/EncuestaReceptorVisitante/Gastos/" + $scope.id; }, 1000); } else { swal("Error", "Por favor corrija los errores", "error"); $scope.errores = data.errores; } }).error(function () { $("body").attr("class", "cbp-spmenu-push"); swal("Error", "Error en la carga, por favor recarga la pagina", "error"); }) } }])
iteaky/random
node_modules/ix/targets/esnext/cjs/asynciterable/first.js
<reponame>iteaky/random Object.defineProperty(exports, "__esModule", { value: true }); async function first(source, predicate = async () => true) { for await (let item of source) { if (await predicate(item)) { return item; } } return undefined; } exports.first = first; //# sourceMappingURL=data:application/json;charset=utf8;base64,<KEY>
dpopkov/knowthenics
knowthenics-data/src/main/java/ru/dpopkov/knowthenics/model/QCollection.java
package ru.dpopkov.knowthenics.model; import lombok.*; import javax.persistence.*; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; @Getter @Setter @NoArgsConstructor @AllArgsConstructor @Entity @Table(name = "qcollections") public class QCollection extends BaseEntity { @Column(name = "title") private String title; @Column(name = "description") private String description; @ManyToMany @JoinTable(name = "qcollection_question", joinColumns = @JoinColumn(name = "qcollection_id"), inverseJoinColumns = @JoinColumn(name = "question_id")) private Set<Question> questions = new HashSet<>(); @Builder public QCollection(Long id, String title, String description, Set<Question> questions) { super(id); this.title = title; this.description = description; this.questions = questions != null ? questions : new HashSet<>(); } public void addQuestion(Question question) { questions.add(question); } public boolean contains(Question question) { return questions.contains(question); } public void updateFrom(QCollection update) { title = update.getTitle(); description = update.getDescription(); var newQuestions = update.getQuestions(); ArrayList<Question> oldQuestions = new ArrayList<>(this.questions); for (Question oldQuestion : oldQuestions) { if (!newQuestions.contains(oldQuestion)) { questions.remove(oldQuestion); } } questions.addAll(newQuestions); } }
JabaHum/Flicks
app/src/main/java/com/codebosses/flicks/pojo/tvpojo/tvshowsdetail/Season.java
<reponame>JabaHum/Flicks package com.codebosses.flicks.pojo.tvpojo.tvshowsdetail; public class Season { private String air_date; private Integer episode_count; private Integer id; private String name; private String overview; private String poster_path; private Integer season_number; public String getAir_date() { return air_date; } public void setAir_date(String air_date) { this.air_date = air_date; } public Integer getEpisode_count() { return episode_count; } public void setEpisode_count(Integer episode_count) { this.episode_count = episode_count; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getOverview() { return overview; } public void setOverview(String overview) { this.overview = overview; } public String getPoster_path() { return poster_path; } public void setPoster_path(String poster_path) { this.poster_path = poster_path; } public Integer getSeason_number() { return season_number; } public void setSeason_number(Integer season_number) { this.season_number = season_number; } }
pashashiz/scanet3
src/main/scala/scanet/models/LogisticRegression.scala
package scanet.models import scanet.core.{Expr, OutputSeq, Shape, TensorType} import scanet.math.Floating import scanet.math.Numeric import scanet.math.syntax._ import scala.collection.immutable.Seq /** Binary Logistic Regression * * Similar to Linear Regression but applies a logistic function on top * to model a binary dependent variable. Hence, the result is a probability in range `[0, 1]`. * * Model always has only one output * * That is equivalent to `layer.Dense(1, Sigmoid)` */ case object LogisticRegression extends Model { override def build[A: Numeric: Floating: TensorType](x: Expr[A], weights: OutputSeq[A]): Expr[A] = (withBias(x, 1f.const.cast[A]) matmul reshape(weights.head).transpose).sigmoid override def penalty[E: Numeric: Floating: TensorType](weights: OutputSeq[E]) = zeros[E](Shape()) private def reshape[A: TensorType](weights: Expr[A]): Expr[A] = weights.reshape(1, weights.shape.head) override def shapes(features: Int): Seq[Shape] = Seq(Shape(features + 1)) override def outputs(): Int = 1 }
tiwer/letv
src/main/java/bolts/AppLinkNavigation.java
<filename>src/main/java/bolts/AppLinkNavigation.java<gh_stars>10-100 package bolts; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.util.SparseArray; import bolts.AppLink.Target; import com.facebook.internal.NativeProtocol; import com.letv.lemallsdk.util.Constants; import io.fabric.sdk.android.services.settings.SettingsJsonConstants; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class AppLinkNavigation { private static final String KEY_NAME_REFERER_APP_LINK = "referer_app_link"; private static final String KEY_NAME_REFERER_APP_LINK_APP_NAME = "app_name"; private static final String KEY_NAME_REFERER_APP_LINK_PACKAGE = "package"; private static final String KEY_NAME_USER_AGENT = "user_agent"; private static final String KEY_NAME_VERSION = "version"; private static final String VERSION = "1.0"; private static AppLinkResolver defaultResolver; private final AppLink appLink; private final Bundle appLinkData; private final Bundle extras; public enum NavigationResult { FAILED(Constants.CALLBACK_FAILD, false), WEB("web", true), APP(SettingsJsonConstants.APP_KEY, true); private String code; private boolean succeeded; public String getCode() { return this.code; } public boolean isSucceeded() { return this.succeeded; } private NavigationResult(String code, boolean success) { this.code = code; this.succeeded = success; } } public AppLinkNavigation(AppLink appLink, Bundle extras, Bundle appLinkData) { if (appLink == null) { throw new IllegalArgumentException("appLink must not be null."); } if (extras == null) { extras = new Bundle(); } if (appLinkData == null) { appLinkData = new Bundle(); } this.appLink = appLink; this.extras = extras; this.appLinkData = appLinkData; } public AppLink getAppLink() { return this.appLink; } public Bundle getAppLinkData() { return this.appLinkData; } public Bundle getExtras() { return this.extras; } private Bundle buildAppLinkDataForNavigation(Context context) { Bundle data = new Bundle(); Bundle refererAppLinkData = new Bundle(); if (context != null) { String refererAppPackage = context.getPackageName(); if (refererAppPackage != null) { refererAppLinkData.putString(KEY_NAME_REFERER_APP_LINK_PACKAGE, refererAppPackage); } ApplicationInfo appInfo = context.getApplicationInfo(); if (appInfo != null) { String refererAppName = context.getString(appInfo.labelRes); if (refererAppName != null) { refererAppLinkData.putString("app_name", refererAppName); } } } data.putAll(getAppLinkData()); data.putString("target_url", getAppLink().getSourceUrl().toString()); data.putString("version", "1.0"); data.putString(KEY_NAME_USER_AGENT, "Bolts Android 1.2.1"); data.putBundle(KEY_NAME_REFERER_APP_LINK, refererAppLinkData); data.putBundle("extras", getExtras()); return data; } private Object getJSONValue(Object value) throws JSONException { if (value instanceof Bundle) { return getJSONForBundle((Bundle) value); } if (value instanceof CharSequence) { return value.toString(); } Object array; if (value instanceof List) { array = new JSONArray(); for (Object listValue : (List) value) { array.put(getJSONValue(listValue)); } return array; } else if (value instanceof SparseArray) { array = new JSONArray(); SparseArray<?> sparseValue = (SparseArray) value; for (int i = 0; i < sparseValue.size(); i++) { array.put(sparseValue.keyAt(i), getJSONValue(sparseValue.valueAt(i))); } return array; } else if (value instanceof Character) { return value.toString(); } else { if (value instanceof Boolean) { return value; } if (value instanceof Number) { if ((value instanceof Double) || (value instanceof Float)) { return Double.valueOf(((Number) value).doubleValue()); } return Long.valueOf(((Number) value).longValue()); } else if (value instanceof boolean[]) { array = new JSONArray(); for (boolean arrValue : (boolean[]) value) { array.put(getJSONValue(Boolean.valueOf(arrValue))); } return array; } else if (value instanceof char[]) { array = new JSONArray(); for (char arrValue2 : (char[]) value) { array.put(getJSONValue(Character.valueOf(arrValue2))); } return array; } else if (value instanceof CharSequence[]) { array = new JSONArray(); for (CharSequence arrValue3 : (CharSequence[]) value) { array.put(getJSONValue(arrValue3)); } return array; } else if (value instanceof double[]) { array = new JSONArray(); for (double arrValue4 : (double[]) value) { array.put(getJSONValue(Double.valueOf(arrValue4))); } return array; } else if (value instanceof float[]) { array = new JSONArray(); for (float arrValue5 : (float[]) value) { array.put(getJSONValue(Float.valueOf(arrValue5))); } return array; } else if (value instanceof int[]) { array = new JSONArray(); for (int arrValue6 : (int[]) value) { array.put(getJSONValue(Integer.valueOf(arrValue6))); } return array; } else if (value instanceof long[]) { array = new JSONArray(); for (long arrValue7 : (long[]) value) { array.put(getJSONValue(Long.valueOf(arrValue7))); } return array; } else if (value instanceof short[]) { array = new JSONArray(); for (short arrValue8 : (short[]) value) { array.put(getJSONValue(Short.valueOf(arrValue8))); } return array; } else if (!(value instanceof String[])) { return null; } else { array = new JSONArray(); for (String arrValue9 : (String[]) value) { array.put(getJSONValue(arrValue9)); } return array; } } } private JSONObject getJSONForBundle(Bundle bundle) throws JSONException { JSONObject root = new JSONObject(); for (String key : bundle.keySet()) { root.put(key, getJSONValue(bundle.get(key))); } return root; } public NavigationResult navigate(Context context) { PackageManager pm = context.getPackageManager(); Bundle finalAppLinkData = buildAppLinkDataForNavigation(context); Intent eligibleTargetIntent = null; for (Target target : getAppLink().getTargets()) { Intent targetIntent = new Intent("android.intent.action.VIEW"); if (target.getUrl() != null) { targetIntent.setData(target.getUrl()); } else { targetIntent.setData(this.appLink.getSourceUrl()); } targetIntent.setPackage(target.getPackageName()); if (target.getClassName() != null) { targetIntent.setClassName(target.getPackageName(), target.getClassName()); } targetIntent.putExtra("al_applink_data", finalAppLinkData); if (pm.resolveActivity(targetIntent, 65536) != null) { eligibleTargetIntent = targetIntent; break; } } Intent outIntent = null; NavigationResult result = NavigationResult.FAILED; if (eligibleTargetIntent != null) { outIntent = eligibleTargetIntent; result = NavigationResult.APP; } else { Uri webUrl = getAppLink().getWebUrl(); if (webUrl != null) { try { outIntent = new Intent("android.intent.action.VIEW", webUrl.buildUpon().appendQueryParameter("al_applink_data", getJSONForBundle(finalAppLinkData).toString()).build()); result = NavigationResult.WEB; } catch (JSONException e) { sendAppLinkNavigateEventBroadcast(context, eligibleTargetIntent, NavigationResult.FAILED, e); throw new RuntimeException(e); } } } sendAppLinkNavigateEventBroadcast(context, outIntent, result, null); if (outIntent != null) { context.startActivity(outIntent); } return result; } private void sendAppLinkNavigateEventBroadcast(Context context, Intent intent, NavigationResult type, JSONException e) { Map<String, String> extraLoggingData = new HashMap(); if (e != null) { extraLoggingData.put(NativeProtocol.BRIDGE_ARG_ERROR_BUNDLE, e.getLocalizedMessage()); } extraLoggingData.put(Constants.CALLBACK_SUCCESS, type.isSucceeded() ? "1" : "0"); extraLoggingData.put("type", type.getCode()); MeasurementEvent.sendBroadcastEvent(context, MeasurementEvent.APP_LINK_NAVIGATE_OUT_EVENT_NAME, intent, extraLoggingData); } public static void setDefaultResolver(AppLinkResolver resolver) { defaultResolver = resolver; } public static AppLinkResolver getDefaultResolver() { return defaultResolver; } private static AppLinkResolver getResolver(Context context) { if (getDefaultResolver() != null) { return getDefaultResolver(); } return new WebViewAppLinkResolver(context); } public static NavigationResult navigate(Context context, AppLink appLink) { return new AppLinkNavigation(appLink, null, null).navigate(context); } public static Task<NavigationResult> navigateInBackground(final Context context, Uri destination, AppLinkResolver resolver) { return resolver.getAppLinkFromUrlInBackground(destination).onSuccess(new Continuation<AppLink, NavigationResult>() { public NavigationResult then(Task<AppLink> task) throws Exception { return AppLinkNavigation.navigate(context, (AppLink) task.getResult()); } }, Task.UI_THREAD_EXECUTOR); } public static Task<NavigationResult> navigateInBackground(Context context, URL destination, AppLinkResolver resolver) { return navigateInBackground(context, Uri.parse(destination.toString()), resolver); } public static Task<NavigationResult> navigateInBackground(Context context, String destinationUrl, AppLinkResolver resolver) { return navigateInBackground(context, Uri.parse(destinationUrl), resolver); } public static Task<NavigationResult> navigateInBackground(Context context, Uri destination) { return navigateInBackground(context, destination, getResolver(context)); } public static Task<NavigationResult> navigateInBackground(Context context, URL destination) { return navigateInBackground(context, destination, getResolver(context)); } public static Task<NavigationResult> navigateInBackground(Context context, String destinationUrl) { return navigateInBackground(context, destinationUrl, getResolver(context)); } }
JackPu/atom-weexpack
pkg/commons-atom/spec/AutocompleteCacher-spec.js
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the license found in the LICENSE file in * the root directory of this source tree. * * @flow */ import {Point} from 'atom'; import {Deferred} from '../../commons-node/promise'; import AutocompleteCacher from '../AutocompleteCacher'; describe('AutocompleteCacher', () => { let getSuggestions: JasmineSpy = (null: any); let updateResults: JasmineSpy = (null: any); let shouldFilter: JasmineSpy | void = undefined; let mockedSuggestions: Promise<?Array<string>> = (null: any); let mockedUpdateResults: ?Array<string> = null; // returned from the second call let secondMockedUpdateResults: Array<string> = (null: any); let autocompleteCacher: AutocompleteCacher<?Array<string>> = (null: any); let mockedRequest: atom$AutocompleteRequest = (null: any); let mockedRequest2: atom$AutocompleteRequest = (null: any); let mockedRequest3: atom$AutocompleteRequest = (null: any); // Denotes a new autocomplete session. Previous results cannot be re-used. let separateMockedRequest: atom$AutocompleteRequest = (null: any); function initializeAutocompleteCacher() { autocompleteCacher = new AutocompleteCacher(getSuggestions, { updateResults, shouldFilter, }); } beforeEach(() => { waitsForPromise(async () => { mockedSuggestions = Promise.resolve([]); mockedUpdateResults = ['first']; secondMockedUpdateResults = ['second']; mockedRequest = { editor: await atom.workspace.open(), bufferPosition: new Point(0, 0), scopeDescriptor: 'foo', prefix: '', activatedManually: false, }; mockedRequest2 = { ...mockedRequest, bufferPosition: new Point(0, 1), prefix: 'b', }; mockedRequest3 = { ...mockedRequest, bufferPosition: new Point(0, 2), prefix: 'ba', }; separateMockedRequest = { ...mockedRequest, bufferPosition: new Point(1, 0), prefix: '', }; getSuggestions = jasmine.createSpy('getSuggestions').andCallFake(() => { return mockedSuggestions; }); let updateResultsCallCount = 0; updateResults = jasmine.createSpy('updateResults').andCallFake(() => { let result; if (updateResultsCallCount > 0) { result = secondMockedUpdateResults; } else { result = mockedUpdateResults; } updateResultsCallCount++; return result; }); initializeAutocompleteCacher(); }); }); it('should call through on first request', () => { waitsForPromise(async () => { const results = await autocompleteCacher.getSuggestions(mockedRequest); expect(results).toBe(await mockedSuggestions); expect(getSuggestions).toHaveBeenCalledWith(mockedRequest); expect(updateResults).not.toHaveBeenCalled(); }); }); it('should just filter original results on the second request', () => { waitsForPromise(async () => { await autocompleteCacher.getSuggestions(mockedRequest); const secondResults = await autocompleteCacher.getSuggestions(mockedRequest2); expect(getSuggestions.callCount).toBe(2); expect(getSuggestions).toHaveBeenCalledWith(mockedRequest); expect(updateResults.callCount).toBe(1); expect(updateResults).toHaveBeenCalledWith(mockedRequest2, await mockedSuggestions); expect(secondResults).toBe(mockedUpdateResults); }); }); it('should satisfy a second query even if the original has not yet resolved', () => { waitsForPromise(async () => { const originalSuggestionDeferred = new Deferred(); mockedSuggestions = originalSuggestionDeferred.promise; // on purpose don't await here. the promise is not resolved until later const firstResultPromise = autocompleteCacher.getSuggestions(mockedRequest); const secondResultPromise = autocompleteCacher.getSuggestions(mockedRequest2); expect(getSuggestions.callCount).toBe(2); expect(getSuggestions).toHaveBeenCalledWith(mockedRequest); expect(updateResults).not.toHaveBeenCalled(); originalSuggestionDeferred.resolve([]); expect(await firstResultPromise).toBe(await originalSuggestionDeferred.promise); expect(updateResults.callCount).toBe(1); expect(updateResults).toHaveBeenCalledWith(mockedRequest2, await firstResultPromise); expect(await secondResultPromise).toBe(mockedUpdateResults); expect(getSuggestions.callCount).toBe(2); }); }); it('should satisfy a third query even if the original has not yet resolved', () => { waitsForPromise(async () => { const originalSuggestionDeferred = new Deferred(); mockedSuggestions = originalSuggestionDeferred.promise; // on purpose don't await here. the promise is not resolved until later autocompleteCacher.getSuggestions(mockedRequest); const secondResult = autocompleteCacher.getSuggestions(mockedRequest2); const finalResult = autocompleteCacher.getSuggestions(mockedRequest3); expect(getSuggestions.callCount).toBe(3); expect(getSuggestions).toHaveBeenCalledWith(mockedRequest); expect(updateResults).not.toHaveBeenCalled(); originalSuggestionDeferred.resolve([]); expect(await secondResult).toBe(mockedUpdateResults); expect(await finalResult).toBe(secondMockedUpdateResults); expect(updateResults.callCount).toBe(2); expect(updateResults.calls.map(call => call.args)).toEqual([ [mockedRequest2, await mockedSuggestions], [mockedRequest3, await mockedSuggestions], ]); expect(getSuggestions.callCount).toBe(3); }); }); it('should pass a new request through if it cannot filter', () => { waitsForPromise(async () => { await autocompleteCacher.getSuggestions(mockedRequest); const secondResults = await autocompleteCacher.getSuggestions(separateMockedRequest); expect(getSuggestions.callCount).toBe(2); expect(getSuggestions.calls.map(call => call.args)).toEqual([ [mockedRequest], [separateMockedRequest], ]); expect(updateResults).not.toHaveBeenCalled(); expect(secondResults).toBe(await mockedSuggestions); }); }); it('should pass a new request through if updateResults is null', () => { waitsForPromise(async () => { await autocompleteCacher.getSuggestions(mockedRequest); mockedUpdateResults = null; mockedSuggestions = Promise.resolve(['new']); const secondResults = await autocompleteCacher.getSuggestions(mockedRequest2); expect(secondResults).toBe(await mockedSuggestions); }); }); it('should pass a new request through if the first returned null', () => { waitsForPromise(async () => { mockedSuggestions = Promise.resolve(null); await autocompleteCacher.getSuggestions(mockedRequest); const secondMockedSuggestion = []; mockedSuggestions = Promise.resolve(secondMockedSuggestion); const secondResults = await autocompleteCacher.getSuggestions(mockedRequest2); expect(getSuggestions.calls.map(call => call.args)).toEqual([ [mockedRequest], [mockedRequest2], ]); expect(updateResults).not.toHaveBeenCalled(); expect(secondResults).toBe(secondMockedSuggestion); }); }); describe('with a custom shouldFilter function', () => { let shouldFilterResult = false; beforeEach(() => { shouldFilter = jasmine.createSpy('shouldFilter').andCallFake(() => shouldFilterResult); initializeAutocompleteCacher(); }); it('should not filter if not allowed', () => { waitsForPromise(async () => { await autocompleteCacher.getSuggestions(mockedRequest); await autocompleteCacher.getSuggestions(mockedRequest2); expect(getSuggestions.callCount).toBe(2); expect(shouldFilter).toHaveBeenCalledWith(mockedRequest, mockedRequest2, 1); expect(updateResults).not.toHaveBeenCalled(); }); }); it('should filter if allowed', () => { waitsForPromise(async () => { shouldFilterResult = true; await autocompleteCacher.getSuggestions(mockedRequest); const secondResults = await autocompleteCacher.getSuggestions(mockedRequest2); expect(getSuggestions.callCount).toBe(2); expect(getSuggestions).toHaveBeenCalledWith(mockedRequest); expect(updateResults.callCount).toBe(1); expect(updateResults).toHaveBeenCalledWith(mockedRequest2, await mockedSuggestions); expect(secondResults).toBe(mockedUpdateResults); }); }); it('should check the cursor positions of requests before calling shouldFilter', () => { waitsForPromise(async () => { await autocompleteCacher.getSuggestions(mockedRequest); await autocompleteCacher.getSuggestions(separateMockedRequest); expect(getSuggestions.callCount).toBe(2); expect(shouldFilter).not.toHaveBeenCalled(); expect(updateResults).not.toHaveBeenCalled(); }); }); }); });
hemanik/arquillian-extension-warp
impl/src/main/java/org/jboss/arquillian/warp/impl/shared/SerializedAnnotation.java
/** * JBoss, Home of Professional Open Source * Copyright 2012, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.arquillian.warp.impl.shared; import java.io.Serializable; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jboss.arquillian.warp.impl.utils.AnnotationInstanceProvider; public class SerializedAnnotation implements Serializable { private static final long serialVersionUID = 1L; private Class<? extends Annotation> annotationType; private Map<String, Serializable> values = new HashMap<String, Serializable>(); public SerializedAnnotation(Annotation annotation) { annotationType = annotation.annotationType(); List<Method> declaredMethods = Arrays.asList(annotationType.getDeclaredMethods()); Collections.sort(declaredMethods, new Comparator<Method>() { @Override public int compare(Method o1, Method o2) { return o1.getName().compareTo(o2.getName()); } }); for (Method method : declaredMethods) { try { Serializable value = (Serializable) method.invoke(annotation); values.put(method.getName(), value); } catch (Exception e) { throw new IllegalStateException(e); } } } public Annotation getAnnotation() { try { return AnnotationInstanceProvider.get(annotationType, values); } catch (Exception e) { throw new IllegalStateException(e); } } }
DropthoughtSDK/dropthought-ios-sdk
react-native-modules/@dropthought/react-native-dt-sdk/lib/commonjs/kiosk-rn-sdk/navigation/Header.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var React = _interopRequireWildcard(require("react")); var _reactNative = require("react-native"); var _reactNativeSafeAreaContext = require("react-native-safe-area-context"); var _reactNativeUi = require("@dropthought/react-native-ui"); var _CloseButton = _interopRequireWildcard(require("../components/CloseButton")); function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); } function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } /** * @typedef {object} Props * @property {string} title * @property {string} themeColor * @property {()=>void=} onClose */ /** * @type {React.FunctionComponent<Props>} * @param {Props} props */ const Header = ({ title, themeColor, onClose }) => { const insets = (0, _reactNativeSafeAreaContext.useSafeAreaInsets)(); const isRtl = _reactNativeUi.i18n.dir() === 'rtl'; const isPhone = (0, _reactNativeUi.useDimensionWidthType)() === _reactNativeUi.DimensionWidthType.phone; return /*#__PURE__*/React.createElement(_reactNative.View, { style: [styles.container, { backgroundColor: themeColor, paddingTop: insets.top }] }, /*#__PURE__*/React.createElement(_reactNative.View, { style: styles.header }, /*#__PURE__*/React.createElement(_reactNative.Text, { numberOfLines: 1, style: [styles.title, isPhone ? styles.titleIPhone : styles.titleAndroid] }, title), /*#__PURE__*/React.createElement(_reactNative.View, { style: [styles.closeButtonWrapper, isRtl ? styles.closeButtonWrapperRtl : styles.closeButtonWrapperLtr] }, /*#__PURE__*/React.createElement(_CloseButton.default, { onPress: onClose })))); }; var _default = Header; exports.default = _default; const styles = _reactNative.StyleSheet.create({ container: { flexDirection: 'row', alignItems: 'center' }, header: { height: _CloseButton.ICON_SIZE, flex: 1, justifyContent: 'center', paddingHorizontal: 4 }, title: { color: 'white', fontSize: 16, fontWeight: '600', marginHorizontal: _CloseButton.ICON_SIZE }, titleIPhone: { textAlign: 'left' }, titleAndroid: { textAlign: 'center' }, closeButtonWrapper: { position: 'absolute' }, closeButtonWrapperRtl: { right: 0 }, closeButtonWrapperLtr: { left: 0 } }); //# sourceMappingURL=Header.js.map
rdubois/tcommon-studio-se
main/plugins/org.talend.cwm.mip/src/orgomg/cwm/foundation/businessinformation/impl/TelephoneImpl.java
<gh_stars>10-100 /** * <copyright> </copyright> * * $Id$ */ package orgomg.cwm.foundation.businessinformation.impl; import java.util.Collection; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.util.EObjectWithInverseResolvingEList; import org.eclipse.emf.ecore.util.InternalEList; import orgomg.cwm.foundation.businessinformation.BusinessinformationPackage; import orgomg.cwm.foundation.businessinformation.Contact; import orgomg.cwm.foundation.businessinformation.Telephone; import orgomg.cwm.objectmodel.core.impl.ModelElementImpl; /** * <!-- begin-user-doc --> An implementation of the model object ' * <em><b>Telephone</b></em>'. <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link orgomg.cwm.foundation.businessinformation.impl.TelephoneImpl#getPhoneNumber <em>Phone Number</em>}</li> * <li>{@link orgomg.cwm.foundation.businessinformation.impl.TelephoneImpl#getPhoneType <em>Phone Type</em>}</li> * <li>{@link orgomg.cwm.foundation.businessinformation.impl.TelephoneImpl#getContact <em>Contact</em>}</li> * </ul> * </p> * * @generated */ public class TelephoneImpl extends ModelElementImpl implements Telephone { /** * The default value of the '{@link #getPhoneNumber() <em>Phone Number</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getPhoneNumber() * @generated * @ordered */ protected static final String PHONE_NUMBER_EDEFAULT = null; /** * The cached value of the '{@link #getPhoneNumber() <em>Phone Number</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getPhoneNumber() * @generated * @ordered */ protected String phoneNumber = PHONE_NUMBER_EDEFAULT; /** * The default value of the '{@link #getPhoneType() <em>Phone Type</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getPhoneType() * @generated * @ordered */ protected static final String PHONE_TYPE_EDEFAULT = null; /** * The cached value of the '{@link #getPhoneType() <em>Phone Type</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getPhoneType() * @generated * @ordered */ protected String phoneType = PHONE_TYPE_EDEFAULT; /** * The cached value of the '{@link #getContact() <em>Contact</em>}' reference list. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getContact() * @generated * @ordered */ protected EList<Contact> contact; /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ protected TelephoneImpl() { super(); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return BusinessinformationPackage.Literals.TELEPHONE; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String getPhoneNumber() { return phoneNumber; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setPhoneNumber(String newPhoneNumber) { String oldPhoneNumber = phoneNumber; phoneNumber = newPhoneNumber; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, BusinessinformationPackage.TELEPHONE__PHONE_NUMBER, oldPhoneNumber, phoneNumber)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public String getPhoneType() { return phoneType; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setPhoneType(String newPhoneType) { String oldPhoneType = phoneType; phoneType = newPhoneType; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, BusinessinformationPackage.TELEPHONE__PHONE_TYPE, oldPhoneType, phoneType)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public EList<Contact> getContact() { if (contact == null) { contact = new EObjectWithInverseResolvingEList.ManyInverse<Contact>(Contact.class, this, BusinessinformationPackage.TELEPHONE__CONTACT, BusinessinformationPackage.CONTACT__TELEPHONE); } return contact; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case BusinessinformationPackage.TELEPHONE__CONTACT: return ((InternalEList<InternalEObject>) (InternalEList<?>) getContact()).basicAdd(otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case BusinessinformationPackage.TELEPHONE__CONTACT: return ((InternalEList<?>) getContact()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case BusinessinformationPackage.TELEPHONE__PHONE_NUMBER: return getPhoneNumber(); case BusinessinformationPackage.TELEPHONE__PHONE_TYPE: return getPhoneType(); case BusinessinformationPackage.TELEPHONE__CONTACT: return getContact(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case BusinessinformationPackage.TELEPHONE__PHONE_NUMBER: setPhoneNumber((String) newValue); return; case BusinessinformationPackage.TELEPHONE__PHONE_TYPE: setPhoneType((String) newValue); return; case BusinessinformationPackage.TELEPHONE__CONTACT: getContact().clear(); getContact().addAll((Collection<? extends Contact>) newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case BusinessinformationPackage.TELEPHONE__PHONE_NUMBER: setPhoneNumber(PHONE_NUMBER_EDEFAULT); return; case BusinessinformationPackage.TELEPHONE__PHONE_TYPE: setPhoneType(PHONE_TYPE_EDEFAULT); return; case BusinessinformationPackage.TELEPHONE__CONTACT: getContact().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case BusinessinformationPackage.TELEPHONE__PHONE_NUMBER: return PHONE_NUMBER_EDEFAULT == null ? phoneNumber != null : !PHONE_NUMBER_EDEFAULT.equals(phoneNumber); case BusinessinformationPackage.TELEPHONE__PHONE_TYPE: return PHONE_TYPE_EDEFAULT == null ? phoneType != null : !PHONE_TYPE_EDEFAULT.equals(phoneType); case BusinessinformationPackage.TELEPHONE__CONTACT: return contact != null && !contact.isEmpty(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (phoneNumber: "); result.append(phoneNumber); result.append(", phoneType: "); result.append(phoneType); result.append(')'); return result.toString(); } } // TelephoneImpl
XianglongLuo/rancher
vendor/github.com/rancher/rke/cloudprovider/aws/aws.go
<gh_stars>10-100 package aws import ( "bytes" "fmt" "github.com/go-ini/ini" "github.com/rancher/types/apis/management.cattle.io/v3" ) const ( AWSCloudProviderName = "aws" AWSConfig = "AWSConfig" ) type CloudProvider struct { Config *v3.AWSCloudProvider Name string } func GetInstance() *CloudProvider { return &CloudProvider{} } func (p *CloudProvider) Init(cloudProviderConfig v3.CloudProvider) error { p.Name = AWSCloudProviderName if cloudProviderConfig.AWSCloudProvider == nil { return nil } p.Config = cloudProviderConfig.AWSCloudProvider return nil } func (p *CloudProvider) GetName() string { return p.Name } func (p *CloudProvider) GenerateCloudConfigFile() (string, error) { if p.Config == nil { return "", nil } // Generate INI style configuration buf := new(bytes.Buffer) cloudConfig, _ := ini.LoadSources(ini.LoadOptions{IgnoreInlineComment: true}, []byte("")) if err := ini.ReflectFrom(cloudConfig, p.Config); err != nil { return "", fmt.Errorf("Failed to parse AWS cloud config") } if _, err := cloudConfig.WriteTo(buf); err != nil { return "", err } return buf.String(), nil }
1399852153/MySimpleDB
lab/src/main/java/simpledb/matadata/types/ColumnType.java
package simpledb.matadata.types; import simpledb.matadata.fields.Field; import java.io.DataInputStream; /** * @author xiongyx * @date 2021/2/1 */ public interface ColumnType { int getLength(); Field parse(DataInputStream dataInputStream); Class javaType(); }
gsoertsz/dojo-services
src/main/java/org/distributedproficiency/dojo/services/RegistrationService.java
package org.distributedproficiency.dojo.services; import java.util.Collection; import org.distributedproficiency.dojo.domain.Registration; import org.distributedproficiency.dojo.dto.InitiatedRegistrationResponse; import org.distributedproficiency.dojo.dto.RegistrationRequest; public interface RegistrationService { public InitiatedRegistrationResponse initiateRegistration(); public void registerPatient(String key, RegistrationRequest r) throws StudentAlreadyExistsException; public Collection<Registration> getAllRegistrations(); public Registration getRegistrationById(Long id); public void approveRegistration(Long id); public void invalidateMissedRegistrations(); }
YunaBraska/maven-deployment
src/test/resources/testApplication/src/test/java/berlin/yuna/project/controller/WebControllerUnitTest.java
<filename>src/test/resources/testApplication/src/test/java/berlin/yuna/project/controller/WebControllerUnitTest.java<gh_stars>1-10 package berlin.yuna.project.controller; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; public class WebControllerUnitTest { @Test public void runUnitTest() throws Exception { assertThat(2 * 2, is(4)); } }
soumyapal96/decentralized-computing
exec_test/node_modules/iexec/dist/cli/cmd/iexec-order.js
#!/usr/bin/env node "use strict"; const Debug = require('debug'); const cli = require('commander'); const order = require('../../common/modules/order'); const { NULL_ADDRESS } = require('../../common/utils/utils'); const { finalizeCli, addGlobalOptions, addWalletLoadOptions, computeWalletLoadOptions, computeTxOptions, checkUpdate, handleError, desc, option, Spinner, pretty, info, isBytes32, prompt, getPropertyFormChain } = require('../utils/cli-helper'); const { checkRequestRequirements } = require('../../common/modules/request-helper'); const { loadIExecConf, initOrderObj, loadDeployedObj, saveSignedOrder, loadSignedOrders } = require('../utils/fs'); const { loadChain, connectKeystore } = require('../utils/chains'); const { Keystore } = require('../utils/keystore'); const debug = Debug('iexec:iexec-order'); const objName = 'order'; cli.name('iexec order').usage('<command> [options]').storeOptionsAsProperties(false); const init = cli.command('init'); addGlobalOptions(init); addWalletLoadOptions(init); init.option(...option.chain()).option(...option.initAppOrder()).option(...option.initDatasetOrder()).option(...option.initWorkerpoolOrder()).option(...option.initRequestOrder()).description(desc.initObj(objName)).action(async opts => { await checkUpdate(opts); const spinner = Spinner(opts); try { const initAll = !(opts.app || opts.dataset || opts.workerpool || opts.request); const walletOptions = await computeWalletLoadOptions(opts); const chain = await loadChain(opts.chain, { spinner }); const success = {}; const failed = []; const initOrder = async resourceName => { const orderName = resourceName.concat('order'); try { spinner.start(`Creating ${orderName}`); const overwrite = {}; if (resourceName === 'request') { const keystore = Keystore(Object.assign(walletOptions, { isSigner: false })); const [address] = await keystore.accounts(); overwrite.requester = address; overwrite.beneficiary = address; } else { const deployedObj = await loadDeployedObj(resourceName); if (deployedObj && deployedObj[chain.id]) { const address = deployedObj[chain.id]; overwrite[resourceName] = address; } } const { saved, fileName } = await initOrderObj(orderName, overwrite); Object.assign(success, { [orderName]: saved }); spinner.info(`Saved default ${orderName} in "${fileName}", you can edit it:${pretty(saved)}`); } catch (error) { failed.push(`${orderName}: ${error.message}`); } }; if (opts.app || initAll) await initOrder('app'); if (opts.dataset || initAll) await initOrder('dataset'); if (opts.workerpool || initAll) await initOrder('workerpool'); if (opts.request || initAll) await initOrder('request'); if (failed.length === 0) { spinner.succeed('Successfully initialized, you can edit in "iexec.json"', { raw: success }); } else { spinner.fail(`Failed to init: ${pretty(failed)}`, { raw: { ...success, fail: failed } }); } } catch (error) { handleError(error, cli, opts); } }); const sign = cli.command('sign'); addGlobalOptions(sign); addWalletLoadOptions(sign); sign.option(...option.chain()).option(...option.force()).option(...option.signAppOrder()).option(...option.signDatasetOrder()).option(...option.signWorkerpoolOrder()).option(...option.signRequestOrder()).option(...option.skipRequestCheck()).description(desc.sign()).action(async opts => { await checkUpdate(opts); const spinner = Spinner(opts); try { const signAll = !(opts.app || opts.dataset || opts.workerpool || opts.request); const walletOptions = await computeWalletLoadOptions(opts); const keystore = Keystore(walletOptions); const [chain, iexecConf] = await Promise.all([loadChain(opts.chain, { spinner }), loadIExecConf()]); await connectKeystore(chain, keystore); const success = {}; const failed = []; const signAppOrder = async () => { spinner.start('Signing apporder'); try { const loadedOrder = iexecConf.order && iexecConf.order.apporder; if (!loadedOrder) { throw new Error(info.missingOrder(order.APP_ORDER, 'app')); } const orderObj = await order.createApporder(chain.contracts, loadedOrder); await chain.contracts.checkDeployedApp(orderObj.app, { strict: true }); const signedOrder = await order.signApporder(chain.contracts, orderObj); const { saved, fileName } = await saveSignedOrder(order.APP_ORDER, chain.id, signedOrder); spinner.info(info.orderSigned(saved, fileName).concat(pretty(signedOrder))); Object.assign(success, { apporder: signedOrder }); } catch (error) { failed.push(`apporder: ${error.message}`); } }; const signDatasetOrder = async () => { spinner.start('Signing datasetorder'); try { const loadedOrder = iexecConf.order && iexecConf.order.datasetorder; if (!loadedOrder) { throw new Error(info.missingOrder(order.DATASET_ORDER, 'dataset')); } const orderObj = await order.createDatasetorder(chain.contracts, loadedOrder); await chain.contracts.checkDeployedDataset(orderObj.dataset, { strict: true }); const signedOrder = await order.signDatasetorder(chain.contracts, orderObj); const { saved, fileName } = await saveSignedOrder(order.DATASET_ORDER, chain.id, signedOrder); spinner.info(info.orderSigned(saved, fileName).concat(pretty(signedOrder))); Object.assign(success, { datasetorder: signedOrder }); } catch (error) { failed.push(`datasetorder: ${error.message}`); } }; const signWorkerpoolOrder = async () => { spinner.start('Signing workerpoolorder'); try { const loadedOrder = iexecConf.order && iexecConf.order.workerpoolorder; if (!loadedOrder) { throw new Error(info.missingOrder(order.WORKERPOOL_ORDER, 'workerpool')); } const orderObj = await order.createWorkerpoolorder(chain.contracts, loadedOrder); await chain.contracts.checkDeployedWorkerpool(orderObj.workerpool, { strict: true }); const signedOrder = await order.signWorkerpoolorder(chain.contracts, orderObj); const { saved, fileName } = await saveSignedOrder(order.WORKERPOOL_ORDER, chain.id, signedOrder); spinner.info(info.orderSigned(saved, fileName).concat(pretty(signedOrder))); Object.assign(success, { workerpoolorder: signedOrder }); } catch (error) { failed.push(`workerpoolorder: ${error.message}`); } }; const signRequestOrder = async () => { spinner.start('Signing requestorder'); try { const loadedOrder = iexecConf.order && iexecConf.order.requestorder; if (!loadedOrder) { throw new Error(info.missingOrder(order.REQUEST_ORDER, 'request')); } const orderObj = await order.createRequestorder({ contracts: chain.contracts, resultProxyURL: chain.resultProxy }, loadedOrder); await chain.contracts.checkDeployedApp(orderObj.app, { strict: true }); if (!opts.skipRequestCheck) { await checkRequestRequirements({ contracts: chain.contracts, smsURL: chain.sms }, orderObj).catch(e => { throw Error(`Request requirements check failed: ${e.message} (If you consider this is not an issue, use ${option.skipRequestCheck()[0]} to skip request requirement check)`); }); } const signedOrder = await order.signRequestorder(chain.contracts, orderObj); const { saved, fileName } = await saveSignedOrder(order.REQUEST_ORDER, chain.id, signedOrder); spinner.info(info.orderSigned(saved, fileName).concat(pretty(signedOrder))); Object.assign(success, { requestorder: signedOrder }); } catch (error) { failed.push(`requestorder: ${error.message}`); } }; if (opts.app || signAll) await signAppOrder(); if (opts.dataset || signAll) await signDatasetOrder(); if (opts.workerpool || signAll) await signWorkerpoolOrder(); if (opts.request || signAll) await signRequestOrder(); if (failed.length === 0) { spinner.succeed('Successfully signed and stored in "orders.json"', { raw: success }); } else { spinner.fail(`Failed to sign: ${pretty(failed)}`, { raw: { ...success, fail: failed } }); } } catch (error) { handleError(error, cli, opts); } }); const fill = cli.command('fill'); addGlobalOptions(fill); addWalletLoadOptions(fill); fill.option(...option.chain()).option(...option.txGasPrice()).option(...option.txConfirms()).option(...option.force()).option(...option.fillAppOrder()).option(...option.fillDatasetOrder()).option(...option.fillWorkerpoolOrder()).option(...option.fillRequestOrder()).option(...option.fillRequestParams()).option(...option.skipRequestCheck()).description(desc.fill(objName)).action(async opts => { await checkUpdate(opts); const spinner = Spinner(opts); try { const walletOptions = await computeWalletLoadOptions(opts); const txOptions = await computeTxOptions(opts); const keystore = Keystore(walletOptions); const [chain, signedOrders] = await Promise.all([loadChain(opts.chain, { txOptions, spinner }), loadSignedOrders()]); const inputParams = opts.params; const requestOnTheFly = inputParams !== undefined; const getOrderByHash = async (orderName, orderHash) => { if (isBytes32(orderHash, { strict: false })) { spinner.info(`Fetching ${orderName} ${orderHash} from iexec marketplace`); const orderRes = await order.fetchPublishedOrderByHash(getPropertyFormChain(chain, 'iexecGateway'), orderName, chain.id, orderHash); if (!orderRes) { throw Error(`${orderName} ${orderHash} is not published on iexec marketplace`); } return orderRes.order; } throw Error(`Invalid ${orderName} hash`); }; const appOrder = opts.app ? await getOrderByHash(order.APP_ORDER, opts.app) : signedOrders[chain.id].apporder; const datasetOrder = opts.dataset ? await getOrderByHash(order.DATASET_ORDER, opts.dataset) : signedOrders[chain.id].datasetorder; const workerpoolOrder = opts.workerpool ? await getOrderByHash(order.WORKERPOOL_ORDER, opts.workerpool) : signedOrders[chain.id].workerpoolorder; let requestOrderInput; if (requestOnTheFly) { requestOrderInput = undefined; } else { requestOrderInput = opts.request ? await getOrderByHash(order.REQUEST_ORDER, opts.request) : signedOrders[chain.id].requestorder; } const useDataset = requestOrderInput ? requestOrderInput.dataset !== NULL_ADDRESS : !!datasetOrder; debug('useDataset', useDataset); if (!appOrder) throw new Error('Missing apporder'); if (!datasetOrder && useDataset) throw new Error('Missing datasetorder'); if (!workerpoolOrder) throw new Error('Missing workerpoolorder'); const computeRequestOrder = async () => { await connectKeystore(chain, keystore, { txOptions }); const unsignedOrder = await order.createRequestorder({ contracts: chain.contracts, resultProxyURL: chain.resultProxy }, { app: appOrder.app, appmaxprice: appOrder.appprice || undefined, dataset: useDataset ? datasetOrder.dataset : undefined, datasetmaxprice: useDataset ? datasetOrder.datasetprice : undefined, workerpool: workerpoolOrder.workerpool || undefined, workerpoolmaxprice: workerpoolOrder.workerpoolprice || undefined, category: workerpoolOrder.category, params: inputParams || undefined }); if (!opts.force) { await prompt.signGeneratedOrder(order.REQUEST_ORDER, pretty(unsignedOrder)); } const signed = await order.signRequestorder(chain.contracts, unsignedOrder); return signed; }; const requestOrder = requestOrderInput || (await computeRequestOrder()); if (!requestOrder) { throw new Error('Missing requestorder'); } if (!opts.skipRequestCheck) { await checkRequestRequirements({ contracts: chain.contracts, smsURL: chain.sms }, requestOrder).catch(e => { throw Error(`Request requirements check failed: ${e.message} (If you consider this is not an issue, use ${option.skipRequestCheck()[0]} to skip request requirement check)`); }); } await connectKeystore(chain, keystore, { txOptions }); spinner.start(info.filling(objName)); const { dealid, volume, txHash } = await order.matchOrders(chain.contracts, appOrder, useDataset ? datasetOrder : undefined, workerpoolOrder, requestOrder); spinner.succeed(`${volume} task successfully purchased with dealid ${dealid}`, { raw: { dealid, volume: volume.toString(), txHash } }); } catch (error) { handleError(error, cli, opts); } }); const publish = cli.command('publish'); addGlobalOptions(publish); addWalletLoadOptions(publish); publish.option(...option.chain()).option(...option.force()).option(...option.publishAppOrder()).option(...option.publishDatasetOrder()).option(...option.publishWorkerpoolOrder()).option(...option.publishRequestOrder()).option(...option.skipRequestCheck()).description(desc.publish(objName)).action(async opts => { await checkUpdate(opts); const spinner = Spinner(opts); try { if (!(opts.app || opts.dataset || opts.workerpool || opts.request)) { throw new Error('No option specified, you should choose one (--app | --dataset | --workerpool | --request)'); } const walletOptions = await computeWalletLoadOptions(opts); const keystore = Keystore(walletOptions); const [chain, signedOrders] = await Promise.all([loadChain(opts.chain, { spinner }), loadSignedOrders()]); await connectKeystore(chain, keystore); const success = {}; const failed = []; const publishOrder = async orderName => { try { const orderToPublish = signedOrders[chain.id] && signedOrders[chain.id][orderName]; if (!orderToPublish) { throw new Error(`Missing signed ${orderName} for chain ${chain.id} in "orders.json"`); } if (!opts.force) await prompt.publishOrder(orderName, pretty(orderToPublish)); spinner.start(`Publishing ${orderName}`); let orderHash; switch (orderName) { case order.APP_ORDER: orderHash = await order.publishApporder(chain.contracts, getPropertyFormChain(chain, 'iexecGateway'), orderToPublish); break; case order.DATASET_ORDER: orderHash = await order.publishDatasetorder(chain.contracts, getPropertyFormChain(chain, 'iexecGateway'), orderToPublish); break; case order.WORKERPOOL_ORDER: orderHash = await order.publishWorkerpoolorder(chain.contracts, getPropertyFormChain(chain, 'iexecGateway'), orderToPublish); break; case order.REQUEST_ORDER: if (!opts.skipRequestCheck) { await checkRequestRequirements({ contracts: chain.contracts, smsURL: chain.sms }, orderToPublish).catch(e => { throw Error(`Request requirements check failed: ${e.message} (If you consider this is not an issue, use ${option.skipRequestCheck()[0]} to skip request requirement check)`); }); } orderHash = await order.publishRequestorder(chain.contracts, getPropertyFormChain(chain, 'iexecGateway'), orderToPublish); break; default: } spinner.info(`${orderName} successfully published with orderHash ${orderHash}`); Object.assign(success, { [orderName]: { orderHash } }); } catch (error) { failed.push(`${orderName}: ${error.message}`); } }; if (opts.app) await publishOrder(order.APP_ORDER); if (opts.dataset) await publishOrder(order.DATASET_ORDER); if (opts.workerpool) await publishOrder(order.WORKERPOOL_ORDER); if (opts.request) await publishOrder(order.REQUEST_ORDER); if (failed.length === 0) { spinner.succeed('Successfully published', { raw: success }); } else { spinner.fail(`Failed to publish: ${pretty(failed)}`, { raw: { ...success, fail: failed } }); } } catch (error) { handleError(error, cli, opts); } }); const unpublish = cli.command('unpublish'); addGlobalOptions(unpublish); addWalletLoadOptions(unpublish); unpublish.option(...option.chain()).option(...option.force()).option(...option.unpublishAppOrder()).option(...option.unpublishDatasetOrder()).option(...option.unpublishWorkerpoolOrder()).option(...option.unpublishRequestOrder()).description(desc.unpublish(objName)).action(async opts => { await checkUpdate(opts); const spinner = Spinner(opts); try { if (!(opts.app || opts.dataset || opts.workerpool || opts.request)) { throw new Error('No option specified, you should choose one (--app | --dataset | --workerpool | --request)'); } const walletOptions = await computeWalletLoadOptions(opts); const keystore = Keystore(walletOptions); const [chain, signedOrders] = await Promise.all([loadChain(opts.chain, { spinner }), loadSignedOrders()]); await connectKeystore(chain, keystore); const success = {}; const failed = []; const unpublishOrder = async (orderName, orderHash) => { try { let orderHashToUnpublish; if (isBytes32(orderHash, { strict: false })) { orderHashToUnpublish = orderHash; } else { spinner.info(`No orderHash specified for unpublish ${orderName}, using orders.json`); const orderToUnpublish = signedOrders[chain.id] && signedOrders[chain.id][orderName]; if (!orderToUnpublish) { throw new Error(`No orderHash specified and no signed ${orderName} found for chain ${chain.id} in "orders.json"`); } orderHashToUnpublish = await order.computeOrderHash(chain.contracts, orderName, orderToUnpublish); if (!opts.force) { await prompt.unpublishFromJsonFile(orderName, pretty(orderToUnpublish)); } } spinner.start(`Unpublishing ${orderName}`); let unpublished; switch (orderName) { case order.APP_ORDER: unpublished = await order.unpublishApporder(chain.contracts, getPropertyFormChain(chain, 'iexecGateway'), orderHashToUnpublish); break; case order.DATASET_ORDER: unpublished = await order.unpublishDatasetorder(chain.contracts, getPropertyFormChain(chain, 'iexecGateway'), orderHashToUnpublish); break; case order.WORKERPOOL_ORDER: unpublished = await order.unpublishWorkerpoolorder(chain.contracts, getPropertyFormChain(chain, 'iexecGateway'), orderHashToUnpublish); break; case order.REQUEST_ORDER: unpublished = await order.unpublishRequestorder(chain.contracts, getPropertyFormChain(chain, 'iexecGateway'), orderHashToUnpublish); break; default: } spinner.info(`${orderName} with orderHash ${unpublished} successfully unpublished`); Object.assign(success, { [orderName]: { orderHash: unpublished } }); } catch (error) { failed.push(`${orderName}: ${error.message}`); } }; if (opts.app) await unpublishOrder(order.APP_ORDER, opts.app); if (opts.dataset) await unpublishOrder(order.DATASET_ORDER, opts.dataset); if (opts.workerpool) await unpublishOrder(order.WORKERPOOL_ORDER, opts.workerpool); if (opts.request) await unpublishOrder(order.REQUEST_ORDER, opts.request); if (failed.length === 0) { spinner.succeed('Successfully unpublished', { raw: success }); } else { spinner.fail(`Failed to unpublish: ${pretty(failed)}`, { raw: { ...success, fail: failed } }); } } catch (error) { handleError(error, cli, opts); } }); const cancel = cli.command('cancel'); addGlobalOptions(cancel); addWalletLoadOptions(cancel); cancel.option(...option.chain()).option(...option.txGasPrice()).option(...option.txConfirms()).option(...option.force()).option(...option.cancelAppOrder()).option(...option.cancelDatasetOrder()).option(...option.cancelWorkerpoolOrder()).option(...option.cancelRequestOrder()).description(desc.cancel(objName)).action(async opts => { await checkUpdate(opts); const spinner = Spinner(opts); try { if (!(opts.app || opts.dataset || opts.workerpool || opts.request)) { throw new Error('No option specified, you should choose one (--app | --dataset | --workerpool | --request)'); } const walletOptions = await computeWalletLoadOptions(opts); const txOptions = await computeTxOptions(opts); const keystore = Keystore(walletOptions); const [chain, signedOrders] = await Promise.all([loadChain(opts.chain, { txOptions, spinner }), loadSignedOrders()]); await connectKeystore(chain, keystore, { txOptions }); const success = {}; const failed = []; const cancelOrder = async orderName => { try { const orderToCancel = signedOrders[chain.id][orderName]; if (!orderToCancel) { throw new Error(`Missing signed ${orderName} for chain ${chain.id} in "orders.json"`); } if (!opts.force) await prompt.cancelOrder(orderName, pretty(orderToCancel)); spinner.start(`Canceling ${orderName}`); let cancelTx; switch (orderName) { case order.APP_ORDER: cancelTx = (await order.cancelApporder(chain.contracts, orderToCancel)).txHash; break; case order.DATASET_ORDER: cancelTx = (await order.cancelDatasetorder(chain.contracts, orderToCancel)).txHash; break; case order.WORKERPOOL_ORDER: cancelTx = (await order.cancelWorkerpoolorder(chain.contracts, orderToCancel)).txHash; break; case order.REQUEST_ORDER: cancelTx = (await order.cancelRequestorder(chain.contracts, orderToCancel)).txHash; break; default: } spinner.info(`${orderName} successfully canceled (${cancelTx})`); Object.assign(success, { [orderName]: { txHash: cancelTx } }); } catch (error) { failed.push(`${orderName}: ${error.message}`); } }; if (opts.app) await cancelOrder(order.APP_ORDER); if (opts.dataset) await cancelOrder(order.DATASET_ORDER); if (opts.workerpool) await cancelOrder(order.WORKERPOOL_ORDER); if (opts.request) await cancelOrder(order.REQUEST_ORDER); if (failed.length === 0) { spinner.succeed('Successfully canceled', { raw: success }); } else { spinner.fail(`Failed to cancel: ${pretty(failed)}`, { raw: { ...success, fail: failed } }); } } catch (error) { handleError(error, cli, opts); } }); const show = cli.command('show'); addGlobalOptions(show); show.option(...option.chain()).option(...option.showAppOrder()).option(...option.showDatasetOrder()).option(...option.showWorkerpoolOrder()).option(...option.showRequestOrder()).option(...option.showOrderDeals()).description(desc.showObj(objName, 'marketplace')).action(async opts => { await checkUpdate(opts); const spinner = Spinner(opts); try { if (!(opts.app || opts.dataset || opts.workerpool || opts.request)) { throw new Error('No option specified, you should choose one (--app | --dataset | --workerpool | --request)'); } const chain = await loadChain(opts.chain, { spinner }); const success = {}; const failed = []; const showOrder = async (orderName, cmdInput) => { try { let orderHash; if (cmdInput === true) { spinner.info(`No order hash specified, showing ${orderName} from "orders.json"`); const signedOrders = (await loadSignedOrders())[chain.id]; const signedOrder = signedOrders && signedOrders[orderName]; if (!signedOrder) { throw Error(`Missing ${orderName} in "orders.json" for chain ${chain.id}`); } orderHash = await order.computeOrderHash(chain.contracts, orderName, signedOrder); } else { orderHash = cmdInput; } isBytes32(orderHash); spinner.start(info.showing(orderName)); const orderToShow = await order.fetchPublishedOrderByHash(getPropertyFormChain(chain, 'iexecGateway'), orderName, chain.id, orderHash); let deals; if (opts.deals) { deals = await order.fetchDealsByOrderHash(getPropertyFormChain(chain, 'iexecGateway'), orderName, chain.id, orderHash); } const orderString = orderToShow ? `${orderName} with orderHash ${orderHash} details:${pretty(orderToShow)}` : `${orderName} with orderHash ${orderHash} is not published`; const dealsString = deals && deals.count ? `\nDeals count: ${deals.count}\nLast deals: ${pretty(deals.deals)}` : '\nDeals count: 0'; const raw = { ...orderToShow, ...(deals && { deals: { count: deals.count, lastDeals: deals.deals } }) }; spinner.info(`${orderString}${opts.deals ? dealsString : ''}`); Object.assign(success, { [orderName]: raw }); } catch (error) { failed.push(`${orderName}: ${error.message}`); } }; if (opts.app) await showOrder(order.APP_ORDER, opts.app); if (opts.dataset) await showOrder(order.DATASET_ORDER, opts.dataset); if (opts.workerpool) await showOrder(order.WORKERPOOL_ORDER, opts.workerpool); if (opts.request) await showOrder(order.REQUEST_ORDER, opts.request); if (failed.length === 0) { spinner.succeed('Successfully found', { raw: success }); } else { spinner.fail(`Failed to show: ${pretty(failed)}`, { raw: { ...success, fail: failed } }); } } catch (error) { handleError(error, cli, opts); } }); finalizeCli(cli);
bbossgroups/bboss
bboss-core-entity/src/com/frameworkset/util/ValueObjectUtil.java
/***************************************************************************** * * * This file is part of the tna framework distribution. * * Documentation and updates may be get from biaoping.yin the author of * * this framework * * * * Sun Public License Notice: * * * * The contents of this file are subject to the Sun Public License Version * * 1.0 (the "License"); you may not use this file except in compliance with * * the License. A copy of the License is available at http://www.sun.com * * * * The Original Code is tag. The Initial Developer of the Original * * Code is <NAME>. Portions created by biaoping yin are Copyright * * (C) 2000. All Rights Reserved. * * * * GNU Public License Notice: * * * * Alternatively, the contents of this file may be used under the terms of * * the GNU Lesser General Public License (the "LGPL"), in which case the * * provisions of LGPL are applicable instead of those above. If you wish to * * allow use of your version of this file only under the terms of the LGPL * * and not to allow others to use your version of this file under the SPL, * * indicate your decision by deleting the provisions above and replace * * them with the notice and other provisions required by the LGPL. If you * * do not delete the provisions above, a recipient may use your version of * * this file under either the SPL or the LGPL. * * * * biaoping.yin (<EMAIL>) * * * *****************************************************************************/ package com.frameworkset.util; import com.frameworkset.common.poolman.NestedSQLException; import com.frameworkset.spi.assemble.BeanInstanceException; import com.frameworkset.spi.assemble.CurrentlyInCreationException; import org.frameworkset.util.BigFile; import org.frameworkset.util.ClassUtil; import org.frameworkset.util.ClassUtil.PropertieDescription; import org.frameworkset.util.DataFormatUtil; import org.frameworkset.util.MethodParameter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.math.BigDecimal; import java.math.BigInteger; import java.net.URL; import java.sql.Blob; import java.sql.Clob; import java.sql.Date; import java.sql.SQLException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * @author biaoping.yin 改类充分使用java.lang.reflection中提供的功能,提供以下工具: 从对象中获取对应属性的值 */ public class ValueObjectUtil { /** * 基本数据类型,bboss定位如下: * java定义的基本数据类型 * BigFile 大附件类型 * 枚举类型 * 日期类型 * 字符串类型 * 这些类型主要应用于mvc控制器方法参数的绑定过程中 */ public static final Class[] baseTypes = {String.class, int.class ,Integer.class, long.class,Long.class, java.sql.Timestamp.class, Date.class,java.util.Date.class, boolean.class ,Boolean.class, BigFile.class, float.class ,Float.class, short.class ,Short.class, double.class,Double.class, char.class ,Character.class, byte.class ,Byte.class, BigDecimal.class,BigInteger.class}; /** * 用于序列化机制识别基础数据类型 */ public static final Class[] basePrimaryTypes = {String.class, int.class , long.class, boolean.class , // BigFile.class, float.class , short.class , double.class, char.class , byte.class , Class.class,BigInteger.class,BigDecimal.class, java.sql.Timestamp.class, Date.class,java.util.Date.class }; /** * 用于序列化机制识别基础数据类型 */ public static final Class[] simplePrimaryTypes = {String.class, int.class , long.class, boolean.class , // BigFile.class, float.class , short.class , double.class, char.class , byte.class , Class.class, java.sql.Timestamp.class, Date.class,java.util.Date.class, Locale.class }; private static final Logger log = LoggerFactory.getLogger(ValueObjectUtil.class); // private static final SimpleDateFormat format = new SimpleDateFormat( // "yyyy-MM-dd HH:mm:ss"); /** * 缓存所有的日期格式 */ // private static final Map<String,SimpleDateFormat> dataformats = new HashMap<String,SimpleDateFormat>(); // /** // * Description:获取对象obj的property属性值 // * // * @param obj // * @param property // * @return Object // */ // public static Object getValue(Object obj, String property) { // return getValue(obj, property); // } /** * Description:获取对象obj的property属性值,params为参数数组 * * @param obj * @param property * @return Object */ public static Object getValue(Object obj, String property) { if (obj == null || property == null || property.trim().length() == 0) return null; Class clazz = obj.getClass(); try { PropertieDescription pd = ClassUtil.getPropertyDescriptor(clazz, property); if(pd != null) return pd.getValue(obj); else { if(log.isDebugEnabled()) log.debug(new StringBuilder().append("类").append(clazz.getCanonicalName()).append("没有定义属性").append( property ).toString()); } } catch (Exception e) { if(log.isDebugEnabled()) log.debug(new StringBuilder().append("获取类").append(clazz.getCanonicalName()).append("属性[") .append( property ).append( "]值异常:").toString(),e); } return null; } /** * Description:获取对象obj的property属性值,params为参数数组 * * @param obj * @param property * @return Object */ public static Object getValueOrSize(Object obj, String property) { boolean issize = false; if(property.startsWith("size:")) { issize = true; property = property.substring(5); } Object value = getValue( obj, property); if(issize) { return length(value); } else { return value; } } public static int length(Object _actualValue) { if(_actualValue == null) return 0; else { if(_actualValue instanceof Collection) { return ((Collection)_actualValue).size(); } else if(_actualValue instanceof Map) { return ((Map)_actualValue).size(); } else if(_actualValue.getClass().isArray()) { return Array.getLength(_actualValue); } else if(_actualValue instanceof String) { return ((String)_actualValue).length(); } else if(_actualValue instanceof ListInfo) { return ((ListInfo)_actualValue).getSize(); } else //评估对象长度 { throw new IllegalArgumentException("无法计算类型为"+_actualValue.getClass().getName()+"的对象长度length。"); } } } public static Object getValue(Object obj, String property,Object[] params) { if (obj == null || property == null || property.trim().length() == 0) return null; Class clazz = obj.getClass(); try { if(params == null || params.length == 0) { PropertieDescription pd = ClassUtil.getPropertyDescriptor(clazz, property); if(pd != null) return pd.getValue(obj); else { if(log.isDebugEnabled()) log.debug(new StringBuilder().append("类").append(clazz.getCanonicalName()).append("没有定义属性").append( property ).toString()); } } // else // { // Method method = getMethodByPropertyName(obj, property); // return getValueByMethod(obj, method, params); // } } catch (Exception e) { if(log.isDebugEnabled()) log.debug(new StringBuilder().append("获取类").append(clazz.getCanonicalName()).append("属性[") .append( property ).append( "]值异常:").toString(),e); } // Object ret = getValueByMethodName(obj, getMethodName(property), // params); // if (ret == null) // { // // log.debug("Try to get Boolean attribute for property[" + property // // + "]."); // ret = getValueByMethodName(obj, getBooleanMethodName(property), // params); // if (ret != null) // log.debug("Get Boolean property[" + property + "=" + ret + "]."); // } // return ret; return null; } /** * Description:根据方法名称获取, 在对象obj上调用改方法并且返回调用的返回值 * * @param obj * @param methodName * 方法名称 * @param params * 方法的参数 * @return Object * @deprecated */ public static Object getValueByMethodName(Object obj, String methodName, Object[] params) { if (obj == null || methodName == null || methodName.trim().length() == 0) return null; return getValueByMethodName(obj, methodName, params, null); } // /* // * // */ // @Deprecated // public static Method getMethodByPropertyName(Object obj, // String propertyName, Class[] paramsTtype) throws Exception { // String name = getMethodName(propertyName); // Method method = null; // try { // method = obj.getClass().getMethod(name, paramsTtype); // } catch (SecurityException e) { // name = getBooleanMethodName(propertyName); // method = obj.getClass().getMethod(name, paramsTtype); // } catch (NoSuchMethodException e) { // name = getBooleanMethodName(propertyName); // method = obj.getClass().getMethod(name, paramsTtype); // } catch (Exception e) { // name = getBooleanMethodName(propertyName); // method = obj.getClass().getMethod(name, paramsTtype); // } // return method; // // } public static Method getMethodByPropertyName(Object obj, String propertyName) throws Exception { // String name = getMethodName(propertyName); Method method = null; try { // method = obj.getClass().getMethod(name, paramsTtype); PropertieDescription pd = ClassUtil.getPropertyDescriptor(obj.getClass(), propertyName); if(pd != null) method = pd.getReadMethod(); } catch (SecurityException e) { // String name = getBooleanMethodName(propertyName); // method = obj.getClass().getMethod(name, null); } catch (Exception e) { // String name = getBooleanMethodName(propertyName); // method = obj.getClass().getMethod(name, null); } if(method == null) { String name = getBooleanMethodName(propertyName); // method = obj.getClass().getMethod(name, null); method = ClassUtil.getDeclaredMethod(obj.getClass(),name); if(method == null) throw new NoSuchMethodException(obj.getClass().getName() + "." + name ); } return method; } /** * Description:根据方法名称获取, 在对象obj上调用改方法并且返回调用的返回值 * * @param obj * @param methodName * 方法名称 * @param params * 方法的参数 * @param paramsTtype * 方法的参数类型 * @deprecated * @return Object */ public static Object getValueByMethodName(Object obj, String methodName, Object[] params, Class[] paramsTtype) { if (obj == null || methodName == null || methodName.trim().length() == 0) return null; try { if(paramsTtype == null || paramsTtype.length == 0) { Method method = ClassUtil.getDeclaredMethod(obj.getClass(),methodName); if (method != null) return method.invoke(obj, params); } else { Method method = obj.getClass().getMethod(methodName, paramsTtype); if (method != null) return method.invoke(obj, params); } } catch (Exception e) { // e.printStackTrace(); log.info("NoSuchMethodException:" + e.getMessage()); } return null; } /** * Description:根据方法名称获取, 在对象obj上调用改方法并且返回调用的返回值 * * @param obj * @param method * 方法名称 * @param params * 方法的参数 * @return Object */ public static Object getValueByMethod(Object obj, Method method, Object[] params) { if (obj == null || method == null) return null; try { // Method method = obj.getClass().getMethod(methodName, // paramsTtype); // if (method != null) return method.invoke(obj, params); } catch (Exception e) { // e.printStackTrace(); log.info("Invoker method[" + method.getName() + "] on " + obj.getClass().getCanonicalName() + " failed:" + e.getMessage()); } return null; } /** * Description:实现在对象调用method并为该方法传入参数数组params * * @param obj * 对象 * @param method * 待调用的方法 * @param params * 参数数组 * @return Object * @throws Exception * Object */ public static Object invoke(Object obj, Method method, Object[] params) throws Exception { return method.invoke(obj, params); } /** * Description:实现在对象调用method并为该方法传入参数数组params * * @param obj * 对象 * @param method * 待调用的方法 * @param params * 参数数组 * @return Object * @throws Exception * Object */ public static Object invoke(Object obj, String method, Object[] params) throws Exception { if(obj == null) { return null; } Class clazz = obj.getClass(); Method _m = ClassUtil.getDeclaredMethod(clazz, method); return _m.invoke(obj, params); } /** * 获取fieldName的getter方法名称 * * @param fieldName * @return String */ public static String getMethodName(String fieldName) { String ret = null; if (fieldName == null) return null; String letter = String.valueOf(fieldName.charAt(0)); letter = letter.toUpperCase(); ret = "get" + letter + fieldName.substring(1); // System.out.println("method name:" + ret); return ret; } public static String getBooleanMethodName(String fieldName) { String ret = null; if (fieldName == null) return null; String letter = String.valueOf(fieldName.charAt(0)); letter = letter.toUpperCase(); ret = "is" + letter + fieldName.substring(1); // System.out.println("method name:" + ret); return ret; } /** * 获取fieldName的setter方法 * * @param fieldName * @return String * @deprecated */ public static String getSetterMethodName(String fieldName) { String ret = null; if (fieldName == null) return null; String letter = String.valueOf(fieldName.charAt(0)); letter = letter.toUpperCase(); ret = "set" + letter + fieldName.substring(1); // System.out.println("method name:" + ret); return ret; } // public final static boolean isSameType(Class type, Class toType) // { // if(toType == Object.class) // return true; // // else if(type == toType) // return true; // else if(toType.isAssignableFrom(type))//检查toType是不是type的父类或者是type所实现的接口 // { // return true; // } // else // if(type.isAssignableFrom(toType))//检查type是不是toType的父类或者是拖油瓶type所实现的接口 // { // if(type.getName().equals(toType.getName())) // return true; // } // // else if((type == int.class && toType == Integer.class) || // type == Integer.class && toType == int.class) // { // return true; // } // else if((type == short.class && toType == Short.class) || // type == Short.class && toType == short.class) // { // return true; // } // else if((type == long.class && toType == Long.class) || // type == Long.class && toType == long.class) // { // return true; // } // else if((type == double.class && toType == Double.class) || // type == Double.class && toType == double.class) // { // return true; // } // else if((type == float.class && toType == Float.class) || // type == Float.class && toType == float.class) // { // return true; // } // else if((type == char.class && toType == Character.class) || // type == Character.class && toType == char.class) // { // return true; // } // return false; // // // } /** * * @param types * 构造函数的参数类型 * @param params * 外部传入的形式参数类型 * @return */ public static boolean isSameTypes(Class[] types, Class[] params, Object[] paramArgs) { if (types.length != params.length) return false; for (int i = 0; i < params.length; i++) { // if(!ValueObjectUtil.isSameType(type, toType)) if (!isSameType(params[i], types[i], paramArgs[i])) { return false; } } return true; } public final static boolean isSameType(Class type, Class toType, Object value) { if (toType == Object.class) return true; else if (type == toType) return true; else if (toType.isAssignableFrom(type))// 检查toType是不是type的父类或者是type所实现的接口 { return true; } else if (type.isAssignableFrom(toType))// 检查type是不是toType的父类或者是拖油瓶toType所实现的接口 { try { toType.cast(value); return true; } catch (Exception e) { return false; } // if(type.getName().equals(toType.getName())) // return true; } else if ((type == boolean.class && toType == Boolean.class) || type == Boolean.class && toType == boolean.class) { return true; } else if ((type == int.class && toType == Integer.class) || type == Integer.class && toType == int.class) { return true; } else if ((type == short.class && toType == Short.class) || type == Short.class && toType == short.class) { return true; } else if ((type == long.class && toType == Long.class) || type == Long.class && toType == long.class) { return true; } else if ((type == double.class && toType == Double.class) || type == Double.class && toType == double.class) { return true; } else if ((type == float.class && toType == Float.class) || type == Float.class && toType == float.class) { return true; } else if ((type == char.class && toType == Character.class) || type == Character.class && toType == char.class) { return true; } return false; } /** * 通过属性编辑器来转换属性值 * * @param obj * @param editor * @return * @throws NoSupportTypeCastException * @throws NumberFormatException * @throws IllegalArgumentException */ public final static Object typeCast(Object obj, EditorInf editor) throws NoSupportTypeCastException, NumberFormatException, IllegalArgumentException { return editor.getValueFromObject(obj); } public final static Object typeCast(Object obj, Class toType,String dateformat ) throws NoSupportTypeCastException, NumberFormatException, IllegalArgumentException { return typeCast( obj, toType, dateformat,(Locale )null); } /** * 将obj对象从类型type转换到类型toType 支持字符串向其他基本类行转换: 支持的类型: * int,char,short,double,float,long,boolean,byte * java.sql.Date,java.util.Date, Integer Long Float Short Double Character * Boolean Byte * * @param obj * @param toType * @return Object * @throws ClassCastException * ,NumberFormatException,IllegalArgumentException */ public final static Object typeCast(Object obj, Class toType,String dateformat,Locale locale) throws NoSupportTypeCastException, NumberFormatException, IllegalArgumentException { if(toType == null) return obj; if (obj == null) return null; return typeCast(obj, obj.getClass(), toType,dateformat, locale); } public final static Object typeCastWithDateformat(Object obj, Class toType,DateFormat dateformat) throws NoSupportTypeCastException, NumberFormatException, IllegalArgumentException { if (obj == null) return null; return typeCastWithDateformat(obj, obj.getClass(), toType,dateformat); } public final static Object typeCast(Object obj, Class toType) throws NoSupportTypeCastException, NumberFormatException, IllegalArgumentException{ return typeCast( obj, toType,(String )null,(Locale )null); } public final static Object typeCast(Object obj, Class type, Class toType) throws NoSupportTypeCastException, NumberFormatException, IllegalArgumentException { return typeCast(obj, type, toType,null,(Locale )null); } public static byte[] getByteArrayFromBlob(Blob blob) throws SQLException { if(blob == null) return null; ByteArrayOutputStream out = null; InputStream in = null; try { out = new ByteArrayOutputStream(); in = blob.getBinaryStream(); byte[] buf = new byte[1024]; int i =0; while((i = in.read(buf)) > 0) { // System.out.println("i=" + i); out.write(buf,0,i); } return out.toByteArray(); } catch(SQLException e) { throw e; } catch(Exception e) { throw new NestedSQLException(e); } finally { try { if(out != null) { out.close(); out = null; } } catch(Exception e) { } try { if(in != null) { in.close(); in = null; } } catch(Exception e) { } } } public static String getStringFromBlob(Blob blob) throws SQLException { if(blob == null) return null; OutputStream out = null; InputStream in = null; try { out = new ByteArrayOutputStream(); in = blob.getBinaryStream(); byte[] buf = new byte[1024]; int i =0; while((i = in.read(buf)) > 0) { // System.out.println("i=" + i); out.write(buf,0,i); } return out.toString(); } catch(SQLException e) { throw e; } catch(Exception e) { throw new NestedSQLException(e); } finally { try { if(out != null) { out.close(); out = null; } } catch(Exception e) { } try { if(in != null) { in.close(); in = null; } } catch(Exception e) { } } } public static byte[] getByteArrayFromClob(Clob clob) throws SQLException { if(clob == null) return null; StringWriter w = null; Reader out = null; try { w = new StringWriter(); out = clob.getCharacterStream(); char[] buf = new char[1024]; int i =0; while((i = out.read(buf)) > 0) { w.write(buf,0,i); } String temp = w.toString(); return temp.getBytes(); } catch(SQLException e) { throw e; } catch(Exception e) { throw new NestedSQLException(e); } finally { try { if(out != null) { out.close(); out = null; } } catch(Exception e) { } try { if(w != null) { w.close(); w = null; } } catch(Exception e) { } } } public static String getStringFromClob(Clob clob) throws SQLException { if(clob == null) return null; StringWriter w = null; Reader out = null; try { w = new StringWriter(); out = clob.getCharacterStream(); char[] buf = new char[1024]; int i =0; while((i = out.read(buf)) > 0) { w.write(buf,0,i); } return w.toString(); } catch(SQLException e) { throw e; } catch(Exception e) { throw new NestedSQLException(e); } finally { try { if(out != null) { out.close(); out = null; } } catch(Exception e) { } try { if(w != null) { w.close(); w = null; } } catch(Exception e) { } } } public static String getByteStringFromBlob(Blob blob) throws SQLException { if(blob == null) return null; ByteArrayOutputStream out = null; InputStream in = null; try { out = new ByteArrayOutputStream(); in = blob.getBinaryStream(); byte[] buf = new byte[1024]; int i =0; while((i = in.read(buf)) > 0) { // System.out.println("i=" + i); out.write(buf,0,i); } Base64 en = new Base64(); return en.encode(out.toByteArray()); } catch(SQLException e) { throw e; } catch(Exception e) { throw new NestedSQLException(e); } finally { try { if(out != null) { out.close(); out = null; } } catch(Exception e) { } try { if(in != null) { in.close(); in = null; } } catch(Exception e) { } } } /** * 父类型向子类型转换 * @param obj * @param toType * @return */ public static Object cast(Object obj,Class toType) { // if (!java.util.Date.class.isAssignableFrom(type)) { if(!toType.isArray()) return toType.cast(obj); else { int size = Array.getLength(obj); Class ctype = toType.getComponentType(); Object ret = Array.newInstance(ctype, size); for(int i = 0; i < size; i ++) { Array.set(ret, i,ctype.cast(Array.get(obj, i))); } return ret; } } /** * 日期类型处理比较特殊 */ // return null; } public final static Object typeCast(Object obj, Class type, Class toType,String dateformat ) throws NoSupportTypeCastException, NumberFormatException, IllegalArgumentException { return typeCast( obj, type, toType, dateformat,(Locale )null); } /** * 将obj对象从类型type转换到类型toType 支持字符串向其他基本类行转换: 支持的类型: * int,char,short,double,float,long,boolean,byte * java.sql.Date,java.util.Date, Integer Long Float Short Double Character * Boolean Byte * * @param obj * @param type * @param toType * @return Object * @throws ClassCastException * ,NumberFormatException,IllegalArgumentException */ public final static Object typeCast(Object obj, Class type, Class toType,String dateformat,Locale locale) throws NoSupportTypeCastException, NumberFormatException, IllegalArgumentException { if (obj == null) return null; if (isSameType(type, toType, obj)) return obj; if (type.isAssignableFrom(toType)) // type是toType的父类,父类向子类转换的过程,这个转换过程是不安全的 { // return shell(toType,obj); if (!java.util.Date.class.isAssignableFrom(type)) // return toType.cast(obj); return cast(obj,toType); } if (type == byte[].class && toType == String.class) { return new String((byte[]) obj); } else if (type == String.class && toType == byte[].class) { return ((String) obj).getBytes(); } else if (Blob.class.isAssignableFrom(type) ) { try { if( File.class.isAssignableFrom(toType)) { File tmp = File.createTempFile(UUID.randomUUID().toString(),".tmp"); getFileFromBlob((Blob)obj,tmp); return tmp; } else if( byte[].class.isAssignableFrom(toType)) { return ValueObjectUtil.getByteArrayFromBlob((Blob)obj); } else return ValueObjectUtil.getStringFromBlob((Blob)obj); } catch (Exception e) { throw new IllegalArgumentException(new StringBuilder().append( "类型无法转换,不支持[").append(type.getName()).append("]向[") .append(toType.getName()).append("]转换").append(",value is ").append(obj).toString()); } } else if (Clob.class.isAssignableFrom(type) ) { try { if( File.class.isAssignableFrom(toType)) { File tmp = File.createTempFile(UUID.randomUUID().toString(),".tmp"); getFileFromClob((Clob)obj,tmp); return tmp; } else if( byte[].class.isAssignableFrom(toType)) { return ValueObjectUtil.getByteArrayFromClob((Clob)obj); } else return ValueObjectUtil.getStringFromClob((Clob)obj); } catch (Exception e) { throw new IllegalArgumentException(new StringBuilder().append( "类型无法转换,不支持[").append(type.getName()).append("]向[") .append(toType.getName()).append("]转换").append(",value is ").append(obj).toString()); } } else if (type == byte[].class && File.class.isAssignableFrom(toType)) { ByteArrayInputStream byteIn = null; FileOutputStream fileOut = null; if(!(obj instanceof byte[])) { Object[] object = (Object[]) obj; try { byteIn = new ByteArrayInputStream((byte[]) object[0]); fileOut = new FileOutputStream((File) object[1]); byte v[] = new byte[1024]; int i = 0; while ((i = byteIn.read(v)) > 0) { fileOut.write(v, 0, i); } fileOut.flush(); return object[1]; } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (byteIn != null) byteIn.close(); } catch (Exception e) { } try { if (fileOut != null) fileOut.close(); } catch (Exception e) { } } } else { try { byteIn = new ByteArrayInputStream((byte[]) obj); File f = File.createTempFile(UUID.randomUUID().toString(), ".soa"); fileOut = new FileOutputStream(f); byte v[] = new byte[1024]; int i = 0; while ((i = byteIn.read(v)) > 0) { fileOut.write(v, 0, i); } fileOut.flush(); return f; } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (byteIn != null) byteIn.close(); } catch (Exception e) { } try { if (fileOut != null) fileOut.close(); } catch (Exception e) { } } } } else if (List.class.isAssignableFrom(toType)) { if (!type.isArray()) { List valueto = new ArrayList(); valueto.add(obj); return valueto; } else { if (type == String[].class) { List valueto = new ArrayList(); for (String data : (String[]) obj) valueto.add(data); return valueto; } } } else if (Set.class.isAssignableFrom(toType)) { if (!type.isArray()) { Set valueto = new TreeSet(); valueto.add(obj); return valueto; } else { if (type == String[].class) { Set valueto = new TreeSet(); for (String data : (String[]) obj) valueto.add(data); return valueto; } } } else if (File.class.isAssignableFrom(toType) && toType == byte[].class) { FileInputStream in = null; ByteArrayOutputStream out = null; try { int i = 0; in = new FileInputStream((File) obj); out = new ByteArrayOutputStream(); byte v[] = new byte[1024]; while ((i = in.read(v)) > 0) { out.write(v, 0, i); } return out.toByteArray(); } catch (Exception e) { } finally { try { if (in != null) in.close(); } catch (Exception e) { } try { if (out != null) out.close(); } catch (Exception e) { } } } else if (type.isArray() && !toType.isArray()){ //|| !type.isArray() //&& toType.isArray()) { // if (type.getName().startsWith("[") // && !toType.getName().startsWith("[") // || !type.getName().startsWith("[") // && toType.getName().startsWith("[")) throw new IllegalArgumentException(new StringBuilder().append("类型无法转换,不支持[") .append(type.getName()).append("]向[").append( toType.getName()).append("]转换").append(",value is ").append(obj).toString()); } else if (type == String.class && toType == Class.class) { try { return getClass((String) obj); } catch (ClassNotFoundException e) { throw new IllegalArgumentException(new StringBuilder().append( "类型无法转换,不支持[").append(type.getName()).append("]向[") .append(toType.getName()).append("]转换").toString(),e); } } Object arrayObj; /** * 基本类型转换和基本类型之间相互转换 */ if (!type.isArray() && !toType.isArray()) { arrayObj = basicTypeCast(obj, type, toType,dateformat, locale); } /** * 字符串数组向其他类型数组之间转换 * 数组和数组之间的转换 * 基础类型数据向数组转换 */ else { arrayObj = arrayTypeCast(obj, type, toType,dateformat); } return arrayObj; } public final static Object typeCastWithDateformat(Object obj, Class type, Class toType,DateFormat dateformat) throws NoSupportTypeCastException, NumberFormatException, IllegalArgumentException { if (obj == null) return null; if (isSameType(type, toType, obj)) return obj; if (type.isAssignableFrom(toType)) // type是toType的父类,父类向子类转换的过程,这个转换过程是不安全的 { // return shell(toType,obj); if (!java.util.Date.class.isAssignableFrom(type)) // return toType.cast(obj); return cast(obj,toType); } if (type == byte[].class && toType == String.class) { return new String((byte[]) obj); } else if (type == String.class && toType == byte[].class) { return ((String) obj).getBytes(); } else if (Blob.class.isAssignableFrom(type) ) { try { if( File.class.isAssignableFrom(toType)) { File tmp = File.createTempFile(UUID.randomUUID().toString(),".tmp"); getFileFromBlob((Blob)obj,tmp); return tmp; } else if( byte[].class.isAssignableFrom(toType)) { return ValueObjectUtil.getByteArrayFromBlob((Blob)obj); } else return ValueObjectUtil.getStringFromBlob((Blob)obj); } catch (Exception e) { throw new IllegalArgumentException(new StringBuilder().append( "类型无法转换,不支持[").append(type.getName()).append("]向[") .append(toType.getName()).append("]转换").append(",value is ").append(obj).toString()); } } else if (Clob.class.isAssignableFrom(type) ) { try { if( File.class.isAssignableFrom(toType)) { File tmp = File.createTempFile(UUID.randomUUID().toString(),".tmp"); getFileFromClob((Clob)obj,tmp); return tmp; } else if( byte[].class.isAssignableFrom(toType)) { return ValueObjectUtil.getByteArrayFromClob((Clob)obj); } else return ValueObjectUtil.getStringFromClob((Clob)obj); } catch (Exception e) { throw new IllegalArgumentException(new StringBuilder().append( "类型无法转换,不支持[").append(type.getName()).append("]向[") .append(toType.getName()).append("]转换").append(",value is ").append(obj).toString()); } } else if (type == byte[].class && File.class.isAssignableFrom(toType)) { ByteArrayInputStream byteIn = null; FileOutputStream fileOut = null; if(!(obj instanceof byte[])) { Object[] object = (Object[]) obj; try { byteIn = new ByteArrayInputStream((byte[]) object[0]); fileOut = new FileOutputStream((File) object[1]); byte v[] = new byte[1024]; int i = 0; while ((i = byteIn.read(v)) > 0) { fileOut.write(v, 0, i); } fileOut.flush(); return object[1]; } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (byteIn != null) byteIn.close(); } catch (Exception e) { } try { if (fileOut != null) fileOut.close(); } catch (Exception e) { } } } else { try { byteIn = new ByteArrayInputStream((byte[]) obj); File f = File.createTempFile(UUID.randomUUID().toString(), ".soa"); fileOut = new FileOutputStream(f); byte v[] = new byte[1024]; int i = 0; while ((i = byteIn.read(v)) > 0) { fileOut.write(v, 0, i); } fileOut.flush(); return f; } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (byteIn != null) byteIn.close(); } catch (Exception e) { } try { if (fileOut != null) fileOut.close(); } catch (Exception e) { } } } } else if (List.class.isAssignableFrom(toType)) { if (!type.isArray()) { List valueto = new ArrayList(); valueto.add(obj); return valueto; } else { if (type == String[].class) { List valueto = new ArrayList(); for (String data : (String[]) obj) valueto.add(data); return valueto; } } } else if (Set.class.isAssignableFrom(toType)) { if (!type.isArray()) { Set valueto = new TreeSet(); valueto.add(obj); return valueto; } else { if (type == String[].class) { Set valueto = new TreeSet(); for (String data : (String[]) obj) valueto.add(data); return valueto; } } } else if (File.class.isAssignableFrom(toType) && toType == byte[].class) { FileInputStream in = null; ByteArrayOutputStream out = null; try { int i = 0; in = new FileInputStream((File) obj); out = new ByteArrayOutputStream(); byte v[] = new byte[1024]; while ((i = in.read(v)) > 0) { out.write(v, 0, i); } return out.toByteArray(); } catch (Exception e) { } finally { try { if (in != null) in.close(); } catch (Exception e) { } try { if (out != null) out.close(); } catch (Exception e) { } } } else if (type.isArray() && !toType.isArray()){ //|| !type.isArray() //&& toType.isArray()) { // if (type.getName().startsWith("[") // && !toType.getName().startsWith("[") // || !type.getName().startsWith("[") // && toType.getName().startsWith("[")) throw new IllegalArgumentException(new StringBuilder().append("类型无法转换,不支持[") .append(type.getName()).append("]向[").append( toType.getName()).append("]转换").append(",value is ").append(obj).toString()); } else if (type == String.class && toType == Class.class) { try { return getClass((String) obj); } catch (ClassNotFoundException e) { throw new IllegalArgumentException(new StringBuilder().append( "类型无法转换,不支持[").append(type.getName()).append("]向[") .append(toType.getName()).append("]转换").toString(),e); } } Object arrayObj; /** * 基本类型转换和基本类型之间相互转换 */ if (!type.isArray() && !toType.isArray()) { arrayObj = basicTypeCastWithDateformat(obj, type, toType,dateformat); } /** * 字符串数组向其他类型数组之间转换 * 数组和数组之间的转换 * 基础类型数据向数组转换 */ else { arrayObj = arrayTypeCastWithDateformat(obj, type, toType,dateformat); } return arrayObj; } /** * 通过BeanShell脚本来转换对象类型 * * @param toType * @param obj * @return */ public static Object shell(Class toType, Object obj) { return toType.cast(obj); // Interpreter interpreter = new Interpreter(); // String shell = toType.getName() + " ret = (" + toType.getName() // + ")obj;return ret;"; // try { // interpreter.set("obj", obj); // Object ret = interpreter.eval(shell); // return ret; // } catch (Exception e) { // throw new RuntimeException(e); // } } public final static Object basicTypeCast(Object obj, Class type, Class toType) throws NoSupportTypeCastException, NumberFormatException { return basicTypeCast( obj, type, toType,null,(Locale )null); } // public static SimpleDateFormat getDateFormat( // String dateformat) // { // if(dateformat == null || dateformat.equals("")) // return format; // SimpleDateFormat f = dataformats.get(dateformat); // if(f != null) // return f; // f = new SimpleDateFormat(dateformat); // dataformats.put(dateformat, f); // return f; // } public static SimpleDateFormat getDefaultDateFormat(){ return DataFormatUtil.getSimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // return new SimpleDateFormat( // "yyyy-MM-dd HH:mm:ss"); } public static SimpleDateFormat getDateFormat( String dateformat,Locale locale) { if(dateformat == null || dateformat.equals("")) return getDefaultDateFormat(); SimpleDateFormat f = DataFormatUtil.getSimpleDateFormat(dateformat, locale); // if(f != null) // return f; // dataformats.put(dateformat, f); return f; } public static Boolean toBoolean(Object obj) { if(obj == null) return new Boolean(false); if(obj instanceof Boolean) { return ((Boolean)obj); } else if(obj instanceof String) { String ret = obj.toString(); if (ret.equals("1") || ret.equals("true")) { return new Boolean(true); } else if (ret.equals("0") || ret.equals("false")) { return new Boolean(false); } else return false; } else if(obj instanceof Integer) { return ((Integer)obj).intValue() > 0; } else if(obj instanceof Long) { return ((Long)obj).longValue() > 0; } else if(obj instanceof Double) { return ((Double)obj).doubleValue() > 0; } else if(obj instanceof Float) { return ((Float)obj).floatValue() > 0; } else if(obj instanceof Short) { return ((Short)obj).shortValue() > 0; } else if(obj instanceof BigInteger) { return ((BigInteger)obj).intValue() > 0; } else if(obj instanceof BigDecimal) { return ((BigDecimal)obj).floatValue() > 0; } return false; } public final static Object basicTypeCast(Object obj, Class type, Class toType,String dateformat ) throws NoSupportTypeCastException, NumberFormatException { return basicTypeCast( obj, type, toType, dateformat,(Locale )null); } /** * Description:基本的数据类型转圜 * * @param obj * @param type * @param toType * @return Object * @throws NoSupportTypeCastException * @throws NumberFormatException * */ public final static Object basicTypeCast(Object obj, Class type, Class toType,String dateformat,Locale locale) throws NoSupportTypeCastException, NumberFormatException { if (obj == null) return null; if (isSameType(type, toType, obj)) return obj; if (type.isAssignableFrom(toType)) // type是toType的父类,父类向子类转换的过程,这个转换过程是不安全的 { if (!java.util.Date.class.isAssignableFrom(type)) return shell(toType, obj); } /** * 如果obj的类型不是String型时直接抛异常, 不支持非字符串和字符串数组的类型转换 */ // if (type != String.class) // throw new NoSupportTypeCastException( // new StringBuilder().append("不支持[") // .append(type) // .append("]向[") // .append(toType) // .append("]的转换") // .toString()); /******************************************* * 字符串向基本类型及其包装器转换 * 如果obj不是相应得数据格式,将抛出 * NumberFormatException * ******************************************/ if (toType == long.class || toType == Long.class) { if (ValueObjectUtil.isNumber(obj)) return ((Number) obj).longValue(); else if(java.util.Date.class.isAssignableFrom(type)) { return ((java.util.Date)obj).getTime(); } return Long.parseLong(obj.toString()); } if (toType == int.class || toType == Integer.class) { if (ValueObjectUtil.isNumber(obj)) return ((Number) obj).intValue(); return Integer.parseInt(obj.toString()); } if (toType == float.class || toType == Float.class) { if (ValueObjectUtil.isNumber(obj)) return ((Number) obj).floatValue(); return Float.parseFloat(obj.toString()); } if (toType == short.class || toType == Short.class) { if (ValueObjectUtil.isNumber(obj)) return ((Number) obj).shortValue(); return Short.parseShort(obj.toString()); } if (toType == double.class || toType == Double.class) { if (ValueObjectUtil.isNumber(obj)) return ((Number) obj).doubleValue(); return Double.parseDouble(obj.toString()); } if (toType == char.class || toType == Character.class) return new Character(obj.toString().charAt(0)); if (toType == boolean.class || toType == Boolean.class) { // String ret = obj.toString(); // if (ret.equals("1") || ret.equals("true")) { // return new Boolean(true); // } else if (ret.equals("0") || ret.equals("false")) { // return new Boolean(false); // } // return new Boolean(ret); return toBoolean(obj); } if (toType == byte.class || toType == Byte.class) return new Byte(obj.toString()); if(toType == BigDecimal.class) { return converObjToBigDecimal(obj); } if(toType == BigInteger.class) { return converObjToBigInteger(obj); } // 如果是字符串则直接返回obj.toString() if (toType == String.class) { if (obj instanceof java.util.Date) { if(!"".equals(obj)) return getDateFormat(dateformat, locale).format(obj); return null; } return obj.toString(); } Object date = convertObjToDate( obj,toType,dateformat,locale); if(date != null) return date; if (type == String.class && toType == Class.class) { try { return getClass((String) obj); } catch (ClassNotFoundException e) { throw new IllegalArgumentException(new StringBuilder().append( "类型无法转换,不支持[").append(type.getName()).append("]向[") .append(toType.getName()).append("]转换").toString(),e); } } if (type == String.class && toType.isEnum()) { try { return convertStringToEnum((String )obj,toType); } catch (SecurityException e) { throw new IllegalArgumentException(new StringBuilder().append( "类型无法转换,不支持[").append(type.getName()).append("]向枚举类型[") .append(toType.getName()).append("]转换,超出枚举值范围").append(",value is ").append(obj).toString()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(new StringBuilder().append( "类型无法转换,不支持[").append(type.getName()).append("]向枚举类型[") .append(toType.getName()).append("]转换,超出枚举值范围").append(",value is ").append(obj).toString()); } catch (NoSuchMethodException e) { throw new IllegalArgumentException(new StringBuilder().append( "类型无法转换,不支持[").append(type.getName()).append("]向枚举类型[") .append(toType.getName()).append("]转换,超出枚举值范围").append(",value is ").append(obj).toString()); } catch (IllegalAccessException e) { throw new IllegalArgumentException(new StringBuilder().append( "类型无法转换,不支持[").append(type.getName()).append("]向枚举类型[") .append(toType.getName()).append("]转换,超出枚举值范围").append(",value is ").append(obj).toString()); } catch (InvocationTargetException e) { throw new IllegalArgumentException(new StringBuilder().append( "类型无法转换,不支持[").append(type.getName()).append("]向枚举类型[") .append(toType.getName()).append("]转换,超出枚举值范围").append(",value is ").append(obj).toString()); } } throw new NoSupportTypeCastException(new StringBuilder().append("不支持[").append( type).append("]向[").append(toType).append("]的转换").append(",value is ").append(obj).toString()); } public final static Object basicTypeCastWithDateformat(Object obj, Class type, Class toType,DateFormat dateformat) throws NoSupportTypeCastException, NumberFormatException { if (obj == null) return null; if (isSameType(type, toType, obj)) return obj; if (type.isAssignableFrom(toType)) // type是toType的父类,父类向子类转换的过程,这个转换过程是不安全的 { if (!java.util.Date.class.isAssignableFrom(type)) return shell(toType, obj); } /** * 如果obj的类型不是String型时直接抛异常, 不支持非字符串和字符串数组的类型转换 */ // if (type != String.class) // throw new NoSupportTypeCastException( // new StringBuilder("不支持[") // .append(type) // .append("]向[") // .append(toType) // .append("]的转换") // .toString()); /******************************************* * 字符串向基本类型及其包装器转换 * 如果obj不是相应得数据格式,将抛出 * NumberFormatException * ******************************************/ if (toType == long.class || toType == Long.class) { if (ValueObjectUtil.isNumber(obj)) return ((Number) obj).longValue(); else if(java.util.Date.class.isAssignableFrom(type)) { return ((java.util.Date)obj).getTime(); } return Long.parseLong(obj.toString()); } if (toType == int.class || toType == Integer.class) { if (ValueObjectUtil.isNumber(obj)) return ((Number) obj).intValue(); return Integer.parseInt(obj.toString()); } if (toType == float.class || toType == Float.class) { if (ValueObjectUtil.isNumber(obj)) return ((Number) obj).floatValue(); return Float.parseFloat(obj.toString()); } if (toType == short.class || toType == Short.class) { if (ValueObjectUtil.isNumber(obj)) return ((Number) obj).shortValue(); return Short.parseShort(obj.toString()); } if (toType == double.class || toType == Double.class) { if (ValueObjectUtil.isNumber(obj)) return ((Number) obj).doubleValue(); return Double.parseDouble(obj.toString()); } if (toType == char.class || toType == Character.class) return new Character(obj.toString().charAt(0)); if (toType == boolean.class || toType == Boolean.class) { // String ret = obj.toString(); // if (ret.equals("1") || ret.equals("true")) { // return new Boolean(true); // } else if (ret.equals("0") || ret.equals("false")) { // return new Boolean(false); // } // return new Boolean(obj.toString()); return toBoolean(obj); } if (toType == byte.class || toType == Byte.class) return new Byte(obj.toString()); if(toType == BigDecimal.class) { return converObjToBigDecimal(obj); } // 如果是字符串则直接返回obj.toString() if (toType == String.class) { if (obj instanceof java.util.Date) { if(!"".equals(obj)) { if(dateformat == null) dateformat = ValueObjectUtil.getDefaultDateFormat(); return dateformat.format(obj); } return null; } return obj.toString(); } Object date = convertObjToDateWithDateformat( obj,toType,dateformat); if(date != null) return date; if (type == String.class && toType == Class.class) { try { return getClass((String) obj); } catch (ClassNotFoundException e) { throw new IllegalArgumentException(new StringBuilder().append( "类型无法转换,不支持[").append(type.getName()).append("]向[") .append(toType.getName()).append("]转换").toString(),e); } } if (type == String.class && toType.isEnum()) { try { return convertStringToEnum((String )obj,toType); } catch (SecurityException e) { throw new IllegalArgumentException(new StringBuilder().append( "类型无法转换,不支持[").append(type.getName()).append("]向枚举类型[") .append(toType.getName()).append("]转换,超出枚举值范围").append(",value is ").append(obj).toString()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(new StringBuilder().append( "类型无法转换,不支持[").append(type.getName()).append("]向枚举类型[") .append(toType.getName()).append("]转换,超出枚举值范围").append(",value is ").append(obj).toString()); } catch (NoSuchMethodException e) { throw new IllegalArgumentException(new StringBuilder().append( "类型无法转换,不支持[").append(type.getName()).append("]向枚举类型[") .append(toType.getName()).append("]转换,超出枚举值范围").append(",value is ").append(obj).toString()); } catch (IllegalAccessException e) { throw new IllegalArgumentException(new StringBuilder().append( "类型无法转换,不支持[").append(type.getName()).append("]向枚举类型[") .append(toType.getName()).append("]转换,超出枚举值范围").append(",value is ").append(obj).toString()); } catch (InvocationTargetException e) { throw new IllegalArgumentException(new StringBuilder().append( "类型无法转换,不支持[").append(type.getName()).append("]向枚举类型[") .append(toType.getName()).append("]转换,超出枚举值范围").append(",value is ").append(obj).toString()); } } throw new NoSupportTypeCastException(new StringBuilder().append("不支持[").append( type).append("]向[").append(toType).append("]的转换").append(",value is ").append(obj).toString()); } public static BigDecimal converObjToBigDecimal(Object obj) { if(obj.getClass() == long.class || obj.getClass() == Long.class) return BigDecimal.valueOf((Long)obj); if(obj.getClass() == short.class || obj.getClass() == Short.class) return BigDecimal.valueOf((Short)obj); if(obj.getClass() == int.class || obj.getClass() == Integer.class) return BigDecimal.valueOf((Integer)obj); if(obj.getClass() == double.class || obj.getClass() == Double.class) return BigDecimal.valueOf((Double)obj); if(obj.getClass() == float.class || obj.getClass() == Float.class) return BigDecimal.valueOf((Float)obj); return new BigDecimal(obj.toString()); } public static BigInteger converObjToBigInteger(Object obj) { if(obj.getClass() == long.class || obj.getClass() == Long.class) return BigInteger.valueOf((Long)obj); if(obj.getClass() == short.class || obj.getClass() == Short.class) return BigInteger.valueOf((Short)obj); if(obj.getClass() == int.class || obj.getClass() == Integer.class) return BigInteger.valueOf((Integer)obj); if(obj.getClass() == double.class || obj.getClass() == Double.class) return BigInteger.valueOf(((Double)obj).longValue()); if(obj.getClass() == float.class || obj.getClass() == Float.class) return BigInteger.valueOf(((Float)obj).longValue()); return new BigInteger(obj.toString()); } public static Object convertObjToDate(Object obj,Class toType,String dateformat ) { return convertObjToDate( obj, toType, dateformat,(Locale )null); } public static Object convertObjToDate(Object obj,Class toType,String dateformat,Locale locale) { if(dateformat == null) return convertObjToDateWithDateformat(obj,toType,null); else return convertObjToDateWithDateformat(obj,toType,ValueObjectUtil.getDateFormat(dateformat, locale)); } public static Object convertObjToDateWithDateformat(Object obj,Class toType,DateFormat dateformat) { /** * 字符串向java.util.Date和java.sql.Date 类型转换 */ if (toType == java.util.Date.class) { if (java.util.Date.class.isAssignableFrom(obj.getClass())) return obj; if(obj.getClass() == long.class || obj.getClass() == Long.class) { return new java.util.Date((Long)obj); } String data_str = obj.toString(); if(!"".equals(data_str)) { if(dateformat == null) { try { long dl = Long.parseLong(data_str); return new java.util.Date(dl); } catch (Exception e1) { try { dateformat = ValueObjectUtil.getDefaultDateFormat(); return new java.util.Date(dateformat.parse(data_str).getTime()); } catch (ParseException e) { throw new IllegalArgumentException(new StringBuilder().append("Date format [").append(((SimpleDateFormat)dateformat).toPattern()).append("] can not format date : ").append(data_str).toString(),e); } } } else { try { return new java.util.Date(dateformat.parse(data_str).getTime()); } catch (ParseException e) { try { long dl = Long.parseLong(data_str); return new java.util.Date(dl); } catch (Exception e1) { throw new IllegalArgumentException(new StringBuilder().append("Date format [").append(((SimpleDateFormat)dateformat).toPattern()).append("] can not format date : ").append(data_str).toString(),e); } } } } else return null; // return new java.util.Date(data_str); } if (toType == Date.class) { // if(obj instanceof java.sql.Date // || obj instanceof java.sql.Time // || obj instanceof java.sql.Timestamp) if (java.util.Date.class.isAssignableFrom(obj.getClass())) return new Date(((java.util.Date) obj).getTime()); if(obj.getClass() == long.class || obj.getClass() == Long.class) { return new Date((Long)obj); } else if(obj.getClass() == int.class || obj.getClass() == Integer.class){ return new Date(((Integer)obj).longValue()); } String data_str = obj.toString(); if(!"".equals(data_str)) { if(dateformat == null) { try { long dl = Long.parseLong(data_str); return new Date(dl); } catch (Exception e1) { try { dateformat = ValueObjectUtil.getDefaultDateFormat(); return new Date(dateformat.parse(data_str).getTime()); } catch (ParseException e) { throw new IllegalArgumentException(new StringBuilder().append("Date format [").append(((SimpleDateFormat)dateformat).toPattern()).append("] can not format date : ").append(data_str).toString(),e); } } } else { try { return new Date(dateformat.parse(data_str).getTime()); } catch (ParseException e) { try { long dl = Long.parseLong(data_str); return new Date(dl); } catch (Exception e1) { throw new IllegalArgumentException(new StringBuilder().append("Date format [").append(((SimpleDateFormat)dateformat).toPattern()).append("] can not format date : ").append(data_str).toString(),e); } } } } else return null; // java.util.Date(obj.toString()).getTime()); } if (toType == java.sql.Timestamp.class) { // if(obj instanceof java.sql.Date // || obj instanceof java.sql.Time // || obj instanceof java.sql.Timestamp) if (java.util.Date.class.isAssignableFrom(obj.getClass())) return new java.sql.Timestamp(((java.util.Date) obj).getTime()); if(obj.getClass() == long.class || obj.getClass() == Long.class) { return new java.sql.Timestamp((Long)obj); } String data_str = obj.toString(); if(!"".equals(data_str)) { if(dateformat == null) { try { long dl = Long.parseLong(data_str); return new java.sql.Timestamp(dl); } catch (Exception e1) { try { dateformat = ValueObjectUtil.getDefaultDateFormat(); return new java.sql.Timestamp(dateformat.parse(data_str).getTime()); } catch (ParseException e) { throw new IllegalArgumentException(new StringBuilder().append("Date format [").append(((SimpleDateFormat)dateformat).toPattern()).append("] can not format date : ").append(data_str).toString(),e); } } } else { try { return new java.sql.Timestamp(dateformat.parse(data_str).getTime()); } catch (ParseException e) { try { long dl = Long.parseLong(data_str); return new java.sql.Timestamp(dl); } catch (Exception e1) { throw new IllegalArgumentException(new StringBuilder().append("Date format [").append(((SimpleDateFormat)dateformat).toPattern()).append("] can not format date : ").append(data_str).toString(),e); } } } } else return null; //java.sql.Timestamp date = new Timestamp(java.sql.Date.valueOf(data_str).getTime());// (new // java.util.Date(obj.toString()).getTime()); //return date; } return null; } public static <T> T convertStringToEnum(String value,Class<T> enumType) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { Method valueof = enumType.getMethod("valueOf", String.class); return (T)valueof.invoke(null, value); } /** * * @param <T> * @param value * @param enumType * @param arrays * @return * @throws SecurityException * @throws NoSuchMethodException * @throws IllegalArgumentException * @throws IllegalAccessException * @throws InvocationTargetException */ public static <T> T[] convertStringToEnumArray(String value,Class<T> enumType,T[] arrays) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { Method valueof = enumType.getMethod("valueOf", String.class); Array.set(arrays, 0, valueof.invoke(null, value)); return arrays; } public static <T> T[] convertStringsToEnumArray(String[] value,Class<T> enumType,T[] arrays) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { if(value == null) return null; // if(value.length == 0) int i = 0; Method valueof = enumType.getMethod("valueOf", String.class); for(String v:value) { Array.set(arrays, i, valueof.invoke(null, value[i])); i ++; } return arrays; } public static <T> T[] convertStringToEnumArray(String value,Class<T> enumType) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { Method valueof = enumType.getMethod("valueOf", String.class); Object retvalue = Array.newInstance(enumType, 1); Array.set(retvalue, 0, valueof.invoke(null, value)); return (T[])retvalue; } public static <T> T[] convertStringsToEnumArray(String[] value,Class<T> enumType) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { if(value == null) return null; // if(value.length == 0) Object retvalue = Array.newInstance(enumType, value.length); int i = 0; Method valueof = enumType.getMethod("valueOf", String.class); for(String v:value) { Array.set(retvalue, i, valueof.invoke(null, value[i])); i ++; } return (T[])retvalue; // return temp_; } public final static Object arrayTypeCast(Object obj, Class type, Class toType) throws NoSupportTypeCastException, NumberFormatException { return arrayTypeCast(obj, type, toType,null); } public final static Object arrayTypeCast(Object obj, Class type, Class toType,String dateformat) throws NoSupportTypeCastException, NumberFormatException{ SimpleDateFormat dateformat_ = null; if(dateformat != null) dateformat_ = DataFormatUtil.getSimpleDateFormat(dateformat); return arrayTypeCastWithDateformat(obj, type, toType,dateformat_); } /** * 数组类型转换 支持字符串数组向一下类型数组得自动转换: int[] Integer[] long[] Long[] short[] Short[] * double[] Double[] boolean[] Boolean[] char[] Character[] float[] Float[] * byte[] Byte[] java.sql.Date[] java.util.Date[] * * @param obj * @param type * @param toType * @return Object * @throws NoSupportTypeCastException * @throws NumberFormatException */ public final static Object arrayTypeCastWithDateformat(Object obj, Class type, Class toType,DateFormat dateformat) throws NoSupportTypeCastException, NumberFormatException { if (isSameType(type, toType, obj)) return obj; // if (type != String[].class) // throw new NoSupportTypeCastException( // new StringBuilder("不支持[") // .append(type) // .append("]向[") // .append(toType) // .append("]的转换") // .toString()); if(dateformat == null) dateformat = ValueObjectUtil.getDefaultDateFormat(); if (toType == long[].class) { Class componentType = ValueObjectUtil.isNumberArray(obj); if (componentType == null) { if(java.util.Date.class.isAssignableFrom(type)) { java.util.Date date = (java.util.Date)obj; return new long[]{date.getTime()}; } else if(!isDateArray(obj)) { String[] values = (String[]) obj; long[] ret = new long[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = Long.parseLong(values[i]); } return ret; } else { int len = Array.getLength(obj); long[] ret = new long[len]; for(int i = 0; i < len; i ++) { java.util.Date date = (java.util.Date)Array.get(obj, i); ret[i] = date.getTime(); } return ret; } } else { return ValueObjectUtil.tolongArray(obj, componentType); } } if (toType == Long[].class) { Class componentType = ValueObjectUtil.isNumberArray(obj); if (componentType == null) { if(!isDateArray(obj)) { String[] values = (String[]) obj; Long[] ret = new Long[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = new Long(values[i]); } return ret; } else { int len = Array.getLength(obj); Long[] ret = new Long[len]; for(int i = 0; i < len; i ++) { java.util.Date date = (java.util.Date)Array.get(obj, i); ret[i] = date.getTime(); } return ret; } } else { return ValueObjectUtil.toLongArray(obj, componentType); } } if (toType == int[].class) { Class componentType = ValueObjectUtil.isNumberArray(obj); if (componentType == null) { String[] values = (String[]) obj; int[] ret = new int[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = Integer.parseInt(values[i]); } return ret; } else { return ValueObjectUtil.toIntArray(obj, componentType); } } if (toType == Integer[].class) { Class componentType = ValueObjectUtil.isNumberArray(obj); if (componentType == null) { String[] values = (String[]) obj; Integer[] ret = new Integer[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = new Integer(values[i]); } return ret; } else { return ValueObjectUtil.toIntegerArray(obj, componentType); } } if (toType == float[].class) { Class componentType = ValueObjectUtil.isNumberArray(obj); if (componentType == null) { String[] values = (String[]) obj; float[] ret = new float[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = Float.parseFloat(values[i]); } return ret; } else { return ValueObjectUtil.tofloatArray(obj, componentType); } } if (toType == Float[].class) { Class componentType = ValueObjectUtil.isNumberArray(obj); if (componentType == null) { String[] values = (String[]) obj; Float[] ret = new Float[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = new Float(values[i]); } return ret; } else { return ValueObjectUtil.toFloatArray(obj, componentType); } } if (toType == short[].class) { Class componentType = ValueObjectUtil.isNumberArray(obj); if (componentType == null) { String[] values = (String[]) obj; short[] ret = new short[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = Short.parseShort(values[i]); } return ret; } else { return ValueObjectUtil.toshortArray(obj, componentType); } } if (toType == Short[].class) { Class componentType = ValueObjectUtil.isNumberArray(obj); if (componentType == null) { String[] values = (String[]) obj; Short[] ret = new Short[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = new Short(values[i]); } return ret; } else { return ValueObjectUtil.toShortArray(obj, componentType); } } if (toType == double[].class) { Class componentType = ValueObjectUtil.isNumberArray(obj); if (componentType == null) { String[] values = (String[]) obj; double[] ret = new double[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = Double.parseDouble(values[i]); } return ret; } else { return ValueObjectUtil.todoubleArray(obj, componentType); } } if (toType == Double[].class) { Class componentType = ValueObjectUtil.isNumberArray(obj); if (componentType == null) { String[] values = (String[]) obj; Double[] ret = new Double[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = new Double(values[i]); } return ret; } else { return ValueObjectUtil.toDoubleArray(obj, componentType); } } if(toType == BigDecimal[].class) { return toBigDecimalArray(obj, null); } if(toType == BigInteger[].class) { return toBigIntegerArray(obj, null); } if (toType == char[].class) { String[] values = (String[]) obj; char[] ret = new char[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].charAt(0); } return ret; } if (toType == Character[].class) { String[] values = (String[]) obj; Character[] ret = new Character[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = new Character(values[i].charAt(0)); } return ret; } if (toType == boolean[].class) { String[] values = (String[]) obj; boolean[] ret = new boolean[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = toBoolean(values[i]);//new Boolean(values[i]).booleanValue(); } return ret; } if (toType == Boolean[].class) { String[] values = (String[]) obj; Boolean[] ret = new Boolean[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = toBoolean(values[i]);//new Boolean(values[i]); } return ret; } if (toType == byte[].class) { String[] values = (String[]) obj; byte[] ret = new byte[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = new Byte(values[i]).byteValue(); } return ret; } if (toType == Byte[].class) { String[] values = (String[]) obj; Byte[] ret = new Byte[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = new Byte(values[i]); } return ret; } // 如果是字符串则直接返回obj.toString() if (toType == String[].class) { { if (obj.getClass() == java.util.Date[].class) return BaseSimpleStringUtil.dateArrayTOStringArray((Date[]) obj); String[] values = (String[]) obj; return values; } // short[] ret = new short[values.length]; // for(int i = 0; i < values.length; i ++) // { // ret[i] = Short.parseShort(values[i]); // } // return ret; } /** * 字符串向java.util.Date和java.sql.Date 类型转换 */ Object dates = convertObjectToDateArrayWithDateFormat( obj,type,toType, dateformat); if(dates != null) return dates; /** * 枚举数组类型处理转换 */ if(toType.isArray() && toType.getComponentType().isEnum()) { if(type == String.class ) { try { Object value = convertStringToEnumArray((String )obj,toType.getComponentType()); return value; } catch (SecurityException e) { throw new IllegalArgumentException(new StringBuilder().append( "类型无法转换,不支持[").append(type.getName()).append("]向枚举类型[") .append(toType.getName()).append("]转换,超出枚举值范围").append(",value is ").append(obj).toString()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(new StringBuilder().append( "类型无法转换,不支持[").append(type.getName()).append("]向枚举类型[") .append(toType.getName()).append("]转换,超出枚举值范围").append(",value is ").append(obj).toString()); } catch (NoSuchMethodException e) { throw new IllegalArgumentException(new StringBuilder().append( "类型无法转换,不支持[").append(type.getName()).append("]向枚举类型[") .append(toType.getName()).append("]转换,超出枚举值范围").append(",value is ").append(obj).toString()); } catch (IllegalAccessException e) { throw new IllegalArgumentException(new StringBuilder().append( "类型无法转换,不支持[").append(type.getName()).append("]向枚举类型[") .append(toType.getName()).append("]转换,超出枚举值范围").append(",value is ").append(obj).toString()); } catch (InvocationTargetException e) { throw new IllegalArgumentException(new StringBuilder().append( "类型无法转换,不支持[").append(type.getName()).append("]向枚举类型[") .append(toType.getName()).append("]转换,超出枚举值范围").append(",value is ").append(obj).toString()); } } else if(type == String[].class ) { try { Object value = convertStringsToEnumArray((String[] )obj,toType.getComponentType()); return value; } catch (SecurityException e) { throw new IllegalArgumentException(new StringBuilder().append( "类型无法转换,不支持[").append(type.getName()).append("]向枚举类型[") .append(toType.getName()).append("]转换,超出枚举值范围").append(",value is ").append(obj).toString()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(new StringBuilder().append( "类型无法转换,不支持[").append(type.getName()).append("]向枚举类型[") .append(toType.getName()).append("]转换,超出枚举值范围").append(",value is ").append(obj).toString()); } catch (NoSuchMethodException e) { throw new IllegalArgumentException(new StringBuilder().append( "类型无法转换,不支持[").append(type.getName()).append("]向枚举类型[") .append(toType.getName()).append("]转换,超出枚举值范围").append(",value is ").append(obj).toString()); } catch (IllegalAccessException e) { throw new IllegalArgumentException(new StringBuilder().append( "类型无法转换,不支持[").append(type.getName()).append("]向枚举类型[") .append(toType.getName()).append("]转换,超出枚举值范围").append(",value is ").append(obj).toString()); } catch (InvocationTargetException e) { throw new IllegalArgumentException(new StringBuilder().append( "类型无法转换,不支持[").append(type.getName()).append("]向枚举类型[") .append(toType.getName()).append("]转换,超出枚举值范围").append(",value is ").append(obj).toString()); } } } throw new NoSupportTypeCastException(new StringBuilder().append("不支持[").append( type).append("]向[").append(toType).append("]的转换").append(",value is ").append(obj).toString()); } public static Object convertObjectToDateArray(Object obj,Class type,Class toType,String dateformat){ return convertObjectToDateArray( obj, type, toType, dateformat,null); } public static Object convertObjectToDateArray(Object obj,Class type,Class toType,String dateformat,Locale locale) { if(dateformat == null) return convertObjectToDateArrayWithDateFormat(obj,type,toType,ValueObjectUtil.getDefaultDateFormat()); else return convertObjectToDateArrayWithDateFormat(obj,type,toType,ValueObjectUtil.getDateFormat(dateformat, locale)); } public static Object convertObjectToDateArrayWithDateFormat(Object obj,Class type,Class toType,DateFormat dateformat) { if(dateformat == null) dateformat = ValueObjectUtil.getDefaultDateFormat(); if (toType == java.util.Date[].class) { if(type.isArray()) { if(type == String[].class) { String[] values = (String[]) obj; return BaseSimpleStringUtil.stringArrayTODateArray(values,dateformat); } else { long[] values = (long[])obj; return BaseSimpleStringUtil.longArrayTODateArray(values,dateformat); } } else { if(type == String.class) { String[] values = new String[] {(String)obj}; return BaseSimpleStringUtil.stringArrayTODateArray(values,dateformat); } else { long[] values = new long[] {((Long)obj).longValue()}; return BaseSimpleStringUtil.longArrayTODateArray(values,dateformat); } } } if (toType == Date[].class) { if(type.isArray()) { if(type == String[].class) { String[] values = (String[] )obj; return BaseSimpleStringUtil.stringArrayTOSQLDateArray(values,dateformat); } else { long[] values = (long[] )obj; return BaseSimpleStringUtil.longArrayTOSQLDateArray(values,dateformat); } } else { if(type == String.class) { String[] values = new String[] {(String)obj}; return BaseSimpleStringUtil.stringArrayTOSQLDateArray(values,dateformat); } else { long[] values = new long[] {((Long)obj).longValue()}; return BaseSimpleStringUtil.longArrayTOSQLDateArray(values,dateformat); } } } if (toType == java.sql.Timestamp[].class) { if(type.isArray()) { if(type == String[].class) { String[] values = (String[] )obj; return BaseSimpleStringUtil.stringArrayTOTimestampArray(values,dateformat); } else { long[] values = (long[] )obj; return BaseSimpleStringUtil.longArrayTOTimestampArray(values,dateformat); } } else { if(type == String.class) { String[] values = new String[] {(String)obj}; return BaseSimpleStringUtil.stringArrayTOTimestampArray(values,dateformat); } else { long[] values = new long[] {((Long)obj).longValue()}; return BaseSimpleStringUtil.longArrayTOTimestampArray(values,dateformat); } } } return null; } public static void getFileFromString(String value, File outfile) throws SQLException { if(value == null) return; byte[] bytes = value.getBytes(); getFileFromBytes(bytes, outfile); } public static void getFileFromBytes(byte[] bytes, File outfile) throws SQLException { if(bytes == null) return; FileOutputStream out = null; ByteArrayInputStream in = null; try { out = new FileOutputStream(outfile); byte v[] = (byte[]) bytes; in = new ByteArrayInputStream(v); byte b[] = new byte[1024]; int i = 0; while ((i = in.read(b)) > 0) { out.write(b, 0, i); } out.flush(); } catch (IOException e) { throw new NestedSQLException(e); } finally { try { if (out != null) { out.close(); out = null; } } catch (Exception e) { } try { if (in != null) { in.close(); in = null; } } catch (Exception e) { } } } public static void getFileFromClob(Clob value, File outfile) throws SQLException { if(value == null) return; Writer out = null; Reader stream = null; try { out = new FileWriter(outfile); Clob clob = (Clob) value; stream = clob.getCharacterStream(); char[] buf = new char[1024]; int i = 0; while ((i = stream.read(buf)) > 0) { out.write(buf, 0, i); } out.flush(); } catch (IOException e) { throw new NestedSQLException(e); } finally { try { if (stream != null) stream.close(); } catch (Exception e) { } try { if (out != null) out.close(); } catch (Exception e) { } } } public static void getFileFromBlob(Blob value, File outfile) throws SQLException { if(value == null) return ; FileOutputStream out = null; InputStream in = null; try { out = new FileOutputStream(outfile); Blob blob = (Blob) value; byte v[] = new byte[1024]; in = blob.getBinaryStream(); int i = 0; while ((i = in.read(v)) > 0) { out.write(v, 0, i); } out.flush(); } catch (IOException e) { throw new NestedSQLException(e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } in = null; } if (out != null) { try { out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } out = null; } } } /** * 根据参数值的类型修正先前定义的参数类型数组中对应的参数 * params中的类型与paramArgs对应位置相同类型的不修改,不相同的修改为paramArgs中相应的类型 * * @param params * @param paramArgs * @return */ public static Class[] synParamTypes(Class[] params, Object[] paramArgs) { Class[] news = new Class[params.length]; for (int i = 0; i < params.length; i++) { if (paramArgs[i] != null) news[i] = paramArgs[i].getClass(); else { news[i] = params[i]; } } return news; } public static Constructor getConstructor(Class clazz, Class[] params_, Object[] paramArgs) { return getConstructor(clazz, params_, paramArgs, false); } /** * 根据参数类型params_,获取clazz的构造函数,paramArgs为参数的值,如果synTypes为true方法会 * 通过参数的值对参数类型进行校正 当符合params_类型的构造函数有多个时,返回最开始匹配上的构造函数,但是当synTypes为true时, * 就会返回严格符合paramArgs值类型对应的构造函数 paramArgs值的类型也会作为获取构造函数的辅助条件, * * @param clazz * @param params_ * @param paramArgs * @param synTypes * @return */ public static Constructor getConstructor(Class clazz, Class[] params_, Object[] paramArgs, boolean synTypes) { if (params_ == null || params_.length == 0) { return null; } Class[] params = null; if (synTypes) params = synParamTypes(params_, paramArgs); else params = params_; try { // Class[] params_ = this.getParamsTypes(params); Constructor constructor = null; // if (params_ != null) constructor = clazz.getConstructor(params); return constructor; } catch (NoSuchMethodException e) { Constructor[] constructors = clazz.getConstructors(); if (constructors == null || constructors.length == 0) throw new CurrentlyInCreationException( "Inject constructor error: no construction define in the " + clazz + ",请检查配置文件是否配置正确,参数个数是否正确."); int l = constructors.length; int size = params.length; Class[] types = null; Constructor fault_ = null; for (int i = 0; i < l; i++) { Constructor temp = constructors[i]; types = temp.getParameterTypes(); if (types != null && types.length == size) { if (fault_ == null) fault_ = temp; if (isSameTypes(types, params, paramArgs)) return temp; } } if (fault_ != null) return fault_; throw new CurrentlyInCreationException( "Inject constructor error: Parameters with construction defined in the " + clazz + " is not matched with the config paramenters .请检查配置文件是否配置正确,参数个数是否正确."); // TODO Auto-generated catch block // throw new BeanInstanceException("Inject constructor error:" // +clazz.getName(),e); } catch (Exception e) { // TODO Auto-generated catch block throw new BeanInstanceException("Inject constructor error:" + clazz.getName(), e); } } public static Object typeCast(Object value, Class requiredType, MethodParameter methodParam) throws NumberFormatException, IllegalArgumentException, NoSupportTypeCastException { // TODO Auto-generated method stub return ValueObjectUtil.typeCast(value, requiredType); } public static Object typeCast(Object oldValue, Object newValue, Class oldtype, Class toType, WrapperEditorInf editorInf) { // TODO Auto-generated method stub if (editorInf != null) return editorInf.getValueFromObject(newValue, oldValue); else { return ValueObjectUtil.typeCast(newValue, oldtype, toType); } } public static Object getDefaultValue(Class toType) { // 如果是字符串则直接返回obj.toString() if (toType == String.class) { return null; } if (toType == long.class ) return 0l; if (toType == int.class ) return 0; if (toType == float.class ) return 0.0f; if (toType == double.class ) return 0.0d; if (toType == boolean.class ) { return false; } if (toType == short.class ) return (short) 0; if (toType == char.class ) return '0'; if( toType == Long.class) return null; if( toType == Integer.class) return null; if( toType == Float.class) return null; if( toType == Short.class) return null; if( toType == Double.class) return null; if (toType == Character.class) return null; if(toType == Boolean.class) return null; if (toType == byte.class) return (byte) 0; if (toType == Byte.class) return new Byte((byte) 0); return null; } // // @org.junit.Test // public void doubletoint() // { // double number = 10.0; // int i = (int)number; // System.out.println(i); // } // @org.junit.Test // public void floatoint() { // float number = 10.1f; // int i = ((Number) number).intValue(); // System.out.println(i); // } // // @org.junit.Test // public void numberArray() { // double[] number = new double[] { 10.1 }; // numberArray(number); // } // // public void numberArray(Object tests) { // System.out.println(isNumberArray(tests)); // // } /** * 对象比较功能,value1 > value2 返回1,value1 < value2 返回-1,value1 == value2 返回0 * 比较之前首先将value2转换为value1的类型 * 目前只支持数字和String,日期类型的比较,复杂类型不能使用改方法进行比较 */ public static int typecompare(Object value1,Object value2) { if(value1 == null && value2 != null) return -1; if(value1 != null && value2 == null) return 1; if(value1 == null && value2 == null) return 0; Class vc1 = value1.getClass(); try { if (value1 instanceof String && value2 instanceof String) { return ((String)value1).compareTo((String)value2); } else if (value1 instanceof String ) { return ((String)value1).compareTo(String.valueOf(value2)); } else if (vc1 == int.class || Integer.class.isAssignableFrom(vc1)) { return intcompare(((Integer)value1).intValue(),value2); } else { if(value2 instanceof String) { if(((String)value2).equals("")) return -100; } if(vc1 == long.class || Long.class.isAssignableFrom(vc1)) return longCompare(((Long)value1).longValue(),value2); else if(vc1 == double.class || Double.class.isAssignableFrom(vc1)) return doubleCompare(((Double)value1).doubleValue(),value2); else if(vc1 == float.class || Float.class.isAssignableFrom(vc1)) return floatCompare(((Float)value1).floatValue(),value2); else if(java.util.Date.class.isAssignableFrom(vc1)) return dateCompare((java.util.Date)value1,value2); else if(value1 instanceof java.util.Date && value2 instanceof java.util.Date) return dateCompare((java.util.Date)value1,(java.util.Date)value2); else if(vc1 == short.class || Short.class.isAssignableFrom(vc1)) return shortCompare(((Short)value1).shortValue(),value2); } } catch(Throwable e) { log.error("compare value1=" + value1 + ",value2=" + value2 + " failed,use default String compare rules instead.",e); return String.valueOf(value1).compareTo(String.valueOf(value2)); } return String.valueOf(value1).compareTo(String.valueOf(value2)); } public static int intcompare(int value1,Object value2) { Class vc2 = value2.getClass(); if(String.class.isAssignableFrom(vc2)) { int v2 = Integer.parseInt((String)value2); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else if(Integer.class.isAssignableFrom(vc2)) { int v2 = ((Integer)value2).intValue(); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else if(Long.class.isAssignableFrom(vc2)) { long v2 = (Long)value2; if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else if(Double.class.isAssignableFrom(vc2)) { double v2 = ((Double)value2).doubleValue(); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else if(Float.class.isAssignableFrom(vc2)) { float v2 = ((Float)value2).floatValue(); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else if(Short.class.isAssignableFrom(vc2)) { short v2 = ((Short)value2).shortValue(); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else if(java.util.Date.class.isAssignableFrom(vc2)) { long v2 = ((java.util.Date)value2).getTime(); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else { int v2 = Integer.parseInt((String)value2); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } } public static int IntegerCompare(Integer value1,Object value2) { return intcompare(value1.intValue(),value2); } public static int longCompare(long value1,Object value2) { Class vc2 = value2.getClass(); if(String.class.isAssignableFrom(vc2)) { long v2 = Long.parseLong((String)value2); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else if(Integer.class.isAssignableFrom(vc2)) { int v2 = ((Integer)value2).intValue(); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else if(Long.class.isAssignableFrom(vc2)) { long v2 = (Long)value2; if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else if(Double.class.isAssignableFrom(vc2)) { double v2 = ((Double)value2).doubleValue(); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else if(Float.class.isAssignableFrom(vc2)) { float v2 = ((Float)value2).floatValue(); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else if(Short.class.isAssignableFrom(vc2)) { short v2 = ((Short)value2).shortValue(); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else if(java.util.Date.class.isAssignableFrom(vc2)) { long v2 = ((java.util.Date)value2).getTime(); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else { long v2 = Long.parseLong((String)value2); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } } public static int LongCompare(Long value1,Object value2) { return longCompare(value1.longValue(),value2); } public static int doubleCompare(double value1,Object value2) { Class vc2 = value2.getClass(); if(String.class.isAssignableFrom(vc2)) { double v2 = Double.parseDouble((String)value2); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else if(Integer.class.isAssignableFrom(vc2)) { int v2 = ((Integer)value2).intValue(); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else if(Long.class.isAssignableFrom(vc2)) { long v2 = (Long)value2; if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else if(Double.class.isAssignableFrom(vc2)) { double v2 = ((Double)value2).doubleValue(); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else if(Float.class.isAssignableFrom(vc2)) { float v2 = ((Float)value2).floatValue(); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else if(Short.class.isAssignableFrom(vc2)) { short v2 = ((Short)value2).shortValue(); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else if(java.util.Date.class.isAssignableFrom(vc2)) { long v2 = ((java.util.Date)value2).getTime(); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else { double v2 = Double.parseDouble((String)value2); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } } public static int DoubleCompare(Double value1,Object value2) { return doubleCompare(value1.doubleValue(),value2); } public static int floatCompare(float value1,Object value2) { Class vc2 = value2.getClass(); if(String.class.isAssignableFrom(vc2)) { float v2 = Float.parseFloat(String.valueOf(value2)); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else if(Integer.class.isAssignableFrom(vc2)) { int v2 = ((Integer)value2).intValue(); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else if(Long.class.isAssignableFrom(vc2)) { long v2 = (Long)value2; if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else if(Double.class.isAssignableFrom(vc2)) { double v2 = ((Double)value2).doubleValue(); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else if(Float.class.isAssignableFrom(vc2)) { float v2 = ((Float)value2).floatValue(); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else if(Short.class.isAssignableFrom(vc2)) { short v2 = ((Short)value2).shortValue(); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else if(java.util.Date.class.isAssignableFrom(vc2)) { long v2 = ((java.util.Date)value2).getTime(); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else { float v2 = Float.parseFloat(String.valueOf(value2)); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } } public static int FloatCompare(Float value1,Object value2) { return floatCompare(value1.floatValue(),value2); } public static int shortCompare(short value1,Object value2) { Class vc2 = value2.getClass(); if(String.class.isAssignableFrom(vc2)) { short v2 = Short.parseShort(String.valueOf(value2)); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else if(Integer.class.isAssignableFrom(vc2)) { int v2 = ((Integer)value2).intValue(); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else if(Long.class.isAssignableFrom(vc2)) { long v2 = (Long)value2; if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else if(Double.class.isAssignableFrom(vc2)) { double v2 = ((Double)value2).doubleValue(); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else if(Float.class.isAssignableFrom(vc2)) { float v2 = ((Float)value2).floatValue(); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else if(Short.class.isAssignableFrom(vc2)) { short v2 = ((Short)value2).shortValue(); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else if(java.util.Date.class.isAssignableFrom(vc2)) { long v2 = ((java.util.Date)value2).getTime(); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } else { short v2 = Short.parseShort(String.valueOf(value2)); if(value1 == v2) return 0; else if(value1 > v2) return 1; else return -1; } } public static int ShortCompare(Short value1,Object value2) { return shortCompare(value1.shortValue(),value2); } public static int dateCompare(java.util.Date value1,Object value2) { try { Class vc2 = value2.getClass(); if(java.util.Date.class.isAssignableFrom(vc2)) { java.util.Date v2 = ((java.util.Date)value2); return dateCompare(value1,v2); } else if(String.class.isAssignableFrom(vc2)) { SimpleDateFormat format = DataFormatUtil.getSimpleDateFormat("yyyy-MM-dd HH:mm:ss"); java.util.Date v2 = format.parse((String)value2); return dateCompare(value1,v2); } else if(Long.class.isAssignableFrom(vc2)) { java.util.Date v2 = new java.util.Date(((Long)value2).longValue()); return dateCompare(value1,v2); } if(Integer.class.isAssignableFrom(vc2)) { java.util.Date v2 = new java.util.Date(((Integer)value2).intValue()); return dateCompare(value1,v2); } else if(Double.class.isAssignableFrom(vc2)) { java.util.Date v2 = new java.util.Date(((Double)value2).longValue()); return dateCompare(value1,v2); } else if(Float.class.isAssignableFrom(vc2)) { java.util.Date v2 = new java.util.Date(((Float)value2).longValue()); return dateCompare(value1,v2); } else if(Short.class.isAssignableFrom(vc2)) { java.util.Date v2 = new java.util.Date(((Short)value2).longValue()); return dateCompare(value1,v2); } else { SimpleDateFormat format = DataFormatUtil.getSimpleDateFormat("yyyy-MM-dd HH:mm:ss"); java.util.Date v2 = format.parse(String.valueOf(value2)); return dateCompare(value1,v2); } } catch (Exception e) { return -1; } } public static int dateCompare(java.util.Date value1,java.util.Date value2) { long thisTime = value1.getTime(); long anotherTime = value2.getTime(); return (thisTime<anotherTime ? -1 : (thisTime==anotherTime ? 0 : 1)); } public static boolean isNumber(Object value) { boolean isnumber = value instanceof Number; // System.out.println(isnumber); // isnumber = number_d instanceof Number; // System.out.println(isnumber); return isnumber; } public static Class isNumberArray(Object value) { if (!value.getClass().isArray()) return null; Class componentType = value.getClass().getComponentType(); if(String.class.isAssignableFrom(componentType)) return null; if (componentType == int.class || Integer.class.isAssignableFrom(componentType) || componentType == long.class || Long.class.isAssignableFrom(componentType) || componentType == double.class || Double.class.isAssignableFrom(componentType) || componentType == float.class || Float.class.isAssignableFrom(componentType) || componentType == short.class || Short.class.isAssignableFrom(componentType)) return componentType; return null; } public static boolean isDateArray(Object value) { if (!value.getClass().isArray()) return false; Class componentType = value.getClass().getComponentType(); if(java.util.Date.class.isAssignableFrom(componentType)) return true; return false; } public static short[] toshortArray(Object value, Class componentType) { if (!value.getClass().isArray()) { if (isNumber(value)) { return new short[] { ((Number) value).shortValue() }; } else { return new short[] { Short.parseShort(value.toString()) }; } } short[] ret = null; if (componentType == int.class) // || Integer.class.isAssignableFrom(componentType)) { int[] values = (int[]) value; ret = new short[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (short)values[i]; } return ret; } if (Integer.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Integer[] values = (Integer[]) value; ret = new short[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].shortValue(); } return ret; } if (componentType == long.class){ long[] values = (long[]) value; ret = new short[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (short) values[i]; } return ret; } if (Long.class.isAssignableFrom(componentType)) { Long[] values = (Long[]) value; ret = new short[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].shortValue(); } return ret; } if (componentType == double.class) // || Integer.class.isAssignableFrom(componentType)) { double[] values = (double[]) value; ret = new short[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (short) values[i]; } return ret; } if (Double.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Double[] values = (Double[]) value; ret = new short[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].shortValue(); } return ret; } if (componentType == float.class) // || Integer.class.isAssignableFrom(componentType)) { float[] values = (float[]) value; ret = new short[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (short) values[i]; } return ret; } if (Float.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Float[] values = (Float[]) value; ret = new short[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].shortValue(); } return ret; } if (componentType == short.class) // || Integer.class.isAssignableFrom(componentType)) { return (short[]) value; } if (Short.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Short[] values = (Short[]) value; ret = new short[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].shortValue(); } return ret; } return null; } public static Short[] toShortArray(Object value, Class componentType) { if (!value.getClass().isArray()) { if (isNumber(value)) { return new Short[] { ((Number) value).shortValue()}; } else { return new Short[] { Short.parseShort(value.toString()) }; } } Short[] ret = null; if (componentType == int.class) // || Integer.class.isAssignableFrom(componentType)) { int[] values = (int[]) value; ret = new Short[values.length]; for (int i = 0; i < values.length; i++) { ret[i] =(short) values[i]; } return ret; } if (Integer.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Integer[] values = (Integer[]) value; ret = new Short[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].shortValue(); } return ret; } if (Long.class.isAssignableFrom(componentType)){ Long[] values = (Long[]) value; ret = new Short[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].shortValue(); } return ret; } if (long.class == componentType) { long[] values = (long[]) value; ret = new Short[values.length]; for (int i = 0; i < values.length; i++) { ret[i] =(short) values[i]; } return ret; } if (componentType == double.class) // || Integer.class.isAssignableFrom(componentType)) { double[] values = (double[]) value; ret = new Short[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (short) values[i]; } return ret; } if (Double.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Double[] values = (Double[]) value; ret = new Short[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].shortValue(); } return ret; } if (componentType == float.class) // || Integer.class.isAssignableFrom(componentType)) { float[] values = (float[]) value; ret = new Short[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (short) values[i]; } return ret; } if (Float.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Float[] values = (Float[]) value; ret = new Short[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].shortValue(); } return ret; } if (componentType == short.class) // || Integer.class.isAssignableFrom(componentType)) { short[] values = (short[]) value; ret = new Short[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (short) values[i]; } return ret; } if (Short.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { return (Short[]) value; } return null; } public static int[] toIntArray(Object value, Class componentType) { if (!value.getClass().isArray()) { if (isNumber(value)) { return new int[] { ((Number) value).intValue() }; } else { return new int[] { Integer.parseInt(value.toString()) }; } } int[] ret = null; if (componentType == int.class) // || Integer.class.isAssignableFrom(componentType)) { return (int[])value; } if (Integer.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Integer[] values = (Integer[]) value; ret = new int[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i]; } return ret; } if (componentType == long.class){ long[] values = (long[]) value; ret = new int[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (int) values[i]; } return ret; } if (Long.class.isAssignableFrom(componentType)) { Long[] values = (Long[]) value; ret = new int[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].intValue(); } return ret; } if (componentType == double.class) // || Integer.class.isAssignableFrom(componentType)) { double[] values = (double[]) value; ret = new int[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (int) values[i]; } return ret; } if (Double.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Double[] values = (Double[]) value; ret = new int[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].intValue(); } return ret; } if (componentType == float.class) // || Integer.class.isAssignableFrom(componentType)) { float[] values = (float[]) value; ret = new int[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (int) values[i]; } return ret; } if (Float.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Float[] values = (Float[]) value; ret = new int[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].intValue(); } return ret; } if (componentType == short.class) // || Integer.class.isAssignableFrom(componentType)) { short[] values = (short[]) value; ret = new int[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (int) values[i]; } return ret; } if (Short.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Short[] values = (Short[]) value; ret = new int[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].intValue(); } return ret; } return null; } public static Integer[] toIntegerArray(Object value, Class componentType) { if (!value.getClass().isArray()) { if (isNumber(value)) { return new Integer[] { ((Number) value).intValue() }; } else { return new Integer[] { Integer.parseInt(value.toString()) }; } } Integer[] ret = null; if (componentType == int.class) // || Integer.class.isAssignableFrom(componentType)) { int[] values = (int[]) value; ret = new Integer[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = new Integer(values[i]); } return ret; } if (Integer.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { return (Integer[]) value; } if (Long.class.isAssignableFrom(componentType)){ Long[] values = (Long[]) value; ret = new Integer[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].intValue(); } return ret; } if (long.class == componentType) { long[] values = (long[]) value; ret = new Integer[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (int)values[i]; } return ret; } if (componentType == double.class) // || Integer.class.isAssignableFrom(componentType)) { double[] values = (double[]) value; ret = new Integer[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (int) values[i]; } return ret; } if (Double.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Double[] values = (Double[]) value; ret = new Integer[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].intValue(); } return ret; } if (componentType == float.class) // || Integer.class.isAssignableFrom(componentType)) { float[] values = (float[]) value; ret = new Integer[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (int) values[i]; } return ret; } if (Float.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Float[] values = (Float[]) value; ret = new Integer[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].intValue(); } return ret; } if (componentType == short.class) // || Integer.class.isAssignableFrom(componentType)) { short[] values = (short[]) value; ret = new Integer[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (int) values[i]; } return ret; } if (Short.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Short[] values = (Short[]) value; ret = new Integer[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].intValue(); } return ret; } return null; } public static long[] tolongArray(Object value, Class componentType) { if (!value.getClass().isArray()) { if (isNumber(value)) { return new long[] { ((Number) value).longValue() }; } else { return new long[] { Long.parseLong(value.toString()) }; } } long[] ret = null; if (componentType == int.class) // || Integer.class.isAssignableFrom(componentType)) { int[] values = (int[]) value; ret = new long[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i]; } return ret; } if (Integer.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Integer[] values = (Integer[]) value; ret = new long[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i]; } return ret; } if (componentType == long.class) return (long[]) value; if (Long.class.isAssignableFrom(componentType)) { Long[] values = (Long[]) value; ret = new long[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i]; } return ret; } if (componentType == double.class) // || Integer.class.isAssignableFrom(componentType)) { double[] values = (double[]) value; ret = new long[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (long) values[i]; } return ret; } if (Double.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Double[] values = (Double[]) value; ret = new long[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].longValue(); } return ret; } if (componentType == float.class) // || Integer.class.isAssignableFrom(componentType)) { float[] values = (float[]) value; ret = new long[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (long) values[i]; } return ret; } if (Float.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Float[] values = (Float[]) value; ret = new long[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].longValue(); } return ret; } if (componentType == short.class) // || Integer.class.isAssignableFrom(componentType)) { short[] values = (short[]) value; ret = new long[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (long) values[i]; } return ret; } if (Short.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Short[] values = (Short[]) value; ret = new long[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].longValue(); } return ret; } return null; } public static Long[] toLongArray(Object value, Class componentType) { if (!value.getClass().isArray()) { if (isNumber(value)) { return new Long[] { ((Number) value).longValue() }; } else { return new Long[] { Long.parseLong(value.toString()) }; } } Long[] ret = null; if (componentType == int.class) // || Integer.class.isAssignableFrom(componentType)) { int[] values = (int[]) value; ret = new Long[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = new Long(values[i]); } return ret; } if (Integer.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Integer[] values = (Integer[]) value; ret = new Long[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].longValue(); } return ret; } if (Long.class.isAssignableFrom(componentType)) return (Long[]) value; if (long.class == componentType) { long[] values = (long[]) value; ret = new Long[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i]; } return ret; } if (componentType == double.class) // || Integer.class.isAssignableFrom(componentType)) { double[] values = (double[]) value; ret = new Long[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (long) values[i]; } return ret; } if (Double.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Double[] values = (Double[]) value; ret = new Long[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].longValue(); } return ret; } if (componentType == float.class) // || Integer.class.isAssignableFrom(componentType)) { float[] values = (float[]) value; ret = new Long[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (long) values[i]; } return ret; } if (Float.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Float[] values = (Float[]) value; ret = new Long[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].longValue(); } return ret; } if (componentType == short.class) // || Integer.class.isAssignableFrom(componentType)) { short[] values = (short[]) value; ret = new Long[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (long) values[i]; } return ret; } if (Short.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Short[] values = (Short[]) value; ret = new Long[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].longValue(); } return ret; } return null; } public static float[] tofloatArray(Object value, Class componentType) { if (!value.getClass().isArray()) { if (isNumber(value)) { return new float[] { ((Number) value).floatValue() }; } else { return new float[] { Float.parseFloat(value.toString()) }; } } float[] ret = null; if (componentType == int.class) // || Integer.class.isAssignableFrom(componentType)) { int[] values = (int[]) value; ret = new float[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i]; } return ret; } if (Integer.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Integer[] values = (Integer[]) value; ret = new float[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i]; } return ret; } if (componentType == long.class){ long[] values = (long[]) value; ret = new float[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (float) values[i]; } return ret; } if (Long.class.isAssignableFrom(componentType)) { Long[] values = (Long[]) value; ret = new float[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i]; } return ret; } if (componentType == double.class) // || Integer.class.isAssignableFrom(componentType)) { double[] values = (double[]) value; ret = new float[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (float) values[i]; } return ret; } if (Double.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Double[] values = (Double[]) value; ret = new float[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].floatValue(); } return ret; } if (componentType == float.class) // || Integer.class.isAssignableFrom(componentType)) { return (float[]) value; } if (Float.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Float[] values = (Float[]) value; ret = new float[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].floatValue(); } return ret; } if (componentType == short.class) // || Integer.class.isAssignableFrom(componentType)) { short[] values = (short[]) value; ret = new float[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (float) values[i]; } return ret; } if (Short.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Short[] values = (Short[]) value; ret = new float[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].floatValue(); } return ret; } return null; } public static Float[] toFloatArray(Object value, Class componentType) { if (!value.getClass().isArray()) { if (isNumber(value)) { return new Float[] { ((Number) value).floatValue() }; } else { return new Float[] { Float.parseFloat(value.toString()) }; } } Float[] ret = null; if (componentType == int.class) // || Integer.class.isAssignableFrom(componentType)) { int[] values = (int[]) value; ret = new Float[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = new Float(values[i]); } return ret; } if (Integer.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Integer[] values = (Integer[]) value; ret = new Float[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].floatValue(); } return ret; } if (Long.class.isAssignableFrom(componentType)){ Long[] values = (Long[]) value; ret = new Float[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].floatValue(); } return ret; } if (long.class == componentType) { long[] values = (long[]) value; ret = new Float[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (float)values[i]; } return ret; } if (componentType == double.class) // || Integer.class.isAssignableFrom(componentType)) { double[] values = (double[]) value; ret = new Float[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (float) values[i]; } return ret; } if (Double.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Double[] values = (Double[]) value; ret = new Float[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].floatValue(); } return ret; } if (componentType == float.class) // || Integer.class.isAssignableFrom(componentType)) { float[] values = (float[]) value; ret = new Float[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (float) values[i]; } return ret; } if (Float.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { return (Float[]) value; } if (componentType == short.class) // || Integer.class.isAssignableFrom(componentType)) { short[] values = (short[]) value; ret = new Float[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (float) values[i]; } return ret; } if (Short.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Short[] values = (Short[]) value; ret = new Float[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].floatValue(); } return ret; } return null; } public static double[] todoubleArray(Object value, Class componentType) { if (!value.getClass().isArray()) { if (isNumber(value)) { return new double[] { ((Number) value).doubleValue()}; } else { return new double[] { Double.parseDouble(value.toString()) }; } } double[] ret = null; if (componentType == int.class) // || Integer.class.isAssignableFrom(componentType)) { int[] values = (int[]) value; ret = new double[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i]; } return ret; } if (Integer.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Integer[] values = (Integer[]) value; ret = new double[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].doubleValue(); } return ret; } if (componentType == double.class) return (double[]) value; if (Long.class.isAssignableFrom(componentType)) { Long[] values = (Long[]) value; ret = new double[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].doubleValue(); } return ret; } if (componentType == long.class) // || Integer.class.isAssignableFrom(componentType)) { long[] values = (long[]) value; ret = new double[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i]; } return ret; } if (Double.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Double[] values = (Double[]) value; ret = new double[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].doubleValue(); } return ret; } if (componentType == float.class) // || Integer.class.isAssignableFrom(componentType)) { float[] values = (float[]) value; ret = new double[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (double) values[i]; } return ret; } if (Float.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Float[] values = (Float[]) value; ret = new double[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].doubleValue(); } return ret; } if (componentType == short.class) // || Integer.class.isAssignableFrom(componentType)) { short[] values = (short[]) value; ret = new double[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i]; } return ret; } if (Short.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Short[] values = (Short[]) value; ret = new double[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].doubleValue(); } return ret; } return null; } public static BigDecimal[] toBigDecimalArray(Object value, Class componentType) { if (!value.getClass().isArray()) { return new BigDecimal[] { converObjToBigDecimal(value)}; } BigDecimal[] ret = null; int length = Array.getLength(value); ret = new BigDecimal[length]; for (int i = 0; i < length; i++) { ret[i] = converObjToBigDecimal(Array.get(value, i)); } return ret; } public static BigInteger[] toBigIntegerArray(Object value, Class componentType) { if (!value.getClass().isArray()) { return new BigInteger[] { converObjToBigInteger(value)}; } BigInteger[] ret = null; int length = Array.getLength(value); ret = new BigInteger[length]; for (int i = 0; i < length; i++) { ret[i] = converObjToBigInteger(Array.get(value, i)); } return ret; } public static Double[] toDoubleArray(Object value, Class componentType) { if (!value.getClass().isArray()) { if (isNumber(value)) { return new Double[] { ((Number) value).doubleValue() }; } else { return new Double[] { Double.parseDouble(value.toString()) }; } } Double[] ret = null; if (componentType == int.class) // || Integer.class.isAssignableFrom(componentType)) { int[] values = (int[]) value; ret = new Double[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = new Double(values[i]); } return ret; } if (Integer.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Integer[] values = (Integer[]) value; ret = new Double[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].doubleValue(); } return ret; } if (Long.class.isAssignableFrom(componentType)){ Long[] values = (Long[]) value; ret = new Double[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].doubleValue(); } return ret; } if (long.class == componentType) { long[] values = (long[]) value; ret = new Double[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = new Double(values[i]); } return ret; } if (componentType == double.class) // || Integer.class.isAssignableFrom(componentType)) { double[] values = (double[]) value; ret = new Double[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (double) values[i]; } return ret; } if (Double.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { return (Double[]) value; } if (componentType == float.class) // || Integer.class.isAssignableFrom(componentType)) { float[] values = (float[]) value; ret = new Double[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (double) values[i]; } return ret; } if (Float.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Float[] values = (Float[]) value; ret = new Double[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].doubleValue(); } return ret; } if (componentType == short.class) // || Integer.class.isAssignableFrom(componentType)) { short[] values = (short[]) value; ret = new Double[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = (double) values[i]; } return ret; } if (Short.class.isAssignableFrom(componentType)) // || Integer.class.isAssignableFrom(componentType)) { Short[] values = (Short[]) value; ret = new Double[values.length]; for (int i = 0; i < values.length; i++) { ret[i] = values[i].doubleValue(); } return ret; } return null; } static enum Test { A,B,C } public static void main(String[] args) throws ClassNotFoundException { // Test[][] a = new Test[][]{{Test.A,Test.B}}; // String ttt = a.getClass().getName(); // Class x= Class.forName(ttt); // System.out.println(); System.out.println(ValueObjectUtil.typecompare(0,"0")); System.out.println(ValueObjectUtil.typecompare(0,0)); Class clazz = List.class; // try { // Test[] temp = ValueObjectUtil.convertStringsToEnumArray(new String[]{"A","B","C"}, Test.class); // System.out.println(temp.getClass().getComponentType()); // System.out.println(temp[0].getClass()); // Method f= Calle.class.getMethod("testEnum", new Class[]{Test[].class}); // // f.invoke(null, new Object[]{temp}); // } catch (SecurityException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IllegalArgumentException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (NoSuchMethodException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IllegalAccessException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (InvocationTargetException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // System.out.println(a.getClass().isArray()); // System.out.println(a.getClass().getComponentType().isEnum()); } static class Calle { public static void testEnum(Test... tests) { System.out.println(tests); } } public static String getTypeName(Class array) { if(array == null) return null; if(array.isArray()) { String ret = array.getComponentType().getName(); if(ret.equals("java.lang.String")) return "String[]"; else if(ret.equals("java.lang.Object")) return "Object[]"; else if(ret.equals("java.lang.Class")) return "Class[]"; else if(ret.equals("byte")) return "byte[]"; else { ret = array.getName(); } return ret; } else { String ret = array.getName() ; if(ret.equals("java.lang.String")) return "String"; else if(ret.equals("java.lang.Object")) return "Object"; else if(ret.equals("java.lang.Class")) return "Class"; return ret; } } public static String getSimpleTypeName(Class array) { if(array == null) return null; if(array.isArray()) { String ret = array.getComponentType().getName(); if(ret.equals("java.lang.String")) return "String[]"; else if(ret.equals("java.lang.Object")) return "Object[]"; else if(ret.equals("java.lang.Class")) return "Class[]"; else if(ret.equals("byte")) return "byte[]"; return array.getName(); } else { String ret = array.getName() ; if(ret.equals("java.lang.String")) return "String"; else if(ret.equals("java.util.ArrayList")) return "ArrayList"; else if(ret.equals("java.util.HashMap")) return "HashMap"; else if(ret.equals("java.lang.Class")) return "Class"; else if(ret.equals("java.util.TreeSet")) return "TreeSet"; else if(ret.equals("java.lang.Object")) return "Object"; return ret; } } /** * 获取数组元素类型名称 * @param array * @return */ public static String getComponentTypeName(Class array) { if(array == null) return null; if(array.isArray()) { String ret = array.getComponentType().getName() ; if(ret.equals("java.lang.String")) return "String"; else if(ret.equals("java.lang.Object")) return "Object"; else if(ret.equals("java.lang.Class")) return "Class"; else if(ret.equals("byte")) return "byte"; return ret; } else { String ret = array.getName() ; if(ret.equals("java.lang.String")) return "String"; else if(ret.equals("java.lang.Object")) return "Object"; else if(ret.equals("java.lang.Class")) return "Class"; return ret; } } public static Class<?> getClass(String type) throws ClassNotFoundException { if(type == null) return null; else if(type.equals("String") ) { return String.class; } else if (type.equals("int")) return int.class; else if (type.equals("Integer")) return Integer.class; else if (type.equals("long")) return long.class; else if (type.equals("Long")) return Long.class; else if (type.equals("boolean")) return boolean.class; else if (type.equals("double")) return double.class; else if (type.equals("float")) return float.class; else if (type.equals("ArrayList")) return ArrayList.class; else if (type.equals("HashMap")) return HashMap.class; else if (type.equals("string") || type.equals("java.lang.String") || type.equals("java.lang.string")) return String.class; else if (type.equals("short")) return short.class; else if (type.equals("char")) return char.class; else if (type.equals("Boolean")) return Boolean.class; else if (type.equals("Double")) return Double.class; else if (type.equals("Float")) return Float.class; else if (type.equals("Short")) return Short.class; else if (type.equals("Char") || type.equals("Character") || type.equals("character")) return Character.class; else if (type.equals("bigint") ) return BigInteger.class; else if (type.equals("bigdecimal") ) return BigDecimal.class; else if( type.equals("String[]")) { return String[].class; } else if (type.equals("int[]")) return int[].class; else if (type.equals("Integer[]")) return Integer[].class; else if (type.equals("byte[]")) return byte[].class; else if (type.equals("string[]") || type.equals("java.lang.String[]")) return String[].class; else if (type.equals("boolean[]")) return boolean[].class; else if (type.equals("double[]")) return double[].class; else if (type.equals("float[]")) return float[].class; else if (type.equals("short[]")) return short[].class; else if (type.equals("char[]")) return char[].class; else if (type.equals("long[]")) return long[].class; else if (type.equals("Long[]")) return Long[].class; else if (type.equals("Boolean[]")) return Boolean[].class; else if (type.equals("Double[]")) return Double[].class; else if (type.equals("Float[]")) return Float[].class; else if (type.equals("Short[]")) return Short[].class; else if (type.equals("bigint[]") ) return BigInteger[].class; else if (type.equals("bigdecimal[]") ) return BigDecimal[].class; else if (type.equals("Char[]") || type.equals("Character[]") || type.equals("character[]")) return Character[].class; else if (type.equals("Class") || type.equals("class")) return Class.class; else if (type.equals("Class[]") || type.equals("class[]")) return Class[].class; else if (type.equals("byte")) return byte.class; else if (type.equals("TreeSet")) return TreeSet.class; else if(type.endsWith("[]")) { int len = type.length() - 2; int idx = type.indexOf("["); String subClass = type.substring(0,idx); String array = type.substring(idx); int count = 0; StringBuilder builder = new StringBuilder(); for(int i = 0; i < array.length(); i ++) { char c = array.charAt(i); if(c == '[') builder.append("["); } builder.append("L").append(subClass).append(";"); return Class.forName(builder.toString()); } Class<?> Type = Class.forName(type); return Type; } public static String byteArrayEncoder(byte[] contents) { Base64 en = new Base64(); return en.encode(contents); } public static byte[] byteArrayDecoder(String contents) throws Exception { if(contents == null) return null; Base64 en = new Base64(); return en.decode(contents); } public static String getFileContent(String configFile) { try { return getFileContent(configFile,"UTF-8"); } catch (Exception e) { return null; } } // public static String getFileContent(String configFile,String charset) // { // // // try { // return getFileContent(getClassPathFile(configFile),charset); // } catch (Exception e) { // return null; // } // // } private static ClassLoader getTCL() throws IllegalAccessException, InvocationTargetException { Method method = null; try { method = (Thread.class).getMethod("getContextClassLoader"); } catch (NoSuchMethodException e) { return null; } return (ClassLoader)method.invoke(Thread.currentThread()); } /** * InputStream reader = null; ByteArrayOutputStream swriter = null; OutputStream temp = null; try { reader = ValueObjectUtil .getInputStreamFromFile(PoolManConstants.XML_CONFIG_FILE_TEMPLATE); swriter = new ByteArrayOutputStream(); temp = new BufferedOutputStream(swriter); int len = 0; byte[] buffer = new byte[1024]; while ((len = reader.read(buffer)) > 0) { temp.write(buffer, 0, len); } temp.flush(); pooltemplates = swriter.toString("UTF-8"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e) { } if (swriter != null) try { swriter.close(); } catch (IOException e) { } if (temp != null) try { temp.close(); } catch (IOException e) { } } * @param file * @param charSet * @return * @throws IOException */ public static String getFileContent(File file,String charSet) throws IOException { ByteArrayOutputStream swriter = null; OutputStream temp = null; InputStream reader = null; try { reader = new FileInputStream(file); swriter = new ByteArrayOutputStream(); temp = new BufferedOutputStream(swriter); int len = 0; byte[] buffer = new byte[1024]; while ((len = reader.read(buffer)) > 0) { temp.write(buffer, 0, len); } temp.flush(); return swriter.toString(charSet); } catch (FileNotFoundException e) { e.printStackTrace(); return ""; } catch (IOException e) { e.printStackTrace(); throw e; } finally { if (reader != null) try { reader.close(); } catch (IOException e) { } if (swriter != null) try { swriter.close(); } catch (IOException e) { } if (temp != null) try { temp.close(); } catch (IOException e) { } } } public static String getFileContent(String file,String charSet) { ByteArrayOutputStream swriter = null; OutputStream temp = null; InputStream reader = null; try { reader = getInputStreamFromFile(file); swriter = new ByteArrayOutputStream(); temp = new BufferedOutputStream(swriter); int len = 0; byte[] buffer = new byte[1024]; while ((len = reader.read(buffer)) > 0) { temp.write(buffer, 0, len); } temp.flush(); return swriter.toString(charSet); } catch (FileNotFoundException e) { e.printStackTrace(); return ""; } catch (IOException e) { e.printStackTrace(); return ""; } catch (Exception e) { // TODO Auto-generated catch block return ""; } finally { if (reader != null) try { reader.close(); } catch (IOException e) { } if (swriter != null) try { swriter.close(); } catch (IOException e) { } if (temp != null) try { temp.close(); } catch (IOException e) { } } } public static byte[] getBytesFileContent(String file) { ByteArrayOutputStream swriter = null; OutputStream temp = null; InputStream reader = null; try { reader = getInputStreamFromFile(file); swriter = new ByteArrayOutputStream(); temp = new BufferedOutputStream(swriter); int len = 0; byte[] buffer = new byte[1024]; while ((len = reader.read(buffer)) > 0) { temp.write(buffer, 0, len); } temp.flush(); return swriter.toByteArray(); } catch (FileNotFoundException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } catch (Exception e) { // TODO Auto-generated catch block return null; } finally { if (reader != null) try { reader.close(); } catch (IOException e) { } if (swriter != null) try { swriter.close(); } catch (IOException e) { } if (temp != null) try { temp.close(); } catch (IOException e) { } } } public static File getClassPathFile(String configFile) throws Exception { String url = configFile; try { URL confURL = ValueObjectUtil.class.getClassLoader().getResource(configFile); if (confURL == null) confURL = ValueObjectUtil.class.getClassLoader().getResource("/" + configFile); else { // String path = confURL.toString(); // System.out.println(path); } if (confURL == null) confURL = getTCL().getResource(configFile); if (confURL == null) confURL = getTCL().getResource("/" + configFile); if (confURL == null) confURL = ClassLoader.getSystemResource(configFile); if (confURL == null) confURL = ClassLoader.getSystemResource("/" + configFile); if (confURL == null) { url = System.getProperty("user.dir"); url += "/" + configFile; File f = new File(url); if(f.exists()) return f; return null; } else { url = confURL.getFile(); File f = new File(url); if(f.exists()) return f; else f = new File(confURL.toString()); return f; } } catch(Exception e) { throw e; } } public static InputStream getInputStreamFromFile(String configFile) throws Exception { String url = configFile; try { URL confURL = ValueObjectUtil.class.getClassLoader().getResource(configFile); if (confURL == null) confURL = ValueObjectUtil.class.getClassLoader().getResource("/" + configFile); if (confURL == null) confURL = getTCL().getResource(configFile); if (confURL == null) confURL = getTCL().getResource("/" + configFile); if (confURL == null) confURL = ClassLoader.getSystemResource(configFile); if (confURL == null) confURL = ClassLoader.getSystemResource("/" + configFile); if (confURL == null) { url = System.getProperty("user.dir"); url += "/" + configFile; return new FileInputStream(new File(url)); } else { return confURL.openStream(); } } catch(Exception e) { return new FileInputStream(configFile); } } /** * 判断类type是否是基础数据类型或者基础数据类型数组 * @param type * @return */ public static boolean isSamplePrimaryType(Class type) { if(!type.isArray()) { if(type.isEnum()) return true; for(Class primaryType:ValueObjectUtil.baseTypes) { if(primaryType == type) return true; } return false; } else { return isPrimaryType(type.getComponentType()); } } /** * 判断类type是否是基础数据类型或者基础数据类型数组 * @param type * @return */ public static boolean isPrimaryType(Class type) { if(!type.isArray()) { if(type.isEnum()) return true; for(Class primaryType:ValueObjectUtil.baseTypes) { if(primaryType.isAssignableFrom(type)) return true; } return false; } else { return isPrimaryType(type.getComponentType()); } } /** * 判断类type是否是数组 * @param type * @return */ public static boolean isArrayType(Class type) { return type.isArray(); } /** * 判断类type是否是数字类型,或者数组的元素类型是否是数字类型 * @param type * @return */ public static boolean isNumeric(Class type) { if(!type.isArray()) { return Integer.class.isAssignableFrom(type) || int.class.isAssignableFrom(type) || Long.class.isAssignableFrom(type) || long.class.isAssignableFrom(type) || Short.class.isAssignableFrom(type) || short.class.isAssignableFrom(type) || Double.class.isAssignableFrom(type) || double.class.isAssignableFrom(type) || float.class.isAssignableFrom(type) || Float.class.isAssignableFrom(type) || char.class.isAssignableFrom(type) || BigDecimal.class.isAssignableFrom(type) || BigInteger.class.isAssignableFrom(type) ; } else{ return isNumeric(type.getComponentType()); } } public static Class getComponentType(Class type){ if(!type.isArray()) return type ; else{ return getComponentType(type.getComponentType()); } } /** * 判断类type是否是List * @param type * @return */ public static boolean isListType(Class type) { return List.class.isAssignableFrom(type); } /** * 判断类type是否是List * @param type * @return */ public static boolean isMapType(Class type) { return Map.class.isAssignableFrom(type); } /** * 判断类type是否是List * @param type * @return */ public static boolean isEnumType(Class type) { return type.isEnum(); } /** * 判断类type是否是基础数据类型 * @param type * @return */ public static boolean isBasePrimaryType(Class type) { if(!type.isArray()) { if(type.isEnum()) return true; for(Class primaryType:ValueObjectUtil.basePrimaryTypes) { if(primaryType.isAssignableFrom(type)) return true; } return false; } return false; } /** * 判断类type是否是基础数据类型 * @param type * @return */ public static boolean isSimplePrimaryType(Class type) { if(!type.isArray()) { for(Class primaryType:ValueObjectUtil.simplePrimaryTypes) { if(primaryType == type) return true; } if(type.isEnum()) return true; return false; } return false; } public static boolean isCollectionType(Class type) { return Collection.class.isAssignableFrom(type); } /** * @param values * @param targetContainer * @param elementType */ public static void typeCastCollection(String[] values, Collection targetContainer, Class elementType) { for(int i = 0 ; values != null && i < values.length;i ++) { String v = values[i]; targetContainer.add(ValueObjectUtil.typeCast(v, elementType)); } } public static void typeCastCollection(Object values, Collection targetContainer, Class elementType,String dateformat) { typeCastCollection( values, targetContainer, elementType, dateformat,null); } /** * @param values * @param targetContainer */ public static void typeCastCollection(Object values, Collection targetContainer, Class elementType,String dateformat,Locale locale) { if(values == null) return; if(values.getClass().isArray()) { for(int i = 0 ; i < Array.getLength(values);i ++) { Object v = Array.get(values,i); targetContainer.add(ValueObjectUtil.typeCast(v, elementType,dateformat, locale)); } } else { targetContainer.add(ValueObjectUtil.typeCast(values, elementType)); } } public static Collection createCollection(Class targetContainerType) { if (List.class.isAssignableFrom(targetContainerType)) { List valueto = new ArrayList(); return valueto; } else //if (Set.class.isAssignableFrom(targetContainerType)) { Set valueto = new TreeSet(); return valueto; } } public static Object typeCastCollection(Object values, Class targetContainerType, Class elementType,String dateformat ) { return typeCastCollection( values, targetContainerType, elementType, dateformat,null); } /** * @param values */ public static Object typeCastCollection(Object values, Class targetContainerType, Class elementType,String dateformat,Locale locale) { if(values == null) return null; Collection targetContainer = createCollection( targetContainerType); if(values.getClass().isArray()) { for(int i = 0 ; i < Array.getLength(values);i ++) { Object v = Array.get(values,i); targetContainer.add(ValueObjectUtil.typeCast(v, elementType,dateformat, locale)); } } else { targetContainer.add(ValueObjectUtil.typeCast(values, elementType,dateformat, locale)); } return targetContainer; } }
chewaiwai/huaweicloud-sdk-c-obs
CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/java/awt/Font.h
<gh_stars>10-100 // DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*- #ifndef __java_awt_Font__ #define __java_awt_Font__ #pragma interface #include <java/lang/Object.h> #include <gcj/array.h> extern "Java" { namespace gnu { namespace java { namespace awt { class ClasspathToolkit; namespace peer { class ClasspathFontPeer; } } } } namespace java { namespace awt { class Font; namespace font { class FontRenderContext; class GlyphVector; class LineMetrics; } namespace geom { class AffineTransform; class Rectangle2D; } namespace peer { class FontPeer; } } namespace text { class AttributedCharacterIterator$Attribute; class CharacterIterator; } } } class java::awt::Font : public ::java::lang::Object { public: static ::java::awt::Font * decode(::java::lang::String *); public: // actually package-private static ::gnu::java::awt::ClasspathToolkit * tk(); static ::java::awt::Font * getFontFromToolkit(::java::lang::String *, ::java::util::Map *); static ::gnu::java::awt::peer::ClasspathFontPeer * getPeerFromToolkit(::java::lang::String *, ::java::util::Map *); public: static ::java::awt::Font * getFont(::java::lang::String *, ::java::awt::Font *); static ::java::awt::Font * getFont(::java::lang::String *); public: // actually protected Font(::java::awt::Font *); public: Font(::java::lang::String *, jint, jint); Font(::java::util::Map *); public: // actually package-private Font(::java::lang::String *, ::java::util::Map *); public: virtual ::java::lang::String * getName(); virtual jint getSize(); virtual jfloat getSize2D(); virtual jboolean isPlain(); virtual jboolean isBold(); virtual jboolean isItalic(); virtual ::java::lang::String * getFamily(); virtual jint getStyle(); virtual jboolean canDisplay(jchar); virtual jboolean canDisplay(jint); virtual jint canDisplayUpTo(::java::lang::String *); virtual jint canDisplayUpTo(JArray< jchar > *, jint, jint); virtual jint canDisplayUpTo(::java::text::CharacterIterator *, jint, jint); static ::java::awt::Font * createFont(jint, ::java::io::InputStream *); static ::java::awt::Font * createFont(jint, ::java::io::File *); virtual ::java::awt::font::GlyphVector * createGlyphVector(::java::awt::font::FontRenderContext *, ::java::lang::String *); virtual ::java::awt::font::GlyphVector * createGlyphVector(::java::awt::font::FontRenderContext *, ::java::text::CharacterIterator *); virtual ::java::awt::font::GlyphVector * createGlyphVector(::java::awt::font::FontRenderContext *, JArray< jchar > *); virtual ::java::awt::font::GlyphVector * createGlyphVector(::java::awt::font::FontRenderContext *, JArray< jint > *); virtual ::java::awt::Font * deriveFont(jint, jfloat); virtual ::java::awt::Font * deriveFont(jfloat); virtual ::java::awt::Font * deriveFont(jint); virtual ::java::awt::Font * deriveFont(jint, ::java::awt::geom::AffineTransform *); virtual ::java::awt::Font * deriveFont(::java::awt::geom::AffineTransform *); virtual ::java::awt::Font * deriveFont(::java::util::Map *); virtual ::java::util::Map * getAttributes(); virtual JArray< ::java::text::AttributedCharacterIterator$Attribute * > * getAvailableAttributes(); virtual jbyte getBaselineFor(jchar); virtual ::java::lang::String * getFamily(::java::util::Locale *); static ::java::awt::Font * getFont(::java::util::Map *); virtual ::java::lang::String * getFontName(); virtual ::java::lang::String * getFontName(::java::util::Locale *); virtual jfloat getItalicAngle(); virtual ::java::awt::font::LineMetrics * getLineMetrics(::java::lang::String *, jint, jint, ::java::awt::font::FontRenderContext *); virtual ::java::awt::font::LineMetrics * getLineMetrics(JArray< jchar > *, jint, jint, ::java::awt::font::FontRenderContext *); virtual ::java::awt::font::LineMetrics * getLineMetrics(::java::text::CharacterIterator *, jint, jint, ::java::awt::font::FontRenderContext *); virtual ::java::awt::geom::Rectangle2D * getMaxCharBounds(::java::awt::font::FontRenderContext *); virtual jint getMissingGlyphCode(); virtual jint getNumGlyphs(); virtual ::java::lang::String * getPSName(); virtual ::java::awt::geom::Rectangle2D * getStringBounds(::java::lang::String *, ::java::awt::font::FontRenderContext *); virtual ::java::awt::geom::Rectangle2D * getStringBounds(::java::lang::String *, jint, jint, ::java::awt::font::FontRenderContext *); virtual ::java::awt::geom::Rectangle2D * getStringBounds(::java::text::CharacterIterator *, jint, jint, ::java::awt::font::FontRenderContext *); virtual ::java::awt::geom::Rectangle2D * getStringBounds(JArray< jchar > *, jint, jint, ::java::awt::font::FontRenderContext *); virtual ::java::awt::geom::AffineTransform * getTransform(); virtual jboolean hasUniformLineMetrics(); virtual jboolean isTransformed(); virtual ::java::awt::font::GlyphVector * layoutGlyphVector(::java::awt::font::FontRenderContext *, JArray< jchar > *, jint, jint, jint); virtual ::java::awt::peer::FontPeer * getPeer(); virtual jint hashCode(); virtual jboolean equals(::java::lang::Object *); virtual ::java::lang::String * toString(); virtual ::java::awt::font::LineMetrics * getLineMetrics(::java::lang::String *, ::java::awt::font::FontRenderContext *); virtual jboolean hasLayoutAttributes(); private: void readObject(::java::io::ObjectInputStream *); public: static const jint PLAIN = 0; static const jint BOLD = 1; static const jint ITALIC = 2; static const jint ROMAN_BASELINE = 0; static const jint CENTER_BASELINE = 1; static const jint HANGING_BASELINE = 2; static const jint TRUETYPE_FONT = 0; static const jint TYPE1_FONT = 1; static const jint LAYOUT_LEFT_TO_RIGHT = 0; static const jint LAYOUT_RIGHT_TO_LEFT = 1; static const jint LAYOUT_NO_START_CONTEXT = 2; static const jint LAYOUT_NO_LIMIT_CONTEXT = 4; static ::java::lang::String * DIALOG; static ::java::lang::String * DIALOG_INPUT; static ::java::lang::String * MONOSPACED; static ::java::lang::String * SANS_SERIF; static ::java::lang::String * SERIF; public: // actually protected ::java::lang::String * __attribute__((aligned(__alignof__( ::java::lang::Object)))) name; jint size; jfloat pointSize; jint style; private: static const jlong serialVersionUID = -4206021311591459213LL; ::gnu::java::awt::peer::ClasspathFontPeer * peer; jint hashCode__; public: static ::java::lang::Class class$; }; #endif // __java_awt_Font__
ramakrishnaork/MetaOmGraph
src/edu/iastate/metnet/metaomgraph/ReplicateGroups.java
<reponame>ramakrishnaork/MetaOmGraph package edu.iastate.metnet.metaomgraph; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.TreeMap; import javax.swing.JOptionPane; /** * Class to store replicate group objects based on old RepAveragedData class * * @author urmi * */ public class ReplicateGroups { private String[] repGroupNames; private double[] values; private double[] stdDevs; private int[] repCounts; private double[] data; private int[] sortOrder; private TreeMap<String, List<Integer>> repsMap; private boolean[] excluded; private String delimChar="::-::"; private boolean errorFlag=false; // create rep groups for current project public ReplicateGroups(TreeMap<String, List<Integer>> repsMapRaw, int row) { this.excluded = MetaOmAnalyzer.getExclude(); // repsmap raw is reps map which contains all the data columns in group even // excluded ones. if (excluded == null) { this.repsMap = new TreeMap<>(); this.repsMap.putAll(repsMapRaw); } else { this.repsMap = removeExcluded(repsMapRaw, excluded); } // repsMap maps repgroup name to its data columns repGroupNames = new String[repsMap.size()]; values = new double[repsMap.size()]; stdDevs = new double[repsMap.size()]; // values = new double[MetaOmGraph.getActiveProject().getDataColumnCount()]; // stdDevs = new double[MetaOmGraph.getActiveProject().getDataColumnCount()]; // repCounts = new int[MetaOmGraph.getActiveProject().getDataColumnCount()]; repCounts = new int[repsMap.size()]; sortOrder = new int[repsMap.size()]; try { data = MetaOmGraph.getActiveProject().getAllData(row); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // add int index = 0; Set<String> allKeys = repsMap.keySet(); //JOptionPane.showMessageDialog(null, "all keys2:"+allKeys.toString()); String[] allKeys_sorted = sortKeys(allKeys); //JOptionPane.showMessageDialog(null, "all keys3:"+Arrays.toString(allKeys_sorted)); for (String key : allKeys_sorted) { repGroupNames[index] = key; double ave = 0.0D; int thisRepscount = 0; List<Integer> colList = repsMap.get(key); if(colList ==null) { //JOptionPane.showMessageDialog(null, "key:"+key+" "+repsMap.get(key)); JOptionPane.showMessageDialog(null, "Please check if the metadata columns contains "+delimChar+", which is special sequence in MOG. Please remove this from the metadata and try again.", "Error", JOptionPane.ERROR_MESSAGE); JOptionPane.showMessageDialog(null, "Groups could not be made", "Error", JOptionPane.ERROR_MESSAGE); errorFlag=true; return; } for (Integer col : colList) { // skip values which are not present in data file if (col < 0) { //JOptionPane.showMessageDialog(null, "key"+key+" val:"+col); continue; } try { ave += data[col.intValue()]; thisRepscount++; } catch (ArrayIndexOutOfBoundsException exception) { JOptionPane.showMessageDialog(null, "Error...:" + col); JOptionPane.showMessageDialog(null, "data col:" + col); JOptionPane.showMessageDialog(null, "data col name:" + MetaOmGraph.getActiveProject().getMetadata() .getNodeForCol(col).getAttributeValue("name")); JOptionPane.showMessageDialog(null, "data col int val:" + col.intValue()); } } /** * add values n times where n is number of datacols in a group */ repCounts[index] = thisRepscount; ave /= repCounts[index]; /* * for (int t=0;t<thisRepscount;t++) { repCounts[indexRepcount++] = * thisRepscount; } ave /= repCounts[indexRepcount-1]; */ // JOptionPane.showMessageDialog(null,"this avg bef:"+ave); // JOptionPane.showMessageDialog(null,"repind:"+repCounts[index]); // ave /= repCounts[index]; // JOptionPane.showMessageDialog(null,"this avg:"+ave); /** * add values n times where n is number of datacols in a group */ values[index] = ave; /* * values[index2++]=ave; for (int t=1;t<thisRepscount;t++) { values[index2++] = * -839.23183; } */ double diffSum = 0.0D; for (Integer col : colList) { // skip values which are not present in data file if (col < 0) { continue; } diffSum += (data[col.intValue()] - ave) * (data[col.intValue()] - ave); } diffSum /= repCounts[index]; stdDevs[index] = Math.sqrt(diffSum); /** * add values n times where n is number of datacols in a group */ /* * for (int t=0;t<thisRepscount;t++) { stdDevs[index3++] = Math.sqrt(diffSum); } */ index++; // JOptionPane.showMessageDialog(null, "Repname:"+key); // JOptionPane.showMessageDialog(null, "repcnt:"+thisRepscount); // JOptionPane.showMessageDialog(null, "avg:"+ave); } } /** * @author urmi * @param repsMapRaw * treemap original with all datacolumns * @param excluded2 * excluded array * @return */ private TreeMap<String, List<Integer>> removeExcluded(TreeMap<String, List<Integer>> repsMapRaw, boolean[] excluded2) { TreeMap<String, List<Integer>> temp = new TreeMap<>(); Set<String> allKeys = repsMapRaw.keySet(); for (String k : allKeys) { List<Integer> thisCols = repsMapRaw.get(k); List<Integer> toKeep = new ArrayList<>(); for (Integer i : thisCols) { if (i >= 0 && !excluded2[i]) { toKeep.add(i); } } // only add those groups which have atleast one data non-excluded column present if (toKeep.size() > 0) { // JOptionPane.showMessageDialog(null, "add:" + toKeep.toString() + " to:" + k); temp.put(k, toKeep); } } return temp; } /** * Sort the keys so groups are sorted according to the column in data file * * @param allKeys * @return */ private String[] sortKeys(Set<String> allKeys) { String[] res = new String[allKeys.size()]; String datacolNames; int datacolIndex; int i = 0; for (String key : allKeys) { datacolNames = MetaOmGraph.getActiveProject().getMetadataHybrid().getXColumnNameRep(key, 0, this.repsMap); datacolIndex = MetaOmGraph.getActiveProject().findDataColumnHeader(datacolNames); res[i] = String.valueOf(datacolIndex) + delimChar + key; i++; } Arrays.sort(res); for (int j = 0; j < res.length; j++) { res[j] = res[j].split(delimChar)[1]; } return res; } /** * Remove the keys which have only -1 as columns * @param allKeys * @return */ private String[] removeEmptyKeys(Set<String> allKeys) { String[] res = new String[allKeys.size()]; return res; } public String[] getGroupnames() { return this.repGroupNames; } /** * * @return Return name of the first sample in each group */ public String[] getSampnames() { String[] gnames = getGroupnames(); String[] sampnames = new String[gnames.length]; for (int i = 0; i < sampnames.length; i++) { sampnames[i] = MetaOmGraph.getActiveProject().getMetadataHybrid().getXColumnNameRep(gnames[i], 0, this.repsMap); } return sampnames; } public double[] getValues() { return this.values; } public double[] getStdDev() { return this.stdDevs; } public int[] getRepCounts() { return this.repCounts; } public boolean getErrorStatus() { return this.errorFlag; } }
Wattyyy/LeetCode
submissions/palindrome-partitioning/solution.py
<filename>submissions/palindrome-partitioning/solution.py class Solution: def backtrack(self, s: str, idx: int, cur: List[int]) -> None: if idx == len(s): self.ans.append(cur[:]) return for i in range(idx, len(s)): if self.is_palindrome[idx][i]: cur.append(s[idx : i + 1]) self.backtrack(s, i + 1, cur) cur.pop() def partition(self, s: str) -> List[List[str]]: self.ans = [] n = len(s) self.is_palindrome = [[False for _ in range(n)] for __ in range(n)] for i in reversed(range(n)): for j in range(i, n): if i == j: self.is_palindrome[i][j] = True elif j - i == 1: if s[i] == s[j]: self.is_palindrome[i][j] = True else: if self.is_palindrome[i + 1][j - 1] and s[i] == s[j]: self.is_palindrome[i][j] = True self.backtrack(s, 0, []) return self.ans
bazzyadb/all-code
Data Structures/Venice Technique.cpp
template<typename T> struct PQ { long long sum = 0; priority_queue<T, vector<T>, greater<T>> Q; void push(T x) { x.w -= sum; Q.push(x); } T pop() { auto ans = Q.top(); Q.pop(); ans.w += sum; return ans; } int size() { return Q.size(); } void add(long long x) { sum += x; } void merge(PQ &&x) { if (size() < x.size()) swap(sum, x.sum), swap(Q, x.Q); while (x.size()) { auto tmp = x.pop(); tmp.w -= sum; Q.push(tmp); } } };
diqiuonline/Demo
study/itcast/dhcc-mybatis-plus/mybatis-mp-generator/src/main/java/com/dhcc/mp/generator/user/mapper/TbUserMapper.java
package com.dhcc.mp.generator.user.mapper; import com.dhcc.mp.generator.user.entity.TbUser; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * <p> * Mapper 接口 * </p> * * @author dhcc * @since 2020-05-24 */ public interface TbUserMapper extends BaseMapper<TbUser> { }
xuyoung2020/arduino-nuclei-sdk
cores/arduino/nuclei_sdk/NMSIS/DSP/PrivateInclude/riscv_sorting.h
/****************************************************************************** * @file riscv_sorting.h * @brief Private header file for NMSIS DSP Library * @version V1.7.0 * @date 2019 ******************************************************************************/ /* * Copyright (c) 2010-2019 Arm Limited or its affiliates. All rights reserved. * Copyright (c) 2019 Nuclei Limited. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * * 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 * * 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. */ #ifndef _RISCV_SORTING_H_ #define _RISCV_SORTING_H_ #include "riscv_math.h" #ifdef __cplusplus extern "C" { #endif /** * @param[in] S points to an instance of the sorting structure. * @param[in] pSrc points to the block of input data. * @param[out] pDst points to the block of output data. * @param[in] blockSize number of samples to process. */ void riscv_bubble_sort_f32( const riscv_sort_instance_f32* S, float32_t* pSrc, float32_t* pDst, uint32_t blockSize); /** * @param[in] S points to an instance of the sorting structure. * @param[in] pSrc points to the block of input data. * @param[out] pDst points to the block of output data. * @param[in] blockSize number of samples to process. */ void riscv_heap_sort_f32( const riscv_sort_instance_f32* S, float32_t* pSrc, float32_t* pDst, uint32_t blockSize); /** * @param[in] S points to an instance of the sorting structure. * @param[in] pSrc points to the block of input data. * @param[out] pDst points to the block of output data. * @param[in] blockSize number of samples to process. */ void riscv_insertion_sort_f32( const riscv_sort_instance_f32* S, float32_t* pSrc, float32_t* pDst, uint32_t blockSize); /** * @param[in] S points to an instance of the sorting structure. * @param[in] pSrc points to the block of input data. * @param[out] pDst points to the block of output data * @param[in] blockSize number of samples to process. */ void riscv_quick_sort_f32( const riscv_sort_instance_f32* S, float32_t* pSrc, float32_t* pDst, uint32_t blockSize); /** * @param[in] S points to an instance of the sorting structure. * @param[in] pSrc points to the block of input data. * @param[out] pDst points to the block of output data * @param[in] blockSize number of samples to process. */ void riscv_selection_sort_f32( const riscv_sort_instance_f32* S, float32_t* pSrc, float32_t* pDst, uint32_t blockSize); /** * @param[in] S points to an instance of the sorting structure. * @param[in] pSrc points to the block of input data. * @param[out] pDst points to the block of output data * @param[in] blockSize number of samples to process. */ void riscv_bitonic_sort_f32( const riscv_sort_instance_f32* S, float32_t* pSrc, float32_t* pDst, uint32_t blockSize); #ifdef __cplusplus } #endif #endif /* _RISCV_SORTING_H */
AkshayPathak/PrivacyStreams
privacystreams-android-sdk/src/main/java/io/github/privacystreams/core/transformations/filter/KeepFieldChangesFilter.java
<reponame>AkshayPathak/PrivacyStreams package io.github.privacystreams.core.transformations.filter; import io.github.privacystreams.core.Item; import io.github.privacystreams.utils.Assertions; /** * Only keep the items whose field value is changed after last item. */ final class KeepFieldChangesFilter<TValue> extends StreamFilter { private final String fieldName; KeepFieldChangesFilter(String fieldName) { this.fieldName = Assertions.notNull("fieldName", fieldName); } private transient TValue lastFieldValue; @Override public boolean keep(Item item) { TValue fieldValue = item.getValueByField(this.fieldName); if (fieldValue == null) { if (lastFieldValue == null) return false; } else if (fieldValue.equals(lastFieldValue)) { return false; } this.lastFieldValue = fieldValue; return true; } }
uw-midsun/project-template
projects/driver_controls_pedal/test/test_throttle_calibration.c
#include "ads1015.h" #include "calib.h" #include "crc32.h" #include "delay.h" #include "event_queue.h" #include "flash.h" #include "gpio.h" #include "gpio_it.h" #include "i2c.h" #include "interrupt.h" #include "log.h" #include "pedal_calib.h" #include "soft_timer.h" #include "throttle.h" #include "throttle_calibration.h" #include "unity.h" #include "config.h" #define TEST_I2C_PORT I2C_PORT_2 static Ads1015Storage s_ads1015_storage; static ThrottleStorage s_throttle_storage; static ThrottleCalibrationStorage s_calibration_storage; static PedalCalibBlob s_calib_blob; void setup_test(void) { gpio_init(); interrupt_init(); gpio_it_init(); soft_timer_init(); crc32_init(); flash_init(); I2CSettings i2c_settings = { .speed = I2C_SPEED_FAST, // .sda = PEDAL_CONFIG_PIN_I2C_SDA, .scl = PEDAL_CONFIG_PIN_I2C_SDL, }; i2c_init(TEST_I2C_PORT, &i2c_settings); GpioAddress ready_pin = { .port = GPIO_PORT_B, // .pin = 2, // }; event_queue_init(); ads1015_init(&s_ads1015_storage, TEST_I2C_PORT, ADS1015_ADDRESS_GND, &ready_pin); ThrottleCalibrationSettings calib_settings = { .ads1015 = &s_ads1015_storage, .adc_channel = { ADS1015_CHANNEL_0, ADS1015_CHANNEL_1 }, .zone_percentage = { 40, 10, 50 }, .sync_safety_factor = 2, .bounds_tolerance_percentage = 1, }; throttle_calibration_init(&s_calibration_storage, &calib_settings); calib_init(&s_calib_blob, sizeof(s_calib_blob), true); } void teardown_test(void) {} void test_throttle_calibration_run(void) { LOG_DEBUG("Please move to full brake.\n"); delay_s(5); LOG_DEBUG("Beginning sampling\n"); throttle_calibration_sample(&s_calibration_storage, THROTTLE_CALIBRATION_POINT_FULL_BRAKE); LOG_DEBUG("Completed sampling\n"); LOG_DEBUG("Please move to full accel.\n"); delay_s(5); LOG_DEBUG("Beginning sampling\n"); throttle_calibration_sample(&s_calibration_storage, THROTTLE_CALIBRATION_POINT_FULL_ACCEL); LOG_DEBUG("Completed sampling\n"); PedalCalibBlob *dc_calib_blob = calib_blob(); throttle_calibration_result(&s_calibration_storage, &dc_calib_blob->throttle_calib); LOG_DEBUG("Stored throttle calib data\n"); calib_commit(); TEST_ASSERT_EQUAL( STATUS_CODE_OK, throttle_init(&s_throttle_storage, &dc_calib_blob->throttle_calib, &s_ads1015_storage)); while (true) { ThrottlePosition position = { .zone = NUM_THROTTLE_ZONES }; throttle_get_position(&s_throttle_storage, &position); const char *zone[] = { "Brake", "Coast", "Accel", "Invalid" }; printf("%s: %d/%d (%d)\n", zone[position.zone], position.numerator, THROTTLE_DENOMINATOR, position.numerator * 100 / THROTTLE_DENOMINATOR); } }
Liberuman/SimpleProject
library/basecomponent/src/main/java/com/sxu/basecomponent/uiwidget/ContainerLayoutStyleImpl.java
package com.sxu.basecomponent.uiwidget; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.support.v4.content.ContextCompat; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.LinearLayout; import com.sxu.basecomponent.R; import com.sxu.baselibrary.commonutils.ViewBgUtil; /******************************************************************************* * Description: 默认实现的Activity/Fragment的基本样式 * * Author: Freeman * * Date: 2018/7/30 * * Copyright: all rights reserved by Freeman. *******************************************************************************/ public class ContainerLayoutStyleImpl implements ContainerLayoutStyle { private ToolbarEx toolbar; private ViewGroup containerLayout; private Context context; public ContainerLayoutStyleImpl(Context context) { this.context = context; } public ToolbarEx getToolbar() { return toolbar; } @Override public void initLayout(int toolbarStyle) { switch (toolbarStyle) { case TOOL_BAR_STYLE_NONE: containerLayout = new FrameLayout(context); break; case TOOL_BAR_STYLE_NORMAL: containerLayout = createNormalToolbarLayout(); break; case TOOL_BAR_STYLE_TRANSPARENT: containerLayout = createTransparentToolbarLayout(true); break; case TOOL_BAR_STYLE_TRANSLUCENT: containerLayout = createTransparentToolbarLayout(false); break; default: break; } } public ViewGroup getContainerLayout() { return containerLayout; } private ViewGroup createNormalToolbarLayout() { LinearLayout containerLayout = new LinearLayout(context); containerLayout.setOrientation(LinearLayout.VERTICAL); toolbar = new ToolbarEx(context); containerLayout.addView(toolbar); return containerLayout; } private ViewGroup createTransparentToolbarLayout(boolean isTransparent) { FrameLayout containerLayout = new FrameLayout(context); toolbar = new ToolbarEx(context); if (isTransparent) { toolbar.setBackgroundColor(Color.TRANSPARENT); } else { ViewBgUtil.setShapeBg(toolbar, GradientDrawable.Orientation.TOP_BOTTOM, new int[] { ContextCompat.getColor(context, R.color.black_50), Color.TRANSPARENT}, 0); } FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, context.getResources().getDimensionPixelOffset(R.dimen.toolbar_height)); containerLayout.addView(toolbar, params); return containerLayout; } }
AronVanAmmers/ledger
libs/storage/tests/file_object.cpp
<reponame>AronVanAmmers/ledger<gh_stars>1-10 //------------------------------------------------------------------------------ // // Copyright 2018 Fetch.AI Limited // // 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. // //------------------------------------------------------------------------------ #include <core/byte_array/byte_array.hpp> #include <core/byte_array/encoders.hpp> #include <core/random/lfg.hpp> #include <crypto/hash.hpp> #include <iostream> #include <storage/file_object.hpp> #include <testing/unittest.hpp> #include <vector> using namespace fetch; using namespace fetch::byte_array; using namespace fetch::storage; fetch::random::LaggedFibonacciGenerator<> lfg; template <std::size_t BS> bool BasicFileCreation() { using stack_type = VersionedRandomAccessStack<FileBlockType<BS>>; stack_type stack; stack.Load("document_data.db", "doc_diff.db", true); FileObject<stack_type> file_object(stack); ByteArray str; str.Resize(1 + (lfg() % 20000)); for (std::size_t j = 0; j < str.size(); ++j) { str[j] = uint8_t(lfg() >> 9); } // auto start = std::chrono::high_resolution_clock::now(); file_object.Write(str.pointer(), str.size()); FileObject<stack_type> file_object2(stack, file_object.id()); assert(file_object.id() == file_object2.id()); ByteArray str2; str2.Resize(str.size()); file_object2.Read(str2.pointer(), str2.size()); // auto end = std::chrono::high_resolution_clock::now(); if (file_object2.size() != str.size()) { return false; } // std::chrono::duration<double> diff = end-start; // std::cout << "Write speed: " << str2.size() / diff.count() / 1e6 << " // mb/s\n"; if (str != str2) { return false; } return true; } template <std::size_t BS> bool MultipleFileCreation() { using stack_type = VersionedRandomAccessStack<FileBlockType<BS>>; { stack_type stack; stack.New("document_data.db", "doc_diff.db"); } for (std::size_t i = 0; i < 10; ++i) { if (!BasicFileCreation<BS>()) return false; } return true; } template <std::size_t BS> bool Overwriting() { using stack_type = VersionedRandomAccessStack<FileBlockType<BS>>; stack_type stack; stack.New("document_data.db", "doc_diff.db"); FileObject<stack_type> file_object(stack); ByteArray str("Hello world! This is a great world."), f("Fetch"), ret; file_object.Seek(0); file_object.Write(str.pointer(), str.size()); file_object.Seek(6); file_object.Write(f.pointer(), f.size()); file_object.Write(f.pointer(), f.size()); file_object.Seek(6); file_object.Write(str.pointer(), str.size()); file_object.Write(f.pointer(), f.size()); file_object.Write(f.pointer(), f.size()); file_object.Seek(0); ret.Resize(file_object.size()); file_object.Read(ret.pointer(), ret.size()); return (ret.size() == file_object.size()) && (ret == "Hello Hello world! This is a great world.FetchFetch"); } template <std::size_t BS> bool HashConsistency() { using stack_type = VersionedRandomAccessStack<FileBlockType<BS>>; stack_type stack; stack.New("document_data.db", "doc_diff.db"); FileObject<stack_type> file_object(stack); ByteArray str; str.Resize(1 + (lfg() % 20000)); for (std::size_t j = 0; j < str.size(); ++j) { str[j] = uint8_t(lfg() >> 9); } ByteArray ret; file_object.Write(str.pointer(), str.size()); ret.Resize(file_object.size()); file_object.Seek(0); file_object.Read(ret.pointer(), ret.size()); return (str == ret) && (file_object.Hash() == crypto::Hash<crypto::SHA256>(str)); } template <std::size_t BS> bool FileLoadValueConsistency() { using stack_type = VersionedRandomAccessStack<FileBlockType<BS>>; std::vector<ByteArray> values; std::vector<uint64_t> file_ids; { stack_type stack; stack.New("document_data.db", "doc_diffXX.db"); for (std::size_t n = 0; n < 100; ++n) { FileObject<stack_type> file_object(stack); ByteArray str; str.Resize(1 + (lfg() % 2000)); for (std::size_t j = 0; j < str.size(); ++j) { str[j] = uint8_t(lfg() >> 9); } file_object.Write(str.pointer(), str.size()); file_ids.push_back(file_object.id()); values.push_back(str); } for (std::size_t n = 0; n < 100; ++n) { FileObject<stack_type> file_object(stack, file_ids[n]); file_object.Seek(0); // std::cout << "Treating: " << n << " " << file_ids[n] << // std::endl; ByteArray test; test.Resize(file_object.size()); file_object.Read(test.pointer(), test.size()); if (test != values[n]) return false; } } { stack_type stack; stack.Load("document_data.db", "doc_diffXX.db"); for (std::size_t n = 0; n < 100; ++n) { FileObject<stack_type> file_object(stack, file_ids[n]); file_object.Seek(0); ByteArray test; test.Resize(file_object.size()); file_object.Read(test.pointer(), test.size()); if (test != values[n]) return false; } } return true; } template <std::size_t BS, std::size_t FS> bool FileSaveLoadFixedSize() { using stack_type = RandomAccessStack<FileBlockType<BS>>; std::vector<ByteArray> strings; std::vector<uint64_t> file_ids; { stack_type stack; stack.New("document_data.db"); //,"doc_diffXX.db"); FileObject<stack_type> file_object(stack); ByteArray str; str.Resize(1 + (lfg() % 2000)); for (std::size_t j = 0; j < str.size(); ++j) { str[j] = uint8_t(lfg() >> 9); } strings.push_back(str); file_object.Write(str.pointer(), str.size()); file_ids.push_back(file_object.id()); } { stack_type stack; stack.Load("document_data.db"); //,"doc_diffXX.db"); FileObject<stack_type> file_object(stack, file_ids[0]); file_object.Seek(0); ByteArray arr; arr.Resize(file_object.size()); file_object.Read(arr.pointer(), arr.size()); if (arr != strings[0]) return false; } return true; } template <std::size_t BS> bool FileLoadHashConsistency() { using stack_type = RandomAccessStack<FileBlockType<BS>>; std::vector<ByteArray> strings; std::vector<ByteArray> hashes; std::vector<uint64_t> file_ids; { stack_type stack; stack.New("document_data.db"); //,"doc_diffXX.db"); for (std::size_t n = 0; n < 100; ++n) { FileObject<stack_type> file_object(stack); ByteArray str; str.Resize(1 + (lfg() % 2000)); for (std::size_t j = 0; j < str.size(); ++j) { str[j] = uint8_t(lfg() >> 9); } strings.push_back(str); file_object.Write(str.pointer(), str.size()); file_ids.push_back(file_object.id()); hashes.push_back(crypto::Hash<crypto::SHA256>(str)); file_object.Seek(0); if (file_object.Hash() != hashes[n]) { std::cout << "Failed??? " << strings[n].size() << " " << file_object.size() << std::endl; return false; } } } { stack_type stack; stack.Load("document_data.db"); //,"doc_diffXX.db"); for (std::size_t n = 0; n < 100; ++n) { FileObject<stack_type> file_object(stack, file_ids[n]); file_object.Seek(0); if (file_object.Hash() != hashes[n]) return false; } } return true; } int main() { SCENARIO("Basics") { SECTION("Creating / reading") { EXPECT(BasicFileCreation<2>()); EXPECT((FileSaveLoadFixedSize<1, 1>())); EXPECT((FileSaveLoadFixedSize<2, 1>())); EXPECT((FileSaveLoadFixedSize<4, 1>())); EXPECT((FileSaveLoadFixedSize<1, 0>())); EXPECT((FileSaveLoadFixedSize<2, 0>())); EXPECT((FileSaveLoadFixedSize<4, 0>())); EXPECT(MultipleFileCreation<1>()); EXPECT(MultipleFileCreation<2>()); EXPECT(MultipleFileCreation<4>()); EXPECT(MultipleFileCreation<9>()); EXPECT(MultipleFileCreation<1023>()); EXPECT(Overwriting<1>()); EXPECT(Overwriting<2>()); EXPECT(Overwriting<4>()); EXPECT(Overwriting<7>()); EXPECT(Overwriting<2048>()); EXPECT(FileLoadValueConsistency<1>()); EXPECT(FileLoadValueConsistency<2>()); EXPECT(FileLoadValueConsistency<4>()); EXPECT(FileLoadValueConsistency<7>()); // EXPECT( FileLoadValueConsistency<1023>() ); }; SECTION("Hash consistency") { EXPECT(HashConsistency<1>()); EXPECT(HashConsistency<2>()); EXPECT(HashConsistency<4>()); EXPECT(HashConsistency<9>()); EXPECT(HashConsistency<13>()); EXPECT(HashConsistency<1024>()); EXPECT(FileLoadHashConsistency<1>()); EXPECT(FileLoadHashConsistency<2>()); EXPECT(FileLoadHashConsistency<4>()); EXPECT(FileLoadHashConsistency<7>()); EXPECT(FileLoadHashConsistency<1023>()); }; }; return 0; }
uktrade/lite-ap
api/staticdata/control_list_entries/serializers.py
from rest_framework import serializers from api.staticdata.control_list_entries.models import ControlListEntry class ControlListEntrySerializer(serializers.Serializer): id = serializers.UUIDField() rating = serializers.CharField(read_only=True) text = serializers.CharField(read_only=True) class ControlListEntrySerializerWithLinks(ControlListEntrySerializer): """ Serializes with links to parent and child objects. """ parent = ControlListEntrySerializer(read_only=True) children = ControlListEntrySerializer(many=True, read_only=True) category = serializers.CharField() class ControlListEntriesListSerializer(serializers.ModelSerializer): class Meta: model = ControlListEntry fields = "__all__"
taojhlwkl/fastjgame
game-core/src/test/java/com/wjybxx/fastjgame/test/ZKUICharsetTest.java
<filename>game-core/src/test/java/com/wjybxx/fastjgame/test/ZKUICharsetTest.java /* * Copyright 2019 wjybxx * * 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.wjybxx.fastjgame.test; import com.wjybxx.fastjgame.mgr.CuratorMgr; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.recipes.cache.ChildData; import org.apache.curator.framework.recipes.cache.TreeCache; import org.apache.curator.framework.recipes.cache.TreeCacheEvent; import java.nio.charset.StandardCharsets; /** * 测试ZKUI的中文是否ok * * @author wjybxx * @version 1.0 * date - 2019/5/18 11:20 * github - https://github.com/hl845740757 */ public class ZKUICharsetTest { public static void main(String[] args) throws Exception { CuratorMgr curatorMgr = CuratorTest.newCuratorMgr(); TreeCache treeCache = TreeCache .newBuilder(curatorMgr.getClient(), "/") .build(); treeCache.getListenable().addListener(ZKUICharsetTest::onEvent); treeCache.start(); Thread.sleep(5000); } private static void onEvent(CuratorFramework client, TreeCacheEvent event) throws Exception { ChildData childData = event.getData(); if (childData == null) { System.out.println(String.format("thread=%s, eventType=%s", Thread.currentThread().getName(), event.getType())); } else { System.out.println(String.format("thread=%s, eventType=%s, path=%s, data=%s", Thread.currentThread().getName(), event.getType(), childData.getPath(), new String(childData.getData(), StandardCharsets.UTF_8))); } } private static void printChild(ChildData childData) { System.out.println(String.format("childData: path=%s, data=%s", childData.getPath(), new String(childData.getData(), StandardCharsets.UTF_8))); } }
AY1920S2-CS2103T-T10-4/main
src/main/java/nasa/storage/JsonAdaptedEvent.java
package nasa.storage; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import nasa.commons.exceptions.IllegalValueException; import nasa.model.activity.Date; import nasa.model.activity.Event; import nasa.model.activity.Name; import nasa.model.activity.Note; import nasa.model.activity.Schedule; /** * Jackson-friendly version of {@link Event}. */ class JsonAdaptedEvent { public static final String MISSING_FIELD_MESSAGE_FORMAT = "Event's %s field is missing!"; private final String name; private final String date; private final String note; private final String startDate; private final String endDate; private final String schedule; /** * Constructs a {@code JsonAdaptedEvent} with the given activity details. */ @JsonCreator public JsonAdaptedEvent(@JsonProperty("name") String name, @JsonProperty("date") String date, @JsonProperty("note") String note, @JsonProperty("startDate") String startDate, @JsonProperty("endDate") String endDate, @JsonProperty("schedule") String schedule) { this.name = name; this.date = date; this.note = note; this.startDate = startDate; this.endDate = endDate; this.schedule = schedule; } /** * Converts a given {@code Event} into this class for Jackson use. */ public JsonAdaptedEvent(Event source) { name = source.getName().name; date = source.getDateCreated().toString(); note = source.getNote().toString(); startDate = source.getStartDate().toString(); endDate = source.getEndDate().toString(); schedule = source.getSchedule().toString(); } /** * Converts this Jackson-friendly adapted activity object into the model's {@code Event} object. * * @throws IllegalValueException if there were any data constraints violated in the adapted activity. */ public Event toModelType() throws IllegalValueException { if (name == null) { throw new IllegalValueException(String.format(MISSING_FIELD_MESSAGE_FORMAT, Name.class.getSimpleName())); } if (!Name.isValidName(name)) { throw new IllegalValueException(Name.MESSAGE_CONSTRAINTS); } final Name modelName = new Name(name); if (date == null) { throw new IllegalValueException(String.format(MISSING_FIELD_MESSAGE_FORMAT, Date.class.getSimpleName())); } if (!Date.isValidDate(date)) { throw new IllegalValueException(Date.MESSAGE_CONSTRAINTS); } final Date modelDate = new Date(date); if (note == null) { throw new IllegalValueException(String.format(MISSING_FIELD_MESSAGE_FORMAT, Note.class.getSimpleName())); } if (!Note.isValidNote(note)) { throw new IllegalValueException(Note.MESSAGE_CONSTRAINTS); } final Note modelNote = new Note(note); if (startDate == null) { throw new IllegalValueException(String.format(MISSING_FIELD_MESSAGE_FORMAT, Date.class.getSimpleName())); } if (!Date.isValidDate(startDate)) { throw new IllegalValueException(Date.MESSAGE_CONSTRAINTS); } final Date eventStartDate = new Date(startDate); if (endDate == null) { throw new IllegalValueException(String.format(MISSING_FIELD_MESSAGE_FORMAT, Date.class.getSimpleName())); } if (!Date.isValidDate(endDate)) { throw new IllegalValueException(Date.MESSAGE_CONSTRAINTS); } final Date modelEndDate = new Date(endDate); final Schedule modelSchedule = new Schedule(schedule); Event event = new Event(modelName, modelDate, modelNote, eventStartDate, modelEndDate); event.setSchedule(modelSchedule); return event; } }
slushatel/connectors-se
localio/src/main/java/org/talend/components/localio/fixed/FixedFlowInput.java
<gh_stars>0 package org.talend.components.localio.fixed; import static org.talend.sdk.component.api.component.Icon.IconType.FILE_O; import org.apache.avro.Schema; import org.apache.avro.generic.IndexedRecord; import org.apache.beam.sdk.io.Read; import org.apache.beam.sdk.transforms.PTransform; import org.apache.beam.sdk.values.PBegin; import org.apache.beam.sdk.values.PCollection; import org.talend.components.localio.runtime.fixedflowinput.FixedFlowInputBoundedSource; import org.talend.sdk.component.api.component.Icon; import org.talend.sdk.component.api.component.Version; import org.talend.sdk.component.api.configuration.Option; import org.talend.sdk.component.api.input.PartitionMapper; import org.talend.sdk.component.api.meta.Documentation; @Version @Icon(FILE_O) @PartitionMapper(name = "FixedFlowInput") @Documentation("This component duplicates an input a configured number of times.") public class FixedFlowInput extends PTransform<PBegin, PCollection<IndexedRecord>> { private final FixedFlowInputConfiguration configuration; public FixedFlowInput(@Option("configuration") final FixedFlowInputConfiguration configuration) { this.configuration = configuration; } @Override public PCollection<IndexedRecord> expand(final PBegin input) { return input.apply( Read.from(new FixedFlowInputBoundedSource().withSchema(new Schema.Parser().parse(configuration.getSchema())) .withValues(configuration.getValues()).withNbRows(configuration.getNbRows()))); } }
philipstaffordwood/govmomi
simulator/feature_test.go
<reponame>philipstaffordwood/govmomi<filename>simulator/feature_test.go /* Copyright (c) 2019 VMware, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package simulator_test import ( "context" "fmt" "io" "io/ioutil" "log" "net/http" "net/url" "os" "os/exec" "github.com/vmware/govmomi" "github.com/vmware/govmomi/find" "github.com/vmware/govmomi/object" "github.com/vmware/govmomi/simulator" "github.com/vmware/govmomi/vim25" "github.com/vmware/govmomi/vim25/types" ) // Custom username + password authentication func Example_usernamePasswordLogin() { model := simulator.VPX() defer model.Remove() err := model.Create() if err != nil { log.Fatal(err) } model.Service.Listen = &url.URL{ User: url.UserPassword("my-<PASSWORD>", "<PASSWORD>"), } s := model.Service.NewServer() defer s.Close() c, err := govmomi.NewClient(context.Background(), s.URL, true) if err != nil { log.Fatal(err) } fmt.Printf("login to %s as %s", c.Client.ServiceContent.About.ApiType, s.URL.User) // Output: login to VirtualCenter as my-username:my-password } // Set VM properties that the API cannot change in a real vCenter. func Example_setVirtualMachineProperties() { simulator.Test(func(ctx context.Context, c *vim25.Client) { vm, err := find.NewFinder(c).VirtualMachine(ctx, "DC0_H0_VM0") if err != nil { log.Fatal(err) } spec := types.VirtualMachineConfigSpec{ ExtraConfig: []types.BaseOptionValue{ &types.OptionValue{Key: "SET.guest.ipAddress", Value: "10.0.0.42"}, }, } task, _ := vm.Reconfigure(ctx, spec) _ = task.Wait(ctx) ip, _ := vm.WaitForIP(ctx) fmt.Printf("ip is %s", ip) }) // Output: ip is 10.0.0.42 } // Tie a docker container to the lifecycle of a vcsim VM func Example_runContainer() { simulator.Test(func(ctx context.Context, c *vim25.Client) { if _, err := exec.LookPath("docker"); err != nil { fmt.Println("0 diff") return // docker is required } finder := find.NewFinder(c) pool, _ := finder.ResourcePool(ctx, "DC0_H0/Resources") dc, err := finder.Datacenter(ctx, "DC0") if err != nil { log.Fatal(err) } f, _ := dc.Folders(ctx) dir, err := os.Getwd() if err != nil { log.Fatal(err) } args := fmt.Sprintf("-v '%s:/usr/share/nginx/html:ro' nginx", dir) spec := types.VirtualMachineConfigSpec{ Name: "nginx", Files: &types.VirtualMachineFileInfo{ VmPathName: "[LocalDS_0] nginx", }, ExtraConfig: []types.BaseOptionValue{ &types.OptionValue{Key: "RUN.container", Value: args}, // run nginx }, } // Create a new VM task, err := f.VmFolder.CreateVM(ctx, spec, pool, nil) if err != nil { log.Fatal(err) } info, err := task.WaitForResult(ctx, nil) if err != nil { log.Fatal(err) } vm := object.NewVirtualMachine(c, info.Result.(types.ManagedObjectReference)) // PowerOn VM starts the nginx container task, _ = vm.PowerOn(ctx) err = task.Wait(ctx) if err != nil { log.Fatal(err) } ip, _ := vm.WaitForIP(ctx, true) // Returns the docker container's IP // Count the number of bytes in feature_test.go via nginx res, err := http.Get(fmt.Sprintf("http://%s/feature_test.go", ip)) if err != nil { log.Fatal(err) } n, err := io.Copy(ioutil.Discard, res.Body) if err != nil { log.Print(err) } // PowerOff stops the container task, _ = vm.PowerOff(ctx) _ = task.Wait(ctx) // Destroy deletes the container task, _ = vm.Destroy(ctx) _ = task.Wait(ctx) st, _ := os.Stat("feature_test.go") fmt.Printf("%d diff", n-st.Size()) }) // Output: 0 diff }
forsyde/DeSyDe
src/platform/platform.hpp
/** * Copyright (c) 2013-2016, <NAME> <<EMAIL>> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef __PLATFORM__ #define __PLATFORM__ #include<iostream> #include <limits> #include <vector> #include <string> #include "math.h" #include <stdio.h> #include <string.h> #include "../xml/xmldoc.hpp" #include "../exceptions/runtimeexception.h" using namespace std; enum InterconnectType { TDMA_BUS, TDN_NOC, NOC, UNASSIGNED }; /** * Trivial class to represent a processing element. */ class PE { public: std::string name; std::string type; std::string model; vector<std::string> modes; size_t n_modes; vector<double> cycle_length; vector<int> memorySize; vector<int> dynPowerCons; vector<int> staticPowerCons; vector<int> areaCost; vector<int> monetaryCost; int NI_bufferSize; PE() {}; PE(std::string p_name, std::string p_type, vector<std::string> p_modes, vector<double> p_cycle, vector<int> p_memSize, vector<int> _dynPower, vector<int> _staticPower, vector<int> _area, vector<int> _money, int p_buffer){ name = p_name; type = p_type; modes = p_modes; n_modes = p_cycle.size(); cycle_length = p_cycle; memorySize = p_memSize; dynPowerCons = _dynPower; staticPowerCons = _staticPower; areaCost = _area; monetaryCost = _money; NI_bufferSize = p_buffer; } PE(std::string p_model, int id){ n_modes = 0; name = p_model + "_" + tools::toString(id); model = p_model; } PE(vector<char*> elements, vector<char*> values, int number) : n_modes(0), NI_bufferSize(0) { for(unsigned int i=0;i< elements.size();i++) { try { if(strcmp(elements[i], "NI_bufferSize") == 0) NI_bufferSize = atoi(values[i]); if(strcmp(elements[i], "n_modes") == 0) n_modes = atoi(values[i]); if(strcmp(elements[i], "type") == 0) type = string(values[i]); if(strcmp(elements[i], "model") == 0) { model = string(values[i]); name = string(values[i]) + to_string(number); } } catch(std::exception const & e) { cout << "reading taskset xml file error : " << e.what() << endl; } } }; void AddMode(vector<char*> elements, vector<char*> values) { /** * need to initialize in case some are not specified in the XML */ string _mode_name = ""; double _cycle_length = std::numeric_limits<double>::max(); int _dynPowerCons = std::numeric_limits<int>::max() - 1; int _staticPowerCons = std::numeric_limits<int>::max() - 1; int _areaCost = std::numeric_limits<int>::max() - 1; int _monetaryCost = std::numeric_limits<int>::max() - 1; int _memorySize = 0; for(unsigned int i=0;i< elements.size();i++) { try { if(strcmp(elements[i], "mode_name") == 0) { _mode_name = values[i]; //n_modes++; } if(strcmp(elements[i], "cycle_length") == 0) { _cycle_length = atof(values[i]); } if(strcmp(elements[i], "dynPowerCons") == 0) _dynPowerCons = atoi(values[i]); if(strcmp(elements[i], "staticPowerCons") == 0) _staticPowerCons = atoi(values[i]); if(strcmp(elements[i], "areaCost") == 0) _areaCost = atoi(values[i]); if(strcmp(elements[i], "monetaryCost") == 0) _monetaryCost = atoi(values[i]); if(strcmp(elements[i], "memorySize") == 0) _memorySize = atoi(values[i]); } catch(std::exception const & e) { cout << "reading taskset xml file error : " << e.what() << endl; } } AddMode(_mode_name, _cycle_length, _memorySize, _dynPowerCons, _staticPowerCons, _areaCost, _monetaryCost); }; friend std::ostream& operator<< (std::ostream &out, const PE &pe) { out << "PE:" << pe.name << "[model=" << pe.model << "], no_types=" << pe.n_modes << ", speeds("; for(unsigned int i=0;i<pe.cycle_length.size();i++) { i!=0 ? out << ", ": out << "" ; out << pe.cycle_length[i]; } out << ")"; return out; } void AddMode(string _mode_name, double _cycle_length, int _memorySize, int _dynPowerCons, int _staticPowerCons, int _areaCost, int _monetaryCost) { n_modes++;///Increase the number of modes modes.push_back(_mode_name); cycle_length.push_back(_cycle_length); memorySize.push_back(_memorySize); dynPowerCons.push_back(_dynPowerCons); staticPowerCons.push_back(_staticPowerCons); areaCost.push_back(_areaCost); monetaryCost.push_back(_monetaryCost); } }; //! Struct to capture the links of the TDN NoC. /*! Provides information on which link on the NoC, and at which TDN cycle. */ struct tdn_link{ int from; /*!< Value -1: from NI to switch at NoC-node \ref tdn_link.to */ int to; /*!< Value -1: from switch to NI at NoC-node \ref tdn_link.from */ size_t cycle; /*!< TDN cycle */ }; //! Struct to capture a route through the TDN NoC. /*! Combines the destination processor with a path of nodes in the TDN graph. * The \ref tnd_route.tdn_nodePath combines information about location with time (TND cycle). */ struct tdn_route{ size_t srcProc; size_t dstProc; /*!< Id of the destination processor / NoC node. */ vector<size_t> tdn_nodePath; /*!< The sequence of node Ids of the TDN-graph nodes, starting with the root node, ending with the node corresponding to \ref tdn_route.dstProc. */ }; //! Struct to capture a node in the TDN graph. /*! */ struct tdn_graphNode{ set<size_t> passingProcs; /*!< All processors whose messages can pass this link. */ tdn_link link; /*!< The link of the NoC that this node represents. */ vector<shared_ptr<tdn_route>> tdn_routes; /*!< All routes that go through this node. */ }; /** * Trivial struct to represent the modes of the Interconnect. */ struct InterconnectMode { string name; size_t cycleLength; size_t roundLength; size_t dynPower_link; size_t dynPower_NI; size_t dynPower_switch; size_t dynPower_bus; size_t staticPow_link; size_t staticPow_NI; size_t staticPow_switch; size_t staticPow_bus; size_t area_link; size_t area_NI; size_t area_switch; size_t area_bus; size_t monetary_link; size_t monetary_NI; size_t monetary_switch; size_t monetary_bus; }; /** * Trivial class to represent the interconnect. */ class Interconnect { public: enum InterconnectType type; string name; size_t dataPerSlot; size_t dataPerRound; size_t tdmaSlots; size_t roundLength; size_t columns; size_t rows; size_t flitSize; size_t tdnCycles; size_t tdnCyclesPerProc; vector<InterconnectMode> modes; vector<tdn_route> all_routes; //all routes, without time (TDN cycles) - unlink in the tdn graph Interconnect() { type = UNASSIGNED; }; Interconnect(InterconnectType p_type, string p_name, size_t p_dps, size_t p_tdma, size_t p_roundLength, size_t p_col, size_t p_row, size_t p_fs, size_t p_tdnC, size_t p_tdnCPP){ type = p_type; name = p_name; dataPerSlot = p_dps; tdmaSlots = p_tdma; roundLength = p_roundLength; columns = p_col; rows = p_row; dataPerRound = dataPerSlot * tdmaSlots; flitSize = p_fs; tdnCycles = p_tdnC; tdnCyclesPerProc = p_tdnCPP; } void addMode(string _name, size_t _cycleLength, size_t _dynPower_link, size_t _dynPower_NI, size_t _dynPower_switch, size_t _staticPow_link, size_t _staticPow_NI, size_t _staticPow_switch, size_t _area_link, size_t _area_NI, size_t _area_switch, size_t _monetary_link, size_t _monetary_NI, size_t _monetary_switch){ modes.push_back(InterconnectMode{_name, _cycleLength, _cycleLength*(size_t)max(tdmaSlots, tdnCycles), _dynPower_link, _dynPower_NI, _dynPower_switch, 0, _staticPow_link, _staticPow_NI, _staticPow_switch, 0, _area_link, _area_NI, _area_switch, 0, _monetary_link, _monetary_NI, _monetary_switch, 0}); } void addMode(string _name, size_t _cycleLength, size_t _dynPower_NI, size_t _dynPower_bus, size_t _staticPow_NI, size_t _staticPow_bus, size_t _area_NI, size_t _area_bus, size_t _monetary_NI, size_t _monetary_bus){ modes.push_back(InterconnectMode{_name, _cycleLength, _cycleLength*(size_t)max(tdmaSlots, tdnCycles), 0, _dynPower_NI, 0, _dynPower_bus, 0, _staticPow_NI, 0, _staticPow_bus, 0, _area_NI, 0, _area_bus, 0, _monetary_NI, 0, _monetary_bus}); } }; //! Struct to capture the links to and from a switch. /*! */ struct neighborNode{ int node_id; /*!< Id of the neighbor node. */ int link_to; /*!< Id of the link to the neighbor node. */ int link_from; /*!< Id of the link from the node. */ }; /** * This class specifies a platform. * TODO: This could be specified in an XML file or something. */ class Platform { protected: std::vector<PE*> compNodes; Interconnect interconnect; vector<tdn_graphNode> tdn_graph; void createTDNGraph() throw (InvalidArgumentException); void createRouteTable(); public: Platform() {}; Platform(XMLdoc& doc) throw (InvalidArgumentException); Platform(size_t p_nodes, int p_cycle, size_t p_memSize, int p_buffer, enum InterconnectType p_type, int p_dps, int p_tdma, int p_roundLength); Platform(std::vector<PE*> p_nodes, InterconnectType p_type, int p_dps, int p_tdma, int p_roundLength); Platform(std::vector<PE*> p_nodes, InterconnectType p_type, int p_dps, int p_tdma, int p_roundLength, int p_col, int p_row); /** * Destructor. */ ~Platform(); void load_xml(XMLdoc& xml) throw (InvalidArgumentException); /** * For TDN config, setting no of TDN slots and slots per proc. */ void setTDNconfig(size_t slots); // Gives the number of nodes size_t nodes() const; // Gives the type of interconnect InterconnectType getInterconnectType() const; // Gives the TDN Graph / Table vector<tdn_graphNode> getTDNGraph() const; size_t getTDNCycles() const; int getTDNCyclesPerProc() const; size_t getInterconnectModes() const; //int getTDNCycleLength() const; vector<tdn_route> getAllRoutes() const; vector<neighborNode> getNeighborNodes(size_t node) const; /*! Gets the cycle length, depending on the NoC mode. */ vector<int> getTDNCycleLengths() const; /*! Gets the dynamic power consumption of a link for each mode. */ vector<int> getDynPowerCons_link() const; /*! Gets the dynamic power consumption of an NI for each mode. */ vector<int> getDynPowerCons_NI() const; /*! Gets the dynamic power consumption of a switch for each mode. */ vector<int> getDynPowerCons_switch() const; /*! Gets the static power consumption of the entire NoC for each mode. */ vector<int> getStaticPowerCons() const; /*! Gets the dynamic power consumption of the link at node node for each mode. */ vector<int> getStaticPowerCons_link(size_t node) const; /*! Gets the dynamic power consumption of a link for each mode. */ vector<int> getStaticPowerCons_link() const; /*! Gets the dynamic power consumption of a NI for each mode. */ vector<int> getStaticPowerCons_NI() const; /*! Gets the dynamic power consumption of a switch for each mode. */ vector<int> getStaticPowerCons_switch() const; /*! Gets the area cost of the NoC, depending on the mode. */ vector<int> interconnectAreaCost() const; /*! Gets the area cost of the links at node node for each mode. */ vector<int> interconnectAreaCost_link(size_t node) const; /*! Gets the area cost of a link for each mode. */ vector<int> interconnectAreaCost_link() const; /*! Gets the area cost of an NI for each mode. */ vector<int> interconnectAreaCost_NI() const; /*! Gets the area cost of a switch for each mode. */ vector<int> interconnectAreaCost_switch() const; /*! Gets the monetary cost of the NoC, depending on the mode. */ vector<int> interconnectMonetaryCost() const; /*! Gets the monetary cost of the links at node node for each mode. */ vector<int> interconnectMonetaryCost_link(size_t node) const; /*! Gets the monetary cost of a link for each mode. */ vector<int> interconnectMonetaryCost_link() const; /*! Gets the monetary cost of a NI for each mode. */ vector<int> interconnectMonetaryCost_NI() const; /*! Gets the monetary cost of a switch for each mode. */ vector<int> interconnectMonetaryCost_switch() const; int getMaxNoCHops() const; int getFlitSize() const; // Gives the number of tdma slots of the interconnect int tdmaSlots() const; // Gives the dataPerSlot of the interconnect int dataPerSlot() const; // Gives the dataPerRound of the interconnect int dataPerRound() const; // Gives the cycle-length of the specified node double speedUp(int node, int mode) const; // Gives the memory size of the specified node size_t memorySize(int node, int mode) const; size_t getModes(int node)const; size_t getMaxModes()const; vector<int> getMemorySize(int node)const; vector<int> getDynPowerCons(int node)const; vector<int> getStatPowerCons(int node)const; vector<int> getAreaCost(int node)const; vector<int> getMonetaryCost(int node)const; // Gives the NI buffer size of the specified node int bufferSize(int node) const; //maximum communication time (=blocking+sending) on the TDM bus for a token of size tokSize //for different TDM slot allocations (index of vector = number of slots //for use with the element constraint in the model const vector<int> maxCommTimes(int tokSize) const; //maximum blocking time on the TDM bus for a token //for different TDM slot allocations (index of vector = number of slots //for use with the element constraint in the model const vector<int> maxBlockingTimes() const; //maximum transer time on the TDM bus for a token of size tokSize //for different TDM slot allocations (index of vector = number of slots //for use with the element constraint in the model const vector<int> maxTransferTimes(int tokSize) const; // True, if none of the procs has alternative modes bool isFixed() const; // True if the nodes are homogeneous bool homogeneousNodes(int node0, int node1) const; // True if the nodes with modes are homogeneous bool homogeneousModeNodes(int node0, int node1) const; // True if the platform is homogeneous bool homogeneous() const; bool allProcsFixed() const; string getProcModel(size_t id); string getProcModelMode(size_t proc_id, size_t mode_id); friend std::ostream& operator<< (std::ostream &out, const Platform &p); }; #endif
Cwiiis/gaia
apps/calendar/test/unit/views/current_time_test.js
<gh_stars>1-10 /* global MockMozIntl */ define(function(require) { 'use strict'; require('/shared/test/unit/mocks/mock_moz_intl.js'); var CurrentTime = require('views/current_time'); suite('Views.CurrentTime', function() { var subject; var container; var timespan; var realMozIntl; suiteSetup(function() { realMozIntl = window.mozIntl; window.mozIntl = MockMozIntl; }); setup(function() { var startOfDay = new Date(); startOfDay.setHours(0, 0, 0, 0); var endOfDay = new Date(); endOfDay.setHours(24, 0, 0, 0); // mocks the Calendar.TimeSpan API needed by CurrentTime timespan = { start: startOfDay, end: endOfDay }; timespan.contains = timespan.containsNumeric = function(date) { return date >= timespan.start && date <= timespan.end; }; container = { 'appendChild': sinon.spy(), 'removeChild': sinon.spy() }; subject = new CurrentTime({ container: container, timespan: timespan }); }); suiteTeardown(function() { window.mozIntl = realMozIntl; }); suite('#_create', function() { setup(function() { subject._create(); }); test('create and append element to DOM', function() { assert.ok(subject.element, 'element'); assert.include( subject.element.className, 'current-time', 'className' ); assert.equal(subject.element.getAttribute('aria-hidden'), 'true'); assert.ok( container.appendChild.calledWithExactly(subject.element), 'append to DOM' ); }); }); suite('#activate', function() { var contains; setup(function() { contains = sinon.stub(timespan, 'containsNumeric'); sinon.stub(subject, '_create'); sinon.stub(subject, '_tick'); sinon.stub(subject, '_maybeActivateInTheFuture'); subject.element = { classList: { add: sinon.stub() } }; }); teardown(function() { contains.restore(); subject._create.restore(); subject._tick.restore(); subject._maybeActivateInTheFuture.restore(); delete subject.element; }); test('create and setup tick if date is inside timespan', function() { contains.returns(true); subject.activate(); assert.ok( timespan.containsNumeric.calledOnce, 'timespan.containsNumeric' ); assert.ok( !subject._maybeActivateInTheFuture.called, '_maybeActivateInTheFuture' ); assert.ok( subject._create.calledOnce, '_create' ); assert.ok( subject._tick.calledOnce, '_tick' ); assert.ok( subject.element.classList.add.calledWithExactly('active'), 'add active class' ); }); test('call _maybeActivateInTheFuture if outside timespan', function() { contains.returns(false); subject.activate(); assert.ok( subject._maybeActivateInTheFuture.calledOnce ); }); }); suite('#_maybeActivateInTheFuture', function() { var clock; var start; var offset = 24 * 60 * 60 * 1000; setup(function() { clock = sinon.useFakeTimers(); start = timespan.start; timespan.start = Date.now() + offset; sinon.stub(subject, 'activate'); sinon.stub(subject, '_clearInterval'); }); teardown(function() { timespan.start = start; subject.activate.restore(); subject._clearInterval.restore(); clock.restore(); }); test('call activate after timeout', function() { subject._maybeActivateInTheFuture(); assert.ok( !subject.activate.called, 'only call activate after timeout' ); assert.ok( subject._clearInterval.calledOnce, 'clear previous timeout' ); clock.tick(offset); assert.ok( subject.activate.calledOnce, 'call activate after timeout' ); }); }); suite('#_render', function() { var clock; var date; var element; setup(function() { date = new Date(2014, 4, 22, 5, 15); clock = sinon.useFakeTimers(+date); element = subject.element; sinon.stub(subject, '_checkOverlap'); subject.element = { textContent: null, style: { top: null }, dataset: { date: null, l10nDateFormat: null } }; }); teardown(function() { clock.restore(); subject.element = element; subject._checkOverlap.restore(); }); test('should update position and time', function() { subject._render(); assert.equal(subject.element.id, 'current-time-indicator'); assert.deepEqual( subject.element, { textContent: '5:15 AM', style: { top: '21.875%' }, id: 'current-time-indicator', dataset: { date: date, l10nDateFormat: 'current-time' } } ); assert.ok( subject._checkOverlap.calledOnce, 'call _checkOverlap once' ); assert.ok( subject._checkOverlap.calledWithExactly(5), 'call _checkOverlap with current hour' ); }); }); suite('#_tick', function() { var clock; setup(function() { sinon.stub(subject, '_render'); sinon.stub(subject, '_clearInterval'); sinon.stub(subject, 'deactivate'); sinon.spy(subject, '_tick'); sinon.stub(timespan, 'contains'); clock = sinon.useFakeTimers(); }); teardown(function() { subject._render.restore(); subject._clearInterval.restore(); subject.deactivate.restore(); subject._tick.restore(); timespan.contains.restore(); clock.restore(); }); test('inside range', function() { timespan.contains.returns(true); subject._tick(); assert.ok( subject._clearInterval.calledOnce, '_clearInterval' ); assert.ok( !subject.deactivate.called, 'deactivate' ); assert.ok( subject._render.calledOnce, '_render' ); // should call tick every minute assert.ok( subject._tick.calledOnce, '_tick #1' ); clock.tick(60000); assert.ok( subject._tick.calledTwice, '_tick #2' ); clock.tick(60000); assert.ok( subject._tick.calledThrice, '_tick #3' ); }); test('outside range', function() { timespan.contains.returns(false); subject._tick(); assert.ok( subject._clearInterval.calledOnce, '_clearInterval' ); assert.ok( subject.deactivate.calledOnce, 'deactivate' ); assert.ok( !subject._render.called, '_render' ); // should not call tick multiple times assert.ok( subject._tick.calledOnce, '_tick #1' ); clock.tick(60000); assert.ok( subject._tick.calledOnce, '_tick #2' ); clock.tick(60000); assert.ok( subject._tick.calledOnce, '_tick #3' ); }); }); suite('#_checkOverlap', function() { var hour2; function HourElement(top, right, left, bottom) { this.getBoundingClientRect = function() { return { top: top, right: right, left: left, bottom: bottom }; }; this.classList = { toggle: sinon.spy(), remove: sinon.spy() }; } setup(function() { hour2 = new HourElement(40, 50, 10, 60); subject._container = { querySelector: sinon.stub() .withArgs('.hour-2 .display-hour') .returns(hour2) }; }); teardown(function() { subject._container = container; delete subject.element; }); suite('> overlaps', function() { setup(function() { subject.element = { getBoundingClientRect: function() { return { top: 55, right: 300, left: 0, bottom: 65 }; } }; subject._previousOverlap = new HourElement(10, 10, 30, 30); }); teardown(function() { delete subject.element; delete subject._previousOverlap; }); test('hide overlapping hour', function() { subject._checkOverlap(2); assert.ok( hour2.classList.toggle.calledWithExactly('is-hidden', true), 'should hide second hour' ); assert.strictEqual( subject._previousOverlap, hour2, 'update _previousOverlap' ); }); }); suite('> doesn\'t overlap', function() { setup(function() { subject.element = { getBoundingClientRect: function() { return { top: 105, right: 300, left: 0, bottom: 115 }; } }; subject._previousOverlap = hour2; }); test('should not hide hour', function() { subject._checkOverlap(2); assert.ok( hour2.classList.toggle.calledWithExactly('is-hidden', false), 'should not hide second hour' ); assert.ok( !hour2.classList.remove.called, 'should display second hour' ); }); }); }); suite('#deactivate', function() { suite('> with element', function() { setup(function() { sinon.stub(subject, '_clearInterval'); subject.element = { classList: { remove: sinon.stub() } }; }); teardown(function() { subject._clearInterval.restore(); delete subject.element; }); test('should clear the interval & remove active class', function() { subject.deactivate(); assert.ok(subject._clearInterval.calledOnce, '_clearInterval'); assert.ok( subject.element.classList.remove.calledWithExactly('active'), 'remove active class' ); }); }); // element is only created after first activate call and we need to ensure // deactivate still works even without an element suite('> without element', function() { setup(function() { sinon.stub(subject, '_clearInterval'); }); teardown(function() { subject._clearInterval.restore(); }); test('should clear the interval', function() { assert.ok(!subject.element, 'no element'); subject.deactivate(); assert.ok(subject._clearInterval.calledOnce, '_clearInterval'); }); }); }); suite('#destroy', function() { var el; setup(function() { el = subject.element = { classList: { remove: sinon.stub() } }; sinon.stub(subject, 'deactivate'); subject._previousOverlap = {}; }); teardown(function() { subject.deactivate.restore(); }); test('stop timer, remove element', function() { subject.destroy(); assert.ok(subject.deactivate.calledOnce, 'deactivate'); assert.ok(container.removeChild.calledWithExactly(el), 'removeChild'); }); }); }); });
omwine/communityengine
app/models/photo.rb
<gh_stars>1-10 class Photo < ActiveRecord::Base acts_as_commentable belongs_to :album has_attachment prepare_options_for_attachment_fu(AppConfig.photo['attachment_fu_options']) # attr_accessor :cropped_size # before_thumbnail_saved do |thumbnail| # raise thumbnail.inspect # # thumbnail.send(:'attributes=', {:thumbnail_resize_options => cropped_size}, false) if thumbnail.parent.cropped_size # if thumbnail.parent.cropped_size[:x1] # # img = Magick::Image::read(@photo.public_filename).first # thumbnail.crop!(::Magick::CenterGravity, parent.cropped_size[:x1].to_i, parent.cropped_size[:y1].to_i, parent.cropped_size[:width].to_i, parent.cropped_size[:height].to_i, true) # raise thumbnail.inspect # # size = AppConfig.photo['attachment_fu_options']['thumbnails']['medium'] # # dimensions = size[1..size.size].split("x") # # img.crop_resized!(dimensions[0].to_i, dimensions[1].to_i) # # img.write @settings.header_image_file # end # end acts_as_taggable acts_as_activity :user, :if => Proc.new{|record| record.parent.nil? && record.album_id.nil?} validates_presence_of :size validates_presence_of :content_type validates_presence_of :filename validates_presence_of :user, :if => Proc.new{|record| record.parent.nil? } validates_inclusion_of :content_type, :in => attachment_options[:content_type], :message => "is not allowed", :allow_nil => true validates_inclusion_of :size, :in => attachment_options[:size], :message => " is too large", :allow_nil => true belongs_to :user has_one :user_as_avatar, :class_name => "User", :foreign_key => "avatar_id" #Named scopes named_scope :recent, :order => "photos.created_at DESC", :conditions => ["photos.parent_id IS NULL"] named_scope :new_this_week, :order => "photos.created_at DESC", :conditions => ["photos.created_at > ? AND photos.parent_id IS NULL", 7.days.ago.to_s(:db)] named_scope :tagged_with, lambda {|tag_name| {:conditions => ["tags.name = ?", tag_name], :include => :tags} } attr_accessible :name, :description def display_name self.name ? self.name : "#{:created_at.l.downcase}: #{I18n.localize(self.created_at.to_date)}" end def description_for_rss "<a href='#{self.link_for_rss}' title='#{self.name}'><img src='#{self.public_filename(:large)}' alt='#{self.name}' /><br />#{self.description}</a>" end def owner self.user end def previous_photo self.user.photos.find(:first, :conditions => ['created_at < ?', created_at], :order => 'created_at DESC') end def next_photo self.user.photos.find(:first, :conditions => ['created_at > ?', created_at], :order => 'created_at ASC') end def previous_in_album return nil unless self.album self.user.photos.find(:first, :conditions => ['created_at < ? and album_id = ?', created_at, self.album.id], :order => 'created_at DESC') end def next_in_album return nil unless self.album self.user.photos.find(:first, :conditions => ['created_at > ? and album_id = ?', created_at, self.album_id], :order => 'created_at ASC') end def self.find_recent(options = {:limit => 3}) self.new_this_week.find(:all, :limit => options[:limit]) end def self.find_related_to(photo, options = {}) merged_options = options.merge({:limit => 8, :order => 'created_at DESC', :conditions => ['photos.id != ?', photo.id] }) photo = find_tagged_with(photo.tags.collect{|t| t.name }, merged_options).uniq end end
qingqibing/iClient-JavaScript
examples-test/base/ExampleTestGlobeParameter.js
<gh_stars>100-1000 GlobeParameter = { datajingjinURL: "http://localhost:8090/iserver/services/data-jingjin/rest/data/datasources/Jingjin/datasets/", datachangchunURL: "http://localhost:8090/iserver/services/data-changchun/rest/data/datasources/Changchun/datasets/", dataspatialAnalystURL: "http://localhost:8090/iserver/services/data-spatialAnalyst/rest/data/datasources/Interpolation/datasets/" };
rnjudge/tools
Test/org/spdx/rdfparser/model/TestAnnotation.java
/** * Copyright (c) 2015 Source Auditor 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 org.spdx.rdfparser.model; import static org.junit.Assert.*; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.spdx.rdfparser.IModelContainer; import org.spdx.rdfparser.InvalidSPDXAnalysisException; import org.spdx.rdfparser.SpdxRdfConstants; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.Resource; /** * @author <NAME> * */ public class TestAnnotation { static final String ANNOTATOR1 = "Person: Annotator1"; static final String ANNOTATOR2 = "Person: Annotator2"; static final String COMMENT1 = "Comment1"; static final String COMMENT2 = "Comment2"; String date; String oldDate; static Annotation.AnnotationType REVIEW_ANNOTATION = Annotation.AnnotationType.annotationType_review; static Annotation.AnnotationType OTHER_ANNOTATION = Annotation.AnnotationType.annotationType_other; /** * @throws java.lang.Exception */ @BeforeClass public static void setUpBeforeClass() throws Exception { } /** * @throws java.lang.Exception */ @AfterClass public static void tearDownAfterClass() throws Exception { } /** * @throws java.lang.Exception */ @Before public void setUp() throws Exception { DateFormat format = new SimpleDateFormat(SpdxRdfConstants.SPDX_DATE_FORMAT); date = format.format(new Date()); oldDate = format.format(new Date(10101)); } /** * @throws java.lang.Exception */ @After public void tearDown() throws Exception { } /** * Test method for {@link org.spdx.rdfparser.model.Annotation#Annotation(java.lang.String, org.spdx.rdfparser.model.Annotation.AnnotationType, java.lang.String, java.lang.String)}. * @throws InvalidSPDXAnalysisException */ @Test public void testAnnotationStringAnnotationTypeStringString() throws InvalidSPDXAnalysisException { Annotation a = new Annotation(ANNOTATOR1, OTHER_ANNOTATION, date, COMMENT1); assertEquals(ANNOTATOR1, a.getAnnotator()); assertEquals(OTHER_ANNOTATION, a.getAnnotationType()); assertEquals(date, a.getAnnotationDate()); assertEquals(COMMENT1, a.getComment()); final Model model = ModelFactory.createDefaultModel(); IModelContainer modelContainer = new ModelContainerForTest(model, "http://testnamespace.com"); Resource r = a.createResource(modelContainer); Annotation copy = new Annotation(modelContainer, r.asNode()); assertEquals(ANNOTATOR1, copy.getAnnotator()); assertEquals(OTHER_ANNOTATION, copy.getAnnotationType()); assertEquals(date, copy.getAnnotationDate()); assertEquals(COMMENT1, copy.getComment()); } /** * Test method for {@link org.spdx.rdfparser.model.Annotation#verify()}. * @throws InvalidSPDXAnalysisException */ @Test public void testVerify() throws InvalidSPDXAnalysisException { Annotation a = new Annotation(ANNOTATOR1, OTHER_ANNOTATION, date, COMMENT1); assertEquals(0, a.verify().size()); a.setAnnotationType(null); a.setAnnotator(null); a.setAnnotationDate(null); a.setComment(null); assertEquals(4, a.verify().size()); } /** * Test method for {@link org.spdx.rdfparser.model.Annotation#setAnnotationType(org.spdx.rdfparser.model.Annotation.AnnotationType)}. * @throws InvalidSPDXAnalysisException */ @Test public void testSetAnnotationType() throws InvalidSPDXAnalysisException { Annotation a = new Annotation(ANNOTATOR1, OTHER_ANNOTATION, date, COMMENT1); assertEquals(ANNOTATOR1, a.getAnnotator()); assertEquals(OTHER_ANNOTATION, a.getAnnotationType()); assertEquals(date, a.getAnnotationDate()); assertEquals(COMMENT1, a.getComment()); final Model model = ModelFactory.createDefaultModel(); IModelContainer modelContainer = new ModelContainerForTest(model, "http://testnamespace.com"); Resource r = a.createResource(modelContainer); a.setAnnotationType(REVIEW_ANNOTATION); assertEquals(REVIEW_ANNOTATION, a.getAnnotationType()); Annotation copy = new Annotation(modelContainer, r.asNode()); assertEquals(REVIEW_ANNOTATION, copy.getAnnotationType()); } /** * Test method for {@link org.spdx.rdfparser.model.Annotation#setAnnotator(java.lang.String)}. * @throws InvalidSPDXAnalysisException */ @Test public void testSetAnnotator() throws InvalidSPDXAnalysisException { Annotation a = new Annotation(ANNOTATOR1, OTHER_ANNOTATION, date, COMMENT1); assertEquals(ANNOTATOR1, a.getAnnotator()); assertEquals(OTHER_ANNOTATION, a.getAnnotationType()); assertEquals(date, a.getAnnotationDate()); assertEquals(COMMENT1, a.getComment()); final Model model = ModelFactory.createDefaultModel(); IModelContainer modelContainer = new ModelContainerForTest(model, "http://testnamespace.com"); Resource r = a.createResource(modelContainer); a.setAnnotator(ANNOTATOR2); assertEquals(ANNOTATOR2, a.getAnnotator()); Annotation copy = new Annotation(modelContainer, r.asNode()); assertEquals(ANNOTATOR2, copy.getAnnotator()); } /** * Test method for {@link org.spdx.rdfparser.model.Annotation#setComment(java.lang.String)}. * @throws InvalidSPDXAnalysisException */ @Test public void testSetComment() throws InvalidSPDXAnalysisException { Annotation a = new Annotation(ANNOTATOR1, OTHER_ANNOTATION, date, COMMENT1); assertEquals(ANNOTATOR1, a.getAnnotator()); assertEquals(OTHER_ANNOTATION, a.getAnnotationType()); assertEquals(date, a.getAnnotationDate()); assertEquals(COMMENT1, a.getComment()); final Model model = ModelFactory.createDefaultModel(); IModelContainer modelContainer = new ModelContainerForTest(model, "http://testnamespace.com"); Resource r = a.createResource(modelContainer); a.setComment(COMMENT2); assertEquals(COMMENT2, a.getComment()); Annotation copy = new Annotation(modelContainer, r.asNode()); assertEquals(COMMENT2, copy.getComment()); } /** * Test method for {@link org.spdx.rdfparser.model.Annotation#setAnnotationDate(java.lang.String)}. * @throws InvalidSPDXAnalysisException */ @Test public void testSetDate() throws InvalidSPDXAnalysisException { Annotation a = new Annotation(ANNOTATOR1, OTHER_ANNOTATION, date, COMMENT1); assertEquals(ANNOTATOR1, a.getAnnotator()); assertEquals(OTHER_ANNOTATION, a.getAnnotationType()); assertEquals(date, a.getAnnotationDate()); assertEquals(COMMENT1, a.getComment()); final Model model = ModelFactory.createDefaultModel(); IModelContainer modelContainer = new ModelContainerForTest(model, "http://testnamespace.com"); Resource r = a.createResource(modelContainer); a.setAnnotationDate(oldDate); assertEquals(oldDate, a.getAnnotationDate()); Annotation copy = new Annotation(modelContainer, r.asNode()); assertEquals(oldDate, copy.getAnnotationDate()); } @Test public void testEquivalent() throws InvalidSPDXAnalysisException { Annotation a1 = new Annotation(ANNOTATOR1, OTHER_ANNOTATION, date, COMMENT1); assertTrue(a1.equivalent(a1)); Annotation a2 = new Annotation(ANNOTATOR1, OTHER_ANNOTATION, date, COMMENT1); assertTrue(a1.equivalent(a2)); final Model model = ModelFactory.createDefaultModel(); IModelContainer modelContainer = new ModelContainerForTest(model, "http://testnamespace.com"); a1.createResource(modelContainer); assertTrue(a1.equivalent(a2)); // annotator a2.setAnnotator(ANNOTATOR2); assertFalse(a1.equivalent(a2)); a2.setAnnotator(ANNOTATOR1); assertTrue(a2.equivalent(a1)); // annotationType a2.setAnnotationType(REVIEW_ANNOTATION); assertFalse(a1.equivalent(a2)); a2.setAnnotationType(OTHER_ANNOTATION); assertTrue(a2.equivalent(a1)); // comment a2.setComment(COMMENT2); assertFalse(a1.equivalent(a2)); a2.setComment(COMMENT1); assertTrue(a2.equivalent(a1)); // date a2.setAnnotationDate(oldDate); assertFalse(a1.equivalent(a2)); a2.setAnnotationDate(date); assertTrue(a2.equivalent(a1)); } @Test public void testClone() throws InvalidSPDXAnalysisException { Annotation a1 = new Annotation(ANNOTATOR1, OTHER_ANNOTATION, date, COMMENT1); final Model model = ModelFactory.createDefaultModel(); IModelContainer modelContainer = new ModelContainerForTest(model, "http://testnamespace.com"); a1.createResource(modelContainer); Annotation a2 = a1.clone(); assertEquals(a1.getAnnotationType(), a2.getAnnotationType()); assertEquals(a1.getAnnotator(), a2.getAnnotator()); assertEquals(a1.getComment(), a2.getComment()); assertEquals(a1.getAnnotationDate(), a2.getAnnotationDate()); assertTrue(a2.model == null); } }
txs13/webapp-template-user-authorization
client/src/components/appNavBar.test.js
import { render, screen, cleanup, } from "@testing-library/react" import userEvent from '@testing-library/user-event' import { Provider } from "react-redux" import '@testing-library/jest-dom' import { expect } from "@jest/globals" import configureMockStore from 'redux-mock-store' import AppNavbar from "./appNavbar.js" import textLabelsEN from "./resources/textLabelsEN.js" import { appStates } from "../store/features/appState.js" const initialState = { user: { value: { _id: null, created: null, name: '', familyname: '', companyname: '', position: '', portalrole: '', rating: 0, email: '', phone: '', address: '', description: '' } }, appState: { value: { state: 'WELCOMESCREEN' } } } const secondState = { user: { value: { _id: "61e59cdb90c58876a5f6b733", created: Date.parse("2022-01-17T16:44:11.224Z"), name: '', familyname: "Pupkin", companyname: '', position: '', portalrole: "Developer", rating: 0, email: '<EMAIL>', phone: '', address: '', description: '' } }, appState: { value: { state: 'WELCOMESCREEN' } } } describe("AppNavbar component unit test", () => { const middleware = [] const mockStore = configureMockStore(middleware) const storeTest1 = mockStore(() => initialState) const storeTest2 = mockStore(() => secondState) test("Component to contain objects NO USER state big screen", () => { global.innerWidth = 1300 render( <Provider store={storeTest1}> <AppNavbar /> </Provider>) const menuButton = screen.getByRole("button", { name: "menuButton" }) const aboutServiceButton = screen.getByText(textLabelsEN.aboutWebsiteLink) const menuLogIn = screen.getByText(textLabelsEN.menuLogIn) const menuRegister = screen.getByText(textLabelsEN.menuRegister) const appName = screen.getByText(textLabelsEN.appName) // checking that all the components are in the document expect(menuButton).toBeInTheDocument() expect(aboutServiceButton).toBeInTheDocument() expect(menuLogIn).toBeInTheDocument() expect(menuRegister).toBeInTheDocument() expect(appName).toBeInTheDocument() //cheking that app name is visible on a wide screen expect(appName).toBeVisible() //checking menu items to be not visible before menu button click expect(menuLogIn).not.toBeVisible() expect(menuRegister).not.toBeVisible() //menu button click userEvent.click(menuButton) //checking menu items to be visible after menu button click expect(menuLogIn).toBeVisible() expect(menuRegister).toBeVisible() //checking login button userEvent.click(menuButton) userEvent.click(menuLogIn) let actions = storeTest1.getActions() expect(actions[0].type).toEqual("appState/changeState") expect(actions[0].payload.state).toEqual(appStates.LOGIN) storeTest1.clearActions() // checking register button userEvent.click(menuButton) userEvent.click(menuRegister) actions = storeTest1.getActions() expect(actions[0].type).toEqual("appState/changeState") expect(actions[0].payload.state).toEqual(appStates.REGISTER) storeTest1.clearActions() cleanup() }) test("Component to contain objects USER AUTHORIZED state small screen", () => { global.innerWidth = 500 global.dispatchEvent(new Event('resize')) render( <Provider store={storeTest2}> <AppNavbar /> </Provider>) const menuButton = screen.getByRole("button", { name: "menuButton" }) const menuToTheApp = screen.getByText(textLabelsEN.menuToTheApp) const menuSettings = screen.getByText(textLabelsEN.menuSettings) const menuProfile = screen.getByText(textLabelsEN.menuProfile) const menuLogOut = screen.getByText(textLabelsEN.menuLogOut) const appName = screen.getByText(textLabelsEN.appName) // checking that all the components are in the document expect(menuButton).toBeInTheDocument() expect(menuToTheApp).toBeInTheDocument() expect(menuSettings).toBeInTheDocument() expect(menuProfile).toBeInTheDocument() expect(menuLogOut).toBeInTheDocument() expect(appName).toBeInTheDocument() //cheking that app name is NOT visible on a smartphone screenw // expect(appName).not.toBeVisible() -- is confirmed to have a bug // checking menu items to be not visible before menu button click expect(menuToTheApp).not.toBeVisible() expect(menuSettings).not.toBeVisible() expect(menuProfile).not.toBeVisible() expect(menuLogOut).not.toBeVisible() // menu button click userEvent.click(menuButton) // checking menu items to be visible after menu button click expect(menuToTheApp).toBeVisible() expect(menuSettings).toBeVisible() expect(menuProfile).toBeVisible() expect(menuLogOut).toBeVisible() // checking to app button userEvent.click(menuButton) userEvent.click(menuToTheApp) let actions = storeTest2.getActions() expect(actions[0].type).toEqual("appState/changeState") expect(actions[0].payload.state).toEqual(appStates.APPMAIN) storeTest2.clearActions() // checking settings button userEvent.click(menuButton) userEvent.click(menuSettings) actions = storeTest2.getActions() expect(actions[0].type).toEqual("appState/changeState") expect(actions[0].payload.state).toEqual(appStates.SETTINGS) storeTest2.clearActions() // checking profile button userEvent.click(menuButton) userEvent.click(menuProfile) actions = storeTest2.getActions() expect(actions[0].type).toEqual("appState/changeState") expect(actions[0].payload.state).toEqual(appStates.PROFILE) storeTest2.clearActions() // checking logout button userEvent.click(menuButton) userEvent.click(menuLogOut) actions = storeTest2.getActions() expect(actions[0].type).toEqual("user/logout") expect(actions[1].type).toEqual("appState/changeState") expect(actions[1].payload.state).toEqual(appStates.LOGIN) storeTest2.clearActions() cleanup() }) })
kmikhailov-tmn/NaviGridContour
src/ru/navilab/grid/contour/ZMapGridReader.java
package ru.navilab.grid.contour; import java.io.FileReader; import java.io.IOException; import java.io.LineNumberReader; import java.util.StringTokenizer; public class ZMapGridReader implements GridLoadAdapter { private static final String FILE_NOT_CORRECT = "can't read ASCII ZMAP grid format"; private int countX; private int countY; private double maxX; private double maxY; private double minX; private double minY; private double xinc; private double yinc; /** * количество значений (токенов) в одной строчке данных */ private int nodesInLine; /** * количество символов на одно значение z */ private int nodeLength; /** * null значение */ private double missingZ = -9999; public boolean fileFormatMatch(String filename) throws GridLoadException { try { LineNumberReader lineNumberReader = new LineNumberReader(new FileReader(filename)); boolean signatureIsOk = checkSignature(lineNumberReader); lineNumberReader.close(); return signatureIsOk; } catch (IOException e) { throw new GridLoadException(e.getMessage()); } } public String getFileFormatDescription() { return "ASCII ZMAP grid format"; } public GridAdapter readGridData(String filename) throws GridLoadException { final String line = null; try { final LineNumberReader in = new LineNumberReader(new FileReader(filename)); loadLabel(in); double[] axisX = makeAxisX(); double[] axisY = makeAxisY(); double[][] zvalues = readZvalues(in); in.close(); XYZGrid xyzGrid = new XYZGrid(axisX, axisY, zvalues, missingZ); return xyzGrid; } catch (final IOException e) { throw new GridLoadException(e.getLocalizedMessage()); } catch (final NumberFormatException e) { throw new GridLoadException(FILE_NOT_CORRECT + "NumberFormatException > " + line); } } double[] makeAxisX() { double[] result = new double[countX]; for (int i = 0; i < result.length; i++) result[i] = minX + xinc * i; return result; } double[] makeAxisY() { double[] result = new double[countY]; for (int i = 0; i < result.length; i++) result[i] = minY + yinc * i; return result; } private void loadLabel(final LineNumberReader in) throws IOException, GridLoadException { String s = in.readLine(); while (s.startsWith("!")) { s = in.readLine(); } if (!s.startsWith("@")) { throw new GridLoadException(FILE_NOT_CORRECT + " expected @ token"); } readGridParameters(s, 1); for (int i = 2; i <= 5; i++) { readGridParameters(in.readLine(), i); } } private boolean checkSignature(final LineNumberReader in) throws IOException { String s = in.readLine(); if (s.startsWith("!") || s.startsWith("@")) return true; return false; } private double[][] readZvalues(final LineNumberReader in) throws NumberFormatException, IOException { String line; int lineOffset; double[][] valuesZ = new double[countX][countY]; for (int i = 0; i < countX; i++) { line = in.readLine(); lineOffset = 0; for (int j = 0; j < countY; j++) { if (lineOffset >= nodesInLine) { line = in.readLine(); lineOffset = 0; } String field = line.substring(lineOffset * nodeLength, ++lineOffset * nodeLength); valuesZ[i][j] = parseDouble(field.trim()); } } return valuesZ; } private final static double parseDouble(String str) { return Double.parseDouble(str.replace(",", ".")); } private void readGridParameters(final String line, final int lineNumber) throws GridLoadException { final StringTokenizer tokener = new StringTokenizer(line, ","); int countTokens = tokener.countTokens(); if (lineNumber == 1) { if (countTokens != 3) throw new GridLoadException(FILE_NOT_CORRECT + "countTokens"); tokener.nextToken(); tokener.nextToken(); nodesInLine = parseHeaderInt(tokener.nextToken()); } else if (lineNumber == 2) { if (countTokens != 4 && countTokens != 5) throw new GridLoadException(FILE_NOT_CORRECT + "countTokens"); nodeLength = parseHeaderInt(tokener.nextToken()); missingZ = parseHeaderDouble(tokener.nextToken()); } else if (lineNumber == 3) { if (countTokens != 6) throw new GridLoadException(FILE_NOT_CORRECT + "countTokens"); countY = parseHeaderInt(tokener.nextToken()); countX = parseHeaderInt(tokener.nextToken()); minX = parseHeaderDouble(tokener.nextToken()); maxX = parseHeaderDouble(tokener.nextToken()); minY = parseHeaderDouble(tokener.nextToken()); maxY = parseHeaderDouble(tokener.nextToken()); xinc = (maxX - minX) / countX; yinc = (maxY - minY) / countY; } else if (lineNumber == 4) { if (countTokens != 3) throw new GridLoadException(FILE_NOT_CORRECT + "countTokens"); } else if (lineNumber == 5) { if (!line.startsWith("@")) throw new GridLoadException(FILE_NOT_CORRECT + " expected @ token"); } } private final static int parseHeaderInt(String string) { return Integer.parseInt(string.trim()); } private final static double parseHeaderDouble(String string) { return parseDouble(string.trim()); } }
kzvd4729/Problem-Solving
codeforces/B - Not Afraid/Accepted.cpp
/**************************************************************************************** * @author: kzvd4729# created: Mar/24/2017 17:55 * solution_verdict: Accepted language: GNU C++14 * run_time: 342 ms memory_used: 2700 KB * problem: https://codeforces.com/contest/787/problem/B ****************************************************************************************/ #include<bits/stdc++.h> using namespace std; int visp[100005]; int visn[100005]; int main() { int n,m,i,j,x,z,f,ff,q; while(cin>>n>>m) { ff=0; for(i=0;i<m;i++) { cin>>x; memset(visp,0,sizeof(visp)); memset(visn,0,sizeof(visn)); f=0; for(j=0;j<x;j++) { cin>>z; if(z<0) { q=z*-1; visn[q]=1; if(visp[q]==1)f=1; } else { visp[z]=1; if(visn[z]==1)f=1; } } if(f==0)ff=1; } if(ff==1)cout<<"YES"<<endl; else cout<<"NO"<<endl; } return 0; }
jodavis42/ZeroPhysicsTestbed
ZeroLibraries/Zilch/Project/Driver/Test12.cpp
#include "Precompiled.hpp" using namespace Zilch; Array<Real3> GetTemporaryArray(); Integer Test12() { Array<Real3> array; array.PushBack(Real3(53.4f, 1, -45)); array.Resize(5); // Because Real3 doesn't have a zeroing constructor memset(array.Data() + 1, 0, sizeof(Real3) * 4); array[1] = array[0]; array[2] += array[0]; array[3] = array[0] * 5; array[4] = Real3(array[2].y); array[(Integer)array[4].x] += GetTemporaryArray()[1]; HashMap<String, Integer> map; map["Hello"] = 5; map["World"] = 9; map["Hello"] += 100; Real total = 0.0f; ZilchForEach(Real3& val, array.All()) { total += val.x + val.y + val.z; } total += map["Hello"] + map["World"]; return (Integer)total; } Array<Real3> GetTemporaryArray() { Array<Real3> array; array.PushBack(Real3(0, 1, 2)); array.PushBack(Real3(3, 4, 5)); array.PushBack(Real3(6, 7, 8)); return array; }
teodyseguin/icreatives
web/themes/custom/particle/jest.config.js
module.exports = { projects: ['<rootDir>/source/*/jest.config.js'], // Everything below here is used by merging into per-design-system jest config verbose: true, testURL: 'http://localhost/', setupFiles: ['<rootDir>/tools/tests/unit/setupJest.js'], moduleFileExtensions: ['js', 'json', 'vue'], moduleNameMapper: { // Jest doesn't care about styles, twig, images, fonts, etc '\\.(twig|md|yml|yaml|css|jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': '<rootDir>/tools/tests/unit/__mocks__/fileMock.js', }, transform: { '^.+\\.js$': 'babel-jest', '^.+\\.vue$': 'vue-jest', }, };
jaor/bigmler
bigmler/resourcesapi/libraries.py
# -*- coding: utf-8 -*- # # Copyright 2020-2022 BigML # # 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. """Resources management functions """ import sys import bigml.api from bigmler.utils import (dated, get_url, log_message, check_resource, check_resource_error, log_created_resources) from bigmler.resourcesapi.common import set_basic_args, \ update_attributes def set_library_args(args, name=None): """Returns a library arguments dict """ if name is None: name = args.name library_args = set_basic_args(args, name) if args.project_id is not None: library_args.update({"project": args.project_id}) if args.imports is not None: library_args.update({"imports": args.imports_}) update_attributes(library_args, args.json_args.get('library')) return library_args def create_library(source_code, library_args, args, api=None, path=None, session_file=None, log=None): """Creates remote library """ if api is None: api = bigml.api.BigML() message = dated("Creating library \"%s\".\n" % library_args["name"]) log_message(message, log_file=session_file, console=args.verbosity) library = api.create_library(source_code, library_args) log_created_resources("library", path, bigml.api.get_library_id(library), mode='a') library_id = check_resource_error(library, "Failed to create library: ") try: library = check_resource(library, api.get_library, raise_on_error=True) except Exception as exception: sys.exit("Failed to get a compiled library: %s" % str(exception)) message = dated("Library created: %s\n" % get_url(library)) log_message(message, log_file=session_file, console=args.verbosity) log_message("%s\n" % library_id, log_file=log) return library
barnyard/pi
robustness/test/java/com/bt/nia/koala/robustness/parsers/DescribeVolumeOutputParserTest.java
package com.bt.nia.koala.robustness.parsers; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import com.bt.nia.koala.robustness.commands.UnexpectedOutputException; public class DescribeVolumeOutputParserTest { private DescribeVolumeOutputParser describeVolumeOutputParser; private List<String> outputLines; private String describeVolumeVolOutput; private String describeVolumeAttOutput; @Before public void before() { describeVolumeOutputParser = new DescribeVolumeOutputParser("playpen"); outputLines = new ArrayList<String>(); describeVolumeVolOutput = "VOLUME vol-2DCF0465 1 available 2009-05-15T16:21:22+0000"; describeVolumeAttOutput = "ATTACHMENT vol-2DCF0465 i-4D930980 sdb 2009-05-15T16:27:07+0000"; } @Test(expected = UnexpectedOutputException.class) public void shouldFailIfNotOneLine() { // act describeVolumeOutputParser.parse(outputLines); } @Test(expected = UnexpectedOutputException.class) public void shouldFailIfGarbage() { // setup outputLines.add("jwe w0-fjsd s0j"); // act describeVolumeOutputParser.parse(outputLines); } @Test public void shouldDetectVolAndReturnState() { // setup outputLines.add(describeVolumeVolOutput); // act String[] res = describeVolumeOutputParser.parse(outputLines); // assert assertEquals(1, res.length); assertEquals("available", res[0]); } @Test public void shouldDetectVolAndReturnStateEucalyptus152() { // setup describeVolumeVolOutput = "VOLUME vol-BA380A20 1 playpen available 2009-07-03T13:37:00+0000"; outputLines.add(describeVolumeVolOutput); // act String[] res = describeVolumeOutputParser.parse(outputLines); // assert assertEquals(1, res.length); assertEquals("available", res[0]); } @Test public void shouldDetectVolAndReturnStateWhenBothVolAndAttLine() { // setup outputLines.add(describeVolumeVolOutput); outputLines.add(describeVolumeAttOutput); // act String[] res = describeVolumeOutputParser.parse(outputLines); // assert assertEquals(2, res.length); assertEquals("available", res[0]); assertEquals("sdb", res[1]); } @Test public void shouldDetectVolAndReturnStateWhenBothVolAndAttLineEucalyptus152() { // setup describeVolumeVolOutput = "VOLUME vol-BA380A20 1 playpen available 2009-07-03T13:37:00+0000"; describeVolumeAttOutput = "ATTACHMENT vol-BA3E0A22 i-4737078C sdb attached 2009-07-03T14:55:44+0000"; outputLines.add(describeVolumeVolOutput); outputLines.add(describeVolumeAttOutput); // act String[] res = describeVolumeOutputParser.parse(outputLines); // assert assertEquals(2, res.length); assertEquals("available", res[0]); assertEquals("sdb", res[1]); } @Test public void shouldDetectVolAndReturnStateWhenBothVolAndAttachingLineEucalyptus152() { // setup describeVolumeVolOutput = "VOLUME vol-BA380A20 1 playpen available 2009-07-03T13:37:00+0000"; describeVolumeAttOutput = "ATTACHMENT vol-BA3E0A22 i-4737078C sdb attaching 2009-07-03T14:55:44+0000"; outputLines.add(describeVolumeVolOutput); outputLines.add(describeVolumeAttOutput); // act String[] res = describeVolumeOutputParser.parse(outputLines); // assert assertEquals(2, res.length); assertEquals("available", res[0]); assertEquals("sdb", res[1]); } @Test public void shouldDetectVolAndReturnStateWhenBothVolAndAttachingLineOnPiOutput() { // setup describeVolumeVolOutput = "VOLUME vol-19CF1135 1 Chigorin available 2010-03-22T16:52:20+0000"; outputLines.add(describeVolumeVolOutput); describeVolumeOutputParser = new DescribeVolumeOutputParser("Chigorin"); // act String[] res = describeVolumeOutputParser.parse(outputLines); // assert assertEquals(1, res.length); assertEquals("available", res[0]); } @Test public void shouldDetectVolAndReturnStateWhenSnapshotIdIsOnPiOutput() { // setup describeVolumeVolOutput = "VOLUME vol-000AKMKI 0 snap-000HU7Ri cube1-1a creating 2010-11-17T14:59:19+0000"; outputLines.add(describeVolumeVolOutput); describeVolumeOutputParser = new DescribeVolumeOutputParser("cube1-1a", true); // act String[] res = describeVolumeOutputParser.parse(outputLines); // assert assertEquals(1, res.length); assertEquals("creating", res[0]); } }
joalmjoalm/crate
sql/src/main/java/io/crate/planner/node/ddl/CreateBlobTablePlan.java
/* * Licensed to 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.planner.node.ddl; import com.google.common.annotations.VisibleForTesting; import io.crate.analyze.AnalyzedCreateBlobTable; import io.crate.analyze.NumberOfShards; import io.crate.analyze.SymbolEvaluator; import io.crate.analyze.TableParameter; import io.crate.analyze.TableParameters; import io.crate.analyze.TablePropertiesAnalyzer; import io.crate.data.Row; import io.crate.data.Row1; import io.crate.data.RowConsumer; import io.crate.execution.support.OneRowActionListener; import io.crate.expression.symbol.Symbol; import io.crate.metadata.CoordinatorTxnCtx; import io.crate.metadata.Functions; import io.crate.metadata.RelationName; import io.crate.planner.DependencyCarrier; import io.crate.planner.Plan; import io.crate.planner.PlannerContext; import io.crate.planner.operators.SubQueryResults; import io.crate.sql.tree.ClusteredBy; import io.crate.sql.tree.CreateBlobTable; import io.crate.sql.tree.GenericProperties; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.common.settings.Settings; import java.util.function.Function; import static io.crate.blob.v2.BlobIndex.fullIndexName; import static io.crate.blob.v2.BlobIndicesService.SETTING_INDEX_BLOBS_ENABLED; public class CreateBlobTablePlan implements Plan { private final AnalyzedCreateBlobTable analyzedBlobTable; private final NumberOfShards numberOfShards; public CreateBlobTablePlan(AnalyzedCreateBlobTable analyzedBlobTable, NumberOfShards numberOfShards) { this.analyzedBlobTable = analyzedBlobTable; this.numberOfShards = numberOfShards; } @Override public StatementType type() { return StatementType.DDL; } @Override public void executeOrFail(DependencyCarrier dependencies, PlannerContext plannerContext, RowConsumer consumer, Row params, SubQueryResults subQueryResults) throws Exception { RelationName relationName = analyzedBlobTable.relationName(); Settings settings = buildSettings( analyzedBlobTable.createBlobTable(), plannerContext.transactionContext(), plannerContext.functions(), params, subQueryResults, numberOfShards); CreateIndexRequest createIndexRequest = new CreateIndexRequest(fullIndexName(relationName.name()), settings); OneRowActionListener<CreateIndexResponse> listener = new OneRowActionListener<>(consumer, r -> new Row1(1L)); dependencies.createIndexAction().execute(createIndexRequest, listener); } @VisibleForTesting public static Settings buildSettings(CreateBlobTable<Symbol> createBlobTable, CoordinatorTxnCtx txnCtx, Functions functions, Row params, SubQueryResults subQueryResults, NumberOfShards numberOfShards) { Function<? super Symbol, Object> eval = x -> SymbolEvaluator.evaluate( txnCtx, functions, x, params, subQueryResults ); CreateBlobTable<Object> blobTable = createBlobTable.map(eval); GenericProperties<Object> properties = blobTable.genericProperties(); // apply default in case it is not specified in the genericProperties, // if it is it will get overwritten afterwards. TableParameter tableParameter = new TableParameter(); TablePropertiesAnalyzer.analyzeWithBoundValues( tableParameter, TableParameters.CREATE_BLOB_TABLE_PARAMETERS, properties, true ); Settings.Builder builder = Settings.builder(); builder.put(tableParameter.settings()); builder.put(SETTING_INDEX_BLOBS_ENABLED.getKey(), true); int numShards; ClusteredBy<Object> clusteredBy = blobTable.clusteredBy(); if (clusteredBy != null) { numShards = numberOfShards.fromClusteredByClause(clusteredBy); } else { numShards = numberOfShards.defaultNumberOfShards(); } builder.put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, numShards); return builder.build(); } }
cuebook/turnilo
build/client/components/vis-measure-label/vis-measure-label.js
<reponame>cuebook/turnilo "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var React = require("react"); var concrete_series_1 = require("../../../common/models/series/concrete-series"); var delta_1 = require("../delta/delta"); require("./vis-measure-label.scss"); function renderPrevious(datum, series) { var current = series.selectValue(datum, concrete_series_1.SeriesDerivation.CURRENT); var previous = series.selectValue(datum, concrete_series_1.SeriesDerivation.PREVIOUS); var formatter = series.formatter(); return React.createElement(React.Fragment, null, React.createElement("span", { className: "measure-previous-value" }, formatter(previous)), React.createElement(delta_1.Delta, { formatter: formatter, lowerIsBetter: series.measure.lowerIsBetter, currentValue: current, previousValue: previous })); } exports.VisMeasureLabel = function (_a) { var series = _a.series, datum = _a.datum, showPrevious = _a.showPrevious; return React.createElement("div", { className: "vis-measure-label" }, React.createElement("span", { className: "measure-title" }, series.title()), React.createElement("span", { className: "colon" }, ": "), React.createElement("span", { className: "measure-value" }, series.formatValue(datum)), showPrevious && renderPrevious(datum, series)); }; //# sourceMappingURL=vis-measure-label.js.map
BryceHQ/form-designer
src/components/mixins/validatable.js
<reponame>BryceHQ/form-designer<filename>src/components/mixins/validatable.js<gh_stars>0 /* * validate rule */ // do the right thing const rules = { //仅数字和字母 ASCII(value) { var flag = !/[^a-zA-Z0-9]/.test(value); if(flag){ //以数字开头 return !/^[0-9]/.test(value); } return flag; }, }; const Validatable = { _validate(rule, value) { if(rules[rule]){ return rules[rule](value); } return true; } }; export default Validatable;
joschout/LazyBum
src/main/java/io/ConsoleAndFileWriter.java
<gh_stars>1-10 package io; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; /** * Created by joschout. */ public class ConsoleAndFileWriter { PrintWriter consoleWriter; PrintWriter fileWriter; public ConsoleAndFileWriter(File file) throws FileNotFoundException { consoleWriter = new PrintWriter(System.out); fileWriter = new PrintWriter(file); } public void writeLine(String string) { consoleWriter.write(string + "\n"); fileWriter.write(string + "\n"); } public void close() { // consoleWriter.close(); fileWriter.close(); } public void flush() { consoleWriter.flush(); fileWriter.flush(); } }
maltez/react_native
HomeWork/igor.polovenko/homework4_igor.polovenko.js
<reponame>maltez/react_native // Singleton with a generator method let Singleton = (function() { class Single { constructor(n) { this.n = n; } *generate() { for (let i = 0; i < this.n; i++) { yield Math.random().toFixed(3) * 1000; } } } let instance; return { getInstance(n) { if (!instance) { instance = new Single(n); } return instance; } } })(); // First instantiation let instance = Singleton.getInstance(5); for (let num of instance.generate()) { console.log(`${typeof num}: ${num}`); } console.log(); // One more time, try with n = 3, n is ignored let instance2 = Singleton.getInstance(3); for (let num of instance2.generate()) { console.log(`${typeof num}: ${num}`); } // Proxy for User objects class User { constructor() { this.name = 'unset'; this.lastName = 'unset'; this.age = 'unset'; } } let user = new Proxy(new User(), { get(target, prop) { if (prop == 'fullName') { return target['name'] + ' ' + target['lastName']; } return target[prop]; }, set(target, prop, value) { verified = false; switch(prop) { case 'name': case 'lastName': if (value.length < 2 || value.length > 50) { console.log(`Error: "${prop}" length must be in the range 2..50! Received: "${value}".`); return false; } verified = true; break; case 'age': if (+value < 0 || +value > 100) { console.log(`Error: "${prop}" must be in the range 0..100! Received: "${value}".`); return false; } verified = true; break; } target[prop] = value; if (verified) { console.log(`Value "${value}" for property "${prop}" is verified and set by proxy.`); } return true; } }) user.name = 'a'; console.log(`User name: ${user.name}`); user.name = 'Ivan'; console.log(`User name: ${user.name}`); user.lastName = 'b'; console.log(`User last name: ${user.lastName}`); user.lastName = 'Popov'; console.log(`User last name: ${user.lastName}`); user.age = 300; console.log(`User age: ${user.age}`); user.age = 30; console.log(`User age: ${user.age}`); console.log(`User full name: ${user.fullName}`);
ValKhv/BGX
MOBILAPP/BGX-App/BGX/ios/Pods/Headers/Private/FirebaseMessaging/FIRMessagingSecureSocket.h
link ../../../FirebaseMessaging/Firebase/Messaging/FIRMessagingSecureSocket.h
gerlichlab/HiCognition
back_end/tests/post_routes/test_api_preprocess_dataset.py
"""Module with tests realted to preprocessign datasets.""" import unittest from unittest.mock import MagicMock, patch import pandas as pd from flask.globals import current_app from hicognition.test_helpers import LoginTestCase, TempDirTestCase # add path to import app # import sys # sys.path.append("./") from app import db from app.models import Dataset, Task, Intervals class TestPreprocessDataset(LoginTestCase, TempDirTestCase): """Tests correct launching of pipelines after posting parameters to /preprocess/datasets/ route. Inherits both from LoginTest and TempDirTestCase to be able to login and make temporary directory""" def setUp(self): """adds test datasets to db""" super().setUp() # create mock csv mock_df = pd.DataFrame( {"chrom": ["chr1"] * 3, "start": [1, 2, 3], "end": [4, 5, 6]} ) mock_df.to_csv( current_app.config["UPLOAD_DIR"] + "/test.bed", index=False, sep="\t" ) # create datasets dataset1 = Dataset( id=1, dataset_name="test1", file_path="/test/path/1", filetype="cooler", user_id=1, ) dataset2 = Dataset( id=2, dataset_name="test2", file_path="/test/path/2", filetype="cooler", user_id=1, ) dataset3 = Dataset( id=3, dataset_name="test3", file_path="/test/path/3", filetype="bedfile", user_id=2, ) dataset4 = Dataset( id=4, dataset_name="test4", file_path=current_app.config["UPLOAD_DIR"] + "/test.bed", filetype="bedfile", user_id=1, ) dataset5 = Dataset( id=5, dataset_name="test1", file_path="/test/path/1", filetype="cooler", user_id=2, public=True, ) dataset6 = Dataset( id=6, dataset_name="test1", file_path="/test/path/1", filetype="bigwig", user_id=1, ) dataset7 = Dataset( id=7, dataset_name="test1", file_path="/test/path/1", filetype="bigwig", user_id=1, ) interval1 = Intervals(id=1, name="interval1", windowsize=100000, dataset_id=4) interval2 = Intervals(id=2, name="interval2", windowsize=50000, dataset_id=4) interval3 = Intervals(id=3, name="interval3", windowsize=400000, dataset_id=4) interval4 = Intervals(id=4, name="interval4", windowsize=1000000, dataset_id=4) interval5 = Intervals(id=5, name="interval5", windowsize=2000000, dataset_id=4) interval6 = Intervals(id=6, name="interval6", windowsize=10000, dataset_id=4) interval7 = Intervals(id=7, name="interval7", windowsize=20000, dataset_id=4) self.default_data = [ dataset1, dataset2, dataset3, dataset4, dataset5, dataset6, dataset7, interval1, interval2, interval3, interval4, interval5, interval6, interval7, ] self.incomplete_data = [ dataset1, dataset2, dataset3, dataset4, dataset5, dataset6, dataset7, interval1, interval2, interval3, interval4, interval5, ] @patch("app.models.User.launch_task") def test_pipeline_pileup_is_called_correctly(self, mock_launch): """Tests whether cooler pipeline to do pileups is called correctly.""" # add data db.session.add_all(self.default_data) db.session.commit() # authenticate token = self.add_and_authenticate("test", "asdf") token_headers = self.get_token_header(token) # define call arguments data = { "dataset_ids": "[1]", "region_ids": "[4]", "preprocessing_map": "PREPROCESSING_MAP", } # dispatch post request response = self.client.post( "/api/preprocess/datasets/", data=data, headers=token_headers, content_type="multipart/form-data", ) self.assertEqual(response.status_code, 200) # check whether pipeline has been called with right parameters intervals = [1, 2, 3, 4, 5] for interval_id in intervals: interval = Intervals.query.get(interval_id) for binsize in current_app.config["PREPROCESSING_MAP"][interval.windowsize][ "cooler" ]: mock_launch.assert_any_call( self.app.queues["long"], "pipeline_pileup", "run pileup pipeline", 1, intervals_id=interval.id, binsize=binsize, ) @patch("app.models.User.launch_task") def test_pipeline_pileup_is_called_correctly_w_small_preprocessing_map( self, mock_launch ): """Tests whether cooler pipeline to do pileups is called correctly.""" # add data db.session.add_all(self.default_data) db.session.commit() # authenticate token = self.add_and_authenticate("test", "asdf") token_headers = self.get_token_header(token) # define call arguments data = { "dataset_ids": "[1]", "region_ids": "[4]", "preprocessing_map": "PREPROCESSING_MAP_SMALL_WINDOWSIZES", } # dispatch post request response = self.client.post( "/api/preprocess/datasets/", data=data, headers=token_headers, content_type="multipart/form-data", ) self.assertEqual(response.status_code, 200) # check whether pipeline has been called with right parameters intervals = [2, 6, 7] for interval_id in intervals: interval = Intervals.query.get(interval_id) for binsize in current_app.config["PREPROCESSING_MAP_SMALL_WINDOWSIZES"][ interval.windowsize ]["cooler"]: mock_launch.assert_any_call( self.app.queues["long"], "pipeline_pileup", "run pileup pipeline", 1, intervals_id=interval.id, binsize=binsize, ) @patch("app.models.User.launch_task") def test_user_cannot_access_other_datasets(self, mock_launch): """Tests whether cooler pipeline to do pileups is called correctly.""" # add data db.session.add_all(self.default_data) db.session.commit() # authenticate token = self.add_and_authenticate("test", "asdf") token_headers = self.get_token_header(token) # construct post data data = { "dataset_ids": "[3]", "region_ids": "[4]", "preprocessing_map": "PREPROCESSING_MAP_SMALL_WINDOWSIZES", } # dispatch post request response = self.client.post( "/api/preprocess/datasets/", data=data, headers=token_headers, content_type="multipart/form-data", ) self.assertEqual(response.status_code, 403) @patch("app.models.User.launch_task") def test_404_on_non_existent_dataset(self, mock_launch): """Tests whether cooler pipeline to do pileups is called correctly.""" # add data db.session.add_all(self.default_data) db.session.commit() # authenticate token = self.add_and_authenticate("test", "asdf") token_headers = self.get_token_header(token) # construct post data data = { "dataset_ids": "[100]", "region_ids": "[4]", "preprocessing_map": "PREPROCESSING_MAP_SMALL_WINDOWSIZES", } # dispatch post request response = self.client.post( "/api/preprocess/datasets/", data=data, headers=token_headers, content_type="multipart/form-data", ) self.assertEqual(response.status_code, 404) @patch("app.models.User.launch_task") def test_400_on_bad_form(self, mock_launch): """Tests whether cooler pipeline to do pileups is called correctly.""" # add data db.session.add_all(self.default_data) db.session.commit() # authenticate token = self.add_and_authenticate("test", "asdf") token_headers = self.get_token_header(token) # construct post data data = {"region_ids": "[4]"} # dispatch post request response = self.client.post( "/api/preprocess/datasets/", data=data, headers=token_headers, content_type="multipart/form-data", ) self.assertEqual(response.status_code, 400) @patch("app.models.User.launch_task") def test_pipeline_pileup_is_called_correctly_for_public_unowned_dataset( self, mock_launch ): """Tests whether cooler pipeline to do pileups is called correctly.""" # add data db.session.add_all(self.default_data) db.session.commit() # authenticate token = self.add_and_authenticate("test", "asdf") token_headers = self.get_token_header(token) # construct post data # call args data = { "dataset_ids": "[5]", "region_ids": "[4]", "preprocessing_map": "PREPROCESSING_MAP", } # dispatch post request response = self.client.post( "/api/preprocess/datasets/", data=data, headers=token_headers, content_type="multipart/form-data", ) self.assertEqual(response.status_code, 200) # check whether pipeline has been called with right parameters intervals = [1, 2, 3, 4, 5] for interval_id in intervals: interval = Intervals.query.get(interval_id) for binsize in current_app.config["PREPROCESSING_MAP"][interval.windowsize][ "cooler" ]: mock_launch.assert_any_call( self.app.queues["long"], "pipeline_pileup", "run pileup pipeline", 5, intervals_id=interval.id, binsize=binsize, ) @patch("app.models.User.launch_task") def test_pipeline_stackup_is_called_correctly_for_owned_dataset(self, mock_launch): """Tests whether bigwig pipeline to do pileups is called correctly.""" # add data db.session.add_all(self.default_data) db.session.commit() # authenticate token = self.add_and_authenticate("test", "asdf") token_headers = self.get_token_header(token) # construct post data data = { "dataset_ids": "[6]", "region_ids": "[4]", "preprocessing_map": "PREPROCESSING_MAP", } # dispatch post request response = self.client.post( "/api/preprocess/datasets/", data=data, headers=token_headers, content_type="multipart/form-data", ) self.assertEqual(response.status_code, 200) # check whether pipeline has been called with right parameters intervals = [1, 2, 3, 4, 5] for interval_id in intervals: interval = Intervals.query.get(interval_id) for binsize in current_app.config["PREPROCESSING_MAP"][interval.windowsize][ "bigwig" ]: mock_launch.assert_any_call( self.app.queues["medium"], "pipeline_stackup", "run stackup pipeline", 6, intervals_id=interval.id, binsize=binsize, ) @patch("app.models.User.launch_task") @patch("app.models.Task.get_rq_job") def test_failed_tasks_deleted_after_relaunch(self, mock_get_rq_job, mock_launch): """Tests whether preprocessing api call deletes any remaining jobs that have failed.""" # add data db.session.add_all(self.default_data) db.session.commit() # patch mock_job = MagicMock() mock_job.get_status.return_value = "failed" mock_get_rq_job.return_value = mock_job # authenticate token = self.add_and_authenticate("test", "asdf") token_headers = self.get_token_header(token) # add tasks to be deleted task1 = Task(id="test", name="test", user_id=1, dataset_id=1, intervals_id=1) task2 = Task(id="test2", name="test2", user_id=1, dataset_id=1, intervals_id=1) # add tasks to be left alone task3 = Task(id="test3", name="test2", user_id=1, dataset_id=1, intervals_id=10) task4 = Task(id="test4", name="test2", user_id=1, dataset_id=2, intervals_id=1) db.session.add_all([task1, task2, task3, task4]) db.session.commit() data = { "dataset_ids": "[1]", "region_ids": "[4]", "preprocessing_map": "PREPROCESSING_MAP", } # dispatch post request response = self.client.post( "/api/preprocess/datasets/", data=data, headers=token_headers, content_type="multipart/form-data", ) self.assertEqual(response.status_code, 200) # check correct tasks where deleted self.assertEqual(Task.query.all(), [task3, task4]) @patch("app.models.User.launch_task") def test_mixed_pipelines_called_correctly_with_multiple_owned_datasets( self, mock_launch ): """Tests whether bigwig pipeline to do pileups is called correctly.""" # add data db.session.add_all(self.default_data) db.session.commit() # authenticate token = self.add_and_authenticate("test", "asdf") token_headers = self.get_token_header(token) # construct post data data = { "dataset_ids": "[2, 6]", "region_ids": "[4]", "preprocessing_map": "PREPROCESSING_MAP", } # dispatch post request response = self.client.post( "/api/preprocess/datasets/", data=data, headers=token_headers, content_type="multipart/form-data", ) self.assertEqual(response.status_code, 200) # check whether pipeline has been called with right parameters intervals = [1] datasets = [2, 6] for interval_id in intervals: interval = Intervals.query.get(interval_id) for dataset_id in datasets: dataset = Dataset.query.get(dataset_id) for binsize in current_app.config["PREPROCESSING_MAP"][ interval.windowsize ][dataset.filetype]: mock_launch.assert_any_call( current_app.queues[ current_app.config["PIPELINE_QUEUES"][dataset.filetype] ], *current_app.config["PIPELINE_NAMES"][dataset.filetype], dataset_id, intervals_id=interval.id, binsize=binsize, ) # check whether processing datasets where added correctly region_dataset = Dataset.query.get(4) feature_datasets = Dataset.query.filter(Dataset.id.in_([2, 6])).all() self.assertEqual(region_dataset.processing_features, feature_datasets) @patch("app.models.User.launch_task") def test_pipeline_stackup_is_called_correctly_for_multiple_owned_datasets( self, mock_launch ): """Tests whether bigwig pipeline to do pileups is called correctly.""" # add data db.session.add_all(self.default_data) db.session.commit() # authenticate token = self.add_and_authenticate("test", "asdf") token_headers = self.get_token_header(token) # construct post data data = { "dataset_ids": "[6, 7]", "region_ids": "[4]", "preprocessing_map": "PREPROCESSING_MAP", } # dispatch post request response = self.client.post( "/api/preprocess/datasets/", data=data, headers=token_headers, content_type="multipart/form-data", ) self.assertEqual(response.status_code, 200) # check whether pipeline has been called with right parameters intervals = [1, 2, 4, 5] datasets = [6, 7] for interval_id in intervals: interval = Intervals.query.get(interval_id) for dataset_id in datasets: dataset = Dataset.query.get(dataset_id) for binsize in current_app.config["PREPROCESSING_MAP"][ interval.windowsize ][dataset.filetype]: mock_launch.assert_any_call( self.app.queues["medium"], "pipeline_stackup", "run stackup pipeline", dataset_id, intervals_id=interval.id, binsize=binsize, ) if __name__ == "__main__": res = unittest.main(verbosity=3, exit=False)
bugvm/robovm
Core/llvm/src/main/swig/include/llvm/Analysis/Passes.h
//===-- llvm/Analysis/Passes.h - Constructors for analyses ------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This header file defines prototypes for accessor functions that expose passes // in the analysis libraries. // //===----------------------------------------------------------------------===// #ifndef LLVM_ANALYSIS_PASSES_H #define LLVM_ANALYSIS_PASSES_H namespace llvm { class FunctionPass; class ImmutablePass; class LoopPass; class ModulePass; class Pass; class PassInfo; class LibCallInfo; //===--------------------------------------------------------------------===// // // createGlobalsModRefPass - This pass provides alias and mod/ref info for // global values that do not have their addresses taken. // Pass *createGlobalsModRefPass(); //===--------------------------------------------------------------------===// // // createAliasDebugger - This pass helps debug clients of AA // Pass *createAliasDebugger(); //===--------------------------------------------------------------------===// // // createAliasAnalysisCounterPass - This pass counts alias queries and how the // alias analysis implementation responds. // ModulePass *createAliasAnalysisCounterPass(); //===--------------------------------------------------------------------===// // // createAAEvalPass - This pass implements a simple N^2 alias analysis // accuracy evaluator. // FunctionPass *createAAEvalPass(); //===--------------------------------------------------------------------===// // // createNoAAPass - This pass implements a "I don't know" alias analysis. // ImmutablePass *createNoAAPass(); //===--------------------------------------------------------------------===// // // createBasicAliasAnalysisPass - This pass implements the stateless alias // analysis. // ImmutablePass *createBasicAliasAnalysisPass(); //===--------------------------------------------------------------------===// // // createCFLAliasAnalysisPass - This pass implements a set-based approach to // alias analysis. // ImmutablePass *createCFLAliasAnalysisPass(); //===--------------------------------------------------------------------===// // /// createLibCallAliasAnalysisPass - Create an alias analysis pass that knows /// about the semantics of a set of libcalls specified by LCI. The newly /// constructed pass takes ownership of the pointer that is provided. /// FunctionPass *createLibCallAliasAnalysisPass(LibCallInfo *LCI); //===--------------------------------------------------------------------===// // // createScalarEvolutionAliasAnalysisPass - This pass implements a simple // alias analysis using ScalarEvolution queries. // FunctionPass *createScalarEvolutionAliasAnalysisPass(); //===--------------------------------------------------------------------===// // // createTypeBasedAliasAnalysisPass - This pass implements metadata-based // type-based alias analysis. // ImmutablePass *createTypeBasedAliasAnalysisPass(); //===--------------------------------------------------------------------===// // // createScopedNoAliasAAPass - This pass implements metadata-based // scoped noalias analysis. // ImmutablePass *createScopedNoAliasAAPass(); //===--------------------------------------------------------------------===// // // createObjCARCAliasAnalysisPass - This pass implements ObjC-ARC-based // alias analysis. // ImmutablePass *createObjCARCAliasAnalysisPass(); FunctionPass *createPAEvalPass(); //===--------------------------------------------------------------------===// // /// createLazyValueInfoPass - This creates an instance of the LazyValueInfo /// pass. FunctionPass *createLazyValueInfoPass(); //===--------------------------------------------------------------------===// // // createDependenceAnalysisPass - This creates an instance of the // DependenceAnalysis pass. // FunctionPass *createDependenceAnalysisPass(); //===--------------------------------------------------------------------===// // // createCostModelAnalysisPass - This creates an instance of the // CostModelAnalysis pass. // FunctionPass *createCostModelAnalysisPass(); //===--------------------------------------------------------------------===// // // createDelinearizationPass - This pass implements attempts to restore // multidimensional array indices from linearized expressions. // FunctionPass *createDelinearizationPass(); //===--------------------------------------------------------------------===// // // Minor pass prototypes, allowing us to expose them through bugpoint and // analyze. FunctionPass *createInstCountPass(); //===--------------------------------------------------------------------===// // // createRegionInfoPass - This pass finds all single entry single exit regions // in a function and builds the region hierarchy. // FunctionPass *createRegionInfoPass(); // Print module-level debug info metadata in human-readable form. ModulePass *createModuleDebugInfoPrinterPass(); //===--------------------------------------------------------------------===// // // createMemDepPrinter - This pass exhaustively collects all memdep // information and prints it with -analyze. // FunctionPass *createMemDepPrinter(); // createJumpInstrTableInfoPass - This creates a pass that stores information // about the jump tables created by JumpInstrTables ImmutablePass *createJumpInstrTableInfoPass(); } #endif
xiliax/web-programming
code/c10-ToDo-Webapp-Bootstrap/todo-app/tests/client/task/factory/tasks_test.js
'use strict'; describe('Tasks', function() { var _Tasks; beforeEach(module('todo')); beforeEach(inject(function($injector) { _Tasks = $injector.get('Tasks'); })); describe('instance', function() { it('should have the right prop for the instance', function() { var _something = new _Tasks(); expect(_something.something).toEqual(123); }); }); describe('isValid', function() { it('should return true', function() { var _something = new _Tasks(); expect(_something.isValid()).toBeTruthy(); }); }); });
codefollower/Open-Source-Research
Javac2007/流程/jvm/ClassReader_methods/indexPool.java
/************************************************************************ * Constant Pool Access ***********************************************************************/ /** Index all constant pool entries, writing their start addresses into * poolIdx. */ void indexPool() { try {//我加上的 DEBUG.P(this,"indexPool()"); poolIdx = new int[nextChar()]; poolObj = new Object[poolIdx.length]; DEBUG.P("poolIdx.length="+poolIdx.length); int i = 1;//常量池索引0保留不用 while (i < poolIdx.length) { poolIdx[i++] = bp; byte tag = buf[bp++]; //DEBUG.P("i="+(i-1)+" tag="+tag+" bp="+(bp-1)); switch (tag) { case CONSTANT_Utf8: case CONSTANT_Unicode: { int len = nextChar(); bp = bp + len; break; } case CONSTANT_Class: case CONSTANT_String: bp = bp + 2; break; case CONSTANT_Fieldref: case CONSTANT_Methodref: case CONSTANT_InterfaceMethodref: case CONSTANT_NameandType: case CONSTANT_Integer: case CONSTANT_Float: bp = bp + 4; break; case CONSTANT_Long: case CONSTANT_Double: bp = bp + 8; i++; break; default: throw badClassFile("bad.const.pool.tag.at", Byte.toString(tag), Integer.toString(bp -1)); } } StringBuffer sb=new StringBuffer(); for(int n:poolIdx) sb.append(n).append(" "); DEBUG.P("poolIdx="+sb.toString()); }finally{//我加上的 DEBUG.P(0,this,"indexPool()"); } }
LendoAB/go-pingdom
acceptance/acceptance_ext_test.go
<filename>acceptance/acceptance_ext_test.go<gh_stars>0 package acceptance import ( "net/http" "os" "testing" "time" "github.com/lendoab/go-pingdom/pingdomext" "github.com/stretchr/testify/assert" ) var client_ext *pingdomext.Client var runExtAcceptance bool func init() { if os.Getenv("PINGDOM_EXT_ACCEPTANCE") == "1" { runExtAcceptance = true config := pingdomext.ClientConfig{ HTTPClient: &http.Client{ Timeout: time.Second * 10, CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }, }, } client_ext, _ = pingdomext.NewClientWithConfig(config) } } func TestIntegrations(t *testing.T) { if !runExtAcceptance { t.Skip() } integration := pingdomext.WebHookIntegration{ Active: false, ProviderID: 2, UserData: &pingdomext.WebHookData{ Name: "wlwu-tets-1", URL: "http://www.example.com", }, } createMsg, err := client_ext.Integrations.Create(&integration) assert.NoError(t, err) assert.NotNil(t, createMsg) assert.NotEmpty(t, createMsg) assert.True(t, createMsg.Status) integrationID := createMsg.ID listMsg, err := client_ext.Integrations.List() assert.NoError(t, err) assert.NotNil(t, listMsg) assert.NotEmpty(t, listMsg) getMsg, err := client_ext.Integrations.Read(integrationID) assert.NoError(t, err) assert.NotNil(t, getMsg) assert.NotEmpty(t, getMsg) assert.NotEmpty(t, getMsg.CreatedAt) assert.NotEmpty(t, getMsg.Name) integration.Active = true integration.UserData.Name = "wlwu-tets-update" integration.UserData.URL = "http://www.example1.com" updateMsg, err := client_ext.Integrations.Update(integrationID, &integration) assert.NoError(t, err) assert.NotNil(t, updateMsg) assert.True(t, updateMsg.Status) delMsg, err := client_ext.Integrations.Delete(integrationID) assert.NoError(t, err) assert.NotNil(t, delMsg) assert.True(t, delMsg.Status) listProviderMsg, err := client_ext.Integrations.ListProviders() assert.NoError(t, err) assert.NotNil(t, listProviderMsg) assert.Equal(t, len(listProviderMsg), 2) }
QuestionableM/Tile-Converter
Code/Tile/TileConverter.hpp
#pragma once #include <string> class ConvertSettings { ConvertSettings() = default; ~ConvertSettings() = default; public: //model settings inline static bool ExportUvs = true; inline static bool ExportNormals = true; inline static bool ExportMaterials = true; inline static bool ExportGroundTextures = false; //tile settings inline static bool ExportClutter = true; inline static bool ExportAssets = true; inline static bool ExportPrefabs = true; inline static bool ExportBlueprints = true; inline static bool ExportHarvestables = true; }; class ConvertError { unsigned short ErrorCode = 0; std::wstring ErrorMessage = L""; public: ConvertError() = default; ConvertError(const unsigned short& ec, const std::wstring& error_msg); explicit operator bool() const noexcept; std::wstring GetErrorMsg() const noexcept; }; class TileConv { TileConv() = default; ~TileConv() = default; static void WriteToFileInternal(class Tile* pTile, const std::wstring& tile_name, ConvertError& cError); public: static void ConvertToModel(const std::wstring& tile_path, const std::wstring& tile_name, ConvertError& cError); };
jjzhang166/balancer
util/system/fstat.h
#pragma once #include "defaults.h" class TFile; class TFileHandle; class Stroka; struct TFileStat { ui32 Mode; /* protection */ ui32 Uid; /* user ID of owner */ ui32 Gid; /* group ID of owner */ ui64 NLinks; /* number of hard links */ ui64 Size; /* total size, in bytes */ time_t ATime; /* time of last access */ time_t MTime; /* time of last modification */ time_t CTime; /* time of last status change */ public: TFileStat(); explicit TFileStat(const TFile&); explicit TFileStat(const TFileHandle&); explicit TFileStat(const Stroka& f); };
tpoveda/tpMayaLib
tpDcc/dccs/maya/core/mash.py
<reponame>tpoveda/tpMayaLib #! /usr/bin/env python # -*- coding: utf-8 -*- """ Module that contains functions and classes related with MASH nodes """ from __future__ import print_function, division, absolute_import import maya.cmds import maya.mel MASH_AVAILABLE = True try: import MASH.api as mapi import MASH.undo as undo import MASHoutliner import mash_repro_utils import mash_repro_aetemplate except ImportError: MASH_AVAILABLE = False from tpDcc.dccs.maya.core import name as naming, gui def get_mash_nodes(): """ Returns a list with all MASH nodes in current Maya scene :return: list<str> """ return maya.cmds.ls(type='MASH_Waiter') def create_mash_network(name='New_Mash_Network', type='repro'): name = naming.find_available_name(name=name) if type == 'instancer': maya.mel.eval('optionVar -iv mOGT 1;') elif type == 'repro': maya.mel.eval('optionVar -iv mOGT 2;') waiter_node = maya.mel.eval('MASHnewNetwork("{0}")'.format(name))[0] mash_network = get_mash_network(waiter_node) return mash_network def get_mash_network(node_name): if maya.cmds.objExists(node_name): return mapi.Network(node_name) return None if MASH_AVAILABLE: @undo.chunk('Removing MASH Network') def remove_mash_network(network): print(type(network)) if type(network) == unicode: network = get_mash_network(network) if network: if maya.cmds.objExists(network.instancer): maya.cmds.delete(network.instancer) if maya.cmds.objExists(network.distribute): maya.cmds.delete(network.distribute) if maya.cmds.objExists(network.waiter): maya.cmds.delete(network.waiter) def get_mash_outliner_tree(): return MASHoutliner.OutlinerTreeView() if MASH_AVAILABLE: @undo.chunk def add_mesh_to_repro(repro_node, meshes=None): maya.cmds.undoInfo(ock=True) if meshes is None: meshes = maya.cmds.ls(sl=True) for obj in meshes: if maya.cmds.objectType(obj) == 'mesh': obj = maya.cmds.listRelatives(obj, parent=True)[0] if maya.cmds.listRelatives(obj, ad=True, type='mesh'): mash_repro_utils.connect.mesh_group(repro_node, obj) maya.cmds.undoInfo(cck=True) def get_repro_object_widget(repro_node): if not repro_node: return maya_window = gui.get_maya_window() repro_widgets = maya_window.findChildren(mash_repro_aetemplate.ObjectsWidget) or [] if len(repro_widgets) > 0: return repro_widgets[0] return None def set_repro_object_widget_enabled(repro_node, flag): repro_widget = get_repro_object_widget(repro_node) if not repro_widget: return repro_widget.parent().parent().setEnabled(flag)
KyleU/databaseflow
app/models/result/CachedResultTransform.scala
<gh_stars>100-1000 package models.result import models.query.QueryResult import models.schema.ColumnType object CachedResultTransform { def transform(columns: Seq[QueryResult.Col], data: Seq[Option[Any]]) = columns.zip(data).map { case x if x._1.t == ColumnType.DateType && x._2.exists(_.isInstanceOf[String]) => x._2.map(_.toString.stripSuffix(" 00:00:00")) case x if x._1.t == ColumnType.StringType && x._2.exists(_.isInstanceOf[String]) => x._2.map { s => val str = s.toString if (str.length > x._1.precision.getOrElse(Int.MaxValue)) { str.substring(0, x._1.precision.getOrElse(Int.MaxValue)) } else { str } } case x => x._2 } }
phatblat/macOSPrivateFrameworks
PrivateFrameworks/GameCenterUI/GKBaseGameCell.h
<gh_stars>10-100 // // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import <GameCenterUI/GKCollectionViewCell.h> @class GKGame, GKGameRecord, NSImageView, NSLayoutConstraint, NSTextField; @interface GKBaseGameCell : GKCollectionViewCell { NSImageView *_iconView; NSTextField *_nameLabel; NSLayoutConstraint *_nameYConstraint; double _nameYOffset; } + (id)itemHeightList; + (double)defaultRowHeight; @property(nonatomic) double nameYOffset; // @synthesize nameYOffset=_nameYOffset; @property(nonatomic) NSLayoutConstraint *nameYConstraint; // @synthesize nameYConstraint=_nameYConstraint; @property(retain, nonatomic) NSTextField *nameLabel; // @synthesize nameLabel=_nameLabel; @property(retain, nonatomic) NSImageView *iconView; // @synthesize iconView=_iconView; - (void)prepareForReuse; - (void)didUpdateModel; - (void)setRepresentedItem:(id)arg1; @property(retain, nonatomic) GKGame *game; @property(retain, nonatomic) GKGameRecord *gameRecord; - (struct CGRect)alignmentRectForText; - (void)dealloc; - (void)setSelected:(BOOL)arg1; - (void)configureContextMenu:(id)arg1; - (void)didUpdateModel; - (void)awakeFromNib; @end
secure-software-engineering/TS4J
EclipseTestWorkspace/net.oschina.app/src/net/oschina/app/bean/User.java
package net.oschina.app.bean; import java.io.IOException; import java.io.InputStream; import net.oschina.app.AppException; import net.oschina.app.common.StringUtils; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.util.Xml; /** * 登录用户实体类 * @author liux (http://my.oschina.net/liux) * @version 1.0 * @created 2012-3-21 */ public class User extends Base { public final static int RELATION_ACTION_DELETE = 0x00;//取消关注 public final static int RELATION_ACTION_ADD = 0x01;//加关注 public final static int RELATION_TYPE_BOTH = 0x01;//双方互为粉丝 public final static int RELATION_TYPE_FANS_HIM = 0x02;//你单方面关注他 public final static int RELATION_TYPE_NULL = 0x03;//互不关注 public final static int RELATION_TYPE_FANS_ME = 0x04;//只有他关注我 private int uid; private String location; private String name; private int followers; private int fans; private int score; private String face; private String account; private String pwd; private Result validate; private boolean isRememberMe; private String jointime; private String gender; private String devplatform; private String expertise; private int relation; private String latestonline; public boolean isRememberMe() { return isRememberMe; } public void setRememberMe(boolean isRememberMe) { this.isRememberMe = isRememberMe; } public String getJointime() { return jointime; } public void setJointime(String jointime) { this.jointime = jointime; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getDevplatform() { return devplatform; } public void setDevplatform(String devplatform) { this.devplatform = devplatform; } public String getExpertise() { return expertise; } public void setExpertise(String expertise) { this.expertise = expertise; } public int getRelation() { return relation; } public void setRelation(int relation) { this.relation = relation; } public String getLatestonline() { return latestonline; } public void setLatestonline(String latestonline) { this.latestonline = latestonline; } public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getFollowers() { return followers; } public void setFollowers(int followers) { this.followers = followers; } public int getFans() { return fans; } public void setFans(int fans) { this.fans = fans; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } public String getFace() { return face; } public void setFace(String face) { this.face = face; } public Result getValidate() { return validate; } public void setValidate(Result validate) { this.validate = validate; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public static User parse(InputStream stream) throws IOException, AppException { User user = new User(); Result res = null; // 获得XmlPullParser解析器 XmlPullParser xmlParser = Xml.newPullParser(); try { xmlParser.setInput(stream, Base.UTF8); // 获得解析到的事件类别,这里有开始文档,结束文档,开始标签,结束标签,文本等等事件。 int evtType = xmlParser.getEventType(); // 一直循环,直到文档结束 while (evtType != XmlPullParser.END_DOCUMENT) { String tag = xmlParser.getName(); switch (evtType) { case XmlPullParser.START_TAG: // 如果是标签开始,则说明需要实例化对象了 if (tag.equalsIgnoreCase("result")) { res = new Result(); } else if (tag.equalsIgnoreCase("errorCode")) { res.setErrorCode(StringUtils.toInt(xmlParser.nextText(), -1)); } else if (tag.equalsIgnoreCase("errorMessage")) { res.setErrorMessage(xmlParser.nextText().trim()); } else if (res != null && res.OK()) { if(tag.equalsIgnoreCase("uid")){ user.uid = StringUtils.toInt(xmlParser.nextText(), 0); }else if(tag.equalsIgnoreCase("location")){ user.setLocation(xmlParser.nextText()); }else if(tag.equalsIgnoreCase("name")){ user.setName(xmlParser.nextText()); }else if(tag.equalsIgnoreCase("followers")){ user.setFollowers(StringUtils.toInt(xmlParser.nextText(), 0)); }else if(tag.equalsIgnoreCase("fans")){ user.setFans(StringUtils.toInt(xmlParser.nextText(), 0)); }else if(tag.equalsIgnoreCase("score")){ user.setScore(StringUtils.toInt(xmlParser.nextText(), 0)); }else if(tag.equalsIgnoreCase("portrait")){ user.setFace(xmlParser.nextText()); } //通知信息 else if(tag.equalsIgnoreCase("notice")) { user.setNotice(new Notice()); } else if(user.getNotice() != null) { if(tag.equalsIgnoreCase("atmeCount")) { user.getNotice().setAtmeCount(StringUtils.toInt(xmlParser.nextText(),0)); } else if(tag.equalsIgnoreCase("msgCount")) { user.getNotice().setMsgCount(StringUtils.toInt(xmlParser.nextText(),0)); } else if(tag.equalsIgnoreCase("reviewCount")) { user.getNotice().setReviewCount(StringUtils.toInt(xmlParser.nextText(),0)); } else if(tag.equalsIgnoreCase("newFansCount")) { user.getNotice().setNewFansCount(StringUtils.toInt(xmlParser.nextText(),0)); } } } break; case XmlPullParser.END_TAG: //如果遇到标签结束,则把对象添加进集合中 if (tag.equalsIgnoreCase("result") && res != null) { user.setValidate(res); } break; } // 如果xml没有结束,则导航到下一个节点 evtType = xmlParser.next(); } } catch (XmlPullParserException e) { throw AppException.xml(e); } finally { stream.close(); } return user; } }
femtoframework/femto-endpoint
endpoint/src/main/java/org/femtoframework/net/nio/cmd/AbstractCommandHandler.java
package org.femtoframework.net.nio.cmd; import java.util.Collections; import java.util.List; /** * 抽象命令处理器 * * @author fengyun * @version 1.00 2005-1-2 15:21:56 */ public abstract class AbstractCommandHandler implements CommandHandler { /** * 监听者列表 */ private CommandListener commandlisteners; /** * 监听者列表 */ private CommandContextListener contextlisteners; /** * 添加Command监听者 * * @param listener */ public void addCommandListener(CommandListener listener) { if (listener == null) { return; } if (commandlisteners == null) { commandlisteners = listener; } else if (commandlisteners instanceof CommandListeners) { ((CommandListeners)commandlisteners).addListener(listener); } else { commandlisteners = new CommandListeners(commandlisteners); ((CommandListeners)commandlisteners).addListener(listener); } } /** * 返回Context侦听者 * * @return BaseCommandListener[] */ public List<CommandListener> getCommandListeners() { if (commandlisteners != null) { if (commandlisteners instanceof CommandListeners) { return ((CommandListeners)commandlisteners).getListeners(); } else { return Collections.singletonList(commandlisteners); } } return Collections.emptyList(); } /** * 设置Context侦听者 * * @param listeners context侦听者 */ public void setCommandListeners(List<CommandListener> listeners) { if (listeners == null || listeners.isEmpty()) { return; } this.commandlisteners = new CommandListeners(listeners); } /** * 删除Command监听者 * * @param listener Command监听者 */ public void removeCommandListener(CommandListener listener) { if (listener == null) { return; } if (commandlisteners != null) { if (commandlisteners instanceof CommandListeners) { ((CommandListeners)commandlisteners).removeListener(listener); } else if (commandlisteners == listener) { commandlisteners = null; } } } /** * 当有命令到达的时候调用 * * @param context Command Context * @param command 命令数据 * @param off 起始位置 * @param len 长度 */ public boolean fireCommandEvent(CommandContext context, byte[] command, int off, int len) { if (commandlisteners != null) { commandlisteners.onCommand(context, command, off, len); return true; } return false; } /** * 添加Context监听者 * * @param listener */ public void addContextListener(CommandContextListener listener) { if (listener == null) { return; } if (contextlisteners == null) { contextlisteners = listener; } else if (contextlisteners instanceof CommandContextListeners) { ((CommandContextListeners)contextlisteners).addListener(listener); } else { contextlisteners = new CommandContextListeners(contextlisteners); ((CommandContextListeners)contextlisteners).addListener(listener); } } /** * 返回Context侦听者 * * @return BaseContextListener[] */ public List<CommandContextListener> getContextListeners() { if (contextlisteners != null) { if (contextlisteners instanceof CommandContextListeners) { return ((CommandContextListeners)contextlisteners).getListeners(); } else { return Collections.singletonList(contextlisteners); } } return Collections.emptyList(); } /** * 设置Context侦听者 * * @param listeners context侦听者 */ public void setContextListeners(List<CommandContextListener> listeners) { if (listeners == null || listeners.isEmpty()) { return; } this.contextlisteners = new CommandContextListeners(listeners); } /** * 删除Context监听者 * * @param listener Context监听者 */ public void removeContextListener(CommandContextListener listener) { if (listener == null) { return; } if (contextlisteners != null) { if (contextlisteners instanceof CommandContextListeners) { ((CommandContextListeners)contextlisteners).removeListener(listener); } else if (contextlisteners == listener) { contextlisteners = null; } } } /** * 处理BaseContext来的事件 * * @param context 上下文 * @param action 动作种类 * @return 是否结束处理 */ public boolean fireEvent(CommandContext context, int action) { if (contextlisteners != null) { return contextlisteners.handle(context, action); } return false; } }
kalodiodev/CustomersNotes
app/src/main/java/eu/kalodiodev/customersnote/utils/DialogHelper.java
/* * Copyright (c) 2017 <NAME> * * 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 eu.kalodiodev.customersnote.utils; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v7.app.AlertDialog; import eu.kalodiodev.customersnote.R; /** * Dialog Helper, contains common dialogs * * @author <NAME> */ public class DialogHelper { /** * Show Confirm Dialog * caller must implement {@link AppDialog.DialogEvents} * * @param fm Fragment Manager * @param dialogId dialog id * @param message message to show * @param positiveRID positive text resource id * @param negativeRID negative text resource id */ public static void showConfirmDialog(FragmentManager fm, int dialogId, String message, int positiveRID, int negativeRID) { // Show dialogue to get confirmation to quit editing AppDialog dialog = new AppDialog(); Bundle args = new Bundle(); args.putInt(AppDialog.DIALOG_ID, dialogId); args.putString(AppDialog.DIALOG_MESSAGE, message); args.putInt(AppDialog.DIALOG_POSITIVE_RID, positiveRID); args.putInt(AppDialog.DIALOG_NEGATIVE_RID, negativeRID); dialog.setArguments(args); dialog.show(fm, null); } /** * Show warning dialog * * @param context caller context * @param title title to be shown * @param message message to be shown */ public static void showWarningDialog(Context context, String title, String message) { AlertDialog alertDialog; alertDialog = new AlertDialog.Builder(context).create(); alertDialog.setTitle(title); alertDialog.setIcon(R.drawable.ic_warning_black_24dp); alertDialog.setMessage(message); alertDialog.setButton(-1, context.getString(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); //Show read only dialog alertDialog.show(); } }
modal/tktoolbox
tktoolbox/examples/canvas/vector_objects.py
<filename>tktoolbox/examples/canvas/vector_objects.py """ Tkinter Color Vector Objects Just the bare minimum to create re-sizable and re-usable color icons in tkinter. - <NAME> """ import tkinter as Tk import math def getregpoly(sides): """ Get points for a unit regular-polygon with n sides. """ points = [] ang = 2*math.pi / sides for i in range(sides): deg = (i+.5)*ang points.append(math.sin(deg)/2.0+.5) points.append(math.cos(deg)/2.0+.5) return points def scale(points, scale): return [x*scale for x in points] def move(points, x, y): xy = [x,y]*(len(points)//2) return [xy+coord for xy, coord in zip(xy,points)] def translate(obj, x, y, zoom): p = scale(obj.points, obj.size) p = move(p, obj.x, obj.y) p = scale(p, zoom) return move(p, x, y) def draw(obj, c, x=0 ,y=0, zoom=1): p = translate(obj, x, y, zoom) if obj.obj=='line': c.create_line( p, fill=obj.fill, width=obj.width, arrow=obj.arrow ) elif obj.obj=='rectangle': c.create_line( p, fill=obj.fill, outline=obj.outline, width=obj.width) elif obj.obj=='polygon': c.create_polygon( p, fill=obj.fill, outline=obj.outline, width=obj.width, smooth=obj.smooth ) elif obj.obj=='text': size = int(obj.size*zoom) font = (obj.font,size,obj.style) c.create_text(p, text=obj.text, font=font, fill=obj.fill) elif obj.obj=='oval': c.create_oval( p, fill=obj.fill, outline=obj.outline, width=obj.width ) elif obj.obj=='arc': c.create_arc( p, start=obj.start, extent=obj.extent, style=obj.style, fill=obj.fill, outline=obj.outline, width=obj.width ) class Shape(object): size = 1 x = y = 0 def __init__(self, **kwds): self.__dict__.update(kwds) def __call__(self, *args, **kwds): for key in self.__dict__: if key not in kwds: kwds[key] = self.__dict__[key] return self.__class__(*args, **kwds) def draw(self, c, x=0, y=0, scale=1.0): draw(self, c, x, y, scale) class Group(list): obj = 'group' def __init__(self, *args, **kwds): self[:] = args self.__dict__.update(kwds) def __call__(self, *args, **kwds): args = self[:]+list(args) for key in self.__dict__: if key not in kwds: # make copies kwds[key] = self.__dict__[key]() return self.__class__(*args, **kwds) def draw(self, c, x=0, y=0, scale=1.0): for item in self: item.draw(c, x, y, scale) for key in self.__dict__: self.__dict__[key].draw(c, x, y, scale) # base shapes. text = Shape( obj='text', text='', fill='black', width=0, font='', style='', points=[0,0] ) line = Shape( obj='line', arrow='none', fill='black', smooth='false', width=1, points=[0,0,1,0]) rectangle = Shape( obj='rectangle', fill='', outline='black', width=1, points=[0,0,1,.5]) polygon = Shape( obj='polygon', fill='grey', outline='', width=0, points=[0,0], smooth='false' ) oval = Shape( obj='oval', fill='grey', outline='', width=0, points=[0,0,1,.75] ) arc = Shape( obj='arc', fill='grey', outline='', width=0, style='arc', start='0', extent='90', points=[0,0,1,1]) # shape variations chord = arc(style='chord') pie = arc(style='pieslice') circle = oval(points=[0,0,1,1]) square = rectangle(points=[0,0,1,1]) triangle = polygon( points=getregpoly(3)) octagon = polygon( points=getregpoly(8)) # CAUTION ICON caution = Group( triangle(x=6, y=5, size=75), triangle(size=75, fill='yellow'), txt = text( text='!', x=38, y=32, size=30, font='times', style='bold') ) # ERROR ICON circlepart = chord( x=15, y=15, size=25, fill='red', start='140', extent='155' ) error = Group( octagon(x=6, y=5, size=56), octagon(size=56, fill='red'), circle(x=9, y=9, size=37, fill='white'), circlepart(), circlepart(start='320') ) # QUESTION & INFO ICONS bubbletip = polygon(points=[34,42,60,56,50,38]) question = Group( bubbletip(x=6, y=5), oval(x=6, y=5, size=60), bubbletip(fill='lightblue'), oval(size=60, fill='lightblue'), txt = text( text='?', x=31, y=22, size=28, font='times', style='bold' ) ) info = question() info.txt.text = 'i' if __name__ == '__main__': root = Tk.Tk() root.title('Resizable Shapes') c = Tk.Canvas(root) caution.draw(c,40,20,.5) error.draw(c,120,20,1) question.draw(c,210,20,2) info.draw(c,50,100) logo = caution() # get a copy logo.txt = text( text='&', fill='#00bb44', x=39, y=34, size=30 ) logo.draw(c,135,110,1.3) message = text( text="What's Your Size?", size=15, fill='white' ) Group( message( x=1, y=1, fill='grey30'), message() ).draw(c,190,235,2) line( width=3, fill='darkgrey', arrow='both' ).draw(c,20,205,336) c.pack() root.mainloop()
iplo/Chain
chrome/browser/extensions/api/management/management_api_browsertest.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/files/file_path.h" #include "base/files/scoped_temp_dir.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/extensions/api/management/management_api.h" #include "chrome/browser/extensions/api/management/management_api_constants.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/extensions/extension_host.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_test_message_listener.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_switches.h" #include "content/public/browser/notification_service.h" #include "content/public/common/url_constants.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_utils.h" #include "extensions/browser/extension_system.h" namespace keys = extension_management_api_constants; namespace util = extension_function_test_utils; namespace extensions { class ExtensionManagementApiBrowserTest : public ExtensionBrowserTest { protected: bool CrashEnabledExtension(const std::string& extension_id) { ExtensionHost* background_host = ExtensionSystem::Get(browser()->profile())-> process_manager()->GetBackgroundHostForExtension(extension_id); if (!background_host) return false; content::CrashTab(background_host->host_contents()); return true; } }; // We test this here instead of in an ExtensionApiTest because normal extensions // are not allowed to call the install function. IN_PROC_BROWSER_TEST_F(ExtensionManagementApiBrowserTest, InstallEvent) { ExtensionTestMessageListener listener1("ready", false); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("management/install_event"))); ASSERT_TRUE(listener1.WaitUntilSatisfied()); ExtensionTestMessageListener listener2("got_event", false); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("api_test/management/enabled_extension"))); ASSERT_TRUE(listener2.WaitUntilSatisfied()); } IN_PROC_BROWSER_TEST_F(ExtensionManagementApiBrowserTest, LaunchApp) { ExtensionTestMessageListener listener1("app_launched", false); ExtensionTestMessageListener listener2("got_expected_error", false); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("management/simple_extension"))); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("management/packaged_app"))); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("management/launch_app"))); ASSERT_TRUE(listener1.WaitUntilSatisfied()); ASSERT_TRUE(listener2.WaitUntilSatisfied()); } IN_PROC_BROWSER_TEST_F(ExtensionManagementApiBrowserTest, LaunchAppFromBackground) { ExtensionTestMessageListener listener1("success", false); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("management/packaged_app"))); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("management/launch_app_from_background"))); ASSERT_TRUE(listener1.WaitUntilSatisfied()); } IN_PROC_BROWSER_TEST_F(ExtensionManagementApiBrowserTest, SelfUninstall) { ExtensionTestMessageListener listener1("success", false); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("management/self_uninstall_helper"))); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("management/self_uninstall"))); ASSERT_TRUE(listener1.WaitUntilSatisfied()); } IN_PROC_BROWSER_TEST_F(ExtensionManagementApiBrowserTest, SelfUninstallNoPermissions) { ExtensionTestMessageListener listener1("success", false); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("management/self_uninstall_helper"))); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("management/self_uninstall_noperm"))); ASSERT_TRUE(listener1.WaitUntilSatisfied()); } IN_PROC_BROWSER_TEST_F(ExtensionManagementApiBrowserTest, UninstallWithConfirmDialog) { ExtensionService* service = ExtensionSystem::Get(browser()->profile())-> extension_service(); // Install an extension. const Extension* extension = InstallExtension( test_data_dir_.AppendASCII("api_test/management/enabled_extension"), 1); ASSERT_TRUE(extension); const std::string id = extension->id(); scoped_refptr<Extension> empty_extension( extension_function_test_utils::CreateEmptyExtension()); // Uninstall, then cancel via the confirm dialog. scoped_refptr<ManagementUninstallFunction> uninstall_function( new ManagementUninstallFunction()); uninstall_function->set_extension(empty_extension); uninstall_function->set_user_gesture(true); ManagementUninstallFunction::SetAutoConfirmForTest(false); EXPECT_TRUE(MatchPattern( util::RunFunctionAndReturnError( uninstall_function.get(), base::StringPrintf("[\"%s\", {\"showConfirmDialog\": true}]", id.c_str()), browser()), keys::kUninstallCanceledError)); // Make sure the extension wasn't uninstalled. EXPECT_TRUE(service->GetExtensionById(id, false) != NULL); // Uninstall, then accept via the confirm dialog. uninstall_function = new ManagementUninstallFunction(); uninstall_function->set_extension(empty_extension); ManagementUninstallFunction::SetAutoConfirmForTest(true); uninstall_function->set_user_gesture(true); util::RunFunctionAndReturnSingleResult( uninstall_function.get(), base::StringPrintf("[\"%s\", {\"showConfirmDialog\": true}]", id.c_str()), browser()); // Make sure the extension was uninstalled. EXPECT_TRUE(service->GetExtensionById(id, false) == NULL); } IN_PROC_BROWSER_TEST_F(ExtensionManagementApiBrowserTest, GetAllIncludesTerminated) { // Load an extension with a background page, so that we know it has a process // running. ExtensionTestMessageListener listener("ready", false); const Extension* extension = LoadExtension( test_data_dir_.AppendASCII("management/install_event")); ASSERT_TRUE(extension); ASSERT_TRUE(listener.WaitUntilSatisfied()); // The management API should list this extension. scoped_refptr<ManagementGetAllFunction> function = new ManagementGetAllFunction(); scoped_ptr<base::Value> result(util::RunFunctionAndReturnSingleResult( function.get(), "[]", browser())); base::ListValue* list; ASSERT_TRUE(result->GetAsList(&list)); EXPECT_EQ(1U, list->GetSize()); // And it should continue to do so even after it crashes. ASSERT_TRUE(CrashEnabledExtension(extension->id())); function = new ManagementGetAllFunction(); result.reset(util::RunFunctionAndReturnSingleResult( function.get(), "[]", browser())); ASSERT_TRUE(result->GetAsList(&list)); EXPECT_EQ(1U, list->GetSize()); } class ExtensionManagementApiEscalationTest : public ExtensionManagementApiBrowserTest { protected: // The id of the permissions escalation test extension we use. static const char kId[]; virtual void SetUpOnMainThread() OVERRIDE { EXPECT_TRUE(scoped_temp_dir_.CreateUniqueTempDir()); base::FilePath pem_path = test_data_dir_. AppendASCII("permissions_increase").AppendASCII("permissions.pem"); base::FilePath path_v1 = PackExtensionWithOptions( test_data_dir_.AppendASCII("permissions_increase").AppendASCII("v1"), scoped_temp_dir_.path().AppendASCII("permissions1.crx"), pem_path, base::FilePath()); base::FilePath path_v2 = PackExtensionWithOptions( test_data_dir_.AppendASCII("permissions_increase").AppendASCII("v2"), scoped_temp_dir_.path().AppendASCII("permissions2.crx"), pem_path, base::FilePath()); ExtensionService* service = ExtensionSystem::Get(browser()->profile())-> extension_service(); // Install low-permission version of the extension. ASSERT_TRUE(InstallExtension(path_v1, 1)); EXPECT_TRUE(service->GetExtensionById(kId, false) != NULL); // Update to a high-permission version - it should get disabled. EXPECT_FALSE(UpdateExtension(kId, path_v2, -1)); EXPECT_TRUE(service->GetExtensionById(kId, false) == NULL); EXPECT_TRUE(service->GetExtensionById(kId, true) != NULL); EXPECT_TRUE(ExtensionPrefs::Get(browser()->profile()) ->DidExtensionEscalatePermissions(kId)); } void SetEnabled(bool enabled, bool user_gesture, const std::string& expected_error) { scoped_refptr<ManagementSetEnabledFunction> function( new ManagementSetEnabledFunction); const char* enabled_string = enabled ? "true" : "false"; if (user_gesture) function->set_user_gesture(true); bool response = util::RunFunction( function.get(), base::StringPrintf("[\"%s\", %s]", kId, enabled_string), browser(), util::NONE); if (expected_error.empty()) { EXPECT_EQ(true, response); } else { EXPECT_TRUE(response == false); EXPECT_EQ(expected_error, function->GetError()); } } private: base::ScopedTempDir scoped_temp_dir_; }; const char ExtensionManagementApiEscalationTest::kId[] = "pgdpcfcocojkjfbgpiianjngphoopgmo"; IN_PROC_BROWSER_TEST_F(ExtensionManagementApiEscalationTest, DisabledReason) { scoped_refptr<ManagementGetFunction> function = new ManagementGetFunction(); scoped_ptr<base::Value> result(util::RunFunctionAndReturnSingleResult( function.get(), base::StringPrintf("[\"%s\"]", kId), browser())); ASSERT_TRUE(result.get() != NULL); ASSERT_TRUE(result->IsType(base::Value::TYPE_DICTIONARY)); base::DictionaryValue* dict = static_cast<base::DictionaryValue*>(result.get()); std::string reason; EXPECT_TRUE(dict->GetStringASCII(keys::kDisabledReasonKey, &reason)); EXPECT_EQ(reason, std::string(keys::kDisabledReasonPermissionsIncrease)); } IN_PROC_BROWSER_TEST_F(ExtensionManagementApiEscalationTest, SetEnabled) { // Expect an error about no gesture. SetEnabled(true, false, keys::kGestureNeededForEscalationError); // Expect an error that user cancelled the dialog. CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kAppsGalleryInstallAutoConfirmForTests, "cancel"); SetEnabled(true, true, keys::kUserDidNotReEnableError); // This should succeed when user accepts dialog. We must wait for the process // to connect *and* for the channel to finish initializing before trying to // crash it. (NOTIFICATION_RENDERER_PROCESS_CREATED does not wait for the // latter and can cause KillProcess to fail on Windows.) content::WindowedNotificationObserver observer( chrome::NOTIFICATION_EXTENSION_HOST_CREATED, content::NotificationService::AllSources()); CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kAppsGalleryInstallAutoConfirmForTests, "accept"); SetEnabled(true, true, std::string()); observer.Wait(); // Crash the extension. Mock a reload by disabling and then enabling. The // extension should be reloaded and enabled. ASSERT_TRUE(CrashEnabledExtension(kId)); SetEnabled(false, true, std::string()); SetEnabled(true, true, std::string()); const Extension* extension = ExtensionSystem::Get(browser()->profile()) ->extension_service()->GetExtensionById(kId, false); EXPECT_TRUE(extension); } } // namespace extensions
Adilla/Blasmatch
external/pet/tests/assume3.c
<gh_stars>1-10 int f(int k) { int a; #pragma scop __pencil_assume(k >= 0); a = k % 16; #pragma endscop return a; }
lorcannolan/MySwing
app/src/main/java/ie/dit/myswing/profile/SocietyListAdapter.java
package ie.dit.myswing.profile; import android.content.Context; import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.ArrayList; import ie.dit.myswing.R; import ie.dit.myswing.java_classes.Society; /* In creating list view for courses, the following tutorial was followed: - https://www.youtube.com/watch?v=E6vE8fqQPTE This tutorial was then adapted to fit data from firebase database */ public class SocietyListAdapter extends ArrayAdapter<Society> { private Context mContext; private int mResourse; public SocietyListAdapter(Context context, int resource, ArrayList<Society> objects) { super(context, resource, objects); mContext = context; mResourse = resource; } @NonNull @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = LayoutInflater.from(mContext); convertView = inflater.inflate(mResourse, parent, false); TextView societyName = (TextView)convertView.findViewById(R.id.society_name); societyName.setText(getItem(position).getName()); TextView societyOrg = (TextView)convertView.findViewById(R.id.organization_name); societyOrg.setText(getItem(position).getOrganization()); TextView createdBy = (TextView)convertView.findViewById(R.id.created_by_user_name); createdBy.setText(getItem(position).getCreatedBy()); return convertView; } }
comprakt/comprakt-fuzz-tests
output/12394db015434e6484dc4397e91b8710.java
class bPjVp { } class zOcUtm { public int[][] I1e9tUkXTh8; public boolean kTc (FEyqg2mUW8wxmI qgZPNqz) { RAMNOk2nr ulMNznP8JaXiEK; boolean EK7O5p = !-!--!!false.n_c2fNDqN = -false.T7(); void[][] N_5dWhZmOx = QdVZM1z()[ -new Hkd3QCW1aZzCM().FWpg254G1E]; ; UV[][][][] iv9sXgBo = ---!new GR9sHBlJo().iToFAmmnNGd() = T8CBSaroh()[ new int[ B().MeG].IHJzzKVqVJva]; while ( ---97752.xXIpaoxhq()) -( KXBWAmOI0Xwri()[ !new void[ -HBRAV.V()].lo]).y7ErBEHUj(); return --fo1K6mQXK.TmaITzlNf(); while ( this[ this.rN31r()]) return; boolean pLl3kdEf = 07389306.wb; while ( --!false.Fk) while ( ( --null[ true[ !( !_SGsbfqvTOx_.QkH()).Fk5Ojo4To8o]]).eVJMFy0kzSj()) if ( new YlIkjTyG3S().Dp85qH) true[ !-this.qoge()]; void i8uMN5BukctGz; int sABpJGwD = !!!!9808626[ --true.cJ7zPHqCgEvlQ]; ; void jicGiPau; new boolean[ ( true.NKji81xEJ460C())[ -743.qCIW0PG01dvq9]].Al0M(); aIMDj331gf0MxS[][][] k5ki50A; boolean[][] NQ3dC_AS3L9j = null.MWmFvU0QoPVH; void[][][][] T; void agtf; while ( -null.sexMDEzz13HwK()) return; } public AFuib[][][][][] A () { void[][] cwSNsTccQ4 = !!!null.mFzsdYv() = null.borKJ32; ; int[] UKkRRmbq_ek = -new cRgzIbw[ !!( new int[ !new Xa[ !-new sCtOw7b().KRrQtkRJ0Ih()].vI()].XinD5i3E7w1gO)[ !( !null.s).n0qmN]][ 7.ecmEXGhcWFTIuM()] = !-dbeZRNnqOQgD()[ !false._()]; boolean b4Hp78wW; if ( --new ha()[ ( !true[ true.TnDwJjv()]).oEnQPV0xuFx]) new boolean[ -true.veNHzOsZq2()].yY; int[] bbQtkhn5; if ( uhE00().eEF_OM_AmtEUS) ; boolean[] tud3lrzH; void[] VQG3LyZycIhE = 864183004[ -WPIOwSC1ugJ.wyX]; return !-new x_9iJQxSRzl().DZsQle(); void AkG0TEQ; boolean[][][] NJh = -!!221356337.zg = -!5323.ka42Fm(); ; if ( ( -this.ihVPyTK)[ !null[ !new T3qOdCODAzf2[ !true[ new bUQVn2WAyS3G().H1rOn()]].NaGrjh7DV5Mvhm()]]) { while ( !!new void[ true.LPvde][ new n1AxM8CnSL().f0]) return; }else if ( true.E()) return; boolean I3LXkEDutarKTM; !this[ -true[ E.o]]; } } class ctF5r8s26Re { } class iufOlXq { public int fCxf7MVzEaX () throws K0nsO8bsqWbQ2 { void[][] xsaeTSRVq0; } } class He { public void[] LrXUV (int IUoVZjk, boolean[] Up, boolean r1c2b, fytg23[] G4lGZ2FxXvAGY, int PbkESJwwsi5B, void wvdcYeO) { void UP8ZNe = null.kpOVBy; boolean I4SHDRWX2W6; } public void[][] F_Lpkvf19; public boolean _tgc (boolean IAmjcgXJ2iXU, void[][] mJejXSso9qHwKI) { return this.d9dSdYOxhW; while ( -!new wziOgYkPQH()[ false.dD1aF0ocL]) while ( 334.zXnXDJ0()) { return; } ; } public boolean[][][][] gd9AG4 () throws KEu { int[] cTVfIBn; int[][] q3jMDKhIN = ---!false[ true.b8i] = -this.WZxWUnumasUd(); while ( new kw6C().p()) if ( true._4) return; int _LeLTW; -new MHiuJS1EmKU7u().NDB4Jh1An7R3rT(); while ( null[ 039840.b()]) ; } public static void sQKvXJOKEDKEw (String[] DisG) { void nCqxU07; void[][][] THJlL; boolean[][] E_FlFq = J1().KnfPHE34 = 999.cj1VOsy9; if ( new nmfu0sxfkZ[ new boolean[ this.On9fVf()][ !false[ -true.leSxJrPC()]]].iqOGVJwMY6) return; int[] iB6; } public boolean[] KfC8Y; public int[][][][] wTshLUnPaGg (void[] gZI5, az6PBcg6 gTlzQa, void UTlu3aetO, s G7ZjeVt, int[][][] z3eS, boolean[] oty_Zhq, boolean X0eHKQlCgI) throws WE2IZD { void RDpax0fyl_EE8; if ( true.z) { boolean[][][] cPR0TU; } int Xg2bCmK5pz; ; return !-true.d(); if ( MaKkS7.E4S_JEIVYqLCpJ) ;else while ( !!n2ThkvZJMdmn4G[ !( !--!true.XLu7TXG())[ !---261539110.ash8q2J()]]) return; !!!null.bZvrVc(); while ( cuR8c().KrPEnNeFk5cPI9) ; boolean[][] mi_a89iqyU = qClzHbYNuKuWB().a4; return bfVqhpa14.wWgfl47d8tD; return 56671[ !null[ LvUujCA()[ new b_QU5()[ !false.i39hrYy3UIfOfQ()]]]]; bAiCp lC8HGAJHsj; boolean iN = Uvww6qgWNRDQf.jqI8 = Q84PPCgw()[ -OMAYBaDg.t4fN0]; p2N4UqT[] wgr_K; if ( --T57J_.ij) if ( -( TlbuB0Lcbi().VsHZjLhiZ()).ohd12_JPAH()) if ( this[ !true.E43ha64c2Wyoj()]) new AVv5YLvul2PSB()[ !----SLz()[ -( false.tDPYcsPn).KjoOVKdP]];else ; void[] Wc = !!-1801771.RCIjgk7dEx = !-!!-new boolean[ --!gsW().g0Vx].rPDItU06pA50tU(); e9tCVc8wRAL knxIStynR = ( !-this.DwTdKd44()).KZpEOVxby8NRes(); } public static void lWAAyS (String[] ociacg) throws C { return this[ -new Me8Tp().F0Sybt0fFr28]; BC[][][][][] RxC4PD4VpWdnLA; { return; ; while ( !false[ --!Uixux2U().Kh2xaqFzekra()]) !!!8.NpIVVSnAiBCkW(); ; if ( --false.M4fHw8zT()) { while ( 8760[ --( --new Syt4AiVCRhN2()[ true.u0AafDEpujRe])[ new wkThk4()[ this.rW_HGBRPyD4]]]) return; } ; Tsxu89Q8b[] aVEgSdD_i8; ; int[][] UE5DXDg; if ( T2OoaZA.Bg4My0trr()) if ( new jgBX4H()[ !-true.pNpq()]) !new int[ new ZpiUgWzM60JY4[ new eS3g8fx3o()[ !--hYr7ZFJ9SdWA_[ new bK64YVF().OqWVspAe8MkQ()]]].CA()][ null[ !--z().gn9()]]; ; rRk J7; int YBDzzex; while ( ( true.pksH).O()) !new void[ !true.T()].DgWUo(); while ( -03873271[ 0015.tuEKljT]) { return; } int[][] E5tsZ1gP5ZL; return; boolean[][][] HN4aD_; ; ; } aCxpJ[][] PBvzUZov; int[] scdH; while ( 5078.MGtSW) ( i[ !-false.QCJtCW3xGXc]).rp(); ; LcBfEFSc MU; while ( !--null.zQdHV()) ; boolean[][][][] W2yqvcDf; while ( false.hk0IXJuO) while ( !!--Bl9T77vwYPg()[ --true[ this.iXqv]]) if ( new LBSj7Bpzy().sbbDm) --47370.t16_; -!null[ CjtU7TAo.cW3IFCo()]; if ( !---new boolean[ this.Q4M7jYaaDo5D].svUBD) true[ !!( 3865275.HD5Yo9JUSrCa).lC3w]; if ( false.Fj_ysku9P) if ( --!!--g8Isn8E().enqBujuTEG()) if ( kRntdK18CHduK().G_pKmPu2) -new VeZk5ujDpIT().qHSBYh(); boolean Bwk6s9EmO02qU = -this.qmBO4RtwLyOYj4(); int jLdhDmMWj = 6237939[ new int[ PYg7Uei086vT().v9ndOgXBAEXl8].tO0UoDT()]; int[][][] Ygt = new int[ false.XEgfp_IWt].cMuWmt9() = false[ !!7947460[ new mC()[ true[ new zteFSK()[ !!0142.o_RtZ4F]]]]]; boolean[][] skVEZ = !!o0SS1[ !-!-null.MzRedMp67bE5()]; } public int x_qunRMH (Pp95GFWHXfqM6[] BBWQ0X6vtpiq, boolean[] Nc, int b, SaoAx6eq[][][] o2KhIkAE66g) { while ( ( v[ false[ --null[ false.mZVGHVHoQ9B()]]]).nd3()) if ( !-this.yMZfgB) ; if ( _KRDe2wp0aavel().TwHvart) !false[ !-775.xma9jfehaF()];else while ( 2969.G4zeG) ; TjfvSQY Iaaw = is.dKCYPnmv9(); } } class DzRzn { public im761 _u0p2Q; public int JbWcFfR5O3PyM () throws I { rLt[] fD = !new RI().xtlk6(); Vzp8cIQaMPF[][] MYxskNhPYns = ( ( true[ --!!Hr9Gy.WhbANCpi()])[ -true[ !aye.pJ7HCTo]]).yxOSwsIO = true.CvB4D2yiRiB(); } public static void _L06L (String[] M) throws S7iFYpuXp8 { void cgXa = --636058[ !-!-!new tWH3cO().UxI75T]; int ooya = !!-this.nwoBoAI() = !ujx56tEGQ()[ qbTsCrVM16A()[ !!new zKC11CM8DQPLE0[ -!!-!-!new int[ null.Z1()][ -null.yvPswLto_c]][ --!null[ ( !( false[ -new L4YLF().qRx8j()]).Gz).mpSwbg()]]]]; int[] AK = null.wmNWFkuCXFsw6 = !---F.y95aWLL1M; boolean[][] DPQytfgUhf7GSD = -!!----true[ false[ !!---!true.AwNThrbzWM()]] = -!eHmDSyyn9fiFh.CQnH5sR(); return new Zokf().d0XtZnA11; ; T8qIpDbhxjJp[][][] eC2Ik; boolean[] HFIF; if ( -Jm().hcwinor2) while ( yCycN2D.T2w1) { boolean[] _Rjz; }else if ( weUtrrer().qU()) { { boolean Z5gSgqlgoD; } } bQCj81Mjgis21 LbcqM_oghm7 = this.jbJ99J; void CO_8wYR; int dVk1KUcsQWMu = EaTN7DvOPc[ 7172803[ -_xLI92xon[ !!Rvt7GpshluO()[ rK2m().z]]]] = new void[ --AbDTybQ[ new int[ new void[ 992341.Rj2_GDc].Z2JWt()].TlyxwQVw]].tlKOp6poiUprX(); return !!!--pXb1fSpuHr()[ !true[ -this[ this.Yu()]]]; !-Ne()[ -new boolean[ null.Rp1U7KamZnP_n].I3lo4Yr5ZtS()]; { SFtYckhK44pCm4 hnuF2; return; return; tG6id3GNeKd98g[][] eeF4_Mu; void KVm4BmNwsz; while ( !LjAR8x().dT_4amIl52O1) return; } } public int[] Q2O3iS; public void zJugcX7 () throws ovwvXQd6uZMoU { return ( new WtwWL4ejWuQW[ -!this.ibs].sSvZjmZOd()).uxiGU; { boolean[][][][] uVf5sF; ; ; O3Do2j11BE[] S6; UX2xlqeDKqu09 G1Zq1uSp1C8; boolean[][] VpupAPr; void[][] sAhz95U_; if ( null.BqkHV6PD_) ; int[][] dpnpSIm6wXU; boolean G6GZvi4Ksz; yaEp OYgK_kalLnm; -A.FmN7; boolean[][][] kRGrQLH; xVkcD8Y().nfNQuglJRL(); return; int[][][][][][] glsiecQ1Sn; } void RXLOU3R0MUMgf; ; while ( fkUH[ -!false.EgGEWI2fyroBI]) { while ( --!!new IcbmJX7s_c().wdVboE()) ; } int jjeVDKcjk4N = !this.tdT; boolean[][] H8LaGx9bM9Gsg = true.Sbnuk() = null[ dGCPaAW9YWx[ false.T74AAK4]]; 31.FVhzpMJiXC(); ----!null[ !false.FxNZT()]; { ( !-new RMvxrj()[ null[ this.r8FXP1Ga1gLwv7]])[ new BSH2F5bbA6EYS().q]; { boolean[] cEIxCU7Z; } { int y30jyR1cbcrJy; } while ( !!this[ !!null[ !---254098.Kf3Iojk()]]) ; boolean[][] iqqBPqo; { { xyXOg98 Phcx; } } return; void d8vM8Syb5Mw; if ( ( !-!--!null[ !Xivjs()[ !-!new GPm5M0hwItmaR().dSzdN_bn()]]).r1()) ; { { boolean M; } } int[][] F2uuVpnpM; } -!782387872.B1aAiG04(); { if ( !!DZ7_L9Zs7Gd[ new W[ -new int[ -new void[ !true[ ( !LAv().RhSZiiq1HPR()).FDTt1FzS()]].Uj8012GLLHVxo()].zqS02ro8EK][ -!!--!!null[ 3163.sBO5dlM()]]]) { TUmn[] N27Wmn; } ; if ( 140987.fUv7xR8()) return; { if ( false[ !new hmDth()[ new boolean[ !-d3J()[ !-true.GdnTB39b]].TXtqoJxNpm()]]) null.AxiSCpis8P6BCS; } } if ( ( -!---!!serm().HQY6NZKBpFTH).Y_M) while ( this.L()) ; boolean ZmiJzT; } public static void JV (String[] YV09cx) throws bL07CCmHBev { int D19nMlR5r; null.bYXXb; -4[ new boolean[ new isC_tczoFYO().xKuZ].iR6tbq()]; int uon_Pkj; if ( false[ !--this.MG()]) this[ !null.K0f3KyZgc2IAN];else return; if ( !!!!HmwSPsYUzix()[ !FOBNGYE8x.LJxLG9hG99S]) while ( !2123[ -null[ !-!!false.okb7dw0K_yf5]]) return; boolean[][] CeLOF50MkG; while ( new I7iQYnQH1ZHzd().Hfsr9JKGnO6()) 137.yhWJPjpcz5h9Qx(); int J12k = new FY().AZje6ZDRizoDo; while ( -!false.abLRwAlwc()) new yntucaaqv8b().TO2rNYtsBofR(); void[][] m = this.cdOk() = false.NJ6Hc6V; aXxqgUJshJgf[] CZuf3WG = !!!true.jJZwwaR0PA_; } public int yrPux57EiJ () { ; int COhY2ygS13ym = !new fAS[ !new void[ new AZpzv()[ new ZQBWnFWD()[ !!-this[ 535.ug0HpZ()]]]].MeD][ ( -!this.EOrrekIAUWmPEf()).Ner4]; return; int vuyzGNQyJT; while ( !-this[ !-null.lPsdo7Cze()]) { void pBkH6EORvfMxMj; } int LfDng5B1k = -XKKPloMCAISHIs.J5h4xHqka_5Eys; if ( -true.S1y3D()) { ; } if ( !null.AD7wCVJqFnzy) if ( -true.hM6wmSWcRANGQ()) --false.Oj(); return; while ( true.cE) if ( -!new Aco1C7YCMWdo[ -58947758[ !IZg()[ true.ckLZA5Oyv]]][ -( !true[ true[ !( !qJEr5GIub5BH[ -!this.SAkFG]).K]])[ !_GWc().mwbleiusN7]]) while ( true[ !-!!P4xGG.HZxaSE1UY]) ; return; while ( !!false.KnC) return; iqIklUEoVRchEn u1R = true[ ( -new uohhve().cTTBuHTYpL).DJ1js_vTWMU3IH]; return; while ( FY_RX()[ !-!K6O().pp5UepUTt3slY()]) { null[ null[ !new pA().Ct]]; } } } class GzcfWbNai7J { public void P5 (il[][][][] iS96_V37j7heKs, boolean[] LQAFvX3Zq, boolean CPO6Va5Eom, void[][][] e1, void QUTk, int aCSFiQU) { return; !!-!-!-!233.iXKqo4NFCPTN; true.nw9EEf(); { { ; } ; while ( this[ new void[ false[ !null[ this.F3Y80Y2QBY()]]].KPBBe8cJ3YuOk()]) { return; } return; { ; } void[] jLQowofML3W; int[][] PdI8IgjFmb; boolean vtU9k; } boolean Pc_ = !-null[ true.A()] = --caVk0jYoOj().RgGU1pGsLjxyM; ; while ( 83955.D1COP0h2B()) while ( true.AcgCi90LDhSXHR()) return; void chMbI2s9GN6T = mtgXXlT3F53m[ !!new eYdgEd()[ mVx6XnF45cy6Rm[ PyyVrqsRUg8().Ia7f4i06]]]; } public static void Eat (String[] F9GL1WCwEp) throws hx5ip6Z5Rj1iU { P[] TLwCLi2zsA = ( true.AH1Gc())[ XzIolUSJFIqNw[ HRqoXpBAZ74aU7.V]]; while ( !true[ !new boolean[ true.UgS][ new void[ new int[ !new Pjc().AAWmPoAxvU].fQQGvsED_R3Z].q5cFQzO6IAg()]]) new IsERiLn().Hz(); this[ !-!!-null[ -!false.ESB()]]; return; while ( ( !false.uxZTviRl2c())[ 719078._E]) ; void iIORNEf13UQl = !( -!!false.KWZno11AVRi())._CFQ() = true[ new Xu8f().BN]; boolean i; return !new G9sKIqW_9f[ !!null.CqwNmuSGNf()].zmxESXIF; if ( !-!!-227[ !-wJ7Tum.e()]) while ( -!null.YcIGsw74Y2Tx9()) return;else if ( !-!0.FqyB7HGpBcJw()) while ( false.C) while ( ( new hioF_3().k1sExAIi3()).DBWh0jiRd) ; int Ac8jthQLVwX; while ( new boolean[ -new y50().bo9piXKAVt78JL()].lhWbmLGzXnm()) if ( !!null[ true.FQU7hAvn97AlI()]) { int[] vdp; } return; -!-new F[ !!!!!new y_19CxX().XpjXO99b].m_(); new void[ -( new _5LaQPV0UlFlM().xPeqFJTqBAHvE_()).G()].TfpaIc74H217HN; } public R8JXC8[] ea51W9 (int[][] ULi60B9Fl, int[] hm4KDxhJLy90, boolean[] bfIi9pH, void[][][][] cuCrcqRaWDqC, int[][][] P0M2, int[] mOH, zcFJkO zGgE_) throws ehVrhFDTCmmgw { int O077AAq6 = !328734.j01Os20N9(); j[] U7ez = 875718.F; { return; boolean[] JkUiiK9s; V UP; int w5OMcUVTU4; while ( !!--true.tRPZFcTF0z) if ( -!-( --( 07[ hzOrjeGoRM.M_3K8vad1QtoxM()]).ZsUjjYheuM3Ew2).BQ_()) while ( ( ZC.ozT6EzN0B).cxzaLb4Ncbi) SAyVspB6nus5i()[ !s1hvQHyALAgG.uJTB3gGKf]; oDzckOnu85N PvuiOlvj4vfFl; void AmjscFK2; boolean[][] e0pXmne; boolean iVoauN41yQOW; boolean[] P; } } public static void tc (String[] Q) { void[] s = new xW3wVcL53vLf().TDE; InC6NT KuV_B3WizlrP = oeLwN.J() = null.HTo_LzhQwQP; int[] VWg1b5; if ( new Lt7h8a().H2TZnWTskn()) if ( true.NnG6grbmR0oIV_) new int[ !!true._sSgDKQt].fU1RK0lVjKqQ; -new int[ !-null.GU9hp][ new NjRuUiIy3rRBHF().mZvtm]; UkXutStSg[] l1IpZ = !( !-new m2WFIot9XPQO8[ -21309201[ !!!new L612Z()[ 2848181.zA5KgmSfHR()]]][ W65()[ this.S9x()]]).XnITlcG; boolean[] BLSsoq; int[][] rdjprftOX; void[] k15BuAnFfCrb = true[ new boolean[ !true.GDlkRPHl9rE()].JRZT2HF0FeFDPt()] = new fdcP_aFi[ -!!( 1.n2dapplw()).WwckC][ new void[ null.YoqCIVMO6C].nAuTFjCsRi]; } public static void zsCTbfWa4Pd (String[] pDi6jCm9aNTaO) { int _YSsMcuGck; int[] nUVL = -this[ new HwP_()[ !this.YqR()]]; if ( -null.SyhYx8RiSL2jPL) kK0mNu4lijc()[ null.RPJ4s()]; if ( !-!!-!!!-false.pEezBgdBy6eUCo()) ; { boolean[] a; int P19eFlrjnbKh; new boolean[ new O().OdvT6lbd_BZI7F].LPCBOSXD5Gxdwm(); void[] _fkM7ys; if ( new h9JNJ9j5bFAMH().I8mPzr()) EEMcd0S().w(); ; return; void[] _; !true[ -( -!( !true.O3iLSL)[ null.hWiG1HxWWq8]).PY26a4_jvazktk]; int LosfZMvzJEi; int YTK3AhQZd; boolean[][] QrS4n0C; if ( -M()[ new dzs8g9jCLpgJAP()[ ( new i2DyG0wyOXHq95()[ new boolean[ !-new int[ --( !09.PcYA).ZLIy][ true.J6da6foY()]][ false.uof0]])[ n6z().HxjUAjR_iRo()]]]) { false.yOio(); } } return; void[][][] BIqA3NJ313QEF = ( new lE[ true[ !-this[ !--true.L7zB_7Iw()]]].l_KcBS8Ta).Zmahy = false[ !d1T().d0]; void ct; { ; SD47sXD6g1[][][][] ZE6ri; while ( 868682.av()) -false.E; void[] geFv; void kw9Pa; boolean MG1m; boolean x; void[][] jEAh2tLsa; if ( !!!!-TVjR_aHM().M1t1j) ; return; void[] oKQ5RBu28i; if ( KMq2RUP.zu50) while ( new oyyOXkreL().Hmh9) while ( -kyRopWh()[ -!-new Sk_YBikWWXT()[ -!true.n20r43NmVeZHi]]) return; { void[][] o_xwiJ; } boolean XeySsAWqkz3d; if ( -new void[ 3.VZwJ5mk83Fka_y()].PTjIgQqvx) if ( --( ( kuicnIwLv_6yHl().PjzOIEDarAU0U1)[ new FrgBgl()[ true[ 4225.EEuBpk]]]).llWhIBKe0h()) new DnwZ()[ this.gLivn]; SyBhHJ[] C; void[] UOC92M; IouNqvQzu_v6k[] dwS; } } public boolean[] dfTvl9V778aHls (int WphVj, boolean[][][] K4R, MAGklGRHVSA[] Zz3wuJ0PuPv, int ASg39Kqwpc, void[] ggeelZ, n9VgvtsLU[] z2d8q, int ilb8xAuyh4vA) throws R9bLtER { int[] zk8lZ; ; while ( --false.Bsj62zjHbl()) while ( new boolean[ -this.djHSpKs5oqJ4bE].oTXMEkrnBwRq) null[ new void[ GTt8v6bwLUq[ 291734956[ false[ -true[ new uMoGivp().J3JklA49]]]]][ -!this.Rl]]; !true[ -!80989047.ltI7K9LSKtw]; void[][] FXHdz; int _qTYzfVsxIpZx; { boolean[][][] e2AqtUdD; return; OgL4Mu[][] eaabaPL; eF0BzhL1e[] U5kw51rP5eO; } boolean[][][][] HGs; return !!-rFv0BC1bjQIfg[ --tgV9o1IK6bBN.eJiNnNlhlSw]; while ( new h6dgiGCXnC().oQ) while ( -new HbuuFtm_eE[ 05746.s].IOyunfOeQK85b()) if ( false.yVc9uOnrAWpE) return; { boolean X_OHxE6lIL; ; } return; } public Zv_oP PSUQOPLNVD () throws NVo4 { if ( ( tHcK51pqSYcu8[ !!29.I()]).zEmwn()) return;else return; boolean[] K9E5ReFe8xf; } public int[] NtbIt_tS0CTqJZ (TrujVq81rxmXw Q) throws g6DUB4BzT { !!new t()[ -this.yyeO6yfMifaH()]; !62.tmo(); void[][][][][] eAkGKekWxX6 = true.se_iUoPNVDzMI; ; boolean dKLVkRw = -umj2u0T9n().ZEC_W4M1(); { return; return; if ( new XQCF5Fe[ !false.MrjA()].kIMKNB3LXCZ) while ( new FyQmU1r[ !this[ true[ !true.EjvLrI6wZnVXY5]]][ !---true.O_fO3EWf()]) return; } int CfmV; { { boolean[] o54; } boolean[] bqq5; int[][][] JWpNt6j5G; } boolean[][] TYA3P = 138885.J96mz6YLHDjGK4() = 45241313.Q7ZUcU9a0cB2Af(); boolean[][][][] QYZtDM5Ia = LZ69jXZkYn1Jz().ROKSUdTUWgBRR; { { void[] x5dTjYkuYQLk; } boolean[] Mi2FOo4suLg6; void BdubT; int[][] tjrAkM6Gw0f0z_; return; return; boolean hWFS; int[] RQ; if ( !-( false[ RSNzWH.Havl2Y()])[ true[ this[ -( true[ enBjyXR.Y8O9Q3BTO2()]).Ed03h_]]]) { -6034052.B; } void[][] U; { -true.mjJaBUdX(); } } } } class EHfRwNHk2CT { } class lgsGcxQ5R { } class LRW33uRWgv { }
bittorrent/okui
include/okui/FileTexture.h
/** * Copyright 2017 BitTorrent 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. */ #pragma once #include <okui/config.h> #include <okui/TextureInterface.h> namespace okui { class FileTexture : public TextureInterface { public: enum class Type { kUnknown, kPNG, kJPEG }; FileTexture() = default; explicit FileTexture(std::string name) : _name{std::move(name)} {} explicit FileTexture(std::shared_ptr<const std::string> data, std::string name = "") { setData(std::move(data), std::move(name)); } virtual ~FileTexture(); void setName(std::string name) { _name = std::move(name); } void setData(std::shared_ptr<const std::string> data, std::string name = ""); const std::string& name() const { return _name; } Type type() const { return _type; } virtual bool hasMetadata() const override { return _type != Type::kUnknown; } virtual int width() const override { return _width; } virtual int height() const override { return _height; } /** * returns success */ bool decompress(); virtual void load() override; virtual GLuint id() const override { return _id; } virtual int allocatedWidth() const override { return _allocatedWidth; } virtual int allocatedHeight() const override { return _allocatedHeight; } private: struct TextureType { GLenum format; GLenum type; }; bool _readPNGMetadata(); bool _loadPNG(); bool _readJPEGMetadata(); bool _loadJPEG(); std::string _name; std::shared_ptr<const std::string> _data; // typically a reference into the application cache std::vector<uint8_t> _decompressedData; Type _type = Type::kUnknown; int _width = 0; int _height = 0; int _allocatedWidth = 0; int _allocatedHeight = 0; TextureType _textureType; GLuint _id = 0; }; } // namespace okui
OshadaViraj/SpringDAOGeneric
core-service/src/main/java/br/com/hhc/sample/fullstackspringhibernate/core/service/impl/InstructorsServiceImpl.java
package br.com.hhc.sample.fullstackspringhibernate.core.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import br.com.hhc.sample.fullstackspringhibernate.core.service.InstructorsService; import br.com.hhc.sample.fullstackspringhibernate.database.data.dao.InstructorsDAO; import br.com.hhc.sample.fullstackspringhibernate.database.data.domain.Instructor; @Service @Transactional public class InstructorsServiceImpl implements InstructorsService { @Autowired private InstructorsDAO instructorsDAO; public List<Instructor> getAll() { return instructorsDAO.findAll(); } }
tz70s/captain
captain-framework/src/multi-jvm/scala/captain/spec/FlatMultiNodeSpec.scala
<reponame>tz70s/captain package captain.spec import akka.remote.testkit.MultiNodeSpecCallbacks import org.scalatest.{BeforeAndAfterAll, FlatSpecLike, Matchers} /** Mixin test helpers with multi-node test functionalities */ trait FlatMultiNodeSpec extends MultiNodeSpecCallbacks with FlatSpecLike with Matchers with BeforeAndAfterAll { override def beforeAll(): Unit = { super.beforeAll() multiNodeSpecBeforeAll() } override def afterAll(): Unit = { multiNodeSpecAfterAll() super.afterAll() } }
syin2/openthread
third_party/silabs/gecko_sdk_suite/v1.0/platform/bootloader/plugin/storage/internal_flash/btl_storage_internal_flash.c
<reponame>syin2/openthread<gh_stars>1-10 /***************************************************************************//** * @file btl_storage_internal_flash.c * @brief Internal flash storage plugin for Silicon Labs Bootloader. * @author Silicon Labs * @version 1.0.0 ******************************************************************************* * @section License * <b>Copyright 2016 Silicon Laboratories, Inc. http://www.silabs.com</b> ******************************************************************************* * * This file is licensed under the Silabs License Agreement. See the file * "Silabs_License_Agreement.txt" for details. Before using this software for * any purpose, you must agree to the terms of that agreement. * ******************************************************************************/ #include "config/btl_config.h" #include "core/flash/btl_internal_flash.h" #include "plugin/storage/btl_storage.h" #include "plugin/storage/internal_flash/btl_storage_internal_flash.h" #include "plugin/debug/btl_debug.h" #include "core/btl_util.h" MISRAC_DISABLE #include "em_device.h" MISRAC_ENABLE #include <string.h> // ----------------------------------------------------------------------------- // Globals const BootloaderStorageLayout_t storageLayout = { INTERNAL_FLASH, BTL_PLUGIN_STORAGE_NUM_SLOTS, BTL_PLUGIN_STORAGE_SLOTS }; // ----------------------------------------------------------------------------- // Statics static const BootloaderStorageImplementationInformation_t deviceInfo = { BOOTLOADER_STORAGE_IMPL_INFO_VERSION, (BOOTLOADER_STORAGE_IMPL_CAPABILITY_ERASE_SUPPORTED | BOOTLOADER_STORAGE_IMPL_CAPABILITY_PAGE_ERASE_REQUIRED), 40, // Datasheet EFR32MG1: max 40 ms for page erase 40, // Datasheet EFR32MG1: max 40 ms for mass erase FLASH_PAGE_SIZE, FLASH_SIZE, "EFR32", 2 }; // ----------------------------------------------------------------------------- // Functions // -------------------------------- // Internal Functions const BootloaderStorageImplementationInformation_t * getDeviceInfo(void) { return &deviceInfo; } static bool verifyAddressRange(uint32_t address, uint32_t length) { // Flash starts at 0, and is FLASH_SIZE large if ((address + length) <= FLASH_SIZE) { return true; } else { return false; } } static bool verifyErased(uint32_t address, uint32_t length) { for (uint32_t i = 0; i < length; i+=4) { if (*(uint32_t *)(address + i) != 0xFFFFFFFF) { return false; } } return true; } // -------------------------------- // API Functions int32_t storage_init(void) { return BOOTLOADER_OK; } bool storage_isBusy(void) { return MSC->STATUS & MSC_STATUS_BUSY; } int32_t storage_readRaw(uint32_t address, uint8_t *data, size_t length) { // Ensure address is is within flash if (!verifyAddressRange(address, length)) { return BOOTLOADER_ERROR_STORAGE_INVALID_ADDRESS; } memcpy(data, (void *)address, length); return BOOTLOADER_OK; } int32_t storage_writeRaw(uint32_t address, uint8_t *data, size_t numBytes) { // Ensure address is is within chip if (!verifyAddressRange(address, numBytes)) { return BOOTLOADER_ERROR_STORAGE_INVALID_ADDRESS; } // Ensure space is empty if (!verifyErased(address, numBytes)) { return BOOTLOADER_ERROR_STORAGE_NEEDS_ERASE; } if (flash_writeBuffer(address, data, numBytes)) { return BOOTLOADER_OK; } else { // TODO: Better return code return BOOTLOADER_ERROR_STORAGE_INVALID_ADDRESS; } } int32_t storage_eraseRaw(uint32_t address, size_t totalLength) { // Ensure erase covers an integer number of pages if (totalLength % FLASH_PAGE_SIZE) { return BOOTLOADER_ERROR_STORAGE_NEEDS_ALIGN; } // Ensure erase is page aligned if (address % FLASH_PAGE_SIZE) { return BOOTLOADER_ERROR_STORAGE_NEEDS_ALIGN; } // Ensure address is is within flash if (!verifyAddressRange(address, totalLength)) { return BOOTLOADER_ERROR_STORAGE_INVALID_ADDRESS; } bool retval = false; do { retval = flash_erasePage(address); address += FLASH_PAGE_SIZE; totalLength -= FLASH_PAGE_SIZE; } while (totalLength > 0 && retval); if (retval) { return BOOTLOADER_OK; } else { // TODO: Better return code? return BOOTLOADER_ERROR_STORAGE_INVALID_ADDRESS; } } int32_t storage_shutdown(void) { return BOOTLOADER_OK; }
Canner/coren
server/build.js
<filename>server/build.js import ora from 'ora'; import logSymbols from 'log-symbols'; import webpack from './webpack'; import loadCorenConfig from './load-coren-config'; import {color} from './utils'; const {error} = color; const runWebpack = (compiler, msg) => { return () => { const spinner = ora(msg).start(); return new Promise((resolve, reject) => { compiler.run((err, stats) => { if (err) { return reject(err); } const jsonStats = stats.toJson(); if (jsonStats.errors.length > 0) { const error = new Error(jsonStats.errors[0]); error.errors = jsonStats.errors; error.warnings = jsonStats.warnings; return reject(error); } spinner.stopAndPersist({ symbol: logSymbols.success, text: msg }); resolve(jsonStats); }); }); }; }; export default function build({dir, env, clientWebpackPath}) { const dev = env !== 'production'; const config = loadCorenConfig(dir); const {clientCompiler, serverCompiler} = webpack({dir, corenConfig: config, dev, clientWebpackPath}); const runServerWebpack = runWebpack(serverCompiler, 'Building server side webpack'); return runServerWebpack() .then(() => { if (!dev) { return runWebpack(clientCompiler, 'Building client side webpack')(); } }) .catch(err => { throw new Error(error(err)); }); }
nextworks-it/5g-catalogue
5gcatalogue-app/src/main/java/it/nextworks/nfvmano/catalogue/plugins/siteInventory/model/Site.java
<reponame>nextworks-it/5g-catalogue package it.nextworks.nfvmano.catalogue.plugins.siteInventory.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import javax.validation.constraints.NotNull; @JsonIgnoreProperties(ignoreUnknown = true) public class Site { @NotNull @JsonProperty("name") private String name; @NotNull @JsonProperty("location") private String location; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } }
xzl8028/xenia-mobile
app/components/status_icons/archive_icon.js
// Copyright (c) 2015-present Xenia, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React, {PureComponent} from 'react'; import PropTypes from 'prop-types'; import {View} from 'react-native'; import Svg, { Path, } from 'react-native-svg'; export default class ArchiveIcon extends PureComponent { static propTypes = { width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, color: PropTypes.string.isRequired, }; render() { const {color, height, width} = this.props; return ( <View style={{height, width, alignItems: 'flex-start'}}> <Svg width={width} height={height} viewBox='0 0 14 14' > <Path d='M8.5 6.5q0-0.203-0.148-0.352t-0.352-0.148h-2q-0.203 0-0.352 0.148t-0.148 0.352 0.148 0.352 0.352 0.148h2q0.203 0 0.352-0.148t0.148-0.352zM13 5v7.5q0 0.203-0.148 0.352t-0.352 0.148h-11q-0.203 0-0.352-0.148t-0.148-0.352v-7.5q0-0.203 0.148-0.352t0.352-0.148h11q0.203 0 0.352 0.148t0.148 0.352zM13.5 1.5v2q0 0.203-0.148 0.352t-0.352 0.148h-12q-0.203 0-0.352-0.148t-0.148-0.352v-2q0-0.203 0.148-0.352t0.352-0.148h12q0.203 0 0.352 0.148t0.148 0.352z' fill={color} /> </Svg> </View> ); } }
Flipajs/FERDA
gui/settings_widgets/parameters_tab.py
__author__ = 'fnaiser' from PyQt4 import QtGui, QtCore from gui import gui_utils from gui.settings import Settings as S_ class ParametersTab(QtGui.QWidget): def __init__(self): super(ParametersTab, self).__init__() self.vbox = QtGui.QVBoxLayout() self.setLayout(self.vbox) self.frame_layout = QtGui.QFormLayout() self.vbox.addLayout(self.frame_layout) self.blur_kernel_size = QtGui.QDoubleSpinBox() self.blur_kernel_size.setMinimum(0.0) self.blur_kernel_size.setMaximum(5.0) self.blur_kernel_size.setSingleStep(0.1) self.blur_kernel_size.setValue(0) self.frame_layout.addRow('Gblur kernel size', self.blur_kernel_size) self.populate() def populate(self): pass def restore_defaults(self): # TODO return def harvest(self): # TODO: pass
makersoft/mybatis-shards
src/main/java/org/makersoft/shards/strategy/reduce/ShardReduceStrategy.java
<reponame>makersoft/mybatis-shards /* * @(#)ShardReduceStrategy.java 2012-9-4 下午4:57:59 * * Copyright (c) 2011-2012 Makersoft.org all rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * */ package org.makersoft.shards.strategy.reduce; import java.util.List; import org.apache.ibatis.session.RowBounds; /** * 分区结果集合并策略. * * @version 2012-9-4 下午4:57:59 * @author <NAME> */ public interface ShardReduceStrategy { /** * 计算结果集 * @param statement * @param parameter * @param rowBounds * @param values noNullList * @return */ List<Object> reduce(String statement, Object parameter, RowBounds rowBounds, List<Object> values); }
project-everest/quackyducky
src/3d/tests/funptr/src/EverParseStream.h
#ifndef __EVERPARSESTREAM #define __EVERPARSESTREAM #include <stdint.h> #include "EverParseEndianness.h" struct es_cell { uint8_t * buf; uint64_t len; struct es_cell * next; }; struct EverParseInputStreamBase_s { struct es_cell * head; }; typedef struct EverParseInputStreamBase_s * EverParseInputStreamBase; EverParseInputStreamBase EverParseCreate(); int EverParsePush(EverParseInputStreamBase x, uint8_t * buf, uint64_t len); typedef struct { BOOLEAN (*has)(EverParseInputStreamBase const x, uint64_t n); uint8_t * (*read)(EverParseInputStreamBase const x, uint64_t n, uint8_t * const dst); void (*skip)(EverParseInputStreamBase const x, uint64_t n); uint64_t (*empty)(EverParseInputStreamBase const x); void (*retreat)(EverParseInputStreamBase const x, uint64_t n); void *errorContext; void (*handleError) (void *errorContext, uint64_t pos, const char *typename, const char *fieldname, const char *reason); } EverParseExtraT; static inline BOOLEAN EverParseHas(EverParseExtraT const f, EverParseInputStreamBase const x, uint64_t n) { return f.has(x, n); } static inline uint8_t *EverParseRead(EverParseExtraT const f, EverParseInputStreamBase const x, uint64_t n, uint8_t * const dst) { return f.read(x, n, dst); } static inline void EverParseSkip(EverParseExtraT const f, EverParseInputStreamBase const x, uint64_t n) { f.skip(x, n); } static inline uint64_t EverParseEmpty(EverParseExtraT const f, EverParseInputStreamBase const x) { return f.empty(x); } static inline void EverParseHandleError(EverParseExtraT const f, uint64_t pos, const char *typename, const char *fieldname, const char *reason) { f.handleError(f.errorContext, pos, typename, fieldname, reason); } static inline void EverParseRetreat(EverParseExtraT const f, EverParseInputStreamBase const x, uint64_t pos) { f.retreat(x, pos); } #endif // __EVERPARSESTREAM
zhangjun1992/rtt-bsp-hpm6750evkmini
libraries/hpm_sdk/soc/ip/hpm_gpio_regs.h
/* * Copyright (c) 2021-2022 hpmicro * * SPDX-License-Identifier: BSD-3-Clause * */ #ifndef HPM_GPIO_H #define HPM_GPIO_H typedef struct { struct { __RW uint32_t VALUE; /* 0x0: GPIO input value */ __RW uint32_t SET; /* 0x4: GPIO input set */ __RW uint32_t CLEAR; /* 0x8: GPIO input clear */ __RW uint32_t TOGGLE; /* 0xC: GPIO input toggle */ } DI[16]; struct { __RW uint32_t VALUE; /* 0x100: GPIO output value */ __RW uint32_t SET; /* 0x104: GPIO output set */ __RW uint32_t CLEAR; /* 0x108: GPIO output clear */ __RW uint32_t TOGGLE; /* 0x10C: GPIO output toggle */ } DO[16]; struct { __RW uint32_t VALUE; /* 0x200: GPIO direction value */ __RW uint32_t SET; /* 0x204: GPIO direction set */ __RW uint32_t CLEAR; /* 0x208: GPIO direction clear */ __RW uint32_t TOGGLE; /* 0x20C: GPIO direction toggle */ } OE[16]; struct { __RW uint32_t VALUE; /* 0x300: GPIO interrupt flag value */ __RW uint32_t SET; /* 0x304: GPIO interrupt flag set */ __RW uint32_t CLEAR; /* 0x308: GPIO interrupt flag clear */ __RW uint32_t TOGGLE; /* 0x30C: GPIO interrupt flag toggle */ } IF[16]; struct { __RW uint32_t VALUE; /* 0x400: GPIO interrupt enable value */ __RW uint32_t SET; /* 0x404: GPIO interrupt enable set */ __RW uint32_t CLEAR; /* 0x408: GPIO interrupt enable clear */ __RW uint32_t TOGGLE; /* 0x40C: GPIO interrupt enable toggle */ } IE[16]; struct { __RW uint32_t VALUE; /* 0x500: GPIO interrupt polarity value */ __RW uint32_t SET; /* 0x504: GPIO interrupt polarity set */ __RW uint32_t CLEAR; /* 0x508: GPIO interrupt polarity clear */ __RW uint32_t TOGGLE; /* 0x50C: GPIO interrupt polarity toggle */ } PL[16]; struct { __RW uint32_t VALUE; /* 0x600: GPIO interrupt type value */ __RW uint32_t SET; /* 0x604: GPIO interrupt type set */ __RW uint32_t CLEAR; /* 0x608: GPIO interrupt type clear */ __RW uint32_t TOGGLE; /* 0x60C: GPIO interrupt type toggle */ } TP[16]; struct { __RW uint32_t VALUE; /* 0x700: GPIO interrupt asynchronous value */ __RW uint32_t SET; /* 0x704: GPIO interrupt asynchronous set */ __RW uint32_t CLEAR; /* 0x708: GPIO interrupt asynchronous clear */ __RW uint32_t TOGGLE; /* 0x70C: GPIO interrupt asynchronous toggle */ } AS[16]; } GPIO_Type; /* Bitfield definition for register of struct array DI: VALUE */ /* * INPUT (RW) * * GPIO input bus value, each bit represents a bus bit * 0: low level presents on chip pin * 1: high level presents on chip pin */ #define GPIO_DI_VALUE_INPUT_MASK (0xFFFFFFFFUL) #define GPIO_DI_VALUE_INPUT_SHIFT (0U) #define GPIO_DI_VALUE_INPUT_SET(x) (((uint32_t)(x) << GPIO_DI_VALUE_INPUT_SHIFT) & GPIO_DI_VALUE_INPUT_MASK) #define GPIO_DI_VALUE_INPUT_GET(x) (((uint32_t)(x) & GPIO_DI_VALUE_INPUT_MASK) >> GPIO_DI_VALUE_INPUT_SHIFT) /* Bitfield definition for register of struct array DI: SET */ /* * INPUT (RW) * * GPIO input bus value, each bit represents a bus bit * 0: low level presents on chip pin * 1: high level presents on chip pin */ #define GPIO_DI_SET_INPUT_MASK (0xFFFFFFFFUL) #define GPIO_DI_SET_INPUT_SHIFT (0U) #define GPIO_DI_SET_INPUT_SET(x) (((uint32_t)(x) << GPIO_DI_SET_INPUT_SHIFT) & GPIO_DI_SET_INPUT_MASK) #define GPIO_DI_SET_INPUT_GET(x) (((uint32_t)(x) & GPIO_DI_SET_INPUT_MASK) >> GPIO_DI_SET_INPUT_SHIFT) /* Bitfield definition for register of struct array DI: CLEAR */ /* * INPUT (RW) * * GPIO input bus value, each bit represents a bus bit * 0: low level presents on chip pin * 1: high level presents on chip pin */ #define GPIO_DI_CLEAR_INPUT_MASK (0xFFFFFFFFUL) #define GPIO_DI_CLEAR_INPUT_SHIFT (0U) #define GPIO_DI_CLEAR_INPUT_SET(x) (((uint32_t)(x) << GPIO_DI_CLEAR_INPUT_SHIFT) & GPIO_DI_CLEAR_INPUT_MASK) #define GPIO_DI_CLEAR_INPUT_GET(x) (((uint32_t)(x) & GPIO_DI_CLEAR_INPUT_MASK) >> GPIO_DI_CLEAR_INPUT_SHIFT) /* Bitfield definition for register of struct array DI: TOGGLE */ /* * INPUT (RW) * * GPIO input bus value, each bit represents a bus bit * 0: low level presents on chip pin * 1: high level presents on chip pin */ #define GPIO_DI_TOGGLE_INPUT_MASK (0xFFFFFFFFUL) #define GPIO_DI_TOGGLE_INPUT_SHIFT (0U) #define GPIO_DI_TOGGLE_INPUT_SET(x) (((uint32_t)(x) << GPIO_DI_TOGGLE_INPUT_SHIFT) & GPIO_DI_TOGGLE_INPUT_MASK) #define GPIO_DI_TOGGLE_INPUT_GET(x) (((uint32_t)(x) & GPIO_DI_TOGGLE_INPUT_MASK) >> GPIO_DI_TOGGLE_INPUT_SHIFT) /* Bitfield definition for register of struct array DO: VALUE */ /* * OUTPUT (RW) * * GPIO output register value, each bit represents a bus bit * 0: chip pin output low level when direction is output * 1: chip pin output high level when direction is output */ #define GPIO_DO_VALUE_OUTPUT_MASK (0xFFFFFFFFUL) #define GPIO_DO_VALUE_OUTPUT_SHIFT (0U) #define GPIO_DO_VALUE_OUTPUT_SET(x) (((uint32_t)(x) << GPIO_DO_VALUE_OUTPUT_SHIFT) & GPIO_DO_VALUE_OUTPUT_MASK) #define GPIO_DO_VALUE_OUTPUT_GET(x) (((uint32_t)(x) & GPIO_DO_VALUE_OUTPUT_MASK) >> GPIO_DO_VALUE_OUTPUT_SHIFT) /* Bitfield definition for register of struct array DO: SET */ /* * OUTPUT (RW) * * GPIO output register value, each bit represents a bus bit * 0: chip pin output low level when direction is output * 1: chip pin output high level when direction is output */ #define GPIO_DO_SET_OUTPUT_MASK (0xFFFFFFFFUL) #define GPIO_DO_SET_OUTPUT_SHIFT (0U) #define GPIO_DO_SET_OUTPUT_SET(x) (((uint32_t)(x) << GPIO_DO_SET_OUTPUT_SHIFT) & GPIO_DO_SET_OUTPUT_MASK) #define GPIO_DO_SET_OUTPUT_GET(x) (((uint32_t)(x) & GPIO_DO_SET_OUTPUT_MASK) >> GPIO_DO_SET_OUTPUT_SHIFT) /* Bitfield definition for register of struct array DO: CLEAR */ /* * OUTPUT (RW) * * GPIO output register value, each bit represents a bus bit * 0: chip pin output low level when direction is output * 1: chip pin output high level when direction is output */ #define GPIO_DO_CLEAR_OUTPUT_MASK (0xFFFFFFFFUL) #define GPIO_DO_CLEAR_OUTPUT_SHIFT (0U) #define GPIO_DO_CLEAR_OUTPUT_SET(x) (((uint32_t)(x) << GPIO_DO_CLEAR_OUTPUT_SHIFT) & GPIO_DO_CLEAR_OUTPUT_MASK) #define GPIO_DO_CLEAR_OUTPUT_GET(x) (((uint32_t)(x) & GPIO_DO_CLEAR_OUTPUT_MASK) >> GPIO_DO_CLEAR_OUTPUT_SHIFT) /* Bitfield definition for register of struct array DO: TOGGLE */ /* * OUTPUT (RW) * * GPIO output register value, each bit represents a bus bit * 0: chip pin output low level when direction is output * 1: chip pin output high level when direction is output */ #define GPIO_DO_TOGGLE_OUTPUT_MASK (0xFFFFFFFFUL) #define GPIO_DO_TOGGLE_OUTPUT_SHIFT (0U) #define GPIO_DO_TOGGLE_OUTPUT_SET(x) (((uint32_t)(x) << GPIO_DO_TOGGLE_OUTPUT_SHIFT) & GPIO_DO_TOGGLE_OUTPUT_MASK) #define GPIO_DO_TOGGLE_OUTPUT_GET(x) (((uint32_t)(x) & GPIO_DO_TOGGLE_OUTPUT_MASK) >> GPIO_DO_TOGGLE_OUTPUT_SHIFT) /* Bitfield definition for register of struct array OE: VALUE */ /* * DIRECTION (RW) * * GPIO direction, each bit represents a bus bit * 0: input * 1: output */ #define GPIO_OE_VALUE_DIRECTION_MASK (0xFFFFFFFFUL) #define GPIO_OE_VALUE_DIRECTION_SHIFT (0U) #define GPIO_OE_VALUE_DIRECTION_SET(x) (((uint32_t)(x) << GPIO_OE_VALUE_DIRECTION_SHIFT) & GPIO_OE_VALUE_DIRECTION_MASK) #define GPIO_OE_VALUE_DIRECTION_GET(x) (((uint32_t)(x) & GPIO_OE_VALUE_DIRECTION_MASK) >> GPIO_OE_VALUE_DIRECTION_SHIFT) /* Bitfield definition for register of struct array OE: SET */ /* * DIRECTION (RW) * * GPIO direction, each bit represents a bus bit * 0: input * 1: output */ #define GPIO_OE_SET_DIRECTION_MASK (0xFFFFFFFFUL) #define GPIO_OE_SET_DIRECTION_SHIFT (0U) #define GPIO_OE_SET_DIRECTION_SET(x) (((uint32_t)(x) << GPIO_OE_SET_DIRECTION_SHIFT) & GPIO_OE_SET_DIRECTION_MASK) #define GPIO_OE_SET_DIRECTION_GET(x) (((uint32_t)(x) & GPIO_OE_SET_DIRECTION_MASK) >> GPIO_OE_SET_DIRECTION_SHIFT) /* Bitfield definition for register of struct array OE: CLEAR */ /* * DIRECTION (RW) * * GPIO direction, each bit represents a bus bit * 0: input * 1: output */ #define GPIO_OE_CLEAR_DIRECTION_MASK (0xFFFFFFFFUL) #define GPIO_OE_CLEAR_DIRECTION_SHIFT (0U) #define GPIO_OE_CLEAR_DIRECTION_SET(x) (((uint32_t)(x) << GPIO_OE_CLEAR_DIRECTION_SHIFT) & GPIO_OE_CLEAR_DIRECTION_MASK) #define GPIO_OE_CLEAR_DIRECTION_GET(x) (((uint32_t)(x) & GPIO_OE_CLEAR_DIRECTION_MASK) >> GPIO_OE_CLEAR_DIRECTION_SHIFT) /* Bitfield definition for register of struct array OE: TOGGLE */ /* * DIRECTION (RW) * * GPIO direction, each bit represents a bus bit * 0: input * 1: output */ #define GPIO_OE_TOGGLE_DIRECTION_MASK (0xFFFFFFFFUL) #define GPIO_OE_TOGGLE_DIRECTION_SHIFT (0U) #define GPIO_OE_TOGGLE_DIRECTION_SET(x) (((uint32_t)(x) << GPIO_OE_TOGGLE_DIRECTION_SHIFT) & GPIO_OE_TOGGLE_DIRECTION_MASK) #define GPIO_OE_TOGGLE_DIRECTION_GET(x) (((uint32_t)(x) & GPIO_OE_TOGGLE_DIRECTION_MASK) >> GPIO_OE_TOGGLE_DIRECTION_SHIFT) /* Bitfield definition for register of struct array IF: VALUE */ /* * IRQ_FLAG (W1C) * * GPIO interrupt flag, write 1 to clear this flag * 0: no irq * 1: irq pending */ #define GPIO_IF_VALUE_IRQ_FLAG_MASK (0xFFFFFFFFUL) #define GPIO_IF_VALUE_IRQ_FLAG_SHIFT (0U) #define GPIO_IF_VALUE_IRQ_FLAG_SET(x) (((uint32_t)(x) << GPIO_IF_VALUE_IRQ_FLAG_SHIFT) & GPIO_IF_VALUE_IRQ_FLAG_MASK) #define GPIO_IF_VALUE_IRQ_FLAG_GET(x) (((uint32_t)(x) & GPIO_IF_VALUE_IRQ_FLAG_MASK) >> GPIO_IF_VALUE_IRQ_FLAG_SHIFT) /* Bitfield definition for register of struct array IF: SET */ /* * IRQ_FLAG (RW) * * GPIO interrupt flag, write 1 to clear this flag * 0: no irq * 1: irq pending */ #define GPIO_IF_SET_IRQ_FLAG_MASK (0xFFFFFFFFUL) #define GPIO_IF_SET_IRQ_FLAG_SHIFT (0U) #define GPIO_IF_SET_IRQ_FLAG_SET(x) (((uint32_t)(x) << GPIO_IF_SET_IRQ_FLAG_SHIFT) & GPIO_IF_SET_IRQ_FLAG_MASK) #define GPIO_IF_SET_IRQ_FLAG_GET(x) (((uint32_t)(x) & GPIO_IF_SET_IRQ_FLAG_MASK) >> GPIO_IF_SET_IRQ_FLAG_SHIFT) /* Bitfield definition for register of struct array IF: CLEAR */ /* * IRQ_FLAG (RW) * * GPIO interrupt flag, write 1 to clear this flag * 0: no irq * 1: irq pending */ #define GPIO_IF_CLEAR_IRQ_FLAG_MASK (0xFFFFFFFFUL) #define GPIO_IF_CLEAR_IRQ_FLAG_SHIFT (0U) #define GPIO_IF_CLEAR_IRQ_FLAG_SET(x) (((uint32_t)(x) << GPIO_IF_CLEAR_IRQ_FLAG_SHIFT) & GPIO_IF_CLEAR_IRQ_FLAG_MASK) #define GPIO_IF_CLEAR_IRQ_FLAG_GET(x) (((uint32_t)(x) & GPIO_IF_CLEAR_IRQ_FLAG_MASK) >> GPIO_IF_CLEAR_IRQ_FLAG_SHIFT) /* Bitfield definition for register of struct array IF: TOGGLE */ /* * IRQ_FLAG (RW) * * GPIO interrupt flag, write 1 to clear this flag * 0: no irq * 1: irq pending */ #define GPIO_IF_TOGGLE_IRQ_FLAG_MASK (0xFFFFFFFFUL) #define GPIO_IF_TOGGLE_IRQ_FLAG_SHIFT (0U) #define GPIO_IF_TOGGLE_IRQ_FLAG_SET(x) (((uint32_t)(x) << GPIO_IF_TOGGLE_IRQ_FLAG_SHIFT) & GPIO_IF_TOGGLE_IRQ_FLAG_MASK) #define GPIO_IF_TOGGLE_IRQ_FLAG_GET(x) (((uint32_t)(x) & GPIO_IF_TOGGLE_IRQ_FLAG_MASK) >> GPIO_IF_TOGGLE_IRQ_FLAG_SHIFT) /* Bitfield definition for register of struct array IE: VALUE */ /* * IRQ_EN (RW) * * GPIO interrupt enable, each bit represents a bus bit * 0: irq is disabled * 1: irq is enable */ #define GPIO_IE_VALUE_IRQ_EN_MASK (0xFFFFFFFFUL) #define GPIO_IE_VALUE_IRQ_EN_SHIFT (0U) #define GPIO_IE_VALUE_IRQ_EN_SET(x) (((uint32_t)(x) << GPIO_IE_VALUE_IRQ_EN_SHIFT) & GPIO_IE_VALUE_IRQ_EN_MASK) #define GPIO_IE_VALUE_IRQ_EN_GET(x) (((uint32_t)(x) & GPIO_IE_VALUE_IRQ_EN_MASK) >> GPIO_IE_VALUE_IRQ_EN_SHIFT) /* Bitfield definition for register of struct array IE: SET */ /* * IRQ_EN (RW) * * GPIO interrupt enable, each bit represents a bus bit * 0: irq is disabled * 1: irq is enable */ #define GPIO_IE_SET_IRQ_EN_MASK (0xFFFFFFFFUL) #define GPIO_IE_SET_IRQ_EN_SHIFT (0U) #define GPIO_IE_SET_IRQ_EN_SET(x) (((uint32_t)(x) << GPIO_IE_SET_IRQ_EN_SHIFT) & GPIO_IE_SET_IRQ_EN_MASK) #define GPIO_IE_SET_IRQ_EN_GET(x) (((uint32_t)(x) & GPIO_IE_SET_IRQ_EN_MASK) >> GPIO_IE_SET_IRQ_EN_SHIFT) /* Bitfield definition for register of struct array IE: CLEAR */ /* * IRQ_EN (RW) * * GPIO interrupt enable, each bit represents a bus bit * 0: irq is disabled * 1: irq is enable */ #define GPIO_IE_CLEAR_IRQ_EN_MASK (0xFFFFFFFFUL) #define GPIO_IE_CLEAR_IRQ_EN_SHIFT (0U) #define GPIO_IE_CLEAR_IRQ_EN_SET(x) (((uint32_t)(x) << GPIO_IE_CLEAR_IRQ_EN_SHIFT) & GPIO_IE_CLEAR_IRQ_EN_MASK) #define GPIO_IE_CLEAR_IRQ_EN_GET(x) (((uint32_t)(x) & GPIO_IE_CLEAR_IRQ_EN_MASK) >> GPIO_IE_CLEAR_IRQ_EN_SHIFT) /* Bitfield definition for register of struct array IE: TOGGLE */ /* * IRQ_EN (RW) * * GPIO interrupt enable, each bit represents a bus bit * 0: irq is disabled * 1: irq is enable */ #define GPIO_IE_TOGGLE_IRQ_EN_MASK (0xFFFFFFFFUL) #define GPIO_IE_TOGGLE_IRQ_EN_SHIFT (0U) #define GPIO_IE_TOGGLE_IRQ_EN_SET(x) (((uint32_t)(x) << GPIO_IE_TOGGLE_IRQ_EN_SHIFT) & GPIO_IE_TOGGLE_IRQ_EN_MASK) #define GPIO_IE_TOGGLE_IRQ_EN_GET(x) (((uint32_t)(x) & GPIO_IE_TOGGLE_IRQ_EN_MASK) >> GPIO_IE_TOGGLE_IRQ_EN_SHIFT) /* Bitfield definition for register of struct array PL: VALUE */ /* * IRQ_POL (RW) * * GPIO interrupt polarity, each bit represents a bus bit * 0: irq is high level or rising edge * 1: irq is low level or falling edge */ #define GPIO_PL_VALUE_IRQ_POL_MASK (0xFFFFFFFFUL) #define GPIO_PL_VALUE_IRQ_POL_SHIFT (0U) #define GPIO_PL_VALUE_IRQ_POL_SET(x) (((uint32_t)(x) << GPIO_PL_VALUE_IRQ_POL_SHIFT) & GPIO_PL_VALUE_IRQ_POL_MASK) #define GPIO_PL_VALUE_IRQ_POL_GET(x) (((uint32_t)(x) & GPIO_PL_VALUE_IRQ_POL_MASK) >> GPIO_PL_VALUE_IRQ_POL_SHIFT) /* Bitfield definition for register of struct array PL: SET */ /* * IRQ_POL (RW) * * GPIO interrupt polarity, each bit represents a bus bit * 0: irq is high level or rising edge * 1: irq is low level or falling edge */ #define GPIO_PL_SET_IRQ_POL_MASK (0xFFFFFFFFUL) #define GPIO_PL_SET_IRQ_POL_SHIFT (0U) #define GPIO_PL_SET_IRQ_POL_SET(x) (((uint32_t)(x) << GPIO_PL_SET_IRQ_POL_SHIFT) & GPIO_PL_SET_IRQ_POL_MASK) #define GPIO_PL_SET_IRQ_POL_GET(x) (((uint32_t)(x) & GPIO_PL_SET_IRQ_POL_MASK) >> GPIO_PL_SET_IRQ_POL_SHIFT) /* Bitfield definition for register of struct array PL: CLEAR */ /* * IRQ_POL (RW) * * GPIO interrupt polarity, each bit represents a bus bit * 0: irq is high level or rising edge * 1: irq is low level or falling edge */ #define GPIO_PL_CLEAR_IRQ_POL_MASK (0xFFFFFFFFUL) #define GPIO_PL_CLEAR_IRQ_POL_SHIFT (0U) #define GPIO_PL_CLEAR_IRQ_POL_SET(x) (((uint32_t)(x) << GPIO_PL_CLEAR_IRQ_POL_SHIFT) & GPIO_PL_CLEAR_IRQ_POL_MASK) #define GPIO_PL_CLEAR_IRQ_POL_GET(x) (((uint32_t)(x) & GPIO_PL_CLEAR_IRQ_POL_MASK) >> GPIO_PL_CLEAR_IRQ_POL_SHIFT) /* Bitfield definition for register of struct array PL: TOGGLE */ /* * IRQ_POL (RW) * * GPIO interrupt polarity, each bit represents a bus bit * 0: irq is high level or rising edge * 1: irq is low level or falling edge */ #define GPIO_PL_TOGGLE_IRQ_POL_MASK (0xFFFFFFFFUL) #define GPIO_PL_TOGGLE_IRQ_POL_SHIFT (0U) #define GPIO_PL_TOGGLE_IRQ_POL_SET(x) (((uint32_t)(x) << GPIO_PL_TOGGLE_IRQ_POL_SHIFT) & GPIO_PL_TOGGLE_IRQ_POL_MASK) #define GPIO_PL_TOGGLE_IRQ_POL_GET(x) (((uint32_t)(x) & GPIO_PL_TOGGLE_IRQ_POL_MASK) >> GPIO_PL_TOGGLE_IRQ_POL_SHIFT) /* Bitfield definition for register of struct array TP: VALUE */ /* * IRQ_TYPE (RW) * * GPIO interrupt type, each bit represents a bus bit * 0: irq is triggered by level * 1: irq is triggered by edge */ #define GPIO_TP_VALUE_IRQ_TYPE_MASK (0xFFFFFFFFUL) #define GPIO_TP_VALUE_IRQ_TYPE_SHIFT (0U) #define GPIO_TP_VALUE_IRQ_TYPE_SET(x) (((uint32_t)(x) << GPIO_TP_VALUE_IRQ_TYPE_SHIFT) & GPIO_TP_VALUE_IRQ_TYPE_MASK) #define GPIO_TP_VALUE_IRQ_TYPE_GET(x) (((uint32_t)(x) & GPIO_TP_VALUE_IRQ_TYPE_MASK) >> GPIO_TP_VALUE_IRQ_TYPE_SHIFT) /* Bitfield definition for register of struct array TP: SET */ /* * IRQ_TYPE (RW) * * GPIO interrupt type, each bit represents a bus bit * 0: irq is triggered by level * 1: irq is triggered by edge */ #define GPIO_TP_SET_IRQ_TYPE_MASK (0xFFFFFFFFUL) #define GPIO_TP_SET_IRQ_TYPE_SHIFT (0U) #define GPIO_TP_SET_IRQ_TYPE_SET(x) (((uint32_t)(x) << GPIO_TP_SET_IRQ_TYPE_SHIFT) & GPIO_TP_SET_IRQ_TYPE_MASK) #define GPIO_TP_SET_IRQ_TYPE_GET(x) (((uint32_t)(x) & GPIO_TP_SET_IRQ_TYPE_MASK) >> GPIO_TP_SET_IRQ_TYPE_SHIFT) /* Bitfield definition for register of struct array TP: CLEAR */ /* * IRQ_TYPE (RW) * * GPIO interrupt type, each bit represents a bus bit * 0: irq is triggered by level * 1: irq is triggered by edge */ #define GPIO_TP_CLEAR_IRQ_TYPE_MASK (0xFFFFFFFFUL) #define GPIO_TP_CLEAR_IRQ_TYPE_SHIFT (0U) #define GPIO_TP_CLEAR_IRQ_TYPE_SET(x) (((uint32_t)(x) << GPIO_TP_CLEAR_IRQ_TYPE_SHIFT) & GPIO_TP_CLEAR_IRQ_TYPE_MASK) #define GPIO_TP_CLEAR_IRQ_TYPE_GET(x) (((uint32_t)(x) & GPIO_TP_CLEAR_IRQ_TYPE_MASK) >> GPIO_TP_CLEAR_IRQ_TYPE_SHIFT) /* Bitfield definition for register of struct array TP: TOGGLE */ /* * IRQ_TYPE (RW) * * GPIO interrupt type, each bit represents a bus bit * 0: irq is triggered by level * 1: irq is triggered by edge */ #define GPIO_TP_TOGGLE_IRQ_TYPE_MASK (0xFFFFFFFFUL) #define GPIO_TP_TOGGLE_IRQ_TYPE_SHIFT (0U) #define GPIO_TP_TOGGLE_IRQ_TYPE_SET(x) (((uint32_t)(x) << GPIO_TP_TOGGLE_IRQ_TYPE_SHIFT) & GPIO_TP_TOGGLE_IRQ_TYPE_MASK) #define GPIO_TP_TOGGLE_IRQ_TYPE_GET(x) (((uint32_t)(x) & GPIO_TP_TOGGLE_IRQ_TYPE_MASK) >> GPIO_TP_TOGGLE_IRQ_TYPE_SHIFT) /* Bitfield definition for register of struct array AS: VALUE */ /* * IRQ_ASYNC (RW) * * GPIO interrupt asynchronous, each bit represents a bus bit * 0: irq is triggered base on system clock * 1: irq is triggered combinational * Note: combinational interrupt is sensitive to environment noise */ #define GPIO_AS_VALUE_IRQ_ASYNC_MASK (0xFFFFFFFFUL) #define GPIO_AS_VALUE_IRQ_ASYNC_SHIFT (0U) #define GPIO_AS_VALUE_IRQ_ASYNC_SET(x) (((uint32_t)(x) << GPIO_AS_VALUE_IRQ_ASYNC_SHIFT) & GPIO_AS_VALUE_IRQ_ASYNC_MASK) #define GPIO_AS_VALUE_IRQ_ASYNC_GET(x) (((uint32_t)(x) & GPIO_AS_VALUE_IRQ_ASYNC_MASK) >> GPIO_AS_VALUE_IRQ_ASYNC_SHIFT) /* Bitfield definition for register of struct array AS: SET */ /* * IRQ_ASYNC (RW) * * GPIO interrupt asynchronous, each bit represents a bus bit * 0: irq is triggered base on system clock * 1: irq is triggered combinational * Note: combinational interrupt is sensitive to environment noise */ #define GPIO_AS_SET_IRQ_ASYNC_MASK (0xFFFFFFFFUL) #define GPIO_AS_SET_IRQ_ASYNC_SHIFT (0U) #define GPIO_AS_SET_IRQ_ASYNC_SET(x) (((uint32_t)(x) << GPIO_AS_SET_IRQ_ASYNC_SHIFT) & GPIO_AS_SET_IRQ_ASYNC_MASK) #define GPIO_AS_SET_IRQ_ASYNC_GET(x) (((uint32_t)(x) & GPIO_AS_SET_IRQ_ASYNC_MASK) >> GPIO_AS_SET_IRQ_ASYNC_SHIFT) /* Bitfield definition for register of struct array AS: CLEAR */ /* * IRQ_ASYNC (RW) * * GPIO interrupt asynchronous, each bit represents a bus bit * 0: irq is triggered base on system clock * 1: irq is triggered combinational * Note: combinational interrupt is sensitive to environment noise */ #define GPIO_AS_CLEAR_IRQ_ASYNC_MASK (0xFFFFFFFFUL) #define GPIO_AS_CLEAR_IRQ_ASYNC_SHIFT (0U) #define GPIO_AS_CLEAR_IRQ_ASYNC_SET(x) (((uint32_t)(x) << GPIO_AS_CLEAR_IRQ_ASYNC_SHIFT) & GPIO_AS_CLEAR_IRQ_ASYNC_MASK) #define GPIO_AS_CLEAR_IRQ_ASYNC_GET(x) (((uint32_t)(x) & GPIO_AS_CLEAR_IRQ_ASYNC_MASK) >> GPIO_AS_CLEAR_IRQ_ASYNC_SHIFT) /* Bitfield definition for register of struct array AS: TOGGLE */ /* * IRQ_ASYNC (RW) * * GPIO interrupt asynchronous, each bit represents a bus bit * 0: irq is triggered base on system clock * 1: irq is triggered combinational * Note: combinational interrupt is sensitive to environment noise */ #define GPIO_AS_TOGGLE_IRQ_ASYNC_MASK (0xFFFFFFFFUL) #define GPIO_AS_TOGGLE_IRQ_ASYNC_SHIFT (0U) #define GPIO_AS_TOGGLE_IRQ_ASYNC_SET(x) (((uint32_t)(x) << GPIO_AS_TOGGLE_IRQ_ASYNC_SHIFT) & GPIO_AS_TOGGLE_IRQ_ASYNC_MASK) #define GPIO_AS_TOGGLE_IRQ_ASYNC_GET(x) (((uint32_t)(x) & GPIO_AS_TOGGLE_IRQ_ASYNC_MASK) >> GPIO_AS_TOGGLE_IRQ_ASYNC_SHIFT) /* DI register group index macro definition */ #define GPIO_DI_GPIOA (0UL) #define GPIO_DI_GPIOB (1UL) #define GPIO_DI_GPIOC (2UL) #define GPIO_DI_GPIOD (3UL) #define GPIO_DI_GPIOE (4UL) #define GPIO_DI_GPIOF (5UL) #define GPIO_DI_GPIOX (13UL) #define GPIO_DI_GPIOY (14UL) #define GPIO_DI_GPIOZ (15UL) /* DO register group index macro definition */ #define GPIO_DO_GPIOA (0UL) #define GPIO_DO_GPIOB (1UL) #define GPIO_DO_GPIOC (2UL) #define GPIO_DO_GPIOD (3UL) #define GPIO_DO_GPIOE (4UL) #define GPIO_DO_GPIOF (5UL) #define GPIO_DO_GPIOX (13UL) #define GPIO_DO_GPIOY (14UL) #define GPIO_DO_GPIOZ (15UL) /* OE register group index macro definition */ #define GPIO_OE_GPIOA (0UL) #define GPIO_OE_GPIOB (1UL) #define GPIO_OE_GPIOC (2UL) #define GPIO_OE_GPIOD (3UL) #define GPIO_OE_GPIOE (4UL) #define GPIO_OE_GPIOF (5UL) #define GPIO_OE_GPIOX (13UL) #define GPIO_OE_GPIOY (14UL) #define GPIO_OE_GPIOZ (15UL) /* IF register group index macro definition */ #define GPIO_IF_GPIOA (0UL) #define GPIO_IF_GPIOB (1UL) #define GPIO_IF_GPIOC (2UL) #define GPIO_IF_GPIOD (3UL) #define GPIO_IF_GPIOE (4UL) #define GPIO_IF_GPIOF (5UL) #define GPIO_IF_GPIOX (13UL) #define GPIO_IF_GPIOY (14UL) #define GPIO_IF_GPIOZ (15UL) /* IE register group index macro definition */ #define GPIO_IE_GPIOA (0UL) #define GPIO_IE_GPIOB (1UL) #define GPIO_IE_GPIOC (2UL) #define GPIO_IE_GPIOD (3UL) #define GPIO_IE_GPIOE (4UL) #define GPIO_IE_GPIOF (5UL) #define GPIO_IE_GPIOX (13UL) #define GPIO_IE_GPIOY (14UL) #define GPIO_IE_GPIOZ (15UL) /* PL register group index macro definition */ #define GPIO_PL_GPIOA (0UL) #define GPIO_PL_GPIOB (1UL) #define GPIO_PL_GPIOC (2UL) #define GPIO_PL_GPIOD (3UL) #define GPIO_PL_GPIOE (4UL) #define GPIO_PL_GPIOF (5UL) #define GPIO_PL_GPIOX (13UL) #define GPIO_PL_GPIOY (14UL) #define GPIO_PL_GPIOZ (15UL) /* TP register group index macro definition */ #define GPIO_TP_GPIOA (0UL) #define GPIO_TP_GPIOB (1UL) #define GPIO_TP_GPIOC (2UL) #define GPIO_TP_GPIOD (3UL) #define GPIO_TP_GPIOE (4UL) #define GPIO_TP_GPIOF (5UL) #define GPIO_TP_GPIOX (13UL) #define GPIO_TP_GPIOY (14UL) #define GPIO_TP_GPIOZ (15UL) /* AS register group index macro definition */ #define GPIO_AS_GPIOA (0UL) #define GPIO_AS_GPIOB (1UL) #define GPIO_AS_GPIOC (2UL) #define GPIO_AS_GPIOD (3UL) #define GPIO_AS_GPIOE (4UL) #define GPIO_AS_GPIOF (5UL) #define GPIO_AS_GPIOX (13UL) #define GPIO_AS_GPIOY (14UL) #define GPIO_AS_GPIOZ (15UL) #endif /* HPM_GPIO_H */