code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
/* * Copyright (c) 2006-2018, RT-Thread Development Team * * SPDX-License-Identifier: Apache-2.0 * * Change Logs: * Date Author Notes * 2017-08-24 chinesebear first version */ #include <rtthread.h> #include <rtdef.h> //#include <lwip/pbuf.h> #include "synopGMAC.h" #include "mii.c" #include "synopGMAC_debug.h" #include <ls1c.h> #include "ls1c_pin.h" #define RMII #define Gmac_base 0xbfe10000 #define Buffer_Size 2048 #define MAX_ADDR_LEN 6 #define NAMESIZE 16 #define LS1B_GMAC0_IRQ 34 #define BUS_SIZE_ALIGN(x) ((x+15)&~15) #define DEFAULT_MAC_ADDRESS {0x00, 0x55, 0x7B, 0xB5, 0x7D, 0xF7} u32 regbase = 0xbfe10000; static u32 GMAC_Power_down; extern void *plat_alloc_consistent_dmaable_memory(synopGMACdevice *pcidev, u32 size, u32 *addr) ; extern s32 synopGMAC_check_phy_init(synopGMACPciNetworkAdapter *adapter) ; extern int init_phy(synopGMACdevice *gmacdev); dma_addr_t plat_dma_map_single(void *hwdev, void *ptr, u32 size); void eth_rx_irq(int irqno, void *param); static char Rx_Buffer[Buffer_Size]; static char Tx_Buffer[Buffer_Size]; struct rt_eth_dev { struct eth_device parent; rt_uint8_t dev_addr[MAX_ADDR_LEN]; char *name; int iobase; int state; int index; struct rt_timer link_timer; struct rt_timer rx_poll_timer; void *priv; }; static struct rt_eth_dev eth_dev; static struct rt_semaphore sem_ack, sem_lock; /** * This sets up the transmit Descriptor queue in ring or chain mode. * This function is tightly coupled to the platform and operating system * Device is interested only after the descriptors are setup. Therefore this function * is not included in the device driver API. This function should be treated as an * example code to design the descriptor structures for ring mode or chain mode. * This function depends on the pcidev structure for allocation consistent dma-able memory in case * of linux. * This limitation is due to the fact that linux uses pci structure to allocate a dmable memory * - Allocates the memory for the descriptors. * - Initialize the Busy and Next descriptors indices to 0(Indicating first descriptor). * - Initialize the Busy and Next descriptors to first descriptor address. * - Initialize the last descriptor with the endof ring in case of ring mode. * - Initialize the descriptors in chain mode. * @param[in] pointer to synopGMACdevice. * @param[in] pointer to pci_device structure. * @param[in] number of descriptor expected in tx descriptor queue. * @param[in] whether descriptors to be created in RING mode or CHAIN mode. * \return 0 upon success. Error code upon failure. * \note This function fails if allocation fails for required number of descriptors in Ring mode, * but in chain mode * function returns -ESYNOPGMACNOMEM in the process of descriptor chain creation. once returned from * this function * user should for gmacdev->TxDescCount to see how many descriptors are there in the chain. Should * continue further * only if the number of descriptors in the chain meets the requirements */ s32 synopGMAC_setup_tx_desc_queue(synopGMACdevice *gmacdev, u32 no_of_desc, u32 desc_mode) { s32 i; DmaDesc *bf1; DmaDesc *first_desc = NULL; dma_addr_t dma_addr; gmacdev->TxDescCount = 0; first_desc = (DmaDesc *)plat_alloc_consistent_dmaable_memory(gmacdev, sizeof(DmaDesc) * no_of_desc, &dma_addr); if (first_desc == NULL) { rt_kprintf("Error in Tx Descriptors memory allocation\n"); return -ESYNOPGMACNOMEM; } DEBUG_MES("tx_first_desc_addr = %p\n", first_desc); DEBUG_MES("dmaadr = %p\n", dma_addr); gmacdev->TxDescCount = no_of_desc; gmacdev->TxDesc = first_desc; gmacdev->TxDescDma = dma_addr; for (i = 0; i < gmacdev->TxDescCount; i++) { synopGMAC_tx_desc_init_ring(gmacdev->TxDesc + i, i == gmacdev->TxDescCount - 1); #if SYNOP_TOP_DEBUG rt_kprintf("\n%02d %08x \n", i, (unsigned int)(gmacdev->TxDesc + i)); rt_kprintf("%08x ", (unsigned int)((gmacdev->TxDesc + i))->status); rt_kprintf("%08x ", (unsigned int)((gmacdev->TxDesc + i)->length)); rt_kprintf("%08x ", (unsigned int)((gmacdev->TxDesc + i)->buffer1)); rt_kprintf("%08x ", (unsigned int)((gmacdev->TxDesc + i)->buffer2)); rt_kprintf("%08x ", (unsigned int)((gmacdev->TxDesc + i)->data1)); rt_kprintf("%08x ", (unsigned int)((gmacdev->TxDesc + i)->data2)); rt_kprintf("%08x ", (unsigned int)((gmacdev->TxDesc + i)->dummy1)); rt_kprintf("%08x ", (unsigned int)((gmacdev->TxDesc + i)->dummy2)); #endif } gmacdev->TxNext = 0; gmacdev->TxBusy = 0; gmacdev->TxNextDesc = gmacdev->TxDesc; gmacdev->TxBusyDesc = gmacdev->TxDesc; gmacdev->BusyTxDesc = 0; return -ESYNOPGMACNOERR; } /** * This sets up the receive Descriptor queue in ring or chain mode. * This function is tightly coupled to the platform and operating system * Device is interested only after the descriptors are setup. Therefore this function * is not included in the device driver API. This function should be treated as an * example code to design the descriptor structures in ring mode or chain mode. * This function depends on the pcidev structure for allocation of consistent dma-able memory in * case of linux. * This limitation is due to the fact that linux uses pci structure to allocate a dmable memory * - Allocates the memory for the descriptors. * - Initialize the Busy and Next descriptors indices to 0(Indicating first descriptor). * - Initialize the Busy and Next descriptors to first descriptor address. * - Initialize the last descriptor with the endof ring in case of ring mode. * - Initialize the descriptors in chain mode. * @param[in] pointer to synopGMACdevice. * @param[in] pointer to pci_device structure. * @param[in] number of descriptor expected in rx descriptor queue. * @param[in] whether descriptors to be created in RING mode or CHAIN mode. * \return 0 upon success. Error code upon failure. * \note This function fails if allocation fails for required number of descriptors in Ring mode, * but in chain mode * function returns -ESYNOPGMACNOMEM in the process of descriptor chain creation. once returned from * this function * user should for gmacdev->RxDescCount to see how many descriptors are there in the chain. Should * continue further * only if the number of descriptors in the chain meets the requirements */ s32 synopGMAC_setup_rx_desc_queue(synopGMACdevice *gmacdev, u32 no_of_desc, u32 desc_mode) { s32 i; DmaDesc *bf1; DmaDesc *first_desc = NULL; dma_addr_t dma_addr; gmacdev->RxDescCount = 0; first_desc = (DmaDesc *)plat_alloc_consistent_dmaable_memory(gmacdev, sizeof(DmaDesc) * no_of_desc, &dma_addr); if (first_desc == NULL) { rt_kprintf("Error in Rx Descriptor Memory allocation in Ring mode\n"); return -ESYNOPGMACNOMEM; } DEBUG_MES("rx_first_desc_addr = %p\n", first_desc); DEBUG_MES("dmaadr = %p\n", dma_addr); gmacdev->RxDescCount = no_of_desc; gmacdev->RxDesc = (DmaDesc *)first_desc; gmacdev->RxDescDma = dma_addr; for (i = 0; i < gmacdev->RxDescCount; i++) { synopGMAC_rx_desc_init_ring(gmacdev->RxDesc + i, i == gmacdev->RxDescCount - 1); } gmacdev->RxNext = 0; gmacdev->RxBusy = 0; gmacdev->RxNextDesc = gmacdev->RxDesc; gmacdev->RxBusyDesc = gmacdev->RxDesc; gmacdev->BusyRxDesc = 0; return -ESYNOPGMACNOERR; } void synopGMAC_linux_cable_unplug_function(void *adaptr) { s32 data; synopGMACPciNetworkAdapter *adapter = (synopGMACPciNetworkAdapter *)adaptr; synopGMACdevice *gmacdev = adapter->synopGMACdev; struct ethtool_cmd cmd; //rt_kprintf("%s\n",__FUNCTION__); if (!mii_link_ok(&adapter->mii)) { if (gmacdev->LinkState) rt_kprintf("\r\nNo Link\r\n"); gmacdev->DuplexMode = 0; gmacdev->Speed = 0; gmacdev->LoopBackMode = 0; gmacdev->LinkState = 0; } else { data = synopGMAC_check_phy_init(adapter); if (gmacdev->LinkState != data) { gmacdev->LinkState = data; synopGMAC_mac_init(gmacdev); rt_kprintf("Link is up in %s mode\n", (gmacdev->DuplexMode == FULLDUPLEX) ? "FULL DUPLEX" : "HALF DUPLEX"); if (gmacdev->Speed == SPEED1000) rt_kprintf("Link is with 1000M Speed \r\n"); if (gmacdev->Speed == SPEED100) rt_kprintf("Link is with 100M Speed \n"); if (gmacdev->Speed == SPEED10) rt_kprintf("Link is with 10M Speed \n"); } } } s32 synopGMAC_check_phy_init(synopGMACPciNetworkAdapter *adapter) { struct ethtool_cmd cmd; synopGMACdevice *gmacdev = adapter->synopGMACdev; if (!mii_link_ok(&adapter->mii)) { gmacdev->DuplexMode = FULLDUPLEX; gmacdev->Speed = SPEED100; return 0; } else { mii_ethtool_gset(&adapter->mii, &cmd); gmacdev->DuplexMode = (cmd.duplex == DUPLEX_FULL) ? FULLDUPLEX : HALFDUPLEX ; if (cmd.speed == SPEED_1000) gmacdev->Speed = SPEED1000; else if (cmd.speed == SPEED_100) gmacdev->Speed = SPEED100; else gmacdev->Speed = SPEED10; } return gmacdev->Speed | (gmacdev->DuplexMode << 4); } static int Mac_change_check(u8 *macaddr0, u8 *macaddr1) { int i; for (i = 0; i < 6; i++) { if (macaddr0[i] != macaddr1[i]) return 1; } return 0; } static rt_err_t eth_init(rt_device_t device) { struct eth_device *eth_device = (struct eth_device *)device; RT_ASSERT(eth_device != RT_NULL); s32 ijk; s32 status = 0; u64 dma_addr; u32 Mac_changed = 0; struct pbuf *pbuf; u8 macaddr[6] = DEFAULT_MAC_ADDRESS; struct rt_eth_dev *dev = &eth_dev; struct synopGMACNetworkAdapter *adapter = dev->priv; synopGMACdevice *gmacdev = (synopGMACdevice *)adapter->synopGMACdev; synopGMAC_reset(gmacdev); synopGMAC_attach(gmacdev, (regbase + MACBASE), (regbase + DMABASE), DEFAULT_PHY_BASE, macaddr); synopGMAC_read_version(gmacdev); synopGMAC_set_mdc_clk_div(gmacdev, GmiiCsrClk3); gmacdev->ClockDivMdc = synopGMAC_get_mdc_clk_div(gmacdev); init_phy(adapter->synopGMACdev); DEBUG_MES("tx desc_queue\n"); synopGMAC_setup_tx_desc_queue(gmacdev, TRANSMIT_DESC_SIZE, RINGMODE); synopGMAC_init_tx_desc_base(gmacdev); DEBUG_MES("rx desc_queue\n"); synopGMAC_setup_rx_desc_queue(gmacdev, RECEIVE_DESC_SIZE, RINGMODE); synopGMAC_init_rx_desc_base(gmacdev); DEBUG_MES("DmaRxBaseAddr = %08x\n", synopGMACReadReg(gmacdev->DmaBase, DmaRxBaseAddr)); // u32 dmaRx_Base_addr = synopGMACReadReg(gmacdev->DmaBase,DmaRxBaseAddr); // rt_kprintf("first_desc_addr = 0x%x\n", dmaRx_Base_addr); #ifdef ENH_DESC_8W synopGMAC_dma_bus_mode_init(gmacdev, DmaBurstLength32 | DmaDescriptorSkip2 | DmaDescriptor8Words); #else //synopGMAC_dma_bus_mode_init(gmacdev, DmaBurstLength4 | DmaDescriptorSkip1); synopGMAC_dma_bus_mode_init(gmacdev, DmaBurstLength4 | DmaDescriptorSkip2); #endif synopGMAC_dma_control_init(gmacdev, DmaStoreAndForward | DmaTxSecondFrame | DmaRxThreshCtrl128); status = synopGMAC_check_phy_init(adapter); synopGMAC_mac_init(gmacdev); synopGMAC_pause_control(gmacdev); #ifdef IPC_OFFLOAD synopGMAC_enable_rx_chksum_offload(gmacdev); synopGMAC_rx_tcpip_chksum_drop_enable(gmacdev); #endif u32 skb; do { skb = (u32)plat_alloc_memory(RX_BUF_SIZE); //should skb aligned here? if (skb == RT_NULL) { rt_kprintf("ERROR in skb buffer allocation\n"); break; } dma_addr = plat_dma_map_single(gmacdev, (void *)skb, RX_BUF_SIZE); //获取 skb 的 dma 地址 status = synopGMAC_set_rx_qptr(gmacdev, dma_addr, RX_BUF_SIZE, (u32)skb, 0, 0, 0); if (status < 0) { rt_kprintf("status < 0!!\n"); plat_free_memory((void *)skb); } } while (status >= 0 && (status < (RECEIVE_DESC_SIZE - 1))); synopGMAC_clear_interrupt(gmacdev); synopGMAC_disable_mmc_tx_interrupt(gmacdev, 0xFFFFFFFF); synopGMAC_disable_mmc_rx_interrupt(gmacdev, 0xFFFFFFFF); synopGMAC_disable_mmc_ipc_rx_interrupt(gmacdev, 0xFFFFFFFF); // synopGMAC_disable_interrupt_all(gmacdev); synopGMAC_enable_interrupt(gmacdev, DmaIntEnable); synopGMAC_enable_dma_rx(gmacdev); synopGMAC_enable_dma_tx(gmacdev); plat_delay(DEFAULT_LOOP_VARIABLE); synopGMAC_check_phy_init(adapter); synopGMAC_mac_init(gmacdev); rt_timer_init(&dev->link_timer, "link_timer", synopGMAC_linux_cable_unplug_function, (void *)adapter, RT_TICK_PER_SECOND, RT_TIMER_FLAG_PERIODIC); rt_timer_start(&dev->link_timer); #ifdef RT_USING_GMAC_INT_MODE /* installl isr */ DEBUG_MES("%s\n", __FUNCTION__); rt_hw_interrupt_install(LS1C_MAC_IRQ, eth_rx_irq, RT_NULL, "e0_isr"); rt_hw_interrupt_umask(LS1C_MAC_IRQ); #else rt_timer_init(&dev->rx_poll_timer, "rx_poll_timer", eth_rx_irq, (void *)adapter, 1, RT_TIMER_FLAG_PERIODIC); rt_timer_start(&dev->rx_poll_timer); #endif /*RT_USING_GMAC_INT_MODE*/ rt_kprintf("eth_inited!\n"); return RT_EOK; } static rt_err_t eth_open(rt_device_t dev, rt_uint16_t oflag) { rt_kprintf("eth_open!!\n"); return RT_EOK; } static rt_err_t eth_close(rt_device_t dev) { return RT_EOK; } static rt_size_t eth_read(rt_device_t dev, rt_off_t pos, void *buffer, rt_size_t size) { rt_set_errno(-RT_ENOSYS); return 0; } static rt_size_t eth_write(rt_device_t dev, rt_off_t pos, const void *buffer, rt_size_t size) { rt_set_errno(-RT_ENOSYS); return 0; } static rt_err_t eth_control(rt_device_t dev, int cmd, void *args) { switch (cmd) { case NIOCTL_GADDR: if (args) rt_memcpy(args, eth_dev.dev_addr, 6); else return -RT_ERROR; break; default : break; } return RT_EOK; } rt_err_t rt_eth_tx(rt_device_t device, struct pbuf *p) { /* lock eth device */ rt_sem_take(&sem_lock, RT_WAITING_FOREVER); DEBUG_MES("in %s\n", __FUNCTION__); s32 status; u32 pbuf; u64 dma_addr; u32 offload_needed = 0; u32 index; DmaDesc *dpr; struct rt_eth_dev *dev = (struct rt_eth_dev *) device; struct synopGMACNetworkAdapter *adapter; synopGMACdevice *gmacdev; adapter = (struct synopGMACNetworkAdapter *) dev->priv; if (adapter == NULL) return -1; gmacdev = (synopGMACdevice *) adapter->synopGMACdev; if (gmacdev == NULL) return -1; if (!synopGMAC_is_desc_owned_by_dma(gmacdev->TxNextDesc)) { pbuf = (u32)plat_alloc_memory(p->tot_len); //pbuf = (u32)pbuf_alloc(PBUF_LINK, p->len, PBUF_RAM); if (pbuf == 0) { rt_kprintf("===error in alloc bf1\n"); return -1; } DEBUG_MES("p->len = %d\n", p->len); pbuf_copy_partial(p, (void *)pbuf, p->tot_len, 0); dma_addr = plat_dma_map_single(gmacdev, (void *)pbuf, p->tot_len); status = synopGMAC_set_tx_qptr(gmacdev, dma_addr, p->tot_len, pbuf, 0, 0, 0, offload_needed, &index, dpr); if (status < 0) { rt_kprintf("%s No More Free Tx Descriptors\n", __FUNCTION__); plat_free_memory((void *)pbuf); return -16; } } synopGMAC_resume_dma_tx(gmacdev); s32 desc_index; u32 data1, data2; u32 dma_addr1, dma_addr2; u32 length1, length2; #ifdef ENH_DESC_8W u32 ext_status; u16 time_stamp_higher; u32 time_stamp_high; u32 time_stamp_low; #endif do { #ifdef ENH_DESC_8W desc_index = synopGMAC_get_tx_qptr(gmacdev, &status, &dma_addr1, &length1, &data1, &dma_addr2, &length2, &data2, &ext_status, &time_stamp_high, &time_stamp_low); synopGMAC_TS_read_timestamp_higher_val(gmacdev, &time_stamp_higher); #else desc_index = synopGMAC_get_tx_qptr(gmacdev, &status, &dma_addr1, &length1, &data1, &dma_addr2, &length2, &data2); #endif if (desc_index >= 0 && data1 != 0) { #ifdef IPC_OFFLOAD if (synopGMAC_is_tx_ipv4header_checksum_error(gmacdev, status)) { rt_kprintf("Harware Failed to Insert IPV4 Header Checksum\n"); } if (synopGMAC_is_tx_payload_checksum_error(gmacdev, status)) { rt_kprintf("Harware Failed to Insert Payload Checksum\n"); } #endif plat_free_memory((void *)(data1)); //sw: data1 = buffer1 if (synopGMAC_is_desc_valid(status)) { adapter->synopGMACNetStats.tx_bytes += length1; adapter->synopGMACNetStats.tx_packets++; } else { adapter->synopGMACNetStats.tx_errors++; adapter->synopGMACNetStats.tx_aborted_errors += synopGMAC_is_tx_aborted(status); adapter->synopGMACNetStats.tx_carrier_errors += synopGMAC_is_tx_carrier_error(status); } } adapter->synopGMACNetStats.collisions += synopGMAC_get_tx_collision_count(status); } while (desc_index >= 0); /* unlock eth device */ rt_sem_release(&sem_lock); // rt_kprintf("output %d bytes\n", p->len); u32 test_data; test_data = synopGMACReadReg(gmacdev->DmaBase, DmaStatus); return RT_EOK; } struct pbuf *rt_eth_rx(rt_device_t device) { DEBUG_MES("%s : \n", __FUNCTION__); struct rt_eth_dev *dev = &eth_dev; struct synopGMACNetworkAdapter *adapter; synopGMACdevice *gmacdev; // struct PmonInet * pinetdev; s32 desc_index; int i; char *ptr; u32 bf1; u32 data1; u32 data2; u32 len; u32 status; u32 dma_addr1; u32 dma_addr2; struct pbuf *pbuf = RT_NULL; rt_sem_take(&sem_lock, RT_WAITING_FOREVER); adapter = (struct synopGMACNetworkAdapter *) dev->priv; if (adapter == NULL) { rt_kprintf("%S : Unknown Device !!\n", __FUNCTION__); return NULL; } gmacdev = (synopGMACdevice *) adapter->synopGMACdev; if (gmacdev == NULL) { rt_kprintf("%s : GMAC device structure is missing\n", __FUNCTION__); return NULL; } /*Handle the Receive Descriptors*/ // do{ desc_index = synopGMAC_get_rx_qptr(gmacdev, &status, &dma_addr1, NULL, &data1, &dma_addr2, NULL, &data2); if (desc_index >= 0 && data1 != 0) { DEBUG_MES("Received Data at Rx Descriptor %d for skb 0x%08x whose status is %08x\n", desc_index, dma_addr1, status); if (synopGMAC_is_rx_desc_valid(status) || SYNOP_PHY_LOOPBACK) { pbuf = pbuf_alloc(PBUF_LINK, MAX_ETHERNET_PAYLOAD, PBUF_RAM); if (pbuf == 0) rt_kprintf("===error in pbuf_alloc\n"); dma_addr1 = plat_dma_map_single(gmacdev, (void *)data1, RX_BUF_SIZE); len = synopGMAC_get_rx_desc_frame_length(status); //Not interested in Ethernet CRC bytes rt_memcpy(pbuf->payload, (char *)data1, len); DEBUG_MES("==get pkg len: %d\n", len); } else { rt_kprintf("s: %08x\n", status); adapter->synopGMACNetStats.rx_errors++; adapter->synopGMACNetStats.collisions += synopGMAC_is_rx_frame_collision(status); adapter->synopGMACNetStats.rx_crc_errors += synopGMAC_is_rx_crc(status); adapter->synopGMACNetStats.rx_frame_errors += synopGMAC_is_frame_dribbling_errors(status); adapter->synopGMACNetStats.rx_length_errors += synopGMAC_is_rx_frame_length_errors(status); } desc_index = synopGMAC_set_rx_qptr(gmacdev, dma_addr1, RX_BUF_SIZE, (u32)data1, 0, 0, 0); if (desc_index < 0) { #if SYNOP_RX_DEBUG rt_kprintf("Cannot set Rx Descriptor for data1 %08x\n", (u32)data1); #endif plat_free_memory((void *)data1); } } // }while(desc_index >= 0); rt_sem_release(&sem_lock); DEBUG_MES("%s : before return \n", __FUNCTION__); return pbuf; } static int rtl88e1111_config_init(synopGMACdevice *gmacdev) { int retval, err; u16 data; DEBUG_MES("in %s\n", __FUNCTION__); synopGMAC_read_phy_reg(gmacdev->MacBase, gmacdev->PhyBase, 0x14, &data); data = data | 0x82; err = synopGMAC_write_phy_reg(gmacdev->MacBase, gmacdev->PhyBase, 0x14, data); synopGMAC_read_phy_reg(gmacdev->MacBase, gmacdev->PhyBase, 0x00, &data); data = data | 0x8000; err = synopGMAC_write_phy_reg(gmacdev->MacBase, gmacdev->PhyBase, 0x00, data); #if SYNOP_PHY_LOOPBACK synopGMAC_read_phy_reg(gmacdev->MacBase, gmacdev->PhyBase, 0x14, &data); data = data | 0x70; data = data & 0xffdf; err = synopGMAC_write_phy_reg(gmacdev->MacBase, gmacdev->PhyBase, 0x14, data); data = 0x8000; err = synopGMAC_write_phy_reg(gmacdev->MacBase, gmacdev->PhyBase, 0x00, data); data = 0x5140; err = synopGMAC_write_phy_reg(gmacdev->MacBase, gmacdev->PhyBase, 0x00, data); #endif if (err < 0) return err; return 0; } int init_phy(synopGMACdevice *gmacdev) { u16 data; synopGMAC_read_phy_reg(gmacdev->MacBase, gmacdev->PhyBase, 2, &data); /*set 88e1111 clock phase delay*/ if (data == 0x141) rtl88e1111_config_init(gmacdev); #if defined (RMII) else if (data == 0x8201) { //RTL8201 data = 0x400; // set RMII mode synopGMAC_write_phy_reg(gmacdev->MacBase, gmacdev->PhyBase, 0x19, data); synopGMAC_read_phy_reg(gmacdev->MacBase, gmacdev->PhyBase, 0x19, &data); TR("phy reg25 is %0x \n", data); data = 0x3100; //set 100M speed synopGMAC_write_phy_reg(gmacdev->MacBase, gmacdev->PhyBase, 0x0, data); } else if (data == 0x0180 || data == 0x0181) { //DM9161 synopGMAC_read_phy_reg(gmacdev->MacBase, gmacdev->PhyBase, 0x10, &data); data |= (1 << 8); //set RMII mode synopGMAC_write_phy_reg(gmacdev->MacBase, gmacdev->PhyBase, 0x10, data); //set RMII mode synopGMAC_read_phy_reg(gmacdev->MacBase, gmacdev->PhyBase, 0x10, &data); TR("phy reg16 is 0x%0x \n", data); // synopGMAC_read_phy_reg(gmacdev->MacBase,gmacdev->PhyBase,0x0,&data); // data &= ~(1<<10); data = 0x3100; //set auto- //data = 0x0100; //set 10M speed synopGMAC_write_phy_reg(gmacdev->MacBase, gmacdev->PhyBase, 0x0, data); } #endif return 0; } u32 synopGMAC_wakeup_filter_config3[] = { 0x00000000, 0x000000FF, 0x00000000, 0x00000000, 0x00000100, 0x00003200, 0x7eED0000, 0x00000000 }; static void synopGMAC_linux_powerdown_mac(synopGMACdevice *gmacdev) { rt_kprintf("Put the GMAC to power down mode..\n"); GMAC_Power_down = 1; synopGMAC_disable_dma_tx(gmacdev); plat_delay(10000); synopGMAC_tx_disable(gmacdev); synopGMAC_rx_disable(gmacdev); plat_delay(10000); synopGMAC_disable_dma_rx(gmacdev); synopGMAC_magic_packet_enable(gmacdev); synopGMAC_write_wakeup_frame_register(gmacdev, synopGMAC_wakeup_filter_config3); synopGMAC_wakeup_frame_enable(gmacdev); synopGMAC_rx_enable(gmacdev); synopGMAC_pmt_int_enable(gmacdev); synopGMAC_power_down_enable(gmacdev); return; } static void synopGMAC_linux_powerup_mac(synopGMACdevice *gmacdev) { GMAC_Power_down = 0; if (synopGMAC_is_magic_packet_received(gmacdev)) rt_kprintf("GMAC wokeup due to Magic Pkt Received\n"); if (synopGMAC_is_wakeup_frame_received(gmacdev)) rt_kprintf("GMAC wokeup due to Wakeup Frame Received\n"); synopGMAC_pmt_int_disable(gmacdev); synopGMAC_rx_enable(gmacdev); synopGMAC_enable_dma_rx(gmacdev); synopGMAC_tx_enable(gmacdev); synopGMAC_enable_dma_tx(gmacdev); return; } static int mdio_read(synopGMACPciNetworkAdapter *adapter, int addr, int reg) { synopGMACdevice *gmacdev; u16 data; gmacdev = adapter->synopGMACdev; synopGMAC_read_phy_reg(gmacdev->MacBase, addr, reg, &data); return data; } static void mdio_write(synopGMACPciNetworkAdapter *adapter, int addr, int reg, int data) { synopGMACdevice *gmacdev; gmacdev = adapter->synopGMACdev; synopGMAC_write_phy_reg(gmacdev->MacBase, addr, reg, data); } void eth_rx_irq(int irqno, void *param) { struct rt_eth_dev *dev = &eth_dev; struct synopGMACNetworkAdapter *adapter = dev->priv; //DEBUG_MES("in irq!!\n"); #ifdef RT_USING_GMAC_INT_MODE int i ; for (i = 0; i < 7200; i++) ; #endif /*RT_USING_GMAC_INT_MODE*/ synopGMACdevice *gmacdev = (synopGMACdevice *)adapter->synopGMACdev; u32 interrupt, dma_status_reg; s32 status; u32 dma_addr; //rt_kprintf("irq i = %d\n", i++); dma_status_reg = synopGMACReadReg(gmacdev->DmaBase, DmaStatus); if (dma_status_reg == 0) { rt_kprintf("dma_status ==0 \n"); return; } //rt_kprintf("dma_status_reg is 0x%x\n", dma_status_reg); u32 gmacstatus; synopGMAC_disable_interrupt_all(gmacdev); gmacstatus = synopGMACReadReg(gmacdev->MacBase, GmacStatus); if (dma_status_reg & GmacPmtIntr) { rt_kprintf("%s:: Interrupt due to PMT module\n", __FUNCTION__); //synopGMAC_linux_powerup_mac(gmacdev); } if (dma_status_reg & GmacMmcIntr) { rt_kprintf("%s:: Interrupt due to MMC module\n", __FUNCTION__); DEBUG_MES("%s:: synopGMAC_rx_int_status = %08x\n", __FUNCTION__, synopGMAC_read_mmc_rx_int_status(gmacdev)); DEBUG_MES("%s:: synopGMAC_tx_int_status = %08x\n", __FUNCTION__, synopGMAC_read_mmc_tx_int_status(gmacdev)); } if (dma_status_reg & GmacLineIntfIntr) { rt_kprintf("%s:: Interrupt due to GMAC LINE module\n", __FUNCTION__); } interrupt = synopGMAC_get_interrupt_type(gmacdev); //rt_kprintf("%s:Interrupts to be handled: 0x%08x\n",__FUNCTION__,interrupt); if (interrupt & synopGMACDmaError) { u8 mac_addr0[6]; rt_kprintf("%s::Fatal Bus Error Inetrrupt Seen\n", __FUNCTION__); memcpy(mac_addr0, dev->dev_addr, 6); synopGMAC_disable_dma_tx(gmacdev); synopGMAC_disable_dma_rx(gmacdev); synopGMAC_take_desc_ownership_tx(gmacdev); synopGMAC_take_desc_ownership_rx(gmacdev); synopGMAC_init_tx_rx_desc_queue(gmacdev); synopGMAC_reset(gmacdev); synopGMAC_set_mac_addr(gmacdev, GmacAddr0High, GmacAddr0Low, mac_addr0); synopGMAC_dma_bus_mode_init(gmacdev, DmaFixedBurstEnable | DmaBurstLength8 | DmaDescriptorSkip2); synopGMAC_dma_control_init(gmacdev, DmaStoreAndForward); synopGMAC_init_rx_desc_base(gmacdev); synopGMAC_init_tx_desc_base(gmacdev); synopGMAC_mac_init(gmacdev); synopGMAC_enable_dma_rx(gmacdev); synopGMAC_enable_dma_tx(gmacdev); } if (interrupt & synopGMACDmaRxNormal) { //DEBUG_MES("%s:: Rx Normal \n", __FUNCTION__); //synop_handle_received_data(netdev); eth_device_ready(&eth_dev.parent); } if (interrupt & synopGMACDmaRxAbnormal) { //rt_kprintf("%s::Abnormal Rx Interrupt Seen\n",__FUNCTION__); if (GMAC_Power_down == 0) { adapter->synopGMACNetStats.rx_over_errors++; synopGMACWriteReg(gmacdev->DmaBase, DmaStatus, 0x80); synopGMAC_resume_dma_rx(gmacdev); } } if (interrupt & synopGMACDmaRxStopped) { rt_kprintf("%s::Receiver stopped seeing Rx interrupts\n", __FUNCTION__); //Receiver gone in to stopped state } if (interrupt & synopGMACDmaTxNormal) { DEBUG_MES("%s::Finished Normal Transmission \n", __FUNCTION__); // synop_handle_transmit_over(netdev); } if (interrupt & synopGMACDmaTxAbnormal) { rt_kprintf("%s::Abnormal Tx Interrupt Seen\n", __FUNCTION__); } if (interrupt & synopGMACDmaTxStopped) { TR("%s::Transmitter stopped sending the packets\n", __FUNCTION__); if (GMAC_Power_down == 0) // If Mac is not in powerdown { synopGMAC_disable_dma_tx(gmacdev); synopGMAC_take_desc_ownership_tx(gmacdev); synopGMAC_enable_dma_tx(gmacdev); // netif_wake_queue(netdev); TR("%s::Transmission Resumed\n", __FUNCTION__); } } /* Enable the interrrupt before returning from ISR*/ synopGMAC_enable_interrupt(gmacdev, DmaIntEnable); return; } int rt_hw_eth_init(void) { u64 base_addr = Gmac_base; struct synopGMACNetworkAdapter *synopGMACadapter; static u8 mac_addr0[6] = DEFAULT_MAC_ADDRESS; int index; rt_sem_init(&sem_ack, "tx_ack", 1, RT_IPC_FLAG_FIFO); rt_sem_init(&sem_lock, "eth_lock", 1, RT_IPC_FLAG_FIFO); for (index = 21; index <= 30; index++) { pin_set_purpose(index, PIN_PURPOSE_OTHER); pin_set_remap(index, PIN_REMAP_DEFAULT); } pin_set_purpose(35, PIN_PURPOSE_OTHER); pin_set_remap(35, PIN_REMAP_DEFAULT); *((volatile unsigned int *)0xbfd00424) &= ~(7 << 28); *((volatile unsigned int *)0xbfd00424) |= (1 << 30); //wl rmii memset(&eth_dev, 0, sizeof(eth_dev)); synopGMACadapter = (struct synopGMACNetworkAdapter *)plat_alloc_memory(sizeof(struct synopGMACNetworkAdapter)); if (!synopGMACadapter) { rt_kprintf("Error in Memory Allocataion, Founction : %s \n", __FUNCTION__); } memset((char *)synopGMACadapter, 0, sizeof(struct synopGMACNetworkAdapter)); synopGMACadapter->synopGMACdev = NULL; synopGMACadapter->synopGMACdev = (synopGMACdevice *) plat_alloc_memory(sizeof(synopGMACdevice)); if (!synopGMACadapter->synopGMACdev) { rt_kprintf("Error in Memory Allocataion, Founction : %s \n", __FUNCTION__); } memset((char *)synopGMACadapter->synopGMACdev, 0, sizeof(synopGMACdevice)); /* * Attach the device to MAC struct This will configure all the required base addresses * such as Mac base, configuration base, phy base address(out of 32 possible phys) * */ synopGMAC_attach(synopGMACadapter->synopGMACdev, (regbase + MACBASE), regbase + DMABASE, DEFAULT_PHY_BASE, mac_addr0); init_phy(synopGMACadapter->synopGMACdev); synopGMAC_reset(synopGMACadapter->synopGMACdev); /* MII setup */ synopGMACadapter->mii.phy_id_mask = 0x1F; synopGMACadapter->mii.reg_num_mask = 0x1F; synopGMACadapter->mii.dev = synopGMACadapter; synopGMACadapter->mii.mdio_read = mdio_read; synopGMACadapter->mii.mdio_write = mdio_write; synopGMACadapter->mii.phy_id = synopGMACadapter->synopGMACdev->PhyBase; synopGMACadapter->mii.supports_gmii = mii_check_gmii_support(&synopGMACadapter->mii); eth_dev.iobase = base_addr; eth_dev.name = "e0"; eth_dev.priv = synopGMACadapter; eth_dev.dev_addr[0] = mac_addr0[0]; eth_dev.dev_addr[1] = mac_addr0[1]; eth_dev.dev_addr[2] = mac_addr0[2]; eth_dev.dev_addr[3] = mac_addr0[3]; eth_dev.dev_addr[4] = mac_addr0[4]; eth_dev.dev_addr[5] = mac_addr0[5]; eth_dev.parent.parent.type = RT_Device_Class_NetIf; eth_dev.parent.parent.init = eth_init; eth_dev.parent.parent.open = eth_open; eth_dev.parent.parent.close = eth_close; eth_dev.parent.parent.read = eth_read; eth_dev.parent.parent.write = eth_write; eth_dev.parent.parent.control = eth_control; eth_dev.parent.parent.user_data = RT_NULL; eth_dev.parent.eth_tx = rt_eth_tx; eth_dev.parent.eth_rx = rt_eth_rx; eth_device_init(&(eth_dev.parent), "e0"); return 0; } INIT_DEVICE_EXPORT(rt_hw_eth_init);
wolfgangz2013/rt-thread
bsp/ls1cdev/drivers/net/synopGMAC.c
C
apache-2.0
32,096
/* Your use of this file is governed by the Microsoft Services Agreement http://go.microsoft.com/fwlink/?LinkId=266419. */ OSF.OUtil.setNamespace("XLS", OSF.DDA); OSF.OUtil.augmentList(Microsoft.Office.WebExtension.FilterType, { OnlyVisible: "onlyVisible" }); OSF.OUtil.augmentList(Microsoft.Office.WebExtension.EventType, { SettingsChanged: "settingsChanged" }); OSF.DDA.XLS.UniqueArguments={ Data: "Data", Properties : "Properties", BindingRequest: "DdaBindingsMethod", BindingResponse: "Bindings", SingleBindingResponse: "singleBindingResponse", GetData: "DdaGetBindingData", AddRowsColumns: "DdaAddRowsColumns", SetData: "DdaSetBindingData", SettingsRequest: "DdaSettingsMethod", BindingEventSource: "ddaBinding" }; OSF.DDA.XLS.SettingsTranslator=(function () { var keyIndex=0; var valueIndex=1; return { read: function OSF_DDA_XLS_SettingsTranslator$read(payload) { var serializedSettings={}; var settingsPayload=payload.Settings; for (var index in settingsPayload) { var setting=settingsPayload[index]; serializedSettings[setting[keyIndex]]=setting[valueIndex]; } return serializedSettings; }, write: function OSF_DDA_XLS_SettingsTranslator$write(serializedSettings) { var settingsPayload=[]; for (var key in serializedSettings) { var setting=[]; setting[keyIndex]=key; setting[valueIndex]=serializedSettings[key]; settingsPayload.push(setting); } return settingsPayload; } } })(); OSF.OUtil.setNamespace("Delegate", OSF.DDA.XLS); OSF.DDA.DispIdHost.getXLSDelegateMethods=function OSF_DDA_DispIdHost_getXLSDelegateMethods() { var delegateMethods={}; delegateMethods[OSF.DDA.DispIdHost.Delegates.ExecuteAsync]=OSF.DDA.XLS.Delegate.executeAsync; delegateMethods[OSF.DDA.DispIdHost.Delegates.RegisterEventAsync]=OSF.DDA.XLS.Delegate.registerEventAsync; delegateMethods[OSF.DDA.DispIdHost.Delegates.UnregisterEventAsync]=OSF.DDA.XLS.Delegate.unregisterEventAsync; return delegateMethods; }; OSF.DDA.XLS.Delegate.SpecialProcessor=function OSF_DDA_XLS_Delegate_SpecialProcessor() { var complexTypes=[ OSF.DDA.PropertyDescriptors.BindingProperties, OSF.DDA.XLS.UniqueArguments.SingleBindingResponse, OSF.DDA.XLS.UniqueArguments.BindingRequest, OSF.DDA.XLS.UniqueArguments.BindingResponse, OSF.DDA.XLS.UniqueArguments.GetData, OSF.DDA.XLS.UniqueArguments.AddRowsColumns, OSF.DDA.XLS.UniqueArguments.SetData, OSF.DDA.XLS.UniqueArguments.SettingsRequest, OSF.DDA.XLS.UniqueArguments.BindingEventSource, OSF.DDA.EventDescriptors.BindingSelectionChangedEvent ]; var dynamicTypes={}; dynamicTypes[Microsoft.Office.WebExtension.Parameters.Data]=(function () { var tableRows="Rows"; var tableHeaders="Headers"; return { toHost: function OSF_DDA_XLS_Delegate_SpecialProcessor_Data$toHost(data) { if (typeof data !="string" && data[OSF.DDA.TableDataProperties.TableRows] !==undefined) { var tableData={}; tableData[tableRows]=data[OSF.DDA.TableDataProperties.TableRows]; tableData[tableHeaders]=data[OSF.DDA.TableDataProperties.TableHeaders]; data=tableData; } else if (OSF.DDA.DataCoercion.determineCoercionType(data)==Microsoft.Office.WebExtension.CoercionType.Text) { data=[[data]]; } return data; }, fromHost: function OSF_DDA_XLS_Delegate_SpecialProcessor_Data$fromHost(hostArgs) { var ret; if (hostArgs[tableRows] !=undefined) { ret={}; ret[OSF.DDA.TableDataProperties.TableRows]=hostArgs[tableRows]; ret[OSF.DDA.TableDataProperties.TableHeaders]=hostArgs[tableHeaders]; } else { ret=hostArgs; } return ret; } } })(); dynamicTypes[OSF.DDA.SettingsManager.SerializedSettings]={ toHost: OSF.DDA.XLS.SettingsTranslator.write, fromHost: OSF.DDA.XLS.SettingsTranslator.read }; OSF.DDA.XLS.Delegate.SpecialProcessor.uber.constructor.call(this, complexTypes, dynamicTypes); this.pack=function OSF_DDA_XLS_Delegate_SpecialProcessor$pack(param, arg) { var value; if (this.isDynamicType(param)) { value=dynamicTypes[param].toHost(arg); } else { value=arg; } return value; }; this.unpack=function OSF_DDA_XLS_Delegate_SpecialProcessor$unpack(param, arg) { var value; if (this.isDynamicType(param)) { value=dynamicTypes[param].fromHost(arg); } else { value=arg; } return value; }; }; OSF.OUtil.extend(OSF.DDA.XLS.Delegate.SpecialProcessor, OSF.DDA.SpecialProcessor); OSF.DDA.XLS.Delegate.ParameterMap=(function () { var parameterMap=new OSF.DDA.HostParameterMap(new OSF.DDA.XLS.Delegate.SpecialProcessor()); var ns; var self=parameterMap.self; function createObject(properties) { var obj=null; if (properties) { obj={}; var len=properties.length; for (var i=0; i < len; i++) { obj[properties[i].name]=properties[i].value; } } return obj; } function define(definition) { var args={}; var toHost=createObject(definition.toHost); if (definition.invertible) { args.map=toHost; } else if (definition.canonical) { args.toHost=args.fromHost=toHost; } else { args.toHost=toHost; args.fromHost=createObject(definition.fromHost); } parameterMap.setMapping(definition.type, args); } ns=Microsoft.Office.WebExtension.Parameters; define({ type: OSF.DDA.XLS.UniqueArguments.BindingRequest, toHost: [ { name: ns.ItemName, value: "ItemName" }, { name: ns.Id, value: "BindingId" }, { name: ns.BindingType, value: "BindingType" }, { name: ns.PromptText, value: "PromptText" }, { name: ns.FailOnCollision, value: "FailOnCollision" } ] }); define({ type: OSF.DDA.XLS.UniqueArguments.GetData, toHost: [ { name: ns.Id, value: "BindingId" }, { name: ns.CoercionType, value: "CoerceType" }, { name: ns.ValueFormat, value: "ValueFormat" }, { name: ns.FilterType, value: "FilterType" }, { name: ns.StartRow, value: "StartRow" }, { name: ns.StartColumn, value: "StartCol" }, { name: ns.RowCount, value: "RowCount" }, { name: ns.ColumnCount, value: "ColCount" } ] }); define({ type: OSF.DDA.XLS.UniqueArguments.SetData, toHost: [ { name: ns.Id, value: "BindingId" }, { name: ns.CoercionType, value: "CoerceType" }, { name: ns.Data, value: OSF.DDA.XLS.UniqueArguments.Data }, { name: ns.StartRow, value: "StartRow" }, { name: ns.StartColumn, value: "StartCol" } ] }); define({ type: OSF.DDA.XLS.UniqueArguments.AddRowsColumns, toHost: [ { name: ns.Id, value: "BindingId" }, { name: ns.Data, value: OSF.DDA.XLS.UniqueArguments.Data } ] }); define({ type: OSF.DDA.XLS.UniqueArguments.SettingsRequest, toHost: [ { name: ns.OverwriteIfStale, value: "OverwriteIfStale" }, { name: OSF.DDA.SettingsManager.SerializedSettings, value: OSF.DDA.XLS.UniqueArguments.Properties } ], invertible: true }); ns=Microsoft.Office.WebExtension.BindingType; define({ type: Microsoft.Office.WebExtension.Parameters.BindingType, toHost: [ { name: ns.Text, value: 2 }, { name: ns.Matrix, value: 3 }, { name: ns.Table, value: 1 } ], invertible: true }); ns=OSF.DDA.BindingProperties; define({ type: OSF.DDA.PropertyDescriptors.BindingProperties, fromHost: [ { name: ns.Id, value: "Name" }, { name: ns.Type, value: "BindingType" }, { name: ns.RowCount, value: "RowCount" }, { name: ns.ColumnCount, value: "ColCount" }, { name: ns.HasHeaders, value: "HasHeaders" } ] }); define({ type: OSF.DDA.XLS.UniqueArguments.SingleBindingResponse, fromHost: [ { name: OSF.DDA.PropertyDescriptors.BindingProperties, value: 0 } ] }); define({ type: OSF.DDA.PropertyDescriptors.Subset, fromHost: [ { name: ns.StartRow, value: "StartRow" }, { name: ns.StartColumn, value: "StartCol" }, { name: ns.RowCount, value: "RowCount" }, { name: ns.ColumnCount, value: "ColCount" } ] }); ns=Microsoft.Office.WebExtension.AsyncResultStatus; define({ type: OSF.DDA.PropertyDescriptors.AsyncResultStatus, fromHost: [ { name: ns.Succeeded, value: 0 }, { name: ns.Failed, value: 1 } ] }); define({ type: OSF.DDA.EventDescriptors.BindingSelectionChangedEvent, fromHost: [ { name: OSF.DDA.PropertyDescriptors.BindingProperties, value: OSF.DDA.XLS.UniqueArguments.BindingEventSource }, { name: OSF.DDA.PropertyDescriptors.Subset, value: OSF.DDA.PropertyDescriptors.Subset } ] }); ns=OSF.DDA.XLS.UniqueArguments; var cns=OSF.DDA.MethodDispId; define({ type: cns.dispidGetSelectedDataMethod, fromHost: [ { name: Microsoft.Office.WebExtension.Parameters.Data, value: ns.Data } ], toHost: [ { name: ns.GetData, value: self } ] }); define({ type: cns.dispidSetSelectedDataMethod, toHost: [ { name: ns.SetData, value: self } ] }); define({ type: cns.dispidAddBindingFromSelectionMethod, fromHost: [ { name: OSF.DDA.XLS.UniqueArguments.SingleBindingResponse, value: OSF.DDA.XLS.UniqueArguments.BindingResponse } ], toHost: [ { name: ns.BindingRequest, value: self } ] }); define({ type: cns.dispidAddBindingFromPromptMethod, fromHost: [ { name: OSF.DDA.XLS.UniqueArguments.SingleBindingResponse, value: OSF.DDA.XLS.UniqueArguments.BindingResponse } ], toHost: [ { name: ns.BindingRequest, value: self } ] }); define({ type: cns.dispidAddBindingFromNamedItemMethod, fromHost: [ { name: OSF.DDA.XLS.UniqueArguments.SingleBindingResponse, value: OSF.DDA.XLS.UniqueArguments.BindingResponse } ], toHost: [ { name: ns.BindingRequest, value: self } ] }); define({ type: cns.dispidReleaseBindingMethod, toHost: [ { name: ns.BindingRequest, value: self } ] }); define({ type: cns.dispidGetBindingMethod, fromHost: [ { name: OSF.DDA.XLS.UniqueArguments.SingleBindingResponse, value: OSF.DDA.XLS.UniqueArguments.BindingResponse } ], toHost: [ { name: ns.BindingRequest, value: self } ] }); define({ type: cns.dispidGetAllBindingsMethod, fromHost: [ { name: OSF.DDA.ListDescriptors.BindingList, value: OSF.DDA.XLS.UniqueArguments.BindingResponse } ] }); define({ type: cns.dispidGetBindingDataMethod, fromHost: [ { name: Microsoft.Office.WebExtension.Parameters.Data, value: ns.Data } ], toHost: [ { name: ns.GetData, value: self } ] }); define({ type: cns.dispidSetBindingDataMethod, toHost: [ { name: ns.SetData, value: self } ] }); define({ type: cns.dispidAddRowsMethod, toHost: [ { name: ns.AddRowsColumns, value: self } ] }); define({ type: cns.dispidAddColumnsMethod, toHost: [ { name: ns.AddRowsColumns, value: self } ] }); define({ type: cns.dispidClearAllRowsMethod, toHost: [ { name: ns.BindingRequest, value: self } ] }); define({ type: cns.dispidLoadSettingsMethod, fromHost: [ { name: OSF.DDA.SettingsManager.SerializedSettings, value: ns.Properties } ] }); define({ type: cns.dispidSaveSettingsMethod, toHost: [ { name: ns.SettingsRequest, value: self } ] }); cns=OSF.DDA.EventDispId define({ type: cns.dispidDocumentSelectionChangedEvent }); define({ type: cns.dispidBindingSelectionChangedEvent, fromHost: [ { name: OSF.DDA.EventDescriptors.BindingSelectionChangedEvent, value: self } ] }); define({ type: cns.dispidBindingDataChangedEvent, fromHost: [ { name: OSF.DDA.PropertyDescriptors.BindingProperties, value: ns.BindingEventSource } ] }); define({ type: cns.dispidSettingsChangedEvent }); return parameterMap; })(); OSF.DDA.XLS.Delegate.version=1; OSF.DDA.XLS.Delegate.executeAsync=function OSF_DDA_XLS_Delegate$executeAsync(args) { if(!args.hostCallArgs) { args.hostCallArgs={}; } args.hostCallArgs["DdaMethod"]={ "ControlId": OSF._OfficeAppFactory.getId(), "Version": OSF.DDA.XLS.Delegate.version, "DispatchId": args.dispId }; if(args.onCalling) { args.onCalling(); } var startTime=(new Date()).getTime(); OSF._OfficeAppFactory.getClientEndPoint().invoke( "executeMethod", function OSF_DDA_XLS_Delegate$OMFacade$OnResponse(xdmStatus, payload) { if(args.onReceiving) { args.onReceiving(); } var error; if (xdmStatus==Microsoft.Office.Common.InvokeResultCode.noError) { OSF.DDA.XLS.Delegate.version=payload["Version"]; error=payload["Error"]; } else { switch (xdmStatus) { case Microsoft.Office.Common.InvokeResultCode.errorHandlingRequestAccessDenied: error=OSF.DDA.ErrorCodeManager.errorCodes.ooeNoCapability; break; default: error=OSF.DDA.ErrorCodeManager.errorCodes.ooeInternalError; break; } } if (args.onComplete) { args.onComplete(error, payload); } if (OSF.AppTelemetry) { OSF.AppTelemetry.onMethodDone(args.dispId, null, Math.abs((new Date()).getTime() - startTime), error); } }, args.hostCallArgs ); }; OSF.DDA.XLS.Delegate._getOnAfterRegisterEvent=function OSF_DDA_XLS_Delegate$GetOnAfterRegisterEvent(register, args) { var startTime=(new Date()).getTime(); return function OSF_DDA_XLS_Delegate$OnAfterRegisterEvent(xdmStatus, succeeded) { if (args.onReceiving) { args.onReceiving(); } var status; if (xdmStatus !=Microsoft.Office.Common.InvokeResultCode.noError) { switch (xdmStatus) { case Microsoft.Office.Common.InvokeResultCode.errorHandlingRequestAccessDenied: status=OSF.DDA.ErrorCodeManager.errorCodes.ooeNoCapability; break; default: status=OSF.DDA.ErrorCodeManager.errorCodes.ooeInternalError; break; } } else { status=succeeded ? OSF.DDA.ErrorCodeManager.errorCodes.ooeSuccess : OSF.DDA.ErrorCodeManager.errorCodes.ooeInternalError; } if (args.onComplete) { args.onComplete(status); } if (OSF.AppTelemetry) { OSF.AppTelemetry.onRegisterDone(register, args.dispId, Math.abs((new Date()).getTime() - startTime), status); } } }; OSF.DDA.XLS.Delegate.registerEventAsync=function OSF_DDA_XLS_Delegate$RegisterEventAsync(args) { if (args.onCalling) { args.onCalling(); } OSF._OfficeAppFactory.getClientEndPoint().registerForEvent( OSF.DDA.getXdmEventName(args.targetId, args.eventType), function OSF_DDA_XLSOMFacade$OnEvent(payload) { if (args.onEvent) { args.onEvent(payload); } if (OSF.AppTelemetry) { OSF.AppTelemetry.onEventDone(args.dispId); } }, OSF.DDA.XLS.Delegate._getOnAfterRegisterEvent(true, args), { "controlId": OSF._OfficeAppFactory.getId(), "eventDispId": args.dispId, "targetId": args.targetId } ); }; OSF.DDA.XLS.Delegate.unregisterEventAsync=function OSF_DDA_XLS_Delegate$UnregisterEventAsync(args) { if (args.onCalling) { args.onCalling(); } OSF._OfficeAppFactory.getClientEndPoint().unregisterForEvent( OSF.DDA.getXdmEventName(args.targetId, args.eventType), OSF.DDA.XLS.Delegate._getOnAfterRegisterEvent(false, args), { "controlId": OSF._OfficeAppFactory.getId(), "eventDispId": args.dispId, "targetId": args.targetId } ); }; OSF.DDA.ExcelWebAppDocument=function Microsoft_Office_WebExtension_ExcelWebAppDocument(officeAppContext, settings) { var bf=new OSF.DDA.BindingFacade(this); OSF.DDA.DispIdHost.addAsyncMethods(bf, [OSF.DDA.AsyncMethodNames.AddFromPromptAsync]); OSF.DDA.ExcelWebAppDocument.uber.constructor.call(this, officeAppContext, bf, settings ); if (this.mode==OSF.ClientMode.ReadOnly) { this.url=document.URL; } OSF.OUtil.finalizeProperties(this); }; OSF.OUtil.extend(OSF.DDA.ExcelWebAppDocument, OSF.DDA.JsomDocument);
CodeMoggy/ngOutlookApp
SocialERPWeb/Scripts/Office/1.1/excelwebapp-15.debug.js
JavaScript
apache-2.0
15,322
#ifndef ANDROID_NDK_VERSION_H #define ANDROID_NDK_VERSION_H /** * Major vision of this NDK. * * For example: 16 for r16. */ #define __NDK_MAJOR__ 16 /** * Minor vision of this NDK. * * For example: 1 for r16b. */ #define __NDK_MINOR__ 1 /** * Beta vision of this NDK. * * For example: 1 for r16 beta 1, 0 for r16. */ #define __NDK_BETA__ 0 /** * Build number for this NDK. * * For a local development build of the NDK, this is -1. */ #define __NDK_BUILD__ 4479499 /** * Set to 1 if this is a canary build, 0 if not. */ #define __NDK_CANARY__ 0 #endif /* ANDROID_NDK_VERSION_H */
qpython-android/QPython3-core
mk/tinycc/sysinculde/android/ndk-version.h
C
apache-2.0
604
#!/bin/bash if ! whoami &>/dev/null; then if [ -w /etc/passwd ]; then echo "${USER_NAME:-molecule}:x:$(id -u):$(id -g):${USER_NAME:-molecule} user:${HOME}:/sbin/nologin" >> /etc/passwd fi fi exec $@
eriknelson/ansible-service-broker
operator/build/entrypoint.sh
Shell
apache-2.0
209
<?php $GLOBALS['PHP_IMPALA_CLASSMAP'] = require_once 'lib/autoload_classmap.php'; spl_autoload_register(function ($class) { if(array_key_exists($class, $GLOBALS['PHP_IMPALA_CLASSMAP'])) { require $GLOBALS['PHP_IMPALA_CLASSMAP'][$class]; } }); use Thrift\Transport\TBufferedTransport; use Thrift\Transport\TSocket; use Thrift\Protocol\TBinaryProtocol; $socket = new TSocket('127.0.0.1', 50000); $transport = new TBufferedTransport($socket); $transport->open(); $protocol = new TBinaryProtocol($transport); $client = new Impala\ImpalaServiceClient($protocol); $query = new Beeswax\Query(); $query->query = 'SHOW TABLES'; $queryHandle = $client->query($query); $result = $client->fetch($queryHandle, false, 100); var_dump($result); ?>
pozypakya/php-impala
test.php
PHP
apache-2.0
744
/* * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tools.classfile; import java.io.IOException; /** * See JVMS3, section 4.8.7. * * <p><b>This is NOT part of any API supported by Sun Microsystems. If * you write code that depends on this, you do so at your own risk. * This code and its internal interfaces are subject to change or * deletion without notice.</b> */ public class EnclosingMethod_attribute extends Attribute { EnclosingMethod_attribute(ClassReader cr, int name_index, int length) throws IOException { super(name_index, length); class_index = cr.readUnsignedShort(); method_index = cr.readUnsignedShort(); } public EnclosingMethod_attribute(ConstantPool constant_pool, int class_index, int method_index) throws ConstantPoolException { this(constant_pool.getUTF8Index(Attribute.EnclosingMethod), class_index, method_index); } public EnclosingMethod_attribute(int name_index, int class_index, int method_index) { super(name_index, 4); this.class_index = class_index; this.method_index = method_index; } public String getClassName(ConstantPool constant_pool) throws ConstantPoolException { return constant_pool.getClassInfo(class_index).getName(); } public String getMethodName(ConstantPool constant_pool) throws ConstantPoolException { if (method_index == 0) return ""; return constant_pool.getNameAndTypeInfo(method_index).getName(); } public <R, D> R accept(Visitor<R, D> visitor, D data) { return visitor.visitEnclosingMethod(this, data); } public final int class_index; public final int method_index; }
ilivoo/ilivoo
java_tools/src/com/sun/tools/classfile/EnclosingMethod_attribute.java
Java
apache-2.0
2,881
package helper import ( "errors" "encoding/json" log "github.com/sirupsen/logrus" "github.com/Cepave/open-falcon-backend/modules/f2e-api/app/model/uic" "github.com/Cepave/open-falcon-backend/modules/f2e-api/config" "github.com/gin-gonic/gin" ) type WebSession struct { Name string Sig string } func GetSession(c *gin.Context) (session WebSession, err error) { var name, sig string apiToken := c.Request.Header.Get("Apitoken") if apiToken == "" { err = errors.New("token key is not set") return } log.Debugf("header: %v, apiToken: %v", c.Request.Header, apiToken) var websession WebSession err = json.Unmarshal([]byte(apiToken), &websession) if err != nil { return } name = websession.Name log.Debugf("session got name: %s", name) if name == "" { err = errors.New("token key:name is empty") return } sig = websession.Sig log.Debugf("session got sig: %s", sig) if sig == "" { err = errors.New("token key:sig is empty") return } if err != nil { return } session = WebSession{name, sig} return } func SessionChecking(c *gin.Context) (auth bool, isServiceToken bool, err error) { auth = false var websessio WebSession websessio, err = GetSession(c) if err != nil { return } Serieves := config.ApiClient if Serieves.Enable && Serieves.NameIncludes(websessio.Name) { if Serieves.AuthToken(websessio.Name, websessio.Sig) { auth = true isServiceToken = true return } log.Warnf("use %s but got wrong sig (%s). Please need check this session", websessio.Name, websessio.Sig) } db := config.Con().Uic var user uic.User db.Where("name = ?", websessio.Name).Find(&user) if user.ID == 0 { err = errors.New("not found this user") return } var session uic.Session db.Table("session").Where("sig = ? and uid = ?", websessio.Sig, user.ID).Scan(&session) if session.ID == 0 { err = errors.New("session not found") return } else { auth = true } return } func GetUser(c *gin.Context) (user uic.User, err error) { db := config.Con().Uic websession, getserr := GetSession(c) if getserr != nil { err = getserr return } if v, ok := c.Get("is_service_token"); ok && v.(bool) { err = errors.New("services token no support this kind of action.") return } user = uic.User{ Name: websession.Name, } dt := db.Where(&user).Find(&user) err = dt.Error return }
masato25/open-falcon-backend
modules/f2e-api/app/helper/session.go
GO
apache-2.0
2,348
/**************************************************************************** * * Copyright 2018 Samsung Electronics 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. * ****************************************************************************/ /* * Helper functions for the RSA module * * Copyright (C) 2006-2017, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. * * This file is part of mbed TLS (https://tls.mbed.org) * */ #include "mbedtls/config.h" #if defined(MBEDTLS_RSA_C) #include "mbedtls/rsa.h" #include "mbedtls/bignum.h" #include "mbedtls/rsa_internal.h" /* * Compute RSA prime factors from public and private exponents * * Summary of algorithm: * Setting F := lcm(P-1,Q-1), the idea is as follows: * * (a) For any 1 <= X < N with gcd(X,N)=1, we have X^F = 1 modulo N, so X^(F/2) * is a square root of 1 in Z/NZ. Since Z/NZ ~= Z/PZ x Z/QZ by CRT and the * square roots of 1 in Z/PZ and Z/QZ are +1 and -1, this leaves the four * possibilities X^(F/2) = (+-1, +-1). If it happens that X^(F/2) = (-1,+1) * or (+1,-1), then gcd(X^(F/2) + 1, N) will be equal to one of the prime * factors of N. * * (b) If we don't know F/2 but (F/2) * K for some odd (!) K, then the same * construction still applies since (-)^K is the identity on the set of * roots of 1 in Z/NZ. * * The public and private key primitives (-)^E and (-)^D are mutually inverse * bijections on Z/NZ if and only if (-)^(DE) is the identity on Z/NZ, i.e. * if and only if DE - 1 is a multiple of F, say DE - 1 = F * L. * Splitting L = 2^t * K with K odd, we have * * DE - 1 = FL = (F/2) * (2^(t+1)) * K, * * so (F / 2) * K is among the numbers * * (DE - 1) >> 1, (DE - 1) >> 2, ..., (DE - 1) >> ord * * where ord is the order of 2 in (DE - 1). * We can therefore iterate through these numbers apply the construction * of (a) and (b) above to attempt to factor N. * */ int mbedtls_rsa_deduce_primes( mbedtls_mpi const *N, mbedtls_mpi const *E, mbedtls_mpi const *D, mbedtls_mpi *P, mbedtls_mpi *Q ) { int ret = 0; uint16_t attempt; /* Number of current attempt */ uint16_t iter; /* Number of squares computed in the current attempt */ uint16_t order; /* Order of 2 in DE - 1 */ mbedtls_mpi T; /* Holds largest odd divisor of DE - 1 */ mbedtls_mpi K; /* Temporary holding the current candidate */ const unsigned char primes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251 }; const size_t num_primes = sizeof( primes ) / sizeof( *primes ); if( P == NULL || Q == NULL || P->p != NULL || Q->p != NULL ) return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA ); if( mbedtls_mpi_cmp_int( N, 0 ) <= 0 || mbedtls_mpi_cmp_int( D, 1 ) <= 0 || mbedtls_mpi_cmp_mpi( D, N ) >= 0 || mbedtls_mpi_cmp_int( E, 1 ) <= 0 || mbedtls_mpi_cmp_mpi( E, N ) >= 0 ) { return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA ); } /* * Initializations and temporary changes */ mbedtls_mpi_init( &K ); mbedtls_mpi_init( &T ); /* T := DE - 1 */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T, D, E ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &T, &T, 1 ) ); if( ( order = (uint16_t) mbedtls_mpi_lsb( &T ) ) == 0 ) { ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA; goto cleanup; } /* After this operation, T holds the largest odd divisor of DE - 1. */ MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &T, order ) ); /* * Actual work */ /* Skip trying 2 if N == 1 mod 8 */ attempt = 0; if( N->p[0] % 8 == 1 ) attempt = 1; for( ; attempt < num_primes; ++attempt ) { mbedtls_mpi_lset( &K, primes[attempt] ); /* Check if gcd(K,N) = 1 */ MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( P, &K, N ) ); if( mbedtls_mpi_cmp_int( P, 1 ) != 0 ) continue; /* Go through K^T + 1, K^(2T) + 1, K^(4T) + 1, ... * and check whether they have nontrivial GCD with N. */ MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &K, &K, &T, N, Q /* temporarily use Q for storing Montgomery * multiplication helper values */ ) ); for( iter = 1; iter <= order; ++iter ) { /* If we reach 1 prematurely, there's no point * in continuing to square K */ if( mbedtls_mpi_cmp_int( &K, 1 ) == 0 ) break; MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( &K, &K, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( P, &K, N ) ); if( mbedtls_mpi_cmp_int( P, 1 ) == 1 && mbedtls_mpi_cmp_mpi( P, N ) == -1 ) { /* * Have found a nontrivial divisor P of N. * Set Q := N / P. */ MBEDTLS_MPI_CHK( mbedtls_mpi_div_mpi( Q, NULL, N, P ) ); goto cleanup; } MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, &K, &K ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, N ) ); } /* * If we get here, then either we prematurely aborted the loop because * we reached 1, or K holds primes[attempt]^(DE - 1) mod N, which must * be 1 if D,E,N were consistent. * Check if that's the case and abort if not, to avoid very long, * yet eventually failing, computations if N,D,E were not sane. */ if( mbedtls_mpi_cmp_int( &K, 1 ) != 0 ) { break; } } ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA; cleanup: mbedtls_mpi_free( &K ); mbedtls_mpi_free( &T ); return( ret ); } /* * Given P, Q and the public exponent E, deduce D. * This is essentially a modular inversion. */ int mbedtls_rsa_deduce_private_exponent( mbedtls_mpi const *P, mbedtls_mpi const *Q, mbedtls_mpi const *E, mbedtls_mpi *D ) { int ret = 0; mbedtls_mpi K, L; if( D == NULL || mbedtls_mpi_cmp_int( D, 0 ) != 0 ) return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA ); if( mbedtls_mpi_cmp_int( P, 1 ) <= 0 || mbedtls_mpi_cmp_int( Q, 1 ) <= 0 || mbedtls_mpi_cmp_int( E, 0 ) == 0 ) { return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA ); } mbedtls_mpi_init( &K ); mbedtls_mpi_init( &L ); /* Temporarily put K := P-1 and L := Q-1 */ MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, P, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &L, Q, 1 ) ); /* Temporarily put D := gcd(P-1, Q-1) */ MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( D, &K, &L ) ); /* K := LCM(P-1, Q-1) */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, &K, &L ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_div_mpi( &K, NULL, &K, D ) ); /* Compute modular inverse of E in LCM(P-1, Q-1) */ MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( D, E, &K ) ); cleanup: mbedtls_mpi_free( &K ); mbedtls_mpi_free( &L ); return( ret ); } /* * Check that RSA CRT parameters are in accordance with core parameters. */ int mbedtls_rsa_validate_crt( const mbedtls_mpi *P, const mbedtls_mpi *Q, const mbedtls_mpi *D, const mbedtls_mpi *DP, const mbedtls_mpi *DQ, const mbedtls_mpi *QP ) { int ret = 0; mbedtls_mpi K, L; mbedtls_mpi_init( &K ); mbedtls_mpi_init( &L ); /* Check that DP - D == 0 mod P - 1 */ if( DP != NULL ) { if( P == NULL ) { ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA; goto cleanup; } MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, P, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &L, DP, D ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &L, &L, &K ) ); if( mbedtls_mpi_cmp_int( &L, 0 ) != 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } } /* Check that DQ - D == 0 mod Q - 1 */ if( DQ != NULL ) { if( Q == NULL ) { ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA; goto cleanup; } MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, Q, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &L, DQ, D ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &L, &L, &K ) ); if( mbedtls_mpi_cmp_int( &L, 0 ) != 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } } /* Check that QP * Q - 1 == 0 mod P */ if( QP != NULL ) { if( P == NULL || Q == NULL ) { ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA; goto cleanup; } MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, QP, Q ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, P ) ); if( mbedtls_mpi_cmp_int( &K, 0 ) != 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } } cleanup: /* Wrap MPI error codes by RSA check failure error code */ if( ret != 0 && ret != MBEDTLS_ERR_RSA_KEY_CHECK_FAILED && ret != MBEDTLS_ERR_RSA_BAD_INPUT_DATA ) { ret += MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; } mbedtls_mpi_free( &K ); mbedtls_mpi_free( &L ); return( ret ); } /* * Check that core RSA parameters are sane. */ int mbedtls_rsa_validate_params( const mbedtls_mpi *N, const mbedtls_mpi *P, const mbedtls_mpi *Q, const mbedtls_mpi *D, const mbedtls_mpi *E, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret = 0; mbedtls_mpi K, L; mbedtls_mpi_init( &K ); mbedtls_mpi_init( &L ); /* * Step 1: If PRNG provided, check that P and Q are prime */ #if defined(MBEDTLS_GENPRIME) if( f_rng != NULL && P != NULL && ( ret = mbedtls_mpi_is_prime( P, f_rng, p_rng ) ) != 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } if( f_rng != NULL && Q != NULL && ( ret = mbedtls_mpi_is_prime( Q, f_rng, p_rng ) ) != 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } #else ((void) f_rng); ((void) p_rng); #endif /* MBEDTLS_GENPRIME */ /* * Step 2: Check that 1 < N = P * Q */ if( P != NULL && Q != NULL && N != NULL ) { MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, P, Q ) ); if( mbedtls_mpi_cmp_int( N, 1 ) <= 0 || mbedtls_mpi_cmp_mpi( &K, N ) != 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } } /* * Step 3: Check and 1 < D, E < N if present. */ if( N != NULL && D != NULL && E != NULL ) { if ( mbedtls_mpi_cmp_int( D, 1 ) <= 0 || mbedtls_mpi_cmp_int( E, 1 ) <= 0 || mbedtls_mpi_cmp_mpi( D, N ) >= 0 || mbedtls_mpi_cmp_mpi( E, N ) >= 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } } /* * Step 4: Check that D, E are inverse modulo P-1 and Q-1 */ if( P != NULL && Q != NULL && D != NULL && E != NULL ) { if( mbedtls_mpi_cmp_int( P, 1 ) <= 0 || mbedtls_mpi_cmp_int( Q, 1 ) <= 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } /* Compute DE-1 mod P-1 */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, D, E ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &L, P, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, &L ) ); if( mbedtls_mpi_cmp_int( &K, 0 ) != 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } /* Compute DE-1 mod Q-1 */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, D, E ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &L, Q, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, &L ) ); if( mbedtls_mpi_cmp_int( &K, 0 ) != 0 ) { ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; goto cleanup; } } cleanup: mbedtls_mpi_free( &K ); mbedtls_mpi_free( &L ); /* Wrap MPI error codes by RSA check failure error code */ if( ret != 0 && ret != MBEDTLS_ERR_RSA_KEY_CHECK_FAILED ) { ret += MBEDTLS_ERR_RSA_KEY_CHECK_FAILED; } return( ret ); } int mbedtls_rsa_deduce_crt( const mbedtls_mpi *P, const mbedtls_mpi *Q, const mbedtls_mpi *D, mbedtls_mpi *DP, mbedtls_mpi *DQ, mbedtls_mpi *QP ) { int ret = 0; mbedtls_mpi K; mbedtls_mpi_init( &K ); /* DP = D mod P-1 */ if( DP != NULL ) { MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, P, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( DP, D, &K ) ); } /* DQ = D mod Q-1 */ if( DQ != NULL ) { MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, Q, 1 ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( DQ, D, &K ) ); } /* QP = Q^{-1} mod P */ if( QP != NULL ) { MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( QP, Q, P ) ); } cleanup: mbedtls_mpi_free( &K ); return( ret ); } #endif /* MBEDTLS_RSA_C */
HONGCHAEHEE/TizenRT
external/mbedtls/rsa_internal.c
C
apache-2.0
15,074
/* * 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.shardingsphere.driver.jdbc.base; import org.h2.tools.RunScript; import org.junit.BeforeClass; import javax.sql.DataSource; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.SQLException; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; public abstract class AbstractSQLTest { private static final List<String> ACTUAL_DATA_SOURCE_NAMES = Arrays.asList("jdbc_0", "jdbc_1", "shadow_jdbc_0", "shadow_jdbc_1", "encrypt", "test_write_ds", "test_read_ds"); private static final Map<String, DataSource> ACTUAL_DATA_SOURCES = new HashMap<>(); @BeforeClass public static synchronized void initializeDataSource() throws SQLException { for (String each : ACTUAL_DATA_SOURCE_NAMES) { createDataSources(each); } } private static void createDataSources(final String dataSourceName) throws SQLException { ACTUAL_DATA_SOURCES.put(dataSourceName, DataSourceBuilder.build(dataSourceName)); initializeSchema(dataSourceName); } private static void initializeSchema(final String dataSourceName) throws SQLException { try (Connection conn = ACTUAL_DATA_SOURCES.get(dataSourceName).getConnection()) { if ("encrypt".equals(dataSourceName)) { RunScript.execute(conn, new InputStreamReader(Objects.requireNonNull(AbstractSQLTest.class.getClassLoader().getResourceAsStream("sql/jdbc_encrypt_init.sql")))); } else if ("shadow_jdbc_0".equals(dataSourceName) || "shadow_jdbc_1".equals(dataSourceName)) { RunScript.execute(conn, new InputStreamReader(Objects.requireNonNull(AbstractSQLTest.class.getClassLoader().getResourceAsStream("sql/jdbc_shadow_init.sql")))); } else { RunScript.execute(conn, new InputStreamReader(Objects.requireNonNull(AbstractSQLTest.class.getClassLoader().getResourceAsStream("sql/jdbc_init.sql")))); } } } protected static Map<String, DataSource> getActualDataSources() { return ACTUAL_DATA_SOURCES; } }
apache/incubator-shardingsphere
shardingsphere-jdbc/shardingsphere-jdbc-core/src/test/java/org/apache/shardingsphere/driver/jdbc/base/AbstractSQLTest.java
Java
apache-2.0
2,963
/* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch licenses this * file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.query; import org.apache.lucene.search.Query; import org.apache.lucene.search.TermRangeQuery; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.lucene.BytesRefs; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.mapper.MapperService; import java.io.IOException; import static org.elasticsearch.index.query.support.QueryParsers.wrapSmartNameQuery; /** * */ public class RangeQueryParser implements QueryParser { public static final String NAME = "range"; @Inject public RangeQueryParser() { } @Override public String[] names() { return new String[]{NAME}; } @Override public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { XContentParser parser = parseContext.parser(); XContentParser.Token token = parser.nextToken(); if (token != XContentParser.Token.FIELD_NAME) { throw new QueryParsingException(parseContext.index(), "[range] query malformed, no field to indicate field name"); } String fieldName = parser.currentName(); token = parser.nextToken(); if (token != XContentParser.Token.START_OBJECT) { throw new QueryParsingException(parseContext.index(), "[range] query malformed, after field missing start object"); } Object from = null; Object to = null; boolean includeLower = true; boolean includeUpper = true; float boost = 1.0f; String currentFieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else { if ("from".equals(currentFieldName)) { from = parser.objectBytes(); } else if ("to".equals(currentFieldName)) { to = parser.objectBytes(); } else if ("include_lower".equals(currentFieldName) || "includeLower".equals(currentFieldName)) { includeLower = parser.booleanValue(); } else if ("include_upper".equals(currentFieldName) || "includeUpper".equals(currentFieldName)) { includeUpper = parser.booleanValue(); } else if ("boost".equals(currentFieldName)) { boost = parser.floatValue(); } else if ("gt".equals(currentFieldName)) { from = parser.objectBytes(); includeLower = false; } else if ("gte".equals(currentFieldName) || "ge".equals(currentFieldName)) { from = parser.objectBytes(); includeLower = true; } else if ("lt".equals(currentFieldName)) { to = parser.objectBytes(); includeUpper = false; } else if ("lte".equals(currentFieldName) || "le".equals(currentFieldName)) { to = parser.objectBytes(); includeUpper = true; } else { throw new QueryParsingException(parseContext.index(), "[range] query does not support [" + currentFieldName + "]"); } } } // move to the next end object, to close the field name token = parser.nextToken(); if (token != XContentParser.Token.END_OBJECT) { throw new QueryParsingException(parseContext.index(), "[range] query malformed, does not end with an object"); } Query query = null; MapperService.SmartNameFieldMappers smartNameFieldMappers = parseContext.smartFieldMappers(fieldName); if (smartNameFieldMappers != null) { if (smartNameFieldMappers.hasMapper()) { //LUCENE 4 UPGRADE Mapper#rangeQuery should use bytesref as well? query = smartNameFieldMappers.mapper().rangeQuery(from, to, includeLower, includeUpper, parseContext); } } if (query == null) { query = new TermRangeQuery(fieldName, BytesRefs.toBytesRef(from), BytesRefs.toBytesRef(to), includeLower, includeUpper); } query.setBoost(boost); return wrapSmartNameQuery(query, smartNameFieldMappers, parseContext); } }
dongaihua/highlight-elasticsearch
src/main/java/org/elasticsearch/index/query/RangeQueryParser.java
Java
apache-2.0
5,206
// config-utils.js -- helpers for coordinating Application runtime vs. Settings configuration // // * ApplicationConfig -- Menu items and API values. // * SettingsConfig -- scoped Settings values. "use strict"; /* eslint-env commonjs */ /* global log */ module.exports = { version: '0.0.1a', ApplicationConfig: ApplicationConfig, SettingsConfig: SettingsConfig }; var _utils = require('./_utils.js'), assert = _utils.assert; Object.assign = Object.assign || _utils.assign; function _debugPrint() { print('config-utils | ' + [].slice.call(arguments).join(' ')); } var debugPrint = function() {}; // ---------------------------------------------------------------------------- // Application-specific configuration values using runtime state / API props // // options.config[] supports the following item formats: // 'settingsName': { menu: 'Menu > MenuItem'}, // assumes MenuItem is a checkbox / checkable value // 'settingsName': { object: [ MyAvatar, 'property' ] }, // 'settingsName': { object: [ MyAvatar, 'getterMethod', 'setterMethod' ] }, // 'settingsName': { menu: 'Menu > MenuItem', object: [ MyAvatar, 'property' ] }, // 'settingsName': { get: function getter() { ...}, set: function(nv) { ... } }, function ApplicationConfig(options) { options = options || {}; assert('namespace' in options && 'config' in options); if (options.debug) { debugPrint = _debugPrint; debugPrint('debugPrinting enabled'); } this.namespace = options.namespace; this.valueUpdated = _utils.signal(function valueUpdated(key, newValue, oldValue, origin){}); this.config = {}; this.register(options.config); } ApplicationConfig.prototype = { resolve: function resolve(key) { assert(typeof key === 'string', 'ApplicationConfig.resolve error: key is not a string: ' + key); if (0 !== key.indexOf('.') && !~key.indexOf('/')) { key = [ this.namespace, key ].join('/'); } return (key in this.config) ? key : (debugPrint('ApplicationConfig -- could not resolve key: ' + key),undefined); }, registerItem: function(settingName, item) { item._settingName = settingName; item.settingName = ~settingName.indexOf('/') ? settingName : [ this.namespace, settingName ].join('/'); return this.config[item.settingName] = this.config[settingName] = new ApplicationConfigItem(item); }, // process items into fully-qualfied ApplicationConfigItem instances register: function(items) { for (var p in items) { var item = items[p]; item && this.registerItem(p, item); } }, _getItem: function(key) { return this.config[this.resolve(key)]; }, getValue: function(key, defaultValue) { var item = this._getItem(key); if (!item) { return defaultValue; } return item.get(); }, setValue: function setValue(key, value) { key = this.resolve(key); var lastValue = this.getValue(key, value); var ret = this._getItem(key).set(value); if (lastValue !== value) { this.valueUpdated(key, value, lastValue, 'ApplicationConfig.setValue'); } return ret; }, // sync dual-source (ie: Menu + API) items resyncValue: function(key) { var item = this._getItem(key); return item && item.resync(); }, // sync Settings values -> Application state applyValue: function applyValue(key, value, origin) { if (this.resolve(key)) { var appValue = this.getValue(key, value); debugPrint('applyValue', key, value, origin ? '['+origin+']' : '', appValue); if (appValue !== value) { this.setValue(key, value); debugPrint('applied new setting', key, value, '(was:'+appValue+')'); return true; } } } }; // ApplicationConfigItem represents a single API/Menu item accessor function ApplicationConfigItem(item) { Object.assign(this, item); Object.assign(this, { _item: item.get && item, _object: this._parseObjectConfig(this.object), _menu: this._parseMenuConfig(this.menu) }); this.authority = this._item ? 'item' : this._object ? 'object' : this._menu ? 'menu' : null; this._authority = this['_'+this.authority]; debugPrint('_authority', this.authority, this._authority, Object.keys(this._authority)); assert(this._authority, 'expected item.get, .object or .menu definition; ' + this.settingName); } ApplicationConfigItem.prototype = { resync: function resync() { var authoritativeValue = this._authority.get(); if (this._menu && this._menu.get() !== authoritativeValue) { _debugPrint(this.settingName, this._menu.menuItem, '... menu value ('+this._menu.get()+') out of sync;', 'setting to authoritativeValue ('+authoritativeValue+')'); this._menu.set(authoritativeValue); } if (this._object && this._object.get() !== authoritativeValue) { _debugPrint(this.settingName, this._object.getter || this._object.property, '... object value ('+this._object.get()+') out of sync;', 'setting to authoritativeValue ('+authoritativeValue+')'); this._object.set(authoritativeValue); } }, toString: function() { return '[ApplicationConfigItem ' + [ 'setting:' + JSON.stringify(this.settingName), 'authority:' + JSON.stringify(this.authority), this._object && 'object:' + JSON.stringify(this._object.property || this._object.getter), this._menu && 'menu:' + JSON.stringify(this._menu.menu) ].filter(Boolean).join(' ') + ']'; }, get: function get() { return this._authority.get(); }, set: function set(nv) { this._object && this._object.set(nv); this._menu && this._menu.set(nv); return nv; }, _raiseError: function(errorMessage) { if (this.debug) { throw new Error(errorMessage); } else { _debugPrint('ERROR: ' + errorMessage); } }, _parseObjectConfig: function(parts) { if (!Array.isArray(parts) || parts.length < 2) { return null; } var object = parts[0], getter = parts[1], setter = parts[2]; if (typeof object[getter] === 'function' && typeof object[setter] === 'function') { // [ API, 'getter', 'setter' ] return { object: object, getter: getter, setter: setter, get: function getObjectValue() { return this.object[this.getter](); }, set: function setObjectValue(nv) { return this.object[this.setter](nv), nv; } }; } else if (getter in object) { // [ API, 'property' ] return { object: object, property: getter, get: function() { return this.object[this.property]; }, set: function(nv) { return this.object[this.property] = nv; } }; } this._raiseError('{ object: [ Object, getterOrPropertyName, setterName ] } -- invalid params or does not exist: ' + [ this.settingName, this.object, getter, setter ].join(' | ')); }, _parseMenuConfig: function(menu) { if (!menu || typeof menu !== 'string') { return null; } var parts = menu.split(/\s*>\s*/), menuItemName = parts.pop(), menuName = parts.join(' > '); if (menuItemName && Menu.menuItemExists(menuName, menuItemName)) { return { menu: menu, menuName: menuName, menuItemName: menuItemName, get: function() { return Menu.isOptionChecked(this.menuItemName); }, set: function(nv) { return Menu.setIsOptionChecked(this.menuItemName, nv), nv; } }; } this._raiseError('{ menu: "Menu > Item" } structure -- invalid params or does not exist: ' + [ this.settingName, this.menu, menuName, menuItemName ].join(' | ')); } }; // ApplicationConfigItem.prototype // ---------------------------------------------------------------------------- // grouped configuration using the Settings.* API function SettingsConfig(options) { options = options || {}; assert('namespace' in options); this.namespace = options.namespace; this.defaultValues = {}; this.valueUpdated = _utils.signal(function valueUpdated(key, newValue, oldValue, origin){}); if (options.defaultValues) { Object.keys(options.defaultValues) .forEach(_utils.bind(this, function(key) { var fullSettingsKey = this.resolve(key); this.defaultValues[fullSettingsKey] = options.defaultValues[key]; })); } } SettingsConfig.prototype = { resolve: function(key) { assert(typeof key === 'string', 'SettingsConfig.resolve error: key is not a string: ' + key); return (0 !== key.indexOf('.') && !~key.indexOf('/')) ? [ this.namespace, key ].join('/') : key; }, getValue: function(key, defaultValue) { key = this.resolve(key); defaultValue = defaultValue === undefined ? this.defaultValues[key] : defaultValue; return Settings.getValue(key, defaultValue); }, setValue: function setValue(key, value) { key = this.resolve(key); var lastValue = this.getValue(key); var ret = Settings.setValue(key, value); if (lastValue !== value) { this.valueUpdated(key, value, lastValue, 'SettingsConfig.setValue'); } return ret; }, getFloat: function getFloat(key, defaultValue) { key = this.resolve(key); defaultValue = defaultValue === undefined ? this.defaultValues[key] : defaultValue; var value = parseFloat(this.getValue(key, defaultValue)); return isFinite(value) ? value : isFinite(defaultValue) ? defaultValue : 0.0; } };
RebeccaStankus/hifi-content
Marketplace/camera-move/modules/config-utils.js
JavaScript
apache-2.0
10,355
<!DOCTYPE html> <html lang="en" manifest="/offline/ovs.appcache"> <head> <!-- Copyright 2014 CloudFounders NV 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. --> <script type="text/javascript"> window.addEventListener('load', function() { applicationCache.addEventListener('updateready', function() { if (applicationCache.status == applicationCache.UPDATEREADY) { applicationCache.swapCache(); } }, false); applicationCache.update(); }, false); </script> </head> <body></body> </html>
mflu/openvstorage_centos
webapps/frontend/offline/cache.html
HTML
apache-2.0
1,222
using System; using Elasticsearch.Net; using Nest; using Tests.Framework; using Tests.Framework.MockData; using Tests.Framework.Integration; using Tests.Framework.ManagedElasticsearch.Clusters; namespace Tests.Mapping.Types.Core.Binary { public class BinaryPropertyTests : PropertyTestsBase { public BinaryPropertyTests(WritableCluster cluster, EndpointUsage usage) : base(cluster, usage) { } protected override object ExpectJson => new { properties = new { name = new { type = "binary", doc_values = true, similarity = "classic", store = true } } }; protected override Func<PropertiesDescriptor<Project>, IPromise<IProperties>> FluentProperties => f => f .Binary(b => b .Name(p => p.Name) .DocValues() .Similarity(SimilarityOption.Classic) .Store() ); protected override IProperties InitializerProperties => new Properties { { "name", new BinaryProperty { DocValues = true, Similarity = SimilarityOption.Classic, Store = true } } }; } }
CSGOpenSource/elasticsearch-net
src/Tests/Mapping/Types/Core/Binary/BinaryPropertyTests.cs
C#
apache-2.0
1,057
-- Copyright (c) 2013-2015 Snowplow Analytics Ltd. All rights reserved. -- -- This program is licensed to you under the Apache License Version 2.0, -- and you may not use this file except in compliance with the Apache License Version 2.0. -- You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. -- -- Unless required by applicable law or agreed to in writing, -- software distributed under the Apache License Version 2.0 is distributed on an -- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. -- -- Authors: Yali Sassoon, Christophe Bogaert -- Copyright: Copyright (c) 2013-2015 Snowplow Analytics Ltd -- License: Apache License Version 2.0 -- Events belonging to the same page view can arrive at different times and could end up in different batches. -- Rows in the page_views_new table therefore have to be merged with those in the pivot table. -- Select information associated with the last event in each page view. DROP TABLE IF EXISTS snowplow_intermediary.page_views_final_frame; CREATE TABLE snowplow_intermediary.page_views_final_frame DISTKEY (domain_userid) -- Optimized to join on other snowplow_intermediary.page_views_X tables SORTKEY (domain_userid, domain_sessionidx) -- Optimized to join on other snowplow_intermediary.page_views_X tables AS ( SELECT * FROM ( SELECT -- Select the information associated with the earliest event (based on dvce_tstamp) a.domain_userid, a.domain_sessionidx, a.page_urlhost, a.page_urlpath, a.blended_user_id, -- Edge case: one page view with multiple logins and events in several batches a.inferred_user_id, -- Edge case: one page view with multiple logins and events in several batches RANK() OVER (PARTITION BY a.domain_userid, a.domain_sessionidx, a.page_urlhost, a.page_urlpath ORDER BY a.blended_user_id, a.inferred_user_id) AS rank FROM snowplow_intermediary.page_views_new AS a INNER JOIN snowplow_intermediary.page_views_aggregate_frame AS b ON a.domain_userid = b.domain_userid AND a.domain_sessionidx = b.domain_sessionidx AND a.page_urlhost = b.page_urlhost AND a.page_urlpath = b.page_urlpath AND a.dvce_max_tstamp = b.dvce_max_tstamp -- Replaces the LAST VALUE window function in SQL GROUP BY 1,2,3,4,5,6 -- Aggregate identital rows (that happen to have the same dvce_tstamp) ) WHERE rank = 1 -- If there are different rows with the same dvce_tstamp, rank and pick the first row );
rogervaas/snowplow
5-data-modeling/sql-runner/redshift/sql/incremental/06-page-views/06-04-merge-part-3.sql
SQL
apache-2.0
2,663
/* * Copyright 2010-2017 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. */ #pragma once #include <aws/redshift/Redshift_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSStreamFwd.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace Utils { namespace Xml { class XmlNode; } // namespace Xml } // namespace Utils namespace Redshift { namespace Model { /** * <p>Describes a cluster version, including the parameter group family and * description of the version.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/redshift-2012-12-01/ClusterVersion">AWS * API Reference</a></p> */ class AWS_REDSHIFT_API ClusterVersion { public: ClusterVersion(); ClusterVersion(const Aws::Utils::Xml::XmlNode& xmlNode); ClusterVersion& operator=(const Aws::Utils::Xml::XmlNode& xmlNode); void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const; void OutputToStream(Aws::OStream& oStream, const char* location) const; /** * <p>The version number used by the cluster.</p> */ inline const Aws::String& GetClusterVersion() const{ return m_clusterVersion; } /** * <p>The version number used by the cluster.</p> */ inline void SetClusterVersion(const Aws::String& value) { m_clusterVersionHasBeenSet = true; m_clusterVersion = value; } /** * <p>The version number used by the cluster.</p> */ inline void SetClusterVersion(Aws::String&& value) { m_clusterVersionHasBeenSet = true; m_clusterVersion = std::move(value); } /** * <p>The version number used by the cluster.</p> */ inline void SetClusterVersion(const char* value) { m_clusterVersionHasBeenSet = true; m_clusterVersion.assign(value); } /** * <p>The version number used by the cluster.</p> */ inline ClusterVersion& WithClusterVersion(const Aws::String& value) { SetClusterVersion(value); return *this;} /** * <p>The version number used by the cluster.</p> */ inline ClusterVersion& WithClusterVersion(Aws::String&& value) { SetClusterVersion(std::move(value)); return *this;} /** * <p>The version number used by the cluster.</p> */ inline ClusterVersion& WithClusterVersion(const char* value) { SetClusterVersion(value); return *this;} /** * <p>The name of the cluster parameter group family for the cluster.</p> */ inline const Aws::String& GetClusterParameterGroupFamily() const{ return m_clusterParameterGroupFamily; } /** * <p>The name of the cluster parameter group family for the cluster.</p> */ inline void SetClusterParameterGroupFamily(const Aws::String& value) { m_clusterParameterGroupFamilyHasBeenSet = true; m_clusterParameterGroupFamily = value; } /** * <p>The name of the cluster parameter group family for the cluster.</p> */ inline void SetClusterParameterGroupFamily(Aws::String&& value) { m_clusterParameterGroupFamilyHasBeenSet = true; m_clusterParameterGroupFamily = std::move(value); } /** * <p>The name of the cluster parameter group family for the cluster.</p> */ inline void SetClusterParameterGroupFamily(const char* value) { m_clusterParameterGroupFamilyHasBeenSet = true; m_clusterParameterGroupFamily.assign(value); } /** * <p>The name of the cluster parameter group family for the cluster.</p> */ inline ClusterVersion& WithClusterParameterGroupFamily(const Aws::String& value) { SetClusterParameterGroupFamily(value); return *this;} /** * <p>The name of the cluster parameter group family for the cluster.</p> */ inline ClusterVersion& WithClusterParameterGroupFamily(Aws::String&& value) { SetClusterParameterGroupFamily(std::move(value)); return *this;} /** * <p>The name of the cluster parameter group family for the cluster.</p> */ inline ClusterVersion& WithClusterParameterGroupFamily(const char* value) { SetClusterParameterGroupFamily(value); return *this;} /** * <p>The description of the cluster version.</p> */ inline const Aws::String& GetDescription() const{ return m_description; } /** * <p>The description of the cluster version.</p> */ inline void SetDescription(const Aws::String& value) { m_descriptionHasBeenSet = true; m_description = value; } /** * <p>The description of the cluster version.</p> */ inline void SetDescription(Aws::String&& value) { m_descriptionHasBeenSet = true; m_description = std::move(value); } /** * <p>The description of the cluster version.</p> */ inline void SetDescription(const char* value) { m_descriptionHasBeenSet = true; m_description.assign(value); } /** * <p>The description of the cluster version.</p> */ inline ClusterVersion& WithDescription(const Aws::String& value) { SetDescription(value); return *this;} /** * <p>The description of the cluster version.</p> */ inline ClusterVersion& WithDescription(Aws::String&& value) { SetDescription(std::move(value)); return *this;} /** * <p>The description of the cluster version.</p> */ inline ClusterVersion& WithDescription(const char* value) { SetDescription(value); return *this;} private: Aws::String m_clusterVersion; bool m_clusterVersionHasBeenSet; Aws::String m_clusterParameterGroupFamily; bool m_clusterParameterGroupFamilyHasBeenSet; Aws::String m_description; bool m_descriptionHasBeenSet; }; } // namespace Model } // namespace Redshift } // namespace Aws
chiaming0914/awe-cpp-sdk
aws-cpp-sdk-redshift/include/aws/redshift/model/ClusterVersion.h
C
apache-2.0
6,143
/* * 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 * * 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.streams.console; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Preconditions; import org.apache.streams.core.StreamsDatum; import org.apache.streams.core.StreamsPersistWriter; import org.apache.streams.jackson.StreamsJacksonMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.PrintStream; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; public class ConsolePersistWriter implements StreamsPersistWriter { private static final Logger LOGGER = LoggerFactory.getLogger(ConsolePersistWriter.class); protected PrintStream printStream = System.out; protected volatile Queue<StreamsDatum> persistQueue; private ObjectMapper mapper = StreamsJacksonMapper.getInstance(); public ConsolePersistWriter() { this.persistQueue = new ConcurrentLinkedQueue<StreamsDatum>(); } public ConsolePersistWriter(PrintStream printStream) { this(); this.printStream = printStream; } public void prepare(Object o) { Preconditions.checkNotNull(persistQueue); } public void cleanUp() { } @Override public void write(StreamsDatum entry) { try { String text = mapper.writeValueAsString(entry); printStream.println(text); } catch (JsonProcessingException e) { LOGGER.warn("save: {}", e); } } }
w2ogroup/incubator-streams
streams-contrib/streams-persist-console/src/main/java/org/apache/streams/console/ConsolePersistWriter.java
Java
apache-2.0
2,248
<!DOCTYPE html> <!-- Template Name: Metronic - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.3.2 Version: 3.7.0 Author: KeenThemes Website: http://www.keenthemes.com/ Contact: support@keenthemes.com Follow: www.twitter.com/keenthemes Like: www.facebook.com/keenthemes Purchase: http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes License: You must have a valid license purchased only from themeforest(the above link) in order to legally use the theme for your project. --> <!--[if IE 8]> <html lang="en" class="ie8 no-js"> <![endif]--> <!--[if IE 9]> <html lang="en" class="ie9 no-js"> <![endif]--> <!--[if !IE]><!--> <html lang="en" dir="rtl"> <!--<![endif]--> <!-- BEGIN HEAD --> <head> <meta charset="utf-8"/> <title>Metronic | Extra - Contact Us</title> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta content="width=device-width, initial-scale=1.0" name="viewport"/> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <meta content="" name="description"/> <meta content="" name="author"/> <!-- BEGIN GLOBAL MANDATORY STYLES --> <link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700&subset=all" rel="stylesheet" type="text/css"> <link href="../../assets/global/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="../../assets/global/plugins/simple-line-icons/simple-line-icons.min.css" rel="stylesheet" type="text/css"> <link href="../../assets/global/plugins/bootstrap/css/bootstrap-rtl.min.css" rel="stylesheet" type="text/css"> <link href="../../assets/global/plugins/uniform/css/uniform.default.css" rel="stylesheet" type="text/css"> <link href="../../assets/global/plugins/bootstrap-switch/css/bootstrap-switch-rtl.min.css" rel="stylesheet" type="text/css"/> <!-- END GLOBAL MANDATORY STYLES --> <!-- BEGIN THEME STYLES --> <link href="../../assets/global/css/components-md-rtl.css" id="style_components" rel="stylesheet" type="text/css"/> <link href="../../assets/global/css/plugins-md-rtl.css" rel="stylesheet" type="text/css"/> <link href="../../assets/admin/layout4/css/layout-rtl.css" rel="stylesheet" type="text/css"/> <link id="style_color" href="../../assets/admin/layout4/css/themes/light-rtl.css" rel="stylesheet" type="text/css"/> <link href="../../assets/admin/layout4/css/custom-rtl.css" rel="stylesheet" type="text/css"/> <!-- END THEME STYLES --> <link rel="shortcut icon" href="favicon.ico"/> </head> <!-- END HEAD --> <!-- BEGIN BODY --> <!-- DOC: Apply "page-header-fixed-mobile" and "page-footer-fixed-mobile" class to body element to force fixed header or footer in mobile devices --> <!-- DOC: Apply "page-sidebar-closed" class to the body and "page-sidebar-menu-closed" class to the sidebar menu element to hide the sidebar by default --> <!-- DOC: Apply "page-sidebar-hide" class to the body to make the sidebar completely hidden on toggle --> <!-- DOC: Apply "page-sidebar-closed-hide-logo" class to the body element to make the logo hidden on sidebar toggle --> <!-- DOC: Apply "page-sidebar-hide" class to body element to completely hide the sidebar on sidebar toggle --> <!-- DOC: Apply "page-sidebar-fixed" class to have fixed sidebar --> <!-- DOC: Apply "page-footer-fixed" class to the body element to have fixed footer --> <!-- DOC: Apply "page-sidebar-reversed" class to put the sidebar on the right side --> <!-- DOC: Apply "page-full-width" class to the body element to have full width page without the sidebar menu --> <body class="page-md page-header-fixed page-sidebar-closed-hide-logo "> <!-- BEGIN HEADER --> <div class="page-header md-shadow-z-1-i navbar navbar-fixed-top"> <!-- BEGIN HEADER INNER --> <div class="page-header-inner"> <!-- BEGIN LOGO --> <div class="page-logo"> <a href="index.html"> <img src="../../assets/admin/layout4/img/logo-light.png" alt="logo" class="logo-default"/> </a> <div class="menu-toggler sidebar-toggler"> <!-- DOC: Remove the above "hide" to enable the sidebar toggler button on header --> </div> </div> <!-- END LOGO --> <!-- BEGIN RESPONSIVE MENU TOGGLER --> <a href="javascript:;" class="menu-toggler responsive-toggler" data-toggle="collapse" data-target=".navbar-collapse"> </a> <!-- END RESPONSIVE MENU TOGGLER --> <!-- BEGIN PAGE ACTIONS --> <!-- DOC: Remove "hide" class to enable the page header actions --> <div class="page-actions"> <div class="btn-group"> <button type="button" class="btn red-haze btn-sm dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <span class="hidden-sm hidden-xs">Actions&nbsp;</span><i class="fa fa-angle-down"></i> </button> <ul class="dropdown-menu" role="menu"> <li> <a href="javascript:;"> <i class="icon-docs"></i> New Post </a> </li> <li> <a href="javascript:;"> <i class="icon-tag"></i> New Comment </a> </li> <li> <a href="javascript:;"> <i class="icon-share"></i> Share </a> </li> <li class="divider"> </li> <li> <a href="javascript:;"> <i class="icon-flag"></i> Comments <span class="badge badge-success">4</span> </a> </li> <li> <a href="javascript:;"> <i class="icon-users"></i> Feedbacks <span class="badge badge-danger">2</span> </a> </li> </ul> </div> </div> <!-- END PAGE ACTIONS --> <!-- BEGIN PAGE TOP --> <div class="page-top"> <!-- BEGIN HEADER SEARCH BOX --> <!-- DOC: Apply "search-form-expanded" right after the "search-form" class to have half expanded search box --> <form class="search-form" action="extra_search.html" method="GET"> <div class="input-group"> <input type="text" class="form-control input-sm" placeholder="Search..." name="query"> <span class="input-group-btn"> <a href="javascript:;" class="btn submit"><i class="icon-magnifier"></i></a> </span> </div> </form> <!-- END HEADER SEARCH BOX --> <!-- BEGIN TOP NAVIGATION MENU --> <div class="top-menu"> <ul class="nav navbar-nav pull-right"> <li class="separator hide"> </li> <!-- BEGIN NOTIFICATION DROPDOWN --> <!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte --> <li class="dropdown dropdown-extended dropdown-notification dropdown-dark" id="header_notification_bar"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <i class="icon-bell"></i> <span class="badge badge-success"> 7 </span> </a> <ul class="dropdown-menu"> <li class="external"> <h3><span class="bold">12 pending</span> notifications</h3> <a href="extra_profile.html">view all</a> </li> <li> <ul class="dropdown-menu-list scroller" style="height: 250px;" data-handle-color="#637283"> <li> <a href="javascript:;"> <span class="time">just now</span> <span class="details"> <span class="label label-sm label-icon label-success"> <i class="fa fa-plus"></i> </span> New user registered. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">3 mins</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> Server #12 overloaded. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">10 mins</span> <span class="details"> <span class="label label-sm label-icon label-warning"> <i class="fa fa-bell-o"></i> </span> Server #2 not responding. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">14 hrs</span> <span class="details"> <span class="label label-sm label-icon label-info"> <i class="fa fa-bullhorn"></i> </span> Application error. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">2 days</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> Database overloaded 68%. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">3 days</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> A user IP blocked. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">4 days</span> <span class="details"> <span class="label label-sm label-icon label-warning"> <i class="fa fa-bell-o"></i> </span> Storage Server #4 not responding dfdfdfd. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">5 days</span> <span class="details"> <span class="label label-sm label-icon label-info"> <i class="fa fa-bullhorn"></i> </span> System Error. </span> </a> </li> <li> <a href="javascript:;"> <span class="time">9 days</span> <span class="details"> <span class="label label-sm label-icon label-danger"> <i class="fa fa-bolt"></i> </span> Storage server failed. </span> </a> </li> </ul> </li> </ul> </li> <!-- END NOTIFICATION DROPDOWN --> <li class="separator hide"> </li> <!-- BEGIN INBOX DROPDOWN --> <!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte --> <li class="dropdown dropdown-extended dropdown-inbox dropdown-dark" id="header_inbox_bar"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <i class="icon-envelope-open"></i> <span class="badge badge-danger"> 4 </span> </a> <ul class="dropdown-menu"> <li class="external"> <h3>You have <span class="bold">7 New</span> Messages</h3> <a href="inbox.html">view all</a> </li> <li> <ul class="dropdown-menu-list scroller" style="height: 275px;" data-handle-color="#637283"> <li> <a href="inbox.html?a=view"> <span class="photo"> <img src="../../assets/admin/layout3/img/avatar2.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Lisa Wong </span> <span class="time">Just Now </span> </span> <span class="message"> Vivamus sed auctor nibh congue nibh. auctor nibh auctor nibh... </span> </a> </li> <li> <a href="inbox.html?a=view"> <span class="photo"> <img src="../../assets/admin/layout3/img/avatar3.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Richard Doe </span> <span class="time">16 mins </span> </span> <span class="message"> Vivamus sed congue nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span> </a> </li> <li> <a href="inbox.html?a=view"> <span class="photo"> <img src="../../assets/admin/layout3/img/avatar1.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Bob Nilson </span> <span class="time">2 hrs </span> </span> <span class="message"> Vivamus sed nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span> </a> </li> <li> <a href="inbox.html?a=view"> <span class="photo"> <img src="../../assets/admin/layout3/img/avatar2.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Lisa Wong </span> <span class="time">40 mins </span> </span> <span class="message"> Vivamus sed auctor 40% nibh congue nibh... </span> </a> </li> <li> <a href="inbox.html?a=view"> <span class="photo"> <img src="../../assets/admin/layout3/img/avatar3.jpg" class="img-circle" alt=""> </span> <span class="subject"> <span class="from"> Richard Doe </span> <span class="time">46 mins </span> </span> <span class="message"> Vivamus sed congue nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span> </a> </li> </ul> </li> </ul> </li> <!-- END INBOX DROPDOWN --> <li class="separator hide"> </li> <!-- BEGIN TODO DROPDOWN --> <!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte --> <li class="dropdown dropdown-extended dropdown-tasks dropdown-dark" id="header_task_bar"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <i class="icon-calendar"></i> <span class="badge badge-primary"> 3 </span> </a> <ul class="dropdown-menu extended tasks"> <li class="external"> <h3>You have <span class="bold">12 pending</span> tasks</h3> <a href="page_todo.html">view all</a> </li> <li> <ul class="dropdown-menu-list scroller" style="height: 275px;" data-handle-color="#637283"> <li> <a href="javascript:;"> <span class="task"> <span class="desc">New release v1.2 </span> <span class="percent">30%</span> </span> <span class="progress"> <span style="width: 40%;" class="progress-bar progress-bar-success" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">40% Complete</span></span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Application deployment</span> <span class="percent">65%</span> </span> <span class="progress"> <span style="width: 65%;" class="progress-bar progress-bar-danger" aria-valuenow="65" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">65% Complete</span></span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Mobile app release</span> <span class="percent">98%</span> </span> <span class="progress"> <span style="width: 98%;" class="progress-bar progress-bar-success" aria-valuenow="98" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">98% Complete</span></span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Database migration</span> <span class="percent">10%</span> </span> <span class="progress"> <span style="width: 10%;" class="progress-bar progress-bar-warning" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">10% Complete</span></span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Web server upgrade</span> <span class="percent">58%</span> </span> <span class="progress"> <span style="width: 58%;" class="progress-bar progress-bar-info" aria-valuenow="58" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">58% Complete</span></span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">Mobile development</span> <span class="percent">85%</span> </span> <span class="progress"> <span style="width: 85%;" class="progress-bar progress-bar-success" aria-valuenow="85" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">85% Complete</span></span> </span> </a> </li> <li> <a href="javascript:;"> <span class="task"> <span class="desc">New UI release</span> <span class="percent">38%</span> </span> <span class="progress progress-striped"> <span style="width: 38%;" class="progress-bar progress-bar-important" aria-valuenow="18" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">38% Complete</span></span> </span> </a> </li> </ul> </li> </ul> </li> <!-- END TODO DROPDOWN --> <!-- BEGIN USER LOGIN DROPDOWN --> <!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte --> <li class="dropdown dropdown-user dropdown-dark"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true"> <span class="username username-hide-on-mobile"> Nick </span> <!-- DOC: Do not remove below empty space(&nbsp;) as its purposely used --> <img alt="" class="img-circle" src="../../assets/admin/layout4/img/avatar9.jpg"/> </a> <ul class="dropdown-menu dropdown-menu-default"> <li> <a href="extra_profile.html"> <i class="icon-user"></i> My Profile </a> </li> <li> <a href="page_calendar.html"> <i class="icon-calendar"></i> My Calendar </a> </li> <li> <a href="inbox.html"> <i class="icon-envelope-open"></i> My Inbox <span class="badge badge-danger"> 3 </span> </a> </li> <li> <a href="page_todo.html"> <i class="icon-rocket"></i> My Tasks <span class="badge badge-success"> 7 </span> </a> </li> <li class="divider"> </li> <li> <a href="extra_lock.html"> <i class="icon-lock"></i> Lock Screen </a> </li> <li> <a href="login.html"> <i class="icon-key"></i> Log Out </a> </li> </ul> </li> <!-- END USER LOGIN DROPDOWN --> </ul> </div> <!-- END TOP NAVIGATION MENU --> </div> <!-- END PAGE TOP --> </div> <!-- END HEADER INNER --> </div> <!-- END HEADER --> <div class="clearfix"> </div> <!-- BEGIN CONTAINER --> <div class="page-container"> <!-- BEGIN SIDEBAR --> <div class="page-sidebar-wrapper"> <!-- DOC: Set data-auto-scroll="false" to disable the sidebar from auto scrolling/focusing --> <!-- DOC: Change data-auto-speed="200" to adjust the sub menu slide up/down speed --> <div class="page-sidebar md-shadow-z-2-i navbar-collapse collapse"> <!-- BEGIN SIDEBAR MENU --> <!-- DOC: Apply "page-sidebar-menu-light" class right after "page-sidebar-menu" to enable light sidebar menu style(without borders) --> <!-- DOC: Apply "page-sidebar-menu-hover-submenu" class right after "page-sidebar-menu" to enable hoverable(hover vs accordion) sub menu mode --> <!-- DOC: Apply "page-sidebar-menu-closed" class right after "page-sidebar-menu" to collapse("page-sidebar-closed" class must be applied to the body element) the sidebar sub menu mode --> <!-- DOC: Set data-auto-scroll="false" to disable the sidebar from auto scrolling/focusing --> <!-- DOC: Set data-keep-expand="true" to keep the submenues expanded --> <!-- DOC: Set data-auto-speed="200" to adjust the sub menu slide up/down speed --> <ul class="page-sidebar-menu " data-keep-expanded="false" data-auto-scroll="true" data-slide-speed="200"> <li class="start "> <a href="index.html"> <i class="icon-home"></i> <span class="title">Dashboard</span> </a> </li> <li> <a href="javascript:;"> <i class="icon-basket"></i> <span class="title">eCommerce</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="ecommerce_index.html"> <i class="icon-home"></i> Dashboard</a> </li> <li> <a href="ecommerce_orders.html"> <i class="icon-basket"></i> Orders</a> </li> <li> <a href="ecommerce_orders_view.html"> <i class="icon-tag"></i> Order View</a> </li> <li> <a href="ecommerce_products.html"> <i class="icon-handbag"></i> Products</a> </li> <li> <a href="ecommerce_products_edit.html"> <i class="icon-pencil"></i> Product Edit</a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-rocket"></i> <span class="title">Page Layouts</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="layout_sidebar_reversed.html"> <span class="badge badge-warning">new</span>Right Sidebar Page</a> </li> <li> <a href="layout_sidebar_fixed.html"> Sidebar Fixed Page</a> </li> <li> <a href="layout_sidebar_closed.html"> Sidebar Closed Page</a> </li> <li> <a href="layout_blank_page.html"> Blank Page</a> </li> <li> <a href="layout_boxed_page.html"> Boxed Page</a> </li> <li> <a href="layout_language_bar.html"> Language Switch Bar</a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-diamond"></i> <span class="title">UI Features</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="ui_general.html"> General Components</a> </li> <li> <a href="ui_buttons.html"> Buttons</a> </li> <li> <a href="ui_icons.html"> <span class="badge badge-danger">new</span>Font Icons</a> </li> <li> <a href="ui_colors.html"> Flat UI Colors</a> </li> <li> <a href="ui_typography.html"> Typography</a> </li> <li> <a href="ui_tabs_accordions_navs.html"> Tabs, Accordions & Navs</a> </li> <li> <a href="ui_tree.html"> <span class="badge badge-danger">new</span>Tree View</a> </li> <li> <a href="ui_page_progress_style_1.html"> <span class="badge badge-warning">new</span>Page Progress Bar - Style 1</a> </li> <li> <a href="ui_blockui.html"> Block UI</a> </li> <li> <a href="ui_bootstrap_growl.html"> <span class="badge badge-roundless badge-warning">new</span>Bootstrap Growl Notifications</a> </li> <li> <a href="ui_notific8.html"> Notific8 Notifications</a> </li> <li> <a href="ui_toastr.html"> Toastr Notifications</a> </li> <li> <a href="ui_alert_dialog_api.html"> <span class="badge badge-danger">new</span>Alerts & Dialogs API</a> </li> <li> <a href="ui_session_timeout.html"> Session Timeout</a> </li> <li> <a href="ui_idle_timeout.html"> User Idle Timeout</a> </li> <li> <a href="ui_modals.html"> Modals</a> </li> <li> <a href="ui_extended_modals.html"> Extended Modals</a> </li> <li> <a href="ui_tiles.html"> Tiles</a> </li> <li> <a href="ui_datepaginator.html"> <span class="badge badge-success">new</span>Date Paginator</a> </li> <li> <a href="ui_nestable.html"> Nestable List</a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-puzzle"></i> <span class="title">UI Components</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="components_pickers.html"> Date & Time Pickers</a> </li> <li> <a href="components_context_menu.html"> Context Menu</a> </li> <li> <a href="components_dropdowns.html"> Custom Dropdowns</a> </li> <li> <a href="components_form_tools.html"> Form Widgets & Tools</a> </li> <li> <a href="components_form_tools2.html"> Form Widgets & Tools 2</a> </li> <li> <a href="components_editors.html"> Markdown & WYSIWYG Editors</a> </li> <li> <a href="components_ion_sliders.html"> Ion Range Sliders</a> </li> <li> <a href="components_noui_sliders.html"> NoUI Range Sliders</a> </li> <li> <a href="components_jqueryui_sliders.html"> jQuery UI Sliders</a> </li> <li> <a href="components_knob_dials.html"> Knob Circle Dials</a> </li> </ul> </li> <!-- BEGIN ANGULARJS LINK --> <li class="tooltips" data-container="body" data-placement="right" data-html="true" data-original-title="AngularJS version demo"> <a href="angularjs" target="_blank"> <i class="icon-paper-plane"></i> <span class="title"> AngularJS Version </span> </a> </li> <!-- END ANGULARJS LINK --> <li> <a href="javascript:;"> <i class="icon-settings"></i> <span class="title">Form Stuff</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="form_controls_md.html"> <span class="badge badge-roundless badge-danger">new</span>Material Design<br> Form Controls</a> </li> <li> <a href="form_controls.html"> Bootstrap<br> Form Controls</a> </li> <li> <a href="form_layouts.html"> Form Layouts</a> </li> <li> <a href="form_editable.html"> <span class="badge badge-warning">new</span>Form X-editable</a> </li> <li> <a href="form_wizard.html"> Form Wizard</a> </li> <li> <a href="form_validation.html"> Form Validation</a> </li> <li> <a href="form_image_crop.html"> <span class="badge badge-danger">new</span>Image Cropping</a> </li> <li> <a href="form_fileupload.html"> Multiple File Upload</a> </li> <li> <a href="form_dropzone.html"> Dropzone File Upload</a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-briefcase"></i> <span class="title">Data Tables</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="table_basic.html"> Basic Datatables</a> </li> <li> <a href="table_tree.html"> Tree Datatables</a> </li> <li> <a href="table_responsive.html"> Responsive Datatables</a> </li> <li> <a href="table_managed.html"> Managed Datatables</a> </li> <li> <a href="table_editable.html"> Editable Datatables</a> </li> <li> <a href="table_advanced.html"> Advanced Datatables</a> </li> <li> <a href="table_ajax.html"> Ajax Datatables</a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-wallet"></i> <span class="title">Portlets</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="portlet_general.html"> General Portlets</a> </li> <li> <a href="portlet_general2.html"> <span class="badge badge-danger">new</span>New Portlets #1</a> </li> <li> <a href="portlet_general3.html"> <span class="badge badge-danger">new</span>New Portlets #2</a> </li> <li> <a href="portlet_ajax.html"> Ajax Portlets</a> </li> <li> <a href="portlet_draggable.html"> Draggable Portlets</a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-bar-chart"></i> <span class="title">Charts</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="charts_amcharts.html"> Amchart</a> </li> <li> <a href="charts_flotcharts.html"> Flotchart</a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-docs"></i> <span class="title">Pages</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="page_timeline.html"> <i class="icon-paper-plane"></i> <span class="badge badge-warning">2</span>New Timeline</a> </li> <li> <a href="extra_profile.html"> <i class="icon-user-following"></i> <span class="badge badge-success badge-roundless">new</span>New User Profile</a> </li> <li> <a href="page_todo.html"> <i class="icon-hourglass"></i> <span class="badge badge-danger">4</span>Todo</a> </li> <li> <a href="inbox.html"> <i class="icon-envelope"></i> <span class="badge badge-danger">4</span>Inbox</a> </li> <li> <a href="extra_faq.html"> <i class="icon-info"></i> FAQ</a> </li> <li> <a href="page_portfolio.html"> <i class="icon-feed"></i> Portfolio</a> </li> <li> <a href="page_timeline.html"> <i class="icon-clock"></i> <span class="badge badge-info">4</span>Timeline</a> </li> <li> <a href="page_coming_soon.html"> <i class="icon-flag"></i> Coming Soon</a> </li> <li> <a href="page_calendar.html"> <i class="icon-calendar"></i> <span class="badge badge-danger">14</span>Calendar</a> </li> <li> <a href="extra_invoice.html"> <i class="icon-flag"></i> Invoice</a> </li> <li> <a href="page_blog.html"> <i class="icon-speech"></i> Blog</a> </li> <li> <a href="page_blog_item.html"> <i class="icon-link"></i> Blog Post</a> </li> <li> <a href="page_news.html"> <i class="icon-eye"></i> <span class="badge badge-success">9</span>News</a> </li> <li> <a href="page_news_item.html"> <i class="icon-bell"></i> News View</a> </li> <li> <a href="page_timeline_old.html"> <i class="icon-paper-plane"></i> <span class="badge badge-warning">2</span>Old Timeline</a> </li> <li> <a href="extra_profile_old.html"> <i class="icon-user"></i> Old User Profile</a> </li> </ul> </li> <li class="active open"> <a href="javascript:;"> <i class="icon-present"></i> <span class="title">Extra</span> <span class="arrow open"></span> </a> <ul class="sub-menu"> <li> <a href="page_about.html"> About Us</a> </li> <li class="active"> <a href="page_contact.html"> Contact Us</a> </li> <li> <a href="extra_search.html"> Search Results</a> </li> <li> <a href="extra_pricing_table.html"> Pricing Tables</a> </li> <li> <a href="extra_404_option1.html"> 404 Page Option 1</a> </li> <li> <a href="extra_404_option2.html"> 404 Page Option 2</a> </li> <li> <a href="extra_404_option3.html"> 404 Page Option 3</a> </li> <li> <a href="extra_500_option1.html"> 500 Page Option 1</a> </li> <li> <a href="extra_500_option2.html"> 500 Page Option 2</a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-folder"></i> <span class="title">Multi Level Menu</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="javascript:;"> <i class="icon-settings"></i> Item 1 <span class="arrow"></span> </a> <ul class="sub-menu"> <li> <a href="javascript:;"> <i class="icon-user"></i> Sample Link 1 <span class="arrow"></span> </a> <ul class="sub-menu"> <li> <a href="#"><i class="icon-power"></i> Sample Link 1</a> </li> <li> <a href="#"><i class="icon-paper-plane"></i> Sample Link 1</a> </li> <li> <a href="#"><i class="icon-star"></i> Sample Link 1</a> </li> </ul> </li> <li> <a href="#"><i class="icon-camera"></i> Sample Link 1</a> </li> <li> <a href="#"><i class="icon-link"></i> Sample Link 2</a> </li> <li> <a href="#"><i class="icon-pointer"></i> Sample Link 3</a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-globe"></i> Item 2 <span class="arrow"></span> </a> <ul class="sub-menu"> <li> <a href="#"><i class="icon-tag"></i> Sample Link 1</a> </li> <li> <a href="#"><i class="icon-pencil"></i> Sample Link 1</a> </li> <li> <a href="#"><i class="icon-graph"></i> Sample Link 1</a> </li> </ul> </li> <li> <a href="#"> <i class="icon-bar-chart"></i> Item 3 </a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-user"></i> <span class="title">Login Options</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="login.html"> Login Form 1</a> </li> <li> <a href="login_2.html"> Login Form 2</a> </li> <li> <a href="login_3.html"> Login Form 3</a> </li> <li> <a href="login_soft.html"> Login Form 4</a> </li> <li> <a href="extra_lock.html"> Lock Screen 1</a> </li> <li> <a href="extra_lock2.html"> Lock Screen 2</a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="icon-envelope-open"></i> <span class="title">Email Templates</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="email_template1.html"> New Email Template 1</a> </li> <li> <a href="email_template2.html"> New Email Template 2</a> </li> <li> <a href="email_template3.html"> New Email Template 3</a> </li> <li> <a href="email_template4.html"> New Email Template 4</a> </li> <li> <a href="email_newsletter.html"> Old Email Template 1</a> </li> <li> <a href="email_system.html"> Old Email Template 2</a> </li> </ul> </li> <li class="last "> <a href="javascript:;"> <i class="icon-pointer"></i> <span class="title">Maps</span> <span class="arrow "></span> </a> <ul class="sub-menu"> <li> <a href="maps_google.html"> Google Maps</a> </li> <li> <a href="maps_vector.html"> Vector Maps</a> </li> </ul> </li> </ul> <!-- END SIDEBAR MENU --> </div> </div> <!-- END SIDEBAR --> <!-- BEGIN CONTENT --> <div class="page-content-wrapper"> <div class="page-content"> <!-- BEGIN SAMPLE PORTLET CONFIGURATION MODAL FORM--> <div class="modal fade" id="portlet-config" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button> <h4 class="modal-title">Modal title</h4> </div> <div class="modal-body"> Widget settings form goes here </div> <div class="modal-footer"> <button type="button" class="btn blue">Save changes</button> <button type="button" class="btn default" data-dismiss="modal">Close</button> </div> </div> <!-- /.modal-content --> </div> <!-- /.modal-dialog --> </div> <!-- /.modal --> <!-- END SAMPLE PORTLET CONFIGURATION MODAL FORM--> <!-- BEGIN PAGE HEADER--> <!-- BEGIN PAGE HEAD --> <div class="page-head"> <!-- BEGIN PAGE TITLE --> <div class="page-title"> <h1>Contact Us <small>contact us page</small></h1> </div> <!-- END PAGE TITLE --> <!-- BEGIN PAGE TOOLBAR --> <div class="page-toolbar"> <!-- BEGIN THEME PANEL --> <div class="btn-group btn-theme-panel"> <a href="javascript:;" class="btn dropdown-toggle" data-toggle="dropdown"> <i class="icon-settings"></i> </a> <div class="dropdown-menu theme-panel pull-right dropdown-custom hold-on-click"> <div class="row"> <div class="col-md-4 col-sm-4 col-xs-12"> <h3>THEME</h3> <ul class="theme-colors"> <li class="theme-color theme-color-default active" data-theme="default"> <span class="theme-color-view"></span> <span class="theme-color-name">Dark Header</span> </li> <li class="theme-color theme-color-light" data-theme="light"> <span class="theme-color-view"></span> <span class="theme-color-name">Light Header</span> </li> </ul> </div> <div class="col-md-8 col-sm-8 col-xs-12 seperator"> <h3>LAYOUT</h3> <ul class="theme-settings"> <li> Theme Style <select class="layout-style-option form-control input-small input-sm"> <option value="square" selected="selected">Square corners</option> <option value="rounded">Rounded corners</option> </select> </li> <li> Layout <select class="layout-option form-control input-small input-sm"> <option value="fluid" selected="selected">Fluid</option> <option value="boxed">Boxed</option> </select> </li> <li> Header <select class="page-header-option form-control input-small input-sm"> <option value="fixed" selected="selected">Fixed</option> <option value="default">Default</option> </select> </li> <li> Top Dropdowns <select class="page-header-top-dropdown-style-option form-control input-small input-sm"> <option value="light">Light</option> <option value="dark" selected="selected">Dark</option> </select> </li> <li> Sidebar Mode <select class="sidebar-option form-control input-small input-sm"> <option value="fixed">Fixed</option> <option value="default" selected="selected">Default</option> </select> </li> <li> Sidebar Menu <select class="sidebar-menu-option form-control input-small input-sm"> <option value="accordion" selected="selected">Accordion</option> <option value="hover">Hover</option> </select> </li> <li> Sidebar Position <select class="sidebar-pos-option form-control input-small input-sm"> <option value="left" selected="selected">Left</option> <option value="right">Right</option> </select> </li> <li> Footer <select class="page-footer-option form-control input-small input-sm"> <option value="fixed">Fixed</option> <option value="default" selected="selected">Default</option> </select> </li> </ul> </div> </div> </div> </div> <!-- END THEME PANEL --> </div> <!-- END PAGE TOOLBAR --> </div> <!-- END PAGE HEAD --> <!-- BEGIN PAGE BREADCRUMB --> <ul class="page-breadcrumb breadcrumb"> <li> <a href="index.html">Home</a> <i class="fa fa-circle"></i> </li> <li> <a href="#">Extra</a> <i class="fa fa-circle"></i> </li> <li> <a href="#">Contact Us</a> </li> </ul> <!-- END PAGE BREADCRUMB --> <!-- END PAGE HEADER--> <!-- BEGIN PAGE CONTENT--> <div class="portlet light"> <div class="portlet-body"> <div class="row"> <div class="col-md-12"> <!-- Google Map --> <div class="row"> <div id="map" class="gmaps margin-bottom-40" style="height:400px;"> </div> </div> <div class="row margin-bottom-20"> <div class="col-md-6"> <div class="space20"> </div> <h3 class="form-section">Contacts</h3> <p> Lorem ipsum dolor sit amet, Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat consectetuer adipiscing elit. </p> <div class="well"> <h4>Address</h4> <address> <strong>Loop, Inc.</strong><br> 795 Park Ave, Suite 120<br> San Francisco, CA 94107<br> <abbr title="Phone">P:</abbr> (234) 145-1810 </address> <address> <strong>Email</strong><br> <a href="mailto:#"> first.last@email.com </a> </address> <ul class="social-icons margin-bottom-10"> <li> <a href="javascript:;" data-original-title="facebook" class="facebook"> </a> </li> <li> <a href="javascript:;" data-original-title="github" class="github"> </a> </li> <li> <a href="javascript:;" data-original-title="Goole Plus" class="googleplus"> </a> </li> <li> <a href="javascript:;" data-original-title="linkedin" class="linkedin"> </a> </li> <li> <a href="javascript:;" data-original-title="rss" class="rss"> </a> </li> <li> <a href="javascript:;" data-original-title="skype" class="skype"> </a> </li> <li> <a href="javascript:;" data-original-title="twitter" class="twitter"> </a> </li> <li> <a href="javascript:;" data-original-title="youtube" class="youtube"> </a> </li> </ul> </div> </div> <div class="col-md-6"> <div class="space20"> </div> <!-- BEGIN FORM--> <form action="#"> <h3 class="form-section">Feedback</h3> <p> Lorem ipsum dolor sit amet, Ut wisi enim ad minim veniam, quis nostrud exerci. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat consectetuer </p> <div class="form-group"> <div class="input-icon"> <i class="fa fa-check"></i> <input type="text" class="form-control" placeholder="Subject"> </div> </div> <div class="form-group"> <div class="input-icon"> <i class="fa fa-user"></i> <input type="text" class="form-control" placeholder="Name"> </div> </div> <div class="form-group"> <div class="input-icon"> <i class="fa fa-envelope"></i> <input type="password" class="form-control" placeholder="Email"> </div> </div> <div class="form-group"> <textarea class="form-control" rows="3=6" placeholder="Feedback"></textarea> </div> <button type="submit" class="btn green">Submit</button> </form> <!-- END FORM--> </div> </div> </div> </div> </div> </div> <!-- END PAGE CONTENT--> </div> </div> <!-- END CONTENT --> </div> <!-- END CONTAINER --> <!-- BEGIN FOOTER --> <div class="page-footer"> <div class="page-footer-inner"> 2014 &copy; Metronic by keenthemes. </div> <div class="scroll-to-top"> <i class="icon-arrow-up"></i> </div> </div> <!-- END FOOTER --> <!-- BEGIN JAVASCRIPTS(Load javascripts at bottom, this will reduce page load time) --> <!-- BEGIN CORE PLUGINS --> <!--[if lt IE 9]> <script src="../../assets/global/plugins/respond.min.js"></script> <script src="../../assets/global/plugins/excanvas.min.js"></script> <![endif]--> <script src="../../assets/global/plugins/jquery.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/jquery-migrate.min.js" type="text/javascript"></script> <!-- IMPORTANT! Load jquery-ui.min.js before bootstrap.min.js to fix bootstrap tooltip conflict with jquery ui tooltip --> <script src="../../assets/global/plugins/jquery-ui/jquery-ui.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/bootstrap-hover-dropdown/bootstrap-hover-dropdown.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/jquery-slimscroll/jquery.slimscroll.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/jquery.blockui.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/jquery.cokie.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/uniform/jquery.uniform.min.js" type="text/javascript"></script> <script src="../../assets/global/plugins/bootstrap-switch/js/bootstrap-switch.min.js" type="text/javascript"></script> <!-- END CORE PLUGINS --> <script src="http://maps.google.com/maps/api/js?sensor=true" type="text/javascript"></script> <script src="../../assets/global/plugins/gmaps/gmaps.min.js" type="text/javascript"></script> <script src="../../assets/global/scripts/metronic.js" type="text/javascript"></script> <script src="../../assets/admin/layout4/scripts/layout.js" type="text/javascript"></script> <script src="../../assets/admin/layout4/scripts/demo.js" type="text/javascript"></script> <script src="../../assets/admin/pages/scripts/contact-us.js"></script> <script> jQuery(document).ready(function() { Metronic.init(); // init metronic core components Layout.init(); // init current layout Demo.init(); // init demo features ContactUs.init(); }); </script> <!-- END JAVASCRIPTS --> </body> <!-- END BODY --> </html>
zzsoszz/metronicv37
theme_rtl/templates/admin4_material_design/page_contact.html
HTML
apache-2.0
47,451
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.repositories.s3; import com.amazonaws.util.json.Jackson; import org.elasticsearch.SpecialPermission; import org.elasticsearch.cluster.metadata.RepositoryMetaData; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.NamedXContentRegistry; import org.elasticsearch.env.Environment; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.plugins.ReloadablePlugin; import org.elasticsearch.plugins.RepositoryPlugin; import org.elasticsearch.repositories.Repository; import org.elasticsearch.threadpool.ThreadPool; import java.io.IOException; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; /** * A plugin to add a repository type that writes to and from the AWS S3. */ public class S3RepositoryPlugin extends Plugin implements RepositoryPlugin, ReloadablePlugin { static { SpecialPermission.check(); AccessController.doPrivileged((PrivilegedAction<Void>) () -> { try { // kick jackson to do some static caching of declared members info Jackson.jsonNodeOf("{}"); // ClientConfiguration clinit has some classloader problems // TODO: fix that Class.forName("com.amazonaws.ClientConfiguration"); } catch (final ClassNotFoundException e) { throw new RuntimeException(e); } return null; }); } protected final S3Service service; public S3RepositoryPlugin(final Settings settings) { this(settings, new S3Service()); } S3RepositoryPlugin(final Settings settings, final S3Service service) { this.service = Objects.requireNonNull(service, "S3 service must not be null"); // eagerly load client settings so that secure settings are read final Map<String, S3ClientSettings> clientsSettings = S3ClientSettings.load(settings); this.service.refreshAndClearCache(clientsSettings); } // proxy method for testing protected S3Repository createRepository( final RepositoryMetaData metadata, final NamedXContentRegistry registry, final ThreadPool threadPool) { return new S3Repository(metadata, registry, service, threadPool); } @Override public Map<String, Repository.Factory> getRepositories(final Environment env, final NamedXContentRegistry registry, final ThreadPool threadPool) { return Collections.singletonMap(S3Repository.TYPE, metadata -> createRepository(metadata, registry, threadPool)); } @Override public List<Setting<?>> getSettings() { return Arrays.asList( // named s3 client configuration settings S3ClientSettings.ACCESS_KEY_SETTING, S3ClientSettings.SECRET_KEY_SETTING, S3ClientSettings.SESSION_TOKEN_SETTING, S3ClientSettings.ENDPOINT_SETTING, S3ClientSettings.PROTOCOL_SETTING, S3ClientSettings.PROXY_HOST_SETTING, S3ClientSettings.PROXY_PORT_SETTING, S3ClientSettings.PROXY_USERNAME_SETTING, S3ClientSettings.PROXY_PASSWORD_SETTING, S3ClientSettings.READ_TIMEOUT_SETTING, S3ClientSettings.MAX_RETRIES_SETTING, S3ClientSettings.USE_THROTTLE_RETRIES_SETTING, S3ClientSettings.USE_PATH_STYLE_ACCESS); } @Override public void reload(Settings settings) { // secure settings should be readable final Map<String, S3ClientSettings> clientsSettings = S3ClientSettings.load(settings); service.refreshAndClearCache(clientsSettings); } @Override public void close() throws IOException { service.close(); } }
coding0011/elasticsearch
plugins/repository-s3/src/main/java/org/elasticsearch/repositories/s3/S3RepositoryPlugin.java
Java
apache-2.0
4,783
/* 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.batik.ext.awt.image.rendered; import java.util.List; import java.util.ArrayList; /** * This class is responsible for breaking up a block of tiles into * a set of smaller requests that are as large as possible without * rerequesting significant numbers of tiles that are already * available. * * @version $Id$ */ public class TileBlock { int occX, occY, occW, occH; int xOff, yOff, w, h, benefit; boolean [] occupied; /** * Construct a tile block this represents a block of contigous * tiles. * @param xOff The x index of left edge of the tile block. * @param yOff The y index of top edge of the tile block. * @param w The number of tiles across in the block * @param h The number of tiles down the block * @param occupied Which entries in the block are already * computed. */ TileBlock(int occX, int occY, int occW, int occH, boolean [] occupied, int xOff, int yOff, int w, int h) { this.occX = occX; this.occY = occY; this.occW = occW; this.occH = occH; this.xOff = xOff; this.yOff = yOff; this.w = w ; this.h = h ; this.occupied = occupied; // System.out.println("Block: [" + // xloc + "," + yloc + "," + // w + "," + h + "]"); for (int y=0; y<h; y++) for (int x=0; x<w; x++) if (!occupied[x+xOff+occW*(y+yOff)]) benefit++; } /** * Really nice to string that outlines what tiles are filled * and what region this block covers. Really useful for * debugging the TileBlock stuff. */ public String toString() { String ret = ""; for (int y=0; y<occH; y++) { for (int x=0; x<occW+1; x++) { if ((x==xOff) || (x==xOff+w)) { if ((y==yOff) || (y==yOff+h-1)) ret += "+"; else if ((y>yOff) && (y<yOff+h-1)) ret += "|"; else ret += " "; } else if ((y==yOff) && (x> xOff) && (x < xOff+w)) ret += "-"; else if ((y==yOff+h-1) && (x> xOff) && (x < xOff+w)) ret += "_"; else ret += " "; if (x== occW) continue; if (occupied[x+y*occW]) ret += "*"; else ret += "."; } ret += "\n"; } return ret; } /** * Return the x location of this block of tiles */ int getXLoc() { return occX+xOff; } /** * Return the y location of this block of tiles */ int getYLoc() { return occY+yOff; } /** * Return the width of this block of tiles */ int getWidth() { return w; } /** * Return the height of this block of tiles */ int getHeight() { return h; } /** * Return the number of new tiles computed. */ int getBenefit() { return benefit; } /** * Return the approximate amount of work required to compute * those tiles. */ int getWork() { return w*h+1; } /** * Returns the total amount of work for the array of tile blocks */ static int getWork(TileBlock [] blocks) { int ret=0; for (int i=0; i<blocks.length; i++) ret += blocks[i].getWork(); return ret; } /** * Returnes an optimized list of TileBlocks to generate that * tries to minimize the work to benefit ratio, for the set of * blocks defined by this block. */ TileBlock [] getBestSplit() { if (simplify()) return null; // Optimal split already... if (benefit == w*h) return new TileBlock [] { this }; return splitOneGo(); } public TileBlock [] splitOneGo() { boolean [] filled = (boolean [])occupied.clone(); List items = new ArrayList(); for (int y=yOff; y<yOff+h; y++) for (int x=xOff; x<xOff+w; x++) { if (!filled[x+y*occW]) { // We have an unfilled tile slot, so first we // figure out how long the slot is in this row. int cw = xOff+w-x; for (int cx=x; cx<x+cw; cx++) if (filled[cx+y*occW]) cw = cx-x; else filled[cx+y*occW] = true; // fill as we go.. // Then we check the next rows until we hit // a row that doesn't have this slot all free. // at which point we stop... int ch=1; for (int cy=y+1; cy<yOff+h; cy++) { int cx=x; for (; cx<x+cw; cx++) if (filled[cx+cy*occW]) break; // Partial row so bail (we'll get it later..) if (cx != x+cw) break; // Fill in the slot since we will use it... for (cx=x; cx<x+cw; cx++) filled[cx+cy*occW] = true; ch++; } items.add(new TileBlock(occX, occY, occW, occH, occupied, x, y, cw, ch)); x+=(cw-1); } } TileBlock [] ret = new TileBlock[items.size()]; items.toArray( ret ); return ret; } public boolean simplify() { boolean[] workOccupied = occupied; // local is cheaper for (int y=0; y<h; y++) { int x; for (x=0; x<w; x++) if (!workOccupied[x+xOff+occW*(y+yOff)]) break; if (x!=w) break; // Fully occupied row so remove it. yOff++; y--; h--; } // return true if we were simplified out of existance. if (h==0) return true; // If we make it past here we must have at least one good block. for (int y=h-1; y>=0; y--) { int x; for (x=0; x<w; x++) if (!workOccupied[x+xOff+occW*(y+yOff)]) break; if (x!=w) break; // Fully occupied row so remove it. h--; } for (int x=0; x<w; x++) { int y; for (y=0; y<h; y++) if (!workOccupied[x+xOff+occW*(y+yOff)]) break; if (y!=h) break; // Fully occupied Col so remove it. xOff++; x--; w--; } for (int x=w-1; x>=0; x--) { int y; for (y=0; y<h; y++) if (!workOccupied[x+xOff+occW*(y+yOff)]) break; if (y!=h) break; // Fully occupied Col so remove it. w--; } return false; } }
Squeegee/batik
sources/org/apache/batik/ext/awt/image/rendered/TileBlock.java
Java
apache-2.0
8,134
--- layout: global title: CACHE TABLE displayTitle: CACHE TABLE license: | 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. --- **This page is under construction**
kiszk/spark
docs/sql-ref-syntax-aux-cache-cache-table.md
Markdown
apache-2.0
896
Schoolbus Inspection Tracking System ====================== OpenShift Configuration and Deployment ---------------- The tran-schoolbus-tools (Tools) project contains the Build Configurations (bc) and Image Streams (is) that are referenced by the Deployment Configurations. The following projects contain the Deployment Configurations (dc) for the various types of deployments: - tran-schoolbus-dev (Development) - tran-schoolbus-test (Test) - tran-schoolbus-prod (Production) In Schoolbus there are 6 components that are deployed - nginx reverse proxy - Postgres Database, built based on the Red Hat Postgres image - .NET Core Front End Server, which also contains the compiled UI files - .NET Core API Server - .NET Core PDF microservice - .NET Core CCW microservice Steps to configure the deployment: ---------------------------------- Ensure that you have access to the build and deployment templates. These can be found in the openshift/templates folder of the project repository. If you are setting up a local OpenShift cluster for development, fork the main project. You'll be using your own fork. Connect to the OpenShift server using the CLI; either your local instance or the production instance. If you have not connected to the production instance before, use the web interface as you will need to login though your GitHub account. Once you login you'll be able to get the token you'll need to login to you project(s) through the CLI from here; Token Request Page. The CLI will also give you a URL to go to if you attempt a login to the OpenShift server without a token. The same basic procedure, minus the GitHub part, can be used to connect to your local instance. Login to the server using the oc command from the page. Switch to the Tools project by running: `oc project tran-schoolbus-tools` `oc process -f https://raw.githubusercontent.com/bcgov/schoolbus/master/openshift/templates/schoolbus-build-template.json > schoolbus-build.json` Create the resources from the resulting file by running `oc create -f schoolbus-build.json` This will produce several builds and image streams. You can now login to the web interface and observe the progress of the initial build. Once the initial build is done, create builds with tags "dev", "test", and "prod" as required for deployment. The deployment configurations will use these tags to determine which image to load. You can edit a build to change the tag. Once you have images tagged for dev, test or prod you are ready to deploy. Open a command prompt and login as above to OpenShift Change to the project for the type of deployment you are configuring. For example, to configure a dev build, switch to tran-schoolbus-dev In the command prompt, type `oc project tran-schoolbus-dev` By default projects do not have permission to access images from other projects. You will need to grant that. Run the following: `oc policy add-role-to-user system:image-puller system:serviceaccount:<project_identifier>:default -n <project namespace where project_identifier needs access>` EXAMPLE - to allow the production project access to the images, run: `oc policy add-role-to-user system:image-puller system:serviceaccount:tran-schoolbus-prod:default -n tran-schoolbus-tools` Decide which Deployment Template you will use. For local test deployments to an environment that does not support persistent volumes, use schoolbus-deployment-template-emptydir.json For any deployment to an environment that does support persistent volumes (such as production), use `schoolbus-deployment-template.json` Parse the deployment template: In the command prompt, type: `oc process -f <deployment template> <target-file>` (where target file is an appropriate filename for the deployment implementation .json) Create the output of the parse: In the command prompt, type: `oc create -f <target-file>` This should produce several deployment configurations, persistent volume claims and services. Verify that the Overview looks correct in the web UI for the project you provisioned If there are any orphan services (a service without a deployment configuration), edit the YAML for the DC and SVC so that the selectors match the labels. If this is not done, then it will not be possible to route traffic to the pod containing the application component for the service You can now trigger deployments. -Go to the Deployments page -Select the component to deploy by clicking the name -Click Deploy If any builds or deployments fail, you can use the events view to see detailed errors. The Postgresql deployment does not automatically run - be sure to deploy it otherwise the Server component will not be able to connect to the database. Secrets ------- Secrets must be manually added to the environment, using an account that has the authority to add secrets. There are several secret files used by the application: **Users.json** `[ { "active": true, "email": ""email address, "givenName": "Given Name", "id": "Id field", "initials": "Initials", "smUserID": "Siteminder User ID", "surname": "Surname", "groupMemberships": [{"Group" : {"name": "Group Name"}}], "userRoles": [{"Role": {"Name": "Role Name"}}] }, <other users> ]` **districts.json** `[ { "endDate": null, "id": "1", "ministryDistrict": "1", "name": "Lower Mainland", "region": { "id": "1", "ministryRegionID": "1" }, "startDate": "1/1/2009" }, <other districts>` ]` **regions.json** `[ { "Name": "South Coast", "endDate": null, "id": "1", "ministryRegionID": "1", "startDate": "1/1/2009" }, <other regions> ]` **CCW.json** `{ "CCW_userId":"Siteminder User ID for the user that will login to CCW", "CCW_guid":"Siteminder GUID for the user that will login to CCW", "CCW_directory":"Siteminder directory for the user that will login to CCW", "CCW_endpointURL":"Endpoint assigned to the application for CCW access", "CCW_applicationIdentifier":"Application Identifier assigned to the application", "CCW_basicAuth_username":"Basic auth username for CCW", "CCW_basicAuth_password":"Basic auth password for CCW" }` In order to provision these secrets, files will need to be created in a secure area of your PC. Then execute the following commands: `oc secrets new ccw-secret ccw.json` Put the remaining secrets inside a folder, which in this example is called secrets `oc secrets new schoolbus-secret secrets` Jenkins Basic Configuration --------------------------- A job will need to be setup for each Build Configuration. This job will be used to build and promote each build configuration. - Configure the job to promote to DEV / TEST / PROD as appropriate - Set Properties Content to: `OS_IMAGE_TAG=jenkins-$PROMOTED_JOB_NAME-$PROMOTED_NUMBER` - Set Execute Shell to (this is an example): `$oc_cmd tag "tran-schoolbus-tools/client:$OS_IMAGE_TAG" tran-schoolbus-tools/client:dev` - Add the Openshift Build action - Enter the name of the BuildConfig to trigger - for example, "client" - Enter the name of the project the BuildConfig is stored on - for example "tran-schoolbus-tools" - Enable pipe the build logs from OpenShift - Add the Tag Openshift Image action - Set the imagestream name to the appropriate image - for example, "client" - Set the name of the current tag to "latest" (ensure that the default tag for the build is also "latest") - Set the new tag to ${BUILD_TAG} (Jenkins will substitute appropriately) - Set the project apropriately, for example "tran-schoolbus-tools" - The FrontEnd build job should be configured to run after Client. Otherwise changes to the Client code will not get deployed. - The Client and Server jobs should be configured to auto build for the Dev instance Jenkins Automated Builds - Enable the GitHub plugin to Jenkins, and make note of the URL endpoint. - The URL endpoint can be found by going to the following: - Jenkins Home Page - Manage Jenkins - Configure Jenkins - Click the (?) in the GitHub section - An example URL endpoint is https://jenkins-tran-schoolbus-tools.pathfinder.gov.bc.ca/github-webhook/ - Request that the git repository administrator configure this as a web hook in the repository. The following info should be sent in the request: - Payload URL: https://jenkins-tran-schoolbus-tools.pathfinder.gov.bc.ca/github-webhook/ - Content type: application/json - Secret: blank, not used - SSL certificate is valid. - Just the push events - Active: Selected/Checked - Now you can configure jobs to use the webhook. Edit a job that builds from the repository - In the Source Code Repositories section, enable Git - Enter the URL of the repository, for example https://github.com/bcgov/schoolbus.git - In the Git Additional Behaviors section, add "Polling ignores commits in certain paths" and specify an included region, which matches the area of the repo containing files for the job. - For example Client/.* - In the Build Triggers section, check the box for "GitHub hook trigger for GITScm polling" - Older versions of the GitHub plugin called this "Build when a change is pushed to GitHub" - Verify that the build automatically runs when a pull request is approved Environment Variables -------------------- The following environment variables are used by the application: | Environment Variable | Purpose | Example | Notes | | ---------------------| ------- | ------- | ----- | | DATABASE_SERVICE_NAME | Database service | postgresql | set to localhost for local development | | POSTGRESQL_USER | PGSQL User | test | Must have enough access to create tables | | POSTGRESQL_PASSWORD | PGSQL User's Password | test | | | POSTGRESQL_DATABASE | Database name | schoolbus | | | UserInitializationFile | Location of user seed data | /secrets/users.json | Json format following the User model definition | | DistrictInitializationFile | Location of District seed data | /secrets/districts.json | Json format following the District model definition | | RegionInitializationFile | Location of Region seed data | /secrets/regions.json | Json format following the Region model definition | | CCWJurisdictionInitializationFile | Location of CCW Jurisdiction seed data | /secrets/ccwjurisdictions.json | Json format following the CCW Jurisdiction model definition | | CCW_SERVICE_NAME | CCW microservice location | http://ccw:8080 | | | PDF_SERVICE_NAME | PDF microservice location | http://pdf:8080 | | | ASPNETCORE_ENVIRONMENT | Type of deployment | Development | Set to other Production (or anything other than Development) to disable development features such as user visible stack traces. | Credit: [George Walker](https://github.com/GeorgeWalker), [Wade Barnes](https://github.com/WadeBarnes) contributed to this page.
WadeBarnes/schoolbus
openshift/templates/README.md
Markdown
apache-2.0
10,644
package com.morcinek.android.codegenerator.plugin.layouts.activity; import com.morcinek.android.codegenerator.codegeneration.providers.factories.ActivityResourceProvidersFactory; import com.morcinek.android.codegenerator.plugin.Activator; import com.morcinek.android.codegenerator.plugin.layouts.LayoutActionHandler; /** * Copyright 2014 Tomasz Morcinek. All rights reserved. */ public class ActivityActionHandler extends LayoutActionHandler { public ActivityActionHandler() { super(Activator.getDefault().createCodeGenerator("Activity_template", new ActivityResourceProvidersFactory()), "Activity"); } }
tmorcinek/android-codegenerator-plugin-eclipse
com.morcinek.android.codegenerator.plugin/src/main/java/com/morcinek/android/codegenerator/plugin/layouts/activity/ActivityActionHandler.java
Java
apache-2.0
626
/* * 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.openaz.xacml.admin.jpa; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import org.apache.openaz.xacml.api.Identifier; import org.apache.openaz.xacml.api.XACML3; import org.apache.openaz.xacml.std.IdentifierImpl; /** * The persistent class for the Categories database table. * */ @Entity @Table(name="Category") @NamedQuery(name="Category.findAll", query="SELECT c FROM Category c") public class Category implements Serializable { private static final long serialVersionUID = 1L; public static final char STANDARD = 'S'; public static final char CUSTOM = 'C'; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="id") private int id; @Column(name="grouping", nullable=false, length=64) private String grouping; @Column(name="is_standard", nullable=false) private char isStandard; @Column(name="xacml_id", nullable=false, unique=true, length=255) private String xacmlId; @Column(name="short_name", nullable=false, length=64) private String shortName; //bi-directional many-to-one association to Attribute @OneToMany(mappedBy="categoryBean") private Set<Attribute> attributes = new HashSet<>(); public Category() { this.xacmlId = XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT.stringValue(); this.grouping = "subject"; this.isStandard = Category.STANDARD; this.shortName = "subject"; } public Category(Identifier cat, String grouping, char isStandard) { if (cat != null) { this.xacmlId = cat.stringValue(); } this.isStandard = isStandard; if (grouping != null) { this.grouping = grouping; } else { this.grouping = Category.extractGrouping(this.xacmlId); } } public Category(Identifier cat, String grouping) { this(cat, grouping, Category.STANDARD); } public Category(Identifier cat, char standard) { this(cat, null, standard); } public Category(Identifier cat) { this(cat, Category.STANDARD); } public int getId() { return this.id; } public void setId(int id) { this.id = id; } public String getGrouping() { return this.grouping; } public void setGrouping(String grouping) { this.grouping = grouping; } public char getIsStandard() { return this.isStandard; } public void setIsStandard(char isStandard) { this.isStandard = isStandard; } public String getXacmlId() { return this.xacmlId; } public void setXacmlId(String xacmlId) { this.xacmlId = xacmlId; } public String getShortName() { return this.shortName; } public void setShortName(String shortName) { this.shortName = shortName; } public Set<Attribute> getAttributes() { return this.attributes; } public void setAttributes(Set<Attribute> attributes) { this.attributes = attributes; } public Attribute addAttribute(Attribute attribute) { getAttributes().add(attribute); attribute.setCategoryBean(this); return attribute; } public Attribute removeAttribute(Attribute attribute) { getAttributes().remove(attribute); attribute.setCategoryBean(null); return attribute; } @Transient public boolean isStandard() { return this.isStandard == Category.STANDARD; } @Transient public boolean isCustom() { return this.isStandard == Category.CUSTOM; } @Transient public static String extractGrouping(String xacmlId) { if (xacmlId == null) { return null; } if (xacmlId.matches(".*:attribute\\-category:.*")) { String[] parts = xacmlId.split("[:]"); if (parts != null && parts.length > 0) { return parts[parts.length - 1]; } } else if (xacmlId.matches(".*:[a-zA-Z]+[\\-]category:.*")) { String[] parts = xacmlId.split("[:]"); if (parts != null && parts.length > 0) { for (String part : parts) { int index = part.indexOf("-category"); if (index > 0) { return part.substring(0, index); } } } } return null; } @Transient public Identifier getIdentifer() { return new IdentifierImpl(this.xacmlId); } @Transient @Override public String toString() { return "Category [id=" + id + ", grouping=" + grouping + ", isStandard=" + isStandard + ", xacmlId=" + xacmlId + ", attributes=" + attributes + "]"; } }
apache/incubator-openaz
openaz-xacml-pap-admin/src/main/java/org/apache/openaz/xacml/admin/jpa/Category.java
Java
apache-2.0
5,308
/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package apiserver import ( "net/http" "time" "k8s.io/apimachinery/pkg/apimachinery/announced" "k8s.io/apimachinery/pkg/apimachinery/registered" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/runtime/serializer" "k8s.io/apimachinery/pkg/version" "k8s.io/apiserver/pkg/endpoints/discovery" genericregistry "k8s.io/apiserver/pkg/registry/generic" "k8s.io/apiserver/pkg/registry/rest" genericapiserver "k8s.io/apiserver/pkg/server" "k8s.io/kube-apiextensions-server/pkg/apis/apiextensions" "k8s.io/kube-apiextensions-server/pkg/apis/apiextensions/install" "k8s.io/kube-apiextensions-server/pkg/apis/apiextensions/v1alpha1" "k8s.io/kube-apiextensions-server/pkg/client/clientset/internalclientset" internalinformers "k8s.io/kube-apiextensions-server/pkg/client/informers/internalversion" "k8s.io/kube-apiextensions-server/pkg/registry/customresourcedefinition" // make sure the generated client works _ "k8s.io/kube-apiextensions-server/pkg/client/clientset/clientset" _ "k8s.io/kube-apiextensions-server/pkg/client/informers/externalversions" _ "k8s.io/kube-apiextensions-server/pkg/client/informers/internalversion" ) var ( groupFactoryRegistry = make(announced.APIGroupFactoryRegistry) registry = registered.NewOrDie("") Scheme = runtime.NewScheme() Codecs = serializer.NewCodecFactory(Scheme) ) func init() { install.Install(groupFactoryRegistry, registry, Scheme) // we need to add the options to empty v1 metav1.AddToGroupVersion(Scheme, schema.GroupVersion{Group: "", Version: "v1"}) unversioned := schema.GroupVersion{Group: "", Version: "v1"} Scheme.AddUnversionedTypes(unversioned, &metav1.Status{}, &metav1.APIVersions{}, &metav1.APIGroupList{}, &metav1.APIGroup{}, &metav1.APIResourceList{}, ) } type Config struct { GenericConfig *genericapiserver.Config CustomResourceDefinitionRESTOptionsGetter genericregistry.RESTOptionsGetter } type CustomResourceDefinitions struct { GenericAPIServer *genericapiserver.GenericAPIServer } type completedConfig struct { *Config } // Complete fills in any fields not set that are required to have valid data. It's mutating the receiver. func (c *Config) Complete() completedConfig { c.GenericConfig.EnableDiscovery = false c.GenericConfig.Complete() c.GenericConfig.Version = &version.Info{ Major: "0", Minor: "1", } return completedConfig{c} } // SkipComplete provides a way to construct a server instance without config completion. func (c *Config) SkipComplete() completedConfig { return completedConfig{c} } // New returns a new instance of CustomResourceDefinitions from the given config. func (c completedConfig) New(delegationTarget genericapiserver.DelegationTarget) (*CustomResourceDefinitions, error) { genericServer, err := c.Config.GenericConfig.SkipComplete().New(genericapiserver.EmptyDelegate) // completion is done in Complete, no need for a second time if err != nil { return nil, err } s := &CustomResourceDefinitions{ GenericAPIServer: genericServer, } apiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(apiextensions.GroupName, registry, Scheme, metav1.ParameterCodec, Codecs) apiGroupInfo.GroupMeta.GroupVersion = v1alpha1.SchemeGroupVersion v1alpha1storage := map[string]rest.Storage{} v1alpha1storage["customresourcedefinitions"] = customresourcedefinition.NewREST(Scheme, c.GenericConfig.RESTOptionsGetter) apiGroupInfo.VersionedResourcesStorageMap["v1alpha1"] = v1alpha1storage if err := s.GenericAPIServer.InstallAPIGroup(&apiGroupInfo); err != nil { return nil, err } customResourceDefinitionClient, err := internalclientset.NewForConfig(s.GenericAPIServer.LoopbackClientConfig) if err != nil { return nil, err } customResourceDefinitionInformers := internalinformers.NewSharedInformerFactory(customResourceDefinitionClient, 5*time.Minute) delegateHandler := delegationTarget.UnprotectedHandler() if delegateHandler == nil { delegateHandler = http.NotFoundHandler() } versionDiscoveryHandler := &versionDiscoveryHandler{ discovery: map[schema.GroupVersion]*discovery.APIVersionHandler{}, delegate: delegateHandler, } groupDiscoveryHandler := &groupDiscoveryHandler{ discovery: map[string]*discovery.APIGroupHandler{}, delegate: delegateHandler, } customResourceDefinitionHandler := NewCustomResourceDefinitionHandler( versionDiscoveryHandler, groupDiscoveryHandler, s.GenericAPIServer.RequestContextMapper(), customResourceDefinitionInformers.Apiextensions().InternalVersion().CustomResourceDefinitions().Lister(), delegateHandler, c.CustomResourceDefinitionRESTOptionsGetter, c.GenericConfig.AdmissionControl, ) s.GenericAPIServer.Handler.PostGoRestfulMux.Handle("/apis", customResourceDefinitionHandler) s.GenericAPIServer.Handler.PostGoRestfulMux.HandlePrefix("/apis/", customResourceDefinitionHandler) customResourceDefinitionController := NewDiscoveryController(customResourceDefinitionInformers.Apiextensions().InternalVersion().CustomResourceDefinitions(), versionDiscoveryHandler, groupDiscoveryHandler) s.GenericAPIServer.AddPostStartHook("start-apiextensions-informers", func(context genericapiserver.PostStartHookContext) error { customResourceDefinitionInformers.Start(context.StopCh) return nil }) s.GenericAPIServer.AddPostStartHook("start-apiextensions-controllers", func(context genericapiserver.PostStartHookContext) error { go customResourceDefinitionController.Run(context.StopCh) return nil }) return s, nil }
cheapRoc/kubernetes
staging/src/k8s.io/kube-apiextensions-server/pkg/apiserver/apiserver.go
GO
apache-2.0
6,174
AddCSLuaFile( "cl_init.lua" ) AddCSLuaFile( "shared.lua" ) util.PrecacheSound( "apc_engine_start" ) util.PrecacheSound( "apc_engine_stop" ) util.PrecacheSound( "common/warning.wav" ) include('shared.lua') function ENT:Initialize() self.BaseClass.Initialize(self) self.Active = 0 self.damaged = 0 self:CreateEnvironment(1, 1, 1, 0, 0, 0, 0, 0) self.currentsize = self:BoundingRadius() self.maxsize = self:BoundingRadius() self.maxO2Level = 100 if not (WireAddon == nil) then self.WireDebugName = self.PrintName self.Inputs = Wire_CreateInputs(self, { "On", "Gravity", "Max O2 level" }) self.Outputs = Wire_CreateOutputs(self, { "On", "Oxygen-Level", "Temperature", "Gravity", "Damaged" }) else self.Inputs = { { Name = "On" }, { Name = "Radius" }, { Name = "Gravity" }, { Name = "Max O2 level" } } end CAF.GetAddon("Resource Distribution").RegisterNonStorageDevice(self) end function ENT:TurnOn() if (self.Active == 0) then self:EmitSound( "apc_engine_start" ) self.Active = 1 self:UpdateSize(self.sbenvironment.size, self.currentsize) --We turn the forcefield that contains the environment on if self.environment and not self.environment:IsSpace() then --Fill the environment with air if the surounding environment has o2, replace with CO2 self.sbenvironment.air.o2 = self.sbenvironment.air.o2 + self.environment:Convert(0, -1, math.Round(self.sbenvironment.air.max/18)) end if not (WireAddon == nil) then Wire_TriggerOutput(self, "On", self.Active) end self:SetOOO(1) end end function ENT:TurnOff() if (self.Active == 1) then self:StopSound( "apc_engine_start" ) self:EmitSound( "apc_engine_stop" ) self.Active = 0 if self.environment then --flush all resources into the environment if we are in one (used for the slownes of the SB updating process, we don't want errors do we?) if self.sbenvironment.air.o2 > 0 then local left = self:SupplyResource("oxygen", self.sbenvironment.air.o2) self.environment:Convert(-1, 0, left) end if self.sbenvironment.air.co2 > 0 then local left = self:SupplyResource("carbon dioxide", self.sbenvironment.air.co2) self.environment:Convert(-1, 1, left) end if self.sbenvironment.air.n > 0 then local left = self:SupplyResource("nitrogen", self.sbenvironment.air.n) self.environment:Convert(-1, 2, left) end if self.sbenvironment.air.h > 0 then local left = self:SupplyResource("hydrogen", self.sbenvironment.air.h) self.environment:Convert(-1, 3, left) end end self.sbenvironment.temperature = 0 self:UpdateSize(self.sbenvironment.size, 0) --We turn the forcefield that contains the environment off! if not (WireAddon == nil) then Wire_TriggerOutput(self, "On", self.Active) end self:SetOOO(0) end end function ENT:TriggerInput(iname, value) if (iname == "On") then self:SetActive(value) elseif (iname == "Gravity") then local gravity = value if value <= 0 then gravity = 0 end self.sbenvironment.gravity = gravity elseif (iname == "Max O2 level") then local level = 100 level = math.Clamp(math.Round(value), 0, 100) self.maxO2Level = level end end function ENT:Damage() if (self.damaged == 0) then self.damaged = 1 end if ((self.Active == 1) and (math.random(1, 10) <= 3)) then self:TurnOff() end end function ENT:Repair() self.BaseClass.Repair(self) self:SetColor(255, 255, 255, 255) self.damaged = 0 end function ENT:Destruct() CAF.GetAddon("Spacebuild").RemoveEnvironment(self) CAF.GetAddon("Life Support").LS_Destruct(self, true) end function ENT:OnRemove() CAF.GetAddon("Spacebuild").RemoveEnvironment(self) self.BaseClass.OnRemove(self) self:StopSound("apc_engine_start") end function ENT:PreEntityCopy() local LivableModule = {} LivableModule.Active = self.Active LivableModule.damaged = self.damaged if WireAddon then duplicator.StoreEntityModifier(self,"WireDupeInfo",WireLib.BuildDupeInfo(self.Entity)) end duplicator.StoreEntityModifier(self, "livable_module", LivableModule) end function ENT:PostEntityPaste(ply, ent, createdEnts) if WireAddon then local emods = ent.EntityMods if emods and emods.WireDupeInfo then WireLib.ApplyDupeInfo(ply, ent, emods.WireDupeInfo, function(id) return createdEnts[id] end) end end end function MakeLivableModule( Player, Data ) local ent = ents.Create( Data.Class ) duplicator.DoGeneric( ent, Data ) ent:Spawn() duplicator.DoGenericPhysics( ent, Player, Data ) ent:SetPlayer(Player) ent.damaged = Data.EntityMods.livable_module.damaged if CPPI then ent:CPPISetOwner(Player) end if Data.EntityMods.livable_module.Active == 1 then ent:TurnOn() end return ent end duplicator.RegisterEntityClass( "livable_module", MakeLivableModule, "Data" ) --[[ function ENT:CreateEnvironment(gravity, atmosphere, pressure, temperature, o2, co2, n, h) --Msg("CreateEnvironment: "..tostring(gravity).."\n") --set Gravity if one is given if gravity and type(gravity) == "number" then if gravity < 0 then gravity = 0 end self.sbenvironment.gravity = gravity end --set atmosphere if given if atmosphere and type(atmosphere) == "number" then if atmosphere < 0 then atmosphere = 0 elseif atmosphere > 1 then atmosphere = 1 end self.sbenvironment.atmosphere = atmosphere end --set pressure if given if pressure and type(pressure) == "number" and pressure >= 0 then self.sbenvironment.pressure = pressure else self.sbenvironment.pressure = math.Round(self.sbenvironment.atmosphere * self.sbenvironment.gravity) end --set temperature if given if temperature and type(temperature) == "number" then self.sbenvironment.temperature = temperature end --set o2 if given if o2 and type(o2) == "number" and o2 > 0 then if o2 > 100 then o2 = 100 end self.sbenvironment.air.o2per = o2 self.sbenvironment.air.o2 = math.Round(o2 * 5 * (self:GetVolume()/1000) * self.sbenvironment.atmosphere) else o2 = 0 self.sbenvironment.air.o2per = 0 self.sbenvironment.air.o2 = 0 end --set co2 if given if co2 and type(co2) == "number" and co2 > 0 then if (100 - o2) < co2 then co2 = 100-o2 end self.sbenvironment.air.co2per = co2 self.sbenvironment.air.co2 = 0 else co2 = 0 self.sbenvironment.air.co2per = 0 self.sbenvironment.air.co2 = 0 end --set n if given if n and type(n) == "number" and n > 0 then if ((100 - o2)-co2) < n then n = (100-o2)-co2 end self.sbenvironment.air.nper = n self.sbenvironment.air.n = 0 else n = 0 self.sbenvironment.air.n = 0 self.sbenvironment.air.n = 0 end --set h if given if h and type(h) == "number" then if (((100 - o2)-co2)-n) < h then h = ((100-o2)-co2)-n end self.sbenvironment.air.hper = h self.sbenvironment.air.h = math.Round(h * 5 * (self:GetVolume()/1000) * self.sbenvironment.atmosphere) else h = 0 self.sbenvironment.air.h = 0 self.sbenvironment.air.h = 0 end if o2 + co2 + n + h < 100 then local tmp = 100 - (o2 + co2 + n + h) self.sbenvironment.air.empty = math.Round(tmp * 5 * (self:GetVolume()/1000) * self.sbenvironment.atmosphere) self.sbenvironment.air.emptyper = tmp elseif o2 + co2 + n + h > 100 then local tmp = (o2 + co2 + n + h) - 100 if co2 > tmp then self.sbenvironment.air.co2 = math.Round((co2 - tmp) * 5 * (self:GetVolume()/1000) * self.sbenvironment.atmosphere) self.sbenvironment.air.co2per = co2 + tmp elseif n > tmp then self.sbenvironment.air.n = math.Round((n - tmp) * 5 * (self:GetVolume()/1000) * self.sbenvironment.atmosphere) self.sbenvironment.air.nper = n + tmp elseif h > tmp then self.sbenvironment.air.h = math.Round((h - tmp) * 5 * (self:GetVolume()/1000) * self.sbenvironment.atmosphere) self.sbenvironment.air.hper = h + tmp elseif o2 > tmp then self.sbenvironment.air.o2 = math.Round((o2 - tmp) * 5 * (self:GetVolume()/1000) * self.sbenvironment.atmosphere) self.sbenvironment.air.o2per = o2 - tmp end end self.sbenvironment.air.max = math.Round(100 * 5 * (self:GetVolume()/1000) * self.sbenvironment.atmosphere) self:PrintVars() end -- ]] --[[ function ENT:UpdateSize(oldsize, newsize) if oldsize == newsize then return end if oldsize and newsize and type(oldsize) == "number" and type(newsize) == "number" and oldsize >= 0 and newsize >= 0 then if oldsize == 0 then self.sbenvironment.air.o2 = 0 self.sbenvironment.air.co2 = 0 self.sbenvironment.air.n = 0 self.sbenvironment.air.h = 0 self.sbenvironment.air.empty = 0 self.sbenvironment.size = newsize elseif newsize == 0 then local tomuch = self.sbenvironment.air.o2 if self.environment then tomuch = self.environment:Convert(-1, 0, tomuch) end tomuch = self.sbenvironment.air.co2 if self.environment then tomuch = self.environment:Convert(-1, 1, tomuch) end tomuch = self.sbenvironment.air.n if self.environment then tomuch = self.environment:Convert(-1, 2, tomuch) end tomuch = self.sbenvironment.air.h if self.environment then tomuch = self.environment:Convert(-1, 3, tomuch) end self.sbenvironment.air.o2 = 0 self.sbenvironment.air.co2 = 0 self.sbenvironment.air.n = 0 self.sbenvironment.air.h = 0 self.sbenvironment.air.empty = 0 self.sbenvironment.size = 0 else self.sbenvironment.air.o2 = (newsize/oldsize) * self.sbenvironment.air.o2 self.sbenvironment.air.co2 = (newsize/oldsize) * self.sbenvironment.air.co2 self.sbenvironment.air.n = (newsize/oldsize) * self.sbenvironment.air.n self.sbenvironment.air.h = (newsize/oldsize) * self.sbenvironment.air.h self.sbenvironment.air.empty = (newsize/oldsize) * self.sbenvironment.air.empty self.sbenvironment.size = newsize end self.sbenvironment.air.max = math.Round(100 * 5 * (self:GetVolume()/1000) * self.sbenvironment.atmosphere) if self.sbenvironment.air.o2 > self.sbenvironment.air.max then local tomuch = self.sbenvironment.air.o2 - self.sbenvironment.air.max if self.environment then tomuch = self.environment:Convert(-1, 0, tomuch) self.sbenvironment.air.o2 = self.sbenvironment.air.max + tomuch end end if self.sbenvironment.air.co2 > self.sbenvironment.air.max then local tomuch = self.sbenvironment.air.co2 - self.sbenvironment.air.max if self.environment then tomuch = self.environment:Convert(-1, 1, tomuch) self.sbenvironment.air.co2 = self.sbenvironment.air.max + tomuch end end if self.sbenvironment.air.n > self.sbenvironment.air.max then local tomuch = self.sbenvironment.air.n - self.sbenvironment.air.max if self.environment then tomuch = self.environment:Convert(-1, 2, tomuch) self.sbenvironment.air.n = self.sbenvironment.air.max + tomuch end end if self.sbenvironment.air.h > self.sbenvironment.air.max then local tomuch = self.sbenvironment.air.h - self.sbenvironment.air.max if self.environment then tomuch = self.environment:Convert(-1, 3, tomuch) self.sbenvironment.air.h = self.sbenvironment.air.max + tomuch end end end end --]] function ENT:Climate_Control() local temperature = 0 local pressure = 0 if self.environment then temperature = self.environment:GetTemperature(self) pressure = self.environment:GetPressure() --Msg("Found environment, updating\n") end --Msg("Temperature: "..tostring(temperature)..", pressure: " ..tostring(pressure).."\n") if self.Active == 1 then --Only do something if the device is on self.energy = self:GetResourceAmount("energy") if self.energy == 0 or self.energy < 3 * math.ceil(self.maxsize/1024) then --Don't have enough power to keep the controler\'s think process running, shut it all down self:TurnOff() return --Msg("Turning of\n") else self.air = self:GetResourceAmount("oxygen") self.coolant = self:GetResourceAmount("water") self.coolant2 = self:GetResourceAmount("nitrogen") self.energy = self:GetResourceAmount("energy") --First let check our air supply and try to stabilize it if we got oxygen left in storage at a rate of 10 oxygen per second if self.sbenvironment.air.o2 < self.sbenvironment.air.max * (self.maxO2Level/100) then --We need some energy to fire the pump! local energyneeded = 5 * math.ceil(self.maxsize/1024) local mul = 1 if self.energy < energyneeded then mul = self.energy/energyneeded self:ConsumeResource("energy", self.energy) else self:ConsumeResource("energy", energyneeded) end local air = math.ceil(1500 * mul) if self.air < air then air = self.air end if self.sbenvironment.air.co2 > 0 then local actual = self:Convert(1, 0, air) self:ConsumeResource("oxygen", actual) self:SupplyResource("carbon dioxide", actual) elseif self.sbenvironment.air.n > 0 then local actual = self:Convert(2, 0, air) self:ConsumeResource("oxygen", actual) self:SupplyResource("nitrogen", actual) elseif self.sbenvironment.air.h > 0 then local actual = self:Convert(3, 0, air) self:ConsumeResource("oxygen", actual) self:SupplyResource("hydrogen", actual) else self:ConsumeResource("oxygen", air) self.sbenvironment.air.o2 = self.sbenvironment.air.o2 + air end elseif self.sbenvironment.air.o2 > self.sbenvironment.air.max then local tmp = self.sbenvironment.air.o2 - self.sbenvironment.air.max self:SupplyResource("oxygen", tmp) end --Now let's check the pressure, if pressure is larger then 1 then we need some more power to keep the climate_controls environment stable. We don\' want any leaks do we? if pressure > 1 then self:ConsumeResource("energy", (pressure-1) * 2 * math.ceil(self.maxsize/1024)) end if temperature < self.sbenvironment.temperature then local dif = self.sbenvironment.temperature - temperature dif = math.ceil(dif/100) --Change temperature depending on the outside temperature, 5° difference does a lot less then 10000° difference self.sbenvironment.temperature = self.sbenvironment.temperature - dif elseif temperature > self.sbenvironment.temperature then local dif = temperature - self.sbenvironment.temperature dif = math.ceil(dif / 100) self.sbenvironment.temperature = self.sbenvironment.temperature + dif end --Msg("Temperature: "..tostring(self.sbenvironment.temperature).."\n") if self.sbenvironment.temperature < 288 then --Msg("Heating up?\n") if self.sbenvironment.temperature + 60 <= 303 then self:ConsumeResource("energy", 24 * math.ceil(self.maxsize/1024)) self.energy = self:GetResourceAmount("energy") if self.energy > 60 * math.ceil(self.maxsize/1024) then --Msg("Enough energy\n") self.sbenvironment.temperature = self.sbenvironment.temperature + 60 self:ConsumeResource("energy", 60 * math.ceil(self.maxsize/1024)) else --Msg("not Enough energy\n") self.sbenvironment.temperature = self.sbenvironment.temperature + math.ceil((self.energy/ 60 * math.ceil(self.maxsize/1024))*60) self:ConsumeResource("energy", self.energy) end elseif self.sbenvironment.temperature + 30 <= 303 then self:ConsumeResource("energy", 12 * math.ceil(self.maxsize/1024)) self.energy = self:GetResourceAmount("energy") if self.energy > 30 * math.ceil(self.maxsize/1024) then --Msg("Enough energy\n") self.sbenvironment.temperature = self.sbenvironment.temperature + 30 self:ConsumeResource("energy", 30 * math.ceil(self.maxsize/1024)) else --Msg("not Enough energy\n") self.sbenvironment.temperature = self.sbenvironment.temperature + math.ceil((self.energy/ 30 * math.ceil(self.maxsize/1024))*30) self:ConsumeResource("energy", self.energy) end elseif self.sbenvironment.temperature + 15 <= 303 then self:ConsumeResource("energy", 6 * math.ceil(self.maxsize/1024)) self.energy = self:GetResourceAmount("energy") if self.energy > 15 * math.ceil(self.maxsize/1024) then --Msg("Enough energy\n") self.sbenvironment.temperature = self.sbenvironment.temperature + 15 self:ConsumeResource("energy", 15 * math.ceil(self.maxsize/1024)) else --Msg("not Enough energy\n") self.sbenvironment.temperature = self.sbenvironment.temperature + math.ceil((self.energy/ 15 * math.ceil(self.maxsize/1024))*15) self:ConsumeResource("energy", self.energy) end else self:ConsumeResource("energy", 2 * math.ceil(self.maxsize/1024)) self.energy = self:GetResourceAmount("energy") if self.energy > 5 * math.ceil(self.maxsize/1024) then --Msg("Enough energy\n") self.sbenvironment.temperature = self.sbenvironment.temperature + 5 self:ConsumeResource("energy", 5 * math.ceil(self.maxsize/1024)) else --Msg("not Enough energy\n") self.sbenvironment.temperature = self.sbenvironment.temperature + math.ceil((self.energy/ 5 * math.ceil(self.maxsize/1024))*5) self:ConsumeResource("energy", self.energy) end end elseif self.sbenvironment.temperature > 303 then if self.sbenvironment.temperature - 60 >= 288 then self:ConsumeResource("energy", 24 * math.ceil(self.maxsize/1024)) if self.coolant2 > 12 * math.ceil(self.maxsize/1024) then self.sbenvironment.temperature = self.sbenvironment.temperature - 60 self:ConsumeResource("nitrogen", 12 * math.ceil(self.maxsize/1024)) elseif self.coolant > 60 * math.ceil(self.maxsize/1024) then self.sbenvironment.temperature = self.sbenvironment.temperature - 60 self:ConsumeResource("water", 60 * math.ceil(self.maxsize/1024)) else if self.coolant2 > 0 then self.sbenvironment.temperature = self.sbenvironment.temperature - math.ceil((self.coolant2/ 12 * math.ceil(self.maxsize/1024))*60) self:ConsumeResource("nitrogen", self.coolant2) elseif self.coolant > 0 then self.sbenvironment.temperature = self.sbenvironment.temperature - math.ceil((self.coolant/ 60 * math.ceil(self.maxsize/1024))*60) self:ConsumeResource("water", self.coolant) end end elseif self.sbenvironment.temperature - 30 >= 288 then self:ConsumeResource("energy", 12 * math.ceil(self.maxsize/1024)) if self.coolant2 > 6 * math.ceil(self.maxsize/1024) then self.sbenvironment.temperature = self.sbenvironment.temperature - 30 self:ConsumeResource("nitrogen", 6 * math.ceil(self.maxsize/1024)) elseif self.coolant > 30 * math.ceil(self.maxsize/1024) then self.sbenvironment.temperature = self.sbenvironment.temperature - 30 self:ConsumeResource("water", 30 * math.ceil(self.maxsize/1024)) else if self.coolant2 > 0 then self.sbenvironment.temperature = self.sbenvironment.temperature - math.ceil((self.coolant2/ 6 * math.ceil(self.maxsize/1024))*30) self:ConsumeResource("nitrogen", self.coolant2) elseif self.coolant > 0 then self.sbenvironment.temperature = self.sbenvironment.temperature - math.ceil((self.coolant/ 30 * math.ceil(self.maxsize/1024))*30) self:ConsumeResource("water", self.coolant) end end elseif self.sbenvironment.temperature - 15 >= 288 then self:ConsumeResource("energy", 6 * math.ceil(self.maxsize/1024)) if self.coolant2 > 3 * math.ceil(self.maxsize/1024) then self.sbenvironment.temperature = self.sbenvironment.temperature - 15 self:ConsumeResource("nitrogen", 3 * math.ceil(self.maxsize/1024)) elseif self.coolant > 15 * math.ceil(self.maxsize/1024) then self.sbenvironment.temperature = self.sbenvironment.temperature - 15 self:ConsumeResource("water", 15 * math.ceil(self.maxsize/1024)) else if self.coolant2 > 0 then self.sbenvironment.temperature = self.sbenvironment.temperature - math.ceil((self.coolant2/ 3 * math.ceil(self.maxsize/1024))*15) self:ConsumeResource("nitrogen", self.coolant2) elseif self.coolant > 0 then self.sbenvironment.temperature = self.sbenvironment.temperature - math.ceil((self.coolant/ 15 * math.ceil(self.maxsize/1024))*15) self:ConsumeResource("water", self.coolant) end end else self:ConsumeResource("energy", 2 * math.ceil(self.maxsize/1024)) if self.coolant2 > 1 * math.ceil(self.maxsize/1024) then self.sbenvironment.temperature = self.sbenvironment.temperature - 5 self:ConsumeResource("nitrogen", 1 * math.ceil(self.maxsize/1024)) elseif self.coolant > 5 * math.ceil(self.maxsize/1024) then self.sbenvironment.temperature = self.sbenvironment.temperature - 5 self:ConsumeResource("water", 5 * math.ceil(self.maxsize/1024)) else if self.coolant2 > 0 then self.sbenvironment.temperature = self.sbenvironment.temperature - math.ceil((self.coolant2/ 1 * math.ceil(self.maxsize/1024))*5) self:ConsumeResource("nitrogen", self.coolant2) elseif self.coolant > 0 then self.sbenvironment.temperature = self.sbenvironment.temperature - math.ceil((self.coolant/ 5 * math.ceil(self.maxsize/1024))*5) self:ConsumeResource("water", self.coolant) end end end end end end if not (WireAddon == nil) then Wire_TriggerOutput(self, "Oxygen-Level", tonumber(self:GetO2Percentage())) Wire_TriggerOutput(self, "Temperature", tonumber(self.sbenvironment.temperature)) Wire_TriggerOutput(self, "Gravity", tonumber(self.sbenvironment.gravity)) Wire_TriggerOutput(self, "Damaged", tonumber(self.damaged)) end end function ENT:Think() self.BaseClass.Think(self) self:Climate_Control() self:NextThink(CurTime() + 1) return true end --[[ function ENT:OnEnvironment(ent) if not ent then return end if ent == self then return end local pos = ent:GetPos() local dist = pos:Distance(self:GetPos()) if dist < self:GetSize() then local min, max = ent:WorldSpaceAABB() if table.HasValue(ents.FindInBox( min, max ), ent) then if not ent.environment then ent.environment = self --self:UpdateGravity(ent) else if ent.environment:GetPriority() < self:GetPriority() then ent.environment = self --self:UpdateGravity(ent) elseif ent.environment:GetPriority() == self:GetPriority() then if ent.environment:GetSize() != 0 then if self:GetSize() <= ent.environment:GetSize() then ent.environment = self --self:UpdateGravity(ent) else if dist < pos:Distance(ent.environment:GetPos()) then ent.environment = self end end else ent.environment = self --self:UpdateGravity(ent) end end end end end end ]]
spacebuild/sbep
lua/entities/livable_module/init.lua
Lua
apache-2.0
22,756
package org.omg.dmn.tck.validation; import javax.xml.XMLConstants; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import java.io.File; import java.net.URI; /** * Created by opatrascoiu on 10/04/2017. */ public class SchemaValidator { private final File schemaLocation; private final String context; public SchemaValidator(File schemaLocation, String context) { this.schemaLocation = schemaLocation; this.context = context; } public void validateFile(File file, String extension) throws Exception { if (file.isDirectory()) { for(File child: file.listFiles()) { validateFile(child, extension); } } else { if (file.getName().endsWith(extension)) { validateSchema(file); } } } private void validateSchema(File file) throws Exception { try { JAXBContext jc = JAXBContext.newInstance(context); Unmarshaller u = jc.createUnmarshaller(); setSchema(u, schemaLocation); u.unmarshal(file.toURI().toURL()); System.out.println(String.format("'%s' is valid", file.getName())); } catch (Exception e) { System.out.println(String.format("'%s' is invalid", file.getName())); e.printStackTrace(); } } private void setSchema(Unmarshaller u, File schemaLocation) throws Exception { SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); URI schemaURI = schemaLocation.toURI(); File schemaFile = new File(schemaURI.getPath()); Schema schema = sf.newSchema(schemaFile); u.setSchema(schema); } public static void main(String[] args) throws Exception { File rootFolder = new File("TestCases"); File testCasesSchemaLocation = new File(rootFolder, "testCases.xsd"); new SchemaValidator(testCasesSchemaLocation, "org.omg.dmn.tck.marshaller._20160719").validateFile(rootFolder, ".xml"); } }
etirelli/tck
runners/dmn-tck-marshaller/src/main/java/org/omg/dmn/tck/validation/SchemaValidator.java
Java
apache-2.0
2,143
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'ProductType' db.create_table('inventory_producttype', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), )) db.send_create_signal('inventory', ['ProductType']) # Adding model 'Product' db.create_table('inventory_product', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('shop', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['shops.Shop'])), ('title', self.gf('django.db.models.fields.CharField')(max_length=200)), ('description', self.gf('django.db.models.fields.TextField')()), ('category', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['market.MarketCategory'])), ('subcategory', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['market.MarketSubCategory'])), ('date_time', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)), ('weight', self.gf('django.db.models.fields.DecimalField')(default='0', max_digits=11, decimal_places=2)), ('type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['inventory.ProductType'], null=True, blank=True)), )) db.send_create_signal('inventory', ['Product']) # Adding model 'Coin' db.create_table('inventory_coin', ( ('producttype_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['inventory.ProductType'], unique=True, primary_key=True)), ('category', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['market.MarketCategory'], null=True, blank=True)), ('subcategory', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['market.MarketSubCategory'], null=True, blank=True)), ('country_code', self.gf('django.db.models.fields.CharField')(default='us', max_length=2)), ('pcgs_number', self.gf('django.db.models.fields.IntegerField')(null=True, blank=True)), ('description', self.gf('django.db.models.fields.TextField')(default='', blank='')), ('year_issued', self.gf('django.db.models.fields.CharField')(default='', max_length=24, blank='')), ('actual_year', self.gf('django.db.models.fields.CharField')(default='', max_length=24, blank='')), ('denomination', self.gf('django.db.models.fields.CharField')(default='', max_length=60, blank='')), ('major_variety', self.gf('django.db.models.fields.CharField')(default='', max_length=60, blank='')), ('die_variety', self.gf('django.db.models.fields.CharField')(default='', max_length=60, blank='')), ('prefix', self.gf('django.db.models.fields.CharField')(default='', max_length=60, blank='')), ('suffix', self.gf('django.db.models.fields.CharField')(default='', max_length=60, blank='')), ('sort_order', self.gf('django.db.models.fields.CharField')(default='', max_length=60, blank='')), ('heading', self.gf('django.db.models.fields.CharField')(default='', max_length=60, blank='')), ('holder_variety', self.gf('django.db.models.fields.CharField')(default='', max_length=60, blank='')), ('holder_variety_2', self.gf('django.db.models.fields.CharField')(default='', max_length=60, blank='')), ('additional_data', self.gf('django.db.models.fields.TextField')(default='', blank='')), ('last_update', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)), )) db.send_create_signal('inventory', ['Coin']) def backwards(self, orm): # Deleting model 'ProductType' db.delete_table('inventory_producttype') # Deleting model 'Product' db.delete_table('inventory_product') # Deleting model 'Coin' db.delete_table('inventory_coin') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '32'}) }, 'contenttypes.contenttype': { 'Meta': {'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'inventory.coin': { 'Meta': {'object_name': 'Coin', '_ormbases': ['inventory.ProductType']}, 'actual_year': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '24', 'blank': "''"}), 'additional_data': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': "''"}), 'category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['market.MarketCategory']", 'null': 'True', 'blank': 'True'}), 'country_code': ('django.db.models.fields.CharField', [], {'default': "'us'", 'max_length': '2'}), 'denomination': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '60', 'blank': "''"}), 'description': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': "''"}), 'die_variety': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '60', 'blank': "''"}), 'heading': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '60', 'blank': "''"}), 'holder_variety': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '60', 'blank': "''"}), 'holder_variety_2': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '60', 'blank': "''"}), 'last_update': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'major_variety': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '60', 'blank': "''"}), 'pcgs_number': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}), 'prefix': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '60', 'blank': "''"}), 'producttype_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['inventory.ProductType']", 'unique': 'True', 'primary_key': 'True'}), 'sort_order': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '60', 'blank': "''"}), 'subcategory': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['market.MarketSubCategory']", 'null': 'True', 'blank': 'True'}), 'suffix': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '60', 'blank': "''"}), 'year_issued': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '24', 'blank': "''"}) }, 'inventory.product': { 'Meta': {'object_name': 'Product'}, 'category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['market.MarketCategory']"}), 'date_time': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'shop': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['shops.Shop']"}), 'subcategory': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['market.MarketSubCategory']"}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['inventory.ProductType']", 'null': 'True', 'blank': 'True'}), 'weight': ('django.db.models.fields.DecimalField', [], {'default': "'0'", 'max_digits': '11', 'decimal_places': '2'}) }, 'inventory.producttype': { 'Meta': {'object_name': 'ProductType'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'market.marketcategory': { 'Meta': {'object_name': 'MarketCategory'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'marketplace': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['market.MarketPlace']"}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '60'}), 'order': ('django.db.models.fields.IntegerField', [], {'default': '255'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '60', 'db_index': 'True'}) }, 'market.marketplace': { 'Meta': {'object_name': 'MarketPlace'}, 'base_domain': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '128'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '92'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '92', 'db_index': 'True'}), 'template_prefix': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '92', 'db_index': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '92'}) }, 'market.marketsubcategory': { 'Meta': {'unique_together': "(('parent', 'slug'),)", 'object_name': 'MarketSubCategory'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'marketplace': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['market.MarketPlace']"}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '60'}), 'order': ('django.db.models.fields.IntegerField', [], {'default': '255'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'subcategories'", 'null': 'True', 'to': "orm['market.MarketCategory']"}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '60', 'db_index': 'True'}) }, 'shops.shop': { 'Meta': {'object_name': 'Shop'}, 'admin': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'bids': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'date_time': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'location': ('django.db.models.fields.CharField', [], {'default': "'39.29038,-76.61219'", 'max_length': '255'}), 'marketplace': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['market.MarketPlace']"}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '60'}), 'views': ('django.db.models.fields.IntegerField', [], {'default': '0'}) } } complete_apps = ['inventory']
codepython/CollectorCity-Market-Place
stores/apps/inventory/migrations/0001_initial.py
Python
apache-2.0
13,952
namespace MediatR.Examples.StructureMap.WebAPI.Areas.HelpPage.ModelDescriptions { public class KeyValuePairModelDescription : ModelDescription { public ModelDescription KeyModelDescription { get; set; } public ModelDescription ValueModelDescription { get; set; } } }
darbio/MediatR
src/MediatR.Examples.StructureMap.WebAPI/Areas/HelpPage/ModelDescriptions/KeyValuePairModelDescription.cs
C#
apache-2.0
303
package org.wikidata.wdtk.rdf.values; /* * #%L * Wikidata Toolkit RDF * %% * Copyright (C) 2014 Wikidata Toolkit Developers * %% * 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. * #L% */ import org.openrdf.model.Value; import org.wikidata.wdtk.datamodel.interfaces.DatatypeIdValue; import org.wikidata.wdtk.datamodel.interfaces.EntityIdValue; import org.wikidata.wdtk.datamodel.interfaces.PropertyIdValue; import org.wikidata.wdtk.rdf.OwlDeclarationBuffer; import org.wikidata.wdtk.rdf.PropertyTypes; import org.wikidata.wdtk.rdf.RdfWriter; public class EntityIdValueConverter extends AbstractValueConverter<EntityIdValue> { public EntityIdValueConverter(RdfWriter rdfWriter, PropertyTypes propertyTypes, OwlDeclarationBuffer rdfConversionBuffer) { super(rdfWriter, propertyTypes, rdfConversionBuffer); } @Override public Value getRdfValue(EntityIdValue value, PropertyIdValue propertyIdValue, boolean simple) { String datatype = this.propertyTypes.setPropertyTypeFromEntityIdValue( propertyIdValue, value); switch (datatype) { case DatatypeIdValue.DT_ITEM: this.rdfConversionBuffer.addObjectProperty(propertyIdValue); return this.rdfWriter.getUri(value.getIri()); default: logIncompatibleValueError(propertyIdValue, datatype, "entity"); return null; } } }
GlorimarCastro/glorimar-wikidata-toolkit
wdtk-rdf/src/main/java/org/wikidata/wdtk/rdf/values/EntityIdValueConverter.java
Java
apache-2.0
1,824
/* * Copyright 2010-2017 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. */ #include <aws/config/model/DescribeRetentionConfigurationsResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::ConfigService::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; DescribeRetentionConfigurationsResult::DescribeRetentionConfigurationsResult() { } DescribeRetentionConfigurationsResult::DescribeRetentionConfigurationsResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } DescribeRetentionConfigurationsResult& DescribeRetentionConfigurationsResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("RetentionConfigurations")) { Array<JsonView> retentionConfigurationsJsonList = jsonValue.GetArray("RetentionConfigurations"); for(unsigned retentionConfigurationsIndex = 0; retentionConfigurationsIndex < retentionConfigurationsJsonList.GetLength(); ++retentionConfigurationsIndex) { m_retentionConfigurations.push_back(retentionConfigurationsJsonList[retentionConfigurationsIndex].AsObject()); } } if(jsonValue.ValueExists("NextToken")) { m_nextToken = jsonValue.GetString("NextToken"); } return *this; }
cedral/aws-sdk-cpp
aws-cpp-sdk-config/source/model/DescribeRetentionConfigurationsResult.cpp
C++
apache-2.0
1,981
/* * * Paros and its related class files. * * Paros is an HTTP/HTTPS proxy for assessing web application security. * Copyright (C) 2003-2004 Chinotec Technologies Company * * This program is free software; you can redistribute it and/or * modify it under the terms of the Clarified Artistic License * as published by the Free Software Foundation. * * 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 * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // ZAP: 2011/05/09 Support for API // ZAP: 2011/05/27 Ensure all PreparedStatements and ResultSets closed to prevent leaks // ZAP: 2012/01/02 Separate param and attack // ZAP: 2012/04/23 Added @Override annotation to the appropriate method. // ZAP: 2012/04/25 Changed to use the method Integer.valueOf. // ZAP: 2012/08/08 Upgrade to HSQLDB 2.x (introduced TABLE_NAME constant + DbUtils) // ZAP: 2013/07/11 Issue 713: Add CWE and WASC numbers to issues // ZAP: 2014/03/04 Issue 1042: Add ALERT_INDEX to speed up session load // ZAP: 2014/03/23 Changed to use try-with-resource statements. // ZAP: 2014/05/23 Issue 1209: Reliability becomes Confidence and add levels // ZAP: 2014/06/16 Issue 990: Allow to delete alerts through the API // ZAP: 2014/08/14 Issue 1283: SQLDataException: data exception: string data, // right truncation while writing an alert to DB // ZAP: 2015/02/09 Issue 1525: Introduce a database interface layer to allow for alternative // implementations // ZAP: 2016/10/11 Issue 2592: Differentiate the source of alerts // ZAP: 2018/02/14 Remove unnecessary boxing / unboxing // ZAP: 2019/06/01 Normalise line endings. // ZAP: 2019/06/05 Normalise format/style. package org.parosproxy.paros.db.paros; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Vector; import org.parosproxy.paros.db.DatabaseException; import org.parosproxy.paros.db.DbUtils; import org.parosproxy.paros.db.RecordAlert; import org.parosproxy.paros.db.TableAlert; public class ParosTableAlert extends ParosAbstractTable implements TableAlert { // ZAP: introduced class constant private static final String TABLE_NAME = "ALERT"; private static final String ALERT_INDEX = "ALERT_INDEX"; private static final String ALERTID = "ALERTID"; private static final String SCANID = "SCANID"; private static final String PLUGINID = "PLUGINID"; private static final String ALERT = "ALERT"; private static final String RISK = "RISK"; private static final String RELIABILITY = "RELIABILITY"; private static final String DESCRIPTION = "DESCRIPTION"; private static final String URI = "URI"; private static final String PARAM = "PARAM"; private static final String ATTACK = "ATTACK"; private static final String OTHERINFO = "OTHERINFO"; private static final String SOLUTION = "SOLUTION"; private static final String REFERENCE = "REFERENCE"; private static final String EVIDENCE = "EVIDENCE"; private static final String CWEID = "CWEID"; private static final String WASCID = "WASCID"; private static final String HISTORYID = "HISTORYID"; private static final String SOURCEHISTORYID = "SOURCEHISTORYID"; private static final String SOURCEID = "SOURCEID"; private PreparedStatement psRead = null; private PreparedStatement psInsert = null; private CallableStatement psGetIdLastInsert = null; private PreparedStatement psDeleteAlert = null; private PreparedStatement psDeleteAllAlerts = null; // private PreparedStatement psDeleteScan = null; private PreparedStatement psUpdate = null; private PreparedStatement psUpdateHistoryIds = null; private PreparedStatement psGetAlertsForHistoryId = null; public ParosTableAlert() {} @Override protected void reconnect(Connection conn) throws DatabaseException { try { // ZAP: Changed to call the method updateTable(Connection). updateTable(conn); psRead = conn.prepareStatement( "SELECT TOP 1 * FROM " + TABLE_NAME + " WHERE " + ALERTID + " = ?"); psInsert = conn.prepareStatement( "INSERT INTO " + TABLE_NAME + " (" + SCANID + "," + PLUGINID + "," + ALERT + "," + RISK + "," + RELIABILITY + "," + DESCRIPTION + "," + URI + "," + PARAM + "," + ATTACK + "," + OTHERINFO + "," + SOLUTION + "," + REFERENCE + "," + EVIDENCE + "," + CWEID + "," + WASCID + "," + HISTORYID + "," + SOURCEHISTORYID + "," + SOURCEID + ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); psGetIdLastInsert = conn.prepareCall("CALL IDENTITY();"); psDeleteAlert = conn.prepareStatement( "DELETE FROM " + TABLE_NAME + " WHERE " + ALERTID + " = ?"); psDeleteAllAlerts = conn.prepareStatement("DELETE FROM " + TABLE_NAME); // psDeleteScan = conn.prepareStatement("DELETE FROM ALERT WHERE " + SCANID + " = ?"); // ZAP: New prepared statement for updating an alert psUpdate = conn.prepareStatement( "UPDATE " + TABLE_NAME + " SET " + ALERT + " = ?, " + RISK + " = ?," + RELIABILITY + " = ?," + DESCRIPTION + " = ?," + URI + " = ?," + PARAM + " = ?," + ATTACK + " = ?," + OTHERINFO + " = ?," + SOLUTION + " = ?," + REFERENCE + " = ?, " + EVIDENCE + " = ?, " + CWEID + " = ?, " + WASCID + " = ?, " + SOURCEHISTORYID + " = ? " + "WHERE " + ALERTID + " = ?"); psUpdateHistoryIds = conn.prepareStatement( "UPDATE " + TABLE_NAME + " SET " + HISTORYID + " = ?, " + SOURCEHISTORYID + " = ? " + "WHERE " + ALERTID + " = ?"); psGetAlertsForHistoryId = conn.prepareStatement( "SELECT * FROM " + TABLE_NAME + " WHERE " + SOURCEHISTORYID + " = ?"); } catch (SQLException e) { throw new DatabaseException(e); } } // ZAP: Added the method. private void updateTable(Connection connection) throws DatabaseException { try { // Add the SOURCEHISTORYID column to the db if necessary if (!DbUtils.hasColumn(connection, TABLE_NAME, SOURCEHISTORYID)) { DbUtils.execute( connection, "ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + SOURCEHISTORYID + " INT DEFAULT 0"); } // Add the ATTACK column to the db if necessary if (!DbUtils.hasColumn(connection, TABLE_NAME, ATTACK)) { DbUtils.execute( connection, "ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + ATTACK + " VARCHAR(32768) DEFAULT ''"); } if (!DbUtils.hasColumn(connection, TABLE_NAME, EVIDENCE)) { // Evidence, cweId and wascId all added at the same time DbUtils.execute( connection, "ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + EVIDENCE + " VARCHAR(16777216) DEFAULT ''"); DbUtils.execute( connection, "ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + CWEID + " INT DEFAULT -1"); DbUtils.execute( connection, "ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + WASCID + " INT DEFAULT -1"); } if (!DbUtils.hasIndex(connection, TABLE_NAME, ALERT_INDEX)) { // this speeds up session loading DbUtils.execute( connection, "CREATE INDEX " + ALERT_INDEX + " ON " + TABLE_NAME + " (" + SOURCEHISTORYID + ")"); } if (!DbUtils.hasColumn(connection, TABLE_NAME, SOURCEID)) { DbUtils.execute( connection, "ALTER TABLE " + TABLE_NAME + " ADD COLUMN " + SOURCEID + " INT DEFAULT 0"); DbUtils.execute( connection, "CREATE INDEX INDEX_ALERT_SOURCEID ON " + TABLE_NAME + " (" + SOURCEID + ")"); } } catch (SQLException e) { throw new DatabaseException(e); } } /* (non-Javadoc) * @see org.parosproxy.paros.db.paros.TableAlert#read(int) */ @Override public synchronized RecordAlert read(int alertId) throws DatabaseException { try { psRead.setInt(1, alertId); try (ResultSet rs = psRead.executeQuery()) { RecordAlert ra = build(rs); return ra; } } catch (Exception e) { throw new DatabaseException(e); } } /* (non-Javadoc) * @see org.parosproxy.paros.db.paros.TableAlert#write(int, int, java.lang.String, int, int, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, int, int, int, int) */ @Override public synchronized RecordAlert write( int scanId, int pluginId, String alert, int risk, int confidence, String description, String uri, String param, String attack, String otherInfo, String solution, String reference, String evidence, int cweId, int wascId, int historyId, int sourceHistoryId, int sourceId) throws DatabaseException { try { psInsert.setInt(1, scanId); psInsert.setInt(2, pluginId); psInsert.setString(3, alert); psInsert.setInt(4, risk); psInsert.setInt(5, confidence); psInsert.setString(6, description); psInsert.setString(7, uri); psInsert.setString(8, param); psInsert.setString(9, attack); psInsert.setString(10, otherInfo); psInsert.setString(11, solution); psInsert.setString(12, reference); psInsert.setString(13, evidence); psInsert.setInt(14, cweId); psInsert.setInt(15, wascId); psInsert.setInt(16, historyId); psInsert.setInt(17, sourceHistoryId); psInsert.setInt(18, sourceId); psInsert.executeUpdate(); int id; try (ResultSet rs = psGetIdLastInsert.executeQuery()) { rs.next(); id = rs.getInt(1); } return read(id); } catch (SQLException e) { throw new DatabaseException(e); } } private RecordAlert build(ResultSet rs) throws DatabaseException { try { RecordAlert alert = null; if (rs.next()) { alert = new RecordAlert( rs.getInt(ALERTID), rs.getInt(SCANID), rs.getInt(PLUGINID), rs.getString(ALERT), rs.getInt(RISK), rs.getInt(RELIABILITY), rs.getString(DESCRIPTION), rs.getString(URI), rs.getString(PARAM), rs.getString(ATTACK), rs.getString(OTHERINFO), rs.getString(SOLUTION), rs.getString(REFERENCE), rs.getString(EVIDENCE), rs.getInt(CWEID), rs.getInt(WASCID), rs.getInt(HISTORYID), rs.getInt(SOURCEHISTORYID), rs.getInt(SOURCEID)); } return alert; } catch (SQLException e) { throw new DatabaseException(e); } } public Vector<Integer> getAlertListByScan(int scanId) throws DatabaseException { try { try (PreparedStatement psReadScan = getConnection() .prepareStatement( "SELECT ALERTID FROM " + TABLE_NAME + " WHERE " + SCANID + " = ?")) { Vector<Integer> v = new Vector<>(); psReadScan.setInt(1, scanId); try (ResultSet rs = psReadScan.executeQuery()) { while (rs.next()) { // ZAP: Changed to use the method Integer.valueOf. v.add(rs.getInt(ALERTID)); } } return v; } } catch (SQLException e) { throw new DatabaseException(e); } } @Override public Vector<Integer> getAlertListBySession(long sessionId) throws DatabaseException { try { try (PreparedStatement psReadSession = getConnection() .prepareStatement( "SELECT ALERTID FROM " + TABLE_NAME + " INNER JOIN SCAN ON ALERT.SCANID = SCAN.SCANID WHERE SESSIONID = ?")) { Vector<Integer> v = new Vector<>(); psReadSession.setLong(1, sessionId); try (ResultSet rs = psReadSession.executeQuery()) { while (rs.next()) { int alertId = rs.getInt(ALERTID); // ZAP: Changed to use the method Integer.valueOf. v.add(alertId); } } return v; } } catch (SQLException e) { throw new DatabaseException(e); } } /* (non-Javadoc) * @see org.parosproxy.paros.db.paros.TableAlert#deleteAlert(int) */ @Override public synchronized void deleteAlert(int alertId) throws DatabaseException { try { psDeleteAlert.setInt(1, alertId); psDeleteAlert.execute(); } catch (SQLException e) { throw new DatabaseException(e); } } /* (non-Javadoc) * @see org.parosproxy.paros.db.paros.TableAlert#deleteAllAlerts() */ @Override public int deleteAllAlerts() throws DatabaseException { try { return psDeleteAllAlerts.executeUpdate(); } catch (SQLException e) { throw new DatabaseException(e); } } /* (non-Javadoc) * @see org.parosproxy.paros.db.paros.TableAlert#update(int, java.lang.String, int, int, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, int, int, int) */ @Override public synchronized void update( int alertId, String alert, int risk, int confidence, String description, String uri, String param, String attack, String otherInfo, String solution, String reference, String evidence, int cweId, int wascId, int sourceHistoryId) throws DatabaseException { try { psUpdate.setString(1, alert); psUpdate.setInt(2, risk); psUpdate.setInt(3, confidence); psUpdate.setString(4, description); psUpdate.setString(5, uri); psUpdate.setString(6, param); psUpdate.setString(7, attack); psUpdate.setString(8, otherInfo); psUpdate.setString(9, solution); psUpdate.setString(10, reference); psUpdate.setString(11, evidence); psUpdate.setInt(12, cweId); psUpdate.setInt(13, wascId); psUpdate.setInt(14, sourceHistoryId); psUpdate.setInt(15, alertId); psUpdate.executeUpdate(); } catch (SQLException e) { throw new DatabaseException(e); } } /* (non-Javadoc) * @see org.parosproxy.paros.db.paros.TableAlert#updateHistoryIds(int, int, int) */ @Override public synchronized void updateHistoryIds(int alertId, int historyId, int sourceHistoryId) throws DatabaseException { try { psUpdateHistoryIds.setInt(1, historyId); psUpdateHistoryIds.setInt(2, sourceHistoryId); psUpdateHistoryIds.setInt(3, alertId); psUpdateHistoryIds.executeUpdate(); } catch (SQLException e) { throw new DatabaseException(e); } } /* (non-Javadoc) * @see org.parosproxy.paros.db.paros.TableAlert#getAlertsBySourceHistoryId(int) */ @Override public synchronized List<RecordAlert> getAlertsBySourceHistoryId(int historyId) throws DatabaseException { try { List<RecordAlert> result = new ArrayList<>(); psGetAlertsForHistoryId.setLong(1, historyId); try (ResultSet rs = psGetAlertsForHistoryId.executeQuery()) { RecordAlert ra = build(rs); while (ra != null) { result.add(ra); ra = build(rs); } } return result; } catch (SQLException e) { throw new DatabaseException(e); } } /* (non-Javadoc) * @see org.parosproxy.paros.db.paros.TableAlert#getAlertList() */ @Override public Vector<Integer> getAlertList() throws DatabaseException { try { try (PreparedStatement psReadScan = getConnection().prepareStatement("SELECT " + ALERTID + " FROM " + TABLE_NAME)) { Vector<Integer> v = new Vector<>(); try (ResultSet rs = psReadScan.executeQuery()) { while (rs.next()) { v.add(rs.getInt(ALERTID)); } } return v; } } catch (SQLException e) { throw new DatabaseException(e); } } }
meitar/zaproxy
zap/src/main/java/org/parosproxy/paros/db/paros/ParosTableAlert.java
Java
apache-2.0
22,718
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* ===== textbox.css ================================================== == Styles used by the XUL textbox element. ======================================================================= */ @namespace url("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"); @namespace html url("http://www.w3.org/1999/xhtml"); /* ::::: textbox ::::: */ textbox { -moz-appearance: textfield; cursor: text; margin: 2px 4px; border: 2px solid; -moz-border-top-colors: ThreeDShadow ThreeDDarkShadow; -moz-border-right-colors: ThreeDHighlight ThreeDLightShadow; -moz-border-bottom-colors: ThreeDHighlight ThreeDLightShadow; -moz-border-left-colors: ThreeDShadow ThreeDDarkShadow; padding: 2px 2px 3px; -moz-padding-start: 4px; background-color: -moz-Field; color: -moz-FieldText; } html|*.textbox-input, html|*.textbox-textarea { margin: 0px !important; border: none !important; padding: 0px !important; background-color: inherit; color: inherit; font: inherit; } html|*.textbox-input:-moz-placeholder, html|*.textbox-textarea:-moz-placeholder { color: GrayText; } .textbox-contextmenu { cursor: default; } /* ..... readonly state ..... */ textbox[readonly="true"] { background-color: -moz-Dialog; color: -moz-DialogText; } /* ..... disabled state ..... */ textbox[disabled="true"] { cursor: default; background-color: -moz-Dialog; color: GrayText; } /* ::::: plain textbox ::::: */ textbox.plain { -moz-appearance: none !important; background-color: transparent; padding: 0px !important; margin: 0px !important; border: none !important; } /* ::::: search textbox ::::: */ .textbox-search-icon { list-style-image: url(moz-icon://stock/gtk-find?size=menu); } .textbox-search-clear { list-style-image: url(moz-icon://stock/gtk-clear?size=menu); } .textbox-search-icon[searchbutton]:not([disabled]) , .textbox-search-clear:not([disabled]) { cursor: pointer; } /* ::::: textboxes inside toolbarpaletteitems ::::: */ toolbarpaletteitem > toolbaritem > textbox > .textbox-input-box > html|*.textbox-input { visibility: hidden; } /* ::::: context menu ::::: */ menuitem:not([type]) { -moz-binding: url("chrome://global/content/bindings/menu.xml#menuitem-iconic"); } menuitem[cmd="cmd_undo"] { list-style-image: url("moz-icon://stock/gtk-undo?size=menu"); } menuitem[cmd="cmd_undo"][disabled] { list-style-image: url("moz-icon://stock/gtk-undo?size=menu&state=disabled"); } menuitem[cmd="cmd_cut"] { list-style-image: url("moz-icon://stock/gtk-cut?size=menu"); } menuitem[cmd="cmd_cut"][disabled] { list-style-image: url("moz-icon://stock/gtk-cut?size=menu&state=disabled"); } menuitem[cmd="cmd_copy"] { list-style-image: url("moz-icon://stock/gtk-copy?size=menu"); } menuitem[cmd="cmd_copy"][disabled] { list-style-image: url("moz-icon://stock/gtk-copy?size=menu&state=disabled"); } menuitem[cmd="cmd_paste"] { list-style-image: url("moz-icon://stock/gtk-paste?size=menu"); } menuitem[cmd="cmd_paste"][disabled] { list-style-image: url("moz-icon://stock/gtk-paste?size=menu&state=disabled"); } menuitem[cmd="cmd_delete"] { list-style-image: url("moz-icon://stock/gtk-delete?size=menu"); } menuitem[cmd="cmd_delete"][disabled] { list-style-image: url("moz-icon://stock/gtk-delete?size=menu&state=disabled"); } menuitem[cmd="cmd_selectAll"] { list-style-image: url("moz-icon://stock/gtk-select-all?size=menu"); } menuitem[cmd="cmd_selectAll"][disabled] { list-style-image: url("moz-icon://stock/gtk-select-all?size=menu&state=disabled"); }
sergecodd/FireFox-OS
B2G/gecko/toolkit/themes/gnomestripe/global/textbox.css
CSS
apache-2.0
3,761
<div class="main-content"> <h2>ApplicationInfo</h2> <table class="table table-hover"> <colgroup> <col style="width: 10%;"/> <col style="width: 30%;"/> <col style="width: 10%;"/> <col style="width: 20%;"/> <col style="width: 30%;"/> </colgroup> <thead> <tr> <th>Name</th> <th>Description</th> <th>Schema</th> <th>Default</th> <th>Example</th> </tr> </thead> <tbody> <tr> <td class="parameter"> <p>applicationId</p> <p class="param-required"> optional </p> </td> <td class="parameter"><p class="marked"></p></td> <td class="parameter"> <a href="#!/models#string">string</a> </td> <td class="parameter"> <p class="marked">null</p></td> <td class="parameter"> <p class="marked">01234567-0123-0123-0123-012345678901</p></td> </tr> <tr> <td class="parameter"> <p>name</p> <p class="param-required"> optional </p> </td> <td class="parameter"><p class="marked"></p></td> <td class="parameter"> <a href="#!/models#string">string</a> </td> <td class="parameter"> <p class="marked">null</p></td> <td class="parameter"> <p class="marked">CalculatorApp</p></td> </tr> <tr> <td class="parameter"> <p>throttlingPolicy</p> <p class="param-required"> optional </p> </td> <td class="parameter"><p class="marked"></p></td> <td class="parameter"> <a href="#!/models#string">string</a> </td> <td class="parameter"> <p class="marked">null</p></td> <td class="parameter"> <p class="marked">Unlimited</p></td> </tr> <tr> <td class="parameter"> <p>description</p> <p class="param-required"> optional </p> </td> <td class="parameter"><p class="marked"></p></td> <td class="parameter"> <a href="#!/models#string">string</a> </td> <td class="parameter"> <p class="marked">null</p></td> <td class="parameter"> <p class="marked">Sample calculator application</p></td> </tr> <tr> <td class="parameter"> <p>status</p> <p class="param-required"> optional </p> </td> <td class="parameter"><p class="marked"></p></td> <td class="parameter"> <a href="#!/models#string">string</a> </td> <td class="parameter"> <p class="marked">null</p></td> <td class="parameter"> <p class="marked">APPROVED</p></td> </tr> <tr> <td class="parameter"> <p>groups</p> <p class="param-required"> optional </p> </td> <td class="parameter"><p class="marked"></p></td> <td class="parameter"> <a href="#!/models#array">array</a> </td> <td class="parameter"> <p class="marked">null</p></td> <td class="parameter"> <p class="marked">&quot;&quot;</p></td> </tr> <tr> <td class="parameter"> <p>subscriptionCount</p> <p class="param-required"> optional </p> </td> <td class="parameter"><p class="marked"></p></td> <td class="parameter"> <a href="#!/models#integer">integer</a> </td> <td class="parameter"> <p class="marked">null</p></td> <td class="parameter"> <p class="marked"></p></td> </tr> <tr> <td class="parameter"> <p>attributes</p> <p class="param-required"> optional </p> </td> <td class="parameter"><p class="marked"></p></td> <td class="parameter"> <a href="#!/models#object">object</a> </td> <td class="parameter"> <p class="marked">null</p></td> <td class="parameter"> <p class="marked">&quot;External Reference ID, Billing Tier&quot;</p></td> </tr> <tr> <td class="parameter"> <p>owner</p> <p class="param-required"> optional </p> </td> <td class="parameter"><p class="marked"></p></td> <td class="parameter"> <a href="#!/models#string">string</a> </td> <td class="parameter"> <p class="marked">null</p></td> <td class="parameter"> <p class="marked">admin</p></td> </tr> </tbody> </table> </div>
nuwand/carbon-apimgt
docs/apidocs/store/v1/models/ApplicationInfo.html
HTML
apache-2.0
7,307
package ca.uhn.fhir.rest.gclient; /*- * #%L * HAPI FHIR - Core Library * %% * Copyright (C) 2014 - 2022 Smile CDR, 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. * #L% */ import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.rest.api.Constants; abstract class BaseClientParam implements IParam { @Override public ICriterion<?> isMissing(boolean theMissing) { return new MissingCriterion(theMissing ? Constants.PARAMQUALIFIER_MISSING_TRUE : Constants.PARAMQUALIFIER_MISSING_FALSE); } private class MissingCriterion implements ICriterion<IParam>, ICriterionInternal { private String myParameterValue; public MissingCriterion(String theParameterValue) { myParameterValue = theParameterValue; } @Override public String getParameterValue(FhirContext theContext) { return myParameterValue; } @Override public String getParameterName() { return BaseClientParam.this.getParamName() + Constants.PARAMQUALIFIER_MISSING; } } }
jamesagnew/hapi-fhir
hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/BaseClientParam.java
Java
apache-2.0
1,496
/* 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.flowable.engine.impl.cmd; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.flowable.engine.delegate.event.FlowableEngineEventType; import org.flowable.engine.delegate.event.impl.FlowableEventBuilder; import org.flowable.engine.impl.interceptor.Command; import org.flowable.engine.impl.interceptor.CommandContext; import org.flowable.engine.impl.persistence.entity.JobEntity; import org.flowable.engine.impl.persistence.entity.TimerJobEntity; /** * Send job cancelled event and delete job * * @author Tom Baeyens */ public class CancelJobsCmd implements Command<Void>, Serializable { private static final long serialVersionUID = 1L; List<String> jobIds; public CancelJobsCmd(List<String> jobIds) { this.jobIds = jobIds; } public CancelJobsCmd(String jobId) { this.jobIds = new ArrayList<String>(); jobIds.add(jobId); } public Void execute(CommandContext commandContext) { JobEntity jobToDelete = null; for (String jobId : jobIds) { jobToDelete = commandContext.getJobEntityManager().findById(jobId); if (jobToDelete != null) { // When given job doesn't exist, ignore if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) { commandContext.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(FlowableEventBuilder.createEntityEvent(FlowableEngineEventType.JOB_CANCELED, jobToDelete)); } commandContext.getJobEntityManager().delete(jobToDelete); } else { TimerJobEntity timerJobToDelete = commandContext.getTimerJobEntityManager().findById(jobId); if (timerJobToDelete != null) { // When given job doesn't exist, ignore if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) { commandContext.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(FlowableEventBuilder.createEntityEvent(FlowableEngineEventType.JOB_CANCELED, timerJobToDelete)); } commandContext.getTimerJobEntityManager().delete(timerJobToDelete); } } } return null; } }
robsoncardosoti/flowable-engine
modules/flowable-engine/src/main/java/org/flowable/engine/impl/cmd/CancelJobsCmd.java
Java
apache-2.0
2,926
/* * 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 com.glaf.base.modules.sys.model; public class RealmInfo implements java.io.Serializable { private static final long serialVersionUID = 1L; protected String item; protected String url; public RealmInfo() { } public String getItem() { return item; } public void setItem(String item) { this.item = item; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
jior/glaf
workspace/glaf-base/src/main/java/com/glaf/base/modules/sys/model/RealmInfo.java
Java
apache-2.0
1,242
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets 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 io.druid.indexer; import com.fasterxml.jackson.databind.InjectableValues; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.metamx.common.Granularity; import io.druid.data.input.MapBasedInputRow; import io.druid.granularity.QueryGranularity; import io.druid.jackson.DefaultObjectMapper; import io.druid.query.aggregation.AggregatorFactory; import io.druid.segment.indexing.DataSchema; import io.druid.segment.indexing.granularity.UniformGranularitySpec; import io.druid.timeline.partition.HashBasedNumberedShardSpec; import org.apache.hadoop.fs.LocalFileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.DistributedFileSystem; import org.joda.time.DateTime; import org.joda.time.Interval; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; import java.util.List; /** */ public class HadoopDruidIndexerConfigTest { private static final ObjectMapper jsonMapper; static { jsonMapper = new DefaultObjectMapper(); jsonMapper.setInjectableValues(new InjectableValues.Std().addValue(ObjectMapper.class, jsonMapper)); } public static <T> T jsonReadWriteRead(String s, Class<T> klass) { try { return jsonMapper.readValue(jsonMapper.writeValueAsBytes(jsonMapper.readValue(s, klass)), klass); } catch (Exception e) { throw Throwables.propagate(e); } } @Test public void shouldMakeHDFSCompliantSegmentOutputPath() { HadoopIngestionSpec schema; try { schema = jsonReadWriteRead( "{\n" + " \"dataSchema\": {\n" + " \"dataSource\": \"source\",\n" + " \"metricsSpec\": [],\n" + " \"granularitySpec\": {\n" + " \"type\": \"uniform\",\n" + " \"segmentGranularity\": \"hour\",\n" + " \"intervals\": [\"2012-07-10/P1D\"]\n" + " }\n" + " },\n" + " \"ioConfig\": {\n" + " \"type\": \"hadoop\",\n" + " \"segmentOutputPath\": \"hdfs://server:9100/tmp/druid/datatest\"\n" + " }\n" + "}", HadoopIngestionSpec.class ); } catch (Exception e) { throw Throwables.propagate(e); } HadoopDruidIndexerConfig cfg = new HadoopDruidIndexerConfig( schema.withTuningConfig( schema.getTuningConfig() .withVersion( "some:brand:new:version" ) ) ); Bucket bucket = new Bucket(4711, new DateTime(2012, 07, 10, 5, 30), 4712); Path path = JobHelper.makeSegmentOutputPath( new Path(cfg.getSchema().getIOConfig().getSegmentOutputPath()), new DistributedFileSystem(), cfg.getSchema().getDataSchema().getDataSource(), cfg.getSchema().getTuningConfig().getVersion(), cfg.getSchema().getDataSchema().getGranularitySpec().bucketInterval(bucket.time).get(), bucket.partitionNum ); Assert.assertEquals( "hdfs://server:9100/tmp/druid/datatest/source/20120710T050000.000Z_20120710T060000.000Z/some_brand_new_version/4712", path.toString() ); } @Test public void shouldMakeDefaultSegmentOutputPathIfNotHDFS() { final HadoopIngestionSpec schema; try { schema = jsonReadWriteRead( "{\n" + " \"dataSchema\": {\n" + " \"dataSource\": \"the:data:source\",\n" + " \"metricsSpec\": [],\n" + " \"granularitySpec\": {\n" + " \"type\": \"uniform\",\n" + " \"segmentGranularity\": \"hour\",\n" + " \"intervals\": [\"2012-07-10/P1D\"]\n" + " }\n" + " },\n" + " \"ioConfig\": {\n" + " \"type\": \"hadoop\",\n" + " \"segmentOutputPath\": \"/tmp/dru:id/data:test\"\n" + " }\n" + "}", HadoopIngestionSpec.class ); } catch (Exception e) { throw Throwables.propagate(e); } HadoopDruidIndexerConfig cfg = new HadoopDruidIndexerConfig( schema.withTuningConfig( schema.getTuningConfig() .withVersion( "some:brand:new:version" ) ) ); Bucket bucket = new Bucket(4711, new DateTime(2012, 07, 10, 5, 30), 4712); Path path = JobHelper.makeSegmentOutputPath( new Path(cfg.getSchema().getIOConfig().getSegmentOutputPath()), new LocalFileSystem(), cfg.getSchema().getDataSchema().getDataSource(), cfg.getSchema().getTuningConfig().getVersion(), cfg.getSchema().getDataSchema().getGranularitySpec().bucketInterval(bucket.time).get(), bucket.partitionNum ); Assert.assertEquals( "file:/tmp/dru:id/data:test/the:data:source/2012-07-10T05:00:00.000Z_2012-07-10T06:00:00.000Z/some:brand:new:version/4712", path.toString() ); } @Test public void testHashedBucketSelection() { List<HadoopyShardSpec> specs = Lists.newArrayList(); final int partitionCount = 10; for (int i = 0; i < partitionCount; i++) { specs.add(new HadoopyShardSpec(new HashBasedNumberedShardSpec(i, partitionCount, new DefaultObjectMapper()), i)); } HadoopIngestionSpec spec = new HadoopIngestionSpec( new DataSchema( "foo", null, new AggregatorFactory[0], new UniformGranularitySpec( Granularity.MINUTE, QueryGranularity.MINUTE, ImmutableList.of(new Interval("2010-01-01/P1D")) ), jsonMapper ), new HadoopIOConfig(ImmutableMap.<String, Object>of("paths", "bar", "type", "static"), null, null), new HadoopTuningConfig( null, null, null, ImmutableMap.of(new DateTime("2010-01-01T01:00:00"), specs), null, null, false, false, false, false, null, false, false, null, null, null ) ); HadoopDruidIndexerConfig config = HadoopDruidIndexerConfig.fromSpec(spec); final List<String> dims = Arrays.asList("diM1", "dIM2"); final ImmutableMap<String, Object> values = ImmutableMap.<String, Object>of( "Dim1", "1", "DiM2", "2", "dim1", "3", "dim2", "4" ); final long timestamp = new DateTime("2010-01-01T01:00:01").getMillis(); final Bucket expectedBucket = config.getBucket(new MapBasedInputRow(timestamp, dims, values)).get(); final long nextBucketTimestamp = QueryGranularity.MINUTE.next(QueryGranularity.MINUTE.truncate(timestamp)); // check that all rows having same set of dims and truncated timestamp hash to same bucket for (int i = 0; timestamp + i < nextBucketTimestamp; i++) { Assert.assertEquals( expectedBucket.partitionNum, config.getBucket(new MapBasedInputRow(timestamp + i, dims, values)).get().partitionNum ); } } }
haoch/druid
indexing-hadoop/src/test/java/io/druid/indexer/HadoopDruidIndexerConfigTest.java
Java
apache-2.0
8,179
describe('Core.selectCell', () => { beforeEach(function() { this.$container = $('<div id="testContainer"></div>').appendTo('body'); }); afterEach(function() { if (this.$container) { destroy(); this.$container.remove(); } }); it('should mark single cell visually (default selectionMode, without headers)', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(6, 4), colHeaders: false, rowHeaders: false, }); selectCell(2, 2); expect(` | : : : | | : : : | | : : # : | | : : : | | : : : | | : : : | `).toBeMatchToSelectionPattern(); }); it('should mark single cell visually (default selectionMode)', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(6, 4), colHeaders: true, rowHeaders: true, }); selectCell(2, 2); expect(` | ║ : : - : | |===:===:===:===:===| | ║ : : : | | ║ : : : | | - ║ : : # : | | ║ : : : | | ║ : : : | | ║ : : : | `).toBeMatchToSelectionPattern(); }); it('should mark range of the cells visually (default selectionMode)', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(6, 4), colHeaders: true, rowHeaders: true, }); selectCell(1, 2, 2, 3); expect(` | ║ : : - : - | |===:===:===:===:===| | ║ : : : | | - ║ : : A : 0 | | - ║ : : 0 : 0 | | ║ : : : | | ║ : : : | | ║ : : : | `).toBeMatchToSelectionPattern(); }); it('should mark single cell visually when selectionMode is set as `single', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(6, 4), selectionMode: 'single', colHeaders: true, rowHeaders: true, }); selectCell(2, 2); expect(` | ║ : : - : | |===:===:===:===:===| | ║ : : : | | ║ : : : | | - ║ : : # : | | ║ : : : | | ║ : : : | | ║ : : : | `).toBeMatchToSelectionPattern(); }); it('should not mark the range of the cells visually when selectionMode is set as `single`', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(6, 4), selectionMode: 'single', colHeaders: true, rowHeaders: true, }); selectCell(1, 2, 2, 3); expect(` | ║ : : - : | |===:===:===:===:===| | ║ : : : | | - ║ : : # : | | ║ : : : | | ║ : : : | | ║ : : : | | ║ : : : | `).toBeMatchToSelectionPattern(); }); it('should mark single cell visually when selectionMode is set as `range', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(6, 4), selectionMode: 'range', colHeaders: true, rowHeaders: true, }); selectCell(2, 2); expect(` | ║ : : - : | |===:===:===:===:===| | ║ : : : | | ║ : : : | | - ║ : : # : | | ║ : : : | | ║ : : : | | ║ : : : | `).toBeMatchToSelectionPattern(); }); it('should mark the range of the cells visually when selectionMode is set as `range`', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(6, 4), selectionMode: 'range', colHeaders: true, rowHeaders: true, }); selectCell(1, 2, 2, 3); expect(` | ║ : : - : - | |===:===:===:===:===| | ║ : : : | | - ║ : : A : 0 | | - ║ : : 0 : 0 | | ║ : : : | | ║ : : : | | ║ : : : | `).toBeMatchToSelectionPattern(); }); it('should mark the headers when whole column and row is selected', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(6, 4), colHeaders: true, rowHeaders: true, }); selectCell(0, 2, 5, 3); expect(` | ║ : : - : - | |===:===:===:===:===| | - ║ : : A : 0 | | - ║ : : 0 : 0 | | - ║ : : 0 : 0 | | - ║ : : 0 : 0 | | - ║ : : 0 : 0 | | - ║ : : 0 : 0 | `).toBeMatchToSelectionPattern(); selectCell(1, 0, 2, 3); expect(` | ║ - : - : - : - | |===:===:===:===:===| | ║ : : : | | - ║ A : 0 : 0 : 0 | | - ║ 0 : 0 : 0 : 0 | | ║ : : : | | ║ : : : | | ║ : : : | `).toBeMatchToSelectionPattern(); }); it('should not deselect current selection when sellectCell is called without arguments', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(6, 4), }); selectCell(0, 0, 2, 2); expect(getSelected()).toEqual([[0, 0, 2, 2]]); selectCell(); expect(getSelected()).toEqual([[0, 0, 2, 2]]); selectCell(1); expect(getSelected()).toEqual([[0, 0, 2, 2]]); }); it('should not deselect current selection when sellectCell is called with one argument', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(6, 4), }); let wasSelected = selectCell(0, 0, 2, 2); expect(getSelected()).toEqual([[0, 0, 2, 2]]); expect(wasSelected).toBe(true); wasSelected = selectCell(1); expect(getSelected()).toEqual([[0, 0, 2, 2]]); expect(wasSelected).toBe(false); }); it('should not deselect current selection when sellectCell is called with negative values', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(6, 4), }); let wasSelected = selectCell(0, 0, 2, 2); expect(getSelected()).toEqual([[0, 0, 2, 2]]); expect(wasSelected).toBe(true); wasSelected = selectCell(0, -1, 0, 0); expect(getSelected()).toEqual([[0, 0, 2, 2]]); expect(wasSelected).toBe(false); wasSelected = selectCell(-1, 0, 0, 0); expect(getSelected()).toEqual([[0, 0, 2, 2]]); expect(wasSelected).toBe(false); wasSelected = selectCell(0, 0, -1, 0); expect(getSelected()).toEqual([[0, 0, 2, 2]]); expect(wasSelected).toBe(false); wasSelected = selectCell(0, 0, 0, -1); expect(getSelected()).toEqual([[0, 0, 2, 2]]); expect(wasSelected).toBe(false); }); it('should not deselect current selection when sellectCell is called with coordinates beyond the table data range', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(3, 4), }); let wasSelected = selectCell(0, 0, 2, 2); expect(getSelected()).toEqual([[0, 0, 2, 2]]); expect(wasSelected).toBe(true); wasSelected = selectCell(3, 0); expect(getSelected()).toEqual([[0, 0, 2, 2]]); expect(wasSelected).toBe(false); wasSelected = selectCell(0, 4); expect(getSelected()).toEqual([[0, 0, 2, 2]]); expect(wasSelected).toBe(false); wasSelected = selectCell(0, 0, 3, 0); expect(getSelected()).toEqual([[0, 0, 2, 2]]); expect(wasSelected).toBe(false); wasSelected = selectCell(0, 0, 0, 4); expect(getSelected()).toEqual([[0, 0, 2, 2]]); expect(wasSelected).toBe(false); }); it('should not deselect current selection when sellectCell is called with undefined column property', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(6, 4), }); let wasSelected = selectCell(0, 0, 2, 2); expect(getSelected()).toEqual([[0, 0, 2, 2]]); expect(wasSelected).toBe(true); wasSelected = selectCell(0, 'notExistProp'); expect(getSelected()).toEqual([[0, 0, 2, 2]]); expect(wasSelected).toBe(false); wasSelected = selectCell(0, 0, 0, 'notExistProp'); expect(getSelected()).toEqual([[0, 0, 2, 2]]); expect(wasSelected).toBe(false); }); it('should select only one cell when two arguments are passed', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(6, 4), }); let wasSelected = selectCell(1, 1); expect(getSelected()).toEqual([[1, 1, 1, 1]]); expect(wasSelected).toBe(true); }); it('should select only one cell when two arguments are passed (column property)', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(6, 4), }); let wasSelected = selectCell(1, 'prop1'); expect(getSelected()).toEqual([[1, 1, 1, 1]]); expect(wasSelected).toBe(true); }); it('should select range of cells when at least the three arguments are passed', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(6, 4), }); let wasSelected = selectCell(0, 0, 1); expect(getSelected()).toEqual([[0, 0, 1, 0]]); expect(wasSelected).toBe(true); }); it('should select range of cells when at least the three arguments are passed (column property)', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(6, 4), }); let wasSelected = selectCell(0, 'prop0', 1); expect(getSelected()).toEqual([[0, 0, 1, 0]]); expect(wasSelected).toBe(true); }); it('should select range of cells when the four arguments are passed', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(6, 4), }); let wasSelected = selectCell(1, 1, 2, 3); expect(getSelected()).toEqual([[1, 1, 2, 3]]); expect(wasSelected).toBe(true); }); it('should select range of cells when the four arguments are passed (column property)', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(6, 4), }); let wasSelected = selectCell(1, 'prop1', 2, 'prop3'); expect(getSelected()).toEqual([[1, 1, 2, 3]]); expect(wasSelected).toBe(true); }); it('should select range of cells when the coordinates are passed in reversed order (from right-bottom to left-top)', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(6, 4), }); let wasSelected = selectCell(2, 3, 1, 1); expect(getSelected()).toEqual([[2, 3, 1, 1]]); expect(wasSelected).toBe(true); }); it('should select range of cells when the coordinates are passed in reversed order (from right-bottom to left-top using column property)', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(6, 4), }); let wasSelected = selectCell(2, 'prop3', 1, 'prop1'); expect(getSelected()).toEqual([[2, 3, 1, 1]]); expect(wasSelected).toBe(true); }); it('should select range of cells when the coordinates are passed in reversed order (from left-bottom to right-top)', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(6, 4), }); let wasSelected = selectCell(2, 1, 1, 3); expect(getSelected()).toEqual([[2, 1, 1, 3]]); expect(wasSelected).toBe(true); }); it('should select range of cells when the coordinates are passed in reversed order (from left-bottom to right-top using column property)', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(6, 4), }); let wasSelected = selectCell(2, 'prop1', 1, 'prop3'); expect(getSelected()).toEqual([[2, 1, 1, 3]]); expect(wasSelected).toBe(true); }); it('should select range of cells when the coordinates are passed in reversed order (from right-top to left-bottom)', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(6, 4), }); let wasSelected = selectCell(1, 3, 2, 1); expect(getSelected()).toEqual([[1, 3, 2, 1]]); expect(wasSelected).toBe(true); }); it('should select range of cells when the coordinates are passed in reversed order (from right-top to left-bottom using column property)', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(6, 4), }); let wasSelected = selectCell(1, 'prop3', 2, 'prop1'); expect(getSelected()).toEqual([[1, 3, 2, 1]]); expect(wasSelected).toBe(true); }); it('should by default scroll the viewport to the selected cell (bottom of the viewport)', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(20, 20), height: 300, width: 300, }); selectCell(15, 0); expect(getCell(15, 0)).toBeVisibleAtBottomOfViewport(); }); it('should by default scroll the viewport to the selected cell using column props (bottom of the viewport)', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(20, 20), height: 300, width: 300, }); selectCell(15, 'prop0'); expect(getCell(15, 0)).toBeVisibleAtBottomOfViewport(); }); it('should by default scroll the viewport to the selected cell (right of the viewport)', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(20, 20), height: 300, width: 300, }); selectCell(5, 15); expect(getCell(5, 15)).toBeVisibleAtRightOfViewport(); }); it('should by default scroll the viewport to the selected cell using column props (right of the viewport)', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(20, 20), height: 300, width: 300, }); selectCell(5, 'prop15'); expect(getCell(5, 15)).toBeVisibleAtRightOfViewport(); }); it('should by default scroll the viewport to the selected cell (left of the viewport)', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(20, 20), height: 300, width: 300, }); selectCell(5, 15); // Scroll to the right of the table. selectCell(5, 0); expect(getCell(5, 0)).toBeVisibleAtLeftOfViewport(); }); it('should by default scroll the viewport to the selected cell using column props (left of the viewport)', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(20, 20), height: 300, width: 300, }); selectCell(5, 15); // Scroll to the right of the table. selectCell(5, 'prop0'); expect(getCell(5, 0)).toBeVisibleAtLeftOfViewport(); }); it('should by default scroll the viewport to the selected cell (top of the viewport)', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(20, 20), height: 300, width: 300, }); selectCell(19, 0); // Scroll to the bottom of the table. selectCell(1, 0); expect(getCell(1, 0)).toBeVisibleAtTopOfViewport(); }); it('should by default scroll the viewport to the selected cell using column props (top of the viewport)', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(20, 20), height: 300, width: 300, }); selectCell(19, 0); // Scroll to the bottom of the table. selectCell(1, 'prop0'); expect(getCell(1, 0)).toBeVisibleAtTopOfViewport(); }); it('should not the scroll the viewport when `false` argument is passed', () => { handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(20, 20), height: 300, width: 300, }); selectCell(15, 0, 15, 0, false); expect(getCell(15, 0)).not.toBeVisibleInViewport(); }); it('should by default change the listener to handsontable instance from the action was triggered', () => { const afterListen = jasmine.createSpy(); handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(20, 20), height: 300, width: 300, afterListen, }); selectCell(15, 0); expect(afterListen).toHaveBeenCalled(); }); it('should not change the listening state when `false` argument is passed', () => { const afterListen = jasmine.createSpy(); handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(20, 20), height: 300, width: 300, afterListen, }); selectCell(15, 0, 15, 0, true, false); expect(afterListen).not.toHaveBeenCalled(); }); it('should fire hooks with proper context', () => { const { afterSelection, afterSelectionByProp, afterSelectionEnd, afterSelectionEndByProp, beforeSetRangeStart, beforeSetRangeStartOnly, beforeSetRangeEnd, } = jasmine.createSpyObj('hooks', [ 'afterSelection', 'afterSelectionByProp', 'afterSelectionEnd', 'afterSelectionEndByProp', 'beforeSetRangeStart', 'beforeSetRangeStartOnly', 'beforeSetRangeEnd', ]); const hot = handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(20, 20), height: 300, width: 300, afterSelection, afterSelectionByProp, afterSelectionEnd, afterSelectionEndByProp, beforeSetRangeStart, beforeSetRangeStartOnly, beforeSetRangeEnd, }); selectCell(1, 2); expect(afterSelection.calls.first().object).toBe(hot); expect(afterSelectionByProp.calls.first().object).toBe(hot); expect(afterSelectionEnd.calls.first().object).toBe(hot); expect(afterSelectionEndByProp.calls.first().object).toBe(hot); expect(beforeSetRangeStartOnly.calls.first().object).toBe(hot); }); it('should fire hooks with proper arguments when a single cell is selected', () => { const { afterSelection, afterSelectionByProp, afterSelectionEnd, afterSelectionEndByProp, beforeSetRangeStart, beforeSetRangeStartOnly, beforeSetRangeEnd, } = jasmine.createSpyObj('hooks', [ 'afterSelection', 'afterSelectionByProp', 'afterSelectionEnd', 'afterSelectionEndByProp', 'beforeSetRangeStart', 'beforeSetRangeStartOnly', 'beforeSetRangeEnd', ]); handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(20, 20), height: 300, width: 300, afterSelection, afterSelectionByProp, afterSelectionEnd, afterSelectionEndByProp, beforeSetRangeStart, beforeSetRangeStartOnly, beforeSetRangeEnd, }); selectCell(1, 2); expect(afterSelection.calls.count()).toBe(1); expect(afterSelection.calls.argsFor(0)).toEqual([1, 2, 1, 2, jasmine.any(Object), 0]); expect(afterSelectionByProp.calls.count()).toBe(1); expect(afterSelectionByProp.calls.argsFor(0)).toEqual([1, 'prop2', 1, 'prop2', jasmine.any(Object), 0]); expect(afterSelectionEnd.calls.count()).toBe(1); expect(afterSelectionEnd.calls.argsFor(0)).toEqual([1, 2, 1, 2, 0, void 0]); expect(afterSelectionEndByProp.calls.count()).toBe(1); expect(afterSelectionEndByProp.calls.argsFor(0)).toEqual([1, 'prop2', 1, 'prop2', 0, void 0]); expect(beforeSetRangeStart.calls.count()).toBe(0); expect(beforeSetRangeStartOnly.calls.count()).toBe(1); expect(beforeSetRangeStartOnly.calls.argsFor(0)[0].row).toBe(1); expect(beforeSetRangeStartOnly.calls.argsFor(0)[0].col).toBe(2); }); it('should fire hooks with proper arguments when range of the cells are selected', () => { const { afterSelection, afterSelectionByProp, afterSelectionEnd, afterSelectionEndByProp, beforeSetRangeStart, beforeSetRangeStartOnly, beforeSetRangeEnd, } = jasmine.createSpyObj('hooks', [ 'afterSelection', 'afterSelectionByProp', 'afterSelectionEnd', 'afterSelectionEndByProp', 'beforeSetRangeStart', 'beforeSetRangeStartOnly', 'beforeSetRangeEnd', ]); handsontable({ data: Handsontable.helper.createSpreadsheetObjectData(20, 20), height: 300, width: 300, afterSelection, afterSelectionByProp, afterSelectionEnd, afterSelectionEndByProp, beforeSetRangeStart, beforeSetRangeStartOnly, beforeSetRangeEnd, }); selectCell(1, 2, 2, 4); expect(afterSelection.calls.count()).toBe(1); expect(afterSelection.calls.argsFor(0)).toEqual([1, 2, 2, 4, jasmine.any(Object), 0]); expect(afterSelectionByProp.calls.count()).toBe(1); expect(afterSelectionByProp.calls.argsFor(0)).toEqual([1, 'prop2', 2, 'prop4', jasmine.any(Object), 0]); expect(afterSelectionEnd.calls.count()).toBe(1); expect(afterSelectionEnd.calls.argsFor(0)).toEqual([1, 2, 2, 4, 0, void 0]); expect(afterSelectionEndByProp.calls.count()).toBe(1); expect(afterSelectionEndByProp.calls.argsFor(0)).toEqual([1, 'prop2', 2, 'prop4', 0, void 0]); expect(beforeSetRangeStart.calls.count()).toBe(0); expect(beforeSetRangeStartOnly.calls.count()).toBe(1); expect(beforeSetRangeStartOnly.calls.argsFor(0)[0].row).toBe(1); expect(beforeSetRangeStartOnly.calls.argsFor(0)[0].col).toBe(2); }); });
victorbrodsky/order-lab
orderflex/public/orderassets/AppUserdirectoryBundle/handsontable-5/test/e2e/core/selectCell.spec.js
JavaScript
apache-2.0
21,243
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.editor.impl.event; import com.intellij.openapi.Disposable; import com.intellij.openapi.editor.event.*; import com.intellij.openapi.editor.ex.*; import com.intellij.openapi.editor.impl.EditorImpl; import com.intellij.util.EventDispatcher; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.TestOnly; import java.beans.PropertyChangeListener; import java.util.*; public class EditorEventMulticasterImpl implements EditorEventMulticasterEx { private final EventDispatcher<DocumentListener> myDocumentMulticaster = EventDispatcher.create(DocumentListener.class); private final EventDispatcher<EditReadOnlyListener> myEditReadOnlyMulticaster = EventDispatcher.create(EditReadOnlyListener.class); private final EventDispatcher<EditorMouseListener> myEditorMouseMulticaster = EventDispatcher.create(EditorMouseListener.class); private final EventDispatcher<EditorMouseMotionListener> myEditorMouseMotionMulticaster = EventDispatcher.create(EditorMouseMotionListener.class); private final EventDispatcher<ErrorStripeListener> myErrorStripeMulticaster = EventDispatcher.create(ErrorStripeListener.class); private final EventDispatcher<CaretListener> myCaretMulticaster = EventDispatcher.create(CaretListener.class); private final EventDispatcher<SelectionListener> mySelectionMulticaster = EventDispatcher.create(SelectionListener.class); private final EventDispatcher<VisibleAreaListener> myVisibleAreaMulticaster = EventDispatcher.create(VisibleAreaListener.class); private final EventDispatcher<PropertyChangeListener> myPropertyChangeMulticaster = EventDispatcher.create(PropertyChangeListener.class); private final EventDispatcher<FocusChangeListener> myFocusChangeListenerMulticaster = EventDispatcher.create(FocusChangeListener.class); public void registerDocument(@NotNull DocumentEx document) { document.addDocumentListener(myDocumentMulticaster.getMulticaster()); document.addEditReadOnlyListener(myEditReadOnlyMulticaster.getMulticaster()); } public void registerEditor(@NotNull EditorEx editor) { editor.addEditorMouseListener(myEditorMouseMulticaster.getMulticaster()); editor.addEditorMouseMotionListener(myEditorMouseMotionMulticaster.getMulticaster()); ((EditorMarkupModel) editor.getMarkupModel()).addErrorMarkerListener(myErrorStripeMulticaster.getMulticaster(), ((EditorImpl)editor).getDisposable()); editor.getCaretModel().addCaretListener(myCaretMulticaster.getMulticaster()); editor.getSelectionModel().addSelectionListener(mySelectionMulticaster.getMulticaster()); editor.getScrollingModel().addVisibleAreaListener(myVisibleAreaMulticaster.getMulticaster()); editor.addPropertyChangeListener(myPropertyChangeMulticaster.getMulticaster()); editor.addFocusListener(myFocusChangeListenerMulticaster.getMulticaster()); } @Override public void addDocumentListener(@NotNull DocumentListener listener) { myDocumentMulticaster.addListener(listener); } @Override public void addDocumentListener(@NotNull DocumentListener listener, @NotNull Disposable parentDisposable) { myDocumentMulticaster.addListener(listener, parentDisposable); } @Override public void removeDocumentListener(@NotNull DocumentListener listener) { myDocumentMulticaster.removeListener(listener); } @Override public void addEditorMouseListener(@NotNull EditorMouseListener listener) { myEditorMouseMulticaster.addListener(listener); } @Override public void addEditorMouseListener(@NotNull EditorMouseListener listener, @NotNull Disposable parentDisposable) { myEditorMouseMulticaster.addListener(listener, parentDisposable); } @Override public void removeEditorMouseListener(@NotNull EditorMouseListener listener) { myEditorMouseMulticaster.removeListener(listener); } @Override public void addEditorMouseMotionListener(@NotNull EditorMouseMotionListener listener) { myEditorMouseMotionMulticaster.addListener(listener); } @Override public void addEditorMouseMotionListener(@NotNull EditorMouseMotionListener listener, @NotNull Disposable parentDisposable) { myEditorMouseMotionMulticaster.addListener(listener, parentDisposable); } @Override public void removeEditorMouseMotionListener(@NotNull EditorMouseMotionListener listener) { myEditorMouseMotionMulticaster.removeListener(listener); } @Override public void addCaretListener(@NotNull CaretListener listener) { myCaretMulticaster.addListener(listener); } @Override public void addCaretListener(@NotNull CaretListener listener, @NotNull Disposable parentDisposable) { myCaretMulticaster.addListener(listener, parentDisposable); } @Override public void removeCaretListener(@NotNull CaretListener listener) { myCaretMulticaster.removeListener(listener); } @Override public void addSelectionListener(@NotNull SelectionListener listener) { mySelectionMulticaster.addListener(listener); } @Override public void addSelectionListener(@NotNull SelectionListener listener, @NotNull Disposable parentDisposable) { mySelectionMulticaster.addListener(listener, parentDisposable); } @Override public void removeSelectionListener(@NotNull SelectionListener listener) { mySelectionMulticaster.removeListener(listener); } @Override public void addErrorStripeListener(@NotNull ErrorStripeListener listener, @NotNull Disposable parentDisposable) { myErrorStripeMulticaster.addListener(listener, parentDisposable); } @Override public void addVisibleAreaListener(@NotNull VisibleAreaListener listener) { myVisibleAreaMulticaster.addListener(listener); } @Override public void removeVisibleAreaListener(@NotNull VisibleAreaListener listener) { myVisibleAreaMulticaster.removeListener(listener); } @Override public void addEditReadOnlyListener(@NotNull EditReadOnlyListener listener, @NotNull Disposable parentDisposable) { myEditReadOnlyMulticaster.addListener(listener, parentDisposable); } @Override public void addPropertyChangeListener(@NotNull PropertyChangeListener listener, @NotNull Disposable parentDisposable) { myPropertyChangeMulticaster.addListener(listener, parentDisposable); } @Override public void addFocusChangeListner(@NotNull FocusChangeListener listener, @NotNull Disposable parentDisposable) { myFocusChangeListenerMulticaster.addListener(listener,parentDisposable); } @TestOnly public Map<Class<? extends EventListener>, List<? extends EventListener>> getListeners() { Map<Class<? extends EventListener>, List<? extends EventListener>> myCopy = new LinkedHashMap<>(); myCopy.put(DocumentListener.class, new ArrayList<>(myDocumentMulticaster.getListeners())); myCopy.put(EditReadOnlyListener.class, new ArrayList<>(myEditReadOnlyMulticaster.getListeners())); myCopy.put(EditorMouseListener.class, new ArrayList<>(myEditorMouseMulticaster.getListeners())); myCopy.put(EditorMouseMotionListener.class, new ArrayList<>(myEditorMouseMotionMulticaster.getListeners())); myCopy.put(ErrorStripeListener.class, new ArrayList<>(myErrorStripeMulticaster.getListeners())); myCopy.put(CaretListener.class, new ArrayList<>(myCaretMulticaster.getListeners())); myCopy.put(SelectionListener.class, new ArrayList<>(mySelectionMulticaster.getListeners())); myCopy.put(VisibleAreaListener.class, new ArrayList<>(myVisibleAreaMulticaster.getListeners())); myCopy.put(PropertyChangeListener.class, new ArrayList<>(myPropertyChangeMulticaster.getListeners())); myCopy.put(FocusChangeListener.class, new ArrayList<>(myFocusChangeListenerMulticaster.getListeners())); return myCopy; } }
jk1/intellij-community
platform/platform-impl/src/com/intellij/openapi/editor/impl/event/EditorEventMulticasterImpl.java
Java
apache-2.0
8,310
/* * Copyright 2022 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {RestyleAttrs, RestyleComponent} from "jsx/mithril-component"; import m from "mithril"; import Stream from "mithril/stream"; import {Errors} from "models/mixins/errors"; import * as defaultStyles from "views/pages/pipelines/server_errors.scss"; type Styles = typeof defaultStyles; interface Attrs extends RestyleAttrs<Styles> { details: Stream<Errors>; message: Stream<string>; } export class ServerErrors extends RestyleComponent<Styles, Attrs> { css: Styles = defaultStyles; view(vnode: m.Vnode<Attrs>) { return <div class={this.css.errorResponse}> {this.message(vnode)} {this.details(vnode)} </div>; } message(vnode: m.Vnode<Attrs>) { const unmatched = vnode.attrs.details(); return <span> { (unmatched && unmatched.keys().length) ? vnode.attrs.message() + ": " : vnode.attrs.message() } </span>; } details(vnode: m.Vnode<Attrs>) { const unmatched = vnode.attrs.details(); if (unmatched && unmatched.keys().length) { return <ol> { unmatched.keys().map((key) => <li>{`${key}: ${unmatched.errorsForDisplay(key)}`}</li>) } </ol>; } } }
gocd/gocd
server/src/main/webapp/WEB-INF/rails/webpack/views/pages/pipelines/server_errors.tsx
TypeScript
apache-2.0
1,740
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.execution; import com.intellij.execution.configurations.ConfigurationFactory; import com.intellij.execution.configurations.ConfigurationType; import com.intellij.execution.configurations.RunConfiguration; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.Collection; import java.util.List; import java.util.Map; public abstract class RunManagerEx extends RunManager { public static RunManagerEx getInstanceEx(final Project project) { return (RunManagerEx)project.getComponent(RunManager.class); } //public abstract boolean isTemporary(@NotNull RunnerAndConfigurationSettings configuration); @Deprecated // use setSelectedConfiguration instead public void setActiveConfiguration(@Nullable RunnerAndConfigurationSettings configuration) { setSelectedConfiguration(configuration); } public abstract void setTemporaryConfiguration(@Nullable RunnerAndConfigurationSettings tempConfiguration); public abstract RunManagerConfig getConfig(); /** * @deprecated use {@link RunManager#createRunConfiguration(String, com.intellij.execution.configurations.ConfigurationFactory)} instead * @param name * @param type * @return */ @NotNull public abstract RunnerAndConfigurationSettings createConfiguration(String name, ConfigurationFactory type); public abstract void addConfiguration(RunnerAndConfigurationSettings settings, boolean isShared, List<BeforeRunTask> tasks, boolean addTemplateTasksIfAbsent); public abstract boolean isConfigurationShared(RunnerAndConfigurationSettings settings); @NotNull public abstract List<BeforeRunTask> getBeforeRunTasks(RunConfiguration settings); public abstract void setBeforeRunTasks(RunConfiguration runConfiguration, List<BeforeRunTask> tasks, boolean addEnabledTemplateTasksIfAbsent); @NotNull public abstract <T extends BeforeRunTask> List<T> getBeforeRunTasks(RunConfiguration settings, Key<T> taskProviderID); @NotNull public abstract <T extends BeforeRunTask> List<T> getBeforeRunTasks(Key<T> taskProviderID); public abstract RunnerAndConfigurationSettings findConfigurationByName(@Nullable final String name); public abstract Icon getConfigurationIcon(@NotNull RunnerAndConfigurationSettings settings); @NotNull public abstract Collection<RunnerAndConfigurationSettings> getSortedConfigurations(); public abstract void removeConfiguration(@Nullable RunnerAndConfigurationSettings settings); public abstract void addRunManagerListener(RunManagerListener listener); public abstract void removeRunManagerListener(RunManagerListener listener); @NotNull public abstract Map<String, List<RunnerAndConfigurationSettings>> getStructure(@NotNull ConfigurationType type); public static void disableTasks(Project project, RunConfiguration settings, Key<? extends BeforeRunTask>... keys) { for (Key<? extends BeforeRunTask> key : keys) { List<? extends BeforeRunTask> tasks = getInstanceEx(project).getBeforeRunTasks(settings, key); for (BeforeRunTask task : tasks) { task.setEnabled(false); } } } public static int getTasksCount(Project project, RunConfiguration settings, Key<? extends BeforeRunTask>... keys) { int result = 0; for (Key<? extends BeforeRunTask> key : keys) { result += getInstanceEx(project).getBeforeRunTasks(settings, key).size(); } return result; } }
ernestp/consulo
platform/lang-impl/src/com/intellij/execution/RunManagerEx.java
Java
apache-2.0
4,258
//// [tests/cases/compiler/importHelpersNoModule.ts] //// //// [external.ts] export class A { } export class B extends A { } declare var dec: any; @dec class C { method(@dec x: number) { } } //// [script.ts] class A { } class B extends A { } declare var dec: any; @dec class C { method(@dec x: number) { } } //// [external.js] "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var A = (function () { function A() { } return A; }()); exports.A = A; var B = (function (_super) { tslib_1.__extends(B, _super); function B() { return _super !== null && _super.apply(this, arguments) || this; } return B; }(A)); exports.B = B; var C = (function () { function C() { } C.prototype.method = function (x) { }; tslib_1.__decorate([ tslib_1.__param(0, dec), tslib_1.__metadata("design:type", Function), tslib_1.__metadata("design:paramtypes", [Number]), tslib_1.__metadata("design:returntype", void 0) ], C.prototype, "method", null); C = tslib_1.__decorate([ dec ], C); return C; }()); //// [script.js] var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; var A = (function () { function A() { } return A; }()); var B = (function (_super) { __extends(B, _super); function B() { return _super !== null && _super.apply(this, arguments) || this; } return B; }(A)); var C = (function () { function C() { } C.prototype.method = function (x) { }; __decorate([ __param(0, dec), __metadata("design:type", Function), __metadata("design:paramtypes", [Number]), __metadata("design:returntype", void 0) ], C.prototype, "method", null); C = __decorate([ dec ], C); return C; }());
mihailik/TypeScript
tests/baselines/reference/importHelpersNoModule.js
JavaScript
apache-2.0
3,297
/** * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "{}" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright {yyyy} {name of copyright owner} * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.deleidos.rtws.webapp.ingestapi.model; import java.util.Map; /** * This class provides the application layer information pertaining to * configuring an ingest parser service. */ public class ParserService extends Service { /** * Constructor. * * @param fqn * the fully qualified service class name * @param description * about the service * @param inputParams * the input params * @param systemParameters * the system parameters */ public ParserService(String fqn, String description, Map<String, Map<String, String>> inputParams, Map<String, Map<String, String>> systemParameters) { super(fqn, description, inputParams, systemParameters); } }
deleidos/digitaledge-platform
webapp-ingestapi/src/main/java/com/deleidos/rtws/webapp/ingestapi/model/ParserService.java
Java
apache-2.0
12,676
/* * Copyright 2002-2019 Drew Noakes and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * More information about this project is available at: * * https://drewnoakes.com/code/exif/ * https://github.com/drewnoakes/metadata-extractor */ package com.drew.metadata.mp4.media; import com.drew.lang.annotations.NotNull; import java.util.HashMap; public class Mp4SoundDirectory extends Mp4MediaDirectory { // Sound Sample Description Atom public static final int TAG_AUDIO_FORMAT = 301; public static final int TAG_NUMBER_OF_CHANNELS = 302; public static final int TAG_AUDIO_SAMPLE_SIZE = 303; public static final int TAG_AUDIO_SAMPLE_RATE = 304; public static final int TAG_SOUND_BALANCE = 305; public Mp4SoundDirectory() { this.setDescriptor(new Mp4SoundDescriptor(this)); } @NotNull private static final HashMap<Integer, String> _tagNameMap = new HashMap<Integer, String>(); static { Mp4MediaDirectory.addMp4MediaTags(_tagNameMap); _tagNameMap.put(TAG_AUDIO_FORMAT, "Format"); _tagNameMap.put(TAG_NUMBER_OF_CHANNELS, "Number of Channels"); _tagNameMap.put(TAG_AUDIO_SAMPLE_SIZE, "Sample Size"); _tagNameMap.put(TAG_AUDIO_SAMPLE_RATE, "Sample Rate"); _tagNameMap.put(TAG_SOUND_BALANCE, "Balance"); } @Override @NotNull public String getName() { return "MP4 Sound"; } @Override @NotNull protected HashMap<Integer, String> getTagNameMap() { return _tagNameMap; } }
drewnoakes/metadata-extractor
Source/com/drew/metadata/mp4/media/Mp4SoundDirectory.java
Java
apache-2.0
2,219
// Copyright (c) 2017 Uber Technologies, 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. import { ApiError } from './api-error'; export type TraceArchive = { isLoading?: boolean; isArchived?: boolean; isError?: boolean; error?: ApiError; isAcknowledged?: boolean; }; export type TracesArchive = Record<string, TraceArchive>;
teamsaas/meq
ui/src/plugins/built-in/panel/jaeger-panel/TraceView/JaegerComponents/types/archive.tsx
TypeScript
apache-2.0
849
/* * Copyright 2014-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.android; import static org.junit.Assert.assertEquals; import com.facebook.buck.android.AndroidBuildConfig.ReadValuesStep; import com.facebook.buck.io.ProjectFilesystem; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.model.BuildTargetFactory; import com.facebook.buck.rules.BuildRuleParams; import com.facebook.buck.rules.BuildRuleResolver; import com.facebook.buck.rules.FakeBuildContext; import com.facebook.buck.rules.FakeBuildRuleParamsBuilder; import com.facebook.buck.rules.FakeBuildableContext; import com.facebook.buck.rules.SourcePath; import com.facebook.buck.rules.SourcePathResolver; import com.facebook.buck.rules.coercer.BuildConfigFields; import com.facebook.buck.step.ExecutionContext; import com.facebook.buck.step.Step; import com.facebook.buck.step.TestExecutionContext; import com.facebook.buck.util.BuckConstant; import com.google.common.base.Optional; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableList; import org.easymock.EasyMock; import org.junit.Test; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; /** * Unit test for {@link AndroidBuildConfig}. */ public class AndroidBuildConfigTest { @Test public void testGetPathToOutput() { AndroidBuildConfig buildConfig = createSimpleBuildConfigRule(); assertEquals( BuckConstant.GEN_PATH.resolve("java/com/example/__build_config__/BuildConfig.java"), buildConfig.getPathToOutput()); } @Test public void testBuildInternal() throws IOException { AndroidBuildConfig buildConfig = createSimpleBuildConfigRule(); List<Step> steps = buildConfig.getBuildSteps( FakeBuildContext.NOOP_CONTEXT, new FakeBuildableContext()); Step generateBuildConfigStep = steps.get(1); GenerateBuildConfigStep expectedStep = new GenerateBuildConfigStep( /* source */ BuildTargetFactory.newInstance("//java/com/example:build_config"), /* javaPackage */ "com.example", /* useConstantExpressions */ false, /* constants */ Suppliers.ofInstance(BuildConfigFields.empty()), BuckConstant.GEN_PATH.resolve("java/com/example/__build_config__/BuildConfig.java")); assertEquals(expectedStep, generateBuildConfigStep); } @Test public void testGetTypeMethodOfBuilder() { assertEquals("android_build_config", AndroidBuildConfigDescription.TYPE.getName()); } @Test @SuppressWarnings("PMD.UseAssertTrueInsteadOfAssertEquals") // PMD has a bad heuristic here. public void testReadValuesStep() throws IOException { Path pathToValues = Paths.get("src/values.txt"); ProjectFilesystem projectFilesystem = EasyMock.createMock(ProjectFilesystem.class); EasyMock.expect(projectFilesystem.readLines(pathToValues)).andReturn( ImmutableList.of("boolean DEBUG = false", "String FOO = \"BAR\"")); EasyMock.replay(projectFilesystem); ReadValuesStep step = new ReadValuesStep(projectFilesystem, pathToValues); ExecutionContext context = TestExecutionContext .newBuilder() .setProjectFilesystem(projectFilesystem) .build(); int exitCode = step.execute(context); assertEquals(0, exitCode); assertEquals( BuildConfigFields.fromFields(ImmutableList.of( BuildConfigFields.Field.of("boolean", "DEBUG", "false"), BuildConfigFields.Field.of("String", "FOO", "\"BAR\""))), step.get()); EasyMock.verify(projectFilesystem); } private static AndroidBuildConfig createSimpleBuildConfigRule() { // First, create the BuildConfig object. BuildTarget buildTarget = BuildTarget.builder("//java/com/example", "build_config").build(); BuildRuleParams params = new FakeBuildRuleParamsBuilder(buildTarget).build(); return new AndroidBuildConfig( params, new SourcePathResolver(new BuildRuleResolver()), /* javaPackage */ "com.example", /* values */ BuildConfigFields.empty(), /* valuesFile */ Optional.<SourcePath>absent(), /* useConstantExpressions */ false); } // TODO(nickpalmer): Add another unit test that passes in a non-trivial DependencyGraph and verify // that the resulting set of libraryManifestPaths is computed correctly. }
neonichu/buck
test/com/facebook/buck/android/AndroidBuildConfigTest.java
Java
apache-2.0
4,898
package com.hubspot.singularity.scheduler; import com.hubspot.mesos.Resources; import com.hubspot.singularity.SingularityTaskCurrentUsage; import com.hubspot.singularity.SingularityTaskId; class TaskIdWithUsage { private final SingularityTaskId taskId; private final Resources requestedResources; private final SingularityTaskCurrentUsage usage; TaskIdWithUsage( SingularityTaskId taskId, Resources requestedResources, SingularityTaskCurrentUsage usage ) { this.taskId = taskId; this.requestedResources = requestedResources; this.usage = usage; } public SingularityTaskId getTaskId() { return taskId; } public Resources getRequestedResources() { return requestedResources; } public SingularityTaskCurrentUsage getUsage() { return usage; } }
hs-jenkins-bot/Singularity
SingularityService/src/main/java/com/hubspot/singularity/scheduler/TaskIdWithUsage.java
Java
apache-2.0
807
/* * Copyright 2013-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cloudfoundry.reactor.uaa.identityzones; import org.cloudfoundry.reactor.InteractionContext; import org.cloudfoundry.reactor.TestRequest; import org.cloudfoundry.reactor.TestResponse; import org.cloudfoundry.reactor.uaa.AbstractUaaApiTest; import org.cloudfoundry.uaa.identityzones.Branding; import org.cloudfoundry.uaa.identityzones.ClientLockoutPolicy; import org.cloudfoundry.uaa.identityzones.CorsConfiguration; import org.cloudfoundry.uaa.identityzones.CorsPolicy; import org.cloudfoundry.uaa.identityzones.CreateIdentityZoneRequest; import org.cloudfoundry.uaa.identityzones.CreateIdentityZoneResponse; import org.cloudfoundry.uaa.identityzones.DeleteIdentityZoneRequest; import org.cloudfoundry.uaa.identityzones.DeleteIdentityZoneResponse; import org.cloudfoundry.uaa.identityzones.GetIdentityZoneRequest; import org.cloudfoundry.uaa.identityzones.GetIdentityZoneResponse; import org.cloudfoundry.uaa.identityzones.IdentityZone; import org.cloudfoundry.uaa.identityzones.IdentityZoneConfiguration; import org.cloudfoundry.uaa.identityzones.Links; import org.cloudfoundry.uaa.identityzones.ListIdentityZonesRequest; import org.cloudfoundry.uaa.identityzones.ListIdentityZonesResponse; import org.cloudfoundry.uaa.identityzones.LogoutLink; import org.cloudfoundry.uaa.identityzones.Prompt; import org.cloudfoundry.uaa.identityzones.SamlConfiguration; import org.cloudfoundry.uaa.identityzones.SelfServiceLink; import org.cloudfoundry.uaa.identityzones.TokenPolicy; import org.cloudfoundry.uaa.identityzones.UpdateIdentityZoneRequest; import org.cloudfoundry.uaa.identityzones.UpdateIdentityZoneResponse; import org.junit.Test; import reactor.test.StepVerifier; import java.time.Duration; import java.util.Collections; import static io.netty.handler.codec.http.HttpMethod.DELETE; import static io.netty.handler.codec.http.HttpMethod.GET; import static io.netty.handler.codec.http.HttpMethod.POST; import static io.netty.handler.codec.http.HttpMethod.PUT; import static io.netty.handler.codec.http.HttpResponseStatus.CREATED; import static io.netty.handler.codec.http.HttpResponseStatus.OK; public final class ReactorIdentityZonesTest extends AbstractUaaApiTest { private final ReactorIdentityZones identityZones = new ReactorIdentityZones(CONNECTION_CONTEXT, this.root, TOKEN_PROVIDER); @Test public void create() { mockRequest(InteractionContext.builder() .request(TestRequest.builder() .method(POST).path("/identity-zones") .payload("fixtures/uaa/identity-zones/POST_request.json") .build()) .response(TestResponse.builder() .status(CREATED) .payload("fixtures/uaa/identity-zones/POST_response.json") .build()) .build()); this.identityZones .create(CreateIdentityZoneRequest.builder() .identityZoneId("twiglet-create") .subdomain("twiglet-create") .configuration(IdentityZoneConfiguration.builder() .clientLockoutPolicy(ClientLockoutPolicy.builder() .lockoutPeriodSeconds(300) .lockoutAfterFailures(5) .countFailuresWithin(3600) .build()) .tokenPolicy(TokenPolicy.builder() .accessTokenValidity(-1) .refreshTokenValidity(-1) .jwtRevocable(false) .key("exampleKeyId", Collections.singletonMap("signingKey", "s1gNiNg.K3y/t3XT")) .build()) .samlConfiguration(SamlConfiguration.builder() .assertionSigned(true) .requestSigned(true) .wantAssertionSigned(true) .wantPartnerAuthenticationRequestSigned(false) .assertionTimeToLive(600) .build()) .corsPolicy(CorsPolicy.builder() .xhrConfiguration(CorsConfiguration.builder() .allowedOrigin(".*") .allowedUri(".*") .allowedHeader("Accept") .allowedHeader("Authorization") .allowedHeader("Content-Type") .allowedMethod("GET") .allowedCredentials(false) .maxAge(1728000L) .build()) .defaultConfiguration(CorsConfiguration.builder() .allowedOrigin(".*") .allowedUri(".*") .allowedHeader("Accept") .allowedHeader("Authorization") .allowedHeader("Content-Type") .allowedMethod("GET") .allowedCredentials(false) .maxAge(1728000L) .build()) .build()) .links(Links.builder() .logout(LogoutLink.builder() .redirectUrl("/login") .redirectParameterName("redirect") .disableRedirectParameter(true) .build()) .homeRedirect("http://my.hosted.homepage.com/") .selfService(SelfServiceLink.builder() .selfServiceLinksEnabled(true) .signupLink("/create_account") .resetPasswordLink("/forgot_password") .build()) .build()) .prompt(Prompt.builder() .fieldName("username") .fieldType("text") .text("Email") .build()) .prompt(Prompt.builder() .fieldName("password") .fieldType("password") .text("Password") .build()) .prompt(Prompt.builder() .fieldName("passcode") .fieldType("password") .text("One Time Code (Get on at /passcode)") .build()) .ldapDiscoveryEnabled(false) .branding(Branding.builder() .companyName("Test Company") .productLogo("VGVzdFByb2R1Y3RMb2dv") .squareLogo("VGVzdFNxdWFyZUxvZ28=") .footerLegalText("Test footer legal text") .footerLink("Support", "http://support.example.com") .build()) .accountChooserEnabled(false) .build()) .name("The Twiglet Zone") .version(0) .description("Like the Twilight Zone but tastier.") .createdAt(1481728057524L) .lastModified(1481728057524L) .build()) .as(StepVerifier::create) .expectNext(CreateIdentityZoneResponse.builder() .id("twiglet-create") .subdomain("twiglet-create") .configuration(IdentityZoneConfiguration.builder() .clientLockoutPolicy(ClientLockoutPolicy.builder() .lockoutPeriodSeconds(300) .lockoutAfterFailures(5) .countFailuresWithin(3600) .build()) .tokenPolicy(TokenPolicy.builder() .accessTokenValidity(-1) .refreshTokenValidity(-1) .jwtRevocable(false) .key("exampleKeyId", Collections.singletonMap("signingKey", "s1gNiNg.K3y/t3XT")) .build()) .samlConfiguration(SamlConfiguration.builder() .assertionSigned(true) .requestSigned(true) .wantAssertionSigned(true) .wantPartnerAuthenticationRequestSigned(false) .assertionTimeToLive(600) .build()) .corsPolicy(CorsPolicy.builder() .xhrConfiguration(CorsConfiguration.builder() .allowedOrigin(".*") .allowedUri(".*") .allowedHeader("Accept") .allowedHeader("Authorization") .allowedHeader("Content-Type") .allowedMethod("GET") .allowedCredentials(false) .maxAge(1728000L) .build()) .defaultConfiguration(CorsConfiguration.builder() .allowedOrigin(".*") .allowedUri(".*") .allowedHeader("Accept") .allowedHeader("Authorization") .allowedHeader("Content-Type") .allowedMethod("GET") .allowedCredentials(false) .maxAge(1728000L) .build()) .build()) .links(Links.builder() .logout(LogoutLink.builder() .redirectUrl("/login") .redirectParameterName("redirect") .disableRedirectParameter(true) .build()) .homeRedirect("http://my.hosted.homepage.com/") .selfService(SelfServiceLink.builder() .selfServiceLinksEnabled(true) .signupLink("/create_account") .resetPasswordLink("/forgot_password") .build()) .build()) .prompt(Prompt.builder() .fieldName("username") .fieldType("text") .text("Email") .build()) .prompt(Prompt.builder() .fieldName("password") .fieldType("password") .text("Password") .build()) .prompt(Prompt.builder() .fieldName("passcode") .fieldType("password") .text("One Time Code (Get on at /passcode)") .build()) .ldapDiscoveryEnabled(false) .branding(Branding.builder() .companyName("Test Company") .productLogo("VGVzdFByb2R1Y3RMb2dv") .squareLogo("VGVzdFNxdWFyZUxvZ28=") .footerLegalText("Test footer legal text") .footerLink("Support", "http://support.example.com") .build()) .accountChooserEnabled(false) .build()) .name("The Twiglet Zone") .version(0) .description("Like the Twilight Zone but tastier.") .createdAt(1481728057533L) .lastModified(1481728057533L) .build()) .expectComplete() .verify(Duration.ofSeconds(5)); } @Test public void delete() { mockRequest(InteractionContext.builder() .request(TestRequest.builder() .method(DELETE).path("/identity-zones/twiglet-delete") .build()) .response(TestResponse.builder() .status(OK) .payload("fixtures/uaa/identity-zones/DELETE_{id}_response.json") .build()) .build()); this.identityZones .delete(DeleteIdentityZoneRequest.builder() .identityZoneId("twiglet-delete") .build()) .as(StepVerifier::create) .expectNext(DeleteIdentityZoneResponse.builder() .id("twiglet-delete") .subdomain("twiglet-delete") .configuration(IdentityZoneConfiguration.builder() .clientLockoutPolicy(ClientLockoutPolicy.builder() .lockoutPeriodSeconds(-1) .lockoutAfterFailures(-1) .countFailuresWithin(-1) .build()) .tokenPolicy(TokenPolicy.builder() .accessTokenValidity(-1) .refreshTokenValidity(-1) .jwtRevocable(false) .keys(Collections.emptyMap()) .build()) .samlConfiguration(SamlConfiguration.builder() .assertionSigned(true) .requestSigned(true) .wantAssertionSigned(true) .wantPartnerAuthenticationRequestSigned(false) .assertionTimeToLive(600) .build()) .corsPolicy(CorsPolicy.builder() .xhrConfiguration(CorsConfiguration.builder() .allowedOrigin(".*") .allowedUri(".*") .allowedHeader("Accept") .allowedHeader("Authorization") .allowedHeader("Content-Type") .allowedMethod("GET") .allowedCredentials(false) .maxAge(1728000L) .build()) .defaultConfiguration(CorsConfiguration.builder() .allowedOrigin(".*") .allowedUri(".*") .allowedHeader("Accept") .allowedHeader("Authorization") .allowedHeader("Content-Type") .allowedMethod("GET") .allowedCredentials(false) .maxAge(1728000L) .build()) .build()) .links(Links.builder() .logout(LogoutLink.builder() .redirectUrl("/login") .redirectParameterName("redirect") .disableRedirectParameter(true) .build()) .homeRedirect("http://my.hosted.homepage.com/") .selfService(SelfServiceLink.builder() .selfServiceLinksEnabled(true) .signupLink("/create_account") .resetPasswordLink("/forgot_password") .build()) .build()) .prompt(Prompt.builder() .fieldName("username") .fieldType("text") .text("Email") .build()) .prompt(Prompt.builder() .fieldName("password") .fieldType("password") .text("Password") .build()) .prompt(Prompt.builder() .fieldName("passcode") .fieldType("password") .text("One Time Code (Get on at /passcode)") .build()) .ldapDiscoveryEnabled(false) .branding(Branding.builder() .companyName("Test Company") .productLogo("VGVzdFByb2R1Y3RMb2dv") .squareLogo("VGVzdFNxdWFyZUxvZ28=") .footerLegalText("Test footer legal text") .footerLink("Support", "http://support.example.com") .build()) .accountChooserEnabled(false) .build()) .name("The Twiglet Zone") .version(0) .createdAt(1481728057024L) .lastModified(1481728057024L) .build()) .expectComplete() .verify(Duration.ofSeconds(5)); } @Test public void get() { mockRequest(InteractionContext.builder() .request(TestRequest.builder() .method(GET).path("/identity-zones/twiglet-get") .build()) .response(TestResponse.builder() .status(OK) .payload("fixtures/uaa/identity-zones/GET_{id}_response.json") .build()) .build()); this.identityZones .get(GetIdentityZoneRequest.builder() .identityZoneId("twiglet-get") .build()) .as(StepVerifier::create) .expectNext(GetIdentityZoneResponse.builder() .id("twiglet-get") .subdomain("twiglet-get") .configuration(IdentityZoneConfiguration.builder() .clientLockoutPolicy(ClientLockoutPolicy.builder() .lockoutPeriodSeconds(-1) .lockoutAfterFailures(-1) .countFailuresWithin(-1) .build()) .tokenPolicy(TokenPolicy.builder() .accessTokenValidity(-1) .refreshTokenValidity(-1) .jwtRevocable(false) .keys(Collections.emptyMap()) .build()) .samlConfiguration(SamlConfiguration.builder() .assertionSigned(true) .requestSigned(true) .wantAssertionSigned(true) .wantPartnerAuthenticationRequestSigned(false) .assertionTimeToLive(600) .build()) .corsPolicy(CorsPolicy.builder() .xhrConfiguration(CorsConfiguration.builder() .allowedOrigin(".*") .allowedUri(".*") .allowedHeader("Accept") .allowedHeader("Authorization") .allowedHeader("Content-Type") .allowedMethod("GET") .allowedCredentials(false) .maxAge(1728000L) .build()) .defaultConfiguration(CorsConfiguration.builder() .allowedOrigin(".*") .allowedUri(".*") .allowedHeader("Accept") .allowedHeader("Authorization") .allowedHeader("Content-Type") .allowedMethod("GET") .allowedCredentials(false) .maxAge(1728000L) .build()) .build()) .links(Links.builder() .logout(LogoutLink.builder() .redirectUrl("/login") .redirectParameterName("redirect") .disableRedirectParameter(true) .build()) .homeRedirect("http://my.hosted.homepage.com/") .selfService(SelfServiceLink.builder() .selfServiceLinksEnabled(true) .signupLink("/create_account") .resetPasswordLink("/forgot_password") .build()) .build()) .prompt(Prompt.builder() .fieldName("username") .fieldType("text") .text("Email") .build()) .prompt(Prompt.builder() .fieldName("password") .fieldType("password") .text("Password") .build()) .prompt(Prompt.builder() .fieldName("passcode") .fieldType("password") .text("One Time Code (Get on at /passcode)") .build()) .ldapDiscoveryEnabled(false) .branding(Branding.builder() .companyName("Test Company") .productLogo("VGVzdFByb2R1Y3RMb2dv") .squareLogo("VGVzdFNxdWFyZUxvZ28=") .footerLegalText("Test footer legal text") .footerLink("Support", "http://support.example.com") .build()) .accountChooserEnabled(false) .build()) .name("The Twiglet Zone") .version(0) .createdAt(1481728057382L) .lastModified(1481728057382L) .build()) .expectComplete() .verify(Duration.ofSeconds(5)); } @Test public void list() { mockRequest(InteractionContext.builder() .request(TestRequest.builder() .method(GET).path("/identity-zones") .build()) .response(TestResponse.builder() .status(OK) .payload("fixtures/uaa/identity-zones/GET_response.json") .build()) .build()); this.identityZones .list(ListIdentityZonesRequest.builder() .build()) .as(StepVerifier::create) .expectNext(ListIdentityZonesResponse.builder() .identityZone(IdentityZone.builder() .id("15wtczzd") .subdomain("15wtczzd") .configuration(IdentityZoneConfiguration.builder() .clientLockoutPolicy(ClientLockoutPolicy.builder() .lockoutPeriodSeconds(-1) .lockoutAfterFailures(-1) .countFailuresWithin(-1) .build()) .tokenPolicy(TokenPolicy.builder() .accessTokenValidity(-1) .refreshTokenValidity(-1) .jwtRevocable(false) .keys(Collections.emptyMap()) .build()) .samlConfiguration(SamlConfiguration.builder() .assertionSigned(true) .requestSigned(true) .wantAssertionSigned(true) .wantPartnerAuthenticationRequestSigned(false) .assertionTimeToLive(600) .build()) .corsPolicy(CorsPolicy.builder() .xhrConfiguration(CorsConfiguration.builder() .allowedOrigin(".*") .allowedUri(".*") .allowedHeader("Accept") .allowedHeader("Authorization") .allowedHeader("Content-Type") .allowedMethod("GET") .allowedCredentials(false) .maxAge(1728000L) .build()) .defaultConfiguration(CorsConfiguration.builder() .allowedOrigin(".*") .allowedUri(".*") .allowedHeader("Accept") .allowedHeader("Authorization") .allowedHeader("Content-Type") .allowedMethod("GET") .allowedCredentials(false) .maxAge(1728000L) .build()) .build()) .links(Links.builder() .logout(LogoutLink.builder() .redirectUrl("/login") .redirectParameterName("redirect") .disableRedirectParameter(true) .build()) .selfService(SelfServiceLink.builder() .selfServiceLinksEnabled(true) .signupLink("/create_account") .resetPasswordLink("/forgot_password") .build()) .build()) .prompt(Prompt.builder() .fieldName("username") .fieldType("text") .text("Email") .build()) .prompt(Prompt.builder() .fieldName("password") .fieldType("password") .text("Password") .build()) .prompt(Prompt.builder() .fieldName("passcode") .fieldType("password") .text("One Time Code (Get on at /passcode)") .build()) .ldapDiscoveryEnabled(false) .accountChooserEnabled(false) .build()) .name("The Twiglet Zone") .version(0) .description("Like the Twilight Zone but tastier.") .createdAt(1481728053399L) .lastModified(1481728053399L) .build()) .build()) .expectComplete() .verify(Duration.ofSeconds(5)); } @Test public void update() { mockRequest(InteractionContext.builder() .request(TestRequest.builder() .method(PUT).path("/identity-zones/twiglet-update") .payload("fixtures/uaa/identity-zones/PUT_{id}_request.json") .build()) .response(TestResponse.builder() .status(OK) .payload("fixtures/uaa/identity-zones/PUT_{id}_response.json") .build()) .build()); this.identityZones .update(UpdateIdentityZoneRequest.builder() .identityZoneId("twiglet-update") .subdomain("twiglet-update") .configuration(IdentityZoneConfiguration.builder() .clientLockoutPolicy(ClientLockoutPolicy.builder() .lockoutPeriodSeconds(-1) .lockoutAfterFailures(-1) .countFailuresWithin(-1) .build()) .tokenPolicy(TokenPolicy.builder() .accessTokenValidity(-1) .refreshTokenValidity(-1) .jwtRevocable(false) .key("updatedKeyId", Collections.singletonMap("signingKey", "upD4t3d.s1gNiNg.K3y/t3XT")) .build()) .samlConfiguration(SamlConfiguration.builder() .assertionSigned(true) .requestSigned(true) .wantAssertionSigned(true) .wantPartnerAuthenticationRequestSigned(false) .assertionTimeToLive(600) .build()) .corsPolicy(CorsPolicy.builder() .xhrConfiguration(CorsConfiguration.builder() .allowedOrigin(".*") .allowedUri(".*") .allowedHeader("Accept") .allowedHeader("Authorization") .allowedHeader("Content-Type") .allowedMethod("GET") .allowedCredentials(false) .maxAge(1728000L) .build()) .defaultConfiguration(CorsConfiguration.builder() .allowedOrigin(".*") .allowedUri(".*") .allowedHeader("Accept") .allowedHeader("Authorization") .allowedHeader("Content-Type") .allowedMethod("GET") .allowedCredentials(false) .maxAge(1728000L) .build()) .build()) .links(Links.builder() .logout(LogoutLink.builder() .redirectUrl("/login") .redirectParameterName("redirect") .disableRedirectParameter(true) .build()) .homeRedirect("http://my.hosted.homepage.com/") .selfService(SelfServiceLink.builder() .selfServiceLinksEnabled(true) .signupLink("/create_account") .resetPasswordLink("/forgot_password") .build()) .build()) .prompt(Prompt.builder() .fieldName("username") .fieldType("text") .text("Email") .build()) .prompt(Prompt.builder() .fieldName("password") .fieldType("password") .text("Password") .build()) .prompt(Prompt.builder() .fieldName("passcode") .fieldType("password") .text("One Time Code (Get on at /passcode)") .build()) .ldapDiscoveryEnabled(false) .branding(Branding.builder() .companyName("Test Company") .productLogo("VGVzdFByb2R1Y3RMb2dv") .squareLogo("VGVzdFNxdWFyZUxvZ28=") .footerLegalText("Test footer legal text") .footerLink("Support", "http://support.example.com") .build()) .accountChooserEnabled(false) .build()) .name("The Updated Twiglet Zone") .version(0) .description("Like the Twilight Zone but not tastier.") .createdAt(1481728057246L) .lastModified(1481728057246L) .build()) .as(StepVerifier::create) .expectNext(UpdateIdentityZoneResponse.builder() .id("twiglet-update") .subdomain("twiglet-update") .configuration(IdentityZoneConfiguration.builder() .clientLockoutPolicy(ClientLockoutPolicy.builder() .lockoutPeriodSeconds(-1) .lockoutAfterFailures(-1) .countFailuresWithin(-1) .build()) .tokenPolicy(TokenPolicy.builder() .accessTokenValidity(-1) .refreshTokenValidity(-1) .jwtRevocable(false) .key("updatedKeyId", Collections.singletonMap("signingKey", "upD4t3d.s1gNiNg.K3y/t3XT")) .build()) .samlConfiguration(SamlConfiguration.builder() .assertionSigned(true) .requestSigned(true) .wantAssertionSigned(true) .wantPartnerAuthenticationRequestSigned(false) .assertionTimeToLive(600) .build()) .corsPolicy(CorsPolicy.builder() .xhrConfiguration(CorsConfiguration.builder() .allowedOrigin(".*") .allowedUri(".*") .allowedHeader("Accept") .allowedHeader("Authorization") .allowedHeader("Content-Type") .allowedMethod("GET") .allowedCredentials(false) .maxAge(1728000L) .build()) .defaultConfiguration(CorsConfiguration.builder() .allowedOrigin(".*") .allowedUri(".*") .allowedHeader("Accept") .allowedHeader("Authorization") .allowedHeader("Content-Type") .allowedMethod("GET") .allowedCredentials(false) .maxAge(1728000L) .build()) .build()) .links(Links.builder() .logout(LogoutLink.builder() .redirectUrl("/login") .redirectParameterName("redirect") .disableRedirectParameter(true) .build()) .homeRedirect("http://my.hosted.homepage.com/") .selfService(SelfServiceLink.builder() .selfServiceLinksEnabled(true) .signupLink("/create_account") .resetPasswordLink("/forgot_password") .build()) .build()) .prompt(Prompt.builder() .fieldName("username") .fieldType("text") .text("Email") .build()) .prompt(Prompt.builder() .fieldName("password") .fieldType("password") .text("Password") .build()) .prompt(Prompt.builder() .fieldName("passcode") .fieldType("password") .text("One Time Code (Get on at /passcode)") .build()) .ldapDiscoveryEnabled(false) .branding(Branding.builder() .companyName("Test Company") .productLogo("VGVzdFByb2R1Y3RMb2dv") .squareLogo("VGVzdFNxdWFyZUxvZ28=") .footerLegalText("Test footer legal text") .footerLink("Support", "http://support.example.com") .build()) .accountChooserEnabled(false) .build()) .name("The Updated Twiglet Zone") .version(1) .description("Like the Twilight Zone but not tastier.") .createdAt(1481728057213L) .lastModified(1481728057259L) .build()) .expectComplete() .verify(Duration.ofSeconds(5)); } }
orange-cloudfoundry/cf-java-client
cloudfoundry-client-reactor/src/test/java/org/cloudfoundry/reactor/uaa/identityzones/ReactorIdentityZonesTest.java
Java
apache-2.0
37,125
/* * 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.ignite.internal.processors.platform.services; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteException; import org.apache.ignite.IgniteServices; import org.apache.ignite.internal.binary.BinaryRawReaderEx; import org.apache.ignite.internal.binary.BinaryRawWriterEx; import org.apache.ignite.internal.processors.platform.PlatformAbstractTarget; import org.apache.ignite.internal.processors.platform.PlatformContext; import org.apache.ignite.internal.processors.platform.PlatformTarget; import org.apache.ignite.internal.processors.platform.cluster.PlatformClusterNodeFilterImpl; import org.apache.ignite.internal.processors.platform.dotnet.PlatformDotNetService; import org.apache.ignite.internal.processors.platform.dotnet.PlatformDotNetServiceImpl; import org.apache.ignite.internal.processors.platform.utils.PlatformFutureUtils; import org.apache.ignite.internal.processors.platform.utils.PlatformUtils; import org.apache.ignite.internal.processors.platform.utils.PlatformWriterBiClosure; import org.apache.ignite.internal.processors.platform.utils.PlatformWriterClosure; import org.apache.ignite.internal.processors.service.GridServiceProxy; import org.apache.ignite.internal.util.typedef.T3; import org.apache.ignite.lang.IgniteFuture; import org.apache.ignite.lang.IgnitePredicate; import org.apache.ignite.services.Service; import org.apache.ignite.services.ServiceConfiguration; import org.apache.ignite.services.ServiceDeploymentException; import org.apache.ignite.services.ServiceDescriptor; import org.jetbrains.annotations.NotNull; /** * Interop services. */ public class PlatformServices extends PlatformAbstractTarget { /** */ private static final int OP_DOTNET_DEPLOY = 1; /** */ private static final int OP_DOTNET_DEPLOY_MULTIPLE = 2; /** */ private static final int OP_DOTNET_SERVICES = 3; /** */ private static final int OP_INVOKE = 4; /** */ private static final int OP_DESCRIPTORS = 5; /** */ private static final int OP_WITH_ASYNC = 6; /** */ private static final int OP_WITH_SERVER_KEEP_BINARY = 7; /** */ private static final int OP_SERVICE_PROXY = 8; /** */ private static final int OP_CANCEL = 9; /** */ private static final int OP_CANCEL_ALL = 10; /** */ private static final int OP_DOTNET_DEPLOY_ASYNC = 11; /** */ private static final int OP_DOTNET_DEPLOY_MULTIPLE_ASYNC = 12; /** */ private static final int OP_CANCEL_ASYNC = 13; /** */ private static final int OP_CANCEL_ALL_ASYNC = 14; /** */ private static final int OP_DOTNET_DEPLOY_ALL = 15; /** */ private static final int OP_DOTNET_DEPLOY_ALL_ASYNC = 16; /** */ private static final byte PLATFORM_JAVA = 0; /** */ private static final byte PLATFORM_DOTNET = 1; /** */ private static final CopyOnWriteConcurrentMap<T3<Class, String, Integer>, Method> SVC_METHODS = new CopyOnWriteConcurrentMap<>(); /** Future result writer. */ private static final PlatformFutureUtils.Writer RESULT_WRITER = new ServiceDeploymentResultWriter(); /** */ private final IgniteServices services; /** Server keep binary flag. */ private final boolean srvKeepBinary; /** * Ctor. * * @param platformCtx Context. * @param services Services facade. * @param srvKeepBinary Server keep binary flag. */ public PlatformServices(PlatformContext platformCtx, IgniteServices services, boolean srvKeepBinary) { super(platformCtx); assert services != null; this.services = services; this.srvKeepBinary = srvKeepBinary; } /** * Finds a service descriptor by name. * * @param name Service name. * @return Descriptor or null. */ private ServiceDescriptor findDescriptor(String name) { for (ServiceDescriptor d : services.serviceDescriptors()) if (d.name().equals(name)) return d; return null; } /** {@inheritDoc} */ @Override public long processInStreamOutLong(int type, BinaryRawReaderEx reader) throws IgniteCheckedException { switch (type) { case OP_DOTNET_DEPLOY_ASYNC: { readAndListenFuture(reader, dotnetDeployAsync(reader, services), RESULT_WRITER); return TRUE; } case OP_DOTNET_DEPLOY_MULTIPLE_ASYNC: { readAndListenFuture(reader, dotnetDeployMultipleAsync(reader), RESULT_WRITER); return TRUE; } case OP_CANCEL: { services.cancel(reader.readString()); return TRUE; } case OP_CANCEL_ASYNC: { readAndListenFuture(reader, services.cancelAsync(reader.readString())); return TRUE; } case OP_CANCEL_ALL_ASYNC: { readAndListenFuture(reader, services.cancelAllAsync()); return TRUE; } case OP_DOTNET_DEPLOY_ALL_ASYNC: { readAndListenFuture(reader, dotnetDeployAllAsync(reader, services), RESULT_WRITER); return TRUE; } default: return super.processInStreamOutLong(type, reader); } } /** {@inheritDoc} */ @Override public void processInStreamOutStream(int type, BinaryRawReaderEx reader, BinaryRawWriterEx writer) throws IgniteCheckedException { switch (type) { case OP_DOTNET_SERVICES: { Collection<Service> svcs = services.services(reader.readString()); PlatformUtils.writeNullableCollection(writer, svcs, new PlatformWriterClosure<Service>() { @Override public void write(BinaryRawWriterEx writer, Service svc) { writer.writeLong(((PlatformService) svc).pointer()); } }, new IgnitePredicate<Service>() { @Override public boolean apply(Service svc) { return svc instanceof PlatformDotNetService; } } ); return; } case OP_DOTNET_DEPLOY: { try { dotnetDeploy(reader, services); writeDeploymentResult(writer, null); } catch (Exception e) { writeDeploymentResult(writer, e); } return; } case OP_DOTNET_DEPLOY_MULTIPLE: { try { dotnetDeployMultiple(reader); writeDeploymentResult(writer, null); } catch (Exception e) { writeDeploymentResult(writer, e); } return; } case OP_DOTNET_DEPLOY_ALL: { try { dotnetDeployAll(reader, services); writeDeploymentResult(writer, null); } catch (Exception e) { writeDeploymentResult(writer, e); } return; } default: super.processInStreamOutStream(type, reader, writer); } } /** {@inheritDoc} */ @Override public PlatformTarget processInObjectStreamOutObjectStream(int type, PlatformTarget arg, BinaryRawReaderEx reader, BinaryRawWriterEx writer) throws IgniteCheckedException { switch (type) { case OP_INVOKE: { assert arg != null; assert arg instanceof ServiceProxyHolder; ServiceProxyHolder svc = (ServiceProxyHolder)arg; String mthdName = reader.readString(); Object[] args; if (reader.readBoolean()) { args = new Object[reader.readInt()]; for (int i = 0; i < args.length; i++) args[i] = reader.readObjectDetached(!srvKeepBinary && !svc.isPlatformService()); } else args = null; try { Object result = svc.invoke(mthdName, srvKeepBinary, args); PlatformUtils.writeInvocationResult(writer, result, null); } catch (Throwable e) { PlatformUtils.writeInvocationResult(writer, null, e); } return null; } } return super.processInObjectStreamOutObjectStream(type, arg, reader, writer); } /** {@inheritDoc} */ @Override public void processOutStream(int type, BinaryRawWriterEx writer) throws IgniteCheckedException { switch (type) { case OP_DESCRIPTORS: { Collection<ServiceDescriptor> descs = services.serviceDescriptors(); PlatformUtils.writeCollection(writer, descs, new PlatformWriterClosure<ServiceDescriptor>() { @Override public void write(BinaryRawWriterEx writer, ServiceDescriptor d) { writer.writeString(d.name()); writer.writeString(d.cacheName()); writer.writeInt(d.maxPerNodeCount()); writer.writeInt(d.totalCount()); writer.writeUuid(d.originNodeId()); writer.writeObject(d.affinityKey()); // Write platform. There are only 2 platforms now. byte platform = d.serviceClass().equals(PlatformDotNetServiceImpl.class) ? PLATFORM_DOTNET : PLATFORM_JAVA; writer.writeByte(platform); Map<UUID, Integer> top = d.topologySnapshot(); PlatformUtils.writeMap(writer, top, new PlatformWriterBiClosure<UUID, Integer>() { @Override public void write(BinaryRawWriterEx writer, UUID key, Integer val) { writer.writeUuid(key); writer.writeInt(val); } }); } }); return; } default: super.processOutStream(type, writer); } } /** {@inheritDoc} */ @Override public PlatformTarget processOutObject(int type) throws IgniteCheckedException { switch (type) { case OP_WITH_ASYNC: if (services.isAsync()) return this; return new PlatformServices(platformCtx, services.withAsync(), srvKeepBinary); case OP_WITH_SERVER_KEEP_BINARY: return srvKeepBinary ? this : new PlatformServices(platformCtx, services, true); } return super.processOutObject(type); } /** {@inheritDoc} */ @Override public long processInLongOutLong(int type, long val) throws IgniteCheckedException { switch (type) { case OP_CANCEL_ALL: services.cancelAll(); return TRUE; } return super.processInLongOutLong(type, val); } /** {@inheritDoc} */ @Override public PlatformTarget processInStreamOutObject(int type, BinaryRawReaderEx reader) throws IgniteCheckedException { switch (type) { case OP_SERVICE_PROXY: { String name = reader.readString(); boolean sticky = reader.readBoolean(); ServiceDescriptor d = findDescriptor(name); if (d == null) throw new IgniteException("Failed to find deployed service: " + name); Object proxy = PlatformService.class.isAssignableFrom(d.serviceClass()) ? services.serviceProxy(name, PlatformService.class, sticky) : new GridServiceProxy<>(services.clusterGroup(), name, Service.class, sticky, 0, platformCtx.kernalContext()); return new ServiceProxyHolder(proxy, d.serviceClass(), platformContext()); } } return super.processInStreamOutObject(type, reader); } /** * Deploys multiple dotnet services. * * @param reader Binary reader. */ private void dotnetDeployMultiple(BinaryRawReaderEx reader) { String name = reader.readString(); Object svc = reader.readObjectDetached(); int totalCnt = reader.readInt(); int maxPerNodeCnt = reader.readInt(); services.deployMultiple(name, new PlatformDotNetServiceImpl(svc, platformCtx, srvKeepBinary), totalCnt, maxPerNodeCnt); } /** * Asynchronously deploys multiple dotnet services. * * @param reader Binary reader. * @return Future of the operation. */ private IgniteFuture<Void> dotnetDeployMultipleAsync(BinaryRawReaderEx reader) { String name = reader.readString(); Object svc = reader.readObjectDetached(); int totalCnt = reader.readInt(); int maxPerNodeCnt = reader.readInt(); return services.deployMultipleAsync(name, new PlatformDotNetServiceImpl(svc, platformCtx, srvKeepBinary), totalCnt, maxPerNodeCnt); } /** * Deploys dotnet service. * * @param reader Binary reader. * @param services Services. */ private void dotnetDeploy(BinaryRawReaderEx reader, IgniteServices services) { ServiceConfiguration cfg = dotnetConfiguration(reader); services.deploy(cfg); } /** * Deploys dotnet service asynchronously. * * @param reader Binary reader. * @param services Services. * @return Future of the operation. */ private IgniteFuture<Void> dotnetDeployAsync(BinaryRawReaderEx reader, IgniteServices services) { ServiceConfiguration cfg = dotnetConfiguration(reader); return services.deployAsync(cfg); } /** * Deploys a collection of dotnet services. * * @param reader Binary reader. * @param services Services. */ private void dotnetDeployAll(BinaryRawReaderEx reader, IgniteServices services) { Collection<ServiceConfiguration> cfgs = dotnetConfigurations(reader); services.deployAll(cfgs); } /** * Deploys a collection of dotnet services asynchronously. * * @param reader Binary reader. * @param services Services. * @return Future of the operation. */ private IgniteFuture<Void> dotnetDeployAllAsync(BinaryRawReaderEx reader, IgniteServices services) { Collection<ServiceConfiguration> cfgs = dotnetConfigurations(reader); return services.deployAllAsync(cfgs); } /** * Read the dotnet service configuration. * * @param reader Binary reader, * @return Service configuration. */ @NotNull private ServiceConfiguration dotnetConfiguration(BinaryRawReaderEx reader) { ServiceConfiguration cfg = new ServiceConfiguration(); cfg.setName(reader.readString()); cfg.setService(new PlatformDotNetServiceImpl(reader.readObjectDetached(), platformCtx, srvKeepBinary)); cfg.setTotalCount(reader.readInt()); cfg.setMaxPerNodeCount(reader.readInt()); cfg.setCacheName(reader.readString()); cfg.setAffinityKey(reader.readObjectDetached()); Object filter = reader.readObjectDetached(); if (filter != null) cfg.setNodeFilter(platformCtx.createClusterNodeFilter(filter)); return cfg; } /** * Reads the collection of dotnet service configurations. * * @param reader Binary reader, * @return Service configuration. */ @NotNull private Collection<ServiceConfiguration> dotnetConfigurations(BinaryRawReaderEx reader) { int numServices = reader.readInt(); List<ServiceConfiguration> cfgs = new ArrayList<>(numServices); for (int i = 0; i < numServices; i++) { cfgs.add(dotnetConfiguration(reader)); } return cfgs; } /** * Finds a suitable method in a class. * * @param clazz Class. * @param mthdName Name. * @param args Args. * @return Method. * @throws NoSuchMethodException On error. */ public static Method getMethod(Class<?> clazz, String mthdName, Object[] args) throws NoSuchMethodException { return ServiceProxyHolder.getMethod(clazz, mthdName, args); } /** * Convert Object[] to T[] when required: * Ignite loses array item types when passing arguments through GridServiceProxy. * * @param args Service method args. * @param mtd Target method. */ public static void convertArrayArgs(Object[] args, Method mtd) { for (int i = 0; i < args.length; i++) { Object arg = args[i]; if (arg instanceof Object[]) { Class<?> parameterType = mtd.getParameterTypes()[i]; if (parameterType.isArray() && parameterType != Object[].class) { Object[] arr = (Object[])arg; Object newArg = Array.newInstance(parameterType.getComponentType(), arr.length); for (int j = 0; j < arr.length; j++) Array.set(newArg, j, arr[j]); args[i] = newArg; } } } } /** * Proxy holder. */ @SuppressWarnings({"unchecked", "rawtypes"}) private static class ServiceProxyHolder extends PlatformAbstractTarget { /** */ private final Object proxy; /** */ private final Class serviceClass; /** */ private static final Map<Class<?>, Class<?>> PRIMITIVES_TO_WRAPPERS = new HashMap<>(); /* Class initializer. */ static { PRIMITIVES_TO_WRAPPERS.put(boolean.class, Boolean.class); PRIMITIVES_TO_WRAPPERS.put(byte.class, Byte.class); PRIMITIVES_TO_WRAPPERS.put(char.class, Character.class); PRIMITIVES_TO_WRAPPERS.put(double.class, Double.class); PRIMITIVES_TO_WRAPPERS.put(float.class, Float.class); PRIMITIVES_TO_WRAPPERS.put(int.class, Integer.class); PRIMITIVES_TO_WRAPPERS.put(long.class, Long.class); PRIMITIVES_TO_WRAPPERS.put(short.class, Short.class); } /** * Ctor. * * @param proxy Proxy object. * @param clazz Proxy class. * @param ctx Platform context. */ private ServiceProxyHolder(Object proxy, Class clazz, PlatformContext ctx) { super(ctx); assert proxy != null; assert clazz != null; this.proxy = proxy; serviceClass = clazz; } /** * Invokes the proxy. * * @param mthdName Method name. * @param srvKeepBinary Binary flag. * @param args Args. * @return Invocation result. * @throws IgniteCheckedException On error. * @throws NoSuchMethodException On error. */ public Object invoke(String mthdName, boolean srvKeepBinary, Object[] args) throws Throwable { if (isPlatformService()) return ((PlatformService)proxy).invokeMethod(mthdName, srvKeepBinary, args); else { assert proxy instanceof GridServiceProxy; // Deserialize arguments for Java service when not in binary mode if (!srvKeepBinary) args = PlatformUtils.unwrapBinariesInArray(args); Method mtd = getMethod(serviceClass, mthdName, args); convertArrayArgs(args, mtd); return ((GridServiceProxy)proxy).invokeMethod(mtd, args); } } /** * Finds a suitable method in a class * * @param clazz Class. * @param mthdName Name. * @param args Args. * @return Method. * @throws NoSuchMethodException On error. */ private static Method getMethod(Class clazz, String mthdName, Object[] args) throws NoSuchMethodException { assert clazz != null; assert mthdName != null; assert args != null; T3<Class, String, Integer> cacheKey = new T3<>(clazz, mthdName, args.length); Method res = SVC_METHODS.get(cacheKey); if (res != null) return res; Method[] allMethods = clazz.getMethods(); List<Method> methods = new ArrayList<>(allMethods.length); // Filter by name and param count for (Method m : allMethods) if (m.getName().equals(mthdName) && m.getParameterTypes().length == args.length) methods.add(m); if (methods.size() == 1) { res = methods.get(0); // Update cache only when there is a single method with a given name and arg count. SVC_METHODS.put(cacheKey, res); return res; } if (methods.isEmpty()) throw new NoSuchMethodException("Could not find proxy method '" + mthdName + "' in class " + clazz); // Filter by param types for (int i = 0; i < methods.size(); i++) if (!areMethodArgsCompatible(methods.get(i).getParameterTypes(), args)) methods.remove(i--); if (methods.size() == 1) return methods.get(0); if (methods.isEmpty()) throw new NoSuchMethodException("Could not find proxy method '" + mthdName + "' in class " + clazz); throw new NoSuchMethodException("Ambiguous proxy method '" + mthdName + "' in class " + clazz); } /** * Determines whether specified method arguments are compatible with given method parameter definitions. * * @param argTypes Method arg types. * @param args Method args. * @return Whether specified args are compatible with argTypes. */ private static boolean areMethodArgsCompatible(Class[] argTypes, Object[] args) { for (int i = 0; i < args.length; i++) { // arg is always of a primitive wrapper class, and argTypes can have actual primitive Object arg = args[i]; Class argType = wrap(argTypes[i]); if (arg != null && !argType.isAssignableFrom(arg.getClass())) return false; } return true; } /** * Gets corresponding wrapper for a primitive type. * @param c Class to convert. * * @return Primitive wrapper, or the same class. */ private static Class wrap(Class c) { return c.isPrimitive() ? PRIMITIVES_TO_WRAPPERS.get(c) : c; } /** @return {@code True} if service is platform service. */ public boolean isPlatformService() { return proxy instanceof PlatformService; } } /** * Concurrent map. */ private static class CopyOnWriteConcurrentMap<K, V> { /** */ private volatile Map<K, V> map = new HashMap<>(); /** * Gets a value. * * @param key Key. * @return Value. */ public V get(K key) { return map.get(key); } /** * Puts a value. * * @param key Key. * @param val Value. */ public void put(K key, V val) { synchronized (this) { if (map.containsKey(key)) return; Map<K, V> map0 = new HashMap<>(map); map0.put(key, val); map = map0; } } } /** * Writes an EventBase. */ private static class ServiceDeploymentResultWriter implements PlatformFutureUtils.Writer { /** <inheritDoc /> */ @Override public void write(BinaryRawWriterEx writer, Object obj, Throwable err) { writeDeploymentResult(writer, err); } /** <inheritDoc /> */ @Override public boolean canWrite(Object obj, Throwable err) { return true; } } /** * Writes a service deployment result for dotnet code. * * @param writer Writer. * @param err Error. */ private static void writeDeploymentResult(BinaryRawWriterEx writer, Throwable err) { PlatformUtils.writeInvocationResult(writer, null, err); Collection<ServiceConfiguration> failedCfgs = null; if (err instanceof ServiceDeploymentException) failedCfgs = ((ServiceDeploymentException)err).getFailedConfigurations(); // write a collection of failed service configurations PlatformUtils.writeNullableCollection(writer, failedCfgs, new PlatformWriterClosure<ServiceConfiguration>() { @Override public void write(BinaryRawWriterEx writer, ServiceConfiguration svcCfg) { writeFailedConfiguration(writer, svcCfg); } }); } /** * Writes a failed service configuration for dotnet code. * * @param w Writer * @param svcCfg Service configuration */ private static void writeFailedConfiguration(BinaryRawWriterEx w, ServiceConfiguration svcCfg) { Object dotnetSvc = null; Object dotnetFilter = null; w.writeString(svcCfg.getName()); if (svcCfg.getService() instanceof PlatformDotNetServiceImpl) dotnetSvc = ((PlatformDotNetServiceImpl)svcCfg.getService()).getInternalService(); w.writeObjectDetached(dotnetSvc); w.writeInt(svcCfg.getTotalCount()); w.writeInt(svcCfg.getMaxPerNodeCount()); w.writeString(svcCfg.getCacheName()); w.writeObjectDetached(svcCfg.getAffinityKey()); if (svcCfg.getNodeFilter() instanceof PlatformClusterNodeFilterImpl) dotnetFilter = ((PlatformClusterNodeFilterImpl)svcCfg.getNodeFilter()).getInternalPredicate(); w.writeObjectDetached(dotnetFilter); } }
ascherbakoff/ignite
modules/core/src/main/java/org/apache/ignite/internal/processors/platform/services/PlatformServices.java
Java
apache-2.0
27,586
public class Date { private int month; private int day; private int year; private static final int[] daysPerMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; public Date (){ } public Date ( int theMonth, int theDay, int theYear ) { month = checkMonth ( theMonth ); year = theYear; day = checkDay ( theDay ); } private int checkMonth ( int testMonth ) { if ( testMonth > 0 && testMonth <= 12 ) { return testMonth; } else { throw new IllegalArgumentException ( "month must be 1-12" ); } } private int checkDay ( int testDay ) { if ( testDay > 0 && testDay <= daysPerMonth[ month ] ) { return testDay; } if ( month == 2 && testDay == 29 && (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) ) { return testDay; } throw new IllegalArgumentException ( "day out-of-range for the specified month and year" ); } public int getMonth ( ) { return month; } public void setMonth ( int month ) { this.month = month; } public int getDay ( ) { return day; } public void setDay ( int day ) { this.day = day; } public int getYear ( ) { return year; } public void setYear ( int year ) { this.year = year; } @Override public String toString ( ) { return String.format ( "%d/%d/%d", month, day, year ); } }
DexDevs/educate-for-oop
java/book-dietel/kinza/10_8_b_Date.java
Java
apache-2.0
1,526
/* * Copyright 2015 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.server.service; import com.thoughtworks.go.config.CaseInsensitiveString; import com.thoughtworks.go.config.CruiseConfig; import com.thoughtworks.go.config.PipelineConfig; import com.thoughtworks.go.config.TimerConfig; import com.thoughtworks.go.listener.PipelineConfigChangedListener; import com.thoughtworks.go.server.scheduling.BuildCauseProducerService; import com.thoughtworks.go.server.service.result.ServerHealthStateOperationResult; import com.thoughtworks.go.serverhealth.HealthStateScope; import com.thoughtworks.go.serverhealth.HealthStateType; import com.thoughtworks.go.serverhealth.ServerHealthService; import com.thoughtworks.go.serverhealth.ServerHealthState; import org.apache.log4j.Logger; import org.quartz.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import sun.reflect.generics.reflectiveObjects.NotImplementedException; import java.text.ParseException; import java.util.List; /** * @understands scheduling pipelines based on a timer */ @Component public class TimerScheduler implements PipelineConfigChangedListener { private static final Logger LOG = Logger.getLogger(TimerScheduler.class); private GoConfigService goConfigService; private BuildCauseProducerService buildCauseProducerService; private SchedulerFactory quartzSchedulerFactory; private ServerHealthService serverHealthService; private Scheduler quartzScheduler; protected static final String QUARTZ_GROUP = "CruiseTimers"; protected static final String BUILD_CAUSE_PRODUCER_SERVICE = "BuildCauseProducerService"; protected static final String PIPELINE_CONFIG = "PipelineConfig"; @Autowired public TimerScheduler(SchedulerFactory quartzSchedulerFactory, GoConfigService goConfigService, BuildCauseProducerService buildCauseProducerService, ServerHealthService serverHealthService) { this.goConfigService = goConfigService; this.buildCauseProducerService = buildCauseProducerService; this.quartzSchedulerFactory = quartzSchedulerFactory; this.serverHealthService = serverHealthService; } public void initialize() { try { quartzScheduler = quartzSchedulerFactory.getScheduler(); quartzScheduler.start(); scheduleAllJobs(goConfigService.getAllPipelineConfigs()); goConfigService.register(this); } catch (SchedulerException e) { showGlobalError("Failed to initialize timer", e); } } private void scheduleAllJobs(List<PipelineConfig> pipelineConfigs) { for (PipelineConfig pipelineConfig : pipelineConfigs) { scheduleJob(quartzScheduler, pipelineConfig); } } private void scheduleJob(Scheduler scheduler, PipelineConfig pipelineConfig) { TimerConfig timer = pipelineConfig.getTimer(); if (timer != null) { try { Trigger trigger = new CronTrigger(CaseInsensitiveString.str(pipelineConfig.name()), QUARTZ_GROUP, timer.getTimerSpec()); JobDetail jobDetail = new JobDetail(CaseInsensitiveString.str(pipelineConfig.name()), QUARTZ_GROUP, SchedulePipelineQuartzJob.class); jobDetail.setJobDataMap(jobDataMapFor(pipelineConfig)); scheduler.scheduleJob(jobDetail, trigger); LOG.info("Initialized timer for pipeline " + pipelineConfig.name() + " with " + timer.getTimerSpec()); } catch (ParseException e) { showPipelineError(pipelineConfig, e, "Bad timer specification for timer in Pipeline: " + pipelineConfig.name(), "Cannot schedule pipeline using the timer"); } catch (SchedulerException e) { showPipelineError(pipelineConfig, e, "Could not register pipeline '" + pipelineConfig.name() + "' with timer", ""); } } } private void showGlobalError(String msg, SchedulerException e) { LOG.error(msg, e); serverHealthService.update( ServerHealthState.error(msg, "Cannot schedule pipelines using the timer", HealthStateType.general(HealthStateScope.GLOBAL))); } private void showPipelineError(PipelineConfig pipelineConfig, Exception e, String msg, String description) { LOG.error(msg, e); serverHealthService.update( ServerHealthState.error(msg, description, HealthStateType.general(HealthStateScope.forPipeline(CaseInsensitiveString.str(pipelineConfig.name()))))); } private JobDataMap jobDataMapFor(PipelineConfig pipelineConfig) { JobDataMap map = new JobDataMap(); map.put(BUILD_CAUSE_PRODUCER_SERVICE, buildCauseProducerService); map.put(PIPELINE_CONFIG, pipelineConfig); return map; } public void onConfigChange(CruiseConfig newCruiseConfig) { unscheduleAllJobs(); scheduleAllJobs(newCruiseConfig.getAllPipelineConfigs()); } @Override public void onPipelineConfigChange(PipelineConfig pipelineConfig, String group) { unscheduleJob(CaseInsensitiveString.str(pipelineConfig.name())); scheduleJob(quartzScheduler, pipelineConfig); } private void unscheduleAllJobs() { try { String[] jobNames = quartzScheduler.getJobNames(QUARTZ_GROUP); for (String jobName : jobNames) { unscheduleJob(jobName); } } catch (SchedulerException e) { LOG.error("Could not unschedule quartz jobs", e); } } private void unscheduleJob(String jobName) { try { if (quartzScheduler.getJobDetail(jobName, QUARTZ_GROUP) != null) { quartzScheduler.unscheduleJob(jobName, QUARTZ_GROUP); quartzScheduler.deleteJob(jobName, QUARTZ_GROUP); } } catch (SchedulerException e) { LOG.error("Could not unschedule quartz jobs", e); } } public static class SchedulePipelineQuartzJob implements Job { public void execute(JobExecutionContext context) throws JobExecutionException { JobDataMap jobDataMap = context.getJobDetail().getJobDataMap(); BuildCauseProducerService buildCauseProducerService = (BuildCauseProducerService) jobDataMap.get(BUILD_CAUSE_PRODUCER_SERVICE); PipelineConfig pipelineConfig = (PipelineConfig) jobDataMap.get(PIPELINE_CONFIG); buildCauseProducerService.timerSchedulePipeline(pipelineConfig, new ServerHealthStateOperationResult()); } } }
xli/gocd
server/src/com/thoughtworks/go/server/service/TimerScheduler.java
Java
apache-2.0
7,349
/*! * ${copyright} */ // Provides the base implementation for all model implementations sap.ui.define(['jquery.sap.global', 'sap/ui/core/format/DateFormat', 'sap/ui/model/SimpleType', 'sap/ui/model/FormatException', 'sap/ui/model/ParseException', 'sap/ui/model/ValidateException'], function(jQuery, DateFormat, SimpleType, FormatException, ParseException, ValidateException) { "use strict"; /** * Constructor for a Date type. * * @class * This class represents date simple types. * * @extends sap.ui.model.SimpleType * * @author SAP SE * @version ${version} * * @public * @param {object} [oFormatOptions] Formatting options. For a list of all available options, see {@link sap.ui.core.format.DateFormat.getDateInstance DateFormat}. * @param {object} [oFormatOptions.source] Additional set of options used to create a second <code>DateFormat</code> object for conversions between * string values in the data source (e.g. model) and <code>Date</code>. This second format object is used to convert from a model <code>string</code> to <code>Date</code> before * converting the <code>Date</code> to <code>string</code> with the primary format object. Vice versa, this 'source' format is also used to format an already parsed * external value (e.g. user input) into the string format that is expected by the data source. * For a list of all available options, see {@link sap.ui.core.format.DateFormat.getDateInstance DateFormat}. * In case an empty object is given, the default is the ISO date notation (yyyy-MM-dd). * @param {object} [oConstraints] Value constraints * @param {Date|string} [oConstraints.minimum] Smallest value allowed for this type. Values for constraints must use the same type as configured via <code>oFormatOptions.source</code>. * @param {Date|string} [oConstraints.maximum] Largest value allowed for this type. Values for constraints must use the same type as configured via <code>oFormatOptions.source</code>. * @alias sap.ui.model.type.Date */ var Date1 = SimpleType.extend("sap.ui.model.type.Date", /** @lends sap.ui.model.type.Date.prototype */ { constructor : function () { SimpleType.apply(this, arguments); this.sName = "Date"; } }); Date1.prototype.formatValue = function(oValue, sInternalType) { var oFormat; switch (this.getPrimitiveType(sInternalType)) { case "string": case "any": if (oValue == null) { return ""; } if (this.oFormatOptions.source && this.oFormatOptions.source.pattern !== "timestamp" && oValue === "") { return ""; } oFormat = this.getModelFormat(); oValue = oFormat.parse(oValue); return this.oOutputFormat.format(oValue); default: throw new FormatException("Don't know how to format Date to " + sInternalType); } }; Date1.prototype.parseValue = function(oValue, sInternalType) { var oResult, oBundle; switch (this.getPrimitiveType(sInternalType)) { case "string": if (oValue === "") { return null; } var oResult = this.oOutputFormat.parse(oValue); if (!oResult) { oBundle = sap.ui.getCore().getLibraryResourceBundle(); throw new ParseException(oBundle.getText(this.sName + ".Invalid")); } if (this.oInputFormat) { if (this.oFormatOptions.source.pattern == "timestamp") { oResult = oResult.getTime(); } else { oResult = this.oInputFormat.format(oResult); } } return oResult; default: throw new ParseException("Don't know how to parse Date from " + sInternalType); } }; Date1.prototype.validateValue = function(oValue) { if (this.oConstraints) { var oBundle = sap.ui.getCore().getLibraryResourceBundle(), aViolatedConstraints = [], aMessages = [], oInputFormat = this.oInputFormat, that = this; // convert date into date object to compare if (oInputFormat && this.oFormatOptions.source.pattern != "timestamp") { oValue = oInputFormat.parse(oValue); } jQuery.each(this.oConstraints, function(sName, oContent) { if (oInputFormat) { oContent = oInputFormat.parse(oContent); } switch (sName) { case "minimum": if (oValue < oContent) { aViolatedConstraints.push("minimum"); aMessages.push(oBundle.getText(that.sName + ".Minimum", [oContent])); } break; case "maximum": if (oValue > oContent) { aViolatedConstraints.push("maximum"); aMessages.push(oBundle.getText(that.sName + ".Maximum", [oContent])); } } }); if (aViolatedConstraints.length > 0) { throw new ValidateException(aMessages.join(" "), aViolatedConstraints); } } }; var oTimestampInputFormat = { format: function(oValue) { if (oValue instanceof Date) { return oValue.getTime(); } return null; }, parse: function(oValue) { if (typeof (oValue) != "number") { if (isNaN(oValue)) { throw new FormatException("Cannot format date: " + oValue + " is not a valid Timestamp"); } else { oValue = parseInt(oValue, 10); } } oValue = new Date(oValue); return oValue; } }; Date1.prototype.getModelFormat = function() { if (this.oInputFormat) { if (this.oFormatOptions.source.pattern == "timestamp") { return oTimestampInputFormat; } else { return this.oInputFormat; } } else { return SimpleType.prototype.getModelFormat.call(this); } }; Date1.prototype.setFormatOptions = function(oFormatOptions) { this.oFormatOptions = oFormatOptions; this._createFormats(); }; /** * @protected */ Date1.prototype.getOutputPattern = function() { return this.oOutputFormat.oFormatOptions.pattern; }; /** * Called by the framework when any localization setting changed * @private */ Date1.prototype._handleLocalizationChange = function() { // recreate formatters this._createFormats(); }; /** * Create formatters used by this type * @private */ Date1.prototype._createFormats = function() { var oSourceOptions = this.oFormatOptions.source; this.oOutputFormat = DateFormat.getInstance(this.oFormatOptions); if (oSourceOptions) { if (jQuery.isEmptyObject(oSourceOptions)) { oSourceOptions = {pattern: "yyyy-MM-dd"}; } this.oInputFormat = DateFormat.getInstance(oSourceOptions); } }; return Date1; });
SQCLabs/openui5
src/sap.ui.core/src/sap/ui/model/type/Date.js
JavaScript
apache-2.0
6,346
program t implicit none C inquire stmt 'delim' specifier (quote) c and character variable in open stmt character*10::a character*5::write='quote' open (56, status='new', file='tmpfile', delim=write) inquire (56, delim=a) print *,a close (56,status='delete') endprogram t
thender/ppp
tests/t0317x/t.f
FORTRAN
apache-2.0
325
package eu.uqasar.web.dashboard.projectqualitygooglechart; /* * #%L * U-QASAR * %% * Copyright (C) 2012 - 2015 U-QASAR Consortium * %% * 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. * #L% */ public interface ProjectQualityGoogleChartFactory { public String createChart(ProjectQualityGoogleChartWidget widget); }
schlotze/u-qasar.platform
src/main/java/eu/uqasar/web/dashboard/projectqualitygooglechart/ProjectQualityGoogleChartFactory.java
Java
apache-2.0
840
module Coppertone # A helper class for finding SPF records for a domain. class RecordEvaluator attr_reader :record def initialize(record) @record = record end def evaluate(macro_context, request_context) result = directive_result(macro_context, request_context) return result unless result.none? || result.fail? if result.fail? evaluate_fail_result(result, macro_context, request_context) else # Evaluate redirect evaluate_none_result(result, macro_context, request_context) end end def directive_result(macro_context, request_context) record.directives.reduce(Result.none) do |memo, d| memo.none? ? d.evaluate(macro_context, request_context) : memo end end def evaluate_fail_result(result, macro_context, request_context) add_exp_to_result(result, macro_context, request_context) end def add_exp_to_result(result, macro_context, request_context) result = add_default_exp(result) return result unless record.exp computed_exp = record.exp.evaluate(macro_context, request_context) result.explanation = computed_exp if computed_exp result rescue Coppertone::Error result end def add_default_exp(result) result.explanation = Coppertone.config.default_explanation result end def follow_redirect? # Ignore the redirect if there's an all # mechanism in the record record.redirect && !record.include_all? end def evaluate_none_result(result, macro_context, request_context) return result unless follow_redirect? finder = Coppertone::RedirectRecordFinder.new(record.redirect, macro_context, request_context) raise InvalidRedirectError unless finder.target && finder.record rc = macro_context.with_domain(finder.target) RecordEvaluator.new(finder.record).evaluate(rc, request_context) end end end
petergoldstein/coppertone
lib/coppertone/record_evaluator.rb
Ruby
apache-2.0
2,012
/*************************************************************************************************/ /*! * \file * * \brief AES and random number security service implemented using HCI. * * Copyright (c) 2010-2018 Arm 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 <string.h> #include "wsf_types.h" #include "wsf_queue.h" #include "wsf_msg.h" #include "wsf_trace.h" #include "sec_api.h" #include "sec_main.h" #include "wsf_buf.h" #include "hci_api.h" #include "util/calc128.h" #include "util/wstr.h" enum { SEC_CMAC_STATE_SUBKEY, SEC_CMAC_STATE_BLOCK, SEC_CMAC_STATE_COMPLETE, }; /************************************************************************************************** External Variables **************************************************************************************************/ extern secCb_t secCb; /*************************************************************************************************/ /*! * \brief Continue the execution of the CMAC algorithm over the next message block. * * \param pBuf Security queue buffer containing CMAC algorithm control block. * * \return None. */ /*************************************************************************************************/ static void secCmacProcessBlock(secQueueBuf_t *pBuf) { secCmacSecCb_t *pCmac = (secCmacSecCb_t*) pBuf->pCb; uint8_t buf[SEC_BLOCK_LEN]; uint8_t *pMn = pCmac->pPlainText + pCmac->position; int8_t remaining = (int16_t) pCmac->len - pCmac->position; /* Check for Last Block */ if (remaining <= SEC_BLOCK_LEN) { WStrReverseCpy(buf, pMn, SEC_BLOCK_LEN); /* Pad the message if necessary */ if (remaining != SEC_BLOCK_LEN) { memset(buf, 0, SEC_BLOCK_LEN - remaining); buf[SEC_BLOCK_LEN-remaining-1] = 0x80; } /* XOr the subkey */ Calc128Xor(buf, pCmac->subkey); pCmac->state = SEC_CMAC_STATE_COMPLETE; } else { /* Copy the block to the buffer */ WStrReverseCpy(buf, pMn, SEC_BLOCK_LEN); } if (pCmac->position != 0) { /* Except for first block, XOr the previous AES calculation */ Calc128Xor(buf, pBuf->ciphertext); } pCmac->position += SEC_BLOCK_LEN; /* Enqueue and perform AES operation */ WsfMsgEnq(&secCb.queue, pCmac->handlerId, pBuf); HciLeEncryptCmd(pCmac->key, buf); } /*************************************************************************************************/ /*! * \brief Step 1 to generate the subkey used in the CMAC algorithm. * * \param pBuf Security queue buffer containing CMAC algorithm control block. * * \return None. */ /*************************************************************************************************/ static void secCmacGenSubkey1(secQueueBuf_t *pBuf) { secCmacSecCb_t *pCmac = (secCmacSecCb_t*) pBuf->pCb; uint8_t buf[SEC_BLOCK_LEN]; /* Perform aes on the key with a constant zero */ memset(buf, 0, SEC_BLOCK_LEN); WsfMsgEnq(&secCb.queue, pCmac->handlerId, pBuf); HciLeEncryptCmd(pCmac->key, buf); } /*************************************************************************************************/ /*! * \brief Left shift a buffer of WSF_CMAC_KEY_LEN bytes by N bits. * * \param pBuf Buffer to left shift. * \param shift Number of bits to shift. * * \return The overflow of the operaiton. */ /*************************************************************************************************/ static uint8_t secCmacKeyShift(uint8_t *pBuf, uint8_t shift) { uint8_t bits, i, prevBits = 0; for (i = 0; i < SEC_CMAC_KEY_LEN; i++) { /* store shifted bits for next byte */ bits = pBuf[i] >> (8 - shift); /* shift byte and OR in shifted bits from previous byte */ pBuf[i] = (pBuf[i] << shift) | prevBits; prevBits = bits; } return prevBits; } /*************************************************************************************************/ /*! * \brief Complete generation of the subkey used in the CMAC algorithm. * * \param pBuf Security queue buffer containing CMAC algorithm control block. * * \return None. */ /*************************************************************************************************/ static void secCmacGenSubkey2(secQueueBuf_t *pBuf) { secCmacSecCb_t *pCmac = (secCmacSecCb_t*) pBuf->pCb; uint8_t overflow; /* Copy the result of the AES oepration */ Calc128Cpy(pCmac->subkey, pBuf->ciphertext); /* Calculate the K1 subkey */ overflow = secCmacKeyShift(pCmac->subkey, 1); if (overflow) { pCmac->subkey[0] ^= SEC_CMAC_RB; } if (pCmac->len % SEC_BLOCK_LEN != 0) { /* If the message len is not a multiple of SEC_BLOCK_LEN */ /* Continue with generation of the K2 subkey based on the K1 key */ overflow = secCmacKeyShift(pCmac->subkey, 1); if (overflow) { pCmac->subkey[0] ^= SEC_CMAC_RB; } } /* Begin CMAC calculation */ pCmac->state = SEC_CMAC_STATE_BLOCK; secCmacProcessBlock(pBuf); } /*************************************************************************************************/ /*! * \brief Send a message to the handler with CMAC result. * * \param pBuf Security queue buffer containing CMAC algorithm control block. * * \return None. */ /*************************************************************************************************/ static void secCmacComplete(secQueueBuf_t *pBuf) { /* CMAC is complete, copy and send result to handler */ secCmacMsg_t *pMsg = (secCmacMsg_t *) &pBuf->msg; secCmacSecCb_t *pCmac = (secCmacSecCb_t*) pBuf->pCb; WStrReverse(pBuf->ciphertext, SEC_CMAC_KEY_LEN); pMsg->pCiphertext = pBuf->ciphertext; WsfBufFree(pCmac->pPlainText); WsfMsgSend(pCmac->handlerId, pMsg); } /*************************************************************************************************/ /*! * \brief Callback for HCI encryption for CMAC operations. * * \param pBuf Pointer to sec queue element. * \param pEvent Pointer to HCI event. * \param handlerId WSF handler ID. * * \return none. */ /*************************************************************************************************/ void SecCmacHciCback(secQueueBuf_t *pBuf, hciEvt_t *pEvent, wsfHandlerId_t handlerId) { secCmacSecCb_t *pCmac = (secCmacSecCb_t *) pBuf->pCb; if (pCmac) { Calc128Cpy(pBuf->ciphertext, pEvent->leEncryptCmdCmpl.data); switch (pCmac->state) { case SEC_CMAC_STATE_SUBKEY: secCmacGenSubkey2(pBuf); break; case SEC_CMAC_STATE_BLOCK: secCmacProcessBlock(pBuf); break; case SEC_CMAC_STATE_COMPLETE: secCmacComplete(pBuf); break; } } } /*************************************************************************************************/ /*! * \brief Execute the CMAC algorithm. * * \param pKey Key used in CMAC operation. * \param pPlainText Data to perform CMAC operation over * \param len Size of pPlaintext in bytes. * \param handlerId WSF handler ID for client. * \param param Optional parameter sent to client's WSF handler. * \param event Event for client's WSF handler. * * \return TRUE if successful, else FALSE. */ /*************************************************************************************************/ bool_t SecCmac(const uint8_t *pKey, uint8_t *pPlainText, uint8_t textLen, wsfHandlerId_t handlerId, uint16_t param, uint8_t event) { secQueueBuf_t *pBuf; uint16_t bufSize = sizeof(secQueueBuf_t) + sizeof(secCmacSecCb_t); if ((pBuf = WsfMsgAlloc(bufSize)) != NULL) { secCmacSecCb_t *pCmacCb = (secCmacSecCb_t *) (pBuf + 1); /* Setup queue buffer */ pBuf->pCb = pCmacCb; pBuf->type = SEC_TYPE_CMAC; pBuf->msg.hdr.status = secCb.token++; pBuf->msg.hdr.param = param; pBuf->msg.hdr.event = event; pCmacCb->pPlainText = pPlainText; pCmacCb->len = textLen; pCmacCb->position = 0; pCmacCb->handlerId = handlerId; pCmacCb->state = SEC_CMAC_STATE_SUBKEY; /* Copy key */ WStrReverseCpy(pCmacCb->key, pKey, SEC_CMAC_KEY_LEN); /* Start the CMAC process by calculating the subkey */ secCmacGenSubkey1(pBuf); return TRUE; } return FALSE; } /*************************************************************************************************/ /*! * \brief Called to initialize CMAC security. * * \param None. * * \return None. */ /*************************************************************************************************/ void SecCmacInit() { secCb.hciCbackTbl[SEC_TYPE_CMAC] = SecCmacHciCback; }
betzw/mbed-os
features/FEATURE_BLE/targets/TARGET_CORDIO/stack/cordio_stack/ble-host/sources/sec/common/sec_cmac.c
C
apache-2.0
9,270
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.client.block.stream; import alluxio.client.file.FileSystemContext; import alluxio.client.file.options.OutStreamOptions; import alluxio.exception.status.ResourceExhaustedException; import alluxio.grpc.RequestType; import alluxio.wire.WorkerNetAddress; import io.netty.buffer.ByteBuf; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import javax.annotation.concurrent.NotThreadSafe; /** * A data writer that writes to local first and fallback to UFS block writes when the block * storage on this local worker is full. */ @NotThreadSafe public final class UfsFallbackLocalFileDataWriter implements DataWriter { private static final Logger LOG = LoggerFactory.getLogger(UfsFallbackLocalFileDataWriter.class); private final DataWriter mLocalFileDataWriter; private final FileSystemContext mContext; private final WorkerNetAddress mWorkerNetAddress; private final long mBlockSize; private final long mBlockId; private final OutStreamOptions mOutStreamOptions; private GrpcDataWriter mGrpcDataWriter; private boolean mIsWritingToLocal; /** * @param context the file system context * @param address the worker network address * @param blockId the block ID * @param blockSize the block size * @param options the output stream options * @return the {@link UfsFallbackLocalFileDataWriter} instance created */ public static UfsFallbackLocalFileDataWriter create(FileSystemContext context, WorkerNetAddress address, long blockId, long blockSize, OutStreamOptions options) throws IOException { try { LocalFileDataWriter localFilePacketWriter = LocalFileDataWriter.create(context, address, blockId, blockSize, options); return new UfsFallbackLocalFileDataWriter(localFilePacketWriter, null, context, address, blockId, blockSize, options); } catch (ResourceExhaustedException e) { LOG.warn("Fallback to create new block {} in UFS due to a failure of insufficient space on " + "the local worker: {}", blockId, e.getMessage()); } // Failed to create the local writer due to insufficient space, fallback to gRPC data writer // directly GrpcDataWriter grpcDataWriter = GrpcDataWriter .create(context, address, blockId, blockSize, RequestType.UFS_FALLBACK_BLOCK, options); return new UfsFallbackLocalFileDataWriter(null, grpcDataWriter, context, address, blockId, blockSize, options); } UfsFallbackLocalFileDataWriter(DataWriter localFileDataWriter, GrpcDataWriter grpcDataWriter, FileSystemContext context, final WorkerNetAddress address, long blockId, long blockSize, OutStreamOptions options) { mLocalFileDataWriter = localFileDataWriter; mGrpcDataWriter = grpcDataWriter; mBlockId = blockId; mContext = context; mWorkerNetAddress = address; mBlockSize = blockSize; mOutStreamOptions = options; mIsWritingToLocal = mLocalFileDataWriter != null; } @Override public void writeChunk(ByteBuf chunk) throws IOException { if (mIsWritingToLocal) { long pos = mLocalFileDataWriter.pos(); try { // chunk.refcount++ to ensure chunk not garbage-collected if writeChunk fails chunk.retain(); // chunk.refcount-- inside regardless of exception mLocalFileDataWriter.writeChunk(chunk); // chunk.refcount-- on success chunk.release(); return; } catch (ResourceExhaustedException e) { LOG.warn("Fallback to write to UFS for block {} due to a failure of insufficient space " + "on the local worker: {}", mBlockId, e.getMessage()); mIsWritingToLocal = false; } try { if (pos == 0) { // Nothing has been written to temp block, we can cancel this failed local writer and // cleanup the temp block. mLocalFileDataWriter.cancel(); } else { // Note that, we can not cancel mLocalFileDataWriter now as the cancel message may // arrive and clean the temp block before it is written to UFS. mLocalFileDataWriter.flush(); } // Close the block writer. We do not close the mLocalFileDataWriter to prevent the worker // completes the block, commit it and remove it. //mLocalFileDataWriter.getWriter().close(); mGrpcDataWriter = GrpcDataWriter .create(mContext, mWorkerNetAddress, mBlockId, mBlockSize, RequestType.UFS_FALLBACK_BLOCK, mOutStreamOptions); // Instruct the server to write the previously transferred data from temp block to UFS only // when there is data already written. if (pos > 0) { mGrpcDataWriter.writeFallbackInitRequest(pos); } } catch (Exception e) { // chunk.refcount-- on exception chunk.release(); throw new IOException("Failed to switch to writing block " + mBlockId + " to UFS", e); } } mGrpcDataWriter.writeChunk(chunk); // refcount-- inside to release chunk } @Override public void flush() throws IOException { if (mIsWritingToLocal) { mLocalFileDataWriter.flush(); } else { mGrpcDataWriter.flush(); } } @Override public int chunkSize() { if (mIsWritingToLocal) { return mLocalFileDataWriter.chunkSize(); } else { return mGrpcDataWriter.chunkSize(); } } @Override public long pos() { if (mIsWritingToLocal) { return mLocalFileDataWriter.pos(); } else { return mGrpcDataWriter.pos(); } } @Override public void cancel() throws IOException { if (mIsWritingToLocal) { mLocalFileDataWriter.cancel(); } else { // Clean up the state of previous temp block left over if (mLocalFileDataWriter != null) { mLocalFileDataWriter.cancel(); } mGrpcDataWriter.cancel(); } } @Override public void close() throws IOException { if (mIsWritingToLocal) { mLocalFileDataWriter.close(); } else { // Clean up the state of previous temp block left over if (mLocalFileDataWriter != null) { mLocalFileDataWriter.cancel(); } mGrpcDataWriter.close(); } } }
bf8086/alluxio
core/client/fs/src/main/java/alluxio/client/block/stream/UfsFallbackLocalFileDataWriter.java
Java
apache-2.0
6,756
/* * Copyright 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.qrcode; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.Writer; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import com.google.zxing.qrcode.encoder.ByteMatrix; import com.google.zxing.qrcode.encoder.Encoder; import com.google.zxing.qrcode.encoder.QRCode; import java.util.Map; /** * This object renders a QR Code as a BitMatrix 2D array of greyscale values. * * @author dswitkin@google.com (Daniel Switkin) */ public final class QRCodeWriter implements Writer { private static final int QUIET_ZONE_SIZE = 4; // Note that the input matrix uses 0 == white, 1 == black, while the output matrix uses // 0 == black, 255 == white (i.e. an 8 bit greyscale bitmap). private static BitMatrix renderResult(QRCode code, int width, int height, int quietZone) { ByteMatrix input = code.getMatrix(); if (input == null) { throw new IllegalStateException(); } int inputWidth = input.getWidth(); int inputHeight = input.getHeight(); int qrWidth = inputWidth + (quietZone * 2); int qrHeight = inputHeight + (quietZone * 2); int outputWidth = Math.max(width, qrWidth); int outputHeight = Math.max(height, qrHeight); int multiple = Math.min(outputWidth / qrWidth, outputHeight / qrHeight); // Padding includes both the quiet zone and the extra white pixels to accommodate the requested // dimensions. For example, if input is 25x25 the QR will be 33x33 including the quiet zone. // If the requested size is 200x160, the multiple will be 4, for a QR of 132x132. These will // handle all the padding from 100x100 (the actual QR) up to 200x160. int leftPadding = (outputWidth - (inputWidth * multiple)) / 2; int topPadding = (outputHeight - (inputHeight * multiple)) / 2; BitMatrix output = new BitMatrix(outputWidth, outputHeight); for (int inputY = 0, outputY = topPadding; inputY < inputHeight; inputY++, outputY += multiple) { // Write the contents of this row of the barcode for (int inputX = 0, outputX = leftPadding; inputX < inputWidth; inputX++, outputX += multiple) { if (input.get(inputX, inputY) == 1) { output.setRegion(outputX, outputY, multiple, multiple); } } } return output; } @Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height) throws WriterException { return encode(contents, format, width, height, null); } @Override public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType, ?> hints) throws WriterException { if (contents.isEmpty()) { throw new IllegalArgumentException("Found empty contents"); } if (format != BarcodeFormat.QR_CODE) { throw new IllegalArgumentException("Can only encode QR_CODE, but got " + format); } if (width < 0 || height < 0) { throw new IllegalArgumentException("Requested dimensions are too small: " + width + 'x' + height); } ErrorCorrectionLevel errorCorrectionLevel = ErrorCorrectionLevel.L; int quietZone = QUIET_ZONE_SIZE; if (hints != null) { ErrorCorrectionLevel requestedECLevel = (ErrorCorrectionLevel) hints.get(EncodeHintType.ERROR_CORRECTION); if (requestedECLevel != null) { errorCorrectionLevel = requestedECLevel; } Integer quietZoneInt = (Integer) hints.get(EncodeHintType.MARGIN); if (quietZoneInt != null) { quietZone = quietZoneInt; } } QRCode code = Encoder.encode(contents, errorCorrectionLevel, hints); return renderResult(code, width, height, quietZone); } }
ben-upsilon/exp-aqr
src/com/google/zxing/qrcode/QRCodeWriter.java
Java
apache-2.0
4,790
# frozen_string_literal: true class CreateLeaveApplications < ActiveRecord::Migration[5.0] def change create_table :leave_applications do |t| t.integer :user_id t.string :leave_type t.integer :hours, default: 0 t.datetime :start_time t.datetime :end_time t.text :description, null: true t.string :status, default: 'pending' t.datetime :sign_date, null: true t.datetime :deleted_at, null: true t.timestamps end add_reference :leave_applications, :manager, index: true end end
5xRuby/daikichi
db/migrate/20160714090133_create_leave_applications.rb
Ruby
apache-2.0
553
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.inject.spi; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.common.truth.Truth.assertThat; import static com.google.inject.Asserts.assertContains; import static com.google.inject.Asserts.assertEqualsBothWays; import static com.google.inject.Asserts.assertNotSerializable; import static com.google.inject.name.Names.named; import static org.junit.Assert.assertThrows; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.inject.ConfigurationException; import com.google.inject.Inject; import com.google.inject.Key; import com.google.inject.Provider; import com.google.inject.TypeLiteral; import com.google.inject.internal.ErrorsException; import com.google.inject.name.Named; import com.google.inject.spi.InjectionPoint.Signature; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import junit.framework.TestCase; /** @author jessewilson@google.com (Jesse Wilson) */ public class InjectionPointTest extends TestCase { public @Inject @Named("a") String foo; public @Inject void bar(@Named("b") String param) {} public static class Constructable { @Inject public Constructable(@Named("c") String param) {} } public void testFieldInjectionPoint() throws NoSuchFieldException, IOException, ErrorsException { TypeLiteral<?> typeLiteral = TypeLiteral.get(getClass()); Field fooField = getClass().getField("foo"); InjectionPoint injectionPoint = new InjectionPoint(typeLiteral, fooField, false); assertSame(fooField, injectionPoint.getMember()); assertFalse(injectionPoint.isOptional()); assertEquals(getClass().getName() + ".foo", injectionPoint.toString()); assertEqualsBothWays(injectionPoint, new InjectionPoint(typeLiteral, fooField, false)); assertNotSerializable(injectionPoint); Dependency<?> dependency = getOnlyElement(injectionPoint.getDependencies()); assertEquals( "Key[type=java.lang.String, annotation=" + named("a") + "]@" + getClass().getName() + ".foo", dependency.toString()); assertEquals(fooField, dependency.getInjectionPoint().getMember()); assertEquals(-1, dependency.getParameterIndex()); assertEquals(Key.get(String.class, named("a")), dependency.getKey()); assertFalse(dependency.isNullable()); assertNotSerializable(dependency); assertEqualsBothWays( dependency, getOnlyElement(new InjectionPoint(typeLiteral, fooField, false).getDependencies())); } public void testMethodInjectionPoint() throws Exception { TypeLiteral<?> typeLiteral = TypeLiteral.get(getClass()); Method barMethod = getClass().getMethod("bar", String.class); InjectionPoint injectionPoint = new InjectionPoint(typeLiteral, barMethod, false); assertSame(barMethod, injectionPoint.getMember()); assertFalse(injectionPoint.isOptional()); assertEquals(getClass().getName() + ".bar()", injectionPoint.toString()); assertEqualsBothWays(injectionPoint, new InjectionPoint(typeLiteral, barMethod, false)); assertNotSerializable(injectionPoint); Dependency<?> dependency = getOnlyElement(injectionPoint.getDependencies()); assertEquals( "Key[type=java.lang.String, annotation=" + named("b") + "]@" + getClass().getName() + ".bar()[0]", dependency.toString()); assertEquals(barMethod, dependency.getInjectionPoint().getMember()); assertEquals(0, dependency.getParameterIndex()); assertEquals(Key.get(String.class, named("b")), dependency.getKey()); assertFalse(dependency.isNullable()); assertNotSerializable(dependency); assertEqualsBothWays( dependency, getOnlyElement(new InjectionPoint(typeLiteral, barMethod, false).getDependencies())); } public void testConstructorInjectionPoint() throws NoSuchMethodException, IOException, ErrorsException { TypeLiteral<?> typeLiteral = TypeLiteral.get(Constructable.class); Constructor<?> constructor = Constructable.class.getConstructor(String.class); InjectionPoint injectionPoint = new InjectionPoint(typeLiteral, constructor); assertSame(constructor, injectionPoint.getMember()); assertFalse(injectionPoint.isOptional()); assertEquals(Constructable.class.getName() + ".<init>()", injectionPoint.toString()); assertEqualsBothWays(injectionPoint, new InjectionPoint(typeLiteral, constructor)); assertNotSerializable(injectionPoint); Dependency<?> dependency = getOnlyElement(injectionPoint.getDependencies()); assertEquals( "Key[type=java.lang.String, annotation=" + named("c") + "]@" + Constructable.class.getName() + ".<init>()[0]", dependency.toString()); assertEquals(constructor, dependency.getInjectionPoint().getMember()); assertEquals(0, dependency.getParameterIndex()); assertEquals(Key.get(String.class, named("c")), dependency.getKey()); assertFalse(dependency.isNullable()); assertNotSerializable(dependency); assertEqualsBothWays( dependency, getOnlyElement(new InjectionPoint(typeLiteral, constructor).getDependencies())); } public void testUnattachedDependency() throws IOException { Dependency<String> dependency = Dependency.get(Key.get(String.class, named("d"))); assertEquals( "Key[type=java.lang.String, annotation=" + named("d") + "]", dependency.toString()); assertNull(dependency.getInjectionPoint()); assertEquals(-1, dependency.getParameterIndex()); assertEquals(Key.get(String.class, named("d")), dependency.getKey()); assertTrue(dependency.isNullable()); assertNotSerializable(dependency); assertEqualsBothWays(dependency, Dependency.get(Key.get(String.class, named("d")))); } public void testForConstructor() throws NoSuchMethodException { @SuppressWarnings("rawtypes") // Unavoidable because class literal uses raw type. Constructor<HashSet> constructor = HashSet.class.getConstructor(); TypeLiteral<HashSet<String>> hashSet = new TypeLiteral<HashSet<String>>() {}; InjectionPoint injectionPoint = InjectionPoint.forConstructor(constructor, hashSet); assertSame(constructor, injectionPoint.getMember()); assertEquals(ImmutableList.of(), injectionPoint.getDependencies()); assertFalse(injectionPoint.isOptional()); try { InjectionPoint.forConstructor(constructor, new TypeLiteral<LinkedHashSet<String>>() {}); fail("Expected ConfigurationException"); } catch (ConfigurationException expected) { assertContains( expected.getMessage(), "LinkedHashSet<String> does not define HashSet.<init>()", "while locating LinkedHashSet<String>"); } try { @SuppressWarnings({"unchecked", "rawtypes"}) // Testing incorrect types Constructor<Set<String>> c = (Constructor) constructor; InjectionPoint.forConstructor(c, new TypeLiteral<Set<String>>() {}); fail("Expected ConfigurationException"); } catch (ConfigurationException expected) { assertContains( expected.getMessage(), "Set<String> does not define HashSet.<init>()", "while locating Set<String>"); } } public void testForConstructorOf() { InjectionPoint injectionPoint = InjectionPoint.forConstructorOf(Constructable.class); assertEquals(Constructable.class.getName() + ".<init>()", injectionPoint.toString()); } public void testForConstructorOfRequireAtInject_success() { InjectionPoint injectionPoint = InjectionPoint.forConstructorOf( TypeLiteral.get(Constructable.class), /* atInjectRequired= */ true); assertEquals(Constructable.class.getName() + ".<init>()", injectionPoint.toString()); } public void testForConstructorOfRequireAtInject_fail() { ConfigurationException exception = assertThrows( ConfigurationException.class, () -> InjectionPoint.forConstructorOf( TypeLiteral.get(NoArgNonConstructable.class), /* atInjectRequired= */ true)); assertThat(exception) .hasMessageThat() .contains( "Injector is configured to require @Inject constructors but class" + " InjectionPointTest$NoArgNonConstructable does not have a @Inject annotated" + " constructor."); } static class NoArgNonConstructable { NoArgNonConstructable() {} } public void testTooManyConstructors() { ConfigurationException exception = assertThrows( ConfigurationException.class, () -> InjectionPoint.forConstructorOf(TypeLiteral.get(TooManyConstructors.class))); assertThat(exception) .hasMessageThat() .contains("has more than one constructor annotated with @Inject."); } @SuppressWarnings("MoreThanOneInjectableConstructor") // Testing too many constructors static class TooManyConstructors { @Inject TooManyConstructors() {} @Inject TooManyConstructors(String str) {} } public void testTooManyConstructors_withOptionalConstructorError() { ConfigurationException exception = assertThrows( ConfigurationException.class, () -> InjectionPoint.forConstructorOf( TypeLiteral.get(TooManyConstructorsWithOptional.class))); // Verify that both errors are reported in the exception assertThat(exception) .hasMessageThat() .contains("has more than one constructor annotated with @Inject."); assertThat(exception) .hasMessageThat() .contains( "TooManyConstructorsWithOptional.<init>() is annotated @Inject(optional=true), but" + " constructors cannot be optional."); } @SuppressWarnings({ "MoreThanOneInjectableConstructor", "InjectedConstructorAnnotations" }) // Testing too many constructors and optional constructor annotation static class TooManyConstructorsWithOptional { @Inject(optional = true) TooManyConstructorsWithOptional() {} @Inject TooManyConstructorsWithOptional(String str) {} } public void testAddForInstanceMethodsAndFields() throws Exception { Method instanceMethod = HasInjections.class.getMethod("instanceMethod", String.class); Field instanceField = HasInjections.class.getField("instanceField"); Field instanceField2 = HasInjections.class.getField("instanceField2"); TypeLiteral<HasInjections> type = TypeLiteral.get(HasInjections.class); Set<InjectionPoint> injectionPoints = InjectionPoint.forInstanceMethodsAndFields(HasInjections.class); // there is a defined order. assert on it assertThat(injectionPoints) .containsExactly( new InjectionPoint(type, instanceField, false), new InjectionPoint(type, instanceField2, false), new InjectionPoint(type, instanceMethod, false)) .inOrder(); } public void testAddForStaticMethodsAndFields() throws Exception { Method staticMethod = HasInjections.class.getMethod("staticMethod", String.class); Field staticField = HasInjections.class.getField("staticField"); Field staticField2 = HasInjections.class.getField("staticField2"); Set<InjectionPoint> injectionPoints = InjectionPoint.forStaticMethodsAndFields(HasInjections.class); TypeLiteral<HasInjections> type = TypeLiteral.get(HasInjections.class); assertThat(injectionPoints) .containsExactly( new InjectionPoint(type, staticField, false), new InjectionPoint(type, staticField2, false), new InjectionPoint(type, staticMethod, false)) .inOrder(); } static class HasInjections { @Inject public static void staticMethod(@Named("a") String a) {} @Inject @Named("c") public static String staticField; @Inject @Named("c") public static String staticField2; @Inject public void instanceMethod(@Named("d") String d) {} @Inject @Named("f") public String instanceField; @Inject @Named("f") public String instanceField2; } public void testAddForParameterizedInjections() { TypeLiteral<?> type = new TypeLiteral<ParameterizedInjections<String>>() {}; InjectionPoint constructor = InjectionPoint.forConstructorOf(type); assertEquals( new Key<Map<String, String>>() {}, getOnlyElement(constructor.getDependencies()).getKey()); InjectionPoint field = getOnlyElement(InjectionPoint.forInstanceMethodsAndFields(type)); assertEquals(new Key<Set<String>>() {}, getOnlyElement(field.getDependencies()).getKey()); } static class ParameterizedInjections<T> { @Inject Set<T> setOfTees; @Inject public ParameterizedInjections(Map<T, T> map) {} } public void testSignature() throws Exception { Signature fooA = new Signature(Foo.class.getDeclaredMethod("a", String.class, int.class)); Signature fooB = new Signature(Foo.class.getDeclaredMethod("b")); Signature barA = new Signature(Bar.class.getDeclaredMethod("a", String.class, int.class)); Signature barB = new Signature(Bar.class.getDeclaredMethod("b")); assertEquals(fooA.hashCode(), barA.hashCode()); assertEquals(fooB.hashCode(), barB.hashCode()); assertEquals(fooA, barA); assertEquals(fooB, barB); } static class Foo { void a(String s, int i) {} int b() { return 0; } } static class Bar { public void a(String s, int i) {} void b() {} } public void testOverrideBehavior() { Set<InjectionPoint> points; points = InjectionPoint.forInstanceMethodsAndFields(Super.class); assertEquals(points.toString(), 6, points.size()); assertPoints( points, Super.class, "atInject", "gInject", "privateAtAndPublicG", "privateGAndPublicAt", "atFirstThenG", "gFirstThenAt"); points = InjectionPoint.forInstanceMethodsAndFields(Sub.class); assertEquals(points.toString(), 7, points.size()); // Superclass will always have is private members injected, // and 'gInject' was last @Injected in Super, so that remains the owner assertPoints(points, Super.class, "privateAtAndPublicG", "privateGAndPublicAt", "gInject"); // Subclass also has the "private" methods, but they do not override // the superclass' methods, and it now owns the inject2 methods. assertPoints( points, Sub.class, "privateAtAndPublicG", "privateGAndPublicAt", "atFirstThenG", "gFirstThenAt"); points = InjectionPoint.forInstanceMethodsAndFields(SubSub.class); assertEquals(points.toString(), 6, points.size()); // Superclass still has all the injection points it did before.. assertPoints(points, Super.class, "privateAtAndPublicG", "privateGAndPublicAt", "gInject"); // Subclass is missing the privateGAndPublicAt because it first became public with // javax.inject.Inject and was overrode without an annotation, which means it // disappears. (It was guice @Inject in Super, but it was private there, so it doesn't // effect the annotations of the subclasses.) assertPoints(points, Sub.class, "privateAtAndPublicG", "atFirstThenG", "gFirstThenAt"); } /** * This test serves two purposes: 1) It makes sure that the bridge methods javax generates don't * stop us from injecting superclass methods in the case of javax.inject.Inject. This would happen * prior to java8 (where javac didn't copy annotations from the superclass into the subclass * method when it generated the bridge methods). * * <p>2) It makes sure that the methods we're going to inject have the correct generic types. * Java8 copies the annotations from super to subclasses, but it doesn't copy the generic type * information. Guice would naively consider the subclass an injectable method and eject the * superclass from the 'overrideIndex', leaving only a class with improper generic types. */ public void testSyntheticBridgeMethodsInSubclasses() { Set<InjectionPoint> points; points = InjectionPoint.forInstanceMethodsAndFields(RestrictedSuper.class); assertPointDependencies(points, new TypeLiteral<Provider<String>>() {}); assertEquals(points.toString(), 2, points.size()); assertPoints(points, RestrictedSuper.class, "jInject", "gInject"); points = InjectionPoint.forInstanceMethodsAndFields(ExposedSub.class); assertPointDependencies(points, new TypeLiteral<Provider<String>>() {}); assertEquals(points.toString(), 2, points.size()); assertPoints(points, RestrictedSuper.class, "jInject", "gInject"); } private void assertPoints( Iterable<InjectionPoint> points, Class<?> clazz, String... methodNames) { Set<String> methods = new HashSet<String>(); for (InjectionPoint point : points) { if (point.getDeclaringType().getRawType() == clazz) { methods.add(point.getMember().getName()); } } assertEquals(points.toString(), ImmutableSet.copyOf(methodNames), methods); } /** Asserts that each injection point has the specified dependencies, in the given order. */ private void assertPointDependencies( Iterable<InjectionPoint> points, TypeLiteral<?>... literals) { for (InjectionPoint point : points) { assertEquals(literals.length, point.getDependencies().size()); for (Dependency<?> dep : point.getDependencies()) { assertEquals(literals[dep.getParameterIndex()], dep.getKey().getTypeLiteral()); } } } static class Super { @javax.inject.Inject public void atInject() {} @com.google.inject.Inject public void gInject() {} @javax.inject.Inject private void privateAtAndPublicG() {} @com.google.inject.Inject private void privateGAndPublicAt() {} @javax.inject.Inject public void atFirstThenG() {} @com.google.inject.Inject public void gFirstThenAt() {} } static class Sub extends Super { @Override @SuppressWarnings("OverridesJavaxInjectableMethod") public void atInject() {} @Override @SuppressWarnings("OverridesGuiceInjectableMethod") public void gInject() {} @com.google.inject.Inject public void privateAtAndPublicG() {} @javax.inject.Inject public void privateGAndPublicAt() {} @com.google.inject.Inject @Override public void atFirstThenG() {} @javax.inject.Inject @Override public void gFirstThenAt() {} } static class SubSub extends Sub { @SuppressWarnings("OverridesGuiceInjectableMethod") @Override public void privateAtAndPublicG() {} @SuppressWarnings("OverridesJavaxInjectableMethod") @Override public void privateGAndPublicAt() {} @SuppressWarnings("OverridesGuiceInjectableMethod") @Override public void atFirstThenG() {} @SuppressWarnings("OverridesGuiceInjectableMethod") @Override public void gFirstThenAt() {} } static class RestrictedSuper { @com.google.inject.Inject public void gInject(Provider<String> p) {} @javax.inject.Inject public void jInject(Provider<String> p) {} } public static class ExposedSub extends RestrictedSuper { // The subclass may generate bridge/synthetic methods to increase the visibility // of the superclass methods, since the superclass was package-private but this is public. } }
mcculls/guice
core/test/com/google/inject/spi/InjectionPointTest.java
Java
apache-2.0
20,295
var ListCache = require('./_ListCache'), stackClear = require('./_stackClear'), stackDelete = require('./_stackDelete'), stackGet = require('./_stackGet'), stackHas = require('./_stackHas'), stackSet = require('./_stackSet'); /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; module.exports = Stack;
ionutbarau/petstore
petstore-app/src/main/resources/static/node_modules/form-data/node_modules/lodash/_Stack.js
JavaScript
apache-2.0
738
<html> <head> <title>NetBSD &amp; Google's Summer of Code: Martin Schuette - Improve syslogd (syslogd)</title> </head> <body> <h1>Testing syslogd</h1> <h2>Compiling</h2> <p>A (hopefully) stable version for testing is available by <a href="http://netbsd-soc.cvs.sourceforge.net/netbsd-soc/syslogd/src/">CVS</a> and as a <a href="syslogd-tls.tar.gz">.tar.gz archive</a>. It contains syslogd itself and all necessary files to build on NetBSD and FreeBSD.</p> <p>To build just type <span style="font-family: monospace;">make</span>. Unless you have a complete NetBSD source tree -- then you can extract the files to <span style="font-family: monospace;">/usr/src/usr.sbin/syslogd</span> and replace the <span style="font-family: monospace;">Makefile</span> with <span style="font-family: monospace;">Makefile.NetBSD</span> and then type <span style="font-family: monospace;">make</span>. <h3>Note on other BSDs</h3> <p>I also tested syslogd on FreeBSD. There are just a few issues/differences:</p> <ul> <li>You have to install libevent first</li> <li>No pidfile is written</li> <li>The code for wallmsg() is only copied, not tested</li> </ul> <p>I assume the same holds for other BSDs but I have no live system to test them.</p> <h2>Command line options</h2> <p>syslogd has to be run as root (because it uses chroot()). You should start it with option "-u username" to drop privileges.</p> <p>By default messages are written in syslog Protocol format. To get the BSD Syslog output like from previous versions use the "-o" option.</p> <h2>syslog.conf</h2> <p>To use TLS some additional configuration is required.</p> <h3>X.509 certificates</h3> <p>Every syslogd using TLS needs an X.509 certificate. The files containing the private key, certificate, and CA are configured with:</p> <pre> tls_key="/etc/openssl/default.key" tls_cert="/etc/openssl/default.crt" tls_ca="/some/where/my.cacert" </pre> <p>If you do not already have a X.509 certificate then you can tell syslogd to generate one for you with</p> <pre> tls_gen_cert=on </pre> <h3>TLS client</h3> <p>To send messages with configure a TLS destination. Here are three examples with different additional options required for authentication</p> <pre> # with CA *.* @[logserver.example.org]:13245 *.* @[127.0.0.1]:13245(subject="logserver.example.org") # without CA *.* @[127.0.0.1]:13245(fingerprint="SHA1:E4:E1:A6:1C:D4:31:D7:D4:9B:B8:DC:DF:DD:CE:30:71:46:00:92:C9") </pre> <p>If using a CA then it is checked whether the server's certificate matches the hostname or a given subject. Assuming the logserver's certificate has "logserver.example.org" as its commonName or as a subjectAltName/dnsName the first line is sufficient. (Once a standard portnumber has been assigned the port becomes optional.) If we do not want to rely on DNS and configure the destination with "127.0.0.1" then the subject comparison will fail. The alternatives are either to configure the subject as an option (as in the example above) or to generate a new certificate with the server's IP as a commonName or subjectAltName/ipAddress.</p> <p>Without a CA the easiest way to authenticate the peer's certificate is its fingerprint as in the last line in the example. syslogd logs the fingerprints of all certificates it loads or tries to connect with, but it can also be read from the shell with "openssl x509 -in /etc/openssl/default.crt -noout -fingerprint".</p> <h3>TLS server</h3> <p>To enable TLS server mode use these lines.</p> <pre> tls_server="on" tls_bindhost="127.0.0.1" tls_bindport="13245" </pre> <p>The bindhost is optional. The bindport is currently required (as long as there is no tcp port defined for the syslog service).</p> <p>With a CA that is all -- there is no additional hostname check for clients. Without a CA the server needs to be told which certificates to trust:</p> <pre> tls_allow_fingerprints = MD5:00:A2:A7:02:CA:A0:0E:00:DC:F1:91:BE:6A:AA:FF:27 "SHA1:E4:E1:A6:1C:D4:31:D7:D4:9B:B8:DC:DF:DD:CE:30:71:46:00:92:C9" </pre> <hr> <table border=0> <tr> <td> <a href="http://sourceforge.net"><img align="top" src="http://sourceforge.net/sflogo.php?group_id=141771&amp;type=2" width="125" height="37" border="0" alt="SourceForge.net Logo" /></a> <td> <table> <tr> <td> Martin Sch&uuml;tte &lt;<tt>info@mschuette.name</tt>&gt; </td> </tr> <tr> <td> $Id: howto.html,v 1.1 2008/10/31 16:12:19 christos Exp $ </td> </tr> </table> </tr> </table> </body> </html>
execunix/vinos
usr.sbin/syslogd/howto.html
HTML
apache-2.0
4,458
# The Zulip browser window There are three major components the your Zulip browser window. ## Central panel Some features for viewing, sending, or searching for messages are located in the central panel of your browser window. ![Central panel](/static/images/help/central-panel.png) ### Search bar The **search bar** is located at the top of the central panel. This feature allows you to narrow your view to show specific messages using [search constraints](/help/search-for-messages). !!! tip "" If your current filter is not the **Home** view, clicking on the home ((<i class="icon-vector-home"></i>) icon to the left of the search bar will also narrow your view to that of the **Home** view. ### Message table The **message table** displays your messages in the middle of your browser window. Depending on your current filter or search constraints, certain messages that you have received will be hidden from the message table. ### Compose box The **Compose box** is located under the message table. By default, the compose box consists of two buttons: **New stream message** and **New private message**. However, when either the **New stream message** or **New private message** button is clicked or when you are in the middle of composing a message, the compose box transforms to include: * **Stream**, **Topic**, and **Compose your message here...** inputs when you compose a [stream message](/help/send-a-stream-message). ![Stream message](/static/images/help/new-stream.png) * **one or more people...** and **Compose your message here...** inputs when you compose a [private message](/help/send-a-private-message). ![Message table](/static/images/help/private-box.png) ## Left sidebar Located on the left side of your browser window, the **left sidebar** shows options for narrowing your view. ![Left sidebar](/static/images/help/left_sidebar.png) ### Preset filters Preset filters are located at the top of the left sidebar. * Clicking on the **Home** filter narrows your view to show all messages from unmuted streams that you're subscribed to as well as private messages that you have received. !!! tip "" If your current filter is not the **Home** view, clicking on the Zulip logo will also narrow your view to that of the **Home** view. * Clicking on the **Private messages** filter narrows your view to show all private messages that you have received. * Clicking on the **Starred messages** filter narrows your view to show all messages that you have [starred](/help/star-a-message). * Clicking on the **Mentions** filter narrows your view to show all messages in which you were [mentioned](/help/at-mention-a-team-member). ### Streams section Located below the preset filters, the **Streams** section shows all the streams that you are subscribed to. * There are two icons located next to the **Streams** section header: * Clicking the magnifying glass (<i class="icon-vector-search"></i>) icon reveals an input that allows you to search for streams. * Clicking the cog (<i class="icon-vector-cog"></i>) icon allows you to [navigate](/help/browse-and-subscribe-to-streams#browse-streams) to the [Streams](/#streams) page. * Hovering over a stream in the **Streams** section reveals a chevron that allows you to modify the stream's settings when you click on it. * Clicking on a stream in the **Streams** section allows you to narrow your view to the stream's messages and view all topics in the stream. * Similarly, hovering over a topic in the **Streams** section reveals a down chevron (<i class="icon-vector-chevron-down"></i>) icon that allows you to modify the topic's settings when you click on it. ## Right sidebar The **right sidebar** shows users in your Zulip organization and some configuration settings on the right side of the browser window. ![Right sidebar](/static/images/help/right_sidebar.png) ### Configuration settings You can access your configuration settings, such as **Settings**, by clicking the cog (<i class="icon-vector-cog"></i>) icon in the top right corner of the right sidebar. ### Users section The **Users** section, also known as the **user list**, shows the statuses of all users in your organization. !!! tip "" The right sidebar is hidden on narrow screens. To display the user list on narrow screens, you can [configure](/help/move-the-users-list-to-the-left-sidebar) your user list to be displayed on the left sidebar. * You can search for specific users in the **Search people** input located directly under the **Users** section header. * Hovering over a user in the **Users** section reveals a down chevron (<i class="icon-vector-chevron-down"></i>) icon that allows you to perform several narrowing and message composing actions when you click on it. * Clicking on a user in the **Users** section allows you to narrow your view to your private messages with that particular user.
jphilipsen05/zulip
templates/zerver/help/the-zulip-browser-window.md
Markdown
apache-2.0
4,956
/* * DefaultConversionService.java */ package org.ngbw.sdk.conversion; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.sql.SQLException; import java.text.ParseException; import java.util.Collection; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.ngbw.sdk.api.conversion.ConversionRegistry; import org.ngbw.sdk.api.conversion.ConversionService; import org.ngbw.sdk.api.conversion.RecordFilter; import org.ngbw.sdk.api.conversion.SourceDocumentConverter; import org.ngbw.sdk.api.conversion.SourceDocumentReader; import org.ngbw.sdk.api.core.GenericDataRecordCollection; import org.ngbw.sdk.common.util.StringUtils; import org.ngbw.sdk.common.util.ValidationResult; import org.ngbw.sdk.core.shared.IndexedDataRecord; import org.ngbw.sdk.core.shared.SourceDocumentBean; import org.ngbw.sdk.core.shared.SourceDocumentType; import org.ngbw.sdk.core.types.DataFormat; import org.ngbw.sdk.database.DataRecord; import org.ngbw.sdk.database.SourceDocument; /** * * @author Roland H. Niedner * */ public class DefaultConversionService implements ConversionService { private static Log log = LogFactory.getLog(DefaultConversionService.class); ConversionRegistry conversionRegistry; DefaultConversionService(ConversionRegistry conversionRegistry) { if(conversionRegistry == null) throw new NullPointerException("ConversionRegistry must not be null!"); this.conversionRegistry = conversionRegistry; } public ConversionRegistry getConversionRegistry() { return conversionRegistry; } public Set<SourceDocumentType> getReadableDocumentTypes() { return conversionRegistry.getReadableDocumentTypes(); } public boolean canConvert(SourceDocumentType sourceKey, SourceDocumentType targetKey) { if(sourceKey == null) throw new NullPointerException("sourceKey must not be null!"); if(targetKey == null) throw new NullPointerException("targetKey must not be null!"); if(sourceKey.equals(targetKey)) return true; return conversionRegistry.hasConverter(sourceKey, targetKey); } public boolean canConvert(SourceDocument srcDocument, SourceDocumentType targetKey) { if(srcDocument == null) throw new NullPointerException("srcDocument must not be null!"); if(targetKey == null) throw new NullPointerException("targetKey must not be null!"); SourceDocumentType sourceKey = srcDocument.getType(); if(sourceKey.equals(targetKey)) return true; if(canConvert(sourceKey, targetKey)== false) throw new RuntimeException("No converter for this transformation registered yet! Please check first with " + "calling canConvert(DataFormat sourceFormat, DataFormat targetFormat)."); SourceDocumentConverter converter = conversionRegistry.getConverter(sourceKey, targetKey); return converter.canRead(srcDocument) && converter.canWrite(targetKey); } public Set<SourceDocumentType> getTargetSourceDocumentTypes(SourceDocumentType sourceDocumentType){ if(sourceDocumentType == null) throw new NullPointerException("sourceDocumentType must not be null!"); return conversionRegistry.getTargetSourceDocumentTypes(sourceDocumentType); } public boolean canRead(SourceDocumentType sourceDocumentType) { if(sourceDocumentType == null) throw new NullPointerException("sourceDocumentType must not be null!"); return conversionRegistry.hasReader(sourceDocumentType); } public boolean validate(SourceDocument srcDocument) throws IOException, SQLException { if(srcDocument == null) throw new NullPointerException("SourceDocument must not be null!"); SourceDocumentType sourceDocumentType = srcDocument.getType(); if (log.isDebugEnabled()) log.debug("validating SourceDocumentType: " + sourceDocumentType); if (canRead(sourceDocumentType) == false) throw new RuntimeException("No Reader for this SourceDocumentType " + sourceDocumentType + " registered yet! Please check first with " + "calling canRead(SourceDocumentType)."); SourceDocumentReader reader = conversionRegistry.getReader(sourceDocumentType); ValidationResult result = reader.validate(srcDocument); if(result == null) throw new NullPointerException("ValidationResult is null - How can that happen!"); if (result.isValid() == false) { if (log.isDebugEnabled()) log.debug("invalid SourceDocumentType: " + sourceDocumentType + " : Reader reports: " + StringUtils.join(result.getErrors(), " | ")); } return result.isValid(); } public boolean check(SourceDocument srcDocument, SourceDocumentType sourceDocumentType) throws IOException, SQLException { if (srcDocument == null || srcDocument.getData() == null) throw new NullPointerException("No input data!"); if (sourceDocumentType == null) throw new NullPointerException("The SourceDocumentType of the SourceDocument is null!"); if(log.isDebugEnabled()) log.debug("Testing srcDocument with type " + srcDocument.getType() + " against " + sourceDocumentType); if (SourceDocumentType.UNKNOWN.equals(sourceDocumentType)) return true; //everything goes if (sourceDocumentType.isIncomplete()) return true; //everything goes if(canRead(srcDocument.getType()) == false) throw new RuntimeException("Cannot read sourceDocument. Please check with canRead method first!"); return validate(new SourceDocumentBean(sourceDocumentType, srcDocument.getData())); } public SourceDocumentType check(SourceDocument srcDocument, Set<SourceDocumentType> sourceDocumentTypes) throws IOException, SQLException { if(srcDocument == null) throw new NullPointerException("SourceDocument must not be null!"); if(sourceDocumentTypes == null || sourceDocumentTypes.isEmpty()) throw new NullPointerException("sourceDocumentTypes must not be null or empty!"); for (SourceDocumentType type : sourceDocumentTypes) { if (check(srcDocument, type)) return type; } return null; } public SourceDocumentType detectSourceDocument(SourceDocument srcDocument) throws IOException, SQLException { if(srcDocument == null) throw new NullPointerException("SourceDocument must not be null!"); // Return the specified SourceDocumentType if is is // (NOT UNKNOWN AND NOT INCOMPLETE AND is validated by the registered SourceDocumentTypeReader) // OR its is flagged validated. if (srcDocument.isValidated() || (SourceDocumentType.UNKNOWN.equals(srcDocument.getType()) == false && srcDocument.getType().isIncomplete() == false && check(srcDocument, srcDocument.getType())) ) return srcDocument.getType(); // Return the SourceDocumentType that is returned by the check method. // SourceDocumentType validatedType = check(srcDocument, getReadableDocumentTypes()); // if(log.isDebugEnabled()) // log.debug("validatedType: " + validatedType); return null; } public SourceDocument convert(SourceDocument srcDocument, SourceDocumentType sourceType, SourceDocumentType targetType) throws IOException, SQLException, ParseException { if(srcDocument == null) throw new NullPointerException("SourceDocument must not be null!"); if(sourceType == null) throw new NullPointerException("sourceType must not be null!"); if(targetType == null) throw new NullPointerException("targetType must not be null!"); if(sourceType.equals(targetType)) return srcDocument; if(canConvert(sourceType, targetType) == false) throw new NullPointerException("No converter registered yet! Please check with the canConvert method first."); return conversionRegistry.getConverter(sourceType, targetType).convert(srcDocument, targetType); } public SourceDocument convert(SourceDocument srcDocument, SourceDocumentType targetKey) throws IOException, SQLException, ParseException { if(srcDocument == null) throw new NullPointerException("SourceDocument must not be null!"); if(targetKey == null) throw new NullPointerException("targetKey must not be null!"); SourceDocumentType srcKey = srcDocument.getType(); if(canConvert(srcKey, targetKey) == false) throw new NullPointerException("No converter registered yet! Please check with the canConvert method first."); return conversionRegistry.getConverter(srcKey, targetKey).convert(srcDocument, targetKey); } public SourceDocument convert(Collection<SourceDocument> srcDocuments, SourceDocumentType targetKey) throws IOException, SQLException, ParseException { if(srcDocuments == null || srcDocuments.isEmpty()) throw new NullPointerException("srcDocuments must not be null or empty!"); if(targetKey == null) throw new NullPointerException("targetKey must not be null!"); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); byte[] data = null; for(SourceDocument srcDocument : srcDocuments) try { buffer.write(convert(srcDocument,targetKey).getData()); buffer.flush(); } catch (IOException e) { throw new RuntimeException(e); } finally { if (buffer != null) try { buffer.close(); } catch (IOException e) { log.warn(e.toString(), e); } } return new SourceDocumentBean(targetKey, data, true); } public GenericDataRecordCollection<IndexedDataRecord> read(SourceDocument srcDocument) throws IOException, SQLException, ParseException { if (srcDocument == null || srcDocument.getData() == null) throw new NullPointerException("No input data!"); SourceDocumentType sourceDocumentType = srcDocument.getType(); if (sourceDocumentType == null) throw new NullPointerException("The DataFormat of the SourceDocument is null!"); if(validate(srcDocument) == false) throw new RuntimeException("Cannot read sourceDocument of type " + srcDocument.getType() + ". Please check with canRead method first!"); SourceDocumentReader reader = conversionRegistry.getReader(sourceDocumentType); return reader.read(srcDocument); } public DataRecord readSingle(SourceDocument srcDocument) throws IOException, SQLException, ParseException { if (srcDocument == null || srcDocument.getData() == null) throw new NullPointerException("No input data!"); if (srcDocument.getDataFormat() == null) throw new NullPointerException("The DataFormat of the SourceDocument is null!"); SourceDocumentReader reader = conversionRegistry.getReader(srcDocument.getType()); return reader.readSingle(srcDocument); } public RecordFilter getRecordFilter(DataFormat dataFormat) { RecordFilter filter = conversionRegistry.getRecordFilter(dataFormat); if(log.isDebugEnabled()) log.debug(dataFormat + " return: " + filter.getClass() + "(" + filter.getFilteredFormat() + ")"); return filter; } public boolean hasRecordFilter(DataFormat dataFormat) { if (dataFormat == null) throw new NullPointerException("DataFormat is null!"); return conversionRegistry.getFilterableDataFormats().contains(dataFormat); } public boolean canExtractSequence(SourceDocument srcDocument) throws IOException, SQLException { if (srcDocument == null || srcDocument.getData() == null) throw new NullPointerException("No input data!"); DataFormat dataFormat = srcDocument.getDataFormat(); return conversionRegistry.hasSequenceParser(dataFormat); } public String extractSequence(SourceDocument srcDocument) throws IOException, SQLException { if (srcDocument == null || srcDocument.getData() == null) throw new NullPointerException("No input data!"); DataFormat dataFormat = srcDocument.getDataFormat(); String sourceRecord = new String(srcDocument.getData()); return conversionRegistry.getSequenceParser(dataFormat).extractSequence(sourceRecord); } public String extractSequence(DataFormat dataFormat, String sourceRecord) { if (dataFormat == null) throw new NullPointerException("dataFormat is null!"); if (sourceRecord == null) throw new NullPointerException("sourceRecord is null!"); return conversionRegistry.getSequenceParser(dataFormat).extractSequence(sourceRecord); } }
SciGaP/DEPRECATED-Cipres-Airavata-POC
saminda/cipres-airavata/sdk/src/main/java/org/ngbw/sdk/conversion/DefaultConversionService.java
Java
apache-2.0
11,940
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.customize; import com.intellij.CommonBundle; import com.intellij.ide.IdeBundle; import com.intellij.ide.WelcomeWizardUtil; import com.intellij.ide.cloudConfig.CloudConfigProvider; import com.intellij.ide.ui.LafManager; import com.intellij.ide.ui.laf.IntelliJLaf; import com.intellij.ide.ui.laf.LafManagerImpl; import com.intellij.ide.ui.laf.darcula.DarculaLaf; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.options.OptionsBundle; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.util.NlsSafe; import com.intellij.openapi.util.SystemInfo; import com.intellij.ui.AppUIUtil; import com.intellij.util.IconUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.StartupUiUtil; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.*; import java.util.Collection; import java.util.LinkedHashSet; import java.util.Set; public class CustomizeUIThemeStepPanel extends AbstractCustomizeWizardStep { public static class ThemeInfo { public final @NonNls String name; public final @NonNls String previewFileName; public final @NonNls String laf; private Icon icon; public ThemeInfo(@NonNls String name, @NonNls String previewFileName, @NonNls String laf) { this.name = name; this.previewFileName = SystemInfo.isMac && "IntelliJ".equals(previewFileName) ? "Aqua" : previewFileName; this.laf = laf; } private Icon getIcon() { if (icon == null) { String selector; if (SystemInfo.isMac) { selector = "OSX"; } else if (SystemInfo.isWindows) { selector = "Windows"; } else { selector = "Linux"; } icon = IconLoader.getIcon("lafs/" + selector + previewFileName + ".png", CustomizeUIThemeStepPanel.class.getClassLoader()); } return icon; } public void apply() { } } protected static final ThemeInfo DARCULA = new ThemeInfo("Darcula", "Darcula", DarculaLaf.class.getName()); protected static final ThemeInfo INTELLIJ = new ThemeInfo("Light", "IntelliJ", IntelliJLaf.class.getName()); private final boolean myColumnMode; private final JLabel myPreviewLabel; private final Set<ThemeInfo> myThemes = new LinkedHashSet<>(); public CustomizeUIThemeStepPanel() { setLayout(createSmallBorderLayout()); initThemes(myThemes); myColumnMode = myThemes.size() > 2; JPanel buttonsPanel = new JPanel(new GridLayout(myColumnMode ? myThemes.size() : 1, myColumnMode ? 1 : myThemes.size(), 5, 5)); ButtonGroup group = new ButtonGroup(); final ThemeInfo myDefaultTheme = getDefaultTheme(); for (final ThemeInfo theme : myThemes) { @NlsSafe String themName = theme.name; final JRadioButton radioButton = new JRadioButton(themName, myDefaultTheme == theme); radioButton.setOpaque(false); final JPanel panel = createBigButtonPanel(createSmallBorderLayout(), radioButton, () -> { CustomizeIDEWizardInteractions.INSTANCE.record(CustomizeIDEWizardInteractionType.UIThemeChanged); applyLaf(theme, this); theme.apply(); }); panel.setBorder(createSmallEmptyBorder()); panel.add(radioButton, myColumnMode ? BorderLayout.WEST : BorderLayout.NORTH); Icon icon = theme.getIcon(); int maxThumbnailSize = 400 / myThemes.size(); final JLabel label = new JLabel( myColumnMode ? IconUtil.scale(IconUtil.cropIcon(icon, maxThumbnailSize * 2, maxThumbnailSize * 2), this, .5f) : icon); label.setVerticalAlignment(SwingConstants.TOP); label.setHorizontalAlignment(SwingConstants.RIGHT); panel.add(label, BorderLayout.CENTER); group.add(radioButton); buttonsPanel.add(panel); } add(buttonsPanel, BorderLayout.CENTER); myPreviewLabel = new JLabel(); myPreviewLabel.setHorizontalAlignment(myColumnMode ? SwingConstants.LEFT : SwingConstants.CENTER); myPreviewLabel.setVerticalAlignment(SwingConstants.CENTER); if (myColumnMode) { add(buttonsPanel, BorderLayout.WEST); JPanel wrapperPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0)); wrapperPanel.add(myPreviewLabel); add(wrapperPanel, BorderLayout.CENTER); } //Static fields initialization. At this point there is no parent window applyLaf(myDefaultTheme, this); //Actual UI initialization //noinspection SSBasedInspection SwingUtilities.invokeLater(() -> applyLaf(myDefaultTheme, this)); } protected void initThemes(Collection<? super ThemeInfo> result) { if (SystemInfo.isMac) { result.add(DARCULA); result.add(getDefaultLafOnMac()); } else if (SystemInfo.isWindows) { result.add(DARCULA); result.add(INTELLIJ); } else { result.add(DARCULA); result.add(INTELLIJ); } } @NotNull protected static ThemeInfo getDefaultLafOnMac() { return INTELLIJ; } @NotNull private ThemeInfo getDefaultTheme() { if (ApplicationManager.getApplication() != null) { if (StartupUiUtil.isUnderDarcula()) return DARCULA; return INTELLIJ; } CloudConfigProvider provider = CloudConfigProvider.getProvider(); if (provider != null) { String lafClassName = provider.getLafClassName(); if (lafClassName != null) { ThemeInfo result = ContainerUtil.find(myThemes, theme -> lafClassName.equals(theme.laf)); if (result != null) { return result; } } } return myThemes.iterator().next(); } @Override public Dimension getPreferredSize() { Dimension size = super.getPreferredSize(); size.width += 30; return size; } @Override public String getTitle() { return IdeBundle.message("step.title.ui.themes"); } @Override public String getHTMLHeader() { return IdeBundle.message("label.set.ui.theme"); } @Override public String getHTMLFooter() { return IdeBundle.message("label.you.can.change.the.ui.theme.later.in.0.1", CommonBundle.settingsTitle(), OptionsBundle.message("configurable.group.appearance.settings.display.name"), CommonBundle.settingsTitle()); } private void applyLaf(ThemeInfo theme, Component component) { UIManager.LookAndFeelInfo info = new UIManager.LookAndFeelInfo(theme.name, theme.laf); try { boolean wasUnderDarcula = StartupUiUtil.isUnderDarcula(); UIManager.setLookAndFeel(info.getClassName()); AppUIUtil.updateForDarcula(StartupUiUtil.isUnderDarcula()); String className = info.getClassName(); WelcomeWizardUtil.setWizardLAF(className); Window window = SwingUtilities.getWindowAncestor(component); if (window != null) { if (SystemInfo.isMac) { window.setBackground(new Color(UIUtil.getPanelBackground().getRGB())); } SwingUtilities.updateComponentTreeUI(window); } if (ApplicationManager.getApplication() != null) { LafManager lafManager = LafManager.getInstance(); lafManager.setCurrentLookAndFeel(info); if (lafManager instanceof LafManagerImpl) { ((LafManagerImpl)lafManager).updateWizardLAF(wasUnderDarcula);//Actually updateUI would be called inside EditorColorsManager } else { lafManager.updateUI(); } } if (myColumnMode) { myPreviewLabel.setIcon(theme.getIcon()); myPreviewLabel.setBorder(BorderFactory.createLineBorder(UIManager.getColor("Label.foreground"))); } } catch (Exception e) { e.printStackTrace(); } } }
jwren/intellij-community
platform/platform-impl/src/com/intellij/ide/customize/CustomizeUIThemeStepPanel.java
Java
apache-2.0
7,842
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Tool * @subpackage Framework * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** * @see Zend_Tool_Project_Context_Filesystem_Directory */ // require_once 'Zend/Tool/Project/Context/Filesystem/Directory.php'; /** * This class is the front most class for utilizing Zend_Tool_Project * * A profile is a hierarchical set of resources that keep track of * items within a specific project. * * @category Zend * @package Zend_Tool * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Tool_Project_Context_Zf_LayoutScriptsDirectory extends Zend_Tool_Project_Context_Filesystem_Directory { /** * @var string */ protected $_filesystemName = 'scripts'; /** * getName() * * @return string */ public function getName() { return 'LayoutScriptsDirectory'; } }
calonso-conabio/intranet
protected/vendors/Zend/Tool/Project/Context/Zf/LayoutScriptsDirectory.php
PHP
apache-2.0
1,598
import json from decimal import Decimal class CustomEncoder(json.JSONEncoder): def default(self, object): if isinstance(object, set): return list(object) if isinstance(object, Decimal): if object % 1 > 0: return float(object) else: return int(object) return super(CustomEncoder, self).default(object)
apoclyps/pyrestful
pyrestful/encoders.py
Python
apache-2.0
399
package org.mindinformatics.gwt.domeo.plugins.persistence.json.model; import java.util.Date; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.i18n.client.DateTimeFormat; /** * @author Paolo Ciccarese <paolo.ciccarese@gmail.com> */ public class JsPublicationArticleReference extends JavaScriptObject { protected JsPublicationArticleReference() {} public final native String getId() /*-{ return this['@id']; }-*/; public final native String getType() /*-{ return this['@type']; }-*/; public final native String getTitle() /*-{ return this.title; }-*/; public final native String getAuthorNames() /*-{ return this.authorNames; }-*/; public final native String getPublicationInfo() /*-{ return this.publicationInfo; }-*/; public final native String getPublicationDate() /*-{ return this.publicationDate; }-*/; public final native String getJournalName() /*-{ return this.journalName; }-*/; public final native String getJournalIssn() /*-{ return this.journalIssn; }-*/; public final native String getDoi() /*-{ return this.doi; }-*/; public final native String getPubMedId() /*-{ return this.pmid; }-*/; public final native String getPubMedCentralId() /*-{ return this.pmcid; }-*/; public final native String getUnrecognized() /*-{ return this.unrecognized; }-*/; public final native String getCreatedOnAsString() /*-{ return this.createdon; }-*/; public final Date getCreatedOn() { DateTimeFormat fmt = DateTimeFormat.getFormat("MM/dd/yyyy HH:mm:ss Z"); return fmt.parse(getCreatedOnAsString()); } }
rkboyce/DomeoClient
src/org/mindinformatics/gwt/domeo/plugins/persistence/json/model/JsPublicationArticleReference.java
Java
apache-2.0
1,552
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.template.soy.basetree; import javax.annotation.Nullable; /** * Abstract implementation of a Node. * * <p> Important: Do not use outside of Soy code (treat as superpackage-private). * */ public abstract class AbstractNode implements Node { /** Just spaces. */ protected static final String SPACES = " "; /** The lowest known upper bound (exclusive!) for the syntax version of this node. */ @Nullable private SyntaxVersionUpperBound syntaxVersionBound; /** The parent of this node. */ private ParentNode<?> parent; protected AbstractNode() { syntaxVersionBound = null; parent = null; } /** * Copy constructor. * @param orig The node to copy. */ protected AbstractNode(AbstractNode orig, CopyState copyState) { parent = null; // important: should not copy parent pointer this.syntaxVersionBound = orig.syntaxVersionBound; } @Override public void maybeSetSyntaxVersionUpperBound( SyntaxVersionUpperBound newSyntaxVersionBound) { syntaxVersionBound = SyntaxVersionUpperBound.selectLower(syntaxVersionBound, newSyntaxVersionBound); } @Override @Nullable public SyntaxVersionUpperBound getSyntaxVersionUpperBound() { return syntaxVersionBound; } @Override public boolean couldHaveSyntaxVersionAtLeast(SyntaxVersion syntaxVersionCutoff) { return syntaxVersionBound == null || syntaxVersionBound.syntaxVersion.num > syntaxVersionCutoff.num; } @Override public void setParent(ParentNode<?> parent) { this.parent = parent; } @Override public ParentNode<?> getParent() { return parent; } @Override public boolean hasAncestor(Class<? extends Node> ancestorClass) { for (Node node = this; node != null; node = node.getParent()) { if (ancestorClass.isInstance(node)) { return true; } } return false; } @Override public <N extends Node> N getNearestAncestor(Class<N> ancestorClass) { for (Node node = this; node != null; node = node.getParent()) { if (ancestorClass.isInstance(node)) { return ancestorClass.cast(node); } } return null; } @Override public String toString() { return this.getClass().getSimpleName(); } }
rgpower/closure-templates
java/src/com/google/template/soy/basetree/AbstractNode.java
Java
apache-2.0
2,883
#ifndef STRINGS_H #define STRINGS_H #endif /* STRINGS_H */
Wapaul1/ray
src/common/shims/windows/strings.h
C
apache-2.0
60
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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. // Generated code. DO NOT EDIT! namespace Google.Cloud.Datastream.V1.Snippets { // [START datastream_v1_generated_Datastream_GetRoute_async] using Google.Cloud.Datastream.V1; using System.Threading.Tasks; public sealed partial class GeneratedDatastreamClientSnippets { /// <summary>Snippet for GetRouteAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task GetRouteRequestObjectAsync() { // Create client DatastreamClient datastreamClient = await DatastreamClient.CreateAsync(); // Initialize request argument(s) GetRouteRequest request = new GetRouteRequest { RouteName = RouteName.FromProjectLocationPrivateConnectionRoute("[PROJECT]", "[LOCATION]", "[PRIVATE_CONNECTION]", "[ROUTE]"), }; // Make the request Route response = await datastreamClient.GetRouteAsync(request); } } // [END datastream_v1_generated_Datastream_GetRoute_async] }
googleapis/google-cloud-dotnet
apis/Google.Cloud.Datastream.V1/Google.Cloud.Datastream.V1.GeneratedSnippets/DatastreamClient.GetRouteRequestObjectAsyncSnippet.g.cs
C#
apache-2.0
1,787
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer2.extractor.ts; import static com.google.common.truth.Truth.assertThat; import androidx.test.core.app.ApplicationProvider; import androidx.test.ext.junit.runners.AndroidJUnit4; import com.google.android.exoplayer2.extractor.Extractor; import com.google.android.exoplayer2.extractor.PositionHolder; import com.google.android.exoplayer2.testutil.FakeExtractorInput; import com.google.android.exoplayer2.testutil.TestUtil; import java.io.IOException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; /** Unit test for {@link TsDurationReader}. */ @RunWith(AndroidJUnit4.class) public final class TsDurationReaderTest { private TsDurationReader tsDurationReader; private PositionHolder seekPositionHolder; @Before public void setUp() { tsDurationReader = new TsDurationReader(); seekPositionHolder = new PositionHolder(); } @Test public void testIsDurationReadPending_returnFalseByDefault() { assertThat(tsDurationReader.isDurationReadFinished()).isFalse(); } @Test public void testReadDuration_returnsCorrectDuration() throws IOException, InterruptedException { FakeExtractorInput input = new FakeExtractorInput.Builder() .setData( TestUtil.getByteArray( ApplicationProvider.getApplicationContext(), "ts/bbb_2500ms.ts")) .setSimulateIOErrors(false) .setSimulateUnknownLength(false) .setSimulatePartialReads(false) .build(); while (!tsDurationReader.isDurationReadFinished()) { int result = tsDurationReader.readDuration(input, seekPositionHolder, /* pcrPid= */ 256); if (result == Extractor.RESULT_END_OF_INPUT) { break; } if (result == Extractor.RESULT_SEEK) { input.setPosition((int) seekPositionHolder.position); } } assertThat(tsDurationReader.getDurationUs() / 1000).isEqualTo(2500); } @Test public void testReadDuration_midStream_returnsCorrectDuration() throws IOException, InterruptedException { FakeExtractorInput input = new FakeExtractorInput.Builder() .setData( TestUtil.getByteArray( ApplicationProvider.getApplicationContext(), "ts/bbb_2500ms.ts")) .setSimulateIOErrors(false) .setSimulateUnknownLength(false) .setSimulatePartialReads(false) .build(); input.setPosition(1234); while (!tsDurationReader.isDurationReadFinished()) { int result = tsDurationReader.readDuration(input, seekPositionHolder, /* pcrPid= */ 256); if (result == Extractor.RESULT_END_OF_INPUT) { break; } if (result == Extractor.RESULT_SEEK) { input.setPosition((int) seekPositionHolder.position); } } assertThat(tsDurationReader.getDurationUs() / 1000).isEqualTo(2500); } }
superbderrick/ExoPlayer
library/core/src/test/java/com/google/android/exoplayer2/extractor/ts/TsDurationReaderTest.java
Java
apache-2.0
3,537
package com.coleman.util; import android.widget.Toast; public class ToastUtil { public static void show(String msg) { showMsg(msg, Toast.LENGTH_SHORT); } public static void show(String msg, int length) { showMsg(msg, length); } private static void showMsg(final String msg, final int length) { MyApp.handler.post(new Runnable() { @Override public void run() { Toast.makeText(MyApp.context, msg, length).show(); } }); } }
79144876/WordReviewProject
src/com/coleman/util/ToastUtil.java
Java
apache-2.0
535
<?php /** * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * The Apereo Foundation 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. */ /** * * Function receive message * This function is used to handle how an error message is used * @param string $user_name = username the error relates to * @param string $type = user / Admin / system * @param string $level = how serious the problem is, or whether it is a success * @param string $subject = The title of the error problem (a preci effectively) * @param string $content = The error message in full. * @version 1.0 * @author Patrick Lockley */ function receive_message($user_name, $type, $level, $subject, $content){ global $xerte_toolkits_site; if($level!="SUCCESS"){ $_SESSION['toolkits_most_recent_error'] = $subject . " " . $content; } if($user_name==""){ $user_name="UNKNOWN"; } /* * If error log message turned on, create an error log */ if(isset($xerte_toolkits_site->error_log_message) && $xerte_toolkits_site->error_log_message=="true"){ write_message($user_name, $type, $level, $subject, $content); } /* * If error email list is set, send an error email message to those users */ if(isset($xerte_toolkits_site->email_error_list) && trim($xerte_toolkits_site->email_error_list) != false){ email_message($user_name, $type, $level, $subject, $content); } } /** * * Function write message * This function is used to log an error message * @param string $user_name = username the error relates to * @param string $type = user / Admin / system * @param string $level = how serious the problem is, or whether it is a success * @param string $subject = The title of the error problem (a preci effectively) * @param string $content = The error message in full. * @version 1.0 * @author Patrick Lockley */ function write_message($user_name, $type, $level, $subject, $content){ global $xerte_toolkits_site; /* * Login/logout and management entries should not get logged to any other log files but their own. */ if ($level != "LOGINS" && $level != "MGMT") { /* * Get the log file contents (a series of HTML paragraphs separated by *) */ $error_string = ''; if(file_exists($xerte_toolkits_site->error_log_path . $user_name . ".log")){ $error_string = file_get_contents($xerte_toolkits_site->error_log_path . $user_name . ".log"); } $error_array = explode("*",$error_string); /* * If the error log is bigger than the maximum size, remove a section */ if(count($error_array)>$xerte_toolkits_site->max_error_size){ array_splice($error_array,0,1); } /* * If the error log is bigger than the maximum size, remove a section */ if(file_exists($xerte_toolkits_site->error_log_path . $user_name . ".log")){ $error_message_handle = fopen($xerte_toolkits_site->error_log_path . $user_name . ".log" , "w"); $string = implode("*", $error_array) . "<p>" . date("G:i:s - d/m/Y") . " " . $level . "<Br>" . $subject . "<Br>" . $content . "</p>*"; fwrite($error_message_handle, $string); fclose($error_message_handle); }else{ $error_message_handle = fopen($xerte_toolkits_site->error_log_path . $user_name . ".log" , "w"); $string = "<p>" . date("G:i:s - d/m/Y") . " " . $level . "<Br>" . $subject . "<Br>" . $content . "</p>*"; fwrite($error_message_handle, $string); fclose($error_message_handle); } } /* * Make an error log file per level as well */ $error_string = ''; if(file_exists($xerte_toolkits_site->error_log_path . $level . ".log")){ $error_string = file_get_contents($xerte_toolkits_site->error_log_path . $level . ".log"); } $error_array = explode("*",$error_string); if(count($error_array)>$xerte_toolkits_site->max_error_size){ array_splice($error_array,0,1); } $red = ($subject == "Failed login") ? " style='color:#FF0000;'" : ""; if(file_exists($xerte_toolkits_site->error_log_path . $level . ".log")){ $error_message_handle = fopen($xerte_toolkits_site->error_log_path . $level . ".log" , "w"); $string = implode("*", $error_array) . "<p" . $red . ">" . date("G:i:s - d/m/Y") . " " . $level . "<Br>" . $subject . "<Br>" . $content . "</p>*"; fwrite($error_message_handle, $string); fclose($error_message_handle); }else{ $error_message_handle = fopen($xerte_toolkits_site->error_log_path . $level . ".log" , "w"); $string = "<p" . $red . ">" . date("G:i:s - d/m/Y") . " " . $level . "<Br>" . $subject . "<Br>" . $content . "</p>*"; fwrite($error_message_handle, $string); fclose($error_message_handle); } } /** * * Function email message * This function is used to send an error email message * @param string $user_name = username the error relates to * @param string $type = user / Admin / system * @param string $level = how serious the problem is, or whether it is a success * @param string $subject = The title of the error problem (a preci effectively) * @param string $content = The error message in full. * @version 1.0 * @author Patrick Lockley */ function email_message($user_name, $type, $level, $subject, $content){ global $xerte_toolkits_site; $email_subject = $user_name . " " . $type . " " . $level . " " . $subject; $email_content = date("G:i:s-d/m/Y") . "\n" . $content; mail($xerte_toolkits_site->email_error_list, $email_subject, $email_content, get_email_headers()); }
thexerteproject/xerteonlinetoolkits
website_code/php/error_library.php
PHP
apache-2.0
6,455
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.search; import org.apache.lucene.index.Term; import org.apache.lucene.queries.BlendedTermQuery; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanClause.Occur; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.BoostQuery; import org.apache.lucene.search.DisjunctionMaxQuery; import org.apache.lucene.search.MatchAllDocsQuery; import org.apache.lucene.search.Query; import org.apache.lucene.search.TermQuery; import org.apache.lucene.util.BytesRef; import org.elasticsearch.common.compress.CompressedXContent; import org.elasticsearch.common.lucene.search.MultiPhrasePrefixQuery; import org.elasticsearch.index.IndexService; import org.elasticsearch.index.engine.Engine; import org.elasticsearch.index.mapper.MapperService; import org.elasticsearch.index.mapper.MockFieldMapper.FakeFieldType; import org.elasticsearch.index.query.MultiMatchQueryBuilder; import org.elasticsearch.index.query.QueryShardContext; import org.elasticsearch.index.search.MultiMatchQuery.FieldAndFieldType; import org.elasticsearch.test.ESSingleNodeTestCase; import org.junit.Before; import java.io.IOException; import java.util.Arrays; import static org.elasticsearch.index.query.QueryBuilders.multiMatchQuery; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; public class MultiMatchQueryTests extends ESSingleNodeTestCase { private IndexService indexService; @Before public void setup() throws IOException { IndexService indexService = createIndex("test"); MapperService mapperService = indexService.mapperService(); String mapping = "{\n" + " \"person\":{\n" + " \"properties\":{\n" + " \"name\":{\n" + " \"properties\":{\n" + " \"first\": {\n" + " \"type\":\"text\"\n" + " }," + " \"last\": {\n" + " \"type\":\"text\"\n" + " }" + " }" + " }\n" + " }\n" + " }\n" + "}"; mapperService.merge("person", new CompressedXContent(mapping), MapperService.MergeReason.MAPPING_UPDATE, false); this.indexService = indexService; } public void testCrossFieldMultiMatchQuery() throws IOException { QueryShardContext queryShardContext = indexService.newQueryShardContext( randomInt(20), null, () -> { throw new UnsupportedOperationException(); }); queryShardContext.setAllowUnmappedFields(true); Query parsedQuery = multiMatchQuery("banon").field("name.first", 2).field("name.last", 3).field("foobar").type(MultiMatchQueryBuilder.Type.CROSS_FIELDS).toQuery(queryShardContext); try (Engine.Searcher searcher = indexService.getShard(0).acquireSearcher("test")) { Query rewrittenQuery = searcher.searcher().rewrite(parsedQuery); BooleanQuery.Builder expected = new BooleanQuery.Builder(); expected.add(new TermQuery(new Term("foobar", "banon")), BooleanClause.Occur.SHOULD); Query tq1 = new BoostQuery(new TermQuery(new Term("name.first", "banon")), 2); Query tq2 = new BoostQuery(new TermQuery(new Term("name.last", "banon")), 3); expected.add(new DisjunctionMaxQuery(Arrays.<Query>asList(tq1, tq2), 0f), BooleanClause.Occur.SHOULD); assertEquals(expected.build(), rewrittenQuery); } } public void testBlendTerms() { FakeFieldType ft1 = new FakeFieldType(); ft1.setName("foo"); FakeFieldType ft2 = new FakeFieldType(); ft2.setName("bar"); Term[] terms = new Term[] { new Term("foo", "baz"), new Term("bar", "baz") }; float[] boosts = new float[] {2, 3}; Query expected = BlendedTermQuery.booleanBlendedQuery(terms, boosts, false); Query actual = MultiMatchQuery.blendTerm( indexService.newQueryShardContext(randomInt(20), null, () -> { throw new UnsupportedOperationException(); }), new BytesRef("baz"), null, 1f, new FieldAndFieldType(ft1, 2), new FieldAndFieldType(ft2, 3)); assertEquals(expected, actual); } public void testBlendTermsWithFieldBoosts() { FakeFieldType ft1 = new FakeFieldType(); ft1.setName("foo"); ft1.setBoost(100); FakeFieldType ft2 = new FakeFieldType(); ft2.setName("bar"); ft2.setBoost(10); Term[] terms = new Term[] { new Term("foo", "baz"), new Term("bar", "baz") }; float[] boosts = new float[] {200, 30}; Query expected = BlendedTermQuery.booleanBlendedQuery(terms, boosts, false); Query actual = MultiMatchQuery.blendTerm( indexService.newQueryShardContext(randomInt(20), null, () -> { throw new UnsupportedOperationException(); }), new BytesRef("baz"), null, 1f, new FieldAndFieldType(ft1, 2), new FieldAndFieldType(ft2, 3)); assertEquals(expected, actual); } public void testBlendTermsUnsupportedValue() { FakeFieldType ft1 = new FakeFieldType(); ft1.setName("foo"); FakeFieldType ft2 = new FakeFieldType() { @Override public Query termQuery(Object value, QueryShardContext context) { throw new IllegalArgumentException(); } }; ft2.setName("bar"); Term[] terms = new Term[] { new Term("foo", "baz") }; float[] boosts = new float[] {2}; Query expected = BlendedTermQuery.booleanBlendedQuery(terms, boosts, false); Query actual = MultiMatchQuery.blendTerm( indexService.newQueryShardContext(randomInt(20), null, () -> { throw new UnsupportedOperationException(); }), new BytesRef("baz"), null, 1f, new FieldAndFieldType(ft1, 2), new FieldAndFieldType(ft2, 3)); assertEquals(expected, actual); } public void testBlendNoTermQuery() { FakeFieldType ft1 = new FakeFieldType(); ft1.setName("foo"); FakeFieldType ft2 = new FakeFieldType() { @Override public Query termQuery(Object value, QueryShardContext context) { return new MatchAllDocsQuery(); } }; ft2.setName("bar"); Term[] terms = new Term[] { new Term("foo", "baz") }; float[] boosts = new float[] {2}; Query expectedClause1 = BlendedTermQuery.booleanBlendedQuery(terms, boosts, false); Query expectedClause2 = new BoostQuery(new MatchAllDocsQuery(), 3); Query expected = new BooleanQuery.Builder().setDisableCoord(true) .add(expectedClause1, Occur.SHOULD) .add(expectedClause2, Occur.SHOULD) .build(); Query actual = MultiMatchQuery.blendTerm( indexService.newQueryShardContext(randomInt(20), null, () -> { throw new UnsupportedOperationException(); }), new BytesRef("baz"), null, 1f, new FieldAndFieldType(ft1, 2), new FieldAndFieldType(ft2, 3)); assertEquals(expected, actual); } public void testMultiMatchPrefixWithAllField() throws IOException { QueryShardContext queryShardContext = indexService.newQueryShardContext( randomInt(20), null, () -> { throw new UnsupportedOperationException(); }); queryShardContext.setAllowUnmappedFields(true); Query parsedQuery = multiMatchQuery("foo").field("_all").type(MultiMatchQueryBuilder.Type.PHRASE_PREFIX).toQuery(queryShardContext); assertThat(parsedQuery, instanceOf(MultiPhrasePrefixQuery.class)); assertThat(parsedQuery.toString(), equalTo("_all:\"foo*\"")); } }
yanjunh/elasticsearch
core/src/test/java/org/elasticsearch/index/search/MultiMatchQueryTests.java
Java
apache-2.0
8,792
from copy import copy import pytest from plenum.common.stacks import nodeStackClass from plenum.common.util import randomString from stp_core.loop.eventually import eventually from stp_core.network.auth_mode import AuthMode from stp_core.network.port_dispenser import genHa from stp_core.test.helper import Printer, prepStacks, checkStacksConnected from stp_zmq.kit_zstack import KITZStack from stp_zmq.test.helper import genKeys from stp_zmq.zstack import Quota @pytest.fixture() def registry(): return { 'Alpha': genHa(), 'Beta': genHa(), 'Gamma': genHa(), 'Delta': genHa() } @pytest.fixture() def connection_timeout(tconf): # TODO: the connection may not be established for the first try because # some of the stacks may not have had a remote yet (that is they haven't had yet called connect) return 2 * tconf.RETRY_TIMEOUT_RESTRICTED + 1 def create_fake_nodestack(tdir, tconf, registry, name='Node1'): def msgHandler(msg): pass stackParams = { "name": name, "ha": genHa(), "auto": 2, "basedirpath": tdir } stack = nodeStackClass(stackParams, msgHandler, registry, randomString(32), config=tconf) return stack @pytest.fixture() def connected_nodestacks(registry, tdir, looper, connection_timeout, tconf): genKeys(tdir, registry.keys()) stacks = [] for name, ha in registry.items(): printer = Printer(name) stackParams = dict(name=name, ha=ha, basedirpath=tdir, auth_mode=AuthMode.RESTRICTED.value) reg = copy(registry) reg.pop(name) stack = KITZStack(stackParams, printer.print, reg) stack.listenerQuota = tconf.NODE_TO_NODE_STACK_QUOTA stack.listenerSize = tconf.NODE_TO_NODE_STACK_SIZE stacks.append(stack) motors = prepStacks(looper, *stacks, connect=False, useKeys=True) looper.run(eventually( checkStacksConnected, stacks, retryWait=1, timeout=connection_timeout)) return stacks, motors def test_set_quota(tdir, tconf, registry): changed_val = 100000 tconf.NODE_TO_NODE_STACK_QUOTA = changed_val stack = create_fake_nodestack(tdir, tconf, registry) assert stack.listenerQuota == tconf.NODE_TO_NODE_STACK_QUOTA def test_set_size(tdir, tconf, registry): changed_val = 100000 tconf.NODE_TO_NODE_STACK_SIZE = changed_val stack = create_fake_nodestack(tdir, tconf, registry) assert stack.listenerSize == tconf.NODE_TO_NODE_STACK_SIZE def test_limit_by_msg_count(looper, tdir, tconf, connected_nodestacks): stacks, motors = connected_nodestacks stackA = stacks[0] stackB = stacks[1] msg = 'some test messages' for i in range(tconf.NODE_TO_NODE_STACK_QUOTA + 10): stackA.send(msg, 'Beta') received_msgs = stackB._receiveFromListener(Quota(count=stackA.listenerQuota, size=stackA.listenerSize)) assert received_msgs <= tconf.NODE_TO_NODE_STACK_QUOTA def test_limit_by_msg_size(looper, tdir, tconf, connected_nodestacks): stacks, motors = connected_nodestacks stackA = stacks[0] stackB = stacks[1] msg = 'some test messages' limit_size = (tconf.NODE_TO_NODE_STACK_QUOTA - 10) * len(msg) stackB.listenerSize = limit_size for i in range(tconf.NODE_TO_NODE_STACK_QUOTA + 10): stackA.send(msg, 'Beta') received_msgs = stackB._receiveFromListener(Quota(count=stackA.listenerQuota, size=stackA.listenerSize)) assert received_msgs < tconf.NODE_TO_NODE_STACK_QUOTA
evernym/zeno
stp_zmq/test/test_node_to_node_quota.py
Python
apache-2.0
3,525
# encoding: utf-8 module RailsBestPractices module Core # Method container. class Methods def initialize @methods = {} @possible_methods = {} end # Add a method. # # @param [String] class name # @param [String] method name # @param [Hash] method meta, file and line, {"file" => "app/models/post.rb", "line" => 5} # @param [String] access control, public, protected or private def add_method(class_name, method_name, meta={}, access_control="public") return if class_name == "" return if has_method?(class_name, method_name) methods(class_name) << Method.new(class_name, method_name, access_control, meta) if access_control == "public" @possible_methods[method_name] = false end end # Get methods of a class. # # @param [String] class name # @param [String] access control # @return [Array] all methods of a class for such access control, if access control is nil, return all public/protected/private methods def get_methods(class_name, access_control=nil) if access_control methods(class_name).select { |method| method.access_control == access_control } else methods(class_name) end end # If a class has a method. # # @param [String] class name # @param [String] method name # @param [String] access control # @return [Boolean] has a method or not def has_method?(class_name, method_name, access_control=nil) if access_control !!methods(class_name).find { |method| method.method_name == method_name && method.access_control == access_control } else !!methods(class_name).find { |method| method.method_name == method_name } end end # Mark parent class' method as used. # # @param [String] class name # @param [String] method name def mark_parent_class_method_used(class_name, method_name) klass = Prepares.klasses.find { |klass| klass.to_s == class_name } if klass && klass.extend_class_name mark_parent_class_method_used(klass.extend_class_name, method_name) method = get_method(klass.extend_class_name, method_name) method.mark_used if method end end # Mark sub classes' method as used. # # @param [String] class name # @param [String] method name def mark_subclasses_method_used(class_name, method_name) Prepares.klasses.select { |klass| klass.extend_class_name == class_name }.each do |klass| mark_subclasses_method_used(klass.to_s, method_name) method = get_method(klass.to_s, method_name) method.mark_used if method end end # Mark the method as public. # # @param [String] class name # @param [String] method name def mark_publicize(class_name, method_name) method = get_method(class_name, method_name) method.publicize if method end # Mark parent classs' method as public. # # @param [String] class name # @param [String] method name def mark_parent_class_methods_publicize(class_name, method_name) klass = Prepares.klasses.find { |klass| klass.to_s == class_name } if klass && klass.extend_class_name mark_parent_class_methods_publicize(klass.extend_class_name, method_name) mark_publicize(class_name, method_name) end end # Remomber the method name, the method is probably be used for the class' public method. # # @param [String] method name def possible_public_used(method_name) @possible_methods[method_name] = true end # Get a method in a class. # # @param [String] class name # @param [String] method name # @param [String] access control # @return [Method] Method object def get_method(class_name, method_name, access_control=nil) if access_control methods(class_name).find { |method| method.method_name == method_name && method.access_control == access_control } else methods(class_name).find { |method| method.method_name == method_name } end end # Get all unused methods. # # @param [String] access control # @return [Array] array of Method def get_all_unused_methods(access_control=nil) @methods.inject([]) { |unused_methods, (class_name, methods)| unused_methods += if access_control methods.select { |method| method.access_control == access_control && !method.used } else methods.select { |method| !method.used } end }.reject { |method| method.access_control == "public" && @possible_methods[method.method_name] } end private # Methods of a class. # # @param [String] class name # @return [Array] array of methods def methods(class_name) @methods[class_name] ||= [] end end # Method info includes class name, method name, access control, file, line, used. class Method attr_reader :access_control, :class_name, :method_name, :used, :file, :line def initialize(class_name, method_name, access_control, meta) @class_name = class_name @method_name = method_name @file = meta["file"] @line = meta["line"] @access_control = access_control @used = false end # Mark the method as used. def mark_used @used = true end # Mark the method as public def publicize @access_control = "public" end end end end
masukomi/mobtvse
vendor/bundle/gems/rails_best_practices-1.9.0/lib/rails_best_practices/core/methods.rb
Ruby
apache-2.0
5,785
# Copyright 2015 Mirantis, 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. import contextlib import logging import oslo_messaging from oslo_messaging._drivers import common as rpc_common from oslo_messaging._drivers.zmq_driver.client.publishers\ import zmq_publisher_base from oslo_messaging._drivers.zmq_driver import zmq_address from oslo_messaging._drivers.zmq_driver import zmq_async from oslo_messaging._drivers.zmq_driver import zmq_names from oslo_messaging._i18n import _LE, _LI LOG = logging.getLogger(__name__) zmq = zmq_async.import_zmq() class ReqPublisher(zmq_publisher_base.PublisherBase): def send_request(self, request): if request.msg_type != zmq_names.CALL_TYPE: raise zmq_publisher_base.UnsupportedSendPattern(request.msg_type) socket = self._connect_to_host(request.target) self._send_request(socket, request) return self._receive_reply(socket, request) def _connect_to_host(self, target): try: self.zmq_context = zmq.Context() socket = self.zmq_context.socket(zmq.REQ) host = self.matchmaker.get_single_host(target) connect_address = zmq_address.get_tcp_direct_address(host) LOG.info(_LI("Connecting REQ to %s") % connect_address) socket.connect(connect_address) self.outbound_sockets[str(target)] = socket return socket except zmq.ZMQError as e: errmsg = _LE("Error connecting to socket: %s") % str(e) LOG.error(_LE("Error connecting to socket: %s") % str(e)) raise rpc_common.RPCException(errmsg) @staticmethod def _receive_reply(socket, request): def _receive_method(socket): return socket.recv_pyobj() # NOTE(ozamiatin): Check for retry here (no retries now) with contextlib.closing(zmq_async.get_reply_poller()) as poller: poller.register(socket, recv_method=_receive_method) reply, socket = poller.poll(timeout=request.timeout) if reply is None: raise oslo_messaging.MessagingTimeout( "Timeout %s seconds was reached" % request.timeout) if reply[zmq_names.FIELD_FAILURE]: raise rpc_common.deserialize_remote_exception( reply[zmq_names.FIELD_FAILURE], request.allowed_remote_exmods) else: return reply[zmq_names.FIELD_REPLY] def close(self): # For contextlib compatibility self.cleanup()
magic0704/oslo.messaging
oslo_messaging/_drivers/zmq_driver/client/publishers/zmq_req_publisher.py
Python
apache-2.0
3,103
<!DOCTYPE html> <html> <head> <script> function performTest(api) { api.Cursor.insertCharacter(" "); api.tests.TestLib.showSelection(); } </script> </head> <body> <p><b></b>[]<br/></p> </body> </html>
corinthia/corinthia-editorlib
tests/cursor/insertCharacter-space05-input.html
HTML
apache-2.0
208
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the demonstration applications of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor ** the names of its contributors may be used to endorse or promote ** products derived from this software without specific prior written ** permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "button.h" #include <QMouseEvent> #include <QPainter> #include <QTimer> Button::Button(QWidget *parent, Qt::WindowFlags f) : QLabel(parent, f) { m_downPixmap = 0; m_disabled = false; m_toggled = false; m_toggle_enabled = false; } Button::~Button() { } void Button::disableBtn(bool b) { m_disabled = b; setPressed(m_disabled); } void Button::mousePressEvent(QMouseEvent *event) { if (!m_disabled) { event->accept(); setPixmap(m_downPixmap); repaint(); // Lift button back to up after 300ms if(m_toggle_enabled) { m_toggled = !m_toggled; setPressed(m_toggled); emit pressed(); } else QTimer::singleShot(300, this, SLOT(backToUp())); } } void Button::backToUp() { setPixmap(m_upPixmap); repaint(); emit pressed(); } void Button::setPixmap(const QPixmap& p) { // Set up and down picture for the button // Set pixmap if (!p.isNull()) QLabel::setPixmap(p); // Make down pixmap if it does not exists if (m_downPixmap.isNull()) { // Store up pixmap m_upPixmap = *pixmap(); // Create down pixmap // Make m_downPixmap as a transparent m_upPixmap QPixmap transparent(m_upPixmap.size()); transparent.fill(Qt::transparent); QPainter painter(&transparent); painter.setCompositionMode(QPainter::CompositionMode_Source); painter.drawPixmap(0, 0, m_upPixmap); painter.setCompositionMode(QPainter::CompositionMode_DestinationIn); painter.fillRect(transparent.rect(), QColor(0, 0, 0, 150)); painter.end(); m_downPixmap = transparent; } } void Button::enableToggle(bool enable) { m_toggle_enabled = enable; } void Button::setPressed(bool isPressed) { if(isPressed) { m_toggled = true; setPixmap(m_downPixmap); } else { m_toggled = false; setPixmap(m_upPixmap); } } bool Button::isPressed() { return m_toggled; }
nolanamy/zxing
symbian/QZXing/examples/QQrDecoder/button.cpp
C++
apache-2.0
4,133
/* * 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.kylin.source; import java.util.HashMap; import java.util.Map; import org.apache.kylin.metadata.model.SegmentRange; import org.apache.kylin.metadata.model.SegmentRange.TSRange; import org.apache.kylin.shaded.com.google.common.base.MoreObjects; /** * Defines a set of source records that will be built into a cube segment. * * There are two main approaches: * 1) by a date range, in case of time partitioned tables like Hive. * 2) by an offset range, in case of offset based source like Kafka. * * For the offset approach, the source can further be partitioned and each partition can define * its own start and end offset within that partition. */ public class SourcePartition { TSRange tsRange; SegmentRange segRange; Map<Integer, Long> sourcePartitionOffsetStart; Map<Integer, Long> sourcePartitionOffsetEnd; public SourcePartition() { } public SourcePartition(TSRange tsRange, SegmentRange segRange, Map<Integer, Long> sourcePartitionOffsetStart, Map<Integer, Long> sourcePartitionOffsetEnd) { this.tsRange = tsRange; this.segRange = segRange; this.sourcePartitionOffsetStart = sourcePartitionOffsetStart; this.sourcePartitionOffsetEnd = sourcePartitionOffsetEnd; } public TSRange getTSRange() { return tsRange; } public void setTSRange(TSRange tsRange) { this.tsRange = tsRange; } public SegmentRange getSegRange() { return segRange; } public void setSegRange(SegmentRange segRange) { this.segRange = segRange; } public Map<Integer, Long> getSourcePartitionOffsetStart() { return sourcePartitionOffsetStart; } public void setSourcePartitionOffsetStart(Map<Integer, Long> sourcePartitionOffsetStart) { this.sourcePartitionOffsetStart = sourcePartitionOffsetStart; } public Map<Integer, Long> getSourcePartitionOffsetEnd() { return sourcePartitionOffsetEnd; } public void setSourcePartitionOffsetEnd(Map<Integer, Long> sourcePartitionOffsetEnd) { this.sourcePartitionOffsetEnd = sourcePartitionOffsetEnd; } @Override public String toString() { return MoreObjects.toStringHelper(this).add("tsRange", tsRange).add("segRange", segRange).add("sourcePartitionOffsetStart", sourcePartitionOffsetStart.toString()).add("sourcePartitionOffsetEnd", sourcePartitionOffsetEnd.toString()).toString(); } public static SourcePartition getCopyOf(SourcePartition origin) { SourcePartition copy = new SourcePartition(); copy.setTSRange(origin.getTSRange()); copy.setSegRange(origin.getSegRange()); if (origin.getSourcePartitionOffsetStart() != null) { copy.setSourcePartitionOffsetStart(new HashMap<>(origin.getSourcePartitionOffsetStart())); } if (origin.getSourcePartitionOffsetEnd() != null) { copy.setSourcePartitionOffsetEnd(new HashMap<>(origin.getSourcePartitionOffsetEnd())); } return copy; } }
apache/kylin
core-metadata/src/main/java/org/apache/kylin/source/SourcePartition.java
Java
apache-2.0
3,845
<?php /******************************************************************************* * Copyright 2009-2016 Amazon Services. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * * You may not use this file except in compliance with the License. * You may obtain a copy of the License at: http://aws.amazon.com/apache2.0 * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. ******************************************************************************* * PHP Version 5 * @category Amazon * @package MWS Merchant Fulfillment Service * @version 2015-06-01 * Library Version: 2016-03-30 * Generated: Fri Nov 11 06:01:18 PST 2016 */ /** * @see MWSMerchantFulfillmentService_Model */ require_once (dirname(__FILE__) . '/../Model.php'); /** * MWSMerchantFulfillmentService_Model_GetShipmentResponse * * Properties: * <ul> * * <li>GetShipmentResult: MWSMerchantFulfillmentService_Model_GetShipmentResult</li> * <li>ResponseMetadata: MWSMerchantFulfillmentService_Model_ResponseMetadata</li> * <li>ResponseHeaderMetadata: MWSMerchantFulfillmentService_Model_ResponseHeaderMetadata</li> * * </ul> */ class MWSMerchantFulfillmentService_Model_GetShipmentResponse extends MWSMerchantFulfillmentService_Model { public function __construct($data = null) { $this->_fields = array ( 'GetShipmentResult' => array('FieldValue' => null, 'FieldType' => 'MWSMerchantFulfillmentService_Model_GetShipmentResult'), 'ResponseMetadata' => array('FieldValue' => null, 'FieldType' => 'MWSMerchantFulfillmentService_Model_ResponseMetadata'), 'ResponseHeaderMetadata' => array('FieldValue' => null, 'FieldType' => 'MWSMerchantFulfillmentService_Model_ResponseHeaderMetadata'), ); parent::__construct($data); } /** * Get the value of the GetShipmentResult property. * * @return GetShipmentResult GetShipmentResult. */ public function getGetShipmentResult() { return $this->_fields['GetShipmentResult']['FieldValue']; } /** * Set the value of the GetShipmentResult property. * * @param MWSMerchantFulfillmentService_Model_GetShipmentResult getShipmentResult * @return this instance */ public function setGetShipmentResult($value) { $this->_fields['GetShipmentResult']['FieldValue'] = $value; return $this; } /** * Check to see if GetShipmentResult is set. * * @return true if GetShipmentResult is set. */ public function isSetGetShipmentResult() { return !is_null($this->_fields['GetShipmentResult']['FieldValue']); } /** * Set the value of GetShipmentResult, return this. * * @param getShipmentResult * The new value to set. * * @return This instance. */ public function withGetShipmentResult($value) { $this->setGetShipmentResult($value); return $this; } /** * Get the value of the ResponseMetadata property. * * @return ResponseMetadata ResponseMetadata. */ public function getResponseMetadata() { return $this->_fields['ResponseMetadata']['FieldValue']; } /** * Set the value of the ResponseMetadata property. * * @param MWSMerchantFulfillmentService_Model_ResponseMetadata responseMetadata * @return this instance */ public function setResponseMetadata($value) { $this->_fields['ResponseMetadata']['FieldValue'] = $value; return $this; } /** * Check to see if ResponseMetadata is set. * * @return true if ResponseMetadata is set. */ public function isSetResponseMetadata() { return !is_null($this->_fields['ResponseMetadata']['FieldValue']); } /** * Set the value of ResponseMetadata, return this. * * @param responseMetadata * The new value to set. * * @return This instance. */ public function withResponseMetadata($value) { $this->setResponseMetadata($value); return $this; } /** * Get the value of the ResponseHeaderMetadata property. * * @return ResponseHeaderMetadata ResponseHeaderMetadata. */ public function getResponseHeaderMetadata() { return $this->_fields['ResponseHeaderMetadata']['FieldValue']; } /** * Set the value of the ResponseHeaderMetadata property. * * @param MWSMerchantFulfillmentService_Model_ResponseHeaderMetadata responseHeaderMetadata * @return this instance */ public function setResponseHeaderMetadata($value) { $this->_fields['ResponseHeaderMetadata']['FieldValue'] = $value; return $this; } /** * Check to see if ResponseHeaderMetadata is set. * * @return true if ResponseHeaderMetadata is set. */ public function isSetResponseHeaderMetadata() { return !is_null($this->_fields['ResponseHeaderMetadata']['FieldValue']); } /** * Set the value of ResponseHeaderMetadata, return this. * * @param responseHeaderMetadata * The new value to set. * * @return This instance. */ public function withResponseHeaderMetadata($value) { $this->setResponseHeaderMetadata($value); return $this; } /** * Construct MWSMerchantFulfillmentService_Model_GetShipmentResponse from XML string * * @param $xml * XML string to construct from * * @return MWSMerchantFulfillmentService_Model_GetShipmentResponse */ public static function fromXML($xml) { $dom = new DOMDocument(); $dom->loadXML($xml); $xpath = new DOMXPath($dom); $response = $xpath->query("//*[local-name()='GetShipmentResponse']"); if ($response->length == 1) { return new MWSMerchantFulfillmentService_Model_GetShipmentResponse(($response->item(0))); } else { throw new Exception ("Unable to construct MWSMerchantFulfillmentService_Model_GetShipmentResponse from provided XML. Make sure that GetShipmentResponse is a root element"); } } /** * XML Representation for this object * * @return string XML for this object */ public function toXML() { $xml = ""; $xml .= "<GetShipmentResponse xmlns=\"https://mws.amazonservices.com/MerchantFulfillment/2015-06-01\">"; $xml .= $this->_toXMLFragment(); $xml .= "</GetShipmentResponse>"; return $xml; } }
enkay83/mws
src/MWSMerchantFulfillmentService/Model/GetShipmentResponse.php
PHP
apache-2.0
6,870
/* * Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved. * * NVIDIA CORPORATION and its licensors retain all intellectual property * and proprietary rights in and to this software, related documentation * and any modifications thereto. Any use, reproduction, disclosure or * distribution of this software and related documentation without an express * license agreement from NVIDIA CORPORATION is strictly prohibited. */ #include "SnConvX.h" #include <stdarg.h> #include "PxErrorCallback.h" #include "PsString.h" #define MAX_DISPLAYED_ISSUES 10 using namespace physx; void Sn::ConvX::resetNbErrors() { mNbErrors = 0; mNbWarnings = 0; } int Sn::ConvX::getNbErrors() const { return mNbErrors; } void Sn::ConvX::displayMessage(PxErrorCode::Enum code, const char* format, ...) { if(silentMode()) return; int sum = mNbWarnings + mNbErrors; if(sum >= MAX_DISPLAYED_ISSUES) return; bool display = false; if(code==PxErrorCode::eINTERNAL_ERROR || code==PxErrorCode::eINVALID_OPERATION || code==PxErrorCode::eINVALID_PARAMETER) { mNbErrors++; display = true; } else if(code == PxErrorCode::eDEBUG_WARNING) { mNbWarnings++; display = true; } if(display || ((sum == 0) && verboseMode()) ) { va_list va; va_start(va, format); Ps::getFoundation().errorImpl(code, __FILE__, __LINE__, format, va); va_end(va); } if(display) { if( sum == 0) { Ps::getFoundation().error(PxErrorCode::eDEBUG_INFO, __FILE__, __LINE__, "Hit warnings or errors: skipping further verbose output.\n"); } else if(sum == MAX_DISPLAYED_ISSUES-1) { Ps::getFoundation().error(PxErrorCode::eDEBUG_INFO, __FILE__, __LINE__, "Exceeding 10 warnings or errors: skipping further output.\n"); } } return; }
LiangYue1981816/CrossEngine
PhysX-3.3/PhysXSDK/Source/PhysXExtensions/src/serialization/Binary/SnConvX_Error.cpp
C++
apache-2.0
1,766
/** * Copyright 2019 The AMP HTML Authors. 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. */ import {CommonSignals} from './common-signals'; import {Services} from './services'; import {VisibilityState} from './visibility-state'; import {childElementsByTag, isConnectedNode} from './dom'; import { createShadowDomWriter, createShadowRoot, importShadowBody, } from './shadow-embed'; import {dev, user} from './log'; import {disposeServicesForDoc, getServicePromiseOrNullForDoc} from './service'; import {getMode} from './mode'; import {installStylesForDoc} from './style-installer'; import {isArray, isObject} from './types'; import {parseUrlDeprecated} from './url'; import {setStyle} from './style'; /** @const @private {string} */ const TAG = 'multidoc-manager'; /** * A manager for documents in the multi-doc environment. */ export class MultidocManager { /** * @param {!Window} win * @param {!./service/ampdoc-impl.AmpDocService} ampdocService * @param {!./service/extensions-impl.Extensions} extensions * @param {!./service/timer-impl.Timer} timer */ constructor(win, ampdocService, extensions, timer) { /** @const */ this.win = win; /** @private @const */ this.ampdocService_ = ampdocService; /** @private @const */ this.extensions_ = extensions; /** @private @const */ this.timer_ = timer; /** @private @const {!Array<!ShadowRoot>} */ this.shadowRoots_ = []; } /** * Attaches the shadow root and calls the supplied DOM builder. * @param {!Element} hostElement * @param {string} url * @param {!Object<string, string>|undefined} params * @param {function(!Object, !ShadowRoot, * !./service/ampdoc-impl.AmpDocShadow):!Promise} builder * @return {!./runtime.ShadowDoc} * @private */ attachShadowDoc_(hostElement, url, params, builder) { params = params || Object.create(null); this.purgeShadowRoots_(); setStyle(hostElement, 'visibility', 'hidden'); const shadowRoot = createShadowRoot(hostElement); // TODO: closeShadowRoot_ is asynchronous. While this safety check is well // intentioned, it leads to a race between unlayout and layout of custom // elements. if (shadowRoot.AMP) { user().warn(TAG, "Shadow doc wasn't previously closed"); this.closeShadowRoot_(shadowRoot); } const amp = {}; shadowRoot.AMP = amp; amp.url = url; const {origin} = parseUrlDeprecated(url); const ampdoc = this.ampdocService_.installShadowDoc(url, shadowRoot, { params, }); /** @const {!./service/ampdoc-impl.AmpDocShadow} */ amp.ampdoc = ampdoc; dev().fine(TAG, 'Attach to shadow root:', shadowRoot, ampdoc); // Install runtime CSS. installStylesForDoc( ampdoc, AMP.combinedCss, /* callback */ null, /* opt_isRuntimeCss */ true ); // Instal doc services. AMP.installAmpdocServices(ampdoc); const viewer = Services.viewerForDoc(ampdoc); /** * Sets the document's visibility state. * @param {!VisibilityState} state */ amp['setVisibilityState'] = function(state) { ampdoc.overrideVisibilityState(state); }; // Messaging pipe. /** * Posts message to the ampdoc. * @param {string} eventType * @param {!JsonObject} data * @param {boolean} unusedAwaitResponse * @return {(!Promise<*>|undefined)} */ amp['postMessage'] = viewer.receiveMessage.bind(viewer); /** @type {function(string, *, boolean):(!Promise<*>|undefined)} */ let onMessage; /** * Provides a message delivery mechanism by which AMP document can send * messages to the viewer. * @param {function(string, *, boolean):(!Promise<*>|undefined)} callback */ amp['onMessage'] = function(callback) { onMessage = callback; }; viewer.setMessageDeliverer((eventType, data, awaitResponse) => { // Special messages. if (eventType == 'broadcast') { this.broadcast_(data, shadowRoot); return awaitResponse ? Promise.resolve() : undefined; } // All other messages. if (onMessage) { return onMessage(eventType, data, awaitResponse); } }, origin); /** * Closes the document, resolving when visibility changes and services have * been cleand up. The document can no longer be activated again. * @return {Promise} */ amp['close'] = () => { return this.closeShadowRoot_(shadowRoot); }; if (getMode().development) { amp.toggleRuntime = viewer.toggleRuntime.bind(viewer); amp.resources = Services.resourcesForDoc(ampdoc); } /** * Expose amp-bind getState * @param {string} name - Name of state or deep state * @return {Promise<*>} - Resolves to a copy of the value of a state */ amp['getState'] = name => { return Services.bindForDocOrNull(shadowRoot).then(bind => { if (!bind) { return Promise.reject('amp-bind is not available in this document'); } return bind.getState(name); }); }; /** * Expose amp-bind setState * @param {(!JsonObject|string)} state - State to be set * @return {Promise} - Resolves after state and history have been updated */ amp['setState'] = state => { return Services.bindForDocOrNull(shadowRoot).then(bind => { if (!bind) { return Promise.reject('amp-bind is not available in this document'); } if (typeof state === 'string') { return bind.setStateWithExpression( /** @type {string} */ (state), /** @type {!JsonObject} */ ({}) ); } else if (isObject(state) || isArray(state)) { return bind.setStateWithObject(/** @type {!JsonObject} */ (state)); } return Promise.reject('Invalid state'); }); }; // Start building the shadow doc DOM. builder(amp, shadowRoot, ampdoc).then(() => { // Document is ready. ampdoc.setReady(); ampdoc.signals().signal(CommonSignals.RENDER_START); setStyle(hostElement, 'visibility', 'visible'); }); // Store reference. if (!this.shadowRoots_.includes(shadowRoot)) { this.shadowRoots_.push(shadowRoot); } dev().fine(TAG, 'Shadow root initialization is done:', shadowRoot, ampdoc); return amp; } /** * Implementation for `attachShadowDoc` function. Attaches the shadow doc and * configures ampdoc for it. * @param {!Element} hostElement * @param {!Document} doc * @param {string} url * @param {!Object<string, string>=} opt_initParams * @return {!./runtime.ShadowDoc} */ attachShadowDoc(hostElement, doc, url, opt_initParams) { user().assertString(url); dev().fine(TAG, 'Attach shadow doc:', doc); // TODO(dvoytenko, #9490): once stable, port full document case to emulated // stream. return this.attachShadowDoc_( hostElement, url, opt_initParams, (amp, shadowRoot, ampdoc) => { // Install extensions. const extensionIds = this.mergeShadowHead_(ampdoc, shadowRoot, doc); this.extensions_.installExtensionsInDoc(ampdoc, extensionIds); // Append body. if (doc.body) { const body = importShadowBody(shadowRoot, doc.body, /* deep */ true); body.classList.add('amp-shadow'); ampdoc.setBody(body); } // TODO(dvoytenko): find a better and more stable way to make content // visible. E.g. integrate with dynamic classes. In shadow case // specifically, we have to wait for stubbing to complete, which may // take awhile due to importNode. setTimeout(() => { ampdoc.signals().signal(CommonSignals.RENDER_START); setStyle(hostElement, 'visibility', 'visible'); }, 50); return Promise.resolve(); } ); } /** * Implementation for `attachShadowDocAsStream` function. Attaches the shadow * doc and configures ampdoc for it. * @param {!Element} hostElement * @param {string} url * @param {!Object<string, string>=} opt_initParams * @return {!Object} */ attachShadowDocAsStream(hostElement, url, opt_initParams) { user().assertString(url); dev().fine(TAG, 'Attach shadow doc as stream'); return this.attachShadowDoc_( hostElement, url, opt_initParams, (amp, shadowRoot, ampdoc) => { // Start streaming. let renderStarted = false; const writer = createShadowDomWriter(this.win); amp['writer'] = writer; writer.onBody(doc => { // Install extensions. const extensionIds = this.mergeShadowHead_(ampdoc, shadowRoot, doc); // Apply all doc extensions. this.extensions_.installExtensionsInDoc(ampdoc, extensionIds); // Append shallow body. const body = importShadowBody( shadowRoot, dev().assertElement(doc.body), /* deep */ false ); body.classList.add('amp-shadow'); ampdoc.setBody(body); return body; }); writer.onBodyChunk(() => { // TODO(dvoytenko): find a better and more stable way to make // content visible. E.g. integrate with dynamic classes. In shadow // case specifically, we have to wait for stubbing to complete, // which may take awhile due to node importing. if (!renderStarted) { renderStarted = true; setTimeout(() => { ampdoc.signals().signal(CommonSignals.RENDER_START); setStyle(hostElement, 'visibility', 'visible'); }, 50); } }); return new Promise(resolve => { writer.onEnd(() => { resolve(); amp.writer = null; }); }); } ); } /** * Processes the contents of the shadow document's head. * @param {!./service/ampdoc-impl.AmpDoc} ampdoc * @param {!ShadowRoot} shadowRoot * @param {!Document} doc * @return {!Array<string>} * @private */ mergeShadowHead_(ampdoc, shadowRoot, doc) { const extensionIds = []; if (doc.head) { shadowRoot.AMP.head = doc.head; const parentLinks = {}; const links = childElementsByTag( dev().assertElement(this.win.document.head), 'link' ); for (let i = 0; i < links.length; i++) { const href = links[i].getAttribute('href'); if (href) { parentLinks[href] = true; } } for (let n = doc.head.firstElementChild; n; n = n.nextElementSibling) { const {tagName} = n; const name = n.getAttribute('name'); const rel = n.getAttribute('rel'); switch (tagName) { case 'TITLE': shadowRoot.AMP.title = n.textContent; dev().fine(TAG, '- set title: ', shadowRoot.AMP.title); break; case 'META': if (n.hasAttribute('charset')) { // Ignore. } else if (name == 'viewport') { // Ignore. } else if (name) { // Store meta name/content pairs. ampdoc.setMetaByName(name, n.getAttribute('content') || ''); } else { // TODO(dvoytenko): copy other meta tags. dev().warn(TAG, 'meta ignored: ', n); } break; case 'LINK': /** @const {string} */ const href = n.getAttribute('href'); if (rel == 'canonical') { shadowRoot.AMP.canonicalUrl = href; dev().fine(TAG, '- set canonical: ', shadowRoot.AMP.canonicalUrl); } else if (rel == 'stylesheet') { // Must be a font definition: no other stylesheets are allowed. if (parentLinks[href]) { dev().fine(TAG, '- stylesheet already included: ', href); } else { parentLinks[href] = true; const el = this.win.document.createElement('link'); el.setAttribute('rel', 'stylesheet'); el.setAttribute('type', 'text/css'); el.setAttribute('href', href); this.win.document.head.appendChild(el); dev().fine(TAG, '- import font to parent: ', href, el); } } else { dev().fine(TAG, '- ignore link rel=', rel); } break; case 'STYLE': if (n.hasAttribute('amp-boilerplate')) { // Ignore. dev().fine(TAG, '- ignore boilerplate style: ', n); } else if (n.hasAttribute('amp-custom')) { installStylesForDoc( ampdoc, n.textContent, /* callback */ null, /* isRuntimeCss */ false, 'amp-custom' ); dev().fine(TAG, '- import style: ', n); } else if (n.hasAttribute('amp-keyframes')) { installStylesForDoc( ampdoc, n.textContent, /* callback */ null, /* isRuntimeCss */ false, 'amp-keyframes' ); dev().fine(TAG, '- import style: ', n); } break; case 'SCRIPT': if (n.hasAttribute('src')) { dev().fine(TAG, '- src script: ', n); const src = n.getAttribute('src'); const isRuntime = src.indexOf('/amp.js') != -1 || src.indexOf('/v0.js') != -1; // Note: Some extensions don't have [custom-element] or // [custom-template] e.g. amp-viewer-integration. const customElement = n.getAttribute('custom-element'); const customTemplate = n.getAttribute('custom-template'); const versionRe = /-(\d+.\d+)(.max)?\.js$/; const match = versionRe.exec(src); const version = match ? match[1] : '0.1'; if (isRuntime) { dev().fine(TAG, '- ignore runtime script: ', src); } else if (customElement || customTemplate) { // This is an extension. this.extensions_.installExtensionForDoc( ampdoc, customElement || customTemplate, version ); dev().fine( TAG, '- load extension: ', customElement || customTemplate, ' ', version ); if (customElement) { extensionIds.push(customElement); } } else if (!n.hasAttribute('data-amp-report-test')) { user().error(TAG, '- unknown script: ', n, src); } } else { // Non-src version of script. const type = n.getAttribute('type') || 'application/javascript'; if (type.indexOf('javascript') == -1) { shadowRoot.appendChild(this.win.document.importNode(n, true)); dev().fine(TAG, '- non-src script: ', n); } else { user().error(TAG, '- unallowed inline javascript: ', n); } } break; case 'NOSCRIPT': // Ignore. break; default: user().error(TAG, '- UNKNOWN head element:', n); break; } } } return extensionIds; } /** * @param {*} data * @param {!ShadowRoot} sender * @private */ broadcast_(data, sender) { this.purgeShadowRoots_(); this.shadowRoots_.forEach(shadowRoot => { if (shadowRoot == sender) { // Don't broadcast to the sender. return; } // Broadcast message asynchronously. const viewer = Services.viewerForDoc(shadowRoot.AMP.ampdoc); this.timer_.delay(() => { viewer.receiveMessage( 'broadcast', /** @type {!JsonObject} */ (data), /* awaitResponse */ false ); }, 0); }); } /** * @param {!ShadowRoot} shadowRoot * @return {Promise} * @private */ closeShadowRoot_(shadowRoot) { this.removeShadowRoot_(shadowRoot); const amp = shadowRoot.AMP; delete shadowRoot.AMP; const {ampdoc} = amp; ampdoc.overrideVisibilityState(VisibilityState.INACTIVE); disposeServicesForDoc(ampdoc); // There is a race between the visibility state change finishing and // resources.onNextPass firing, but this is intentional. closeShadowRoot_ // was traditionally introduced as a synchronous method, so PWAs in the wild // do not expect to have to wait for a promise to resolve before the shadow // is deemed 'closed'. Moving .overrideVisibilityState() and // disposeServicesForDoc inside a promise could adversely affect sites that // depend on at least the synchronous portions of those methods completing // before proceeding. The promise race is designed to be very quick so that // even if the pass callback completes before resources.onNextPass is called // below, we only delay promise resolution by a few ms. return this.timer_ .timeoutPromise( 15, // Delay for queued pass after visibility change is 10ms new this.win.Promise(resolve => { getServicePromiseOrNullForDoc(ampdoc, 'resources').then(resources => { if (resources) { resources.onNextPass(resolve); } else { resolve(); } }); }), 'Timeout reached waiting for visibility state change callback' ) .catch(error => { user().info(TAG, error); }); } /** * @param {!ShadowRoot} shadowRoot * @private */ removeShadowRoot_(shadowRoot) { const index = this.shadowRoots_.indexOf(shadowRoot); if (index != -1) { this.shadowRoots_.splice(index, 1); } } /** * @param {!ShadowRoot} shadowRoot * @private */ closeShadowRootAsync_(shadowRoot) { this.timer_.delay(() => { this.closeShadowRoot_(shadowRoot); }, 0); } /** @private */ purgeShadowRoots_() { this.shadowRoots_.forEach(shadowRoot => { // The shadow root has been disconnected. Force it closed. if (!shadowRoot.host || !isConnectedNode(shadowRoot.host)) { user().warn(TAG, "Shadow doc wasn't previously closed"); this.removeShadowRoot_(shadowRoot); this.closeShadowRootAsync_(shadowRoot); } }); } }
cory-work/amphtml
src/multidoc-manager.js
JavaScript
apache-2.0
19,226
/* * Copyright 2015-2016 USEF Foundation * * 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 energy.usef.dso.workflow.step; import energy.usef.core.workflow.WorkflowContext; import energy.usef.core.workflow.WorkflowStep; import energy.usef.dso.pbcfeederimpl.PbcFeederService; import energy.usef.dso.workflow.operate.DsoLimitConnectionsStepParameter; import java.util.Random; import javax.inject.Inject; import org.joda.time.LocalDate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * DsoLimitConnectionsStub. */ public class DsoLimitConnectionsStub implements WorkflowStep { private static final Logger LOGGER = LoggerFactory.getLogger(DsoLimitConnectionsStub.class); private static final int LOWER_PERCENTAGE = 50; private static final int UPPER_PERCENTAGE = 75; private static final double HUDRED_PERCENT = 100d; private static final int LIMITATION_DURATION_IN_PTUS = 1; @Inject private PbcFeederService pbcFeederService; /** * {@inheritDoc} */ @Override public WorkflowContext invoke(WorkflowContext context) { LOGGER.debug("Starting workflow step 'Limit Connections'."); String congestionPointEntityAddress = (String) context.getValue( DsoLimitConnectionsStepParameter.IN.CONGESTION_POINT_ENTITY_ADDRESS.name()); LocalDate period = (LocalDate) context.getValue(DsoLimitConnectionsStepParameter.IN.PERIOD.name()); Integer ptuIndex = (Integer) context.getValue(DsoLimitConnectionsStepParameter.IN.PTU_INDEX.name()); LOGGER.debug("Parameters in the context : congestion point=[{}], period=[{}], ptu index=[{}]", congestionPointEntityAddress, period, ptuIndex); context.setValue(DsoLimitConnectionsStepParameter.OUT.POWER_DECREASE.name(), Math.round(determineMaximumLoad(congestionPointEntityAddress, period, ptuIndex))); LOGGER.debug("Ending successfully workflow step 'Limit Connections'."); return context; } private double determineMaximumLoad(String congestionPointEntityAddress, LocalDate period, Integer ptuIndex) { double uncontrolledLoad = pbcFeederService.getUncontrolledLoad(congestionPointEntityAddress, period, ptuIndex, LIMITATION_DURATION_IN_PTUS); double upperdBound = (UPPER_PERCENTAGE / HUDRED_PERCENT) * uncontrolledLoad; double lowerBound = (LOWER_PERCENTAGE / HUDRED_PERCENT) * uncontrolledLoad; return lowerBound + ((upperdBound - lowerBound) * new Random().nextDouble()); } }
USEF-Foundation/ri.usef.energy
usef-build/usef-simulation/usef-simulation-dso/src/main/java/energy/usef/dso/workflow/step/DsoLimitConnectionsStub.java
Java
apache-2.0
3,060
/* * Copyright 2002-2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.beans.factory.xml; import junit.framework.TestCase; import org.springframework.beans.ITestBean; import org.springframework.beans.TestBean; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.core.io.ClassPathResource; /** * @author Rob Harrop * @author Juergen Hoeller */ public class ShortcutTests extends TestCase { public void testSimpleBeanConfigured() throws Exception { XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("shortcutTests.xml", getClass())); ITestBean rob = (TestBean) beanFactory.getBean("rob"); ITestBean sally = (TestBean) beanFactory.getBean("sally"); assertEquals("Rob Harrop", rob.getName()); assertEquals(24, rob.getAge()); assertEquals(rob.getSpouse(), sally); } public void testInnerBeanConfigured() throws Exception { XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("shortcutTests.xml", getClass())); TestBean sally = (TestBean) beanFactory.getBean("sally2"); ITestBean rob = (TestBean) sally.getSpouse(); assertEquals("Rob Harrop", rob.getName()); assertEquals(24, rob.getAge()); assertEquals(rob.getSpouse(), sally); } public void testWithPropertyDefinedTwice() throws Exception { try { new XmlBeanFactory(new ClassPathResource("shortcutTestsWithErrors.xml", getClass())); fail("Should not be able to load a file with property specified twice."); } catch (BeanDefinitionStoreException e) { // success } } public void testPropertyWithNameEndingInRef() throws Exception { XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("shortcutTests.xml", getClass())); ITestBean sally = (TestBean) beanFactory.getBean("derivedSally"); assertEquals("r", sally.getSpouse().getName()); } }
cbeams-archive/spring-framework-2.5.x
test/org/springframework/beans/factory/xml/ShortcutTests.java
Java
apache-2.0
2,428
# Copyright 2014 PerfKitBenchmarker Authors. 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. """Class to represent a Static Virtual Machine object. All static VMs provided in a given group will be used before any non-static VMs are provisioned. For example, in a test that uses 4 VMs, if 3 static VMs are provided, all of them will be used and one additional non-static VM will be provisioned. The VM's should be set up with passwordless ssh and passwordless sudo (neither sshing nor running a sudo command should prompt the user for a password). All VM specifics are self-contained and the class provides methods to operate on the VM: boot, shutdown, etc. """ import collections import json import logging import threading from perfkitbenchmarker import disk from perfkitbenchmarker import flags from perfkitbenchmarker import linux_virtual_machine from perfkitbenchmarker import virtual_machine from perfkitbenchmarker import windows_virtual_machine WINDOWS = 'windows' DEBIAN = 'debian' RHEL = 'rhel' UBUNTU_CONTAINER = 'ubuntu_container' FLAGS = flags.FLAGS class StaticVmSpec(virtual_machine.BaseVmSpec): """Object containing all info needed to create a Static VM.""" def __init__(self, ip_address=None, user_name=None, ssh_private_key=None, internal_ip=None, ssh_port=22, install_packages=True, password=None, disk_specs=None, os_type=None, **kwargs): """Initialize the StaticVmSpec object. Args: ip_address: The public ip address of the VM. user_name: The username of the VM that the keyfile corresponds to. ssh_private_key: The absolute path to the private keyfile to use to ssh to the VM. internal_ip: The internal ip address of the VM. ssh_port: The port number to use for SSH and SCP commands. install_packages: If false, no packages will be installed. This is useful if benchmark dependencies have already been installed. password: The password used to log into the VM (Windows Only). disk_specs: A list of dictionaries containing kwargs used to create disk.BaseDiskSpecs. os_type: The OS type of the VM. See the flag of the same name for more information. """ super(StaticVmSpec, self).__init__(**kwargs) self.ip_address = ip_address self.user_name = user_name self.ssh_private_key = ssh_private_key self.internal_ip = internal_ip self.ssh_port = ssh_port self.install_packages = install_packages self.password = password self.os_type = os_type self.disk_specs = disk_specs class StaticDisk(disk.BaseDisk): """Object representing a static Disk.""" def _Create(self): """StaticDisks don't implement _Create().""" pass def _Delete(self): """StaticDisks don't implement _Delete().""" pass def Attach(self): """StaticDisks don't implement Attach().""" pass def Detach(self): """StaticDisks don't implement Detach().""" pass class StaticVirtualMachine(virtual_machine.BaseVirtualMachine): """Object representing a Static Virtual Machine.""" is_static = True vm_pool = collections.deque() vm_pool_lock = threading.Lock() def __init__(self, vm_spec): """Initialize a static virtual machine. Args: vm_spec: A StaticVmSpec object containing arguments. """ super(StaticVirtualMachine, self).__init__(vm_spec, None, None) self.ip_address = vm_spec.ip_address self.user_name = vm_spec.user_name self.ssh_private_key = vm_spec.ssh_private_key self.internal_ip = vm_spec.internal_ip self.zone = self.zone or ('Static - %s@%s' % (self.user_name, self.ip_address)) self.ssh_port = vm_spec.ssh_port self.install_packages = vm_spec.install_packages self.password = vm_spec.password if vm_spec.disk_specs: for spec in vm_spec.disk_specs: self.disk_specs.append(disk.BaseDiskSpec(**spec)) self.from_pool = False def _Create(self): """StaticVirtualMachines do not implement _Create().""" pass def _Delete(self): """Returns the virtual machine to the pool.""" if self.from_pool: with self.vm_pool_lock: self.vm_pool.appendleft(self) def CreateScratchDisk(self, disk_spec): """Create a VM's scratch disk. Args: disk_spec: virtual_machine.BaseDiskSpec object of the disk. """ spec = self.disk_specs[len(self.scratch_disks)] self.scratch_disks.append(StaticDisk(spec)) def DeleteScratchDisks(self): """StaticVirtualMachines do not delete scratch disks.""" pass def GetLocalDisks(self): """Returns a list of local disks on the VM.""" return [disk_spec.device_path for disk_spec in self.disk_specs if disk_spec.device_path] @classmethod def ReadStaticVirtualMachineFile(cls, file_obj): """Read a file describing the static VMs to use. This function will read the static VM information from the provided file, instantiate VMs corresponding to the info, and add the VMs to the static VM pool. The provided file should contain a single array in JSON-format. Each element in the array must be an object with required format: ip_address: string. user_name: string. keyfile_path: string. ssh_port: integer, optional. Default 22 internal_ip: string, optional. zone: string, optional. local_disks: array of strings, optional. scratch_disk_mountpoints: array of strings, optional os_type: string, optional (see package_managers) install_packages: bool, optional Args: file_obj: An open handle to a file containing the static VM info. Raises: ValueError: On missing required keys, or invalid keys. """ vm_arr = json.load(file_obj) if not isinstance(vm_arr, list): raise ValueError('Invalid static VM file. Expected array, got: %s.' % type(vm_arr)) required_keys = frozenset(['ip_address', 'user_name']) linux_required_keys = required_keys | frozenset(['keyfile_path']) required_keys_by_os = { WINDOWS: required_keys | frozenset(['password']), DEBIAN: linux_required_keys, RHEL: linux_required_keys, UBUNTU_CONTAINER: linux_required_keys, } required_keys = required_keys_by_os[FLAGS.os_type] optional_keys = frozenset(['internal_ip', 'zone', 'local_disks', 'scratch_disk_mountpoints', 'os_type', 'ssh_port', 'install_packages']) allowed_keys = required_keys | optional_keys def VerifyItemFormat(item): """Verify that the decoded JSON object matches the required schema.""" item_keys = frozenset(item) extra_keys = sorted(item_keys - allowed_keys) missing_keys = required_keys - item_keys if extra_keys: raise ValueError('Unexpected keys: {0}'.format(', '.join(extra_keys))) elif missing_keys: raise ValueError('Missing required keys: {0}'.format( ', '.join(missing_keys))) for item in vm_arr: VerifyItemFormat(item) ip_address = item['ip_address'] user_name = item['user_name'] keyfile_path = item.get('keyfile_path') internal_ip = item.get('internal_ip') zone = item.get('zone') local_disks = item.get('local_disks', []) password = item.get('password') if not isinstance(local_disks, list): raise ValueError('Expected a list of local disks, got: {0}'.format( local_disks)) scratch_disk_mountpoints = item.get('scratch_disk_mountpoints', []) if not isinstance(scratch_disk_mountpoints, list): raise ValueError( 'Expected a list of disk mount points, got: {0}'.format( scratch_disk_mountpoints)) ssh_port = item.get('ssh_port', 22) os_type = item.get('os_type') install_packages = item.get('install_packages', True) if ((os_type == WINDOWS and FLAGS.os_type != WINDOWS) or (os_type != WINDOWS and FLAGS.os_type == WINDOWS)): raise ValueError('Please only use Windows VMs when using ' '--os_type=windows and vice versa.') disk_kwargs_list = [] for path in scratch_disk_mountpoints: disk_kwargs_list.append({'mount_point': path}) for local_disk in local_disks: disk_kwargs_list.append({'device_path': local_disk}) vm_spec = StaticVmSpec( ip_address=ip_address, user_name=user_name, ssh_port=ssh_port, install_packages=install_packages, ssh_private_key=keyfile_path, internal_ip=internal_ip, zone=zone, disk_specs=disk_kwargs_list, password=password) vm_class = GetStaticVmClass(os_type) vm = vm_class(vm_spec) cls.vm_pool.append(vm) @classmethod def GetStaticVirtualMachine(cls): """Pull a Static VM from the pool of static VMs. If there are no VMs left in the pool, the method will return None. Returns: A static VM from the pool, or None if there are no static VMs left. """ with cls.vm_pool_lock: if cls.vm_pool: vm = cls.vm_pool.popleft() vm.from_pool = True return vm else: return None def GetStaticVmClass(os_type): """Returns the static VM class that corresponds to the os_type.""" class_dict = { DEBIAN: DebianBasedStaticVirtualMachine, RHEL: RhelBasedStaticVirtualMachine, WINDOWS: WindowsBasedStaticVirtualMachine, UBUNTU_CONTAINER: ContainerizedStaticVirtualMachine, } if os_type in class_dict: return class_dict[os_type] else: logging.warning('Could not find os type for VM. Defaulting to debian.') return DebianBasedStaticVirtualMachine class ContainerizedStaticVirtualMachine( StaticVirtualMachine, linux_virtual_machine.ContainerizedDebianMixin): pass class DebianBasedStaticVirtualMachine(StaticVirtualMachine, linux_virtual_machine.DebianMixin): pass class RhelBasedStaticVirtualMachine(StaticVirtualMachine, linux_virtual_machine.RhelMixin): pass class WindowsBasedStaticVirtualMachine(StaticVirtualMachine, windows_virtual_machine.WindowsMixin): pass
syed/PerfKitBenchmarker
perfkitbenchmarker/static_virtual_machine.py
Python
apache-2.0
10,858
/* * Copyright 2012-2016 the Flamingo Community. * * 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. */ Ext.ns('Flamingo.view.workflowdesigner.shape'); Ext.ns('Flamingo.view.workflowdesigner.shape.ankus'); Ext.ns('Flamingo.view.workflowdesigner.shape.bpmn'); Ext.ns('Flamingo.view.workflowdesigner.shape.etl'); Ext.ns('Flamingo.view.workflowdesigner.shape.giraph'); Ext.ns('Flamingo.view.workflowdesigner.shape.mahout'); Ext.ns('Flamingo.view.workflowdesigner.shape.rules'); Ext.ns('Flamingo.view.workflowdesigner.shape.gis'); /** * Workflow Designer의 각 모듈과 서버 사이드에 정의된 모듈과 통신하기 위해서는 * applicationContext-activiti.xml에 taskProps ID가 정의되어 있어야 실행이 가능하다. * * @type {string[]} */ var shapes = [ // TODO : 추후 다른 컴포넌트도 추가 필요 'Flamingo.view.workflowdesigner.shape.OOZIE_DECISION', 'Flamingo.view.workflowdesigner.shape.OOZIE_FORK', 'Flamingo.view.workflowdesigner.shape.OOZIE_JOIN', 'Flamingo.view.workflowdesigner.shape.OOZIE_SUBWORKFLOW', 'Flamingo.view.workflowdesigner.shape.OOZIE_KILL', 'Flamingo.view.workflowdesigner.shape.OOZIE_MAPREDUCE', 'Flamingo.view.workflowdesigner.shape.OOZIE_DISTCP', 'Flamingo.view.workflowdesigner.shape.OOZIE_SHELL', 'Flamingo.view.workflowdesigner.shape.OOZIE_SSH', 'Flamingo.view.workflowdesigner.shape.OOZIE_EMAIL', 'Flamingo.view.workflowdesigner.shape.OOZIE_SPARK', 'Flamingo.view.workflowdesigner.shape.OOZIE_SQOOP', 'Flamingo.view.workflowdesigner.shape.OOZIE_FS' ]; for (var i = 0; i < shapes.length; i++) { var text = shapes[i]; var splitText = shapes[i].split('.'); var alias = splitText[splitText.length - 1]; var ref = (splitText.length == 5) ? alias : splitText[splitText.length - 2] + "." + [alias]; makeShape(ref, alias, text); } // ref function makeShape(ref, alias, text) { var refArr = ref.split('.'); if (refArr.length == 1) { Flamingo.view.workflowdesigner.shape[ref] = function (image, label) { Flamingo[alias].superclass.call(this, image, label); this.SHAPE_ID = text; }; Flamingo.view.workflowdesigner.shape[ref].prototype = new OG.shape.ImageShape(); Flamingo.view.workflowdesigner.shape[ref].superclass = OG.shape.ImageShape; Flamingo.view.workflowdesigner.shape[ref].prototype.constructor = text; Flamingo.view.workflowdesigner.shape[ref].className = text; Flamingo[alias] = Flamingo.view.workflowdesigner.shape[ref]; } else if (refArr.length == 2) { Flamingo.view.workflowdesigner.shape[refArr[0]][refArr[1]] = function (image, label) { Flamingo[alias].superclass.call(this, image, label); this.SHAPE_ID = text; }; Flamingo.view.workflowdesigner.shape[refArr[0]][refArr[1]].prototype = new OG.shape.ImageShape(); Flamingo.view.workflowdesigner.shape[refArr[0]][refArr[1]].superclass = OG.shape.ImageShape; Flamingo.view.workflowdesigner.shape[refArr[0]][refArr[1]].prototype.constructor = text; Flamingo.view.workflowdesigner.shape[refArr[0]][refArr[1]].className = text; Flamingo[alias] = Flamingo.view.workflowdesigner.shape[refArr[0]][refArr[1]]; } } Ext.define('Flamingo.view.workflowdesigner.canvas.Canvas', { extend: 'Ext.form.Panel', alias: 'widget.canvas', /** * Workflow Designer의 UI 노드 */ requires: [ 'Flamingo.view.workflowdesigner.canvas.CanvasController', // 'Flamingo.view.workflowdesigner.property.OOZIE_DECISION', // 'Flamingo.view.workflowdesigner.property.OOZIE_FORK', // 'Flamingo.view.workflowdesigner.property.OOZIE_JOIN', // 'Flamingo.view.workflowdesigner.property.OOZIE_SUBWORKFLOW', // 'Flamingo.view.workflowdesigner.property.OOZIE_KILL', 'Flamingo.view.workflowdesigner.property.OOZIE_MAPREDUCE', // 'Flamingo.view.workflowdesigner.property.OOZIE_DISTCP', 'Flamingo.view.workflowdesigner.property.OOZIE_SHELL', // 'Flamingo.view.workflowdesigner.property.OOZIE_SSH', // 'Flamingo.view.workflowdesigner.property.OOZIE_EMAIL', 'Flamingo.view.workflowdesigner.property.OOZIE_SPARK', 'Flamingo.view.workflowdesigner.property.OOZIE_SQOOP' // 'Flamingo.view.workflowdesigner.property.OOZIE_FS' ], controller: 'canvasController', layout: 'fit', autoScroll: true, forceLayout: true, cls: 'canvas_contents', graph: null, dockedItems: [ { xtype: 'toolbar', dock: 'top', items: [ { xtype: 'textfield', width: 400, labelWidth: 100, maxLength: 100, fieldLabel: 'Workflow name', id: 'wd_fld_name', name: 'name', emptyText: 'Enter a Workflow name.', allowBlank: false }, { xtype: 'hidden', id: 'wd_fld_id', name: 'id', allowBlank: true }, { xtype: 'hidden', id: 'wd_fld_tree_id', name: 'tree_id', allowBlank: true }, { xtype: 'hidden', id: 'wd_fld_status', name: 'status', allowBlank: true }, { xtype: 'hidden', id: 'wd_fld_process_id', name: 'process_id', allowBlank: true }, { xtype: 'hidden', id: 'wd_fld_process_definition_id', name: 'process_definition_id', allowBlank: true }, { xtype: 'hidden', id: 'wd_fld_deployment_id', name: 'deployment_id', allowBlank: true }, { xtype: 'hidden', id: 'wd_fld_desc', name: 'desc', allowBlank: true } ] }, { xtype: 'toolbar', dock: 'top', items: [ { id: 'wd_btn_create', text: 'New', iconCls: 'common-new', listeners: { click: 'onCreateClick' } }, { id: 'wd_btn_save', text: 'Save', iconCls: 'common-save', listeners: { click: 'onSaveClick' } }, { id: 'wd_btn_run', text: 'Run', iconCls: 'common-execute', disabled: true, listeners: { click: 'onRunClick' } }, { id: 'wd_btn_action', text: 'Action', iconCls: 'common-execute', listeners: { click: 'onActionClick' } }, // '-', { id: 'wd_btn_xml', text: 'View', iconCls: 'hdfs-directory-info', disabled: true, hidden: true, listeners: { click: 'onWorkflowXMLClick' } }, // '-', { id: 'wd_btn_copy', text: 'Copy', iconCls: 'common-file-copy', disabled: true, listeners: { click: 'onWorkflowCopyClick' } } ] } ], listeners: { highlightById: 'highlightById', unhighlightById: 'unhighlightById', getwiredIdByElement: 'getwiredIdByElement', setwireEvent: 'setwireEvent', setwireEventAll: 'setwireEventAll', render: 'onCanvasRender', resize: 'onCanvasResize', nodeBeforeConnect: 'onCanvasNodeBeforeConnect', nodeConnect: 'onCanvasNodeConnect', nodeDisconnected: 'onCanvasNodeDisconnected', nodeBeforeRemove: 'onCanvasNodeBeforeRemove', beforeLabelChange: 'onCanvasBeforeLabelChange', labelChanged: 'onCanvasLabelChanged' }, highlightById: function (elementId) { this.fireEvent('highlightById', elementId); }, unhighlightById: function (elementId) { this.fireEvent('unhighlightById', elementId); }, setwireEvent: function (shapeElement) { this.fireEvent('setwireEvent', shapeElement); }, setwireEventAll: function () { this.fireEvent('setwireEventAll'); } });
hyokun31/wisekb-management-platform
wisekb-web/src/main/webapp/flamingo/app/view/workflowdesigner/canvas/Canvas.js
JavaScript
apache-2.0
9,828
# Copyright 2012 OpenStack Foundation # 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. from oslo_middleware import request_id import webob from tacker import auth from tacker.tests import base class TackerKeystoneContextTestCase(base.BaseTestCase): def setUp(self): super(TackerKeystoneContextTestCase, self).setUp() @webob.dec.wsgify def fake_app(req): self.context = req.environ['tacker.context'] return webob.Response() self.context = None self.middleware = auth.TackerKeystoneContext(fake_app) self.request = webob.Request.blank('/') self.request.headers['X_AUTH_TOKEN'] = 'testauthtoken' def test_no_user_id(self): self.request.headers['X_PROJECT_ID'] = 'testtenantid' response = self.request.get_response(self.middleware) self.assertEqual(response.status, '401 Unauthorized') def test_with_user_id(self): self.request.headers['X_PROJECT_ID'] = 'testtenantid' self.request.headers['X_USER_ID'] = 'testuserid' response = self.request.get_response(self.middleware) self.assertEqual(response.status, '200 OK') self.assertEqual(self.context.user_id, 'testuserid') self.assertEqual(self.context.user, 'testuserid') def test_with_tenant_id(self): self.request.headers['X_PROJECT_ID'] = 'testtenantid' self.request.headers['X_USER_ID'] = 'test_user_id' response = self.request.get_response(self.middleware) self.assertEqual(response.status, '200 OK') self.assertEqual(self.context.tenant_id, 'testtenantid') self.assertEqual(self.context.tenant, 'testtenantid') def test_roles_no_admin(self): self.request.headers['X_PROJECT_ID'] = 'testtenantid' self.request.headers['X_USER_ID'] = 'testuserid' self.request.headers['X_ROLES'] = 'role1, role2 , role3,role4,role5' response = self.request.get_response(self.middleware) self.assertEqual(response.status, '200 OK') self.assertEqual(self.context.roles, ['role1', 'role2', 'role3', 'role4', 'role5']) self.assertEqual(self.context.is_admin, False) def test_roles_with_admin(self): self.request.headers['X_PROJECT_ID'] = 'testtenantid' self.request.headers['X_USER_ID'] = 'testuserid' self.request.headers['X_ROLES'] = ('role1, role2 , role3,role4,role5,' 'AdMiN') response = self.request.get_response(self.middleware) self.assertEqual(response.status, '200 OK') self.assertEqual(self.context.roles, ['role1', 'role2', 'role3', 'role4', 'role5', 'AdMiN']) self.assertEqual(self.context.is_admin, True) def test_with_user_tenant_name(self): self.request.headers['X_PROJECT_ID'] = 'testtenantid' self.request.headers['X_USER_ID'] = 'testuserid' self.request.headers['X_PROJECT_NAME'] = 'testtenantname' self.request.headers['X_USER_NAME'] = 'testusername' response = self.request.get_response(self.middleware) self.assertEqual(response.status, '200 OK') self.assertEqual(self.context.user_id, 'testuserid') self.assertEqual(self.context.user_name, 'testusername') self.assertEqual(self.context.tenant_id, 'testtenantid') self.assertEqual(self.context.tenant_name, 'testtenantname') def test_request_id_extracted_from_env(self): req_id = 'dummy-request-id' self.request.headers['X_PROJECT_ID'] = 'testtenantid' self.request.headers['X_USER_ID'] = 'testuserid' self.request.environ[request_id.ENV_REQUEST_ID] = req_id self.request.get_response(self.middleware) self.assertEqual(req_id, self.context.request_id)
priya-pp/Tacker
tacker/tests/unit/test_auth.py
Python
apache-2.0
4,418
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInsight.daemon.quickFix; import com.intellij.JavaTestUtil; import com.intellij.codeInspection.LocalInspectionTool; import com.intellij.codeInspection.javaDoc.JavaDocReferenceInspection; import com.intellij.openapi.projectRoots.JavaSdkVersion; import com.intellij.testFramework.IdeaTestUtil; import com.intellij.testFramework.LightProjectDescriptor; import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase; import org.jetbrains.annotations.NotNull; public class SuppressModuleInfoInspectionsTest extends LightCodeInsightFixtureTestCase { public void testModuleInfo() { // need to set jdk version here because it is not set correctly in the mock jdk which causes problems in // com.intellij.codeInspection.JavaSuppressionUtil#canHave15Suppressions() IdeaTestUtil.setTestVersion(JavaSdkVersion.JDK_1_9, myFixture.getModule(), getTestRootDisposable()); final LocalInspectionTool inspection = new JavaDocReferenceInspection(); myFixture.enableInspections(inspection); myFixture.configureByFile("module-info.java"); myFixture.testHighlighting(); myFixture.launchAction(myFixture.findSingleIntention("Suppress for module declaration")); myFixture.checkResultByFile("module-info.after.java"); } @Override protected String getTestDataPath() { return JavaTestUtil.getJavaTestDataPath() + "/codeInsight/daemonCodeAnalyzer/quickFix/suppressModuleInfoInspections"; } @NotNull @Override protected LightProjectDescriptor getProjectDescriptor() { return JAVA_9; } }
FHannes/intellij-community
java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/SuppressModuleInfoInspectionsTest.java
Java
apache-2.0
2,162
/* ============================================================================ Author : Ztiany Description : 标准输入输出 ============================================================================ */ #include <iostream> using namespace std; int main() { string line; cin.getline(line); //最后换行丢弃 cin.get(buf, 256); //不会读最后换行 return 0; }
Ztiany/CodeRepository
C&C++/cpp-program/010-io/06_stdio.cpp
C++
apache-2.0
404
--- layout: vakit_dashboard title: GHAZNI, AFGANISTAN için iftar, namaz vakitleri ve hava durumu - ilçe/eyalet seç permalink: /AFGANISTAN/GHAZNI/ --- <script type="text/javascript"> var GLOBAL_COUNTRY = 'AFGANISTAN'; var GLOBAL_CITY = 'GHAZNI'; var GLOBAL_STATE = ''; var lat = 72; var lon = 21; </script>
hakanu/iftar
_posts_/vakit/AFGANISTAN/GHAZNI/2017-02-01-.markdown
Markdown
apache-2.0
320
/* * Copyright 2014, The Sporting Exchange Limited * Copyright 2015, Simon Matić Langford * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.betfair.cougar.core.api; import com.betfair.cougar.core.api.ev.OperationKey; public interface OperationBindingDescriptor { /** * Get the key values of the Operation (service name, service version and operation name) * @return */ OperationKey getOperationKey(); }
betfair/cougar
cougar-framework/cougar-core-api/src/main/java/com/betfair/cougar/core/api/OperationBindingDescriptor.java
Java
apache-2.0
954
//===- LoopPass.cpp - Loop Pass and Loop Pass Manager ---------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements LoopPass and LPPassManager. All loop optimization // and transformation passes are derived from LoopPass. LPPassManager is // responsible for managing LoopPasses. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/LoopPass.h" #include "llvm/Analysis/LoopAnalysisManager.h" #include "llvm/IR/Dominators.h" #include "llvm/IR/IRPrintingPasses.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/OptBisect.h" #include "llvm/IR/PassManager.h" #include "llvm/IR/PassTimingInfo.h" #include "llvm/IR/StructuralHash.h" #include "llvm/InitializePasses.h" #include "llvm/Support/Debug.h" #include "llvm/Support/TimeProfiler.h" #include "llvm/Support/Timer.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; #define DEBUG_TYPE "loop-pass-manager" namespace { /// PrintLoopPass - Print a Function corresponding to a Loop. /// class PrintLoopPassWrapper : public LoopPass { raw_ostream &OS; std::string Banner; public: static char ID; PrintLoopPassWrapper() : LoopPass(ID), OS(dbgs()) {} PrintLoopPassWrapper(raw_ostream &OS, const std::string &Banner) : LoopPass(ID), OS(OS), Banner(Banner) {} void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesAll(); } bool runOnLoop(Loop *L, LPPassManager &) override { auto BBI = llvm::find_if(L->blocks(), [](BasicBlock *BB) { return BB; }); if (BBI != L->blocks().end() && isFunctionInPrintList((*BBI)->getParent()->getName())) { printLoop(*L, OS, Banner); } return false; } StringRef getPassName() const override { return "Print Loop IR"; } }; char PrintLoopPassWrapper::ID = 0; } //===----------------------------------------------------------------------===// // LPPassManager // char LPPassManager::ID = 0; LPPassManager::LPPassManager() : FunctionPass(ID), PMDataManager() { LI = nullptr; CurrentLoop = nullptr; } // Insert loop into loop nest (LoopInfo) and loop queue (LQ). void LPPassManager::addLoop(Loop &L) { if (!L.getParentLoop()) { // This is the top level loop. LQ.push_front(&L); return; } // Insert L into the loop queue after the parent loop. for (auto I = LQ.begin(), E = LQ.end(); I != E; ++I) { if (*I == L.getParentLoop()) { // deque does not support insert after. ++I; LQ.insert(I, 1, &L); return; } } } // Recurse through all subloops and all loops into LQ. static void addLoopIntoQueue(Loop *L, std::deque<Loop *> &LQ) { LQ.push_back(L); for (Loop *I : reverse(*L)) addLoopIntoQueue(I, LQ); } /// Pass Manager itself does not invalidate any analysis info. void LPPassManager::getAnalysisUsage(AnalysisUsage &Info) const { // LPPassManager needs LoopInfo. In the long term LoopInfo class will // become part of LPPassManager. Info.addRequired<LoopInfoWrapperPass>(); Info.addRequired<DominatorTreeWrapperPass>(); Info.setPreservesAll(); } void LPPassManager::markLoopAsDeleted(Loop &L) { assert((&L == CurrentLoop || CurrentLoop->contains(&L)) && "Must not delete loop outside the current loop tree!"); // If this loop appears elsewhere within the queue, we also need to remove it // there. However, we have to be careful to not remove the back of the queue // as that is assumed to match the current loop. assert(LQ.back() == CurrentLoop && "Loop queue back isn't the current loop!"); LQ.erase(std::remove(LQ.begin(), LQ.end(), &L), LQ.end()); if (&L == CurrentLoop) { CurrentLoopDeleted = true; // Add this loop back onto the back of the queue to preserve our invariants. LQ.push_back(&L); } } /// run - Execute all of the passes scheduled for execution. Keep track of /// whether any of the passes modifies the function, and if so, return true. bool LPPassManager::runOnFunction(Function &F) { auto &LIWP = getAnalysis<LoopInfoWrapperPass>(); LI = &LIWP.getLoopInfo(); Module &M = *F.getParent(); #if 0 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); #endif bool Changed = false; // Collect inherited analysis from Module level pass manager. populateInheritedAnalysis(TPM->activeStack); // Populate the loop queue in reverse program order. There is no clear need to // process sibling loops in either forward or reverse order. There may be some // advantage in deleting uses in a later loop before optimizing the // definitions in an earlier loop. If we find a clear reason to process in // forward order, then a forward variant of LoopPassManager should be created. // // Note that LoopInfo::iterator visits loops in reverse program // order. Here, reverse_iterator gives us a forward order, and the LoopQueue // reverses the order a third time by popping from the back. for (Loop *L : reverse(*LI)) addLoopIntoQueue(L, LQ); if (LQ.empty()) // No loops, skip calling finalizers return false; // Initialization for (Loop *L : LQ) { for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) { LoopPass *P = getContainedPass(Index); Changed |= P->doInitialization(L, *this); } } // Walk Loops unsigned InstrCount, FunctionSize = 0; StringMap<std::pair<unsigned, unsigned>> FunctionToInstrCount; bool EmitICRemark = M.shouldEmitInstrCountChangedRemark(); // Collect the initial size of the module and the function we're looking at. if (EmitICRemark) { InstrCount = initSizeRemarkInfo(M, FunctionToInstrCount); FunctionSize = F.getInstructionCount(); } while (!LQ.empty()) { CurrentLoopDeleted = false; CurrentLoop = LQ.back(); // Run all passes on the current Loop. for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) { LoopPass *P = getContainedPass(Index); llvm::TimeTraceScope LoopPassScope("RunLoopPass", P->getPassName()); dumpPassInfo(P, EXECUTION_MSG, ON_LOOP_MSG, CurrentLoop->getHeader()->getName()); dumpRequiredSet(P); initializeAnalysisImpl(P); bool LocalChanged = false; { PassManagerPrettyStackEntry X(P, *CurrentLoop->getHeader()); TimeRegion PassTimer(getPassTimer(P)); #ifdef EXPENSIVE_CHECKS uint64_t RefHash = StructuralHash(F); #endif LocalChanged = P->runOnLoop(CurrentLoop, *this); #ifdef EXPENSIVE_CHECKS if (!LocalChanged && (RefHash != StructuralHash(F))) { llvm::errs() << "Pass modifies its input and doesn't report it: " << P->getPassName() << "\n"; llvm_unreachable("Pass modifies its input and doesn't report it"); } #endif Changed |= LocalChanged; if (EmitICRemark) { unsigned NewSize = F.getInstructionCount(); // Update the size of the function, emit a remark, and update the // size of the module. if (NewSize != FunctionSize) { int64_t Delta = static_cast<int64_t>(NewSize) - static_cast<int64_t>(FunctionSize); emitInstrCountChangedRemark(P, M, Delta, InstrCount, FunctionToInstrCount, &F); InstrCount = static_cast<int64_t>(InstrCount) + Delta; FunctionSize = NewSize; } } } if (LocalChanged) dumpPassInfo(P, MODIFICATION_MSG, ON_LOOP_MSG, CurrentLoopDeleted ? "<deleted loop>" : CurrentLoop->getName()); dumpPreservedSet(P); if (!CurrentLoopDeleted) { // Manually check that this loop is still healthy. This is done // instead of relying on LoopInfo::verifyLoop since LoopInfo // is a function pass and it's really expensive to verify every // loop in the function every time. That level of checking can be // enabled with the -verify-loop-info option. { TimeRegion PassTimer(getPassTimer(&LIWP)); CurrentLoop->verifyLoop(); } // Here we apply same reasoning as in the above case. Only difference // is that LPPassManager might run passes which do not require LCSSA // form (LoopPassPrinter for example). We should skip verification for // such passes. // FIXME: Loop-sink currently break LCSSA. Fix it and reenable the // verification! #if 0 if (mustPreserveAnalysisID(LCSSAVerificationPass::ID)) assert(CurrentLoop->isRecursivelyLCSSAForm(*DT, *LI)); #endif // Then call the regular verifyAnalysis functions. verifyPreservedAnalysis(P); F.getContext().yield(); } if (LocalChanged) removeNotPreservedAnalysis(P); recordAvailableAnalysis(P); removeDeadPasses(P, CurrentLoopDeleted ? "<deleted>" : CurrentLoop->getHeader()->getName(), ON_LOOP_MSG); if (CurrentLoopDeleted) // Do not run other passes on this loop. break; } // If the loop was deleted, release all the loop passes. This frees up // some memory, and avoids trouble with the pass manager trying to call // verifyAnalysis on them. if (CurrentLoopDeleted) { for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) { Pass *P = getContainedPass(Index); freePass(P, "<deleted>", ON_LOOP_MSG); } } // Pop the loop from queue after running all passes. LQ.pop_back(); } // Finalization for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) { LoopPass *P = getContainedPass(Index); Changed |= P->doFinalization(); } return Changed; } /// Print passes managed by this manager void LPPassManager::dumpPassStructure(unsigned Offset) { errs().indent(Offset*2) << "Loop Pass Manager\n"; for (unsigned Index = 0; Index < getNumContainedPasses(); ++Index) { Pass *P = getContainedPass(Index); P->dumpPassStructure(Offset + 1); dumpLastUses(P, Offset+1); } } //===----------------------------------------------------------------------===// // LoopPass Pass *LoopPass::createPrinterPass(raw_ostream &O, const std::string &Banner) const { return new PrintLoopPassWrapper(O, Banner); } // Check if this pass is suitable for the current LPPassManager, if // available. This pass P is not suitable for a LPPassManager if P // is not preserving higher level analysis info used by other // LPPassManager passes. In such case, pop LPPassManager from the // stack. This will force assignPassManager() to create new // LPPassManger as expected. void LoopPass::preparePassManager(PMStack &PMS) { // Find LPPassManager while (!PMS.empty() && PMS.top()->getPassManagerType() > PMT_LoopPassManager) PMS.pop(); // If this pass is destroying high level information that is used // by other passes that are managed by LPM then do not insert // this pass in current LPM. Use new LPPassManager. if (PMS.top()->getPassManagerType() == PMT_LoopPassManager && !PMS.top()->preserveHigherLevelAnalysis(this)) PMS.pop(); } /// Assign pass manager to manage this pass. void LoopPass::assignPassManager(PMStack &PMS, PassManagerType PreferredType) { // Find LPPassManager while (!PMS.empty() && PMS.top()->getPassManagerType() > PMT_LoopPassManager) PMS.pop(); LPPassManager *LPPM; if (PMS.top()->getPassManagerType() == PMT_LoopPassManager) LPPM = (LPPassManager*)PMS.top(); else { // Create new Loop Pass Manager if it does not exist. assert (!PMS.empty() && "Unable to create Loop Pass Manager"); PMDataManager *PMD = PMS.top(); // [1] Create new Loop Pass Manager LPPM = new LPPassManager(); LPPM->populateInheritedAnalysis(PMS); // [2] Set up new manager's top level manager PMTopLevelManager *TPM = PMD->getTopLevelManager(); TPM->addIndirectPassManager(LPPM); // [3] Assign manager to manage this new manager. This may create // and push new managers into PMS Pass *P = LPPM->getAsPass(); TPM->schedulePass(P); // [4] Push new manager into PMS PMS.push(LPPM); } LPPM->add(this); } static std::string getDescription(const Loop &L) { return "loop"; } bool LoopPass::skipLoop(const Loop *L) const { const Function *F = L->getHeader()->getParent(); if (!F) return false; // Check the opt bisect limit. OptPassGate &Gate = F->getContext().getOptPassGate(); if (Gate.isEnabled() && !Gate.shouldRunPass(this, getDescription(*L))) return true; // Check for the OptimizeNone attribute. if (F->hasOptNone()) { // FIXME: Report this to dbgs() only once per function. LLVM_DEBUG(dbgs() << "Skipping pass '" << getPassName() << "' in function " << F->getName() << "\n"); // FIXME: Delete loop from pass manager's queue? return true; } return false; } LCSSAVerificationPass::LCSSAVerificationPass() : FunctionPass(ID) { initializeLCSSAVerificationPassPass(*PassRegistry::getPassRegistry()); } char LCSSAVerificationPass::ID = 0; INITIALIZE_PASS(LCSSAVerificationPass, "lcssa-verification", "LCSSA Verifier", false, false)
google/llvm-propeller
llvm/lib/Analysis/LoopPass.cpp
C++
apache-2.0
13,649
using System; using System.Data; using System.Text; using System.Text.RegularExpressions; using System.Collections; using CPTT.DataAccess; using CPTT.SystemFramework; namespace CPTT.BusinessRule { /// <summary> /// FinanInfoRules µÄժҪ˵Ã÷¡£ /// </summary> public class FinanInfoRules { private double getMessRestoreCharge; private double getAdmRestoreCharge; private double getModifyMessRestoreCharge; private double getModifyAdmRestoreCharge; public FinanInfoRules() { // // TODO: ÔÚ´Ë´¦Ìí¼Ó¹¹Ô캯ÊýÂß¼­ // } public DataSet GetContiAbsForMess(string getGrade,string getClass, string getName,string getNumber,DateTime balanceMonth,FinanInfo finanInfo) { using ( FinanInfoDataAccess finanInfoDataAccess = new FinanInfoDataAccess() ) { try { DataSet dsFinanBuild = finanInfoDataAccess.SetFinanStuInfo(getGrade,getClass,getName,getNumber); DataSet dsAdmRestoreDays = finanInfoDataAccess.SetContiAbsForMess(true,getGrade,getClass, getName,getNumber,balanceMonth,finanInfo.GetMessRestoreDays); DataSet dsMessRestoreDays = finanInfoDataAccess.SetContiAbsForMess(false,getGrade,getClass, getName,getNumber,balanceMonth,finanInfo.GetMessRestoreDays); DataColumn needHandDaysColumn = new DataColumn("info_needHandDays"); needHandDaysColumn.DataType = System.Type.GetType("System.Int32"); dsFinanBuild.Tables[0].Columns.Add(needHandDaysColumn); DataColumn messStopDaysColumn = new DataColumn("info_messStopDays"); messStopDaysColumn.DataType = System.Type.GetType("System.Int32"); dsFinanBuild.Tables[0].Columns.Add(messStopDaysColumn); dsFinanBuild.Tables[0].Columns.AddRange(new DataColumn[]{ new DataColumn("info_admCharge"),new DataColumn("info_messCharge"), new DataColumn("info_nightCharge"),new DataColumn("info_commCharge"), new DataColumn("info_milkCharge"),new DataColumn("info_extraCharge"), new DataColumn("info_admRestoreCharge"),new DataColumn("info_messRestoreCharge"), new DataColumn("info_currency"),new DataColumn("info_remark")}); for ( int finanRow = 0; finanRow < dsFinanBuild.Tables[0].Rows.Count; finanRow ++ ) { //Ó¦½»ÌìÊý dsFinanBuild.Tables[0].Rows[finanRow][3] = GetWorkDays(balanceMonth); //Í£»ïÌìÊý¼°ÍË»ïʳ·Ñ dsFinanBuild.Tables[0].Rows[finanRow][4] = 0; dsFinanBuild.Tables[0].Rows[finanRow][12] = "0.00£¤"; foreach(DataRow messRow in dsMessRestoreDays.Tables[0].Rows) { if ( dsFinanBuild.Tables[0].Rows[finanRow][0].ToString().Equals(messRow[0].ToString()) ) { dsFinanBuild.Tables[0].Rows[finanRow][4] = messRow[1]; dsFinanBuild.Tables[0].Rows[finanRow][12] = (finanInfo.GetMessCharge/GetWorkDays(balanceMonth)* Convert.ToDouble(messRow[1])).ToString("0.00")+"£¤"; getMessRestoreCharge = finanInfo.GetMessCharge/GetWorkDays(balanceMonth)* Convert.ToDouble(messRow[1]); break; } else { dsFinanBuild.Tables[0].Rows[finanRow][4] = 0; dsFinanBuild.Tables[0].Rows[finanRow][12] = "0.00£¤"; getMessRestoreCharge = 0; } } //¹ÜÀí·Ñ dsFinanBuild.Tables[0].Rows[finanRow][5] = finanInfo.GetAdmCharge.ToString("0.00")+"£¤"; dsFinanBuild.Tables[0].Rows[finanRow][11] = "0.00£¤"; foreach(DataRow admRow in dsAdmRestoreDays.Tables[0].Rows) { if ( dsFinanBuild.Tables[0].Rows[finanRow][0].ToString().Equals(admRow[0].ToString())) { if ( Convert.ToInt32(admRow[1]) >= finanInfo.GetAdmRestoreDays ) { dsFinanBuild.Tables[0].Rows[finanRow][11] = (finanInfo.GetAdmCharge/2).ToString("0.00")+"£¤"; getAdmRestoreCharge = finanInfo.GetAdmCharge/2; break; } else { dsFinanBuild.Tables[0].Rows[finanRow][11] = "0.00£¤"; getAdmRestoreCharge = 0; } } // else // { // dsFinanBuild.Tables[0].Rows[finanRow][5] = finanInfo.GetAdmCharge.ToString("0.00")+"£¤"; // dsFinanBuild.Tables[0].Rows[finanRow][11] = "0.00£¤"; // getAdmRestoreCharge = 0; // } } //»ïʳ·Ñ dsFinanBuild.Tables[0].Rows[finanRow][6] = finanInfo.GetMessCharge.ToString("0.00")+"£¤"; //ÍíÍÐ·Ñ dsFinanBuild.Tables[0].Rows[finanRow][7] = finanInfo.GetNightCharge.ToString("0.00")+"£¤"; //´ú°ì·Ñ dsFinanBuild.Tables[0].Rows[finanRow][8] = finanInfo.GetCommCharge.ToString("0.00")+"£¤"; //Å£ÄÌ·Ñ dsFinanBuild.Tables[0].Rows[finanRow][9] = finanInfo.GetMilkCharge.ToString("0.00")+"£¤"; //¸½¼Ó·Ñ dsFinanBuild.Tables[0].Rows[finanRow][10] = finanInfo.GetExtraCharge.ToString("0.00")+"£¤"; //ʵÊÕ½ð¶î dsFinanBuild.Tables[0].Rows[finanRow][13] = (finanInfo.GetMessCharge + finanInfo.GetAdmCharge + finanInfo.GetNightCharge + finanInfo.GetMilkCharge + finanInfo.GetCommCharge +finanInfo.GetExtraCharge - getMessRestoreCharge - getAdmRestoreCharge).ToString("0.00")+"£¤"; //±¸×¢ dsFinanBuild.Tables[0].Rows[finanRow][14] = finanInfo.GetRemark; } return dsFinanBuild; } catch(Exception e) { Util.WriteLog(e.Message,Util.EXCEPTION_LOG_TITLE); return null; } } } public DataSet ModifyFinanInfo(FinanInfo finanInfo,DataSet getDS,string getNumber,DateTime balanceMonth) { using ( FinanInfoDataAccess finanInfoDataAccess = new FinanInfoDataAccess() ) { try { DataSet dsModifyMessInfo = finanInfoDataAccess.SetContiAbsForMess(false,"","","",getNumber, balanceMonth,finanInfo.GetMessRestoreDays); DataSet dsModifyAdmInfo = finanInfoDataAccess.SetContiAbsForMess(true,"","","",getNumber, balanceMonth,finanInfo.GetMessRestoreDays); foreach(DataRow modifyRow in getDS.Tables[0].Rows) { if ( modifyRow[0].ToString().Equals(getNumber) ) { modifyRow[4] = 0; modifyRow[12] = "0.00£¤"; if ( dsModifyMessInfo.Tables[0].Rows.Count != 0) { modifyRow[4] = dsModifyAdmInfo.Tables[0].Rows[0][1]; modifyRow[12] = (finanInfo.GetMessCharge/GetWorkDays(balanceMonth)* Convert.ToDouble(dsModifyAdmInfo.Tables[0].Rows[0][1])).ToString("0.00")+"£¤"; getModifyMessRestoreCharge = finanInfo.GetMessCharge/GetWorkDays(balanceMonth)* Convert.ToDouble(dsModifyAdmInfo.Tables[0].Rows[0][1]); } modifyRow[5] = finanInfo.GetAdmCharge.ToString("0.00")+"£¤"; modifyRow[11] = "0.00£¤"; if ( dsModifyAdmInfo.Tables[0].Rows.Count !=0 ) { if ( Convert.ToInt32(dsModifyAdmInfo.Tables[0].Rows[0][1]) >= finanInfo.GetAdmRestoreDays ) { modifyRow[11] = (finanInfo.GetAdmCharge/2).ToString("0.00")+"£¤"; getModifyAdmRestoreCharge = finanInfo.GetAdmCharge/2; } } modifyRow[6] = finanInfo.GetMessCharge.ToString("0.00")+"£¤"; modifyRow[7] = finanInfo.GetNightCharge.ToString("0.00")+"£¤"; modifyRow[8] = finanInfo.GetCommCharge.ToString("0.00")+"£¤"; modifyRow[9] = finanInfo.GetMilkCharge.ToString("0.00")+"£¤"; modifyRow[10] = finanInfo.GetExtraCharge.ToString("0.00")+"£¤"; modifyRow[13] = (finanInfo.GetMessCharge + finanInfo.GetAdmCharge + finanInfo.GetNightCharge + finanInfo.GetMilkCharge + finanInfo.GetCommCharge +finanInfo.GetExtraCharge - getModifyMessRestoreCharge - getModifyAdmRestoreCharge).ToString("0.00")+"£¤"; modifyRow[14] = finanInfo.GetRemark; } } return getDS; } catch(Exception e) { Util.WriteLog(e.Message,Util.EXCEPTION_LOG_TITLE); return null; } } } public void DoInsertFinanInfo(DataSet dsFinanInfo,DateTime getDate,int getMessRestoreDays,int getAdmRestoreDays) { using ( FinanInfoDataAccess finanInfoDataAccess = new FinanInfoDataAccess() ) { try { foreach(DataRow finanInfoRow in dsFinanInfo.Tables[0].Rows) { finanInfoDataAccess.InsertFinanInfo(finanInfoRow,getDate,getMessRestoreDays,getAdmRestoreDays); } } catch(Exception e) { Util.WriteLog(e.Message,Util.EXCEPTION_LOG_TITLE); } } } public void DoDeleteFinanInfo(DateTime getDate) { using ( FinanInfoDataAccess finanInfoDataAccess = new FinanInfoDataAccess() ) { try { finanInfoDataAccess.DeleteFinanInfo(getDate); } catch(Exception e) { Util.WriteLog(e.Message,Util.EXCEPTION_LOG_TITLE); } } } private int GetDaysInMonth(DateTime getDate) { int rtnDay = 1; if ( getDate.Year % 4 != 0 ) { switch ( getDate.Month ) { case 1: rtnDay = 31; break; case 2: rtnDay = 28; break; case 3: rtnDay = 31; break; case 4: rtnDay = 30; break; case 5: rtnDay = 31; break; case 6: rtnDay = 30; break; case 7: rtnDay = 31; break; case 8: rtnDay = 31; break; case 9: rtnDay = 30; break; case 10: rtnDay = 31; break; case 11: rtnDay = 30; break; case 12: rtnDay = 31; break; } return rtnDay; } else { switch ( getDate.Month ) { case 1: rtnDay = 31; break; case 2: rtnDay = 29; break; case 3: rtnDay = 31; break; case 4: rtnDay = 30; break; case 5: rtnDay = 31; break; case 6: rtnDay = 30; break; case 7: rtnDay = 31; break; case 8: rtnDay = 31; break; case 9: rtnDay = 30; break; case 10: rtnDay = 31; break; case 11: rtnDay = 30; break; case 12: rtnDay = 31; break; } return rtnDay; } } private int GetWorkDays(DateTime getDate) { DateTime initBegDate = new DateTime(getDate.Year,getDate.Month,1); //ÐÝÏ¢ÈÕ int restingDays = 0; //µ±ÔÂÈÕÊý int dayNumbers = GetDaysInMonth(getDate); for(int i=0;i<dayNumbers;i++) { //ÎåÒ»ºÍʮһ if (initBegDate.AddDays(i).Month == 10) { if ( initBegDate.AddDays(i).Day <= 3) restingDays ++; } //Ôªµ© if ((initBegDate.AddDays(i).Month == 1 || initBegDate.AddDays(i).Month == 5) && initBegDate.AddDays(i).Day == 1) restingDays ++; //Ë«ÐÞÈÕ if ( initBegDate.AddDays(i).DayOfWeek.ToString().Equals("Saturday") || initBegDate.AddDays(i).DayOfWeek.ToString().Equals("Sunday") ) { restingDays ++; } } return (dayNumbers - restingDays); } private DataTable BuildingFinanceStat(DataTable filterTemplateContents) { DataTable dtBuilded = new DataTable(); dtBuilded.Columns.AddRange(new DataColumn[]{new DataColumn("ѧºÅ", Type.GetType("System.Int32")), new DataColumn("ÐÕÃû", Type.GetType("System.String")), new DataColumn("°à¼¶", Type.GetType("System.String"))}); if (filterTemplateContents != null && filterTemplateContents.Rows.Count > 0) { foreach (DataRow dr in filterTemplateContents.Rows) { dtBuilded.Columns.Add(dr["name"].ToString(), Type.GetType("System.String")); } return dtBuilded; } else { return null; } } public DataTable FilterTemplateContents(string templateName, string grade, string className) { DataTable dtTemplateContents = new FinanInfoDataAccess().GetTemplateContents(templateName); if (dtTemplateContents != null && dtTemplateContents.Rows.Count > 0) { DataTable dtReBuilding = dtTemplateContents.Clone(); foreach (DataRow dr in dtTemplateContents.Rows) { string name = dr["name"].ToString(); DataRow newRow = dtReBuilding.NewRow(); DataRow[] temp1 = dtTemplateContents.Select(string.Format("name='{0}'", name), "order asc"); if (temp1.Length > 1) { if (dtReBuilding.Select(string.Format("name='{0}'", name)).Length == 0) { DataRow[] temp2 = dtTemplateContents.Select(string.Format("name='{0}' AND grade='{1}' AND (class = " + "'{2}' OR class = '²»Ñ¡Ôñ')", name, grade, className), "order asc"); if (temp2.Length == 1) { newRow.ItemArray = temp2[0].ItemArray; dtReBuilding.Rows.Add(newRow); } else { DataRow[] temp3 = dtTemplateContents.Select(string.Format("name='{0}' AND grade='²»Ñ¡Ôñ'", name), "order asc"); if (temp3.Length == 1) { newRow.ItemArray = temp3[0].ItemArray; dtReBuilding.Rows.Add(newRow); } else { newRow.ItemArray = dr.ItemArray; dtReBuilding.Rows.Add(newRow); } } } } else { newRow.ItemArray = dr.ItemArray; dtReBuilding.Rows.Add(newRow); } } return dtReBuilding; } else { return null; } } public DataTable MakingFinanceStat(string templateName, string grade, string className, DateTime date, out ArrayList list) { list = new ArrayList(); try { using (DataTable dtStudentPresents = new FinanInfoDataAccess().GetStudentPresents(date, className)) { if (dtStudentPresents != null && dtStudentPresents.Rows.Count > 0) { DataTable dtFilterTemplateContents = FilterTemplateContents(templateName, grade, className); DataTable dtBuilded = BuildingFinanceStat(dtFilterTemplateContents); foreach (DataRow dr in dtStudentPresents.Rows) { DataRow newRow = dtBuilded.NewRow(); int index = 3; foreach(DataRow drContents in dtFilterTemplateContents.Rows) { TemplateContentsRecordSet contents = new TemplateContentsRecordSet(drContents["name"].ToString(), drContents["fullDays"].ToString(), drContents["fullDaysSpend"].ToString(), drContents["halfDaysSpend"].ToString(), drContents["perDaySpend"].ToString(), drContents["noSpendMonth"].ToString(), drContents["halfSpendMonth"].ToString(), drContents["grade"].ToString(), drContents["class"].ToString()); newRow[0] = dr["ѧºÅ"]; newRow[1] = dr["ÐÕÃû"]; newRow[2] = dr["°à¼¶"]; if (contents.Grade == "²»Ñ¡Ôñ" || Regex.Match(contents.Grade + contents.ClassName, string.Format("^{2}{0}|{2}{1}$", className, "²»Ñ¡Ôñ", grade)).Success) { if (!contents.FullDays.Equals("-")) { if (!contents.FullDaysSpend.Equals("-")) { int fullDays = Convert.ToInt32(contents.FullDays); int presentDays = Convert.ToInt32(dr["times"]); if (presentDays >= fullDays) { newRow[index] = contents.FullDaysSpend; } else { if (!contents.HalfDaysSpend.Equals("-")) { newRow[index] = contents.HalfDaysSpend; } else { if (!contents.PerDaySpend.Equals("-")) { double perDaySpend = Convert.ToDouble(contents.PerDaySpend); newRow[index] = Convert.ToInt32(dr["times"]) * perDaySpend; } else { newRow[index] = 0; } } } } else { if (!contents.PerDaySpend.Equals("-")) { double perDaySpend = Convert.ToDouble(contents.PerDaySpend); newRow[index] = Convert.ToInt32(dr["times"]) * perDaySpend; } else { newRow[index] = 0; } } } else { if (!contents.PerDaySpend.Equals("-")) { double perDaySpend = Convert.ToDouble(contents.PerDaySpend); newRow[index] = Convert.ToInt32(dr["times"]) * perDaySpend; } else { newRow[index] = 0; } } if (!contents.NoSpendMonth.Equals("-")) { string month = date.Month.ToString(); string pattern = string.Format(@"^{0}$", contents.NoSpendMonth.Replace(",", "|")); if (Convert.ToInt32(dr["times"]) == 0) { newRow[index] = Regex.Match(month, pattern).Success ? 0 : newRow[index]; } } if (!contents.HalfSpendMonth.Equals("-")) { string month = date.Month.ToString(); string pattern = string.Format(@"^{0}$", contents.HalfSpendMonth.Replace(",", "|")); newRow[index] = Regex.Match(month, pattern).Success ? Convert.ToDouble(newRow[index]) / 2 : newRow[index]; } } else { if (!list.Contains(contents.ColumnName)) { list.Add(contents.ColumnName); } newRow[index] = 0; } index++; } dtBuilded.Rows.Add(newRow); } return dtBuilded; } else { return null; } } } catch(Exception ex) { Util.WriteLog(ex.Message, Util.EXCEPTION_LOG_TITLE); return null; } } private struct TemplateContentsRecordSet { private string _columnName; private string _fullDays; private string _fullDaysSpend; private string _halfDaysSpend; private string _perDaySpend; private string _noSpendMonth; private string _halfSpendMonth; private string _grade; private string _className; public TemplateContentsRecordSet(string columnName, string fullDays, string fullDaysSpend, string halfDaysSpend, string perDaySpend, string noSpendMonth, string halfSpendMonth, string grade, string className) { _columnName = columnName; _fullDays = fullDays; _fullDaysSpend = fullDaysSpend; _halfDaysSpend = halfDaysSpend; _perDaySpend = perDaySpend; _noSpendMonth = noSpendMonth; _halfSpendMonth = halfSpendMonth; _grade = grade; _className = className; } public string ColumnName { get { return _columnName; } set { _columnName = value; } } public string FullDays { get { return _fullDays; } set { _fullDays = value; } } public string FullDaysSpend { get { return _fullDaysSpend; } set { _fullDaysSpend = value; } } public string HalfDaysSpend { get { return _halfDaysSpend; } set { _halfDaysSpend = value; } } public string PerDaySpend { get { return _perDaySpend; } set { _perDaySpend = value; } } public string NoSpendMonth { get { return _noSpendMonth; } set { _noSpendMonth = value; } } public string HalfSpendMonth { get { return _halfSpendMonth; } set { _halfSpendMonth = value; } } public string Grade { get { return _grade; } set { _grade = value; } } public string ClassName { get { return _className; } set { _className = value; } } } } }
zesus19/c4.v2.T
CPTT.BusinessRule/FinanInfoRules.cs
C#
apache-2.0
19,039
var t = new Map(); var objectKey = {}; var stringKey = 'keykeykey'; var numberKey = 42.24; var booleanKey = true; var undefinedKey = undefined; var nullKey = null; var nanKey = NaN; var zeroKey = 0; var frozenKey = Object.freeze({}); assert.equal(t.size, 0); assert.isUndefined(t.get(objectKey)); assert.isUndefined(t.get(frozenKey)); assert.isFalse(t.has(objectKey)); assert.isFalse(t.has(frozenKey)); t.set(undefinedKey, 'value8'); t.set(nullKey, 'value9'); t.set(stringKey, 'value5'); t.set(numberKey, 'value6'); t.set(booleanKey, 'value7'); t.set(objectKey, 'value1'); t.set(nanKey, 'value10'); t.set(zeroKey, 'value11'); t.set(frozenKey, 'value12'); assert.equal(t.size, 9); assert.equal(t.get(objectKey), 'value1'); assert.equal(t.get(stringKey), 'value5'); assert.equal(t.get(numberKey), 'value6'); assert.equal(t.get(booleanKey), 'value7'); assert.equal(t.get(undefinedKey), 'value8'); assert.equal(t.get(nullKey), 'value9'); assert.equal(t.get(nanKey), 'value10'); assert.equal(t.get(zeroKey), 'value11'); assert.equal(t.get(frozenKey), 'value12'); assert.equal(t.get({}), undefined); assert.equal(t.get('keykeykey'), 'value5'); assert.equal(t.get(42.24), 'value6'); assert.equal(t.get(true), 'value7'); assert.equal(t.get(undefined), 'value8'); assert.equal(t.get(null), 'value9'); assert.equal(t.get(NaN), 'value10'); assert.equal(t.get(0), 'value11'); assert.equal(t.get(1 / Infinity), 'value11'); assert.equal(t.get(Object.freeze({})), undefined); // V8 is broken for -0 // https://code.google.com/p/v8/issues/detail?id=3906 // assert.equal(t.get(-1 / Infinity), 'value11'); assert.isTrue(!t.has({})); assert.isTrue(t.has(objectKey)); assert.isTrue(t.has(stringKey)); assert.isTrue(t.has(numberKey)); assert.isTrue(t.has(booleanKey)); assert.isTrue(t.has(undefinedKey)); assert.isTrue(t.has(nullKey)); assert.isTrue(t.has(nanKey)); assert.isTrue(t.has(zeroKey)); assert.isTrue(t.has(frozenKey)); assert.isTrue(t.has('keykeykey')); assert.isTrue(t.has(42.24)); assert.isTrue(t.has(true)); assert.isTrue(t.has(undefined)); assert.isTrue(t.has(null)); assert.isTrue(t.has(NaN)); assert.isTrue(t.has(0)); // V8 is broken for -0 // https://code.google.com/p/v8/issues/detail?id=3906 // assert.isTrue(t.has(-0)); // forEach var arrKeys = []; var arr = []; var cnt = 0; t.forEach(function (value, key, map) { if (cnt === 0) { t.set('foo', 42); } assert.equal(map, t); arrKeys.push(key); arr.push(value); cnt++; }); assert.equal(cnt, 10); t.delete('foo'); assertArrayEquals(arrKeys, [ undefinedKey, nullKey, stringKey, numberKey, booleanKey, objectKey, nanKey, zeroKey, frozenKey, 'foo' ]); assertArrayEquals(arr, [ 'value8', 'value9', 'value5', 'value6', 'value7', 'value1', 'value10', 'value11', 'value12', 42 ]); // iterator arrKeys = []; arr = []; cnt = 0; for (var mapIterItem of t) { if (cnt === 0) { t.set('foo', 42); } var [mapIterItemKey, mapIterItemVal] = mapIterItem; arrKeys.push(mapIterItemKey); arr.push(mapIterItemVal); cnt++; } assert.equal(cnt, 10); t.delete('foo'); assertArrayEquals(arrKeys, [ undefinedKey, nullKey, stringKey, numberKey, booleanKey, objectKey, nanKey, zeroKey, frozenKey, 'foo' ]); assertArrayEquals(arr, [ 'value8', 'value9', 'value5', 'value6', 'value7', 'value1', 'value10', 'value11', 'value12', 42 ]); // .entries() arrKeys = []; arr = []; cnt = 0; for (var mapIterItem of t.entries()) { var [mapIterItemKey, mapIterItemVal] = mapIterItem; arrKeys.push(mapIterItemKey); arr.push(mapIterItemVal); cnt++; } assert.equal(cnt, 9); assertArrayEquals(arrKeys, [ undefinedKey, nullKey, stringKey, numberKey, booleanKey, objectKey, nanKey, zeroKey, frozenKey ]); assertArrayEquals(arr, [ 'value8', 'value9', 'value5', 'value6', 'value7', 'value1', 'value10', 'value11', 'value12' ]); // .keys() arrKeys = []; cnt = 0; for (var mapIterKey of t.keys()) { arrKeys.push(mapIterKey); cnt++; } assert.equal(cnt, 9); assertArrayEquals(arrKeys, [ undefinedKey, nullKey, stringKey, numberKey, booleanKey, objectKey, nanKey, zeroKey, frozenKey ]); // .values() arr = []; cnt = 0; for (var mapIterVal of t.values()) { arr.push(mapIterVal); cnt++; } assert.equal(cnt, 9); assertArrayEquals(arr, [ 'value8', 'value9', 'value5', 'value6', 'value7', 'value1', 'value10', 'value11', 'value12' ]); var t3 = new Map([ [[],[]], [{},{}], [NaN,NaN] ]); var deleteReturnValue; assert.equal(t3.size, 3); assert.isTrue(t3.has(NaN)); assert.isTrue(isNaN(t3.get(NaN))); assert.equal(t3.set(NaN, NaN), t3); // test of 23.1.3.9.11 deleteReturnValue = t3.delete(NaN); assert.equal(t3.size, 2); assert.isTrue(deleteReturnValue); deleteReturnValue = t3.delete(NaN); assert.equal(t3.size, 2); assert.isFalse(deleteReturnValue); t3.clear(); assert.equal(t3.size, 0); assert.equal(Map.prototype[Symbol.iterator], Map.prototype.entries);
arv/traceur-compiler
test/feature/Collections/Map.js
JavaScript
apache-2.0
4,965
<?php /** * Copyright (c) 2012 Robin Appelman <icewind@owncloud.com> * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ namespace OC\Files\Storage; class FTP extends \OC\Files\Storage\StreamWrapper{ private $password; private $user; private $host; private $secure; private $root; private static $tempFiles=array(); public function __construct($params) { if (isset($params['host']) && isset($params['user']) && isset($params['password'])) { $this->host=$params['host']; $this->user=$params['user']; $this->password=$params['password']; if (isset($params['secure'])) { if (is_string($params['secure'])) { $this->secure = ($params['secure'] === 'true'); } else { $this->secure = (bool)$params['secure']; } } else { $this->secure = false; } $this->root=isset($params['root'])?$params['root']:'/'; if ( ! $this->root || $this->root[0]!='/') { $this->root='/'.$this->root; } if (substr($this->root, -1) !== '/') { $this->root .= '/'; } } else { throw new \Exception('Creating \OC\Files\Storage\FTP storage failed'); } } public function getId(){ return 'ftp::' . $this->user . '@' . $this->host . '/' . $this->root; } /** * construct the ftp url * @param string $path * @return string */ public function constructUrl($path) { $url='ftp'; if ($this->secure) { $url.='s'; } $url.='://'.$this->user.':'.$this->password.'@'.$this->host.$this->root.$path; return $url; } /** * Unlinks file or directory * @param string $path */ public function unlink($path) { if ($this->is_dir($path)) { return $this->rmdir($path); } else { $url = $this->constructUrl($path); $result = unlink($url); clearstatcache(true, $url); return $result; } } public function fopen($path,$mode) { switch($mode) { case 'r': case 'rb': case 'w': case 'wb': case 'a': case 'ab': //these are supported by the wrapper $context = stream_context_create(array('ftp' => array('overwrite' => true))); return fopen($this->constructUrl($path), $mode, false, $context); case 'r+': case 'w+': case 'wb+': case 'a+': case 'x': case 'x+': case 'c': case 'c+': //emulate these if (strrpos($path, '.')!==false) { $ext=substr($path, strrpos($path, '.')); } else { $ext=''; } $tmpFile=\OCP\Files::tmpFile($ext); \OC\Files\Stream\Close::registerCallback($tmpFile, array($this, 'writeBack')); if ($this->file_exists($path)) { $this->getFile($path, $tmpFile); } self::$tempFiles[$tmpFile]=$path; return fopen('close://'.$tmpFile, $mode); } return false; } public function writeBack($tmpFile) { if (isset(self::$tempFiles[$tmpFile])) { $this->uploadFile($tmpFile, self::$tempFiles[$tmpFile]); unlink($tmpFile); } } /** * check if php-ftp is installed */ public static function checkDependencies() { if (function_exists('ftp_login')) { return(true); } else { return array('ftp'); } } }
kebenxiaoming/owncloudRedis
apps/files_external/lib/ftp.php
PHP
apache-2.0
3,100
/* * Copyright 2016 org.NLP4L * * 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.nlp4l.framework.builtin.lucene import java.io.FileInputStream import java.nio.file.FileSystems import com.typesafe.config.Config import org.apache.lucene.analysis.standard.StandardAnalyzer import org.apache.lucene.index.{IndexWriterConfig, DirectoryReader} import org.apache.lucene.search.spell.{Dictionary => SpellDictionary, PlainTextDictionary, LuceneDictionary, SpellChecker} import org.apache.lucene.search.suggest.FileDictionary import org.apache.lucene.store.FSDirectory import org.nlp4l.framework.models.{Cell, Record, Dictionary} import org.nlp4l.framework.processors._ class LuceneSpellcheckIndexingProcessorFactory(settings: Config) extends ProcessorFactory(settings) { override def getInstance(): Processor = { new LuceneSpellcheckIndexingProcessor( getStrParamRequired("index"), getStrParamRequired("dicType"), getConfigParam("settings", null)) } } class LuceneSpellcheckIndexingProcessor(val index: String, val dicType: String, val settings: Config) extends Processor { override def execute(data: Option[Dictionary]): Option[Dictionary] = { val dictionary: SpellDictionary = dicType match { case "plainText" => { val file = settings.getString("file") new PlainTextDictionary(FileSystems.getDefault.getPath(file)) } case "file" => { val file = settings.getString("file") val delimiter = if(settings.hasPath("delimiter")) settings.getString("delimiter") else FileDictionary.DEFAULT_FIELD_DELIMITER val is = new FileInputStream(file) new FileDictionary(is, delimiter) } case "lucene" => { val idxDir = FSDirectory.open(FileSystems.getDefault.getPath(settings.getString("index"))) val field = settings.getString("field") val reader = DirectoryReader.open(idxDir) new LuceneDictionary(reader, field) } case a => throw new IllegalArgumentException(s"unknown dictionary type was specified: $a") } val spellChecker: SpellChecker = new SpellChecker(FSDirectory.open(FileSystems.getDefault.getPath(index))) spellChecker.clearIndex(); spellChecker.indexDictionary(dictionary, new IndexWriterConfig(new StandardAnalyzer()), true) spellChecker.close val dict = Dictionary(Seq( Record(Seq( Cell("result", s"success: spellcheck index '$index' has been created.") )))) Some(dict) } }
fubuki/nlp4l
app/org/nlp4l/framework/builtin/lucene/LuceneSpellcheckIndexingProcessor.scala
Scala
apache-2.0
2,996
/*! * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * 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 Lesser General Public License for more details. * * Copyright (c) 2002-2017 Hitachi Vantara.. All rights reserved. */ package org.pentaho.platform.dataaccess.datasource.wizard.service.impl; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * @author Vadim_Polynkov. */ public class DatasourceResourceTest { @Test public void testPrepareDataSourceInfo_OnlyQuotesEscaped() { StringBuilder dataSourceInfo = new StringBuilder(); dataSourceInfo.append( "DataSource=" ) .append( "\"DS &quot;Test&apos;s&quot; &amp; &lt;Fun&gt;\";" ) .append( "DynamicSchemaProcessor=" ) .append( "\"DSP&apos;s &amp; &quot;Other&quot; &lt;stuff&gt;\";" ); StringBuilder expectedResult = new StringBuilder(); expectedResult.append( "DataSource=" ) .append( "\"DS &quot;Test's&quot; & <Fun>\";" ) .append( "DynamicSchemaProcessor=" ) .append( "\"DSP's & &quot;Other&quot; <stuff>\";" ); String result = DatasourceResource.prepareDataSourceInfo( dataSourceInfo.toString() ); assertEquals( result, expectedResult.toString() ); } }
kurtwalker/data-access
core/src/test/java/org/pentaho/platform/dataaccess/datasource/wizard/service/impl/DatasourceResourceTest.java
Java
apache-2.0
1,813
/* Copyright 2019 The Vitess Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package binlogplayer import ( "fmt" "strings" "vitess.io/vitess/go/sqltypes" ) type fakeDBClient struct { } // NewFakeDBClient returns a fake DBClient. Its functions return // preset responses to requests. func NewFakeDBClient() DBClient { return &fakeDBClient{} } func (dc *fakeDBClient) DBName() string { return "db" } func (dc *fakeDBClient) Connect() error { return nil } func (dc *fakeDBClient) Begin() error { return nil } func (dc *fakeDBClient) Commit() error { return nil } func (dc *fakeDBClient) Rollback() error { return nil } func (dc *fakeDBClient) Close() { } func (dc *fakeDBClient) ExecuteFetch(query string, maxrows int) (qr *sqltypes.Result, err error) { query = strings.ToLower(query) switch { case strings.HasPrefix(query, "insert"): return &sqltypes.Result{InsertID: 1}, nil case strings.HasPrefix(query, "update"): return &sqltypes.Result{RowsAffected: 1}, nil case strings.HasPrefix(query, "delete"): return &sqltypes.Result{RowsAffected: 1}, nil case strings.HasPrefix(query, "select"): if strings.Contains(query, "where") { return sqltypes.MakeTestResult( sqltypes.MakeTestFields( "id|state|source", "int64|varchar|varchar", ), `1|Running|keyspace:"ks" shard:"0" key_range:<end:"\200" > `, ), nil } return &sqltypes.Result{}, nil case strings.HasPrefix(query, "use"): return &sqltypes.Result{}, nil } return nil, fmt.Errorf("unexpected: %v", query) }
mahak/vitess
go/vt/binlog/binlogplayer/fake_dbclient.go
GO
apache-2.0
2,015