repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
dplbsd/soc2013
head/sys/cam/ctl/ctl_private.h
<filename>head/sys/cam/ctl/ctl_private.h /*- * Copyright (c) 2003, 2004, 2005, 2008 Silicon Graphics International Corp. * 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, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * * NO WARRANTY * 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 MERCHANTIBILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR 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 DAMAGES. * * $Id: //depot/users/kenm/FreeBSD-test2/sys/cam/ctl/ctl_private.h#7 $ * $FreeBSD: soc2013/dpl/head/sys/cam/ctl/ctl_private.h 234246 2012-04-06 22:23:13Z ken $ */ /* * CAM Target Layer driver private data structures/definitions. * * Author: <NAME> <<EMAIL>> */ #ifndef _CTL_PRIVATE_H_ #define _CTL_PRIVATE_H_ /* * SCSI vendor and product names. */ #define CTL_VENDOR "FREEBSD " #define CTL_DIRECT_PRODUCT "CTLDISK " #define CTL_PROCESSOR_PRODUCT "CTLPROCESSOR " #define CTL_UNKNOWN_PRODUCT "CTLDEVICE " struct ctl_fe_ioctl_startstop_info { struct cv sem; struct ctl_hard_startstop_info hs_info; }; struct ctl_fe_ioctl_bbrread_info { struct cv sem; struct ctl_bbrread_info *bbr_info; int wakeup_done; struct mtx *lock; }; typedef enum { CTL_IOCTL_INPROG, CTL_IOCTL_DATAMOVE, CTL_IOCTL_DONE } ctl_fe_ioctl_state; struct ctl_fe_ioctl_params { struct cv sem; struct mtx ioctl_mtx; ctl_fe_ioctl_state state; }; #define CTL_POOL_ENTRIES_INTERNAL 200 #define CTL_POOL_ENTRIES_EMERGENCY 300 #define CTL_POOL_ENTRIES_OTHER_SC 200 typedef enum { CTL_POOL_INTERNAL, CTL_POOL_FETD, CTL_POOL_EMERGENCY, CTL_POOL_IOCTL, CTL_POOL_4OTHERSC } ctl_pool_type; typedef enum { CTL_POOL_FLAG_NONE = 0x00, CTL_POOL_FLAG_INVALID = 0x01 } ctl_pool_flags; struct ctl_io_pool { ctl_pool_type type; ctl_pool_flags flags; uint32_t id; struct ctl_softc *ctl_softc; uint32_t refcount; uint64_t total_allocated; uint64_t total_freed; int32_t total_ctl_io; int32_t free_ctl_io; STAILQ_HEAD(, ctl_io_hdr) free_queue; STAILQ_ENTRY(ctl_io_pool) links; }; typedef enum { CTL_IOCTL_FLAG_NONE = 0x00, CTL_IOCTL_FLAG_ENABLED = 0x01 } ctl_ioctl_flags; struct ctl_ioctl_info { ctl_ioctl_flags flags; uint32_t cur_tag_num; struct ctl_frontend fe; char port_name[24]; }; typedef enum { CTL_SER_BLOCK, CTL_SER_EXTENT, CTL_SER_PASS, CTL_SER_SKIP } ctl_serialize_action; typedef enum { CTL_ACTION_BLOCK, CTL_ACTION_OVERLAP, CTL_ACTION_OVERLAP_TAG, CTL_ACTION_PASS, CTL_ACTION_SKIP, CTL_ACTION_ERROR } ctl_action; /* * WARNING: Keep the bottom nibble here free, we OR in the data direction * flags for each command. * * Note: "OK_ON_ALL_LUNS" == we don't have to have a lun configured * "OK_ON_BOTH" == we have to have a lun configured */ typedef enum { CTL_CMD_FLAG_NONE = 0x0000, CTL_CMD_FLAG_NO_SENSE = 0x0010, CTL_CMD_FLAG_OK_ON_ALL_LUNS = 0x0020, CTL_CMD_FLAG_ALLOW_ON_RESV = 0x0040, CTL_CMD_FLAG_OK_ON_PROC = 0x0100, CTL_CMD_FLAG_OK_ON_SLUN = 0x0200, CTL_CMD_FLAG_OK_ON_BOTH = 0x0300, CTL_CMD_FLAG_OK_ON_STOPPED = 0x0400, CTL_CMD_FLAG_OK_ON_INOPERABLE = 0x0800, CTL_CMD_FLAG_OK_ON_OFFLINE = 0x1000, CTL_CMD_FLAG_OK_ON_SECONDARY = 0x2000, CTL_CMD_FLAG_ALLOW_ON_PR_RESV = 0x4000 } ctl_cmd_flags; typedef enum { CTL_SERIDX_TUR = 0, CTL_SERIDX_READ, CTL_SERIDX_WRITE, CTL_SERIDX_MD_SNS, CTL_SERIDX_MD_SEL, CTL_SERIDX_RQ_SNS, CTL_SERIDX_INQ, CTL_SERIDX_RD_CAP, CTL_SERIDX_RESV, CTL_SERIDX_REL, CTL_SERIDX_LOG_SNS, CTL_SERIDX_FORMAT, CTL_SERIDX_START, CTL_SERIDX_PRES_IN, CTL_SERIDX_PRES_OUT, CTL_SERIDX_MAIN_IN, /* TBD: others to be filled in as needed */ CTL_SERIDX_COUNT, /* LAST, not a normal code, provides # codes */ CTL_SERIDX_INVLD = CTL_SERIDX_COUNT } ctl_seridx; typedef int ctl_opfunc(struct ctl_scsiio *ctsio); struct ctl_cmd_entry { ctl_opfunc *execute; ctl_seridx seridx; ctl_cmd_flags flags; ctl_lun_error_pattern pattern; }; typedef enum { CTL_LUN_NONE = 0x000, CTL_LUN_CONTROL = 0x001, CTL_LUN_RESERVED = 0x002, CTL_LUN_INVALID = 0x004, CTL_LUN_DISABLED = 0x008, CTL_LUN_MALLOCED = 0x010, CTL_LUN_STOPPED = 0x020, CTL_LUN_INOPERABLE = 0x040, CTL_LUN_OFFLINE = 0x080, CTL_LUN_PR_RESERVED = 0x100, CTL_LUN_PRIMARY_SC = 0x200, CTL_LUN_SENSE_DESC = 0x400 } ctl_lun_flags; typedef enum { CTLBLOCK_FLAG_NONE = 0x00, CTLBLOCK_FLAG_INVALID = 0x01 } ctlblock_flags; union ctl_softcs { struct ctl_softc *ctl_softc; struct ctlblock_softc *ctlblock_softc; }; /* * Mode page defaults. */ #if 0 /* * These values make Solaris trim off some of the capacity. */ #define CTL_DEFAULT_SECTORS_PER_TRACK 63 #define CTL_DEFAULT_HEADS 255 /* * These values seem to work okay. */ #define CTL_DEFAULT_SECTORS_PER_TRACK 63 #define CTL_DEFAULT_HEADS 16 /* * These values work reasonably well. */ #define CTL_DEFAULT_SECTORS_PER_TRACK 512 #define CTL_DEFAULT_HEADS 64 #endif /* * Solaris is somewhat picky about how many heads and sectors per track you * have defined in mode pages 3 and 4. These values seem to cause Solaris * to get the capacity more or less right when you run the format tool. * They still have problems when dealing with devices larger than 1TB, * but there isn't anything we can do about that. * * For smaller LUN sizes, this ends up causing the number of cylinders to * work out to 0. Solaris actually recognizes that and comes up with its * own bogus geometry to fit the actual capacity of the drive. They really * should just give up on geometry and stick to the read capacity * information alone for modern disk drives. * * One thing worth mentioning about Solaris' mkfs command is that it * doesn't like sectors per track values larger than 256. 512 seems to * work okay for format, but causes problems when you try to make a * filesystem. * * Another caveat about these values: the product of these two values * really should be a power of 2. This is because of the simplistic * shift-based calculation that we have to use on the i386 platform to * calculate the number of cylinders here. (If you use a divide, you end * up calling __udivdi3(), which is a hardware FP call on the PC. On the * XScale, it is done in software, so you can do that from inside the * kernel.) * * So for the current values (256 S/T, 128 H), we get 32768, which works * very nicely for calculating cylinders. * * If you want to change these values so that their product is no longer a * power of 2, re-visit the calculation in ctl_init_page_index(). You may * need to make it a bit more complicated to get the number of cylinders * right. */ #define CTL_DEFAULT_SECTORS_PER_TRACK 256 #define CTL_DEFAULT_HEADS 128 #define CTL_DEFAULT_ROTATION_RATE 10000 struct ctl_page_index; typedef int ctl_modesen_handler(struct ctl_scsiio *ctsio, struct ctl_page_index *page_index, int pc); typedef int ctl_modesel_handler(struct ctl_scsiio *ctsio, struct ctl_page_index *page_index, uint8_t *page_ptr); typedef enum { CTL_PAGE_FLAG_NONE = 0x00, CTL_PAGE_FLAG_DISK_ONLY = 0x01 } ctl_page_flags; struct ctl_page_index { uint8_t page_code; uint8_t subpage; uint16_t page_len; uint8_t *page_data; ctl_page_flags page_flags; ctl_modesen_handler *sense_handler; ctl_modesel_handler *select_handler; }; #define CTL_PAGE_CURRENT 0x00 #define CTL_PAGE_CHANGEABLE 0x01 #define CTL_PAGE_DEFAULT 0x02 #define CTL_PAGE_SAVED 0x03 static const struct ctl_page_index page_index_template[] = { {SMS_FORMAT_DEVICE_PAGE, 0, sizeof(struct scsi_format_page), NULL, CTL_PAGE_FLAG_DISK_ONLY, NULL, NULL}, {SMS_RIGID_DISK_PAGE, 0, sizeof(struct scsi_rigid_disk_page), NULL, CTL_PAGE_FLAG_DISK_ONLY, NULL, NULL}, {SMS_CACHING_PAGE, 0, sizeof(struct scsi_caching_page), NULL, CTL_PAGE_FLAG_DISK_ONLY, NULL, NULL}, {SMS_CONTROL_MODE_PAGE, 0, sizeof(struct scsi_control_page), NULL, CTL_PAGE_FLAG_NONE, NULL, ctl_control_page_handler}, {SMS_VENDOR_SPECIFIC_PAGE | SMPH_SPF, PWR_SUBPAGE_CODE, sizeof(struct copan_power_subpage), NULL, CTL_PAGE_FLAG_NONE, ctl_power_sp_sense_handler, ctl_power_sp_handler}, {SMS_VENDOR_SPECIFIC_PAGE | SMPH_SPF, APS_SUBPAGE_CODE, sizeof(struct copan_aps_subpage), NULL, CTL_PAGE_FLAG_NONE, NULL, ctl_aps_sp_handler}, {SMS_VENDOR_SPECIFIC_PAGE | SMPH_SPF, DBGCNF_SUBPAGE_CODE, sizeof(struct copan_debugconf_subpage), NULL, CTL_PAGE_FLAG_NONE, ctl_debugconf_sp_sense_handler, ctl_debugconf_sp_select_handler}, }; #define CTL_NUM_MODE_PAGES sizeof(page_index_template)/ \ sizeof(page_index_template[0]) struct ctl_mode_pages { struct scsi_format_page format_page[4]; struct scsi_rigid_disk_page rigid_disk_page[4]; struct scsi_caching_page caching_page[4]; struct scsi_control_page control_page[4]; struct copan_power_subpage power_subpage[4]; struct copan_aps_subpage aps_subpage[4]; struct copan_debugconf_subpage debugconf_subpage[4]; struct ctl_page_index index[CTL_NUM_MODE_PAGES]; }; struct ctl_pending_sense { ctl_ua_type ua_pending; struct scsi_sense_data sense; }; struct ctl_lun_delay_info { ctl_delay_type datamove_type; uint32_t datamove_delay; ctl_delay_type done_type; uint32_t done_delay; }; typedef enum { CTL_ERR_INJ_NONE = 0x00, CTL_ERR_INJ_ABORTED = 0x01 } ctl_err_inject_flags; typedef enum { CTL_PR_FLAG_NONE = 0x00, CTL_PR_FLAG_REGISTERED = 0x01, CTL_PR_FLAG_ACTIVE_RES = 0x02 } ctl_per_res_flags; struct ctl_per_res_info { struct scsi_per_res_key res_key; uint8_t registered; }; #define CTL_PR_ALL_REGISTRANTS 0xFFFF #define CTL_PR_NO_RESERVATION 0xFFF0 /* * For report target port groups. */ #define NUM_TARGET_PORT_GROUPS 2 #define NUM_PORTS_PER_GRP 2 struct ctl_lun { struct mtx lun_lock; struct ctl_id target; uint64_t lun; ctl_lun_flags flags; STAILQ_HEAD(,ctl_error_desc) error_list; uint64_t error_serial; struct ctl_softc *ctl_softc; struct ctl_be_lun *be_lun; struct ctl_backend_driver *backend; int io_count; struct ctl_lun_delay_info delay_info; int sync_interval; int sync_count; TAILQ_HEAD(ctl_ooaq, ctl_io_hdr) ooa_queue; TAILQ_HEAD(ctl_blockq,ctl_io_hdr) blocked_queue; STAILQ_ENTRY(ctl_lun) links; STAILQ_ENTRY(ctl_lun) run_links; struct ctl_nexus rsv_nexus; uint32_t have_ca[CTL_MAX_INITIATORS >> 5]; struct ctl_pending_sense pending_sense[CTL_MAX_INITIATORS]; struct ctl_mode_pages mode_pages; struct ctl_lun_io_stats stats; struct ctl_per_res_info per_res[2*CTL_MAX_INITIATORS]; unsigned int PRGeneration; int pr_key_count; uint16_t pr_res_idx; uint8_t res_type; uint8_t write_buffer[524288]; }; typedef enum { CTL_FLAG_TASK_PENDING = 0x01, CTL_FLAG_REAL_SYNC = 0x02, CTL_FLAG_MASTER_SHELF = 0x04 } ctl_gen_flags; struct ctl_wwpn_iid { int in_use; uint64_t wwpn; uint32_t iid; int32_t port; }; struct ctl_softc { struct mtx ctl_lock; struct cdev *dev; int open_count; struct ctl_id target; int num_disks; int num_luns; ctl_gen_flags flags; ctl_ha_mode ha_mode; int inquiry_pq_no_lun; struct sysctl_ctx_list sysctl_ctx; struct sysctl_oid *sysctl_tree; struct ctl_ioctl_info ioctl_info; struct ctl_lun lun; struct ctl_io_pool *internal_pool; struct ctl_io_pool *emergency_pool; struct ctl_io_pool *othersc_pool; struct proc *work_thread; int targ_online; uint32_t ctl_lun_mask[CTL_MAX_LUNS >> 5]; struct ctl_lun *ctl_luns[CTL_MAX_LUNS]; struct ctl_wwpn_iid wwpn_iid[CTL_MAX_PORTS][CTL_MAX_INIT_PER_PORT]; uint32_t ctl_port_mask; uint64_t aps_locked_lun; STAILQ_HEAD(, ctl_lun) lun_list; STAILQ_HEAD(, ctl_be_lun) pending_lun_queue; STAILQ_HEAD(, ctl_io_hdr) task_queue; STAILQ_HEAD(, ctl_io_hdr) incoming_queue; STAILQ_HEAD(, ctl_io_hdr) rtr_queue; STAILQ_HEAD(, ctl_io_hdr) done_queue; STAILQ_HEAD(, ctl_io_hdr) isc_queue; uint32_t num_frontends; STAILQ_HEAD(, ctl_frontend) fe_list; struct ctl_frontend *ctl_ports[CTL_MAX_PORTS]; uint32_t num_backends; STAILQ_HEAD(, ctl_backend_driver) be_list; uint32_t num_pools; uint32_t cur_pool_id; STAILQ_HEAD(, ctl_io_pool) io_pools; time_t last_print_jiffies; uint32_t skipped_prints; }; #ifdef _KERNEL extern struct ctl_cmd_entry ctl_cmd_table[]; uint32_t ctl_get_initindex(struct ctl_nexus *nexus); int ctl_pool_create(struct ctl_softc *ctl_softc, ctl_pool_type pool_type, uint32_t total_ctl_io, struct ctl_io_pool **npool); int ctl_pool_acquire(struct ctl_io_pool *pool); int ctl_pool_invalidate(struct ctl_io_pool *pool); int ctl_pool_release(struct ctl_io_pool *pool); void ctl_pool_free(struct ctl_softc *ctl_softc, struct ctl_io_pool *pool); int ctl_scsi_release(struct ctl_scsiio *ctsio); int ctl_scsi_reserve(struct ctl_scsiio *ctsio); int ctl_start_stop(struct ctl_scsiio *ctsio); int ctl_sync_cache(struct ctl_scsiio *ctsio); int ctl_format(struct ctl_scsiio *ctsio); int ctl_write_buffer(struct ctl_scsiio *ctsio); int ctl_mode_select(struct ctl_scsiio *ctsio); int ctl_mode_sense(struct ctl_scsiio *ctsio); int ctl_read_capacity(struct ctl_scsiio *ctsio); int ctl_service_action_in(struct ctl_scsiio *ctsio); int ctl_read_write(struct ctl_scsiio *ctsio); int ctl_report_luns(struct ctl_scsiio *ctsio); int ctl_request_sense(struct ctl_scsiio *ctsio); int ctl_tur(struct ctl_scsiio *ctsio); int ctl_inquiry(struct ctl_scsiio *ctsio); int ctl_persistent_reserve_in(struct ctl_scsiio *ctsio); int ctl_persistent_reserve_out(struct ctl_scsiio *ctsio); int ctl_maintenance_in(struct ctl_scsiio *ctsio); void ctl_done_lock(union ctl_io *io, int have_lock); int ctl_isc(struct ctl_scsiio *ctsio); #endif /* _KERNEL */ #endif /* _CTL_PRIVATE_H_ */ /* * vim: ts=8 */
ttungl/Coding-Interview-Challenge
source-code/Maximum Depth of Binary Tree 104.py
<reponame>ttungl/Coding-Interview-Challenge # 104. Maximum Depth of Binary Tree # <EMAIL> # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ # sol 1: recursion (DFS) # time O(logn); space O(n) # runtime: 86ms # -- if not root: return 0 return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) # sol 2 # BFS iterative # runtime: 76ms if not root: return 0 res, queue = 0, [root] # node,depth while queue: queue = [leaf for i in queue for leaf in (i.left, i.right) if leaf] res += 1 return res # sol 2: iterative (BFS) using stack for level order # count the number of level in binary tree # runtime: 48ms # -- if not root: return 0 stack, level = [root], 0 # count the level while stack: next = [] # next level while stack: top = stack.pop() if top.left: next.append(top.left) if top.right: next.append(top.right) stack = next level+=1 return level # sol 3: iterative using queue for level order # runtime: 43ms # -- if not root: return 0 queue, level = collections.deque([root]), 0 while queue: next = collections.deque() # next level while queue: head = queue.popleft() # return an element from left side of deque. (head/tail of queue) if head.left: next.append(head.left) if head.right: next.append(head.right) queue = next level+=1 return level
cool112/game
src/main/java/com/garowing/gameexp/game/rts/skill/script/effect/trigger/BlockEffectTriggerPrototype.java
<filename>src/main/java/com/garowing/gameexp/game/rts/skill/script/effect/trigger/BlockEffectTriggerPrototype.java<gh_stars>0 package com.garowing.gameexp.game.rts.skill.script.effect.trigger; import com.garowing.gameexp.game.rts.skill.constants.SkillEventType; import com.garowing.gameexp.game.rts.skill.constants.TriggerEventType; import com.garowing.gameexp.game.rts.skill.entity.EffectEntity; import com.garowing.gameexp.game.rts.skill.event.AbstractSkillEvent; import com.garowing.gameexp.game.rts.skill.model.SkillError; import com.yeto.war.module.troop.Troop; /** * 技能格挡触发器 * @author seg * */ public class BlockEffectTriggerPrototype extends AbstractEffectTriggerPrototype { @Override public SkillError handleEventImpl(AbstractSkillEvent event, EffectEntity effect, long currTime) { if(event.getEventType() != SkillEventType.ATTACK) return SkillError.ERROR_BASE_DATA_ERROR; Troop target = (Troop)event.getTarget(); target.getFightStates().setEffectBlock(true); return SkillError.SUCCESS; } @Override public TriggerEventType getEventType() { return TriggerEventType.BE_ATTACK_EVENT; } }
mikiec84/chantek
commands/bengwiki/command.py
from . import bengwiki CACHEABLE = True methods = ("define", "pagetext") arguments = { "expanded" : False, "q" : { "required" : True, "type" : str } } def run(args, method): if method == "define": return bengwiki.define(args["q"], expanded = args["expanded"]) elif method == "pagetext": return bengwiki.pagetext(args["q"])
donmccaughey/fiends_and_fortune
src/magic/spell.c
<reponame>donmccaughey/fiends_and_fortune #include "spell.h" #include <assert.h> #include <stddef.h> #include <base/base.h> #include <mechanics/mechanics.h> char const * spell_determine(struct rnd *rnd, enum spell_type spell_type, int spell_level) { assert(spell_level >= 1); assert(spell_level <= (spell_type == spell_type_magic_user ? 9 : 7)); struct { enum spell_type type; int level; char const *name; } const spells_table[] = { { spell_type_clerical, 1, "bless" }, { spell_type_clerical, 1, "command" }, { spell_type_clerical, 1, "create water" }, { spell_type_clerical, 1, "cure light wounds" }, { spell_type_clerical, 1, "detect evil" }, { spell_type_clerical, 1, "detect magic" }, { spell_type_clerical, 1, "light" }, { spell_type_clerical, 1, "protection from evil" }, { spell_type_clerical, 1, "purify food & drink" }, { spell_type_clerical, 1, "remove fear" }, { spell_type_clerical, 1, "resist cold" }, { spell_type_clerical, 1, "sanctuary" }, { spell_type_clerical, 2, "augury" }, { spell_type_clerical, 2, "chant" }, { spell_type_clerical, 2, "detect charm" }, { spell_type_clerical, 2, "find traps" }, { spell_type_clerical, 2, "hold person" }, { spell_type_clerical, 2, "know alignment" }, { spell_type_clerical, 2, "resist fire" }, { spell_type_clerical, 2, "silence 15' radius" }, { spell_type_clerical, 2, "slow poison" }, { spell_type_clerical, 2, "snake charm" }, { spell_type_clerical, 2, "speak with animals" }, { spell_type_clerical, 2, "spiritual hammer" }, { spell_type_clerical, 3, "animate dead" }, { spell_type_clerical, 3, "continual light" }, { spell_type_clerical, 3, "create food & water" }, { spell_type_clerical, 3, "cure blindness" }, { spell_type_clerical, 3, "cure disease" }, { spell_type_clerical, 3, "dispel magic" }, { spell_type_clerical, 3, "feign death" }, { spell_type_clerical, 3, "glyph of warding" }, { spell_type_clerical, 3, "locate object" }, { spell_type_clerical, 3, "prayer" }, { spell_type_clerical, 3, "remove curse" }, { spell_type_clerical, 3, "speak with dead" }, { spell_type_clerical, 4, "cure serious wounds" }, { spell_type_clerical, 4, "detect lie" }, { spell_type_clerical, 4, "divination" }, { spell_type_clerical, 4, "exorcise" }, { spell_type_clerical, 4, "lower water" }, { spell_type_clerical, 4, "neutralize poison" }, { spell_type_clerical, 4, "protection from evil 10' radius" }, { spell_type_clerical, 4, "speak with plants" }, { spell_type_clerical, 4, "sticks to snakes" }, { spell_type_clerical, 4, "tongues" }, { spell_type_clerical, 5, "atonement" }, { spell_type_clerical, 5, "commune" }, { spell_type_clerical, 5, "cure critical wounds" }, { spell_type_clerical, 5, "dispel evil" }, { spell_type_clerical, 5, "flame strike" }, { spell_type_clerical, 5, "insect plague" }, { spell_type_clerical, 5, "plane shift" }, { spell_type_clerical, 5, "quest" }, { spell_type_clerical, 5, "raise dead" }, { spell_type_clerical, 5, "true seeing" }, { spell_type_clerical, 6, "aerial servant" }, { spell_type_clerical, 6, "animate object" }, { spell_type_clerical, 6, "blade barrier" }, { spell_type_clerical, 6, "conjure animals" }, { spell_type_clerical, 6, "find the path" }, { spell_type_clerical, 6, "heal" }, { spell_type_clerical, 6, "part water" }, { spell_type_clerical, 6, "speak with monsters" }, { spell_type_clerical, 6, "stone tell" }, { spell_type_clerical, 6, "word of recall" }, { spell_type_clerical, 7, "astral spell" }, { spell_type_clerical, 7, "control weather" }, { spell_type_clerical, 7, "earthquake" }, { spell_type_clerical, 7, "gate" }, { spell_type_clerical, 7, "holy (unholy) word" }, { spell_type_clerical, 7, "regenerate" }, { spell_type_clerical, 7, "restoration" }, { spell_type_clerical, 7, "resurrection" }, { spell_type_clerical, 7, "symbol" }, { spell_type_clerical, 7, "wind walk" }, { spell_type_drudical, 1, "animal friendship" }, { spell_type_drudical, 1, "detect magic" }, { spell_type_drudical, 1, "detect snares & pits" }, { spell_type_drudical, 1, "entangle" }, { spell_type_drudical, 1, "faerie fire" }, { spell_type_drudical, 1, "invisibility to animals" }, { spell_type_drudical, 1, "locate animals" }, { spell_type_drudical, 1, "pass without trace" }, { spell_type_drudical, 1, "predict weather" }, { spell_type_drudical, 1, "purify water" }, { spell_type_drudical, 1, "shillelagh" }, { spell_type_drudical, 1, "speak with animals" }, { spell_type_drudical, 2, "barkskin" }, { spell_type_drudical, 2, "charm person or mammal" }, { spell_type_drudical, 2, "create water" }, { spell_type_drudical, 2, "cure light wounds" }, { spell_type_drudical, 2, "feign death" }, { spell_type_drudical, 2, "fire trap" }, { spell_type_drudical, 2, "heat metal" }, { spell_type_drudical, 2, "locate plants" }, { spell_type_drudical, 2, "obscurement" }, { spell_type_drudical, 2, "produce flame" }, { spell_type_drudical, 2, "trip" }, { spell_type_drudical, 2, "warp wood" }, { spell_type_drudical, 3, "call lightning" }, { spell_type_drudical, 3, "cure disease" }, { spell_type_drudical, 3, "hold animal" }, { spell_type_drudical, 3, "neutralize poison" }, { spell_type_drudical, 3, "plant growth" }, { spell_type_drudical, 3, "protection from fire" }, { spell_type_drudical, 3, "pyrotechnics" }, { spell_type_drudical, 3, "snare" }, { spell_type_drudical, 3, "stone shape" }, { spell_type_drudical, 3, "summon insects" }, { spell_type_drudical, 3, "tree" }, { spell_type_drudical, 3, "water breathing" }, { spell_type_drudical, 4, "animal summoning I" }, { spell_type_drudical, 4, "call woodland beings" }, { spell_type_drudical, 4, "control temperature 10' radius" }, { spell_type_drudical, 4, "cure serious wounds" }, { spell_type_drudical, 4, "dispel magic" }, { spell_type_drudical, 4, "hallucinatory forest" }, { spell_type_drudical, 4, "hold plant" }, { spell_type_drudical, 4, "plant door" }, { spell_type_drudical, 4, "produce fire" }, { spell_type_drudical, 4, "protection from lightning" }, { spell_type_drudical, 4, "repel insects" }, { spell_type_drudical, 4, "speak with plants" }, { spell_type_drudical, 5, "animal growth" }, { spell_type_drudical, 5, "animal summoning II" }, { spell_type_drudical, 5, "anti-plant shell" }, { spell_type_drudical, 5, "commune with nature" }, { spell_type_drudical, 5, "control winds" }, { spell_type_drudical, 5, "insect plague" }, { spell_type_drudical, 5, "pass plant" }, { spell_type_drudical, 5, "sticks to snakes" }, { spell_type_drudical, 5, "transmute rock to mud" }, { spell_type_drudical, 5, "wall of fire" }, { spell_type_drudical, 6, "animal summoning III" }, { spell_type_drudical, 6, "anti-animal shell" }, { spell_type_drudical, 6, "conjure fire elemental" }, { spell_type_drudical, 6, "cure critical wounds" }, { spell_type_drudical, 6, "feeblemind" }, { spell_type_drudical, 6, "fire seeds" }, { spell_type_drudical, 6, "transport via plants" }, { spell_type_drudical, 6, "turn wood" }, { spell_type_drudical, 6, "wall of thorns" }, { spell_type_drudical, 6, "weather summoning" }, { spell_type_drudical, 7, "animate rock" }, { spell_type_drudical, 7, "chariot of Sustarre" }, { spell_type_drudical, 7, "confusion" }, { spell_type_drudical, 7, "conjure earth elemental" }, { spell_type_drudical, 7, "control weather" }, { spell_type_drudical, 7, "creeping doom" }, { spell_type_drudical, 7, "finger of death" }, { spell_type_drudical, 7, "fire storm" }, { spell_type_drudical, 7, "reincarnate" }, { spell_type_drudical, 7, "transmute metal to wood" }, { spell_type_magic_user, 1, "affect normal fires" }, { spell_type_magic_user, 1, "burning hands" }, { spell_type_magic_user, 1, "charm person" }, { spell_type_magic_user, 1, "comprehend languages" }, { spell_type_magic_user, 1, "dancing lights" }, { spell_type_magic_user, 1, "detect magic" }, { spell_type_magic_user, 1, "enlarge" }, { spell_type_magic_user, 1, "erase" }, { spell_type_magic_user, 1, "feather fall" }, { spell_type_magic_user, 1, "find familiar" }, { spell_type_magic_user, 1, "friends" }, { spell_type_magic_user, 1, "hold portal" }, { spell_type_magic_user, 1, "identify" }, { spell_type_magic_user, 1, "jump" }, { spell_type_magic_user, 1, "light" }, { spell_type_magic_user, 1, "magic missile" }, { spell_type_magic_user, 1, "mending" }, { spell_type_magic_user, 1, "message" }, { spell_type_magic_user, 1, "Nystul's magic aura" }, { spell_type_magic_user, 1, "protection from evil" }, { spell_type_magic_user, 1, "push" }, { spell_type_magic_user, 1, "read magic" }, { spell_type_magic_user, 1, "shield" }, { spell_type_magic_user, 1, "shocking grasp" }, { spell_type_magic_user, 1, "sleep" }, { spell_type_magic_user, 1, "spider climb" }, { spell_type_magic_user, 1, "Tenser's floating disc" }, { spell_type_magic_user, 1, "unseen servant" }, { spell_type_magic_user, 1, "ventriloquism" }, { spell_type_magic_user, 1, "write" }, { spell_type_magic_user, 2, "audible glamer" }, { spell_type_magic_user, 2, "continual light" }, { spell_type_magic_user, 2, "darkness 15' radius" }, { spell_type_magic_user, 2, "detect evil" }, { spell_type_magic_user, 2, "detect invisibility" }, { spell_type_magic_user, 2, "ESP" }, { spell_type_magic_user, 2, "fools gold" }, { spell_type_magic_user, 2, "forget" }, { spell_type_magic_user, 2, "invisibility" }, { spell_type_magic_user, 2, "knock" }, { spell_type_magic_user, 2, "Leomund's trap" }, { spell_type_magic_user, 2, "levitate" }, { spell_type_magic_user, 2, "locate object" }, { spell_type_magic_user, 2, "magic mouth" }, { spell_type_magic_user, 2, "mirror image" }, { spell_type_magic_user, 2, "pyrotechnics" }, { spell_type_magic_user, 2, "ray of enfeeblement" }, { spell_type_magic_user, 2, "rope trick" }, { spell_type_magic_user, 2, "scare" }, { spell_type_magic_user, 2, "shatter" }, { spell_type_magic_user, 2, "stinking cloud" }, { spell_type_magic_user, 2, "strength" }, { spell_type_magic_user, 2, "web" }, { spell_type_magic_user, 2, "wizard lock" }, { spell_type_magic_user, 3, "blink" }, { spell_type_magic_user, 3, "clairaudience" }, { spell_type_magic_user, 3, "clairvoyance" }, { spell_type_magic_user, 3, "dispel magic" }, { spell_type_magic_user, 3, "explosive runes" }, { spell_type_magic_user, 3, "feign death" }, { spell_type_magic_user, 3, "fireball" }, { spell_type_magic_user, 3, "flame arrow" }, { spell_type_magic_user, 3, "fly" }, { spell_type_magic_user, 3, "gust of wind" }, { spell_type_magic_user, 3, "haste" }, { spell_type_magic_user, 3, "hold person" }, { spell_type_magic_user, 3, "infravision" }, { spell_type_magic_user, 3, "invisibility 10' radius" }, { spell_type_magic_user, 3, "Leomund's tiny hut" }, { spell_type_magic_user, 3, "lightning bolt" }, { spell_type_magic_user, 3, "monster summoning I" }, { spell_type_magic_user, 3, "phantasmal force" }, { spell_type_magic_user, 3, "protection from evil 10' radius" }, { spell_type_magic_user, 3, "protection from normal missiles" }, { spell_type_magic_user, 3, "slow" }, { spell_type_magic_user, 3, "suggestion" }, { spell_type_magic_user, 3, "tongues" }, { spell_type_magic_user, 3, "water breathing" }, { spell_type_magic_user, 4, "charm monster" }, { spell_type_magic_user, 4, "confusion" }, { spell_type_magic_user, 4, "dig" }, { spell_type_magic_user, 4, "dimension door" }, { spell_type_magic_user, 4, "enchanted weapon" }, { spell_type_magic_user, 4, "extension I" }, { spell_type_magic_user, 4, "fear" }, { spell_type_magic_user, 4, "fire charm" }, { spell_type_magic_user, 4, "fire shield" }, { spell_type_magic_user, 4, "fire trap" }, { spell_type_magic_user, 4, "fumble" }, { spell_type_magic_user, 4, "hallucinatory terrain" }, { spell_type_magic_user, 4, "ice storm" }, { spell_type_magic_user, 4, "massmorph" }, { spell_type_magic_user, 4, "minor globe of invulnerability" }, { spell_type_magic_user, 4, "monster summoning II" }, { spell_type_magic_user, 4, "plant growth" }, { spell_type_magic_user, 4, "polymorph other" }, { spell_type_magic_user, 4, "polymorph self" }, { spell_type_magic_user, 4, "Rary's mnemonic enhancer" }, { spell_type_magic_user, 4, "remove curse" }, { spell_type_magic_user, 4, "wall of fire" }, { spell_type_magic_user, 4, "wall if ice" }, { spell_type_magic_user, 4, "wizard eye" }, { spell_type_magic_user, 5, "airy water" }, { spell_type_magic_user, 5, "animal growth" }, { spell_type_magic_user, 5, "animate dead" }, { spell_type_magic_user, 5, "Bigby's interposing hand" }, { spell_type_magic_user, 5, "cloudkill" }, { spell_type_magic_user, 5, "conjure elemental" }, { spell_type_magic_user, 5, "cone of cold" }, { spell_type_magic_user, 5, "contact other plane" }, { spell_type_magic_user, 5, "distance distortion" }, { spell_type_magic_user, 5, "extension II" }, { spell_type_magic_user, 5, "feeblemind" }, { spell_type_magic_user, 5, "hold monster" }, { spell_type_magic_user, 5, "Leomund's secret chest" }, { spell_type_magic_user, 5, "magic jar" }, { spell_type_magic_user, 5, "monster summoning III" }, { spell_type_magic_user, 5, "Mordenkainen's faithful hound" }, { spell_type_magic_user, 5, "passwall" }, { spell_type_magic_user, 5, "stone shape" }, { spell_type_magic_user, 5, "telekinesis" }, { spell_type_magic_user, 5, "teleport" }, { spell_type_magic_user, 5, "transmute rock to mud" }, { spell_type_magic_user, 5, "wall of force" }, { spell_type_magic_user, 5, "wall of iron" }, { spell_type_magic_user, 5, "wall of stone" }, { spell_type_magic_user, 6, "anti-magic shell" }, { spell_type_magic_user, 6, "Bigby's forceful hand" }, { spell_type_magic_user, 6, "control weather" }, { spell_type_magic_user, 6, "death spell" }, { spell_type_magic_user, 6, "disintegrate" }, { spell_type_magic_user, 6, "enchant an item" }, { spell_type_magic_user, 6, "extension III" }, { spell_type_magic_user, 6, "geas" }, { spell_type_magic_user, 6, "glassee" }, { spell_type_magic_user, 6, "globe of invulnerability" }, { spell_type_magic_user, 6, "guards and wards" }, { spell_type_magic_user, 6, "invisible stalker" }, { spell_type_magic_user, 6, "legend lore" }, { spell_type_magic_user, 6, "lower water" }, { spell_type_magic_user, 6, "monster summoning IV" }, { spell_type_magic_user, 6, "move earth" }, { spell_type_magic_user, 6, "Otiluke's freezing sphere" }, { spell_type_magic_user, 6, "part water" }, { spell_type_magic_user, 6, "project image" }, { spell_type_magic_user, 6, "reincarnation" }, { spell_type_magic_user, 6, "repulsion" }, { spell_type_magic_user, 6, "spiritwrack" }, { spell_type_magic_user, 6, "stone to flesh" }, { spell_type_magic_user, 6, "Tenser's transformation" }, { spell_type_magic_user, 7, "Bigby's grasping hand" }, { spell_type_magic_user, 7, "cacodemon" }, { spell_type_magic_user, 7, "charm plants" }, { spell_type_magic_user, 7, "delayed blast fireball" }, { spell_type_magic_user, 7, "Drawmij's instant summons" }, { spell_type_magic_user, 7, "duo-dimension" }, { spell_type_magic_user, 7, "limited wish" }, { spell_type_magic_user, 7, "mass invisibility" }, { spell_type_magic_user, 7, "monster summoning V" }, { spell_type_magic_user, 7, "Mordenkainen's sword" }, { spell_type_magic_user, 7, "phase door" }, { spell_type_magic_user, 7, "power word, stun" }, { spell_type_magic_user, 7, "reverse gravity" }, { spell_type_magic_user, 7, "simulacrum" }, { spell_type_magic_user, 7, "statue" }, { spell_type_magic_user, 7, "vanish" }, { spell_type_magic_user, 8, "antipathy/sympathy" }, { spell_type_magic_user, 8, "Bigby's clenched fist" }, { spell_type_magic_user, 8, "clone" }, { spell_type_magic_user, 8, "glassteel" }, { spell_type_magic_user, 8, "incendiary cloud" }, { spell_type_magic_user, 8, "mass charm" }, { spell_type_magic_user, 8, "maze" }, { spell_type_magic_user, 8, "mind blank" }, { spell_type_magic_user, 8, "monster summoning VI" }, { spell_type_magic_user, 8, "Otto's irresistible dance" }, { spell_type_magic_user, 8, "permanency" }, { spell_type_magic_user, 8, "polymorph any object" }, { spell_type_magic_user, 8, "power word, blind" }, { spell_type_magic_user, 8, "Serten's spell immunity" }, { spell_type_magic_user, 8, "symbol" }, { spell_type_magic_user, 8, "trap the soul" }, { spell_type_magic_user, 9, "astral spell" }, { spell_type_magic_user, 9, "Bigby's crushing hand" }, { spell_type_magic_user, 9, "gate" }, { spell_type_magic_user, 9, "imprisonment" }, { spell_type_magic_user, 9, "meteor swarm" }, { spell_type_magic_user, 9, "monster summoning VII" }, { spell_type_magic_user, 9, "power word, kill" }, { spell_type_magic_user, 9, "prismatic sphere" }, { spell_type_magic_user, 9, "shape change" }, { spell_type_magic_user, 9, "temporal stasis" }, { spell_type_magic_user, 9, "time stop" }, { spell_type_magic_user, 9, "wish" }, { spell_type_illusionist, 1, "audible glamer" }, { spell_type_illusionist, 1, "change self" }, { spell_type_illusionist, 1, "color spray" }, { spell_type_illusionist, 1, "dancing lights" }, { spell_type_illusionist, 1, "darkness" }, { spell_type_illusionist, 1, "detect illusion" }, { spell_type_illusionist, 1, "detect invisibility" }, { spell_type_illusionist, 1, "gaze reflection" }, { spell_type_illusionist, 1, "hypnotism" }, { spell_type_illusionist, 1, "light" }, { spell_type_illusionist, 1, "phantasmal force" }, { spell_type_illusionist, 1, "wall of fog" }, { spell_type_illusionist, 2, "blindness" }, { spell_type_illusionist, 2, "blur" }, { spell_type_illusionist, 2, "deafness" }, { spell_type_illusionist, 2, "detect magic" }, { spell_type_illusionist, 2, "fog cloud" }, { spell_type_illusionist, 2, "hypnotic pattern" }, { spell_type_illusionist, 2, "improved phantasmal force" }, { spell_type_illusionist, 2, "invisibility" }, { spell_type_illusionist, 2, "magic mouth" }, { spell_type_illusionist, 2, "mirror image" }, { spell_type_illusionist, 2, "misdirection" }, { spell_type_illusionist, 2, "ventriloquism" }, { spell_type_illusionist, 3, "continual darkness" }, { spell_type_illusionist, 3, "continual light" }, { spell_type_illusionist, 3, "dispel illusion" }, { spell_type_illusionist, 3, "fear" }, { spell_type_illusionist, 3, "hallucinatory terrain" }, { spell_type_illusionist, 3, "illusionary script" }, { spell_type_illusionist, 3, "invisibility 10' radius" }, { spell_type_illusionist, 3, "non-detection" }, { spell_type_illusionist, 3, "paralyzation" }, { spell_type_illusionist, 3, "rope trick" }, { spell_type_illusionist, 3, "spectral force" }, { spell_type_illusionist, 3, "suggestion" }, { spell_type_illusionist, 4, "confusion" }, { spell_type_illusionist, 4, "dispel exhaustion" }, { spell_type_illusionist, 4, "emotion" }, { spell_type_illusionist, 4, "improved invisibility" }, { spell_type_illusionist, 4, "massmorph" }, { spell_type_illusionist, 4, "minor creation" }, { spell_type_illusionist, 4, "phantasmal killer" }, { spell_type_illusionist, 4, "shadow monsters" }, { spell_type_illusionist, 5, "chaos" }, { spell_type_illusionist, 5, "demi-shadow monsters" }, { spell_type_illusionist, 5, "major creation" }, { spell_type_illusionist, 5, "maze" }, { spell_type_illusionist, 5, "projected image" }, { spell_type_illusionist, 5, "shadow door" }, { spell_type_illusionist, 5, "shadow magic" }, { spell_type_illusionist, 5, "summon shadow" }, { spell_type_illusionist, 6, "conjure animals" }, { spell_type_illusionist, 6, "demi-shadow magic" }, { spell_type_illusionist, 6, "mass suggestion" }, { spell_type_illusionist, 6, "permanent illusion" }, { spell_type_illusionist, 6, "programmed illusion" }, { spell_type_illusionist, 6, "shades" }, { spell_type_illusionist, 6, "true sight" }, { spell_type_illusionist, 6, "veil" }, { spell_type_illusionist, 7, "alter reality" }, { spell_type_illusionist, 7, "astral spell" }, { spell_type_illusionist, 7, "prismatic spray" }, { spell_type_illusionist, 7, "prismatic wall" }, { spell_type_illusionist, 7, "vision" } }; size_t const spells_table_count = ARRAY_COUNT(spells_table); int total = 0; for (int i = 0; i < spells_table_count; ++i) { if ( spells_table[i].type == spell_type && spells_table[i].level == spell_level) { ++total; } } assert(total); int score = dice_roll(dice_make(1, total), rnd, NULL); int range = 0; for (int i = 0; i < spells_table_count; ++i) { if ( spells_table[i].type == spell_type && spells_table[i].level == spell_level) { ++range; if (score <= range) return spells_table[i].name; } } fail("Did not match table entry (score=%i, range=%i)", score, range); return "(spell)"; }
haibowen/AndroidStudy
MyTest002/app/src/main/java/activity/ListViewActivity.java
<filename>MyTest002/app/src/main/java/activity/ListViewActivity.java<gh_stars>0 package activity; import android.content.BroadcastReceiver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import com.example.mytest002.R; import db.MySqlDatabase; public class ListViewActivity extends AppCompatActivity { private IntentFilter intentFilter; private static final String TAG = "ListViewActivity"; private ListView listView; private Button buttondb; private MySqlDatabase mySqlDatabase; private Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list_view); buttondb=findViewById(R.id.bt_createdb); mySqlDatabase=new MySqlDatabase(this,"TEST.db",null,1); buttondb.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mySqlDatabase.getWritableDatabase(); SQLiteDatabase db=mySqlDatabase.getWritableDatabase(); ContentValues contentValues=new ContentValues(); contentValues.put("name","The Da Vinci Code"); contentValues.put("author","haibo"); contentValues.put("pages","222"); db.insert("book",null,contentValues); } }); insert(); QueryBook(); intentFilter=new IntentFilter(); intentFilter.addAction("android.net.haibowen"); registerReceiver(mybroad,intentFilter); //listView.invalidateViews(); } private void QueryBook() { handler=new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { SQLiteDatabase db =mySqlDatabase.getWritableDatabase(); db.rawQuery("select * from book",null); Toast.makeText(ListViewActivity.this,"已经查询了",Toast.LENGTH_SHORT).show(); Log.e(TAG, "run: "+db.rawQuery("select * from book",null)); } },5000); } private void insert() { handler=new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { SQLiteDatabase db=mySqlDatabase.getWritableDatabase(); db.execSQL("insert into book (name, author,pages,price) values(?,?,?,?)",new String[] {"haibo","cool","333","78.34"}); Toast.makeText(ListViewActivity.this,"已经插入了",Toast.LENGTH_SHORT).show(); } },3000); } private BroadcastReceiver mybroad=new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.e(TAG, "onReceive: "+intent.getAction() ); if (intent.getAction().equals("android.net.haibowen")){ Toast.makeText(context,"收到海波的广播了",Toast.LENGTH_LONG).show(); }else { Toast.makeText(context,"没有收到广播",Toast.LENGTH_LONG).show(); } } }; @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mybroad); } }
zhangwei217245/Lego
Meshwork/src/main/java/mr/x/meshwork/edge/EdgeBizFilter.java
package mr.x.meshwork.edge; /** * Created by zhangwei on 14-4-2. * @author zhangwei */ public interface EdgeBizFilter<V> { public boolean accept(Edge edge); public V value(); }
tommorse/nrn
src/nrniv/rotate3d.cpp
#include <../../nrnconf.h> #if HAVE_IV // to end of file #include <math.h> #include <InterViews/canvas.h> #include <IV-look/kit.h> #include <InterViews/font.h> #include <InterViews/polyglyph.h> #include "rot3band.h" #include <stdio.h> #include "nrnoc2iv.h" #include "shape.h" #include "ivoc.h" #define Rotate_ "Rotate3D PlotShape" Rotation3d::Rotation3d() { identity(); int i, j; for (i=0; i < 2; ++i) for (j=0; j < 3; ++j) o_[i][j] = 0.; } Rotation3d::~Rotation3d() {} void Rotation3d::identity(){ int i, j; for (i=0; i < 3; ++i) { for (j=0; j < 3; ++j) { a_[i][j] = 0.; } a_[i][i] = 1.; } } void Rotation3d::rotate_x(float radian){ Rotation3d m; m.a_[1][1] = m.a_[2][2] = cos(radian); m.a_[2][1] = - (m.a_[1][2] = sin(radian)); post_multiply(m); } void Rotation3d::rotate_y(float radian){ Rotation3d m; m.a_[2][2] = m.a_[0][0] = cos(radian); m.a_[2][0] = - (m.a_[0][2] = sin(radian)); post_multiply(m); } void Rotation3d::rotate_z(float radian){ Rotation3d m; m.a_[0][0] = m.a_[1][1] = cos(radian); m.a_[1][0] = - (m.a_[0][1] = sin(radian)); post_multiply(m); } void Rotation3d::post_multiply(Rotation3d& m) { // r = m*r float x[3][3]; int i, j, k; for (i=0; i < 3; ++i) { for (j=0; j < 3; ++j) { x[i][j] = 0; for (k=0; k < 3; ++k) { x[i][j] += m.a_[i][k]*a_[k][j]; } } } for (i=0; i < 3; ++i) { for (j=0; j < 3; ++j) { a_[i][j] = x[i][j]; } } } void Rotation3d::rotate(float x, float y, float z, float* tr) const { float r[3]; r[0] = x; r[1] = y; r[2] = z; rotate(r, tr); } void Rotation3d::rotate(float* r, float* tr) const { int i; float x[3]; for (i=0; i < 3; ++i) { x[i] = r[i] - o_[0][i]; } for (i=0; i < 3; ++i) { tr[i] = a_[i][0]*x[0] + a_[i][1]*x[1] + a_[i][2]*x[2] + o_[1][i]; } } void Rotation3d::origin(float x, float y, float z) { o_[0][0] = x; o_[0][1] = y; o_[0][2] = z; } void Rotation3d::offset(float x, float y) { o_[1][0] = x; o_[1][1] = y; o_[1][2] = 0.; } void Rotation3d::x_axis(float& x, float& y) const { x = a_[0][0]; y = a_[1][0]; } void Rotation3d::y_axis(float& x, float& y) const { x = a_[0][1]; y = a_[1][1]; } void Rotation3d::z_axis(float& x, float& y) const { x = a_[0][2]; y = a_[1][2]; } void Rotation3d::inverse_rotate(float* tr, float* r) const { int i; float x[3]; for (i=0; i < 3; ++i) { x[i] = tr[i]; } for (i=0; i < 3; ++i) { r[i] = a_[0][i]*x[0] + a_[1][i]*x[1] + a_[2][i]*x[2]; } } Rotate3Band::Rotate3Band(Rotation3d* r3, RubberAction* ra, Canvas* c) : Rubberband(ra, c) { if (r3) { rot_ = r3; }else{ rot_ = new Rotation3d(); } Resource::ref(rot_); } Rotate3Band::~Rotate3Band(){ Resource::unref(rot_); } Rotation3d* Rotate3Band::rotation() { return rot_; } bool Rotate3Band::event(Event& e) { const float deg = 3.14159265358979323846/18.; if (e.type() == Event::key) { undraw(x(), y()); char buf[2]; if (e.mapkey(buf, 1) > 0) switch (buf[0]) { case 'x': rot_->identity(); rot_->rotate_y(3.14159265358979323846/2.); break; case 'y': case 'a': rot_->identity(); rot_->rotate_x(3.14159265358979323846/2.); break; case 'z': case ' ': rot_->identity(); break; case 'X': rot_->rotate_x(deg); break; case 'Y': case 'A': rot_->rotate_y(deg); break; case 'Z': rot_->rotate_z(deg); break; case 037&'x': rot_->rotate_x(-deg); break; case 037&'y': case 037&'a': rot_->rotate_y(-deg); break; case 037&'z': rot_->rotate_z(-deg); break; default: break; } draw(x(), y()); return true; }else{ return Rubberband::event(e); } } void Rotate3Band::help() { Oc::help(Rotate_); } void Rotate3Band::press(Event& e) { Canvas* c = canvas(); c->push_transform(); Transformer t; c->transformer(transformer()); XYView* v = XYView::current_pick_view(); c->fill_rect(v->left(), v->bottom(), v->right(), v->top(), Scene::default_background()); c->pop_transform(); x_old_ = x(); y_old_ = y(); ShapeScene* ss = (ShapeScene*)v->scene(); Coord x1, y1; transformer().inverse_transform(x(), y(), x1, y1); ss->nearest(x1, y1); ShapeSection* ssec = ss->selected(); Section* s = ssec->section(); // this is the point we want to stay fixed. int i = ssec->get_coord(ss->arc_selected(), x1, y1); // what is it now float r[3]; rot_->rotate(s->pt3d[i].x, s->pt3d[i].y, s->pt3d[i].z, r); rot_->origin(s->pt3d[i].x, s->pt3d[i].y, s->pt3d[i].z); rot_->offset(r[0], r[1]); } void Rotate3Band::drag(Event&) { float dx = x() - x_old_; float dy = y() - y_old_; //printf ("dx=%g dy=%g\n", dx,dy); rot_->rotate_x(dy/50); rot_->rotate_y(dx/50); x_old_ = x(); y_old_ = y(); } void Rotate3Band::draw(Coord, Coord) { Canvas* c = canvas(); const Font* f = WidgetKit::instance()->font(); float x, y; float x0, y0; c->push_transform(); c->transformer(transformer()); #if 0 hoc_Item* qsec; ForAllSections(sec) //{ #else PolyGlyph* sg = ((ShapeScene*)XYView::current_pick_view()->scene()) ->shape_section_list(); GlyphIndex cnt = sg->count(); for (GlyphIndex i=0; i < cnt; ++i) { Section* sec = ((ShapeSection*)sg->component(i))->section(); #endif if (sec->npt3d) { float r[3]; int i = 0; r[0] = sec->pt3d[i].x; r[1] = sec->pt3d[i].y; r[2] = sec->pt3d[i].z; rot_->rotate(r, r); c->move_to(r[0], r[1]); i = sec->npt3d - 1; r[0] = sec->pt3d[i].x; r[1] = sec->pt3d[i].y; r[2] = sec->pt3d[i].z; rot_->rotate(r, r); c->line_to(r[0], r[1]); c->stroke(color(), brush()); } } c->pop_transform(); x0 = x_begin(); y0 = y_begin(); c->push_transform(); Transformer t; c->transformer(t); c->new_path(); Coord w = canvas()->width()/4; rot_->x_axis(x, y); //printf("x_axis %g %g\n", x, y); c->line(x0, y0, x0+x*w, y0+y*w, color(), brush()); #ifndef WIN32 c->character(f, 'x', f->width('x'), color(), x0+x*w*1.1, y0+y*w*1.1); #endif rot_->y_axis(x, y); //printf("y_axis %g %g\n", x, y); c->line(x0, y0, x0+x*w, y0+y*w, color(), brush()); #ifndef WIN32 c->character(f, 'y', f->width('y'), color(), x0+x*w*1.1, y0+y*w*1.1); #endif rot_->z_axis(x, y); //printf("z_axis %g %g\n", x, y); c->line(x0, y0, x0+x*w, y0+y*w, color(), brush()); #ifndef WIN32 c->character(f, 'z', f->width('z'), color(), x0+x*w*1.1, y0+y*w*1.1); #endif c->pop_transform(); } #endif
mion00/predict-react
src/__tests__/reducers/Splits.test.js
<filename>src/__tests__/reducers/Splits.test.js /** * Created by tonis.kasekamp on 02/07/18. */ import splits from '../../reducers/Splits'; import { splitFailed, splitsFailed, splitsRequested, splitsRetrieved, splitSucceeded, submitSplit } from '../../actions/SplitActions'; const initState = {fetchState: {inFlight: false}, allIds: [], byId: {}}; describe('SplitList', () => { it('has nothing initially', () => { expect(splits(undefined, {})).toEqual(initState); }); it('changes fetchState when requesting', () => { const state = splits(undefined, splitsRequested()); expect(state).toEqual({fetchState: {inFlight: true}, allIds: [], byId: {}}); }); it('adds splits when request completed', () => { const splitList = [{id: 1, type: 'single'}]; const state = splits(undefined, splitsRequested()); const state2 = splits(state, splitsRetrieved(splitList)); expect(state2.fetchState).toEqual({inFlight: false}); const {allIds, byId} = state2; expect(allIds).toEqual([1]); expect(Object.keys(byId).length).toEqual(1); expect(byId[1].type).toBe('single'); }); it('stores error message', () => { const state = splits(undefined, splitsRequested()); const state2 = splits(state, splitsFailed('error')); expect(state2).toEqual({fetchState: {inFlight: false, error: 'error'}, allIds: [], byId: {}}); }); }); describe('Split submitting', () => { it('changes fetchState when submitted', () => { const state = splits(undefined, submitSplit()); expect(state).toEqual({allIds: [], byId: {}, fetchState: {inFlight: true}}); }); it('adds to state when submit success', () => { const splitList = [{id: 1, type: 'single'}]; const state = splits(splits(undefined, splitsRetrieved(splitList)), submitSplit()); const state2 = splits(state, splitSucceeded({id: 2, type: 'double'})); expect(state2.fetchState).toEqual({inFlight: false}); const {allIds, byId} = state2; expect(allIds).toEqual([1, 2]); expect(Object.keys(byId).length).toEqual(2); expect(byId[2].type).toBe('double'); }); it('stores error message', () => { const state = splits(undefined, submitSplit()); const state2 = splits(state, splitFailed('error')); expect(state2).toEqual({allIds: [], byId: {}, fetchState: {inFlight: false, error: 'error'}}); }); });
tuanzuo/redismanager
redismanager-core/src/main/java/com/tz/redismanager/strategy/queryvalue/handler/QueryListValueHandler.java
<reponame>tuanzuo/redismanager package com.tz.redismanager.strategy.queryvalue.handler; import com.tz.redismanager.annotation.HandlerType; import com.tz.redismanager.domain.vo.RedisValueQueryVO; import com.tz.redismanager.enm.HandlerTypeEnum; import com.tz.redismanager.strategy.queryvalue.AbstractQueryValueHandler; import com.tz.redismanager.trace.TraceLoggerFactory; import com.tz.redismanager.util.RedisContextUtils; import org.slf4j.Logger; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; /** * 查询list的value处理器 * * @author tuanzuo * @version 1.0 * @time 2019-06-23 21:33 **/ @Service @HandlerType({HandlerTypeEnum.LIST}) public class QueryListValueHandler extends AbstractQueryValueHandler { private static final Logger logger = TraceLoggerFactory.getLogger(QueryListValueHandler.class); @Override public Object handle(RedisValueQueryVO vo) { RedisTemplate<String, Object> redisTemplate = RedisContextUtils.getRedisTemplate(); Object value = null; try { value = redisTemplate.opsForList().range(vo.getSearchKey(), vo.getStart(), vo.getEnd()); if (null == value) { //重新设置keySerializer this.reSetKeySerializer(redisTemplate); value = redisTemplate.opsForList().range(vo.getSearchKey(), vo.getStart(), vo.getEnd()); } } catch (Exception e) { logger.error("{id:{}查询出错,message:{}}", vo.getId(), e.getMessage()); logger.info("{ValueSerializer从{}切换到StringRedisSerializer处理}", redisTemplate.getValueSerializer().getClass().getSimpleName()); redisTemplate.setValueSerializer(redisTemplate.getStringSerializer()); value = redisTemplate.opsForList().range(vo.getSearchKey(), vo.getStart(), vo.getEnd()); } return value; } }
lofunz/mieme
MAME4all/trunk/src/vidhrdw/wc90b.cpp
<gh_stars>10-100 #include "driver.h" #include "vidhrdw/generic.h" unsigned char *wc90b_shared; unsigned char *wc90b_tile_colorram, *wc90b_tile_videoram; unsigned char *wc90b_tile_colorram2, *wc90b_tile_videoram2; unsigned char *wc90b_scroll1xlo, *wc90b_scroll1xhi; unsigned char *wc90b_scroll2xlo, *wc90b_scroll2xhi; unsigned char *wc90b_scroll1ylo, *wc90b_scroll1yhi; unsigned char *wc90b_scroll2ylo, *wc90b_scroll2yhi; size_t wc90b_tile_videoram_size; size_t wc90b_tile_videoram_size2; static unsigned char *dirtybuffer1 = 0, *dirtybuffer2 = 0; static struct osd_bitmap *tmpbitmap1 = 0,*tmpbitmap2 = 0; int wc90b_vh_start( void ) { if ( generic_vh_start() ) return 1; if ( ( dirtybuffer1 = (unsigned char*)malloc( wc90b_tile_videoram_size ) ) == 0 ) { return 1; } memset( dirtybuffer1, 1, wc90b_tile_videoram_size ); if ( ( tmpbitmap1 = bitmap_alloc(4*Machine->drv->screen_width,2*Machine->drv->screen_height) ) == 0 ){ free( dirtybuffer1 ); generic_vh_stop(); return 1; } if ( ( dirtybuffer2 = (unsigned char*)malloc( wc90b_tile_videoram_size2 ) ) == 0 ) { bitmap_free(tmpbitmap1); free(dirtybuffer1); generic_vh_stop(); return 1; } memset( dirtybuffer2, 1, wc90b_tile_videoram_size2 ); if ( ( tmpbitmap2 = bitmap_alloc( 4*Machine->drv->screen_width,2*Machine->drv->screen_height ) ) == 0 ){ bitmap_free(tmpbitmap1); free(dirtybuffer1); free(dirtybuffer2); generic_vh_stop(); return 1; } // Free the generic bitmap and allocate one twice as wide free( tmpbitmap ); if ( ( tmpbitmap = bitmap_alloc( 2*Machine->drv->screen_width,Machine->drv->screen_height ) ) == 0 ){ bitmap_free(tmpbitmap1); bitmap_free(tmpbitmap2); free(dirtybuffer); free(dirtybuffer1); free(dirtybuffer2); generic_vh_stop(); return 1; } return 0; } void wc90b_vh_stop ( void ) { free( dirtybuffer1 ); free( dirtybuffer2 ); bitmap_free( tmpbitmap1 ); bitmap_free( tmpbitmap2 ); generic_vh_stop(); } READ_HANDLER( wc90b_tile_videoram_r ) { return wc90b_tile_videoram[offset]; } WRITE_HANDLER( wc90b_tile_videoram_w ) { if ( wc90b_tile_videoram[offset] != data ) { dirtybuffer1[offset] = 1; wc90b_tile_videoram[offset] = data; } } READ_HANDLER( wc90b_tile_colorram_r ) { return wc90b_tile_colorram[offset]; } WRITE_HANDLER( wc90b_tile_colorram_w ) { if ( wc90b_tile_colorram[offset] != data ) { dirtybuffer1[offset] = 1; wc90b_tile_colorram[offset] = data; } } READ_HANDLER( wc90b_tile_videoram2_r ) { return wc90b_tile_videoram2[offset]; } WRITE_HANDLER( wc90b_tile_videoram2_w ) { if ( wc90b_tile_videoram2[offset] != data ) { dirtybuffer2[offset] = 1; wc90b_tile_videoram2[offset] = data; } } READ_HANDLER( wc90b_tile_colorram2_r ) { return wc90b_tile_colorram2[offset]; } WRITE_HANDLER( wc90b_tile_colorram2_w ) { if ( wc90b_tile_colorram2[offset] != data ) { dirtybuffer2[offset] = 1; wc90b_tile_colorram2[offset] = data; } } READ_HANDLER( wc90b_shared_r ) { return wc90b_shared[offset]; } WRITE_HANDLER( wc90b_shared_w ) { wc90b_shared[offset] = data; } static void wc90b_draw_sprites( struct osd_bitmap *bitmap, int priority ){ int offs; /* draw all visible sprites of specified priority */ for ( offs = spriteram_size - 8;offs >= 0;offs -= 8 ){ if ( ( ~( spriteram[offs+3] >> 6 ) & 3 ) == priority ) { if ( spriteram[offs+1] > 16 ) { /* visible */ int code = ( spriteram[offs+3] & 0x3f ) << 4; int bank = spriteram[offs+0]; int flags = spriteram[offs+4]; code += ( bank & 0xf0 ) >> 4; code <<= 2; code += ( bank & 0x0f ) >> 2; drawgfx( bitmap,Machine->gfx[ 17 ], code, flags >> 4, /* color */ bank&1, /* flipx */ bank&2, /* flipy */ spriteram[offs + 2], /* sx */ 240 - spriteram[offs + 1], /* sy */ &Machine->visible_area,TRANSPARENCY_PEN,15 ); } } } } void wc90b_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh) { int offs, i; int scrollx, scrolly; /* compute palette usage */ { unsigned short palette_map[4 * 16]; int tile, gfx, cram; memset (palette_map, 0, sizeof (palette_map)); for ( offs = wc90b_tile_videoram_size2 - 1; offs >= 0; offs-- ) { tile = wc90b_tile_videoram2[offs]; cram = wc90b_tile_colorram2[offs]; gfx = 9 + ( cram & 3 ) + ( ( cram >> 1 ) & 4 ); palette_map[3*16 + (cram >> 4)] |= Machine->gfx[gfx]->pen_usage[tile]; } for ( offs = wc90b_tile_videoram_size - 1; offs >= 0; offs-- ) { tile = wc90b_tile_videoram[offs]; cram = wc90b_tile_colorram[offs]; gfx = 1 + ( cram & 3 ) + ( ( cram >> 1 ) & 4 ); palette_map[2*16 + (cram >> 4)] |= Machine->gfx[gfx]->pen_usage[tile]; } for ( offs = videoram_size - 1; offs >= 0; offs-- ) { cram = colorram[offs]; tile = videoram[offs] + ( ( cram & 0x07 ) << 8 ); palette_map[1*16 + (cram >> 4)] |= Machine->gfx[0]->pen_usage[tile]; } for ( offs = spriteram_size - 8;offs >= 0;offs -= 8 ){ if ( spriteram[offs+1] > 16 ) { /* visible */ int flags = spriteram[offs+4]; palette_map[0*16 + (flags >> 4)] |= 0xfffe; } } /* expand the results */ for (i = 0; i < 1*16; i++) { int usage = palette_map[i], j; if (usage) { palette_used_colors[i * 16 + 0] = PALETTE_COLOR_TRANSPARENT; for (j = 1; j < 16; j++) if (usage & (1 << j)) palette_used_colors[i * 16 + j] = PALETTE_COLOR_USED; else palette_used_colors[i * 16 + j] = PALETTE_COLOR_UNUSED; } else memset (&palette_used_colors[i * 16 + 0], PALETTE_COLOR_UNUSED, 16); } for (i = 1*16; i < 4*16; i++) { int usage = palette_map[i], j; if (usage) { for (j = 0; j < 15; j++) if (usage & (1 << j)) palette_used_colors[i * 16 + j] = PALETTE_COLOR_USED; else palette_used_colors[i * 16 + j] = PALETTE_COLOR_UNUSED; palette_used_colors[i * 16 + 15] = PALETTE_COLOR_TRANSPARENT; } else memset (&palette_used_colors[i * 16 + 0], PALETTE_COLOR_UNUSED, 16); } if (palette_recalc ()) { memset( dirtybuffer, 1, videoram_size ); memset( dirtybuffer1, 1, wc90b_tile_videoram_size ); memset( dirtybuffer2, 1, wc90b_tile_videoram_size2 ); } } /* commented out -- if we copyscrollbitmap below with TRANSPARENCY_NONE, we shouldn't waste our time here: wc90b_draw_sprites( bitmap, 3 ); */ for ( offs = wc90b_tile_videoram_size2 - 1; offs >= 0; offs-- ) { int sx, sy, tile, gfx; if ( dirtybuffer2[offs] ) { dirtybuffer2[offs] = 0; sx = ( offs % 64 ); sy = ( offs / 64 ); tile = wc90b_tile_videoram2[offs]; gfx = 9 + ( wc90b_tile_colorram2[offs] & 3 ) + ( ( wc90b_tile_colorram2[offs] >> 1 ) & 4 ); drawgfx(tmpbitmap2,Machine->gfx[ gfx ], tile, wc90b_tile_colorram2[offs] >> 4, 0,0, sx*16,sy*16, 0,TRANSPARENCY_NONE,0); } } scrollx = -wc90b_scroll2xlo[0] - 256 * ( wc90b_scroll2xhi[0] & 3 ); scrolly = -wc90b_scroll2ylo[0] - 256 * ( wc90b_scroll2yhi[0] & 1 ); copyscrollbitmap(bitmap,tmpbitmap2,1,&scrollx,1,&scrolly,&Machine->visible_area,TRANSPARENCY_NONE,0); wc90b_draw_sprites( bitmap, 2 ); for ( offs = wc90b_tile_videoram_size - 1; offs >= 0; offs-- ) { int sx, sy, tile, gfx; if ( dirtybuffer1[offs] ) { dirtybuffer1[offs] = 0; sx = ( offs % 64 ); sy = ( offs / 64 ); tile = wc90b_tile_videoram[offs]; gfx = 1 + ( wc90b_tile_colorram[offs] & 3 ) + ( ( wc90b_tile_colorram[offs] >> 1 ) & 4 ); drawgfx(tmpbitmap1,Machine->gfx[ gfx ], tile, wc90b_tile_colorram[offs] >> 4, 0,0, sx*16,sy*16, 0,TRANSPARENCY_NONE,0); } } scrollx = -wc90b_scroll1xlo[0] - 256 * ( wc90b_scroll1xhi[0] & 3 ); scrolly = -wc90b_scroll1ylo[0] - 256 * ( wc90b_scroll1yhi[0] & 1 ); copyscrollbitmap(bitmap,tmpbitmap1,1,&scrollx,1,&scrolly,&Machine->visible_area,TRANSPARENCY_PEN,palette_transparent_pen); wc90b_draw_sprites( bitmap, 1 ); for ( offs = videoram_size - 1; offs >= 0; offs-- ) { if ( dirtybuffer[offs] ) { int sx, sy; dirtybuffer[offs] = 0; sx = (offs % 64); sy = (offs / 64); drawgfx(tmpbitmap,Machine->gfx[0], videoram[offs] + ( ( colorram[offs] & 0x07 ) << 8 ), colorram[offs] >> 4, 0,0, sx*8,sy*8, 0,TRANSPARENCY_NONE,0); } } copybitmap( bitmap, tmpbitmap, 0, 0, 0, 0,&Machine->visible_area, TRANSPARENCY_PEN,palette_transparent_pen ); wc90b_draw_sprites( bitmap, 0 ); }
trabab/opsgenie-cloudformation-resources
opsgenie_integration/src/main/java/com/atlassian/opsgenie/integration/ListHandler.java
package com.atlassian.opsgenie.integration; import software.amazon.cloudformation.proxy.*; import com.atlassian.opsgenie.integration.model.ListIntegrationResponse; import com.atlassian.opsgenie.integration.client.OpsgenieClient; import com.atlassian.opsgenie.integration.client.OpsgenieClientException; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class ListHandler extends BaseHandler<CallbackContext> { @Override public ProgressEvent<ResourceModel, CallbackContext> handleRequest( final AmazonWebServicesClientProxy proxy, final ResourceHandlerRequest<ResourceModel> request, final CallbackContext callbackContext, final Logger logger) { final List<ResourceModel> models = new ArrayList<>(); OpsgenieClient OGClient = new OpsgenieClient(request.getDesiredResourceState().getOpsgenieApiEndpoint(), request.getDesiredResourceState().getOpsgenieApiKey()); try { ListIntegrationResponse resp = OGClient.ListIntegrations(); logger.log(resp.toString()); resp.getData().stream().forEach(model -> { ResourceModel resourceModel = new ResourceModel(); resourceModel.setName(model.getName()); resourceModel.setIntegrationType(model.getType()); resourceModel.setIntegrationId(model.getId()); resourceModel.setOpsgenieApiEndpoint(request.getDesiredResourceState().getOpsgenieApiEndpoint()); resourceModel.setOpsgenieApiKey(request.getDesiredResourceState().getOpsgenieApiKey()); models.add(resourceModel); }); } catch (IOException e) { logger.log(e.getMessage()); e.printStackTrace(); return ProgressEvent.<ResourceModel, CallbackContext>builder() .status(OperationStatus.FAILED) .build(); } catch (OpsgenieClientException e) { logger.log(e.getMessage()); HandlerErrorCode errorCode = HandlerErrorCode.GeneralServiceException; if (e.getCode() == 404) { errorCode = HandlerErrorCode.NotFound; } return ProgressEvent.<ResourceModel, CallbackContext>builder() .errorCode(errorCode) .status(OperationStatus.FAILED) .build(); } return ProgressEvent.<ResourceModel, CallbackContext>builder() .resourceModels(models) .status(OperationStatus.SUCCESS) .build(); } }
mihayl1/aimp-control-plugin
src/aimp/manager_impl_common.h
<reponame>mihayl1/aimp-control-plugin // Copyright (c) 2014, <NAME> #pragma once #include "../utils/scope_guard.h" #include "../utils/sqlite_util.h" #include "manager2.6.h" #include "manager3.0.h" namespace AIMPPlayer { inline const char* asString(AIMPManager::STATUS status) { switch (status) { case AIMPManager::STATUS_VOLUME: return "VOLUME"; case AIMPManager::STATUS_BALANCE: return "BALANCE"; case AIMPManager::STATUS_SPEED: return "SPEED"; case AIMPManager::STATUS_Player: return "Player"; case AIMPManager::STATUS_MUTE: return "MUTE"; case AIMPManager::STATUS_REVERB: return "REVERB"; case AIMPManager::STATUS_ECHO: return "ECHO"; case AIMPManager::STATUS_CHORUS: return "CHORUS"; case AIMPManager::STATUS_Flanger: return "Flanger"; case AIMPManager::STATUS_EQ_STS: return "EQ_STS"; case AIMPManager::STATUS_EQ_SLDR01: return "EQ_SLDR01"; case AIMPManager::STATUS_EQ_SLDR02: return "EQ_SLDR02"; case AIMPManager::STATUS_EQ_SLDR03: return "EQ_SLDR03"; case AIMPManager::STATUS_EQ_SLDR04: return "EQ_SLDR04"; case AIMPManager::STATUS_EQ_SLDR05: return "EQ_SLDR05"; case AIMPManager::STATUS_EQ_SLDR06: return "EQ_SLDR06"; case AIMPManager::STATUS_EQ_SLDR07: return "EQ_SLDR07"; case AIMPManager::STATUS_EQ_SLDR08: return "EQ_SLDR08"; case AIMPManager::STATUS_EQ_SLDR09: return "EQ_SLDR09"; case AIMPManager::STATUS_EQ_SLDR10: return "EQ_SLDR10"; case AIMPManager::STATUS_EQ_SLDR11: return "EQ_SLDR11"; case AIMPManager::STATUS_EQ_SLDR12: return "EQ_SLDR12"; case AIMPManager::STATUS_EQ_SLDR13: return "EQ_SLDR13"; case AIMPManager::STATUS_EQ_SLDR14: return "EQ_SLDR14"; case AIMPManager::STATUS_EQ_SLDR15: return "EQ_SLDR15"; case AIMPManager::STATUS_EQ_SLDR16: return "EQ_SLDR16"; case AIMPManager::STATUS_EQ_SLDR17: return "EQ_SLDR17"; case AIMPManager::STATUS_EQ_SLDR18: return "EQ_SLDR18"; case AIMPManager::STATUS_REPEAT: return "REPEAT"; case AIMPManager::STATUS_STAY_ON_TOP: return "STAY_ON_TOP"; case AIMPManager::STATUS_POS: return "POS"; case AIMPManager::STATUS_LENGTH: return "LENGTH"; case AIMPManager::STATUS_ACTION_ON_END_OF_PLAYLIST: return "ACTION_ON_END_OF_PLAYLIST"; case AIMPManager::STATUS_REPEAT_SINGLE_FILE_PLAYLISTS: return "REPEAT_SINGLE_FILE_PLAYLISTS"; case AIMPManager::STATUS_KBPS: return "KBPS"; case AIMPManager::STATUS_KHZ: return "KHZ"; case AIMPManager::STATUS_MODE: return "MODE"; case AIMPManager::STATUS_RADIO_CAPTURE: return "RADIO_CAPTURE"; case AIMPManager::STATUS_STREAM_TYPE: return "STREAM_TYPE"; case AIMPManager::STATUS_REVERSETIME: return "REVERSETIME"; case AIMPManager::STATUS_SHUFFLE: return "SHUFFLE"; case AIMPManager::STATUS_MAIN_HWND: return "MAIN_HWND"; case AIMPManager::STATUS_TC_HWND: return "TC_HWND"; case AIMPManager::STATUS_APP_HWND: return "APP_HWND"; case AIMPManager::STATUS_PL_HWND: return "PL_HWND"; case AIMPManager::STATUS_EQ_HWND: return "EQ_HWND"; case AIMPManager::STATUS_TRAY: return "TRAY"; default: break; } assert(!"unknown status in "__FUNCTION__); static std::string status_string; std::stringstream os; os << static_cast<int>(status); status_string = os.str(); return status_string.c_str(); } inline size_t getEntriesCountDB(PlaylistID playlist_id, sqlite3* playlists_db) { using namespace Utilities; std::ostringstream query; query << "SELECT COUNT(*) FROM PlaylistsEntries WHERE playlist_id=" << playlist_id; sqlite3_stmt* stmt = createStmt( playlists_db, query.str() ); ON_BLOCK_EXIT(&sqlite3_finalize, stmt); size_t total_entries_count = 0; const int rc_db = sqlite3_step(stmt); if (SQLITE_ROW == rc_db) { assert(sqlite3_column_count(stmt) > 0); total_entries_count = sqlite3_column_int(stmt, 0); } else { const std::string msg = MakeString() << "sqlite3_step() error " << rc_db << ": " << sqlite3_errmsg(playlists_db) << ". Query: " << query.str(); throw std::runtime_error(msg); } return total_entries_count; } inline sqlite3* getPlaylistsDB(const AIMPPlayer::AIMPManager& aimp_manager) { if ( const AIMPPlayer::AIMPManager30* mgr3 = dynamic_cast<const AIMPPlayer::AIMPManager30*>(&aimp_manager) ) { return mgr3->playlists_db(); } else if (const AIMPPlayer::AIMPManager26* mgr2 = dynamic_cast<const AIMPPlayer::AIMPManager26*>(&aimp_manager) ) { return mgr2->playlists_db(); } else { using namespace Utilities; const std::string msg = MakeString() << __FUNCTION__ ": invalid AIMPManager object. AIMPManager30 and AIMPManager26 are only supported."; throw std::runtime_error(msg); } } } // namespace AIMPPlayer
boldak/jace-front
src/modules/vuetifydl/mixins/recordable.js
export default { computed: { $parameters () { return this.$options.propsData }, isNewRecord: function () { return (!this.$options.primaryKey || !this.$options.propsData) || !this.$options.propsData[this.$options.primaryKey] } } }
KenWoo/Algorithm
Algorithms/Easy/976. Largest Perimeter Triangle/answer.py
from typing import List class Solution: def largestPerimeter(self, A: List[int]) -> int: A.sort() for i in range(len(A)-3, -1, -1): if A[i] + A[i+1] > A[i+2]: return A[i] + A[i+1] + A[i+2] return 0 if __name__ == "__main__": s = Solution() result = s.largestPerimeter([2, 1, 2]) print(result)
Malamut54/dbobrov
chapter_007/src/main/java/ru/job4j/task3/Main.java
<gh_stars>0 package ru.job4j.task3; /** * Task 3. * * @author <NAME> (<EMAIL>) * @since 13.10.2017 */ public class Main { /** * Stsrt program. * @param args input args. */ public static void main(String[] args) { Thread time = new Thread(new Time(100)); time.start(); } }
Markus-Schwer/quarkus
independent-projects/tools/codestarts/src/test/java/io/quarkus/devtools/codestarts/core/CodestartDataTest.java
package io.quarkus.devtools.codestarts.core; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.*; import io.quarkus.devtools.codestarts.CodestartCatalog; import io.quarkus.devtools.codestarts.CodestartProjectGenerationTest; import io.quarkus.devtools.codestarts.CodestartProjectInput; import java.io.IOException; import java.util.Map; import java.util.Set; import org.assertj.core.util.Lists; import org.assertj.core.util.Sets; import org.junit.jupiter.api.Test; class CodestartDataTest { @Test @SuppressWarnings("unchecked") void testDependenciesOverrideWithVersion() throws IOException { final CodestartCatalog<CodestartProjectInput> catalog = CodestartProjectGenerationTest.loadSpecific("deps"); final Map<String, Object> dependenciesData = CodestartData.buildDependenciesData(catalog.getCodestarts().stream() .filter(c -> c.isSelected(Sets.newLinkedHashSet("codestart-dep1", "codestart-dep2"))), "a", Lists.list("input.group:some-dep:1.2", "my.group:base-dep1", "my.group:a-dep1:1.1"), Lists.list("input.group:some-bom")); assertThat((Set<Map<String, String>>) dependenciesData.get("dependencies")) .isNotNull() .map(m -> m.get("formatted-gav")) .containsExactlyInAnyOrder( "input.group:some-dep:1.2", "my.group:base-dep1", "my.group:a-dep1:1.1", "my.group:base-depversion:1.10", "my.group:base-dep2", "my.group:a-dep2"); assertThat((Set<Map<String, String>>) dependenciesData.get("test-dependencies")) .isNotNull() .map(m -> m.get("formatted-gav")) .containsExactlyInAnyOrder( "my.group:base-test-dep1", "my.group:a-test-dep1", "my.group:base-test-dep2"); assertThat((Set<Map<String, String>>) dependenciesData.get("boms")) .isNotNull() .map(m -> m.get("formatted-gav")) .containsExactly("input.group:some-bom"); } @Test @SuppressWarnings("unchecked") void testDependenciesOverrideNoVersion() throws IOException { final CodestartCatalog<CodestartProjectInput> catalog = CodestartProjectGenerationTest.loadSpecific("deps"); final Map<String, Object> dependenciesData = CodestartData.buildDependenciesData(catalog.getCodestarts().stream() .filter(c -> c.isSelected(Sets.newLinkedHashSet("codestart-dep1"))), "a", Lists.list("my.group:base-depversion"), Lists.newArrayList()); assertThat((Set<Map<String, String>>) dependenciesData.get("dependencies")) .isNotNull() .map(m -> m.get("formatted-gav")) .containsExactlyInAnyOrder( "my.group:base-dep1", "my.group:a-dep1", "my.group:base-depversion"); } }
jWeb94/kit_wissenschaftliches_programmieren_fuer_ingenieure
uebung3/musterloesung/game_of_life_lsg_WS1819/functions_game.cpp
<filename>uebung3/musterloesung/game_of_life_lsg_WS1819/functions_game.cpp<gh_stars>0 #include "functions_game.h" using namespace std; MatrixXi create_field2d(const unsigned int nx, const unsigned int ny){ MatrixXi field=MatrixXi::Zero(nx,ny); return field; } void init_field2d(MatrixXi &field, const double frac){ int count = 0; int todo_fill; int rand_x, rand_y; const unsigned int nx = field.rows(); const unsigned int ny = field.cols(); todo_fill = int(nx*ny*frac); //Anzahl der zu fuellenden Felder while(count < todo_fill){ rand_x = rand()%nx; rand_y = rand()%ny; if(field(rand_x,rand_y) != 1){ field(rand_x,rand_y) = 1; count++; } } } void make_step(MatrixXi & field,MatrixXi & field_tmp){ int n_neigh; const unsigned int nx = field.rows(); const unsigned int ny = field.cols(); for(int i = 0; i<nx; i++){ for(int j = 0; j<ny; j++){ //alle 8 Nachbarn checken: n_neigh = int(field((i-1+nx)%nx,j))+ int(field((i+1)%nx,j))+ int(field(i,(j-1+ny)%ny))+ int(field(i,(j+1)%ny))+ int(field((i-1+nx)%nx,(j-1+ny)%ny))+ int(field((i-1+nx)%nx,(j+1)%ny))+ int(field((i+1)%nx,(j-1+ny)%ny))+ int(field((i+1)%nx,(j+1)%ny)); if(field(i,j) == 1){ switch(n_neigh){ case(2): break; case(3): break; default: field_tmp(i,j) = 0; } } else{ if(n_neigh == 3){ field_tmp(i,j)= 1; } } } } field = field_tmp; } void plot_field(MatrixXi const & field, const unsigned int nstep){ char Dateiname[256]; ofstream Datei; const unsigned int nx = field.rows(); const unsigned int ny = field.cols(); sprintf(Dateiname,"field%d.dat",nstep); Datei.open(Dateiname); for(int i = 0;i<nx;i++){ for(int j=0;j<ny;j++){ Datei<<i<<" "<<j<<" "<<field(i,j)<<endl; } Datei<<endl; } Datei.close(); }
apache/tuscany-sca-2.x
modules/domain-node/src/test/java/org/apache/tuscany/sca/runtime/TuscanyRuntimeTestCase.java
<gh_stars>10-100 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.tuscany.sca.runtime; import java.net.MalformedURLException; import java.net.URI; import java.util.List; import java.util.Map; import junit.framework.Assert; import org.apache.tuscany.sca.Node; import org.apache.tuscany.sca.TuscanyRuntime; import org.apache.tuscany.sca.contribution.processor.ContributionReadException; import org.apache.tuscany.sca.monitor.ValidationException; import org.junit.Ignore; import org.junit.Test; import org.oasisopen.sca.NoSuchDomainException; import org.oasisopen.sca.NoSuchServiceException; import sample.Helloworld; public class TuscanyRuntimeTestCase { @Test public void testInstallDeployable() throws NoSuchServiceException, NoSuchDomainException, ContributionReadException, ActivationException, ValidationException { Node node = TuscanyRuntime.newInstance().createNode("default"); node.installContribution("helloworld", "src/test/resources/sample-helloworld.jar", null, null); node.startComposite("helloworld", "helloworld.composite"); Helloworld helloworldService = node.getService(Helloworld.class, "HelloworldComponent"); Assert.assertEquals("Hello petra", helloworldService.sayHello("petra")); } @Test public void testStopStart() throws NoSuchServiceException, NoSuchDomainException, ContributionReadException, ActivationException, ValidationException { Node node = TuscanyRuntime.newInstance().createNode("default"); node.installContribution("helloworld", "src/test/resources/sample-helloworld.jar", null, null); node.startComposite("helloworld", "helloworld.composite"); Map<String, List<String>> ci = node.getStartedCompositeURIs(); Assert.assertEquals(1, ci.size()); Helloworld helloworldService = node.getService(Helloworld.class, "HelloworldComponent"); Assert.assertEquals("Hello petra", helloworldService.sayHello("petra")); node.stopComposite("helloworld", "helloworld.composite"); try { node.getService(Helloworld.class, "HelloworldComponent"); Assert.fail(); } catch (NoSuchServiceException e) { // expected as there is no deployables } node.startComposite("helloworld", "helloworld.composite"); helloworldService = node.getService(Helloworld.class, "HelloworldComponent"); Assert.assertEquals("Hello petra", helloworldService.sayHello("petra")); } @Test @Ignore("Depdends on itest/T3558 which isn't in the build?") public void testInstallWithDependent() throws NoSuchServiceException, ContributionReadException, ActivationException, ValidationException { Node node = TuscanyRuntime.newInstance().createNode("default"); node.installContribution("store", "../../testing/itest/T3558/src/test/resources/sample-store.jar", null, null); node.installContribution("store-client", "../../testing/itest/T3558/src/test/resources/sample-store-client.jar", null, null); node.startComposite("store", "store.composite"); node.startComposite("store-client", "store-client.composite"); Helloworld helloworldService = node.getService(Helloworld.class, "HelloworldComponent"); Assert.assertEquals("Hello petra", helloworldService.sayHello("petra")); } @Test public void testInstallNoDeployable() throws NoSuchServiceException, NoSuchDomainException, ContributionReadException, ActivationException, ValidationException { Node node = TuscanyRuntime.newInstance().createNode("default"); node.installContribution("helloworld", "src/test/resources/sample-helloworld-nodeployable.jar", null, null); try { node.getService(Helloworld.class, "HelloworldComponent"); Assert.fail(); } catch (NoSuchServiceException e) { // expected as there is no deployables } node.startComposite("helloworld", "helloworld.composite"); Helloworld helloworldService = node.getService(Helloworld.class, "HelloworldComponent"); Assert.assertEquals("Hello petra", helloworldService.sayHello("petra")); } @Test public void testGetInstalledContributions() throws NoSuchServiceException, NoSuchDomainException, ContributionReadException, ActivationException, ValidationException { Node node = TuscanyRuntime.newInstance().createNode("default"); node.installContribution("foo", "src/test/resources/sample-helloworld-nodeployable.jar", null, null); List<String> ics = node.getInstalledContributionURIs(); Assert.assertEquals(1, ics.size()); Assert.assertEquals("foo", ics.get(0)); } @Test public void testGetDeployedCompostes() throws NoSuchServiceException, NoSuchDomainException, ContributionReadException, MalformedURLException, ActivationException, ValidationException { Node node = TuscanyRuntime.newInstance().createNode("default"); node.installContribution("foo", "src/test/resources/sample-helloworld.jar", null, null); List<String> dcs = node.startDeployables("foo"); Assert.assertEquals(1, dcs.size()); Assert.assertEquals("helloworld.composite", dcs.get(0)); } @Test public void testRemoveComposte() throws NoSuchServiceException, NoSuchDomainException, ContributionReadException, MalformedURLException, ActivationException, ValidationException { Node node = TuscanyRuntime.newInstance().createNode("default"); node.installContribution("foo", "src/test/resources/sample-helloworld.jar", null, null); List<String> dcs = node.startDeployables("foo"); Assert.assertEquals(1, dcs.size()); Map<String, List<String>> dcsx = node.getStartedCompositeURIs(); Assert.assertEquals(1, dcsx.size()); node.stopComposite("foo", "helloworld.composite"); dcsx = node.getStartedCompositeURIs(); Assert.assertEquals(0, dcsx.size()); } @Test public void testInstallWithMetaData() throws ContributionReadException, ActivationException, ValidationException, NoSuchServiceException { Node node = TuscanyRuntime.newInstance().createNode("default"); node.installContribution("helloworld", "src/test/resources/sample-helloworld-nodeployable.jar", "src/test/resources/sca-contribution-generated.xml", null); node.startComposite("helloworld", "helloworld.composite"); Map<String, List<String>> dcs = node.getStartedCompositeURIs(); Assert.assertEquals(1, dcs.size()); Assert.assertEquals("helloworld.composite", dcs.get("helloworld").get(0)); Helloworld helloworldService = node.getService(Helloworld.class, "HelloworldComponent"); Assert.assertEquals("Hello petra", helloworldService.sayHello("petra")); } @Test public void testURI() throws NoSuchServiceException, NoSuchDomainException, ContributionReadException, ActivationException, ValidationException { Node node = TuscanyRuntime.newInstance().createNode("default"); String uri = node.installContribution("src/test/resources/sample-helloworld.jar"); Assert.assertEquals("sample-helloworld", uri); } @Test public void testStaticCreate() { Node node = TuscanyRuntime.runComposite("helloworld.composite", "src/test/resources/sample-helloworld.jar"); List<String> cs = node.getInstalledContributionURIs(); Assert.assertEquals(1, cs.size()); Map<String, List<String>> dcs = node.getStartedCompositeURIs(); Assert.assertEquals(1, dcs.size()); Assert.assertEquals("helloworld.composite", dcs.get("sample-helloworld").get(0)); } @Test public void testStaticCreateWithNullComposite() { Node node = TuscanyRuntime.runComposite(null, "src/test/resources/sample-helloworld.jar"); List<String> cs = node.getInstalledContributionURIs(); Assert.assertEquals(1, cs.size()); Map<String, List<String>> dcs = node.getStartedCompositeURIs(); Assert.assertEquals(1, dcs.size()); Assert.assertEquals("helloworld.composite", dcs.get("sample-helloworld").get(0)); } @Test public void testRunComposite() throws NoSuchServiceException { Node node = TuscanyRuntime.runComposite("helloworld.composite", "src/test/resources/sample-helloworld.jar"); Helloworld helloworldService = node.getService(Helloworld.class, "HelloworldComponent"); Assert.assertEquals("Hello petra", helloworldService.sayHello("petra")); } @Test public void testRunCompositeSharedRuntime() throws NoSuchServiceException { Node node = TuscanyRuntime.runComposite(URI.create("default"), "helloworld.composite", "src/test/resources/sample-helloworld.jar"); Helloworld helloworldService = node.getService(Helloworld.class, "HelloworldComponent"); Assert.assertEquals("Hello petra", helloworldService.sayHello("petra")); } }
bogus-sudo/ONE-1
compiler/mir/src/mir_onnx_importer/Op/Transpose.cpp
<gh_stars>100-1000 /* * Copyright (c) 2019 Samsung Electronics Co., Ltd. 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. */ #include "Transpose.h" #include "ONNXHelpers.h" #include "AttributeHelpers.h" #include "mir/ops/TransposeOp.h" #include <numeric> namespace mir_onnx { void convertTransposeV1(const onnx::NodeProto &onnx_node, ConverterContext *context) { const auto inputs = context->getNodeInputs(onnx_node); mir::Graph *graph = context->getGraph(); assert(inputs.size() == 1); auto input = inputs[0]; const int num_axes = input->getShape().rank(); std::vector<std::size_t> axis_order(num_axes); const auto *perm_attr = findAttribute(onnx_node, "perm"); if (perm_attr == nullptr) { // Reverse the dimensions. std::iota(axis_order.rbegin(), axis_order.rend(), 0); } else { const auto perm = getAttributeValue<std::vector<std::int64_t>>(*perm_attr); assert(static_cast<int>(perm.size()) == num_axes); std::copy(perm.cbegin(), perm.cend(), axis_order.begin()); } auto result = createOp<mir::ops::TransposeOp>(graph, input, axis_order)->getOutput(0); context->setNodeOutputs(onnx_node, {result}); } } // namespace mir_onnx
ali-sharif/avm
org.aion.avm.embed/test/org/aion/avm/embed/deploy/renamer/resources/ClassB.java
package org.aion.avm.embed.deploy.renamer.resources; //NOTE: This is a copy of a test in org.aion.avm.tooling in order to support the RenameDeployTest. public class ClassB extends ClassA implements Comparable<String>{ }
npocmaka/Windows-Server-2003
enduser/netmeeting/ui/wb/user.hpp
// // USER.HPP // User Class // // Copyright Microsoft 1998- // #ifndef __USER_HPP_ #define __USER_HPP_ // // // Class: WbUser // // Purpose: User object recorder // // class DCWbGraphicPointer; class WbUser { public: // // Constructor // WbUser(POM_OBJECT hUser = NULL); // // Destructor // ~WbUser(void); // // Return the user handle // POM_OBJECT Handle(void) const { return(m_hUser);} // // Refresh the user details // void Refresh(void); // // Update the external copy of the user information // void Update(void); // // Return the user name // LPCSTR Name(void) const { return(m_strName); } // // Synchronize the users page with other synced users // void Sync(void); void Unsync(void); // // Update the user's position from the sync position. This does not // change the sync position. // void GetSyncPosition(void); // // Update the sync position from the user's current position // void PutSyncPosition(void); // // Return a remote pointer object for this user // DCWbGraphicPointer* GetPointer(void) { return(m_pRemotePointer); } // // Put the user's remote pointer at the position specified // void PutPointer(WB_PAGE_HANDLE hPage, POINT point); // // Remove the user's remote pointer // void RemovePointer(void); // // Return TRUE if the user is synced // BOOL IsSynced(void) const { return m_bSynced; } // // Return TRUE if the user has the contents lock // BOOL HasContentsLock(void) const; // // Return TRUE if the user has their remote pointer active // BOOL IsUsingPointer(void) const; // // Return the current page of the user // WB_PAGE_HANDLE Page(void) const {return m_hPageCurrent; } void SetPage(WB_PAGE_HANDLE hPage); // // Return the current position within the page of the user // void GetVisibleRect(LPRECT lprc) { *lprc = m_rectVisible; } void SetVisibleRect(LPCRECT lprc); // // Return the page of the user's pointer // WB_PAGE_HANDLE PointerPage(void) const; // // Return the position of the user's pointer // void GetPointerPosition(LPPOINT lpptPos); // // Return the user's color // COLORREF Color(void) const { return(m_color); } // // Return TRUE if this is the local user // BOOL IsLocalUser(void) const { return(m_bLocalUser); } // // Operators // virtual WbUser& operator=(const WbUser& user); virtual BOOL operator!=(const WbUser& user) const; virtual BOOL operator==(const WbUser& user) const; // // Set zoom/unzoom state // void Zoom(void) { m_zoomed = TRUE; } void Unzoom(void) { m_zoomed = FALSE; } BOOL GetZoom(void) const { return(m_zoomed); } protected: // // Core access handle // POM_OBJECT m_hUser; // // Flag indicating Whether this is the local user // BOOL m_bLocalUser; BOOL m_zoomed; // // Local copies of the user information // char m_strName[TSHR_MAX_PERSON_NAME_LEN]; BOOL m_bSynced; WB_PAGE_HANDLE m_hPageCurrent; RECT m_rectVisible; COLORREF m_color; // // Graphic pointer associated with this user // DCWbGraphicPointer* m_pRemotePointer; }; // // // Class: WbUserList // // Purpose: Map from user handles to user object pointers // // class WbUserList : public COBLIST { public: // // Destructor // ~WbUserList(void); // // Clear all entries from the map, deleting the associated object // void Clear(void); }; // // Return lock status // BOOL WB_Locked(void); BOOL WB_ContentsLocked(void); BOOL WB_GotLock(void); BOOL WB_GotContentsLock(void); BOOL WB_PresentationMode(void); // // Return an object representing the local user // WbUser* WB_LocalUser(void); // // Retrieving users // WbUser* WB_GetUser(POM_OBJECT hUser); WbUser* WB_GetFirstUser(void); WbUser* WB_GetNextUser(const WbUser* pUser); // // Return an object representing the user who has the lock // WbUser* WB_LockUser(void); #endif // __USER_HPP_
3rdIteration/bip_utils
bip_utils/bip/bip39/bip39_mnemonic.py
# Copyright (c) 2021 <NAME> # # 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. """Module for BIP39 mnemonic.""" # Imports from enum import auto, IntEnum, unique from typing import Dict, List from bip_utils.utils.misc import StringUtils from bip_utils.utils.mnemonic import Mnemonic, MnemonicLanguages @unique class Bip39WordsNum(IntEnum): """Enumerative for BIP39 words number.""" WORDS_NUM_12 = 12 WORDS_NUM_15 = 15 WORDS_NUM_18 = 18 WORDS_NUM_21 = 21 WORDS_NUM_24 = 24 @unique class Bip39Languages(MnemonicLanguages): """Enumerative for BIP39 languages.""" CHINESE_SIMPLIFIED = auto() CHINESE_TRADITIONAL = auto() CZECH = auto() ENGLISH = auto() FRENCH = auto() ITALIAN = auto() KOREAN = auto() PORTUGUESE = auto() SPANISH = auto() class Bip39MnemonicConst: """Class container for BIP39 mnemonic constants.""" # Accepted mnemonic word numbers MNEMONIC_WORD_NUM: List[Bip39WordsNum] = [ Bip39WordsNum.WORDS_NUM_12, Bip39WordsNum.WORDS_NUM_15, Bip39WordsNum.WORDS_NUM_18, Bip39WordsNum.WORDS_NUM_21, Bip39WordsNum.WORDS_NUM_24, ] # Language files LANGUAGE_FILES: Dict[Bip39Languages, str] = { Bip39Languages.ENGLISH: "bip39_words/english.txt", Bip39Languages.ITALIAN: "bip39_words/italian.txt", Bip39Languages.FRENCH: "bip39_words/french.txt", Bip39Languages.SPANISH: "bip39_words/spanish.txt", Bip39Languages.PORTUGUESE: "bip39_words/portuguese.txt", Bip39Languages.CZECH: "bip39_words/czech.txt", Bip39Languages.CHINESE_SIMPLIFIED: "bip39_words/chinese_simplified.txt", Bip39Languages.CHINESE_TRADITIONAL: "bip39_words/chinese_traditional.txt", Bip39Languages.KOREAN: "bip39_words/korean.txt", } # Total number of words WORDS_LIST_NUM: int = 2048 # Word length in bit WORD_BIT_LEN: int = 11 class Bip39Mnemonic(Mnemonic): """ BIP39 mnemonic class. It adds NFKD normalization to mnemonic. """ def __init__(self, mnemonic_list: List[str]) -> None: """ Construct class. Args: mnemonic_list (list[str]): Mnemonic list """ # Normalize using NFKD as specified by BIP-0039 super().__init__(self.__NormalizeNfkd(mnemonic_list)) @staticmethod def __NormalizeNfkd(mnemonic_list: List[str]) -> List[str]: """ Normalize mnemonic list using NFKD. Args: mnemonic_list (list[str]): Mnemonic list Returns: list[str]: Normalized mnemonic list """ return list(map(StringUtils.NormalizeNfkd, mnemonic_list))
WhittKinley/Legos
submissions/Kinley/mygames.py
<gh_stars>0 from collections import namedtuple from games import (Game) class GameState: def __init__(self, to_move, board, label=None, depth=5): self.to_move = to_move self.board = board self.label = label self.maxDepth = depth # self.validSpaces = () def __str__(self): if self.label == None: return super(GameState, self).__str__() return self.label class FlagrantCopy(Game): """A flagrant copy of TicTacToe, from game.py It's simplified, so that moves and utility are calculated as needed Play TicTacToe on an h x v board, with Max (first player) playing 'X'. A state has the player to move and a board, in the form of a dict of {(x, y): Player} entries, where Player is 'X' or 'O'.""" def __init__(self, h=7, v=6, k=4): self.h = h self.v = v self.k = k self.initial = GameState(to_move='X', board={}) def land(self, board, column): for row in reversed(range(self.v)): position = (row,column) if position in board.keys(): continue return position def hasRoom(self, board, column): topRow = self.v-6 topCell = (topRow, column) if topCell in board.keys(): return False else: return True def actions(self, state): try: return state.moves except: pass "Legal moves are any square not yet taken." moves = [] for x in range(self.h): if self.hasRoom(state.board, x): moves.append(x) state.moves = moves return moves # defines the order of play def opponent(self, player): if player == 'X': return 'O' if player == 'O': return 'X' return None def result(self, state, move): if move not in self.actions(state): return state # Illegal move has no effect board = state.board.copy() player = state.to_move position = self.land(board,move) board[position] = player # board[move] = player next_mover = self.opponent(player) return GameState(to_move=next_mover, board=board) def utility(self, state, player): "Return the value to player; 1 for win, -1 for loss, 0 otherwise." try: return state.utility if player == 'X' else -state.utility except: pass board = state.board util = self.check_win(board, 'X') if util == 0: util = -self.check_win(board, 'O') state.utility = util return util if player == 'X' else -util # # Did I win? # def check_win(self, board, player): # # check rows # for y in range(1, self.v + 1): # if self.k_in_row(board, (1,y), player, (1,0)): # return 1 # # check columns # for x in range(1, self.h + 1): # if self.k_in_row(board, (x,1), player, (0,1)): # return 1 # # check \ diagonal # if self.k_in_row(board, (1,1), player, (1,1)): # return 1 # # check / diagonal # if self.k_in_row(board, (3,1), player, (-1,1)): # return 1 # return 0 def check_win(self, board, player): for y in range(self.v): if self.checkColumnWin(board, y, player) == self.k: return -1 for x in range(self.h): if self.checkRowWin(board, x, player) == self.k: return -1 for y in range(self.v): if self.checkDiagonalWin(board, (6,y), player, (-1,1)) == self.k: return -1 for y in range(self.v): if self.checkDiagonalWin(board, (6,y), player, (-1,1)): return -1 return 0 def checkRowWin(self, board, row, player): count = 0 for column in range(self.v): position = (row, column) if board.get(position) == player: count += 1 if count == self.k: return count else: count = 0 def checkColumnWin(self, board, column, player): count = 0 for row in range(self.h): position = (row, column) if board.get(position) == player: count += 1 if count == self.k: return count else: count = 0 def checkDiagonalWin(self, board, start, player, direction): count = 0 (d_x, d_y) = direction x, y = start while board.get((x,y)) == player: count += 1 x = x + d_x y = y + d_y if count == self.k: return count # does player have K in a row? return 1 if so, 0 if not # def k_in_row(self, board, start, player, direction): # "Return true if there is a line through start on board for player." # (delta_x, delta_y) = direction # x, y = start # n = 0 # n is number of moves in row # while board.get((x, y)) == player: # n += 1 # x, y = x + delta_x, y + delta_y # x, y = start # while board.get((x, y)) == player: # n += 1 # x, y = x - delta_x, y - delta_y # n -= 1 # Because we counted start itself twice # return n >= self.k def terminal_test(self, state): "A state is terminal if it is won or there are no empty squares." return self.utility(state, 'X') != 0 or len(self.actions(state)) == 0 def display(self, state): board = state.board # for x in range(1, self.h + 1): for x in range(self.h): # for y in range(1, self.v + 1): for y in range(self.v): print(board.get((x, y), '.'), end=' ') print() myGame = FlagrantCopy() won = GameState( to_move = 'O', board = {(5,1): 'O', (5,2): 'O', (5,3): 'O', (2,1): 'X', (2,2): 'X', }, label = 'won' ) winin1 = GameState( to_move = 'X', board = {(1,1): 'X', (1,2): 'X', (1,3): 'X', (2,1): 'O', (2,2): 'O', (2,3): 'O' }, label = 'winin1' ) losein1 = GameState( to_move = 'O', board = {(2,1): 'X', (2,2): 'X', (4,1): 'O', (4,2): 'O', (4,3): 'O', (3,1): 'X', (3,1): 'X' }, label = 'losein1' ) winin2 = GameState( to_move = 'X', board = {(5,1): 'O', (5,3): 'O', (6,1): 'X', (6,3): 'X'}, label = 'winin2' ) lost = GameState( to_move = 'X', board = {(0,2): 'O', (0,3): 'X', (1,1): 'X', (1,2): 'O', (1,3): 'O', (2, 1): 'X', (2, 2): 'O', (2, 3): 'X', (3, 1): 'X', (3, 2): 'O', (3, 3): 'O', (4, 1): 'O', (4, 2): 'X', (4, 3): 'X', (5, 1): 'O', (5, 2): 'O', (5, 3): 'O', (6, 1): 'X', (6, 2): 'X', (6, 3): 'X', }, label = 'lost' ) myGames = { myGame: [ won, winin1, losein1, winin2, lost, ] }
ethz-asl/mav_findmine
libs/fm_control/src/position_controller.cc
<gh_stars>1-10 /* MIT License Copyright (c) 2020 <NAME>, ASL, ETH Zurich, Switzerland Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "fm_control/position_controller.h" #include <functional> #include <limits> #include <angles/angles.h> #include <dji_sdk/SDKControlAuthority.h> #include <dji_sdk/dji_sdk.h> #include <eigen_conversions/eigen_msg.h> #include <fm_comm/dji_interface.h> #include <geometry_msgs/PoseStamped.h> #include <mav_msgs/conversions.h> #include <mav_trajectory_generation/trajectory_sampling.h> #include <mav_trajectory_generation_ros/ros_conversions.h> #include <sensor_msgs/Joy.h> #include <std_msgs/Bool.h> #include <std_msgs/Float32.h> namespace fm_control { constexpr double kDefaultKPx = 1.0; constexpr double kDefaultKPy = 1.0; constexpr double kDefaultKPz = 1.0; constexpr double kDefaultKYaw = 1.0; constexpr double kDefaultKVx = 1.5; constexpr double kDefaultKVy = 1.5; constexpr double kDefaultKVz = 1.5; constexpr double kDefaultKYawRate = 0.5; constexpr double kDefaultKAx = 0.1; constexpr double kDefaultKAy = 0.1; constexpr double kDefaultKAz = 0.1; constexpr double kDefaultKYawAcc = 0.0; constexpr double kDefaultVXyMax = 12.0; constexpr double kDefaultVZUpMax = 3.0; constexpr double kDefaultVZDownMax = 2.0; const double kDefaultYawRateMax = angles::from_degrees(120.0); const ControlType kDefaultControlType = ControlType::kVelocity; const AltitudeMode kDefaultAltitudeMode = AltitudeMode::kENU; constexpr double kDefaultMinTransitionAltitude = -1.0; PositionController::PositionController(const ros::NodeHandle& nh, const ros::NodeHandle& nh_private) : nh_(nh), nh_private_(nh_private) { advertiseServices(); subscribeServices(); advertiseTopics(); subscribeTopics(); intializeDynamicReconfigure(); } PositionController::States::States() : has_ctrl_authority(false), goal_type(GoalType::kNone), has_position(false), has_velocity(false), has_translational_acceleration(false), has_attitude(false), has_angular_velocity(false), has_angular_acceleration(false), has_agl(false), flight_mode_axis(std::numeric_limits<int>::max()) {} void PositionController::States::reset() { *this = States(); } PositionController::Parameters::Parameters() : K_px(kDefaultKPx), K_py(kDefaultKPy), K_pz(kDefaultKPz), K_yaw(kDefaultKYaw), K_vx(kDefaultKVx), K_vy(kDefaultKVy), K_vz(kDefaultKVz), K_yaw_rate(kDefaultKYawRate), K_ax(kDefaultKAx), K_ay(kDefaultKAy), K_az(kDefaultKAz), K_yaw_acc(kDefaultKYawAcc), v_xy_max(kDefaultVXyMax), v_z_up_max(kDefaultVZUpMax), v_z_down_max(kDefaultVZDownMax), yaw_rate_max(kDefaultYawRateMax), control_type(kDefaultControlType), altitude_mode(kDefaultAltitudeMode), min_transition_altitude(kDefaultMinTransitionAltitude) {} void PositionController::intializeDynamicReconfigure() { dynamic_reconfigure::Server<PositionControllerConfig>::CallbackType f; f = std::bind(&PositionController::dynamicReconfigure, this, std::placeholders::_1, std::placeholders::_2); dyn_config_server_.setCallback(f); } void PositionController::dynamicReconfigure(PositionControllerConfig& config, uint32_t level) { params_.K_px = config.K_px; params_.K_py = config.K_py; params_.K_pz = config.K_pz; params_.K_yaw = config.K_yaw; params_.K_vx = config.K_vx; params_.K_vy = config.K_vy; params_.K_vz = config.K_vz; params_.K_yaw_rate = config.K_yaw_rate; params_.K_ax = config.K_ax; params_.K_ay = config.K_ay; params_.K_az = config.K_az; params_.K_yaw_acc = config.K_yaw_acc; params_.v_xy_max = config.v_xy_max; params_.v_z_up_max = config.v_z_up_max; params_.v_z_down_max = config.v_z_down_max; params_.yaw_rate_max = config.yaw_rate_max; params_.control_type = static_cast<ControlType>(config.control_type); params_.min_transition_altitude = config.min_transition_altitude; } void PositionController::advertiseServices() { switch_control_frame_srv_ = nh_.advertiseService( "switch_control_frame", &PositionController::switchControlFrame, this); obtain_ctrl_authority_srv_ = nh_.advertiseService("obtain_control_authority", &PositionController::obtainControlAuthority, this); release_ctrl_authority_srv_ = nh_.advertiseService("release_control_authority", &PositionController::releaseControlAuthority, this); } void PositionController::subscribeServices() { sdk_ctrl_authority_client_ = nh_.serviceClient<dji_sdk::SDKControlAuthority>( "dji_sdk/sdk_control_authority"); } const bool kQueueSize = 1; void PositionController::advertiseTopics() { const bool kLatchTopic = false; ctrl_vel_yawrate_pub_ = nh_.advertise<sensor_msgs::Joy>( "dji_sdk/flight_control_setpoint_ENUvelocity_yawrate", kQueueSize, kLatchTopic); ctrl_pos_yaw_pub_ = nh_.advertise<sensor_msgs::Joy>( "dji_sdk/flight_control_setpoint_ENUposition_yaw", kQueueSize, kLatchTopic); pos_error_pub_ = nh_private_.advertise<std_msgs::Float32>( "pos_error", kQueueSize, kLatchTopic); pos_yaw_ref_pub_ = nh_private_.advertise<geometry_msgs::PoseStamped>( "pos_yaw_ref", kQueueSize, kLatchTopic); ctrl_auth_pub_ = nh_private_.advertise<std_msgs::Bool>("ctrl_authority", kQueueSize, false); } void PositionController::subscribeTopics() { // Translational control. local_position_sub_ = nh_.subscribe("dji_sdk/local_position", kQueueSize, &PositionController::receiveLocalPosition, this); velocity_sub_ = nh_.subscribe("dji_sdk/velocity", kQueueSize, &PositionController::receiveVelocity, this); acceleration_sub_ = nh_.subscribe("dji_sdk/acceleration_ground_fused", kQueueSize, &PositionController::receiveAcceleration, this); // Yaw control. attitude_sub_ = nh_.subscribe("dji_sdk/attitude", kQueueSize, &PositionController::receiveAttitude, this); angular_velocity_sub_ = nh_.subscribe("dji_sdk/angular_velocity_fused", kQueueSize, &PositionController::receiveAngularVelocity, this); // AGL. agl_sub_ = nh_.subscribe("fm_altitude_estimator/state", kQueueSize, &PositionController::receiveAGL, this); // Command subscriber. goal_sub_ = nh_.subscribe("command/pose", kQueueSize, &PositionController::receiveGoal, this); poly_trajectory_sub_ = nh_.subscribe("command/polynomial_trajectory", kQueueSize, &PositionController::receivePolynomialTrajectory, this); rc_sub_ = nh_.subscribe("dji_sdk/rc", kQueueSize, &PositionController::receiveRC, this); } bool PositionController::obtainControlAuthority( std_srvs::Empty::Request& request, std_srvs::Empty::Response& response) { dji_sdk::SDKControlAuthority::Request sdk_ca_req; sdk_ca_req.control_enable = dji_sdk::SDKControlAuthority::Request::REQUEST_CONTROL; states_.has_ctrl_authority = fm_comm::callDjiTask<dji_sdk::SDKControlAuthority>( sdk_ca_req, sdk_ctrl_authority_client_); if (states_.has_ctrl_authority) { ROS_INFO("Obtained control authority."); } else { ROS_WARN("Failed obtaining control authority."); } std_msgs::Bool msg; msg.data = states_.has_ctrl_authority; ctrl_auth_pub_.publish(msg); return states_.has_ctrl_authority; } bool PositionController::releaseControlAuthority( std_srvs::Empty::Request& request, std_srvs::Empty::Response& response) { dji_sdk::SDKControlAuthority::Request sdk_ca_req; sdk_ca_req.control_enable = dji_sdk::SDKControlAuthority::Request::RELEASE_CONTROL; const bool success = fm_comm::callDjiTask<dji_sdk::SDKControlAuthority>( sdk_ca_req, sdk_ctrl_authority_client_); if (success && states_.has_ctrl_authority) { ROS_INFO("Released control authority."); states_.reset(); // Invalidate state. } else if (!success && states_.has_ctrl_authority) { ROS_ERROR("Cannot release control authority."); // Invalidate goal. Controller will stop publishing and DJI will hover at // current position. states_.reset(); // Invalidate state. states_.has_ctrl_authority = true; } else { states_.reset(); // Invalidate state. } std_msgs::Bool msg; msg.data = states_.has_ctrl_authority; ctrl_auth_pub_.publish(msg); return success; } bool PositionController::switchControlFrame( std_srvs::SetBool::Request& request, std_srvs::SetBool::Response& response) { // true means AGL! if (request.data && params_.altitude_mode != AltitudeMode::kAGL) { // check if requirements are met for AGL if (states_.has_agl) { states_.goal_type = GoalType::kPose; mav_msgs::EigenTrajectoryPoint new_goal; new_goal.timestamp_ns = ros::Time::now().toNSec(); new_goal.orientation_W_B = states_.mav.orientation_W_B; new_goal.position_W = states_.mav.position_W; new_goal.position_W.z() = states_.agl; // set z- setpoint to current AGL. states_.goal = new_goal; params_.altitude_mode = AltitudeMode::kAGL; response.success = true; } else { ROS_WARN_STREAM("Switch to AGL Mode failed, agl data not received."); response.success = false; } } else if (!request.data && params_.altitude_mode != kENU) { // Switch back to ENU if (states_.agl >= params_.min_transition_altitude) { states_.goal_type = GoalType::kPose; mav_msgs::EigenTrajectoryPoint new_goal; new_goal.timestamp_ns = ros::Time::now().toNSec(); new_goal.orientation_W_B = states_.mav.orientation_W_B; new_goal.position_W = states_.mav.position_W; states_.goal = new_goal; params_.altitude_mode = AltitudeMode::kENU; response.success = true; } else { ROS_WARN_STREAM("Below transition altitude for AGL => ENU switch."); response.success = false; } } else if (request.data && params_.altitude_mode == kAGL) { // Already in this mode. response.success = true; } else if (!request.data && params_.altitude_mode == kENU) { // Already in this mode. response.success = true; } return true; } void PositionController::receiveGoal( const geometry_msgs::PoseStampedConstPtr& msg) { ROS_INFO_ONCE("Received first pose command."); if (!states_.has_ctrl_authority) return; // if (params_.altitude_mode == AltitudeMode::kAGL // && msg->header.frame_id != "AGL") { // ROS_WARN_STREAM( // "Received Goal in frame " << msg->header.frame_id << " in AGL // Mode!"); // return; // } // // if (params_.altitude_mode == AltitudeMode::kENU // && msg->header.frame_id == "AGL") { // ROS_WARN_STREAM( // "Received Goal in frame " << msg->header.frame_id << " in ENU // Mode!"); // return; // } mav_msgs::eigenTrajectoryPointFromPoseMsg(*msg, &states_.goal); states_.goal_type = GoalType::kPose; } void PositionController::receivePolynomialTrajectory( const mav_planning_msgs::PolynomialTrajectory4D& msg) { ROS_INFO_ONCE("Received first trajectory command."); if (!states_.has_ctrl_authority) return; // TODO(rikba): Set correct frame in trajectory message. // if (params_.altitude_mode == AltitudeMode::kAGL // && msg.header.frame_id != "AGL") { // return; // } // // if (params_.altitude_mode == AltitudeMode::kENU // && msg.header.frame_id == "AGL") { // return; // } if (!mav_trajectory_generation::polynomialTrajectoryMsgToTrajectory( msg, &states_.trajectory)) { ROS_ERROR("Cannot convert trajectory message."); states_.goal_type = GoalType::kNone; return; } states_.trajectory_start = ros::Time::now(); states_.goal_type = GoalType::kPolynomialTrajectory; } void PositionController::updateGoalPose() { switch (states_.goal_type) { case GoalType::kPose: { break; } case GoalType::kPolynomialTrajectory: { double t = (ros::Time::now() - states_.trajectory_start).toSec(); t = t > states_.trajectory.getMaxTime() ? states_.trajectory.getMaxTime() : t; if (!mav_trajectory_generation::sampleTrajectoryAtTime( states_.trajectory, t, &states_.goal)) { ROS_ERROR("Cannot sample trajectory. Release control authority."); std_srvs::Empty::Request req; std_srvs::Empty::Response res; while (!releaseControlAuthority(req, res)) { ros::Duration(0.1).sleep(); } } break; } default: break; } } void PositionController::receiveLocalPosition( const geometry_msgs::PointStampedConstPtr& msg) { if (states_.goal_type == GoalType::kNone || !states_.has_ctrl_authority) return; states_.has_position = true; tf::pointMsgToEigen(msg->point, states_.mav.position_W); // Control action. // TODO(rikba): Handle message time synchronization... updateGoalPose(); switch (params_.control_type) { case ControlType::kPosition: { sensor_msgs::Joy ctrl_ENUposition_yaw; if (updatePositionControlReference(&ctrl_ENUposition_yaw)) { ctrl_pos_yaw_pub_.publish(ctrl_ENUposition_yaw); } break; } case ControlType::kVelocity: { sensor_msgs::Joy ctrl_ENUvelocity_yawrate; if (updateVelocityControlReference(&ctrl_ENUvelocity_yawrate)) { ctrl_vel_yawrate_pub_.publish(ctrl_ENUvelocity_yawrate); } break; } default: break; } } bool PositionController::updatePositionControlReference( sensor_msgs::Joy* ctrl_ENUposition_yaw) const { ROS_ASSERT(ctrl_ENUposition_yaw); ctrl_ENUposition_yaw->axes.clear(); ctrl_ENUposition_yaw->header.stamp = ros::Time::now(); ctrl_ENUposition_yaw->header.frame_id = "ground_ENU"; if (states_.goal_type == GoalType::kNone || !states_.has_ctrl_authority) return false; // DJI coordinate transform. double x_off = states_.goal.position_W.x() - states_.mav.position_W.x(); // Position offset x. double y_off = states_.goal.position_W.y() - states_.mav.position_W.y(); // Position offset y. // Control action. ctrl_ENUposition_yaw->axes.push_back(x_off); ctrl_ENUposition_yaw->axes.push_back(y_off); double z_off = 0.0; if (params_.altitude_mode == AltitudeMode::kAGL) { z_off = states_.mav.position_W.z() - states_.agl; } ctrl_ENUposition_yaw->axes.push_back(states_.goal.position_W.z() + z_off); ctrl_ENUposition_yaw->axes.push_back(states_.goal.position_W.z()); ctrl_ENUposition_yaw->axes.push_back(states_.goal.getYaw()); // Publish reference for visualization. geometry_msgs::PoseStamped ref; mav_msgs::msgPoseStampedFromEigenTrajectoryPoint(states_.goal, &ref); ref.header = ctrl_ENUposition_yaw->header; pos_yaw_ref_pub_.publish(ref); // Publish position error Eigen::Vector3d position_error(x_off, y_off, z_off); std_msgs::Float32 pos_error_msg; pos_error_msg.data = position_error.norm(); pos_error_pub_.publish(pos_error_msg); return true; } bool PositionController::updateVelocityControlReference( sensor_msgs::Joy* ctrl_ENUvelocity_yawrate) const { ROS_ASSERT(ctrl_ENUvelocity_yawrate); ctrl_ENUvelocity_yawrate->axes.clear(); ctrl_ENUvelocity_yawrate->header.stamp = ros::Time::now(); ctrl_ENUvelocity_yawrate->header.frame_id = "ground_ENU"; const std::string kWarningPrefix = "Cannot update control reference. "; if (!states_.has_position) { ROS_WARN_STREAM(kWarningPrefix << "No position."); return false; } if (!states_.has_velocity) { ROS_WARN_STREAM(kWarningPrefix << "No linear velocity."); return false; } if (!states_.has_translational_acceleration) { ROS_WARN_STREAM(kWarningPrefix << "No linear acceleration."); return false; } if (!states_.has_attitude) { ROS_WARN_STREAM(kWarningPrefix << "No attitude."); return false; } if (!states_.has_angular_velocity) { ROS_WARN_STREAM(kWarningPrefix << "No angular velocity."); return false; } if (!states_.has_angular_acceleration) { ROS_WARN_STREAM(kWarningPrefix << "No angular acceleration."); return false; } if (!states_.has_ctrl_authority) { ROS_WARN_STREAM(kWarningPrefix << "No control authority."); return false; } if (params_.altitude_mode == kAGL && !states_.has_agl) { ROS_WARN_STREAM(kWarningPrefix << "No AGL."); return false; } if (states_.goal_type == GoalType::kNone) { ROS_WARN_STREAM(kWarningPrefix << "Invalid goal type."); return false; } // Translation. Eigen::Vector3d position_error = states_.goal.position_W - states_.mav.position_W; if (params_.altitude_mode == kAGL) { position_error.z() = states_.goal.position_W.z() - states_.agl; } const Eigen::Vector3d velocity_error = states_.goal.velocity_W - states_.mav.velocity_W; const Eigen::Vector3d acceleration_W = states_.mav.orientation_W_B.toRotationMatrix() * states_.mav.acceleration_B; const Eigen::Vector3d acceleration_error = states_.goal.acceleration_W - acceleration_W; const Eigen::Vector3d dv = Eigen::Vector3d(params_.K_px, params_.K_py, params_.K_pz).asDiagonal() * position_error + Eigen::Vector3d(params_.K_vx, params_.K_vy, params_.K_vz).asDiagonal() * velocity_error + Eigen::Vector3d(params_.K_ax, params_.K_ay, params_.K_az).asDiagonal() * acceleration_error; const Eigen::Vector3d v_ref = states_.mav.velocity_W + dv; ctrl_ENUvelocity_yawrate->axes.push_back(v_ref.x()); ctrl_ENUvelocity_yawrate->axes.push_back(v_ref.y()); ctrl_ENUvelocity_yawrate->axes.push_back(v_ref.z()); // Orientation. // Map the yaw error to lie in the range [-pi, pi]. const double yaw_error = angles::shortest_angular_distance( mav_msgs::yawFromQuaternion(states_.mav.orientation_W_B), states_.goal.getYaw()); const Eigen::Vector3d angular_velocity_W = states_.mav.orientation_W_B.toRotationMatrix() * states_.mav.angular_velocity_B; const double yaw_rate_error = states_.goal.getYawRate() - angular_velocity_W.z(); const Eigen::Vector3d angular_acceleration_W = states_.mav.orientation_W_B.toRotationMatrix() * states_.mav.angular_acceleration_B; const double yaw_acc_error = states_.goal.getYawAcc() - angular_acceleration_W.z(); const double d_omega = params_.K_yaw * yaw_error + params_.K_yaw_rate * yaw_rate_error + params_.K_yaw_acc * yaw_acc_error; const double omega_ref = angular_velocity_W.z() + d_omega; ctrl_ENUvelocity_yawrate->axes.push_back(omega_ref); limitVelocityControlReference(ctrl_ENUvelocity_yawrate); // Publish reference for visualization. geometry_msgs::PoseStamped ref; mav_msgs::msgPoseStampedFromEigenTrajectoryPoint(states_.goal, &ref); ref.header = ctrl_ENUvelocity_yawrate->header; pos_yaw_ref_pub_.publish(ref); // Publish position error std_msgs::Float32 pos_error_msg; pos_error_msg.data = position_error.norm(); pos_error_pub_.publish(pos_error_msg); return true; } void PositionController::limitVelocityControlReference( sensor_msgs::Joy* ctrl_ENUvelocity_yawrate) const { ROS_ASSERT(ctrl_ENUvelocity_yawrate); ROS_ASSERT(ctrl_ENUvelocity_yawrate->axes.size() != 4); // v_xy_max. double v_xy = Eigen::Vector2d(ctrl_ENUvelocity_yawrate->axes[0], ctrl_ENUvelocity_yawrate->axes[1]) .norm(); if (v_xy > params_.v_xy_max) { Eigen::Vector2d v_xy_new = Eigen::Vector2d(ctrl_ENUvelocity_yawrate->axes[0], ctrl_ENUvelocity_yawrate->axes[1]) .normalized() * params_.v_xy_max; ctrl_ENUvelocity_yawrate->axes[0] = v_xy_new.x(); ctrl_ENUvelocity_yawrate->axes[1] = v_xy_new.y(); } // v_z. if (ctrl_ENUvelocity_yawrate->axes[2] > params_.v_z_up_max) { ctrl_ENUvelocity_yawrate->axes[2] = params_.v_z_up_max; } else if (ctrl_ENUvelocity_yawrate->axes[2] < -params_.v_z_down_max) { ctrl_ENUvelocity_yawrate->axes[2] = -params_.v_z_down_max; } // Yaw rate. if (ctrl_ENUvelocity_yawrate->axes[3] > params_.yaw_rate_max) { ctrl_ENUvelocity_yawrate->axes[3] = params_.yaw_rate_max; } else if (ctrl_ENUvelocity_yawrate->axes[3] < -params_.yaw_rate_max) { ctrl_ENUvelocity_yawrate->axes[3] = -params_.yaw_rate_max; } } void PositionController::receiveVelocity( const geometry_msgs::Vector3StampedConstPtr& msg) { if (states_.goal_type == GoalType::kNone || !states_.has_ctrl_authority) return; states_.has_velocity = true; tf::vectorMsgToEigen(msg->vector, states_.mav.velocity_W); } void PositionController::receiveAGL( const geometry_msgs::PointStampedConstPtr& msg) { ROS_INFO_ONCE("Received first AGL."); states_.has_agl = true; states_.agl = msg->point.z; } void PositionController::receiveAcceleration( const geometry_msgs::Vector3StampedConstPtr& msg) { if (states_.goal_type == GoalType::kNone || !states_.has_ctrl_authority) return; states_.has_translational_acceleration = true; Eigen::Vector3d acceleration_W; tf::vectorMsgToEigen(msg->vector, acceleration_W); states_.mav.acceleration_B = states_.mav.orientation_W_B.inverse().toRotationMatrix() * acceleration_W; } void PositionController::receiveAttitude( const geometry_msgs::QuaternionStampedConstPtr& msg) { if (states_.goal_type == GoalType::kNone || !states_.has_ctrl_authority) return; states_.has_attitude = true; tf::quaternionMsgToEigen(msg->quaternion, states_.mav.orientation_W_B); } void PositionController::receiveAngularVelocity( const geometry_msgs::Vector3StampedConstPtr& msg) { if (states_.goal_type == GoalType::kNone || !states_.has_ctrl_authority) return; // Angular velocity. states_.has_angular_velocity = true; tf::vectorMsgToEigen(msg->vector, states_.mav.angular_velocity_B); // Angular acceleration. const geometry_msgs::Vector3Stamped previous_angular_velocity_B = states_.angular_velocity_B; states_.angular_velocity_B = *msg; if (previous_angular_velocity_B.header.stamp.isValid()) { states_.has_angular_acceleration = true; Eigen::Vector3d omega, omega_prev; tf::vectorMsgToEigen(states_.angular_velocity_B.vector, omega); tf::vectorMsgToEigen(previous_angular_velocity_B.vector, omega_prev); const double dt = (states_.angular_velocity_B.header.stamp - previous_angular_velocity_B.header.stamp) .toSec(); states_.mav.angular_acceleration_B = (omega - omega_prev) / dt; } } void PositionController::receiveRC(const sensor_msgs::JoyConstPtr& msg) { // Invalidate goal on new mode. if (msg->axes[4] != states_.flight_mode_axis) { ROS_INFO_COND(states_.goal_type != GoalType::kNone, "Invalidate current goal."); ROS_INFO_COND(states_.has_ctrl_authority, "Release control authority."); std_srvs::Empty::Request req; std_srvs::Empty::Response res; while (!releaseControlAuthority(req, res)) { ros::Duration(0.1).sleep(); } } states_.flight_mode_axis = msg->axes[4]; } } // namespace fm_control
isawnyu/isaw.web
src/isaw.theme/isaw/theme/browser/people.py
<gh_stars>0 from Products.Five.browser import BrowserView class PeopleView(BrowserView): """Base vew class for the @@people-view""" def people(self): brains = self._query() result = [] for brain in brains: profile = brain.getObject() data = { 'id': profile.getId(), 'name': profile.Title(), 'email': profile.Email or '', 'html_blurb': profile.Titles(), 'url': profile.absolute_url(), 'has_image': getattr(profile, 'Image', False), 'image_url': '{}/@@images/Image/mini'.format( profile.absolute_url() ), } result.append(data) return result class PeopleViewFolder(PeopleView): """View class for the @@people-view on Folders""" def _query(self): return self.context.getFolderContents( contentFilter={'portal_type': 'profile'} ) class PeopleViewCollection(PeopleView): """View class for the @@people-view on Collections""" def _query(self): return [ b for b in self.context.queryCatalog() if b.portal_type == 'profile' ]
hanlukman/projectD
assets/demos/complete/rotatablenodes/RotatablePorts.js
/**************************************************************************** ** @license ** This demo file is part of yFiles for HTML 2.2. ** Copyright (c) 2000-2019 by yWorks GmbH, Vor dem Kreuzberg 28, ** 72070 Tuebingen, Germany. All rights reserved. ** ** yFiles demo files exhibit yFiles for HTML functionalities. Any redistribution ** of demo files in source code or binary form, with or without ** modification, is not permitted. ** ** Owners of a valid software license for a yFiles for HTML version that this ** demo is shipped with are allowed to use the demo source code as basis ** for their own yFiles for HTML powered applications. Use of such programs is ** governed by the rights and conditions as set out in the yFiles for HTML ** license agreement. ** ** THIS SOFTWARE IS PROVIDED ''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 yWorks 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. ** ***************************************************************************/ import { BaseClass, Class, FreeNodePortLocationModel, ILookup, IMarkupExtensionConverter, INode, IPort, IPortLocationModel, IPortLocationModelParameter, IPortOwner, IWriteContext, MarkupExtension, Matrix, Point } from 'yfiles' import { RotatableNodeStyleDecorator } from './RotatableNodes.js' /** * Port location model decorator that automatically provides the location in the rotated coordinates of the owner. */ export class RotatablePortLocationModelDecorator extends BaseClass( IPortLocationModel, IMarkupExtensionConverter ) { static get INSTANCE() { // eslint-disable-next-line no-return-assign return ( RotatablePortLocationModelDecorator.$instance || (RotatablePortLocationModelDecorator.$instance = new RotatablePortLocationModelDecorator()) ) } /** * Creates a new instance wrapping a {@link FreeNodePortLocationModel}. */ constructor() { super() this.$wrapped = new FreeNodePortLocationModel() } /** * Returns the wrapped location model. * @return {FreeNodePortLocationModel} */ get wrapped() { return this.$wrapped } /** * Specifies the wrapped location model. * It is only used when new parameters are created via {@link #createParameter}. * @param {FreeNodePortLocationModel} wrapped */ set wrapped(wrapped) { this.$wrapped = wrapped } /** * Delegates to the wrapped location model's lookup. * @param {Class} type */ lookup(type) { return this.wrapped.lookup(type) } /** * Recalculates the coordinates provided by parameter. * This has only an effect when parameter is created by this model and the owner of port has a * {@link RotatableNodes.RotatableNodeStyleDecorator}. * @param {IPort} port * @param {IPortLocationModelParameter} parameter * @return {Point} */ getLocation(port, parameter) { const param = parameter.wrapped const coreLocation = this.wrapped.getLocation(port, param) const ownerNode = port.owner if (!INode.isInstance(ownerNode)) { return coreLocation } const angle = getAngle(ownerNode) if (Math.abs(angle) < EPS) { return coreLocation } const matrix = new Matrix() matrix.rotate(-toRadians(angle), ownerNode.layout.center) return matrix.transform(coreLocation) } /** * Creates a parameter that matches the given location. * @param {IPortOwner} portOwner * @param {Point} location * @return {IPortLocationModelParameter} */ createParameter(portOwner, location) { const ownerNode = portOwner const angle = INode.isInstance(ownerNode) ? getAngle(ownerNode) : 0 if (Math.abs(angle) >= EPS) { // Undo the rotation by the ownerNode so that we can create a core parameter for the unrotated layout. const matrix = new Matrix() matrix.rotate(toRadians(angle), ownerNode.layout.center) location = matrix.transform(location) } return new RotatablePortLocationModelDecoratorParameter( this.wrapped.createParameter(portOwner, location), this ) } /** * Wraps a given parameter so it can be automatically rotated. * The core parameter is assumed to provide coordinates for an un-rotated owner. * @param {IPortLocationModelParameter} coreParameter * @return {IPortLocationModelParameter} */ createWrappingParameter(coreParameter) { return new RotatablePortLocationModelDecoratorParameter(coreParameter, this) } /** * Returns the lookup of the wrapped location model. * @param {IPort} port * @param {IPortLocationModelParameter} parameter * @return {ILookup} */ getContext(port, parameter) { return this.wrapped.getContext(port, parameter) } /** * Returns that this port location model can be converted. * @param {IWriteContext} context * @param {object} value * @return {boolean} */ canConvert(context, value) { return true } /** * Converts this port location model using {@link RotatablePortLocationModelDecoratorExtension}. * @param {IWriteContext} context * @param {object} value * @return {MarkupExtension} */ convert(context, value) { const markupExtension = new RotatablePortLocationModelDecoratorExtension() markupExtension.wrapped = this.wrapped return markupExtension } } const EPS = 0.001 /** * A {@link IPortLocationModelParameter} decorator for ports using * {@link RotatablePortLocationModelDecorator} to adjust the port location to the node rotation. */ export class RotatablePortLocationModelDecoratorParameter extends BaseClass( IPortLocationModelParameter, IMarkupExtensionConverter ) { /** * Creates a new instance wrapping the given location model parameter. * @param {IPortLocationModelParameter} wrapped * @param {RotatablePortLocationModelDecorator} model */ constructor(wrapped, model) { super() this.$wrapped = wrapped this.$model = model } /** * Creates a copy of this location model parameter. * @return {RotatablePortLocationModelDecoratorParameter} */ clone() { return new RotatablePortLocationModelDecoratorParameter(this.wrapped.clone(), this.model) } /** * Returns the model. * @return {RotatablePortLocationModelDecorator} */ get model() { return this.$model } /** * Returns the wrapped parameter. * @return {RotatablePortLocationModelDecorator} */ get wrapped() { return this.$wrapped } /** * Accepts all port owners that are supported by the wrapped parameter. * @param {IPortOwner} portOwner * @return {boolean} */ supports(portOwner) { return this.wrapped.supports(portOwner) } /** * Returns that this port location model parameter can be converted. * @param {IWriteContext} context * @param {object} value * @return {boolean} */ canConvert(context, value) { return true } /** * Converts this port location model parameter using {@link RotatablePortLocationModelDecoratorParameterExtension}. * @param {IWriteContext} context * @param {object} value * @return {MarkupExtension} */ convert(context, value) { const markupExtension = new RotatablePortLocationModelDecoratorParameterExtension() markupExtension.model = RotatablePortLocationModelDecoratorParameter.INSTANCE ? null : this.model markupExtension.wrapped = this.wrapped return markupExtension } } /** * Markup extension that helps (de-)serializing a {@link RotatablePortLocationModelDecorator). */ export const RotatablePortLocationModelDecoratorExtension = Class( 'RotatablePortLocationModelDecoratorExtension', { $extends: MarkupExtension, $wrapped: null, wrapped: { get() { return this.$wrapped }, set(value) { this.$wrapped = value } }, /** * @param {ILookup} serviceProvider * @return {object} */ provideValue(serviceProvider) { const model = new RotatablePortLocationModelDecorator() model.wrapped = this.wrapped return model } } ) /** * Markup extension that helps (de-)serializing a {@link RotatablePortLocationModelDecoratorParameter). */ export const RotatablePortLocationModelDecoratorParameterExtension = Class( 'RotatablePortLocationModelDecoratorParameterExtension', { $extends: MarkupExtension, $model: null, model: { get() { return this.$model }, set(value) { this.$model = value } }, $wrapped: null, wrapped: { get() { return this.$wrapped }, set(value) { this.$wrapped = value } }, /** * @param {ILookup} serviceProvider * @return {object} */ provideValue(serviceProvider) { const model = this.model instanceof RotatablePortLocationModelDecorator ? this.model : RotatablePortLocationModelDecorator.INSTANCE return model.createWrappingParameter(this.wrapped) } } ) /** * Returns the current angle of the given rotated node. * @param {INode} node * @return {number} */ function getAngle(node) { return node.style instanceof RotatableNodeStyleDecorator ? node.style.angle : 0 } /** * Returns the given angle in radians. * @param {number} degrees * @return {number} */ function toRadians(degrees) { return degrees / 180 * Math.PI }
ketanchoyal/theParker
theParker/app/src/main/java/com/service/parking/theparker/View/SnackbarWrapper.java
<filename>theParker/app/src/main/java/com/service/parking/theparker/View/SnackbarWrapper.java package com.service.parking.theparker.View; import android.content.Context; import android.graphics.PixelFormat; import android.os.IBinder; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.coordinatorlayout.widget.CoordinatorLayout; import com.google.android.material.snackbar.Snackbar; import android.view.ContextThemeWrapper; import android.view.Gravity; import android.view.View; import android.view.WindowManager; import android.widget.FrameLayout; import com.service.parking.theparker.R; public class SnackbarWrapper { private final CharSequence text; private final int duration; private final WindowManager windowManager; private final Context appplicationContext; @Nullable private Snackbar.Callback externalCallback; @Nullable private Action action; @NonNull public static SnackbarWrapper make(@NonNull Context applicationContext, @NonNull CharSequence text, @Snackbar.Duration int duration) { return new SnackbarWrapper(applicationContext, text, duration); } @NonNull public static SnackbarWrapper make(@NonNull Context applicationContext, @NonNull CharSequence text) { return new SnackbarWrapper(applicationContext, text); } private SnackbarWrapper(@NonNull final Context appplicationContext, @NonNull CharSequence text, @Snackbar.Duration int duration) { this.appplicationContext = appplicationContext; this.windowManager = (WindowManager) appplicationContext.getSystemService(Context.WINDOW_SERVICE); this.text = text; this.duration = duration; } private SnackbarWrapper(@NonNull final Context appplicationContext, @NonNull CharSequence text) { this.appplicationContext = appplicationContext; this.windowManager = (WindowManager) appplicationContext.getSystemService(Context.WINDOW_SERVICE); this.text = text; this.duration = Snackbar.LENGTH_LONG; } public void show() { WindowManager.LayoutParams layoutParams = createDefaultLayoutParams(WindowManager.LayoutParams.TYPE_TOAST, null); windowManager.addView(new FrameLayout(appplicationContext) { @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); onRootViewAvailable(this); } }, layoutParams); } private void onRootViewAvailable(final FrameLayout rootView) { final CoordinatorLayout snackbarContainer = new CoordinatorLayout(new ContextThemeWrapper(appplicationContext, R.style.FOL_Theme_SnackbarWrapper)) { @Override public void onAttachedToWindow() { super.onAttachedToWindow(); onSnackbarContainerAttached(rootView, this); } }; windowManager.addView(snackbarContainer, createDefaultLayoutParams(WindowManager.LayoutParams.TYPE_APPLICATION_PANEL, rootView.getWindowToken())); } private void onSnackbarContainerAttached(final View rootView, final CoordinatorLayout snackbarContainer) { Snackbar snackbar = Snackbar.make(snackbarContainer, text, duration); snackbar.addCallback(new Snackbar.Callback() { @Override public void onDismissed(Snackbar snackbar, int event) { super.onDismissed(snackbar, event); // Clean up (NOTE! This callback can be called multiple times) if (snackbarContainer.getParent() != null && rootView.getParent() != null) { windowManager.removeView(snackbarContainer); windowManager.removeView(rootView); } if (externalCallback != null) { externalCallback.onDismissed(snackbar, event); } } @Override public void onShown(Snackbar snackbar) { super.onShown(snackbar); if (externalCallback != null) { externalCallback.onShown(snackbar); } } }); if (action != null) { snackbar.setAction(action.text, action.listener); } snackbar.show(); } private WindowManager.LayoutParams createDefaultLayoutParams(int type, @Nullable IBinder windowToken) { WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(); layoutParams.format = PixelFormat.TRANSLUCENT; layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT; layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT; layoutParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM; layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL; layoutParams.type = type; layoutParams.token = windowToken; return layoutParams; } @NonNull public SnackbarWrapper setCallback(@Nullable Snackbar.Callback callback) { this.externalCallback = callback; return this; } @NonNull public SnackbarWrapper setAction(CharSequence text, final View.OnClickListener listener) { action = new Action(text, listener); return this; } private static class Action { private final CharSequence text; private final View.OnClickListener listener; public Action(CharSequence text, View.OnClickListener listener) { this.text = text; this.listener = listener; } } }
juandarr/ProjectEuler
11.py
""" Finds biggest product of n digits in a 2D grid in every possible direction Author: <NAME> """ import math ar = """08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48""" ar = ar.split('\n') for i in range(len(ar)): ar[i] = ar[i].split(' ') digits = 4 directions = [] for i in range(len(ar)): directions.append([]) for j in range(len(ar[0])): directions[-1].append([[0,0],[0,0],[0,0],[0,0]]) for j in range(len(directions[0])): for i in range(digits-1): directions[i][j][0][0]=1 directions[i][j][2][0]=1 directions[i][j][3][0]=1 for j in range(len(directions[0])): for i in range(len(directions)-digits+1, len(directions)): directions[i][j][0][1]=1 directions[i][j][2][1]=1 directions[i][j][3][1]=1 for j in range(digits-1): for i in range(len(directions)): directions[i][j][1][1]=1 directions[i][j][2][1]=1 directions[i][j][3][0]=1 for j in range(len(directions[0])-digits+1, len(directions[0])): for i in range(len(directions)): directions[i][j][1][0]=1 directions[i][j][2][0]=1 directions[i][j][3][1]=1 inc = {(0,0):(-1,0), (0,1):(1,0),(1,0):(0,1),(1,1):(0,-1),(2,0):(-1,1),(2,1):(1,-1),(3,0):(-1,-1),(3,1):(1,1)} def biggest_product(array, directions, inc): max_product = 0 for i in range(len(array)): for j in range(len(array[0])): for ori in range(4): for d in range(2): if directions[i][j][ori][d]==0: number = 1 for counter in range(4): number *= int(array[i+counter*inc[(ori,d)][0]][j+counter*inc[(ori,d)][1]]) directions[i][j][ori][d] = 1 directions[i+3*inc[(ori,d)][0]][j+3*inc[(ori,d)][1]][ori][abs(d-1)] = 1 if number > max_product: max_product = number return max_product if __name__ == "__main__": print('The biggest product of {0} digits in any direction of the 2D is {1}'.format(digits, biggest_product(ar, directions, inc)))
nguillaumin/nabaztag-server
net.violet.platform/src/main/java/net/violet/platform/daemons/crawlers/PurgeContentDaemon.java
<filename>net.violet.platform/src/main/java/net/violet/platform/daemons/crawlers/PurgeContentDaemon.java package net.violet.platform.daemons.crawlers; import net.violet.db.records.Record.RecordWalker; import net.violet.platform.datamodel.Content; import net.violet.platform.datamodel.Files; import net.violet.platform.datamodel.ObjectHasReadContent; import net.violet.platform.datamodel.VAction; import net.violet.platform.datamodel.factories.Factories; import net.violet.platform.datamodel.factories.ServiceFactory; import org.apache.log4j.Logger; public class PurgeContentDaemon extends AbstractCrawler { private static final Logger LOGGER = Logger.getLogger(PurgeContentDaemon.class); private static final int NB_SAFE_CONTENT_PODCAST = 2; private static final int NB_SAFE_CONTENT_RSS = 31; /** * Processeur des contenus. */ private static final RecordWalker<Content> CONTENT_WALKER = new RecordWalker<Content>() { private VAction action; public void process(Content inContent) { if ((inContent.getAction() != null) && ((this.action == null) || !inContent.getAction().equals(this.action))) { this.action = inContent.getAction(); final Content content = Factories.CONTENT.findOldestByAction(this.action, (this.action.getService().equals(ServiceFactory.SERVICE.PODCAST.getService())) ? PurgeContentDaemon.NB_SAFE_CONTENT_PODCAST : PurgeContentDaemon.NB_SAFE_CONTENT_RSS); for (final ObjectHasReadContent anOHRC : Factories.OBJECT_HAS_READ_CONTENT.findAllByAction(this.action)) { if (content.getId() > anOHRC.getContent().getId()) { anOHRC.setContent(content); } } } final Files theFile = inContent.getFile(); if (inContent.countObjectHasReadContent() == 0) { PurgeContentDaemon.LOGGER.info("Deleting content " + inContent.getId()); if (inContent.delete() && (theFile != null)) { theFile.scheduleDeletion(); } } } }; /** * Constructeur à partir des paramètres en ligne de commande. */ public PurgeContentDaemon(String[] inArgs) { super(inArgs); } /** * Itération. */ @Override protected void process() { Factories.VACTION.walk(new RecordWalker<VAction>() { public void process(VAction inAction) { PurgeContentDaemon.processAction(inAction, (inAction.getService().equals(ServiceFactory.SERVICE.PODCAST.getService())) ? PurgeContentDaemon.NB_SAFE_CONTENT_PODCAST : PurgeContentDaemon.NB_SAFE_CONTENT_RSS); } }); // 1/ purge des contenus sans action Factories.CONTENT.walkWithoutAction(PurgeContentDaemon.CONTENT_WALKER); } /** * Travaille sur une action. */ public static void processAction(VAction inAction, int inNbContent2Keep) { // TODO: // 2/ purge des actions sans personne d'abonné. // 3/ récupération d'un nombre variable de contenus. PurgeContentDaemon.LOGGER.info("Processing action " + inAction.getId() + "(" + inAction.getUrl() + ")"); Factories.CONTENT.walkOlderByAction(inAction, inNbContent2Keep, PurgeContentDaemon.CONTENT_WALKER); } }
skolbin-ssi/Dynamics-365-Fraud-Protection-ManualReview
backend/queues/src/main/java/com/griddynamics/msd365fp/manualreview/queues/model/ItemEvent.java
<filename>backend/queues/src/main/java/com/griddynamics/msd365fp/manualreview/queues/model/ItemEvent.java<gh_stars>1-10 // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. package com.griddynamics.msd365fp.manualreview.queues.model; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.griddynamics.msd365fp.manualreview.model.event.Event; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import java.io.Serializable; @NoArgsConstructor @AllArgsConstructor @Data @Slf4j public class ItemEvent implements Serializable { @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "klass", visible = true) private Event event; private Class<? extends Event> klass; private String sendingId; }
imcloudfloating/Cloud-OJ
judge-service/src/main/java/group/_204/oj/judge/config/RabbitConfig.java
<reponame>imcloudfloating/Cloud-OJ package group._204.oj.judge.config; import org.springframework.amqp.core.Queue; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class RabbitConfig { public static final String JUDGE_QUEUE = "JudgeQueue"; public static final String COMMIT_QUEUE = "CommitQueue"; @Bean public Queue commitQueue() { return new Queue(COMMIT_QUEUE); } @Bean public Queue judgeQueue() { return new Queue(JUDGE_QUEUE); } }
forestGzh/VTK
IO/XML/vtkXMLPolyDataWriter.h
<reponame>forestGzh/VTK /*========================================================================= Program: Visualization Toolkit Module: vtkXMLPolyDataWriter.h Copyright (c) <NAME>, <NAME>, <NAME> All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /** * @class vtkXMLPolyDataWriter * @brief Write VTK XML PolyData files. * * vtkXMLPolyDataWriter writes the VTK XML PolyData file format. One * polygonal data input can be written into one file in any number of * streamed pieces (if supported by the rest of the pipeline). The * standard extension for this writer's file format is "vtp". This * writer is also used to write a single piece of the parallel file * format. * * @sa * vtkXMLPPolyDataWriter */ #ifndef vtkXMLPolyDataWriter_h #define vtkXMLPolyDataWriter_h #include "vtkIOXMLModule.h" // For export macro #include "vtkXMLUnstructuredDataWriter.h" class vtkPolyData; class VTKIOXML_EXPORT vtkXMLPolyDataWriter : public vtkXMLUnstructuredDataWriter { public: vtkTypeMacro(vtkXMLPolyDataWriter,vtkXMLUnstructuredDataWriter); void PrintSelf(ostream& os, vtkIndent indent) override; static vtkXMLPolyDataWriter* New(); /** * Get/Set the writer's input. */ vtkPolyData* GetInput(); /** * Get the default file extension for files written by this writer. */ const char* GetDefaultFileExtension() override; protected: vtkXMLPolyDataWriter(); ~vtkXMLPolyDataWriter() override; // see algorithm for more info int FillInputPortInformation(int port, vtkInformation* info) override; const char* GetDataSetName() override; void AllocatePositionArrays() override; void DeletePositionArrays() override; void WriteInlinePieceAttributes() override; void WriteInlinePiece(vtkIndent indent) override; void WriteAppendedPieceAttributes(int index) override; void WriteAppendedPiece(int index, vtkIndent indent) override; void WriteAppendedPieceData(int index) override; vtkIdType GetNumberOfInputCells() override; void CalculateSuperclassFraction(float* fractions); // Positions of attributes for each piece. unsigned long* NumberOfVertsPositions; unsigned long* NumberOfLinesPositions; unsigned long* NumberOfStripsPositions; unsigned long* NumberOfPolysPositions; OffsetsManagerArray *VertsOM; OffsetsManagerArray *LinesOM; OffsetsManagerArray *StripsOM; OffsetsManagerArray *PolysOM; private: vtkXMLPolyDataWriter(const vtkXMLPolyDataWriter&) = delete; void operator=(const vtkXMLPolyDataWriter&) = delete; }; #endif
qq187155684/BrowserDemo
src/com/android/myapidemo/smartisan/wxapi/AllShareActivity.java
package com.android.myapidemo.smartisan.wxapi; import com.android.myapidemo.R; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; public class AllShareActivity extends Activity { Handler mHandler = new Handler() { public void handleMessage(Message msg) { ShareInfo info = (ShareInfo) msg.obj; Drawable drawable = getResources().getDrawable(R.drawable.weixin_share_icon); Bitmap bitmap = null; if(drawable instanceof BitmapDrawable){ bitmap = ((BitmapDrawable)drawable).getBitmap(); } ShareUtil.shareCircleOfFriends(info.title, info.url, bitmap, info.shareType); }; }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); if (intent == null) { finish(); return; } String title = intent.getStringExtra(Intent.EXTRA_SUBJECT); String url = intent.getStringExtra(Intent.EXTRA_TEXT); int type = intent.getIntExtra(ShareUtil.SHARE_TYPE, -1); finish(); switch (type) { case ShareUtil.WEIXIN: case ShareUtil.CICLE_OF_FRIEND: ShareInfo info = new ShareInfo(url, title, type); Message msg = Message.obtain(mHandler); msg.obj = info; mHandler.sendMessageDelayed(msg, 300);//if not delay,the dialog can't dismiss. break; case ShareUtil.COPY://do nothing break; default: break; } } class ShareInfo { String url; String title; int shareType; public ShareInfo(String url, String title, int type) { this.url = url; this.title = title; this.shareType = type; } } }
UNC-Libraries/hy-c
spec/helpers/blacklight/facets_helper_behavior_spec.rb
<gh_stars>1-10 require 'rails_helper' RSpec.describe Blacklight::FacetsHelperBehavior do # only testing overridden method describe '#facet_display_value' do it "is the facet value for an ordinary facet" do allow(helper).to receive(:facet_configuration_for_field).with('simple_field').and_return(double(query: nil, date: nil, helper_method: nil, url_method: nil)) expect(helper.facet_display_value('simple_field', 'asdf')).to eq 'asdf' end it "extracts the configuration label for a query facet" do allow(helper).to receive(:facet_configuration_for_field).with('query_facet').and_return(double(query: { 'query_key' => { label: 'XYZ' } }, date: nil, helper_method: nil, url_method: nil)) expect(helper.facet_display_value('query_facet', 'query_key')).to eq 'XYZ' end it "localizes the label for date-type facets" do allow(helper).to receive(:facet_configuration_for_field).with('date_facet').and_return(double('date' => true, :query => nil, :helper_method => nil, :url_method => nil)) expect(helper.facet_display_value('date_facet', '2012-01-01')).to eq 'Sun, 01 Jan 2012 00:00:00 +0000' end it "humanizes the label for date_issued_sim facet" do # we do not flag date_issued as date type in blacklight config allow(helper).to receive(:facet_configuration_for_field).with('date_issued_sim').and_return(double('date' => false, :query => nil, :helper_method => nil, :url_method => nil)) expect(helper.facet_display_value('date_issued_sim', '2012-01-01')).to eq 'January 1, 2012' end it "humanizes the label for date_created_sim facet" do # we do not flag date_created as date type in blacklight config allow(helper).to receive(:facet_configuration_for_field).with('date_created_sim').and_return(double('date' => false, :query => nil, :helper_method => nil, :url_method => nil)) expect(helper.facet_display_value('date_created_sim', '2012-01-01')).to eq 'January 1, 2012' end it "localizes the label for date-type facets with the supplied localization options" do allow(helper).to receive(:facet_configuration_for_field).with('date_facet').and_return(double('date' => { format: :short }, :query => nil, :helper_method => nil, :url_method => nil)) expect(helper.facet_display_value('date_facet', '2012-01-01')).to eq '01 Jan 00:00' end end end
codaxy/cx-diagrams
docs/app/config/FourSides.js
import { Md } from '../components/Md'; import node from './Node'; export default { ...node, gap: { type: 'number', key: true, description: ( <cx> <Md>Inner distance between the elements.</Md> </cx> ), }, slots: { type: 'array', key: true, description: ( <cx> <Md>Order of slots. Default is `['center', 'right', 'down', 'left', 'up']`.</Md> </cx> ), }, };
j-boivie/fiaas-deploy-daemon
tests/fiaas_deploy_daemon/test_retry.py
<filename>tests/fiaas_deploy_daemon/test_retry.py from requests import Response from k8s.client import ClientError import mock import pytest from fiaas_deploy_daemon.retry import retry_on_upsert_conflict, UpsertConflict, canonical_name @pytest.mark.parametrize("status", ( 400, # Bad Request 402, # Payment Required 403, # Forbidden 404, # Not Found 405, # Method Not Allowed 406, # Not Acceptable 408, # Request Timeout 410, # Gone 411, # Length Required 413, # Payload Too Large 414, # URI Too long 415, # Unsupported Media Type 417, # Expectation Failed 426, # Upgrade Required )) def test_retry_on_conflict_should_raise_clienterror_for_non_conflict_clienterror(status): response = mock.MagicMock(spec=Response) response.status_code = status @retry_on_upsert_conflict def fail(): raise ClientError("No", response=response) with pytest.raises(ClientError): fail() def test_retry_on_conflict_should_raise_upsertconflict_for_conflict(): response = mock.MagicMock(spec=Response) response.status_code = 409 # Conflict @retry_on_upsert_conflict(max_value_seconds=0.001, max_tries=1) def fail(): raise ClientError("No", response=response) with pytest.raises(UpsertConflict): fail() def test_retry_on_conflict_should_retry_on_conflict(): response = mock.MagicMock(spec=Response) response.status_code = 409 # Conflict max_tries = 3 global calls calls = 0 @retry_on_upsert_conflict(max_value_seconds=0.001, max_tries=max_tries) def fail(): global calls calls += 1 raise ClientError(response=response) with pytest.raises(UpsertConflict): fail() assert calls == max_tries def test_retry_on_conflict_calls_decorated_function_and_returns_return_value(): expected = object() max_tries = 1 global calls calls = 0 @retry_on_upsert_conflict def succeed(): global calls calls += 1 return expected assert succeed() == expected assert calls == max_tries class NameTester(object): @classmethod def clsmethod(cls): pass def method(self): pass def name_test_function(): pass @pytest.mark.parametrize("func, expected", ( (id, "__builtin__.id"), (name_test_function, "{}.name_test_function".format(__name__)), (NameTester.clsmethod, "{}.NameTester.clsmethod".format(__name__)), (NameTester.method, "{}.NameTester.method".format(__name__)), )) def test_canonical_name(func, expected): assert canonical_name(func) == expected
finnroblin/timeblock
web/node_modules/urql/dist/urql.js
var e = require("@urql/core"); var t = require("react"); var r = require("wonka"); var n = e.createClient({ url: "/graphql" }); var u = t.createContext(n); var i = u.Provider; var a = u.Consumer; u.displayName = "UrqlContext"; var s = !1; function useClient() { var e = t.useContext(u); if ("production" !== process.env.NODE_ENV && e === n && !s) { s = !0; console.warn("Default Client: No client has been specified using urql's Provider.This means that urql will be falling back to defaults including making requests to `/graphql`.\nIf that's not what you want, please create a client and add a Provider."); } return e; } function _extends() { return (_extends = Object.assign || function(e) { for (var t = 1; t < arguments.length; t++) { var r = arguments[t]; for (var n in r) { if (Object.prototype.hasOwnProperty.call(r, n)) { e[n] = r[n]; } } } return e; }).apply(this, arguments); } var o = { fetching: !1, stale: !1, error: void 0, data: void 0, extensions: void 0, operation: void 0 }; function computeNextState(e, t) { var r = _extends({}, e, t, { fetching: !!t.fetching, stale: !!t.stale }); return function isShallowDifferent(e, t) { if ("object" != typeof e || "object" != typeof t) { return e !== t; } for (var r in e) { if (!(r in t)) { return !0; } } for (var n in t) { if (e[n] !== t[n]) { return !0; } } return !1; }(e, r) ? r : e; } function hasDepsChanged(e, t) { for (var r = 0, n = t.length; r < n; r++) { if (e[r] !== t[r]) { return !0; } } return !1; } function useMutation(n) { var u = t.useRef(!0); var i = useClient(); var a = t.useState(o); var s = a[0]; var c = a[1]; var f = t.useCallback((function(t, a) { c(_extends({}, o, { fetching: !0 })); return r.toPromise(i.executeMutation(e.createRequest(n, t), a || {})).then((function(e) { if (u.current) { c({ fetching: !1, stale: !!e.stale, data: e.data, error: e.error, extensions: e.extensions, operation: e.operation }); } return e; })); }), [ i, n, c ]); t.useEffect((function() { return function() { u.current = !1; }; }), []); return [ s, f ]; } function useRequest(r, n) { var u = t.useRef(void 0); return t.useMemo((function() { var t = e.createRequest(r, n); if (void 0 !== u.current && u.current.key === t.key) { return u.current; } else { u.current = t; return t; } }), [ r, n ]); } var c = !1; function useQuery(e) { var n = useClient(); var u = function getCacheForClient(e) { if (!e._react) { var t = new Set; var n = new Map; if (e.operations$) { r.subscribe((function(e) { if ("teardown" === e.kind && t.has(e.key)) { t.delete(e.key); n.delete(e.key); } }))(e.operations$); } e._react = { get: function get(e) { return n.get(e); }, set: function set(e, r) { t.delete(e); n.set(e, r); }, dispose: function dispose(e) { t.add(e); } }; } return e._react; }(n); var i = function isSuspense(e, t) { return e.suspense && (!t || !1 !== t.suspense); }(n, e.context); var a = useRequest(e.query, e.variables); var s = t.useMemo((function() { if (e.pause) { return null; } var t = n.executeQuery(a, _extends({}, { requestPolicy: e.requestPolicy }, e.context)); return i ? r.onPush((function(e) { u.set(a.key, e); }))(t) : t; }), [ u, n, a, i, e.pause, e.requestPolicy, e.context ]); var f = t.useCallback((function(e, t) { if (!e) { return { fetching: !1 }; } var n = u.get(a.key); if (!n) { var i; var s = r.subscribe((function(e) { n = e; if (i) { i(n); } }))(r.takeWhile((function() { return t && !i || !n; }))(e)); if (null == n && t) { var o = new Promise((function(e) { i = e; })); u.set(a.key, o); throw o; } else { s.unsubscribe(); } } else if (t && null != n && "then" in n) { throw n; } return n || { fetching: !0 }; }), [ u, a ]); var l = [ n, a, e.requestPolicy, e.context, e.pause ]; var v = t.useState((function() { c = !0; try { return [ s, computeNextState(o, f(s, i)), l ]; } finally { c = !1; } })); var p = v[0]; var d = v[1]; var x = p[1]; if (s !== p[0] && hasDepsChanged(p[2], l)) { d([ s, x = computeNextState(p[1], f(s, i)), l ]); } t.useEffect((function() { var e = p[0]; var t = p[2][1]; var n = !1; function updateResult(e) { n = !0; if (!c) { d((function(t) { var r = computeNextState(t[1], e); return t[1] !== r ? [ t[0], r, t[2] ] : t; })); } } if (e) { var i = r.subscribe(updateResult)(r.onEnd((function() { updateResult({ fetching: !1 }); }))(e)); if (!n) { updateResult({ fetching: !0 }); } return function() { u.dispose(t.key); i.unsubscribe(); }; } else { updateResult({ fetching: !1 }); } }), [ u, p[0], p[2][1] ]); return [ x, t.useCallback((function(t) { var s = _extends({}, { requestPolicy: e.requestPolicy }, e.context, t); d((function(e) { return [ i ? r.onPush((function(e) { u.set(a.key, e); }))(n.executeQuery(a, s)) : n.executeQuery(a, s), e[1], l ]; })); }), [ n, u, a, i, f, e.requestPolicy, e.context ]) ]; } function useSubscription(e, n) { var u = useClient(); var i = useRequest(e.query, e.variables); var a = t.useRef(n); a.current = n; var s = t.useMemo((function() { return !e.pause ? u.executeSubscription(i, e.context) : null; }), [ u, i, e.pause, e.context ]); var c = [ u, i, e.context, e.pause ]; var f = t.useState((function() { return [ s, _extends({}, o, { fetching: !!s }), c ]; })); var l = f[0]; var v = f[1]; var p = l[1]; if (s !== l[0] && hasDepsChanged(l[2], c)) { v([ s, p = computeNextState(l[1], { fetching: !!s }), c ]); } t.useEffect((function() { function updateResult(e) { v((function(t) { var r = computeNextState(t[1], e); if (t[1] === r) { return t; } if (a.current && t[1].data !== r.data) { r.data = a.current(t[1].data, r.data); } return [ t[0], r, t[2] ]; })); } if (l[0]) { return r.subscribe(updateResult)(r.onEnd((function() { updateResult({ fetching: !1 }); }))(l[0])).unsubscribe; } else { updateResult({ fetching: !1 }); } }), [ l[0] ]); return [ p, t.useCallback((function(t) { var r = u.executeSubscription(i, _extends({}, e.context, t)); v((function(e) { return [ r, e[1], e[2] ]; })); }), [ u, e.context, i ]) ]; } exports.Consumer = a; exports.Context = u; exports.Mutation = function Mutation(e) { var t = useMutation(e.query); return e.children(_extends({}, t[0], { executeMutation: t[1] })); }; exports.Provider = i; exports.Query = function Query(e) { var t = useQuery(e); return e.children(_extends({}, t[0], { executeQuery: t[1] })); }; exports.Subscription = function Subscription(e) { var t = useSubscription(e, e.handler); return e.children(_extends({}, t[0], { executeSubscription: t[1] })); }; exports.useClient = useClient; exports.useMutation = useMutation; exports.useQuery = useQuery; exports.useSubscription = useSubscription; Object.keys(e).forEach((function(t) { if ("default" !== t && !exports.hasOwnProperty(t)) { exports[t] = e[t]; } })); //# sourceMappingURL=urql.js.map
ngomalalibo/web-librarian
src/main/java/com/pc/weblibrarian/utils/ModifyEntityContent.java
package com.pc.weblibrarian.utils; import com.pc.weblibrarian.dataService.AuthorDataService; import com.pc.weblibrarian.entity.Author; import com.pc.weblibrarian.entity.PersistingBaseEntity; import org.bson.Document; import java.time.LocalDateTime; public class ModifyEntityContent { public static <T extends PersistingBaseEntity> Document modifyEntity(T t) { // UpdateResult ur = collection.updateOne(query, Updates.combine(Updates.set("$set", entity), Updates.set("modifiedDate", LocalDateTime.now())), options); Document doc = new Document(); if (t instanceof Author) { Author author = (Author) t; doc.put("wikiLink", author.getWikiLink()); doc.put("biography", author.getBiography()); doc.put("modifiedDate", LocalDateTime.now()); Author db = AuthorDataService.getAuthor(t.getUuid()); System.out.println(db.getWikiLink().equals(((Author) t).getWikiLink()) ? "The same" : "Different"); } return doc; } }
OliCSADoerr/kresus-sa
client/components/menu/total-balance.js
import React from 'react'; import { connect } from 'react-redux'; import { get } from '../../store'; import { translate as $t } from '../../helpers'; import ColoredAmount from './colored-amount'; let TotalBalanceComponent = props => { let totalEntries = Object.entries(props.totals); let totalElement; if (totalEntries.length) { totalElement = totalEntries .map(([key, value]) => ( <ColoredAmount key={key} amount={value.total} formatCurrency={value.formatCurrency} /> )) .reduce((prev, curr) => [prev, ' | ', curr]); } else { totalElement = 'N/A'; } return ( <p className="bank-details bank-total-accesses"> <span>{$t('client.menu.overall_balance')}</span> &ensp; {totalElement} </p> ); }; const computeTotalBalance = (state, accessIds) => { let totals = {}; for (let accessId of accessIds) { let accessTotal = get.accessTotal(state, accessId); for (let currency in accessTotal) { if (!(currency in totals)) { totals[currency] = accessTotal[currency]; } else { totals[currency].total += accessTotal[currency].total; } } } return totals; }; const TotalBalance = connect(state => { let accessIds = get.accessIds(state); let totals = computeTotalBalance(state, accessIds); return { totals }; })(TotalBalanceComponent); export default TotalBalance;
colorshifter/caaers
caAERS/software/web/src/main/java/gov/nih/nci/cabig/caaers/web/rule/RuleAjaxObject.java
/******************************************************************************* * Copyright SemanticBits, Northwestern University and Akaza Research * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/caaers/LICENSE.txt for details. ******************************************************************************/ package gov.nih.nci.cabig.caaers.web.rule; public class RuleAjaxObject { private String value; private String displayName; public RuleAjaxObject(String value, String displayName) { this.value = value; this.displayName = displayName; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
MatheusEwen/Exercicios_Do_CursoDePython
ExPython/CursoemVideo/ex004.py
<reponame>MatheusEwen/Exercicios_Do_CursoDePython a = input('Digite algo: ') print('\033[1;31mo tipo primitivo desse valor é',type(a)) print('\033[1;32msó tem espaços?:',a.isspace()) print('\033[1;33mé um número?:',a.isnumeric()) print('\033[1;34mé alfabetico?:', a.isalpha()) print('\033[1;35mé um alnumerico?:', a.isalnum()) print('\033[1;36mesta em maiusculas?:',a.isupper()) print('\033[1;37mesta em letra minisculas?:',a.islower()) print('\033[7;30mesta capitalizada?:',a.istitle(),'\033[m')
paullewallencom/java-978-1-7871-2886-6
_src/src/BlockBreakerPanel.java
<reponame>paullewallencom/java-978-1-7871-2886-6 import java.awt.Graphics; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.ArrayList; import java.util.Random; import javax.swing.JPanel; public class BlockBreakerPanel extends JPanel implements KeyListener{ ArrayList<Block> blocks = new ArrayList<Block>(); ArrayList<Block> ball = new ArrayList<Block>(); ArrayList<Block> powerup = new ArrayList<Block>(); Block paddle; Thread thread; Animate animate; int size = 25; BlockBreakerPanel(){ paddle = new Block(175, 480, 150, 25, "paddle.png"); for(int i = 0 ; i<8 ;i++){ blocks.add(new Block((i*60+2), 0, 60, 25, "blue.png")); } for(int i = 0 ; i<8 ;i++){ blocks.add(new Block((i*60+2), 25, 60, 25, "red.png")); } for(int i = 0 ; i<8 ;i++){ blocks.add(new Block((i*60+2), 50, 60, 25, "green.png")); } for(int i = 0 ; i<8 ;i++){ blocks.add(new Block((i*60+2), 75, 60, 25, "yellow.png")); } Random random = new Random(); blocks.get(random.nextInt(32)).powerup = true; blocks.get(random.nextInt(32)).powerup = true; blocks.get(random.nextInt(32)).powerup = true; blocks.get(random.nextInt(32)).powerup = true; blocks.get(random.nextInt(32)).powerup = true; blocks.get(random.nextInt(32)).powerup = true; ball.add(new Block(237, 437, 25, 25, "ball.png")); addKeyListener(this); setFocusable(true); } public void paintComponent(Graphics g){ super.paintComponent(g); for(Block b : blocks) b.draw(g, this); for(Block b : ball) b.draw(g, this); for(Block p : powerup) p.draw(g, this); paddle.draw(g, this); } public void update(){ for(Block p : powerup){ p.y+=1; if(p.intersects(paddle) && !p.destroyed){ p.destroyed = true; ball.add(new Block(paddle.x+75, 437, 25, 25, "ball.png")); } } for(Block ba : ball){ ba.x+=ba.dx; if(ba.x>(getWidth()-size) && ba.dx>0 || ba.x < 0) ba.dx*=-1; if(ba.y < 0 || ba.intersects(paddle)) ba.dy*=-1; ba.y+=ba.dy; for(Block b : blocks){ if((b.left.intersects(ba)||b.right.intersects(ba)) && !b.destroyed){ ba.dx*=-1; b.destroyed = true; if(b.powerup) powerup.add(new Block(b.x, b.y, 25, 19, "extra.png")); } else if(ba.intersects(b) && !b.destroyed){ b.destroyed = true; ba.dy*=-1; if(b.powerup) powerup.add(new Block(b.x, b.y, 25, 19, "extra.png")); } } } repaint(); } @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub if(e.getKeyCode() == KeyEvent.VK_ENTER){ animate = new Animate(this); thread = new Thread(animate); thread.start(); } if(e.getKeyCode() == KeyEvent.VK_LEFT && paddle.x > 0){ paddle.x-=15; } if(e.getKeyCode() == KeyEvent.VK_RIGHT && paddle.x < (getWidth()-paddle.width)){ paddle.x+=15; } } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } }
AdvancedVEXLibrary/Advanced-VEX-Library
vex/include/avl_istiny.h
#pragma once #ifndef _AVL_ISTINY_H_ #define _AVL_ISTINY_H_ #include <math.h> int avl_istiny(const int geometry; const int primnum; const float epsilon) { int points[] = primpoints(geometry, primnum); float epsilon2 = epsilon * epsilon; for (int pt = len(points) - 2; pt > -2; --pt) { vector position1 = point(geometry, 'P', points[pt]); vector position2 = point(geometry, 'P', points[pt+1]); if (distance2(position1, position2) < epsilon2) return 1; } return 0; } int avl_istiny(const int geometry; const int primnum) { return avl_istiny(geometry, primnum, M_TOLERANCE); } int avl_istiny(const string geometry; const int primnum; const float epsilon) { int points[] = primpoints(geometry, primnum); float epsilon2 = epsilon * epsilon; for (int pt = len(points) - 2; pt > -2; --pt) { vector position1 = point(geometry, 'P', points[pt]); vector position2 = point(geometry, 'P', points[pt+1]); if (distance2(position1, position2) < epsilon2) return 1; } return 0; } int avl_istiny(const string geometry; const int primnum) { return avl_istiny(geometry, primnum, M_TOLERANCE); } #endif // _AVL_ISTINY_H_
lmarent/network_agents_ver2
ClockServer/include/TimerNotification.h
#ifndef TimerNotification_INCLUDED #define TimerNotification_INCLUDED #include <Poco/Timer.h> #include <Poco/Thread.h> #include <Poco/Stopwatch.h> #include <iostream> namespace ChoiceNet { namespace Eco { class TimerNotification { public: TimerNotification(int intervals_per_cycle); void onEndPeriod(Poco::Timer& timer); private: Poco::Stopwatch _sw; int _intervals_per_cycle; }; } /// End Eco namespace } /// End ChoiceNet namespace #endif
niloc132/viola
viola-web/src/main/java/com/colinalworth/gwt/viola/web/server/JobWebService.java
package com.colinalworth.gwt.viola.web.server; import com.colinalworth.gwt.viola.entity.CompiledProject; import com.colinalworth.gwt.viola.entity.CompilerLog; import com.colinalworth.gwt.viola.entity.SourceProject; import com.colinalworth.gwt.viola.service.JobService; import com.colinalworth.gwt.viola.service.UserService; import com.colinalworth.gwt.viola.web.shared.dto.CompileLimitException; import com.colinalworth.gwt.viola.web.shared.dto.CompiledProjectStatus; import com.colinalworth.gwt.viola.web.shared.dto.CompilerLogNode; import com.colinalworth.gwt.viola.web.shared.dto.MustBeLoggedInException; import com.colinalworth.gwt.viola.web.shared.dto.NotFoundException; import com.colinalworth.gwt.viola.web.shared.dto.Project; import com.google.inject.Inject; import com.google.inject.Singleton; import rxf.server.CouchService; import rxf.shared.CouchTx; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; @Singleton public class JobWebService { public static final int MAX_DAILY_COMPILES = 20; private Set<String> allowedExtensions = new HashSet<>(Arrays.asList("html", "xml", "java", "css", "js")); @Inject JobService jobService; @Inject SessionService sessionService; @Inject UserService userService; public String getAttachment(String projectId, String path) throws NotFoundException { if (path.endsWith("/")) { return ""; } return jobService.getSourceAsString(jobService.find(projectId), path); } public Project attach(String projectId, String filename, String contents) throws MustBeLoggedInException, NotFoundException { SourceProject proj = jobService.find(projectId); if (proj.getAuthorId().equals(sessionService.getThreadLocalUserId("attach"))) { String file = filename.substring(1 + filename.lastIndexOf("/")); if (!allowedExtensions.contains(file.substring(1 + file.lastIndexOf(".")))) { throw new NotFoundException("Can't create that file extension");//TODO use a better named exception } final CouchTx tx; if (proj.getAttachments().containsKey(filename)) { tx = jobService.updateSourceFile(proj, filename, contents); } else { tx = jobService.createSourceFile(proj, filename, contents); } return getProject(tx.id()); } throw new MustBeLoggedInException("Can't change files of project you don't own"); } public Project delete(String projectId, String filename) throws MustBeLoggedInException, NotFoundException { SourceProject proj = jobService.find(projectId); if (proj.getAuthorId().equals(sessionService.getThreadLocalUserId("delete"))) { if (proj.getAttachments().size() <= 1) { throw new NotFoundException("Can't delete last file");//TODO use a better named exception } CouchTx tx = jobService.deleteSourceFile(proj, filename); return getProject(tx.id()); } throw new MustBeLoggedInException("Can't delete a project you don't own"); } public Project getProject(String id) throws NotFoundException { SourceProject sourceProject = jobService.find(id); if (sourceProject == null) { throw new NotFoundException("Project with id '" + id + "' could not be found"); } Project p = new Project(); p.setId(id); p.setAuthorId(sourceProject.getAuthorId()); p.setDescription(sourceProject.getDescription()); p.setTitle(sourceProject.getTitle()); p.setFiles(new ArrayList<>(sourceProject.getAttachments().keySet())); Collections.sort(p.getFiles()); return p; } public Project createProject() throws MustBeLoggedInException { String owner = sessionService.getThreadLocalUserId("create"); if (owner == null) { throw new MustBeLoggedInException("Can't create a project without logging in"); } SourceProject project = jobService.createProject(owner); try { return getProject(project.getId()); } catch (NotFoundException e) { //not possible, just created it return null; } } public Project cloneProject(String otherId) throws MustBeLoggedInException, NotFoundException { String owner = sessionService.getThreadLocalUserId("clone"); if (owner == null) { throw new MustBeLoggedInException("Can't clone a project without logging in"); } SourceProject original = jobService.find(otherId); if (original == null) { throw new NotFoundException("Project with id " + otherId + " could not be found"); } SourceProject clone = jobService.cloneProjectToUser(original, owner); return getProject(clone.getId()); } public Project saveProject(Project project) throws MustBeLoggedInException, NotFoundException { SourceProject sourceProject = jobService.find(project.getId()); if (sourceProject == null) { throw new NotFoundException("Project with id " + project.getId() + " could not be found"); } if (sourceProject.getAuthorId().equals(sessionService.getThreadLocalUserId("save"))) { sourceProject.setDescription(project.getDescription()); sourceProject.setTitle(project.getTitle()); jobService.saveProject(sourceProject); return getProject(project.getId()); } throw new MustBeLoggedInException("Can't save project user doesn't own"); } public void build(String projectId) throws CompileLimitException, MustBeLoggedInException { SourceProject project = jobService.find(projectId); String userId = sessionService.getThreadLocalUserId("compile"); if (project.getAuthorId().equals(userId)) { //user owns the project //user is not presently compiling anything if (jobService.isCurrentlyCompiling(userId)){ throw new CompileLimitException("You are already compiling, can't have multiple concurrent jobs running"); } //user is within their quota if (jobService.getCompileCountTodayForUser(userId) > MAX_DAILY_COMPILES) { throw new CompileLimitException("You've exceeded your daily limit for compiles"); } jobService.submitJob(project); } else { throw new MustBeLoggedInException("Can't build project user doesn't own"); } } public CompiledProjectStatus checkStatus(String projectId) throws NotFoundException { SourceProject proj = jobService.find(projectId); if (proj == null) { throw new NotFoundException("Project with id " + projectId + " could not be found"); } CompiledProject compiledOuput = jobService.getLatestCompiledOuput(proj); if (compiledOuput == null) { throw new NotFoundException("Project with id " + projectId + " has not been submitted to be compiled"); } return CompiledProjectStatus.values()[compiledOuput.getStatus().ordinal()]; } public String getCompiledId(String id) throws NotFoundException { SourceProject proj = jobService.find(id); if (proj == null) { throw new NotFoundException("Project with id " + id + " could not be found"); } CompiledProject output = jobService.getLatestCompiledOuput(proj); if (output == null) { return null; } return output.getId(); } public interface LogQueries extends CouchService<CompilerLog> { @View(map="function(doc) {" + "emit(doc.compiledProjectId, doc);" + "}") // @Limit(1)//can only have one result, this db is used to just keep crap out of the compiled db List<LogWrap> findFromCompiled(String id); } public static class LogWrap { CompilerLogNode node; } @Inject LogQueries logQueries; public CompilerLogNode getLog(String compiledId) throws NotFoundException { //should be 1 or 0 List<LogWrap> logs = logQueries.findFromCompiled(compiledId); return logs.isEmpty() ? null : logs.get(0).node; } }
KretschiHSR/HSR-SmartProductsApp
Source/SmartProductBrowser/app/src/main/java/ch/ost/wing/smartproducts/smartproductbrowser/views/adapters/ProductsAdapter.java
package ch.ost.wing.smartproducts.smartproductbrowser.views.adapters; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import androidx.databinding.DataBindingUtil; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import javax.inject.Provider; import ch.ost.wing.smartproducts.R; import ch.ost.wing.smartproducts.databinding.ProductBinding; import ch.ost.wing.smartproducts.smartproductbrowser.IApp; import ch.ost.wing.smartproducts.smartproductbrowser.dataaccess.local.entities.Product; import ch.ost.wing.smartproducts.smartproductbrowser.viewmodels.IAdapterBinding; import ch.ost.wing.smartproducts.smartproductbrowser.viewmodels.ProductViewModel; public class ProductsAdapter extends BaseAdapter implements IAdapterBinding<Product> { private final Provider<ProductViewModel> _vmFactory; private final IApp _app; @Inject public ProductsAdapter(Provider<ProductViewModel> vmFactory, IApp app){ this._vmFactory = vmFactory; this._app = app; } private List<ProductViewModel> _productViewModels = new ArrayList<>(); public void refresh(Iterable<Product> products){ List<ProductViewModel> vms = new ArrayList<>(); for (Product product: products) { ProductViewModel vm = this._vmFactory.get(); vm.init(product); vms.add(vm); } this._productViewModels = vms; this.notifyDataSetChanged(); } @Override public int getCount() { return this._productViewModels.size(); } @Override public Object getItem(int position) { return this.getProductAt(position); } private ProductViewModel getProductAt(int position){ return this._productViewModels.get(position); } @Override public long getItemId(int position) { return this._productViewModels.get(0).hashCode(); } @Override public View getView(int position, View convertView, ViewGroup parent) { BindingViewHolder<ProductBinding> holder; if (convertView == null) { ProductBinding binding = DataBindingUtil.inflate(LayoutInflater.from(this._app.getAppContext()), R.layout.product, parent, false); holder = new BindingViewHolder<>(binding); holder.getView().setTag(holder); } else { holder = (BindingViewHolder<ProductBinding>)convertView.getTag(); } holder.getBinding().setProductViewModel(this.getProductAt(position)); return holder.getView(); } }
pardoman/hig
packages/tabs/src/presenters/TabCloseButtonPresenter.js
<reponame>pardoman/hig import React from "react"; import PropTypes from "prop-types"; import { CloseSUI, CloseXsUI } from "@hig/icons"; import ThemeContext from "@hig/theme-context"; import { ControlBehavior } from "@hig/behaviors"; import { cx, css } from "emotion"; import stylesheet from "./Tab.stylesheet"; export default class TabCloseButtonPresenter extends React.Component { static propTypes = { /** * Prevents user actions on the button */ disabled: PropTypes.bool, /** * Called when user moves focus away from the button */ onBlur: PropTypes.func, /** * Called when user clicks the button */ onClick: PropTypes.func, /** * Called when user moves focus onto the button */ onFocus: PropTypes.func, /** * Called when mouse is pressed over the button */ onMouseDown: PropTypes.func, /** * Called when mouse begins to move over the button */ onMouseEnter: PropTypes.func, /** * Called when mouse stops moving over the button */ onMouseLeave: PropTypes.func, /** * Called when mouse is released over the button */ onMouseUp: PropTypes.func, /** * Function to modify the component's styles */ stylesheet: PropTypes.func }; render() { const { disabled, onBlur, onFocus, onMouseDown, onMouseEnter, onMouseLeave, onMouseUp, onClick, stylesheet: customStylesheet, ...otherProps } = this.props; function handleClick(event) { event.preventDefault(); event.stopPropagation(); onClick(event); } return ( <ControlBehavior onBlur={onBlur} onFocus={onFocus} onMouseDown={onMouseDown} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} onMouseUp={onMouseUp} > {({ hasFocus, hasHover, isPressed, onBlur: handleBlur, onFocus: handleFocus, onMouseDown: handleMouseDown, onMouseEnter: handleMouseEnter, onMouseLeave: handleMouseLeave, onMouseUp: handleMouseUp }) => ( <ThemeContext.Consumer> {({ resolvedRoles, metadata }) => { const styles = stylesheet( { hasFocus, hasHover, isPressed, stylesheet: customStylesheet }, resolvedRoles, metadata ); const { className } = otherProps; const CloseIcon = metadata.densityId === "medium-density" ? CloseSUI : CloseXsUI; return ( <button onBlur={handleBlur} onFocus={handleFocus} onMouseDown={handleMouseDown} onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave} onMouseUp={handleMouseUp} className={cx(css(styles.button), className)} tabIndex="-1" onClick={handleClick} disabled={disabled} title="close" > <CloseIcon /> </button> ); }} </ThemeContext.Consumer> )} </ControlBehavior> ); } }
bis83/pomdog
src/SoundSystem.XAudio2/SoundEffectXAudio2.hpp
<reponame>bis83/pomdog // Copyright (c) 2013-2015 mogemimi. // Distributed under the MIT license. See LICENSE.md file for details. #ifndef POMDOG_SOUNDEFFECTXAUDIO2_ED1F6835_HPP #define POMDOG_SOUNDEFFECTXAUDIO2_ED1F6835_HPP #include "PrerequisitesXAudio2.hpp" #include "../Utility/Noncopyable.hpp" #include <memory> namespace Pomdog { class AudioEmitter; class AudioListener; } // namespace Pomdog namespace Pomdog { namespace Detail { namespace SoundSystem { namespace XAudio2 { class AudioClipXAudio2; class AudioEngineXAudio2; class SoundEffectXAudio2 final: Noncopyable { public: SoundEffectXAudio2(AudioEngineXAudio2 & audioEngine, std::shared_ptr<AudioClipXAudio2> const& audioClip, bool isLooped); ~SoundEffectXAudio2(); void ExitLoop(); void Pause(); void Play(); void Stop(); void Apply3D(AudioListener const& listener, AudioEmitter const& emitter); void Pitch(float pitch); void Volume(float volume); private: std::shared_ptr<AudioClipXAudio2> audioClip; IXAudio2SourceVoice* sourceVoice; bool isLooped; }; } // namespace XAudio2 } // namespace SoundSystem } // namespace Detail } // namespace Pomdog #endif // POMDOG_SOUNDEFFECTXAUDIO2_ED1F6835_HPP
TeamNut/CotEngine-Release
include/math/CotColor.h
#pragma once #include "base/CotRule.h" namespace Cot { class Color32; class COT_API Color final { public: union { struct { float r, g, b, a; }; float ToArray[4]; }; Color(); Color(const float red, const float green, const float blue, const float alpha = 1.0f); Color(const float* array); Color(const Color& color); Color(const Color&& color); Color(const Color32& color); ~Color(); const Color operator+(const Color& color) const; const Color operator-(const Color& color) const; const Color operator*(const Color& color) const; const Color operator/(const Color& color) const; const Color operator+(const float value) const; const Color operator-(const float value) const; const Color operator*(const float value) const; const Color operator/(const float value) const; Color& operator+=(const Color& color); Color& operator-=(const Color& color); Color& operator*=(const Color& color); Color& operator/=(const Color& color); Color& operator+=(const float value); Color& operator-=(const float value); Color& operator*=(const float value); Color& operator/=(const float value); Color& operator=(const Color& color); Color& operator=(const Color32& color); bool operator==(const Color& color) const; bool operator!=(const Color& color) const; bool operator==(const Color32& color) const; bool operator!=(const Color32& color) const; bool operator<(const Color&) = delete; bool operator>(const Color&) = delete; Color operator-() = delete; const static Color White; const static Color Yellow; const static Color Blue; const static Color Green; const static Color Red; const static Color Magenta; const static Color Black; const static Color Orange; const static Color Gray; }; }
pdmack/djl
examples/src/main/java/ai/djl/examples/training/util/ExampleTrainingResult.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package ai.djl.examples.training.util; import ai.djl.metric.Metrics; import ai.djl.training.Trainer; import ai.djl.training.evaluator.Evaluator; import ai.djl.training.listener.EvaluatorTrainingListener; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class ExampleTrainingResult { private String lossName; Map<String, Float> evaluations; public ExampleTrainingResult(Trainer trainer) { lossName = trainer.getLoss().getName(); Metrics metrics = trainer.getMetrics(); evaluations = new ConcurrentHashMap<>(); for (Evaluator evaluator : trainer.getEvaluators()) { float value = metrics.latestMetric( EvaluatorTrainingListener.metricName( evaluator, EvaluatorTrainingListener.VALIDATE_EPOCH)) .getValue() .floatValue(); evaluations.put(evaluator.getName(), value); } } public float getEvaluation(String name) { return evaluations.get(name); } public float getLoss() { return evaluations.get(lossName); } }
xvwh/batch-scheduler
auth/src/main/java/com/asofdate/hauth/dao/impl/HandleLogDaoImpl.java
<filename>auth/src/main/java/com/asofdate/hauth/dao/impl/HandleLogDaoImpl.java package com.asofdate.hauth.dao.impl; import com.asofdate.hauth.dao.HandleLogDao; import com.asofdate.hauth.entity.HandleLogEntity; import com.asofdate.hauth.sql.SqlText; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import java.util.List; /** * Created by hzwy23 on 2017/6/18. */ @Repository public class HandleLogDaoImpl implements HandleLogDao { @Autowired private JdbcTemplate jdbcTemplate; @Autowired private SqlText sqlText; @Override public List<HandleLogEntity> findAll(String domainId) { RowMapper<HandleLogEntity> rowMapper = new BeanPropertyRowMapper<>(HandleLogEntity.class); return jdbcTemplate.query(sqlText.getSql("sys012"), rowMapper, domainId); } @Override public List<HandleLogEntity> findAll(String domainId, Integer offset, Integer limit) { RowMapper<HandleLogEntity> rowMapper = new BeanPropertyRowMapper<>(HandleLogEntity.class); return jdbcTemplate.query(sqlText.getSql("sys029"), rowMapper, domainId, offset, limit); } @Override public Integer getTotal(String domainId) { return jdbcTemplate.queryForObject(sqlText.getSql("sys030"), Integer.class, domainId); } }
PqES/ArchPython
src/Models/problem.py
class Problem: def __init__(self, problem_type, origin_module, restrictions_broken, is_warning = False): self.problem_type = problem_type self.origin_module = origin_module self.restrictions_broken = restrictions_broken self.category = "warning" if is_warning else "problem" def print_problem(self): print(f"A {self.category} was found at {self.origin_module.name}: {self.problem_type['Message']} - Types: {str(self.restrictions_broken)}") def get_problem_as_dict(self): return { "Module" : self.origin_module.name, "Category" : self.category, "Problem_Code" : self.problem_type['Code'], "Problem_Message" : self.problem_type['Message'], "Types" : str(self.restrictions_broken), }
YDJaken/ThreeEarth
src/Renderer/Shaders/ShaderChunk/emissivemap_pars_fragment.js
<gh_stars>0 //This file is automatically rebuilt by the Speed3DGis build process. class emissivemap_pars_fragment{static theWord() { return "#ifdef USE_EMISSIVEMAP\n\ \n\ uniform sampler2D emissiveMap;\n\ \n\ #endif\n\ "; }} export {emissivemap_pars_fragment};
12589-PioneerRobotics/FtcRobotController
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/tests/OpenCVTestOpMode.java
package org.firstinspires.ftc.teamcode.tests; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import org.firstinspires.ftc.robotcore.external.hardware.camera.WebcamName; import org.firstinspires.ftc.teamcode.core.CVRingDetection; import org.openftc.easyopencv.OpenCvCamera; import org.openftc.easyopencv.OpenCvCameraFactory; @Autonomous(name = "OpenCV Test") public class OpenCVTestOpMode extends LinearOpMode { @Override public void runOpMode() throws InterruptedException { OpenCvCamera webcam; CVRingDetection frame = new CVRingDetection(); int cameraMonitorViewId = hardwareMap.appContext.getResources().getIdentifier("cameraMonitorViewId", "id", hardwareMap.appContext.getPackageName()); webcam = OpenCvCameraFactory.getInstance().createWebcam(hardwareMap.get(WebcamName.class, "Webcam 1"), cameraMonitorViewId); webcam.setPipeline(frame); waitForStart(); if(isStopRequested()) return; while(opModeIsActive()) { telemetry.addData("# Contours", frame.getContourCount()); telemetry.addData("Ring case", frame.getRingCase()); telemetry.addData("Bounding rect height", frame.getBoundingRectHeight()); telemetry.update(); } } }
Robbbert/messui
src/lib/formats/apd_dsk.h
<reponame>Robbbert/messui<filename>src/lib/formats/apd_dsk.h // license:BSD-3-Clause // copyright-holders:<NAME> /********************************************************************* formats/apd_dsk.h Archimedes Protected Disk Image format *********************************************************************/ #ifndef MAME_FORMATS_APD_DSK_H #define MAME_FORMATS_APD_DSK_H #pragma once #include "flopimg.h" class apd_format : public floppy_image_format_t { public: apd_format(); virtual const char *name() const override; virtual const char *description() const override; virtual const char *extensions() const override; virtual int identify(util::random_read &io, uint32_t form_factor, const std::vector<uint32_t> &variants) override; virtual bool load(util::random_read &io, uint32_t form_factor, const std::vector<uint32_t> &variants, floppy_image *image) override; virtual bool supports_save() const override; }; extern const floppy_format_type FLOPPY_APD_FORMAT; #endif // MAME_FORMATS_APD_DSK_H
meilihao/demo
etcd/lock/etcdv3.go
// from https://yemilice.com/2019/12/13/etcd%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81%E5%AE%9E%E7%8E%B0%E9%80%89%E4%B8%BB%E6%9C%BA%E5%88%B6-golang/ package main import ( "context" "errors" "fmt" "io" "math" "os" "sync" "time" clientv3 "go.etcd.io/etcd/client/v3" ) const ( defaultTTL = 60 formatErrTryLockFailed = "trylock failed, corrent owner is %s" formatTime = "2006-01-02_15:04:05.999999999" ) type LockedByOtherError struct { Owner string } func (e *LockedByOtherError) Error() string { return fmt.Sprintf(formatErrTryLockFailed, e.Owner) } type LockTimeoutError struct { Timeout int64 } func (e *LockTimeoutError) Error() string { return fmt.Sprintf("lock timeout: %ds", e.Timeout) } // A Mutex is a mutual exclusion lock which is distributed across a cluster. type Mutex struct { key string value string // The identity of the caller ttl int64 client *clientv3.Client lease clientv3.Lease leaseID clientv3.LeaseID mutex *sync.Mutex logger io.Writer } // New creates a Mutex with the given key which must be the same // across the cluster nodes. // endpoints are the ectd cluster addresses func New(key string, ttl int64, endpoints []string) (*Mutex, error) { if len(key) == 0 || len(endpoints) == 0 { return nil, errors.New("wrong lock args") } cli, err := clientv3.New(clientv3.Config{ Endpoints: endpoints, DialTimeout: 5 * time.Second, }) if err != nil { return nil, err } hostname, _ := os.Hostname() if key[0] != '/' { key = "/" + key } if ttl < 1 { ttl = defaultTTL } m := &Mutex{ key: key, value: fmt.Sprintf("%v#%v#%v", hostname, os.Getpid(), time.Now().Format(formatTime)), // lock owner ttl: ttl, client: cli, lease: clientv3.NewLease(cli), // 上锁用(创建租约,自动续租) mutex: new(sync.Mutex), logger: os.Stderr, } // 设置ttl秒租约(过期时间) leaseResp, err := m.lease.Grant(context.TODO(), m.ttl) if err != nil { m.lease.Close() cli.Close() return nil, err } // 租约id m.leaseID = leaseResp.ID if _, err = m.lease.KeepAlive(context.TODO(), m.leaseID); err != nil { m.lease.Close() cli.Close() return nil, err } if err = m.lock(); err != nil { m.lease.Close() cli.Close() return nil, err } return m, nil } func (m *Mutex) close() { if m.lease != nil { m.lease.Close() } if m.client != nil { m.client.Close() } } // NewWithRetry trylock with timeout // n=-1, trylock forever; otherwise trylock n times, if failed, sleep 1s, then try again func NewWithRetry(key string, ttl int64, endpoints []string, n int64) (*Mutex, error) { var ok bool var l *Mutex var err error i := n if i == -1 { i = math.MaxInt32 } for i > 0 { // log.Printf("Trying to create a node : key=%v\n", key) l, err = New(key, ttl, endpoints) if err == nil { return l, nil } if _, ok = err.(*LockedByOtherError); !ok { return nil, err } time.Sleep(time.Second) i-- } return nil, &LockTimeoutError{Timeout: n} } // Lock locks m. // If the lock is already in use, the calling goroutine // blocks until the mutex is available. func (m *Mutex) lock() (err error) { m.mutex.Lock() m.debug("Trying to create a node : key=%v", m.key) // txn事务:if else then txn := clientv3.NewKV(m.client).Txn(context.TODO()) txn.If(clientv3.Compare(clientv3.CreateRevision(m.key), "=", 0)). // 比较key的revision为0(0标示没有key) Then(clientv3.OpPut(m.key, m.value, clientv3.WithLease(m.leaseID))). Else(clientv3.OpGet(m.key)) // OpGet后TxnResponse才包含Responses var resp *clientv3.TxnResponse resp, err = txn.Commit() if err != nil { return err } if !resp.Succeeded { //判断txn.if条件是否成立, 即判断是否抢到了锁 return &LockedByOtherError{Owner: string(resp.Responses[0].GetResponseRange().Kvs[0].Value)} } return err } // Unlock unlocks m. // It is a runtime error if m is not locked on entry to Unlock. // // A locked Mutex is not associated with a particular goroutine. // It is allowed for one goroutine to lock a Mutex and then // arrange for another goroutine to unlock it. func (m *Mutex) Unlock() (err error) { defer m.mutex.Unlock() defer m.close() var resp *clientv3.LeaseRevokeResponse resp, err = m.lease.Revoke(context.TODO(), m.leaseID) // 终止租约(去掉过期时间), key will deleted auto. ps: 租约提前过期时该调用也不报错 if err == nil { m.debug("Delete %v OK", m.key) return nil } else { m.debug("Delete %v failed: %v", m.key, err) } _ = resp return err } func (m *Mutex) debug(format string, v ...interface{}) { if m.logger != nil { m.logger.Write([]byte(m.value)) m.logger.Write([]byte(" ")) m.logger.Write([]byte(fmt.Sprintf(format, v...))) m.logger.Write([]byte("\n")) } } func (m *Mutex) SetDebugLogger(w io.Writer) { m.logger = w }
HuangJie1990/Algorithms
src/c1/s5/UF.java
<filename>src/c1/s5/UF.java<gh_stars>0 package c1.s5; public abstract class UF { protected int[] id; protected int count; /* add connection between p and q */ public abstract void union(int p, int q); /* component identifier for p(0 to N-1) */ public abstract int find(int i); /* are p and q in the same component? */ public abstract boolean connected(int p, int q); /* number of components */ public int count() { return count; } }
dgarson/jdbceptor
src/main/java/org/drg/jdbceptor/hibernate/InstrumentedConnectionProvider.java
package org.drg.jdbceptor.hibernate; import com.google.common.base.Preconditions; import org.apache.commons.lang3.StringUtils; import org.drg.jdbceptor.api.InstrumentedConnection; import org.drg.jdbceptor.hibernate.config.HibernateDataSourceConfiguration; import org.drg.jdbceptor.hibernate.event.ConnectionProviderAware; import org.drg.jdbceptor.hibernate.event.ConnectionProviderListener; import org.drg.jdbceptor.hibernate.event.ConnectionProviderListenerSettings; import org.drg.jdbceptor.hibernate.event.PostConnectionAcquisitionListener; import org.drg.jdbceptor.hibernate.event.PostConnectionCloseListener; import org.drg.jdbceptor.hibernate.event.PreConnectionAcquisitionListener; import org.drg.jdbceptor.hibernate.event.PreConnectionCloseListener; import org.drg.jdbceptor.impl.DataSourceManager; import org.drg.jdbceptor.internal.DataSourceMember; import org.hibernate.HibernateException; import org.hibernate.cfg.Environment; import org.hibernate.connection.ConnectionProvider; import org.hibernate.connection.ConnectionProviderFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * Abstract base class for a {@link org.hibernate.connection.ConnectionProvider} implementation that will be used with * the Hibernate integration of Jdbceptor. This provider implementation may only be used when also using the provided * Jdbceptor-subclass of {@link org.hibernate.cfg.Configuration}. * * @author dgarson * * @see InstrumentedHibernateConfiguration */ public class InstrumentedConnectionProvider implements ConnectionProvider, DataSourceMember { public static final String DELEGATING_CONNECTION_PROVIDER_CLASS = "hibernate.connection.delegate_provider_class"; protected final Logger log = LoggerFactory.getLogger(getClass()); // configuration for the associated data source, handed off via a thread-local private final HibernateDataSourceConfiguration dataSourceConfig; private final String dataSourceId; private DataSourceManager dataSourceManager; // the real connection provider we are delegating to private ConnectionProvider realConnectionProvider; // cached JDBC connection URL private String jdbcUrl; // list of zero or more ConnectionProviderListener that are registered with this connection provider wrapper private final List<PreConnectionAcquisitionListener> preAcquisitionListeners = new ArrayList<>(); private final List<PostConnectionAcquisitionListener> postAcquisitionListeners = new ArrayList<>(); private final List<PreConnectionCloseListener> preCloseListeners = new ArrayList<>(); private final List<PostConnectionCloseListener> postCloseListeners = new ArrayList<>(); private final Map<Class<? extends ConnectionProviderListener>, ConnectionProviderListener> listenerMap = new HashMap<>(); public InstrumentedConnectionProvider() { dataSourceConfig = InstrumentedHibernateConfiguration.getCurrentDataSourceConfig(); dataSourceId = dataSourceConfig.getId(); if (dataSourceConfig == null) { throw new IllegalStateException("You must use an InstrumentedHibernateConfiguration to build a " + "SessionFactory with Jdbceptor integration"); } } /** * Creates and attaches any listeners that are declared for the connection provider in the data source config. This * method is called from the {@link #configure(Properties)} method. * @param props the hibernate properties * @see HibernateDataSourceConfiguration#getConnectionProviderListenerClasses() */ private void configureListeners(Properties props) { // cleanup any possible listeners that were registered already, which will only be the case in tests removeAllListeners(); // grab listener classes from the data source configuration Class<? extends ConnectionProviderListener>[] listenerClasses = dataSourceConfig.getConnectionProviderListenerClasses(); if (listenerClasses == null) { log.warn("The data source configuration for '{}' should not return a <null> array of listener classes", dataSourceId); } else { int numListeners = 0; for (Class<? extends ConnectionProviderListener> listenerClass : listenerClasses) { ConnectionProviderListener listener = createListener(props, listenerClass); // once the listener has been created and initialized, add it to the proper callback list if (listener != null) { addToListenerLists(listener); numListeners++; } } log.trace("Attached {} listeners to connection provider for data source '{}'", numListeners, dataSourceId); } } @Override public final void configure(Properties props) throws HibernateException { // allow subclass to pre-process if desired preConfigure(props); // cache JDBC url jdbcUrl = props.getProperty(Environment.URL); // create the real connection provider instance // restore the real connection provider class name from the delegating property name String delegateConnectionProviderClass = props.getProperty(DELEGATING_CONNECTION_PROVIDER_CLASS); if (StringUtils.isBlank(delegateConnectionProviderClass)) { throw new IllegalStateException("Missing delegating connection provider class name in Hibernate " + "property '" + DELEGATING_CONNECTION_PROVIDER_CLASS + "'"); } props.setProperty(Environment.CONNECTION_PROVIDER, delegateConnectionProviderClass); realConnectionProvider = ConnectionProviderFactory.newConnectionProvider(props); log.trace("Created real connection provider of type {} connected to {}", delegateConnectionProviderClass, jdbcUrl); // do actual initialization in subclass impl. initialize(props); // configure our connection provider lists configureListeners(props); // post-configuration callback configured(props); log.info("Finished initializing InstrumentedConnectionProvider for data source '{}'", dataSourceId); } void setDataSourceManager(@Nonnull DataSourceManager dataSourceManager) { Preconditions.checkNotNull(dataSourceManager, "dataSourceManager was null"); Preconditions.checkArgument(dataSourceManager.getId().equals(dataSourceId), "unable to use dataSourceManager " + "for '" + dataSourceManager.getId() + "' with a different data source: " + dataSourceId); this.dataSourceManager = dataSourceManager; } /** * Invoked immediately prior to the business logic in {@link #configure(Properties)} method. */ protected void preConfigure(Properties props) { // no-op } /** * Overrideable callback invoked by {@link #configure(Properties)} so that subclasses can perform their own * initialization, but allows this abstract superclass to control the way it is invoked, allowing pre and post * processing. */ protected void initialize(Properties props) throws HibernateException { // no-op } /** * Callback method invoked at the end of the {@link #configure(Properties)} call so that post-processing can be * done. * @param props the properties used to configure this connection provider */ protected void configured(Properties props){ // no-op by default, optional override } /** * Creates a new {@link ConnectionProviderListenerSettings} object that will be passed into listeners being attached * to this connection provider. */ protected ConnectionProviderListenerSettings createListenerSettings(Properties hibernateProperties) { return new ConnectionProviderListenerSettings(this, hibernateProperties); } /** * Callback that is invoked after prior to calling all post-acquisition callbacks for failures. This provides * subclasses the opportunity to either squelch or customize reactions to and respond to exceptions acquiring * connections outside of the listeners attached to this provider. </br> * After this method returns, the SQLException will be propagated up, unless another {@link SQLException} is * returned from this call. */ protected SQLException connectionAcquisitionFailed(@Nonnull SQLException exception) { return exception; } /** * Callback that is invoked after acquiring a connection thru {@link #getConnection()} but prior to invoking any of * the registered post-acquisition callbacks. * @param instrConn the instrumented connection instance * @param acquiredConn the exact connection instance that was acquired from the underlying provider */ protected void connectionAcquired(@Nonnull InstrumentedConnection instrConn, @Nonnull Connection acquiredConn) { // no-op } /** * Callback that is invoked immediately prior to calling {@link ConnectionProvider#closeConnection(Connection)} for * the provided <strong>connection</strong>. */ protected void beforeRelease(@Nonnull InstrumentedConnection instrConn, @Nonnull Connection closingConn) { // no-op } /** * Callback that is invoked immediately after calling {@link ConnectionProvider#closeConnection(Connection)} for * the provided <strong>connection</strong>. */ protected void connectionReleased(@Nonnull InstrumentedConnection instrConn, @Nonnull Connection closedConn) { // no-op } /** * Callback that is invoked prior to performing the actual {@link ConnectionProvider#close()} on the delegate * connection provider, allowing a subclass to hook into this event. */ protected void onClose() { // no-op } /** * Returns the real connection provider that this instrumented wrapper is delegating to. This may return a value of * <code>null</code> if the {@link #configure(Properties)} method has not yet been invoked. */ @Nullable public ConnectionProvider getWrappedConnectionProvider() { return realConnectionProvider; } /** * Returns the JDBC url that this connection provider will be using for establishing connections. */ @Nonnull public final String getJdbcUrl() { return jdbcUrl; } @Nonnull @Override public final String getDataSourceId() { return dataSourceId; } @Override public final DataSourceManager getDataSourceManager() { return dataSourceManager; } @Override public final void close() throws HibernateException { onClose(); realConnectionProvider.close(); } @Override public boolean supportsAggressiveRelease() { return realConnectionProvider.supportsAggressiveRelease(); } @Override public final Connection getConnection() throws SQLException { Connection acquiredConn; try { acquiredConn = executeOperation(/*existingConnection=*/null, /*isAcquisition=*/true, /*invokeFailureListeners=*/false); } catch (SQLException se) { // notify subclass of failure prior to invoking failure listeners SQLException rethrowException = connectionAcquisitionFailed(se); // invoke failure listeners invokeListeners(/*isBefore=*/false, /*isAcquisition=*/true, /*exception=*/se, /*connection=*/null); // rethrow exception if (rethrowException == null) { rethrowException = se; } throw rethrowException; } // invoke callback for subclass afterAcquisition(acquiredConn); return acquiredConn; } @Override public final void closeConnection(Connection closedConn) throws SQLException { // we must extract the InstrumentedConnection first since it may be unavailable if using a pooled connection // and executeOperation(..) clears the 'inner' connection ref InstrumentedConnection instrumentedConn = null; if (closedConn instanceof InstrumentedConnection) { // we are using the instrumented driver directly underneath this connection provider, without nesting instrumentedConn = (InstrumentedConnection) closedConn; } else if (closedConn != null) { // if using c3p0, or any other nested data source, we want to attempt to resolve the nested connection impl. // that was created by Jdbceptor instrumentedConn = dataSourceManager.resolveInstrumentedConnection(closedConn); } try { beforeRelease(instrumentedConn, closedConn); executeOperation(closedConn, /*isAcquisition=*/false, /*invokeFailureListeners=*/true); } finally { // make sure to always call this so book-keeping elsewhere does not have major problems afterClose(instrumentedConn, closedConn); } } private void afterAcquisition(Connection acquiredConn) { InstrumentedConnection instrumentedConn = dataSourceManager.resolveInstrumentedConnection(acquiredConn, /*useDefaultNull=*/true); // connection-pool-specific callback if (instrumentedConn != null && instrumentedConn instanceof HibernateAwareInstrumentedConnection) { ((HibernateAwareInstrumentedConnection) instrumentedConn).acquiredFromConnectionProvider(acquiredConn); } // invoke callback for subclass connectionAcquired(instrumentedConn, acquiredConn); } private void afterClose(InstrumentedConnection instrumentedConn, Connection closedConn) { // connection-pool-specific callback if (instrumentedConn != null && instrumentedConn instanceof HibernateAwareInstrumentedConnection) { ((HibernateAwareInstrumentedConnection)instrumentedConn).releasedToConnectionProvider(); } // invoke callback for subclass connectionReleased(instrumentedConn, closedConn); } /** * Executes the appropriate connection operation depending on the value of <strong>existingConnection</strong>. * Whenever a connection is provided, we know that we are definitely going * to be performing a close operation, since no connection exists to be passed in when acquiring a connection. As * such, if the <strong>existingConnection</strong> is found to be * <code>null</code> then we know that we are definitely acquiring/opening a new connection. * * @param existingConnection the existing connection, if closing a connection, otherwise <code>null</code> for * opening a connection * @param isAcquisition explicit declaration of whether this is an open vs. close (needed for unit testability) * @param invokeFailureListeners if true then failure handlers will be invoked automatically if an exception occurs, * otherwise if <code>false</code> then the caller of this method is responsible * for invoking the failure handlers in all subscribed and enabled interceptors in the chain * @return a connection that was successfully acquired, or <code>null</code> if <strong>existingConnection</strong> * was provided and we closed the connection successfully * @throws SQLException on any database or connection pooling exceptions */ private Connection executeOperation(Connection existingConnection, boolean isAcquisition, boolean invokeFailureListeners) throws SQLException { // invoke pre-* callbacks invokeListeners(/* isBefore=*/ true, /*isAcquisition=*/ isAcquisition, /*exc=*/null, /*connection=*/existingConnection); // invoke the actual operation Connection result; try { if (isAcquisition) { // acquire a connection using the delegate connection provider result = realConnectionProvider.getConnection(); // invoke internal callbacks before registered listeners are called afterAcquireBeforeCallbacks(result); } else { // simply close the connection and return null realConnectionProvider.closeConnection(existingConnection); result = null; } } catch (SQLException | RuntimeException e) { // we are catching these to make sure we can properly invoke the failure listeners that are attached to this // operation. if we immediately propagated the exception up to the caller, then we would never invoke // these listeners // invoke failure callbacks in interceptor(s), but only if the caller is not going to do so themselves if (invokeFailureListeners) { // make sure to pass in the 'existingConnection' value invokeListeners(/* isBefore=*/ false, /*isAcquisition=*/ isAcquisition, /*exc=*/e, /*connection=*/existingConnection); } // rethrow the exception throw e; } // if we get this far, then we succeeded at applying the operation and must invoke post-operation callbacks // on interceptors invokeListeners(/* isBefore=*/ false, /*isAcquisition=*/ isAcquisition, /*exc=*/null, /*connection=*/result); // return the result return result; } /** * Apply customization logic, if applicable. We must always do this before invoking our listener callbacks since the * customizer's actions may be necessary for callbacks to function properly. * @param acquiredConn the acquired connection */ private void afterAcquireBeforeCallbacks(Connection acquiredConn) { if (acquiredConn == null) { return; } // customize if necessary InstrumentedConnection instrumentedConn = dataSourceManager.resolveInstrumentedConnection(acquiredConn, /*useDefaultNull=*/true); if (instrumentedConn != null) { dataSourceManager.customizeConnection(instrumentedConn); } } /** * Invokes all subscribed interceptor callbacks for the specified operation. * @param isBefore true if invoking a pre vs. post listener handler method * @param isAcquisition true if acquiring a connection, false if releasing a connection * @param exception any exception that was caught while performing the operation requested * @param connection any connection that was being closed (on exception) or an opened connection (after successful * acquire), or <code>null</code> after a successful release and failed acquire */ private void invokeListeners(boolean isBefore, boolean isAcquisition, Throwable exception, Connection connection) { for (ConnectionProviderListener listener : /* only loop over the listeners that are registered for this particular event type (pre/post open/close) */ getListenersForEventType(isBefore, isAcquisition)) { // allow the listener itself to determine whether it is enabled and will have this callback invocation skipped or not String methodName = "<unknown>"; try { if (isAcquisition) { if (isBefore) { methodName = "beforeConnectionAcquisition"; ((PreConnectionAcquisitionListener) listener).beforeConnectionAcquisition(this); } else { PostConnectionAcquisitionListener postListener = (PostConnectionAcquisitionListener) listener; if (exception != null) { methodName = "afterConnectionAcquisitionFailed"; postListener.afterConnectionAcquisitionFailed(this, exception); } else { methodName = "afterConnectionAcquired"; postListener.afterConnectionAcquired(this, connection); } } } else { if (isBefore) { methodName = "beforeClosingConnection"; ((PreConnectionCloseListener) listener).beforeClosingConnection(connection); } else { PostConnectionCloseListener postListener = (PostConnectionCloseListener) listener; if (exception != null) { methodName = "afterConnectionClosingFailed"; postListener.afterConnectionClosingFailed(connection, exception); } else { methodName = "afterConnectionClosed"; postListener.afterConnectionClosed(); } } } } catch (Throwable t) { if (log.isErrorEnabled()) { log.error("Unable to invoke {} from data source '{}' for listener of type: {}", methodName, dataSourceId, listener.getClass(), t); } } } } private List<? extends ConnectionProviderListener> getListenersForEventType(boolean isBefore, boolean isAcquisition) { if (isAcquisition) { return (isBefore ? preAcquisitionListeners : postAcquisitionListeners); } else { return (isBefore ? preCloseListeners : postCloseListeners); } } <L extends ConnectionProviderListener> L getListenerOfType(Class<L> listenerType) { ConnectionProviderListener listener = listenerMap.get(listenerType); if (listener == null) { return null; } return listenerType.cast(listener); } /** * Creates an instance of the {@link ConnectionProviderListener} implementation defined in the * <strong>listenerClazz</strong> and both constructs an instance, passes in database settings for this connection * provider, and injects this ConnectionProviderWrapper into the listener instance * @param hibernateProps the hibernate properties, which may be used by the listener to check if it is * enabled/disabled, or to extract configurable values * @param listenerClazz the listener implementation class that should be used * @return the listener instance that was created or <code>null</code> if there are any exceptions constructing or * initializing the new listener */ private ConnectionProviderListener createListener(Properties hibernateProps, Class<? extends ConnectionProviderListener> listenerClazz) { // try to locate a constructor that takes ConnectionProviderListenerSettings object first Constructor<? extends ConnectionProviderListener> constructor; try { constructor = listenerClazz.getDeclaredConstructor(); // make it accessible if it is not already if (!constructor.isAccessible()) { constructor.setAccessible(true); } } catch (NoSuchMethodException nsme) { log.error("Unable to attach connection provider listener to data source '{}' because it does not declare " + "a zero-argument constructor: {}", dataSourceId, listenerClazz); return null; } catch (SecurityException se) { log.error("Unable to make constructor accessible for listener class '{}' for data source '{}'", listenerClazz, dataSourceId, se); return null; } // now that we know it is accessible, instantiate it and attach to this InstrumentedConnectionProvider ConnectionProviderListener listener; try { // instantiate the new listener instance listener = constructor.newInstance(); } catch (IllegalAccessException iae) { log.error("Unable to access constructor for listener class '{}' for data source '{}'", listenerClazz, dataSourceId, iae); return null; } catch (InvocationTargetException ite) { Throwable cause = ite.getTargetException(); log.error("Unable to create new instance of '{}' for data source '{}' because constructor threw in an " + "exception", listenerClazz, dataSourceId, cause); return null; } catch (InstantiationException ie) { Throwable cause = (ie.getCause() != null ? ie.getCause() : ie); log.error("Unable to create new instance of '{}' to attach to data source '{}' due to an unexpected " + "exception", listenerClazz, dataSourceId, cause); return null; } // create the listener settings object, which can be done in a subclass and therefore may throw an exception ConnectionProviderListenerSettings settings; try { // pass in the Settings, which a subclass of this provider can override settings = createListenerSettings(hibernateProps); } catch (Exception e) { log.error("Encountered exception while creating listener settings for data source: '{}'", dataSourceId, e); return null; } // finish the initialization and return to caller try { // inject the parent (this) InstrumentedConnectionProvider into the listener object we just created, but // make sure to do so before we call initialize(..) method if (listener instanceof ConnectionProviderAware) { ((ConnectionProviderAware) listener).setConnectionProvider(this); } // allow the listener to initialize itself listener.initialize(settings); // listener has been fully configured, now return it return listener; } catch (Exception e) { log.error("Unable to initialize listener '{}' for data source '{}'", listenerClazz, dataSourceId, e); return null; } } /** * Adds a given {@link ConnectionProviderListener} to its specific interface-implementing event listener types. * This allows us to optimize invocations to listeners based on the event so we are not forced to iterate over all * listeners that may not subscribe to that callback. * * @param listener the listener to add to appropriate listener type lists */ private void addToListenerLists(ConnectionProviderListener listener) { Class<? extends ConnectionProviderListener> listenerClass = listener.getClass(); if (listenerMap.containsKey(listenerClass)) { throw new IllegalStateException("There is already a listener attached to data source '" + dataSourceId + "' with the same implementation class: " + listenerClass); } // add to the connection provider's map of singleton listeners listenerMap.put(listenerClass, listener); // attach to each phase-specific listener lists, one for each listener interface it implements if (listener instanceof PreConnectionAcquisitionListener) { preAcquisitionListeners.add((PreConnectionAcquisitionListener)listener); } if (listener instanceof PostConnectionAcquisitionListener) { postAcquisitionListeners.add((PostConnectionAcquisitionListener)listener); } if (listener instanceof PreConnectionCloseListener) { preCloseListeners.add((PreConnectionCloseListener)listener); } if (listener instanceof PostConnectionCloseListener) { postCloseListeners.add((PostConnectionCloseListener)listener); } } /** * Removes all listeners from this connection provider. * @see #addToListenerLists(org.drg.jdbceptor.hibernate.event.ConnectionProviderListener) */ protected void removeAllListeners() { preAcquisitionListeners.clear(); postAcquisitionListeners.clear(); preCloseListeners.clear(); postCloseListeners.clear(); } }
karussell/openlr
binary/openlr/binary/encoder/ClosedLineEncoder.java
/** * Licensed to the TomTom International B.V. under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. TomTom International B.V. * 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. */ /** * Copyright (C) 2009-2012 TomTom International B.V. * * TomTom (Legal Department) * Email: <EMAIL> * * TomTom (Technical contact) * Email: <EMAIL> * * Address: TomTom International B.V., Oosterdoksstraat 114, 1011DK Amsterdam, * the Netherlands */ package openlr.binary.encoder; import java.util.List; import openlr.LocationReference; import openlr.LocationReferencePoint; import openlr.LocationType; import openlr.PhysicalFormatException; import openlr.binary.BinaryReturnCode; import openlr.binary.ByteArray; import openlr.binary.bitstream.impl.ByteArrayBitstreamOutput; import openlr.binary.data.FirstLRP; import openlr.binary.data.Header; import openlr.binary.data.IntermediateLRP; import openlr.binary.data.LastClosedLineLRP; import openlr.binary.impl.LocationReferenceBinaryImpl; import openlr.rawLocRef.RawLocationReference; import org.apache.log4j.Logger; /** * The encoder for the line location type. * * <p> * OpenLR is a trade mark of TomTom International B.V. * <p> * email: <EMAIL> * * @author DLR e.V. (RE) */ public class ClosedLineEncoder extends AbstractEncoder { /** Logging */ private static final Logger LOG = Logger.getLogger(ClosedLineEncoder.class); /** * {@inheritDoc} */ @Override public final LocationReference encodeData( final RawLocationReference rawLocRef, final int version) { if (rawLocRef == null) { return new LocationReferenceBinaryImpl("", BinaryReturnCode.MISSING_DATA, LocationType.CLOSED_LINE, version); } List<? extends LocationReferencePoint> locRef = rawLocRef .getLocationReferencePoints(); if (locRef == null || locRef.isEmpty()) { return new LocationReferenceBinaryImpl(rawLocRef.getID(), BinaryReturnCode.MISSING_DATA, LocationType.CLOSED_LINE, version); } LocationReference lr = null; try { byte[] bd = generateBinaryClosedLineLocation(locRef, version); ByteArray ba = new ByteArray(bd.clone()); lr = new LocationReferenceBinaryImpl(rawLocRef.getID(), ba); } catch (PhysicalFormatException e) { lr = new LocationReferenceBinaryImpl(rawLocRef.getID(), BinaryReturnCode.INVALID_BINARY_DATA, LocationType.CLOSED_LINE, version); } return lr; } /** * Generates binary data of a closed line location reference according to * the OpenLR white paper. * * @param locref list of location reference points * @param version the version * @return the binary location reference * @throws PhysicalFormatException the physical format exception */ private byte[] generateBinaryClosedLineLocation( final List<? extends LocationReferencePoint> locref, final int version) throws PhysicalFormatException { Header header = generateHeader(version, LocationType.CLOSED_LINE, true); FirstLRP firstLRP = generateFirstLRP(locref.get(0)); IntermediateLRP[] lrps = generateLRPs(locref); LastClosedLineLRP lastLineLRP = generateLastLineLRP( locref); byte[] data = null; ByteArrayBitstreamOutput out = new ByteArrayBitstreamOutput(); header.put(out); firstLRP.put(out); for (int i = 0; i < lrps.length; ++i) { lrps[i].put(out); } lastLineLRP.put(out); data = out.getData(); if (LOG.isDebugEnabled()) { LOG.debug("binary data size (bytes): " + data.length); } return data; } }
wanghaiyang-github/dna-cloud
bazl-dna-mix/src/main/java/com/bazl/dna/mix/model/vo/MixedSampleGeneVo.java
<filename>bazl-dna-mix/src/main/java/com/bazl/dna/mix/model/vo/MixedSampleGeneVo.java package com.bazl.dna.mix.model.vo; import com.bazl.dna.mix.model.po.MixedSampleGene; import java.io.Serializable; import java.util.Date; import java.util.Map; /** * Created by Administrator on 2017/1/4. */ public class MixedSampleGeneVo extends AbstractBaseVO<MixedSampleGene> implements Serializable { private static final long serialVersionUID = 1L; public MixedSampleGeneVo() { super(); this.entity = new MixedSampleGene(); } public MixedSampleGeneVo(MixedSampleGene entity) { super(); this.entity = entity; } private String caseId; private String sampleNo; private String sampleNobizhong; private String sampleName; private String sampleType; private String sampleTypeName; private String sampleFlag; private String refPersonId; private String remark; private String caseNo; private String caseName; private String orgId; private String userId; private Map<String, Object> resultGeneInfo; private Map<String, Object> geneMap; private String newGeneInfo; private String geneImagePath; /** * 混合id */ private String mixedSampleGendId; /** * 比中id */ private String singlegeneId; /** * 名称 */ private String personName; /** * 比中数 */ private Short ratio; /** * 差异数 */ private Short splitDigit; /** * 比中时间 */ private Date comparisonTime; public String getNewGeneInfo() { return newGeneInfo; } public void setNewGeneInfo(String newGeneInfo) { this.newGeneInfo = newGeneInfo; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getOrgId() { return orgId; } public void setOrgId(String orgId) { this.orgId = orgId; } public Map<String, Object> getResultGeneInfo() { return resultGeneInfo; } public void setResultGeneInfo(Map<String, Object> resultGeneInfo) { this.resultGeneInfo = resultGeneInfo; } public String getCaseNo() { return caseNo; } public void setCaseNo(String caseNo) { this.caseNo = caseNo; } public String getCaseName() { return caseName; } public void setCaseName(String caseName) { this.caseName = caseName; } public String getCaseId() { return caseId; } public void setCaseId(String caseId) { this.caseId = caseId; } public String getSampleNo() { return sampleNo; } public void setSampleNo(String sampleNo) { this.sampleNo = sampleNo; } public String getSampleName() { return sampleName; } public void setSampleName(String sampleName) { this.sampleName = sampleName; } public String getSampleType() { return sampleType; } public void setSampleType(String sampleType) { this.sampleType = sampleType; } public String getSampleFlag() { return sampleFlag; } public void setSampleFlag(String sampleFlag) { this.sampleFlag = sampleFlag; } public String getRefPersonId() { return refPersonId; } public void setRefPersonId(String refPersonId) { this.refPersonId = refPersonId; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getMixedSampleGendId() { return mixedSampleGendId; } public void setMixedSampleGendId(String mixedSampleGendId) { this.mixedSampleGendId = mixedSampleGendId; } public String getSinglegeneId() { return singlegeneId; } public void setSinglegeneId(String singlegeneId) { this.singlegeneId = singlegeneId; } public Short getRatio() { return ratio; } public void setRatio(Short ratio) { this.ratio = ratio; } public Short getSplitDigit() { return splitDigit; } public void setSplitDigit(Short splitDigit) { this.splitDigit = splitDigit; } public Date getComparisonTime() { return comparisonTime; } public void setComparisonTime(Date comparisonTime) { this.comparisonTime = comparisonTime; } public String getSampleNobizhong() { return sampleNobizhong; } public void setSampleNobizhong(String sampleNobizhong) { this.sampleNobizhong = sampleNobizhong; } public String getPersonName() { return personName; } public void setPersonName(String personName) { this.personName = personName; } public Map<String, Object> getGeneMap() { return geneMap; } public void setGeneMap(Map<String, Object> geneMap) { this.geneMap = geneMap; } public String getGeneImagePath() { return geneImagePath; } public void setGeneImagePath(String geneImagePath) { this.geneImagePath = geneImagePath; } public String getSampleTypeName() { return sampleTypeName; } public void setSampleTypeName(String sampleTypeName) { this.sampleTypeName = sampleTypeName; } }
rohankadekodi/compilers_project
lonestar/experimental/meshsingularities/DAGSolver3D/Node.hpp
<gh_stars>0 #ifndef NODE_HPP #define NODE_HPP #include <vector> #include <string> #include <cstdio> #include <cstdlib> #include "Element.hpp" #include "EquationSystem.hpp" #include <set> class Mesh; class Node { private: int node = -1; Node* left = NULL; Node* right = NULL; Node* parent = NULL; std::vector<uint64_t>* meshSupernodes; std::vector<Element*> mergedElements; std::string production; std::vector<uint64_t> supernodes; std::vector<uint64_t> offsets; uint64_t supernodesToElim; public: EquationSystem* system; // TODO: temporary, add friend class for serialization or sth. int n_left = -1; int n_right = -1; int l = 0; int r = 0; std::vector<uint64_t> leftPlaces; std::vector<uint64_t> rightPlaces; Node() : node(0), system(NULL) {} Node(std::vector<uint64_t>* meshSupernodes, int num) : meshSupernodes(meshSupernodes), node(num), system(NULL) {} ~Node() { delete system; } void setLeft(Node* left); void setRight(Node* right); void setParent(Node* parent); Node* getLeft() const; Node* getRight() const; Node* getParent() const; void addElement(Element* e); std::vector<Element*>& getElements(); void clearElements(); void addSupernode(uint64_t supernode); std::vector<uint64_t>& getSupernodes(); void clearSupernodes(); void computeOffsets(); int getId() const; void setSupernodesToElim(uint64_t dofs); uint64_t getSupernodesToElim() const; void allocateSystem(SolverMode mode); void deallocateSystem(); void setProduction(std::string& prodname); std::string& getProduction(); void (*mergeProduction)(double** matrixA, double* rhsA, double** matrixB, double* rhsB, double** matrixOut, double* rhsOut); void (*preprocessProduction)(double** matrixIn, double* rhsIn, double** matrixOut, double* rhsOut); void fillin() const; void merge() const; void eliminate() const; void bs() const; unsigned long getSizeInMemory(bool recursive = true); unsigned long getFLOPs(bool recursive = true); unsigned long getMemoryRearrangements(); /*DEBUG*/ int treeSize(); /*END OF DEBUG*/ }; #endif // NODE_HPP
ryklin/master
libhid/usb-1608FS-Plus.h
<reponame>ryklin/master /* * * Copyright (c) 2013 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef USB_1608FS_PLUS_H #define USB_1608FS_PLUS_H #ifdef __cplusplus extern "C" { #endif #include <usb.h> #define USB1608FS_PLUS_PID (0x00ea) /* Description of the requestType byte */ // Data transfer direction D7 #define HOST_TO_DEVICE (0x0 << 7) #define DEVICE_TO_HOST (0x1 << 7) // Type D5-D6 #define STANDARD_TYPE (0x0 << 5) #define CLASS_TYPE (0x1 << 5) #define VENDOR_TYPE (0x2 << 5) #define RESERVED_TYPE (0x3 << 5) // Recipient D0 - D4 #define DEVICE_RECIPIENT (0x0) #define INTERFACE_RECIPIENT (0x1) #define ENDPOINT_RECIPIENT (0x2) #define OTHER_RECIPIENT (0x3) #define RESERVED_RECIPIENT (0x4) /* Commands and HID Report ID for USB 1608FS-Plus */ /* Digital I/O Commands */ #define DTRISTATE (0x00) // Read/Write Tristate register #define DPORT (0x01) // Read digital port pins #define DLATCH (0x02) // Read/Write Digital port output latch register /* Analog Input Commands */ #define AIN (0x10) // Read analog input channel #define AIN_SCAN_START (0x11) // Start analog input scan #define AIN_SCAN_STOP (0x12) // Stop analog input scan #define AIN_CONFIG (0x14) // Analog input channel configuration #define AIN_CLR_FIFO (0x15) // Clear the analog input scan FIFO /* Counter/Timer Commands */ #define COUNTER (0x20) // Read/reset event counter /* Memory Commands */ #define CAL_MEMORY (0x30) // Read/Write Calibration Memory #define USER_MEMORY (0x31) // Read/Write User Memory #define MBD_MEMORY (0x32) // Read/Write MBD Memory /* Miscellaneous Commands */ #define BLINK_LED (0x41) // Causes LED to blink #define RESET (0x42) // Reset device #define STATUS (0x44) // Read device status #define SERIAL (0x48) // Read/Write serial number #define DFU (0x50) // Enter device firmware upgrade mode /* MBD */ #define MBD_COMMAND (0x80) // Text-based MBD command / response #define MBD_RAW (0x81) // Raw MBD response /* Analog Input Scan Options */ #define IMMEDIATE_TRANSFER_MODE (0x1) #define BLOCK_TRANSFER_MODE (0x0) #define INTERNAL_PACER_ON (0x2) // output internal pacer on SYNC #define INTERNAL_PACER_OFF (0x0) #define NO_TRIGGER (0x0) #define TRIG_EDGE_RISING (0x1 << 2) #define TRIG_EDGE_FALLING (0x2 << 2) #define TRIG_LEVEL_HIGH (0x3 << 2) #define TRIG_LEVEL_LOW (0x4 << 2) #define DEBUG_MODE (0x10) #define STALL_ON_OVERRUN (0x0) #define INHIBIT_STALL (0x1 << 7) /* Aanalog Input */ #define SINGLE_ENDED 0 #define DIFFERENTIAL 1 #define CALIBRATION 3 #define LAST_CHANNEL (0x80) #define PACKET_SIZE 64 // max bulk transfer size in bytes /* Ranges */ #define BP_10V 0x0 // +/- 10 V #define BP_5V 0x1 // +/- 5V #define BP_2_5V 0x2 // +/- 2.5V #define BP_2V 0x3 // +/- 2V #define BP_1_25V 0x4 // +/- 1.25V #define BP_1V 0x5 // +/- 1V #define BP_625V 0x6 // +/- 0.625V #define BP_3125V 0x7 // +/- 0.3125V /* Status bit values */ #define AIN_SCAN_RUNNING (0x1 << 1) #define AIN_SCAN_OVERRUN (0x1 << 2) #define NCHAN_USB1608FS_PLUS 8 // max number of A/D channels in the device #define NGAINS_USB1608FS_PLUS 8 // max number of gain levels #define MAX_PACKET_SIZE 64 // max packet size for FS device typedef struct t_calibrationTimeStamp { __u8 year; // Calibration date year __u8 month; // Calibration date month __u8 day; // Calibration date day __u8 hour; // Calibration date hour __u8 minute; // Calibration date minute __u8 second; // Calibration date second } calibrationTimeStamp; /* function prototypes for the USB-1608FS-Plus */ __u8 usbDTristateR_USB1608FS_Plus(usb_dev_handle *udev); void usbDTristateW_USB1608FS_Plus(usb_dev_handle *udev, __u8 value); __u8 usbDPort_USB1608FS_Plus(usb_dev_handle *udev); __u8 usbDLatchR_USB1608FS_Plus(usb_dev_handle *udev); void usbDLatchW_USB1608FS_Plus(usb_dev_handle *udev, __u8 value); __u16 usbAIn_USB1608FS_Plus(usb_dev_handle *udev, __u8 channel, __u8 range); void usbAInScanStart_USB1608FS_Plus(usb_dev_handle *udev, __u32 count, double frequency, __u8 channels, __u8 options); void usbAInScanConfig_USB1608FS_Plus(usb_dev_handle *udev, __u8 ranges[8]); void usbAInScanConfigR_USB1608FS_Plus(usb_dev_handle *udev, __u8 *ranges); int usbAInScanRead_USB1608FS_Plus(usb_dev_handle *udev, int nScan, int nChan, __u16 *data); void usbAInScanStop_USB1608FS_Plus(usb_dev_handle *udev); void usbAInScanClearFIFO_USB1608FS_Plus(usb_dev_handle *udev); __u32 usbCounter_USB1608FS_Plus(usb_dev_handle *udev); void usbCounterInit_USB1608FS_Plus(usb_dev_handle *udev); void usbReadCalMemory_USB1608FS_Plus(usb_dev_handle *udev, __u16 address, __u16 count, __u8 memory[]); void usbWriteCalMemory_USB1608FS_Plus(usb_dev_handle *udev, __u16 address, __u16 count, __u8 data[]); void usbReadUserMemory_USB1608FS_Plus(usb_dev_handle *udev, __u16 address, __u16 count, __u8 memory[]); void usbWriteUserMemory_USB1608FS_Plus(usb_dev_handle *udev, __u16 address, __u16 count, __u8 data[]); void usbReadMBDMemory_USB1608FS_Plus(usb_dev_handle *udev, __u16 address, __u16 count, __u8 memory[]); void usbWriteMBDMemory_USB1608FS_Plus(usb_dev_handle *udev, __u16 address, __u16 count, __u8 data[]); void usbBlink_USB1608FS_Plus(usb_dev_handle *udev, __u8 count); void usbReset_USB1608FS_Plus(usb_dev_handle *udev); __u16 usbStatus_USB1608FS_Plus(usb_dev_handle *udev); void usbGetSerialNumber_USB1608FS_Plus(usb_dev_handle *udev, char serial[9]); void usbDFU_USB1608FS_Plus(usb_dev_handle *udev); void usbMBDCommand_USB1608FS_Plus(usb_dev_handle *udev, __u8 str[]); void usbMBDRaw_USB1608FS_Plus(usb_dev_handle *udev, __u8 cmd[], __u16 size); void cleanup_USB1608FS_Plus(usb_dev_handle *udev); void usbBuildGainTable_USB1608FS_Plus(usb_dev_handle *udev, float table[NGAINS_USB1608FS_PLUS][NCHAN_USB1608FS_PLUS][2]); double volts_USB1608FS_Plus(usb_dev_handle *udev, __u16 value, __u8 range); #ifdef __cplusplus } /* closing brace for extern "C" */ #endif #endif //USB_1608FS_PLUS_H
cy15196/FastCAE
Code/HeuDataSrcIO/ProgressBar.h
<filename>Code/HeuDataSrcIO/ProgressBar.h #ifndef PROGRESSBAR_H #define PROGRESSBAR_H #include <QLabel> #include <QProgressBar> #include <QPushButton> #include "heudatasrcio_global.h" class ProgressBar : public QWidget { Q_OBJECT public: int mRangeSize=100; ProgressBar(QWidget *parent = 0); ~ProgressBar(); void SetRange(int range); void SetMessage(const QString& msg); void SetProgress(int pos); bool IsTaskAborted() { return mAbortJob; } private slots: void OnAbort(); private: QLabel *mMsgLabel; QProgressBar *mProgBar; QPushButton *mAbortBtn; bool mAbortJob; }; #endif // PROGRESSBAR_H
vjh0107/Skellett
src/main/java/com/gmail/thelimeglass/Expressions/ExprShootGetArrow.java
package com.gmail.thelimeglass.Expressions; import org.bukkit.entity.Entity; import org.bukkit.event.Event; import org.bukkit.event.entity.EntityShootBowEvent; import org.eclipse.jdt.annotation.Nullable; import com.gmail.thelimeglass.Utils.Annotations.Config; import com.gmail.thelimeglass.Utils.Annotations.FullConfig; import com.gmail.thelimeglass.Utils.Annotations.PropertyType; import com.gmail.thelimeglass.Utils.Annotations.Syntax; import ch.njol.skript.ScriptLoader; import ch.njol.skript.Skript; import ch.njol.skript.classes.Changer; import ch.njol.skript.classes.Changer.ChangeMode; import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.ExpressionType; import ch.njol.skript.lang.SkriptParser; import ch.njol.skript.lang.util.SimpleExpression; import ch.njol.util.Kleenean; import ch.njol.util.coll.CollectionUtils; @Syntax("[the] [skellett] [(event|get)] [the] shot (arrow|projectile)") @Config("Main.Shooting") @FullConfig @PropertyType(ExpressionType.SIMPLE) public class ExprShootGetArrow extends SimpleExpression<Entity> { public Class<? extends Entity> getReturnType() { return Entity.class; } public boolean isSingle() { return true; } public boolean init(Expression<?>[] args, int arg1, Kleenean arg2, SkriptParser.ParseResult arg3) { if (!ScriptLoader.isCurrentEvent(EntityShootBowEvent.class)) { Skript.error("You can not use Get Arrow expression in any event but 'on entity shoot:' event!"); return false; } return true; } public String toString(@Nullable Event arg0, boolean arg1) { return "Shooter Arrow"; } @Nullable protected Entity[] get(Event e) { return new Entity[]{((EntityShootBowEvent)e).getProjectile()}; } @Override public void change(Event e, Object[] delta, Changer.ChangeMode mode){ if (mode == ChangeMode.SET) { ((EntityShootBowEvent)e).setProjectile((Entity)delta[0]); } } @Override public Class<?>[] acceptChange(final Changer.ChangeMode mode) { if (mode == ChangeMode.SET) { return CollectionUtils.array(Entity.class); } return null; } }
googleapis/googleapis-gen
google/cloud/clouddms/v1/google-cloud-clouddms-v1-java/proto-google-cloud-clouddms-v1-java/src/main/java/com/google/cloud/clouddms/v1/CloudSqlConnectionProfileOrBuilder.java
<gh_stars>1-10 // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/clouddms/v1/clouddms_resources.proto package com.google.cloud.clouddms.v1; public interface CloudSqlConnectionProfileOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.clouddms.v1.CloudSqlConnectionProfile) com.google.protobuf.MessageOrBuilder { /** * <pre> * Output only. The Cloud SQL instance ID that this connection profile is associated with. * </pre> * * <code>string cloud_sql_id = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The cloudSqlId. */ java.lang.String getCloudSqlId(); /** * <pre> * Output only. The Cloud SQL instance ID that this connection profile is associated with. * </pre> * * <code>string cloud_sql_id = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for cloudSqlId. */ com.google.protobuf.ByteString getCloudSqlIdBytes(); /** * <pre> * Immutable. Metadata used to create the destination Cloud SQL database. * </pre> * * <code>.google.cloud.clouddms.v1.CloudSqlSettings settings = 2 [(.google.api.field_behavior) = IMMUTABLE];</code> * @return Whether the settings field is set. */ boolean hasSettings(); /** * <pre> * Immutable. Metadata used to create the destination Cloud SQL database. * </pre> * * <code>.google.cloud.clouddms.v1.CloudSqlSettings settings = 2 [(.google.api.field_behavior) = IMMUTABLE];</code> * @return The settings. */ com.google.cloud.clouddms.v1.CloudSqlSettings getSettings(); /** * <pre> * Immutable. Metadata used to create the destination Cloud SQL database. * </pre> * * <code>.google.cloud.clouddms.v1.CloudSqlSettings settings = 2 [(.google.api.field_behavior) = IMMUTABLE];</code> */ com.google.cloud.clouddms.v1.CloudSqlSettingsOrBuilder getSettingsOrBuilder(); /** * <pre> * Output only. The Cloud SQL database instance's private IP. * </pre> * * <code>string private_ip = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The privateIp. */ java.lang.String getPrivateIp(); /** * <pre> * Output only. The Cloud SQL database instance's private IP. * </pre> * * <code>string private_ip = 3 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for privateIp. */ com.google.protobuf.ByteString getPrivateIpBytes(); /** * <pre> * Output only. The Cloud SQL database instance's public IP. * </pre> * * <code>string public_ip = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The publicIp. */ java.lang.String getPublicIp(); /** * <pre> * Output only. The Cloud SQL database instance's public IP. * </pre> * * <code>string public_ip = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code> * @return The bytes for publicIp. */ com.google.protobuf.ByteString getPublicIpBytes(); }
redlink-gmbh/redlink-nlp
ner/opennlp/ner-opennlp/src/main/java/io/redlink/nlp/opennlp/NameFinderModel.java
/* * Copyright (c) 2022 Redlink GmbH. * * 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 io.redlink.nlp.opennlp; import io.redlink.nlp.model.ner.NerTag; import java.util.HashMap; import java.util.Map; import opennlp.tools.namefind.NameFinderME; import opennlp.tools.namefind.TokenNameFinderModel; /** * Represents a configured OpenNLP {@link TokenNameFinderModel}. * <p> * During construction the name and type mappings are set. During the * activation the model is loaded. {@link ThreadLocal} {@link NameFinderME} * instances are created at runtime. * * @author <NAME> */ public class NameFinderModel { private final Map<String, String> typeMappings = new HashMap<>(); /** * The name of the model. */ protected final String modelName; private TokenNameFinderModel model; private ThreadLocal<NameFinderME> nameFinder; public NameFinderModel(String modelName) { assert modelName != null; assert !modelName.isEmpty(); this.modelName = modelName; } /** * Creates a NameFinderModel including some type mappings * * @param modelName the name of the {@link TokenNameFinderModel} * @param typeMappings the type mappings formatted like * <code>[modelType1, type1, modelType2, type2, ... , modelTypeN, typeN]</code> */ public NameFinderModel(String modelName, String... typeMappings) { this(modelName); assert typeMappings != null; assert typeMappings.length % 2 == 0; for (int i = 0; i < typeMappings.length - 1; i++) { addMapping(typeMappings[i++], typeMappings[i]); } } /** * Adds a type mapping for the model. * * @param modelType the type string used by the model * @param type the type string used by the {@link NamedEntity#type} * @return Returns this instance */ public NameFinderModel addMapping(String modelType, String type) { typeMappings.put(modelType, type); return this; } /** * Used by the {@link OpenNlpNerModel#activate()} method to set the * loaded model. * * @param model the model to set */ void setModel(TokenNameFinderModel model) { assert model != null; this.model = model; this.nameFinder = new ThreadLocal<NameFinderME>() { @Override protected NameFinderME initialValue() { return new NameFinderME(NameFinderModel.this.model); } }; } /** * Allows to reset the {@link #model} and {@link #nameFinder} */ void reset() { this.model = null; this.nameFinder = null; } /** * Getter for the model. * * @return the model */ public TokenNameFinderModel getModel() { return model; } /** * Getter for the name finder * * @return the name finder */ public NameFinderME getNameFinder() { return nameFinder == null ? null : nameFinder.get(); } @Override public String toString() { return modelName; } /** * Getter for the type based on the model type * * @param type the model type * @return the mapped type or <code>null</code> if no mapping for this type * is present. If <code>null</code> is parsed this will return * {@link Constants.Extraction#NAMED_ENTITY_UNKOWN} */ public String getType(String type) { return type == null ? NerTag.NAMED_ENTITY_UNKOWN : typeMappings.get(type); } }
ResearchSoftwareInstitute/MyHPOM
hs_core/page_processors.py
"""Page processors for hs_core app.""" from dateutil import parser from functools import partial, wraps from django.conf import settings from django.core.exceptions import PermissionDenied from django.forms.models import formset_factory from mezzanine.pages.page_processors import processor_for from hs_core.models import GenericResource, Relation from hs_core import languages_iso from forms import CreatorForm, ContributorForm, SubjectsForm, AbstractForm, RelationForm, \ SourceForm, FundingAgencyForm, BaseCreatorFormSet, BaseContributorFormSet, BaseFormSet, \ MetaDataElementDeleteForm, CoverageTemporalForm, CoverageSpatialForm, ExtendedMetadataForm from hs_core.views.utils import show_relations_section, \ can_user_copy_resource from hs_core.hydroshare.resource import METADATA_STATUS_SUFFICIENT, METADATA_STATUS_INSUFFICIENT from hs_tools_resource.app_launch_helper import resource_level_tool_urls @processor_for(GenericResource) def landing_page(request, page): """Return resource landing page context.""" edit_resource = check_resource_mode(request) return get_page_context(page, request.user, resource_edit=edit_resource, request=request) @processor_for('sign-up') def sign_up(request, page): """ Add Captcha SITE_KEY to the sign up page context. """ return { 'SITE_KEY': settings.RECAPTCHA_SITE_KEY } # resource type specific app needs to call this method to inject a crispy_form layout # object for displaying metadata UI for the extended metadata for their resource def get_page_context(page, user, resource_edit=False, extended_metadata_layout=None, request=None): """Inject a crispy_form layout into the page to display extended metadata. :param page: which page to get the template context for :param user: the user who is viewing the page :param resource_edit: True if and only if the page should render in edit mode :param extended_metadata_layout: layout information used to build an ExtendedMetadataForm :param request: the Django request associated with the page load :return: the basic template context (a python dict) used to render a resource page. can and should be extended by page/resource-specific page_processors Resource type specific app needs to call this method to inject a crispy_form layout object for displaying metadata UI for the extended metadata for their resource TODO: refactor to make it clear that there are two different modes = EDITABLE | READONLY - split into two functions: get_readonly_page_context(...) and get_editable_page_context(...) """ file_type_error = '' if request: file_type_error = request.session.get("file_type_error", None) if file_type_error: del request.session["file_type_error"] content_model = page.get_content_model() # whether the user has permission to view this resource can_view = content_model.can_view(request) if not can_view: raise PermissionDenied() discoverable = content_model.raccess.discoverable validation_error = None resource_is_mine = False if user.is_authenticated(): resource_is_mine = content_model.rlabels.is_mine(user) metadata_status = _get_metadata_status(content_model) belongs_to_collections = content_model.collections.all() relevant_tools = None tool_homepage_url = None if not resource_edit: # In view mode landing_page_res_obj = content_model landing_page_res_type_str = landing_page_res_obj.resource_type if landing_page_res_type_str.lower() == "toolresource": if landing_page_res_obj.metadata.app_home_page_url: tool_homepage_url = content_model.metadata.app_home_page_url.value else: relevant_tools = resource_level_tool_urls(landing_page_res_obj, request) just_created = False just_copied = False create_resource_error = None just_published = False if request: validation_error = check_for_validation(request) just_created = request.session.get('just_created', False) if 'just_created' in request.session: del request.session['just_created'] just_copied = request.session.get('just_copied', False) if 'just_copied' in request.session: del request.session['just_copied'] create_resource_error = request.session.get('resource_creation_error', None) if 'resource_creation_error' in request.session: del request.session['resource_creation_error'] just_published = request.session.get('just_published', False) if 'just_published' in request.session: del request.session['just_published'] bag_url = content_model.bag_url if user.is_authenticated(): show_content_files = user.uaccess.can_view_resource(content_model) else: # if anonymous user getting access to a private resource (since resource is discoverable), # then don't show content files show_content_files = content_model.raccess.public allow_copy = can_user_copy_resource(content_model, user) qholder = content_model.get_quota_holder() # user requested the resource in READONLY mode if not resource_edit: temporal_coverages = content_model.metadata.coverages.all().filter(type='period') if len(temporal_coverages) > 0: temporal_coverage_data_dict = {} temporal_coverage = temporal_coverages[0] start_date = parser.parse(temporal_coverage.value['start']) end_date = parser.parse(temporal_coverage.value['end']) temporal_coverage_data_dict['start_date'] = start_date.strftime('%Y-%m-%d') temporal_coverage_data_dict['end_date'] = end_date.strftime('%Y-%m-%d') temporal_coverage_data_dict['name'] = temporal_coverage.value.get('name', '') else: temporal_coverage_data_dict = None spatial_coverages = content_model.metadata.coverages.all().exclude(type='period') if len(spatial_coverages) > 0: spatial_coverage_data_dict = {} spatial_coverage = spatial_coverages[0] spatial_coverage_data_dict['name'] = spatial_coverage.value.get('name', None) spatial_coverage_data_dict['units'] = spatial_coverage.value['units'] spatial_coverage_data_dict['zunits'] = spatial_coverage.value.get('zunits', None) spatial_coverage_data_dict['projection'] = spatial_coverage.value.get('projection', None) spatial_coverage_data_dict['type'] = spatial_coverage.type if spatial_coverage.type == 'point': spatial_coverage_data_dict['east'] = spatial_coverage.value['east'] spatial_coverage_data_dict['north'] = spatial_coverage.value['north'] spatial_coverage_data_dict['elevation'] = spatial_coverage.value.get('elevation', None) else: spatial_coverage_data_dict['northlimit'] = spatial_coverage.value['northlimit'] spatial_coverage_data_dict['eastlimit'] = spatial_coverage.value['eastlimit'] spatial_coverage_data_dict['southlimit'] = spatial_coverage.value['southlimit'] spatial_coverage_data_dict['westlimit'] = spatial_coverage.value['westlimit'] spatial_coverage_data_dict['uplimit'] = spatial_coverage.value.get('uplimit', None) spatial_coverage_data_dict['downlimit'] = spatial_coverage.value.get('downlimit', None) else: spatial_coverage_data_dict = None keywords = ",".join([sub.value for sub in content_model.metadata.subjects.all()]) languages_dict = dict(languages_iso.languages) language = languages_dict[content_model.metadata.language.code] if \ content_model.metadata.language else None title = content_model.metadata.title.value if content_model.metadata.title else None abstract = content_model.metadata.description.abstract if \ content_model.metadata.description else None missing_metadata_elements = content_model.metadata.get_required_missing_elements() context = { 'resource_edit_mode': resource_edit, 'metadata_form': None, 'citation': content_model.get_citation(), 'title': title, 'abstract': abstract, 'creators': content_model.metadata.creators.all(), 'contributors': content_model.metadata.contributors.all(), 'temporal_coverage': temporal_coverage_data_dict, 'spatial_coverage': spatial_coverage_data_dict, 'language': language, 'keywords': keywords, 'rights': content_model.metadata.rights, 'sources': content_model.metadata.sources.all(), 'relations': content_model.metadata.relations.all(), 'show_relations_section': show_relations_section(content_model), 'fundingagencies': content_model.metadata.funding_agencies.all(), 'metadata_status': metadata_status, 'missing_metadata_elements': missing_metadata_elements, 'validation_error': validation_error if validation_error else None, 'resource_creation_error': create_resource_error, 'relevant_tools': relevant_tools, 'tool_homepage_url': tool_homepage_url, 'file_type_error': file_type_error, 'just_created': just_created, 'just_copied': just_copied, 'just_published': just_published, 'bag_url': bag_url, 'show_content_files': show_content_files, 'discoverable': discoverable, 'resource_is_mine': resource_is_mine, 'allow_resource_copy': allow_copy, 'is_resource_specific_tab_active': False, 'quota_holder': qholder, 'belongs_to_collections': belongs_to_collections, 'current_user': user } if 'task_id' in request.session: task_id = request.session.get('task_id', None) if task_id: context['task_id'] = task_id del request.session['task_id'] if 'download_path' in request.session: download_path = request.session.get('download_path', None) if download_path: context['download_path'] = download_path del request.session['download_path'] return context # user requested the resource in EDIT MODE # whether the user has permission to change the model can_change = content_model.can_change(request) if not can_change: raise PermissionDenied() add_creator_modal_form = CreatorForm(allow_edit=can_change, res_short_id=content_model.short_id) add_contributor_modal_form = ContributorForm(allow_edit=can_change, res_short_id=content_model.short_id) add_relation_modal_form = RelationForm(allow_edit=can_change, res_short_id=content_model.short_id) add_source_modal_form = SourceForm(allow_edit=can_change, res_short_id=content_model.short_id) add_fundingagency_modal_form = FundingAgencyForm(allow_edit=can_change, res_short_id=content_model.short_id) keywords = ",".join([sub.value for sub in content_model.metadata.subjects.all()]) subjects_form = SubjectsForm(initial={'value': keywords}, allow_edit=can_change, res_short_id=content_model.short_id, element_id=None) abstract_form = AbstractForm(instance=content_model.metadata.description, allow_edit=can_change, res_short_id=content_model.short_id, element_id=content_model.metadata.description.id if content_model.metadata.description else None) CreatorFormSetEdit = formset_factory(wraps(CreatorForm)(partial(CreatorForm, allow_edit=can_change)), formset=BaseCreatorFormSet, extra=0) creator_formset = CreatorFormSetEdit(initial=content_model.metadata.creators.all().values(), prefix='creator') index = 0 # TODO: dont track index manually. use enumerate, or zip for creator_form in creator_formset.forms: creator_form.action = "/hydroshare/hsapi/_internal/%s/creator/%s/update-metadata/" % \ (content_model.short_id, creator_form.initial['id']) creator_form.number = creator_form.initial['id'] index += 1 ContributorFormSetEdit = formset_factory(wraps(ContributorForm)(partial(ContributorForm, allow_edit=can_change)), formset=BaseContributorFormSet, extra=0) contributor_formset = ContributorFormSetEdit(initial=content_model.metadata.contributors.all(). values(), prefix='contributor') index = 0 # TODO: dont track index manually. use enumerate, or zip for contributor_form in contributor_formset.forms: contributor_form.action = "/hydroshare/hsapi/_internal/%s/contributor/%s/update-metadata/" % \ (content_model.short_id, contributor_form.initial['id']) contributor_form.number = contributor_form.initial['id'] index += 1 RelationFormSetEdit = formset_factory(wraps(RelationForm)(partial(RelationForm, allow_edit=can_change)), formset=BaseFormSet, extra=0) relation_formset = RelationFormSetEdit(initial=content_model.metadata.relations.all().values(), prefix='relation') for relation_form in relation_formset.forms: relation_form.action = "/hydroshare/hsapi/_internal/%s/relation/%s/update-metadata/" % \ (content_model.short_id, relation_form.initial['id']) relation_form.number = relation_form.initial['id'] SourceFormSetEdit = formset_factory(wraps(SourceForm)(partial(SourceForm, allow_edit=can_change)), formset=BaseFormSet, extra=0) source_formset = SourceFormSetEdit(initial=content_model.metadata.sources.all().values(), prefix='source') for source_form in source_formset.forms: source_form.action = "/hydroshare/hsapi/_internal/%s/source/%s/update-metadata/" % \ (content_model.short_id, source_form.initial['id']) source_form.delete_modal_form = MetaDataElementDeleteForm(content_model.short_id, 'source', source_form.initial['id']) source_form.number = source_form.initial['id'] FundingAgencyFormSetEdit = formset_factory(wraps(FundingAgencyForm)(partial( FundingAgencyForm, allow_edit=can_change)), formset=BaseFormSet, extra=0) fundingagency_formset = FundingAgencyFormSetEdit( initial=content_model.metadata.funding_agencies.all().values(), prefix='fundingagency') for fundingagency_form in fundingagency_formset.forms: action = "/hydroshare/hsapi/_internal/{}/fundingagnecy/{}/update-metadata/" action = action.format(content_model.short_id, fundingagency_form.initial['id']) fundingagency_form.action = action fundingagency_form.number = fundingagency_form.initial['id'] temporal_coverages = content_model.metadata.coverages.all().filter(type='period') temporal_coverage_data_dict = {} if len(temporal_coverages) > 0: temporal_coverage = temporal_coverages[0] start_date = parser.parse(temporal_coverage.value['start']) end_date = parser.parse(temporal_coverage.value['end']) temporal_coverage_data_dict['start'] = start_date.strftime('%m-%d-%Y') temporal_coverage_data_dict['end'] = end_date.strftime('%m-%d-%Y') temporal_coverage_data_dict['name'] = temporal_coverage.value.get('name', '') temporal_coverage_data_dict['id'] = temporal_coverage.id else: temporal_coverage = None coverage_temporal_form = CoverageTemporalForm(initial=temporal_coverage_data_dict, allow_edit=can_change, res_short_id=content_model.short_id, element_id=temporal_coverage.id if temporal_coverage else None) spatial_coverages = content_model.metadata.coverages.all().exclude(type='period') spatial_coverage_data_dict = {'type': 'point'} if len(spatial_coverages) > 0: spatial_coverage = spatial_coverages[0] spatial_coverage_data_dict['name'] = spatial_coverage.value.get('name', None) spatial_coverage_data_dict['units'] = spatial_coverage.value['units'] spatial_coverage_data_dict['zunits'] = spatial_coverage.value.get('zunits', None) spatial_coverage_data_dict['projection'] = spatial_coverage.value.get('projection', None) spatial_coverage_data_dict['type'] = spatial_coverage.type spatial_coverage_data_dict['id'] = spatial_coverage.id if spatial_coverage.type == 'point': spatial_coverage_data_dict['east'] = spatial_coverage.value['east'] spatial_coverage_data_dict['north'] = spatial_coverage.value['north'] spatial_coverage_data_dict['elevation'] = spatial_coverage.value.get('elevation', None) else: spatial_coverage_data_dict['northlimit'] = spatial_coverage.value['northlimit'] spatial_coverage_data_dict['eastlimit'] = spatial_coverage.value['eastlimit'] spatial_coverage_data_dict['southlimit'] = spatial_coverage.value['southlimit'] spatial_coverage_data_dict['westlimit'] = spatial_coverage.value['westlimit'] spatial_coverage_data_dict['uplimit'] = spatial_coverage.value.get('uplimit', None) spatial_coverage_data_dict['downlimit'] = spatial_coverage.value.get('downlimit', None) else: spatial_coverage = None coverage_spatial_form = CoverageSpatialForm(initial=spatial_coverage_data_dict, allow_edit=can_change, res_short_id=content_model.short_id, element_id=spatial_coverage.id if spatial_coverage else None) metadata_form = ExtendedMetadataForm(resource_mode='edit' if can_change else 'view', extended_metadata_layout=extended_metadata_layout) context = { 'resource_edit_mode': resource_edit, 'metadata_form': metadata_form, 'creator_formset': creator_formset, 'add_creator_modal_form': add_creator_modal_form, 'creator_profilelink_formset': None, 'title': content_model.metadata.title, 'abstract_form': abstract_form, 'contributor_formset': contributor_formset, 'add_contributor_modal_form': add_contributor_modal_form, 'relation_formset': relation_formset, 'add_relation_modal_form': add_relation_modal_form, 'source_formset': source_formset, 'add_source_modal_form': add_source_modal_form, 'fundingagnency_formset': fundingagency_formset, 'add_fundinagency_modal_form': add_fundingagency_modal_form, 'coverage_temporal_form': coverage_temporal_form, 'coverage_spatial_form': coverage_spatial_form, 'spatial_coverage': spatial_coverage_data_dict, 'subjects_form': subjects_form, 'metadata_status': metadata_status, 'missing_metadata_elements': content_model.metadata.get_required_missing_elements(), 'citation': content_model.get_citation(), 'rights': content_model.metadata.rights, 'extended_metadata_layout': extended_metadata_layout, 'bag_url': bag_url, 'current_user': user, 'show_content_files': show_content_files, 'validation_error': validation_error if validation_error else None, 'discoverable': discoverable, 'resource_is_mine': resource_is_mine, 'quota_holder': qholder, 'relation_source_types': tuple((type_value, type_display) for type_value, type_display in Relation.SOURCE_TYPES if type_value != 'isReplacedBy' and type_value != 'isVersionOf' and type_value != 'hasPart'), 'is_resource_specific_tab_active': False, 'belongs_to_collections': belongs_to_collections } return context def check_resource_mode(request): """Determine whether the `request` represents an attempt to edit a resource. A request is considered an attempt to edit if any of the following conditions are met: 1. the HTTP verb is not "GET" 2. the HTTP verb is "GET" and the 'resource-mode' property is set to 'edit' This function erases the 'resource-mode' property of `request.session` if it exists. :param request: the `request` for a resource :return: True if the request represents an attempt to edit a resource, and False otherwise. """ if request.method == "GET": edit_resource = request.session.get('resource-mode', None) == 'edit' if edit_resource: del request.session['resource-mode'] else: edit_resource = request.GET.get('resource-mode', None) == 'edit' else: edit_resource = True return edit_resource def check_for_validation(request): """Check for validation error in request session.""" if request.method == "GET": validation_error = request.session.get('validation_error', None) if validation_error: del request.session['validation_error'] return validation_error return None def _get_metadata_status(resource): if resource.metadata.has_all_required_elements(): metadata_status = METADATA_STATUS_SUFFICIENT else: metadata_status = METADATA_STATUS_INSUFFICIENT return metadata_status
SteveKunG/FishOfThieves
common/src/main/java/com/stevekung/fishofthieves/entity/FishVariant.java
<filename>common/src/main/java/com/stevekung/fishofthieves/entity/FishVariant.java package com.stevekung.fishofthieves.entity; import java.util.function.Predicate; import com.stevekung.fishofthieves.spawn.SpawnConditionContext; public interface FishVariant { String getName(); int getId(); Predicate<SpawnConditionContext> getCondition(); }
tomgratte/trakem2_to_bdv
src/main/java/bdv/img/cache/CacheIoTiming.java
<reponame>tomgratte/trakem2_to_bdv /* * #%L * BigDataViewer core classes with minimal dependencies * %% * Copyright (C) 2012 - 2015 BigDataViewer authors * %% * 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 HOLDERS 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. * #L% */ package bdv.img.cache; import java.util.concurrent.ConcurrentHashMap; import net.imglib2.ui.util.StopWatch; /** * Utilities for per {@link ThreadGroup} measuring and budgeting of time spent * in (blocking) IO. * * @author <NAME> &lt;<EMAIL>&gt; */ public class CacheIoTiming { /** * Budget of time that can be spent in blocking IO. The budget is grouped by * priority levels, where level 0 is the highest priority. The budget for * level <em>i&gt;j</em> must always be smaller-equal the budget for level * <em>j</em>. */ public static class IoTimeBudget { private final long[] budget; public IoTimeBudget( final int numLevels ) { budget = new long[ numLevels ]; } public synchronized void reset( final long[] partialBudget ) { if ( partialBudget == null ) clear(); else { for ( int i = 0; i < budget.length; ++i ) budget[ i ] = partialBudget.length > i ? partialBudget[ i ] : partialBudget[ partialBudget.length - 1 ]; for ( int i = 1; i < budget.length; ++i ) if ( budget[ i ] > budget[ i - 1 ] ) budget[ i ] = budget[ i - 1 ]; } } public synchronized void clear() { for ( int i = 0; i < budget.length; ++i ) budget[ i ] = 0; } public synchronized long timeLeft( final int level ) { return budget[ level ]; } public synchronized void use( final long t, final int level ) { int l = 0; for ( ; l <= level; ++l ) budget[ l ] -= t; for ( ; l < budget.length && budget[ l ] > budget[ l - 1 ]; ++l ) budget[ l ] = budget[ l - 1 ]; } } public static class IoStatistics { private final ConcurrentHashMap< Thread, StopWatch > perThreadStopWatches = new ConcurrentHashMap< Thread, StopWatch >(); private final StopWatch stopWatch; private int numRunningThreads; private long ioBytes; private IoTimeBudget ioTimeBudget; public IoStatistics() { stopWatch = new StopWatch(); ioBytes = 0; numRunningThreads = 0; ioTimeBudget = null; } public synchronized void start() { getThreadStopWatch().start(); if( numRunningThreads++ == 0 ) stopWatch.start(); } public synchronized void stop() { getThreadStopWatch().stop(); if( --numRunningThreads == 0 ) stopWatch.stop(); } public void incIoBytes( final long n ) { ioBytes += n; } public long getIoBytes() { return ioBytes; } public long getIoNanoTime() { return stopWatch.nanoTime(); } public long getCumulativeIoNanoTime() { long sum = 0; for ( final StopWatch w : perThreadStopWatches.values() ) sum += w.nanoTime(); return sum; } public IoTimeBudget getIoTimeBudget() { return ioTimeBudget; } public void setIoTimeBudget( final IoTimeBudget budget ) { ioTimeBudget = budget; } private StopWatch getThreadStopWatch() { final Thread thread = Thread.currentThread(); StopWatch w = perThreadStopWatches.get( thread ); if ( w == null ) { w = new StopWatch(); perThreadStopWatches.put( thread, w ); } return w; } } private final ConcurrentHashMap< ThreadGroup, IoStatistics > perThreadGroupIoStatistics = new ConcurrentHashMap< ThreadGroup, IoStatistics >(); public IoStatistics getThreadGroupIoStatistics() { final ThreadGroup threadGroup = Thread.currentThread().getThreadGroup(); IoStatistics statistics = perThreadGroupIoStatistics.get( threadGroup ); if ( statistics == null ) { statistics = new IoStatistics(); perThreadGroupIoStatistics.put( threadGroup, statistics ); } return statistics; } public long getThreadGroupIoNanoTime() { return getThreadGroupIoStatistics().getIoNanoTime(); } public long getThreadGroupIoBytes() { return getThreadGroupIoStatistics().getIoBytes(); } }
gelson-barros/Explica-o-apanhados-js
a3.js
console.log("2009" - "1995")//14
limeng32/mybatis.flying
src/test/java/indi/mybatis/flying/service2/TransactiveService3.java
package indi.mybatis.flying.service2; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import indi.mybatis.flying.exceptions.Configurer2Exception; import indi.mybatis.flying.service.TransactiveService; @Service public class TransactiveService3 { @Autowired private TransactiveService transactiveService; @Autowired private TransactiveService2 transactiveService2; @Transactional(rollbackFor = { Configurer2Exception.class }, readOnly = false, propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED) public void testTransactive() throws Configurer2Exception { transactiveService.addAccountTransactive2(); transactiveService2.addAccount2Transactive(); } }
CourtHive/competitionFactory
src/drawEngine/governors/scoreGovernor/keyValueScore/constants.js
export const SPACE_CHARACTER = ' '; export const OUTCOME_DEFAULT = 'DEF'; export const OUTCOME_COMPLETE = 'COMPLETED'; export const OUTCOME_WALKOVER = 'WO'; export const OUTCOME_DOUBLE_WALKOVER = 'WO/WO'; export const OUTCOME_ABANDONED = 'ABN'; export const OUTCOME_SUSPENDED = 'SUS'; export const OUTCOME_RETIREMENT = 'RET'; export const OUTCOME_INTERRUPTED = 'INT'; export const OUTCOMES = [ OUTCOME_RETIREMENT, OUTCOME_DEFAULT, OUTCOME_WALKOVER, OUTCOME_DOUBLE_WALKOVER, OUTCOME_ABANDONED, OUTCOME_SUSPENDED, OUTCOME_INTERRUPTED, ]; export const WINNING_OUTCOMES = [ OUTCOME_RETIREMENT, OUTCOME_DEFAULT, OUTCOME_WALKOVER, ]; export const STATUS_DEFAULT = 'DEFAULTED'; export const STATUS_COMPLETE = 'COMPLETED'; export const STATUS_WALKOVER = 'WALKOVER'; export const STATUS_DOUBLE_DEFAULT = 'DOUBLE_DEFAULT'; export const STATUS_DOUBLE_WALKOVER = 'DOUBLE_WALKOVER'; export const STATUS_ABANDONED = 'ABANDONED'; export const STATUS_SUSPENDED = 'SUSPENDED'; export const STATUS_RETIREMENT = 'RETIRED'; export const STATUS_INTERRUPTED = 'INTERRUPTED'; export const STATUSES = [ STATUS_RETIREMENT, STATUS_DEFAULT, STATUS_WALKOVER, STATUS_DOUBLE_DEFAULT, STATUS_DOUBLE_WALKOVER, STATUS_ABANDONED, STATUS_SUSPENDED, STATUS_INTERRUPTED, ]; export const WINNING_STATUSES = [ STATUS_RETIREMENT, STATUS_DEFAULT, STATUS_WALKOVER, ]; export const PROMPT = 'Enter Score'; export const SET_TIEBREAK_BRACKETS = '()'; export const MATCH_TIEBREAK_BRACKETS = '[]'; export const MOVEUP = ['up', 'left', 'shift+tab']; export const MOVEDOWN = ['enter', 'down', 'tab', 'right']; export const BACKSPACE = 'backspace'; export const RETIRE = 'r'; export const SUSPEND = 's'; export const ABANDON = 'a'; export const DEFAULT = 'd'; export const WALKOVER = 'w'; export const INTERRUPT = 'i'; export const OUTCOMEKEYS = [ RETIRE, DEFAULT, WALKOVER, ABANDON, SUSPEND, INTERRUPT, ]; export const SPACE_KEY = 'space'; export const OPENERS = ['[', '(']; export const CLOSERS = [...MOVEUP, ...MOVEDOWN, SPACE_KEY, ']']; export const DASH = '-'; export const FORWARD_SLASH = '/'; export const SCORE_JOINER = DASH; export const MATCH_TIEBREAK_JOINER = DASH; export const ALTERNATE_JOINERS = [FORWARD_SLASH]; export const ZERO = 0; export const TEST = ['=', '+', 'num_1', 'num_2', 'shift+=', 'shift+-']; export const SIDE1KEYS = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ].concat(OUTCOMEKEYS); export const SIDE2KEYS = SIDE1KEYS.map((key) => `shift+${key}`); export const MODIFIERS = [SCORE_JOINER, BACKSPACE].concat( CLOSERS, ALTERNATE_JOINERS ); export const VALID_VALUE_KEYS = [SIDE1KEYS, SIDE2KEYS, MODIFIERS].join(','); export const HOTKEYS = [VALID_VALUE_KEYS, MOVEUP, MOVEDOWN, TEST].join(','); // for testing purposes; side keys overrepresented export const SCORE_TEST_KEYS = [].concat( ...SIDE1KEYS, ...SIDE1KEYS, ...MODIFIERS, ...SIDE1KEYS, ...SIDE1KEYS, ...SIDE1KEYS, ...SIDE1KEYS, ...SIDE1KEYS, ...SIDE1KEYS ); export const keyValueConstants = { SIDE1KEYS, SIDE2KEYS, MODIFIERS, PROMPT, MOVEUP, MOVEDOWN, HOTKEYS, };
arastoul/kairosdb-client
src/main/java/org/kairosdb/client/response/QueryResult.java
/* * Copyright 2013 Proofpoint 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.kairosdb.client.response; import com.google.common.base.MoreObjects; import com.google.gson.annotations.SerializedName; import java.util.List; /** * Resulting object from a Query. */ public class QueryResult { private List<Result> results; @SerializedName("sample_size") private long sampleSize; public QueryResult(List<Result> results, long sampleSize) { this.results = results; this.sampleSize = sampleSize; } public List<Result> getResults() { return results; } /** * Returns the number of data points returned by the query prior to aggregation. Aggregation by reduce the number * of data points actually returned. * * @return number of data points returned by the query */ public long getSampleSize() { return sampleSize; } public Result getFirstResultByGroup(GroupResult matchingGroup) { for (Result result : results) { if (result != null) { for (GroupResult groupResult : result.getGroupResults()) { if (matchingGroup.equals(groupResult)) return (result); } } } return null; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; QueryResult that = (QueryResult) o; if (sampleSize != that.sampleSize) return false; return results != null ? results.equals(that.results) : that.results == null; } @Override public int hashCode() { int result = results != null ? results.hashCode() : 0; result = 31 * result + (int) (sampleSize ^ (sampleSize >>> 32)); return result; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("results", results) .add("sampleSize", sampleSize) .toString(); } }
johanrydstrom/FluentLenium
fluentlenium-core/src/test/java/org/fluentlenium/integration/TakeSnapshotOnLabsTest.java
<filename>fluentlenium-core/src/test/java/org/fluentlenium/integration/TakeSnapshotOnLabsTest.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.fluentlenium.integration; import org.fluentlenium.integration.localtest.SauceLabsFluentCase; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; public class TakeSnapshotOnLabsTest extends SauceLabsFluentCase { @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void can_take_a_snapshot() throws IOException { goTo(DEFAULT_URL); String absolutePath = folder.newFile("fluentlenium.png").getAbsolutePath(); takeScreenShot(absolutePath); assertThat(new File(absolutePath)).exists(); } }
mbostler/zenful_attribution
db/migrate/20150623154221_create_attribution_days.rb
class CreateAttributionDays < ActiveRecord::Migration[5.1] def change create_table :attribution_days do |t| t.integer :portfolio_id t.date :date t.float :performance t.timestamps null: false end end end
beyzanurkarakaya/Java-Programming
Lab-Lessons/Week7/Employee3/CommissionEmployee.java
// CommissionEmployee class uses methods to manipulate its // private instance variables. public class CommissionEmployee { private final String firstName; private final String lastName; private final String socialSecurityNumber; private double grossSales; // gross weekly sales private double commissionRate; // commission percentage // five-argument constructor public CommissionEmployee(String firstName, String lastName, String socialSecurityNumber, double grossSales, double commissionRate) { // implicit call to Object constructor occurs here // if grossSales is invalid throw exception if (grossSales < 0.0) { throw new IllegalArgumentException("Gross sales must be >= 0.0"); } // if commissionRate is invalid throw exception if (commissionRate <= 0.0 || commissionRate >= 1.0) { throw new IllegalArgumentException( "Commission rate must be > 0.0 and < 1.0"); } this.firstName = firstName; this.lastName = lastName; this.socialSecurityNumber = socialSecurityNumber; this.grossSales = grossSales; this.commissionRate = commissionRate; } // return first name public String getFirstName() {return firstName;} // return last name public String getLastName() {return lastName;} // return social security number public String getSocialSecurityNumber() {return socialSecurityNumber;} // set gross sales amount public void setGrossSales(double grossSales) { if (grossSales < 0.0) { throw new IllegalArgumentException("Gross sales must be >= 0.0"); } this.grossSales = grossSales; } // return gross sales amount public double getGrossSales() {return grossSales;} // set commission rate public void setCommissionRate(double commissionRate) { if (commissionRate <= 0.0 || commissionRate >= 1.0) { throw new IllegalArgumentException( "Commission rate must be > 0.0 and < 1.0"); } this.commissionRate = commissionRate; } // return commission rate public double getCommissionRate() {return commissionRate;} // calculate earnings public double earnings() { return getCommissionRate() * getGrossSales(); } // return String representation of CommissionEmployee object @Override public String toString() { return String.format("%s: %s %s%n%s: %s%n%s: %.2f%n%s: %.2f", "commission employee", getFirstName(), getLastName(), "social security number", getSocialSecurityNumber(), "gross sales", getGrossSales(), "commission rate", getCommissionRate()); } }
ajs6f/stanbol
ontologymanager/ontonet/src/main/java/org/apache/stanbol/ontologymanager/ontonet/api/ONManager.java
<gh_stars>0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.stanbol.ontologymanager.ontonet.api; import java.io.File; import org.apache.stanbol.commons.owl.OWLOntologyManagerFactory; import org.apache.stanbol.ontologymanager.ontonet.api.ontology.OntologyProvider; import org.apache.stanbol.ontologymanager.ontonet.api.scope.OntologyScopeFactory; import org.apache.stanbol.ontologymanager.ontonet.api.scope.OntologySpaceFactory; import org.apache.stanbol.ontologymanager.ontonet.api.scope.ScopeRegistry; import org.apache.stanbol.ontologymanager.ontonet.api.session.SessionManager; import org.apache.stanbol.ontologymanager.ontonet.impl.session.SessionManagerImpl; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLOntologyAlreadyExistsException; import org.semanticweb.owlapi.model.OWLOntologyManager; /** * An Ontology Network Manager holds all references and tools for creating, modifying and deleting the logical * realms that store Web Ontologies, as well as offer facilities for handling the ontologies contained * therein. * * @author alexdma, anuzzolese * */ public interface ONManager { /** * The key used to configure the path of the ontology network configuration. */ String CONFIG_ONTOLOGY_PATH = "org.apache.stanbol.ontologymanager.ontonet.onconfig"; /** * The key used to configure the ID of the ontology network manager. */ String ID = "org.apache.stanbol.ontologymanager.ontonet.id"; /** * The key used to configure the simple identifier of the scope registry (which should also be * concatenated with the base namespace to obtain the registry's HTTP endpoint URI). */ String ID_SCOPE_REGISTRY = "org.apache.stanbol.ontologymanager.ontonet.scopeRegistry.id"; /** * The key used to configure the base namespace of the ontology network. */ String ONTOLOGY_NETWORK_NS = "org.apache.stanbol.ontologymanager.ontonet.ns"; /** * Returns the offline configuration set for this ontology network manager, if any. * * @return the offline configuration, or null if none was set. */ OfflineConfiguration getOfflineConfiguration(); /** * Implementations should be able to create a {@link File} object from this path. * * @return the local path of the ontology storing the ontology network configuration. */ String getOntologyNetworkConfigurationPath(); /** * Returns the base namespace to be used for the Stanbol ontology network (e.g. for the creation of new * scopes). For convenience, it is returned as a string so that it can be concatenated to form IRIs. * * @return the base namespace of the Stanbol ontology network. */ String getOntologyNetworkNamespace(); /** * Returns the ontology scope factory that was created along with the manager context. * * @return the default ontology scope factory */ OntologyScopeFactory getOntologyScopeFactory(); /** * Returns the ontology space factory that was created along with the manager context. * * @return the default ontology space factory. */ OntologySpaceFactory getOntologySpaceFactory(); /** * Returns an OWL Ontology Manager that is never cleared of its ontologies, so it can be used for caching * ontologies without having to reload them using other managers. It is sufficient to catch * {@link OWLOntologyAlreadyExistsException}s and obtain the ontology with that same ID from this manager. * * @deprecated the ONManager will soon stop providing a cache manager, as it will gradually be replaced by * {@link OntologyProvider}. Implementations that need to use an OWLOntologyManager which * avoids reloading stored ontologies can either call {@link OntologyProvider#getStore()} on * an {@link OWLOntologyManager}-based implementation, or create a new one by calling * {@link OWLOntologyManagerFactory#createOWLOntologyManager(IRI[])} or OWL API methods. * @return the OWL Ontology Manager used for caching ontologies. */ OWLOntologyManager getOwlCacheManager(); /** * Returns the unique ontology scope registry for this context. * * @return the ontology scope registry. */ ScopeRegistry getScopeRegistry(); /** * Returns the unique session manager for this context. * * @deprecated {@link SessionManager} is now a standalone component and should be accessed independently * from the ONManager (e.g. by instantiating a new {@link SessionManagerImpl} or by * referencing {@link SessionManager} in OSGi components). * * @return the session manager. */ SessionManager getSessionManager(); /** * Returns the list of IRIs that identify scopes that should be activated on startup, <i>if they * exist</i>. * * @return the list of scope IDs to activate. */ String[] getUrisToActivate(); }
LZ0211/eReader
node_modules/Wedge-eBooks/lib/txtz/index.js
var Zip = require('../zip'); var txt = require('../txt'); function encode(str){ return str.split('').map(char=>`&#${char.charCodeAt(0)};`).join('') } function leftPad(str,padding,length){ str = '' + str; if (str.length >= length){ return str; } for (var i=str.length;i<length;i++){ str = padding + str; } return str; } function formatTime(date,template){ var time = new Date(date) var day = template || "yyyy-MM-dd hh:mm:ss"; day = day.replace(/(y+)/,function ($,$1){ return leftPad(time.getFullYear(),0,$1.length) }); day = day.replace(/(M+)/,function ($,$1){ return leftPad(time.getMonth() + 1,0,$1.length) }); day = day.replace(/(d+)/,function ($,$1){ return leftPad(time.getDate(),0,$1.length) }); day = day.replace(/(h+)/,function ($,$1){ return leftPad(time.getHours(),0,$1.length) }); day = day.replace(/(m+)/,function ($,$1){ return leftPad(time.getMinutes(),0,$1.length) }); day = day.replace(/(s+)/,function ($,$1){ return leftPad(time.getSeconds(),0,$1.length) }); return day; } function metadata(book){ return `<metadata> <dc-metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:oebpackage="http://openebook.org/namespaces/oeb-package/1.0/"> <dc:Title>${encode(book.meta.title)}</dc:Title> <dc:Language>zh</dc:Language> <dc:Description>${encode(book.meta.brief)}</dc:Description> <dc:Publisher>Wedge</dc:Publisher> <dc:Creator file-as="${encode(book.meta.author)}" role="aut">${encode(book.meta.author)}</dc:Creator> <dc:Subject>${encode(book.meta.classes)}</dc:Subject> <dc:Date>${formatTime(new Date(),'yyyy-MM-ddThh:mm:ss+00:00')}</dc:Date> <dc:Identifier id="uuid_id" scheme="uuid">${book.meta.uuid}</dc:Identifier> </dc-metadata> <x-metadata> <meta name="cover" content="cover"/> <meta name="ms-chaptertour" content="chaptertour"/> </x-metadata> </metadata>` } module.exports = function (book,fn){ txt(book,function(text){ var ebk = new Zip(); ebk.writeFile("cover.jpeg", Buffer.from(book.meta.cover, 'base64'), true); ebk.writeFile("metadata.opf", metadata(book), true); ebk.writeFile("index.txt", text, true); fn(ebk.generate()); }); }
vladn-ma/vladn-ovs-doc
doxygen/ovs_all/html/search/pages_b.js
var searchData= [ ['why_20open_20vswitch_3f',['Why Open vSwitch?',['../md__home_vladn_git_ovs_WHY-OVS.html',1,'']]] ];
nishanttotla/cpachecker-crowdprover
src/org/sosy_lab/cpachecker/cpa/seplogic/SeplogicTransferRelation.java
<gh_stars>0 /* * CPAchecker is a tool for configurable software verification. * This file is part of CPAchecker. * * Copyright (C) 2007-2014 <NAME> * 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. * * * CPAchecker web page: * http://cpachecker.sosy-lab.org */ package org.sosy_lab.cpachecker.cpa.seplogic; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.logging.Level; import org.sosy_lab.common.log.LogManager; import org.sosy_lab.cpachecker.cfa.ast.c.CAssignment; import org.sosy_lab.cpachecker.cfa.ast.c.CBinaryExpression; import org.sosy_lab.cpachecker.cfa.ast.c.CBinaryExpression.BinaryOperator; import org.sosy_lab.cpachecker.cfa.ast.c.CCastExpression; import org.sosy_lab.cpachecker.cfa.ast.c.CExpression; import org.sosy_lab.cpachecker.cfa.ast.c.CFunctionCall; import org.sosy_lab.cpachecker.cfa.ast.c.CFunctionCallAssignmentStatement; import org.sosy_lab.cpachecker.cfa.ast.c.CFunctionCallExpression; import org.sosy_lab.cpachecker.cfa.ast.c.CFunctionCallStatement; import org.sosy_lab.cpachecker.cfa.ast.c.CIdExpression; import org.sosy_lab.cpachecker.cfa.ast.c.CIntegerLiteralExpression; import org.sosy_lab.cpachecker.cfa.ast.c.CLiteralExpression; import org.sosy_lab.cpachecker.cfa.ast.c.CPointerExpression; import org.sosy_lab.cpachecker.cfa.ast.c.CRightHandSide; import org.sosy_lab.cpachecker.cfa.ast.c.CStatement; import org.sosy_lab.cpachecker.cfa.ast.c.CStringLiteralExpression; import org.sosy_lab.cpachecker.cfa.ast.c.CUnaryExpression; import org.sosy_lab.cpachecker.cfa.ast.c.CUnaryExpression.UnaryOperator; import org.sosy_lab.cpachecker.cfa.model.AssumeEdge; import org.sosy_lab.cpachecker.cfa.model.CFAEdge; import org.sosy_lab.cpachecker.cfa.model.FunctionReturnEdge; import org.sosy_lab.cpachecker.cfa.model.FunctionSummaryEdge; import org.sosy_lab.cpachecker.cfa.model.c.CDeclarationEdge; import org.sosy_lab.cpachecker.cfa.model.c.CFunctionCallEdge; import org.sosy_lab.cpachecker.cfa.model.c.CFunctionEntryNode; import org.sosy_lab.cpachecker.cfa.model.c.CReturnStatementEdge; import org.sosy_lab.cpachecker.cfa.model.c.CStatementEdge; import org.sosy_lab.cpachecker.cfa.types.c.CCompositeType; import org.sosy_lab.cpachecker.cfa.types.c.CElaboratedType; import org.sosy_lab.cpachecker.cfa.types.c.CEnumType; import org.sosy_lab.cpachecker.cfa.types.c.CFunctionType; import org.sosy_lab.cpachecker.cfa.types.c.CType; import org.sosy_lab.cpachecker.core.defaults.SingleEdgeTransferRelation; import org.sosy_lab.cpachecker.core.interfaces.AbstractState; import org.sosy_lab.cpachecker.core.interfaces.Precision; import org.sosy_lab.cpachecker.cpa.seplogic.SeplogicState.SeplogicQueryUnsuccessful; import org.sosy_lab.cpachecker.cpa.seplogic.interfaces.Handle; import org.sosy_lab.cpachecker.cpa.seplogic.interfaces.PartingstarInterface; import org.sosy_lab.cpachecker.exceptions.CPATransferException; import org.sosy_lab.cpachecker.exceptions.UnrecognizedCCodeException; import org.sosy_lab.cpachecker.exceptions.UnrecognizedCFAEdgeException; import com.google.common.base.Optional; public class SeplogicTransferRelation extends SingleEdgeTransferRelation { boolean entryFunctionProcessed = false; long existentialVarIndex = 0; private long namespaceCounter = 0; private PartingstarInterface psInterface; static final String RETVAR = "$RET"; private final LogManager logger; public SeplogicTransferRelation(SeplogicCPA cpa, LogManager pLogger) { super(); psInterface = cpa.getPartingstarInterface(); logger = pLogger; } private Handle makeFreshExistential() { return psInterface.makeVar(psInterface.loadString("_v" + existentialVarIndex++)); } @Override public Collection<SeplogicState> getAbstractSuccessorsForEdge( AbstractState element, Precision precision, CFAEdge cfaEdge) throws CPATransferException { SeplogicState currentElement = (SeplogicState) element; SeplogicState successor; try { switch (cfaEdge.getEdgeType()) { case DeclarationEdge: CDeclarationEdge declEdge = (CDeclarationEdge) cfaEdge; successor = handleDeclaration(currentElement, cfaEdge, declEdge.getDeclaration().getName(), declEdge.getDeclaration().getType()); break; case StatementEdge: successor = handleStatement(currentElement, ((CStatementEdge) cfaEdge).getStatement(), (CStatementEdge) cfaEdge); break; case ReturnStatementEdge: Optional<CExpression> expression = ((CReturnStatementEdge) cfaEdge).getExpression(); if (expression.isPresent()) { // non-void function successor = handleAssignment(currentElement, RETVAR, false, expression.get(), cfaEdge); } else { successor = currentElement; } break; case AssumeEdge: AssumeEdge assumeEdge = (AssumeEdge) cfaEdge; successor = handleAssume(currentElement, (CExpression) assumeEdge.getExpression(), assumeEdge.getTruthAssumption(), assumeEdge); break; case FunctionCallEdge: successor = handleFunctionCall(currentElement, cfaEdge); break; case FunctionReturnEdge: // now handle the complete a = func(x) statement in the CallToReturnEdge FunctionReturnEdge returnEdge = (FunctionReturnEdge) cfaEdge; FunctionSummaryEdge ctrEdge = returnEdge.getSuccessor().getEnteringSummaryEdge(); successor = handleReturnFromFunction(currentElement, (CFunctionCall) ctrEdge.getExpression(), ctrEdge); break; case BlankEdge: //the first function start dummy edge is the actual start of the entry function // XXX code? successor = currentElement; break; default: throw new UnrecognizedCFAEdgeException(cfaEdge); } } catch (SeplogicQueryUnsuccessful e) { if (e.isPureGuard() != null && e.isPureGuard().booleanValue()) { logger.logUserException(Level.WARNING, e, "Pure guard failed (-> false) in CFA Edge: N" + cfaEdge.getPredecessor().getNodeNumber() + " -> N" + cfaEdge.getSuccessor().getNodeNumber()); return Collections.emptySet(); //return Collections.singleton(currentElement.makeExceptionState(e)); } else { logger.logUserException(Level.WARNING, e, "Must be a null-dereference in CFA Edge: N" + cfaEdge.getPredecessor().getNodeNumber() + " -> N" + cfaEdge.getSuccessor().getNodeNumber()); return Collections.singleton(currentElement.makeExceptionState(e)); } //throw e; } if (successor.isFalse()) { logger.log(Level.WARNING, "Successor implies false in CFA Edge: N" + cfaEdge.getPredecessor().getNodeNumber() + " -> N" + cfaEdge.getSuccessor().getNodeNumber()); return Collections.emptySet(); } // XXX a bit too arbitrary if (!successor.doBreak() && (cfaEdge.getSuccessor().isLoopStart() || true)) { successor = successor.abstract_(); } return Collections.singleton(successor); } private SeplogicState handleDeclaration(SeplogicState element, CFAEdge edge, String name, CType specifier) throws CPATransferException { if (name == null && (specifier instanceof CElaboratedType || specifier instanceof CCompositeType)) { // ignore struct prototypes return element; } if (name == null) { throw new UnrecognizedCCodeException("not expected in CIL", edge); } if (specifier instanceof CFunctionType) { return element; } if (specifier instanceof CCompositeType || specifier instanceof CElaboratedType || specifier instanceof CEnumType) { // structs on stack etc. return element; } return element; //XXX wrong // throw new UnrecognizedCCodeException("unsupported", edge); /* XXX fill String varName = name; if (specifier instanceof IASTArrayTypeSpecifier) { Pointer p = new Pointer(1); element.addNewLocalPointer(varName, p); IType nestedSpecifier = ((IASTArrayTypeSpecifier)specifier).getType(); if (!(nestedSpecifier instanceof IASTSimpleDeclSpecifier)) { throw new UnrecognizedCCodeException("unsupported array declaration", edge); } IASTExpression lengthExpression = ((IASTArrayTypeSpecifier)specifier).getLength(); if (!(lengthExpression instanceof IASTLiteralExpression)) { throw new UnrecognizedCCodeException("variable sized stack arrays are not supported", edge); } long length = parseIntegerLiteral((IASTLiteralExpression)lengthExpression, edge); StackArrayCell array = new StackArrayCell(element.getCurrentFunctionName(), new StackArray(varName, length)); element.pointerOp(new Pointer.Assign(array), p); // store the pointer so the type analysis CPA can update its // type information missing = new MissingInformation(); missing.typeInformationPointer = p; missing.typeInformationEdge = edge; missing.typeInformationName = name; } else if (specifier instanceof IASTPointerTypeSpecifier) { int depth = 0; IType nestedSpecifier = specifier; do { nestedSpecifier = ((IASTPointerTypeSpecifier)nestedSpecifier).getType(); depth++; } while (nestedSpecifier instanceof IASTPointerTypeSpecifier); if (nestedSpecifier instanceof IASTElaboratedTypeSpecifier) { // declaration of pointer to struct Pointer ptr = new Pointer(depth); if (edge instanceof GlobalDeclarationEdge) { element.addNewGlobalPointer(varName, ptr); element.pointerOp(new Pointer.Assign(Memory.UNINITIALIZED_POINTER), ptr); } else { // edge is instance of LocalDeclarationEdge element.addNewLocalPointer(varName, ptr); if (entryFunctionProcessed) { element.pointerOp( new Pointer.Assign(Memory.UNINITIALIZED_POINTER), ptr); } else { // ptr is a function parameter element.pointerOp( new Pointer.Assign(Memory.UNKNOWN_POINTER), ptr); } } missing = new MissingInformation(); missing.typeInformationPointer = ptr; missing.typeInformationEdge = edge; missing.typeInformationName = name; } else { Pointer p = new Pointer(depth); if (edge instanceof GlobalDeclarationEdge) { element.addNewGlobalPointer(varName, p); element.pointerOp(new Pointer.Assign(Memory.UNINITIALIZED_POINTER), p); } else { element.addNewLocalPointer(varName, p); //if the entryFunction has not yet been processed, this means this pointer is a parameter //and should be considered unknown rather than uninitialized PointerTarget pTarg = (!entryFunctionProcessed ? Memory.UNKNOWN_POINTER : Memory.UNINITIALIZED_POINTER); element.pointerOp(new Pointer.Assign(pTarg), p); } // store the pointer so the type analysis CPA can update its // type information missing = new MissingInformation(); missing.typeInformationPointer = p; missing.typeInformationEdge = edge; missing.typeInformationName = name; // initializers do not need to be considered, because they have to be // constant and constant pointers are considered null // local variables do not have initializers in CIL } } else { if (edge instanceof GlobalDeclarationEdge) { element.addNewGlobalPointer(varName, null); } else { element.addNewLocalPointer(varName, null); } } */ } private SeplogicState handleAssume(SeplogicState element, CExpression expression, boolean isTrueBranch, AssumeEdge assumeEdge) throws UnrecognizedCCodeException, SeplogicQueryUnsuccessful { Handle a1, a2; if (expression instanceof CBinaryExpression) { CBinaryExpression binaryExpression = (CBinaryExpression) expression; if (binaryExpression.getOperator() == BinaryOperator.EQUALS) { return handleBinaryAssume(element, binaryExpression, isTrueBranch, assumeEdge); } else if (binaryExpression.getOperator() == BinaryOperator.NOT_EQUALS) { return handleBinaryAssume(element, binaryExpression, !isTrueBranch, assumeEdge); } else { // assume it's not a pointer comparison return element; } } else if (expression instanceof CUnaryExpression) { throw new UnrecognizedCCodeException("not expected in CIL", assumeEdge, expression); } else if (expression instanceof CIdExpression) { // if (a) String varName = ((CIdExpression) expression).getName(); a1 = makeVarArg(varName, element); a2 = makeIntegerConstant(0); } else if (expression instanceof CCastExpression) { return handleAssume(element, ((CCastExpression) expression).getOperand(), isTrueBranch, assumeEdge); } else if (expression instanceof CPointerExpression) { // if (*var) String varName = expression.toASTString(); if (!isTrueBranch) { return element; } a1 = makeVarArg(varName, element); a2 = makeIntegerConstant(0); isTrueBranch = !isTrueBranch; } else { throw new UnrecognizedCCodeException("unsupported", assumeEdge); } Handle f; if (isTrueBranch) { f = psInterface.makeEq(a1, a2); } else { f = psInterface.makeIneq(a1, a2); } try { return element.performSpecificationAssignment(psInterface.makeEmp(), f, null); } catch (SeplogicQueryUnsuccessful e) { e.setIsPureGuard(true); throw e; } } private String quoteVar(String varName, SeplogicState element) { return quoteVar(varName, element.getNamespace()); } private String quoteVar(String varName, String localNamespace) { varName = localNamespace + "$" + varName; return (varName.charAt(0) == '_') ? ("ZZZ" + varName) : varName; } private Handle makeVarArg(String varName, SeplogicState element) { return makeVarArg(varName, element.getNamespace()); } private Handle makeVarArg(String varName, String localNamespace) { return psInterface.makeVar(psInterface.loadString(quoteVar(varName, localNamespace))); } private SeplogicState handleBinaryAssume(SeplogicState element, CBinaryExpression expression, boolean isTrueBranch, AssumeEdge assumeEdge) throws UnrecognizedCCodeException, SeplogicQueryUnsuccessful { CExpression leftOp = expression.getOperand1(); CExpression rightOp = expression.getOperand2(); Handle f; Handle a1 = convertOperandToArgument(leftOp, element); Handle a2 = convertOperandToArgument(rightOp, element); if (isTrueBranch) { f = psInterface.makeEq(a1, a2); } else { f = psInterface.makeIneq(a1, a2); } try { return element.performSpecificationAssignment(psInterface.makeEmp(), f, null); } catch (SeplogicQueryUnsuccessful e) { e.setIsPureGuard(true); throw e; } } private Handle convertOperandToArgument(CExpression pLeftOp, SeplogicState element) throws UnrecognizedCCodeException { if (pLeftOp instanceof CIntegerLiteralExpression) { return makeIntegerConstant(((CIntegerLiteralExpression) pLeftOp).getValue().longValue()); } else if (pLeftOp instanceof CIdExpression) { return makeVarArg(pLeftOp.toASTString(), element); } else { throw new UnrecognizedCCodeException("unsupported expression type", null, pLeftOp); } } private SeplogicState handleFunctionCall(SeplogicState element, CFAEdge cfaEdge) throws UnrecognizedCCodeException { CFunctionEntryNode funcDefNode = (CFunctionEntryNode) cfaEdge.getSuccessor(); String funcName = funcDefNode.getFunctionName(); String nsName = funcName + namespaceCounter++; List<String> formalParameters = funcDefNode.getFunctionParameterNames(); List<CExpression> actualParameters = ((CFunctionCallEdge) cfaEdge).getArguments(); if (formalParameters != null && formalParameters.size() > 0 && !actualParameters.isEmpty()) { assert formalParameters.size() == actualParameters.size(); for (int i = 0; i < actualParameters.size(); i++) { CExpression parameter = actualParameters.get(i); String formalParameter = formalParameters.get(i); element = handleAssignment(element, formalParameter, false, parameter, cfaEdge, nsName); /* if (parameter instanceof IASTIdExpression) { String paramName = ((IASTIdExpression)parameter).getName(); } else if (parameter instanceof IASTLiteralExpression) { IASTLiteralExpression literal = (IASTLiteralExpression)parameter; if (literal instanceof IASTIntegerLiteralExpression) { long value = ((IASTIntegerLiteralExpression) literal).asLong(); if (value == 0) { } } } else if (parameter instanceof IASTUnaryExpression) { IASTUnaryExpression unaryExpression = (IASTUnaryExpression)parameter; if (unaryExpression.getOperator() == UnaryOperator.AMPER && unaryExpression.getOperand() instanceof IASTIdExpression) { String varName = unaryExpression.getOperand().toASTString(); Variable var = element.lookupVariable(varName); actualValues.add(new Pointer(var)); } else { throw new UnrecognizedCCodeException("not expected in CIL", cfaEdge, unaryExpression); } } else { throw new UnrecognizedCCodeException("not expected in CIL", cfaEdge, parameter); } */ } } return element.pushNamespace(nsName); } private SeplogicState handleReturnFromFunction(SeplogicState element, CFunctionCall expression, CFAEdge cfaEdge) throws UnrecognizedCCodeException { element = element.popNamespace(); // use function result if (expression instanceof CFunctionCallAssignmentStatement) { // a = func() CFunctionCallAssignmentStatement assignExpression = (CFunctionCallAssignmentStatement) expression; CExpression leftOperand = assignExpression.getLeftHandSide(); if (leftOperand instanceof CIdExpression) { throw new UnrecognizedCCodeException("unsupported", cfaEdge); /* XXX fill Pointer leftPointer = element.lookupPointer(((IASTIdExpression)leftOperand).getName()); if (leftPointer != null) { if (resultPointer != null) { // do not use Assign(resultPointer) here, as this would try to make // resultPointer an alias of leftPointer element.pointerOp(new Pointer.AssignListOfTargets(resultPointer .getTargets()), leftPointer); } else { throw new UnrecognizedCCodeException( "assigning non-pointer value to pointer variable", cfaEdge, assignExpression); } } else { // function result is not assigned to a pointer, ignore } */ } else { // *x = func() etc. throw new UnrecognizedCCodeException("not expected in CIL", cfaEdge, assignExpression); } } else if (expression instanceof CFunctionCallStatement) { // func() // ignore return element; } else { throw new UnrecognizedCCodeException("Unrecognized", cfaEdge); } } private SeplogicState handleStatement(SeplogicState element, CStatement expression, CStatementEdge cfaEdge) throws UnrecognizedCCodeException, SeplogicQueryUnsuccessful { if (expression instanceof CFunctionCallStatement) { // this is a mere function call (func(a)) CFunctionCallExpression funcExpression = ((CFunctionCallStatement) expression).getFunctionCallExpression(); String functionName = funcExpression.getFunctionNameExpression().toASTString(); if (functionName.equals("free")) { return handleFree(element, funcExpression, cfaEdge); } else if (functionName.equals("malloc")) { // malloc without assignment (will lead to memory leak) return element; // XXX .performSpecificationAssignment(new Empty(), makePointsTo(new OpArgument("nil", new ArrayList<Argument>()), makeFreshExistential()), null); } else { return element; // XXX correct? } } else if (expression instanceof CAssignment) { // statement is an assignment expression, e.g. a = b or a = a+b; return handleAssignmentStatement(element, (CAssignment) expression, cfaEdge); } else { throw new UnrecognizedCCodeException(expression.toASTString(), cfaEdge); } } private SeplogicState handleFree(SeplogicState element, CFunctionCallExpression expression, CFAEdge cfaEdge) throws UnrecognizedCCodeException, SeplogicQueryUnsuccessful { List<CExpression> parameters = expression.getParameterExpressions(); if (parameters.size() != 1) { throw new UnrecognizedCCodeException("Wrong number of arguments for free", cfaEdge, expression); } CExpression parameter = parameters.get(0); if (parameter instanceof CIdExpression) { String ident = ((CIdExpression) parameter).getName(); return element.performSpecificationAssignment(makePointsTo(makeVarArg(ident, element), makeFreshExistential()), psInterface.makeEmp(), null); } else { throw new UnrecognizedCCodeException("not expected in CIL", cfaEdge, parameter); } } private Handle makePointsTo(Handle pA1, Handle pA2) { return psInterface.makeSpatialPredicate(psInterface.loadString("NodeLL"), pA1, pA2); } private SeplogicState handleAssignmentStatement(SeplogicState element, CAssignment expression, CFAEdge cfaEdge) throws UnrecognizedCCodeException, SeplogicQueryUnsuccessful { // left hand side CExpression leftExpression = expression.getLeftHandSide(); String leftVarName = null; boolean leftDereference; if (leftExpression instanceof CIdExpression) { // a leftDereference = false; leftVarName = ((CIdExpression) leftExpression).getName(); } else if (leftExpression instanceof CPointerExpression) { // *a CPointerExpression ptrExpression = (CPointerExpression)leftExpression; leftDereference = true; leftExpression = ptrExpression.getOperand(); if (leftExpression instanceof CCastExpression) { leftExpression = ((CCastExpression) leftExpression).getOperand(); } if (!(leftExpression instanceof CIdExpression)) { // not a variable at left hand side throw new UnrecognizedCCodeException("not expected in CIL", cfaEdge, leftExpression); } leftVarName = leftExpression.toASTString(); } else { // TODO fields, arrays throw new UnrecognizedCCodeException("not expected in CIL", cfaEdge, leftExpression); } // right hand side CRightHandSide op2 = expression.getRightHandSide(); // handles *a = x and a = x return handleAssignment(element, leftVarName, leftDereference, op2, cfaEdge); } private SeplogicState handleAssignment(SeplogicState element, String leftVarName, boolean leftDereference, CRightHandSide expression, CFAEdge cfaEdge) throws UnrecognizedCCodeException, SeplogicQueryUnsuccessful { return handleAssignment(element, leftVarName, leftDereference, expression, cfaEdge, element.getNamespace()); } private SeplogicState handleAssignment(SeplogicState element, String leftVarName, boolean leftDereference, CRightHandSide expression, CFAEdge cfaEdge, String leftNamespace) throws UnrecognizedCCodeException, SeplogicQueryUnsuccessful { Handle fPre, fPost; String sVarName = null; boolean isPureGuard = false; if (expression instanceof CStringLiteralExpression) { // char* s = "hello world" if (leftDereference) { throw new UnrecognizedCCodeException("not expected in CIL", cfaEdge, expression); } fPre = psInterface.makeEmp(); fPost = psInterface.makeEq(psInterface.makeVar(psInterface.loadString(RETVAR)), makeFreshExistential()); // XXX wrong sVarName = leftVarName; isPureGuard = true; } else if (expression instanceof CLiteralExpression) { // a = INT if (!(expression instanceof CIntegerLiteralExpression)) { throw new UnrecognizedCCodeException( "unsupported literal", cfaEdge, expression); } long value = ((CIntegerLiteralExpression) expression).getValue().longValue(); Handle rhsArg; rhsArg = makeIntegerConstant(value); if (leftDereference) { fPre = makePointsTo(makeVarArg(leftVarName, leftNamespace), makeFreshExistential()); fPost = makePointsTo(makeVarArg(leftVarName, leftNamespace), rhsArg); } else { fPre = psInterface.makeEmp(); fPost = psInterface.makeEq(psInterface.makeVar(psInterface.loadString(RETVAR)), rhsArg); sVarName = leftVarName; isPureGuard = true; } } else if (expression instanceof CCastExpression) { // a = (int*)b CExpression operand = ((CCastExpression) expression).getOperand(); Handle rhsArg; if ("0".equals(operand.toASTString())) { rhsArg = psInterface.makeNil(); } else { rhsArg = makeVarArg(operand.toASTString(), element); } if (leftDereference) { fPre = makePointsTo(makeVarArg(leftVarName, leftNamespace), makeFreshExistential()); fPost = makePointsTo(makeVarArg(leftVarName, leftNamespace), rhsArg); } else { fPre = psInterface.makeEmp(); fPost = psInterface.makeEq(psInterface.makeVar(psInterface.loadString(RETVAR)), rhsArg); sVarName = leftVarName; isPureGuard = true; } } else if (expression instanceof CFunctionCallExpression) { // a = func() CFunctionCallExpression funcExpression = (CFunctionCallExpression) expression; String functionName = funcExpression.getFunctionNameExpression().toASTString(); if (functionName.equals("malloc")) { return handleMalloc(element, leftVarName, leftDereference, funcExpression, cfaEdge); } else { // if it's an internal call, it's handled in handleReturnFromFunction() // it it's an external call and we do not know the function, we cannot // do more than set the pointer to unknown fPre = psInterface.makeEmp(); fPost = psInterface.makeEq(psInterface.makeVar(psInterface.loadString(RETVAR)), makeFreshExistential()); sVarName = leftVarName; } } else if (expression instanceof CBinaryExpression) { // a = b + c CBinaryExpression binExpression = (CBinaryExpression) expression; BinaryOperator typeOfOperator = binExpression.getOperator(); CExpression op1 = binExpression.getOperand1(); CExpression op2 = binExpression.getOperand2(); if (op1 instanceof CCastExpression) { op1 = ((CCastExpression) op1).getOperand(); } if (op1 instanceof CIdExpression) { String rightName = ((CIdExpression) op1).getName(); if (!(typeOfOperator == BinaryOperator.PLUS || typeOfOperator == BinaryOperator.MINUS)) { throw new UnrecognizedCCodeException(binExpression.toASTString(), cfaEdge); } if (op2 instanceof CLiteralExpression) { long offset = ((CIntegerLiteralExpression) op2).asLong(); if (typeOfOperator == BinaryOperator.MINUS) { offset = -offset; } fPre = psInterface.makeEmp(); fPost = psInterface.makeEq(psInterface.makeVar(psInterface.loadString(RETVAR)), psInterface.makePlus(makeVarArg(rightName, element), makeIntegerConstant(offset))); sVarName = leftVarName; isPureGuard = true; } else if (op2 instanceof CIdExpression) { throw new UnrecognizedCCodeException("unsupported variable addition", cfaEdge, op2); /* XXX fill missing = new MissingInformation(); missing.actionLeftPointer = leftPointer; missing.actionRightPointer = rightPointer; missing.actionDereferenceFirst = leftDereference; missing.actionOffsetNegative = (typeOfOperator == BinaryOperator.MINUS); missing.actionASTNode = op2; */ } else { throw new UnrecognizedCCodeException("not expected in CIL", cfaEdge, op2); } } else { throw new UnrecognizedCCodeException("unsupported", cfaEdge, expression); } /* XXX fill } else if (op1 instanceof IASTLiteralExpression) { if (leftPointer == null) { return; } if (op2 instanceof IASTLiteralExpression) { addWarning("Assigning non-pointer value " + binExpression.toASTString() + " to pointer " + leftPointer.getLocation(), cfaEdge, binExpression .toASTString()); element.pointerOp(new Pointer.Assign(Memory.UNKNOWN_POINTER), leftPointer, leftDereference); } else { throw new UnrecognizedCCodeException("not expected in CIL", cfaEdge, op2); } } else { throw new UnrecognizedCCodeException("not expected in CIL", cfaEdge, op1); } */ } else if (expression instanceof CUnaryExpression) { CUnaryExpression unaryExpression = (CUnaryExpression) expression; UnaryOperator op = unaryExpression.getOperator(); if (op == UnaryOperator.AMPER) { // a = &b // XXX correct?! Handle rhsArg = makeVarArg(unaryExpression.getOperand().toASTString(), element); if (leftDereference) { fPre = makePointsTo(makeVarArg(leftVarName, leftNamespace), makeFreshExistential()); fPost = makePointsTo(makeVarArg(leftVarName, leftNamespace), rhsArg); } else { fPre = psInterface.makeEmp(); fPost = psInterface.makeEq(psInterface.makeVar(psInterface.loadString(RETVAR)), rhsArg); sVarName = leftVarName; isPureGuard = true; } } else if (op == UnaryOperator.MINUS) { throw new UnrecognizedCCodeException("unsupported", cfaEdge, expression); } else { throw new UnrecognizedCCodeException("not expected in CIL", cfaEdge, unaryExpression); } } else if (expression instanceof CPointerExpression) { // a = *b CPointerExpression ptrExpression = (CPointerExpression) expression; expression = ptrExpression.getOperand(); if (expression instanceof CCastExpression) { expression = ((CCastExpression) expression).getOperand(); } if (!(expression instanceof CIdExpression)) { // not a variable at left hand side throw new UnrecognizedCCodeException("not expected in CIL", cfaEdge, expression); } if (leftDereference) { throw new UnrecognizedCCodeException("unsupported", cfaEdge, expression); } else { Handle rhsArg = makeFreshExistential(); fPre = makePointsTo(makeVarArg(expression.toASTString(), element), rhsArg); fPost = psInterface.makeStar(fPre, psInterface.makeEq(psInterface.makeVar(psInterface.loadString(RETVAR)), rhsArg)); sVarName = leftVarName; } } else if (expression instanceof CIdExpression) { // a = b String rightName = ((CIdExpression) expression).getName(); Handle lhsArg = makeVarArg(rightName, element); if (leftDereference) { fPre = makePointsTo(makeVarArg(leftVarName, leftNamespace), makeFreshExistential()); fPost = makePointsTo(makeVarArg(leftVarName, leftNamespace), lhsArg); } else { fPre = psInterface.makeEmp(); fPost = psInterface.makeEq(psInterface.makeVar(psInterface.loadString(RETVAR)), lhsArg); sVarName = leftVarName; isPureGuard = true; } } else { throw new UnrecognizedCCodeException("not expected in CIL", cfaEdge, expression); } try { return element.performSpecificationAssignment(fPre, fPost, (sVarName == null) ? null : quoteVar(sVarName, leftNamespace)); } catch (SeplogicQueryUnsuccessful e) { e.setIsPureGuard(isPureGuard); throw e; } } private SeplogicState handleMalloc(SeplogicState element, String pLeftVarName, boolean leftDereference, CFunctionCallExpression expression, CFAEdge cfaEdge) throws UnrecognizedCCodeException, SeplogicQueryUnsuccessful { List<CExpression> parameters = expression.getParameterExpressions(); if (parameters.size() != 1) { throw new UnrecognizedCCodeException("Wrong number of arguments for malloc", cfaEdge, expression); } CExpression parameter = parameters.get(0); if (leftDereference) { throw new UnrecognizedCCodeException("unsupported", cfaEdge, expression); } long size; if (parameter instanceof CLiteralExpression) { if (!(parameter instanceof CIntegerLiteralExpression)) { throw new UnrecognizedCCodeException("non-integers not supported", cfaEdge, parameter); } size = ((CIntegerLiteralExpression) parameter).asLong(); if (size < 0) { throw new UnrecognizedCCodeException("malloc with size < 0, but malloc takes unsigned parameter", cfaEdge, parameter); } if (size > 0x7FFFFFFF) { throw new UnrecognizedCCodeException("Malloc too large", cfaEdge, expression); } } else if (parameter instanceof CIdExpression) { String varName = quoteVar(((CIdExpression) parameter).getName(), element); Long sizeLong = element.extractExplicitValue(varName); if (sizeLong == null) { throw new UnrecognizedCCodeException("Could not extract malloc size (no equalities found)", cfaEdge, expression); } size = sizeLong.longValue(); } else { throw new UnrecognizedCCodeException("not expected in CIL", cfaEdge, parameter); } // XXX freshen correct? SeplogicState curElem = element.freshenVariable(quoteVar(pLeftVarName, element)).performSpecificationAssignment(psInterface.makeEmp(), makePointsTo(makeVarArg(pLeftVarName, element), makeFreshExistential()), null); // XXX completely nuts but enough for list2.cil.c on amd64 int i = 8; while (i < size) { curElem = curElem.performSpecificationAssignment( psInterface.makeEmp(), makePointsTo(psInterface.makePlus(makeVarArg(pLeftVarName, element), makeIntegerConstant(i)), makeFreshExistential()), null); i += 8; } return curElem; } private Handle makeIntegerConstant(long pL) { return psInterface.makeInt(psInterface.loadString("" + pL)); } @Override public Collection<? extends AbstractState> strengthen( AbstractState element, List<AbstractState> elements, CFAEdge cfaEdge, Precision precision) throws CPATransferException { return null; } }
Odvin/s3-uploader
services/api-server/redis/index.js
const Redis = require('ioredis'); const config = { host: 'redis', port: 6379 }; const redis = new Redis(config); module.exports = redis;
layerzero/cc0
src/toolchain/core/CodeDom/NopExpression.cpp
<gh_stars>0 #include "NopExpression.h" #include "ExpressionVisitor.h" #include <core/Type/VoidType.h> Type* NopExpression::GetType() { return new VoidType(); } Expression* NopExpression::GetLValue() { return NULL; } void NopExpression::Accept(ExpressionVisitor* visitor) { visitor->Visit(this); } NopExpression::NopExpression() :Expression(Expression::Nop) { } NopExpression::~NopExpression() { }
kagome1007/MegEngine
dnn/src/arm_common/conv_bias/int8/direct_kernels/dot_direct_nchw44_common.h
/** * \file * dnn/src/arm_common/conv_bias/int8/direct_kernels/dot_direct_nchw44_common.h * MegEngine is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2014-2021 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. */ #pragma once #include "megdnn/arch.h" #include "src/arm_common/conv_bias/intrinsic_helper.h" #if MGB_ENABLE_DOT #include "src/arm_common/elemwise_helper/elemwise_op.h" #include "src/arm_common/intrinsic_helper.h" #include "src/arm_common/neon_struct.h" #include "src/common/unroll_macro.h" namespace megdnn { namespace arm_common { namespace direct_dotprod_nchw44 { constexpr int SIMD_LEN = 16; constexpr int IC_PACK_SIZE = 4; constexpr int OC_PACK_SIZE = 4; constexpr int filter_next_col = IC_PACK_SIZE * OC_PACK_SIZE; //! [OC/4, IC/4, FH, FW, 4OC, 4IC] template <int row, BiasMode bias_mode> MEGDNN_ALWAYS_INLINE void init_ocx_ow8( int32x4_t c[][8], const int32_t* bias_ptr, int oc_step) { static_assert(row == 1 || row == 2 || row == 3, "Invalid OC number."); if (bias_mode == BiasMode::BROADCAST_CHANNEL_BIAS) { #define BIAS_INIT(step, i) c[i][step] = vld1q_s32(bias_ptr + i * oc_step); switch (row) { case 3: UNROLL_CALL_RAW(8, BIAS_INIT, 2); case 2: UNROLL_CALL_RAW(8, BIAS_INIT, 1); default: UNROLL_CALL_RAW(8, BIAS_INIT, 0); } #undef BIAS_INIT } else { #define BIAS_INIT(step, i) c[i][step] = vdupq_n_s32(0); switch (row) { case 3: UNROLL_CALL_RAW(8, BIAS_INIT, 2); case 2: UNROLL_CALL_RAW(8, BIAS_INIT, 1); default: UNROLL_CALL_RAW(8, BIAS_INIT, 0); } #undef BIAS_INIT } } #define cb11(col) op(res[0][col], reinterpret_cast<dt_qint8*>(dst_ptr + col / 2 * 8)); #define cb21(col) \ op(res[0][col], reinterpret_cast<dt_qint8*>(dst_ptr + col / 2 * 8)); \ op(res[1][col], reinterpret_cast<dt_qint8*>(dst_ptr + ld_dst_oc + col / 2 * 8)); #define cb31(col) \ op(res[0][col], reinterpret_cast<dt_qint8*>(dst_ptr + col / 2 * 8)); \ op(res[1][col], reinterpret_cast<dt_qint8*>(dst_ptr + ld_dst_oc + col / 2 * 8)); \ op(res[2][col], \ reinterpret_cast<dt_qint8*>(dst_ptr + ld_dst_oc + ld_dst_oc + col / 2 * 8)); #define cb12(step) \ op({{res[0][2 * step], res[0][2 * step + 1]}}, \ reinterpret_cast<dt_qint8*>(dst_ptr + step * 8)); #define cb22(step) \ op({{res[0][2 * step], res[0][2 * step + 1]}}, \ reinterpret_cast<dt_qint8*>(dst_ptr + step * 8)); \ op({{res[1][2 * step], res[1][2 * step + 1]}}, \ reinterpret_cast<dt_qint8*>(dst_ptr + ld_dst_oc + step * 8)); #define cb32(step) \ op({{res[0][2 * step], res[0][2 * step + 1]}}, \ reinterpret_cast<dt_qint8*>(dst_ptr + step * 8)); \ op({{res[1][2 * step], res[1][2 * step + 1]}}, \ reinterpret_cast<dt_qint8*>(dst_ptr + ld_dst_oc + step * 8)); \ op({{res[2][2 * step], res[2][2 * step + 1]}}, \ reinterpret_cast<dt_qint8*>(dst_ptr + 2 * ld_dst_oc + step * 8)); template <int row, int ow_remain, typename Op, typename T> struct StoreOCxOWx { static MEGDNN_ALWAYS_INLINE void impl( int32x4_t res[][8], const Op& op, T* dst_ptr, const int ld_dst_oc); }; template <int ow_remain, typename Op, typename T> struct StoreOCxOWx<1, ow_remain, Op, T> { static void impl( int32x4_t res[][8], const Op& op, T* dst_ptr, const int ld_dst_oc) { MEGDNN_MARK_USED_VAR(ld_dst_oc); switch (ow_remain) { case 8: UNROLL_CALL_RAW(4, cb12); break; case 7: cb11(6); case 6: UNROLL_CALL_RAW(3, cb12); break; case 5: cb11(4); case 4: UNROLL_CALL_RAW(2, cb12); break; case 3: cb11(2); case 2: UNROLL_CALL_RAW(1, cb12); break; case 1: cb11(0); default: break; } } }; template <int ow_remain, typename Op, typename T> struct StoreOCxOWx<2, ow_remain, Op, T> { static MEGDNN_ALWAYS_INLINE void impl( int32x4_t res[][8], const Op& op, T* dst_ptr, const int ld_dst_oc) { switch (ow_remain) { case 8: UNROLL_CALL_RAW(4, cb22); break; case 7: cb21(6); case 6: UNROLL_CALL_RAW(3, cb22); break; case 5: cb21(4); case 4: UNROLL_CALL_RAW(2, cb22); break; case 3: cb21(2); case 2: UNROLL_CALL_RAW(1, cb22); break; case 1: cb21(0); default: break; } } }; template <int ow_remain, typename Op, typename T> struct StoreOCxOWx<3, ow_remain, Op, T> { static MEGDNN_ALWAYS_INLINE void impl( int32x4_t res[][8], const Op& op, T* dst_ptr, const int ld_dst_oc) { switch (ow_remain) { case 8: UNROLL_CALL_RAW(4, cb32); break; case 7: cb31(6); case 6: UNROLL_CALL_RAW(3, cb32); break; case 5: cb31(4); case 4: UNROLL_CALL_RAW(2, cb32); break; case 3: cb31(2); case 2: UNROLL_CALL_RAW(1, cb32); break; case 1: cb31(0); default: break; } } }; #undef cb11 #undef cb21 #undef cb31 #undef cb12 #undef cb22 #undef cb32 template <int row, int ow_remain, typename Op, typename T> MEGDNN_ALWAYS_INLINE void store_ocx_owx_remain_static( int32x4_t res[][8], const Op& op, T* dst_ptr, const int ld_dst_oc) { StoreOCxOWx<row, ow_remain, Op, T>::impl(res, op, dst_ptr, ld_dst_oc); } template < int res_row, int src_row, int src_start_idx, int weight_idx, typename T, typename T2, typename T3> struct ShiftCalHelper { MEGDNN_ATTRIBUTE_TARGET("dotprod") static MEGDNN_ALWAYS_INLINE void impl(T& res, T2& src, T3& weight) { #define cb(step) \ res[res_row][step] = vdotq_laneq_s32( \ res[res_row][step], weight[weight_idx], \ src[src_row][(src_start_idx + step) / 4], (src_start_idx + step) % 4); UNROLL_CALL_RAW(8, cb); #undef cb } }; template < int res_row, int src_row, int src_start_idx, int weight_idx, typename T, typename T2, typename T3> MEGDNN_ATTRIBUTE_TARGET("dotprod") MEGDNN_ALWAYS_INLINE void cal_helper(T& res, T2& src, T3& weight) { ShiftCalHelper<res_row, src_row, src_start_idx, weight_idx, T, T2, T3>::impl( res, src, weight); }; /** * oc12_owx(m = 12, n = x) and oc8_owx(m = 8, n = x) and oc4_owx(m = 4, n = x) * gemm like kernel * */ template < typename dst_type, int stride, BiasMode bias_mode, typename Op, int ow_remain, int filter_size, int oc_interval, int ow_interval> struct KernNeonSdotNCHW44 { static void impl( dst_type* dst, const int dst_step, const int8_t* src, const int ih, const int iw, const int8_t* filter, const int32_t* bias, const int ic, const Op& op); }; } // namespace direct_dotprod_nchw44 } // namespace arm_common } // namespace megdnn #endif // vim: syntax=cpp.doxygen
joshluisaac/powerapps-serviceengine
src/main/java/com/profitera/services/business/rpm/RPMEngineTestService.java
<gh_stars>0 package com.profitera.services.business.rpm; import com.profitera.deployment.rmi.RPMEngineTestServiceIntf; import com.profitera.descriptor.business.TransferObject; import com.profitera.services.business.BusinessService; import com.profitera.services.system.rpm.RuleTest; public class RPMEngineTestService extends BusinessService implements RPMEngineTestServiceIntf { public RPMEngineTestService() { } /** * Returns a vector with 3 elements, a hashtable array containing the descriptors * (same as calling fetchAccountStates()), a 2 dim Long array containing the * rules foired for each descriptor, and another Hashtable array containing * the descriptors after the changes made by the rules have take effect. * * For thread-safety the implementation is in RuleTest, at each invokation we * crate a Ruletest instance and make it do the work, see that class for the real goods. * @see com.profitera.deployment.rmi.RPMEngineTestServiceIntf#testRules(int, java.lang.Long[]) */ public TransferObject testRules(int accountCount, Long[] ruleIds) { RuleTest rt = new RuleTest(); return rt.testRules(accountCount,ruleIds); } /** * This method will return a transfer object containing an array of hashtables, * the keys are the names of the methods used by the rules and the data is a * Vector of Strings that represents the data passed in followed by the resulting value. * If the method is called more than once the params are just appended to the end of * the vector. The descriptors/dictionaries should never have polymophic methods anyway. * The client side can use the dictionary to pull these values and display * them properly. * <br/> * For thread-safety the implementation is in RuleTest, at each invokation we * crate a Ruletest instance and make it do the work, see that class for the real goods. * * @see com.profitera.deployment.rmi.RPMEngineTestServiceIntf#fetchAccountStates(int, java.lang.Long[]) * @see com.profitera.services.system.rpm.RuleTest */ public TransferObject fetchAccountStates(int accountCount, Long[] ruleIds) { RuleTest rt = new RuleTest(); return rt.fetchAccountStates(accountCount,ruleIds); } }
AntonioIonica/Automation_testing
Fuzzywuzzy_course_exercice/src/test_script.py
<gh_stars>0 """ Fuzzywuzzy for data as cities name using partial_ratio and QRatio """ from fuzzywuzzy import fuzz def test_case1(input_data, expected_data): similarity = fuzz.partial_ratio(input_data, expected_data) if similarity > 90: print(f'Test passed with the score of {similarity}!') elif 80 < similarity < 90: print(f'Test passed with the score of {similarity}! There is a warning!') else: print(f'Test failed with the score of {similarity}!') return similarity def test_case2(input_data, expected_data): q_ratio = fuzz.QRatio(input_data, expected_data) if q_ratio > 80: print(f'Test passed with the score of QRatio of {q_ratio}!') elif 60 < q_ratio < 80: print(f'QRatio test passed with a score of {q_ratio}!') else: print(f'Test failed with a QRatio of {q_ratio}!') return q_ratio
dgolovin/org.jboss.tools.ssp
framework/bundles/org.jboss.tools.rsp.launching/src/main/java/org/jboss/tools/rsp/eclipse/debug/core/model/IProcess.java
<filename>framework/bundles/org.jboss.tools.rsp.launching/src/main/java/org/jboss/tools/rsp/eclipse/debug/core/model/IProcess.java /******************************************************************************* * Copyright (c) 2000, 2005 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v2.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v20.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.jboss.tools.rsp.eclipse.debug.core.model; import org.jboss.tools.rsp.eclipse.debug.core.DebugPluginConstants; import org.jboss.tools.rsp.eclipse.debug.core.DebugException; import org.jboss.tools.rsp.eclipse.debug.core.ILaunch; /** * A process represents a program running in normal (non-debug) mode. * Processes support setting and getting of client defined attributes. * This way, clients can annotate a process with any extra information * important to them. For example, classpath annotations, or command * line arguments used to launch the process may be important to a client. * <p> * Clients may implement this interface, however, the debug plug-in * provides an implementation of this interface for a * <code>java.lang.Process</code>. * </p> * @see org.jboss.tools.rsp.eclipse.debug.core.DebugPluginConstants#newProcess(ILaunch, Process, String) */ public interface IProcess extends ITerminate { /** * Attribute key for a common, optional, process property. The value of this * attribute is the command line a process was launched with. * * @since 2.1 */ public final static String ATTR_CMDLINE= DebugPluginConstants.DEBUG_CORE_ID + ".ATTR_CMDLINE"; //$NON-NLS-1$ /** * Attribute key for a common, optional, process property. The value of this * attribute is an identifier for the type of this process. Process types * are client defined - whoever creates a process may define its type. For * example, a process type could be "java", "javadoc", or "ant". * * @since 2.1 */ public final static String ATTR_PROCESS_TYPE = DebugPluginConstants.DEBUG_CORE_ID + ".ATTR_PROCESS_TYPE"; //$NON-NLS-1$ /** * Attribute key for a common, optional, process property. The value of this * attribute specifies an alternate dynamic label for a process, displayed by * the console. * * @since 3.0 */ public final static String ATTR_PROCESS_LABEL = DebugPluginConstants.DEBUG_CORE_ID + ".ATTR_PROCESS_LABEL"; //$NON-NLS-1$ /** * Returns a human-readable label for this process. * * @return a label for this process */ public String getLabel(); /** * Returns the launch this element originated from. * * @return the launch this process is contained in */ public ILaunch getLaunch(); /** * Returns a proxy to the standard input, output, and error streams * for this process, or <code>null</code> if not supported. * * @return a streams proxy, or <code>null</code> if not supported */ public IStreamsProxy getStreamsProxy(); /** * Sets the value of a client defined attribute. * * @param key the attribute key * @param value the attribute value */ public void setAttribute(String key, String value); /** * Returns the value of a client defined attribute. * * @param key the attribute key * @return value the String attribute value, or <code>null</code> if undefined */ public String getAttribute(String key); /** * Returns the exit value of this process. Conventionally, 0 indicates * normal termination. * * @return the exit value of this process * @exception DebugException if this process has not yet terminated */ public int getExitValue() throws DebugException; }
anipmehta/Elements_Of_Programming_Interview
src/maximum_performance_of_team/Solution.java
package maximum_performance_of_team; import com.sun.scenario.effect.impl.sw.java.JSWEffectPeer; import java.util.*; public class Solution { public static void main(String [] args){ char ch = 'a'+ 1; System.out.println(ch); } class Engineer{ public int efficiency; public int speed; public Engineer(int efficiency, int speed){ this.efficiency = efficiency; this.speed = speed; } } public int maxPerformance(int n, int[] speed, int[] efficiency, int k) { // take greedy approach here // start picking from the most efficient employees and pop out the one with smallest speed as we iterate Queue<Engineer> pq = new PriorityQueue<>(k, new Comparator<Engineer>() { @Override public int compare(Engineer o1, Engineer o2) { return o1.speed - o2.speed; } }); long maxPerformance = 0; long totalSpeed = 0; List<Engineer> engineers = new ArrayList<>(); for(int i=0;i<n;i++){ engineers.add(new Engineer(efficiency[i], speed[i])); } Collections.sort(engineers, new Comparator<Engineer>() { @Override public int compare(Engineer o1, Engineer o2) { return o2.efficiency - o1.efficiency; } }); for(Engineer engineer : engineers){ pq.offer(engineer); totalSpeed += engineer.speed; if(pq.size()>k){ Engineer slow = pq.poll(); totalSpeed -= slow.speed; } maxPerformance = Math.max(maxPerformance, totalSpeed * engineer.efficiency); System.out.println(maxPerformance); } return (int) (maxPerformance % (long)(1e9 + 7)); } }
imgstack/stackpath-cdn-go
models/cdn_site_script.go
<reponame>imgstack/stackpath-cdn-go // Code generated by go-swagger; DO NOT EDIT. package models // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "context" "github.com/go-openapi/errors" "github.com/go-openapi/strfmt" "github.com/go-openapi/swag" "github.com/go-openapi/validate" ) // CdnSiteScript An EdgeEngine script // // EdgeEngine scripts are hosted and executed on StackPath's edge nodes. // // swagger:model cdnSiteScript type CdnSiteScript struct { // The contents of an EdgeEngine script // Format: byte Code strfmt.Base64 `json:"code,omitempty"` // The date an EdgeEngine script was created // Format: date-time CreatedAt strfmt.DateTime `json:"createdAt,omitempty"` // An EdgeEngine script's unique identifier ID string `json:"id,omitempty"` // An EdgeEngine script's name Name string `json:"name,omitempty"` // The URL paths that incoming requests should answer with an EdgeEngine script // // Every EdgeEngine script needs at least one path, and paths must be unique. Paths []string `json:"paths,omitempty"` // The ID of the site to which an EdgeEngine script belongs SiteID string `json:"siteId,omitempty"` // The ID of the stack to which an EdgeEngine script's site belongs StackID string `json:"stackId,omitempty"` // The date an EdgeEngine script was last updated // Format: date-time UpdatedAt strfmt.DateTime `json:"updatedAt,omitempty"` // An EdgeEngine script's version number // // Version numbers start at 1 and are incremented every time the script is updated. Version string `json:"version,omitempty"` } // Validate validates this cdn site script func (m *CdnSiteScript) Validate(formats strfmt.Registry) error { var res []error if err := m.validateCreatedAt(formats); err != nil { res = append(res, err) } if err := m.validateUpdatedAt(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *CdnSiteScript) validateCreatedAt(formats strfmt.Registry) error { if swag.IsZero(m.CreatedAt) { // not required return nil } if err := validate.FormatOf("createdAt", "body", "date-time", m.CreatedAt.String(), formats); err != nil { return err } return nil } func (m *CdnSiteScript) validateUpdatedAt(formats strfmt.Registry) error { if swag.IsZero(m.UpdatedAt) { // not required return nil } if err := validate.FormatOf("updatedAt", "body", "date-time", m.UpdatedAt.String(), formats); err != nil { return err } return nil } // ContextValidate validates this cdn site script based on context it is used func (m *CdnSiteScript) ContextValidate(ctx context.Context, formats strfmt.Registry) error { return nil } // MarshalBinary interface implementation func (m *CdnSiteScript) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } // UnmarshalBinary interface implementation func (m *CdnSiteScript) UnmarshalBinary(b []byte) error { var res CdnSiteScript if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil }
SharikaN/WebDevToolkitForDx
digexp-wcm-design/test/config.js
/* * Copyright HCL Technologies Ltd. 2001, 2020 * 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. */ /** * Config for unit tests. */ module.exports = { TEST_USERNAME: "wpsadmin", TEST_PASSWORD: "<PASSWORD>", TEST_HOST: "localhost", // gsager80.rtp.raleigh.hcl.com TEST_PORT: 30015, // 10039 TEST_SECURE_PORT: 30016, // 10042 TEST_CONTENT_HANDLER: "/wps/mycontenthandler", LONG_TIMEOUT: 300000 };
voku/mod-spdy
src/third_party/chromium/src/base/system_monitor/system_monitor.h
<reponame>voku/mod-spdy // 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. #ifndef BASE_SYSTEM_MONITOR_SYSTEM_MONITOR_H_ #define BASE_SYSTEM_MONITOR_SYSTEM_MONITOR_H_ #include <string> #include <vector> #include "base/base_export.h" #include "base/basictypes.h" #include "base/tuple.h" #include "build/build_config.h" // Windows HiRes timers drain the battery faster so we need to know the battery // status. This isn't true for other platforms. #if defined(OS_WIN) #define ENABLE_BATTERY_MONITORING 1 #else #undef ENABLE_BATTERY_MONITORING #endif // !OS_WIN #include "base/observer_list_threadsafe.h" #if defined(ENABLE_BATTERY_MONITORING) #include "base/timer.h" #endif // defined(ENABLE_BATTERY_MONITORING) #if defined(OS_MACOSX) && !defined(OS_IOS) #include <IOKit/pwr_mgt/IOPMLib.h> #include <IOKit/IOMessage.h> #endif // OS_MACOSX && !OS_IOS #if defined(OS_IOS) #include <objc/runtime.h> #endif // OS_IOS class FilePath; namespace base { // Class for monitoring various system-related subsystems // such as power management, network status, etc. // TODO(mbelshe): Add support beyond just power management. class BASE_EXPORT SystemMonitor { public: // Normalized list of power events. enum PowerEvent { POWER_STATE_EVENT, // The Power status of the system has changed. SUSPEND_EVENT, // The system is being suspended. RESUME_EVENT // The system is being resumed. }; typedef unsigned int DeviceIdType; // (Media device id, Media device name, Media device path) typedef Tuple3<DeviceIdType, std::string, FilePath> MediaDeviceInfo; // Create SystemMonitor. Only one SystemMonitor instance per application // is allowed. SystemMonitor(); ~SystemMonitor(); // Get the application-wide SystemMonitor (if not present, returns NULL). static SystemMonitor* Get(); #if defined(OS_MACOSX) // Allocate system resources needed by the SystemMonitor class. // // This function must be called before instantiating an instance of the class // and before the Sandbox is initialized. #if !defined(OS_IOS) static void AllocateSystemIOPorts(); #else static void AllocateSystemIOPorts() {} #endif // OS_IOS #endif // OS_MACOSX // // Power-related APIs // // Is the computer currently on battery power. // Can be called on any thread. bool BatteryPower() const { // Using a lock here is not necessary for just a bool. return battery_in_use_; } // Callbacks will be called on the thread which creates the SystemMonitor. // During the callback, Add/RemoveObserver will block until the callbacks // are finished. Observers should implement quick callback functions; if // lengthy operations are needed, the observer should take care to invoke // the operation on an appropriate thread. class BASE_EXPORT PowerObserver { public: // Notification of a change in power status of the computer, such // as from switching between battery and A/C power. virtual void OnPowerStateChange(bool on_battery_power) {} // Notification that the system is suspending. virtual void OnSuspend() {} // Notification that the system is resuming. virtual void OnResume() {} protected: virtual ~PowerObserver() {} }; class BASE_EXPORT DevicesChangedObserver { public: // Notification that the devices connected to the system have changed. // This is only implemented on Windows currently. virtual void OnDevicesChanged() {} // When a media device is attached or detached, one of these two events // is triggered. // TODO(vandebo) Pass an appropriate device identifier or way to interact // with the devices instead of FilePath. virtual void OnMediaDeviceAttached(const DeviceIdType& id, const std::string& name, const FilePath& path) {} virtual void OnMediaDeviceDetached(const DeviceIdType& id) {} protected: virtual ~DevicesChangedObserver() {} }; // Add a new observer. // Can be called from any thread. // Must not be called from within a notification callback. void AddPowerObserver(PowerObserver* obs); void AddDevicesChangedObserver(DevicesChangedObserver* obs); // Remove an existing observer. // Can be called from any thread. // Must not be called from within a notification callback. void RemovePowerObserver(PowerObserver* obs); void RemoveDevicesChangedObserver(DevicesChangedObserver* obs); #if defined(OS_WIN) // Windows-specific handling of a WM_POWERBROADCAST message. // Embedders of this API should hook their top-level window // message loop and forward WM_POWERBROADCAST through this call. void ProcessWmPowerBroadcastMessage(int event_id); #endif // Cross-platform handling of a power event. void ProcessPowerMessage(PowerEvent event_id); // Cross-platform handling of a device change event. void ProcessDevicesChanged(); void ProcessMediaDeviceAttached(const DeviceIdType& id, const std::string& name, const FilePath& path); void ProcessMediaDeviceDetached(const DeviceIdType& id); // Returns information for attached media devices. std::vector<MediaDeviceInfo> GetAttachedMediaDevices() const; private: typedef std::map<base::SystemMonitor::DeviceIdType, MediaDeviceInfo> MediaDeviceMap; #if defined(OS_MACOSX) void PlatformInit(); void PlatformDestroy(); #endif // Platform-specific method to check whether the system is currently // running on battery power. Returns true if running on batteries, // false otherwise. bool IsBatteryPower(); // Checks the battery status and notifies observers if the battery // status has changed. void BatteryCheck(); // Functions to trigger notifications. void NotifyDevicesChanged(); void NotifyMediaDeviceAttached(const DeviceIdType& id, const std::string& name, const FilePath& path); void NotifyMediaDeviceDetached(const DeviceIdType& id); void NotifyPowerStateChange(); void NotifySuspend(); void NotifyResume(); scoped_refptr<ObserverListThreadSafe<PowerObserver> > power_observer_list_; scoped_refptr<ObserverListThreadSafe<DevicesChangedObserver> > devices_changed_observer_list_; bool battery_in_use_; bool suspended_; #if defined(ENABLE_BATTERY_MONITORING) base::OneShotTimer<SystemMonitor> delayed_battery_check_; #endif #if defined(OS_IOS) // Holds pointers to system event notification observers. std::vector<id> notification_observers_; #endif MediaDeviceMap media_device_map_; DISALLOW_COPY_AND_ASSIGN(SystemMonitor); }; } // namespace base #endif // BASE_SYSTEM_MONITOR_SYSTEM_MONITOR_H_
robertfoss/i2p.i2p-bote
core/src/test/java/i2p/bote/packet/dht/EncryptedEmailPacketTest.java
/** * Copyright (C) 2009 <EMAIL> * * The GPG fingerprint for <EMAIL> is: * 6DD3 EAA2 9990 29BC 4AD2 7486 1E2C 7B61 76DC DC12 * * This file is part of I2P-Bote. * I2P-Bote is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * I2P-Bote is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with I2P-Bote. If not, see <http://www.gnu.org/licenses/>. */ package i2p.bote.packet.dht; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import i2p.bote.UniqueId; import i2p.bote.crypto.ECDH521_ECDSA521; import i2p.bote.crypto.ElGamal2048_DSA1024; import i2p.bote.email.EmailDestination; import i2p.bote.email.EmailIdentity; import i2p.bote.packet.I2PBotePacket; import java.io.ByteArrayInputStream; import java.lang.reflect.Field; import net.i2p.crypto.SHA256Generator; import net.i2p.data.Hash; import org.junit.Before; import org.junit.Test; public class EncryptedEmailPacketTest { EncryptedEmailPacket[] encryptedPackets; EncryptedEmailPacket ecdhEncryptedPacket; UnencryptedEmailPacket plaintextPacket; EmailIdentity[] identities; String message = "This is a test message. Test 1 2 3 Test"; @Before public void setUp() throws Exception { // make an UnencryptedEmailPacket byte[] content = message.getBytes(); byte[] messageIdBytes = new byte[] {-69, -24, -109, 1, 69, -122, -69, 113, -68, -90, 55, -28, 105, 97, 125, 70, 51, 58, 14, 2, -13, -53, 90, -29, 36, 67, 36, -94, -108, -125, 11, 123}; UniqueId messageId = new UniqueId(messageIdBytes, 0); int fragmentIndex = 0; plaintextPacket = new UnencryptedEmailPacket(new ByteArrayInputStream(content), messageId, fragmentIndex, I2PBotePacket.MAX_DATAGRAM_SIZE); plaintextPacket.setNumFragments(1); encryptedPackets = new EncryptedEmailPacket[2]; identities = new EmailIdentity[2]; // make a ElGamal/DSA identity String elGamalBase64 = "<KEY>"; identities[0] = new EmailIdentity(elGamalBase64); EmailDestination elGamalDestination = new EmailDestination(identities[0].getKey()); // make an ElGamal encrypted packet assertTrue(identities[0].getCryptoImpl() instanceof ElGamal2048_DSA1024); encryptedPackets[0] = new EncryptedEmailPacket(plaintextPacket, elGamalDestination); // make a ECDH/ECDSA identity String ecdhBase64 = "<KEY>"; identities[1] = new EmailIdentity(ecdhBase64); EmailDestination ecdhDestination = new EmailDestination(identities[1].getKey()); // make an ECDH encrypted packet assertTrue(identities[1].getCryptoImpl() instanceof ECDH521_ECDSA521); encryptedPackets[1] = new EncryptedEmailPacket(plaintextPacket, ecdhDestination); } @Test public void toByteArrayAndBack() throws Exception { for (EncryptedEmailPacket packet: encryptedPackets) { byte[] arrayA = packet.toByteArray(); byte[] arrayB = new EncryptedEmailPacket(arrayA).toByteArray(); assertArrayEquals("The two arrays differ! CryptoImplementation = " + packet.getCryptoImpl().getName(), arrayA, arrayB); } } @Test public void testEncryptionDecryption() throws Exception { for (int i=0; i<encryptedPackets.length; i++) { EncryptedEmailPacket packet = encryptedPackets[i]; UnencryptedEmailPacket decryptedPacket = packet.decrypt(identities[i]); byte[] arrayA = decryptedPacket.getContent(); byte[] arrayB = message.getBytes(); assertArrayEquals("Email message differs after decryption! CryptoImplementation = " + packet.getCryptoImpl().getName(), arrayA, arrayB); } } @Test public void testDeleteVerificationHash() { for (int i=0; i<encryptedPackets.length; i++) { EncryptedEmailPacket packet = encryptedPackets[i]; Hash expectedHash = SHA256Generator.getInstance().calculateHash(plaintextPacket.getDeleteAuthorization().toByteArray()); assertEquals("The delete authorization key does not hash to the delete verification hash!", expectedHash, packet.getDeleteVerificationHash()); } } @Test public void testHash() throws Exception { for (EncryptedEmailPacket packet: encryptedPackets) { assertTrue("Hash not valid! CryptoImplementation = " + packet.getCryptoImpl().getName(), packet.verifyPacketHash()); alterEncryptedData(packet); assertFalse("Hash is valid, but should be invalid! CryptoImplementation = " + packet.getCryptoImpl().getName(), packet.verifyPacketHash()); } } private void alterEncryptedData(EncryptedEmailPacket packet) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Field encryptedDataField = EncryptedEmailPacket.class.getDeclaredField("encryptedData"); encryptedDataField.setAccessible(true); Object encryptedDataObject = encryptedDataField.get(packet); byte[] encryptedData = (byte[])encryptedDataObject; // flip one bit encryptedData[0] ^= 1; } }
ALP-active-miner/ALP
MUDetect/mubench/src/main/java/de/tu_darmstadt/stg/mudetect/ranking/NodeWeightFunction.java
package de.tu_darmstadt.stg.mudetect.ranking; import de.tu_darmstadt.stg.mudetect.aug.model.Node; import java.util.Collection; public interface NodeWeightFunction { double getWeight(Node node); default double getWeight(Collection<Node> nodes) { return nodes.stream().mapToDouble(this::getWeight).sum(); } default double getInverseWeight(Node node) { return 1 / getWeight(node); } default double getInverseWeight(Collection<Node> nodes) { return nodes.stream().mapToDouble(this::getInverseWeight).sum(); } }
CMU-TRP/podd-api
podd/settings/base.py
# At the top of settings/base.py # -*- encoding: utf-8 -*- import os from os.path import join, abspath, dirname import raven from celery.schedules import crontab from datetime import timedelta here = lambda *x: join(abspath(dirname(__file__)), *x) PROJECT_ROOT = here("..", "..") root = lambda *x: join(abspath(PROJECT_ROOT), *x) STATIC_ROOT = root('sitestatic') STATIC_URL = '/static/' STATICFILES_DIRS = ( root("static"), ) MEDIA_ROOT = root('media') MEDIA_URL = '/media/' """ Django settings for podd project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( #'opbeat.contrib.django', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.gis', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'test_without_migrations', # log 'raven.contrib.django.raven_compat', # libs 'haystack', 'leaflet', 'rest_framework', 'rest_framework.authtoken', 'treebeard', 'corsheaders', 'django_extensions', 'taggit', 'cacheops', # apps 'common', 'accounts', 'analysis', 'areas', 'feed', 'flags', 'logs', 'monitorings', 'mentions', 'notifications', 'news', 'reports', 'supervisors', 'plans', 'pages', 'summary', 'firebase', 'dodd', 'covid', ) MIDDLEWARE_CLASSES = ( #'opbeat.contrib.django.middleware.OpbeatAPMMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'common.middleware.SwitchDomainMiddleware', 'crum.CurrentRequestUserMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', ) from crum import CurrentRequestUserMiddleware TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.core.context_processors.static', 'django.core.context_processors.tz', 'django.core.context_processors.request', 'django.contrib.messages.context_processors.messages', ) from django.template.base import add_to_builtins add_to_builtins('plans.templatetags.plans_tags') ROOT_URLCONF = 'podd.urls' WSGI_APPLICATION = 'podd.wsgi.application' # Internationalization # https://docs.djangoproject.com/en/1.7/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LOGGING = { 'version': 1, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler' } }, 'loggers': { 'management_commands': { 'handlers': ['console'], 'level': 'INFO', 'propagate': False } } } DEBUG_TOOLBAR_PANELS = [ 'debug_toolbar.panels.versions.VersionsPanel', 'debug_toolbar.panels.timer.TimerPanel', 'debug_toolbar.panels.settings.SettingsPanel', 'debug_toolbar.panels.headers.HeadersPanel', 'debug_toolbar.panels.request.RequestPanel', 'debug_toolbar.panels.sql.SQLPanel', 'debug_toolbar.panels.staticfiles.StaticFilesPanel', 'debug_toolbar.panels.templates.TemplatesPanel', 'debug_toolbar.panels.cache.CachePanel', 'debug_toolbar.panels.signals.SignalsPanel', 'debug_toolbar.panels.logging.LoggingPanel', 'debug_toolbar.panels.redirects.RedirectsPanel', ] TEMPLATE_DIRS = ( # os.path.join(BASE_DIR, 'templates'), root('templates'), ) # Authenticated LOGIN_REDIRECT_URL = '/supervisors/users/' AUTH_USER_MODEL = 'accounts.User' AUTHENTICATION_BACKENDS = ( 'accounts.backends.OneDayPasswordModelBackend', 'django.contrib.auth.backends.ModelBackend' ) # Rest Framework REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'TEST_REQUEST_DEFAULT_FORMAT': 'json', } # Haystack HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'podd.backends.ConfigurableElasticSearchEngine', 'URL': 'http://127.0.0.1:9200/', 'INDEX_NAME': 'haystack', }, } HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor' # Leaflet LEAFLET_CONFIG = { 'DEFAULT_CENTER': (13.0, 100.0), 'DEFAULT_ZOOM': 5, 'MIN_ZOOM': 3, 'MAX_ZOOM': 18, } CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/0", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "CONNECTION_POOL_KWARGS": { "max_connections": 100, }, } } } BROKER_URL = CACHES['default']['LOCATION'] SESSION_ENGINE = "django.contrib.sessions.backends.cache" SESSION_CACHE_ALIAS = "default" MAX_ATTACH_FILE_COMMENT_SIZE = 10485760 CORS_ORIGIN_ALLOW_ALL = True # EMAIL EMAIL_ADDRESS_NO_REPLY = u'ผู้ดูแลระบบ <<EMAIL>>' DEFAULT_DOMAIN = { 'code': 'api.cmonehealth.org, localhost:8000, 127.0.0.1:8000', 'name': 'cmonehealth' } # raven RAVEN_CONFIG = { 'dsn': '', 'site': 'PODD Django', } # CELERYBEAT MINUTES_PER_DAY = 24*60 AUTHORITY_INVITE_EXPIRE_DAYS = 30*12*20 NOTIFICATION_THRESHOLDS = { 'delayed_follow_up_interval': timedelta(minutes=5), 'delayed_follow_up_check_period': timedelta(minutes=15), } CELERYBEAT_SCHEDULE = { 'report-follow-up': { 'task': 'notifications.tasks.send_alert_follow_up', 'schedule': timedelta(minutes=MINUTES_PER_DAY) }, 'delayed-follow-up': { 'task': 'notifications.tasks.send_delayed_follow_up', 'schedule': NOTIFICATION_THRESHOLDS['delayed_follow_up_interval'], }, 'purge-all-expired-cache': { 'task': 'feed.tasks.purge_all_expired_cache_task', 'schedule': timedelta(days=1), }, 'fetch-dashboard-for-every-days': { 'task': 'pages.tasks.fetch_dashboard_for_every_days', 'schedule': crontab(hour=0, minute=0), }, 'covid-daily-summarize': { 'task': 'covid.tasks.daily_summarize', 'schedule': crontab(hour=0, minute=0), # UTC TIME }, 'covid-reporter-followup-notification': { 'task': 'covid.tasks.notify_reporter_when_no_followup_in_n_days', 'schedule': crontab(hour=0, minute=30), # UTC TIME }, 'covid-daily-summary-notification': { 'task': 'covid.tasks.daily_notify_authority', 'schedule': crontab(hour=3, minute=0), # UTC TIME } } NOTIFICATION_DISABLED = True UPDATE_REPORT_STATE_KEY = 'must-override-in-settings-local.py' ESPER_CONNECTION_URL = '' ESPER_RESPONSE_BASE_URL = '' #ESPER_CONNECTION_URL = 'http://127.0.0.1:8080/' # production #ESPER_RESPONSE_BASE_URL = 'http://127.0.0.1:8000/' # production NEO4J_CONNECTION_URL = 'http://127.0.0.1:7474/db/data/' SITE_URL = '' import sys TESTING = sys.argv[1:2] == ['test'] SHELLING = sys.argv[1:2] == ['shell'] or sys.argv[1:2] == ['shell_plus'] ADJUST_DATE = True CACHEOPS_REDIS = { 'host': 'localhost', # redis-server is on same machine 'port': 6379, # default redis port 'db': 1, # SELECT non-default redis database # using separate redis db or redis instance # is highly recommended 'socket_timeout': 3, # connection timeout in seconds, optional } CACHEOPS = { # Automatically cache any User.objects.get() calls for 15 minutes # This includes request.user or post.author access, # where Post.author is a foreign key to auth.User 'accounts.user': {'ops': 'get', 'timeout': 60*15}, # Automatically cache all gets and queryset fetches # to other django.contrib.auth models for an hour 'accounts.*': {'ops': ('fetch', 'get'), 'timeout': 60*60}, # Cache gets, fetches, counts and exists to Permission # 'all' is just an alias for ('get', 'fetch', 'count', 'exists') #'auth.permission': {'ops': 'all', 'timeout': 60*60}, # Enable manual caching on all other models with default timeout of an hour # Use Post.objects.cache().get(...) # or Tags.objects.filter(...).order_by(...).cache() # to cache particular ORM request. # Invalidation is still automatic #'*.*': {'ops': (), 'timeout': 60*60}, 'reports.report': {'ops': ('get'), 'timeout': 60 * 5}, 'reports.reportimage': {'ops': ('get', 'fetch'), 'timeout': 60 * 5}, 'reports.reporttype': {'ops': ('fetch', 'get'), 'timeout': 60 * 60}, 'reports.administrationarea': {'ops': ('fetch', 'get'), 'timeout': 60 * 60}, 'common.domain': {'ops': ('fetch', 'get'), 'timeout': 60 * 60 * 24}, 'authtoken.token': {'ops': ('get'), 'timeout': 60 * 60}, # And since ops is empty by default you can rewrite last line as: #'*.*': {'timeout': 60*60}, } if TESTING: CELERY_ALWAYS_EAGER = True CELERY_EAGER_PROPAGATES_EXCEPTIONS = True BROKER_BACKEND = 'memory' NOTIFICATION_DISABLED = True CURRENT_DOMAIN_ID = 0 ADJUST_DATE = False # Haystack HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'podd.backends.ConfigurableElasticSearchEngine', 'URL': 'http://127.0.0.1:9200/', 'INDEX_NAME': 'test_index', }, } CACHES['default']['LOCATION'] = "redis://127.0.0.1:6379/5" CACHEOPS = {} elif SHELLING: CELERY_ALWAYS_EAGER = True CELERY_EAGER_PROPAGATES_EXCEPTIONS = True BROKER_BACKEND = 'memory' ''' Firebase settings ''' FIREBASE_CHAT_API_URL = 'http://example.com/api' FIREBASE_CHAT_API_KEY = 'REPLACE_WITH_YOUR_KEY' FIREBASE_SERVICE_ACCOUNT_CERT = '' # For production only. #OPBEAT = { # 'ORGANIZATION_ID': '', # 'APP_ID': '', # 'SECRET_TOKEN': '', #} SNS_REPORT_ENABLE = False SNS_REPORT_MAPPING = { } COVID_REPORT_TYPE_CODE = "surveillance-covid-19" COVID_FOLLOWUP_TYPE_CODE = "surveillance-covid-19-followup" COVID_FOLLOWUP_TERMINATE_14_DAYS_PATTERN = u"สิ้นสุดการติดตาม" COVID_FOLLOWUP_TERMINATE_DEPARTURE_PATTERN = u"ออกนอกพื้นที่" COVID_FOLLOWUP_CONFIRMED_CASE_PATTERN = u"ผู้ป่วยยืนยัน" COVID_FOLLOWUP_TERMINATE_FIELD_NAME = "activity_close" COVID_FOLLOWUP_DAYS = 14 COVID_FOLLOWUP_NOTIFICATION_ALARM_DAYS = 2 COVID_FOLLOWUP_NOTIFICATION_MESSAGE = u"พบรายงานผู้มีความเสี่ยง Covid-19 ขาดการติดตามเกิน 2 วัน" COVID_FOLLOWUP_TAG = u"ขาดการติดตามเกิน %s วัน" COVID_MONITORING_ENABLE = False LINE_MESSAGING_API_ENDPOINT = 'https://api.line.me/v2/bot/message/push' LINE_ACCESS_TOKEN = '<PASSWORD>' LINE_LIFF_COVID_MONITORING_URL = 'https://liff.line.me/1653967705-q4Rrb8x6' LINE_FOLLOWUP_LABEL = u'ดูรายชื่อคนที่ต้องติดตาม'
slaclab/gdml
Common/Schema/Schema/offset.h
<reponame>slaclab/gdml // #ifndef OFFSET_H #define OFFSET_H 1 #include "Saxana/SAXObject.h" #include "Schema/DimensionsType.h" class offset : public SAXObject, public QuantityType { public: offset() { } virtual ~offset() { } virtual SAXObject::Type type() { return SAXObject::element; } }; #endif // OFFSET_H
btjanaka/competitive-programming-solutions
uva/12532.cpp
<gh_stars>1-10 // Author: btjanaka (<NAME>) // Problem: (UVa) 12532 #include <bits/stdc++.h> #define GET(x) scanf("%d", &x) #define GED(x) scanf("%lf", &x) typedef long long ll; using namespace std; typedef pair<int, int> ii; int a[100100]; struct FenwickTree { vector<int> ft; FenwickTree(int n) { ft.assign(n + 1, 0); } int lsone(int i) { return i & (-i); } int rsq(int b) { int sum = 0; for (; b; b -= lsone(b)) sum += ft[b]; return sum; } int rsq(int a, int b) { return rsq(b) - (a == 1 ? 0 : rsq(a - 1)); } void adjust(int k, int v) { for (; k < (int)ft.size(); k += lsone(k)) ft[k] += v; } }; int main() { // store number of negatives and 0's instead of actual products int n, k; while (GET(n) > 0) { FenwickTree neg(n), zero(n); GET(k); for (int i = 1; i <= n; ++i) { GET(a[i]); if (a[i] < 0) { neg.adjust(i, 1); } else if (a[i] == 0) { zero.adjust(i, 1); } } char ch; int i, j; while (k--) { scanf(" %c %d %d", &ch, &i, &j); switch (ch) { case 'C': if (j > 0) { if (a[i] < 0) { neg.adjust(i, -1); } else if (a[i] == 0) { zero.adjust(i, -1); } } else if (j < 0) { if (a[i] == 0) { zero.adjust(i, -1); } if (a[i] >= 0) { neg.adjust(i, 1); } } else { if (a[i] < 0) { neg.adjust(i, -1); } if (a[i] != 0) { zero.adjust(i, 1); } } a[i] = j; break; case 'P': int zeros = zero.rsq(i, j); int negs = neg.rsq(i, j); if (zeros > 0) { putchar('0'); } else if (negs % 2 == 0) { putchar('+'); } else { putchar('-'); } break; } } putchar('\n'); } return 0; }
nik-io/uDepot
trt/src/tests/trt_epoll_echo.cc
<filename>trt/src/tests/trt_epoll_echo.cc /* * Copyright (c) 2020 International Business Machines * All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause * * Authors: <NAME> (<EMAIL>, <EMAIL>) * */ // Spawn an echo server using trt+epoll #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <netinet/tcp.h> // TCP_NODELAY #include <string.h> // strerror #include "trt/uapi/trt.hh" #include "trt_backends/trt_epoll.hh" extern "C" { #include "trt_util/net_helpers.h" } using namespace trt; static void * echo_task(void *arg) { char buff[1024]; ssize_t r_ret, s_ret; int fd = (int)(uintptr_t)arg; const int optval = 1; if (setsockopt(fd, SOL_TCP, TCP_NODELAY, &optval, sizeof(optval)) == -1) { fprintf(stderr, "setsockopt %s err=%d.\n", strerror(errno), errno); return nullptr; } while (true) { r_ret = Epoll::recv(fd, buff, sizeof(buff), 0); if (r_ret < 0) { perror("recv"); break; } else if (r_ret == 0) { break; } s_ret = Epoll::send(fd, buff, r_ret, 0); if (s_ret < 0) { perror("send"); continue; } else if (s_ret != r_ret) { fprintf(stderr, "Partial write: FIXME!\n"); abort(); } } Epoll::close(fd); return nullptr; } static void * echo_srv(void *arg) { int err, fd; struct url url; const char *url_str = (const char *)arg; struct addrinfo *ai_list, *ai_b; // initialize epoll and start poller Epoll::init(); T::spawn(Epoll::poller_task, nullptr, nullptr, true, TaskType::TASK); // bind and listen to URL given by the user err = url_parse(&url, url_str); if (err) { fprintf(stderr, "url_parse failed\n"); exit(1); } ai_list = url_getaddrinfo(&url, true); fd = ai_bind(ai_list, &ai_b); printf("listen to: %s\n", url_str); err = Epoll::listen(fd, 128); if (err == -1) { perror("listen failed"); exit(1); } struct sockaddr cli_addr; socklen_t cli_addr_len; while (true) { printf("accept\n"); int accept_fd = Epoll::accept(fd, &cli_addr, &cli_addr_len); printf("accept returned: %d\n", accept_fd); if (accept_fd == -1) { perror("accept"); } T::spawn(echo_task, (void *)(uintptr_t)accept_fd, nullptr, true, TaskType::TASK); } url_free_fields(&url); freeaddrinfo(ai_b); return nullptr; } int main(int argc, char *argv[]) { Controller c; const char server_url[] = "tcp://*:8000"; c.spawn_scheduler(echo_srv, (void *)server_url, TaskType::TASK); while (true) { sleep(10); } return 0; }
fizquierdo/opencga
opencga-analysis/src/main/java/org/opencb/opencga/analysis/variant/VariantStorageAnalysisExecutor.java
<gh_stars>0 package org.opencb.opencga.analysis.variant; import org.apache.commons.lang3.StringUtils; import org.opencb.commons.datastore.core.ObjectMap; import org.opencb.opencga.analysis.ConfigurationUtils; import org.opencb.opencga.core.exception.AnalysisExecutorException; import org.opencb.opencga.catalog.exceptions.CatalogException; import org.opencb.opencga.catalog.managers.CatalogManager; import org.opencb.opencga.core.config.Configuration; import org.opencb.opencga.storage.core.StorageEngineFactory; import org.opencb.opencga.storage.core.config.StorageConfiguration; import org.opencb.opencga.storage.core.exceptions.StorageEngineException; import org.opencb.opencga.storage.core.variant.VariantStorageEngine; import java.io.IOException; /** * Helper interface to be used by opencga local analysis executors. */ public interface VariantStorageAnalysisExecutor { ObjectMap getExecutorParams(); default VariantStorageManager getVariantStorageManager() throws AnalysisExecutorException { String opencgaHome = getExecutorParams().getString("opencgaHome"); try { Configuration configuration = ConfigurationUtils.loadConfiguration(opencgaHome); StorageConfiguration storageConfiguration = ConfigurationUtils.loadStorageConfiguration(opencgaHome); CatalogManager catalogManager = new CatalogManager(configuration); StorageEngineFactory engineFactory = StorageEngineFactory.get(storageConfiguration); return new VariantStorageManager(catalogManager, engineFactory); } catch (CatalogException | IOException e) { throw new AnalysisExecutorException(e); } } default VariantStorageEngine getVariantStorageEngine() throws AnalysisExecutorException { ObjectMap executorParams = getExecutorParams(); String storageEngine = executorParams.getString("storageEngineId"); String dbName = executorParams.getString("dbName"); if (StringUtils.isEmpty(storageEngine) || StringUtils.isEmpty(dbName)) { throw new AnalysisExecutorException("Missing arguments!"); } else { try { return StorageEngineFactory.get().getVariantStorageEngine(storageEngine, dbName); } catch (StorageEngineException e) { throw new AnalysisExecutorException(e); } } } }
phatblat/macOSPrivateFrameworks
PrivateFrameworks/StorageKit/SKRAIDDisk.h
<reponame>phatblat/macOSPrivateFrameworks<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 <StorageKit/SKDisk.h> @class NSArray, NSDictionary, NSString; @interface SKRAIDDisk : SKDisk { BOOL _isRAIDSet; NSString *_raidUUID; NSArray *_setMemberUUIDs; NSArray *_setSpareUUIDs; NSString *_status; NSDictionary *_contentDiskDictionary; } @property(retain) NSDictionary *contentDiskDictionary; // @synthesize contentDiskDictionary=_contentDiskDictionary; @property(retain) NSString *status; // @synthesize status=_status; @property(retain) NSArray *setSpareUUIDs; // @synthesize setSpareUUIDs=_setSpareUUIDs; @property(retain) NSArray *setMemberUUIDs; // @synthesize setMemberUUIDs=_setMemberUUIDs; @property BOOL isRAIDSet; // @synthesize isRAIDSet=_isRAIDSet; @property(retain) NSString *raidUUID; // @synthesize raidUUID=_raidUUID; - (void).cxx_destruct; - (void)deleteRAIDWithProgress:(CDUnknownBlockType)arg1 completionBlock:(CDUnknownBlockType)arg2; - (void)removeDiskFromRAID:(id)arg1 progress:(CDUnknownBlockType)arg2 completionBlock:(CDUnknownBlockType)arg3; - (void)repairRAIDWithDisk:(id)arg1 progress:(CDUnknownBlockType)arg2 completionBlock:(CDUnknownBlockType)arg3; - (void)addDisksToRAID:(id)arg1 withType:(id)arg2 progress:(CDUnknownBlockType)arg3 completionBlock:(CDUnknownBlockType)arg4; - (id)contentDiskIdentifier; @property(readonly, retain) SKDisk *contentDisk; - (BOOL)canResize; - (id)description; - (id)supportedFilesystems; - (BOOL)matchesDictionary:(id)arg1; - (unsigned long long)hash; - (BOOL)isEqual:(id)arg1; - (id)dictionaryRepresentation; - (id)minimalDictionaryRepresentation; - (void)updateWithDictionary:(id)arg1; @end
emanuelepaiano/jespresso-lite
src/main/java/io/github/emanuelepaiano/jespresso/include/unifi/dto/LoginDTO.java
package io.github.emanuelepaiano.jespresso.include.unifi.dto; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * The Class LoginDTO. */ @Data @NoArgsConstructor @AllArgsConstructor public class LoginDTO { /** The username. */ private String username; /** The password. */ private String password; }