repo_name
stringlengths
4
116
path
stringlengths
3
942
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
cdmdotnet/CQRS
wiki/docs/2.1/html/classCqrs_1_1Domain_1_1Factories_1_1AggregateFactory_a78a24b5139cda7a07f938169a406f66e.html
4980
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.13"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>CQRS.NET: Cqrs.Domain.Factories.AggregateFactory.Logger</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ extensions: ["tex2jax.js"], jax: ["input/TeX","output/HTML-CSS"], }); </script><script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="ChinChilla-Software-Red.png"/></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">CQRS.NET &#160;<span id="projectnumber">2.1</span> </div> <div id="projectbrief">A lightweight enterprise framework to write CQRS, event-sourced and micro-service applications in hybrid multi-datacentre, on-premise and Azure environments.</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.13 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('classCqrs_1_1Domain_1_1Factories_1_1AggregateFactory_a78a24b5139cda7a07f938169a406f66e.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="contents"> <a id="a78a24b5139cda7a07f938169a406f66e"></a> <h2 class="memtitle"><span class="permalink"><a href="#a78a24b5139cda7a07f938169a406f66e">&#9670;&nbsp;</a></span>Logger</h2> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">ILogger Cqrs.Domain.Factories.AggregateFactory.Logger</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">get</span><span class="mlabel">protected</span></span> </td> </tr> </table> </div><div class="memdoc"> </div> </div> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="navelem"><a class="el" href="namespaceCqrs.html">Cqrs</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1Domain.html">Domain</a></li><li class="navelem"><a class="el" href="namespaceCqrs_1_1Domain_1_1Factories.html">Factories</a></li><li class="navelem"><a class="el" href="classCqrs_1_1Domain_1_1Factories_1_1AggregateFactory.html">AggregateFactory</a></li> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.13 </li> </ul> </div> </body> </html>
lgpl-2.1
flow123d/dealii
tests/bits/find_cell_alt_1.cc
2263
// --------------------------------------------------------------------- // // Copyright (C) 2003 - 2013 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // Public License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- // same as find_cell_1, but for the alternative algorithm // take a 2d mesh and check that we can find an arbitrary point's cell // in it #include "../tests.h" #include <deal.II/base/logstream.h> #include <deal.II/grid/tria.h> #include <deal.II/grid/tria_accessor.h> #include <deal.II/grid/tria_iterator.h> #include <deal.II/grid/grid_tools.h> #include <deal.II/grid/grid_generator.h> #include <deal.II/grid/tria_boundary_lib.h> #include <deal.II/fe/mapping_q.h> #include <fstream> void check (Triangulation<2> &tria) { MappingQ<2> map(3); // Let's take a higher order mapping Point<2> p (1./3., 1./2.); std::pair<Triangulation<2>::active_cell_iterator, Point<2> > cell = GridTools::find_active_cell_around_point (map, tria, p); deallog << cell.first << std::endl; for (unsigned int v=0; v<GeometryInfo<2>::vertices_per_cell; ++v) deallog << "<" << cell.first->vertex(v) << "> "; deallog << "[ " << cell.second << "] "; deallog << std::endl; Assert (p.distance (cell.first->center()) < cell.first->diameter()/2, ExcInternalError()); } int main () { std::ofstream logfile("output"); deallog.attach(logfile); deallog.depth_console(0); deallog.threshold_double(1.e-10); { Triangulation<2> coarse_grid; GridGenerator::hyper_cube (coarse_grid); coarse_grid.refine_global (2); check (coarse_grid); } { Triangulation<2> coarse_grid; GridGenerator::hyper_ball (coarse_grid); static const HyperBallBoundary<2> boundary; coarse_grid.set_boundary (0, boundary); coarse_grid.refine_global (2); check (coarse_grid); } }
lgpl-2.1
nonrational/qt-everywhere-opensource-src-4.8.6
src/qt3support/widgets/q3grid.cpp
4161
/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt3Support module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "q3grid.h" #include "qlayout.h" #include "qapplication.h" QT_BEGIN_NAMESPACE /*! \class Q3Grid \brief The Q3Grid widget provides simple geometry management of its children. \compat The grid places its widgets either in columns or in rows depending on its orientation. The number of rows \e or columns is defined in the constructor. All the grid's children will be placed and sized in accordance with their sizeHint() and sizePolicy(). Use setMargin() to add space around the grid itself, and setSpacing() to add space between the widgets. \sa Q3VBox Q3HBox QGridLayout */ /*! \typedef Q3Grid::Direction \internal */ /*! Constructs a grid widget with parent \a parent, called \a name. If \a orient is \c Horizontal, \a n specifies the number of columns. If \a orient is \c Vertical, \a n specifies the number of rows. The widget flags \a f are passed to the Q3Frame constructor. */ Q3Grid::Q3Grid(int n, Qt::Orientation orient, QWidget *parent, const char *name, Qt::WindowFlags f) : Q3Frame(parent, name, f) { int nCols, nRows; if (orient == Qt::Horizontal) { nCols = n; nRows = -1; } else { nCols = -1; nRows = n; } (new QGridLayout(this, nRows, nCols, 0, 0, name))->setAutoAdd(true); } /*! Constructs a grid widget with parent \a parent, called \a name. \a n specifies the number of columns. The widget flags \a f are passed to the Q3Frame constructor. */ Q3Grid::Q3Grid(int n, QWidget *parent, const char *name, Qt::WindowFlags f) : Q3Frame(parent, name, f) { (new QGridLayout(this, -1, n, 0, 0, name))->setAutoAdd(true); } /*! Sets the spacing between the child widgets to \a space. */ void Q3Grid::setSpacing(int space) { if (layout()) layout()->setSpacing(space); } /*!\reimp */ void Q3Grid::frameChanged() { if (layout()) layout()->setMargin(frameWidth()); } /*! \reimp */ QSize Q3Grid::sizeHint() const { QWidget *mThis = (QWidget*)this; QApplication::sendPostedEvents(mThis, QEvent::ChildInserted); return Q3Frame::sizeHint(); } QT_END_NAMESPACE
lgpl-2.1
locicontrols/RIOT
cpu/lpc1768/include/LPC17xx.h
34958
/**************************************************************************//** * @file LPC17xx.h * @brief CMSIS Cortex-M3 Core Peripheral Access Layer Header File for * NXP LPC17xx Device Series * @version: V1.09 * @date: 17. March 2010 * * @note * Copyright (C) 2009 ARM Limited. All rights reserved. * * @par * ARM Limited (ARM) is supplying this software for use with Cortex-M * processor based microcontrollers. This file can be freely distributed * within development tools that are supporting such ARM based processors. * * THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED * OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. * ARM SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR * CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER. * ******************************************************************************/ #ifndef __LPC17xx_H__ #define __LPC17xx_H__ /* * ========================================================================== * ---------- Interrupt Number Definition ----------------------------------- * ========================================================================== */ typedef enum IRQn { /****** Cortex-M3 Processor Exceptions Numbers ***************************************************/ NonMaskableInt_IRQn = -14, /*!< 2 Non Maskable Interrupt */ MemoryManagement_IRQn = -12, /*!< 4 Cortex-M3 Memory Management Interrupt */ BusFault_IRQn = -11, /*!< 5 Cortex-M3 Bus Fault Interrupt */ UsageFault_IRQn = -10, /*!< 6 Cortex-M3 Usage Fault Interrupt */ SVCall_IRQn = -5, /*!< 11 Cortex-M3 SV Call Interrupt */ DebugMonitor_IRQn = -4, /*!< 12 Cortex-M3 Debug Monitor Interrupt */ PendSV_IRQn = -2, /*!< 14 Cortex-M3 Pend SV Interrupt */ SysTick_IRQn = -1, /*!< 15 Cortex-M3 System Tick Interrupt */ /****** LPC17xx Specific Interrupt Numbers *******************************************************/ WDT_IRQn = 0, /*!< Watchdog Timer Interrupt */ TIMER0_IRQn = 1, /*!< Timer0 Interrupt */ TIMER1_IRQn = 2, /*!< Timer1 Interrupt */ TIMER2_IRQn = 3, /*!< Timer2 Interrupt */ TIMER3_IRQn = 4, /*!< Timer3 Interrupt */ UART0_IRQn = 5, /*!< UART0 Interrupt */ UART1_IRQn = 6, /*!< UART1 Interrupt */ UART2_IRQn = 7, /*!< UART2 Interrupt */ UART3_IRQn = 8, /*!< UART3 Interrupt */ PWM1_IRQn = 9, /*!< PWM1 Interrupt */ I2C0_IRQn = 10, /*!< I2C0 Interrupt */ I2C1_IRQn = 11, /*!< I2C1 Interrupt */ I2C2_IRQn = 12, /*!< I2C2 Interrupt */ SPI_IRQn = 13, /*!< SPI Interrupt */ SSP0_IRQn = 14, /*!< SSP0 Interrupt */ SSP1_IRQn = 15, /*!< SSP1 Interrupt */ PLL0_IRQn = 16, /*!< PLL0 Lock (Main PLL) Interrupt */ RTC_IRQn = 17, /*!< Real Time Clock Interrupt */ EINT0_IRQn = 18, /*!< External Interrupt 0 Interrupt */ EINT1_IRQn = 19, /*!< External Interrupt 1 Interrupt */ EINT2_IRQn = 20, /*!< External Interrupt 2 Interrupt */ EINT3_IRQn = 21, /*!< External Interrupt 3 Interrupt */ ADC_IRQn = 22, /*!< A/D Converter Interrupt */ BOD_IRQn = 23, /*!< Brown-Out Detect Interrupt */ USB_IRQn = 24, /*!< USB Interrupt */ CAN_IRQn = 25, /*!< CAN Interrupt */ DMA_IRQn = 26, /*!< General Purpose DMA Interrupt */ I2S_IRQn = 27, /*!< I2S Interrupt */ ENET_IRQn = 28, /*!< Ethernet Interrupt */ RIT_IRQn = 29, /*!< Repetitive Interrupt Timer Interrupt */ MCPWM_IRQn = 30, /*!< Motor Control PWM Interrupt */ QEI_IRQn = 31, /*!< Quadrature Encoder Interface Interrupt */ PLL1_IRQn = 32, /*!< PLL1 Lock (USB PLL) Interrupt */ USBActivity_IRQn = 33, /* USB Activity interrupt */ CANActivity_IRQn = 34, /* CAN Activity interrupt */ } IRQn_Type; /* * ========================================================================== * ----------- Processor and Core Peripheral Section ------------------------ * ========================================================================== */ /* Configuration of the Cortex-M3 Processor and Core Peripherals */ #define __MPU_PRESENT 1 /*!< MPU present or not */ #define __NVIC_PRIO_BITS 5 /*!< Number of Bits used for Priority Levels */ #define __Vendor_SysTickConfig 0 /*!< Set to 1 if different SysTick Config is used */ #include "core_cm3.h" /* Cortex-M3 processor and core peripherals */ /******************************************************************************/ /* Device Specific Peripheral registers structures */ /******************************************************************************/ #if defined ( __CC_ARM ) #pragma anon_unions #endif /*------------- System Control (SC) ------------------------------------------*/ typedef struct { __IO uint32_t FLASHCFG; /* Flash Accelerator Module */ uint32_t RESERVED0[31]; __IO uint32_t PLL0CON; /* Clocking and Power Control */ __IO uint32_t PLL0CFG; __I uint32_t PLL0STAT; __O uint32_t PLL0FEED; uint32_t RESERVED1[4]; __IO uint32_t PLL1CON; __IO uint32_t PLL1CFG; __I uint32_t PLL1STAT; __O uint32_t PLL1FEED; uint32_t RESERVED2[4]; __IO uint32_t PCON; __IO uint32_t PCONP; uint32_t RESERVED3[15]; __IO uint32_t CCLKCFG; __IO uint32_t USBCLKCFG; __IO uint32_t CLKSRCSEL; __IO uint32_t CANSLEEPCLR; __IO uint32_t CANWAKEFLAGS; uint32_t RESERVED4[10]; __IO uint32_t EXTINT; /* External Interrupts */ uint32_t RESERVED5; __IO uint32_t EXTMODE; __IO uint32_t EXTPOLAR; uint32_t RESERVED6[12]; __IO uint32_t RSID; /* Reset */ uint32_t RESERVED7[7]; __IO uint32_t SCS; /* Syscon Miscellaneous Registers */ __IO uint32_t IRCTRIM; /* Clock Dividers */ __IO uint32_t PCLKSEL0; __IO uint32_t PCLKSEL1; uint32_t RESERVED8[4]; __IO uint32_t USBIntSt; /* USB Device/OTG Interrupt Register */ __IO uint32_t DMAREQSEL; __IO uint32_t CLKOUTCFG; /* Clock Output Configuration */ } LPC_SC_TypeDef; /*------------- Pin Connect Block (PINCON) -----------------------------------*/ typedef struct { __IO uint32_t PINSEL0; __IO uint32_t PINSEL1; __IO uint32_t PINSEL2; __IO uint32_t PINSEL3; __IO uint32_t PINSEL4; __IO uint32_t PINSEL5; __IO uint32_t PINSEL6; __IO uint32_t PINSEL7; __IO uint32_t PINSEL8; __IO uint32_t PINSEL9; __IO uint32_t PINSEL10; uint32_t RESERVED0[5]; __IO uint32_t PINMODE0; __IO uint32_t PINMODE1; __IO uint32_t PINMODE2; __IO uint32_t PINMODE3; __IO uint32_t PINMODE4; __IO uint32_t PINMODE5; __IO uint32_t PINMODE6; __IO uint32_t PINMODE7; __IO uint32_t PINMODE8; __IO uint32_t PINMODE9; __IO uint32_t PINMODE_OD0; __IO uint32_t PINMODE_OD1; __IO uint32_t PINMODE_OD2; __IO uint32_t PINMODE_OD3; __IO uint32_t PINMODE_OD4; __IO uint32_t I2CPADCFG; } LPC_PINCON_TypeDef; /*------------- General Purpose Input/Output (GPIO) --------------------------*/ typedef struct { union { __IO uint32_t FIODIR; struct { __IO uint16_t FIODIRL; __IO uint16_t FIODIRH; }; struct { __IO uint8_t FIODIR0; __IO uint8_t FIODIR1; __IO uint8_t FIODIR2; __IO uint8_t FIODIR3; }; }; uint32_t RESERVED0[3]; union { __IO uint32_t FIOMASK; struct { __IO uint16_t FIOMASKL; __IO uint16_t FIOMASKH; }; struct { __IO uint8_t FIOMASK0; __IO uint8_t FIOMASK1; __IO uint8_t FIOMASK2; __IO uint8_t FIOMASK3; }; }; union { __IO uint32_t FIOPIN; struct { __IO uint16_t FIOPINL; __IO uint16_t FIOPINH; }; struct { __IO uint8_t FIOPIN0; __IO uint8_t FIOPIN1; __IO uint8_t FIOPIN2; __IO uint8_t FIOPIN3; }; }; union { __IO uint32_t FIOSET; struct { __IO uint16_t FIOSETL; __IO uint16_t FIOSETH; }; struct { __IO uint8_t FIOSET0; __IO uint8_t FIOSET1; __IO uint8_t FIOSET2; __IO uint8_t FIOSET3; }; }; union { __O uint32_t FIOCLR; struct { __O uint16_t FIOCLRL; __O uint16_t FIOCLRH; }; struct { __O uint8_t FIOCLR0; __O uint8_t FIOCLR1; __O uint8_t FIOCLR2; __O uint8_t FIOCLR3; }; }; } LPC_GPIO_TypeDef; typedef struct { __I uint32_t IntStatus; __I uint32_t IO0IntStatR; __I uint32_t IO0IntStatF; __O uint32_t IO0IntClr; __IO uint32_t IO0IntEnR; __IO uint32_t IO0IntEnF; uint32_t RESERVED0[3]; __I uint32_t IO2IntStatR; __I uint32_t IO2IntStatF; __O uint32_t IO2IntClr; __IO uint32_t IO2IntEnR; __IO uint32_t IO2IntEnF; } LPC_GPIOINT_TypeDef; /*------------- Timer (TIM) --------------------------------------------------*/ typedef struct { __IO uint32_t IR; __IO uint32_t TCR; __IO uint32_t TC; __IO uint32_t PR; __IO uint32_t PC; __IO uint32_t MCR; __IO uint32_t MR0; __IO uint32_t MR1; __IO uint32_t MR2; __IO uint32_t MR3; __IO uint32_t CCR; __I uint32_t CR0; __I uint32_t CR1; uint32_t RESERVED0[2]; __IO uint32_t EMR; uint32_t RESERVED1[12]; __IO uint32_t CTCR; } LPC_TIM_TypeDef; /*------------- Pulse-Width Modulation (PWM) ---------------------------------*/ typedef struct { __IO uint32_t IR; __IO uint32_t TCR; __IO uint32_t TC; __IO uint32_t PR; __IO uint32_t PC; __IO uint32_t MCR; __IO uint32_t MR0; __IO uint32_t MR1; __IO uint32_t MR2; __IO uint32_t MR3; __IO uint32_t CCR; __I uint32_t CR0; __I uint32_t CR1; __I uint32_t CR2; __I uint32_t CR3; uint32_t RESERVED0; __IO uint32_t MR4; __IO uint32_t MR5; __IO uint32_t MR6; __IO uint32_t PCR; __IO uint32_t LER; uint32_t RESERVED1[7]; __IO uint32_t CTCR; } LPC_PWM_TypeDef; /*------------- Universal Asynchronous Receiver Transmitter (UART) -----------*/ typedef struct { union { __I uint8_t RBR; __O uint8_t THR; __IO uint8_t DLL; uint32_t RESERVED0; }; union { __IO uint8_t DLM; __IO uint32_t IER; }; union { __I uint32_t IIR; __O uint8_t FCR; }; __IO uint8_t LCR; uint8_t RESERVED1[7]; __I uint8_t LSR; uint8_t RESERVED2[7]; __IO uint8_t SCR; uint8_t RESERVED3[3]; __IO uint32_t ACR; __IO uint8_t ICR; uint8_t RESERVED4[3]; __IO uint8_t FDR; uint8_t RESERVED5[7]; __IO uint8_t TER; uint8_t RESERVED6[39]; __IO uint32_t FIFOLVL; } LPC_UART_TypeDef; typedef struct { union { __I uint8_t RBR; __O uint8_t THR; __IO uint8_t DLL; uint32_t RESERVED0; }; union { __IO uint8_t DLM; __IO uint32_t IER; }; union { __I uint32_t IIR; __O uint8_t FCR; }; __IO uint8_t LCR; uint8_t RESERVED1[7]; __I uint8_t LSR; uint8_t RESERVED2[7]; __IO uint8_t SCR; uint8_t RESERVED3[3]; __IO uint32_t ACR; __IO uint8_t ICR; uint8_t RESERVED4[3]; __IO uint8_t FDR; uint8_t RESERVED5[7]; __IO uint8_t TER; uint8_t RESERVED6[39]; __IO uint32_t FIFOLVL; } LPC_UART0_TypeDef; typedef struct { union { __I uint8_t RBR; __O uint8_t THR; __IO uint8_t DLL; uint32_t RESERVED0; }; union { __IO uint8_t DLM; __IO uint32_t IER; }; union { __I uint32_t IIR; __O uint8_t FCR; }; __IO uint8_t LCR; uint8_t RESERVED1[3]; __IO uint8_t MCR; uint8_t RESERVED2[3]; __I uint8_t LSR; uint8_t RESERVED3[3]; __I uint8_t MSR; uint8_t RESERVED4[3]; __IO uint8_t SCR; uint8_t RESERVED5[3]; __IO uint32_t ACR; uint32_t RESERVED6; __IO uint32_t FDR; uint32_t RESERVED7; __IO uint8_t TER; uint8_t RESERVED8[27]; __IO uint8_t RS485CTRL; uint8_t RESERVED9[3]; __IO uint8_t ADRMATCH; uint8_t RESERVED10[3]; __IO uint8_t RS485DLY; uint8_t RESERVED11[3]; __IO uint32_t FIFOLVL; } LPC_UART1_TypeDef; /*------------- Serial Peripheral Interface (SPI) ----------------------------*/ typedef struct { __IO uint32_t SPCR; __I uint32_t SPSR; __IO uint32_t SPDR; __IO uint32_t SPCCR; uint32_t RESERVED0[3]; __IO uint32_t SPINT; } LPC_SPI_TypeDef; /*------------- Synchronous Serial Communication (SSP) -----------------------*/ typedef struct { __IO uint32_t CR0; __IO uint32_t CR1; __IO uint32_t DR; __I uint32_t SR; __IO uint32_t CPSR; __IO uint32_t IMSC; __IO uint32_t RIS; __IO uint32_t MIS; __IO uint32_t ICR; __IO uint32_t DMACR; } LPC_SSP_TypeDef; /*------------- Inter-Integrated Circuit (I2C) -------------------------------*/ typedef struct { __IO uint32_t I2CONSET; __I uint32_t I2STAT; __IO uint32_t I2DAT; __IO uint32_t I2ADR0; __IO uint32_t I2SCLH; __IO uint32_t I2SCLL; __O uint32_t I2CONCLR; __IO uint32_t MMCTRL; __IO uint32_t I2ADR1; __IO uint32_t I2ADR2; __IO uint32_t I2ADR3; __I uint32_t I2DATA_BUFFER; __IO uint32_t I2MASK0; __IO uint32_t I2MASK1; __IO uint32_t I2MASK2; __IO uint32_t I2MASK3; } LPC_I2C_TypeDef; /*------------- Inter IC Sound (I2S) -----------------------------------------*/ typedef struct { __IO uint32_t I2SDAO; __IO uint32_t I2SDAI; __O uint32_t I2STXFIFO; __I uint32_t I2SRXFIFO; __I uint32_t I2SSTATE; __IO uint32_t I2SDMA1; __IO uint32_t I2SDMA2; __IO uint32_t I2SIRQ; __IO uint32_t I2STXRATE; __IO uint32_t I2SRXRATE; __IO uint32_t I2STXBITRATE; __IO uint32_t I2SRXBITRATE; __IO uint32_t I2STXMODE; __IO uint32_t I2SRXMODE; } LPC_I2S_TypeDef; /*------------- Repetitive Interrupt Timer (RIT) -----------------------------*/ typedef struct { __IO uint32_t RICOMPVAL; __IO uint32_t RIMASK; __IO uint8_t RICTRL; uint8_t RESERVED0[3]; __IO uint32_t RICOUNTER; } LPC_RIT_TypeDef; /*------------- Real-Time Clock (RTC) ----------------------------------------*/ typedef struct { __IO uint8_t ILR; uint8_t RESERVED0[7]; __IO uint8_t CCR; uint8_t RESERVED1[3]; __IO uint8_t CIIR; uint8_t RESERVED2[3]; __IO uint8_t AMR; uint8_t RESERVED3[3]; __I uint32_t CTIME0; __I uint32_t CTIME1; __I uint32_t CTIME2; __IO uint8_t SEC; uint8_t RESERVED4[3]; __IO uint8_t MIN; uint8_t RESERVED5[3]; __IO uint8_t HOUR; uint8_t RESERVED6[3]; __IO uint8_t DOM; uint8_t RESERVED7[3]; __IO uint8_t DOW; uint8_t RESERVED8[3]; __IO uint16_t DOY; uint16_t RESERVED9; __IO uint8_t MONTH; uint8_t RESERVED10[3]; __IO uint16_t YEAR; uint16_t RESERVED11; __IO uint32_t CALIBRATION; __IO uint32_t GPREG0; __IO uint32_t GPREG1; __IO uint32_t GPREG2; __IO uint32_t GPREG3; __IO uint32_t GPREG4; __IO uint8_t RTC_AUXEN; uint8_t RESERVED12[3]; __IO uint8_t RTC_AUX; uint8_t RESERVED13[3]; __IO uint8_t ALSEC; uint8_t RESERVED14[3]; __IO uint8_t ALMIN; uint8_t RESERVED15[3]; __IO uint8_t ALHOUR; uint8_t RESERVED16[3]; __IO uint8_t ALDOM; uint8_t RESERVED17[3]; __IO uint8_t ALDOW; uint8_t RESERVED18[3]; __IO uint16_t ALDOY; uint16_t RESERVED19; __IO uint8_t ALMON; uint8_t RESERVED20[3]; __IO uint16_t ALYEAR; uint16_t RESERVED21; } LPC_RTC_TypeDef; /*------------- Watchdog Timer (WDT) -----------------------------------------*/ typedef struct { __IO uint8_t WDMOD; uint8_t RESERVED0[3]; __IO uint32_t WDTC; __O uint8_t WDFEED; uint8_t RESERVED1[3]; __I uint32_t WDTV; __IO uint32_t WDCLKSEL; } LPC_WDT_TypeDef; /*------------- Analog-to-Digital Converter (ADC) ----------------------------*/ typedef struct { __IO uint32_t ADCR; __IO uint32_t ADGDR; uint32_t RESERVED0; __IO uint32_t ADINTEN; __I uint32_t ADDR0; __I uint32_t ADDR1; __I uint32_t ADDR2; __I uint32_t ADDR3; __I uint32_t ADDR4; __I uint32_t ADDR5; __I uint32_t ADDR6; __I uint32_t ADDR7; __I uint32_t ADSTAT; __IO uint32_t ADTRM; } LPC_ADC_TypeDef; /*------------- Digital-to-Analog Converter (DAC) ----------------------------*/ typedef struct { __IO uint32_t DACR; __IO uint32_t DACCTRL; __IO uint16_t DACCNTVAL; } LPC_DAC_TypeDef; /*------------- Motor Control Pulse-Width Modulation (MCPWM) -----------------*/ typedef struct { __I uint32_t MCCON; __O uint32_t MCCON_SET; __O uint32_t MCCON_CLR; __I uint32_t MCCAPCON; __O uint32_t MCCAPCON_SET; __O uint32_t MCCAPCON_CLR; __IO uint32_t MCTIM0; __IO uint32_t MCTIM1; __IO uint32_t MCTIM2; __IO uint32_t MCPER0; __IO uint32_t MCPER1; __IO uint32_t MCPER2; __IO uint32_t MCPW0; __IO uint32_t MCPW1; __IO uint32_t MCPW2; __IO uint32_t MCDEADTIME; __IO uint32_t MCCCP; __IO uint32_t MCCR0; __IO uint32_t MCCR1; __IO uint32_t MCCR2; __I uint32_t MCINTEN; __O uint32_t MCINTEN_SET; __O uint32_t MCINTEN_CLR; __I uint32_t MCCNTCON; __O uint32_t MCCNTCON_SET; __O uint32_t MCCNTCON_CLR; __I uint32_t MCINTFLAG; __O uint32_t MCINTFLAG_SET; __O uint32_t MCINTFLAG_CLR; __O uint32_t MCCAP_CLR; } LPC_MCPWM_TypeDef; /*------------- Quadrature Encoder Interface (QEI) ---------------------------*/ typedef struct { __O uint32_t QEICON; __I uint32_t QEISTAT; __IO uint32_t QEICONF; __I uint32_t QEIPOS; __IO uint32_t QEIMAXPOS; __IO uint32_t CMPOS0; __IO uint32_t CMPOS1; __IO uint32_t CMPOS2; __I uint32_t INXCNT; __IO uint32_t INXCMP; __IO uint32_t QEILOAD; __I uint32_t QEITIME; __I uint32_t QEIVEL; __I uint32_t QEICAP; __IO uint32_t VELCOMP; __IO uint32_t FILTER; uint32_t RESERVED0[998]; __O uint32_t QEIIEC; __O uint32_t QEIIES; __I uint32_t QEIINTSTAT; __I uint32_t QEIIE; __O uint32_t QEICLR; __O uint32_t QEISET; } LPC_QEI_TypeDef; /*------------- Controller Area Network (CAN) --------------------------------*/ typedef struct { __IO uint32_t mask[512]; /* ID Masks */ } LPC_CANAF_RAM_TypeDef; typedef struct /* Acceptance Filter Registers */ { __IO uint32_t AFMR; __IO uint32_t SFF_sa; __IO uint32_t SFF_GRP_sa; __IO uint32_t EFF_sa; __IO uint32_t EFF_GRP_sa; __IO uint32_t ENDofTable; __I uint32_t LUTerrAd; __I uint32_t LUTerr; __IO uint32_t FCANIE; __IO uint32_t FCANIC0; __IO uint32_t FCANIC1; } LPC_CANAF_TypeDef; typedef struct /* Central Registers */ { __I uint32_t CANTxSR; __I uint32_t CANRxSR; __I uint32_t CANMSR; } LPC_CANCR_TypeDef; typedef struct /* Controller Registers */ { __IO uint32_t MOD; __O uint32_t CMR; __IO uint32_t GSR; __I uint32_t ICR; __IO uint32_t IER; __IO uint32_t BTR; __IO uint32_t EWL; __I uint32_t SR; __IO uint32_t RFS; __IO uint32_t RID; __IO uint32_t RDA; __IO uint32_t RDB; __IO uint32_t TFI1; __IO uint32_t TID1; __IO uint32_t TDA1; __IO uint32_t TDB1; __IO uint32_t TFI2; __IO uint32_t TID2; __IO uint32_t TDA2; __IO uint32_t TDB2; __IO uint32_t TFI3; __IO uint32_t TID3; __IO uint32_t TDA3; __IO uint32_t TDB3; } LPC_CAN_TypeDef; /*------------- General Purpose Direct Memory Access (GPDMA) -----------------*/ typedef struct /* Common Registers */ { __I uint32_t DMACIntStat; __I uint32_t DMACIntTCStat; __O uint32_t DMACIntTCClear; __I uint32_t DMACIntErrStat; __O uint32_t DMACIntErrClr; __I uint32_t DMACRawIntTCStat; __I uint32_t DMACRawIntErrStat; __I uint32_t DMACEnbldChns; __IO uint32_t DMACSoftBReq; __IO uint32_t DMACSoftSReq; __IO uint32_t DMACSoftLBReq; __IO uint32_t DMACSoftLSReq; __IO uint32_t DMACConfig; __IO uint32_t DMACSync; } LPC_GPDMA_TypeDef; typedef struct /* Channel Registers */ { __IO uint32_t DMACCSrcAddr; __IO uint32_t DMACCDestAddr; __IO uint32_t DMACCLLI; __IO uint32_t DMACCControl; __IO uint32_t DMACCConfig; } LPC_GPDMACH_TypeDef; /*------------- Universal Serial Bus (USB) -----------------------------------*/ typedef struct { __I uint32_t HcRevision; /* USB Host Registers */ __IO uint32_t HcControl; __IO uint32_t HcCommandStatus; __IO uint32_t HcInterruptStatus; __IO uint32_t HcInterruptEnable; __IO uint32_t HcInterruptDisable; __IO uint32_t HcHCCA; __I uint32_t HcPeriodCurrentED; __IO uint32_t HcControlHeadED; __IO uint32_t HcControlCurrentED; __IO uint32_t HcBulkHeadED; __IO uint32_t HcBulkCurrentED; __I uint32_t HcDoneHead; __IO uint32_t HcFmInterval; __I uint32_t HcFmRemaining; __I uint32_t HcFmNumber; __IO uint32_t HcPeriodicStart; __IO uint32_t HcLSTreshold; __IO uint32_t HcRhDescriptorA; __IO uint32_t HcRhDescriptorB; __IO uint32_t HcRhStatus; __IO uint32_t HcRhPortStatus1; __IO uint32_t HcRhPortStatus2; uint32_t RESERVED0[40]; __I uint32_t Module_ID; __I uint32_t OTGIntSt; /* USB On-The-Go Registers */ __IO uint32_t OTGIntEn; __O uint32_t OTGIntSet; __O uint32_t OTGIntClr; __IO uint32_t OTGStCtrl; __IO uint32_t OTGTmr; uint32_t RESERVED1[58]; __I uint32_t USBDevIntSt; /* USB Device Interrupt Registers */ __IO uint32_t USBDevIntEn; __O uint32_t USBDevIntClr; __O uint32_t USBDevIntSet; __O uint32_t USBCmdCode; /* USB Device SIE Command Registers */ __I uint32_t USBCmdData; __I uint32_t USBRxData; /* USB Device Transfer Registers */ __O uint32_t USBTxData; __I uint32_t USBRxPLen; __O uint32_t USBTxPLen; __IO uint32_t USBCtrl; __O uint32_t USBDevIntPri; __I uint32_t USBEpIntSt; /* USB Device Endpoint Interrupt Regs */ __IO uint32_t USBEpIntEn; __O uint32_t USBEpIntClr; __O uint32_t USBEpIntSet; __O uint32_t USBEpIntPri; __IO uint32_t USBReEp; /* USB Device Endpoint Realization Reg*/ __O uint32_t USBEpInd; __IO uint32_t USBMaxPSize; __I uint32_t USBDMARSt; /* USB Device DMA Registers */ __O uint32_t USBDMARClr; __O uint32_t USBDMARSet; uint32_t RESERVED2[9]; __IO uint32_t USBUDCAH; __I uint32_t USBEpDMASt; __O uint32_t USBEpDMAEn; __O uint32_t USBEpDMADis; __I uint32_t USBDMAIntSt; __IO uint32_t USBDMAIntEn; uint32_t RESERVED3[2]; __I uint32_t USBEoTIntSt; __O uint32_t USBEoTIntClr; __O uint32_t USBEoTIntSet; __I uint32_t USBNDDRIntSt; __O uint32_t USBNDDRIntClr; __O uint32_t USBNDDRIntSet; __I uint32_t USBSysErrIntSt; __O uint32_t USBSysErrIntClr; __O uint32_t USBSysErrIntSet; uint32_t RESERVED4[15]; union { __I uint32_t I2C_RX; /* USB OTG I2C Registers */ __O uint32_t I2C_TX; }; __I uint32_t I2C_STS; __IO uint32_t I2C_CTL; __IO uint32_t I2C_CLKHI; __O uint32_t I2C_CLKLO; uint32_t RESERVED5[824]; union { __IO uint32_t USBClkCtrl; /* USB Clock Control Registers */ __IO uint32_t OTGClkCtrl; }; union { __I uint32_t USBClkSt; __I uint32_t OTGClkSt; }; } LPC_USB_TypeDef; /*------------- Ethernet Media Access Controller (EMAC) ----------------------*/ typedef struct { __IO uint32_t MAC1; /* MAC Registers */ __IO uint32_t MAC2; __IO uint32_t IPGT; __IO uint32_t IPGR; __IO uint32_t CLRT; __IO uint32_t MAXF; __IO uint32_t SUPP; __IO uint32_t TEST; __IO uint32_t MCFG; __IO uint32_t MCMD; __IO uint32_t MADR; __O uint32_t MWTD; __I uint32_t MRDD; __I uint32_t MIND; uint32_t RESERVED0[2]; __IO uint32_t SA0; __IO uint32_t SA1; __IO uint32_t SA2; uint32_t RESERVED1[45]; __IO uint32_t Command; /* Control Registers */ __I uint32_t Status; __IO uint32_t RxDescriptor; __IO uint32_t RxStatus; __IO uint32_t RxDescriptorNumber; __I uint32_t RxProduceIndex; __IO uint32_t RxConsumeIndex; __IO uint32_t TxDescriptor; __IO uint32_t TxStatus; __IO uint32_t TxDescriptorNumber; __IO uint32_t TxProduceIndex; __I uint32_t TxConsumeIndex; uint32_t RESERVED2[10]; __I uint32_t TSV0; __I uint32_t TSV1; __I uint32_t RSV; uint32_t RESERVED3[3]; __IO uint32_t FlowControlCounter; __I uint32_t FlowControlStatus; uint32_t RESERVED4[34]; __IO uint32_t RxFilterCtrl; /* Rx Filter Registers */ __IO uint32_t RxFilterWoLStatus; __IO uint32_t RxFilterWoLClear; uint32_t RESERVED5; __IO uint32_t HashFilterL; __IO uint32_t HashFilterH; uint32_t RESERVED6[882]; __I uint32_t IntStatus; /* Module Control Registers */ __IO uint32_t IntEnable; __O uint32_t IntClear; __O uint32_t IntSet; uint32_t RESERVED7; __IO uint32_t PowerDown; uint32_t RESERVED8; __IO uint32_t Module_ID; } LPC_EMAC_TypeDef; #if defined ( __CC_ARM ) #pragma no_anon_unions #endif /******************************************************************************/ /* Peripheral memory map */ /******************************************************************************/ /* Base addresses */ #define LPC_FLASH_BASE (0x00000000UL) #define LPC_RAM_BASE (0x10000000UL) #define LPC_GPIO_BASE (0x2009C000UL) #define LPC_APB0_BASE (0x40000000UL) #define LPC_APB1_BASE (0x40080000UL) #define LPC_AHB_BASE (0x50000000UL) #define LPC_CM3_BASE (0xE0000000UL) /* APB0 peripherals */ #define LPC_WDT_BASE (LPC_APB0_BASE + 0x00000) #define LPC_TIM0_BASE (LPC_APB0_BASE + 0x04000) #define LPC_TIM1_BASE (LPC_APB0_BASE + 0x08000) #define LPC_UART0_BASE (LPC_APB0_BASE + 0x0C000) #define LPC_UART1_BASE (LPC_APB0_BASE + 0x10000) #define LPC_PWM1_BASE (LPC_APB0_BASE + 0x18000) #define LPC_I2C0_BASE (LPC_APB0_BASE + 0x1C000) #define LPC_SPI_BASE (LPC_APB0_BASE + 0x20000) #define LPC_RTC_BASE (LPC_APB0_BASE + 0x24000) #define LPC_GPIOINT_BASE (LPC_APB0_BASE + 0x28080) #define LPC_PINCON_BASE (LPC_APB0_BASE + 0x2C000) #define LPC_SSP1_BASE (LPC_APB0_BASE + 0x30000) #define LPC_ADC_BASE (LPC_APB0_BASE + 0x34000) #define LPC_CANAF_RAM_BASE (LPC_APB0_BASE + 0x38000) #define LPC_CANAF_BASE (LPC_APB0_BASE + 0x3C000) #define LPC_CANCR_BASE (LPC_APB0_BASE + 0x40000) #define LPC_CAN1_BASE (LPC_APB0_BASE + 0x44000) #define LPC_CAN2_BASE (LPC_APB0_BASE + 0x48000) #define LPC_I2C1_BASE (LPC_APB0_BASE + 0x5C000) /* APB1 peripherals */ #define LPC_SSP0_BASE (LPC_APB1_BASE + 0x08000) #define LPC_DAC_BASE (LPC_APB1_BASE + 0x0C000) #define LPC_TIM2_BASE (LPC_APB1_BASE + 0x10000) #define LPC_TIM3_BASE (LPC_APB1_BASE + 0x14000) #define LPC_UART2_BASE (LPC_APB1_BASE + 0x18000) #define LPC_UART3_BASE (LPC_APB1_BASE + 0x1C000) #define LPC_I2C2_BASE (LPC_APB1_BASE + 0x20000) #define LPC_I2S_BASE (LPC_APB1_BASE + 0x28000) #define LPC_RIT_BASE (LPC_APB1_BASE + 0x30000) #define LPC_MCPWM_BASE (LPC_APB1_BASE + 0x38000) #define LPC_QEI_BASE (LPC_APB1_BASE + 0x3C000) #define LPC_SC_BASE (LPC_APB1_BASE + 0x7C000) /* AHB peripherals */ #define LPC_EMAC_BASE (LPC_AHB_BASE + 0x00000) #define LPC_GPDMA_BASE (LPC_AHB_BASE + 0x04000) #define LPC_GPDMACH0_BASE (LPC_AHB_BASE + 0x04100) #define LPC_GPDMACH1_BASE (LPC_AHB_BASE + 0x04120) #define LPC_GPDMACH2_BASE (LPC_AHB_BASE + 0x04140) #define LPC_GPDMACH3_BASE (LPC_AHB_BASE + 0x04160) #define LPC_GPDMACH4_BASE (LPC_AHB_BASE + 0x04180) #define LPC_GPDMACH5_BASE (LPC_AHB_BASE + 0x041A0) #define LPC_GPDMACH6_BASE (LPC_AHB_BASE + 0x041C0) #define LPC_GPDMACH7_BASE (LPC_AHB_BASE + 0x041E0) #define LPC_USB_BASE (LPC_AHB_BASE + 0x0C000) /* GPIOs */ #define LPC_GPIO0_BASE (LPC_GPIO_BASE + 0x00000) #define LPC_GPIO1_BASE (LPC_GPIO_BASE + 0x00020) #define LPC_GPIO2_BASE (LPC_GPIO_BASE + 0x00040) #define LPC_GPIO3_BASE (LPC_GPIO_BASE + 0x00060) #define LPC_GPIO4_BASE (LPC_GPIO_BASE + 0x00080) /******************************************************************************/ /* Peripheral declaration */ /******************************************************************************/ #define LPC_SC ((LPC_SC_TypeDef *) LPC_SC_BASE ) #define LPC_GPIO0 ((LPC_GPIO_TypeDef *) LPC_GPIO0_BASE ) #define LPC_GPIO1 ((LPC_GPIO_TypeDef *) LPC_GPIO1_BASE ) #define LPC_GPIO2 ((LPC_GPIO_TypeDef *) LPC_GPIO2_BASE ) #define LPC_GPIO3 ((LPC_GPIO_TypeDef *) LPC_GPIO3_BASE ) #define LPC_GPIO4 ((LPC_GPIO_TypeDef *) LPC_GPIO4_BASE ) #define LPC_WDT ((LPC_WDT_TypeDef *) LPC_WDT_BASE ) #define LPC_TIM0 ((LPC_TIM_TypeDef *) LPC_TIM0_BASE ) #define LPC_TIM1 ((LPC_TIM_TypeDef *) LPC_TIM1_BASE ) #define LPC_TIM2 ((LPC_TIM_TypeDef *) LPC_TIM2_BASE ) #define LPC_TIM3 ((LPC_TIM_TypeDef *) LPC_TIM3_BASE ) #define LPC_RIT ((LPC_RIT_TypeDef *) LPC_RIT_BASE ) #define LPC_UART0 ((LPC_UART0_TypeDef *) LPC_UART0_BASE ) #define LPC_UART1 ((LPC_UART1_TypeDef *) LPC_UART1_BASE ) #define LPC_UART2 ((LPC_UART_TypeDef *) LPC_UART2_BASE ) #define LPC_UART3 ((LPC_UART_TypeDef *) LPC_UART3_BASE ) #define LPC_PWM1 ((LPC_PWM_TypeDef *) LPC_PWM1_BASE ) #define LPC_I2C0 ((LPC_I2C_TypeDef *) LPC_I2C0_BASE ) #define LPC_I2C1 ((LPC_I2C_TypeDef *) LPC_I2C1_BASE ) #define LPC_I2C2 ((LPC_I2C_TypeDef *) LPC_I2C2_BASE ) #define LPC_I2S ((LPC_I2S_TypeDef *) LPC_I2S_BASE ) #define LPC_SPI ((LPC_SPI_TypeDef *) LPC_SPI_BASE ) #define LPC_RTC ((LPC_RTC_TypeDef *) LPC_RTC_BASE ) #define LPC_GPIOINT ((LPC_GPIOINT_TypeDef *) LPC_GPIOINT_BASE ) #define LPC_PINCON ((LPC_PINCON_TypeDef *) LPC_PINCON_BASE ) #define LPC_SSP0 ((LPC_SSP_TypeDef *) LPC_SSP0_BASE ) #define LPC_SSP1 ((LPC_SSP_TypeDef *) LPC_SSP1_BASE ) #define LPC_ADC ((LPC_ADC_TypeDef *) LPC_ADC_BASE ) #define LPC_DAC ((LPC_DAC_TypeDef *) LPC_DAC_BASE ) #define LPC_CANAF_RAM ((LPC_CANAF_RAM_TypeDef *) LPC_CANAF_RAM_BASE) #define LPC_CANAF ((LPC_CANAF_TypeDef *) LPC_CANAF_BASE ) #define LPC_CANCR ((LPC_CANCR_TypeDef *) LPC_CANCR_BASE ) #define LPC_CAN1 ((LPC_CAN_TypeDef *) LPC_CAN1_BASE ) #define LPC_CAN2 ((LPC_CAN_TypeDef *) LPC_CAN2_BASE ) #define LPC_MCPWM ((LPC_MCPWM_TypeDef *) LPC_MCPWM_BASE ) #define LPC_QEI ((LPC_QEI_TypeDef *) LPC_QEI_BASE ) #define LPC_EMAC ((LPC_EMAC_TypeDef *) LPC_EMAC_BASE ) #define LPC_GPDMA ((LPC_GPDMA_TypeDef *) LPC_GPDMA_BASE ) #define LPC_GPDMACH0 ((LPC_GPDMACH_TypeDef *) LPC_GPDMACH0_BASE ) #define LPC_GPDMACH1 ((LPC_GPDMACH_TypeDef *) LPC_GPDMACH1_BASE ) #define LPC_GPDMACH2 ((LPC_GPDMACH_TypeDef *) LPC_GPDMACH2_BASE ) #define LPC_GPDMACH3 ((LPC_GPDMACH_TypeDef *) LPC_GPDMACH3_BASE ) #define LPC_GPDMACH4 ((LPC_GPDMACH_TypeDef *) LPC_GPDMACH4_BASE ) #define LPC_GPDMACH5 ((LPC_GPDMACH_TypeDef *) LPC_GPDMACH5_BASE ) #define LPC_GPDMACH6 ((LPC_GPDMACH_TypeDef *) LPC_GPDMACH6_BASE ) #define LPC_GPDMACH7 ((LPC_GPDMACH_TypeDef *) LPC_GPDMACH7_BASE ) #define LPC_USB ((LPC_USB_TypeDef *) LPC_USB_BASE ) #endif // __LPC17xx_H__
lgpl-2.1
farseerri/git_code
src/plugins/debugger/debuggerplugin.cpp
133201
/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://www.qt.io/licensing. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "debuggerplugin.h" #include "debuggerstartparameters.h" #include "debuggeractions.h" #include "debuggerinternalconstants.h" #include "debuggercore.h" #include "debuggerkitconfigwidget.h" #include "debuggerdialogs.h" #include "debuggerengine.h" #include "debuggeritemmanager.h" #include "debuggermainwindow.h" #include "debuggerrunconfigurationaspect.h" #include "debuggerruncontrol.h" #include "debuggerstringutils.h" #include "debuggeroptionspage.h" #include "debuggerkitinformation.h" #include "memoryagent.h" #include "breakhandler.h" #include "breakwindow.h" #include "disassemblerlines.h" #include "logwindow.h" #include "moduleswindow.h" #include "moduleshandler.h" #include "registerwindow.h" #include "snapshotwindow.h" #include "stackhandler.h" #include "stackwindow.h" #include "sourcefileswindow.h" #include "threadswindow.h" #include "watchhandler.h" #include "watchwindow.h" #include "watchutils.h" #include "unstartedappwatcherdialog.h" #include "debuggertooltipmanager.h" #include "localsandexpressionswindow.h" #include "loadcoredialog.h" #include "sourceutils.h" #include <debugger/shared/hostutils.h> #include "snapshothandler.h" #include "threadshandler.h" #include "commonoptionspage.h" #include "gdb/startgdbserverdialog.h" #include <coreplugin/actionmanager/actionmanager.h> #include <coreplugin/actionmanager/actioncontainer.h> #include <coreplugin/find/itemviewfind.h> #include <coreplugin/imode.h> #include <coreplugin/coreconstants.h> #include <coreplugin/icore.h> #include <coreplugin/messagebox.h> #include <coreplugin/messagemanager.h> #include <coreplugin/modemanager.h> #include <cppeditor/cppeditorconstants.h> #include <cpptools/cppmodelmanager.h> #include <extensionsystem/invoker.h> #include <projectexplorer/localapplicationrunconfiguration.h> #include <projectexplorer/buildmanager.h> #include <projectexplorer/taskhub.h> #include <projectexplorer/toolchain.h> #include <projectexplorer/devicesupport/deviceprocesslist.h> #include <projectexplorer/devicesupport/deviceprocessesdialog.h> #include <projectexplorer/projectexplorer.h> #include <projectexplorer/projecttree.h> #include <projectexplorer/projectexplorersettings.h> #include <projectexplorer/project.h> #include <projectexplorer/session.h> #include <projectexplorer/target.h> #include <texteditor/texteditor.h> #include <texteditor/fontsettings.h> #include <texteditor/texteditorsettings.h> #include <utils/basetreeview.h> #include <utils/hostosinfo.h> #include <utils/proxyaction.h> #include <utils/qtcassert.h> #include <utils/savedaction.h> #include <utils/statuslabel.h> #include <utils/styledbar.h> #include <utils/winutils.h> #include <QApplication> #include <QCheckBox> #include <QComboBox> #include <QDockWidget> #include <QFileDialog> #include <QHBoxLayout> #include <QHeaderView> #include <QInputDialog> #include <QMessageBox> #include <QTextBlock> #include <QToolButton> #include <QtPlugin> #include <QTreeWidget> #include <QVBoxLayout> #ifdef WITH_TESTS #include <QTest> #include <QSignalSpy> #include <QTestEventLoop> //#define WITH_BENCHMARK #ifdef WITH_BENCHMARK #include <valgrind/callgrind.h> #endif #endif // WITH_TESTS #include <climits> #define DEBUG_STATE 1 #ifdef DEBUG_STATE //# define STATE_DEBUG(s) // do { QString msg; QTextStream ts(&msg); ts << s; // showMessage(msg, LogDebug); } while (0) # define STATE_DEBUG(s) do { qDebug() << s; } while (0) #else # define STATE_DEBUG(s) #endif /*! \namespace Debugger Debugger plugin namespace */ /*! \namespace Debugger::Internal Internal namespace of the Debugger plugin \internal */ /*! \class Debugger::DebuggerEngine \brief The DebuggerEngine class is the base class of a debugger engine. \note The Debugger process itself and any helper processes like gdbserver are referred to as 'Engine', whereas the debugged process is referred to as 'Inferior'. Transitions marked by '---' are done in the individual engines. Transitions marked by '+-+' are done in the base DebuggerEngine. Transitions marked by '*' are done asynchronously. The GdbEngine->setupEngine() function is described in more detail below. The engines are responsible for local roll-back to the last acknowledged state before calling notify*Failed. I.e. before calling notifyEngineSetupFailed() any process started during setupEngine() so far must be terminated. \code DebuggerNotReady progressmanager/progressmanager.cpp + EngineSetupRequested + (calls *Engine->setupEngine()) | | | | {notify- {notify- Engine- Engine- SetupOk} SetupFailed} + + + `+-+-+> EngineSetupFailed + + + [calls RunControl->startFailed] + + + DebuggerFinished v EngineSetupOk + [calls RunControl->StartSuccessful] + InferiorSetupRequested + (calls *Engine->setupInferior()) | | | | {notify- {notify- Inferior- Inferior- SetupOk} SetupFailed} + + + ` +-+-> InferiorSetupFailed +-+-+-+-+-+->. + + InferiorSetupOk + + + EngineRunRequested + + + (calls *Engine->runEngine()) + / | | \ + / | | \ + | (core) | (attach) | | + | | | | + {notify- {notifyER&- {notifyER&- {notify- + Inferior- Inferior- Inferior- EngineRun- + Unrunnable} StopOk} RunOk} Failed} + + + + + + InferiorUnrunnable + InferiorRunOk + + + + + InferiorStopOk EngineRunFailed + + v `-+-+-+-+-+-+-+-+-+-+-+>-+ + + #Interrupt@InferiorRunOk# + + + InferiorStopRequested + #SpontaneousStop + + @InferiorRunOk# (calls *Engine-> + + interruptInferior()) + {notify- | | + Spontaneous- {notify- {notify- + Inferior- Inferior- Inferior- + StopOk} StopOk} StopFailed} + + + + + + + + + InferiorStopOk + + + + + + + + + + + #Stop@InferiorUnrunnable# + + #Creator Close Event# + + + + + InferiorShutdownRequested + + + (calls *Engine->shutdownInferior()) + | | + {notify- {notify- + Inferior- Inferior- + ShutdownOk} ShutdownFailed} + + + + + + + #Inferior exited# + + + | + + + {notifyInferior- + + + Exited} + + + + + + + InferiorExitOk + + + + + + + InferiorShutdownOk InferiorShutdownFailed + * * + EngineShutdownRequested + + + (calls *Engine->shutdownEngine()) <+-+-+-+-+-+-+-+-+-+-+-+-+-+' | | | | {notify- {notify- Engine- Engine- ShutdownOk} ShutdownFailed} + + EngineShutdownOk EngineShutdownFailed * * DebuggerFinished \endcode */ /* Here is a matching graph as a GraphViz graph. View it using * \code grep "^sg1:" debuggerplugin.cpp | cut -c5- | dot -osg1.ps -Tps && gv sg1.ps sg1: digraph DebuggerStates { sg1: DebuggerNotReady -> EngineSetupRequested sg1: EngineSetupRequested -> EngineSetupOk [ label="notifyEngineSetupOk", style="dashed" ]; sg1: EngineSetupRequested -> EngineSetupFailed [ label= "notifyEngineSetupFailed", style="dashed"]; sg1: EngineSetupFailed -> DebuggerFinished [ label= "RunControl::StartFailed" ]; sg1: EngineSetupOk -> InferiorSetupRequested [ label= "RunControl::StartSuccessful" ]; sg1: InferiorSetupRequested -> InferiorSetupOk [ label="notifyInferiorSetupOk", style="dashed" ]; sg1: InferiorSetupRequested -> InferiorSetupFailed [ label="notifyInferiorFailed", style="dashed" ]; sg1: InferiorSetupOk -> EngineRunRequested sg1: InferiorSetupFailed -> EngineShutdownRequested sg1: EngineRunRequested -> InferiorUnrunnable [ label="notifyInferiorUnrunnable", style="dashed" ]; sg1: EngineRunRequested -> InferiorStopOk [ label="notifyEngineRunAndInferiorStopOk", style="dashed" ]; sg1: EngineRunRequested -> InferiorRunOk [ label="notifyEngineRunAndInferiorRunOk", style="dashed" ]; sg1: EngineRunRequested -> EngineRunFailed [ label="notifyEngineRunFailed", style="dashed" ]; sg1: EngineRunFailed -> EngineShutdownRequested sg1: InferiorRunOk -> InferiorStopOk [ label="SpontaneousStop\nnotifyInferiorSpontaneousStop", style="dashed" ]; sg1: InferiorRunOk -> InferiorStopRequested [ label="User stop\nEngine::interruptInferior", style="dashed"]; sg1: InferiorStopRequested -> InferiorStopOk [ label="notifyInferiorStopOk", style="dashed" ]; sg1: InferiorStopRequested -> InferiorShutdownRequested [ label="notifyInferiorStopFailed", style="dashed" ]; sg1: InferiorStopOk -> InferiorRunRequested [ label="User\nEngine::continueInferior" ]; sg1: InferiorRunRequested -> InferiorRunOk [ label="notifyInferiorRunOk", style="dashed"]; sg1: InferiorRunRequested -> InferiorRunFailed [ label="notifyInferiorRunFailed", style="dashed"]; sg1: InferiorRunFailed -> InferiorStopOk sg1: InferiorStopOk -> InferiorShutdownRequested [ label="Close event" ]; sg1: InferiorUnrunnable -> InferiorShutdownRequested [ label="Close event" ]; sg1: InferiorShutdownRequested -> InferiorShutdownOk [ label= "Engine::shutdownInferior\nnotifyInferiorShutdownOk", style="dashed" ]; sg1: InferiorShutdownRequested -> InferiorShutdownFailed [ label="Engine::shutdownInferior\nnotifyInferiorShutdownFailed", style="dashed" ]; sg1: InferiorExited -> InferiorExitOk [ label="notifyInferiorExited", style="dashed"]; sg1: InferiorExitOk -> InferiorShutdownOk sg1: InferiorShutdownOk -> EngineShutdownRequested sg1: InferiorShutdownFailed -> EngineShutdownRequested sg1: EngineShutdownRequested -> EngineShutdownOk [ label="Engine::shutdownEngine\nnotifyEngineShutdownOk", style="dashed" ]; sg1: EngineShutdownRequested -> EngineShutdownFailed [ label="Engine::shutdownEngine\nnotifyEngineShutdownFailed", style="dashed" ]; sg1: EngineShutdownOk -> DebuggerFinished [ style = "dotted" ]; sg1: EngineShutdownFailed -> DebuggerFinished [ style = "dotted" ]; sg1: } * \endcode */ // Additional signalling: {notifyInferiorIll} {notifyEngineIll} /*! \class Debugger::Internal::GdbEngine \brief The GdbEngine class implements Debugger::Engine driving a GDB executable. GdbEngine specific startup. All happens in EngineSetupRequested state: \list \li Transitions marked by '---' are done in the individual adapters. \li Transitions marked by '+-+' are done in the GdbEngine. \endlist \code GdbEngine::setupEngine() + (calls *Adapter->startAdapter()) | | | `---> handleAdapterStartFailed() | + | {notifyEngineSetupFailed} | handleAdapterStarted() + {notifyEngineSetupOk} GdbEngine::setupInferior() + (calls *Adapter->prepareInferior()) | | | `---> handlePrepareInferiorFailed() | + | {notifyInferiorSetupFailed} | handleInferiorPrepared() + {notifyInferiorSetupOk} \endcode */ using namespace Core; using namespace Debugger::Constants; using namespace Debugger::Internal; using namespace ExtensionSystem; using namespace ProjectExplorer; using namespace TextEditor; using namespace Utils; namespace CC = Core::Constants; namespace PE = ProjectExplorer::Constants; namespace Debugger { namespace Internal { // To be passed through margin menu action's data struct BreakpointMenuContextData : public ContextData { enum Mode { Breakpoint, MessageTracePoint }; BreakpointMenuContextData() : mode(Breakpoint) {} Mode mode; }; struct TestCallBack { TestCallBack() : receiver(0), slot(0) {} TestCallBack(QObject *ob, const char *s) : receiver(ob), slot(s) {} QObject *receiver; const char *slot; QVariant cookie; }; } // namespace Internal } // namespace Debugger Q_DECLARE_METATYPE(Debugger::Internal::BreakpointMenuContextData) Q_DECLARE_METATYPE(Debugger::Internal::TestCallBack) namespace Debugger { namespace Internal { void addCdbOptionPages(QList<IOptionsPage*> *opts); void addGdbOptionPages(QList<IOptionsPage*> *opts); static QToolButton *toolButton(QAction *action) { QToolButton *button = new QToolButton; button->setDefaultAction(action); return button; } static void setProxyAction(ProxyAction *proxy, Core::Id id) { proxy->setAction(ActionManager::command(id)->action()); } static QToolButton *toolButton(Core::Id id) { return toolButton(ActionManager::command(id)->action()); } /////////////////////////////////////////////////////////////////////// // // DummyEngine // /////////////////////////////////////////////////////////////////////// class DummyEngine : public DebuggerEngine { Q_OBJECT public: DummyEngine() : DebuggerEngine(DebuggerStartParameters()) {} ~DummyEngine() {} void setupEngine() {} void setupInferior() {} void runEngine() {} void shutdownEngine() {} void shutdownInferior() {} bool hasCapability(unsigned cap) const; bool acceptsBreakpoint(BreakpointModelId) const { return false; } bool acceptsDebuggerCommands() const { return false; } void selectThread(ThreadId) {} }; bool DummyEngine::hasCapability(unsigned cap) const { // This can only be a first approximation of what to expect when running. Project *project = ProjectTree::currentProject(); if (!project) return 0; Target *target = project->activeTarget(); QTC_ASSERT(target, return 0); RunConfiguration *activeRc = target->activeRunConfiguration(); QTC_ASSERT(activeRc, return 0); // This is a non-started Cdb or Gdb engine: if (activeRc->extraAspect<Debugger::DebuggerRunConfigurationAspect>()->useCppDebugger()) return cap & (WatchpointByAddressCapability | BreakConditionCapability | TracePointCapability | OperateNativeMixed | OperateByInstructionCapability); // This is a Qml or unknown engine. return cap & AddWatcherCapability; } /////////////////////////////////////////////////////////////////////// // // DebugMode // /////////////////////////////////////////////////////////////////////// class DebugMode : public IMode { public: DebugMode() { setObjectName(QLatin1String("DebugMode")); setContext(Context(C_DEBUGMODE, CC::C_NAVIGATION_PANE)); setDisplayName(DebuggerPlugin::tr("Debug")); setIcon(QIcon(QLatin1String(":/debugger/images/mode_debug.png"))); setPriority(85); setId(MODE_DEBUG); } ~DebugMode() { delete m_widget; } }; /////////////////////////////////////////////////////////////////////// // // Misc // /////////////////////////////////////////////////////////////////////// static QWidget *addSearch(BaseTreeView *treeView, const QString &title, const char *objectName) { QAction *act = action(UseAlternatingRowColors); treeView->setAlternatingRowColors(act->isChecked()); QObject::connect(act, &QAction::toggled, treeView, &BaseTreeView::setAlternatingRowColorsHelper); QWidget *widget = ItemViewFind::createSearchableWrapper(treeView); widget->setObjectName(QLatin1String(objectName)); widget->setWindowTitle(title); return widget; } static std::function<bool(const Kit *)> cdbMatcher(char wordWidth = 0) { return [wordWidth](const Kit *k) -> bool { if (DebuggerKitInformation::engineType(k) != CdbEngineType || !DebuggerKitInformation::isValidDebugger(k)) { return false; } if (wordWidth) { const ToolChain *tc = ToolChainKitInformation::toolChain(k); return tc && wordWidth == tc->targetAbi().wordWidth(); } return true; }; } // Find a CDB kit for debugging unknown processes. // On a 64bit OS, prefer a 64bit debugger. static Kit *findUniversalCdbKit() { if (Utils::is64BitWindowsSystem()) { if (Kit *cdb64Kit = KitManager::find(cdbMatcher(64))) return cdb64Kit; } return KitManager::find(cdbMatcher()); } static bool currentTextEditorPosition(ContextData *data) { BaseTextEditor *textEditor = BaseTextEditor::currentTextEditor(); if (!textEditor) return false; const TextDocument *document = textEditor->textDocument(); QTC_ASSERT(document, return false); data->fileName = document->filePath().toString(); if (document->property(Constants::OPENED_WITH_DISASSEMBLY).toBool()) { int lineNumber = textEditor->currentLine(); QString line = textEditor->textDocument()->plainText() .section(QLatin1Char('\n'), lineNumber - 1, lineNumber - 1); data->address = DisassemblerLine::addressFromDisassemblyLine(line); } else { data->lineNumber = textEditor->currentLine(); } return true; } /////////////////////////////////////////////////////////////////////// // // DebuggerPluginPrivate // /////////////////////////////////////////////////////////////////////// static DebuggerPluginPrivate *dd = 0; /*! \class Debugger::Internal::DebuggerCore This is the "internal" interface of the debugger plugin that's used by debugger views and debugger engines. The interface is implemented in DebuggerPluginPrivate. */ /*! \class Debugger::Internal::DebuggerPluginPrivate Implementation of DebuggerCore. */ class DebuggerPluginPrivate : public QObject { Q_OBJECT public: explicit DebuggerPluginPrivate(DebuggerPlugin *plugin); ~DebuggerPluginPrivate(); bool initialize(const QStringList &arguments, QString *errorMessage); void extensionsInitialized(); void aboutToShutdown(); void connectEngine(DebuggerEngine *engine); void disconnectEngine() { connectEngine(0); } DebuggerEngine *dummyEngine(); void setThreads(const QStringList &list, int index) { const bool state = m_threadBox->blockSignals(true); m_threadBox->clear(); foreach (const QString &item, list) m_threadBox->addItem(item); m_threadBox->setCurrentIndex(index); m_threadBox->blockSignals(state); } DebuggerRunControl *attachToRunningProcess(Kit *kit, DeviceProcessItem process); void writeSettings() { m_debuggerSettings->writeSettings(); m_mainWindow->writeSettings(); } void selectThread(int index) { ThreadId id = m_currentEngine->threadsHandler()->threadAt(index); m_currentEngine->selectThread(id); } void breakpointSetMarginActionTriggered() { const QAction *action = qobject_cast<const QAction *>(sender()); QTC_ASSERT(action, return); const BreakpointMenuContextData data = action->data().value<BreakpointMenuContextData>(); QString message; if (data.mode == BreakpointMenuContextData::MessageTracePoint) { if (data.address) { //: Message tracepoint: Address hit. message = tr("0x%1 hit").arg(data.address, 0, 16); } else { //: Message tracepoint: %1 file, %2 line %3 function hit. message = tr("%1:%2 %3() hit").arg(QFileInfo(data.fileName).fileName()). arg(data.lineNumber). arg(cppFunctionAt(data.fileName, data.lineNumber)); } QInputDialog dialog; // Create wide input dialog. dialog.setWindowFlags(dialog.windowFlags() & ~(Qt::WindowContextHelpButtonHint|Qt::MSWindowsFixedSizeDialogHint)); dialog.resize(600, dialog.height()); dialog.setWindowTitle(tr("Add Message Tracepoint")); dialog.setLabelText (tr("Message:")); dialog.setTextValue(message); if (dialog.exec() != QDialog::Accepted || dialog.textValue().isEmpty()) return; message = dialog.textValue(); } if (data.address) toggleBreakpointByAddress(data.address, message); else toggleBreakpointByFileAndLine(data.fileName, data.lineNumber, message); } void breakpointRemoveMarginActionTriggered() { const QAction *act = qobject_cast<QAction *>(sender()); QTC_ASSERT(act, return); BreakpointModelId id = act->data().value<BreakpointModelId>(); m_breakHandler->removeBreakpoint(id); } void breakpointEnableMarginActionTriggered() { const QAction *act = qobject_cast<QAction *>(sender()); QTC_ASSERT(act, return); BreakpointModelId id = act->data().value<BreakpointModelId>(); breakHandler()->setEnabled(id, true); } void breakpointDisableMarginActionTriggered() { const QAction *act = qobject_cast<QAction *>(sender()); QTC_ASSERT(act, return); BreakpointModelId id = act->data().value<BreakpointModelId>(); breakHandler()->setEnabled(id, false); } void updateWatchersHeader(int section, int, int newSize) { m_watchersView->header()->resizeSection(section, newSize); m_returnView->header()->resizeSection(section, newSize); } void sourceFilesDockToggled(bool on) { if (on && m_currentEngine->state() == InferiorStopOk) m_currentEngine->reloadSourceFiles(); } void modulesDockToggled(bool on) { if (on && m_currentEngine->state() == InferiorStopOk) m_currentEngine->reloadModules(); } void registerDockToggled(bool on) { if (on && m_currentEngine->state() == InferiorStopOk) m_currentEngine->reloadRegisters(); } void synchronizeBreakpoints() { showMessage(QLatin1String("ATTEMPT SYNC"), LogDebug); for (int i = 0, n = m_snapshotHandler->size(); i != n; ++i) { if (DebuggerEngine *engine = m_snapshotHandler->at(i)) engine->attemptBreakpointSynchronization(); } } void editorOpened(Core::IEditor *editor); void updateBreakMenuItem(Core::IEditor *editor); void setBusyCursor(bool busy); void requestMark(TextEditor::TextEditorWidget *widget, int lineNumber, TextEditor::TextMarkRequestKind kind); void requestContextMenu(TextEditor::TextEditorWidget *widget, int lineNumber, QMenu *menu); void activatePreviousMode(); void activateDebugMode(); void toggleBreakpoint(); void toggleBreakpointByFileAndLine(const QString &fileName, int lineNumber, const QString &tracePointMessage = QString()); void toggleBreakpointByAddress(quint64 address, const QString &tracePointMessage = QString()); void onModeChanged(Core::IMode *mode); void onCoreAboutToOpen(); void showSettingsDialog(); void updateDebugWithoutDeployMenu(); void debugProject(); void debugProjectWithoutDeploy(); void debugProjectBreakMain(); void startAndDebugApplication(); void startRemoteCdbSession(); void startRemoteServer(); void attachToRemoteServer(); void attachToProcess(bool startServerOnly); void attachToRunningApplication(); void attachToUnstartedApplicationDialog(); void attachToFoundProcess(); void continueOnAttach(Debugger::DebuggerState state); void attachToQmlPort(); Q_SLOT void runScheduled(); void attachCore(); void enableReverseDebuggingTriggered(const QVariant &value); void showStatusMessage(const QString &msg, int timeout = -1); DebuggerMainWindow *mainWindow() const { return m_mainWindow; } bool isDockVisible(const QString &objectName) const { QDockWidget *dock = mainWindow()->findChild<QDockWidget *>(objectName); return dock && dock->toggleViewAction()->isChecked(); } void runControlStarted(DebuggerEngine *engine); void runControlFinished(DebuggerEngine *engine); void remoteCommand(const QStringList &options, const QStringList &); void displayDebugger(DebuggerEngine *engine, bool updateEngine = true); void dumpLog(); void cleanupViews(); void setInitialState(); void fontSettingsChanged(const TextEditor::FontSettings &settings); void updateState(DebuggerEngine *engine); void updateWatchersWindow(bool showWatch, bool showReturn); void onCurrentProjectChanged(ProjectExplorer::Project *project); void sessionLoaded(); void aboutToUnloadSession(); void aboutToSaveSession(); void coreShutdown(); #ifdef WITH_TESTS public slots: void testLoadProject(const QString &proFile, const TestCallBack &cb); void testProjectLoaded(ProjectExplorer::Project *project); void testProjectEvaluated(); void testProjectBuilt(bool success); void testUnloadProject(); void testFinished(); void testRunProject(const DebuggerStartParameters &sp, const TestCallBack &cb); void testRunControlFinished(); // void testStateMachine1(); // void testStateMachine2(); // void testStateMachine3(); void testBenchmark1(); public: Project *m_testProject; bool m_testSuccess; QList<TestCallBack> m_testCallbacks; #endif public slots: void updateDebugActions(); void handleExecDetach() { currentEngine()->resetLocation(); currentEngine()->detachDebugger(); } void handleExecContinue() { currentEngine()->resetLocation(); currentEngine()->continueInferior(); } void handleExecInterrupt() { currentEngine()->resetLocation(); currentEngine()->requestInterruptInferior(); } void handleAbort() { currentEngine()->resetLocation(); currentEngine()->abortDebugger(); } void handleReset() { currentEngine()->resetLocation(); currentEngine()->resetInferior(); } void handleExecStep() { if (currentEngine()->state() == DebuggerNotReady) { debugProjectBreakMain(); } else { currentEngine()->resetLocation(); if (boolSetting(OperateByInstruction)) currentEngine()->executeStepI(); else currentEngine()->executeStep(); } } void handleExecNext() { if (currentEngine()->state() == DebuggerNotReady) { debugProjectBreakMain(); } else { currentEngine()->resetLocation(); if (boolSetting(OperateByInstruction)) currentEngine()->executeNextI(); else currentEngine()->executeNext(); } } void handleExecStepOut() { currentEngine()->resetLocation(); currentEngine()->executeStepOut(); } void handleExecReturn() { currentEngine()->resetLocation(); currentEngine()->executeReturn(); } void handleExecJumpToLine() { currentEngine()->resetLocation(); ContextData data; if (currentTextEditorPosition(&data)) currentEngine()->executeJumpToLine(data); } void handleExecRunToLine() { currentEngine()->resetLocation(); ContextData data; if (currentTextEditorPosition(&data)) currentEngine()->executeRunToLine(data); } void handleExecRunToSelectedFunction() { BaseTextEditor *textEditor = BaseTextEditor::currentTextEditor(); QTC_ASSERT(textEditor, return); QTextCursor cursor = textEditor->textCursor(); QString functionName = cursor.selectedText(); if (functionName.isEmpty()) { const QTextBlock block = cursor.block(); const QString line = block.text(); foreach (const QString &str, line.trimmed().split(QLatin1Char('('))) { QString a; for (int i = str.size(); --i >= 0; ) { if (!str.at(i).isLetterOrNumber()) break; a = str.at(i) + a; } if (!a.isEmpty()) { functionName = a; break; } } } if (functionName.isEmpty()) { showStatusMessage(tr("No function selected.")); } else { showStatusMessage(tr("Running to function \"%1\".") .arg(functionName)); currentEngine()->resetLocation(); currentEngine()->executeRunToFunction(functionName); } } void slotEditBreakpoint() { const QAction *act = qobject_cast<QAction *>(sender()); QTC_ASSERT(act, return); const BreakpointModelId id = act->data().value<BreakpointModelId>(); QTC_ASSERT(id > 0, return); BreakTreeView::editBreakpoint(id, ICore::dialogParent()); } void slotRunToLine() { const QAction *action = qobject_cast<const QAction *>(sender()); QTC_ASSERT(action, return); const BreakpointMenuContextData data = action->data().value<BreakpointMenuContextData>(); currentEngine()->executeRunToLine(data); } void slotJumpToLine() { const QAction *action = qobject_cast<const QAction *>(sender()); QTC_ASSERT(action, return); const BreakpointMenuContextData data = action->data().value<BreakpointMenuContextData>(); currentEngine()->executeJumpToLine(data); } void slotDisassembleFunction() { const QAction *action = qobject_cast<const QAction *>(sender()); QTC_ASSERT(action, return); const StackFrame frame = action->data().value<StackFrame>(); QTC_ASSERT(!frame.function.isEmpty(), return); currentEngine()->openDisassemblerView(Location(frame)); } void handleAddToWatchWindow() { // Requires a selection, but that's the only case we want anyway. BaseTextEditor *textEditor = BaseTextEditor::currentTextEditor(); if (!textEditor) return; QTextCursor tc = textEditor->textCursor(); QString exp; if (tc.hasSelection()) { exp = tc.selectedText(); } else { int line, column; exp = cppExpressionAt(textEditor->editorWidget(), tc.position(), &line, &column); } if (currentEngine()->hasCapability(WatchComplexExpressionsCapability)) exp = removeObviousSideEffects(exp); else exp = fixCppExpression(exp); if (exp.isEmpty()) return; currentEngine()->watchHandler()->watchVariable(exp); } void handleExecExit() { currentEngine()->exitDebugger(); } void handleFrameDown() { currentEngine()->frameDown(); } void handleFrameUp() { currentEngine()->frameUp(); } void handleOperateByInstructionTriggered(bool operateByInstructionTriggered) { // Go to source only if we have the file. if (currentEngine()->stackHandler()->currentIndex() >= 0) { const StackFrame frame = currentEngine()->stackHandler()->currentFrame(); if (operateByInstructionTriggered || frame.isUsable()) currentEngine()->gotoLocation(Location(frame, true)); } } void showMessage(const QString &msg, int channel, int timeout = -1); bool parseArgument(QStringList::const_iterator &it, const QStringList::const_iterator &cend, QString *errorMessage); bool parseArguments(const QStringList &args, QString *errorMessage); void parseCommandLineArguments(); void updateQmlActions() { action(QmlUpdateOnSave)->setEnabled(boolSetting(ShowQmlObjectTree)); } public: DebuggerMainWindow *m_mainWindow; DebuggerRunControlFactory *m_debuggerRunControlFactory; Id m_previousMode; QList<DebuggerStartParameters> m_scheduledStarts; ProxyAction *m_visibleStartAction; ProxyAction *m_hiddenStopAction; QAction *m_startAction; QAction *m_debugWithoutDeployAction; QAction *m_startAndDebugApplicationAction; QAction *m_startRemoteServerAction; QAction *m_attachToRunningApplication; QAction *m_attachToUnstartedApplication; QAction *m_attachToQmlPortAction; QAction *m_attachToRemoteServerAction; QAction *m_startRemoteCdbAction; QAction *m_attachToCoreAction; QAction *m_detachAction; QAction *m_continueAction; QAction *m_exitAction; // On application output button if "Stop" is possible QAction *m_interruptAction; // On the fat debug button if "Pause" is possible QAction *m_undisturbableAction; // On the fat debug button if nothing can be done QAction *m_abortAction; QAction *m_stepAction; QAction *m_stepOutAction; QAction *m_runToLineAction; // In the debug menu QAction *m_runToSelectedFunctionAction; QAction *m_jumpToLineAction; // In the Debug menu. QAction *m_returnFromFunctionAction; QAction *m_nextAction; QAction *m_watchAction1; // In the Debug menu. QAction *m_watchAction2; // In the text editor context menu. QAction *m_breakAction; QAction *m_reverseDirectionAction; QAction *m_frameUpAction; QAction *m_frameDownAction; QAction *m_resetAction; QToolButton *m_reverseToolButton; QIcon m_startIcon; QIcon m_exitIcon; QIcon m_continueIcon; QIcon m_interruptIcon; QIcon m_locationMarkIcon; QIcon m_resetIcon; StatusLabel *m_statusLabel; QComboBox *m_threadBox; BaseTreeView *m_breakView; BaseTreeView *m_returnView; BaseTreeView *m_localsView; BaseTreeView *m_watchersView; BaseTreeView *m_inspectorView; BaseTreeView *m_registerView; BaseTreeView *m_modulesView; BaseTreeView *m_snapshotView; BaseTreeView *m_sourceFilesView; BaseTreeView *m_stackView; BaseTreeView *m_threadsView; QWidget *m_breakWindow; BreakHandler *m_breakHandler; QWidget *m_returnWindow; QWidget *m_localsWindow; QWidget *m_watchersWindow; QWidget *m_inspectorWindow; QWidget *m_registerWindow; QWidget *m_modulesWindow; QWidget *m_snapshotWindow; QWidget *m_sourceFilesWindow; QWidget *m_stackWindow; QWidget *m_threadsWindow; LogWindow *m_logWindow; LocalsAndExpressionsWindow *m_localsAndExpressionsWindow; bool m_busy; QString m_lastPermanentStatusMessage; mutable CPlusPlus::Snapshot m_codeModelSnapshot; DebuggerPlugin *m_plugin; SnapshotHandler *m_snapshotHandler; bool m_shuttingDown; DebuggerEngine *m_currentEngine; DebuggerSettings *m_debuggerSettings; QStringList m_arguments; DebuggerToolTipManager m_toolTipManager; CommonOptionsPage *m_commonOptionsPage; DummyEngine *m_dummyEngine; const QSharedPointer<GlobalDebuggerOptions> m_globalDebuggerOptions; }; DebuggerPluginPrivate::DebuggerPluginPrivate(DebuggerPlugin *plugin) : m_dummyEngine(0), m_globalDebuggerOptions(new GlobalDebuggerOptions) { qRegisterMetaType<WatchData>("WatchData"); qRegisterMetaType<ContextData>("ContextData"); qRegisterMetaType<DebuggerStartParameters>("DebuggerStartParameters"); QTC_CHECK(!dd); dd = this; m_plugin = plugin; m_startRemoteCdbAction = 0; m_shuttingDown = false; m_statusLabel = 0; m_threadBox = 0; m_breakWindow = 0; m_breakHandler = 0; m_returnWindow = 0; m_localsWindow = 0; m_watchersWindow = 0; m_inspectorWindow = 0; m_registerWindow = 0; m_modulesWindow = 0; m_snapshotWindow = 0; m_sourceFilesWindow = 0; m_stackWindow = 0; m_threadsWindow = 0; m_logWindow = 0; m_localsAndExpressionsWindow = 0; m_mainWindow = 0; m_snapshotHandler = 0; m_currentEngine = 0; m_debuggerSettings = 0; m_reverseToolButton = 0; m_startAction = 0; m_debugWithoutDeployAction = 0; m_startAndDebugApplicationAction = 0; m_attachToRemoteServerAction = 0; m_attachToRunningApplication = 0; m_attachToUnstartedApplication = 0; m_attachToQmlPortAction = 0; m_startRemoteCdbAction = 0; m_attachToCoreAction = 0; m_detachAction = 0; m_commonOptionsPage = 0; } DebuggerPluginPrivate::~DebuggerPluginPrivate() { delete m_debuggerSettings; m_debuggerSettings = 0; // Mainwindow will be deleted by debug mode. delete m_snapshotHandler; m_snapshotHandler = 0; delete m_breakHandler; m_breakHandler = 0; } DebuggerEngine *DebuggerPluginPrivate::dummyEngine() { if (!m_dummyEngine) { m_dummyEngine = new DummyEngine; m_dummyEngine->setParent(this); m_dummyEngine->setObjectName(_("DummyEngine")); } return m_dummyEngine; } static QString msgParameterMissing(const QString &a) { return DebuggerPlugin::tr("Option \"%1\" is missing the parameter.").arg(a); } bool DebuggerPluginPrivate::parseArgument(QStringList::const_iterator &it, const QStringList::const_iterator &cend, QString *errorMessage) { const QString &option = *it; // '-debug <pid>' // '-debug <exe>[,server=<server:port>][,core=<core>][,kit=<kit>]' if (*it == _("-debug")) { ++it; if (it == cend) { *errorMessage = msgParameterMissing(*it); return false; } Kit *kit = 0; DebuggerStartParameters sp; qulonglong pid = it->toULongLong(); if (pid) { sp.startMode = AttachExternal; sp.closeMode = DetachAtClose; sp.attachPID = pid; sp.displayName = tr("Process %1").arg(sp.attachPID); sp.startMessage = tr("Attaching to local process %1.").arg(sp.attachPID); } else { sp.startMode = StartExternal; QStringList args = it->split(QLatin1Char(',')); foreach (const QString &arg, args) { QString key = arg.section(QLatin1Char('='), 0, 0); QString val = arg.section(QLatin1Char('='), 1, 1); if (val.isEmpty()) { if (key.isEmpty()) { continue; } else if (sp.executable.isEmpty()) { sp.executable = key; } else { *errorMessage = DebuggerPlugin::tr("Only one executable allowed."); return false; } } if (key == QLatin1String("server")) { sp.startMode = AttachToRemoteServer; sp.remoteChannel = val; sp.displayName = tr("Remote: \"%1\"").arg(sp.remoteChannel); sp.startMessage = tr("Attaching to remote server %1.").arg(sp.remoteChannel); } else if (key == QLatin1String("core")) { sp.startMode = AttachCore; sp.closeMode = DetachAtClose; sp.coreFile = val; sp.displayName = tr("Core file \"%1\"").arg(sp.coreFile); sp.startMessage = tr("Attaching to core file %1.").arg(sp.coreFile); } else if (key == QLatin1String("kit")) { kit = KitManager::find(Id::fromString(val)); } } } if (!DebuggerRunControlFactory::fillParametersFromKit(&sp, kit, errorMessage)) return false; if (sp.startMode == StartExternal) { sp.displayName = tr("Executable file \"%1\"").arg(sp.executable); sp.startMessage = tr("Debugging file %1.").arg(sp.executable); } m_scheduledStarts.append(sp); return true; } // -wincrashevent <event-handle>:<pid>. A handle used for // a handshake when attaching to a crashed Windows process. // This is created by $QTC/src/tools/qtcdebugger/main.cpp: // args << QLatin1String("-wincrashevent") // << QString::fromLatin1("%1:%2").arg(argWinCrashEvent).arg(argProcessId); if (*it == _("-wincrashevent")) { ++it; if (it == cend) { *errorMessage = msgParameterMissing(*it); return false; } DebuggerStartParameters sp; if (!DebuggerRunControlFactory::fillParametersFromKit(&sp, findUniversalCdbKit(), errorMessage)) return false; sp.startMode = AttachCrashedExternal; sp.crashParameter = it->section(QLatin1Char(':'), 0, 0); sp.attachPID = it->section(QLatin1Char(':'), 1, 1).toULongLong(); sp.displayName = tr("Crashed process %1").arg(sp.attachPID); sp.startMessage = tr("Attaching to crashed process %1").arg(sp.attachPID); if (!sp.attachPID) { *errorMessage = DebuggerPlugin::tr("The parameter \"%1\" of option \"%2\" " "does not match the pattern <handle>:<pid>.").arg(*it, option); return false; } m_scheduledStarts.append(sp); return true; } *errorMessage = DebuggerPlugin::tr("Invalid debugger option: %1").arg(option); return false; } bool DebuggerPluginPrivate::parseArguments(const QStringList &args, QString *errorMessage) { const QStringList::const_iterator cend = args.constEnd(); for (QStringList::const_iterator it = args.constBegin(); it != cend; ++it) if (!parseArgument(it, cend, errorMessage)) return false; return true; } void DebuggerPluginPrivate::parseCommandLineArguments() { QString errorMessage; if (!parseArguments(m_arguments, &errorMessage)) { errorMessage = tr("Error evaluating command line arguments: %1") .arg(errorMessage); qWarning("%s\n", qPrintable(errorMessage)); MessageManager::write(errorMessage); } if (!m_scheduledStarts.isEmpty()) QTimer::singleShot(0, this, SLOT(runScheduled())); } bool DebuggerPluginPrivate::initialize(const QStringList &arguments, QString *errorMessage) { Q_UNUSED(errorMessage); m_arguments = arguments; if (!m_arguments.isEmpty()) connect(KitManager::instance(), &KitManager::kitsLoaded, this, &DebuggerPluginPrivate::parseCommandLineArguments); // Cpp/Qml ui setup m_mainWindow = new DebuggerMainWindow; TaskHub::addCategory(Debugger::Constants::TASK_CATEGORY_DEBUGGER_DEBUGINFO, tr("Debug Information")); TaskHub::addCategory(Debugger::Constants::TASK_CATEGORY_DEBUGGER_RUNTIME, tr("Debugger Runtime")); return true; } void setConfigValue(const QByteArray &name, const QVariant &value) { ICore::settings()->setValue(_("DebugMode/" + name), value); } QVariant configValue(const QByteArray &name) { return ICore::settings()->value(_("DebugMode/" + name)); } void DebuggerPluginPrivate::onCurrentProjectChanged(Project *project) { RunConfiguration *activeRc = 0; if (project) { Target *target = project->activeTarget(); if (target) activeRc = target->activeRunConfiguration(); if (!activeRc) return; } for (int i = 0, n = m_snapshotHandler->size(); i != n; ++i) { // Run controls might be deleted during exit. if (DebuggerEngine *engine = m_snapshotHandler->at(i)) { DebuggerRunControl *runControl = engine->runControl(); RunConfiguration *rc = runControl->runConfiguration(); if (rc == activeRc) { m_snapshotHandler->setCurrentIndex(i); updateState(engine); return; } } } // If we have a running debugger, don't touch it. if (m_snapshotHandler->size()) return; // No corresponding debugger found. So we are ready to start one. m_interruptAction->setEnabled(false); m_continueAction->setEnabled(false); m_exitAction->setEnabled(false); QString whyNot; const bool canRun = ProjectExplorerPlugin::canRun(project, DebugRunMode, &whyNot); m_startAction->setEnabled(canRun); m_startAction->setToolTip(whyNot); m_debugWithoutDeployAction->setEnabled(canRun); setProxyAction(m_visibleStartAction, Core::Id(Constants::DEBUG)); } void DebuggerPluginPrivate::debugProject() { ProjectExplorerPlugin::runProject(SessionManager::startupProject(), DebugRunMode); } void DebuggerPluginPrivate::debugProjectWithoutDeploy() { ProjectExplorerPlugin::runProject(SessionManager::startupProject(), DebugRunMode, true); } void DebuggerPluginPrivate::debugProjectBreakMain() { ProjectExplorerPlugin::runProject(SessionManager::startupProject(), DebugRunModeWithBreakOnMain); } void DebuggerPluginPrivate::startAndDebugApplication() { DebuggerStartParameters sp; if (StartApplicationDialog::run(ICore::dialogParent(), &sp)) DebuggerRunControlFactory::createAndScheduleRun(sp); } void DebuggerPluginPrivate::attachCore() { AttachCoreDialog dlg(ICore::dialogParent()); const QString lastExternalKit = configValue("LastExternalKit").toString(); if (!lastExternalKit.isEmpty()) dlg.setKitId(Id::fromString(lastExternalKit)); dlg.setLocalExecutableFile(configValue("LastExternalExecutableFile").toString()); dlg.setLocalCoreFile(configValue("LastLocalCoreFile").toString()); dlg.setRemoteCoreFile(configValue("LastRemoteCoreFile").toString()); dlg.setOverrideStartScript(configValue("LastExternalStartScript").toString()); dlg.setForceLocalCoreFile(configValue("LastForceLocalCoreFile").toBool()); if (dlg.exec() != QDialog::Accepted) return; setConfigValue("LastExternalExecutableFile", dlg.localExecutableFile()); setConfigValue("LastLocalCoreFile", dlg.localCoreFile()); setConfigValue("LastRemoteCoreFile", dlg.remoteCoreFile()); setConfigValue("LastExternalKit", dlg.kit()->id().toSetting()); setConfigValue("LastExternalStartScript", dlg.overrideStartScript()); setConfigValue("LastForceLocalCoreFile", dlg.forcesLocalCoreFile()); QString display = dlg.useLocalCoreFile() ? dlg.localCoreFile() : dlg.remoteCoreFile(); DebuggerStartParameters sp; bool res = DebuggerRunControlFactory::fillParametersFromKit(&sp, dlg.kit()); QTC_ASSERT(res, return); sp.masterEngineType = DebuggerKitInformation::engineType(dlg.kit()); sp.executable = dlg.localExecutableFile(); sp.coreFile = dlg.localCoreFile(); sp.displayName = tr("Core file \"%1\"").arg(display); sp.startMode = AttachCore; sp.closeMode = DetachAtClose; sp.overrideStartScript = dlg.overrideStartScript(); DebuggerRunControlFactory::createAndScheduleRun(sp); } void DebuggerPluginPrivate::startRemoteCdbSession() { const QByteArray connectionKey = "CdbRemoteConnection"; DebuggerStartParameters sp; Kit *kit = findUniversalCdbKit(); QTC_ASSERT(kit, return); bool res = DebuggerRunControlFactory::fillParametersFromKit(&sp, kit); QTC_ASSERT(res, return); sp.startMode = AttachToRemoteServer; sp.closeMode = KillAtClose; StartRemoteCdbDialog dlg(ICore::dialogParent()); QString previousConnection = configValue(connectionKey).toString(); if (previousConnection.isEmpty()) previousConnection = QLatin1String("localhost:1234"); dlg.setConnection(previousConnection); if (dlg.exec() != QDialog::Accepted) return; sp.remoteChannel = dlg.connection(); setConfigValue(connectionKey, sp.remoteChannel); DebuggerRunControlFactory::createAndScheduleRun(sp); } void DebuggerPluginPrivate::attachToRemoteServer() { DebuggerStartParameters sp; sp.startMode = AttachToRemoteServer; if (StartApplicationDialog::run(ICore::dialogParent(), &sp)) { sp.closeMode = KillAtClose; sp.serverStartScript.clear(); DebuggerRunControlFactory::createAndScheduleRun(sp); } } void DebuggerPluginPrivate::startRemoteServer() { attachToProcess(true); } void DebuggerPluginPrivate::attachToRunningApplication() { attachToProcess(false); } void DebuggerPluginPrivate::attachToProcess(bool startServerOnly) { const DebuggerKitChooser::Mode mode = startServerOnly ? DebuggerKitChooser::RemoteDebugging : DebuggerKitChooser::LocalDebugging; DebuggerKitChooser *kitChooser = new DebuggerKitChooser(mode); DeviceProcessesDialog *dlg = new DeviceProcessesDialog(kitChooser, ICore::dialogParent()); dlg->addAcceptButton(ProjectExplorer::DeviceProcessesDialog::tr("&Attach to Process")); dlg->showAllDevices(); if (dlg->exec() == QDialog::Rejected) { delete dlg; return; } dlg->setAttribute(Qt::WA_DeleteOnClose); Kit *kit = kitChooser->currentKit(); QTC_ASSERT(kit, return); IDevice::ConstPtr device = DeviceKitInformation::device(kit); QTC_ASSERT(device, return); if (device->type() != PE::DESKTOP_DEVICE_TYPE) { GdbServerStarter *starter = new GdbServerStarter(dlg, startServerOnly); starter->run(); } else { attachToRunningProcess(kit, dlg->currentProcess()); } } void DebuggerPluginPrivate::attachToUnstartedApplicationDialog() { UnstartedAppWatcherDialog *dlg = new UnstartedAppWatcherDialog(ICore::dialogParent()); connect(dlg, &QDialog::finished, dlg, &QObject::deleteLater); connect(dlg, &UnstartedAppWatcherDialog::processFound, this, &DebuggerPluginPrivate::attachToFoundProcess); dlg->show(); } void DebuggerPluginPrivate::attachToFoundProcess() { UnstartedAppWatcherDialog *dlg = qobject_cast<UnstartedAppWatcherDialog *>(QObject::sender()); if (!dlg) return; DebuggerRunControl *rc = attachToRunningProcess(dlg->currentKit(), dlg->currentProcess()); if (!rc) return; if (dlg->hideOnAttach()) connect(rc, &RunControl::finished, dlg, &UnstartedAppWatcherDialog::startWatching); if (dlg->continueOnAttach()) { connect(currentEngine(), &DebuggerEngine::stateChanged, this, &DebuggerPluginPrivate::continueOnAttach); } } void DebuggerPluginPrivate::continueOnAttach(Debugger::DebuggerState state) { // wait for state when we can continue if (state != InferiorStopOk) return; // disconnect and continue disconnect(currentEngine(), &DebuggerEngine::stateChanged, this, &DebuggerPluginPrivate::continueOnAttach); handleExecContinue(); } DebuggerRunControl *DebuggerPluginPrivate::attachToRunningProcess(Kit *kit, DeviceProcessItem process) { QTC_ASSERT(kit, return 0); IDevice::ConstPtr device = DeviceKitInformation::device(kit); QTC_ASSERT(device, return 0); if (process.pid == 0) { Core::AsynchronousMessageBox::warning(tr("Warning"), tr("Cannot attach to process with PID 0")); return 0; } bool isWindows = false; if (const ToolChain *tc = ToolChainKitInformation::toolChain(kit)) isWindows = tc->targetAbi().os() == Abi::WindowsOS; if (isWindows && isWinProcessBeingDebugged(process.pid)) { Core::AsynchronousMessageBox::warning(tr("Process Already Under Debugger Control"), tr("The process %1 is already under the control of a debugger.\n" "Qt Creator cannot attach to it.").arg(process.pid)); return 0; } if (device->type() != PE::DESKTOP_DEVICE_TYPE) { Core::AsynchronousMessageBox::warning(tr("Not a Desktop Device Type"), tr("It is only possible to attach to a locally running process.")); return 0; } DebuggerStartParameters sp; bool res = DebuggerRunControlFactory::fillParametersFromKit(&sp, kit); QTC_ASSERT(res, return 0); sp.attachPID = process.pid; sp.displayName = tr("Process %1").arg(process.pid); sp.executable = process.exe; sp.startMode = AttachExternal; sp.closeMode = DetachAtClose; return DebuggerRunControlFactory::createAndScheduleRun(sp); } void DebuggerPlugin::attachExternalApplication(RunControl *rc) { DebuggerStartParameters sp; sp.attachPID = rc->applicationProcessHandle().pid(); sp.displayName = tr("Process %1").arg(sp.attachPID); sp.startMode = AttachExternal; sp.closeMode = DetachAtClose; sp.toolChainAbi = rc->abi(); Kit *kit = 0; if (const RunConfiguration *runConfiguration = rc->runConfiguration()) if (const Target *target = runConfiguration->target()) kit = target->kit(); bool res = DebuggerRunControlFactory::fillParametersFromKit(&sp, kit); QTC_ASSERT(res, return); DebuggerRunControlFactory::createAndScheduleRun(sp); } void DebuggerPluginPrivate::attachToQmlPort() { DebuggerStartParameters sp; AttachToQmlPortDialog dlg(ICore::mainWindow()); const QVariant qmlServerPort = configValue("LastQmlServerPort"); if (qmlServerPort.isValid()) dlg.setPort(qmlServerPort.toInt()); else dlg.setPort(sp.qmlServerPort); const Id kitId = Id::fromSetting(configValue("LastProfile")); if (kitId.isValid()) dlg.setKitId(kitId); if (dlg.exec() != QDialog::Accepted) return; Kit *kit = dlg.kit(); QTC_ASSERT(kit, return); bool res = DebuggerRunControlFactory::fillParametersFromKit(&sp, kit); QTC_ASSERT(res, return); setConfigValue("LastQmlServerPort", dlg.port()); setConfigValue("LastProfile", kit->id().toSetting()); IDevice::ConstPtr device = DeviceKitInformation::device(kit); if (device) { sp.connParams = device->sshParameters(); sp.qmlServerAddress = device->qmlProfilerHost(); } sp.qmlServerPort = dlg.port(); sp.startMode = AttachToRemoteProcess; sp.closeMode = KillAtClose; sp.languages = QmlLanguage; sp.masterEngineType = QmlEngineType; // // get files from all the projects in the session // QList<Project *> projects = SessionManager::projects(); if (Project *startupProject = SessionManager::startupProject()) { // startup project first projects.removeOne(startupProject); projects.insert(0, startupProject); } QStringList sourceFiles; foreach (Project *project, projects) sourceFiles << project->files(Project::ExcludeGeneratedFiles); sp.projectSourceDirectory = !projects.isEmpty() ? projects.first()->projectDirectory().toString() : QString(); sp.projectSourceFiles = sourceFiles; sp.sysRoot = SysRootKitInformation::sysRoot(kit).toString(); DebuggerRunControlFactory::createAndScheduleRun(sp); } void DebuggerPluginPrivate::enableReverseDebuggingTriggered(const QVariant &value) { QTC_ASSERT(m_reverseToolButton, return); m_reverseToolButton->setVisible(value.toBool()); m_reverseDirectionAction->setChecked(false); m_reverseDirectionAction->setEnabled(value.toBool()); } void DebuggerPluginPrivate::runScheduled() { foreach (const DebuggerStartParameters &sp, m_scheduledStarts) DebuggerRunControlFactory::createAndScheduleRun(sp); } void DebuggerPluginPrivate::editorOpened(IEditor *editor) { if (auto widget = qobject_cast<TextEditorWidget *>(editor->widget())) { connect(widget, &TextEditorWidget::markRequested, this, &DebuggerPluginPrivate::requestMark); connect(widget, &TextEditorWidget::markContextMenuRequested, this, &DebuggerPluginPrivate::requestContextMenu); } } void DebuggerPluginPrivate::updateBreakMenuItem(IEditor *editor) { BaseTextEditor *textEditor = qobject_cast<BaseTextEditor *>(editor); m_breakAction->setEnabled(textEditor != 0); } void DebuggerPluginPrivate::requestContextMenu(TextEditorWidget *widget, int lineNumber, QMenu *menu) { BreakpointMenuContextData args; args.lineNumber = lineNumber; bool contextUsable = true; BreakpointModelId id = BreakpointModelId(); TextDocument *document = widget->textDocument(); args.fileName = document->filePath().toString(); if (document->property(Constants::OPENED_WITH_DISASSEMBLY).toBool()) { QString line = document->plainText() .section(QLatin1Char('\n'), lineNumber - 1, lineNumber - 1); BreakpointResponse needle; needle.type = BreakpointByAddress; needle.address = DisassemblerLine::addressFromDisassemblyLine(line); args.address = needle.address; needle.lineNumber = -1; id = breakHandler()->findSimilarBreakpoint(needle); contextUsable = args.address != 0; } else { id = breakHandler() ->findBreakpointByFileAndLine(args.fileName, lineNumber); if (!id) id = breakHandler()->findBreakpointByFileAndLine(args.fileName, lineNumber, false); } if (id) { // Remove existing breakpoint. QAction *act = new QAction(menu); act->setData(QVariant::fromValue(id)); act->setText(tr("Remove Breakpoint %1").arg(id.toString())); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::breakpointRemoveMarginActionTriggered); menu->addAction(act); // Enable/disable existing breakpoint. act = new QAction(menu); act->setData(QVariant::fromValue(id)); if (breakHandler()->isEnabled(id)) { act->setText(tr("Disable Breakpoint %1").arg(id.toString())); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::breakpointDisableMarginActionTriggered); } else { act->setText(tr("Enable Breakpoint %1").arg(id.toString())); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::breakpointEnableMarginActionTriggered); } menu->addAction(act); // Edit existing breakpoint. act = new QAction(menu); act->setText(tr("Edit Breakpoint %1...").arg(id.toString())); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::slotEditBreakpoint); act->setData(QVariant::fromValue(id)); menu->addAction(act); } else { // Handle non-existing breakpoint. const QString text = args.address ? tr("Set Breakpoint at 0x%1").arg(args.address, 0, 16) : tr("Set Breakpoint at Line %1").arg(lineNumber); QAction *act = new QAction(text, menu); act->setData(QVariant::fromValue(args)); act->setEnabled(contextUsable); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::breakpointSetMarginActionTriggered); menu->addAction(act); // Message trace point args.mode = BreakpointMenuContextData::MessageTracePoint; const QString tracePointText = args.address ? tr("Set Message Tracepoint at 0x%1...").arg(args.address, 0, 16) : tr("Set Message Tracepoint at Line %1...").arg(lineNumber); act = new QAction(tracePointText, menu); act->setData(QVariant::fromValue(args)); act->setEnabled(contextUsable); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::breakpointSetMarginActionTriggered); menu->addAction(act); } // Run to, jump to line below in stopped state. if (currentEngine()->state() == InferiorStopOk && contextUsable) { menu->addSeparator(); if (currentEngine()->hasCapability(RunToLineCapability)) { const QString runText = args.address ? DebuggerEngine::tr("Run to Address 0x%1").arg(args.address, 0, 16) : DebuggerEngine::tr("Run to Line %1").arg(args.lineNumber); QAction *runToLineAction = new QAction(runText, menu); runToLineAction->setData(QVariant::fromValue(args)); connect(runToLineAction, &QAction::triggered, this, &DebuggerPluginPrivate::slotRunToLine); menu->addAction(runToLineAction); } if (currentEngine()->hasCapability(JumpToLineCapability)) { const QString jumpText = args.address ? DebuggerEngine::tr("Jump to Address 0x%1").arg(args.address, 0, 16) : DebuggerEngine::tr("Jump to Line %1").arg(args.lineNumber); QAction *jumpToLineAction = new QAction(jumpText, menu); jumpToLineAction->setData(QVariant::fromValue(args)); connect(jumpToLineAction, &QAction::triggered, this, &DebuggerPluginPrivate::slotJumpToLine); menu->addAction(jumpToLineAction); } // Disassemble current function in stopped state. if (currentEngine()->state() == InferiorStopOk && currentEngine()->hasCapability(DisassemblerCapability)) { StackFrame frame; frame.function = cppFunctionAt(args.fileName, lineNumber); frame.line = 42; // trick gdb into mixed mode. if (!frame.function.isEmpty()) { const QString text = tr("Disassemble Function \"%1\"") .arg(frame.function); QAction *disassembleAction = new QAction(text, menu); disassembleAction->setData(QVariant::fromValue(frame)); connect(disassembleAction, &QAction::triggered, this, &DebuggerPluginPrivate::slotDisassembleFunction); menu->addAction(disassembleAction ); } } } } void DebuggerPluginPrivate::toggleBreakpoint() { BaseTextEditor *textEditor = BaseTextEditor::currentTextEditor(); QTC_ASSERT(textEditor, return); const int lineNumber = textEditor->currentLine(); if (textEditor->property(Constants::OPENED_WITH_DISASSEMBLY).toBool()) { QString line = textEditor->textDocument()->plainText() .section(QLatin1Char('\n'), lineNumber - 1, lineNumber - 1); quint64 address = DisassemblerLine::addressFromDisassemblyLine(line); toggleBreakpointByAddress(address); } else if (lineNumber >= 0) { toggleBreakpointByFileAndLine(textEditor->document()->filePath().toString(), lineNumber); } } void DebuggerPluginPrivate::toggleBreakpointByFileAndLine(const QString &fileName, int lineNumber, const QString &tracePointMessage) { BreakHandler *handler = m_breakHandler; BreakpointModelId id = handler->findBreakpointByFileAndLine(fileName, lineNumber, true); if (!id) id = handler->findBreakpointByFileAndLine(fileName, lineNumber, false); if (id) { handler->removeBreakpoint(id); } else { BreakpointParameters data(BreakpointByFileAndLine); if (boolSetting(BreakpointsFullPathByDefault)) data.pathUsage = BreakpointUseFullPath; data.tracepoint = !tracePointMessage.isEmpty(); data.message = tracePointMessage; data.fileName = fileName; data.lineNumber = lineNumber; handler->appendBreakpoint(data); } } void DebuggerPluginPrivate::toggleBreakpointByAddress(quint64 address, const QString &tracePointMessage) { BreakHandler *handler = m_breakHandler; BreakpointModelId id = handler->findBreakpointByAddress(address); if (id) { handler->removeBreakpoint(id); } else { BreakpointParameters data(BreakpointByAddress); data.tracepoint = !tracePointMessage.isEmpty(); data.message = tracePointMessage; data.address = address; handler->appendBreakpoint(data); } } void DebuggerPluginPrivate::requestMark(TextEditorWidget *widget, int lineNumber, TextMarkRequestKind kind) { if (kind != BreakpointRequest) return; TextDocument *document = widget->textDocument(); if (document->property(Constants::OPENED_WITH_DISASSEMBLY).toBool()) { QString line = document->plainText() .section(QLatin1Char('\n'), lineNumber - 1, lineNumber - 1); quint64 address = DisassemblerLine::addressFromDisassemblyLine(line); toggleBreakpointByAddress(address); } else { toggleBreakpointByFileAndLine(document->filePath().toString(), lineNumber); } } // If updateEngine is set, the engine will update its threads/modules and so forth. void DebuggerPluginPrivate::displayDebugger(DebuggerEngine *engine, bool updateEngine) { QTC_ASSERT(engine, return); disconnectEngine(); connectEngine(engine); if (updateEngine) engine->updateAll(); engine->updateViews(); } void DebuggerPluginPrivate::connectEngine(DebuggerEngine *engine) { if (!engine) engine = dummyEngine(); if (m_currentEngine == engine) return; if (m_currentEngine) m_currentEngine->resetLocation(); m_currentEngine = engine; m_localsView->setModel(engine->watchModel()); m_modulesView->setModel(engine->modulesModel()); m_registerView->setModel(engine->registerModel()); m_returnView->setModel(engine->watchModel()); m_sourceFilesView->setModel(engine->sourceFilesModel()); m_stackView->setModel(engine->stackModel()); m_threadsView->setModel(engine->threadsModel()); m_watchersView->setModel(engine->watchModel()); m_inspectorView->setModel(engine->watchModel()); mainWindow()->setEngineDebugLanguages(engine->startParameters().languages); } static void changeFontSize(QWidget *widget, qreal size) { QFont font = widget->font(); font.setPointSizeF(size); widget->setFont(font); } void DebuggerPluginPrivate::fontSettingsChanged (const TextEditor::FontSettings &settings) { if (!boolSetting(FontSizeFollowsEditor)) return; qreal size = settings.fontZoom() * settings.fontSize() / 100.; changeFontSize(m_breakWindow, size); changeFontSize(m_logWindow, size); changeFontSize(m_localsWindow, size); changeFontSize(m_modulesWindow, size); //changeFontSize(m_consoleWindow, size); changeFontSize(m_registerWindow, size); changeFontSize(m_returnWindow, size); changeFontSize(m_sourceFilesWindow, size); changeFontSize(m_stackWindow, size); changeFontSize(m_threadsWindow, size); changeFontSize(m_watchersWindow, size); changeFontSize(m_inspectorWindow, size); } void DebuggerPluginPrivate::cleanupViews() { m_reverseDirectionAction->setChecked(false); m_reverseDirectionAction->setEnabled(false); const bool closeSource = boolSetting(CloseSourceBuffersOnExit); const bool closeMemory = boolSetting(CloseMemoryBuffersOnExit); QList<IDocument *> toClose; foreach (IDocument *document, DocumentModel::openedDocuments()) { const bool isMemory = document->property(Constants::OPENED_WITH_DISASSEMBLY).toBool(); if (document->property(Constants::OPENED_BY_DEBUGGER).toBool()) { bool keepIt = true; if (document->isModified()) keepIt = true; else if (document->filePath().toString().contains(_("qeventdispatcher"))) keepIt = false; else if (isMemory) keepIt = !closeMemory; else keepIt = !closeSource; if (keepIt) document->setProperty(Constants::OPENED_BY_DEBUGGER, false); else toClose.append(document); } } EditorManager::closeDocuments(toClose); } void DebuggerPluginPrivate::setBusyCursor(bool busy) { //STATE_DEBUG("BUSY FROM: " << m_busy << " TO: " << busy); if (busy == m_busy) return; m_busy = busy; QCursor cursor(busy ? Qt::BusyCursor : Qt::ArrowCursor); m_breakWindow->setCursor(cursor); //m_consoleWindow->setCursor(cursor); m_localsWindow->setCursor(cursor); m_modulesWindow->setCursor(cursor); m_logWindow->setCursor(cursor); m_registerWindow->setCursor(cursor); m_returnWindow->setCursor(cursor); m_sourceFilesWindow->setCursor(cursor); m_stackWindow->setCursor(cursor); m_threadsWindow->setCursor(cursor); m_watchersWindow->setCursor(cursor); m_snapshotWindow->setCursor(cursor); } void DebuggerPluginPrivate::setInitialState() { m_watchersWindow->setVisible(false); m_returnWindow->setVisible(false); setBusyCursor(false); m_reverseDirectionAction->setChecked(false); m_reverseDirectionAction->setEnabled(false); m_toolTipManager.closeAllToolTips(); m_startAndDebugApplicationAction->setEnabled(true); m_attachToQmlPortAction->setEnabled(true); m_attachToCoreAction->setEnabled(true); m_attachToRemoteServerAction->setEnabled(true); m_attachToRunningApplication->setEnabled(true); m_attachToUnstartedApplication->setEnabled(true); m_detachAction->setEnabled(false); m_watchAction1->setEnabled(true); m_watchAction2->setEnabled(true); m_breakAction->setEnabled(false); //m_snapshotAction->setEnabled(false); action(OperateByInstruction)->setEnabled(false); m_exitAction->setEnabled(false); m_abortAction->setEnabled(false); m_resetAction->setEnabled(false); m_interruptAction->setEnabled(false); m_continueAction->setEnabled(false); m_stepAction->setEnabled(true); m_stepOutAction->setEnabled(false); m_runToLineAction->setEnabled(false); m_runToSelectedFunctionAction->setEnabled(true); m_returnFromFunctionAction->setEnabled(false); m_jumpToLineAction->setEnabled(false); m_nextAction->setEnabled(true); action(AutoDerefPointers)->setEnabled(true); action(ExpandStack)->setEnabled(false); } void DebuggerPluginPrivate::updateWatchersWindow(bool showWatch, bool showReturn) { m_watchersWindow->setVisible(showWatch); m_returnWindow->setVisible(showReturn); } void DebuggerPluginPrivate::updateState(DebuggerEngine *engine) { QTC_ASSERT(engine, return); QTC_ASSERT(m_watchersView->model(), return); QTC_ASSERT(m_returnView->model(), return); QTC_ASSERT(!engine->isSlaveEngine(), return); m_threadBox->setCurrentIndex(engine->threadsHandler()->currentThreadIndex()); engine->watchHandler()->updateWatchersWindow(); const DebuggerState state = engine->state(); //showMessage(QString::fromLatin1("PLUGIN SET STATE: ") // + DebuggerEngine::stateName(state), LogStatus); //qDebug() << "PLUGIN SET STATE: " << state; static DebuggerState previousState = DebuggerNotReady; if (state == previousState) return; bool actionsEnabled = DebuggerEngine::debuggerActionsEnabled(state); if (state == DebuggerNotReady) { QTC_ASSERT(false, /* We use the Core's m_debugAction here */); // F5 starts debugging. It is "startable". m_interruptAction->setEnabled(false); m_continueAction->setEnabled(false); m_exitAction->setEnabled(false); m_startAction->setEnabled(true); m_debugWithoutDeployAction->setEnabled(true); setProxyAction(m_visibleStartAction, Core::Id(Constants::DEBUG)); m_hiddenStopAction->setAction(m_undisturbableAction); } else if (state == InferiorStopOk) { // F5 continues, Shift-F5 kills. It is "continuable". m_interruptAction->setEnabled(false); m_continueAction->setEnabled(true); m_exitAction->setEnabled(true); m_startAction->setEnabled(false); m_debugWithoutDeployAction->setEnabled(false); setProxyAction(m_visibleStartAction, Core::Id(Constants::CONTINUE)); m_hiddenStopAction->setAction(m_exitAction); m_localsAndExpressionsWindow->setShowLocals(true); } else if (state == InferiorRunOk) { // Shift-F5 interrupts. It is also "interruptible". m_interruptAction->setEnabled(true); m_continueAction->setEnabled(false); m_exitAction->setEnabled(true); m_startAction->setEnabled(false); m_debugWithoutDeployAction->setEnabled(false); setProxyAction(m_visibleStartAction, Core::Id(Constants::INTERRUPT)); m_hiddenStopAction->setAction(m_interruptAction); m_localsAndExpressionsWindow->setShowLocals(false); } else if (state == DebuggerFinished) { Project *project = SessionManager::startupProject(); const bool canRun = ProjectExplorerPlugin::canRun(project, DebugRunMode); // We don't want to do anything anymore. m_interruptAction->setEnabled(false); m_continueAction->setEnabled(false); m_exitAction->setEnabled(false); m_startAction->setEnabled(canRun); m_debugWithoutDeployAction->setEnabled(canRun); setProxyAction(m_visibleStartAction, Core::Id(Constants::DEBUG)); m_hiddenStopAction->setAction(m_undisturbableAction); m_codeModelSnapshot = CPlusPlus::Snapshot(); setBusyCursor(false); cleanupViews(); } else if (state == InferiorUnrunnable) { // We don't want to do anything anymore. m_interruptAction->setEnabled(false); m_continueAction->setEnabled(false); m_exitAction->setEnabled(true); m_startAction->setEnabled(false); m_debugWithoutDeployAction->setEnabled(false); m_visibleStartAction->setAction(m_undisturbableAction); m_hiddenStopAction->setAction(m_exitAction); // show locals in core dumps m_localsAndExpressionsWindow->setShowLocals(true); } else { // Everything else is "undisturbable". m_interruptAction->setEnabled(false); m_continueAction->setEnabled(false); m_exitAction->setEnabled(false); m_startAction->setEnabled(false); m_debugWithoutDeployAction->setEnabled(false); m_visibleStartAction->setAction(m_undisturbableAction); m_hiddenStopAction->setAction(m_undisturbableAction); } m_startAndDebugApplicationAction->setEnabled(true); m_attachToQmlPortAction->setEnabled(true); m_attachToCoreAction->setEnabled(true); m_attachToRemoteServerAction->setEnabled(true); m_attachToRunningApplication->setEnabled(true); m_attachToUnstartedApplication->setEnabled(true); m_threadBox->setEnabled(state == InferiorStopOk || state == InferiorUnrunnable); const bool isCore = engine->startParameters().startMode == AttachCore; const bool stopped = state == InferiorStopOk; const bool detachable = stopped && !isCore; m_detachAction->setEnabled(detachable); if (stopped) QApplication::alert(mainWindow(), 3000); const bool canReverse = engine->hasCapability(ReverseSteppingCapability) && boolSetting(EnableReverseDebugging); m_reverseDirectionAction->setEnabled(canReverse); m_watchAction1->setEnabled(true); m_watchAction2->setEnabled(true); m_breakAction->setEnabled(true); const bool canOperateByInstruction = engine->hasCapability(OperateByInstructionCapability) && (stopped || isCore); action(OperateByInstruction)->setEnabled(canOperateByInstruction); m_abortAction->setEnabled(state != DebuggerNotReady && state != DebuggerFinished); m_resetAction->setEnabled((stopped || state == DebuggerNotReady) && engine->hasCapability(ResetInferiorCapability)); m_stepAction->setEnabled(stopped || state == DebuggerNotReady); m_nextAction->setEnabled(stopped || state == DebuggerNotReady); m_stepAction->setToolTip(QString()); m_nextAction->setToolTip(QString()); m_stepOutAction->setEnabled(stopped); m_runToLineAction->setEnabled(stopped && engine->hasCapability(RunToLineCapability)); m_runToSelectedFunctionAction->setEnabled(stopped); m_returnFromFunctionAction-> setEnabled(stopped && engine->hasCapability(ReturnFromFunctionCapability)); const bool canJump = stopped && engine->hasCapability(JumpToLineCapability); m_jumpToLineAction->setEnabled(canJump); const bool canDeref = actionsEnabled && engine->hasCapability(AutoDerefPointersCapability); action(AutoDerefPointers)->setEnabled(canDeref); action(AutoDerefPointers)->setEnabled(true); action(ExpandStack)->setEnabled(actionsEnabled); const bool notbusy = state == InferiorStopOk || state == DebuggerNotReady || state == DebuggerFinished || state == InferiorUnrunnable; setBusyCursor(!notbusy); } void DebuggerPluginPrivate::updateDebugActions() { //if we're currently debugging the actions are controlled by engine if (m_currentEngine->state() != DebuggerNotReady) return; Project *project = SessionManager::startupProject(); QString whyNot; const bool canRun = ProjectExplorerPlugin::canRun(project, DebugRunMode, &whyNot); m_startAction->setEnabled(canRun); m_startAction->setToolTip(whyNot); m_debugWithoutDeployAction->setEnabled(canRun); // Step into/next: Start and break at 'main' unless a debugger is running. if (m_snapshotHandler->currentIndex() < 0) { QString toolTip; const bool canRunAndBreakMain = ProjectExplorerPlugin::canRun(project, DebugRunModeWithBreakOnMain, &toolTip); m_stepAction->setEnabled(canRunAndBreakMain); m_nextAction->setEnabled(canRunAndBreakMain); if (canRunAndBreakMain) { QTC_ASSERT(project, return ; ); toolTip = tr("Start \"%1\" and break at function \"main()\"") .arg(project->displayName()); } m_stepAction->setToolTip(toolTip); m_nextAction->setToolTip(toolTip); } } void DebuggerPluginPrivate::onCoreAboutToOpen() { m_mainWindow->onModeChanged(ModeManager::currentMode()); } void DebuggerPluginPrivate::onModeChanged(IMode *mode) { // FIXME: This one gets always called, even if switching between modes // different then the debugger mode. E.g. Welcome and Help mode and // also on shutdown. m_mainWindow->onModeChanged(mode); if (mode->id() != Constants::MODE_DEBUG) { m_toolTipManager.leavingDebugMode(); return; } if (IEditor *editor = EditorManager::currentEditor()) editor->widget()->setFocus(); m_toolTipManager.debugModeEntered(); } void DebuggerPluginPrivate::showSettingsDialog() { ICore::showOptionsDialog(DEBUGGER_SETTINGS_CATEGORY, DEBUGGER_COMMON_SETTINGS_ID); } void DebuggerPluginPrivate::updateDebugWithoutDeployMenu() { const bool state = ProjectExplorerPlugin::projectExplorerSettings().deployBeforeRun; m_debugWithoutDeployAction->setVisible(state); } void DebuggerPluginPrivate::dumpLog() { QString fileName = QFileDialog::getSaveFileName(ICore::mainWindow(), tr("Save Debugger Log"), QDir::tempPath()); if (fileName.isEmpty()) return; FileSaver saver(fileName); if (!saver.hasError()) { QTextStream ts(saver.file()); ts << m_logWindow->inputContents(); ts << "\n\n=======================================\n\n"; ts << m_logWindow->combinedContents(); saver.setResult(&ts); } saver.finalize(ICore::mainWindow()); } /*! Activates the previous mode when the current mode is the debug mode. */ void DebuggerPluginPrivate::activatePreviousMode() { if (ModeManager::currentMode() == ModeManager::mode(MODE_DEBUG) && m_previousMode.isValid()) { ModeManager::activateMode(m_previousMode); m_previousMode = Id(); } } void DebuggerPluginPrivate::activateDebugMode() { m_reverseDirectionAction->setChecked(false); m_reverseDirectionAction->setEnabled(false); m_previousMode = ModeManager::currentMode()->id(); ModeManager::activateMode(MODE_DEBUG); } void DebuggerPluginPrivate::sessionLoaded() { m_breakHandler->loadSessionData(); dummyEngine()->watchHandler()->loadSessionData(); DebuggerToolTipManager::loadSessionData(); } void DebuggerPluginPrivate::aboutToUnloadSession() { m_toolTipManager.sessionAboutToChange(); } void DebuggerPluginPrivate::aboutToSaveSession() { dummyEngine()->watchHandler()->saveSessionData(); m_breakHandler->saveSessionData(); DebuggerToolTipManager::saveSessionData(); } void DebuggerPluginPrivate::showStatusMessage(const QString &msg0, int timeout) { showMessage(msg0, LogStatus); QString msg = msg0; msg.remove(QLatin1Char('\n')); m_statusLabel->showStatusMessage(msg, timeout); } void DebuggerPluginPrivate::coreShutdown() { m_shuttingDown = true; } const CPlusPlus::Snapshot &cppCodeModelSnapshot() { if (dd->m_codeModelSnapshot.isEmpty() && action(UseCodeModel)->isChecked()) dd->m_codeModelSnapshot = CppTools::CppModelManager::instance()->snapshot(); return dd->m_codeModelSnapshot; } void setSessionValue(const QByteArray &key, const QVariant &value) { SessionManager::setValue(QString::fromUtf8(key), value); } QVariant sessionValue(const QByteArray &key) { return SessionManager::value(QString::fromUtf8(key)); } QTreeView *inspectorView() { return dd->m_inspectorView; } void DebuggerPluginPrivate::showMessage(const QString &msg, int channel, int timeout) { //qDebug() << "PLUGIN OUTPUT: " << channel << msg; //ConsoleWindow *cw = m_consoleWindow; QTC_ASSERT(m_logWindow, return); switch (channel) { case StatusBar: // This will append to m_logWindow's output pane, too. showStatusMessage(msg, timeout); break; case LogMiscInput: m_logWindow->showInput(LogMisc, msg); m_logWindow->showOutput(LogMisc, msg); break; case LogInput: m_logWindow->showInput(LogInput, msg); m_logWindow->showOutput(LogInput, msg); break; case LogError: m_logWindow->showInput(LogError, QLatin1String("ERROR: ") + msg); m_logWindow->showOutput(LogError, QLatin1String("ERROR: ") + msg); break; default: m_logWindow->showOutput(channel, msg); break; } } void createNewDock(QWidget *widget) { QDockWidget *dockWidget = dd->m_mainWindow->createDockWidget(CppLanguage, widget); dockWidget->setWindowTitle(widget->windowTitle()); dockWidget->setFeatures(QDockWidget::DockWidgetClosable); dockWidget->show(); } static QString formatStartParameters(DebuggerStartParameters &sp) { QString rc; QTextStream str(&rc); str << "Start parameters: '" << sp.displayName << "' mode: " << sp.startMode << "\nABI: " << sp.toolChainAbi.toString() << '\n'; str << "Languages: "; if (sp.languages == AnyLanguage) str << "any"; if (sp.languages & CppLanguage) str << "c++ "; if (sp.languages & QmlLanguage) str << "qml"; str << '\n'; if (!sp.executable.isEmpty()) { str << "Executable: " << QDir::toNativeSeparators(sp.executable) << ' ' << sp.processArgs; if (sp.useTerminal) str << " [terminal]"; str << '\n'; if (!sp.workingDirectory.isEmpty()) str << "Directory: " << QDir::toNativeSeparators(sp.workingDirectory) << '\n'; } QString cmd = sp.debuggerCommand; if (!cmd.isEmpty()) str << "Debugger: " << QDir::toNativeSeparators(cmd) << '\n'; if (!sp.coreFile.isEmpty()) str << "Core: " << QDir::toNativeSeparators(sp.coreFile) << '\n'; if (sp.attachPID > 0) str << "PID: " << sp.attachPID << ' ' << sp.crashParameter << '\n'; if (!sp.projectSourceDirectory.isEmpty()) { str << "Project: " << QDir::toNativeSeparators(sp.projectSourceDirectory); if (!sp.projectBuildDirectory.isEmpty()) str << " (built: " << QDir::toNativeSeparators(sp.projectBuildDirectory) << ')'; str << '\n'; } if (!sp.qmlServerAddress.isEmpty()) str << "QML server: " << sp.qmlServerAddress << ':' << sp.qmlServerPort << '\n'; if (!sp.remoteChannel.isEmpty()) { str << "Remote: " << sp.remoteChannel << '\n'; if (!sp.remoteSourcesDir.isEmpty()) str << "Remote sources: " << sp.remoteSourcesDir << '\n'; if (!sp.remoteMountPoint.isEmpty()) str << "Remote mount point: " << sp.remoteMountPoint << " Local: " << sp.localMountDir << '\n'; } str << "Sysroot: " << sp.sysRoot << '\n'; str << "Debug Source Location: " << sp.debugSourceLocation.join(QLatin1Char(':')) << '\n'; return rc; } void DebuggerPluginPrivate::runControlStarted(DebuggerEngine *engine) { activateDebugMode(); const QString message = tr("Starting debugger \"%1\" for ABI \"%2\"...") .arg(engine->objectName()) .arg(engine->startParameters().toolChainAbi.toString()); showStatusMessage(message); showMessage(formatStartParameters(engine->startParameters()), LogDebug); showMessage(m_debuggerSettings->dump(), LogDebug); m_snapshotHandler->appendSnapshot(engine); connectEngine(engine); } void DebuggerPluginPrivate::runControlFinished(DebuggerEngine *engine) { showStatusMessage(tr("Debugger finished.")); m_snapshotHandler->removeSnapshot(engine); if (m_snapshotHandler->size() == 0) { // Last engine quits. disconnectEngine(); if (boolSetting(SwitchModeOnExit)) activatePreviousMode(); } else { // Connect to some existing engine. m_snapshotHandler->activateSnapshot(0); } action(OperateByInstruction)->setValue(QVariant(false)); m_logWindow->clearUndoRedoStacks(); } void DebuggerPluginPrivate::remoteCommand(const QStringList &options, const QStringList &) { if (options.isEmpty()) return; QString errorMessage; if (!parseArguments(options, &errorMessage)) { qWarning("%s", qPrintable(errorMessage)); return; } runScheduled(); } QMessageBox *showMessageBox(int icon, const QString &title, const QString &text, int buttons) { QMessageBox *mb = new QMessageBox(QMessageBox::Icon(icon), title, text, QMessageBox::StandardButtons(buttons), ICore::mainWindow()); mb->setAttribute(Qt::WA_DeleteOnClose); mb->setTextInteractionFlags(Qt::TextSelectableByMouse); mb->show(); return mb; } bool isNativeMixedEnabled() { static bool enabled = qEnvironmentVariableIsSet("QTC_DEBUGGER_NATIVE_MIXED"); return enabled; } bool isNativeMixedActive() { return isNativeMixedEnabled() && boolSetting(OperateNativeMixed); } void DebuggerPluginPrivate::extensionsInitialized() { const QKeySequence debugKey = QKeySequence(UseMacShortcuts ? tr("Ctrl+Y") : tr("F5")); QSettings *settings = Core::ICore::settings(); m_debuggerSettings = new DebuggerSettings; m_debuggerSettings->readSettings(); connect(ICore::instance(), &ICore::coreAboutToClose, this, &DebuggerPluginPrivate::coreShutdown); const Context globalcontext(CC::C_GLOBAL); const Context cppDebuggercontext(C_CPPDEBUGGER); const Context cppeditorcontext(CppEditor::Constants::CPPEDITOR_ID); m_startIcon = QIcon(_(":/debugger/images/debugger_start_small.png")); m_startIcon.addFile(QLatin1String(":/debugger/images/debugger_start.png")); m_exitIcon = QIcon(_(":/debugger/images/debugger_stop_small.png")); m_exitIcon.addFile(QLatin1String(":/debugger/images/debugger_stop.png")); m_continueIcon = QIcon(QLatin1String(":/debugger/images/debugger_continue_small.png")); m_continueIcon.addFile(QLatin1String(":/debugger/images/debugger_continue.png")); m_interruptIcon = QIcon(_(Core::Constants::ICON_PAUSE)); m_interruptIcon.addFile(QLatin1String(":/debugger/images/debugger_interrupt.png")); m_locationMarkIcon = QIcon(_(":/debugger/images/location_16.png")); m_resetIcon = QIcon(_(":/debugger/images/debugger_restart_small.png:")); m_resetIcon.addFile(QLatin1String(":/debugger/images/debugger_restart.png")); m_busy = false; m_statusLabel = new StatusLabel; m_logWindow = new LogWindow; m_logWindow->setObjectName(QLatin1String(DOCKWIDGET_OUTPUT)); m_breakHandler = new BreakHandler; m_breakView = new BreakTreeView; m_breakView->setSettings(settings, "Debugger.BreakWindow"); m_breakView->setModel(m_breakHandler->model()); m_breakWindow = addSearch(m_breakView, tr("Breakpoints"), DOCKWIDGET_BREAK); m_modulesView = new ModulesTreeView; m_modulesView->setSettings(settings, "Debugger.ModulesView"); m_modulesWindow = addSearch(m_modulesView, tr("Modules"), DOCKWIDGET_MODULES); m_registerView = new RegisterTreeView; m_registerView->setSettings(settings, "Debugger.RegisterView"); m_registerWindow = addSearch(m_registerView, tr("Registers"), DOCKWIDGET_REGISTER); m_stackView = new StackTreeView; m_stackView->setSettings(settings, "Debugger.StackView"); m_stackWindow = addSearch(m_stackView, tr("Stack"), DOCKWIDGET_STACK); m_sourceFilesView = new SourceFilesTreeView; m_sourceFilesView->setSettings(settings, "Debugger.SourceFilesView"); m_sourceFilesWindow = addSearch(m_sourceFilesView, tr("Source Files"), DOCKWIDGET_SOURCE_FILES); m_threadsView = new ThreadsTreeView; m_threadsView->setSettings(settings, "Debugger.ThreadsView"); m_threadsWindow = addSearch(m_threadsView, tr("Threads"), DOCKWIDGET_THREADS); m_returnView = new WatchTreeView(ReturnType); // No settings. m_returnWindow = addSearch(m_returnView, tr("Locals and Expressions"), "CppDebugReturn"); m_localsView = new WatchTreeView(LocalsType); m_localsView->setSettings(settings, "Debugger.LocalsView"); m_localsWindow = addSearch(m_localsView, tr("Locals and Expressions"), "CppDebugLocals"); m_watchersView = new WatchTreeView(WatchersType); // No settings. m_watchersWindow = addSearch(m_watchersView, tr("Locals and Expressions"), "CppDebugWatchers"); m_inspectorView = new WatchTreeView(InspectType); m_inspectorView->setSettings(settings, "Debugger.LocalsView"); // sic! same as locals view. m_inspectorWindow = addSearch(m_inspectorView, tr("Locals and Expressions"), "Inspector"); // Snapshot m_snapshotHandler = new SnapshotHandler; m_snapshotView = new SnapshotTreeView(m_snapshotHandler); m_snapshotView->setSettings(settings, "Debugger.SnapshotView"); m_snapshotView->setModel(m_snapshotHandler->model()); m_snapshotWindow = addSearch(m_snapshotView, tr("Snapshots"), DOCKWIDGET_SNAPSHOTS); // Watchers connect(m_localsView->header(), &QHeaderView::sectionResized, this, &DebuggerPluginPrivate::updateWatchersHeader, Qt::QueuedConnection); QAction *act = 0; act = m_continueAction = new QAction(tr("Continue"), this); act->setIcon(m_continueIcon); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecContinue); act = m_exitAction = new QAction(tr("Stop Debugger"), this); act->setIcon(m_exitIcon); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecExit); act = m_interruptAction = new QAction(tr("Interrupt"), this); act->setIcon(m_interruptIcon); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecInterrupt); // A "disabled pause" seems to be a good choice. act = m_undisturbableAction = new QAction(tr("Debugger is Busy"), this); act->setIcon(m_interruptIcon); act->setEnabled(false); act = m_abortAction = new QAction(tr("Abort Debugging"), this); act->setToolTip(tr("Aborts debugging and " "resets the debugger to the initial state.")); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleAbort); act = m_resetAction = new QAction(tr("Restart Debugging"),this); act->setToolTip(tr("Restart the debugging session.")); act->setIcon(m_resetIcon); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleReset); act = m_nextAction = new QAction(tr("Step Over"), this); act->setIcon(QIcon(QLatin1String(":/debugger/images/debugger_stepover_small.png"))); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecNext); act = m_stepAction = new QAction(tr("Step Into"), this); act->setIcon(QIcon(QLatin1String(":/debugger/images/debugger_stepinto_small.png"))); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecStep); act = m_stepOutAction = new QAction(tr("Step Out"), this); act->setIcon(QIcon(QLatin1String(":/debugger/images/debugger_stepout_small.png"))); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecStepOut); act = m_runToLineAction = new QAction(tr("Run to Line"), this); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecRunToLine); act = m_runToSelectedFunctionAction = new QAction(tr("Run to Selected Function"), this); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecRunToSelectedFunction); act = m_returnFromFunctionAction = new QAction(tr("Immediately Return From Inner Function"), this); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecReturn); act = m_jumpToLineAction = new QAction(tr("Jump to Line"), this); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecJumpToLine); m_breakAction = new QAction(tr("Toggle Breakpoint"), this); act = m_watchAction1 = new QAction(tr("Add Expression Evaluator"), this); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleAddToWatchWindow); act = m_watchAction2 = new QAction(tr("Add Expression Evaluator"), this); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleAddToWatchWindow); //m_snapshotAction = new QAction(tr("Create Snapshot"), this); //m_snapshotAction->setProperty(Role, RequestCreateSnapshotRole); //m_snapshotAction->setIcon( // QIcon(__(":/debugger/images/debugger_snapshot_small.png"))); act = m_reverseDirectionAction = new QAction(tr("Reverse Direction"), this); act->setCheckable(true); act->setChecked(false); act->setCheckable(false); act->setIcon(QIcon(QLatin1String(":/debugger/images/debugger_reversemode_16.png"))); act->setIconVisibleInMenu(false); act = m_frameDownAction = new QAction(tr("Move to Called Frame"), this); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleFrameDown); act = m_frameUpAction = new QAction(tr("Move to Calling Frame"), this); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleFrameUp); connect(action(OperateByInstruction), SIGNAL(triggered(bool)), SLOT(handleOperateByInstructionTriggered(bool))); ActionContainer *debugMenu = ActionManager::actionContainer(PE::M_DEBUG); // Dock widgets QDockWidget *dock = 0; dock = m_mainWindow->createDockWidget(CppLanguage, m_modulesWindow); connect(dock->toggleViewAction(), &QAction::toggled, this, &DebuggerPluginPrivate::modulesDockToggled, Qt::QueuedConnection); dock = m_mainWindow->createDockWidget(CppLanguage, m_registerWindow); connect(dock->toggleViewAction(), &QAction::toggled, this, &DebuggerPluginPrivate::registerDockToggled, Qt::QueuedConnection); dock = m_mainWindow->createDockWidget(CppLanguage, m_sourceFilesWindow); connect(dock->toggleViewAction(), &QAction::toggled, this, &DebuggerPluginPrivate::sourceFilesDockToggled, Qt::QueuedConnection); dock = m_mainWindow->createDockWidget(AnyLanguage, m_logWindow); dock->setProperty(DOCKWIDGET_DEFAULT_AREA, Qt::TopDockWidgetArea); m_mainWindow->createDockWidget(CppLanguage, m_breakWindow); m_mainWindow->createDockWidget(CppLanguage, m_snapshotWindow); m_mainWindow->createDockWidget(CppLanguage, m_stackWindow); m_mainWindow->createDockWidget(CppLanguage, m_threadsWindow); m_localsAndExpressionsWindow = new LocalsAndExpressionsWindow( m_localsWindow, m_inspectorWindow, m_returnWindow, m_watchersWindow); m_localsAndExpressionsWindow->setObjectName(QLatin1String(DOCKWIDGET_WATCHERS)); m_localsAndExpressionsWindow->setWindowTitle(m_localsWindow->windowTitle()); dock = m_mainWindow->createDockWidget(CppLanguage, m_localsAndExpressionsWindow); dock->setProperty(DOCKWIDGET_DEFAULT_AREA, Qt::RightDockWidgetArea); m_mainWindow->addStagedMenuEntries(); // Register factory of DebuggerRunControl. m_debuggerRunControlFactory = new DebuggerRunControlFactory(m_plugin); m_plugin->addAutoReleasedObject(m_debuggerRunControlFactory); // The main "Start Debugging" action. act = m_startAction = new QAction(this); QIcon debuggerIcon(QLatin1String(":/projectexplorer/images/debugger_start_small.png")); debuggerIcon.addFile(QLatin1String(":/projectexplorer/images/debugger_start.png")); act->setIcon(debuggerIcon); act->setText(tr("Start Debugging")); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::debugProject); act = m_debugWithoutDeployAction = new QAction(this); act->setText(tr("Start Debugging Without Deployment")); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::debugProjectWithoutDeploy); act = m_startAndDebugApplicationAction = new QAction(this); act->setText(tr("Start and Debug External Application...")); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::startAndDebugApplication); act = m_attachToCoreAction = new QAction(this); act->setText(tr("Load Core File...")); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::attachCore); act = m_attachToRemoteServerAction = new QAction(this); act->setText(tr("Attach to Remote Debug Server...")); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::attachToRemoteServer); act = m_startRemoteServerAction = new QAction(this); act->setText(tr("Start Remote Debug Server Attached to Process...")); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::startRemoteServer); act = m_attachToRunningApplication = new QAction(this); act->setText(tr("Attach to Running Application...")); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::attachToRunningApplication); act = m_attachToUnstartedApplication = new QAction(this); act->setText(tr("Attach to Unstarted Application...")); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::attachToUnstartedApplicationDialog); act = m_attachToQmlPortAction = new QAction(this); act->setText(tr("Attach to QML Port...")); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::attachToQmlPort); if (HostOsInfo::isWindowsHost()) { m_startRemoteCdbAction = new QAction(tr("Attach to Remote CDB Session..."), this); connect(m_startRemoteCdbAction, &QAction::triggered, this, &DebuggerPluginPrivate::startRemoteCdbSession); } act = m_detachAction = new QAction(this); act->setText(tr("Detach Debugger")); connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecDetach); // "Start Debugging" sub-menu // groups: // G_DEFAULT_ONE // G_START_LOCAL // G_START_REMOTE // G_START_QML Command *cmd = 0; ActionContainer *mstart = ActionManager::actionContainer(PE::M_DEBUG_STARTDEBUGGING); cmd = ActionManager::registerAction(m_startAction, Constants::DEBUG, globalcontext); cmd->setDescription(tr("Start Debugging")); cmd->setDefaultKeySequence(debugKey); cmd->setAttribute(Command::CA_UpdateText); mstart->addAction(cmd, CC::G_DEFAULT_ONE); m_visibleStartAction = new ProxyAction(this); m_visibleStartAction->initialize(cmd->action()); m_visibleStartAction->setAttribute(ProxyAction::UpdateText); m_visibleStartAction->setAttribute(ProxyAction::UpdateIcon); m_visibleStartAction->setAction(cmd->action()); ModeManager::addAction(m_visibleStartAction, Constants::P_ACTION_DEBUG); cmd = ActionManager::registerAction(m_debugWithoutDeployAction, "Debugger.DebugWithoutDeploy", globalcontext); cmd->setAttribute(Command::CA_Hide); mstart->addAction(cmd, CC::G_DEFAULT_ONE); cmd = ActionManager::registerAction(m_attachToRunningApplication, "Debugger.AttachToRemoteProcess", globalcontext); cmd->setDescription(tr("Attach to Running Application")); mstart->addAction(cmd, Debugger::Constants::G_GENERAL); cmd = ActionManager::registerAction(m_attachToUnstartedApplication, "Debugger.AttachToUnstartedProcess", globalcontext); cmd->setDescription(tr("Attach to Unstarted Application")); mstart->addAction(cmd, Debugger::Constants::G_GENERAL); cmd = ActionManager::registerAction(m_startAndDebugApplicationAction, "Debugger.StartAndDebugApplication", globalcontext); cmd->setAttribute(Command::CA_Hide); mstart->addAction(cmd, Debugger::Constants::G_GENERAL); cmd = ActionManager::registerAction(m_attachToCoreAction, "Debugger.AttachCore", globalcontext); cmd->setAttribute(Command::CA_Hide); mstart->addAction(cmd, Constants::G_GENERAL); cmd = ActionManager::registerAction(m_attachToRemoteServerAction, "Debugger.AttachToRemoteServer", globalcontext); cmd->setAttribute(Command::CA_Hide); mstart->addAction(cmd, Constants::G_SPECIAL); cmd = ActionManager::registerAction(m_startRemoteServerAction, "Debugger.StartRemoteServer", globalcontext); cmd->setDescription(tr("Start Gdbserver")); mstart->addAction(cmd, Constants::G_SPECIAL); if (m_startRemoteCdbAction) { cmd = ActionManager::registerAction(m_startRemoteCdbAction, "Debugger.AttachRemoteCdb", globalcontext); cmd->setAttribute(Command::CA_Hide); mstart->addAction(cmd, Constants::G_SPECIAL); } mstart->addSeparator(globalcontext, Constants::G_START_QML); cmd = ActionManager::registerAction(m_attachToQmlPortAction, "Debugger.AttachToQmlPort", globalcontext); cmd->setAttribute(Command::CA_Hide); mstart->addAction(cmd, Constants::G_START_QML); cmd = ActionManager::registerAction(m_detachAction, "Debugger.Detach", globalcontext); cmd->setAttribute(Command::CA_Hide); debugMenu->addAction(cmd, CC::G_DEFAULT_ONE); cmd = ActionManager::registerAction(m_interruptAction, Constants::INTERRUPT, globalcontext); cmd->setDescription(tr("Interrupt Debugger")); debugMenu->addAction(cmd, CC::G_DEFAULT_ONE); cmd = ActionManager::registerAction(m_continueAction, Constants::CONTINUE, globalcontext); cmd->setDefaultKeySequence(debugKey); debugMenu->addAction(cmd, CC::G_DEFAULT_ONE); cmd = ActionManager::registerAction(m_exitAction, Constants::STOP, globalcontext); debugMenu->addAction(cmd, CC::G_DEFAULT_ONE); m_hiddenStopAction = new ProxyAction(this); m_hiddenStopAction->initialize(cmd->action()); m_hiddenStopAction->setAttribute(ProxyAction::UpdateText); m_hiddenStopAction->setAttribute(ProxyAction::UpdateIcon); cmd = ActionManager::registerAction(m_hiddenStopAction, Constants::HIDDEN_STOP, globalcontext); cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Shift+Ctrl+Y") : tr("Shift+F5"))); cmd = ActionManager::registerAction(m_abortAction, Constants::ABORT, globalcontext); cmd->setDescription(tr("Reset Debugger")); debugMenu->addAction(cmd, CC::G_DEFAULT_ONE); cmd = ActionManager::registerAction(m_resetAction, Constants::RESET, globalcontext); cmd->setDescription(tr("Restart Debugging")); debugMenu->addAction(cmd, CC::G_DEFAULT_ONE); debugMenu->addSeparator(globalcontext); cmd = ActionManager::registerAction(m_nextAction, Constants::NEXT, globalcontext); cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Ctrl+Shift+O") : tr("F10"))); cmd->setAttribute(Command::CA_Hide); cmd->setAttribute(Command::CA_UpdateText); debugMenu->addAction(cmd); cmd = ActionManager::registerAction(m_stepAction, Constants::STEP, globalcontext); cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Ctrl+Shift+I") : tr("F11"))); cmd->setAttribute(Command::CA_Hide); cmd->setAttribute(Command::CA_UpdateText); debugMenu->addAction(cmd); cmd = ActionManager::registerAction(m_stepOutAction, Constants::STEPOUT, cppDebuggercontext); cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Ctrl+Shift+T") : tr("Shift+F11"))); cmd->setAttribute(Command::CA_Hide); debugMenu->addAction(cmd); cmd = ActionManager::registerAction(m_runToLineAction, "Debugger.RunToLine", cppDebuggercontext); cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Shift+F8") : tr("Ctrl+F10"))); cmd->setAttribute(Command::CA_Hide); debugMenu->addAction(cmd); cmd = ActionManager::registerAction(m_runToSelectedFunctionAction, "Debugger.RunToSelectedFunction", cppDebuggercontext); cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+F6"))); cmd->setAttribute(Command::CA_Hide); // Don't add to menu by default as keeping its enabled state // and text up-to-date is a lot of hassle. // debugMenu->addAction(cmd); cmd = ActionManager::registerAction(m_jumpToLineAction, "Debugger.JumpToLine", cppDebuggercontext); cmd->setAttribute(Command::CA_Hide); debugMenu->addAction(cmd); cmd = ActionManager::registerAction(m_returnFromFunctionAction, "Debugger.ReturnFromFunction", cppDebuggercontext); cmd->setAttribute(Command::CA_Hide); debugMenu->addAction(cmd); cmd = ActionManager::registerAction(m_reverseDirectionAction, Constants::REVERSE, cppDebuggercontext); cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? QString() : tr("F12"))); cmd->setAttribute(Command::CA_Hide); debugMenu->addAction(cmd); debugMenu->addSeparator(globalcontext); //cmd = ActionManager::registerAction(m_snapshotAction, // "Debugger.Snapshot", cppDebuggercontext); //cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+D,Ctrl+S"))); //cmd->setAttribute(Command::CA_Hide); //debugMenu->addAction(cmd); cmd = ActionManager::registerAction(m_frameDownAction, "Debugger.FrameDown", cppDebuggercontext); ActionManager::registerAction(m_frameUpAction, "Debugger.FrameUp", cppDebuggercontext); cmd = ActionManager::registerAction(action(OperateByInstruction), Constants::OPERATE_BY_INSTRUCTION, cppDebuggercontext); cmd->setAttribute(Command::CA_Hide); debugMenu->addAction(cmd); if (isNativeMixedEnabled()) { SavedAction *act = action(OperateNativeMixed); act->setValue(true); cmd = ActionManager::registerAction(act, Constants::OPERATE_NATIVE_MIXED, globalcontext); cmd->setAttribute(Command::CA_Hide); debugMenu->addAction(cmd); connect(cmd->action(), &QAction::triggered, [this] { currentEngine()->updateAll(); }); } cmd = ActionManager::registerAction(m_breakAction, "Debugger.ToggleBreak", globalcontext); cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("F8") : tr("F9"))); debugMenu->addAction(cmd); connect(m_breakAction, &QAction::triggered, this, &DebuggerPluginPrivate::toggleBreakpoint); debugMenu->addSeparator(globalcontext); // currently broken // QAction *qmlUpdateOnSaveDummyAction = new QAction(tr("Apply Changes on Save"), this); // qmlUpdateOnSaveDummyAction->setCheckable(true); // qmlUpdateOnSaveDummyAction->setIcon(QIcon(_(":/debugger/images/qml/apply-on-save.png"))); // qmlUpdateOnSaveDummyAction->setEnabled(false); // cmd = ActionManager::registerAction(qmlUpdateOnSaveDummyAction, Constants::QML_UPDATE_ON_SAVE, // globalcontext); // debugMenu->addAction(cmd); QAction *qmlShowAppOnTopDummyAction = new QAction(tr("Show Application on Top"), this); qmlShowAppOnTopDummyAction->setCheckable(true); qmlShowAppOnTopDummyAction->setIcon(QIcon(_(":/debugger/images/qml/app-on-top.png"))); qmlShowAppOnTopDummyAction->setEnabled(false); cmd = ActionManager::registerAction(qmlShowAppOnTopDummyAction, Constants::QML_SHOW_APP_ON_TOP, globalcontext); debugMenu->addAction(cmd); QAction *qmlSelectDummyAction = new QAction(tr("Select"), this); qmlSelectDummyAction->setCheckable(true); qmlSelectDummyAction->setIcon(QIcon(_(":/debugger/images/qml/select.png"))); qmlSelectDummyAction->setEnabled(false); cmd = ActionManager::registerAction(qmlSelectDummyAction, Constants::QML_SELECTTOOL, globalcontext); debugMenu->addAction(cmd); QAction *qmlZoomDummyAction = new QAction(tr("Zoom"), this); qmlZoomDummyAction->setCheckable(true); qmlZoomDummyAction->setIcon(QIcon(_(":/debugger/images/qml/zoom.png"))); qmlZoomDummyAction->setEnabled(false); cmd = ActionManager::registerAction(qmlZoomDummyAction, Constants::QML_ZOOMTOOL, globalcontext); debugMenu->addAction(cmd); debugMenu->addSeparator(globalcontext); // Don't add '1' to the string as it shows up in the shortcut dialog. cmd = ActionManager::registerAction(m_watchAction1, "Debugger.AddToWatch", cppeditorcontext); //cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+D,Ctrl+W"))); debugMenu->addAction(cmd); // If the CppEditor plugin is there, we want to add something to // the editor context menu. if (ActionContainer *editorContextMenu = ActionManager::actionContainer(CppEditor::Constants::M_CONTEXT)) { cmd = editorContextMenu->addSeparator(cppDebuggercontext); cmd->setAttribute(Command::CA_Hide); cmd = ActionManager::registerAction(m_watchAction2, "Debugger.AddToWatch2", cppDebuggercontext); cmd->action()->setEnabled(true); editorContextMenu->addAction(cmd); cmd->setAttribute(Command::CA_Hide); cmd->setAttribute(Command::CA_NonConfigurable); // Debugger.AddToWatch is enough. } QList<IOptionsPage *> engineOptionPages; addGdbOptionPages(&engineOptionPages); addCdbOptionPages(&engineOptionPages); foreach (IOptionsPage *op, engineOptionPages) m_plugin->addAutoReleasedObject(op); m_plugin->addAutoReleasedObject(new LocalsAndExpressionsOptionsPage); m_plugin->addAutoReleasedObject(new DebuggerOptionsPage); connect(ModeManager::instance(), &ModeManager::currentModeChanged, this, &DebuggerPluginPrivate::onModeChanged); connect(ICore::instance(), &ICore::coreAboutToOpen, this, &DebuggerPluginPrivate::onCoreAboutToOpen); connect(ProjectExplorerPlugin::instance(), &ProjectExplorerPlugin::settingsChanged, this, &DebuggerPluginPrivate::updateDebugWithoutDeployMenu); // Debug mode setup DebugMode *debugMode = new DebugMode; QWidget *widget = m_mainWindow->createContents(debugMode); Core::IContext *modeContextObject = new Core::IContext(this); modeContextObject->setContext(Core::Context(CC::C_EDITORMANAGER)); modeContextObject->setWidget(widget); Core::ICore::addContextObject(modeContextObject); debugMode->setWidget(widget); m_plugin->addAutoReleasedObject(debugMode); // // Connections // // Core connect(ICore::instance(), &ICore::saveSettingsRequested, this, &DebuggerPluginPrivate::writeSettings); // TextEditor connect(TextEditorSettings::instance(), &TextEditorSettings::fontSettingsChanged, this, &DebuggerPluginPrivate::fontSettingsChanged); // ProjectExplorer connect(SessionManager::instance(), &SessionManager::sessionLoaded, this, &DebuggerPluginPrivate::sessionLoaded); connect(SessionManager::instance(), &SessionManager::aboutToSaveSession, this, &DebuggerPluginPrivate::aboutToSaveSession); connect(SessionManager::instance(), &SessionManager::aboutToUnloadSession, this, &DebuggerPluginPrivate::aboutToUnloadSession); connect(ProjectExplorerPlugin::instance(), &ProjectExplorerPlugin::updateRunActions, this, &DebuggerPluginPrivate::updateDebugActions); // EditorManager connect(EditorManager::instance(), &EditorManager::editorOpened, this, &DebuggerPluginPrivate::editorOpened); connect(EditorManager::instance(), &EditorManager::currentEditorChanged, this, &DebuggerPluginPrivate::updateBreakMenuItem); // Application interaction connect(action(SettingsDialog), &QAction::triggered, this, &DebuggerPluginPrivate::showSettingsDialog); // QML Actions connect(action(ShowQmlObjectTree), &SavedAction::valueChanged, this, &DebuggerPluginPrivate::updateQmlActions); updateQmlActions(); // Toolbar QWidget *toolbarContainer = new QWidget; QHBoxLayout *hbox = new QHBoxLayout(toolbarContainer); hbox->setMargin(0); hbox->setSpacing(0); hbox->addWidget(toolButton(m_visibleStartAction)); hbox->addWidget(toolButton(Constants::STOP)); hbox->addWidget(toolButton(Constants::NEXT)); hbox->addWidget(toolButton(Constants::STEP)); hbox->addWidget(toolButton(Constants::STEPOUT)); hbox->addWidget(toolButton(Constants::RESET)); hbox->addWidget(toolButton(Constants::OPERATE_BY_INSTRUCTION)); if (isNativeMixedEnabled()) hbox->addWidget(toolButton(Constants::OPERATE_NATIVE_MIXED)); //hbox->addWidget(new StyledSeparator); m_reverseToolButton = toolButton(Constants::REVERSE); hbox->addWidget(m_reverseToolButton); //m_reverseToolButton->hide(); hbox->addWidget(new StyledSeparator); hbox->addWidget(new QLabel(tr("Threads:"))); m_threadBox = new QComboBox; m_threadBox->setSizeAdjustPolicy(QComboBox::AdjustToContents); connect(m_threadBox, static_cast<void(QComboBox::*)(int)>(&QComboBox::activated), this, &DebuggerPluginPrivate::selectThread); hbox->addWidget(m_threadBox); hbox->addSpacerItem(new QSpacerItem(4, 0)); m_mainWindow->setToolBar(CppLanguage, toolbarContainer); QWidget *qmlToolbar = new QWidget(m_mainWindow); hbox = new QHBoxLayout(qmlToolbar); hbox->setMargin(0); hbox->setSpacing(0); // currently broken //hbox->addWidget(toolButton(Constants::QML_UPDATE_ON_SAVE)); hbox->addWidget(toolButton(Constants::QML_SHOW_APP_ON_TOP)); hbox->addWidget(new StyledSeparator); hbox->addWidget(toolButton(Constants::QML_SELECTTOOL)); hbox->addWidget(toolButton(Constants::QML_ZOOMTOOL)); hbox->addWidget(new StyledSeparator); m_mainWindow->setToolBar(QmlLanguage, qmlToolbar); m_mainWindow->setToolBar(AnyLanguage, m_statusLabel); connect(action(EnableReverseDebugging), &SavedAction::valueChanged, this, &DebuggerPluginPrivate::enableReverseDebuggingTriggered); setInitialState(); connectEngine(0); connect(SessionManager::instance(), &SessionManager::startupProjectChanged, this, &DebuggerPluginPrivate::onCurrentProjectChanged); m_commonOptionsPage = new CommonOptionsPage(m_globalDebuggerOptions); m_plugin->addAutoReleasedObject(m_commonOptionsPage); m_globalDebuggerOptions->fromSettings(); m_watchersWindow->setVisible(false); m_returnWindow->setVisible(false); // time gdb -i mi -ex 'b debuggerplugin.cpp:800' -ex r -ex q bin/qtcreator.bin } DebuggerEngine *currentEngine() { return dd->m_currentEngine; } SavedAction *action(int code) { return dd->m_debuggerSettings->item(code); } bool boolSetting(int code) { return dd->m_debuggerSettings->item(code)->value().toBool(); } QString stringSetting(int code) { QString raw = dd->m_debuggerSettings->item(code)->value().toString(); return globalMacroExpander()->expand(raw); } QStringList stringListSetting(int code) { return dd->m_debuggerSettings->item(code)->value().toStringList(); } BreakHandler *breakHandler() { return dd->m_breakHandler; } void showModuleSymbols(const QString &moduleName, const Symbols &symbols) { QTreeWidget *w = new QTreeWidget; w->setUniformRowHeights(true); w->setColumnCount(5); w->setRootIsDecorated(false); w->setAlternatingRowColors(true); w->setSortingEnabled(true); w->setObjectName(QLatin1String("Symbols.") + moduleName); QStringList header; header.append(DebuggerPlugin::tr("Symbol")); header.append(DebuggerPlugin::tr("Address")); header.append(DebuggerPlugin::tr("Code")); header.append(DebuggerPlugin::tr("Section")); header.append(DebuggerPlugin::tr("Name")); w->setHeaderLabels(header); w->setWindowTitle(DebuggerPlugin::tr("Symbols in \"%1\"").arg(moduleName)); foreach (const Symbol &s, symbols) { QTreeWidgetItem *it = new QTreeWidgetItem; it->setData(0, Qt::DisplayRole, s.name); it->setData(1, Qt::DisplayRole, s.address); it->setData(2, Qt::DisplayRole, s.state); it->setData(3, Qt::DisplayRole, s.section); it->setData(4, Qt::DisplayRole, s.demangled); w->addTopLevelItem(it); } createNewDock(w); } void showModuleSections(const QString &moduleName, const Sections &sections) { QTreeWidget *w = new QTreeWidget; w->setUniformRowHeights(true); w->setColumnCount(5); w->setRootIsDecorated(false); w->setAlternatingRowColors(true); w->setSortingEnabled(true); w->setObjectName(QLatin1String("Sections.") + moduleName); QStringList header; header.append(DebuggerPlugin::tr("Name")); header.append(DebuggerPlugin::tr("From")); header.append(DebuggerPlugin::tr("To")); header.append(DebuggerPlugin::tr("Address")); header.append(DebuggerPlugin::tr("Flags")); w->setHeaderLabels(header); w->setWindowTitle(DebuggerPlugin::tr("Sections in \"%1\"").arg(moduleName)); foreach (const Section &s, sections) { QTreeWidgetItem *it = new QTreeWidgetItem; it->setData(0, Qt::DisplayRole, s.name); it->setData(1, Qt::DisplayRole, s.from); it->setData(2, Qt::DisplayRole, s.to); it->setData(3, Qt::DisplayRole, s.address); it->setData(4, Qt::DisplayRole, s.flags); w->addTopLevelItem(it); } createNewDock(w); } void DebuggerPluginPrivate::aboutToShutdown() { disconnect(SessionManager::instance(), SIGNAL(startupProjectChanged(ProjectExplorer::Project*)), this, 0); } void updateState(DebuggerEngine *engine) { dd->updateState(engine); } void updateWatchersWindow(bool showWatch, bool showReturn) { dd->updateWatchersWindow(showWatch, showReturn); } QIcon locationMarkIcon() { return dd->m_locationMarkIcon; } bool hasSnapshots() { return dd->m_snapshotHandler->size(); } void openTextEditor(const QString &titlePattern0, const QString &contents) { if (dd->m_shuttingDown) return; QString titlePattern = titlePattern0; IEditor *editor = EditorManager::openEditorWithContents( CC::K_DEFAULT_TEXT_EDITOR_ID, &titlePattern, contents.toUtf8(), EditorManager::IgnoreNavigationHistory); QTC_ASSERT(editor, return); } bool isActiveDebugLanguage(int language) { return dd->m_mainWindow->activeDebugLanguages() & language; } // void runTest(const QString &fileName); void showMessage(const QString &msg, int channel, int timeout) { dd->showMessage(msg, channel, timeout); } bool isReverseDebugging() { return dd->m_reverseDirectionAction->isChecked(); } void runControlStarted(DebuggerEngine *engine) { dd->runControlStarted(engine); } void runControlFinished(DebuggerEngine *engine) { dd->runControlFinished(engine); } void displayDebugger(DebuggerEngine *engine, bool updateEngine) { dd->displayDebugger(engine, updateEngine); } DebuggerLanguages activeLanguages() { QTC_ASSERT(dd->m_mainWindow, return AnyLanguage); return dd->m_mainWindow->activeDebugLanguages(); } void synchronizeBreakpoints() { dd->synchronizeBreakpoints(); } QWidget *mainWindow() { return dd->mainWindow(); } bool isDockVisible(const QString &objectName) { return dd->isDockVisible(objectName); } void openMemoryEditor() { AddressDialog dialog; if (dialog.exec() == QDialog::Accepted) { MemoryViewSetupData data; data.startAddress = dialog.address(); currentEngine()->openMemoryView(data); } } void setThreads(const QStringList &list, int index) { dd->setThreads(list, index); } QSharedPointer<Internal::GlobalDebuggerOptions> globalDebuggerOptions() { return dd->m_globalDebuggerOptions; } } // namespace Internal /////////////////////////////////////////////////////////////////////// // // DebuggerPlugin // /////////////////////////////////////////////////////////////////////// /*! \class Debugger::DebuggerPlugin This is the "external" interface of the debugger plugin that's visible from Qt Creator core. The internal interface to global debugger functionality that is used by debugger views and debugger engines is DebuggerCore, implemented in DebuggerPluginPrivate. */ DebuggerPlugin::DebuggerPlugin() { setObjectName(QLatin1String("DebuggerPlugin")); addObject(this); dd = new DebuggerPluginPrivate(this); } DebuggerPlugin::~DebuggerPlugin() { delete dd; dd = 0; } bool DebuggerPlugin::initialize(const QStringList &arguments, QString *errorMessage) { // Menu groups const Context globalcontext(CC::C_GLOBAL); ActionContainer *mstart = ActionManager::actionContainer(PE::M_DEBUG_STARTDEBUGGING); mstart->appendGroup(Constants::G_GENERAL); mstart->appendGroup(Constants::G_SPECIAL); mstart->appendGroup(Constants::G_START_QML); // Separators mstart->addSeparator(globalcontext, Constants::G_GENERAL); mstart->addSeparator(globalcontext, Constants::G_SPECIAL); addAutoReleasedObject(new DebuggerItemManager); DebuggerItemManager::restoreDebuggers(); KitManager::registerKitInformation(new DebuggerKitInformation); return dd->initialize(arguments, errorMessage); } IPlugin::ShutdownFlag DebuggerPlugin::aboutToShutdown() { removeObject(this); dd->aboutToShutdown(); return SynchronousShutdown; } QObject *DebuggerPlugin::remoteCommand(const QStringList &options, const QStringList &list) { dd->remoteCommand(options, list); return 0; } void DebuggerPlugin::extensionsInitialized() { dd->extensionsInitialized(); } #ifdef WITH_TESTS void DebuggerPluginPrivate::testLoadProject(const QString &proFile, const TestCallBack &cb) { connect(ProjectTree::instance(), &ProjectTree::currentProjectChanged, this, &DebuggerPluginPrivate::testProjectLoaded); m_testCallbacks.append(cb); QString error; if (ProjectExplorerPlugin::openProject(proFile, &error)) { // Will end up in callback below due to the connections to // signal currentProjectChanged(). return; } // Project opening failed. Eat the unused callback. qWarning("Cannot open %s: %s", qPrintable(proFile), qPrintable(error)); QVERIFY(false); m_testCallbacks.pop_back(); } void DebuggerPluginPrivate::testProjectLoaded(Project *project) { if (!project) { qWarning("Changed to null project."); return; } m_testProject = project; connect(project, SIGNAL(proFilesEvaluated()), SLOT(testProjectEvaluated())); project->configureAsExampleProject(QStringList()); } void DebuggerPluginPrivate::testProjectEvaluated() { QString fileName = m_testProject->projectFilePath().toUserOutput(); QVERIFY(!fileName.isEmpty()); qWarning("Project %s loaded", qPrintable(fileName)); connect(BuildManager::instance(), SIGNAL(buildQueueFinished(bool)), SLOT(testProjectBuilt(bool))); ProjectExplorerPlugin::buildProject(m_testProject); } void DebuggerPluginPrivate::testProjectBuilt(bool success) { QVERIFY(success); QVERIFY(!m_testCallbacks.isEmpty()); TestCallBack cb = m_testCallbacks.takeLast(); invoke<void>(cb.receiver, cb.slot); } void DebuggerPluginPrivate::testUnloadProject() { ProjectExplorerPlugin *pe = ProjectExplorerPlugin::instance(); invoke<void>(pe, "unloadProject"); } //static Target *activeTarget() //{ // Project *project = ProjectExplorerPlugin::instance()->currentProject(); // return project->activeTarget(); //} //static Kit *currentKit() //{ // Target *t = activeTarget(); // if (!t || !t->isEnabled()) // return 0; // return t->kit(); //} //static LocalApplicationRunConfiguration *activeLocalRunConfiguration() //{ // Target *t = activeTarget(); // return t ? qobject_cast<LocalApplicationRunConfiguration *>(t->activeRunConfiguration()) : 0; //} void DebuggerPluginPrivate::testRunProject(const DebuggerStartParameters &sp, const TestCallBack &cb) { m_testCallbacks.append(cb); RunControl *rc = DebuggerRunControlFactory::createAndScheduleRun(sp); connect(rc, &RunControl::finished, this, &DebuggerPluginPrivate::testRunControlFinished); } void DebuggerPluginPrivate::testRunControlFinished() { QVERIFY(!m_testCallbacks.isEmpty()); TestCallBack cb = m_testCallbacks.takeLast(); ExtensionSystem::invoke<void>(cb.receiver, cb.slot); } void DebuggerPluginPrivate::testFinished() { QTestEventLoop::instance().exitLoop(); QVERIFY(m_testSuccess); } /////////////////////////////////////////////////////////////////////////// //void DebuggerPlugin::testStateMachine() //{ // dd->testStateMachine1(); //} //void DebuggerPluginPrivate::testStateMachine1() //{ // m_testSuccess = true; // QString proFile = ICore::resourcePath(); // if (Utils::HostOsInfo::isMacHost()) // proFile += QLatin1String("/../.."); // proFile += QLatin1String("/../../tests/manual/debugger/simple/simple.pro"); // testLoadProject(proFile, TestCallBack(this, "testStateMachine2")); // QVERIFY(m_testSuccess); // QTestEventLoop::instance().enterLoop(20); //} //void DebuggerPluginPrivate::testStateMachine2() //{ // DebuggerStartParameters sp; // fillParameters(&sp, currentKit()); // sp.executable = activeLocalRunConfiguration()->executable(); // sp.testCase = TestNoBoundsOfCurrentFunction; // testRunProject(sp, TestCallBack(this, "testStateMachine3")); //} //void DebuggerPluginPrivate::testStateMachine3() //{ // testUnloadProject(); // testFinished(); //} /////////////////////////////////////////////////////////////////////////// void DebuggerPlugin::testBenchmark() { dd->testBenchmark1(); } enum FakeEnum { FakeDebuggerCommonSettingsId }; void DebuggerPluginPrivate::testBenchmark1() { #ifdef WITH_BENCHMARK CALLGRIND_START_INSTRUMENTATION; volatile Core::Id id1 = Core::Id(DEBUGGER_COMMON_SETTINGS_ID); CALLGRIND_STOP_INSTRUMENTATION; CALLGRIND_DUMP_STATS; CALLGRIND_START_INSTRUMENTATION; volatile FakeEnum id2 = FakeDebuggerCommonSettingsId; CALLGRIND_STOP_INSTRUMENTATION; CALLGRIND_DUMP_STATS; #endif } #endif // if WITH_TESTS } // namespace Debugger #include "debuggerplugin.moc"
lgpl-2.1
nemomobile-graveyard/meegotouch-controlpanelapplets
src/resetapplet/resetwidget.h
2012
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of meegotouch-controlpanelapplets. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** This library 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #ifndef RESETWIDGET_H #define RESETWIDGET_H #include <QPointer> #include <MBanner> #include "dcpwidget.h" #include "resetbusinesslogic.h" class MLinearLayoutPolicy; class MHelpButton; class MButton; class ResetWidget : public DcpWidget { Q_OBJECT Q_ENUMS (CurrentPlan); public: ResetWidget ( ResetBusinessLogic *resetBusinessLogic, QGraphicsWidget *parent = 0); ~ResetWidget (); enum CurrentPlan { None = 0, ResetSettings, ClearData }; void createContent (); private slots: void restoreActivated (); void restoreConfirmed (); void clearActivated (); void clearConfirmed (); void operationCancelled (); void showMassStorageWarning (); void doTheWork (); private: void addButtonContainer ( MLinearLayoutPolicy *mainLayout, MButton *button1, MButton *button2); MHelpButton *createHelpButton (const QString &link); private: QPointer<ResetBusinessLogic> m_ResetBusinessLogic; CurrentPlan m_currentPlan; MBanner *infoBanner; #ifdef UNIT_TEST friend class Ut_ResetApplet; // friend class Ut #endif }; #endif
lgpl-2.1
gidlbn/dlbn_02
src/plugins/qmldesigner/designercore/model/objectpropertybinding.cpp
1611
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "objectpropertybinding.h" namespace QmlDesigner { ObjectPropertyBinding::ObjectPropertyBinding() { } ObjectPropertyBinding::ObjectPropertyBinding(const ModelNode &node) : m_node(node) { } ModelNode ObjectPropertyBinding::modelNode() const { return m_node; } bool ObjectPropertyBinding::isValid() const { return m_node.isValid(); } } // namespace QmlDesigner
lgpl-2.1
mfherbst/spack
var/spack/repos/builtin/packages/fp16/package.py
1604
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, [email protected], All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # 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 terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class Fp16(Package): """FP16 is a header-only library for conversion to/from half-precision floating point formats""" homepage = "https://github.com/Maratyszcza/FP16/" git = "https://github.com/Maratyszcza/FP16.git" version('master') def install(self, spec, prefix): install_tree('include', prefix.include)
lgpl-2.1
alex1818/host
src/org/reprap/gui/botConsole/BotConsoleFrame.java
9111
/* * !!!!! * NOTE: PLEASE ONLY EDIT THIS USING THE NETBEANS IDE 6.0.1 OR HIGHER!!!! * !!!!! * * ... an .xml file is associated with this class. Cheers. * * BotConsoleFrame.java * * Created on 28 March 2008, 08:35 */ package org.reprap.gui.botConsole; import org.reprap.Preferences; import org.reprap.utilities.Debug; import javax.swing.JOptionPane; /** * * @author Ed Sells, March 2008 * * Console to operate the RepRap printer manually. * */ public class BotConsoleFrame extends javax.swing.JFrame { private static final long serialVersionUID = 1L; private Thread pollThread = null; boolean updatePosition = false; private boolean carryOnPolling = true; private GenericExtruderTabPanel[] extruderPanels; double fractionDone = -1; int layer = -1; int outOf = -1; private static BotConsoleFrame bcf = null; private static int exPanelNumber; /** Creates new form BotConsoleFrame */ public BotConsoleFrame() { try { checkPrefs(); } catch (Exception e) { Debug.e("Failure trying to initialise comms in botConsole: " + e); JOptionPane.showMessageDialog(null, e.getMessage()); return; } updatePosition = false; initComponents(); this.setTitle("RepRap Console"); /* * Fork off a thread to keep the panels up-to-date */ exPanelNumber = 0; pollThread = new Thread() { public void run() { Thread.currentThread().setName("GUI Poll"); while(true) { try { Thread.sleep(1500); updateProgress(); if(carryOnPolling) updatePanels(); } catch (InterruptedException ex) { // This is normal when shutting down, so ignore } } } }; pollThread.start(); } public void handleException(Exception e) { } /** * The update thread calls this to update everything * that relies on information from the RepRap machine. */ private void updatePanels() { int currentExtruder = org.reprap.Main.gui.getPrinter().getExtruder().getID(); try { org.reprap.Main.gui.getPrinter().selectExtruder(exPanelNumber, true); } catch (Exception e) { handleException(e); } extruderPanels[exPanelNumber].refreshTemperature(); try { org.reprap.Main.gui.getPrinter().selectExtruder(currentExtruder, true); } catch (Exception e) { handleException(e); } exPanelNumber++; if(exPanelNumber >= extruderPanels.length) { xYZTabPanel.refreshTemperature(); exPanelNumber = 0; } if(updatePosition) xYZTabPanel.recordCurrentPosition(); updatePosition = false; } public void getPosition() { updatePosition = true; } /** * The update thread calls this to update everything * that is independent of the RepRap machine. * @param fractionDone */ private void updateProgress() { printTabFrame1.updateProgress(fractionDone, layer, outOf); } public void setFractionDone(double f, int l, int o) { if(f >= 0) fractionDone = f; if(l >= 0) layer = l; if(o >= 0) outOf = o; } /** * "Suspend" and "resume" the poll thread. * We don't use the actual suspend call (depricated anyway) to * prevent resource locking. * */ public void suspendPolling() { carryOnPolling = false; try { Thread.sleep(200); } catch (InterruptedException ex) { // This is normal when shutting down, so ignore } } public void resumePolling() { try { Thread.sleep(200); } catch (InterruptedException ex) { // This is normal when shutting down, so ignore } carryOnPolling = true; } private void checkPrefs() throws Exception { // ID the number of extruder extruderCount = Preferences.loadGlobalInt("NumberOfExtruders"); if (extruderCount < 1) throw new Exception("A Reprap printer must contain at least one extruder"); } private void initialiseExtruderPanels() { extruderPanels = new GenericExtruderTabPanel[extruderCount]; for (int i = 0; i < extruderCount; i++) { extruderPanels[i] = new GenericExtruderTabPanel(); try { extruderPanels[i].initialiseExtruders(i); } catch (Exception e) { System.out.println("Failure trying to initialise extruders in botConsole: " + e); JOptionPane.showMessageDialog(null, e.getMessage()); return; } try { extruderPanels[i].setPrefs(); } catch (Exception e) { System.out.println("Problem loading prefs for Extruder " + i); JOptionPane.showMessageDialog(null, "Problem loading prefs for Extruder " + i); } } } private void addExtruderPanels() { xYZTabPanel = new org.reprap.gui.botConsole.XYZTabPanel(); jTabbedPane1.addTab("XYZ", xYZTabPanel); for (int i = 0; i < extruderCount; i++) { //jTabbedPane1.addTab("Extruder " + i, extruderPanels[i]); jTabbedPane1.addTab(extruderPanels[i].getExtruder().getMaterial(), extruderPanels[i]); } pack(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jTabbedPane1 = new javax.swing.JTabbedPane(); initialiseExtruderPanels(); printTabFrame1 = new org.reprap.gui.botConsole.PrintTabFrame(false); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jTabbedPane1.setRequestFocusEnabled(false); jTabbedPane1.addTab("Print", printTabFrame1); addExtruderPanels(); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(jTabbedPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 750, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addContainerGap(5, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(jTabbedPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 430, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addContainerGap(5, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { bcf = new BotConsoleFrame(); bcf.setVisible(true); bcf.printTabFrame1.setConsoleFrame(bcf); bcf.xYZTabPanel.setConsoleFrame(bcf); for(int i = 0; i < bcf.extruderPanels.length; i++) bcf.extruderPanels[i].setConsoleFrame(bcf); } }); } public static BotConsoleFrame getBotConsoleFrame() { return bcf; } // // public static org.reprap.gui.botConsole.XYZTabPanel XYZ() // { // return bcf.xYZTabPanel; // } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTabbedPane jTabbedPane1; private org.reprap.gui.botConsole.PrintTabFrame printTabFrame1; // End of variables declaration//GEN-END:variables private org.reprap.gui.botConsole.XYZTabPanel xYZTabPanel; // private static int motorID = 0; // public static int getMotorID() { // motorID++; // return motorID; // } public static PrintTabFrame getPrintTabFrame() { return bcf.printTabFrame1; } public static XYZTabPanel getXYZTabPanel() { return bcf.xYZTabPanel; } public static GenericExtruderTabPanel getGenericExtruderTabPanel(int i) { if(i >= 0 && i < bcf.extruderPanels.length) return bcf.extruderPanels[i]; Debug.e("getGenericExtruderTabPanel - extruder out of range: " + i); return bcf.extruderPanels[0]; } private int extruderCount; //private int currentExtruder; }
lgpl-2.1
gidlbn/dlbn_02
src/plugins/coreplugin/actionmanager/actioncontainer.h
2229
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #ifndef ACTIONCONTAINER_H #define ACTIONCONTAINER_H #include <QtCore/QObject> QT_BEGIN_NAMESPACE class QMenu; class QMenuBar; class QAction; QT_END_NAMESPACE namespace Core { class Command; class ActionContainer : public QObject { Q_OBJECT public: enum EmptyAction { EA_Mask = 0xFF00, EA_None = 0x0100, EA_Hide = 0x0200, EA_Disable = 0x0300 }; virtual void setEmptyAction(EmptyAction ea) = 0; virtual int id() const = 0; virtual QMenu *menu() const = 0; virtual QMenuBar *menuBar() const = 0; virtual QAction *insertLocation(const QString &group) const = 0; virtual void appendGroup(const QString &group) = 0; virtual void addAction(Core::Command *action, const QString &group = QString()) = 0; virtual void addMenu(Core::ActionContainer *menu, const QString &group = QString()) = 0; virtual ~ActionContainer() {} }; } // namespace Core #endif // ACTIONCONTAINER_H
lgpl-2.1
mornelon/QtCreator_compliments
src/plugins/qmljseditor/qmljseditoractionhandler.cpp
2052
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "qmljseditoractionhandler.h" #include "qmljseditorconstants.h" #include "qmljseditor.h" #include <coreplugin/icore.h> #include <coreplugin/actionmanager/actionmanager.h> #include <QDebug> #include <QAction> #include <QMessageBox> namespace QmlJSEditor { namespace Internal { QmlJSEditorActionHandler::QmlJSEditorActionHandler() : TextEditor::TextEditorActionHandler(QmlJSEditor::Constants::C_QMLJSEDITOR_ID, Format) { } void QmlJSEditorActionHandler::createActions() { TextEditor::TextEditorActionHandler::createActions(); } } // namespace Internal } // namespace QmlJSEditor
lgpl-2.1
yiqingj/work
include/mapnik/symbolizer.hpp
3393
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_SYMBOLIZER_HPP #define MAPNIK_SYMBOLIZER_HPP // mapnik #include <mapnik/config.hpp> #include <mapnik/path_expression.hpp> #include <mapnik/image_compositing.hpp> #include <mapnik/simplify.hpp> // boost #include <memory> // stl #include <vector> #include <string> namespace agg { struct trans_affine; } namespace mapnik { // fwd declares // TODO - move these transform declares to own header namespace detail { struct transform_node; } typedef std::vector<detail::transform_node> transform_list; typedef std::shared_ptr<transform_list> transform_list_ptr; typedef transform_list_ptr transform_type; class feature_impl; MAPNIK_DECL void evaluate_transform(agg::trans_affine& tr, feature_impl const& feature, transform_type const& trans_expr); class MAPNIK_DECL symbolizer_base { public: symbolizer_base(); symbolizer_base(symbolizer_base const& other); void set_comp_op(composite_mode_e comp_op); composite_mode_e comp_op() const; void set_transform(transform_type const& ); transform_type const& get_transform() const; std::string get_transform_string() const; void set_clip(bool clip); bool clip() const; void set_simplify_algorithm(simplify_algorithm_e algorithm); simplify_algorithm_e simplify_algorithm() const; void set_simplify_tolerance(double simplify_tolerance); double simplify_tolerance() const; void set_smooth(double smooth); double smooth() const; private: composite_mode_e comp_op_; transform_type affine_transform_; bool clip_; simplify_algorithm_e simplify_algorithm_value_; double simplify_tolerance_value_; double smooth_value_; }; class MAPNIK_DECL symbolizer_with_image { public: path_expression_ptr const& get_filename() const; void set_filename(path_expression_ptr const& filename); void set_opacity(float opacity); float get_opacity() const; void set_image_transform(transform_type const& tr); transform_type const& get_image_transform() const; std::string get_image_transform_string() const; protected: symbolizer_with_image(path_expression_ptr filename = path_expression_ptr()); symbolizer_with_image(symbolizer_with_image const& rhs); path_expression_ptr image_filename_; float image_opacity_; transform_type image_transform_; }; } #endif // MAPNIK_SYMBOLIZER_HPP
lgpl-2.1
gstreamer-sharp/gstreamer-sharp
sources/generated/Gst/CustomMeta.cs
2690
// This file was generated by the Gtk# code generator. // Any changes made will be lost if regenerated. namespace Gst { using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; #region Autogenerated code [StructLayout(LayoutKind.Sequential)] public partial struct CustomMeta : IEquatable<CustomMeta> { public Gst.Meta Meta; public static Gst.CustomMeta Zero = new Gst.CustomMeta (); public static Gst.CustomMeta New(IntPtr raw) { if (raw == IntPtr.Zero) return Gst.CustomMeta.Zero; return (Gst.CustomMeta) Marshal.PtrToStructure (raw, typeof (Gst.CustomMeta)); } [DllImport("gstreamer-1.0-0.dll", CallingConvention = CallingConvention.Cdecl)] static extern IntPtr gst_custom_meta_get_structure(IntPtr raw); public Gst.Structure Structure { get { IntPtr this_as_native = System.Runtime.InteropServices.Marshal.AllocHGlobal (System.Runtime.InteropServices.Marshal.SizeOf (this)); System.Runtime.InteropServices.Marshal.StructureToPtr (this, this_as_native, false); IntPtr raw_ret = gst_custom_meta_get_structure(this_as_native); Gst.Structure ret = raw_ret == IntPtr.Zero ? null : (Gst.Structure) GLib.Opaque.GetOpaque (raw_ret, typeof (Gst.Structure), false); ReadNative (this_as_native, ref this); System.Runtime.InteropServices.Marshal.FreeHGlobal (this_as_native); return ret; } } [DllImport("gstreamer-1.0-0.dll", CallingConvention = CallingConvention.Cdecl)] static extern bool gst_custom_meta_has_name(IntPtr raw, IntPtr name); public bool HasName(string name) { IntPtr this_as_native = System.Runtime.InteropServices.Marshal.AllocHGlobal (System.Runtime.InteropServices.Marshal.SizeOf (this)); System.Runtime.InteropServices.Marshal.StructureToPtr (this, this_as_native, false); IntPtr native_name = GLib.Marshaller.StringToPtrGStrdup (name); bool raw_ret = gst_custom_meta_has_name(this_as_native, native_name); bool ret = raw_ret; ReadNative (this_as_native, ref this); System.Runtime.InteropServices.Marshal.FreeHGlobal (this_as_native); GLib.Marshaller.Free (native_name); return ret; } static void ReadNative (IntPtr native, ref Gst.CustomMeta target) { target = New (native); } public bool Equals (CustomMeta other) { return true && Meta.Equals (other.Meta); } public override bool Equals (object other) { return other is CustomMeta && Equals ((CustomMeta) other); } public override int GetHashCode () { return this.GetType ().FullName.GetHashCode () ^ Meta.GetHashCode (); } private static GLib.GType GType { get { return GLib.GType.Pointer; } } #endregion } }
lgpl-2.1
LLNL/spack
var/spack/repos/builtin/packages/py-bx-python/package.py
1225
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyBxPython(PythonPackage): """The bx-python project is a python library and associated set of scripts to allow for rapid implementation of genome scale analyses.""" homepage = "https://github.com/bxlab/bx-python" pypi = "bx-python/bx-python-0.8.8.tar.gz" version('0.8.8', sha256='ad0808ab19c007e8beebadc31827e0d7560ac0e935f1100fb8cc93607400bb47') version('0.7.4', sha256='1066d1e56d062d0661f23c19942eb757bd7ab7cb8bc7d89a72fdc3931c995cb4', url="https://github.com/bxlab/bx-python/archive/v0.7.4.tar.gz", deprecated=True) depends_on('[email protected]:2.7', type=('build', 'run'), when='@:0.7') depends_on('[email protected]:2.8,3.5:', type=('build', 'run'), when='@0.8:') depends_on('py-setuptools', type='build') depends_on('py-python-lzo', type=('build', 'run'), when='@:0.7') depends_on('py-cython', type='build', when='@0.8:') depends_on('py-numpy', type=('build', 'run')) depends_on('py-six', type=('build', 'run'), when='@0.8:')
lgpl-2.1
kkoopa/GeoIP
deps/GeoIP-1.5.1/libGeoIP/GeoIP.h
15884
/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 2; tab-width: 2 -*- */ /* GeoIP.h * * Copyright (C) 2006 MaxMind LLC * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef GEOIP_H #define GEOIP_H #ifdef __cplusplus extern "C" { #endif #include <sys/types.h> #if !defined(_WIN32) #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #else /* !defined(_WIN32) */ #include <winsock2.h> #include <ws2tcpip.h> #define snprintf _snprintf #define FILETIME_TO_USEC(ft) (((unsigned __int64) ft.dwHighDateTime << 32 | ft.dwLowDateTime) / 10) #endif /* !defined(_WIN32) */ #include<stdio.h> #include<stdlib.h> #include<string.h> #include <sys/types.h> /* for fstat */ #include <sys/stat.h> /* for fstat */ #define SEGMENT_RECORD_LENGTH 3 #define LARGE_SEGMENT_RECORD_LENGTH 4 #define STANDARD_RECORD_LENGTH 3 #define ORG_RECORD_LENGTH 4 #define MAX_RECORD_LENGTH 4 #define NUM_DB_TYPES (38+1) /* 128 bit address in network order */ typedef struct in6_addr geoipv6_t; #define GEOIP_CHKBIT_V6(bit,ptr) (ptr[((127UL - bit) >> 3)] & (1UL << (~(127 - bit) & 7))) typedef struct GeoIPTag { FILE *GeoIPDatabase; char *file_path; unsigned char *cache; unsigned char *index_cache; unsigned int *databaseSegments; char databaseType; time_t mtime; int flags; off_t size; char record_length; int charset; /* 0 iso-8859-1 1 utf8 */ int record_iter; /* used in GeoIP_next_record */ int netmask; /* netmask of last lookup - set using depth in _GeoIP_seek_record */ time_t last_mtime_check; off_t dyn_seg_size; /* currently only used by the cityconfidence database */ unsigned int ext_flags; /* bit 0 teredo support enabled */ } GeoIP; typedef struct GeoIPLookup { int netmask; } GeoIPLookup; typedef enum { GEOIP_TEREDO_BIT = 0 } GeoIPExtFlags; typedef enum { GEOIP_CHARSET_ISO_8859_1 = 0, GEOIP_CHARSET_UTF8 = 1 } GeoIPCharset; typedef struct GeoIPRegionTag { char country_code[3]; char region[3]; } GeoIPRegion; typedef enum { GEOIP_STANDARD = 0, GEOIP_MEMORY_CACHE = 1, GEOIP_CHECK_CACHE = 2, GEOIP_INDEX_CACHE = 4, GEOIP_MMAP_CACHE = 8, } GeoIPOptions; typedef enum { GEOIP_COUNTRY_EDITION = 1, GEOIP_REGION_EDITION_REV0 = 7, GEOIP_CITY_EDITION_REV0 = 6, GEOIP_ORG_EDITION = 5, GEOIP_ISP_EDITION = 4, GEOIP_CITY_EDITION_REV1 = 2, GEOIP_REGION_EDITION_REV1 = 3, GEOIP_PROXY_EDITION = 8, GEOIP_ASNUM_EDITION = 9, GEOIP_NETSPEED_EDITION = 10, GEOIP_DOMAIN_EDITION = 11, GEOIP_COUNTRY_EDITION_V6 = 12, GEOIP_LOCATIONA_EDITION = 13, GEOIP_ACCURACYRADIUS_EDITION = 14, GEOIP_CITYCONFIDENCE_EDITION = 15, /* unsupported */ GEOIP_CITYCONFIDENCEDIST_EDITION = 16, /* unsupported */ GEOIP_LARGE_COUNTRY_EDITION = 17, GEOIP_LARGE_COUNTRY_EDITION_V6 = 18, GEOIP_CITYCONFIDENCEDIST_ISP_ORG_EDITION = 19, /* unsued, but gaps are not allowed */ GEOIP_CCM_COUNTRY_EDITION =20, /* unsued, but gaps are not allowed */ GEOIP_ASNUM_EDITION_V6 = 21, GEOIP_ISP_EDITION_V6 = 22, GEOIP_ORG_EDITION_V6 = 23, GEOIP_DOMAIN_EDITION_V6 = 24, GEOIP_LOCATIONA_EDITION_V6 = 25, GEOIP_REGISTRAR_EDITION = 26, GEOIP_REGISTRAR_EDITION_V6 = 27, GEOIP_USERTYPE_EDITION = 28, GEOIP_USERTYPE_EDITION_V6 = 29, GEOIP_CITY_EDITION_REV1_V6 = 30, GEOIP_CITY_EDITION_REV0_V6 = 31, GEOIP_NETSPEED_EDITION_REV1 = 32, GEOIP_NETSPEED_EDITION_REV1_V6 = 33, GEOIP_COUNTRYCONF_EDITION = 34, GEOIP_CITYCONF_EDITION = 35, GEOIP_REGIONCONF_EDITION = 36, GEOIP_POSTALCONF_EDITION = 37, GEOIP_ACCURACYRADIUS_EDITION_V6 = 38 } GeoIPDBTypes; typedef enum { GEOIP_ANON_PROXY = 1, GEOIP_HTTP_X_FORWARDED_FOR_PROXY = 2, GEOIP_HTTP_CLIENT_IP_PROXY = 3, } GeoIPProxyTypes; typedef enum { GEOIP_UNKNOWN_SPEED = 0, GEOIP_DIALUP_SPEED = 1, GEOIP_CABLEDSL_SPEED = 2, GEOIP_CORPORATE_SPEED = 3, } GeoIPNetspeedValues; extern char **GeoIPDBFileName; extern const char * GeoIPDBDescription[NUM_DB_TYPES]; extern const char *GeoIPCountryDBFileName; extern const char *GeoIPRegionDBFileName; extern const char *GeoIPCityDBFileName; extern const char *GeoIPOrgDBFileName; extern const char *GeoIPISPDBFileName; extern const char *GeoIPLocationADBFileName; extern const char *GeoIPAccuracyRadiusFileName; extern const char *GeoIPCityConfidenceFileName; extern char * GeoIP_custom_directory; /* Warning: do not use those arrays as doing so may break your * program with newer GeoIP versions */ extern const char GeoIP_country_code[255][3]; extern const char GeoIP_country_code3[255][4]; extern const char * GeoIP_country_name[255]; extern const char * GeoIP_utf8_country_name[255]; extern const char GeoIP_country_continent[255][3]; #ifdef DLL #define GEOIP_API __declspec(dllexport) #else #define GEOIP_API #endif /* DLL */ GEOIP_API void GeoIP_setup_custom_directory(char *dir); GEOIP_API GeoIP* GeoIP_open_type (int type, int flags); GEOIP_API GeoIP* GeoIP_new(int flags); GEOIP_API GeoIP* GeoIP_open(const char * filename, int flags); GEOIP_API int GeoIP_db_avail(int type); GEOIP_API void GeoIP_delete(GeoIP* gi); GEOIP_API const char *GeoIP_country_code_by_addr_gl (GeoIP* gi, const char *addr, GeoIPLookup * gl); GEOIP_API const char *GeoIP_country_code_by_name_gl (GeoIP* gi, const char *host, GeoIPLookup * gl); GEOIP_API const char *GeoIP_country_code3_by_addr_gl (GeoIP* gi, const char *addr, GeoIPLookup * gl); GEOIP_API const char *GeoIP_country_code3_by_name_gl (GeoIP* gi, const char *host, GeoIPLookup * gl); GEOIP_API const char *GeoIP_country_name_by_addr_gl (GeoIP* gi, const char *addr, GeoIPLookup * gl); GEOIP_API const char *GeoIP_country_name_by_name_gl (GeoIP* gi, const char *host, GeoIPLookup * gl); GEOIP_API const char *GeoIP_country_name_by_ipnum_gl (GeoIP* gi, unsigned long ipnum, GeoIPLookup * gl); GEOIP_API const char *GeoIP_country_code_by_ipnum_gl (GeoIP* gi, unsigned long ipnum, GeoIPLookup * gl); GEOIP_API const char *GeoIP_country_code3_by_ipnum_gl (GeoIP* gi, unsigned long ipnum, GeoIPLookup * gl); /* */ GEOIP_API const char *GeoIP_country_name_by_ipnum_v6_gl (GeoIP* gi, geoipv6_t ipnum, GeoIPLookup * gl); GEOIP_API const char *GeoIP_country_code_by_ipnum_v6_gl (GeoIP* gi, geoipv6_t ipnum, GeoIPLookup * gl); GEOIP_API const char *GeoIP_country_code3_by_ipnum_v6_gl (GeoIP* gi, geoipv6_t ipnum, GeoIPLookup * gl); GEOIP_API const char *GeoIP_country_code_by_addr_v6_gl (GeoIP* gi, const char *addr, GeoIPLookup * gl); GEOIP_API const char *GeoIP_country_code_by_name_v6_gl (GeoIP* gi, const char *host, GeoIPLookup * gl); GEOIP_API const char *GeoIP_country_code3_by_addr_v6_gl (GeoIP* gi, const char *addr, GeoIPLookup * gl); GEOIP_API const char *GeoIP_country_code3_by_name_v6_gl (GeoIP* gi, const char *host, GeoIPLookup * gl); GEOIP_API const char *GeoIP_country_name_by_addr_v6_gl (GeoIP* gi, const char *addr, GeoIPLookup * gl); GEOIP_API const char *GeoIP_country_name_by_name_v6_gl (GeoIP* gi, const char *host, GeoIPLookup * gl); GEOIP_API int GeoIP_id_by_addr_gl (GeoIP* gi, const char *addr, GeoIPLookup * gl); GEOIP_API int GeoIP_id_by_name_gl (GeoIP* gi, const char *host, GeoIPLookup * gl); GEOIP_API int GeoIP_id_by_ipnum_gl (GeoIP* gi, unsigned long ipnum, GeoIPLookup * gl); GEOIP_API int GeoIP_id_by_addr_v6_gl (GeoIP* gi, const char *addr, GeoIPLookup * gl); GEOIP_API int GeoIP_id_by_name_v6_gl (GeoIP* gi, const char *host, GeoIPLookup * gl); GEOIP_API int GeoIP_id_by_ipnum_v6_gl (GeoIP* gi, geoipv6_t ipnum, GeoIPLookup * gl); GEOIP_API GeoIPRegion * GeoIP_region_by_addr_gl (GeoIP* gi, const char *addr, GeoIPLookup * gl); GEOIP_API GeoIPRegion * GeoIP_region_by_name_gl (GeoIP* gi, const char *host, GeoIPLookup * gl); GEOIP_API GeoIPRegion * GeoIP_region_by_ipnum_gl (GeoIP *gi, unsigned long ipnum, GeoIPLookup * gl); GEOIP_API GeoIPRegion * GeoIP_region_by_addr_v6_gl (GeoIP* gi, const char *addr, GeoIPLookup * gl); GEOIP_API GeoIPRegion * GeoIP_region_by_name_v6_gl (GeoIP* gi, const char *host, GeoIPLookup * gl); GEOIP_API GeoIPRegion * GeoIP_region_by_ipnum_v6_gl (GeoIP *gi, geoipv6_t ipnum, GeoIPLookup * gl); /* Warning - don't call this after GeoIP_assign_region_by_inetaddr calls */ GEOIP_API void GeoIPRegion_delete (GeoIPRegion *gir); GEOIP_API void GeoIP_assign_region_by_inetaddr_gl(GeoIP* gi, unsigned long inetaddr, GeoIPRegion *gir, GeoIPLookup * gl); GEOIP_API void GeoIP_assign_region_by_inetaddr_v6_gl(GeoIP* gi, geoipv6_t inetaddr, GeoIPRegion *gir, GeoIPLookup * gl); /* Used to query GeoIP Organization, ISP and AS Number databases */ GEOIP_API char *GeoIP_name_by_ipnum_gl (GeoIP* gi, unsigned long ipnum, GeoIPLookup * gl); GEOIP_API char *GeoIP_name_by_addr_gl (GeoIP* gi, const char *addr, GeoIPLookup * gl); GEOIP_API char *GeoIP_name_by_name_gl (GeoIP* gi, const char *host, GeoIPLookup * gl); GEOIP_API char *GeoIP_name_by_ipnum_v6_gl (GeoIP* gi, geoipv6_t ipnum, GeoIPLookup * gl); GEOIP_API char *GeoIP_name_by_addr_v6_gl (GeoIP* gi, const char *addr, GeoIPLookup * gl); GEOIP_API char *GeoIP_name_by_name_v6_gl (GeoIP* gi, const char *name, GeoIPLookup * gl); /** return two letter country code */ GEOIP_API const char* GeoIP_code_by_id(int id); /** return three letter country code */ GEOIP_API const char* GeoIP_code3_by_id(int id); /** return full name of country in utf8 or iso-8859-1 */ GEOIP_API const char* GeoIP_country_name_by_id(GeoIP* gi, int id); /** return full name of country */ GEOIP_API const char* GeoIP_name_by_id(int id); /** return continent of country */ GEOIP_API const char* GeoIP_continent_by_id(int id); /** return id by country code **/ GEOIP_API int GeoIP_id_by_code(const char *country); /** return return number of known countries */ GEOIP_API unsigned GeoIP_num_countries(void); GEOIP_API char *GeoIP_database_info (GeoIP* gi); GEOIP_API unsigned char GeoIP_database_edition (GeoIP* gi); GEOIP_API int GeoIP_charset (GeoIP* gi); GEOIP_API int GeoIP_set_charset (GeoIP* gi, int charset); GEOIP_API int GeoIP_enable_teredo (GeoIP* gi, int true_false ); GEOIP_API int GeoIP_teredo (GeoIP* gi ); GEOIP_API char **GeoIP_range_by_ip_gl (GeoIP* gi, const char *addr, GeoIPLookup * gl); GEOIP_API void GeoIP_range_by_ip_delete(char **ptr); /* Convert region code to region name */ GEOIP_API const char * GeoIP_region_name_by_code(const char *country_code, const char *region_code); /* Get timezone from country and region code */ GEOIP_API const char * GeoIP_time_zone_by_country_and_region(const char *country_code, const char *region_code); /* some v4 helper functions as of 1.4.7 exported to the public API */ GEOIP_API unsigned long GeoIP_addr_to_num(const char *addr); GEOIP_API char * GeoIP_num_to_addr(unsigned long ipnum); /* Internal function -- convert iso to utf8; return a malloced utf8 string. */ char * _GeoIP_iso_8859_1__utf8(const char * iso); /* Cleans up memory used to hold file name paths. Returns 1 if successful; otherwise 0. * */ GEOIP_API int GeoIP_cleanup(void); /* Returns the library version in use. Helpful if your loading dynamically. */ GEOIP_API const char * GeoIP_lib_version(void); /* depricated */ GEOIP_API const char *GeoIP_country_code_by_addr (GeoIP* gi, const char *addr); GEOIP_API const char *GeoIP_country_code_by_name (GeoIP* gi, const char *host); GEOIP_API const char *GeoIP_country_code3_by_addr (GeoIP* gi, const char *addr); GEOIP_API const char *GeoIP_country_code3_by_name (GeoIP* gi, const char *host); GEOIP_API const char *GeoIP_country_name_by_addr (GeoIP* gi, const char *addr); GEOIP_API const char *GeoIP_country_name_by_name (GeoIP* gi, const char *host); GEOIP_API const char *GeoIP_country_name_by_ipnum (GeoIP* gi, unsigned long ipnum); GEOIP_API const char *GeoIP_country_code_by_ipnum (GeoIP* gi, unsigned long ipnum); GEOIP_API const char *GeoIP_country_code3_by_ipnum (GeoIP* gi, unsigned long ipnum); GEOIP_API const char *GeoIP_country_name_by_ipnum_v6 (GeoIP* gi, geoipv6_t ipnum); GEOIP_API const char *GeoIP_country_code_by_ipnum_v6 (GeoIP* gi, geoipv6_t ipnum); GEOIP_API const char *GeoIP_country_code3_by_ipnum_v6 (GeoIP* gi, geoipv6_t ipnum); GEOIP_API const char *GeoIP_country_code_by_addr_v6 (GeoIP* gi, const char *addr); GEOIP_API const char *GeoIP_country_code_by_name_v6 (GeoIP* gi, const char *host); GEOIP_API const char *GeoIP_country_code3_by_addr_v6 (GeoIP* gi, const char *addr); GEOIP_API const char *GeoIP_country_code3_by_name_v6 (GeoIP* gi, const char *host); GEOIP_API const char *GeoIP_country_name_by_addr_v6 (GeoIP* gi, const char *addr); GEOIP_API const char *GeoIP_country_name_by_name_v6 (GeoIP* gi, const char *host); GEOIP_API int GeoIP_id_by_addr (GeoIP* gi, const char *addr); GEOIP_API int GeoIP_id_by_name (GeoIP* gi, const char *host); GEOIP_API int GeoIP_id_by_ipnum (GeoIP* gi, unsigned long ipnum); GEOIP_API int GeoIP_id_by_addr_v6 (GeoIP* gi, const char *addr); GEOIP_API int GeoIP_id_by_name_v6 (GeoIP* gi, const char *host); GEOIP_API int GeoIP_id_by_ipnum_v6 (GeoIP* gi, geoipv6_t ipnum); GEOIP_API GeoIPRegion * GeoIP_region_by_addr (GeoIP* gi, const char *addr); GEOIP_API GeoIPRegion * GeoIP_region_by_name (GeoIP* gi, const char *host); GEOIP_API GeoIPRegion * GeoIP_region_by_ipnum (GeoIP *gi, unsigned long ipnum); GEOIP_API GeoIPRegion * GeoIP_region_by_addr_v6 (GeoIP* gi, const char *addr); GEOIP_API GeoIPRegion * GeoIP_region_by_name_v6 (GeoIP* gi, const char *host); GEOIP_API GeoIPRegion * GeoIP_region_by_ipnum_v6 (GeoIP *gi, geoipv6_t ipnum); GEOIP_API void GeoIP_assign_region_by_inetaddr(GeoIP* gi, unsigned long inetaddr, GeoIPRegion *gir); GEOIP_API void GeoIP_assign_region_by_inetaddr_v6(GeoIP* gi, geoipv6_t inetaddr, GeoIPRegion *gir); GEOIP_API char *GeoIP_name_by_ipnum (GeoIP* gi, unsigned long ipnum); GEOIP_API char *GeoIP_name_by_addr (GeoIP* gi, const char *addr); GEOIP_API char *GeoIP_name_by_name (GeoIP* gi, const char *host); GEOIP_API char *GeoIP_name_by_ipnum_v6 (GeoIP* gi, geoipv6_t ipnum); GEOIP_API char *GeoIP_name_by_addr_v6 (GeoIP* gi, const char *addr); GEOIP_API char *GeoIP_name_by_name_v6 (GeoIP* gi, const char *name); /** GeoIP_last_netmask is deprecated - it is not thread safe */ GEOIP_API int GeoIP_last_netmask (GeoIP* gi); GEOIP_API char **GeoIP_range_by_ip (GeoIP* gi, const char *addr); /* Deprecated - for backwards compatibility only */ GEOIP_API int GeoIP_country_id_by_addr (GeoIP* gi, const char *addr); GEOIP_API int GeoIP_country_id_by_name (GeoIP* gi, const char *host); GEOIP_API char *GeoIP_org_by_addr (GeoIP* gi, const char *addr); GEOIP_API char *GeoIP_org_by_name (GeoIP* gi, const char *host); GEOIP_API char *GeoIP_org_by_ipnum (GeoIP* gi, unsigned long ipnum); GEOIP_API int GeoIP_country_id_by_addr_v6 (GeoIP* gi, const char *addr); GEOIP_API char *GeoIP_org_by_ipnum_v6 (GeoIP* gi, geoipv6_t ipnum); GEOIP_API char *GeoIP_org_by_addr_v6 (GeoIP* gi, const char *addr); GEOIP_API char *GeoIP_org_by_name_v6 (GeoIP* gi, const char *name); /* End deprecated */ # #ifdef __cplusplus } #endif #endif /* GEOIP_H */
lgpl-2.1
enachb/freetel-code
src/wxWidgets-2.9.4/src/gtk/infobar.cpp
7415
/////////////////////////////////////////////////////////////////////////////// // Name: src/gtk/infobar.cpp // Purpose: wxInfoBar implementation for GTK // Author: Vadim Zeitlin // Created: 2009-09-27 // RCS-ID: $Id$ // Copyright: (c) 2009 Vadim Zeitlin <[email protected]> // Licence: wxWindows licence /////////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // for compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #include "wx/infobar.h" #if wxUSE_INFOBAR && defined(wxHAS_NATIVE_INFOBAR) #ifndef WX_PRECOMP #endif // WX_PRECOMP #include "wx/vector.h" #include "wx/stockitem.h" #include "wx/gtk/private.h" #include "wx/gtk/private/messagetype.h" // ---------------------------------------------------------------------------- // local classes // ---------------------------------------------------------------------------- class wxInfoBarGTKImpl { public: wxInfoBarGTKImpl() { m_label = NULL; m_close = NULL; } // label for the text shown in the bar GtkWidget *m_label; // the default close button, NULL if not needed (m_buttons is not empty) or // not created yet GtkWidget *m_close; // information about the buttons added using AddButton() struct Button { Button(GtkWidget *button_, int id_) : button(button_), id(id_) { } GtkWidget *button; int id; }; typedef wxVector<Button> Buttons; Buttons m_buttons; }; // ---------------------------------------------------------------------------- // local functions // ---------------------------------------------------------------------------- namespace { inline bool UseNative() { #ifdef __WXGTK3__ return true; #else // native GtkInfoBar widget is only available in GTK+ 2.18 and later return gtk_check_version(2, 18, 0) == 0; #endif } } // anonymous namespace extern "C" { static void wxgtk_infobar_response(GtkInfoBar * WXUNUSED(infobar), gint btnid, wxInfoBar *win) { win->GTKResponse(btnid); } static void wxgtk_infobar_close(GtkInfoBar * WXUNUSED(infobar), wxInfoBar *win) { win->GTKResponse(wxID_CANCEL); } } // extern "C" section with GTK+ callbacks // ============================================================================ // wxInfoBar implementation // ============================================================================ bool wxInfoBar::Create(wxWindow *parent, wxWindowID winid) { if ( !UseNative() ) return wxInfoBarGeneric::Create(parent, winid); m_impl = new wxInfoBarGTKImpl; // this control is created initially hidden Hide(); if ( !CreateBase(parent, winid) ) return false; // create the info bar widget itself m_widget = gtk_info_bar_new(); wxCHECK_MSG( m_widget, false, "failed to create GtkInfoBar" ); g_object_ref(m_widget); // also create a label which will be used to show our message m_impl->m_label = gtk_label_new(""); gtk_widget_show(m_impl->m_label); GtkWidget * const contentArea = gtk_info_bar_get_content_area(GTK_INFO_BAR(m_widget)); wxCHECK_MSG( contentArea, false, "failed to get GtkInfoBar content area" ); gtk_container_add(GTK_CONTAINER(contentArea), m_impl->m_label); // finish creation and connect to all the signals we're interested in m_parent->DoAddChild(this); PostCreation(wxDefaultSize); GTKConnectWidget("response", G_CALLBACK(wxgtk_infobar_response)); GTKConnectWidget("close", G_CALLBACK(wxgtk_infobar_close)); return true; } wxInfoBar::~wxInfoBar() { delete m_impl; } void wxInfoBar::ShowMessage(const wxString& msg, int flags) { if ( !UseNative() ) { wxInfoBarGeneric::ShowMessage(msg, flags); return; } // if we don't have any buttons, create a standard close one to give the // user at least some way to close the bar if ( m_impl->m_buttons.empty() && !m_impl->m_close ) { m_impl->m_close = GTKAddButton(wxID_CLOSE); } GtkMessageType type; if ( wxGTKImpl::ConvertMessageTypeFromWX(flags, &type) ) gtk_info_bar_set_message_type(GTK_INFO_BAR(m_widget), type); gtk_label_set_text(GTK_LABEL(m_impl->m_label), wxGTK_CONV(msg)); if ( !IsShown() ) Show(); UpdateParent(); } void wxInfoBar::Dismiss() { if ( !UseNative() ) { wxInfoBarGeneric::Dismiss(); return; } Hide(); UpdateParent(); } void wxInfoBar::GTKResponse(int btnid) { wxCommandEvent event(wxEVT_COMMAND_BUTTON_CLICKED, btnid); event.SetEventObject(this); if ( !HandleWindowEvent(event) ) Dismiss(); } GtkWidget *wxInfoBar::GTKAddButton(wxWindowID btnid, const wxString& label) { // as GTK+ lays out the buttons vertically, adding another button changes // our best size (at least in vertical direction) InvalidateBestSize(); GtkWidget *button = gtk_info_bar_add_button ( GTK_INFO_BAR(m_widget), (label.empty() ? GTKConvertMnemonics(wxGetStockGtkID(btnid)) : label).utf8_str(), btnid ); wxASSERT_MSG( button, "unexpectedly failed to add button to info bar" ); return button; } void wxInfoBar::AddButton(wxWindowID btnid, const wxString& label) { if ( !UseNative() ) { wxInfoBarGeneric::AddButton(btnid, label); return; } // if we had created the default close button before, remove it now that we // have some user-defined button if ( m_impl->m_close ) { gtk_widget_destroy(m_impl->m_close); m_impl->m_close = NULL; } GtkWidget * const button = GTKAddButton(btnid, label); if ( button ) m_impl->m_buttons.push_back(wxInfoBarGTKImpl::Button(button, btnid)); } void wxInfoBar::RemoveButton(wxWindowID btnid) { if ( !UseNative() ) { wxInfoBarGeneric::RemoveButton(btnid); return; } // as in the generic version, look for the button starting from the end wxInfoBarGTKImpl::Buttons& buttons = m_impl->m_buttons; for ( wxInfoBarGTKImpl::Buttons::reverse_iterator i = buttons.rbegin(); i != buttons.rend(); ++i ) { if (i->id == btnid) { gtk_widget_destroy(i->button); buttons.erase(i.base()); // see comment in GTKAddButton() InvalidateBestSize(); return; } } wxFAIL_MSG( wxString::Format("button with id %d not found", btnid) ); } void wxInfoBar::DoApplyWidgetStyle(GtkRcStyle *style) { wxInfoBarGeneric::DoApplyWidgetStyle(style); if ( UseNative() ) GTKApplyStyle(m_impl->m_label, style); } #endif // wxUSE_INFOBAR
lgpl-2.1
LegionPE/LegionPE-Theta-Base
src/legionpe/theta/command/RestartCommand.php
1320
<?php /* * LegionPE * * Copyright (C) 2015 PEMapModder and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * @author PEMapModder */ namespace legionpe\theta\command; use legionpe\theta\BasePlugin; use legionpe\theta\lang\Phrases; use legionpe\theta\Session; use legionpe\theta\utils\MUtils; use pocketmine\command\CommandSender; use pocketmine\Player; class RestartCommand extends ThetaCommand{ public function __construct(BasePlugin $main){ parent::__construct($main, "restart", "Check server restart time", "/restart", ["rst"]); } public function execute(CommandSender $sender, $commandLabel, array $args){ $leftTicks = $this->getMain()->getServer()->getTick() - $this->getMain()->getRestartTime(); $leftSecs = $leftTicks / 20; $string = MUtils::time_secsToString((int) $leftSecs); if($sender instanceof Player and ($ses = $this->getSession($sender)) instanceof Session){ $ses->translate(Phrases::CMD_RESTART_RESPONSE, ["time" => $string]); }else{ $sender->sendMessage(Phrases::VAR_em . $string . Phrases::VAR_info . " left before server restart"); } } }
lgpl-3.0
ProjectSWGCore/NGECore2
scripts/mobiles/corellia/greck_smuggler.py
1924
import sys from services.spawn import MobileTemplate from services.spawn import WeaponTemplate from resources.datatables import WeaponType from resources.datatables import Difficulty from resources.datatables import Options from java.util import Vector def addTemplate(core): mobileTemplate = MobileTemplate() mobileTemplate.setCreatureName('greck_smuggler') mobileTemplate.setLevel(25) mobileTemplate.setDifficulty(Difficulty.NORMAL) mobileTemplate.setMinSpawnDistance(4) mobileTemplate.setMaxSpawnDistance(8) mobileTemplate.setDeathblow(False) mobileTemplate.setScale(1) mobileTemplate.setSocialGroup("olag greck") mobileTemplate.setAssistRange(6) mobileTemplate.setStalker(True) mobileTemplate.setOptionsBitmask(128) templates = Vector() templates.add('object/mobile/shared_greck_thug_f_01.iff') templates.add('object/mobile/shared_greck_thug_f_02.iff') templates.add('object/mobile/shared_greck_thug_f_03.iff') templates.add('object/mobile/shared_greck_thug_m_01.iff') templates.add('object/mobile/shared_greck_thug_m_02.iff') templates.add('object/mobile/shared_greck_thug_m_03.iff') templates.add('object/mobile/shared_greck_thug_m_04.iff') templates.add('object/mobile/shared_greck_thug_m_05.iff') mobileTemplate.setTemplates(templates) weaponTemplates = Vector() weapontemplate = WeaponTemplate('object/weapon/melee/unarmed/shared_unarmed_default.iff', WeaponType.UNARMED, 1.0, 6, 'kinetic') weaponTemplates.add(weapontemplate) mobileTemplate.setWeaponTemplateVector(weaponTemplates) attacks = Vector() mobileTemplate.setDefaultAttack('meleeHit') mobileTemplate.setAttacks(attacks) lootPoolNames_1 = ['Junk'] lootPoolChances_1 = [100] lootGroupChance_1 = 100 mobileTemplate.addToLootGroups(lootPoolNames_1,lootPoolChances_1,lootGroupChance_1) core.spawnService.addMobileTemplate('greck_smuggler', mobileTemplate) return
lgpl-3.0
zxl777/yy
bin/php7/include/php/ext/hash/php_hash_tiger.h
2003
/* +----------------------------------------------------------------------+ | PHP Version 7 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2016 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Michael Wallner <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifndef PHP_HASH_TIGER_H #define PHP_HASH_TIGER_H /* TIGER context */ typedef struct { php_hash_uint64 state[3]; php_hash_uint64 passed; unsigned char buffer[64]; unsigned int passes:1; unsigned int length:7; } PHP_TIGER_CTX; PHP_HASH_API void PHP_3TIGERInit(PHP_TIGER_CTX *context); PHP_HASH_API void PHP_4TIGERInit(PHP_TIGER_CTX *context); PHP_HASH_API void PHP_TIGERUpdate(PHP_TIGER_CTX *context, const unsigned char *input, size_t len); PHP_HASH_API void PHP_TIGER128Final(unsigned char digest[16], PHP_TIGER_CTX *context); PHP_HASH_API void PHP_TIGER160Final(unsigned char digest[20], PHP_TIGER_CTX *context); PHP_HASH_API void PHP_TIGER192Final(unsigned char digest[24], PHP_TIGER_CTX *context); #endif /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
lgpl-3.0
ssangkong/NVRAM_KWU
qt-everywhere-opensource-src-4.7.4/examples/touch/knobs/knob.h
2220
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the examples 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$ ** ****************************************************************************/ #ifndef KNOB_H #define KNOB_H #include <QGraphicsItem> class Knob : public QGraphicsEllipseItem { public: Knob(); bool sceneEvent(QEvent *event); }; #endif // KNOB_H
lgpl-3.0
Tecsisa/serial-communication-manager
com.embeddedunveiled.native/macOS_serial/src/unix_like_list_usb.c
17357
/*************************************************************************************************** * Author : Rishi Gupta * * This file is part of 'serial communication manager' library. * * The 'serial communication manager' is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * The 'serial communication manager' is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with serial communication manager. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************************************/ #include <stdlib.h> #include <string.h> #include <unistd.h> #include <stdio.h> #if defined (__linux__) #include <libudev.h> #endif #if defined (__APPLE__) #include <CoreFoundation/CoreFoundation.h> #include <IOKit/IOKitLib.h> #include <IOKit/serial/IOSerialKeys.h> #include <IOKit/serial/ioss.h> #include <IOKit/IOBSD.h> #include <IOKit/IOMessage.h> #include <IOKit/usb/IOUSBLib.h> #endif #include <jni.h> #include "unix_like_serial_lib.h" #if defined (__linux__) /* * Cleans up resources and set exception that will get thrown upon return to java layer. */ jstring linux_listusb_clean_throw_exp(JNIEnv *env, int task, const char *expmsg, struct jstrarray_list *list, struct udev_device *udev_device, struct udev_enumerate *enumerator, struct udev *udev_ctx) { (*env)->ExceptionClear(env); free_jstrarraylist(list); /* free memory first, so even if throwing JNI exception fails, this succeeds. */ if(task == 1) { udev_device_unref(udev_device); udev_enumerate_unref(enumerator); udev_unref(udev_ctx); }else { } jclass serialComExceptionClass = (*env)->FindClass(env, SCOMEXPCLASS); if((serialComExceptionClass == NULL) || ((*env)->ExceptionOccurred(env) != NULL)) { (*env)->ExceptionClear(env); if(task == 1) { LOGE(E_FINDCLASSSCOMEXPSTR, E_NEWSTRUTFSTR); }else { LOGE(E_FINDCLASSSCOMEXPSTR, expmsg); } return NULL; } if(task == 1) { (*env)->ThrowNew(env, serialComExceptionClass, E_NEWSTRUTFSTR); }else { (*env)->ThrowNew(env, serialComExceptionClass, expmsg); } return NULL; } /* * Finds information about USB devices using operating system specific facilities and API. * The sequence of entries in array must match with what java layer expect (6 informations * per USB device). If a particular USB attribute is not set in descriptor or can not be * obtained "---" is placed in its place. * * Return array of USB device's information found, empty array if no USB device is found, * NULL if an error occurs (additionally throws exception). */ jobjectArray list_usb_devices(JNIEnv *env, jint vendor_to_match) { int x = 0; struct jstrarray_list list = {0}; jstring usb_dev_info; jclass strClass = NULL; jobjectArray usbDevicesFound = NULL; struct udev *udev_ctx; struct udev_enumerate *enumerator; struct udev_list_entry *devices, *dev_list_entry; const char *sysattr_val; const char *prop_val; const char *path; struct udev_device *udev_device; char *endptr; init_jstrarraylist(&list, 100); /* libudev is reference counted. Memory is freed when counts reach to zero. */ udev_ctx = udev_new(); enumerator = udev_enumerate_new(udev_ctx); udev_enumerate_add_match_subsystem(enumerator, "usb"); udev_enumerate_scan_devices(enumerator); devices = udev_enumerate_get_list_entry(enumerator); udev_list_entry_foreach(dev_list_entry, devices) { path = udev_list_entry_get_name(dev_list_entry); udev_device = udev_device_new_from_syspath(udev_enumerate_get_udev(enumerator), path); if(udev_device == NULL) { continue; } if(strcmp("usb_device", udev_device_get_devtype(udev_device)) == 0) { /* In context of this library, application is not interested in USB hub and USB * host controllers. Skip then from listing. */ sysattr_val = udev_device_get_sysattr_value(udev_device, "bDeviceClass"); if(sysattr_val != NULL) { if(0x09 == strtol(sysattr_val, &endptr, 16)) { udev_device_unref(udev_device); continue; } } /* USB-IF vendor ID */ sysattr_val = udev_device_get_sysattr_value(udev_device, "idVendor"); if(sysattr_val != NULL) { if(vendor_to_match != 0) { /* we need to apply filter for identify specific vendor */ if(vendor_to_match != (0x0000FFFF & (int)strtol(sysattr_val, &endptr, 16))) { udev_device_unref(udev_device); continue; } } usb_dev_info = (*env)->NewStringUTF(env, sysattr_val); }else { usb_dev_info = (*env)->NewStringUTF(env, "---"); } if((usb_dev_info == NULL) || ((*env)->ExceptionOccurred(env) != NULL)) { return linux_listusb_clean_throw_exp(env, 1, NULL, &list, udev_device, enumerator, udev_ctx); } insert_jstrarraylist(&list, usb_dev_info); /* USB product ID */ sysattr_val = udev_device_get_sysattr_value(udev_device, "idProduct"); if(sysattr_val != NULL) { usb_dev_info = (*env)->NewStringUTF(env, sysattr_val); }else { usb_dev_info = (*env)->NewStringUTF(env, "---"); } if((usb_dev_info == NULL) || ((*env)->ExceptionOccurred(env) != NULL)) { return linux_listusb_clean_throw_exp(env, 1, NULL, &list, udev_device, enumerator, udev_ctx); } insert_jstrarraylist(&list, usb_dev_info); /* SERIAL NUMBER */ sysattr_val = udev_device_get_sysattr_value(udev_device, "serial"); if(sysattr_val != NULL) { usb_dev_info = (*env)->NewStringUTF(env, sysattr_val); }else { usb_dev_info = (*env)->NewStringUTF(env, "---"); } if((usb_dev_info == NULL) || ((*env)->ExceptionOccurred(env) != NULL)) { return linux_listusb_clean_throw_exp(env, 1, NULL, &list, udev_device, enumerator, udev_ctx); } insert_jstrarraylist(&list, usb_dev_info); /* PRODUCT */ sysattr_val = udev_device_get_sysattr_value(udev_device, "product"); if(sysattr_val != NULL) { usb_dev_info = (*env)->NewStringUTF(env, sysattr_val); }else { usb_dev_info = (*env)->NewStringUTF(env, "---"); } if((usb_dev_info == NULL) || ((*env)->ExceptionOccurred(env) != NULL)) { return linux_listusb_clean_throw_exp(env, 1, NULL, &list, udev_device, enumerator, udev_ctx); } insert_jstrarraylist(&list, usb_dev_info); /* MANUFACTURER */ sysattr_val = udev_device_get_sysattr_value(udev_device, "manufacturer"); if(sysattr_val != NULL) { usb_dev_info = (*env)->NewStringUTF(env, sysattr_val); }else { usb_dev_info = (*env)->NewStringUTF(env, "---"); } if((usb_dev_info == NULL) || ((*env)->ExceptionOccurred(env) != NULL)) { return linux_listusb_clean_throw_exp(env, 1, NULL, &list, udev_device, enumerator, udev_ctx); } insert_jstrarraylist(&list, usb_dev_info); /* LOCATION */ prop_val = udev_device_get_property_value(udev_device, "DEVPATH"); if(prop_val != NULL) { usb_dev_info = (*env)->NewStringUTF(env, prop_val); }else { usb_dev_info = (*env)->NewStringUTF(env, "---"); } if((usb_dev_info == NULL) || ((*env)->ExceptionOccurred(env) != NULL)) { return linux_listusb_clean_throw_exp(env, 1, NULL, &list, udev_device, enumerator, udev_ctx); } insert_jstrarraylist(&list, usb_dev_info); } udev_device_unref(udev_device); } udev_enumerate_unref(enumerator); udev_unref(udev_ctx); /* Create a JAVA/JNI style array of String object, populate it and return to java layer. */ strClass = (*env)->FindClass(env, JAVALSTRING); if((strClass == NULL) || ((*env)->ExceptionOccurred(env) != NULL)) { return linux_listusb_clean_throw_exp(env, 2, E_FINDCLASSSSTRINGSTR, &list, NULL, NULL, NULL); } usbDevicesFound = (*env)->NewObjectArray(env, (jsize) list.index, strClass, NULL); if((usbDevicesFound == NULL) || ((*env)->ExceptionOccurred(env) != NULL)) { return linux_listusb_clean_throw_exp(env, 2, E_NEWOBJECTARRAYSTR, &list, NULL, NULL, NULL); } for (x=0; x < list.index; x++) { (*env)->SetObjectArrayElement(env, usbDevicesFound, x, list.base[x]); if((*env)->ExceptionOccurred(env)) { return linux_listusb_clean_throw_exp(env, 2, E_SETOBJECTARRAYSTR, &list, NULL, NULL, NULL); } } free_jstrarraylist(&list); return usbDevicesFound; } #endif #if defined (__APPLE__) /* * Cleans up resources and set exception that will get thrown upon return to java layer. */ jstring mac_listusb_clean_throw_exp(JNIEnv *env, int task, const char *expmsg, struct jstrarray_list *list, io_service_t usb_dev_obj, io_iterator_t iterator) { /* free memory first, so even if throwing JNI exception fails, this succeeds. */ if(task == 1) { IOObjectRelease(usb_dev_obj); IOObjectRelease(iterator); }else { } jclass serialComExceptionClass = (*env)->FindClass(env, SCOMEXPCLASS); if((serialComExceptionClass == NULL) || ((*env)->ExceptionOccurred(env) != NULL)) { (*env)->ExceptionClear(env); if(task == 1) { LOGE(E_FINDCLASSSCOMEXPSTR, E_NEWSTRUTFSTR); }else { LOGE(E_FINDCLASSSCOMEXPSTR, expmsg); } return NULL; } if(task == 1) { (*env)->ThrowNew(env, serialComExceptionClass, E_NEWSTRUTFSTR); }else { (*env)->ThrowNew(env, serialComExceptionClass, expmsg); } return NULL; } /* * Finds information about USB devices using operating system specific facilities and API. * The sequence of entries in array must match with what java layer expect (6 informations * per USB device). If a particular USB attribute is not set in descriptor or can not be * obtained "---" is placed in its place. * * Return array of USB device's information found, empty array if no USB device is found, * NULL if an error occurs (additionally throws exception). */ jobjectArray list_usb_devices(JNIEnv *env, jint vendor_to_match) { int x = 0; struct jstrarray_list list = {0}; jstring usb_dev_info; jclass strClass = NULL; jobjectArray usbDevicesFound = NULL; kern_return_t kr; CFDictionaryRef matching_dictionary = NULL; io_iterator_t iterator = 0; io_service_t usb_dev_obj; CFNumberRef num_ref; CFStringRef str_ref; int result; char hexcharbuffer[5]; /* For storing USB descriptor attributes string like manufacturer, product, serial number etc. * in any encoding 1024 is sufficient. We prevented malloc() every time for every new attribute. */ char charbuffer[1024]; init_jstrarraylist(&list, 100); matching_dictionary = IOServiceMatching("IOUSBDevice"); if(matching_dictionary == NULL) { /* handle error*/ } kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matching_dictionary, &iterator); if(kr != KERN_SUCCESS) { /* handle error*/ } if(!iterator) { /* handle error*/ } while((usb_dev_obj = IOIteratorNext(iterator)) != 0) { /* In context of this library, application is not interested in USB hub and USB * host controllers. Skip then from listing. */ num_ref = (CFNumberRef) IORegistryEntrySearchCFProperty(usb_dev_obj, kIOServicePlane, CFSTR(kUSBDeviceClass), NULL, kIORegistryIterateRecursively | kIORegistryIterateParents); if(num_ref) { CFNumberGetValue(num_ref, kCFNumberSInt32Type, &result); CFRelease(num_ref); if(0x09 == result) { IOObjectRelease(usb_dev_obj); continue; } }else { CFRelease(num_ref); IOObjectRelease(usb_dev_obj); continue; } /* USB-IF vendor ID */ memset(hexcharbuffer, '\0', sizeof(hexcharbuffer)); num_ref = (CFNumberRef) IORegistryEntrySearchCFProperty(usb_dev_obj, kIOServicePlane, CFSTR(kUSBVendorID), NULL, kIORegistryIterateRecursively | kIORegistryIterateParents); if(num_ref) { CFNumberGetValue(num_ref, kCFNumberSInt32Type, &result); if(vendor_to_match != 0) { /* we need to apply filter for identify specific vendor */ if(vendor_to_match != (result & 0x0000FFFF)) { CFRelease(num_ref); IOObjectRelease(usb_dev_obj); continue; } } CFRelease(num_ref); snprintf(hexcharbuffer, 5, "%04X", result & 0x0000FFFF); usb_dev_info = (*env)->NewStringUTF(env, hexcharbuffer); }else { usb_dev_info = (*env)->NewStringUTF(env, "---"); } if((usb_dev_info == NULL) || ((*env)->ExceptionOccurred(env) != NULL)) { return mac_listusb_clean_throw_exp(env, 1, NULL, &list, usb_dev_obj, iterator); } insert_jstrarraylist(&list, usb_dev_info); /* USB product ID */ memset(hexcharbuffer, '\0', sizeof(hexcharbuffer)); num_ref = (CFNumberRef) IORegistryEntrySearchCFProperty(usb_dev_obj, kIOServicePlane, CFSTR(kUSBProductID), NULL, kIORegistryIterateRecursively | kIORegistryIterateParents); if(num_ref) { CFNumberGetValue(num_ref, kCFNumberSInt32Type, &result); CFRelease(num_ref); snprintf(hexcharbuffer, 5, "%04X", result & 0x0000FFFF); usb_dev_info = (*env)->NewStringUTF(env, hexcharbuffer); }else { usb_dev_info = (*env)->NewStringUTF(env, "---"); } if((usb_dev_info == NULL) || ((*env)->ExceptionOccurred(env) != NULL)) { return mac_listusb_clean_throw_exp(env, 1, NULL, &list, usb_dev_obj, iterator); } insert_jstrarraylist(&list, usb_dev_info); /* SERIAL NUMBER */ str_ref = (CFStringRef) IORegistryEntrySearchCFProperty(usb_dev_obj, kIOServicePlane, CFSTR(kUSBSerialNumberString), NULL, kIORegistryIterateRecursively | kIORegistryIterateParents); if(str_ref) { memset(charbuffer, '\0', sizeof(charbuffer)); CFStringGetCString(str_ref, charbuffer, sizeof(charbuffer), kCFStringEncodingUTF8); CFRelease(str_ref); usb_dev_info = (*env)->NewStringUTF(env, charbuffer); }else { usb_dev_info = (*env)->NewStringUTF(env, "---"); } if((usb_dev_info == NULL) || ((*env)->ExceptionOccurred(env) != NULL)) { return mac_listusb_clean_throw_exp(env, 1, NULL, &list, usb_dev_obj, iterator); } insert_jstrarraylist(&list, usb_dev_info); /* PRODUCT */ str_ref = (CFStringRef) IORegistryEntrySearchCFProperty(usb_dev_obj, kIOServicePlane, CFSTR(kUSBProductString), NULL, kIORegistryIterateRecursively | kIORegistryIterateParents); if(str_ref) { memset(charbuffer, '\0', sizeof(charbuffer)); CFStringGetCString(str_ref, charbuffer, sizeof(charbuffer), kCFStringEncodingUTF8); CFRelease(str_ref); usb_dev_info = (*env)->NewStringUTF(env, charbuffer); }else { usb_dev_info = (*env)->NewStringUTF(env, "---"); } if((usb_dev_info == NULL) || ((*env)->ExceptionOccurred(env) != NULL)) { return mac_listusb_clean_throw_exp(env, 1, NULL, &list, usb_dev_obj, iterator); } insert_jstrarraylist(&list, usb_dev_info); /* MANUFACTURER */ str_ref = (CFStringRef) IORegistryEntrySearchCFProperty(usb_dev_obj, kIOServicePlane, CFSTR(kUSBVendorString), NULL, kIORegistryIterateRecursively | kIORegistryIterateParents); if(str_ref) { memset(charbuffer, '\0', sizeof(charbuffer)); CFStringGetCString(str_ref, charbuffer, sizeof(charbuffer), kCFStringEncodingUTF8); CFRelease(str_ref); usb_dev_info = (*env)->NewStringUTF(env, charbuffer); }else { usb_dev_info = (*env)->NewStringUTF(env, "---"); } if((usb_dev_info == NULL) || ((*env)->ExceptionOccurred(env) != NULL)) { return mac_listusb_clean_throw_exp(env, 1, NULL, &list, usb_dev_obj, iterator); } insert_jstrarraylist(&list, usb_dev_info); /* LOCATION */ memset(charbuffer, '\0', sizeof(charbuffer)); num_ref = (CFNumberRef) IORegistryEntrySearchCFProperty(usb_dev_obj, kIOServicePlane, CFSTR(kUSBDevicePropertyLocationID), NULL, kIORegistryIterateRecursively | kIORegistryIterateParents); if(num_ref) { CFNumberGetValue(num_ref, kCFNumberSInt32Type, &result); CFRelease(num_ref); snprintf(charbuffer, 1024, "%x", result); usb_dev_info = (*env)->NewStringUTF(env, charbuffer); }else { usb_dev_info = (*env)->NewStringUTF(env, "---"); } if((usb_dev_info == NULL) || ((*env)->ExceptionOccurred(env) != NULL)) { return mac_listusb_clean_throw_exp(env, 1, NULL, &list, usb_dev_obj, iterator); } insert_jstrarraylist(&list, usb_dev_info); IOObjectRelease(usb_dev_obj); } IOObjectRelease(iterator); /* Create a JAVA/JNI style array of String object, populate it and return to java layer. */ strClass = (*env)->FindClass(env, JAVALSTRING); if((strClass == NULL) || ((*env)->ExceptionOccurred(env) != NULL)) { return mac_listusb_clean_throw_exp(env, 2, E_FINDCLASSSSTRINGSTR, &list, NULL, NULL); } usbDevicesFound = (*env)->NewObjectArray(env, (jsize) list.index, strClass, NULL); if((usbDevicesFound == NULL) || ((*env)->ExceptionOccurred(env) != NULL)) { return mac_listusb_clean_throw_exp(env, 2, E_NEWOBJECTARRAYSTR, &list, NULL, NULL); } for (x=0; x < list.index; x++) { (*env)->SetObjectArrayElement(env, usbDevicesFound, x, list.base[x]); if((*env)->ExceptionOccurred(env)) { return mac_listusb_clean_throw_exp(env, 2, E_SETOBJECTARRAYSTR, &list, NULL, NULL); } } free_jstrarraylist(&list); return usbDevicesFound; } #endif
lgpl-3.0
webforge-labs/psc-cms-js
tests/Psc/UI/ErrorPaneTest.js
1066
define(['psc-tests-assert','Psc/UI/ErrorPane'], function(t) { var setup = function(test) { return t.setup(test); }; module("Psc.UI.ErrorPane"); test("acceptance", function() { setup(this); var errorPane = new Psc.UI.ErrorPane({ container: $('#qunit-fixture'), label: 'some', errorMessage: 'some text'+"\nwillbe converted" }); errorPane.display(); this.assertEquals(1, $('#qunit-fixture .psc-cms-ui-error-pane').length); // does not attach twice errorPane.display(); this.assertEquals(1, $('#qunit-fixture .psc-cms-ui-error-pane').length); }); test("can be removed", function () { setup(this); var errorPane = new Psc.UI.ErrorPane({ container: $('#qunit-fixture'), label: 'some', errorMessage: 'some text'+"\nwillbe converted" }); errorPane.display(); this.assertEquals(1, $('#qunit-fixture .psc-cms-ui-error-pane').length); errorPane.hide(); this.assertEquals(0, $('#qunit-fixture .psc-cms-ui-error-pane').length); }); });
lgpl-3.0
dtklein/vFense
tp/src/notifications/__init__.py
3134
import re from vFense.operations._constants import vFensePlugins VALID_NOTIFICATION_PLUGINS = ( vFensePlugins.RV_PLUGIN, vFensePlugins.MONITORING_PLUGIN ) INSTALL = 'install' UNINSTALL = 'uninstall' REBOOT = 'reboot' SHUTDOWN = 'shutdown' PASS = 'pass' FAIL = 'fail' CPU = 'cpu' MEM = 'mem' FS = 'filesystem' VALID_RV_NOTIFICATIONS = (INSTALL, UNINSTALL, REBOOT, SHUTDOWN) VALID_MONITORING_NOTIFICATIONS = (CPU, MEM, FS) VALID_NOTIFICATIONS = VALID_RV_NOTIFICATIONS + VALID_MONITORING_NOTIFICATIONS VALID_STATUSES_TO_ALERT_ON = (PASS, FAIL) class NotificationCollections(): Notifications = 'notifications' NotificationsHistory = 'notifications_history' NotificationPlugins = 'notification_plugins' class NotificationKeys(): NotificationId = 'notification_id' NotificationType = 'notification_type' RuleName = 'rule_name' RuleDescription = 'rule_description' CreatedBy = 'created_by' CreatedTime = 'created_time' ModifiedBy = 'modified_by' ModifiedTime = 'modified_time' Plugin = 'plugin' User = 'user' Group = 'group' AllAgents = 'all_agents' Agents = 'agents' Tags = 'tags' CustomerName = 'customer_name' AppThreshold = 'app_threshold' RebootThreshold = 'reboot_threshold' ShutdownThreshold = 'shutdown_threshold' CpuThreshold = 'cpu_threshold' MemThreshold = 'mem_threshold' FileSystemThreshold = 'filesystem_threshold' FileSystem = 'filesystem' class NotificationIndexes(): CustomerName = 'customer_name' RuleNameAndCustomer = 'rule_name_and_customer' NotificationTypeAndCustomer = 'notification_type_and_customer' AppThresholdAndCustomer = 'app_threshold_and_customer' RebootThresholdAndCustomer = 'reboot_threshold_and_customer' ShutdownThresholdAndCustomer = 'shutdown_threshold_and_customer' MemThresholdAndCustomer = 'mem_threshold_and_customer' CpuThresholdAndCustomer = 'cpu_threshold_and_customer' FileSystemThresholdAndFileSystemAndCustomer = ( 'fs_threshold_and_fs_and_customer' ) class NotificationHistoryKeys(): Id = 'id' NotificationId = 'notification_id' AlertSent = 'alert_sent' AlertSentTime = 'alert_sent_time' class NotificationHistoryIndexes(): NotificationId = 'notification_id' class NotificationPluginKeys(): Id = 'id' CustomerName = 'customer_name' PluginName = 'plugin_name' CreatedTime = 'created_time' ModifiedTime = 'modified_time' CreatedBy = 'created_by' ModifiedBy = 'modified_by' UserName = 'username' Password = 'password' Server = 'server' Port = 'port' IsTls = 'is_tls' IsSsl = 'is_ssl' FromEmail = 'from_email' ToEmail = 'to_email' class NotificationPluginIndexes(): CustomerName = 'customer_name' def return_notif_type_from_operation(oper_type): if re.search(r'^install', oper_type): oper_type = INSTALL elif re.search(r'^uninstall', oper_type): oper_type = UNINSTALL elif oper_type == REBOOT: oper_type = REBOOT elif oper_type == SHUTDOWN: oper_type = SHUTDOWN return(oper_type)
lgpl-3.0
webasyst/webasyst-framework
wa-apps/installer/templates/actions/assets/Assets.html
3906
<section class="article js-assets"> <div class="article-body"> <h1>[`Manage apps`]</h1> {if !empty($messages)} {foreach $messages as $message} <h2 class="state-{$message.result}"> {if $message.result == 'success'} <i class="fas fa-check-circle"></i> {elseif $message.result == 'fail'} <i class="fas fa-times-circle"></i> {/if} {$message.text|escape} </h2> {/foreach} {/if} <table id="i-assets-list" class="i-assets-list"> <tbody> {* list of available updates *} {foreach $items as $app_id => $app} {if empty($app.virtual) || !empty($app.plugins)} {include file="./Assets.row.html" item=$app item_id=$app_id item_type='app' inline} {/if} {if !empty($app.plugins)} {foreach $app.plugins as $item_id => $plugin} {include file="./Assets.row.html" item=$plugin item_id=$item_id item_type='plugin' inline} {/foreach} {/if} {if !empty($app.themes)} {foreach $app.themes as $item_id => $theme} {if $item_id !='default'} {include file="./Assets.row.html" item=$theme item_id=$item_id item_type='theme' inline} {/if} {/foreach} {/if} {if !empty($app.widgets)} {foreach $app.widgets as $item_id => $widget} {include file="./Assets.row.html" item=$widget item_id=$item_id item_type='widget' app=$app inline} {/foreach} {/if} {/foreach} </tbody> </table> </div> </section> <script type="text/javascript"> document.title = {$title|json_encode}; $('.js-remove-item').on('click', function(e) { e.preventDefault(); const $this = $(this); $.waDialog.confirm({ title: '[`This will delete the product’s source code and data, without a recovery option. Are you sure?`]', success_button_title: '[`Delete`]', success_button_class: 'danger', cancel_button_title: '[`Cancel`]', cancel_button_class: 'light-gray', onSuccess() { $this.css('pointer-events', 'none'); $this.find('.js-remove-item-icon').addClass('hidden'); $this.find('.js-remove-item-spinner').removeClass('hidden'); $this.siblings('.js-remove-item-form').submit(); } }); }); $('#i-assets-list a.js-switch-item').click(function () { var $link = $(this); var url = $link.data('url'); var data = $link.data('data'); $link.data('url', null); $link.find('.js-installer-assets-icon').hide(); $link.find('.js-installer-assets-spinner').addClass('-active'); if (url) { $.post(url, data, function (data, textStatus) { if (data.status == 'ok') { setTimeout(function () { window.location.reload(); }, 1000); } else { var message = ''; if (data.errors) { for (var i = 0; i < data.errors.length; i++) { message = (message ? (message + ' ') : '') + data.errors[i][0]; } } else { message = textStatus; } $link.parent().text(message) } }); } return false; }); //--> </script>
lgpl-3.0
smba/oak
edu.cmu.cs.oak/src/test/resources/anchor/.github/ISSUE_TEMPLATE.md
313
### Summary A brief but detailed explanation of the issue, bug or feature you are reporting. ### Expected Behaviour - A list of steps you expected to happen in order ### Actual Behaviour - A list of steps you actually encountered ### Context details (if applicable) - Anchor version: - Server setup: - URL
lgpl-3.0
edwinspire/VSharp
class/System.ComponentModel.DataAnnotations/System.ComponentModel.DataAnnotations/ValidationException.cs
2799
// // ValidationException.cs // // Author: // Atsushi Enomoto <[email protected]> // // Copyright (C) 2008-2011 Novell Inc. http://novell.com // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.ComponentModel; using System.Runtime.Serialization; using System.Security.Permissions; namespace System.ComponentModel.DataAnnotations { [Serializable] public class ValidationException : Exception { public ValidationException () { } public ValidationException (string message) : base (message) { } public ValidationException (string message, Exception innerException) : base (message, innerException) { } public ValidationException (string errorMessage, ValidationAttribute validatingAttribute, object value) : base (errorMessage) { ValidationAttribute = validatingAttribute; Value = value; } protected ValidationException (SerializationInfo info, StreamingContext context) : base (info, context) { throw new NotImplementedException (); } #if NET_4_0 public ValidationException (ValidationResult validationResult, ValidationAttribute validatingAttribute, object value) : this (validationResult != null ? validationResult.ErrorMessage : null, validatingAttribute, value) { this.ValidationResult = validationResult; } public ValidationResult ValidationResult { get; private set; } #endif public ValidationAttribute ValidationAttribute { get; private set; } public object Value { get; private set; } #if !NET_4_5 [SecurityPermission (SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] public override void GetObjectData (SerializationInfo info, StreamingContext context) { throw new NotImplementedException (); } #endif } }
lgpl-3.0
MrYsLab/rbDashBoard
libs/RGraph/demos/bar-grouped.html
4545
<!DOCTYPE html > <html> <head> <link rel="stylesheet" href="demos.css" type="text/css" media="screen" /> <script src="../libraries/RGraph.common.core.js" ></script> <script src="../libraries/RGraph.bar.js" ></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <!--[if lt IE 9]><script src="../excanvas/excanvas.js"></script><![endif]--> <title>A Bar chart with long labels</title> <meta name="robots" content="noindex,nofollow" /> <meta name="description" content="A Bar chart with long labels" /> </head> <body> <h1>A Bar chart with long labels</h1> <canvas id="cvs" width="500" height="350" style="border: 1px solid #ddd">[No canvas support]</canvas> <script> $(document).ready(function () { var data = [[4,5,3],[4,8,6],[4,2,4],[4,2,3],[1,2,3],[8,8,4],[4,8,6]]; var bar = new RGraph.Bar({ id: 'cvs', data: data, options: { labels: ['Mondays sales statistics','Tuesdays sales statistics','Wednesdays sales statistics','Thursdays sales statistics','Fridays sales statistics','Saturdays sales statistics','Sundays sales statistics'], colors: ['red','yellow', 'pink'], grouping: 'stacked', gutter: { left: 100, top: 5, bottom: 125, right: 5 }, text: { angle: 45 }, strokestyle: 'rgba(0,0,0,0)' } }).draw(); }); </script> <p></p> This goes in the documents header (or you could place it just above the jQuery ready event code): <pre class="code"> &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="RGraph.common.core.js"&gt;&lt;/script&gt; &lt;script src="RGraph.bar.js"&gt;&lt;/script&gt; </pre> Put this where you want the chart to show up: <pre class="code"> &lt;canvas id="cvs" width="600" height="250" !style="border: 1px solid #ccc"&gt; [No canvas support] &lt;/canvas&gt; </pre> This is the code that generates the chart. Because it's using the jQuery ready event you can put this at the bottom of the document: <pre class="code"> &lt;script&gt; $(document).ready(function () { var data = [[4,5,3],[4,8,6],[4,2,4],[4,2,3],[1,2,3],[8,8,4],[4,8,6]]; var bar = new RGraph.Bar({ id: 'cvs', data: data, options: { labels: ['Mondays sales statistics','Tuesdays sales statistics','Wednesdays sales statistics','Thursdays sales statistics','Fridays sales statistics','Saturdays sales statistics','Sundays sales statistics'], colors: ['red','yellow', 'pink'], grouping: 'stacked', gutter: { left: 100, top: 5, bottom: 125, right: 5 }, text: { angle: 45 }, strokestyle: 'rgba(0,0,0,0)' } }).draw(); }); &lt;/script&gt; </pre> <p> <a href="https://www.facebook.com/sharer/sharer.php?u=http://www.rgraph.net" target="_blank" onclick="window.open('https://www.facebook.com/sharer/sharer.php?u=http://www.rgraph.net', null, 'top=50,left=50,width=600,height=368'); return false"><img src="../images/facebook-large.png" width="200" height="43" alt="Share on Facebook" border="0" title="Visit the RGraph Facebook page" /></a> <a href="https://twitter.com/_rgraph" target="_blank" onclick="window.open('https://twitter.com/_rgraph', null, 'top=50,left=50,width=700,height=400'); return false"><img src="../images/twitter-large.png" width="200" height="43" alt="Share on Twitter" border="0" title="Mention RGraph on Twitter" /></a> <a href="https://plus.google.com/107668942726927917971/posts" target="_blank" onclick="window.open('https://plus.google.com/107668942726927917971/posts', null, 'top=20,left=20,width=950,height=600'); return false"><img src="../images/google-plus--large.png" width="230" height="43" alt="Share on Google Plus" border="0" title="Mention RGraph on Google Plus" /></a> </p> <p> <a href="">&laquo; Back</a> </p> </body> </html>
lgpl-3.0
agry/NGECore2
scripts/loot/lootItems/rarelootchest/shard_of_the_serpent.py
538
def itemTemplate(): return ['object/tangible/component/weapon/lightsaber/shared_lightsaber_module_force_crystal.iff'] def customItemName(): return "Shard Of The Serpent" def biolink(): return 1 def customColor1(): return 3 def lootDescriptor(): return 'rarebuffitem' def itemStats(): stats =['proc_name','towCrystalUberCombat','towCrystalUberCombat'] stats +=['effectname','Harmonious Counteraction','Harmonious Counteraction'] stats +=['duration','180','180'] stats +=['cooldown','3600','3600'] return stats
lgpl-3.0
OneGet/0install-win
src/Backend/DesktopIntegration/Windows/AppAlias.cs
7765
/* * Copyright 2010-2015 Bastian Eicher * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser Public License for more details. * * You should have received a copy of the GNU Lesser Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.IO; using System.Linq; using System.Net; using JetBrains.Annotations; using Microsoft.Win32; using NanoByte.Common; using NanoByte.Common.Native; using NanoByte.Common.Storage; using NanoByte.Common.Tasks; using ZeroInstall.DesktopIntegration.Properties; using ZeroInstall.Store; namespace ZeroInstall.DesktopIntegration.Windows { /// <summary> /// Contains control logic for applying <see cref="AccessPoints.AppAlias"/> on Windows systems. /// </summary> public static class AppAlias { #region Constants /// <summary>The HKCU/HKLM registry key for storing application lookup paths.</summary> public const string RegKeyAppPaths = @"Software\Microsoft\Windows\CurrentVersion\App Paths"; #endregion #region Create /// <summary> /// Creates an application alias in the current system. /// </summary> /// <param name="target">The application being integrated.</param> /// <param name="command">The command within <paramref name="target"/> the alias shall point to; can be <see langword="null"/>.</param> /// <param name="aliasName">The name of the alias to be created.</param> /// <param name="machineWide">Create the alias machine-wide instead of just for the current user.</param> /// <param name="handler">A callback object used when the the user is to be informed about the progress of long-running operations such as downloads.</param> /// <exception cref="OperationCanceledException">The user canceled the task.</exception> /// <exception cref="IOException">A problem occurs while writing to the filesystem or registry.</exception> /// <exception cref="WebException">A problem occured while downloading additional data (such as icons).</exception> /// <exception cref="UnauthorizedAccessException">Write access to the filesystem or registry is not permitted.</exception> public static void Create(FeedTarget target, [CanBeNull] string command, [NotNull] string aliasName, bool machineWide, [NotNull] ITaskHandler handler) { #region Sanity checks if (string.IsNullOrEmpty(aliasName)) throw new ArgumentNullException("aliasName"); if (handler == null) throw new ArgumentNullException("handler"); #endregion if (string.IsNullOrEmpty(aliasName) || aliasName.IndexOfAny(Path.GetInvalidFileNameChars()) != -1) throw new IOException(string.Format(Resources.NameInvalidChars, aliasName)); string stubDirPath = Locations.GetIntegrationDirPath("0install.net", machineWide, "desktop-integration", "aliases"); string stubFilePath = Path.Combine(stubDirPath, aliasName + ".exe"); target.BuildRunStub(stubFilePath, handler, needsTerminal: true, command: command); AddToPath(stubDirPath, machineWide); AddToAppPaths(aliasName + ".exe", stubFilePath, machineWide); } /// <summary> /// Adds a directory to the system's search path. /// </summary> /// <param name="directory">The directory to add to the search path.</param> /// <param name="machineWide"><see langword="true"/> to use the machine-wide path variable; <see langword="false"/> for the per-user variant.</param> private static void AddToPath(string directory, bool machineWide) { var variableTarget = machineWide ? EnvironmentVariableTarget.Machine : EnvironmentVariableTarget.User; string existingValue = Environment.GetEnvironmentVariable("PATH", variableTarget); if (existingValue == null || !existingValue.Contains(directory)) { Environment.SetEnvironmentVariable("PATH", existingValue + Path.PathSeparator + directory, variableTarget); WindowsUtils.NotifyEnvironmentChanged(); } } /// <summary> /// Adds an EXE to the AppPath registry key. /// </summary> /// <param name="exeName">The name of the EXE file to add (including the file ending).</param> /// <param name="exePath">The full path to the EXE file.</param> /// <param name="machineWide"><see langword="true"/> to use the machine-wide registry key; <see langword="false"/> for the per-user variant.</param> private static void AddToAppPaths(string exeName, string exePath, bool machineWide) { // Only Windows 7 and newer support per-user AppPaths if (!machineWide && !WindowsUtils.IsWindows7) return; var hive = machineWide ? Registry.LocalMachine : Registry.CurrentUser; using (var appPathsKey = hive.CreateSubKeyChecked(RegKeyAppPaths)) using (var exeKey = appPathsKey.CreateSubKeyChecked(exeName)) exeKey.SetValue("", exePath); } #endregion #region Remove /// <summary> /// Removes an application alias from the current system. /// </summary> /// <param name="aliasName">The name of the alias to be removed.</param> /// <param name="machineWide">The alias was created machine-wide instead of just for the current user.</param> /// <exception cref="IOException">A problem occurs while writing to the filesystem or registry.</exception> /// <exception cref="UnauthorizedAccessException">Write access to the filesystem or registry is not permitted.</exception> public static void Remove(string aliasName, bool machineWide) { #region Sanity checks if (string.IsNullOrEmpty(aliasName)) throw new ArgumentNullException("aliasName"); #endregion string stubDirPath = Locations.GetIntegrationDirPath("0install.net", machineWide, "desktop-integration", "aliases"); string stubFilePath = Path.Combine(stubDirPath, aliasName + ".exe"); RemoveFromAppPaths(aliasName + ".exe", machineWide); if (File.Exists(stubFilePath)) File.Delete(stubFilePath); } /// <summary> /// Removes an EXE from the AppPath registry key. /// </summary> /// <param name="exeName">The name of the EXE file to add (including the file ending).</param> /// <param name="machineWide"><see langword="true"/> to use the machine-wide registry key; <see langword="false"/> for the per-user variant.</param> private static void RemoveFromAppPaths(string exeName, bool machineWide) { var hive = machineWide ? Registry.LocalMachine : Registry.CurrentUser; using (var appPathsKey = hive.OpenSubKey(RegKeyAppPaths, writable: true)) { if (appPathsKey != null && appPathsKey.GetSubKeyNames().Contains(exeName)) appPathsKey.DeleteSubKey(exeName); } } #endregion } }
lgpl-3.0
cpopescu/whispermedialib
third-party/gstreamer/gst-plugins-bad-0.10.19/gst/pnm/gstpnmenc.c
7937
/* GStreamer PNM encoder * Copyright (C) 2009 Lutz Mueller <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /** * SECTION:element-pnmenc * * Encodes pnm images. This plugin supports both raw and ASCII encoding. * To enable ASCII encoding, set the parameter ascii to TRUE. If you omit * the parameter or set it to FALSE, the output will be raw encoded. * * <refsect"> * <title>Example launch line</title> * |[ * gst-launch videotestsrc num_buffers=1 ! ffmpegcolorspace ! "video/x-raw-gray" ! pnmenc ascii=true ! filesink location=test.pnm * ]| The above pipeline writes a test pnm file (ASCII encoding). * </refsect2> */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "gstpnmenc.h" #include "gstpnmutils.h" #include <gst/gstutils.h> #include <gst/video/video.h> #include <string.h> enum { GST_PNMENC_PROP_0, GST_PNMENC_PROP_ASCII /* Add here. */ }; static GstStaticPadTemplate sink_pad_template = GST_STATIC_PAD_TEMPLATE ("sink", GST_PAD_SINK, GST_PAD_ALWAYS, GST_STATIC_CAPS (GST_VIDEO_CAPS_RGB "; " "video/x-raw-gray, width =" GST_VIDEO_SIZE_RANGE ", " "height =" GST_VIDEO_SIZE_RANGE ", framerate =" GST_VIDEO_FPS_RANGE ", " "bpp= (int) 8, depth= (int) 8")); static GstStaticPadTemplate src_pad_template = GST_STATIC_PAD_TEMPLATE ("src", GST_PAD_SRC, GST_PAD_ALWAYS, GST_STATIC_CAPS (MIME_ALL)); GST_BOILERPLATE (GstPnmenc, gst_pnmenc, GstElement, GST_TYPE_ELEMENT); static void gst_pnmenc_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec) { GstPnmenc *s = GST_PNMENC (object); switch (prop_id) { case GST_PNMENC_PROP_ASCII: if (g_value_get_boolean (value)) s->info.encoding = GST_PNM_ENCODING_ASCII; else s->info.encoding = GST_PNM_ENCODING_RAW; s->info.fields |= GST_PNM_INFO_FIELDS_ENCODING; break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void gst_pnmenc_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec) { GstPnmenc *s = GST_PNMENC (object); switch (prop_id) { case GST_PNMENC_PROP_ASCII: g_value_set_boolean (value, s->info.encoding == GST_PNM_ENCODING_ASCII); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static GstFlowReturn gst_pnmenc_chain (GstPad * pad, GstBuffer * buf) { GstPnmenc *s = GST_PNMENC (gst_pad_get_parent (pad)); GstFlowReturn r; gchar *header; GstBuffer *out; /* Assumption: One buffer, one image. That is, always first write header. */ header = g_strdup_printf ("P%i\n%i %i\n%i\n", s->info.type + 3 * (1 - s->info.encoding), s->info.width, s->info.height, s->info.max); out = gst_buffer_new (); gst_buffer_set_data (out, (guchar *) header, strlen (header)); gst_buffer_set_caps (out, GST_PAD_CAPS (s->src)); if ((r = gst_pad_push (s->src, out)) != GST_FLOW_OK) goto out; /* Need to convert from GStreamer rowstride to PNM rowstride */ if (s->info.width % 4 != 0) { guint i_rowstride; guint o_rowstride; GstBuffer *obuf; guint i; if (s->info.type == GST_PNM_TYPE_PIXMAP) { o_rowstride = 3 * s->info.width; i_rowstride = GST_ROUND_UP_4 (o_rowstride); } else { o_rowstride = s->info.width; i_rowstride = GST_ROUND_UP_4 (o_rowstride); } obuf = gst_buffer_new_and_alloc (o_rowstride * s->info.height); for (i = 0; i < s->info.height; i++) memcpy (GST_BUFFER_DATA (obuf) + o_rowstride * i, GST_BUFFER_DATA (buf) + i_rowstride * i, o_rowstride); gst_buffer_unref (buf); buf = obuf; } else { /* Pass through the data. */ buf = gst_buffer_make_metadata_writable (buf); } /* We might need to convert to ASCII... */ if (s->info.encoding == GST_PNM_ENCODING_ASCII) { GstBuffer *obuf; guint i, o; obuf = gst_buffer_new_and_alloc (GST_BUFFER_SIZE (buf) * (4 + 1 / 20.)); for (i = o = 0; i < GST_BUFFER_SIZE (buf); i++) { g_snprintf ((char *) GST_BUFFER_DATA (obuf) + o, 4, "%3i", GST_BUFFER_DATA (buf)[i]); o += 3; GST_BUFFER_DATA (obuf)[o++] = ' '; if (!((i + 1) % 20)) GST_BUFFER_DATA (obuf)[o++] = '\n'; } gst_buffer_unref (buf); buf = obuf; } gst_buffer_set_caps (buf, GST_PAD_CAPS (s->src)); r = gst_pad_push (s->src, buf); out: gst_object_unref (s); return r; } static gboolean gst_pnmenc_setcaps_func_sink (GstPad * pad, GstCaps * caps) { GstPnmenc *s = GST_PNMENC (gst_pad_get_parent (pad)); GstStructure *structure = gst_caps_get_structure (caps, 0); const gchar *mime = gst_structure_get_name (structure); gboolean r = TRUE; GstCaps *srccaps; s->info.max = 255; s->info.fields = GST_PNM_INFO_FIELDS_MAX; /* Set caps on the source. */ if (!strcmp (mime, "video/x-raw-rgb")) { s->info.type = GST_PNM_TYPE_PIXMAP; srccaps = gst_caps_from_string (MIME_PM); } else if (!strcmp (mime, "video/x-raw-gray")) { s->info.type = GST_PNM_TYPE_GRAYMAP; srccaps = gst_caps_from_string (MIME_GM); } else { r = FALSE; goto out; } gst_pad_set_caps (s->src, srccaps); gst_caps_unref (srccaps); s->info.fields |= GST_PNM_INFO_FIELDS_TYPE; /* Remember width and height of the input data. */ if (!gst_structure_get_int (structure, "width", (int *) &s->info.width) || !gst_structure_get_int (structure, "height", (int *) &s->info.height)) { r = FALSE; goto out; } s->info.fields |= GST_PNM_INFO_FIELDS_WIDTH | GST_PNM_INFO_FIELDS_HEIGHT; out: gst_object_unref (s); return r; } static void gst_pnmenc_init (GstPnmenc * s, GstPnmencClass * klass) { GstPad *pad; pad = gst_pad_new_from_template (gst_static_pad_template_get (&sink_pad_template), "sink"); gst_pad_set_setcaps_function (pad, gst_pnmenc_setcaps_func_sink); gst_pad_set_chain_function (pad, gst_pnmenc_chain); gst_pad_use_fixed_caps (pad); gst_element_add_pad (GST_ELEMENT (s), pad); s->src = gst_pad_new_from_template (gst_static_pad_template_get (&src_pad_template), "src"); gst_element_add_pad (GST_ELEMENT (s), s->src); } static void gst_pnmenc_base_init (gpointer g_class) { GstElementClass *element_class = GST_ELEMENT_CLASS (g_class); gst_element_class_add_pad_template (element_class, gst_static_pad_template_get (&sink_pad_template)); gst_element_class_add_pad_template (element_class, gst_static_pad_template_get (&src_pad_template)); gst_element_class_set_details_simple (element_class, "PNM image encoder", "Codec/Encoder/Image", "Encodes images into portable pixmap or graymap (PNM) format", "Lutz Mueller <[email protected]>"); } static void gst_pnmenc_class_init (GstPnmencClass * klass) { GObjectClass *gobject_class = G_OBJECT_CLASS (klass); gobject_class->set_property = gst_pnmenc_set_property; gobject_class->get_property = gst_pnmenc_get_property; g_object_class_install_property (gobject_class, GST_PNMENC_PROP_ASCII, g_param_spec_boolean ("ascii", "ASCII Encoding", "The output will be " "ASCII encoded", FALSE, G_PARAM_READWRITE)); }
lgpl-3.0
simingl/IM_Debug_Terran_GA_Micro
BasicAIModule/Source/Dll.cpp
668
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers #include <windows.h> #include <stdio.h> #include <tchar.h> #include <BWAPI.h> #include "BasicAIModule.h" namespace BWAPI { Game* Broodwar; } BOOL APIENTRY DllMain( HANDLE , DWORD ul_reason_for_call, LPVOID lpReserved ) { int i = 0; i++; switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: BWAPI::BWAPI_init(); break; case DLL_PROCESS_DETACH: break; } return TRUE; } extern "C" __declspec(dllexport) BWAPI::AIModule* newAIModule(BWAPI::Game* game) { BWAPI::Broodwar=game; return new BasicAIModule(); }
lgpl-3.0
simeshev/parabuild-ci
3rdparty/dwr-2.0.1/src/java/org/directwebremoting/convert/ObjectConverter.java
3798
/* * Copyright 2005 Joe Walker * * 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.directwebremoting.convert; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; import org.directwebremoting.extend.Converter; import org.directwebremoting.extend.InboundContext; import org.directwebremoting.extend.MarshallException; import org.directwebremoting.extend.Property; import org.directwebremoting.extend.TypeHintContext; import org.directwebremoting.impl.FieldProperty; /** * Convert a Javascript associative array into a JavaBean * @author Joe Walker [joe at getahead dot ltd dot uk] */ public class ObjectConverter extends BasicObjectConverter implements Converter { /** * Do we force accessibility for private fields * @param force "true|false" to set the force accessibility flag */ public void setForce(String force) { this.force = Boolean.valueOf(force).booleanValue(); } /* (non-Javadoc) * @see org.directwebremoting.extend.NamedConverter#getPropertyMapFromObject(java.lang.Object, boolean, boolean) */ public Map getPropertyMapFromObject(Object example, boolean readRequired, boolean writeRequired) throws MarshallException { Class clazz = example.getClass(); return getPropertyMapFromClass(clazz, readRequired, writeRequired); } /* (non-Javadoc) * @see org.directwebremoting.extend.NamedConverter#getPropertyMap(java.lang.Class, boolean, boolean) */ public Map getPropertyMapFromClass(Class type, boolean readRequired, boolean writeRequired) { Map allFields = new HashMap(); while (type != Object.class) { Field[] fields = type.getDeclaredFields(); fieldLoop: for (int i = 0; i < fields.length; i++) { Field field = fields[i]; String name = field.getName(); // We don't marshall getClass() if ("class".equals(name)) { continue fieldLoop; } // Access rules mean we might not want to do this one if (!isAllowedByIncludeExcludeRules(name)) { continue fieldLoop; } if (!Modifier.isPublic(field.getModifiers())) { if (force) { field.setAccessible(true); } else { continue fieldLoop; } } allFields.put(name, new FieldProperty(field)); } type = type.getSuperclass(); } return allFields; } /* (non-Javadoc) * @see org.directwebremoting.convert.BasicObjectConverter#createTypeHintContext(org.directwebremoting.extend.InboundContext, org.directwebremoting.extend.Property) */ protected TypeHintContext createTypeHintContext(InboundContext inctx, Property property) { return inctx.getCurrentTypeHintContext(); } /** * Do we force accessibillity for hidden fields */ private boolean force = false; }
lgpl-3.0
newdebug/NewDebug
Qt/3DDigitalSystemMan/ScriptManager/treemodel.cpp
6914
#include <QtGui> #include <QStringList> #include "treeitem.h" #include "treemodel.h" TreeModel::TreeModel(const QStringList &headers, const QString &data, QObject *parent): QAbstractItemModel(parent) { QVector<QVariant> rootData; foreach (QString header, headers) rootData << header; rootItem = new TreeItem(rootData); setupModelData(data.split(QString("\n")), rootItem); } TreeModel::~TreeModel() { delete rootItem; } int TreeModel::columnCount(const QModelIndex &parent) const { if (parent.isValid()) return static_cast<TreeItem*>(parent.internalPointer())->columnCount(); else return rootItem->columnCount(); } QVariant TreeModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if (role != Qt::DisplayRole) return QVariant(); TreeItem *item = static_cast<TreeItem*>(index.internalPointer()); return item->data(index.column()); } Qt::ItemFlags TreeModel::flags(const QModelIndex &index) const { if (!index.isValid()) return 0; return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable; } bool TreeModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (role != Qt::EditRole) return false; TreeItem *item = getItem(index); bool result = item->setData(index.column(), value); if (result) emit dataChanged(index, index); return result; } bool TreeModel::setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role) { if (role != Qt::EditRole || orientation != Qt::Horizontal) return false; bool result = rootItem->setData(section, value); if (result) emit headerDataChanged(orientation, section, section); return result; } bool TreeModel::insertColumns(int position, int columns, const QModelIndex &parent) { bool success; beginInsertColumns(parent, position, position + columns - 1); success = rootItem->insertColumns(position, columns); endInsertColumns(); return success; } bool TreeModel::removeColumns(int position, int columns, const QModelIndex &parent) { bool success; beginRemoveColumns(parent, position, position + columns - 1); success = rootItem->removeColumns(position, columns); endRemoveColumns(); if (rootItem->columnCount() == 0) removeRows(0, rowCount()); return success; } bool TreeModel::insertRows(int position, int rows, const QModelIndex &parent) { TreeItem *parentItem = getItem(parent); bool success; beginInsertRows(parent, position, position + rows - 1); success = parentItem->insertChildren(position, rows, rootItem->columnCount()); endInsertRows(); return success; } bool TreeModel::removeRows(int position, int rows, const QModelIndex &parent) { TreeItem *parentItem = getItem(parent); bool success = true; beginRemoveRows(parent, position, position + rows - 1); success = parentItem->removeChildren(position, rows); endRemoveRows(); return success; } TreeItem *TreeModel::getItem(const QModelIndex &index) const { if (index.isValid()) { TreeItem *item = static_cast<TreeItem*>(index.internalPointer()); if (item) return item; } return rootItem; } QVariant TreeModel::headerData(int section, Qt::Orientation orientation, int role) const { if (orientation == Qt::Horizontal && role == Qt::DisplayRole) return rootItem->data(section); return QVariant(); } QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent) const { if (!hasIndex(row, column, parent)) return QModelIndex(); TreeItem *parentItem = getItem(parent); if (!parent.isValid()) parentItem = rootItem; else parentItem = static_cast<TreeItem*>(parent.internalPointer()); TreeItem *childItem = parentItem->child(row); if (childItem) return createIndex(row, column, childItem); else return QModelIndex(); } QModelIndex TreeModel::parent(const QModelIndex &index) const { if (!index.isValid()) return QModelIndex(); TreeItem *childItem = getItem(index); TreeItem *parentItem = childItem->parent(); if (parentItem == rootItem) return QModelIndex(); return createIndex(parentItem->row(), 0, parentItem);//row() == childNumber() } int TreeModel::rowCount(const QModelIndex &parent) const { TreeItem *parentItem = getItem(parent); if (parent.column() > 0) return 0; if (!parent.isValid()) parentItem = rootItem; else parentItem = static_cast<TreeItem*>(parent.internalPointer()); return parentItem->childCount(); } void TreeModel::setupModelData(const QStringList &lines, TreeItem *parent) { QList<TreeItem*> parents; QList<int> indentations; parents << parent; indentations << 0; int number = 0; while (number < lines.count()) { int position = 0; while (position < lines[number].length()) { if (lines[number].mid(position, 1) != " ") break; position++; } QString lineData = lines[number].mid(position).trimmed(); if (!lineData.isEmpty()) { // Read the column data from the rest of the line. QStringList columnStrings = lineData.split("\t", QString::SkipEmptyParts); QList<QVariant> columnData; for (int column = 0; column < columnStrings.count(); ++column) columnData << columnStrings[column]; if (position > indentations.last()) { // The last child of the current parent is now the new parent // unless the current parent has no children. if (parents.last()->childCount() > 0) { parents << parents.last()->child(parents.last()->childCount()-1); indentations << position; } } else { while (position < indentations.last() && parents.count() > 0) { parents.pop_back(); indentations.pop_back(); } } // Append a new item to the current parent's list of children. TreeItem *parent = parents.last(); parent->insertChildren(parent->childCount(), 1, rootItem->columnCount()); for (int column = 0; column < columnData.size(); ++column) parent->child(parent->childCount() - 1)->setData(column, columnData[column]); } number++; } }
lgpl-3.0
olliwang/makegyp
makegyp/formula/openssl.py
2054
import os import shutil from makegyp import formula from makegyp.core import gyp from makegyp.core import parser class Openssl(formula.Formula): parser = parser.GccParser() url = 'http://www.openssl.org/source/openssl-1.0.1e.tar.gz' sha256 = 'f74f15e8c8ff11aa3d5bb5f276d202ec18d7246e95f961db76054199c69c1ae3' dependencies = ['zlib'] default_target_arch = 'ia32' def configure(self): return './config zlib no-shared' def make(self): return 'make' def patch_gyp_dict(self, gyp_dict): # Patchs the libcrypto target: for target in gyp_dict['targets']: if target['target_name'] == 'libcrypto': # Adds the missing `mem_clr.c` source: target['sources'].append('crypto/mem_clr.c') target['sources'].sort() # Adds zlib as dependency: target['dependencies'] = ['../zlib/zlib.gyp:libz'] break def post_process(self, package_root): # Copies the generated "*.s" files to package: for target in self.gyp['targets']: for source in target['sources']: if source.endswith('.s'): print('Copying source file: %s' % source) path_components = source.split('/') source = os.path.join(self.tmp_package_root, *path_components) dest = os.path.join(package_root, *path_components) shutil.copyfile(source, dest) # Copies config files: config_file_paths = ['crypto/buildinf.h'] for path in config_file_paths: print('Copying config file: %s' % path) source = os.path.join(self.tmp_package_root, *path.split('/')) dest = os.path.join(package_root, formula.kConfigRootDirectoryName, gyp.get_os(), self.default_target_arch, os.path.basename(source)) shutil.copyfile(source, dest)
lgpl-3.0
arthurzam/QMPlay2
src/qmplay2/ModuleCommon.cpp
1226
/* QMPlay2 is a video and audio player. Copyright (C) 2010-2022 Błażej Szczygieł This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This 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. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <ModuleCommon.hpp> bool ModuleCommon::set() { return true; } ModuleCommon::~ModuleCommon() { if (module) { module->mutex.lock(); module->instances.removeOne(this); module->mutex.unlock(); } } void ModuleCommon::SetModule(Module &m) { if (!module) { module = &m; module->mutex.lock(); module->instances.append(this); module->mutex.unlock(); set(); } }
lgpl-3.0
zdzhaoyong/PIL
Thirdparty/opmapcontrol/core.1/memorycache.h
1638
/** ****************************************************************************** * * @file memorycache.h * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2012. * @brief * @see The GNU Public License (GPL) Version 3 * @defgroup OPMapWidget * @{ * *****************************************************************************/ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef MEMORYCACHE_H #define MEMORYCACHE_H #include "rawtile.h" #include <QMutex> #include <QReadWriteLock> #include <QQueue> #include "kibertilecache.h" #include <QDebug> #include "debugheader.h" namespace core { class MemoryCache { public: MemoryCache(); KiberTileCache TilesInMemory; QByteArray GetTileFromMemoryCache(const RawTile &tile); void AddTileToMemoryCache(const RawTile &tile, const QByteArray &pic); QReadWriteLock kiberCacheLock; }; } #endif // MEMORYCACHE_H
lgpl-3.0
ljug/java-tutorials
ACCOV/TPJanvier2017/PCaSem/src/pcasem/Consommateur.java
1991
/* * Copyright © <Pascal Fares @ ISSAE - Cnam Liban> * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * The Software is provided “as is”, without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, * whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the Software. » */ package pcasem; /** * * @author pascalfares */ public class Consommateur extends Thread { private TampCirc Tampon; private Integer Valeur_Lue; public Consommateur(TampCirc Tampon) { this.Tampon = Tampon; } ////////////////////////////////////////////////////////// public void run() { while (true) { Valeur_Lue = ((Integer)Tampon.Consommer()); // System.out.println(" --- Consommateur " + Thread.currentThread().getName() + " lit " +((Integer)Tampon.Consommer()).toString() ); System.out.println(" --- Consommateur " + Thread.currentThread().getName() + " lit " + Valeur_Lue); // verifier le timeout //if (Valeur_Lue == null) break; try { Thread.sleep((int)(Math.random()*200)); // sleep : en ms } catch (InterruptedException e) {} } } }
lgpl-3.0
sandipde/plumed-sandip
src/reference/ArgumentOnlyDistance.h
1756
/* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Copyright (c) 2012-2014 The plumed team (see the PEOPLE file at the root of the distribution for a list of names) See http://www.plumed-code.org for more information. This file is part of plumed, version 2. plumed is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. plumed is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with plumed. If not, see <http://www.gnu.org/licenses/>. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ #ifndef __PLUMED_reference_ArgumentOnlyDistance_h #define __PLUMED_reference_ArgumentOnlyDistance_h #include <vector> #include <string> #include "ReferenceArguments.h" namespace PLMD { class PDB; class Pbc; class ArgumentOnlyDistance : public ReferenceArguments { private: std::vector<double> tmparg; public: ArgumentOnlyDistance( const ReferenceConfigurationOptions& ro ); double calc( const std::vector<Vector>& pos, const Pbc& pbc, const std::vector<Value*>& vals, const std::vector<double>& arg, const bool& squared ); double calculate( const std::vector<Value*>& vals, const bool& squared ); virtual double calc( const std::vector<Value*>& vals, const std::vector<double>& arg, const bool& squared )=0; }; } #endif
lgpl-3.0
croll/captainhook
mod/smarty/smarty/libs/plugins/modifiercompiler.count_paragraphs.php
806
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsModifierCompiler */ /** * Smarty count_paragraphs modifier plugin * * Type: modifier<br> * Name: count_paragraphs<br> * Purpose: count the number of paragraphs in a text * * @link http://www.smarty.net/manual/en/language.modifier.count.paragraphs.php * count_paragraphs (Smarty online manual) * @author Uwe Tews * * @param string $input input string * @return string with compiled code */ // NOTE: The parser does pass all parameter as strings which could be directly inserted into the compiled code string function smarty_modifiercompiler_count_paragraphs($input) { // count \r or \n characters return '(preg_match_all(\'#[\r\n]+#\', ' . $input . ', $tmp)+1)'; } ?>
lgpl-3.0
arruda/pyfuzzy
fuzzy/doc/structure/dot/__init__.py
826
# -*- coding: iso-8859-1 -*- # # Copyright (C) 2009 Rene Liebscher # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. # # This 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. # # You should have received a copy of the GNU Lesser General Public License along with # this program; if not, see <http://www.gnu.org/licenses/>. # """Documentation """ __revision__ = "$Id: __init__.py,v 1.2 2009/08/07 07:19:18 rliebscher Exp $"
lgpl-3.0
ccarducci/Ushahidi_local
G3MiOSSDK/Commons/GEO/GEO2DLineStringGeometry.hpp
713
// // GEO2DLineStringGeometry.hpp // G3MiOSSDK // // Created by Diego Gomez Deck on 11/30/12. // // #ifndef __G3MiOSSDK__GEO2DLineStringGeometry__ #define __G3MiOSSDK__GEO2DLineStringGeometry__ #include "GEOGeometry2D.hpp" class Geodetic2D; #include <vector> class GEO2DLineStringGeometry : public GEOGeometry2D { private: std::vector<Geodetic2D*>* _coordinates; protected: std::vector<GEOSymbol*>* createSymbols(const GEOSymbolizer* symbolizer) const; public: GEO2DLineStringGeometry(std::vector<Geodetic2D*>* coordinates) : _coordinates(coordinates) { } ~GEO2DLineStringGeometry(); const std::vector<Geodetic2D*>* getCoordinates() const { return _coordinates; } }; #endif
lgpl-3.0
getvasanth/QtSpeech
festival/speech_tools/wrappers/python/EST_Track.py
8370
# This file was automatically generated by SWIG (http://www.swig.org). # Version 1.3.40 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. # This file is compatible with both classic and new-style classes. from sys import version_info if version_info >= (2,6,0): def swig_import_helper(): from os.path import dirname import imp fp = None try: fp, pathname, description = imp.find_module('_EST_Track', [dirname(__file__)]) except ImportError: import _EST_Track return _EST_Track if fp is not None: try: _mod = imp.load_module('_EST_Track', fp, pathname, description) finally: fp.close() return _mod _EST_Track = swig_import_helper() del swig_import_helper else: import _EST_Track del version_info try: _swig_property = property except NameError: pass # Python < 2.2 doesn't have 'property'. def _swig_setattr_nondynamic(self,class_type,name,value,static=1): if (name == "thisown"): return self.this.own(value) if (name == "this"): if type(value).__name__ == 'SwigPyObject': self.__dict__[name] = value return method = class_type.__swig_setmethods__.get(name,None) if method: return method(self,value) if (not static) or hasattr(self,name): self.__dict__[name] = value else: raise AttributeError("You cannot add attributes to %s" % self) def _swig_setattr(self,class_type,name,value): return _swig_setattr_nondynamic(self,class_type,name,value,0) def _swig_getattr(self,class_type,name): if (name == "thisown"): return self.this.own() method = class_type.__swig_getmethods__.get(name,None) if method: return method(self) raise AttributeError(name) def _swig_repr(self): try: strthis = "proxy of " + self.this.__repr__() except: strthis = "" return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,) try: _object = object _newclass = 1 except AttributeError: class _object : pass _newclass = 0 read_ok = _EST_Track.read_ok read_format_error = _EST_Track.read_format_error read_not_found_error = _EST_Track.read_not_found_error read_error = _EST_Track.read_error write_ok = _EST_Track.write_ok write_fail = _EST_Track.write_fail write_error = _EST_Track.write_error write_partial = _EST_Track.write_partial connect_ok = _EST_Track.connect_ok connect_not_found_error = _EST_Track.connect_not_found_error connect_not_allowed_error = _EST_Track.connect_not_allowed_error connect_system_error = _EST_Track.connect_system_error connect_error = _EST_Track.connect_error import EST_FVector class EST_Track(_object): __swig_setmethods__ = {} __setattr__ = lambda self, name, value: _swig_setattr(self, EST_Track, name, value) __swig_getmethods__ = {} __getattr__ = lambda self, name: _swig_getattr(self, EST_Track, name) __repr__ = _swig_repr __swig_getmethods__["default_frame_shift"] = _EST_Track.EST_Track_default_frame_shift_get if _newclass:default_frame_shift = _swig_property(_EST_Track.EST_Track_default_frame_shift_get) __swig_getmethods__["default_sample_rate"] = _EST_Track.EST_Track_default_sample_rate_get if _newclass:default_sample_rate = _swig_property(_EST_Track.EST_Track_default_sample_rate_get) def __init__(self, *args): this = _EST_Track.new_EST_Track(*args) try: self.this.append(this) except: self.this = this __swig_destroy__ = _EST_Track.delete_EST_Track __del__ = lambda self : None; def resize(self, *args): return _EST_Track.EST_Track_resize(self, *args) def set_num_channels(self, *args): return _EST_Track.EST_Track_set_num_channels(self, *args) def set_num_frames(self, *args): return _EST_Track.EST_Track_set_num_frames(self, *args) def set_channel_name(self, *args): return _EST_Track.EST_Track_set_channel_name(self, *args) def set_aux_channel_name(self, *args): return _EST_Track.EST_Track_set_aux_channel_name(self, *args) def copy_setup(self, *args): return _EST_Track.EST_Track_copy_setup(self, *args) def name(self): return _EST_Track.EST_Track_name(self) def set_name(self, *args): return _EST_Track.EST_Track_set_name(self, *args) def frame(self, *args): return _EST_Track.EST_Track_frame(self, *args) def channel(self, *args): return _EST_Track.EST_Track_channel(self, *args) def sub_track(self, *args): return _EST_Track.EST_Track_sub_track(self, *args) def copy_sub_track(self, *args): return _EST_Track.EST_Track_copy_sub_track(self, *args) def copy_sub_track_out(self, *args): return _EST_Track.EST_Track_copy_sub_track_out(self, *args) def copy_channel_out(self, *args): return _EST_Track.EST_Track_copy_channel_out(self, *args) def copy_frame_out(self, *args): return _EST_Track.EST_Track_copy_frame_out(self, *args) def copy_channel_in(self, *args): return _EST_Track.EST_Track_copy_channel_in(self, *args) def copy_frame_in(self, *args): return _EST_Track.EST_Track_copy_frame_in(self, *args) def channel_position(self, *args): return _EST_Track.EST_Track_channel_position(self, *args) def has_channel(self, *args): return _EST_Track.EST_Track_has_channel(self, *args) def a(self, *args): return _EST_Track.EST_Track_a(self, *args) def t(self, i = 0): return _EST_Track.EST_Track_t(self, i) def ms_t(self, *args): return _EST_Track.EST_Track_ms_t(self, *args) def fill_time(self, *args): return _EST_Track.EST_Track_fill_time(self, *args) def fill(self, *args): return _EST_Track.EST_Track_fill(self, *args) def sample(self, *args): return _EST_Track.EST_Track_sample(self, *args) def shift(self): return _EST_Track.EST_Track_shift(self) def start(self): return _EST_Track.EST_Track_start(self) def end(self): return _EST_Track.EST_Track_end(self) def load(self, *args): return _EST_Track.EST_Track_load(self, *args) def save(self, *args): return _EST_Track.EST_Track_save(self, *args) def set_break(self, *args): return _EST_Track.EST_Track_set_break(self, *args) def set_value(self, *args): return _EST_Track.EST_Track_set_value(self, *args) def val(self, *args): return _EST_Track.EST_Track_val(self, *args) def track_break(self, *args): return _EST_Track.EST_Track_track_break(self, *args) def prev_non_break(self, *args): return _EST_Track.EST_Track_prev_non_break(self, *args) def next_non_break(self, *args): return _EST_Track.EST_Track_next_non_break(self, *args) def empty(self): return _EST_Track.EST_Track_empty(self) def index(self, *args): return _EST_Track.EST_Track_index(self, *args) def index_below(self, *args): return _EST_Track.EST_Track_index_below(self, *args) def num_frames(self): return _EST_Track.EST_Track_num_frames(self) def length(self): return _EST_Track.EST_Track_length(self) def num_channels(self): return _EST_Track.EST_Track_num_channels(self) def num_aux_channels(self): return _EST_Track.EST_Track_num_aux_channels(self) def equal_space(self): return _EST_Track.EST_Track_equal_space(self) def single_break(self): return _EST_Track.EST_Track_single_break(self) def set_equal_space(self, *args): return _EST_Track.EST_Track_set_equal_space(self, *args) def set_single_break(self, *args): return _EST_Track.EST_Track_set_single_break(self, *args) def __iadd__(self, *args): return _EST_Track.EST_Track___iadd__(self, *args) def __ior__(self, *args): return _EST_Track.EST_Track___ior__(self, *args) def load_channel_names(self, *args): return _EST_Track.EST_Track_load_channel_names(self, *args) def save_channel_names(self, *args): return _EST_Track.EST_Track_save_channel_names(self, *args) def channel_name(self, *args): return _EST_Track.EST_Track_channel_name(self, *args) def aux_channel_name(self, *args): return _EST_Track.EST_Track_aux_channel_name(self, *args) EST_Track_swigregister = _EST_Track.EST_Track_swigregister EST_Track_swigregister(EST_Track) def mean(*args): return _EST_Track.mean(*args) mean = _EST_Track.mean def meansd(*args): return _EST_Track.meansd(*args) meansd = _EST_Track.meansd def normalise(*args): return _EST_Track.normalise(*args) normalise = _EST_Track.normalise
lgpl-3.0
khaledhosny/libmathview
src/engine/MathMLPhantomElement.hh
1812
// Copyright (C) 2000-2007, Luca Padovani <[email protected]>. // // This file is part of GtkMathView, a flexible, high-quality rendering // engine for MathML documents. // // GtkMathView is free software; you can redistribute it and/or modify it // either under the terms of the GNU Lesser General Public License version // 3 as published by the Free Software Foundation (the "LGPL") or, at your // option, under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation (the "GPL"). If you do not // alter this notice, a recipient may use your version of this file under // either the GPL or the LGPL. // // GtkMathView 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 LGPL or // the GPL for more details. // // You should have received a copy of the LGPL and of the GPL along with // this program in the files COPYING-LGPL-3 and COPYING-GPL-2; if not, see // <http://www.gnu.org/licenses/>. #ifndef __MathMLPhantomElement_hh__ #define __MathMLPhantomElement_hh__ #include "MathMLEmbellishment.hh" #include "MathMLNormalizingContainerElement.hh" class MathMLPhantomElement : public MathMLNormalizingContainerElement, public MathMLEmbellishment { public: MathMLPhantomElement(const SmartPtr<class MathMLNamespaceContext>&); virtual ~MathMLPhantomElement(); public: static SmartPtr<MathMLPhantomElement> create(const SmartPtr<class MathMLNamespaceContext>& view) { return new MathMLPhantomElement(view); } virtual AreaRef format(class FormattingContext&); virtual bool IsSpaceLike(void) const; virtual SmartPtr<class MathMLOperatorElement> getCoreOperator(void); }; #endif // __MathMLPhantomElement_hh__
lgpl-3.0
flobee/mumsys-js
src/Mumsys/Generic/README.md
2990
# Using the generic item/manager ## Forword DTO/DAO is quite simple an very powerful. But understanding this simple thing sometimes takes a time. This generic version has some BUTs but you will agree: - It will downgrade implementation time - Server requests will slow down (performance boost) because only changed data will be served. - Clean interface (But danger in detail! You may implement for each task individual items/manager interfaces) - Closed data handling: Must have using get/set methodes to get or change data. Which helps to reduce memory/ GC. ## Usage Eg.: You load a list of objects form the server which serves jsonrpc 2.0 as follow. E.g: ### Request: var myManager = new Mumsys_Generic_Manager_Default("/requestjson"); var requestData = {}; var requestOptions = {"async":false}; myManager.loadItems(requestData, requestOptions); ### Response (JsonRPC): The list shows e.g. some rows of your database. Well formed. { "jsonrpc": "2.0", "result": { "list": [ {"id": 1, "name": "Some name 1"}, {"id": 3, "name": "Some name 3"}, {"id": 5, "name": "Some name 5"}, {"id": 7, "name": "Some name 7"} ] } , "id": null, // request ID, Optional } ### Result myManager now includes 4 Objects implementing the Mumsys_Generic_Item_Default class/ interface. Now you can work with it e.g. Showing the list, some forms to change the data. E.g: var item1 = myManager.getItem("id", 5); // Example using jQuery $('#myform id').val( item1.get("id") ); $('#myform name').val( item1.get("name", "Name not set") ); Now you change some values and want to save them: item1.set("name", $('#myform name').val() ); // prepeare saving, e.g: var params = {"controller":"mycontroller","action":"someaction"}; var requestOptions = {"async": false, "type": "POST", "url": "/some-post-url"}; myManager.saveItem( item1, params, requestOptions ); Whats happend now: If the item values has changes a real request performs to the given url. It send the data to the server e.g. as post request. You save the data. The answer must be a jsonrpc response and must be as follow: { "jsonrpc":"2.0", "result":{ "item":{ "id":5, "name":"Your changed value" } }, "id":null, // future: request ID } Now the new item returns with the new value the item already knows. If the server updates some properties like ctime, mtime values you need to update the item! It will not be set automatically (currently) and i want to keep that open for individual requirements. Performance resons! If you need it: myManager.removeItem( itemID ); myManager.addItem( myManager.createItem( oJsonResponse.result.item ) ); Thats all. A very simple but powerful option to handle data.
lgpl-3.0
Allors/allors2
Platform/Database/Adapters/Allors.Database.Adapters.Npgsql/Predicates/CompositePredicate.cs
9590
// <copyright file="CompositePredicate.cs" company="Allors bvba"> // Copyright (c) Allors bvba. All rights reserved. // Licensed under the LGPL license. See LICENSE file in the project root for full license information. // </copyright> namespace Allors.Database.Adapters.Npgsql { using System; using System.Collections.Generic; using System.Linq; using Allors.Meta; internal abstract class CompositePredicate : Predicate, ICompositePredicate { protected CompositePredicate(ExtentFiltered extent) { this.Extent = extent; this.Filters = new List<Predicate>(4); if (extent.Strategy != null) { var allorsObject = extent.Strategy.GetObject(); if (extent.AssociationType != null) { var role = extent.AssociationType.RoleType; if (role.IsMany) { this.AddContains(role, allorsObject); } else { this.AddEquals(role, allorsObject); } } else { var association = extent.RoleType.AssociationType; if (association.IsMany) { this.AddContains(association, allorsObject); } else { this.AddEquals(association, allorsObject); } } } } internal override bool Include { get { foreach (var filter in this.Filters) { if (filter.Include) { return true; } } return false; } } protected ExtentFiltered Extent { get; } protected List<Predicate> Filters { get; } public ICompositePredicate AddAnd() { this.Extent.FlushCache(); var allFilter = new AndPredicate(this.Extent); this.Filters.Add(allFilter); return allFilter; } public ICompositePredicate AddBetween(IRoleType role, object firstValue, object secondValue) { this.Extent.FlushCache(); if (firstValue is IRoleType betweenRoleA && secondValue is IRoleType betweenRoleB) { this.Filters.Add(new RoleBetweenRole(this.Extent, role, betweenRoleA, betweenRoleB)); } else if (firstValue is IAssociationType betweenAssociationA && secondValue is IAssociationType betweenAssociationB) { throw new NotImplementedException(); } else { this.Filters.Add(new RoleBetweenValue(this.Extent, role, firstValue, secondValue)); } return this; } public ICompositePredicate AddContainedIn(IRoleType role, Allors.Extent containingExtent) { this.Extent.FlushCache(); this.Filters.Add(new RoleContainedInExtent(this.Extent, role, containingExtent)); return this; } public ICompositePredicate AddContainedIn(IRoleType role, IEnumerable<IObject> containingEnumerable) { this.Extent.FlushCache(); this.Filters.Add(new RoleContainedInEnumerable(this.Extent, role, containingEnumerable)); return this; } public ICompositePredicate AddContainedIn(IAssociationType association, Allors.Extent containingExtent) { this.Extent.FlushCache(); this.Filters.Add(new AssociationContainedInExtent(this.Extent, association, containingExtent)); return this; } public ICompositePredicate AddContainedIn(IAssociationType association, IEnumerable<IObject> containingEnumerable) { this.Extent.FlushCache(); this.Filters.Add(new AssociationContainedInEnumerable(this.Extent, association, containingEnumerable)); return this; } public ICompositePredicate AddContains(IRoleType role, IObject containedObject) { this.Extent.FlushCache(); this.Filters.Add(new RoleContains(this.Extent, role, containedObject)); return this; } public ICompositePredicate AddContains(IAssociationType association, IObject containedObject) { this.Extent.FlushCache(); this.Filters.Add(new AssociationContains(this.Extent, association, containedObject)); return this; } public ICompositePredicate AddEquals(IObject allorsObject) { this.Extent.FlushCache(); this.Filters.Add(new Equals(allorsObject)); return this; } public ICompositePredicate AddEquals(IRoleType role, object obj) { this.Extent.FlushCache(); if (obj is IRoleType equalsRole) { this.Filters.Add(new RoleEqualsRole(this.Extent, role, equalsRole)); } else if (obj is IAssociationType equalsAssociation) { throw new NotImplementedException(); } else { this.Filters.Add(new RoleEqualsValue(this.Extent, role, obj)); } return this; } public ICompositePredicate AddEquals(IAssociationType association, IObject allorsObject) { this.Extent.FlushCache(); this.Filters.Add(new AssociationEquals(this.Extent, association, allorsObject)); return this; } public ICompositePredicate AddExists(IRoleType role) { this.Extent.FlushCache(); this.Filters.Add(new RoleExists(this.Extent, role)); return this; } public ICompositePredicate AddExists(IAssociationType association) { this.Extent.FlushCache(); this.Filters.Add(new AssociationExists(this.Extent, association)); return this; } public ICompositePredicate AddGreaterThan(IRoleType role, object value) { this.Extent.FlushCache(); if (value is IRoleType greaterThanRole) { this.Filters.Add(new RoleGreaterThanRole(this.Extent, role, greaterThanRole)); } else if (value is IAssociationType greaterThanAssociation) { throw new NotImplementedException(); } else { this.Filters.Add(new RoleGreaterThanValue(this.Extent, role, value)); } return this; } public ICompositePredicate AddInstanceof(IComposite type) { this.Extent.FlushCache(); this.Filters.Add(new InstanceOf(type, GetConcreteSubClasses(type))); return this; } public ICompositePredicate AddInstanceof(IRoleType role, IComposite type) { this.Extent.FlushCache(); this.Filters.Add(new RoleInstanceof(this.Extent, role, type, GetConcreteSubClasses(type))); return this; } public ICompositePredicate AddInstanceof(IAssociationType association, IComposite type) { this.Extent.FlushCache(); this.Filters.Add(new AssociationInstanceOf(this.Extent, association, type, GetConcreteSubClasses(type))); return this; } public ICompositePredicate AddLessThan(IRoleType role, object value) { this.Extent.FlushCache(); if (value is IRoleType lessThanRole) { this.Filters.Add(new RoleLessThanRole(this.Extent, role, lessThanRole)); } else if (value is IAssociationType lessThanAssociation) { throw new NotImplementedException(); } else { this.Filters.Add(new RoleLessThanValue(this.Extent, role, value)); } return this; } public ICompositePredicate AddLike(IRoleType role, string value) { this.Extent.FlushCache(); this.Filters.Add(new RoleLike(this.Extent, role, value)); return this; } public ICompositePredicate AddNot() { this.Extent.FlushCache(); var noneFilter = new Not(this.Extent); this.Filters.Add(noneFilter); return noneFilter; } public ICompositePredicate AddOr() { this.Extent.FlushCache(); var anyFilter = new Or(this.Extent); this.Filters.Add(anyFilter); return anyFilter; } internal static IObjectType[] GetConcreteSubClasses(IObjectType type) { if (type.IsInterface) { return ((IInterface)type).Subclasses.ToArray(); } var concreteSubclasses = new IObjectType[1]; concreteSubclasses[0] = type; return concreteSubclasses; } internal override void Setup(ExtentStatement statement) { foreach (var filter in this.Filters) { filter.Setup(statement); } } } }
lgpl-3.0
ipeychev/lfr-amd-loader
src/loader/__tests__/__fixtures__/loader/local-require/to-url.js
278
/** * SPDX-FileCopyrightText: © 2014 Liferay, Inc. <https://liferay.com> * SPDX-License-Identifier: LGPL-3.0-or-later */ Loader.define( 'local-require/to-url', ['module', 'require'], (module, require) => { module.exports = require.toUrl('local-require/to-url'); } );
lgpl-3.0
kingjiang/SharpDevelopLite
src/Main/ICSharpCode.Core.WinForms/Menu/MenuCheckBox.cs
2415
// <file> // <copyright see="prj:///doc/copyright.txt"/> // <license see="prj:///doc/license.txt"/> // <owner name="Mike Krüger" email="[email protected]"/> // <version>$Revision$</version> // </file> using System; using System.Windows.Forms; namespace ICSharpCode.Core.WinForms { public class MenuCheckBox : ToolStripMenuItem , IStatusUpdate { object caller; Codon codon; string description = String.Empty; ICheckableMenuCommand menuCommand = null; void CreateMenuCommand() { if (menuCommand == null) { try { menuCommand = (ICheckableMenuCommand)codon.AddIn.CreateObject(codon.Properties["class"]); } catch (Exception e) { MessageService.ShowError(e, "Can't create menu command : " + codon.Id); } } } public ICheckableMenuCommand MenuCommand { get { CreateMenuCommand(); return menuCommand; } } public string Description { get { return description; } set { description = value; } } public MenuCheckBox(string text) { this.RightToLeft = RightToLeft.Inherit; Text = text; } public MenuCheckBox(Codon codon, object caller) { this.RightToLeft = RightToLeft.Inherit; this.caller = caller; this.codon = codon; UpdateText(); } protected override void OnClick(System.EventArgs e) { base.OnClick(e); if (codon != null) { MenuCommand.Run(); Checked = MenuCommand.IsChecked; } } public override bool Enabled { get { if (codon == null) { return base.Enabled; } ConditionFailedAction failedAction = codon.GetFailedAction(caller); return failedAction != ConditionFailedAction.Disable; } } public virtual void UpdateStatus() { if (codon != null) { ConditionFailedAction failedAction = codon.GetFailedAction(caller); this.Visible = failedAction != ConditionFailedAction.Exclude; if (menuCommand == null && !string.IsNullOrEmpty(codon.Properties["checked"])) { Checked = string.Equals(StringParser.Parse(codon.Properties["checked"]), bool.TrueString, StringComparison.OrdinalIgnoreCase); } else { CreateMenuCommand(); if (menuCommand != null) { Checked = menuCommand.IsChecked; } } } } public virtual void UpdateText() { if (codon != null) { Text = StringParser.Parse(codon.Properties["label"]); } } } }
lgpl-3.0
bsc-pm/nanox
tests/test/00_arch/unix-os/nanos_register.cpp
2137
/*************************************************************************************/ /* Copyright 2009-2018 Barcelona Supercomputing Center */ /* */ /* This file is part of the NANOS++ library. */ /* */ /* NANOS++ is free software: you can redistribute it and/or modify */ /* it under the terms of the GNU Lesser General Public License as published by */ /* the Free Software Foundation, either version 3 of the License, or */ /* (at your option) any later version. */ /* */ /* NANOS++ is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /* GNU Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with NANOS++. If not, see <https://www.gnu.org/licenses/>. */ /*************************************************************************************/ /* <testinfo> test_generator="gens/core-generator" test_generator_ENV=( "NX_TEST_MODE=performance" "NX_TEST_MAX_CPUS=1" "NX_TEST_SCHEDULE=bf" "NX_TEST_ARCH=smp" ) </testinfo> */ #include "nanos-int.h" #include "compatibility.hpp" static int error = 1; extern "C" { void my_init(void *arg); void my_init(void *arg) { error = 0; } } NANOS_REGISTER(nanos_init, nanos_init_desc_t, { my_init, 0 }); int main ( int argc, char **argv ) { return error; }
lgpl-3.0
consumentor/Server
trunk/tools/AspNetAjaxLibraryBeta0911/Scripts/extended/PopupExtender/PopupBehavior.debug.js
30754
/// <reference name="MicrosoftAjax.debug.js" /> /// <reference path="../ExtenderBase/BaseScripts.js" /> /// <reference path="../Common/Common.js" /> /// <reference path="../Animation/Animations.js" /> /// <reference path="../Animation/AnimationBehavior.js" /> (function() { var scriptName = "ExtendedPopup"; function execute() { Type.registerNamespace('Sys.Extended.UI'); Sys.Extended.UI.PopupBehavior = function(element) { /// <summary> /// The PopupBehavior is used to show/hide an element at a position /// relative to another element /// </summary> /// <param name="element" type="Sys.UI.DomElement" mayBeNull="false" domElement="true"> /// The DOM element the behavior is associated with /// </param> Sys.Extended.UI.PopupBehavior.initializeBase(this, [element]); this._x = 0; this._y = 0; this._positioningMode = Sys.Extended.UI.PositioningMode.Absolute; this._parentElement = null; this._parentElementID = null; this._moveHandler = null; this._firstPopup = true; this._originalParent = null; this._visible = false; // Generic animation behaviors that automatically build animations // from JSON descriptions this._onShow = null; this._onHide = null; // Create handlers for the animation ended events this._onShowEndedHandler = Function.createDelegate(this, this._onShowEnded); this._onHideEndedHandler = Function.createDelegate(this, this._onHideEnded); } Sys.Extended.UI.PopupBehavior.prototype = { initialize: function() { /// <summary> /// Initialize the PopupBehavior /// </summary> Sys.Extended.UI.PopupBehavior.callBaseMethod(this, 'initialize'); this._hidePopup(); this.get_element().style.position = "absolute"; }, dispose: function() { /// <summary> /// Dispose the PopupBehavior /// </summary> var element = this.get_element(); if (element) { if (this._visible) { this.hide(); } if (this._originalParent) { element.parentNode.removeChild(element); this._originalParent.appendChild(element); this._originalParent = null; } // Remove expando properties element._hideWindowedElementsIFrame = null; } this._parentElement = null; // Remove the animation ended events and wipe the animations // (we don't need to dispose them because that will happen // automatically in our base dispose) if (this._onShow && this._onShow.get_animation()) { this._onShow.get_animation().remove_ended(this._onShowEndedHandler); } this._onShow = null; if (this._onHide && this._onHide.get_animation()) { this._onHide.get_animation().remove_ended(this._onHideEndedHandler); } this._onHide = null; Sys.Extended.UI.PopupBehavior.callBaseMethod(this, 'dispose'); }, show: function() { /// <summary> /// Show the popup /// </summary> // Ignore requests to hide multiple times if (this._visible) { return; } var eventArgs = new Sys.CancelEventArgs(); this.raiseShowing(eventArgs); if (eventArgs.get_cancel()) { return; } // Either show the popup or play an animation that does // (note: even if we're animating, we still show and position // the popup before hiding it again and playing the animation // which makes the animation much simpler) this._visible = true; var element = this.get_element(); $common.setVisible(element, true); this.setupPopup(); if (this._onShow) { $common.setVisible(element, false); this.onShow(); } else { this.raiseShown(Sys.EventArgs.Empty); } }, hide: function() { /// <summary> /// Hide the popup /// </summary> // Ignore requests to hide multiple times if (!this._visible) { return; } var eventArgs = new Sys.CancelEventArgs(); this.raiseHiding(eventArgs); if (eventArgs.get_cancel()) { return; } // Either hide the popup or play an animation that does this._visible = false; if (this._onHide) { this.onHide(); } else { this._hidePopup(); this._hideCleanup(); } }, getBounds: function() { /// <summary> /// Get the expected bounds of the popup relative to its parent /// </summary> /// <returns type="Sys.UI.Bounds" mayBeNull="false"> /// Bounds of the popup relative to its parent /// </returns> /// <remarks> /// The actual final position can only be calculated after it is /// initially set and we can verify it doesn't bleed off the edge /// of the screen. /// </remarks> var element = this.get_element(); // offsetParent (doc element if absolutely positioned or no offsetparent available) var offsetParent = element.offsetParent || document.documentElement; // diff = difference in position between element's offsetParent and the element we will attach popup to. // this is basically so we can position the popup in the right spot even though it may not be absolutely positioned var diff; var parentBounds; if (this.get_parentElement()) { // we will be positioning the element against the assigned parent parentBounds = $common.getBounds(this.get_parentElement()); var offsetParentLocation = $common.getLocation(offsetParent); diff = { x: parentBounds.x - offsetParentLocation.x, y: parentBounds.y - offsetParentLocation.y }; } else { // we will be positioning the element against the offset parent by default, since no parent element given parentBounds = $common.getBounds(offsetParent); diff = { x: 0, y: 0 }; } // width/height of the element, needed for calculations that involve width like centering var width = element.offsetWidth - (element.clientLeft ? element.clientLeft * 2 : 0); var height = element.offsetHeight - (element.clientTop ? element.clientTop * 2 : 0); // Setting the width causes the element to grow by border+passing every // time. But not setting it causes strange behavior in safari. Just set it once. if (this._firstpopup) { element.style.width = width + "px"; this._firstpopup = false; } var position, pos; switch (this._positioningMode) { case Sys.Extended.UI.PositioningMode.Center: pos = { x: Math.round(parentBounds.width / 2 - width / 2), y: Math.round(parentBounds.height / 2 - height / 2), altX: Math.round(parentBounds.width / 2 - width / 2), altY: Math.round(parentBounds.height / 2 - height / 2) }; break; case Sys.Extended.UI.PositioningMode.BottomLeft: pos = { x: 0, y: parentBounds.height, altX: parentBounds.width - width, altY: 0 - height } break; case Sys.Extended.UI.PositioningMode.BottomRight: pos = { x: parentBounds.width - width, y: parentBounds.height, altX: 0, altY: 0 - height } break; case Sys.Extended.UI.PositioningMode.TopLeft: pos = { x: 0, y: -element.offsetHeight, altX: parentBounds.width - width, altY: parentBounds.height } break; case Sys.Extended.UI.PositioningMode.TopRight: pos = { x: parentBounds.width - width, y: -element.offsetHeight, altX: 0, altY: parentBounds.height } break; case Sys.Extended.UI.PositioningMode.Right: pos = { x: parentBounds.width, y: 0, altX: -element.offsetWidth, altY: parentBounds.height - height } break; case Sys.Extended.UI.PositioningMode.Left: pos = { x: -element.offsetWidth, y: 0, altX: parentBounds.width, altY: parentBounds.height - height } break; default: pos = { x: 0, y: 0, altX: 0, altY: 0 }; } pos.x += this._x + diff.x; pos.altX += this._x + diff.x; pos.y += this._y + diff.y; pos.altY += this._y + diff.y; position = this._verifyPosition(pos, width, height, parentBounds); return new Sys.UI.Bounds(position.x, position.y, width, height); }, _verifyPosition: function(pos, elementWidth, elementHeight, parentBounds) { /// <summary> /// Checks whether the popup is entirely visible and attempts to change its position to make it entirely visihle. /// </summary> var newX = 0, newY = 0; var windowBounds = this._getWindowBounds(); // Check horizontal positioning if (!((pos.x + elementWidth > windowBounds.x + windowBounds.width) || (pos.x < windowBounds.x))) { newX = pos.x; } else { newX = pos.altX; if (pos.altX < windowBounds.x) { if (pos.x > pos.altX) { newX = pos.x; } } else if (windowBounds.width + windowBounds.x - pos.altX < elementWidth) { var xDiff = pos.x > pos.altX ? Math.abs(windowBounds.x - pos.x) : (windowBounds.x - pos.x); if (xDiff < elementWidth - windowBounds.width - windowBounds.x + pos.altX) { newX = pos.x; } } } // Check vertical positioning if (!((pos.y + elementHeight > windowBounds.y + windowBounds.height) || (pos.y < windowBounds.y))) { newY = pos.y; } else { newY = pos.altY; if (pos.altY < windowBounds.y) { if (windowBounds.y - pos.altY > elementHeight - windowBounds.height - windowBounds.y + pos.y) { newY = pos.y; } } else if (windowBounds.height + windowBounds.y - pos.altY < elementHeight) { if (windowBounds.y - pos.y < elementHeight - windowBounds.height - windowBounds.y + pos.altY) { newY = pos.y; } } } return { x: newX, y: newY }; }, _getWindowBounds: function() { var bounds = { x: this._getWindowScrollLeft(), y: this._getWindowScrollTop(), width: this._getWindowWidth(), height: this._getWindowHeight() }; return bounds; }, _getWindowHeight: function() { var windowHeight = 0; if (document.documentElement && document.documentElement.clientHeight) { windowHeight = document.documentElement.clientHeight; } else if (document.body && document.body.clientHeight) { windowHeight = document.body.clientHeight; } return windowHeight; }, _getWindowWidth: function() { var windowWidth = 0; if (document.documentElement && document.documentElement.clientWidth) { windowWidth = document.documentElement.clientWidth; } else if (document.body && document.body.clientWidth) { windowWidth = document.body.clientWidth; } return windowWidth; }, _getWindowScrollTop: function() { var scrollTop = 0; if (typeof (window.pageYOffset) == 'number') { scrollTop = window.pageYOffset; } if (document.body && document.body.scrollTop) { scrollTop = document.body.scrollTop; } else if (document.documentElement && document.documentElement.scrollTop) { scrollTop = document.documentElement.scrollTop; } return scrollTop; }, _getWindowScrollLeft: function() { var scrollLeft = 0; if (typeof (window.pageXOffset) == 'number') { scrollLeft = window.pageXOffset; } else if (document.body && document.body.scrollLeft) { scrollLeft = document.body.scrollLeft; } else if (document.documentElement && document.documentElement.scrollLeft) { scrollLeft = document.documentElement.scrollLeft; } return scrollLeft; }, adjustPopupPosition: function(bounds) { /// <summary> /// Adjust the position of the popup after it's originally bet set /// to make sure that it's visible on the page. /// </summary> /// <param name="bounds" type="Sys.UI.Bounds" mayBeNull="true" optional="true"> /// Original bounds of the parent element /// </param> var element = this.get_element(); if (!bounds) { bounds = this.getBounds(); } // Get the new bounds now that we've shown the popup var newPosition = $common.getBounds(element); var updateNeeded = false; if (newPosition.x < 0) { bounds.x -= newPosition.x; updateNeeded = true; } if (newPosition.y < 0) { bounds.y -= newPosition.y; updateNeeded = true; } // If the popup was off the screen, reposition it if (updateNeeded) { $common.setLocation(element, bounds); } }, addBackgroundIFrame: function() { /// <summary> /// Add an empty IFRAME behind the popup (for IE6 only) so that SELECT, etc., won't /// show through the popup. /// </summary> // Get the child frame var element = this.get_element(); if ((Sys.Browser.agent === Sys.Browser.InternetExplorer) && (Sys.Browser.version < 7)) { var childFrame = element._hideWindowedElementsIFrame; // Create the child frame if it wasn't found if (!childFrame) { childFrame = document.createElement("iframe"); childFrame.src = "javascript:'<html></html>';"; childFrame.style.position = "absolute"; childFrame.style.display = "none"; childFrame.scrolling = "no"; childFrame.frameBorder = "0"; childFrame.tabIndex = "-1"; childFrame.style.filter = "progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)"; element.parentNode.insertBefore(childFrame, element); element._hideWindowedElementsIFrame = childFrame; this._moveHandler = Function.createDelegate(this, this._onMove); Sys.UI.DomEvent.addHandler(element, "move", this._moveHandler); } // Position the frame exactly behind the element $common.setBounds(childFrame, $common.getBounds(element)); childFrame.style.left = element.style.left; childFrame.style.top = element.style.top; childFrame.style.display = element.style.display; if (element.currentStyle && element.currentStyle.zIndex) { childFrame.style.zIndex = element.currentStyle.zIndex; } else if (element.style.zIndex) { childFrame.style.zIndex = element.style.zIndex; } } }, setupPopup: function() { /// <summary> /// Position the popup relative to its parent /// </summary> var element = this.get_element(); var bounds = this.getBounds(); $common.setLocation(element, bounds); // Tweak the position, set the zIndex, and add the background iframe in IE6 this.adjustPopupPosition(bounds); element.style.zIndex = 1000; this.addBackgroundIFrame(); }, _hidePopup: function() { /// <summary> /// Internal hide implementation /// </summary> var element = this.get_element(); $common.setVisible(element, false); if (element.originalWidth) { element.style.width = element.originalWidth + "px"; element.originalWidth = null; } }, _hideCleanup: function() { /// <summary> /// Perform cleanup after hiding the element /// </summary> var element = this.get_element(); // Remove the tracking handler if (this._moveHandler) { Sys.UI.DomEvent.removeHandler(element, "move", this._moveHandler); this._moveHandler = null; } // Hide the child frame if (Sys.Browser.agent === Sys.Browser.InternetExplorer) { var childFrame = element._hideWindowedElementsIFrame; if (childFrame) { childFrame.style.display = "none"; } } this.raiseHidden(Sys.EventArgs.Empty); }, _onMove: function() { /// <summary> /// Track the popup's movements so the hidden IFrame (IE6 only) can /// be moved along with it /// </summary> var element = this.get_element(); if (element._hideWindowedElementsIFrame) { element.parentNode.insertBefore(element._hideWindowedElementsIFrame, element); element._hideWindowedElementsIFrame.style.top = element.style.top; element._hideWindowedElementsIFrame.style.left = element.style.left; } }, get_onShow: function() { /// <value type="String" mayBeNull="true"> /// Generic OnShow Animation's JSON definition /// </value> return this._onShow ? this._onShow.get_json() : null; }, set_onShow: function(value) { if (!this._onShow) { this._onShow = new Sys.Extended.UI.Animation.GenericAnimationBehavior(this.get_element()); this._onShow.initialize(); } this._onShow.set_json(value); var animation = this._onShow.get_animation(); if (animation) { animation.add_ended(this._onShowEndedHandler); } this.raisePropertyChanged('onShow'); }, get_onShowBehavior: function() { /// <value type="Sys.Extended.UI.Animation.GenericAnimationBehavior"> /// Generic OnShow Animation's behavior /// </value> return this._onShow; }, onShow: function() { /// <summary> /// Play the OnShow animation /// </summary> /// <returns /> if (this._onShow) { if (this._onHide) { this._onHide.quit(); } this._onShow.play(); } }, _onShowEnded: function() { /// <summary> /// Handler for the OnShow Animation's Ended event /// </summary> // Make sure the popup is where it belongs this.adjustPopupPosition(); this.addBackgroundIFrame(); this.raiseShown(Sys.EventArgs.Empty); }, get_onHide: function() { /// <value type="String" mayBeNull="true"> /// Generic OnHide Animation's JSON definition /// </value> return this._onHide ? this._onHide.get_json() : null; }, set_onHide: function(value) { if (!this._onHide) { this._onHide = new Sys.Extended.UI.Animation.GenericAnimationBehavior(this.get_element()); this._onHide.initialize(); } this._onHide.set_json(value); var animation = this._onHide.get_animation(); if (animation) { animation.add_ended(this._onHideEndedHandler); } this.raisePropertyChanged('onHide'); }, get_onHideBehavior: function() { /// <value type="Sys.Extended.UI.Animation.GenericAnimationBehavior"> /// Generic OnHide Animation's behavior /// </value> return this._onHide; }, onHide: function() { /// <summary> /// Play the OnHide animation /// </summary> /// <returns /> if (this._onHide) { if (this._onShow) { this._onShow.quit(); } this._onHide.play(); } }, _onHideEnded: function() { /// <summary> /// Handler for the OnHide Animation's Ended event /// </summary> this._hideCleanup(); }, get_parentElement: function() { /// <value type="Sys.UI.DomElement" domElement="true"> /// Parent dom element. /// </value> if (!this._parentElement && this._parentElementID) { this.set_parentElement($get(this._parentElementID)); //Sys.Debug.assert(this._parentElement != null, String.format(Sys.Extended.UI.Resources.PopupExtender_NoParentElement, this._parentElementID)); } return this._parentElement; }, set_parentElement: function(element) { this._parentElement = element; this.raisePropertyChanged('parentElement'); }, get_parentElementID: function() { /// <value type="String"> /// Parent dom element. /// </value> if (this._parentElement) { return this._parentElement.id } return this._parentElementID; }, set_parentElementID: function(elementID) { this._parentElementID = elementID; if (this.get_isInitialized()) { this.set_parentElement($get(elementID)); } }, get_positioningMode: function() { /// <value type="Sys.Extended.UI.PositioningMode"> /// Positioning mode. /// </value> return this._positioningMode; }, set_positioningMode: function(mode) { this._positioningMode = mode; this.raisePropertyChanged('positioningMode'); }, get_x: function() { /// <value type="Number"> /// X coordinate. /// </value> return this._x; }, set_x: function(value) { if (value != this._x) { this._x = value; // Reposition the popup if it's already showing if (this._visible) { this.setupPopup(); } this.raisePropertyChanged('x'); } }, get_y: function() { /// <value type="Number"> /// Y coordinate. /// </value> return this._y; }, set_y: function(value) { if (value != this._y) { this._y = value; // Reposition the popup if it's already showing if (this._visible) { this.setupPopup(); } this.raisePropertyChanged('y'); } }, get_visible: function() { /// <value type="Boolean" mayBeNull="false"> /// Whether or not the popup is currently visible /// </value> return this._visible; }, add_showing: function(handler) { /// <summary> /// Add an event handler for the showing event /// </summary> /// <param name="handler" type="Function" mayBeNull="false"> /// Event handler /// </param> /// <returns /> this.get_events().addHandler('showing', handler); }, remove_showing: function(handler) { /// <summary> /// Remove an event handler from the showing event /// </summary> /// <param name="handler" type="Function" mayBeNull="false"> /// Event handler /// </param> /// <returns /> this.get_events().removeHandler('showing', handler); }, raiseShowing: function(eventArgs) { /// <summary> /// Raise the showing event /// </summary> /// <param name="eventArgs" type="Sys.CancelEventArgs" mayBeNull="false"> /// Event arguments for the showing event /// </param> /// <returns /> var handler = this.get_events().getHandler('showing'); if (handler) { handler(this, eventArgs); } }, add_shown: function(handler) { /// <summary> /// Add an event handler for the shown event /// </summary> /// <param name="handler" type="Function" mayBeNull="false"> /// Event handler /// </param> /// <returns /> this.get_events().addHandler('shown', handler); }, remove_shown: function(handler) { /// <summary> /// Remove an event handler from the shown event /// </summary> /// <param name="handler" type="Function" mayBeNull="false"> /// Event handler /// </param> /// <returns /> this.get_events().removeHandler('shown', handler); }, raiseShown: function(eventArgs) { /// <summary> /// Raise the shown event /// </summary> /// <param name="eventArgs" type="Sys.EventArgs" mayBeNull="false"> /// Event arguments for the shown event /// </param> /// <returns /> var handler = this.get_events().getHandler('shown'); if (handler) { handler(this, eventArgs); } }, add_hiding: function(handler) { /// <summary> /// Add an event handler for the hiding event /// </summary> /// <param name="handler" type="Function" mayBeNull="false"> /// Event handler /// </param> /// <returns /> this.get_events().addHandler('hiding', handler); }, remove_hiding: function(handler) { /// <summary> /// Remove an event handler from the hiding event /// </summary> /// <param name="handler" type="Function" mayBeNull="false"> /// Event handler /// </param> /// <returns /> this.get_events().removeHandler('hiding', handler); }, raiseHiding: function(eventArgs) { /// <summary> /// Raise the hiding event /// </summary> /// <param name="eventArgs" type="Sys.CancelEventArgs" mayBeNull="false"> /// Event arguments for the hiding event /// </param> /// <returns /> var handler = this.get_events().getHandler('hiding'); if (handler) { handler(this, eventArgs); } }, add_hidden: function(handler) { /// <summary> /// Add an event handler for the hidden event /// </summary> /// <param name="handler" type="Function" mayBeNull="false"> /// Event handler /// </param> /// <returns /> this.get_events().addHandler('hidden', handler); }, remove_hidden: function(handler) { /// <summary> /// Remove an event handler from the hidden event /// </summary> /// <param name="handler" type="Function" mayBeNull="false"> /// Event handler /// </param> /// <returns /> this.get_events().removeHandler('hidden', handler); }, raiseHidden: function(eventArgs) { /// <summary> /// Raise the hidden event /// </summary> /// <param name="eventArgs" type="Sys.EventArgs" mayBeNull="false"> /// Event arguments for the hidden event /// </param> /// <returns /> var handler = this.get_events().getHandler('hidden'); if (handler) { handler(this, eventArgs); } } } Sys.Extended.UI.PopupBehavior.registerClass('Sys.Extended.UI.PopupBehavior', Sys.Extended.UI.BehaviorBase); Sys.registerComponent(Sys.Extended.UI.PopupBehavior, { name: "popup" }); //Sys.Extended.UI.PopupBehavior.descriptor = { // properties: [ {name: 'parentElement', attributes: [ Sys.Attributes.Element, true ] }, // {name: 'positioningMode', type: Sys.Extended.UI.PositioningMode}, // {name: 'x', type: Number}, // {name: 'y', type: Number} ], // events: [ {name: 'show'}, // {name: 'hide'} ] //} Sys.Extended.UI.PositioningMode = function() { /// <summary> /// Positioning mode describing how the popup should be positioned /// relative to its specified parent /// </summary> /// <field name="Absolute" type="Number" integer="true" /> /// <field name="Center" type="Number" integer="true" /> /// <field name="BottomLeft" type="Number" integer="true" /> /// <field name="BottomRight" type="Number" integer="true" /> /// <field name="TopLeft" type="Number" integer="true" /> /// <field name="TopRight" type="Number" integer="true" /> /// <field name="Right" type="Number" integer="true" /> /// <field name="Left" type="Number" integer="true" /> throw Error.invalidOperation(); } Sys.Extended.UI.PositioningMode.prototype = { Absolute: 0, Center: 1, BottomLeft: 2, BottomRight: 3, TopLeft: 4, TopRight: 5, Right: 6, Left: 7 } Sys.Extended.UI.PositioningMode.registerEnum('Sys.Extended.UI.PositioningMode'); } // execute if (window.Sys && Sys.loader) { Sys.loader.registerScript(scriptName, ["ExtendedAnimations", "ExtendedAnimationBehavior"], execute); } else { execute(); } })();
lgpl-3.0
simeshev/parabuild-ci
3rdparty/httpunit154/doc/tutorial/pool_editor_static.html
2014
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head><title>UniSports Betting Pool - Definition</title></head> <body> <table width='90%' style='background-color=yellow; border-color: black; border-width: 2; border-style: solid'> <tr><td colspan='2'><b>Cannot open pool for betting:</b></td></tr> <tr><td width="5">&nbsp;</td><td>No tiebreaker was specified</td></tr> </table> Enter teams for up to 10 games, selecting one as a tie-breaker. <form method="POST"> <table> <tr><th>Home Team</th><th>Away Team</th><th>Tiebreaker?</th></tr> <tr><td><input name="home0"></td><td><input name="away0"></td><td><input type="radio" name="tiebreaker" value="0"/></td></tr> <tr><td><input name="home1"></td><td><input name="away1"></td><td><input type="radio" name="tiebreaker" value="1"/></td></tr> <tr><td><input name="home2"></td><td><input name="away2"></td><td><input type="radio" name="tiebreaker" value="2"/></td></tr> <tr><td bgcolor="red"><input name="home3"></td><td><input name="away3"></td><td><input type="radio" name="tiebreaker" value="3"/></td></tr> <tr><td><input name="home4"></td><td><input name="away4"></td><td><input type="radio" name="tiebreaker" value="4"/></td></tr> <tr><td><input name="home5"></td><td><input name="away5"></td><td><input type="radio" name="tiebreaker" value="5"/></td></tr> <tr><td><input name="home6"></td><td><input name="away6"></td><td><input type="radio" name="tiebreaker" value="6"/></td></tr> <tr><td><input name="home7"></td><td><input name="away7"></td><td><input type="radio" name="tiebreaker" value="7"/></td></tr> <tr><td><input name="home8"></td><td><input name="away8"></td><td><input type="radio" name="tiebreaker" value="8"/></td></tr> <tr><td><input name="home9"></td><td><input name="away9"></td><td><input type="radio" name="tiebreaker" value="9"/></td></tr> </table> <input type="submit" name="save" value="Save"/> <input type="submit" name="save" value="Open Pool"/> </form> </body> </html>
lgpl-3.0
ruijieguo/firtex2
src/search/IndexFeature.cpp
1305
#include "firtex/search/IndexFeature.h" FX_NS_USE(index); FX_NS_DEF(search); SETUP_STREAM_LOGGER(search, IndexFeature); IndexFeature::IndexFeature() : m_nTotalTermCount(0) , m_nTotalDocCount(0) { } IndexFeature::~IndexFeature() { } void IndexFeature::init(const IndexReaderPtr& pIndexReader) { m_nTotalDocCount = (uint64_t)pIndexReader->getDocCount(); FX_STREAM_LOG(TRACE) << "Total doc count: " << m_nTotalDocCount << FIRTEX_ENDL; IndexMeta indexMeta = pIndexReader->getIndexMeta(); m_nTotalTermCount = 0; for (size_t i = 0; i < indexMeta.size(); ++i) { const FieldMeta& fieldMeta = indexMeta[i]; m_fieldsAvgLength.insert(make_pair(fieldMeta.fieldName, (uint32_t)(fieldMeta.totalTermCount / m_nTotalDocCount))); FX_STREAM_LOG(TRACE) << "Average field length: field: " << fieldMeta.fieldName << ", length: " << fieldMeta.totalTermCount/m_nTotalDocCount << FIRTEX_ENDL; m_nTotalTermCount += fieldMeta.totalTermCount; } FX_STREAM_LOG(TRACE) << "Total term count: " << m_nTotalTermCount << FIRTEX_ENDL; m_pIndexReader = pIndexReader; } FX_NS_END
lgpl-3.0
anlambert/tulip
thirdparty/libvpsc/PairingHeap.h
3195
/** * \brief Pairing heap datastructure implementation * * Based on example code in "Data structures and Algorithm Analysis in C++" * by Mark Allen Weiss, used and released under the LGPL by permission * of the author. * * No promises about correctness. Use at your own risk! * * Authors: * Mark Allen Weiss * Tim Dwyer <[email protected]> * * Copyright (C) 2005 Authors * * Released under GNU LGPL. Read the file 'COPYING' for more information. */ #ifndef PAIRING_HEAP_H_ #define PAIRING_HEAP_H_ #include <cstdlib> #include <fstream> // Pairing heap class // // CONSTRUCTION: with no parameters // // ******************PUBLIC OPERATIONS********************* // PairNode & insert( x ) --> Insert x // deleteMin( minItem ) --> Remove (and optionally return) smallest item // T findMin( ) --> Return smallest item // bool isEmpty( ) --> Return true if empty; else false // bool isFull( ) --> Return true if empty; else false // void makeEmpty( ) --> Remove all items // void decreaseKey( PairNode p, newVal ) // --> Decrease value in node p // ******************ERRORS******************************** // Throws Underflow as warranted // Node and forward declaration because g++ does // not understand nested classes. template <class T> class PairingHeap; template <class T> std::ostream &operator<<(std::ostream &os, const PairingHeap<T> &b); template <class T> class PairNode { friend std::ostream &operator<<<T>(std::ostream &os, const PairingHeap<T> &b); T element; PairNode *leftChild; PairNode *nextSibling; PairNode *prev; PairNode(const T &theElement) : element(theElement), leftChild(nullptr), nextSibling(nullptr), prev(nullptr) {} friend class PairingHeap<T>; }; template <class T> class Comparator { public: virtual bool isLessThan(T const &lhs, T const &rhs) const = 0; }; template <class T> class PairingHeap { friend std::ostream &operator<<<T>(std::ostream &os, const PairingHeap<T> &b); public: PairingHeap(bool (*lessThan)(T const &lhs, T const &rhs)); PairingHeap(const PairingHeap &rhs); ~PairingHeap(); bool isEmpty() const; bool isFull() const; int size(); PairNode<T> *insert(const T &x); const T &findMin() const; void deleteMin(); const T extractMin() { T v = findMin(); deleteMin(); return v; } void makeEmpty(); void decreaseKey(PairNode<T> *p, const T &newVal); void merge(PairingHeap<T> *rhs) { PairNode<T> *broot = rhs->getRoot(); if (root == nullptr) { if (broot != nullptr) { root = broot; } } else { compareAndLink(root, broot); } counter += rhs->size(); } const PairingHeap &operator=(const PairingHeap &rhs); protected: PairNode<T> *getRoot() { PairNode<T> *r = root; root = nullptr; return r; } private: PairNode<T> *root; bool (*lessThan)(T const &lhs, T const &rhs); int counter; void reclaimMemory(PairNode<T> *t) const; void compareAndLink(PairNode<T> *&first, PairNode<T> *second) const; PairNode<T> *combineSiblings(PairNode<T> *firstSibling) const; PairNode<T> *clone(PairNode<T> *t) const; }; #include "PairingHeap.cpp" #endif
lgpl-3.0
dresden-ocl/dresdenocl
plugins/org.dresdenocl.modelinstancetype.xml/src/org/dresdenocl/modelinstancetype/xml/internal/modelinstance/XmlModelInstanceFactory.java
19025
/* Copyright (C) 2010 by Claas Wilke ([email protected]) This file is part of the XML Model Instance Plug-in of Dresden OCL2 for Eclipse. Dresden OCL2 for Eclipse is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Dresden OCL2 for Eclipse is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Dresden OCL2 for Eclipse. If not, see <http://www.gnu.org/licenses/>. */ package org.dresdenocl.modelinstancetype.xml.internal.modelinstance; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.WeakHashMap; import org.apache.log4j.Logger; import org.eclipse.osgi.util.NLS; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.dresdenocl.essentialocl.types.CollectionType; import org.dresdenocl.model.IModel; import org.dresdenocl.model.ModelAccessException; import org.dresdenocl.modelinstancetype.exception.TypeNotFoundInModelException; import org.dresdenocl.modelinstancetype.types.IModelInstanceBoolean; import org.dresdenocl.modelinstancetype.types.IModelInstanceElement; import org.dresdenocl.modelinstancetype.types.IModelInstanceEnumerationLiteral; import org.dresdenocl.modelinstancetype.types.IModelInstanceFactory; import org.dresdenocl.modelinstancetype.types.IModelInstanceInteger; import org.dresdenocl.modelinstancetype.types.IModelInstanceObject; import org.dresdenocl.modelinstancetype.types.IModelInstanceReal; import org.dresdenocl.modelinstancetype.types.IModelInstanceString; import org.dresdenocl.modelinstancetype.types.base.BasisJavaModelInstanceFactory; import org.dresdenocl.modelinstancetype.xml.XmlModelInstanceTypePlugin; import org.dresdenocl.modelinstancetype.xml.internal.msg.XmlModelInstanceTypeMessages; import org.dresdenocl.pivotmodel.Enumeration; import org.dresdenocl.pivotmodel.EnumerationLiteral; import org.dresdenocl.pivotmodel.PrimitiveType; import org.dresdenocl.pivotmodel.Property; import org.dresdenocl.pivotmodel.Type; /** * <p> * {@link IModelInstanceFactory} implementation for {@link XmlModelInstance}s. * </p> * * @author Claas Wilke */ public class XmlModelInstanceFactory extends BasisJavaModelInstanceFactory { /** The {@link Logger} for this class. */ private static final Logger LOGGER = XmlModelInstanceTypePlugin .getLogger(XmlModelInstanceFactory.class); /** * The {@link IModel} for whose {@link Type}s {@link IModelInstanceElement}s * shall be created. */ private IModel model; /** * The cached {@link IModelInstanceObject}s of this * {@link XmlModelInstanceFactory} identified by their adapted {@link Node}. */ private Map<Node, IModelInstanceObject> cacheModelInstanceObjects = new WeakHashMap<Node, IModelInstanceObject>(); /** * <p> * Creates a new {@link XmlModelInstanceFactory}. * </p> * * @param model * The {@link IModel} for whose {@link Type}s * {@link IModelInstanceElement}s shall be created. */ public XmlModelInstanceFactory(IModel model) { if (model == null) { throw new IllegalArgumentException( "Parameter 'model' must not be null."); } // no else. this.model = model; } /* * (non-Javadoc) * * @see org.dresdenocl.modelbus.modelinstance.types.IModelInstanceFactory * #createModelInstanceElement(java.lang.Object) */ @Override public IModelInstanceElement createModelInstanceElement(Object adapted) throws TypeNotFoundInModelException { /* Probably debug the entry of this method. */ if (LOGGER.isDebugEnabled()) { String msg; msg = "createModelInstanceElement("; //$NON-NLS-1$ msg += "adapted = " + adapted; //$NON-NLS-1$ msg += ")"; //$NON-NLS-1$ LOGGER.debug(msg); } // no else. IModelInstanceElement result; if (adapted instanceof Node) { Node node; node = (Node) adapted; result = this.createModelInstanceElement(node); } else { throw new IllegalArgumentException( NLS.bind( XmlModelInstanceTypeMessages.XmlModelInstanceFactory_UnknownClassOfAdaptee, adapted.getClass().getCanonicalName())); } /* Probably debug the exit of this method. */ if (LOGGER.isDebugEnabled()) { String msg; msg = "createModelInstanceElement(Object) - exit"; //$NON-NLS-1$ LOGGER.debug(msg); } // no else. return result; } /* * (non-Javadoc) * * @see org.dresdenocl.modelbus.modelinstance.types.IModelInstanceFactory * #createModelInstanceElement(java.lang.Object, * org.dresdenocl.pivotmodel.Type) */ @SuppressWarnings("unchecked") @Override public IModelInstanceElement createModelInstanceElement(Object adapted, Type type) { /* Probably debug the entry of this method. */ if (LOGGER.isDebugEnabled()) { String msg; msg = "createModelInstanceElement("; //$NON-NLS-1$ msg += "adapted = " + adapted; //$NON-NLS-1$ msg += "type = " + type; //$NON-NLS-1$ msg += ")"; //$NON-NLS-1$ LOGGER.debug(msg); } // no else. IModelInstanceElement result; if (adapted == null || adapted instanceof Node) { Node node; node = null; if (adapted != null) { node = (Node) adapted; } // no else. /* Probably adapt a literal. */ if (type instanceof Enumeration) { result = this.createModelInstanceEnumerationLiteral(node, (Enumeration) type); } /* Else probably adapt a primitive type. */ else if (type instanceof PrimitiveType) { switch (((PrimitiveType) type).getKind()) { case BOOLEAN: result = this.createModelInstanceBoolean(node, type); break; case INTEGER: result = this.createModelInstanceInteger(node, type); break; case REAL: result = this.createModelInstanceReal(node, type); break; case STRING: result = this.createModelInstanceString(node, type); break; default: throw new IllegalArgumentException( NLS.bind( XmlModelInstanceTypeMessages.XmlModelInstanceFactory_UnknownClassOfAdaptee, adapted.getClass().getCanonicalName())); } // end select. } else { /* Probably use a cached result. */ if (this.cacheModelInstanceObjects.containsKey(node)) { result = this.cacheModelInstanceObjects.get(node); } else { result = this.createModelInstanceObject(node, type); /* Add the result to the cache. */ this.cacheModelInstanceObjects.put(node, (IModelInstanceObject) result); } // end else. } } else if (type instanceof CollectionType && adapted instanceof Collection<?>) { result = BasisJavaModelInstanceFactory .createModelInstanceCollection( (Collection<IModelInstanceElement>) adapted, (CollectionType) type); } else { throw new IllegalArgumentException( NLS.bind( XmlModelInstanceTypeMessages.XmlModelInstanceFactory_UnknownClassOfAdaptee, adapted.getClass().getCanonicalName())); } /* Probably debug the exit of this method. */ if (LOGGER.isDebugEnabled()) { String msg; msg = "createModelInstanceElement(Object, Set<Type>) - exit"; //$NON-NLS-1$ LOGGER.debug(msg); } // no else. return result; } /** * <p> * Creates an {@link IModelInstanceBoolean} for a given {@link Node} and a * given {@link Type}. * * @param node * The {@link Node} that shall be adapted. * @param type * The {@link Type} of the {@link IModelInstanceBoolean} in the * {@link IModel}. * @return The created {@link IModelInstanceBoolean}. */ private IModelInstanceBoolean createModelInstanceBoolean(Node node, Type type) { IModelInstanceBoolean result; /* * Use the java basis types here because the adaptation of a node would * not help. If you adapt a node, cast it to boolean and then to string, * you have to alter the nodes' value to get the right result such as * 'true', 'false' or null in all other cases! */ if (node == null || node.getTextContent() == null) { result = super.createModelInstanceBoolean(null); } else if (node.getTextContent().trim().equalsIgnoreCase("true")) { result = super.createModelInstanceBoolean(true); } else if (node.getTextContent().trim().equalsIgnoreCase("false")) { result = super.createModelInstanceBoolean(false); } else { result = super.createModelInstanceBoolean(null); } return result; } /** * <p> * Creates an {@link IModelInstanceElement} for a given {@link Node}. * * @param node * The {@link Node} that shall be adapted. * @return The created {@link IModelInstanceElement}. * @throws TypeNotFoundInModelException * Thrown, if now {@link Type} in the {@link IModel} can be * found that matches to the given {@link Node}. */ private IModelInstanceElement createModelInstanceElement(Node node) throws TypeNotFoundInModelException { IModelInstanceElement result; Type type; type = this.findTypeOfNode(node); result = (IModelInstanceElement) this.createModelInstanceElement(node, type); return result; } /** * <p> * Creates an {@link IModelInstanceEnumerationLiteral} for the given * {@link Node} and the given {@link Enumeration}. * </p> * * @param node * The {@link Node} for that an * {@link IModelInstanceEnumerationLiteral} shall be created. * @param enumeration * The {@link Enumeration} type for that the * {@link IModelInstanceEnumerationLiteral} shall be created. * @return The created {@link IModelInstanceEnumerationLiteral}. */ private IModelInstanceEnumerationLiteral createModelInstanceEnumerationLiteral( Node node, Enumeration enumeration) { IModelInstanceEnumerationLiteral result; if (node == null || node.getTextContent() == null) { result = super.createModelInstanceEnumerationLiteral(null); } else { EnumerationLiteral literal; literal = null; /* Try to find a literal that matches to the node's value. */ for (EnumerationLiteral aLiteral : enumeration.getOwnedLiteral()) { if (aLiteral.getName().equalsIgnoreCase( node.getTextContent().trim())) { literal = aLiteral; break; } // no else. } // end for. result = super.createModelInstanceEnumerationLiteral(literal); } return result; } /** * <p> * Creates an {@link IModelInstanceInteger} for a given {@link Node} and a * given {@link Type}. * * @param node * The {@link Node} that shall be adapted. * @param type * The {@link Type} of the {@link IModelInstanceInteger} in the * {@link IModel}. * @return The created {@link IModelInstanceInteger}. */ private IModelInstanceInteger createModelInstanceInteger(Node node, Type type) { IModelInstanceInteger result; /* * Use the java basis types here because the adaptation of a node would * not help. If you adapt a node, cast it to integer and then to string, * you have to alter the nodes' value to get the right result such as * '1' except of '1.23', or null in many cases! */ if (node == null || node.getTextContent() == null) { result = super.createModelInstanceInteger(null); } else { Long longValue; try { longValue = new Double( Double.parseDouble(node.getTextContent())).longValue(); } catch (NumberFormatException e) { longValue = null; } result = super.createModelInstanceInteger(longValue); } return result; } /** * <p> * Creates an {@link IModelInstanceReal} for a given {@link Node} and a * given {@link Type}. * * @param node * The {@link Node} that shall be adapted. * @param type * The {@link Type} of the {@link IModelInstanceReal} in the * {@link IModel}. * @return The created {@link IModelInstanceReal}. */ private IModelInstanceReal createModelInstanceReal(Node node, Type type) { IModelInstanceReal result; /* * Use the java basis types here because the adaptation of a node would * not help. If you adapt a node, cast it to real and then to string, * you have to alter the nodes' value to get the right result such as * '1' except of '1.0', or null in many cases! */ if (node == null || node.getTextContent() == null) { result = super.createModelInstanceReal(null); } else { Double doubleValue; try { doubleValue = new Double(Double.parseDouble(node .getTextContent())); } catch (NumberFormatException e) { doubleValue = null; } result = super.createModelInstanceReal(doubleValue); } return result; } /** * <p> * Creates an {@link IModelInstanceString} for a given {@link Node} and a * given {@link Type}. * * @param node * The {@link Node} that shall be adapted. * @param type * The {@link Type} of the {@link IModelInstanceString} in the * {@link IModel}. * @return The created {@link IModelInstanceString}. */ private IModelInstanceString createModelInstanceString(Node node, Type type) { IModelInstanceString result; /* * Use the java basis types here because the adaptation of a node would * not help. If you adapt a node, cast it to integer and then to string, * you have to alter the nodes' value to get the right result such as * 'truefalse' except of null! */ if (node == null || node.getTextContent() == null) { result = super.createModelInstanceString(null); } else { result = super.createModelInstanceString(node.getTextContent()); } return result; } /** * <p> * Creates an {@link XmlModelInstanceObject} for a given {@link Node} and a * given {@link Type}. * * @param node * The {@link Node} that shall be adapted. * @param type * The {@link Type} of the {@link XmlModelInstanceObject} in the * {@link IModel}. * @return The created {@link XmlModelInstanceObject}. */ private XmlModelInstanceObject createModelInstanceObject(Node node, Type type) { XmlModelInstanceObject result; result = new XmlModelInstanceObject(node, type, type, this); return result; } private Type findTypeOfNode(Node node) throws TypeNotFoundInModelException { Type result; result = null; /* Collect all parent nodes. */ List<Node> parents; parents = new ArrayList<Node>(); Node aNode; aNode = node; while (aNode != null) { if (aNode == aNode.getParentNode() || aNode instanceof Document) { break; } else { parents.add(aNode); aNode = aNode.getParentNode(); } } // end while. if (parents.size() != 0) { /* Try to find the type of the root node. */ Type rootType; rootType = this .findTypeOfRootNode(parents.remove(parents.size() - 1)); if (rootType != null) { result = rootType; /* Take the next node, try to find its property and its type. */ while (parents.size() > 0) { List<Property> properties; properties = result.allProperties(); aNode = parents.remove(parents.size() - 1); result = null; for (Property property : properties) { if (property.getName().equalsIgnoreCase( aNode.getNodeName().trim())) { if (property.getType() instanceof CollectionType) { result = ((CollectionType) property.getType()) .getElementType(); } else { result = property.getType(); } break; } // no else. } // end for. } } // no else (root type not found). } // no else (no parent node found). if (result == null) { throw new TypeNotFoundInModelException( NLS.bind( XmlModelInstanceTypeMessages.XmlModelInstanceFactory_UnknownTypeOfAdaptee, node)); } // no else. return result; } /** * <p> * A helper method that searches for the {@link Type} of a given * {@link Node} in the {@link IModel}. * </p> * * @param node * The {@link Node} for that a {@link Type} shall be found. * @return The found {@link Type}. */ private Type findTypeOfRootNode(Node node) throws TypeNotFoundInModelException { Type result; result = null; String nodeName; nodeName = node.getNodeName(); List<String> pathName; pathName = new ArrayList<String>(); pathName.add(nodeName); /* FIXME Claas: Probably handle the node's name space. */ try { result = this.model.findType(pathName); /* FIXME Lars: Try to handle the namespace */ if (result == null) { String typeName = pathName.get(pathName.size() - 1); while (typeName.contains(":")) { typeName = pathName.remove(pathName.size() - 1); typeName = typeName.substring(typeName.indexOf(":") + 1); pathName.add(typeName); result = this.model.findType(pathName); if (result != null) { break; } } } /* * FIXME Claas: This is a very hacky dependency to the XSD * meta-model and should be fixed in the Meta-model instead. */ /* * change the first character into an upper case character and try * again. */ if (result == null) { String typeName = pathName.remove(pathName.size() - 1); pathName.add(typeName.substring(0, 1).toUpperCase() + typeName.substring(1, typeName.length())); result = this.model.findType(pathName); } // no else. /* * FIXME Claas: This is a very hacky dependency to the XSD * meta-model and should be fixed in the Meta-model instead. */ /* Add a 'Type' to the node name and try again. */ if (result == null) { pathName.add(pathName.remove(pathName.size() - 1) + "Type"); result = this.model.findType(pathName); } // no else. } // end try. catch (ModelAccessException e) { throw new TypeNotFoundInModelException( NLS.bind( XmlModelInstanceTypeMessages.XmlModelInstanceFactory_UnknownTypeOfAdaptee, node), e); } // end catch. return result; } }
lgpl-3.0
ashic/netmq
src/NetMQ/OutgoingSocketExtensions.cs
38297
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using JetBrains.Annotations; namespace NetMQ { /// <summary> /// This static class serves to provide extension methods for IOutgoingSocket. /// </summary> public static class OutgoingSocketExtensions { /// <summary> /// Block until the message is can be sent. /// </summary> /// <remarks> /// The call blocks until the message can be sent and cannot be interrupted. /// Wether the message can be sent depends on the socket type. /// </remarks> /// <param name="socket">The socket to send the message on.</param> /// <param name="msg">An object with message's data to send.</param> /// <param name="more">Indicate if another frame is expected after this frame</param> public static void Send(this IOutgoingSocket socket, ref Msg msg, bool more) { var result = socket.TrySend(ref msg, SendReceiveConstants.InfiniteTimeout, more); Debug.Assert(result); } #region Sending Byte Array #region Blocking /// <summary> /// Transmit a byte-array of data over this socket, block until frame is sent. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="data">the byte-array of data to send</param> /// <param name="more">set this flag to true to signal that you will be immediately sending another frame (optional: default is false)</param> public static void SendFrame([NotNull] this IOutgoingSocket socket, [NotNull] byte[] data, bool more = false) { SendFrame(socket, data, data.Length, more); } /// <summary> /// Transmit a byte-array of data over this socket, block until frame is sent. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="data">the byte-array of data to send</param> /// <param name="length">the number of bytes to send from <paramref name="data"/>.</param> /// <param name="more">set this flag to true to signal that you will be immediately sending another frame (optional: default is false)</param> public static void SendFrame([NotNull] this IOutgoingSocket socket, [NotNull] byte[] data, int length, bool more = false) { var msg = new Msg(); msg.InitPool(length); Buffer.BlockCopy(data, 0, msg.Data, 0, data.Length); socket.Send(ref msg, more); msg.Close(); } /// <summary> /// Transmit a byte-array of data over this socket, block until frame is sent. /// Send more frame, another frame must be sent after this frame. Use to chain Send methods. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="data">the byte-array of data to send</param> [NotNull] public static IOutgoingSocket SendMoreFrame([NotNull] this IOutgoingSocket socket, [NotNull] byte[] data) { SendFrame(socket, data, true); return socket; } /// <summary> /// Transmit a byte-array of data over this socket, block until frame is sent. /// Send more frame, another frame must be sent after this frame. Use to chain Send methods. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="data">the byte-array of data to send</param> /// <param name="length">the number of bytes to send from <paramref name="data"/>.</param> [NotNull] public static IOutgoingSocket SendMoreFrame([NotNull] this IOutgoingSocket socket, [NotNull] byte[] data, int length) { SendFrame(socket, data, length, true); return socket; } #endregion #region Timeout /// <summary> /// Attempt to transmit a single frame on <paramref cref="socket"/>. /// If message cannot be sent within <paramref name="timeout"/>, return <c>false</c>. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="timeout">The maximum period of time to try to send a message.</param> /// <param name="data">the byte-array of data to send</param> /// <param name="length">the number of bytes to send from <paramref name="data"/>.</param> /// <param name="more">set this flag to true to signal that you will be immediately sending another frame (optional: default is false)</param> /// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns> public static bool TrySendFrame([NotNull] this IOutgoingSocket socket, TimeSpan timeout, [NotNull] byte[] data, int length, bool more = false) { var msg = new Msg(); msg.InitPool(length); Buffer.BlockCopy(data, 0, msg.Data, 0, data.Length); if (!socket.TrySend(ref msg, timeout, more)) { msg.Close(); return false; } msg.Close(); return true; } /// <summary> /// Attempt to transmit a single frame on <paramref cref="socket"/>. /// If message cannot be sent within <paramref name="timeout"/>, return <c>false</c>. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="timeout">The maximum period of time to try to send a message.</param> /// <param name="data">the byte-array of data to send</param> /// <param name="more">set this flag to true to signal that you will be immediately sending another frame (optional: default is false)</param> /// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns> public static bool TrySendFrame([NotNull] this IOutgoingSocket socket, TimeSpan timeout, [NotNull] byte[] data, bool more = false) { return TrySendFrame(socket, timeout, data, data.Length, more); } #endregion #region Immediate /// <summary> /// Attempt to transmit a single frame on <paramref cref="socket"/>. /// If message cannot be sent immediately, return <c>false</c>. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="data">the byte-array of data to send</param> /// <param name="more">set this flag to true to signal that you will be immediately sending another frame (optional: default is false)</param> /// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns> public static bool TrySendFrame([NotNull] this IOutgoingSocket socket, [NotNull] byte[] data, bool more = false) { return TrySendFrame(socket, TimeSpan.Zero, data, more); } /// <summary> /// Attempt to transmit a single frame on <paramref cref="socket"/>. /// If message cannot be sent immediately, return <c>false</c>. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="data">the byte-array of data to send</param> /// <param name="length">the number of bytes to send from <paramref name="data"/>.</param> /// <param name="more">set this flag to true to signal that you will be immediately sending another frame (optional: default is false)</param> /// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns> public static bool TrySendFrame([NotNull] this IOutgoingSocket socket, [NotNull] byte[] data, int length, bool more = false) { return TrySendFrame(socket, TimeSpan.Zero, data, length, more); } #endregion #region Obsolete /// <summary> /// Transmit a byte-array of data over this socket. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="data">the byte-array of data to send</param> /// <param name="length">the number of bytes to send from <paramref name="data"/>.</param> /// <param name="options">options to control how the data is sent</param> [Obsolete("Use SendFrame or TrySendFrame")] public static void Send([NotNull] this IOutgoingSocket socket, [NotNull] byte[] data, int length, SendReceiveOptions options) { var msg = new Msg(); msg.InitPool(length); Buffer.BlockCopy(data, 0, msg.Data, 0, length); socket.Send(ref msg, options); msg.Close(); } /// <summary> /// Transmit a byte-array of data over this socket. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="data">the byte-array of data to send</param> /// <param name="length">the number of bytes to send</param> /// <param name="dontWait">if true, return immediately without waiting for the send operation to complete (optional: default is false)</param> /// <param name="sendMore">set this flag to true to signal that you will be immediately sending another message (optional: default is false)</param> [Obsolete("Use SendFrame or TrySendFrame")] public static void Send([NotNull] this IOutgoingSocket socket, [NotNull] byte[] data, int length, bool dontWait = false, bool sendMore = false) { var options = SendReceiveOptions.None; if (dontWait) { options |= SendReceiveOptions.DontWait; } if (sendMore) { options |= SendReceiveOptions.SendMore; } socket.Send(data, length, options); } /// <summary> /// Transmit a byte-array of data over this socket. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="data">the byte-array of data to send</param> [Obsolete("Use SendFrame or TrySendFrame")] public static void Send([NotNull] this IOutgoingSocket socket, [NotNull] byte[] data) { socket.Send(data, data.Length); } /// <summary> /// Transmit a string-message of data over this socket, while indicating that more is to come /// (the SendMore flag is set to true). /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="data">the byte-array of data to send</param> /// <param name="dontWait">if true, return immediately without waiting for the send operation to complete (optional: default is false)</param> /// <returns>a reference to this IOutgoingSocket so that method-calls may be chained together</returns> [NotNull] [Obsolete("Use SendMoreFrame or TrySendFrame")] public static IOutgoingSocket SendMore([NotNull] this IOutgoingSocket socket, [NotNull] byte[] data, bool dontWait = false) { socket.Send(data, data.Length, dontWait, true); return socket; } /// <summary> /// Transmit a string-message of data over this socket, while indicating that more is to come /// (the SendMore flag is set to true). /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="data">the byte-array of data to send</param> /// <param name="length">the number of bytes to send</param> /// <param name="dontWait">if true, return immediately without waiting for the send operation to complete (optional: default is false)</param> /// <returns>a reference to this IOutgoingSocket so that method-calls may be chained together</returns> [NotNull] [Obsolete("Use SendMoreFrame or TrySendFrame")] public static IOutgoingSocket SendMore([NotNull] this IOutgoingSocket socket, [NotNull] byte[] data, int length, bool dontWait = false) { socket.Send(data, length, dontWait, true); return socket; } #endregion #endregion #region Sending a multipart message as byte arrays #region Blocking /// <summary> /// Send multiple frames on <paramref cref="socket"/>, blocking until all frames are sent. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="frames">frames to transmit</param> public static void SendMultipartBytes([NotNull] this IOutgoingSocket socket, params byte[][] frames) { SendMultipartBytes(socket, (IEnumerable<byte[]>)frames); } /// <summary> /// Send multiple frames on <paramref cref="socket"/>, blocking until all frames are sent. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="frames">frames to transmit</param> public static void SendMultipartBytes([NotNull] this IOutgoingSocket socket, IEnumerable<byte[]> frames) { var enumerator = frames.GetEnumerator(); try { // move to the first emlement, if false frames is empty if (!enumerator.MoveNext()) { throw new ArgumentException("frames is empty", "frames"); } var current = enumerator.Current; // we always one item back to make sure we send the last frame without the more flag while (enumerator.MoveNext()) { // this is a more frame socket.SendMoreFrame(current); current = enumerator.Current; } // sending the last frame socket.SendFrame(current); } finally { enumerator.Dispose(); } } #endregion #region Timeout /// <summary> /// Attempt to transmit a mulitple frames on <paramref cref="socket"/>. /// If frames cannot be sent within <paramref name="timeout"/>, return <c>false</c>. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="frames">frames to transmit</param> public static bool TrySendMultipartBytes([NotNull] this IOutgoingSocket socket, TimeSpan timeout, params byte[][] frames) { return TrySendMultipartBytes(socket, timeout, (IEnumerable<byte[]>)frames); } /// <summary> /// Attempt to transmit a mulitple frames on <paramref cref="socket"/>. /// If frames cannot be sent within <paramref name="timeout"/>, return <c>false</c>. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="timeout">The maximum period of time to try to send a message.</param> /// <param name="frames">frames to transmit</param> public static bool TrySendMultipartBytes([NotNull] this IOutgoingSocket socket, TimeSpan timeout, IEnumerable<byte[]> frames) { var enumerator = frames.GetEnumerator(); try { // move to the first emlement, if false frames is empty if (!enumerator.MoveNext()) { throw new ArgumentException("frames is empty", "frames"); } var current = enumerator.Current; // only the first frame need to be sent with a timeout if (!enumerator.MoveNext()) { return socket.TrySendFrame(timeout, current); } else { bool sentSuccessfully = socket.TrySendFrame(timeout, current, true); if (!sentSuccessfully) return false; } // fetching the second frame current = enumerator.Current; // we always one item back to make sure we send the last frame without the more flag while (enumerator.MoveNext()) { // this is a more frame socket.SendMoreFrame(current); current = enumerator.Current; } // sending the last frame socket.SendFrame(current); return true; } finally { enumerator.Dispose(); } } #endregion #region Immediate /// <summary> /// Attempt to transmit a mulitple frames on <paramref cref="socket"/>. /// If frames cannot be sent immediatly, return <c>false</c>. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="frames">frames to transmit</param> public static bool TrySendMultipartBytes([NotNull] this IOutgoingSocket socket, params byte[][] frames) { return TrySendMultipartBytes(socket, TimeSpan.Zero, (IEnumerable<byte[]>)frames); } /// <summary> /// Attempt to transmit a mulitple frames on <paramref cref="socket"/>. /// If frames cannot be sent immediatly, return <c>false</c>. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="frames">frames to transmit</param> public static bool TrySendMultipartBytes([NotNull] this IOutgoingSocket socket, IEnumerable<byte[]> frames) { return TrySendMultipartBytes(socket, TimeSpan.Zero, frames); } #endregion #endregion #region Sending Strings #region Blocking /// <summary> /// Transmit a string over this socket, block until frame is sent. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="message">the string to send</param> /// <param name="more">set this flag to true to signal that you will be immediately sending another frame (optional: default is false)</param> public static void SendFrame([NotNull] this IOutgoingSocket socket, [NotNull] string message, bool more = false) { var msg = new Msg(); // Count the number of bytes required to encode the string. // Note that non-ASCII strings may not have an equal number of characters // and bytes. The encoding must be queried for this answer. // With this number, request a buffer from the pool. msg.InitPool(SendReceiveConstants.DefaultEncoding.GetByteCount(message)); // Encode the string into the buffer SendReceiveConstants.DefaultEncoding.GetBytes(message, 0, message.Length, msg.Data, 0); socket.Send(ref msg, more); msg.Close(); } /// <summary> /// Transmit a string over this socket, block until frame is sent. /// Send more frame, another frame must be sent after this frame. Use to chain Send methods. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="message">the string to send</param> [NotNull] public static IOutgoingSocket SendMoreFrame([NotNull] this IOutgoingSocket socket, [NotNull] string message) { SendFrame(socket, message, true); return socket; } #endregion #region Timeout /// <summary> /// Attempt to transmit a single string frame on <paramref cref="socket"/>. /// If message cannot be sent within <paramref name="timeout"/>, return <c>false</c>. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="timeout">The maximum period of time to try to send a message.</param> /// <param name="message">the string to send</param> /// <param name="more">set this flag to true to signal that you will be immediately sending another frame (optional: default is false)</param> /// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns> public static bool TrySendFrame([NotNull] this IOutgoingSocket socket, TimeSpan timeout, [NotNull] string message, bool more = false) { var msg = new Msg(); // Count the number of bytes required to encode the string. // Note that non-ASCII strings may not have an equal number of characters // and bytes. The encoding must be queried for this answer. // With this number, request a buffer from the pool. msg.InitPool(SendReceiveConstants.DefaultEncoding.GetByteCount(message)); // Encode the string into the buffer SendReceiveConstants.DefaultEncoding.GetBytes(message, 0, message.Length, msg.Data, 0); if (!socket.TrySend(ref msg, timeout, more)) { msg.Close(); return false; } msg.Close(); return true; } #endregion #region Immediate /// <summary> /// Attempt to transmit a single string frame on <paramref cref="socket"/>. // If message cannot be sent immediately, return <c>false</c>. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="message">the string to send</param> /// <param name="more">set this flag to true to signal that you will be immediately sending another frame (optional: default is false)</param> /// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns> public static bool TrySendFrame([NotNull] this IOutgoingSocket socket, [NotNull] string message, bool more = false) { return TrySendFrame(socket, TimeSpan.Zero, message, more); } #endregion #region obsolete /// <summary> /// Transmit a string-message of data over this socket. The string will be encoded into bytes using the specified Encoding. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="message">a string containing the message to send</param> /// <param name="encoding">the Encoding to use when converting the message-string into bytes</param> /// <param name="options">use this to specify which of the DontWait and SendMore flags to set</param> [Obsolete("Use SendFrame or TrySendFrame")] public static void Send([NotNull] this IOutgoingSocket socket, [NotNull] string message, [NotNull] Encoding encoding, SendReceiveOptions options) { var msg = new Msg(); // Count the number of bytes required to encode the string. // Note that non-ASCII strings may not have an equal number of characters // and bytes. The encoding must be queried for this answer. // With this number, request a buffer from the pool. msg.InitPool(encoding.GetByteCount(message)); // Encode the string into the buffer encoding.GetBytes(message, 0, message.Length, msg.Data, 0); socket.Send(ref msg, options); msg.Close(); } /// <summary> /// Transmit a string-message of data over this socket. The string will be encoded into bytes using the specified Encoding. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="message">a string containing the message to send</param> /// <param name="encoding">the Encoding to use when converting the message-string into bytes</param> /// <param name="dontWait">if true, return immediately without waiting for the send operation to complete (optional: default is false)</param> /// <param name="sendMore">set this flag to true to signal that you will be immediately sending another message (optional: default is false)</param> [Obsolete("Use SendFrame or TrySendFrame")] public static void Send([NotNull] this IOutgoingSocket socket, [NotNull] string message, [NotNull] Encoding encoding, bool dontWait = false, bool sendMore = false) { var options = SendReceiveOptions.None; if (dontWait) { options |= SendReceiveOptions.DontWait; } if (sendMore) { options |= SendReceiveOptions.SendMore; } socket.Send(message, encoding, options); } /// <summary> /// Transmit a string-message of data over this socket. The string will be encoded into bytes using the default Encoding (ASCII). /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="message">a string containing the message to send</param> /// <param name="dontWait">if true, return immediately without waiting for the send operation to complete (optional: default is false)</param> /// <param name="sendMore">set this flag to true to signal that you will be immediately sending another message (optional: default is false)</param> [Obsolete("Use SendFrame or TrySendFrame")] public static void Send([NotNull] this IOutgoingSocket socket, [NotNull] string message, bool dontWait = false, bool sendMore = false) { Send(socket, message, Encoding.ASCII, dontWait, sendMore); } /// <summary> /// Transmit a string-message of data over this socket, while indicating that more is to come /// (the SendMore flag is set to true). /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="message">a string containing the message to send</param> /// <param name="dontWait">if true, return immediately without waiting for the send operation to complete</param> /// <returns>a reference to this IOutgoingSocket so that method-calls may be chained together</returns> [NotNull] [Obsolete("Use SendMoreFrame or TrySendFrame")] public static IOutgoingSocket SendMore([NotNull] this IOutgoingSocket socket, [NotNull] string message, bool dontWait = false) { socket.Send(message, dontWait, true); return socket; } /// <summary> /// Transmit a string-message of data over this socket and also signal that you are sending more. /// The string will be encoded into bytes using the specified Encoding. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="message">a string containing the message to send</param> /// <param name="encoding">the Encoding to use when converting the message-string into bytes</param> /// <param name="dontWait">if true, return immediately without waiting for the send operation to complete (optional: default is false)</param> /// <returns>a reference to this IOutgoingSocket so that method-calls may be chained together</returns> [NotNull] [Obsolete("Use SendMoreFrame or TrySendFrame")] public static IOutgoingSocket SendMore([NotNull] this IOutgoingSocket socket, [NotNull] string message, [NotNull] Encoding encoding, bool dontWait = false) { socket.Send(message, encoding, dontWait, true); return socket; } #endregion #endregion #region Sending a multipart message as NetMQMessage #region Blocking /// <summary> /// Send multiple message on <paramref cref="socket"/>, blocking until all entire message is sent. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="message">message to transmit</param> public static void SendMultipartMessage([NotNull] this IOutgoingSocket socket, [NotNull] NetMQMessage message) { if (message.FrameCount == 0) throw new ArgumentException("message is empty", "message"); for (int i = 0; i < message.FrameCount - 1; i++) { socket.SendMoreFrame(message[i].Buffer, message[i].MessageSize); } socket.SendFrame(message.Last.Buffer, message.Last.MessageSize); } #endregion #region Timeout /// <summary> /// Attempt to transmit a mulitple message on <paramref cref="socket"/>. /// If message cannot be sent within <paramref name="timeout"/>, return <c>false</c>. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="message">message to transmit</param> public static bool TrySendMultipartMessage([NotNull] this IOutgoingSocket socket, TimeSpan timeout, [NotNull] NetMQMessage message) { if (message.FrameCount == 0) throw new ArgumentException("message is empty", "message"); else if (message.FrameCount == 1) { return TrySendFrame(socket, timeout, message[0].Buffer, message[0].MessageSize); } else { bool sentSuccessfully = TrySendFrame(socket, timeout, message[0].Buffer, message[0].MessageSize, true); if (!sentSuccessfully) return false; } for (int i = 1; i < message.FrameCount - 1; i++) { socket.SendMoreFrame(message[i].Buffer, message[i].MessageSize); } socket.SendFrame(message.Last.Buffer, message.Last.MessageSize); return true; } #endregion #region Immediate /// <summary> /// Attempt to transmit a mulitple message on <paramref cref="socket"/>. /// If frames cannot be sent immediatly, return <c>false</c>. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="message">message to transmit</param> public static bool TrySendMultipartMessage([NotNull] this IOutgoingSocket socket, [NotNull] NetMQMessage message) { return TrySendMultipartMessage(socket, TimeSpan.Zero, message); } #endregion #region obsolete /// <summary> /// Transmit a message over this socket. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="message">the NetMQMessage that contains the frames of data to send</param> /// <param name="dontWait">if true, return immediately without waiting for the send operation to complete (optional: default is false)</param> [Obsolete("Use TrySendMultipartMessage or SendMultipartMessage")] public static void SendMessage([NotNull] this IOutgoingSocket socket, [NotNull] NetMQMessage message, bool dontWait = false) { for (int i = 0; i < message.FrameCount - 1; i++) { socket.Send(message[i].Buffer, message[i].MessageSize, dontWait, true); } socket.Send(message.Last.Buffer, message.Last.MessageSize, dontWait); } #endregion #endregion #region Sending an empty frame private static readonly byte[] s_empty = new byte[0]; #region Blocking /// <summary> /// Transmit an empty frame over this socket, block until frame is sent. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="more">set this flag to true to signal that you will be immediately sending another frame (optional: default is false)</param> public static void SendFrameEmpty([NotNull] this IOutgoingSocket socket, bool more = false) { SendFrame(socket, s_empty, more); } /// <summary> /// Transmit an empty frame over this socket, block until frame is sent. /// Send more frame, another frame must be sent after this frame. Use to chain Send methods. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> public static void SendMoreFrameEmpty([NotNull] this IOutgoingSocket socket) { SendFrame(socket, s_empty, true); } #endregion #region Timeout /// <summary> /// Attempt to transmit an empty frame on <paramref cref="socket"/>. /// If message cannot be sent within <paramref name="timeout"/>, return <c>false</c>. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="timeout">The maximum period of time to try to send a message.</param> /// <param name="more">set this flag to true to signal that you will be immediately sending another frame (optional: default is false)</param> /// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns> public static bool TrySendFrameEmpty([NotNull] this IOutgoingSocket socket, TimeSpan timeout, bool more = false) { return TrySendFrame(socket, timeout, s_empty, more); } #endregion #region Immediate /// <summary> /// Attempt to transmit an empty frame on <paramref cref="socket"/>. /// If message cannot be sent immediately, return <c>false</c>. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="more">set this flag to true to signal that you will be immediately sending another frame (optional: default is false)</param> /// <returns><c>true</c> if a message was available, otherwise <c>false</c>.</returns> public static bool TrySendFrameEmpty([NotNull] this IOutgoingSocket socket, bool more = false) { return TrySendFrame(socket, s_empty, more); } #endregion #endregion #region Sending Signals /// <summary> /// Transmit a status-signal over this socket. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="status">a byte that contains the status signal to send</param> private static void Signal([NotNull] this IOutgoingSocket socket, byte status) { long signalValue = 0x7766554433221100L + status; Msg msg = new Msg(); msg.InitPool(8); NetworkOrderBitsConverter.PutInt64(signalValue, msg.Data); socket.Send(ref msg, false); msg.Close(); } /// <summary> /// Attempt to transmit a status-signal over this socket. /// If signal cannot be sent immediately, return <c>false</c>. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> /// <param name="status">a byte that contains the status signal to send</param> private static bool TrySignal([NotNull] this IOutgoingSocket socket, byte status) { long signalValue = 0x7766554433221100L + status; Msg msg = new Msg(); msg.InitPool(8); NetworkOrderBitsConverter.PutInt64(signalValue, msg.Data); if (!socket.TrySend(ref msg, TimeSpan.Zero, false)) { msg.Close(); return false; } msg.Close(); return true; } /// <summary> /// Transmit a specific status-signal over this socket that indicates OK. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> public static void SignalOK([NotNull] this IOutgoingSocket socket) { socket.Signal(0); } /// <summary> /// Attempt to transmit a specific status-signal over this socket that indicates OK. /// If signal cannot be sent immediately, return <c>false</c>. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> public static bool TrySignalOK([NotNull] this IOutgoingSocket socket) { return TrySignal(socket, 0); } /// <summary> /// Transmit a specific status-signal over this socket that indicates there is an error. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> public static void SignalError([NotNull] this IOutgoingSocket socket) { socket.Signal(1); } /// <summary> /// Attempt to transmit a specific status-signal over this socket that indicates there is an error. /// If signal cannot be sent immediately, return <c>false</c>. /// </summary> /// <param name="socket">the IOutgoingSocket to transmit on</param> public static bool TrySignalError([NotNull] this IOutgoingSocket socket) { return socket.TrySignal(1); } #endregion } }
lgpl-3.0
jspresso/jspresso-ce
util/src/main/java/org/jspresso/framework/util/spring/NullFactoryBean.java
1417
/* * Copyright (c) 2005-2016 Vincent Vandenschrick. All rights reserved. * * This file is part of the Jspresso framework. * * Jspresso is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Jspresso is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Jspresso. If not, see <http://www.gnu.org/licenses/>. */ package org.jspresso.framework.util.spring; import org.springframework.beans.factory.FactoryBean; /** * This is a simple utility bean to get a named null bean. * * @author Vincent Vandenschrick */ public class NullFactoryBean implements FactoryBean<Object> { /** * Returns true. * <p> * {@inheritDoc} */ @Override public boolean isSingleton() { return true; } /** * {@inheritDoc} */ @Override public Object getObject() throws Exception { return null; } /** * {@inheritDoc} */ @Override public Class<Object> getObjectType() { return Object.class; } }
lgpl-3.0
amifsud/sot-stabilizer
src/dynamic_graph/sot/application/stabilizer/scenarii/seqplay_lqr_twoDof_coupled_stabilizer_hrp2.py
2157
from dynamic_graph.sot.application.stabilizer.scenarii.seqplay_lqr_twoDof_coupled_stabilizer import SeqPlayLqrTwoDofCoupledStabilizer from dynamic_graph.sot.application.stabilizer.scenarii.hrp2_lqr_twoDof_coupled_stabilizer import HRP2LqrTwoDofCoupledStabilizer from dynamic_graph.sot.core.meta_tasks import GainAdaptive from dynamic_graph import plug from dynamic_graph.sot.core.matrix_util import matrixToTuple from dynamic_graph.sot.core import MatrixToUTheta, HomoToMatrix, HomoToRotation, Multiply_matrix_vector from numpy import diag class SeqPlayLqrTwoDofCoupledStabilizerHRP2(SeqPlayLqrTwoDofCoupledStabilizer): def __init__(self,robot,sequenceFilename,trunkStabilize = False, hands = False, posture =False,forceSeqplay=True): SeqPlayLqrTwoDofCoupledStabilizer.__init__(self,robot,sequenceFilename,trunkStabilize,hands,posture,forceSeqplay) def createStabilizedCoMTask (self): task = HRP2LqrTwoDofCoupledStabilizer(self.robot) gain = GainAdaptive('gain'+task.name) plug(self.comRef,task.comRef) task.waistOriRef.value=(0,)*3 task.flexOriRef.value=(0,)*3 task.comDotRef.value=(0,)*3 task.waistVelRef.value=(0,)*3 task.flexAngVelRef.value=(0,)*3 plug(gain.gain, task.controlGain) plug(task.error, gain.error) return (task, gain) def initTaskPosture(self): # --- LEAST NORM weight_ff = 0 weight_leg = 3 weight_knee = 5 weight_chest = 1 weight_chesttilt = 10 weight_head = 0.3 weight_arm = 1 #weight = diag( (weight_ff,)*6 + (weight_leg,)*12 + (weight_chest,)*2 + (weight_head,)*2 + (weight_arm,)*14) #weight[9,9] = weight_knee #weight[15,15] = weight_knee #weight[19,19] = weight_chesttilt weight = diag( (0,)*6+(1,)*30) #weight = weight[6:,:] self.featurePosture.jacobianIN.value = matrixToTuple(weight) self.featurePostureDes.errorIN.value = self.robot.halfSitting #mask = '1'*36 #mask = '1'*14+'0'*22 #self.tasks['posture'].controlSelec.value = mask
lgpl-3.0
iris-edu/pyweed
pyweed/gui/uic/SpinnerWidget.py
2674
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'pyweed/gui/uic/SpinnerWidget.ui' # # Created by: PyQt5 UI code generator 5.6 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_SpinnerWidget(object): def setupUi(self, SpinnerWidget): SpinnerWidget.setObjectName("SpinnerWidget") SpinnerWidget.resize(306, 207) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Ignored, QtWidgets.QSizePolicy.Ignored) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(SpinnerWidget.sizePolicy().hasHeightForWidth()) SpinnerWidget.setSizePolicy(sizePolicy) SpinnerWidget.setStyleSheet("QFrame { background-color: rgba(224,224,224,192)} \n" "QLabel { background-color: transparent }") self.verticalLayout = QtWidgets.QVBoxLayout(SpinnerWidget) self.verticalLayout.setSpacing(0) self.verticalLayout.setObjectName("verticalLayout") self.icon = QtWidgets.QLabel(SpinnerWidget) self.icon.setText("") self.icon.setAlignment(QtCore.Qt.AlignBottom|QtCore.Qt.AlignHCenter) self.icon.setObjectName("icon") self.verticalLayout.addWidget(self.icon) self.label = QtWidgets.QLabel(SpinnerWidget) self.label.setText("") self.label.setAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt.AlignTop) self.label.setObjectName("label") self.verticalLayout.addWidget(self.label) self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.cancelButton = QtWidgets.QPushButton(SpinnerWidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cancelButton.sizePolicy().hasHeightForWidth()) self.cancelButton.setSizePolicy(sizePolicy) self.cancelButton.setObjectName("cancelButton") self.horizontalLayout.addWidget(self.cancelButton) self.verticalLayout.addLayout(self.horizontalLayout) self.verticalLayout.setStretch(0, 1) self.verticalLayout.setStretch(1, 1) self.retranslateUi(SpinnerWidget) QtCore.QMetaObject.connectSlotsByName(SpinnerWidget) def retranslateUi(self, SpinnerWidget): _translate = QtCore.QCoreApplication.translate SpinnerWidget.setWindowTitle(_translate("SpinnerWidget", "Form")) self.cancelButton.setText(_translate("SpinnerWidget", "Cancel"))
lgpl-3.0
dtklein/vFense
tp/src/plugins/patching/utils/__init__.py
1957
import re from hashlib import sha256 from vFense.plugins.patching import AppsKey from vFense.plugins.patching._constants import CommonSeverityKeys def build_app_id(name, version): """ Return the 64 character hexdigest of the appid. The app_id is generated by creating a hexdigest based of the name and the version of the application. Args: app (dict): Dictionary containing the name and version of the application. Basic Usage: >>> from vFense.plugins.patching.utils import build_app_id >>> name = 'app_name' >>> version = '2.2.0' >>> build_app_id(name, version) Returns: String 'bab72e94f26a0af32a8e1fc8eef732b99150fac9bc17a720dac06f5474b53f08' """ app_id = name.encode('utf8') + version.encode('utf8') return sha256(app_id).hexdigest() def build_agent_app_id(agent_id, app_id): """ Return the 64 character hexdigest of the appid and agentid combined Args: agent_id (str): The 36 character UUID of the agent. app_id (str): The 64 character hexdigest of the app id Basic Usage: >>> vFense.plugins.patching.patching import build_agent_app_id >>> agent_id = '7f242ab8-a9d7-418f-9ce2-7bcba6c2d9dc' >>> app_id = '15fa819554aca425d7f699e81a2097898b06f00a0f2dd6e8d51a18405360a6eb' >>> build_agent_app_id(agent_id, app_id) Returns: String '0009281d779a37cc73919656f6575de471237c3ed99f585160708defe8396d3d' """ agent_app_id = agent_id.encode('utf8') + app_id.encode('utf8') return sha256(agent_app_id).hexdigest() def get_proper_severity(severity): if re.search(r'Critical|Important|Security', severity, re.IGNORECASE): return CommonSeverityKeys.CRITICAL elif re.search(r'Recommended|Moderate|Low|Bugfix', severity, re.IGNORECASE): return CommonSeverityKeys.RECOMMENDED return CommonSeverityKeys.OPTIONAL
lgpl-3.0
edwinspire/VSharp
class/Facades/System.Xml.XDocument/Makefile
505
MCS_BUILD_DIR = ../../../build thisdir = class/Facades/System.Xml.XDocument SUBDIRS = include $(MCS_BUILD_DIR)/rules.make LIBRARY_SUBDIR = Facades LIBRARY_INSTALL_DIR = $(mono_libdir)/mono/$(FRAMEWORK_VERSION)/Facades LIBRARY = System.Xml.XDocument.dll KEY_FILE = ../../msfinal.pub SIGN_FLAGS = /delaysign /keyfile:$(KEY_FILE) /nowarn:1616,1699 LIB_MCS_FLAGS = $(SIGN_FLAGS) /r:mscorlib /r:System.Xml.Linq /r:System.Xml PLATFORM_DEBUG_FLAGS = NO_TEST = yes include $(MCS_BUILD_DIR)/library.make
lgpl-3.0
am2rican5/go-ethereum
eth/filters/filter_system_test.go
18403
// Copyright 2016 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. package filters import ( "context" "fmt" "math/big" "reflect" "testing" "time" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethdb" "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/rpc" ) type testBackend struct { mux *event.TypeMux db ethdb.Database } func (b *testBackend) ChainDb() ethdb.Database { return b.db } func (b *testBackend) EventMux() *event.TypeMux { return b.mux } func (b *testBackend) HeaderByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*types.Header, error) { var hash common.Hash var num uint64 if blockNr == rpc.LatestBlockNumber { hash = core.GetHeadBlockHash(b.db) num = core.GetBlockNumber(b.db, hash) } else { num = uint64(blockNr) hash = core.GetCanonicalHash(b.db, num) } return core.GetHeader(b.db, hash, num), nil } func (b *testBackend) GetReceipts(ctx context.Context, blockHash common.Hash) (types.Receipts, error) { num := core.GetBlockNumber(b.db, blockHash) return core.GetBlockReceipts(b.db, blockHash, num), nil } // TestBlockSubscription tests if a block subscription returns block hashes for posted chain events. // It creates multiple subscriptions: // - one at the start and should receive all posted chain events and a second (blockHashes) // - one that is created after a cutoff moment and uninstalled after a second cutoff moment (blockHashes[cutoff1:cutoff2]) // - one that is created after the second cutoff moment (blockHashes[cutoff2:]) func TestBlockSubscription(t *testing.T) { t.Parallel() var ( mux = new(event.TypeMux) db, _ = ethdb.NewMemDatabase() backend = &testBackend{mux, db} api = NewPublicFilterAPI(backend, false) genesis = new(core.Genesis).MustCommit(db) chain, _ = core.GenerateChain(params.TestChainConfig, genesis, db, 10, func(i int, gen *core.BlockGen) {}) chainEvents = []core.ChainEvent{} ) for _, blk := range chain { chainEvents = append(chainEvents, core.ChainEvent{Hash: blk.Hash(), Block: blk}) } chan0 := make(chan *types.Header) sub0 := api.events.SubscribeNewHeads(chan0) chan1 := make(chan *types.Header) sub1 := api.events.SubscribeNewHeads(chan1) go func() { // simulate client i1, i2 := 0, 0 for i1 != len(chainEvents) || i2 != len(chainEvents) { select { case header := <-chan0: if chainEvents[i1].Hash != header.Hash() { t.Errorf("sub0 received invalid hash on index %d, want %x, got %x", i1, chainEvents[i1].Hash, header.Hash()) } i1++ case header := <-chan1: if chainEvents[i2].Hash != header.Hash() { t.Errorf("sub1 received invalid hash on index %d, want %x, got %x", i2, chainEvents[i2].Hash, header.Hash()) } i2++ } } sub0.Unsubscribe() sub1.Unsubscribe() }() time.Sleep(1 * time.Second) for _, e := range chainEvents { mux.Post(e) } <-sub0.Err() <-sub1.Err() } // TestPendingTxFilter tests whether pending tx filters retrieve all pending transactions that are posted to the event mux. func TestPendingTxFilter(t *testing.T) { t.Parallel() var ( mux = new(event.TypeMux) db, _ = ethdb.NewMemDatabase() backend = &testBackend{mux, db} api = NewPublicFilterAPI(backend, false) transactions = []*types.Transaction{ types.NewTransaction(0, common.HexToAddress("0xb794f5ea0ba39494ce83a213fffba74279579268"), new(big.Int), new(big.Int), new(big.Int), nil), types.NewTransaction(1, common.HexToAddress("0xb794f5ea0ba39494ce83a213fffba74279579268"), new(big.Int), new(big.Int), new(big.Int), nil), types.NewTransaction(2, common.HexToAddress("0xb794f5ea0ba39494ce83a213fffba74279579268"), new(big.Int), new(big.Int), new(big.Int), nil), types.NewTransaction(3, common.HexToAddress("0xb794f5ea0ba39494ce83a213fffba74279579268"), new(big.Int), new(big.Int), new(big.Int), nil), types.NewTransaction(4, common.HexToAddress("0xb794f5ea0ba39494ce83a213fffba74279579268"), new(big.Int), new(big.Int), new(big.Int), nil), } hashes []common.Hash ) fid0 := api.NewPendingTransactionFilter() time.Sleep(1 * time.Second) for _, tx := range transactions { ev := core.TxPreEvent{Tx: tx} mux.Post(ev) } for { results, err := api.GetFilterChanges(fid0) if err != nil { t.Fatalf("Unable to retrieve logs: %v", err) } h := results.([]common.Hash) hashes = append(hashes, h...) if len(hashes) >= len(transactions) { break } time.Sleep(100 * time.Millisecond) } for i := range hashes { if hashes[i] != transactions[i].Hash() { t.Errorf("hashes[%d] invalid, want %x, got %x", i, transactions[i].Hash(), hashes[i]) } } } // TestLogFilterCreation test whether a given filter criteria makes sense. // If not it must return an error. func TestLogFilterCreation(t *testing.T) { var ( mux = new(event.TypeMux) db, _ = ethdb.NewMemDatabase() backend = &testBackend{mux, db} api = NewPublicFilterAPI(backend, false) testCases = []struct { crit FilterCriteria success bool }{ // defaults {FilterCriteria{}, true}, // valid block number range {FilterCriteria{FromBlock: big.NewInt(1), ToBlock: big.NewInt(2)}, true}, // "mined" block range to pending {FilterCriteria{FromBlock: big.NewInt(1), ToBlock: big.NewInt(rpc.LatestBlockNumber.Int64())}, true}, // new mined and pending blocks {FilterCriteria{FromBlock: big.NewInt(rpc.LatestBlockNumber.Int64()), ToBlock: big.NewInt(rpc.PendingBlockNumber.Int64())}, true}, // from block "higher" than to block {FilterCriteria{FromBlock: big.NewInt(2), ToBlock: big.NewInt(1)}, false}, // from block "higher" than to block {FilterCriteria{FromBlock: big.NewInt(rpc.LatestBlockNumber.Int64()), ToBlock: big.NewInt(100)}, false}, // from block "higher" than to block {FilterCriteria{FromBlock: big.NewInt(rpc.PendingBlockNumber.Int64()), ToBlock: big.NewInt(100)}, false}, // from block "higher" than to block {FilterCriteria{FromBlock: big.NewInt(rpc.PendingBlockNumber.Int64()), ToBlock: big.NewInt(rpc.LatestBlockNumber.Int64())}, false}, } ) for i, test := range testCases { _, err := api.NewFilter(test.crit) if test.success && err != nil { t.Errorf("expected filter creation for case %d to success, got %v", i, err) } if !test.success && err == nil { t.Errorf("expected testcase %d to fail with an error", i) } } } // TestInvalidLogFilterCreation tests whether invalid filter log criteria results in an error // when the filter is created. func TestInvalidLogFilterCreation(t *testing.T) { t.Parallel() var ( mux = new(event.TypeMux) db, _ = ethdb.NewMemDatabase() backend = &testBackend{mux, db} api = NewPublicFilterAPI(backend, false) ) // different situations where log filter creation should fail. // Reason: fromBlock > toBlock testCases := []FilterCriteria{ 0: {FromBlock: big.NewInt(rpc.PendingBlockNumber.Int64()), ToBlock: big.NewInt(rpc.LatestBlockNumber.Int64())}, 1: {FromBlock: big.NewInt(rpc.PendingBlockNumber.Int64()), ToBlock: big.NewInt(100)}, 2: {FromBlock: big.NewInt(rpc.LatestBlockNumber.Int64()), ToBlock: big.NewInt(100)}, } for i, test := range testCases { if _, err := api.NewFilter(test); err == nil { t.Errorf("Expected NewFilter for case #%d to fail", i) } } } // TestLogFilter tests whether log filters match the correct logs that are posted to the event mux. func TestLogFilter(t *testing.T) { t.Parallel() var ( mux = new(event.TypeMux) db, _ = ethdb.NewMemDatabase() backend = &testBackend{mux, db} api = NewPublicFilterAPI(backend, false) firstAddr = common.HexToAddress("0x1111111111111111111111111111111111111111") secondAddr = common.HexToAddress("0x2222222222222222222222222222222222222222") thirdAddress = common.HexToAddress("0x3333333333333333333333333333333333333333") notUsedAddress = common.HexToAddress("0x9999999999999999999999999999999999999999") firstTopic = common.HexToHash("0x1111111111111111111111111111111111111111111111111111111111111111") secondTopic = common.HexToHash("0x2222222222222222222222222222222222222222222222222222222222222222") notUsedTopic = common.HexToHash("0x9999999999999999999999999999999999999999999999999999999999999999") // posted twice, once as vm.Logs and once as core.PendingLogsEvent allLogs = []*types.Log{ {Address: firstAddr}, {Address: firstAddr, Topics: []common.Hash{firstTopic}, BlockNumber: 1}, {Address: secondAddr, Topics: []common.Hash{firstTopic}, BlockNumber: 1}, {Address: thirdAddress, Topics: []common.Hash{secondTopic}, BlockNumber: 2}, {Address: thirdAddress, Topics: []common.Hash{secondTopic}, BlockNumber: 3}, } expectedCase7 = []*types.Log{allLogs[3], allLogs[4], allLogs[0], allLogs[1], allLogs[2], allLogs[3], allLogs[4]} expectedCase11 = []*types.Log{allLogs[1], allLogs[2], allLogs[1], allLogs[2]} testCases = []struct { crit FilterCriteria expected []*types.Log id rpc.ID }{ // match all 0: {FilterCriteria{}, allLogs, ""}, // match none due to no matching addresses 1: {FilterCriteria{Addresses: []common.Address{{}, notUsedAddress}, Topics: [][]common.Hash{allLogs[0].Topics}}, []*types.Log{}, ""}, // match logs based on addresses, ignore topics 2: {FilterCriteria{Addresses: []common.Address{firstAddr}}, allLogs[:2], ""}, // match none due to no matching topics (match with address) 3: {FilterCriteria{Addresses: []common.Address{secondAddr}, Topics: [][]common.Hash{{notUsedTopic}}}, []*types.Log{}, ""}, // match logs based on addresses and topics 4: {FilterCriteria{Addresses: []common.Address{thirdAddress}, Topics: [][]common.Hash{{firstTopic, secondTopic}}}, allLogs[3:5], ""}, // match logs based on multiple addresses and "or" topics 5: {FilterCriteria{Addresses: []common.Address{secondAddr, thirdAddress}, Topics: [][]common.Hash{{firstTopic, secondTopic}}}, allLogs[2:5], ""}, // logs in the pending block 6: {FilterCriteria{Addresses: []common.Address{firstAddr}, FromBlock: big.NewInt(rpc.PendingBlockNumber.Int64()), ToBlock: big.NewInt(rpc.PendingBlockNumber.Int64())}, allLogs[:2], ""}, // mined logs with block num >= 2 or pending logs 7: {FilterCriteria{FromBlock: big.NewInt(2), ToBlock: big.NewInt(rpc.PendingBlockNumber.Int64())}, expectedCase7, ""}, // all "mined" logs with block num >= 2 8: {FilterCriteria{FromBlock: big.NewInt(2), ToBlock: big.NewInt(rpc.LatestBlockNumber.Int64())}, allLogs[3:], ""}, // all "mined" logs 9: {FilterCriteria{ToBlock: big.NewInt(rpc.LatestBlockNumber.Int64())}, allLogs, ""}, // all "mined" logs with 1>= block num <=2 and topic secondTopic 10: {FilterCriteria{FromBlock: big.NewInt(1), ToBlock: big.NewInt(2), Topics: [][]common.Hash{{secondTopic}}}, allLogs[3:4], ""}, // all "mined" and pending logs with topic firstTopic 11: {FilterCriteria{FromBlock: big.NewInt(rpc.LatestBlockNumber.Int64()), ToBlock: big.NewInt(rpc.PendingBlockNumber.Int64()), Topics: [][]common.Hash{{firstTopic}}}, expectedCase11, ""}, } ) // create all filters for i := range testCases { testCases[i].id, _ = api.NewFilter(testCases[i].crit) } // raise events time.Sleep(1 * time.Second) if err := mux.Post(allLogs); err != nil { t.Fatal(err) } if err := mux.Post(core.PendingLogsEvent{Logs: allLogs}); err != nil { t.Fatal(err) } for i, tt := range testCases { var fetched []*types.Log for { // fetch all expected logs results, err := api.GetFilterChanges(tt.id) if err != nil { t.Fatalf("Unable to fetch logs: %v", err) } fetched = append(fetched, results.([]*types.Log)...) if len(fetched) >= len(tt.expected) { break } time.Sleep(100 * time.Millisecond) } if len(fetched) != len(tt.expected) { t.Errorf("invalid number of logs for case %d, want %d log(s), got %d", i, len(tt.expected), len(fetched)) return } for l := range fetched { if fetched[l].Removed { t.Errorf("expected log not to be removed for log %d in case %d", l, i) } if !reflect.DeepEqual(fetched[l], tt.expected[l]) { t.Errorf("invalid log on index %d for case %d", l, i) } } } } // TestPendingLogsSubscription tests if a subscription receives the correct pending logs that are posted to the event mux. func TestPendingLogsSubscription(t *testing.T) { t.Parallel() var ( mux = new(event.TypeMux) db, _ = ethdb.NewMemDatabase() backend = &testBackend{mux, db} api = NewPublicFilterAPI(backend, false) firstAddr = common.HexToAddress("0x1111111111111111111111111111111111111111") secondAddr = common.HexToAddress("0x2222222222222222222222222222222222222222") thirdAddress = common.HexToAddress("0x3333333333333333333333333333333333333333") notUsedAddress = common.HexToAddress("0x9999999999999999999999999999999999999999") firstTopic = common.HexToHash("0x1111111111111111111111111111111111111111111111111111111111111111") secondTopic = common.HexToHash("0x2222222222222222222222222222222222222222222222222222222222222222") thirdTopic = common.HexToHash("0x3333333333333333333333333333333333333333333333333333333333333333") forthTopic = common.HexToHash("0x4444444444444444444444444444444444444444444444444444444444444444") notUsedTopic = common.HexToHash("0x9999999999999999999999999999999999999999999999999999999999999999") allLogs = []core.PendingLogsEvent{ {Logs: []*types.Log{{Address: firstAddr, Topics: []common.Hash{}, BlockNumber: 0}}}, {Logs: []*types.Log{{Address: firstAddr, Topics: []common.Hash{firstTopic}, BlockNumber: 1}}}, {Logs: []*types.Log{{Address: secondAddr, Topics: []common.Hash{firstTopic}, BlockNumber: 2}}}, {Logs: []*types.Log{{Address: thirdAddress, Topics: []common.Hash{secondTopic}, BlockNumber: 3}}}, {Logs: []*types.Log{{Address: thirdAddress, Topics: []common.Hash{secondTopic}, BlockNumber: 4}}}, {Logs: []*types.Log{ {Address: thirdAddress, Topics: []common.Hash{firstTopic}, BlockNumber: 5}, {Address: thirdAddress, Topics: []common.Hash{thirdTopic}, BlockNumber: 5}, {Address: thirdAddress, Topics: []common.Hash{forthTopic}, BlockNumber: 5}, {Address: firstAddr, Topics: []common.Hash{firstTopic}, BlockNumber: 5}, }}, } convertLogs = func(pl []core.PendingLogsEvent) []*types.Log { var logs []*types.Log for _, l := range pl { logs = append(logs, l.Logs...) } return logs } testCases = []struct { crit FilterCriteria expected []*types.Log c chan []*types.Log sub *Subscription }{ // match all {FilterCriteria{}, convertLogs(allLogs), nil, nil}, // match none due to no matching addresses {FilterCriteria{Addresses: []common.Address{{}, notUsedAddress}, Topics: [][]common.Hash{{}}}, []*types.Log{}, nil, nil}, // match logs based on addresses, ignore topics {FilterCriteria{Addresses: []common.Address{firstAddr}}, append(convertLogs(allLogs[:2]), allLogs[5].Logs[3]), nil, nil}, // match none due to no matching topics (match with address) {FilterCriteria{Addresses: []common.Address{secondAddr}, Topics: [][]common.Hash{{notUsedTopic}}}, []*types.Log{}, nil, nil}, // match logs based on addresses and topics {FilterCriteria{Addresses: []common.Address{thirdAddress}, Topics: [][]common.Hash{{firstTopic, secondTopic}}}, append(convertLogs(allLogs[3:5]), allLogs[5].Logs[0]), nil, nil}, // match logs based on multiple addresses and "or" topics {FilterCriteria{Addresses: []common.Address{secondAddr, thirdAddress}, Topics: [][]common.Hash{{firstTopic, secondTopic}}}, append(convertLogs(allLogs[2:5]), allLogs[5].Logs[0]), nil, nil}, // block numbers are ignored for filters created with New***Filter, these return all logs that match the given criteria when the state changes {FilterCriteria{Addresses: []common.Address{firstAddr}, FromBlock: big.NewInt(2), ToBlock: big.NewInt(3)}, append(convertLogs(allLogs[:2]), allLogs[5].Logs[3]), nil, nil}, // multiple pending logs, should match only 2 topics from the logs in block 5 {FilterCriteria{Addresses: []common.Address{thirdAddress}, Topics: [][]common.Hash{{firstTopic, forthTopic}}}, []*types.Log{allLogs[5].Logs[0], allLogs[5].Logs[2]}, nil, nil}, } ) // create all subscriptions, this ensures all subscriptions are created before the events are posted. // on slow machines this could otherwise lead to missing events when the subscription is created after // (some) events are posted. for i := range testCases { testCases[i].c = make(chan []*types.Log) testCases[i].sub, _ = api.events.SubscribeLogs(testCases[i].crit, testCases[i].c) } for n, test := range testCases { i := n tt := test go func() { var fetched []*types.Log fetchLoop: for { logs := <-tt.c fetched = append(fetched, logs...) if len(fetched) >= len(tt.expected) { break fetchLoop } } if len(fetched) != len(tt.expected) { panic(fmt.Sprintf("invalid number of logs for case %d, want %d log(s), got %d", i, len(tt.expected), len(fetched))) } for l := range fetched { if fetched[l].Removed { panic(fmt.Sprintf("expected log not to be removed for log %d in case %d", l, i)) } if !reflect.DeepEqual(fetched[l], tt.expected[l]) { panic(fmt.Sprintf("invalid log on index %d for case %d", l, i)) } } }() } // raise events time.Sleep(1 * time.Second) for _, l := range allLogs { if err := mux.Post(l); err != nil { t.Fatal(err) } } }
lgpl-3.0
MM2CSYNDIC/syndic
syndic-repository-core/src/main/java/fr/upond/syndic/repository/userRole/UserRoleDaoImpl.java
1100
package fr.upond.syndic.repository.userRole; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import fr.upond.syndic.repository.IDao; import fr.upond.syndic.security.model.UserRole; /** * * @author LYES KHERBICHE * */ public class UserRoleDaoImpl implements IDao<UserRole> { private static final Log logger = LogFactory.getLog(UserRoleDaoImpl.class); @Autowired private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Override public List<UserRole> get(UserRole obj) { return new ArrayList<UserRole>(); } @Override public void put(UserRole obj) { logger.info("===== Insert UserRole ====="); this.sessionFactory.getCurrentSession().save(obj); } @Override public void delete(UserRole obj) { // to implement } @Override public void upDate(UserRole obj) { // to implement } }
lgpl-3.0
dresden-ocl/dresdenocl
plugins/org.dresdenocl.tools.CWM/src/orgomg/cwm/resource/relational/impl/SQLStructuredTypeImpl.java
9279
/** * <copyright> * </copyright> * * $Id$ */ package orgomg.cwm.resource.relational.impl; import java.util.Collection; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.util.EObjectWithInverseResolvingEList; import org.eclipse.emf.ecore.util.InternalEList; import orgomg.cwm.objectmodel.core.impl.ClassImpl; import orgomg.cwm.resource.relational.Column; import orgomg.cwm.resource.relational.NamedColumnSet; import orgomg.cwm.resource.relational.RelationalPackage; import orgomg.cwm.resource.relational.SQLDataType; import orgomg.cwm.resource.relational.SQLStructuredType; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>SQL Structured Type</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link orgomg.cwm.resource.relational.impl.SQLStructuredTypeImpl#getTypeNumber <em>Type Number</em>}</li> * <li>{@link orgomg.cwm.resource.relational.impl.SQLStructuredTypeImpl#getColumnSet <em>Column Set</em>}</li> * <li>{@link orgomg.cwm.resource.relational.impl.SQLStructuredTypeImpl#getReferencingColumn <em>Referencing Column</em>}</li> * </ul> * </p> * * @generated */ public class SQLStructuredTypeImpl extends ClassImpl implements SQLStructuredType { /** * The default value of the '{@link #getTypeNumber() <em>Type Number</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTypeNumber() * @generated * @ordered */ protected static final long TYPE_NUMBER_EDEFAULT = 0L; /** * The cached value of the '{@link #getTypeNumber() <em>Type Number</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getTypeNumber() * @generated * @ordered */ protected long typeNumber = TYPE_NUMBER_EDEFAULT; /** * The cached value of the '{@link #getColumnSet() <em>Column Set</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getColumnSet() * @generated * @ordered */ protected EList<NamedColumnSet> columnSet; /** * The cached value of the '{@link #getReferencingColumn() <em>Referencing Column</em>}' reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getReferencingColumn() * @generated * @ordered */ protected EList<Column> referencingColumn; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected SQLStructuredTypeImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return RelationalPackage.Literals.SQL_STRUCTURED_TYPE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public long getTypeNumber() { return typeNumber; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setTypeNumber(long newTypeNumber) { long oldTypeNumber = typeNumber; typeNumber = newTypeNumber; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, RelationalPackage.SQL_STRUCTURED_TYPE__TYPE_NUMBER, oldTypeNumber, typeNumber)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<NamedColumnSet> getColumnSet() { if (columnSet == null) { columnSet = new EObjectWithInverseResolvingEList<NamedColumnSet>(NamedColumnSet.class, this, RelationalPackage.SQL_STRUCTURED_TYPE__COLUMN_SET, RelationalPackage.NAMED_COLUMN_SET__TYPE); } return columnSet; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<Column> getReferencingColumn() { if (referencingColumn == null) { referencingColumn = new EObjectWithInverseResolvingEList<Column>(Column.class, this, RelationalPackage.SQL_STRUCTURED_TYPE__REFERENCING_COLUMN, RelationalPackage.COLUMN__REFERENCED_TABLE_TYPE); } return referencingColumn; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case RelationalPackage.SQL_STRUCTURED_TYPE__COLUMN_SET: return ((InternalEList<InternalEObject>)(InternalEList<?>)getColumnSet()).basicAdd(otherEnd, msgs); case RelationalPackage.SQL_STRUCTURED_TYPE__REFERENCING_COLUMN: return ((InternalEList<InternalEObject>)(InternalEList<?>)getReferencingColumn()).basicAdd(otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case RelationalPackage.SQL_STRUCTURED_TYPE__COLUMN_SET: return ((InternalEList<?>)getColumnSet()).basicRemove(otherEnd, msgs); case RelationalPackage.SQL_STRUCTURED_TYPE__REFERENCING_COLUMN: return ((InternalEList<?>)getReferencingColumn()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case RelationalPackage.SQL_STRUCTURED_TYPE__TYPE_NUMBER: return getTypeNumber(); case RelationalPackage.SQL_STRUCTURED_TYPE__COLUMN_SET: return getColumnSet(); case RelationalPackage.SQL_STRUCTURED_TYPE__REFERENCING_COLUMN: return getReferencingColumn(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case RelationalPackage.SQL_STRUCTURED_TYPE__TYPE_NUMBER: setTypeNumber((Long)newValue); return; case RelationalPackage.SQL_STRUCTURED_TYPE__COLUMN_SET: getColumnSet().clear(); getColumnSet().addAll((Collection<? extends NamedColumnSet>)newValue); return; case RelationalPackage.SQL_STRUCTURED_TYPE__REFERENCING_COLUMN: getReferencingColumn().clear(); getReferencingColumn().addAll((Collection<? extends Column>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case RelationalPackage.SQL_STRUCTURED_TYPE__TYPE_NUMBER: setTypeNumber(TYPE_NUMBER_EDEFAULT); return; case RelationalPackage.SQL_STRUCTURED_TYPE__COLUMN_SET: getColumnSet().clear(); return; case RelationalPackage.SQL_STRUCTURED_TYPE__REFERENCING_COLUMN: getReferencingColumn().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case RelationalPackage.SQL_STRUCTURED_TYPE__TYPE_NUMBER: return typeNumber != TYPE_NUMBER_EDEFAULT; case RelationalPackage.SQL_STRUCTURED_TYPE__COLUMN_SET: return columnSet != null && !columnSet.isEmpty(); case RelationalPackage.SQL_STRUCTURED_TYPE__REFERENCING_COLUMN: return referencingColumn != null && !referencingColumn.isEmpty(); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public int eBaseStructuralFeatureID(int derivedFeatureID, Class<?> baseClass) { if (baseClass == SQLDataType.class) { switch (derivedFeatureID) { case RelationalPackage.SQL_STRUCTURED_TYPE__TYPE_NUMBER: return RelationalPackage.SQL_DATA_TYPE__TYPE_NUMBER; default: return -1; } } return super.eBaseStructuralFeatureID(derivedFeatureID, baseClass); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public int eDerivedStructuralFeatureID(int baseFeatureID, Class<?> baseClass) { if (baseClass == SQLDataType.class) { switch (baseFeatureID) { case RelationalPackage.SQL_DATA_TYPE__TYPE_NUMBER: return RelationalPackage.SQL_STRUCTURED_TYPE__TYPE_NUMBER; default: return -1; } } return super.eDerivedStructuralFeatureID(baseFeatureID, baseClass); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (typeNumber: "); result.append(typeNumber); result.append(')'); return result.toString(); } } //SQLStructuredTypeImpl
lgpl-3.0
roboptim/roboptim-capsule
include/roboptim/capsule/distance-capsule-point.hh
2895
// Copyright (C) 2012 by Antonio El Khoury, CNRS. // // This file is part of the roboptim-capsule. // // roboptim-capsule is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either // version 3 of the License, or (at your option) any later version. // // roboptim-capsule is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with roboptim-capsule. If not, see // <http://www.gnu.org/licenses/>. /** * \brief Declaration of DistanceSegmentPoint class that computes * the distance between a segment and a point. */ #ifndef ROBOPTIM_CAPSULE_DISTANCE_CAPSULE_POINT_HH # define ROBOPTIM_CAPSULE_DISTANCE_CAPSULE_POINT_HH # include <roboptim/core/differentiable-function.hh> # include <roboptim/capsule/types.hh> namespace roboptim { namespace capsule { /// \brief Distance to point RobOptim function. class DistanceCapsulePoint : public roboptim::DifferentiableFunction { public: /// \brief Constructor. /// /// \param point point that will be used in computing distance /// between the capsule and the point. DistanceCapsulePoint (const point_t& point, std::string name = "distance to point"); ~DistanceCapsulePoint (); /// \brief Get point attribute. virtual const point_t& point () const; protected: /// \brief Computes the distance from capsule to a point. /// /// If the result is negative, the point is inside the capsule, /// otherwise it is outside the capsule. /// /// \param argument vector containing the capsule parameters. It /// contains in this order: the segment first end point /// coordinates, the segment second end point coordinates, the /// capsule radius. virtual void impl_compute (result_ref result, const_argument_ref argument) const; /// \brief Compute of the distance gradient with respect to the /// capsule parameters. /// /// \param argument vector containing the capsule parameters. It /// contains in this order: the segment first end point /// coordinates, the segment second end point coordinates, the /// capsule radius. virtual void impl_gradient (gradient_ref gradient, const_argument_ref argument, size_type functionId = 0) const; private: /// \brief Point attribute. point_t point_; }; } // end of namespace capsule. } // end of namespace roboptim. #endif //! ROBOPTIM_CAPSULE_DISTANCE_CAPSULE_POINT_HH
lgpl-3.0
tvsonar/sonarlint-vs
src/SonarAnalyzer.CSharp/Rules/WcfNonVoidOneWay.cs
4697
/* * SonarAnalyzer for .NET * Copyright (C) 2015-2016 SonarSource SA * mailto:[email protected] * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This 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. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using SonarAnalyzer.Common; using SonarAnalyzer.Common.Sqale; using SonarAnalyzer.Helpers; using Microsoft.CodeAnalysis.CSharp; using System; namespace SonarAnalyzer.Rules.CSharp { [DiagnosticAnalyzer(LanguageNames.CSharp)] [SqaleConstantRemediation("15min")] [SqaleSubCharacteristic(SqaleSubCharacteristic.DataReliability)] [Rule(DiagnosticId, RuleSeverity, Title, IsActivatedByDefault)] [Tags(Tag.Bug)] public class WcfNonVoidOneWay : SonarDiagnosticAnalyzer { internal const string DiagnosticId = "S3598"; internal const string Title = "One-way \"OperationContract\" methods should have \"void\" return type"; internal const string Description = "When declaring a Windows Communication Foundation (WCF) \"OperationContract\" method one-way, that service method won't return any result, not " + "even an underlying empty confirmation message. These are fire-and-forget methods that are useful in event-like communication. Specifying a return " + "type therefore does not make sense."; internal const string MessageFormat = "This method can't return any values because it is marked as one-way operation."; internal const string Category = SonarAnalyzer.Common.Category.Reliability; internal const Severity RuleSeverity = Severity.Critical; internal const bool IsActivatedByDefault = true; internal static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, RuleSeverity.ToDiagnosticSeverity(), IsActivatedByDefault, helpLinkUri: DiagnosticId.GetHelpLink(), description: Description); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } } protected override void Initialize(SonarAnalysisContext context) { context.RegisterSyntaxNodeActionInNonGenerated( c => { var methodDeclaration = (MethodDeclarationSyntax)c.Node; var methodSymbol = c.SemanticModel.GetDeclaredSymbol(methodDeclaration); if (methodSymbol == null || methodSymbol.ReturnsVoid) { return; } AttributeData attribute; if (!TryGetOperationContract(methodSymbol, out attribute)) { return; } var asyncPattern = attribute.NamedArguments.FirstOrDefault(na => na.Key == "AsyncPattern").Value.Value as bool?; if (asyncPattern.HasValue && asyncPattern.Value) { return; } var isOneWay = attribute.NamedArguments.FirstOrDefault(na => na.Key == "IsOneWay").Value.Value as bool?; if (isOneWay.HasValue && isOneWay.Value) { c.ReportDiagnostic(Diagnostic.Create(Rule, methodDeclaration.ReturnType.GetLocation())); } }, SyntaxKind.MethodDeclaration); } private static bool TryGetOperationContract(IMethodSymbol methodSymbol, out AttributeData attribute) { attribute = methodSymbol.GetAttributes() .FirstOrDefault(a => a.AttributeClass.Is(KnownType.System_ServiceModel_OperationContractAttribute)); return attribute != null; } } }
lgpl-3.0
kidaa/Awakening-Core3
bin/scripts/object/draft_schematic/droid/navicomputer_6.lua
3290
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_draft_schematic_droid_navicomputer_6 = object_draft_schematic_droid_shared_navicomputer_6:new { templateType = DRAFTSCHEMATIC, customObjectName = "v6 Flight Computer", craftingToolTab = 32, -- (See DraftSchemticImplementation.h) complexity = 25, size = 1, xpType = "crafting_droid_general", xp = 202, assemblySkill = "droid_assembly", experimentingSkill = "droid_experimentation", customizationSkill = "droid_customization", customizationOptions = {}, customizationStringNames = {}, customizationDefaults = {}, ingredientTemplateNames = {"craft_droid_ingredients_n", "craft_droid_ingredients_n", "craft_droid_ingredients_n", "craft_droid_ingredients_n", "craft_droid_ingredients_n"}, ingredientTitleNames = {"primary_frame", "body_shell", "droid_brain", "engine_unit", "sensor_suite"}, ingredientSlotType = {0, 0, 0, 0, 0}, resourceTypes = {"metal", "chemical", "metal", "metal", "metal"}, resourceQuantities = {45, 40, 37, 40, 31}, contribution = {100, 100, 100, 100, 100}, targetTemplate = "object/tangible/droid/navicomputer_6.iff", additionalTemplates = { } } ObjectTemplates:addTemplate(object_draft_schematic_droid_navicomputer_6, "object/draft_schematic/droid/navicomputer_6.iff")
lgpl-3.0
ilpianista/libsystemd-qt
src/ldmanager.h
3804
/* * Copyright (C) 2013 Andrea Scarpino <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ #ifndef LD_MANAGER_H #define LD_MANAGER_H #include <QObject> #include "QtSystemd-export.h" #include "generic-types.h" #include "seat.h" #include "session.h" #include "user.h" /** * This class allows querying the underlying system. * * It is the unique entry point for logind. * * Note that it is implemented as a singleton */ namespace Systemd { namespace Logind { enum Permission { Challenge, Na, No, Yes }; class SDQT_EXPORT Notifier : public QObject { Q_OBJECT Q_SIGNALS: void prepareForSleep(const bool active); void prepareForShutdown(const bool active); void seatNew(const Seat::Ptr &seat); void seatRemoved(const Seat::Ptr &seat); void sessionNew(const Session::Ptr &session); void sessionRemoved(const Session::Ptr &session); void userNew(const User::Ptr &user); void userRemoved(const User::Ptr &user); }; /* * Tests whether the system supports hibernation. */ SDQT_EXPORT Permission canHibernate(); /* * Tests whether the system supports hibernation + suspension. */ SDQT_EXPORT Permission canHybridSleep(); /* * Tests whether the system can be powered off. */ SDQT_EXPORT Permission canPowerOff(); /* * Tests whether the system supports reboot. */ SDQT_EXPORT Permission canReboot(); /* * Tests whether the system supports suspension. */ SDQT_EXPORT Permission canSuspend(); /** * May be used to get a Seat for the given id. */ SDQT_EXPORT Seat::Ptr getSeat(const QString &id); /** * May be used to get a Session for the given id. */ SDQT_EXPORT Session::Ptr getSession(const QString &id); /** * May be used to get a Session for the given process id. */ SDQT_EXPORT Session::Ptr getSessionByPID(const uint &pid); /** * May be used to get a User for the given user id. */ SDQT_EXPORT User::Ptr getUser(const uint &uid); /** * May be used to get a User for the given process id. */ SDQT_EXPORT User::Ptr getUserByPID(const uint &pid); /** * Results in the system being hibernated. */ SDQT_EXPORT void hibernate(const bool interactive); /** * Results in the system being hibernated + suspended. */ SDQT_EXPORT void hybridSleep(const bool interactive); /** * Returns an array with all currently available inhibitors. */ SDQT_EXPORT QList<LoginInhibitor> listInhibitors(); /** * Returns an array with all currently available seats. */ SDQT_EXPORT QList<Seat::Ptr> listSeats(); /** * Returns an array with all currently available sessions. */ SDQT_EXPORT QList<Session::Ptr> listSessions(); /** * Returns an array with all currently available users. */ SDQT_EXPORT QList<User::Ptr> listUsers(); /** * Results in the system being powered off. */ SDQT_EXPORT void powerOff(const bool interactive); /** * Results in the system being rebooted. */ SDQT_EXPORT void reboot(const bool interactive); /** * Results in the system being suspended. */ SDQT_EXPORT void suspend(const bool interactive); SDQT_EXPORT Notifier* notifier(); } } #endif
lgpl-3.0
psi4/psi4
psi4/driver/psifiles.py
10284
# # @BEGIN LICENSE # # Psi4: an open-source quantum chemistry software package # # Copyright (c) 2007-2022 The Psi4 Developers. # # The copyrights for code used from other parties are included in # the corresponding files. # # This file is part of Psi4. # # Psi4 is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, version 3. # # Psi4 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along # with Psi4; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # @END LICENSE # # Do not modify this file! It is auto-generated by the document_psifiles # script, from psi4topdir/psi4/include/psi4/psifiles.h PSIF_OPTKING = 1 # PSIF_GRAD = 11 # geometry optimization, geometry, and gradient; currently is an ASCII file like output.grad PSIF_INTCO = 12 # internal coordinates file, currently is ASCII file like output.intco PSIF_3INDEX = 16 # PSIF_SO_TEI = 33 # PSIF_SO_PK = 34 # PSIF_OEI = 35 # PSIF_SO_ERF_TEI = 36 # PSIF_SO_ERFC_TEI = 37 # PSIF_SO_R12 = 38 # PSIF_SO_R12T1 = 39 # PSIF_DERINFO = 40 # PSIF_SO_PRESORT = 41 # PSIF_CIVECT = 43 # CI vector from DETCI along with string and determinant info PSIF_AO_DGDBX = 44 # B-field derivative AO integrals over GIAO Gaussians -- only bra-ket permutational symmetry holds PSIF_AO_DGDBY = 45 # PSIF_AO_DGDBZ = 46 # PSIF_PSIMRCC_INTEGRALS = 50 # PSIF_PSIMRCC_RESTART = 51 # PSIF_MCSCF = 52 # PSIF_TPDM_HALFTRANS = 53 # PSIF_DETCAS = 60 # PSIF_LIBTRANS_DPD = 61 # libtrans: All transformed integrals in DPD format are sent here by default PSIF_LIBTRANS_A_HT = 62 # libtrans: Alpha half-transformed integrals in DPD format PSIF_LIBTRANS_B_HT = 63 # libtrans: Beta half-transformed integrals in DPD format PSIF_LIBDIIS = 64 # Storage for libdiis PSIF_TPDM_PRESORT = 71 # PSIF_MO_TEI = 72 # PSIF_MO_OPDM = 73 # PSIF_MO_TPDM = 74 # PSIF_MO_LAG = 75 # PSIF_AO_OPDM = 76 # PSIF_AO_OPDM also contains AO Lagrangian PSIF_AO_TPDM = 77 # PSIF_MO_R12 = 79 # PSIF_MO_R12T2 = 80 # PSIF_MO_AA_TEI = 81 # PSIF_MO_BB_TEI = 82 # PSIF_MO_AB_TEI = 83 # PSIF_MO_AA_TPDM = 84 # PSIF_MO_BB_TPDM = 85 # PSIF_MO_AB_TPDM = 86 # PSIF_AA_PRESORT = 87 # AA UHF twopdm presort file PSIF_BB_PRESORT = 88 # BB UHF twopdm presort file PSIF_AB_PRESORT = 89 # AB UHF twopdm presort file PSIF_SO_PKSUPER1 = 92 # PSIF_SO_PKSUPER2 = 93 # PSIF_HALFT0 = 94 # PSIF_HALFT1 = 95 # PSIF_DFSCF_BJ = 97 # B Matrix containing 3-index tensor in AOs with J^-1/2 for use with DF-SCF PSIF_CC_INFO = 100 # PSIF_CC_OEI = 101 # PSIF_CC_AINTS = 102 # PSIF_CC_BINTS = 103 # PSIF_CC_CINTS = 104 # PSIF_CC_DINTS = 105 # PSIF_CC_EINTS = 106 # PSIF_CC_FINTS = 107 # PSIF_CC_DENOM = 108 # PSIF_CC_TAMPS = 109 # PSIF_CC_GAMMA = 110 # PSIF_CC_MISC = 111 # PSIF_CC_HBAR = 112 # PSIF_CC_OEI_NEW = 113 # PSIF_CC_GAMMA_NEW = 114 # PSIF_CC_AINTS_NEW = 115 # PSIF_CC_BINTS_NEW = 116 # PSIF_CC_CINTS_NEW = 117 # PSIF_CC_DINTS_NEW = 118 # PSIF_CC_EINTS_NEW = 119 # PSIF_CC_FINTS_NEW = 120 # PSIF_CC_LAMBDA = 121 # PSIF_CC_RAMPS = 122 # PSIF_CC_LAMPS = 123 # PSIF_CC_LR = 124 # PSIF_CC_DIIS_ERR = 125 # PSIF_CC_DIIS_AMP = 126 # PSIF_CC_TMP = 127 # PSIF_CC_TMP0 = 128 # PSIF_CC_TMP1 = 129 # PSIF_CC_TMP2 = 130 # PSIF_CC_TMP3 = 131 # PSIF_CC_TMP4 = 132 # PSIF_CC_TMP5 = 133 # PSIF_CC_TMP6 = 134 # PSIF_CC_TMP7 = 135 # PSIF_CC_TMP8 = 135 # PSIF_CC_TMP9 = 137 # PSIF_CC_TMP10 = 138 # PSIF_CC_TMP11 = 139 # PSIF_EOM_D = 140 # PSIF_EOM_CME = 141 # PSIF_EOM_Cme = 142 # PSIF_EOM_CMNEF = 143 # PSIF_EOM_Cmnef = 144 # PSIF_EOM_CMnEf = 145 # PSIF_EOM_SIA = 146 # PSIF_EOM_Sia = 147 # PSIF_EOM_SIJAB = 148 # PSIF_EOM_Sijab = 149 # PSIF_EOM_SIjAb = 150 # PSIF_EOM_R = 151 # holds residual PSIF_CC_GLG = 152 # left-hand psi for g.s. parts of cc-density PSIF_CC_GL = 153 # left-hand psi for e.s. parts of cc-density PSIF_CC_GR = 154 # right-hand eigenvector for cc-density PSIF_EOM_TMP1 = 155 # intermediates just for single contractions PSIF_EOM_TMP0 = 156 # temporary copies of density PSIF_EOM_TMP_XI = 157 # intermediates for xi computation PSIF_EOM_XI = 158 # xi = dE/dt amplitudes PSIF_EOM_TMP = 159 # intermediates used more than once PSIF_CC3_HET1 = 160 # [H,e^T1] PSIF_CC3_HC1 = 161 # [H,C1] PSIF_CC3_HC1ET1 = 162 # [[H,e^T1],C1] PSIF_CC3_MISC = 163 # various intermediates needed in CC3 codes PSIF_CC2_HET1 = 164 # [H,e^T1] PSIF_WK_PK = 165 # File to contain wK pre-sorted integrals for PK PSIF_SCF_MOS = 180 # Save SCF orbitals for re-use later as guess, etc. PSIF_DFMP2_AIA = 181 # Unfitted three-index MO ints for DFMP2 PSIF_DFMP2_QIA = 182 # Fitted-three index MO ints for DFMP2 PSIF_ADC = 183 # ADC PSIF_ADC_SEM = 184 # ADC PSIF_SAPT_DIMER = 190 # SAPT Two-Body Dimer PSIF_SAPT_MONOMERA = 191 # SAPT Two-Body Mon A PSIF_SAPT_MONOMERB = 192 # SAPT Two-Body Mon B PSIF_SAPT_AA_DF_INTS = 193 # SAPT AA DF Ints PSIF_SAPT_AB_DF_INTS = 194 # SAPT AB DF Ints PSIF_SAPT_BB_DF_INTS = 195 # SAPT BB DF Ints PSIF_SAPT_AMPS = 196 # SAPT Amplitudes PSIF_SAPT_TEMP = 197 # SAPT Temporary worlds fastest code file PSIF_SAPT_LRINTS = 198 # SAPT0 2-Body linear response LDA integrals PSIF_3B_SAPT_TRIMER = 220 # SAPT Three-Body Trimer PSIF_3B_SAPT_DIMER_AB = 221 # SAPT Three-Body Dimer AB PSIF_3B_SAPT_DIMER_AC = 222 # SAPT Three-Body Dimer AC PSIF_3B_SAPT_DIMER_BC = 223 # SAPT Three-Body Dimer BC PSIF_3B_SAPT_MONOMER_A = 224 # SAPT Three-Body Mon A PSIF_3B_SAPT_MONOMER_B = 225 # SAPT Three-Body Mon B PSIF_3B_SAPT_MONOMER_C = 226 # SAPT Three-Body Mon C PSIF_3B_SAPT_AA_DF_INTS = 227 # PSIF_3B_SAPT_BB_DF_INTS = 228 # PSIF_3B_SAPT_CC_DF_INTS = 229 # PSIF_3B_SAPT_AMPS = 230 # PSIF_DCC_IJAK = 250 # CEPA/CC (ij|ak) PSIF_DCC_IJAK2 = 251 # CEPA/CC (ij|ak) PSIF_DCC_ABCI = 252 # CEPA/CC (ia|bc) PSIF_DCC_ABCI2 = 253 # CEPA/CC (ia|bc) PSIF_DCC_ABCI3 = 254 # CEPA/CC (ia|bc) PSIF_DCC_ABCI4 = 255 # CEPA/CC (ia|bc) PSIF_DCC_ABCI5 = 256 # CEPA/CC (ia|bc) PSIF_DCC_ABCD1 = 257 # CEPA/CC (ab|cd)+ PSIF_DCC_ABCD2 = 258 # CEPA/CC (ab|cd)- PSIF_DCC_IJAB = 259 # CEPA/CC (ij|ab) PSIF_DCC_IAJB = 260 # CEPA/CC (ia|jb) PSIF_DCC_IJKL = 261 # CEPA/CC (ij|kl) PSIF_DCC_OVEC = 262 # CEPA/CC old vectors for diis PSIF_DCC_EVEC = 263 # CEPA/CC error vectors for diis PSIF_DCC_R2 = 264 # CEPA/CC residual PSIF_DCC_TEMP = 265 # CEPA/CC temporary storage PSIF_DCC_T2 = 266 # CEPA/CC t2 amplitudes PSIF_DCC_QSO = 267 # DFCC 3-index integrals PSIF_DCC_SORT_START = 270 # CEPA/CC integral sort starting file number PSIF_SAPT_CCD = 271 # SAPT2+ CCD Utility File PSIF_HESS = 272 # Hessian Utility File PSIF_OCC_DPD = 273 # OCC DPD PSIF_OCC_DENSITY = 274 # OCC Density PSIF_OCC_IABC = 275 # OCC out-of-core <IA|BC> PSIF_DFOCC_INTS = 276 # DFOCC Integrals PSIF_DFOCC_AMPS = 277 # DFOCC Amplitudes PSIF_DFOCC_DENS = 278 # DFOCC PDMs PSIF_DFOCC_IABC = 279 # DFOCC (IA|BC) PSIF_DFOCC_ABIC = 280 # DFOCC <AB|IC> PSIF_DFOCC_MIABC = 281 # DFOCC M_iabc PSIF_DFOCC_TEMP = 282 # DFOCC temporary storage PSIF_SAD = 300 # A SAD file (File for SAD related quantities PSIF_CI_HD_FILE = 350 # DETCI H diagonal PSIF_CI_C_FILE = 351 # DETCI CI coeffs PSIF_CI_S_FILE = 352 # DETCI sigma coeffs PSIF_CI_D_FILE = 353 # DETCI D correction vectors PSIF_DCT_DPD = 400 # DCT DPD handle PSIF_DCT_DENSITY = 401 # DCT density
lgpl-3.0
emyrto/TARDIS
OxyPlot-2014.1.240.1/Documentation/API/OxyPlot.Axes.DateTimeIntervalType.html
2096
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>DateTimeIntervalType Enumeration (OxyPlot.Axes)</title> <meta name="keywords" content="" /> <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body> <h1 id="OxyPlot.Axes.DateTimeIntervalType">DateTimeIntervalType Enumeration</h1> <p>Specifies the date time interval for <a title="DateTimeAxis Class" href="OxyPlot.Axes.DateTimeAxis.html">DateTimeAxis</a>.</p> <p> <strong>Namespace:</strong> <a href="OxyPlot.Axes.html">OxyPlot.Axes</a> <br /> <strong>Assembly: </strong>OxyPlot (in OxyPlot.dll)</p> <h2>Syntax</h2> <pre><code><span class="keyword">public</span> <span class="keyword">enum</span> DateTimeIntervalType : Enum</code></pre> <h2>Members</h2> <table> <tr> <th>Name</th> <th>Description</th> </tr> <tr> <td>Auto</td> <td>Automatically determine interval.</td> </tr> <tr> <td>Days</td> <td>Interval type is days.</td> </tr> <tr> <td>Hours</td> <td>Interval type is hours.</td> </tr> <tr> <td>Manual</td> <td>Manual definition of intervals.</td> </tr> <tr> <td>Milliseconds</td> <td>Interval type is milliseconds.</td> </tr> <tr> <td>Minutes</td> <td>Interval type is minutes.</td> </tr> <tr> <td>Months</td> <td>Interval type is months.</td> </tr> <tr> <td>Seconds</td> <td>Interval type is seconds.</td> </tr> <tr> <td>Weeks</td> <td>Interval type is weeks.</td> </tr> <tr> <td>Years</td> <td>Interval type is years.</td> </tr> </table> <footer><div class="footer">OxyPlot version 2014.1.240.1 | <a href="http://oxyplot.org">oxyplot.org</a> | <a href="index.html">Index</a></div></footer> </body> </html>
lgpl-3.0
Fiware/i2nd.KIARA
src/test/java/org/fiware/kiara/serialization/types/IDLText.java
1565
/* KIARA - Middleware for efficient and QoS/Security-aware invocation of services and exchange of messages * * Copyright (C) 2014 Proyectos y Sistemas de Mantenimiento S.L. (eProsima) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * * * @file IDLText.java * This file contains IDL text. * * This file was generated by using the tool Kiaragen. * */ package org.fiware.kiara.serialization.types; /** * Class containing the IDL text for all the services. * * @author Kiaragen tool. * */ public final class IDLText { public static final String contents = "# 1 \"src/test/resources/idl/enumeration.idl\"\n# 1 \"<built-in>\"\n# 1 \"<command-line>\"\n# 1 \"/usr/include/stdc-predef.h\" 1 3 4\n# 1 \"<command-line>\" 2\n# 1 \"src/test/resources/idl/enumeration.idl\"\nenum GenericEnumeration {\n first_val,\n second_val,\n third_val\n};\n"; private IDLText() { throw new UnsupportedOperationException(); } }
lgpl-3.0
neeil1990/almamed
wa-apps/shop/lib/config/site.php
14862
<?php wa('shop'); $type_model = new shopTypeModel(); $types = $type_model->select('id,name')->fetchAll('id', true); $currencies = wa('shop')->getConfig()->getCurrencies(); foreach ($currencies as &$c) { $c = $c['title']; } unset($c); $payment_items = $shipping_items = array(); foreach (shopHelper::getPaymentMethods() as $p) { $payment_items[$p['id']] = $p['name']; } foreach (shopHelper::getShippingMethods() as $s) { $shipping_items[$s['id']] = $s['name']; } $stock_model = new shopStockModel(); $public_stocks = $stocks = array(); foreach(shopHelper::getStocks() as $stock_id => $s) { $stocks[$stock_id] = $s['name']; if ($s['public']) { $public_stocks[$stock_id] = $s['name']; } } return array( 'params' => array( _w('Homepage'), 'title' => array( 'name' => _w('Homepage title <title>'), 'type' => 'input', ), 'meta_keywords' => array( 'name' => _w('Homepage META Keywords'), 'type' => 'input' ), 'meta_description' => array( 'name' => _w('Homepage META Description'), 'type' => 'textarea' ), 'og_title' => array( 'name' => _w('Social sharing Title (og:title)'), 'type' => 'input', 'description' => _w('For detailed information on Open Graph parameters and examples please refer to <a href="http://ogp.me" target="_blank">ogp.me</a>') ), 'og_image' => array( 'name' => _w('Social sharing Image URL (og:image)'), 'type' => 'input' ), 'og_video' => array( 'name' => _w('Social sharing Video URL (og:video)'), 'type' => 'input' ), 'og_description' => array( 'name' => _w('Social sharing Description (og:description)'), 'type' => 'textarea' ), 'og_type' => array( 'name' => _w('Social sharing Type (og:type)'), 'type' => 'input', 'description' => _w('E.g. <b>website</b>.').' '._w('For detailed information on Open Graph parameters and examples please refer to <a href="http://ogp.me" target="_blank">ogp.me</a>') ), _w('Products'), 'url_type' => array( 'name' => _w('URLs'), 'type' => 'radio_select', 'items' => array( 2 => array( 'name' => _w('Natural'), 'description' => _w('<br>Product URLs: /<strong>category-name/subcategory-name/product-name/</strong><br>Category URLs: /<strong>category-name/subcategory-name/</strong>'), ), 0 => array( 'name' => _w('Mixed'), 'description' => _w('<br>Product URLs: /<strong>product-name/</strong><br>Category URLs: /category/<strong>category-name/subcategory-name/subcategory-name/...</strong>'), ), 1 => array( 'name' => _w('Plain').' (WebAsyst Shop-Script)', 'description' => _w('<br>Product URLs: /product/<strong>product-name/</strong><br>Category URLs: /category/<strong>category-name/</strong>'), ), ) ), 'type_id' => array( 'name' => _w('Published products'), 'type' => 'radio_checkbox', 'items' => array( 0 => array( 'name' => _w('All product types'), 'description' => '', ), array ( 'name' => _w('Selected only'), 'description' => '', 'items' => $types ) ) ), 'currency' => array( 'name' => _w('Default currency'), 'type' => 'select', 'items' => $currencies ), 'stock_id' => array( 'name' => _w('Default stock'), 'description' => _w('Select primary stock to which this storefront is associated with. When you process orders from placed via this storefront, selected stock will be automatically offered for product stock update.'), 'type' => 'select', 'items' => $stocks ), 'public_stocks' => array( 'name' => _w('Visible stocks'), 'type' => 'radio_checkbox', 'items' => array( 0 => array( 'name' => _w('All public stocks'), 'description' => '', ), array( 'name' => _w('Selected only'), 'description' => '', 'items' => $public_stocks, ) ) ), 'drop_out_of_stock' => array( 'name' => _w('Out-of-stock products'), 'type' => 'radio_select', 'items' => array( 1 => array( 'name' => _w('Force drop out-of-stock products to the bottom of all lists'), 'description' => _w('When enabled, out-of-stock products will be automatically dropped to the bottom of every product list on this storefront, e.g. in product search results, category product filtering, and more.'), ), 2 => array( 'name' => _w('Hide out-of-stock products'), 'description' => _w('Out-of-stock products will remain published, but will be automatically hidden from all product lists on this storefront, e.g. product search results, category product filtering, and others.') ), 0 => array( 'name' => _w('Display as is'), 'description' => _w('All product lists will contain both in-stock and out-of-stock products.'), ) ) ), _w('Checkout'), 'payment_id' => array( 'name' => _w('Payment options'), 'type' => 'radio_checkbox', 'items' => array( 0 => array( 'name' => _w('All available payment options'), 'description' => '', ), array ( 'name' => _w('Selected only'), 'description' => '', 'items' => $payment_items ) ) ), 'shipping_id' => array( 'name' => _w('Shipping options'), 'type' => 'radio_checkbox', 'items' => array( 0 => array( 'name' => _w('All available shipping options'), 'description' => '', ), array ( 'name' => _w('Selected only'), 'description' => '', 'items' => $shipping_items ) ) ), 'ssl' => array( 'name' => _w('Use HTTPS for checkout and personal accounts'), 'description' => _w('Automatically redirect to secure https:// mode for checkout (/checkout/) and personal account (/my/) pages of your online storefront. Make sure you have valid SSL certificate installed for this domain name before enabling this option.'), 'type' => 'checkbox' ) ), 'vars' => array( 'category.html' => array( '$category.id' => '', '$category.name' => '', '$category.parent_id' => '', '$category.description' => '', ), 'index.html' => array( '$content' => _w('Core content loaded according to the requested resource: product, category, search results, static page, etc.'), ), 'product.html' => array( '$product.id' => _w('Product id. Other elements of <em>$product</em> available in this template are listed below'), '$product.name' => _w('Product name'), '$product.summary' => _w('Product summary (brief description)'), '$product.description' => _w('Product description'), '$product.rating' => _w('Product average rating (float, 0 to 5)'), '$product.skus' => _w('Array of product SKUs'), '$product.images' => _w('Array of product images'), '$product.categories' => _w('Array of product categories'), '$product.tags' => _w('Array of product tags'), '$product.pages' => _w('Array of product static info pages'), '$product.features' => _w('Array of product features and values'), '$reviews' => _w('Array of product reviews'), '$services' => _w('Array of services available for this product'), /* '$category' => _w('Conditional! Available only if current context of photo is album. Below are describe keys of this param'), '$category.id' => '', '$category.name' => '', '$category.parent_id' => '', '$category.description' => '', */ ), 'search.html' => array( '$title' => '' ), 'list-table.html' => array( '$products' => array( '$id' => '', '...' => _w('Available vars are listed in the cheat sheet for product.html template') ) ), 'list-thumbs.html' => array( '$products' => array( '$id' => '', '...' => _w('Available vars are listed in the cheat sheet for product.html template') ) ), '$wa' => array( '$wa->shop->badgeHtml(<em>$product.code</em>)' => _w('Displays badge of the specified product (<em>$product</em> object)'), '$wa->shop->cart()' => _w('Returns current cart object'), '$wa->shop->categories(<em>$id = 0, $depth = null, $tree = false, $params = false, $route = null</em>)' => _w('Returns array of subcategories of the specified category. Omit parent category for the entire array of categories'), '$wa->shop->category(<em>$category_id</em>)' => _w('Returns category object by <em>$category_id</em>'), '<em>$category</em>.params()' => _w('Array of custom category parameters'), '$wa->shop->compare()' => _w('Returns array of products currently added into a comparison list'), '$wa->shop->crossSelling(<em>$product_id</em>, <em>$limit = 5</em>, <em>$available_only = false</em>)' => _w('Returns array of cross-sell products.<em>$product_id</em> can be either a number (ID of the specified base product) or an array of products IDs').'. '._w('Setting <em>$available_only = true</em> will automatically exclude all out-of-stock products from the return'), '$wa->shop->currency()' => _w('Returns current currency object'), '$wa->shop->product(<em>$product_id</em>)' => _w('Returns product object by <em>$product_id</em>').'<br><br> '. '$product-><strong>productUrl()</strong>: '._w('Returns valid product page URL').'<br>'. '$product-><strong>upSelling</strong>(<em>$limit = 5</em>, <em>$available_only = false</em>):'._w('Returns array of upsell products for the specified product').'. '._w('Setting <em>$available_only = true</em> will automatically exclude all out-of-stock products from the return').'<br>'. '$product-><strong>crossSelling</strong>(<em>$limit = 5</em>, <em>$available_only = false</em>):'._w('Returns array of upsell products for the specified product').'. '._w('Setting <em>$available_only = true</em> will automatically exclude all out-of-stock products from the return').'<br><br>'. '$product.<strong>id</strong>: '._w('Product id. Other elements of <em>$product</em> available in this template are listed below').'<br>'. '$product.<strong>name</strong>: '._w('Product name').'<br>'. '$product.<strong>description</strong>: '._w('Product summary (brief description)').'<br>'. '$product.<strong>rating</strong>: '._w('Product average rating (float, 0 to 5)').'<br>'. '$product.<strong>skus</strong>: '._w('Array of product SKUs').'<br>'. '$product.<strong>images</strong>: '._w('Array of product images').'<br>'. '$product.<strong>categories</strong>: '._w('Array of product categories').'<br>'. '$product.<strong>tags</strong>: '._w('Array of product tags').'<br>'. '$product.<strong>pages</strong>: '._w('Array of product static info pages').'<br>'. '$product.<strong>features</strong>: '._w('Array of product features and values').'<br>'. '$product.<strong>reviews</strong>: '._w('Array of product reviews').'<br>', '$wa->shop->productImgHtml($product, $size, $attributes = array())' => _w('Displays specified $product object’s default image'), '$wa->shop->productImgUrl($product, $size)' => _w('Returns specified $product default image URL'), '$wa->shop->products(<em>search_conditions</em>[,<em>offset</em>[, <em>limit</em>[, <em>options</em>]]])' => _w('Returns array of products by search criteria, e.g. <em>"tag/new"</em>, <em>"category/12"</em>, <em>"id/1,5,7"</em>, <em>"set/1"</em>, or <em>"*"</em> for all products list.').' '._w('Optional <em>options</em> parameter indicates additional product options, e.g. <em>["params" => 1]</em> to include product custom parameter values into the output.'), '$wa->shop->productsCount(<em>search_conditions</em>)' => _w('Returns number of products matching specified search conditions, e.g. <em>"tag/new"</em>, <em>"category/12"</em>, <em>"id/1,5,7"</em>, <em>"set/1"</em>, or <em>"*"</em> for all products list.'), '$wa->shop->productSet(<em>set_id</em>)' => _w('Returns array of products from the specified set.').' '._w('Optional <em>options</em> parameter indicates additional product options, e.g. <em>["params" => 1]</em> to include product custom parameter values into the output.'), '$wa->shop->ratingHtml(<em>$rating, $size = 10, $show_when_zero = false</em>)' => _w('Displays 1—5 stars rating. $size indicates icon size and can be either 10 or 16'), '$wa->shop->features(<em>product_ids</em>)' => _w('Returns array of feature values for the specified list of products'), '$wa->shop->reviews([<em>$limit = 10</em>])' => _w('Returns array of latest product reviews'), '$wa->shop->stocks()' => _w('Returns array of stocks'), '$wa->shop->settings("<em>option_id</em>")' => _w('Returns store’s general setting option by <em>option_id</em>, e.g. "name", "email", "country"'), '$wa->shop->themePath("<em>theme_id</em>")' => _ws('Returns path to theme folder by <em>theme_id</em>'), ), ), 'blocks' => array( ), );
lgpl-3.0
relsi/DaVinci
app/core/gimpimage-snap.c
23301
/* GIMP - The GNU Image Manipulation Program * Copyright (C) 1995 Spencer Kimball and Peter Mattis * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "config.h" #include <gdk-pixbuf/gdk-pixbuf.h> #include <gegl.h> #include "libgimpmath/gimpmath.h" #include "core-types.h" #include "gimp.h" #include "gimpgrid.h" #include "gimpguide.h" #include "gimpimage.h" #include "gimpimage-grid.h" #include "gimpimage-guides.h" #include "gimpimage-snap.h" #include "vectors/gimpstroke.h" #include "vectors/gimpvectors.h" #include "gimp-intl.h" static gboolean gimp_image_snap_distance (const gdouble unsnapped, const gdouble nearest, const gdouble epsilon, gdouble *mindist, gdouble *target); /* public functions */ gboolean gimp_image_snap_x (GimpImage *image, gdouble x, gdouble *tx, gdouble epsilon_x, gboolean snap_to_guides, gboolean snap_to_grid, gboolean snap_to_canvas) { gdouble mindist = G_MAXDOUBLE; gboolean snapped = FALSE; g_return_val_if_fail (GIMP_IS_IMAGE (image), FALSE); g_return_val_if_fail (tx != NULL, FALSE); *tx = x; if (! gimp_image_get_guides (image)) snap_to_guides = FALSE; if (! gimp_image_get_grid (image)) snap_to_grid = FALSE; if (! (snap_to_guides || snap_to_grid || snap_to_canvas)) return FALSE; if (x < -epsilon_x || x >= (gimp_image_get_width (image) + epsilon_x)) return FALSE; if (snap_to_guides) { GList *list; for (list = gimp_image_get_guides (image); list; list = g_list_next (list)) { GimpGuide *guide = list->data; gint position = gimp_guide_get_position (guide); if (gimp_guide_get_orientation (guide) == GIMP_ORIENTATION_VERTICAL) { snapped |= gimp_image_snap_distance (x, position, epsilon_x, &mindist, tx); } } } if (snap_to_grid) { GimpGrid *grid = gimp_image_get_grid (image); gdouble xspacing; gdouble xoffset; gdouble i; gimp_grid_get_spacing (grid, &xspacing, NULL); gimp_grid_get_offset (grid, &xoffset, NULL); /* the snap-to-grid part could probably be rewritten */ while (xoffset > xspacing) xoffset -= xspacing; for (i = xoffset; i <= gimp_image_get_width (image); i += xspacing) { if (i < 0) continue; snapped |= gimp_image_snap_distance (x, i, epsilon_x, &mindist, tx); } } if (snap_to_canvas) { snapped |= gimp_image_snap_distance (x, 0, epsilon_x, &mindist, tx); snapped |= gimp_image_snap_distance (x, gimp_image_get_width (image), epsilon_x, &mindist, tx); } return snapped; } gboolean gimp_image_snap_y (GimpImage *image, gdouble y, gdouble *ty, gdouble epsilon_y, gboolean snap_to_guides, gboolean snap_to_grid, gboolean snap_to_canvas) { gdouble mindist = G_MAXDOUBLE; gboolean snapped = FALSE; g_return_val_if_fail (GIMP_IS_IMAGE (image), FALSE); g_return_val_if_fail (ty != NULL, FALSE); *ty = y; if (! gimp_image_get_guides (image)) snap_to_guides = FALSE; if (! gimp_image_get_grid (image)) snap_to_grid = FALSE; if (! (snap_to_guides || snap_to_grid || snap_to_canvas)) return FALSE; if (y < -epsilon_y || y >= (gimp_image_get_height (image) + epsilon_y)) return FALSE; if (snap_to_guides) { GList *list; for (list = gimp_image_get_guides (image); list; list = g_list_next (list)) { GimpGuide *guide = list->data; gint position = gimp_guide_get_position (guide); if (gimp_guide_get_orientation (guide) == GIMP_ORIENTATION_HORIZONTAL) { snapped |= gimp_image_snap_distance (y, position, epsilon_y, &mindist, ty); } } } if (snap_to_grid) { GimpGrid *grid = gimp_image_get_grid (image); gdouble yspacing; gdouble yoffset; gdouble i; gimp_grid_get_spacing (grid, NULL, &yspacing); gimp_grid_get_offset (grid, NULL, &yoffset); while (yoffset > yspacing) yoffset -= yspacing; for (i = yoffset; i <= gimp_image_get_height (image); i += yspacing) { if (i < 0) continue; snapped |= gimp_image_snap_distance (y, i, epsilon_y, &mindist, ty); } } if (snap_to_canvas) { snapped |= gimp_image_snap_distance (y, 0, epsilon_y, &mindist, ty); snapped |= gimp_image_snap_distance (y, gimp_image_get_height (image), epsilon_y, &mindist, ty); } return snapped; } gboolean gimp_image_snap_point (GimpImage *image, gdouble x, gdouble y, gdouble *tx, gdouble *ty, gdouble epsilon_x, gdouble epsilon_y, gboolean snap_to_guides, gboolean snap_to_grid, gboolean snap_to_canvas, gboolean snap_to_vectors) { gdouble mindist_x = G_MAXDOUBLE; gdouble mindist_y = G_MAXDOUBLE; gboolean snapped = FALSE; g_return_val_if_fail (GIMP_IS_IMAGE (image), FALSE); g_return_val_if_fail (tx != NULL, FALSE); g_return_val_if_fail (ty != NULL, FALSE); *tx = x; *ty = y; if (! gimp_image_get_guides (image)) snap_to_guides = FALSE; if (! gimp_image_get_grid (image)) snap_to_grid = FALSE; if (! gimp_image_get_active_vectors (image)) snap_to_vectors = FALSE; if (! (snap_to_guides || snap_to_grid || snap_to_canvas || snap_to_vectors)) return FALSE; if (x < -epsilon_x || x >= (gimp_image_get_width (image) + epsilon_x) || y < -epsilon_y || y >= (gimp_image_get_height (image) + epsilon_y)) { return FALSE; } if (snap_to_guides) { GList *list; for (list = gimp_image_get_guides (image); list; list = g_list_next (list)) { GimpGuide *guide = list->data; gint position = gimp_guide_get_position (guide); switch (gimp_guide_get_orientation (guide)) { case GIMP_ORIENTATION_HORIZONTAL: snapped |= gimp_image_snap_distance (y, position, epsilon_y, &mindist_y, ty); break; case GIMP_ORIENTATION_VERTICAL: snapped |= gimp_image_snap_distance (x, position, epsilon_x, &mindist_x, tx); break; default: break; } } } if (snap_to_grid) { GimpGrid *grid = gimp_image_get_grid (image); gdouble xspacing, yspacing; gdouble xoffset, yoffset; gdouble i; gimp_grid_get_spacing (grid, &xspacing, &yspacing); gimp_grid_get_offset (grid, &xoffset, &yoffset); while (xoffset > xspacing) xoffset -= xspacing; while (yoffset > yspacing) yoffset -= yspacing; for (i = xoffset; i <= gimp_image_get_width (image); i += xspacing) { if (i < 0) continue; snapped |= gimp_image_snap_distance (x, i, epsilon_x, &mindist_x, tx); } for (i = yoffset; i <= gimp_image_get_height (image); i += yspacing) { if (i < 0) continue; snapped |= gimp_image_snap_distance (y, i, epsilon_y, &mindist_y, ty); } } if (snap_to_canvas) { snapped |= gimp_image_snap_distance (x, 0, epsilon_x, &mindist_x, tx); snapped |= gimp_image_snap_distance (x, gimp_image_get_width (image), epsilon_x, &mindist_x, tx); snapped |= gimp_image_snap_distance (y, 0, epsilon_y, &mindist_y, ty); snapped |= gimp_image_snap_distance (y, gimp_image_get_height (image), epsilon_y, &mindist_y, ty); } if (snap_to_vectors) { GimpVectors *vectors = gimp_image_get_active_vectors (image); GimpStroke *stroke = NULL; GimpCoords coords = { 0, 0, 0, 0, 0 }; coords.x = x; coords.y = y; while ((stroke = gimp_vectors_stroke_get_next (vectors, stroke))) { GimpCoords nearest; if (gimp_stroke_nearest_point_get (stroke, &coords, 1.0, &nearest, NULL, NULL, NULL) >= 0) { snapped |= gimp_image_snap_distance (x, nearest.x, epsilon_x, &mindist_x, tx); snapped |= gimp_image_snap_distance (y, nearest.y, epsilon_y, &mindist_y, ty); } } } return snapped; } gboolean gimp_image_snap_rectangle (GimpImage *image, gdouble x1, gdouble y1, gdouble x2, gdouble y2, gdouble *tx1, gdouble *ty1, gdouble epsilon_x, gdouble epsilon_y, gboolean snap_to_guides, gboolean snap_to_grid, gboolean snap_to_canvas, gboolean snap_to_vectors) { gdouble nx, ny; gdouble mindist_x = G_MAXDOUBLE; gdouble mindist_y = G_MAXDOUBLE; gdouble x_center = (x1 + x2) / 2.0; gdouble y_center = (y1 + y2) / 2.0; gboolean snapped = FALSE; g_return_val_if_fail (GIMP_IS_IMAGE (image), FALSE); g_return_val_if_fail (tx1 != NULL, FALSE); g_return_val_if_fail (ty1 != NULL, FALSE); *tx1 = x1; *ty1 = y1; if (! gimp_image_get_guides (image)) snap_to_guides = FALSE; if (! gimp_image_get_grid (image)) snap_to_grid = FALSE; if (! gimp_image_get_active_vectors (image)) snap_to_vectors = FALSE; if (! (snap_to_guides || snap_to_grid || snap_to_canvas || snap_to_vectors)) return FALSE; /* left edge */ if (gimp_image_snap_x (image, x1, &nx, MIN (epsilon_x, mindist_x), snap_to_guides, snap_to_grid, snap_to_canvas)) { mindist_x = ABS (nx - x1); *tx1 = nx; snapped = TRUE; } /* right edge */ if (gimp_image_snap_x (image, x2, &nx, MIN (epsilon_x, mindist_x), snap_to_guides, snap_to_grid, snap_to_canvas)) { mindist_x = ABS (nx - x2); *tx1 = RINT (x1 + (nx - x2)); snapped = TRUE; } /* center, vertical */ if (gimp_image_snap_x (image, x_center, &nx, MIN (epsilon_x, mindist_x), snap_to_guides, snap_to_grid, snap_to_canvas)) { mindist_x = ABS (nx - x_center); *tx1 = RINT (x1 + (nx - x_center)); snapped = TRUE; } /* top edge */ if (gimp_image_snap_y (image, y1, &ny, MIN (epsilon_y, mindist_y), snap_to_guides, snap_to_grid, snap_to_canvas)) { mindist_y = ABS (ny - y1); *ty1 = ny; snapped = TRUE; } /* bottom edge */ if (gimp_image_snap_y (image, y2, &ny, MIN (epsilon_y, mindist_y), snap_to_guides, snap_to_grid, snap_to_canvas)) { mindist_y = ABS (ny - y2); *ty1 = RINT (y1 + (ny - y2)); snapped = TRUE; } /* center, horizontal */ if (gimp_image_snap_y (image, y_center, &ny, MIN (epsilon_y, mindist_y), snap_to_guides, snap_to_grid, snap_to_canvas)) { mindist_y = ABS (ny - y_center); *ty1 = RINT (y1 + (ny - y_center)); snapped = TRUE; } if (snap_to_vectors) { GimpVectors *vectors = gimp_image_get_active_vectors (image); GimpStroke *stroke = NULL; GimpCoords coords1 = GIMP_COORDS_DEFAULT_VALUES; GimpCoords coords2 = GIMP_COORDS_DEFAULT_VALUES; while ((stroke = gimp_vectors_stroke_get_next (vectors, stroke))) { GimpCoords nearest; gdouble dist; /* top edge */ coords1.x = x1; coords1.y = y1; coords2.x = x2; coords2.y = y1; if (gimp_stroke_nearest_tangent_get (stroke, &coords1, &coords2, 1.0, &nearest, NULL, NULL, NULL) >= 0) { snapped |= gimp_image_snap_distance (y1, nearest.y, epsilon_y, &mindist_y, ty1); } if (gimp_stroke_nearest_intersection_get (stroke, &coords1, &coords2, 1.0, &nearest, NULL, NULL, NULL) >= 0) { snapped |= gimp_image_snap_distance (x1, nearest.x, epsilon_x, &mindist_x, tx1); } if (gimp_stroke_nearest_intersection_get (stroke, &coords2, &coords1, 1.0, &nearest, NULL, NULL, NULL) >= 0) { dist = ABS (nearest.x - x2); if (dist < MIN (epsilon_x, mindist_x)) { mindist_x = dist; *tx1 = RINT (x1 + (nearest.x - x2)); snapped = TRUE; } } /* bottom edge */ coords1.x = x1; coords1.y = y2; coords2.x = x2; coords2.y = y2; if (gimp_stroke_nearest_tangent_get (stroke, &coords1, &coords2, 1.0, &nearest, NULL, NULL, NULL) >= 0) { dist = ABS (nearest.y - y2); if (dist < MIN (epsilon_y, mindist_y)) { mindist_y = dist; *ty1 = RINT (y1 + (nearest.y - y2)); snapped = TRUE; } } if (gimp_stroke_nearest_intersection_get (stroke, &coords1, &coords2, 1.0, &nearest, NULL, NULL, NULL) >= 0) { snapped |= gimp_image_snap_distance (x1, nearest.x, epsilon_x, &mindist_x, tx1); } if (gimp_stroke_nearest_intersection_get (stroke, &coords2, &coords1, 1.0, &nearest, NULL, NULL, NULL) >= 0) { dist = ABS (nearest.x - x2); if (dist < MIN (epsilon_x, mindist_x)) { mindist_x = dist; *tx1 = RINT (x1 + (nearest.x - x2)); snapped = TRUE; } } /* left edge */ coords1.x = x1; coords1.y = y1; coords2.x = x1; coords2.y = y2; if (gimp_stroke_nearest_tangent_get (stroke, &coords1, &coords2, 1.0, &nearest, NULL, NULL, NULL) >= 0) { snapped |= gimp_image_snap_distance (x1, nearest.x, epsilon_x, &mindist_x, tx1); } if (gimp_stroke_nearest_intersection_get (stroke, &coords1, &coords2, 1.0, &nearest, NULL, NULL, NULL) >= 0) { snapped |= gimp_image_snap_distance (y1, nearest.y, epsilon_y, &mindist_y, ty1); } if (gimp_stroke_nearest_intersection_get (stroke, &coords2, &coords1, 1.0, &nearest, NULL, NULL, NULL) >= 0) { dist = ABS (nearest.y - y2); if (dist < MIN (epsilon_y, mindist_y)) { mindist_y = dist; *ty1 = RINT (y1 + (nearest.y - y2)); snapped = TRUE; } } /* right edge */ coords1.x = x2; coords1.y = y1; coords2.x = x2; coords2.y = y2; if (gimp_stroke_nearest_tangent_get (stroke, &coords1, &coords2, 1.0, &nearest, NULL, NULL, NULL) >= 0) { dist = ABS (nearest.x - x2); if (dist < MIN (epsilon_x, mindist_x)) { mindist_x = dist; *tx1 = RINT (x1 + (nearest.x - x2)); snapped = TRUE; } } if (gimp_stroke_nearest_intersection_get (stroke, &coords1, &coords2, 1.0, &nearest, NULL, NULL, NULL) >= 0) { snapped |= gimp_image_snap_distance (y1, nearest.y, epsilon_y, &mindist_y, ty1); } if (gimp_stroke_nearest_intersection_get (stroke, &coords2, &coords1, 1.0, &nearest, NULL, NULL, NULL) >= 0) { dist = ABS (nearest.y - y2); if (dist < MIN (epsilon_y, mindist_y)) { mindist_y = dist; *ty1 = RINT (y1 + (nearest.y - y2)); snapped = TRUE; } } /* center */ coords1.x = x_center; coords1.y = y_center; if (gimp_stroke_nearest_point_get (stroke, &coords1, 1.0, &nearest, NULL, NULL, NULL) >= 0) { if (gimp_image_snap_distance (x_center, nearest.x, epsilon_x, &mindist_x, &nx)) { mindist_x = ABS (nx - x_center); *tx1 = RINT (x1 + (nx - x_center)); snapped = TRUE; } if (gimp_image_snap_distance (y_center, nearest.y, epsilon_y, &mindist_y, &ny)) { mindist_y = ABS (ny - y_center); *ty1 = RINT (y1 + (ny - y_center)); snapped = TRUE; } } } } return snapped; } /* private functions */ /** * gimp_image_snap_distance: * @unsnapped: One coordinate of the unsnapped position * @nearest: One coordinate of a snapping position candidate * @epsilon: The snapping threshold * @mindist: The distance to the currently closest snapping target * @target: The currently closest snapping target * * Finds out if snapping occurs from position to a snapping candidate * and sets the target accordingly. * * Return value: %TRUE if snapping occurred, %FALSE otherwise */ static gboolean gimp_image_snap_distance (const gdouble unsnapped, const gdouble nearest, const gdouble epsilon, gdouble *mindist, gdouble *target) { const gdouble dist = ABS (nearest - unsnapped); if (dist < MIN (epsilon, *mindist)) { *mindist = dist; *target = nearest; return TRUE; } return FALSE; }
lgpl-3.0
Esteemed-Innovation/Flaxbeards-Steam-Power
old/main/java/eiteam/esteemedinnovation/transport/fluid/screw/InputOnlyFluidHandler.java
966
package eiteam.esteemedinnovation.transport.fluid.screw; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; import net.minecraftforge.fluids.capability.IFluidHandler; import net.minecraftforge.fluids.capability.IFluidTankProperties; import javax.annotation.Nullable; public class InputOnlyFluidHandler implements IFluidHandler { private final FluidTank tank; InputOnlyFluidHandler(FluidTank tank) { this.tank = tank; } @Override public IFluidTankProperties[] getTankProperties() { return tank.getTankProperties(); } @Override public int fill(FluidStack resource, boolean doFill) { return tank.fill(resource, doFill); } @Nullable @Override public FluidStack drain(FluidStack resource, boolean doDrain) { return null; } @Nullable @Override public FluidStack drain(int maxDrain, boolean doDrain) { return null; } }
lgpl-3.0
cubem2013/reservation2013
_package/rb/modules/bbs/var/var.www.php
813
<?php $d['bbs']['layout'] = ""; $d['bbs']['skin'] = "_pc/list02"; $d['bbs']['m_skin'] = ""; $d['bbs']['c_skin'] = ""; $d['bbs']['c_mskin'] = ""; $d['bbs']['c_hidden'] = ""; $d['bbs']['c_open'] = ""; $d['bbs']['perm_g_list'] = ""; $d['bbs']['perm_g_view'] = ""; $d['bbs']['perm_g_write'] = ""; $d['bbs']['perm_g_down'] = ""; $d['bbs']['perm_l_list'] = "0"; $d['bbs']['perm_l_view'] = "0"; $d['bbs']['perm_l_write'] = "1"; $d['bbs']['perm_l_down'] = "1"; $d['bbs']['admin'] = ""; $d['bbs']['hitcount'] = "0"; $d['bbs']['recnum'] = "20"; $d['bbs']['sbjcut'] = "40"; $d['bbs']['newtime'] = "24"; $d['bbs']['rss'] = ""; $d['bbs']['sosokmenu'] = ""; $d['bbs']['point1'] = "0"; $d['bbs']['point2'] = "0"; $d['bbs']['point3'] = "0"; $d['bbs']['display'] = ""; $d['bbs']['hidelist'] = ""; $d['bbs']['snsconnect'] = "0"; ?>
lgpl-3.0
SoftwareEngineeringToolDemos/FSE-2011-EvoSuite
runtime/src/main/java/org/evosuite/runtime/mock/EvoSuiteMock.java
955
/** * Copyright (C) 2010-2015 Gordon Fraser, Andrea Arcuri and EvoSuite * contributors * * This file is part of EvoSuite. * * EvoSuite is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser Public License as published by the * Free Software Foundation, either version 3.0 of the License, or (at your * option) any later version. * * EvoSuite 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 Public License for more details. * * You should have received a copy of the GNU Lesser Public License along * with EvoSuite. If not, see <http://www.gnu.org/licenses/>. */ package org.evosuite.runtime.mock; /** * This interface is used to mark a class as an environment mock for a Java API class. * * @author arcuri * */ public interface EvoSuiteMock { }
lgpl-3.0
lamastex/scalable-data-science
db/week1/01_introduction/002_loginToDatabricks.md
6185
// Databricks notebook source exported at Fri, 17 Jun 2016 03:29:41 UTC # [Scalable Data Science](http://www.math.canterbury.ac.nz/~r.sainudiin/courses/ScalableDataScience/) ### prepared by [Raazesh Sainudiin](https://nz.linkedin.com/in/raazesh-sainudiin-45955845) and [Sivanand Sivaram](https://www.linkedin.com/in/sivanand) *supported by* [![](https://raw.githubusercontent.com/raazesh-sainudiin/scalable-data-science/master/images/databricks_logoTM_200px.png)](https://databricks.com/) and [![](https://raw.githubusercontent.com/raazesh-sainudiin/scalable-data-science/master/images/AWS_logoTM_200px.png)](https://www.awseducate.com/microsite/CommunitiesEngageHome) The [html source url](https://raw.githubusercontent.com/raazesh-sainudiin/scalable-data-science/master/db/week1/01_introduction/002_loginToDatabricks.html) of this databricks notebook and its recorded Uji ![Image of Uji, Dogen's Time-Being](https://raw.githubusercontent.com/raazesh-sainudiin/scalable-data-science/master/images/UjiTimeBeingDogen.png "uji"): [![sds/uji/week1/01_introduction/001_whySpark](http://img.youtube.com/vi/O8JbxgPpAU8/0.jpg)](https://www.youtube.com/v/O8JbxgPpAU8?rel=0&autoplay=1&modestbranding=1&start=3330&end=4511) # Outline ### I. 21 Easy Steps for Sharing your AWS Educate Credits * [Workspace -> scalable-data-science -> xtraResources -> awsEducate -> sharing (relative to 'Workspace' link!)](/#workspace/scalable-data-science/xtraResources/awsEducate/sharing) * If you are not in `*.cloud.databricks` or the above link is useless then go to [html here](http://www.math.canterbury.ac.nz/~r.sainudiin/courses/ScalableDataScience/2016/S1/xtraResources/awsEducate/sharing.html). ### II. 7 Steps to the Databricks Cloud ### III. Essentials of the Databricks Cloud ## I. Contributing your AWS credits to the course's databricks cluster. Paul, add the steps for AWS credit sharing here. ## II. 7 Steps to the Databricks Cloud ### Step 1: go to [http://www.math.canterbury.ac.nz/databricks](http://www.math.canterbury.ac.nz/databricks) and login using your email address and temporary password given to you in person (now). ![](https://raw.githubusercontent.com/raazesh-sainudiin/scalable-data-science/master/images/week1/dbLogin_01_sds_2016S1.png) ![](https://raw.githubusercontent.com/raazesh-sainudiin/scalable-data-science/master/images/week1/dbLogin_02_sds_2016S1.png) ### Step 2: Change your password immediately (now). ![](https://raw.githubusercontent.com/raazesh-sainudiin/scalable-data-science/master/images/week1/dbLogin_pswdChange_sds_2016S1.png) ![](https://raw.githubusercontent.com/raazesh-sainudiin/scalable-data-science/master/images/week1/dbLogin_pswdChanged_sds_2016S1.png) ### Step 3: recognize your ``Home`` area in ``Workspace`` where you can read and write. ![](https://raw.githubusercontent.com/raazesh-sainudiin/scalable-data-science/master/images/week1/dbLogin_03_sds_2016S1.png) ### Step 4: cloning the ``scalable-data-science/week1`` folder ![](https://raw.githubusercontent.com/raazesh-sainudiin/scalable-data-science/master/images/week1/dbLogin_04_sds_2016S1.png) ### Step 5: rename the cloned ``week1 (*)`` folder as ``week1`` for simplicity. ![](https://raw.githubusercontent.com/raazesh-sainudiin/scalable-data-science/master/images/week1/dbLogin_05_sds_2016S1.png) **Note**: From week 2 onwards, you only need to clone the folder for that week (to preserve any changes you made to the notebooks from previous weeks). ### Step 6: loading the ``003_scalaCrashCourse`` notebook ![](https://raw.githubusercontent.com/raazesh-sainudiin/scalable-data-science/master/images/week1/dbLogin_06_sds_2016S1.png) ![](https://raw.githubusercontent.com/raazesh-sainudiin/scalable-data-science/master/images/week1/dbLogin_07_sds_2016S1.png) ### Step 7: Attaching ``003_scalaCrashCourse`` notebook to the databricks clusters #### UC-enrolled students connect to ``studentsEnrolled`` cluster. #### others plese connect to ``studentsObserving1`` cluster. #### in the example below our mock student has connected to the ``classCluster`` cluster. ![](https://raw.githubusercontent.com/raazesh-sainudiin/scalable-data-science/master/images/week1/dbLogin_08_sds_2016S1.png) ![](https://raw.githubusercontent.com/raazesh-sainudiin/scalable-data-science/master/images/week1/dbLogin_09_sds_2016S1.png) ![](https://raw.githubusercontent.com/raazesh-sainudiin/scalable-data-science/master/images/week1/dbLogin_10_sds_2016S1.png) **Finally**, you are ready to use the notebook in your own Workspace and follow along the material being covered, execute cells, modify examples and try them out right away, take extra notes in mark-down enhanced via latex, etc. ## III. Essentials of Databricks Cloud (DBC) ## DBC Essentials: What is Databricks Cloud? ![DB workspace, spark, platform](https://raw.githubusercontent.com/raazesh-sainudiin/scalable-data-science/master/images/week1/dbTrImg_WorkspaceSparkPlatform700x.png) ## DBC Essentials: Shard, Cluster, Notebook and Dashboard ![DB workspace, spark, platform](https://raw.githubusercontent.com/raazesh-sainudiin/scalable-data-science/master/images/week1/dbTrImg_ShardClusterNotebookDashboard700x.png) ## DBC Essentials: Team, State, Collaboration, Elastic Resources ![DB workspace, spark, platform](https://raw.githubusercontent.com/raazesh-sainudiin/scalable-data-science/master/images/week1/dbTrImg_TeamStateCollaborationElasticResources700x.png) Let us dive into Scala crash course in a notebook! # [Scalable Data Science](http://www.math.canterbury.ac.nz/~r.sainudiin/courses/ScalableDataScience/) ### prepared by [Raazesh Sainudiin](https://nz.linkedin.com/in/raazesh-sainudiin-45955845) and [Sivanand Sivaram](https://www.linkedin.com/in/sivanand) *supported by* [![](https://raw.githubusercontent.com/raazesh-sainudiin/scalable-data-science/master/images/databricks_logoTM_200px.png)](https://databricks.com/) and [![](https://raw.githubusercontent.com/raazesh-sainudiin/scalable-data-science/master/images/AWS_logoTM_200px.png)](https://www.awseducate.com/microsite/CommunitiesEngageHome)
unlicense
crockeea/rlwekex
rlwe.h
1075
/* This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * See LICENSE for complete information. */ #ifndef _RLWE_H_ #define _RLWE_H_ #include <stdint.h> #include "fft.h" void sample_ct(uint32_t *s); void sample(uint32_t *s); void round2_ct(uint64_t *out, const uint32_t *in); void round2(uint64_t *out, const uint32_t *in); /* We assume that e contains two random bits in the two * least significant positions. */ uint64_t dbl(const uint32_t in, int32_t e); void crossround2_ct(uint64_t *out, const uint32_t *in); void crossround2(uint64_t *out, const uint32_t *in); void rec_ct(uint64_t *out, const uint32_t *w, const uint64_t *b); void rec(uint64_t *out, const uint32_t *w, const uint64_t *b); void key_gen(uint32_t *out, const uint32_t *a, const uint32_t *s, const uint32_t *e, FFT_CTX *ctx); #endif /* _RLWE_H_ */
unlicense
neiltest/neil_test_selenium
selenium_test/test_case/login.py
433
#coding: utf-8 """ @Author: Well @Date: 2014 - 04 - 16 """ import time def login(self, username, password): browser = self.browser # 输入用户名 browser.find_element_by_id('user_login').send_keys(username) # 输入密码 browser.find_element_by_id('user_pass').send_keys(password) # 点击登录按钮 browser.find_element_by_id('wp-submit').click() # 等待几秒进行加载 time.sleep(5)
unlicense
maikodaraine/EnlightenmentUbuntu
misc/ephysics_tests/src/bin/test_camera.c
7981
#ifdef HAVE_CONFIG_H # include <config.h> #endif #include "ephysics_test.h" typedef struct _Camera_Data Camera_Data; struct _Camera_Data { Test_Data base; Ecore_Animator *animator; int old_x; }; static void _update_floor(Evas_Object *floor_obj, Evas_Coord delta) { int fx, x, y; evas_object_geometry_get(floor_obj, &x, &y, NULL, NULL); fx = x + delta; if (fx < -FLOOR_WIDTH) fx += 2 * FLOOR_WIDTH; evas_object_move(floor_obj, fx, y); } static void _camera_moved_cb(void *data, EPhysics_World *world __UNUSED__, void *event_info) { EPhysics_Camera *camera = event_info; Camera_Data *camera_data = data; Evas_Object *floor_obj; int x; DBG("Camera moved"); ephysics_camera_position_get(camera, &x, NULL); floor_obj = evas_object_data_get(camera_data->base.layout, "floor"); _update_floor(floor_obj, camera_data->old_x - x); floor_obj = evas_object_data_get(camera_data->base.layout, "floor2"); _update_floor(floor_obj, camera_data->old_x - x); camera_data->old_x = x; } static Eina_Bool _camera_move_cb(void *data) { Camera_Data *camera_data = data; EPhysics_Camera *camera; int x, y, w; ephysics_world_render_geometry_get(camera_data->base.world, NULL, NULL, NULL, &w, NULL, NULL); camera = ephysics_world_camera_get(camera_data->base.world); ephysics_camera_position_get(camera, &x, &y); if (x + w > WIDTH * 2) { camera_data->animator = NULL; return EINA_FALSE; } x += 2; ephysics_camera_position_set(camera, x, y); return EINA_TRUE; } static void _world_populate(Camera_Data *camera_data) { Evas_Object *sphere, *shadow; EPhysics_Body *fall_body; shadow = elm_layout_add(camera_data->base.win); elm_layout_file_set( shadow, PACKAGE_DATA_DIR "/" EPHYSICS_TEST_THEME ".edj", "shadow-ball"); evas_object_move(shadow, WIDTH / 3, FLOOR_Y); evas_object_resize(shadow, 70, 3); evas_object_show(shadow); camera_data->base.evas_objs = eina_list_append(camera_data->base.evas_objs, shadow); sphere = elm_image_add(camera_data->base.win); elm_image_file_set( sphere, PACKAGE_DATA_DIR "/" EPHYSICS_TEST_THEME ".edj", "big-blue-ball"); evas_object_move(sphere, WIDTH / 3, FLOOR_Y - 70); evas_object_resize(sphere, 70, 70); evas_object_show(sphere); camera_data->base.evas_objs = eina_list_append(camera_data->base.evas_objs, sphere); fall_body = ephysics_body_sphere_add(camera_data->base.world); ephysics_body_evas_object_set(fall_body, sphere, EINA_TRUE); ephysics_body_restitution_set(fall_body, 0.2); ephysics_body_friction_set(fall_body, 1); ephysics_body_event_callback_add(fall_body, EPHYSICS_CALLBACK_BODY_UPDATE, update_object_cb, shadow); camera_data->base.bodies = eina_list_append(camera_data->base.bodies, fall_body); ephysics_body_central_impulse_apply(fall_body, 300, 0, 0); shadow = elm_layout_add(camera_data->base.win); elm_layout_file_set( shadow, PACKAGE_DATA_DIR "/" EPHYSICS_TEST_THEME ".edj", "shadow-ball"); evas_object_move(shadow, WIDTH * 4 / 3, FLOOR_Y); evas_object_resize(shadow, 70, 3); evas_object_show(shadow); camera_data->base.evas_objs = eina_list_append(camera_data->base.evas_objs, shadow); sphere = elm_image_add(camera_data->base.win); elm_image_file_set( sphere, PACKAGE_DATA_DIR "/" EPHYSICS_TEST_THEME ".edj", "big-red-ball"); evas_object_move(sphere, WIDTH * 4 / 3, FLOOR_Y - 70); evas_object_resize(sphere, 70, 70); evas_object_show(sphere); camera_data->base.evas_objs = eina_list_append(camera_data->base.evas_objs, sphere); fall_body = ephysics_body_sphere_add(camera_data->base.world); ephysics_body_mass_set(fall_body, 4.6); ephysics_body_evas_object_set(fall_body, sphere, EINA_TRUE); ephysics_body_restitution_set(fall_body, 0.12); ephysics_body_friction_set(fall_body, 2); ephysics_body_event_callback_add(fall_body, EPHYSICS_CALLBACK_BODY_UPDATE, update_object_cb, shadow); camera_data->base.bodies = eina_list_append(camera_data->base.bodies, fall_body); camera_data->animator = ecore_animator_add(_camera_move_cb, camera_data); } static void _win_del(void *data, Evas *e __UNUSED__, Evas_Object *obj __UNUSED__, void *event_info __UNUSED__) { Camera_Data *camera_data = data; if (camera_data->animator) ecore_animator_del(camera_data->animator); test_clean((Test_Data *)camera_data); evas_object_del(camera_data->base.layout); ephysics_world_del(camera_data->base.world); free(camera_data); ephysics_shutdown(); } static void _restart(void *data, Evas_Object *obj __UNUSED__, const char *emission __UNUSED__, const char *source __UNUSED__) { Camera_Data *camera_data = data; EPhysics_Camera *camera; Evas_Object *floor_obj; DBG("Restart pressed"); if (camera_data->animator) ecore_animator_del(camera_data->animator); camera = ephysics_world_camera_get(camera_data->base.world); ephysics_camera_position_set(camera, 50, 40); camera_data->old_x = 0; floor_obj = evas_object_data_get(camera_data->base.layout, "floor"); evas_object_move(floor_obj, 0, FLOOR_Y - 20); floor_obj = evas_object_data_get(camera_data->base.layout, "floor2"); evas_object_move(floor_obj, FLOOR_WIDTH, FLOOR_Y - 20); test_clean((Test_Data *)camera_data); _world_populate(camera_data); } void test_camera(void *data __UNUSED__, Evas_Object *obj __UNUSED__, void *event_info __UNUSED__) { Camera_Data *camera_data; EPhysics_Body *boundary; Evas_Object *floor_obj; EPhysics_World *world; if (!ephysics_init()) return; camera_data = calloc(1, sizeof(Camera_Data)); if (!camera_data) { ERR("Failed to create test data"); ephysics_shutdown(); return; } test_win_add((Test_Data *)camera_data, "Camera", EINA_FALSE); evas_object_event_callback_add(camera_data->base.win, EVAS_CALLBACK_DEL, _win_del, camera_data); elm_layout_signal_callback_add(camera_data->base.layout, "restart", "test-theme", _restart, camera_data); floor_obj = elm_image_add(camera_data->base.win); elm_image_file_set( floor_obj, PACKAGE_DATA_DIR "/" EPHYSICS_TEST_THEME ".edj", "floor"); evas_object_move(floor_obj, 0, FLOOR_Y - 20); evas_object_resize(floor_obj, FLOOR_WIDTH, 224); evas_object_show(floor_obj); evas_object_data_set(camera_data->base.layout, "floor", floor_obj); floor_obj = elm_image_add(camera_data->base.win); elm_image_file_set( floor_obj, PACKAGE_DATA_DIR "/" EPHYSICS_TEST_THEME ".edj", "floor"); evas_object_move(floor_obj, FLOOR_WIDTH, FLOOR_Y - 20); evas_object_resize(floor_obj, FLOOR_WIDTH, 224); evas_object_show(floor_obj); evas_object_data_set(camera_data->base.layout, "floor2", floor_obj); world = ephysics_world_new(); ephysics_world_render_geometry_set(world, 50, 40, -50, WIDTH - 100, FLOOR_Y - 40, DEPTH); ephysics_world_event_callback_add(world, EPHYSICS_CALLBACK_WORLD_CAMERA_MOVED, _camera_moved_cb, camera_data); camera_data->base.world = world; boundary = ephysics_body_box_add(camera_data->base.world); ephysics_body_mass_set(boundary, 0); ephysics_body_geometry_set(boundary, 0, FLOOR_Y, -15, WIDTH * 2, 10, 30); ephysics_body_restitution_set(boundary, 0.65); ephysics_body_friction_set(boundary, 4); _world_populate(camera_data); }
unlicense
adiwg/mdTranslator
lib/adiwg/mdtranslator/readers/mdJson/modules/module_processing.rb
3891
# unpack processing # Reader - ADIwg JSON to internal data structure # History: # Stan Smith 2019-09-23 original script require_relative 'module_identifier' require_relative 'module_citation' require_relative 'module_algorithm' module ADIWG module Mdtranslator module Readers module MdJson module Processing def self.unpack(hProcessing, responseObj, inContext = nil) @MessagePath = ADIWG::Mdtranslator::Readers::MdJson::MdJson # return nil object if input is empty if hProcessing.empty? @MessagePath.issueWarning(990, responseObj, inContext) return nil end # instance classes needed in script intMetadataClass = InternalMetadata.new intProcessing = intMetadataClass.newProcessing outContext = 'process step report' outContext = inContext + ' > ' + outContext unless inContext.nil? # processing - identifier {identifier} (required) if hProcessing.has_key?('identifier') unless hProcessing['identifier'].empty? hReturn = Identifier.unpack(hProcessing['identifier'], responseObj, outContext) unless hReturn.nil? intProcessing[:identifier] = hReturn end end end if intProcessing[:identifier].empty? @MessagePath.issueWarning(991, responseObj, inContext) end # processing - software reference if hProcessing.has_key?('softwareReference') unless hProcessing['softwareReference'].empty? hReturn = Citation.unpack(hProcessing['softwareReference'], responseObj, outContext) unless hReturn.nil? intProcessing[:softwareReference] = hReturn end end end # processing - procedure description if hProcessing.has_key?('procedureDescription') unless hProcessing['procedureDescription'] == '' intProcessing[:procedureDescription] = hProcessing['procedureDescription'] end end # processing - documentation if hProcessing.has_key?('documentation') aCitation = hProcessing['documentation'] aCitation.each do |item| hCitation = Citation.unpack(item, responseObj, outContext) unless hCitation.nil? intProcessing[:documentation] << hCitation end end end # processing - runtime parameters if hProcessing.has_key?('runtimeParameters') unless hProcessing['runtimeParameters'] == '' intProcessing[:runtimeParameters] = hProcessing['runtimeParameters'] end end # processing - algorithm if hProcessing.has_key?('algorithm') aAlgorithm = hProcessing['algorithm'] aAlgorithm.each do |item| hAlgorithm = Algorithm.unpack(item, responseObj, outContext) unless hAlgorithm.nil? intProcessing[:algorithms] << hAlgorithm end end end return intProcessing end end end end end end
unlicense
Offirmo/html_tests
tosort/2016/requirejs/famous_002_centering.html
2453
<!doctype html> <html lang="en" xmlns:ng="http://angularjs.org" ng-controller="AppCtrl"> <head> <meta charset="utf-8"> <title ng-bind="title">Angular test fallback title</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> #root { position: fixed; top: 0; right: 0; bottom: 0; left: 0; color: black; } </style> <script> // ... </script> </head> <body> <div id="root" fa-app> <fa-modifier fa-opacity="0.5"> <!-- this modifier allows to spot surface that overlap --> <!-- background --> <fa-surface fa-background-color="'LightSteelBlue'" fa-size="[undefined,undefined]"></fa-surface> <fa-modifier fa-origin="[.5, .5]" fa-align="[.5, .5]"> <fa-surface fa-background-color="'Khaki'" fa-size="[300,300]"> This will be shown on screen. </fa-surface> </fa-modifier> <fa-surface fa-background-color="'green'" fa-size="[400,200]"> Hello world <dl> <dt>browser viewport height <dd id="bvheight">? <dt>browser viewport width <dd id="bvwidth">? <dt>HTML document height <dd id="hdheight">? <dt>HTML document width <dd id="hdwidth">? </dl> </fa-surface> </fa-modifier> </div> <script async data-main="misc/components.js" src="../bower_components/requirejs/require.js"></script> <script> window.main = function() { requirejs( [ 'lodash', 'jquery', 'famous-global', 'angular', 'famous-angular', 'bootstrap' ], function(_, $jq, famous) { var app = angular.module('App', ['famous.angular']); app.controller('AppCtrl', ['$q', '$scope', function($q, $scope) { $scope.title = "Famo.us Test 002"; }]); console.log("Bootstrapping angular..."); angular.element(document).ready(function() { angular.bootstrap(document, ['App'], {strictDi: true}); }); function update_window_dimensions() { // http://stackoverflow.com/questions/3437786/how-to-get-web-page-size-browser-window-size-screen-size-in-a-cross-browser-wa $jq("dd#bvheight" ).text( $jq(window).height() ); $jq("dd#bvwidth" ).text( $jq(window).width() ); $jq("dd#hdheight" ).text( $jq(document).height() ); $jq("dd#hdwidth" ).text( $jq(document).width() ); } update_window_dimensions(); // http://stackoverflow.com/questions/2996431/detect-when-a-window-is-resized-using-javascript $jq(window).resize(update_window_dimensions); }); }; </script> </body> </html>
unlicense
rg3/youtube-dl
youtube_dl/extractor/youporn.py
7294
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( extract_attributes, int_or_none, str_to_int, unified_strdate, url_or_none, ) class YouPornIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?youporn\.com/(?:watch|embed)/(?P<id>\d+)(?:/(?P<display_id>[^/?#&]+))?' _TESTS = [{ 'url': 'http://www.youporn.com/watch/505835/sex-ed-is-it-safe-to-masturbate-daily/', 'md5': '3744d24c50438cf5b6f6d59feb5055c2', 'info_dict': { 'id': '505835', 'display_id': 'sex-ed-is-it-safe-to-masturbate-daily', 'ext': 'mp4', 'title': 'Sex Ed: Is It Safe To Masturbate Daily?', 'description': 'Love & Sex Answers: http://bit.ly/DanAndJenn -- Is It Unhealthy To Masturbate Daily?', 'thumbnail': r're:^https?://.*\.jpg$', 'duration': 210, 'uploader': 'Ask Dan And Jennifer', 'upload_date': '20101217', 'average_rating': int, 'view_count': int, 'categories': list, 'tags': list, 'age_limit': 18, }, 'skip': 'This video has been disabled', }, { # Unknown uploader 'url': 'http://www.youporn.com/watch/561726/big-tits-awesome-brunette-on-amazing-webcam-show/?from=related3&al=2&from_id=561726&pos=4', 'info_dict': { 'id': '561726', 'display_id': 'big-tits-awesome-brunette-on-amazing-webcam-show', 'ext': 'mp4', 'title': 'Big Tits Awesome Brunette On amazing webcam show', 'description': 'http://sweetlivegirls.com Big Tits Awesome Brunette On amazing webcam show.mp4', 'thumbnail': r're:^https?://.*\.jpg$', 'uploader': 'Unknown', 'upload_date': '20110418', 'average_rating': int, 'view_count': int, 'categories': list, 'tags': list, 'age_limit': 18, }, 'params': { 'skip_download': True, }, 'skip': '404', }, { 'url': 'https://www.youporn.com/embed/505835/sex-ed-is-it-safe-to-masturbate-daily/', 'only_matching': True, }, { 'url': 'http://www.youporn.com/watch/505835', 'only_matching': True, }, { 'url': 'https://www.youporn.com/watch/13922959/femdom-principal/', 'only_matching': True, }] @staticmethod def _extract_urls(webpage): return re.findall( r'<iframe[^>]+\bsrc=["\']((?:https?:)?//(?:www\.)?youporn\.com/embed/\d+)', webpage) def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group('id') display_id = mobj.group('display_id') or video_id definitions = self._download_json( 'https://www.youporn.com/api/video/media_definitions/%s/' % video_id, display_id) formats = [] for definition in definitions: if not isinstance(definition, dict): continue video_url = url_or_none(definition.get('videoUrl')) if not video_url: continue f = { 'url': video_url, 'filesize': int_or_none(definition.get('videoSize')), } height = int_or_none(definition.get('quality')) # Video URL's path looks like this: # /201012/17/505835/720p_1500k_505835/YouPorn%20-%20Sex%20Ed%20Is%20It%20Safe%20To%20Masturbate%20Daily.mp4 # /201012/17/505835/vl_240p_240k_505835/YouPorn%20-%20Sex%20Ed%20Is%20It%20Safe%20To%20Masturbate%20Daily.mp4 # /videos/201703/11/109285532/1080P_4000K_109285532.mp4 # We will benefit from it by extracting some metadata mobj = re.search(r'(?P<height>\d{3,4})[pP]_(?P<bitrate>\d+)[kK]_\d+', video_url) if mobj: if not height: height = int(mobj.group('height')) bitrate = int(mobj.group('bitrate')) f.update({ 'format_id': '%dp-%dk' % (height, bitrate), 'tbr': bitrate, }) f['height'] = height formats.append(f) self._sort_formats(formats) webpage = self._download_webpage( 'http://www.youporn.com/watch/%s' % video_id, display_id, headers={'Cookie': 'age_verified=1'}) title = self._html_search_regex( r'(?s)<div[^>]+class=["\']watchVideoTitle[^>]+>(.+?)</div>', webpage, 'title', default=None) or self._og_search_title( webpage, default=None) or self._html_search_meta( 'title', webpage, fatal=True) description = self._html_search_regex( r'(?s)<div[^>]+\bid=["\']description["\'][^>]*>(.+?)</div>', webpage, 'description', default=None) or self._og_search_description( webpage, default=None) thumbnail = self._search_regex( r'(?:imageurl\s*=|poster\s*:)\s*(["\'])(?P<thumbnail>.+?)\1', webpage, 'thumbnail', fatal=False, group='thumbnail') duration = int_or_none(self._html_search_meta( 'video:duration', webpage, 'duration', fatal=False)) uploader = self._html_search_regex( r'(?s)<div[^>]+class=["\']submitByLink["\'][^>]*>(.+?)</div>', webpage, 'uploader', fatal=False) upload_date = unified_strdate(self._html_search_regex( [r'UPLOADED:\s*<span>([^<]+)', r'Date\s+[Aa]dded:\s*<span>([^<]+)', r'(?s)<div[^>]+class=["\']videoInfo(?:Date|Time)["\'][^>]*>(.+?)</div>'], webpage, 'upload date', fatal=False)) age_limit = self._rta_search(webpage) view_count = None views = self._search_regex( r'(<div[^>]+\bclass=["\']js_videoInfoViews["\']>)', webpage, 'views', default=None) if views: view_count = str_to_int(extract_attributes(views).get('data-value')) comment_count = str_to_int(self._search_regex( r'>All [Cc]omments? \(([\d,.]+)\)', webpage, 'comment count', default=None)) def extract_tag_box(regex, title): tag_box = self._search_regex(regex, webpage, title, default=None) if not tag_box: return [] return re.findall(r'<a[^>]+href=[^>]+>([^<]+)', tag_box) categories = extract_tag_box( r'(?s)Categories:.*?</[^>]+>(.+?)</div>', 'categories') tags = extract_tag_box( r'(?s)Tags:.*?</div>\s*<div[^>]+class=["\']tagBoxContent["\'][^>]*>(.+?)</div>', 'tags') return { 'id': video_id, 'display_id': display_id, 'title': title, 'description': description, 'thumbnail': thumbnail, 'duration': duration, 'uploader': uploader, 'upload_date': upload_date, 'view_count': view_count, 'comment_count': comment_count, 'categories': categories, 'tags': tags, 'age_limit': age_limit, 'formats': formats, }
unlicense
open-austin/open-austin.org
_posts/2016-03-10-codeacross-austin-2016-recap.md
4844
--- layout: post title: CodeAcross Austin 2016 Recap date: 2016-03-10 type: post published: true thumb: codeacross-actors-performers_250.jpg thumbalt: Participants add their sticky notes to canvas author: first_name: Victoria last_name: O'Dell --- This past Saturday, March 5, 2015, Open Austin had it’s 6th annual CodeAcross Austin event. This national day of action aligns with International Open Data Day. [CodeAcross](https://www.codeforamerica.org/events/codeacross-2016/) is the first major event of the year that Open Austin organizes as a volunteer brigade affiliated with Code for America. It is a part of a series of events in collaboration with the City of Austin and St. Edward’s leading up to ATX Hack For Change (June 3-5). The purpose of Code Across Austin this year was to identify and frame challenges in Austin that can be solved using technology, data, design and the diverse skills and knowledge of volunteers. The morning kicked off at 10:00 am with introductory remarks from Mateo Clarke & Victoria O’Dell of Open Austin. Then, visiting from San Francisco, Monique Baena-Tan, Brigade Program Coordinator from Code for America, spoke about the international reach of the brigade program. The morning presentations ended with Kerry O’Connor, Chief Innovation Officer for the City of Austin sharing inspiring words about the importance of civic hacking events like CodeAcross. ![Pano view of the crowd during morning presentations](/assets/images/codeacross-2016-pano.jpg) <blockquote class="twitter-tweet" data-lang="en"><p lang="en" dir="ltr">Favorite quote from <a href="https://twitter.com/hashtag/codeacrossatx?src=hash">#codeacrossatx</a> &quot;Disruption will come to government either as an opportunity or a threat.&quot; <a href="https://twitter.com/kerry_atx">@kerry_atx</a> ⚡️<a href="https://twitter.com/openaustin">@openaustin</a></p>&mdash; Mateo Clarke (@MateoClarke) <a href="https://twitter.com/MateoClarke/status/706265412795658240">March 5, 2016</a></blockquote> <script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script> _Quote from Kerry O’Connor’s presentation_ ![Description of Code for America from slidedeck.](/assets/images/cfa-slide.png) _[View Monique’s presentation](https://docs.google.com/presentation/d/1INnwL4NGuiIFqIl_N_eLJrxKmhxT_hdULH9uCFW7zTw/edit#slide=id.g11c404532b_4_63)_ The rest of day was broken into group activities arranged around 8 themes and their relation to the city of Austin. - Health and Human services - Public Safety & Justice - Economic Development - Communication and Engagement - Transportation - Broadband and Digital Opportunities - Sustainability - Planning and Land Use Participants with varying backgrounds brainstormed on challenges the city faces and worked on actionable steps that could be taken to tackle them. By the end of the morning, groups focused on each theme had drafted at least three “How might we..” challenge statements. ![A participant add a sticky to a how might we challenge](/assets/images/how-might-we.jpg) The second half of the day focused on turning the challenge statements into potential solutions with an actionable plan. Charles Purma, project manager for the City of Austin, presented the [“Civic Tech Canvas”](http://www.open-austin.org/civic-tech-canvas/) that groups used to plan out a solution to their chosen challenge statements. ![Two ladies add post it notes to their hack canvas](/assets/images/hack-canvas.jpg) With contributions from around 60 participants of different backgrounds, ages, and professions, [11 different project ideas](https://github.com/open-austin/project-ideas/issues?q=is%3Aopen+is%3Aissue+label%3ACodeAcross2016) were presented. Code Across is over but the ideas sharing and collaboration that occurred will allow the Austin community and Open Austin to continue to do open source civic tech and design work for the people. --- View [our deck](https://docs.google.com/presentation/d/1aWNB5wWr9ZIjwvMNEZR2uoGJcK9zDKuFw0_B1JIhFBk/edit#slide=id.g11c5e340a8_0_17) from event and check out tweets from the event at [#codeacrossatx](https://twitter.com/search?q=codeacrossatx&src=typd&lang=en) Check out our event [photo album](https://www.facebook.com/media/set/?set=a.962504890492340.1073741830.412390968837071&type=1&l=d32fcb860f). Missed out on this year’s CodeAcross? Come out to our next event. [Civic Hack Saturday](http://www.meetup.com/Open-Austin/events/228334335/) is on March 19th. Join the Open Austin community on Slack: [Get an invite](http://slack.open-austin.org/)<br> RSVP for our future events on Meetup: [RSVP](http://www.meetup.com/Open-Austin/)<br> Follow us on Twitter: [Follow](https://twitter.com/openaustin?lang=en)<br> & Like us on Facebook: [Like](https://www.facebook.com/Open-Austin-412390968837071/)
unlicense
vad7/PowerMeter
bin/make_firmware_image.py
1000
#!/usr/bin/env python # # ESP8266 make firmware image # # Arguments: dir of *.bin # # (c) vad7 import argparse import os argp = argparse.ArgumentParser() argp.add_argument('flashsize', action='store', help='Flash size, kb') argp.add_argument('dir', action='store', help='Directory of *.bin') args = argp.parse_args() fout_name = args.dir + "firmware.bin" fout = open(fout_name, "wb") fin = open(args.dir + "0x00000.bin", "rb") data = fin.read() fin.close() data += b"\xFF" * (0x7000 - len(data)) fin = open(args.dir + "0x07000.bin", "rb") data2 = fin.read() fin.close() data = data + data2 fout.write(data) fout.flush() size = os.fstat(fout.fileno()).st_size fout.close() print "Make: " + fout_name if int(args.flashsize) == 512: webfs = (size + 0xFFF) & 0xFF000 maxota = (0x7B000 / 2) & 0xFF000 else: webfs = 0x80000 maxota = 0x7B000 print "Firmware size: " + str(size) + ", WebFS addr: " + str(webfs) + ", Max OTA size: " + str(maxota) print "Space available for OTA: " + str(maxota - size)
unlicense
flower1024/nodePoloApi
public/string.js
23495
/*jslint nomen: true */ /*jslint plusplus: true */ /*jslint browser: true*/ /*jslint node: true*/ /*global d3, io, nunjucks*/ 'use strict'; // // JavaScript unit // Add-on for the string and number manipulation // // Copyright (c) 2005, 2006, 2007, 2010, 2011 by Ildar Shaimordanov // /* The following code is described in ECMA drafts and might be implemented in the future of ECMA */ if (!String.prototype.repeat) { /** * object.x(number) * object.repeat(number) * Transform the string object multiplying the string * * @param number Amount of repeating * @return string * @access public * @see http://svn.debugger.ru/repos/jslibs/BrowserExtensions/trunk/ext/string.js * @see http://wiki.ecmascript.org/doku.php?id=harmony:string_extras */ String.prototype.repeat = function (n) { n = Math.max(n || 0, 0); return new Array(n + 1).join(this.valueOf()); }; } if (!String.prototype.startsWith) { /** * Returns true if the sequence of characters of searchString converted * to a String match the corresponding characters of this object * (converted to a String) starting at position. Otherwise returns false. * * @param string * @param integer * @return bollean * @acess public */ String.prototype.startsWith = function (searchString, position) { position = Math.max(position || 0, 0); return this.indexOf(searchString) == position; }; } if (!String.prototype.endsWith) { /** * Returns true if the sequence of characters of searchString converted * to a String match the corresponding characters of this object * (converted to a String) starting at endPosition - length(this). * Otherwise returns false. * * @param string * @param integer * @return bollean * @acess public */ String.prototype.endsWith = function (searchString, endPosition) { endPosition = Math.max(endPosition || 0, 0); var s = String(searchString); var pos = this.lastIndexOf(s); return pos >= 0 && pos == this.length - s.length - endPosition; }; } if (!String.prototype.contains) { /** * If searchString appears as a substring of the result of converting * this object to a String, at one or more positions that are greater than * or equal to position, then return true; otherwise, returns false. * If position is undefined, 0 is assumed, so as to search all of the String. * * @param string * @param integer * @return bollean * @acess public */ String.prototype.contains = function (searchString, position) { position = Math.max(position || 0, 0); return this.indexOf(searchString) != -1; }; } if (!String.prototype.toArray) { /** * Returns an Array object with elements corresponding to * the characters of this object (converted to a String). * * @param void * @return array * @acess public */ String.prototype.toArray = function () { return this.split(''); }; } if (!String.prototype.reverse) { /** * Returns an Array object with elements corresponding to * the characters of this object (converted to a String) in reverse order. * * @param void * @return string * @acess public */ String.prototype.reverse = function () { return this.split('').reverse().join(''); }; } /* The following ode is not described in ECMA specs or drafts. */ /** * String.validBrackets(string) * Checks string to be valid brackets. Valid brackets are: * quotes - '' "" `' `` * single - <> {} [] () %% || // \\ * double - miltiline comments * /** / C/C++ like (without whitespace) * <??> PHP like * <%%> ASP like * (**) Pascal like * * @param string Brackets (left and right) * @return boolean Result of validity of brackets * @access static */ String.validBrackets = function (br) { if (!br) { return false; } var quot = "''\"\"`'``"; var sgl = "<>{}[]()%%||//\\\\"; var dbl = "/**/<??><%%>(**)"; return (br.length == 2 && (quot + sgl).indexOf(br) != -1) || (br.length == 4 && dbl.indexOf(br) != -1); }; /** * object.bracketize(string) * Transform the string object by setting in frame of valid brackets * * @param string Brackets * @return string Bracketized string * @access public */ String.prototype.brace = String.prototype.bracketize = function (br) { var string = this; if (!String.validBrackets(br)) { return string; } var midPos = br.length / 2; return br.substr(0, midPos) + string.toString() + br.substr(midPos); }; /** * object.unbracketize(string) * Transform the string object removing the leading and trailing brackets * If the parameter is not defined the method will try to remove existing valid brackets * * @param string Brackets * @return string Unbracketized string * @access public */ String.prototype.unbrace = String.prototype.unbracketize = function (br) { var string = this; if (!br) { var len = string.length; for (var i = 2; i >= 1; i--) { br = string.substring(0, i) + string.substring(len - i); if (String.validBrackets(br)) { return string.substring(i, len - i); } } } if (!String.validBrackets(br)) { return string; } var midPos = br.length / 2; var i = string.indexOf(br.substr(0, midPos)); var j = string.lastIndexOf(br.substr(midPos)); if (i == 0 && j == string.length - midPos) { string = string.substring(i + midPos, j); } return string; }; /** * object.radix(number, number, string) * Transform the number object to string in accordance with a scale of notation * If it is necessary the numeric string will aligned to right and filled by '0' character, by default * * @param number Radix of scale of notation (it have to be greater or equal 2 and below or equal 36) * @param number Width of numeric string * @param string Padding chacracter (by default, '0') * @return string Numeric string * @access public */ Number.prototype.radix = function (r, n, c) { return this.toString(r).padding(-n, c); // return this.toString(r).padding(-Math.abs(n), c); }; /** * object.bin(number, string) * Transform the number object to string of binary presentation * * @param number Width of numeric string * @param string Padding chacracter (by default, '0') * @return string Numeric string * @access public */ Number.prototype.bin = function (n, c) { return this.radix(0x02, n, c); // return this.radix(0x02, (n) ? n : 16, c); }; /** * object.oct(number, string) * Transform the number object to string of octal presentation * * @param number Width of numeric string * @param string Padding chacracter (by default, '0') * @return string Numeric string * @access public */ Number.prototype.oct = function (n, c) { return this.radix(0x08, n, c); // return this.radix(0x08, (n) ? n : 6, c); }; /** * object.dec(number, string) * Transform the number object to string of decimal presentation * * @param number Width of numeric string * @param string Padding chacracter (by default, '0') * @return string Numeric string * @access public */ Number.prototype.dec = function (n, c) { return this.radix(0x0A, n, c); }; /** * object.hexl(number, string) * Transform the number object to string of hexadecimal presentation in lower-case of major characters (0-9 and a-f) * * @param number Width of numeric string * @param string Padding chacracter (by default, '0') * @return string Numeric string * @access public */ Number.prototype.hexl = function (n, c) { return this.radix(0x10, n, c); // return this.radix(0x10, (n) ? n : 4, c); }; /** * object.hex(number, string) * Transform the number object to string of the hexadecimal presentation * in upper-case of major characters (0-9 and A-F) * * @param number Width of numeric string * @param string Padding chacracter (by default, '0') * @return string Numeric string * @access public */ Number.prototype.hex = function (n, c) { return this.radix(0x10, n, c).toUpperCase(); }; /** * object.human([digits[, true]]) * Transform the number object to string in human-readable format (e.h., 1k, 234M, 5G) * * @example * var n = 1001; * * // will output 1.001K * var h = n.human(3); * * // will output 1001.000 * var H = n.human(3, true); * * @param integer Optional. Number of digits after the decimal point. Must be in the range 0-20, inclusive. * @param boolean Optional. If true then use powers of 1024 not 1000 * @return string Human-readable string * @access public */ Number.prototype.human = function (digits, binary) { var n = Math.abs(this); var p = this; var s = ''; var divs = arguments.callee.add(binary); for (var i = divs.length - 1; i >= 0; i--) { if (n >= divs[i].d) { p /= divs[i].d; s = divs[i].s; break; } } return p.toFixed(digits) + s; }; /** * Subsidiary method. * Stores suffixes and divisors to use in Number.prototype.human. * * @param boolean * @param string * @param divisor * @return array * @access static */ Number.prototype.human.add = function (binary, suffix, divisor) { var name = binary ? 'div2' : 'div10'; var divs = Number.prototype.human[name] = Number.prototype.human[name] || []; if (arguments.length < 3) { return divs; } divs.push({ s: suffix, d: Math.abs(divisor) }); divs.sort(function (a, b) { return a.d - b.d; }); return divs; }; // Binary prefixes Number.prototype.human.add(true, 'K', 1 << 10); Number.prototype.human.add(true, 'M', 1 << 20); Number.prototype.human.add(true, 'G', 1 << 30); Number.prototype.human.add(true, 'T', Math.pow(2, 40)); // Decimal prefixes Number.prototype.human.add(false, 'K', 1e3); Number.prototype.human.add(false, 'M', 1e6); Number.prototype.human.add(false, 'G', 1e9); Number.prototype.human.add(false, 'T', 1e12); /** * object.fromHuman([digits[, binary]]) * Transform the human-friendly string to the valid numeriv value * * @example * var n = 1001; * * // will output 1.001K * var h = n.human(3); * * // will output 1001 * var m = h.fromHuman(h); * * @param boolean Optional. If true then use powers of 1024 not 1000 * @return number * @access public */ Number.fromHuman = function (value, binary) { var m = String(value).match(/^([\-\+]?\d+\.?\d*)([A-Z])?$/); if (!m) { return Number.NaN; } if (!m[2]) { return +m[1]; } var divs = Number.prototype.human.add(binary); for (var i = 0; i < divs.length; i++) { if (divs[i].s == m[2]) { return m[1] * divs[i].d; } } return Number.NaN; }; if (!String.prototype.trim) { /** * object.trim() * Transform the string object removing leading and trailing whitespaces * * @return string * @access public */ String.prototype.trim = function () { return this.replace(/(^\s*)|(\s*$)/g, ""); }; } if (!String.prototype.trimLeft) { /** * object.trimLeft() * Transform the string object removing leading whitespaces * * @return string * @access public */ String.prototype.trimLeft = function () { return this.replace(/(^\s*)/, ""); }; } if (!String.prototype.trimRight) { /** * object.trimRight() * Transform the string object removing trailing whitespaces * * @return string * @access public */ String.prototype.trimRight = function () { return this.replace(/(\s*$)/g, ""); }; } /** * object.dup() * Transform the string object duplicating the string * * @return string * @access public */ String.prototype.dup = function () { var val = this.valueOf(); return val + val; }; /** * object.padding(number, string) * Transform the string object to string of the actual width filling by the padding character (by default ' ') * Negative value of width means left padding, and positive value means right one * * @param number Width of string * @param string Padding chacracter (by default, ' ') * @return string * @access public */ String.prototype.padding = function (n, c) { var val = this.valueOf(); if (Math.abs(n) <= val.length) { return val; } var m = Math.max((Math.abs(n) - this.length) || 0, 0); var pad = Array(m + 1).join(String(c || ' ').charAt(0)); // var pad = String(c || ' ').charAt(0).repeat(Math.abs(n) - this.length); return (n < 0) ? pad + val : val + pad; // return (n < 0) ? val + pad : pad + val; }; /** * object.padLeft(number, string) * Wrapper for object.padding * Transform the string object to string of the actual width adding the leading padding character (by default ' ') * * @param number Width of string * @param string Padding chacracter * @return string * @access public */ String.prototype.padLeft = function (n, c) { return this.padding(-Math.abs(n), c); }; /** * object.alignRight(number, string) * Wrapper for object.padding * Synonym for object.padLeft * * @param number Width of string * @param string Padding chacracter * @return string * @access public */ String.prototype.alignRight = String.prototype.padLeft; /** * object.padRight(number, string) * Wrapper for object.padding * Transform the string object to string of the actual width adding the trailing padding character (by default ' ') * * @param number Width of string * @param string Padding chacracter * @return string * @access public */ String.prototype.padRight = function (n, c) { return this.padding(Math.abs(n), c); }; /** * Formats arguments accordingly the formatting string. * Each occurence of the "{\d+}" substring refers to * the appropriate argument. * * @example * '{0}is not {1} + {2}'.format('JavaScript', 'Java', 'Script'); * * @param mixed * @return string * @access public */ String.prototype.format = function () { var args = arguments; return this.replace(/\{(\d+)\}/g, function ($0, $1) { return args[$1] !== void 0 ? args[$1] : $0; }); }; /** * object.alignLeft(number, string) * Wrapper for object.padding * Synonym for object.padRight * * @param number Width of string * @param string Padding chacracter * @return string * @access public */ String.prototype.alignLeft = String.prototype.padRight; /** * sprintf(format, argument_list) * * The string function like one in C/C++, PHP, Perl * Each conversion specification is defined as below: * * %[index][alignment][padding][width][precision]type * * index An optional index specifier that changes the order of the * arguments in the list to be displayed. * alignment An optional alignment specifier that says if the result should be * left-justified or right-justified. The default is * right-justified; a "-" character here will make it left-justified. * padding An optional padding specifier that says what character will be * used for padding the results to the right string size. This may * be a space character or a "0" (zero character). The default is to * pad with spaces. An alternate padding character can be specified * by prefixing it with a single quote ('). See the examples below. * width An optional number, a width specifier that says how many * characters (minimum) this conversion should result in. * precision An optional precision specifier that says how many decimal digits * should be displayed for floating-point numbers. This option has * no effect for other types than float. * type A type specifier that says what type the argument data should be * treated as. Possible types: * * % - a literal percent character. No argument is required. * b - the argument is treated as an integer, and presented as a binary number. * c - the argument is treated as an integer, and presented as the character * with that ASCII value. * d - the argument is treated as an integer, and presented as a decimal number. * u - the same as "d". * f - the argument is treated as a float, and presented as a floating-point. * o - the argument is treated as an integer, and presented as an octal number. * s - the argument is treated as and presented as a string. * x - the argument is treated as an integer and presented as a hexadecimal * number (with lowercase letters). * X - the argument is treated as an integer and presented as a hexadecimal * number (with uppercase letters). * h - the argument is treated as an integer and presented in human-readable format * using powers of 1024. * H - the argument is treated as an integer and presented in human-readable format * using powers of 1000. */ String.prototype.sprintf = function () { var args = arguments; var index = 0; var x; var ins; var fn; /* * The callback function accepts the following properties * x.index contains the substring position found at the origin string * x[0] contains the found substring * x[1] contains the index specifier (as \d+\$ or \d+#) * x[2] contains the alignment specifier ("+" or "-" or empty) * x[3] contains the padding specifier (space char, "0" or defined as '.) * x[4] contains the width specifier (as \d*) * x[5] contains the floating-point precision specifier (as \.\d*) * x[6] contains the type specifier (as [bcdfosuxX]) */ return this.replace(String.prototype.sprintf.re, function () { if (arguments[0] == "%%") { return "%"; } x = []; for (var i = 0; i < arguments.length; i++) { x[i] = arguments[i] || ''; } x[3] = x[3].slice(-1) || ' '; ins = args[+x[1] ? x[1] - 1 : index++]; // index++; return String.prototype.sprintf[x[6]](ins, x); }); }; String.prototype.sprintf.re = /%%|%(?:(\d+)[\$#])?([+-])?('.|0| )?(\d*)(?:\.(\d+))?([bcdfosuxXhH])/g; String.prototype.sprintf.b = function (ins, x) { return Number(ins).bin(x[2] + x[4], x[3]); }; String.prototype.sprintf.c = function (ins, x) { return String.fromCharCode(ins).padding(x[2] + x[4], x[3]); }; String.prototype.sprintf.d = String.prototype.sprintf.u = function (ins, x) { return Number(ins).dec(x[2] + x[4], x[3]); }; String.prototype.sprintf.f = function (ins, x) { var ins = Number(ins); // var fn = String.prototype.padding; if (x[5]) { ins = ins.toFixed(x[5]); } else if (x[4]) { ins = ins.toExponential(x[4]); } else { ins = ins.toExponential(); } // Invert sign because this is not number but string x[2] = x[2] == "-" ? "+" : "-"; return ins.padding(x[2] + x[4], x[3]); // return fn.call(ins, x[2] + x[4], x[3]); }; String.prototype.sprintf.o = function (ins, x) { return Number(ins).oct(x[2] + x[4], x[3]); }; String.prototype.sprintf.s = function (ins, x) { return String(ins).padding(x[2] + x[4], x[3]); }; String.prototype.sprintf.x = function (ins, x) { return Number(ins).hexl(x[2] + x[4], x[3]); }; String.prototype.sprintf.X = function (ins, x) { return Number(ins).hex(x[2] + x[4], x[3]); }; String.prototype.sprintf.h = function (ins, x) { var ins = String.prototype.replace.call(ins, /,/g, ''); // Invert sign because this is not number but string x[2] = x[2] == "-" ? "+" : "-"; return Number(ins).human(x[5], true).padding(x[2] + x[4], x[3]); }; String.prototype.sprintf.H = function (ins, x) { var ins = String.prototype.replace.call(ins, /,/g, ''); // Invert sign because this is not number but string x[2] = x[2] == "-" ? "+" : "-"; return Number(ins).human(x[5], false).padding(x[2] + x[4], x[3]); }; /** * compile() * * This string function compiles the formatting string to the internal function * to acelerate an execution a formatting within loops. * * @example * // Standard usage of the sprintf method * var s = ''; * for (var p in obj) { * s += '%s = %s'.sprintf(p, obj[p]); * } * * // The more speed usage of the sprintf method * var sprintf = '%s = %s'.compile(); * var s = ''; * for (var p in obj) { * s += sprintf(p, obj[p]); * } * * @see String.prototype.sprintf() */ String.prototype.compile = function () { var args = arguments; var index = 0; var x; var ins; var fn; /* * The callback function accepts the following properties * x.index contains the substring position found at the origin string * x[0] contains the found substring * x[1] contains the index specifier (as \d+\$ or \d+#) * x[2] contains the alignment specifier ("+" or "-" or empty) * x[3] contains the padding specifier (space char, "0" or defined as '.) * x[4] contains the width specifier (as \d*) * x[5] contains the floating-point precision specifier (as \.\d*) * x[6] contains the type specifier (as [bcdfosuxX]) */ var result = this.replace(/(\\|")/g, '\\$1').replace(String.prototype.sprintf.re, function () { if (arguments[0] == "%%") { return "%"; } arguments.length = 7; x = []; for (var i = 0; i < arguments.length; i++) { x[i] = arguments[i] || ''; } x[3] = x[3].slice(-1) || ' '; ins = x[1] ? x[1] - 1 : index++; // index++; return '", String.prototype.sprintf.' + x[6] + '(arguments[' + ins + '], ["' + x.join('", "') + '"]), "'; }); return Function('', 'return ["' + result + '"].join("")'); }; /** * Considers the string object as URL and returns it's parts separately * * @param void * @return Object * @access public */ String.prototype.parseUrl = function () { var matches = this.match(arguments.callee.re); if (!matches) { return null; } var result = { 'scheme': matches[1] || '', 'subscheme': matches[2] || '', 'user': matches[3] || '', 'pass': matches[4] || '', 'host': matches[5], 'port': matches[6] || '', 'path': matches[7] || '', 'query': matches[8] || '', 'fragment': matches[9] || '' }; return result; }; String.prototype.parseUrl.re = /^(?:([a-z]+):(?:([a-z]*):)?\/\/)?(?:([^:@]*)(?::([^:@]*))?@)?((?:[a-z0-9_-]+\.)+[a-z]{2,}|localhost|(?:(?:[01]?\d\d?|2[0-4]\d|25[0-5])\.){3}(?:(?:[01]?\d\d?|2[0-4]\d|25[0-5])))(?::(\d+))?(?:([^:\?\#]+))?(?:\?([^\#]+))?(?:\#([^\s]+))?$/i; String.prototype.camelize = function () { return this.replace(/([^-]+)|(?:-(.)([^-]+))/mg, function ($0, $1, $2, $3) { return ($2 || '').toUpperCase() + ($3 || $1).toLowerCase(); }); }; String.prototype.uncamelize = function () { return this.replace(/[A-Z]/g, function ($0) { return '-' + $0.toLowerCase(); }); };
unlicense
tiagofernandez/boobot
vendor/src/github.com/labstack/echo/context_test.go
11278
package echo import ( "bytes" "errors" "io" "mime/multipart" "net/http" "os" "testing" "text/template" "time" "golang.org/x/net/context" "strings" "net/url" "encoding/xml" "github.com/labstack/echo/test" "github.com/stretchr/testify/assert" ) type ( Template struct { templates *template.Template } ) func (t *Template) Render(w io.Writer, name string, data interface{}, c Context) error { return t.templates.ExecuteTemplate(w, name, data) } func TestContext(t *testing.T) { e := New() req := test.NewRequest(POST, "/", strings.NewReader(userJSON)) rec := test.NewResponseRecorder() c := e.NewContext(req, rec).(*echoContext) // Echo assert.Equal(t, e, c.Echo()) // Request assert.Equal(t, req, c.Request()) // Response assert.Equal(t, rec, c.Response()) // Logger assert.Equal(t, e.logger, c.Logger()) //-------- // Render //-------- tpl := &Template{ templates: template.Must(template.New("hello").Parse("Hello, {{.}}!")), } c.echo.SetRenderer(tpl) err := c.Render(http.StatusOK, "hello", "Jon Snow") if assert.NoError(t, err) { assert.Equal(t, http.StatusOK, rec.Status()) assert.Equal(t, "Hello, Jon Snow!", rec.Body.String()) } c.echo.renderer = nil err = c.Render(http.StatusOK, "hello", "Jon Snow") assert.Error(t, err) // JSON rec = test.NewResponseRecorder() c = e.NewContext(req, rec).(*echoContext) err = c.JSON(http.StatusOK, user{1, "Jon Snow"}) if assert.NoError(t, err) { assert.Equal(t, http.StatusOK, rec.Status()) assert.Equal(t, MIMEApplicationJSONCharsetUTF8, rec.Header().Get(HeaderContentType)) assert.Equal(t, userJSON, rec.Body.String()) } // JSON (error) rec = test.NewResponseRecorder() c = e.NewContext(req, rec).(*echoContext) err = c.JSON(http.StatusOK, make(chan bool)) assert.Error(t, err) // JSONP rec = test.NewResponseRecorder() c = e.NewContext(req, rec).(*echoContext) callback := "callback" err = c.JSONP(http.StatusOK, callback, user{1, "Jon Snow"}) if assert.NoError(t, err) { assert.Equal(t, http.StatusOK, rec.Status()) assert.Equal(t, MIMEApplicationJavaScriptCharsetUTF8, rec.Header().Get(HeaderContentType)) assert.Equal(t, callback+"("+userJSON+");", rec.Body.String()) } // XML rec = test.NewResponseRecorder() c = e.NewContext(req, rec).(*echoContext) err = c.XML(http.StatusOK, user{1, "Jon Snow"}) if assert.NoError(t, err) { assert.Equal(t, http.StatusOK, rec.Status()) assert.Equal(t, MIMEApplicationXMLCharsetUTF8, rec.Header().Get(HeaderContentType)) assert.Equal(t, xml.Header+userXML, rec.Body.String()) } // XML (error) rec = test.NewResponseRecorder() c = e.NewContext(req, rec).(*echoContext) err = c.XML(http.StatusOK, make(chan bool)) assert.Error(t, err) // String rec = test.NewResponseRecorder() c = e.NewContext(req, rec).(*echoContext) err = c.String(http.StatusOK, "Hello, World!") if assert.NoError(t, err) { assert.Equal(t, http.StatusOK, rec.Status()) assert.Equal(t, MIMETextPlainCharsetUTF8, rec.Header().Get(HeaderContentType)) assert.Equal(t, "Hello, World!", rec.Body.String()) } // HTML rec = test.NewResponseRecorder() c = e.NewContext(req, rec).(*echoContext) err = c.HTML(http.StatusOK, "Hello, <strong>World!</strong>") if assert.NoError(t, err) { assert.Equal(t, http.StatusOK, rec.Status()) assert.Equal(t, MIMETextHTMLCharsetUTF8, rec.Header().Get(HeaderContentType)) assert.Equal(t, "Hello, <strong>World!</strong>", rec.Body.String()) } // Stream rec = test.NewResponseRecorder() c = e.NewContext(req, rec).(*echoContext) r := strings.NewReader("response from a stream") err = c.Stream(http.StatusOK, "application/octet-stream", r) if assert.NoError(t, err) { assert.Equal(t, http.StatusOK, rec.Status()) assert.Equal(t, "application/octet-stream", rec.Header().Get(HeaderContentType)) assert.Equal(t, "response from a stream", rec.Body.String()) } // Attachment rec = test.NewResponseRecorder() c = e.NewContext(req, rec).(*echoContext) file, err := os.Open("_fixture/images/walle.png") if assert.NoError(t, err) { err = c.Attachment(file, "walle.png") if assert.NoError(t, err) { assert.Equal(t, http.StatusOK, rec.Status()) assert.Equal(t, "attachment; filename=walle.png", rec.Header().Get(HeaderContentDisposition)) assert.Equal(t, 219885, rec.Body.Len()) } } // Inline rec = test.NewResponseRecorder() c = e.NewContext(req, rec).(*echoContext) file, err = os.Open("_fixture/images/walle.png") if assert.NoError(t, err) { err = c.Inline(file, "walle.png") if assert.NoError(t, err) { assert.Equal(t, http.StatusOK, rec.Status()) assert.Equal(t, "inline; filename=walle.png", rec.Header().Get(HeaderContentDisposition)) assert.Equal(t, 219885, rec.Body.Len()) } } // NoContent rec = test.NewResponseRecorder() c = e.NewContext(req, rec).(*echoContext) c.NoContent(http.StatusOK) assert.Equal(t, http.StatusOK, rec.Status()) // Error rec = test.NewResponseRecorder() c = e.NewContext(req, rec).(*echoContext) c.Error(errors.New("error")) assert.Equal(t, http.StatusInternalServerError, rec.Status()) // Reset c.Reset(req, test.NewResponseRecorder()) } func TestContextCookie(t *testing.T) { e := New() req := test.NewRequest(GET, "/", nil) theme := "theme=light" user := "user=Jon Snow" req.Header().Add(HeaderCookie, theme) req.Header().Add(HeaderCookie, user) rec := test.NewResponseRecorder() c := e.NewContext(req, rec).(*echoContext) // Read single cookie, err := c.Cookie("theme") if assert.NoError(t, err) { assert.Equal(t, "theme", cookie.Name()) assert.Equal(t, "light", cookie.Value()) } // Read multiple for _, cookie := range c.Cookies() { switch cookie.Name() { case "theme": assert.Equal(t, "light", cookie.Value()) case "user": assert.Equal(t, "Jon Snow", cookie.Value()) } } // Write cookie = &test.Cookie{Cookie: &http.Cookie{ Name: "SSID", Value: "Ap4PGTEq", Domain: "labstack.com", Path: "/", Expires: time.Now(), Secure: true, HttpOnly: true, }} c.SetCookie(cookie) assert.Contains(t, rec.Header().Get(HeaderSetCookie), "SSID") assert.Contains(t, rec.Header().Get(HeaderSetCookie), "Ap4PGTEq") assert.Contains(t, rec.Header().Get(HeaderSetCookie), "labstack.com") assert.Contains(t, rec.Header().Get(HeaderSetCookie), "Secure") assert.Contains(t, rec.Header().Get(HeaderSetCookie), "HttpOnly") } func TestContextPath(t *testing.T) { e := New() r := e.Router() r.Add(GET, "/users/:id", nil, e) c := e.NewContext(nil, nil) r.Find(GET, "/users/1", c) assert.Equal(t, "/users/:id", c.Path()) r.Add(GET, "/users/:uid/files/:fid", nil, e) c = e.NewContext(nil, nil) r.Find(GET, "/users/1/files/1", c) assert.Equal(t, "/users/:uid/files/:fid", c.Path()) } func TestContextPathParam(t *testing.T) { e := New() req := test.NewRequest(GET, "/", nil) c := e.NewContext(req, nil) // ParamNames c.SetParamNames("uid", "fid") assert.EqualValues(t, []string{"uid", "fid"}, c.ParamNames()) // ParamValues c.SetParamValues("101", "501") assert.EqualValues(t, []string{"101", "501"}, c.ParamValues()) // P assert.Equal(t, "101", c.P(0)) // Param assert.Equal(t, "501", c.Param("fid")) } func TestContextFormValue(t *testing.T) { f := make(url.Values) f.Set("name", "Jon Snow") f.Set("email", "[email protected]") e := New() req := test.NewRequest(POST, "/", strings.NewReader(f.Encode())) req.Header().Add(HeaderContentType, MIMEApplicationForm) c := e.NewContext(req, nil) // FormValue assert.Equal(t, "Jon Snow", c.FormValue("name")) assert.Equal(t, "[email protected]", c.FormValue("email")) // FormParams assert.Equal(t, map[string][]string{ "name": []string{"Jon Snow"}, "email": []string{"[email protected]"}, }, c.FormParams()) } func TestContextQueryParam(t *testing.T) { q := make(url.Values) q.Set("name", "Jon Snow") q.Set("email", "[email protected]") req := test.NewRequest(GET, "/?"+q.Encode(), nil) e := New() c := e.NewContext(req, nil) // QueryParam assert.Equal(t, "Jon Snow", c.QueryParam("name")) assert.Equal(t, "[email protected]", c.QueryParam("email")) // QueryParams assert.Equal(t, map[string][]string{ "name": []string{"Jon Snow"}, "email": []string{"[email protected]"}, }, c.QueryParams()) } func TestContextFormFile(t *testing.T) { e := New() buf := new(bytes.Buffer) mr := multipart.NewWriter(buf) w, err := mr.CreateFormFile("file", "test") if assert.NoError(t, err) { w.Write([]byte("test")) } mr.Close() req := test.NewRequest(POST, "/", buf) req.Header().Set(HeaderContentType, mr.FormDataContentType()) rec := test.NewResponseRecorder() c := e.NewContext(req, rec) f, err := c.FormFile("file") if assert.NoError(t, err) { assert.Equal(t, "test", f.Filename) } } func TestContextMultipartForm(t *testing.T) { e := New() buf := new(bytes.Buffer) mw := multipart.NewWriter(buf) mw.WriteField("name", "Jon Snow") mw.Close() req := test.NewRequest(POST, "/", buf) req.Header().Set(HeaderContentType, mw.FormDataContentType()) rec := test.NewResponseRecorder() c := e.NewContext(req, rec) f, err := c.MultipartForm() if assert.NoError(t, err) { assert.NotNil(t, f) } } func TestContextRedirect(t *testing.T) { e := New() req := test.NewRequest(GET, "/", nil) rec := test.NewResponseRecorder() c := e.NewContext(req, rec) assert.Equal(t, nil, c.Redirect(http.StatusMovedPermanently, "http://labstack.github.io/echo")) assert.Equal(t, http.StatusMovedPermanently, rec.Status()) assert.Equal(t, "http://labstack.github.io/echo", rec.Header().Get(HeaderLocation)) assert.Error(t, c.Redirect(310, "http://labstack.github.io/echo")) } func TestContextEmbedded(t *testing.T) { var c Context c = new(echoContext) c.SetStdContext(context.WithValue(c, "key", "val")) assert.Equal(t, "val", c.Value("key")) now := time.Now() ctx, _ := context.WithDeadline(context.Background(), now) c.SetStdContext(ctx) n, _ := ctx.Deadline() assert.Equal(t, now, n) assert.Equal(t, context.DeadlineExceeded, c.Err()) assert.NotNil(t, c.Done()) } func TestContextStore(t *testing.T) { var c Context c = new(echoContext) c.Set("name", "Jon Snow") assert.Equal(t, "Jon Snow", c.Get("name")) } func TestContextServeContent(t *testing.T) { e := New() req := test.NewRequest(GET, "/", nil) rec := test.NewResponseRecorder() c := e.NewContext(req, rec) fs := http.Dir("_fixture/images") f, err := fs.Open("walle.png") if assert.NoError(t, err) { fi, err := f.Stat() if assert.NoError(t, err) { // Not cached if assert.NoError(t, c.ServeContent(f, fi.Name(), fi.ModTime())) { assert.Equal(t, http.StatusOK, rec.Status()) } // Cached rec = test.NewResponseRecorder() c = e.NewContext(req, rec) req.Header().Set(HeaderIfModifiedSince, fi.ModTime().UTC().Format(http.TimeFormat)) if assert.NoError(t, c.ServeContent(f, fi.Name(), fi.ModTime())) { assert.Equal(t, http.StatusNotModified, rec.Status()) } } } } func TestContextHandler(t *testing.T) { e := New() r := e.Router() b := new(bytes.Buffer) r.Add(GET, "/handler", func(Context) error { _, err := b.Write([]byte("handler")) return err }, e) c := e.NewContext(nil, nil) r.Find(GET, "/handler", c) c.Handler()(c) assert.Equal(t, "handler", b.String()) }
unlicense
newincpp/LunaticPlatypus
LunaticPlatypus/Alembic/AbcGeom/IPolyMesh.h
10807
//-***************************************************************************** // // Copyright (c) 2009-2012, // Sony Pictures Imageworks Inc. and // Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Sony Pictures Imageworks, nor // Industrial Light & Magic, nor the names of their 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. // //-***************************************************************************** #ifndef _Alembic_AbcGeom_IPolyMesh_h_ #define _Alembic_AbcGeom_IPolyMesh_h_ #include <Alembic/Util/Export.h> #include <Alembic/AbcGeom/Foundation.h> #include <Alembic/AbcGeom/SchemaInfoDeclarations.h> #include <Alembic/AbcGeom/IFaceSet.h> #include <Alembic/AbcGeom/IGeomParam.h> #include <Alembic/AbcGeom/IGeomBase.h> namespace Alembic { namespace AbcGeom { namespace ALEMBIC_VERSION_NS { //-***************************************************************************** class ALEMBIC_EXPORT IPolyMeshSchema : public IGeomBaseSchema<PolyMeshSchemaInfo> { public: class Sample { public: typedef Sample this_type; // Users don't ever create this data directly. Sample() { reset(); } Abc::P3fArraySamplePtr getPositions() const { return m_positions; } Abc::V3fArraySamplePtr getVelocities() const { return m_velocities; } Abc::Int32ArraySamplePtr getFaceIndices() const { return m_indices; } Abc::Int32ArraySamplePtr getFaceCounts() const { return m_counts; } Abc::Box3d getSelfBounds() const { return m_selfBounds; } bool valid() const { return m_positions && m_indices && m_counts; } void reset() { m_positions.reset(); m_velocities.reset(); m_indices.reset(); m_counts.reset(); m_selfBounds.makeEmpty(); } ALEMBIC_OPERATOR_BOOL( valid() ); protected: friend class IPolyMeshSchema; Abc::P3fArraySamplePtr m_positions; Abc::V3fArraySamplePtr m_velocities; Abc::Int32ArraySamplePtr m_indices; Abc::Int32ArraySamplePtr m_counts; Abc::Box3d m_selfBounds; }; //-************************************************************************* // POLY MESH SCHEMA //-************************************************************************* public: //! By convention we always define this_type in AbcGeom classes. //! Used by unspecified-bool-type conversion below typedef IPolyMeshSchema this_type; //-************************************************************************* // CONSTRUCTION, DESTRUCTION, ASSIGNMENT //-************************************************************************* //! The default constructor creates an empty OPolyMeshSchema //! ... IPolyMeshSchema() {} //! This constructor creates a new mesh reader. //! The first argument is the parent ICompoundProperty, from which the //! error handler policy for is derived. The second argument is the name //! of the ICompoundProperty that contains this schemas properties. The //! remaining optional arguments can be used to override the //! ErrorHandlerPolicy and to specify schema interpretation matching. IPolyMeshSchema( const ICompoundProperty &iParent, const std::string &iName, const Abc::Argument &iArg0 = Abc::Argument(), const Abc::Argument &iArg1 = Abc::Argument() ) : IGeomBaseSchema<PolyMeshSchemaInfo>( iParent, iName, iArg0, iArg1 ) { init( iArg0, iArg1 ); } //! This constructor wraps an existing ICompoundProperty as the mesh //! reader, and the error handler policy is derived from it. //! The remaining optional arguments can be used to override the //! ErrorHandlerPolicy and to specify schema interpretation matching. IPolyMeshSchema( const ICompoundProperty &iProp, const Abc::Argument &iArg0 = Abc::Argument(), const Abc::Argument &iArg1 = Abc::Argument() ) : IGeomBaseSchema<PolyMeshSchemaInfo>( iProp, iArg0, iArg1 ) { init( iArg0, iArg1 ); } //! Copy constructor. IPolyMeshSchema(const IPolyMeshSchema& iCopy) : IGeomBaseSchema<PolyMeshSchemaInfo>() { *this = iCopy; } const IPolyMeshSchema & operator=(const IPolyMeshSchema & rhs); //! Return the number of samples contained in the property. //! This can be any number, including zero. //! This returns the number of samples that were written, independently //! of whether or not they were constant. size_t getNumSamples() const { return m_positionsProperty.getNumSamples(); } //! Return the topological variance. //! This indicates how the mesh may change. MeshTopologyVariance getTopologyVariance() const; //! Ask if we're constant - no change in value amongst samples, //! regardless of the time sampling. bool isConstant() const { return getTopologyVariance() == kConstantTopology; } //! Time information. //! Any of the properties could be the bearer of the time //! sampling information, which otherwise defaults to Identity. AbcA::TimeSamplingPtr getTimeSampling() const { if ( m_positionsProperty.valid() ) { return m_positionsProperty.getTimeSampling(); } else { return getObject().getArchive().getTimeSampling( 0 ); } } //-************************************************************************* void get( Sample &oSample, const Abc::ISampleSelector &iSS = Abc::ISampleSelector() ) const { ALEMBIC_ABC_SAFE_CALL_BEGIN( "IPolyMeshSchema::get()" ); m_positionsProperty.get( oSample.m_positions, iSS ); m_indicesProperty.get( oSample.m_indices, iSS ); m_countsProperty.get( oSample.m_counts, iSS ); m_selfBoundsProperty.get( oSample.m_selfBounds, iSS ); if ( m_velocitiesProperty && m_velocitiesProperty.getNumSamples() > 0 ) { m_velocitiesProperty.get( oSample.m_velocities, iSS ); } // Could error check here. ALEMBIC_ABC_SAFE_CALL_END(); } Sample getValue( const Abc::ISampleSelector &iSS = Abc::ISampleSelector() ) const { Sample smp; get( smp, iSS ); return smp; } IV2fGeomParam getUVsParam() const { return m_uvsParam; } IN3fGeomParam getNormalsParam() const { return m_normalsParam; } Abc::IInt32ArrayProperty getFaceCountsProperty() const { return m_countsProperty; } Abc::IInt32ArrayProperty getFaceIndicesProperty() const { return m_indicesProperty; } Abc::IP3fArrayProperty getPositionsProperty() const { return m_positionsProperty; } Abc::IV3fArrayProperty getVelocitiesProperty() const { return m_velocitiesProperty; } //-************************************************************************* // ABC BASE MECHANISMS // These functions are used by Abc to deal with errors, rewrapping, // and so on. //-************************************************************************* //! Reset returns this function set to an empty, default //! state. void reset() { m_positionsProperty.reset(); m_velocitiesProperty.reset(); m_indicesProperty.reset(); m_countsProperty.reset(); m_uvsParam.reset(); m_normalsParam.reset(); IGeomBaseSchema<PolyMeshSchemaInfo>::reset(); } //! Valid returns whether this function set is //! valid. bool valid() const { return ( IGeomBaseSchema<PolyMeshSchemaInfo>::valid() && m_positionsProperty.valid() && m_indicesProperty.valid() && m_countsProperty.valid() ); } // FaceSet related //! Appends the names of any FaceSets for this PolyMesh. void getFaceSetNames (std::vector <std::string> & oFaceSetNames); IFaceSet getFaceSet( const std::string &iFaceSetName ); bool hasFaceSet( const std::string &iFaceSetName ); //! unspecified-bool-type operator overload. //! ... ALEMBIC_OVERRIDE_OPERATOR_BOOL( IPolyMeshSchema::valid() ); protected: void init( const Abc::Argument &iArg0, const Abc::Argument &iArg1 ); Abc::IP3fArrayProperty m_positionsProperty; Abc::IV3fArrayProperty m_velocitiesProperty; Abc::IInt32ArrayProperty m_indicesProperty; Abc::IInt32ArrayProperty m_countsProperty; IV2fGeomParam m_uvsParam; IN3fGeomParam m_normalsParam; // FaceSets, this starts as empty until client // code attempts to access facesets. bool m_faceSetsLoaded; std::map <std::string, IFaceSet> m_faceSets; Alembic::Util::mutex m_faceSetsMutex; void loadFaceSetNames(); }; //-***************************************************************************** typedef Abc::ISchemaObject<IPolyMeshSchema> IPolyMesh; typedef Util::shared_ptr< IPolyMesh > IPolyMeshPtr; } // End namespace ALEMBIC_VERSION_NS using namespace ALEMBIC_VERSION_NS; } // End namespace AbcGeom } // End namespace Alembic #endif
unlicense
twolfson/sublime-files
Packages/HTML/encode_html_entities.py
764
import sublime import sublime_plugin from html.entities import codepoint2name as cp2n class EncodeHtmlEntities(sublime_plugin.TextCommand): def run(self, edit, **args): view = self.view for sel in view.sel(): buf = [] for pt in range(sel.begin(), sel.end()): ch = view.substr(pt) ch_ord = ord(ch) if (not view.match_selector(pt, ('meta.tag - string, constant.character.entity')) and ch_ord in cp2n and not (ch in ('"', "'") and view.match_selector(pt, 'string'))): ch = '&%s;' % cp2n[ch_ord] buf.append(ch) view.replace(edit, sel, ''.join(buf))
unlicense
harveyiliu/mcml-photon-scattering-python
README.md
191
monte-carlo-photon-scattering ============================= Derived from the MCML C-based code set developed for Monte Carlo simulation of photon distribution in multi-layered turbid media.
unlicense
GuyFawkesFromKorea/RSBP
JWLibrary.FFmpeg/FrameDropChecker.cs
2179
using System; using System.Timers; namespace JWLibrary.FFmpeg { class FrameDropChecker : IDisposable { #region delegate events public event EventHandler<EventArgs> FrameDroped; protected virtual void OnFrameDroped(object sender, EventArgs e) { if (FrameDroped != null) { FrameDroped(this, e); } } #endregion #region variable public int FrameDropCount { get; set; } public bool IsLimit { get; set; } private const int FRAME_LIMIT_COUNT = 50; private Timer _timer; private int _timerElapsedCount; #endregion #region constructor public FrameDropChecker() { _timer = new Timer(); _timer.Interval = 500; _timer.Elapsed += _timer_Elapsed; } public FrameDropChecker(double chkTime) { _timer = new Timer(); _timer.Interval = chkTime; _timer.Elapsed += _timer_Elapsed; } #endregion #region funtions public void FrameDropCheckStart() { _timerElapsedCount = 0; FrameDropCount = 0; IsLimit = false; _timer.Start(); } public void FrameDropCheckStop() { _timer.Enabled = false; _timer.Stop(); } #endregion #region event private void _timer_Elapsed(object sender, ElapsedEventArgs e) { if (FRAME_LIMIT_COUNT < FrameDropCount) { IsLimit = true; OnFrameDroped(this, new EventArgs()); } else { if (_timerElapsedCount == FRAME_LIMIT_COUNT) _timerElapsedCount = 0; } _timerElapsedCount++; } #endregion #region dispose public void Dispose() { if (_timer != null) { _timer.Stop(); _timer.Dispose(); _timer = null; } } #endregion } }
unlicense
AqD/JXTN
jxtn-jfx-makers/src/javafx/scene/media/TrackMakerExt.java
605
// @formatter:off /* * Unlicensed, generated by javafx.ftl */ package javafx.scene.media; /** * {@link Track}建構器延伸(供客製化) * * @author JarReflectionDataLoader-1.0.0 * @version jfxrt.jar * @param <Z> 要建構的物件型態(需繼承{@link Track}) * @param <B> 建構器本身的型態(需繼承{@link TrackMaker}) */ @javax.annotation.Generated("Generated by javafx.ftl") @SuppressWarnings("all") public interface TrackMakerExt<Z extends Track, B extends TrackMaker<Z, B>> extends jxtn.jfx.makers.AbstractMakerExt<Z, B> { // nothing yet }
unlicense
bigdinotech/zephyr
drivers/sensor/mpu6050/mpu6050.h
1795
/* * Copyright (c) 2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef __SENSOR_MPU6050_H__ #define __SENSOR_MPU6050_H__ #include <device.h> #include <gpio.h> #include <misc/util.h> #include <zephyr/types.h> #define SYS_LOG_DOMAIN "MPU6050" #define SYS_LOG_LEVEL CONFIG_SYS_LOG_SENSOR_LEVEL #include <logging/sys_log.h> #define MPU6050_REG_CHIP_ID 0x75 #define MPU6050_CHIP_ID 0x68 #define MPU6050_REG_GYRO_CFG 0x1B #define MPU6050_GYRO_FS_SHIFT 3 #define MPU6050_REG_ACCEL_CFG 0x1C #define MPU6050_ACCEL_FS_SHIFT 3 #define MPU6050_REG_INT_EN 0x38 #define MPU6050_DRDY_EN BIT(0) #define MPU6050_REG_DATA_START 0x3B #define MPU6050_REG_PWR_MGMT1 0x6B #define MPU6050_SLEEP_EN BIT(6) /* measured in degrees/sec x10 to avoid floating point */ static const u16_t mpu6050_gyro_sensitivity_x10[] = { 1310, 655, 328, 164 }; struct mpu6050_data { struct device *i2c; s16_t accel_x; s16_t accel_y; s16_t accel_z; u16_t accel_sensitivity_shift; s16_t temp; s16_t gyro_x; s16_t gyro_y; s16_t gyro_z; u16_t gyro_sensitivity_x10; #ifdef CONFIG_MPU6050_TRIGGER struct device *gpio; struct gpio_callback gpio_cb; struct sensor_trigger data_ready_trigger; sensor_trigger_handler_t data_ready_handler; #if defined(CONFIG_MPU6050_TRIGGER_OWN_THREAD) char __stack thread_stack[CONFIG_MPU6050_THREAD_STACK_SIZE]; struct k_thread thread; struct k_sem gpio_sem; #elif defined(CONFIG_MPU6050_TRIGGER_GLOBAL_THREAD) struct k_work work; struct device *dev; #endif #endif /* CONFIG_MPU6050_TRIGGER */ }; #ifdef CONFIG_MPU6050_TRIGGER int mpu6050_trigger_set(struct device *dev, const struct sensor_trigger *trig, sensor_trigger_handler_t handler); int mpu6050_init_interrupt(struct device *dev); #endif #endif /* __SENSOR_MPU6050__ */
apache-2.0
ioanrogers/aws-sdk-perl
auto-lib/Paws/DMS/ModifyReplicationInstanceResponse.pm
458
package Paws::DMS::ModifyReplicationInstanceResponse; use Moose; has ReplicationInstance => (is => 'ro', isa => 'Paws::DMS::ReplicationInstance'); has _request_id => (is => 'ro', isa => 'Str'); ### main pod documentation begin ### =head1 NAME Paws::DMS::ModifyReplicationInstanceResponse =head1 ATTRIBUTES =head2 ReplicationInstance => L<Paws::DMS::ReplicationInstance> The modified replication instance. =head2 _request_id => Str =cut 1;
apache-2.0
gocd/gocd
server/src/main/java/com/thoughtworks/go/server/service/materials/NoOpPoller.java
1712
/* * 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. */ package com.thoughtworks.go.server.service.materials; import java.io.File; import java.util.List; import com.thoughtworks.go.config.materials.SubprocessExecutionContext; import com.thoughtworks.go.domain.materials.Material; import com.thoughtworks.go.domain.materials.Modification; import com.thoughtworks.go.domain.materials.Revision; public class NoOpPoller implements MaterialPoller<Material> { @Override public List<Modification> latestModification(Material material, File baseDir, SubprocessExecutionContext execCtx) { throw new RuntimeException("unknown material type " + material.getDisplayName()); } @Override public List<Modification> modificationsSince(Material material, File baseDir, Revision revision, SubprocessExecutionContext execCtx) { throw new RuntimeException("unknown material type " + material.getDisplayName()); } @Override public void checkout(Material material, File baseDir, Revision revision, SubprocessExecutionContext execCtx) { throw new RuntimeException("unknown material type " + material.getDisplayName()); } }
apache-2.0
toenu23/zeroclickinfo-spice
lib/DDG/Spice/SalesTax.pm
2141
package DDG::Spice::SalesTax; #ABSTRACT: Returns the sales tax for any state (not including territories) in the United States. use DDG::Spice; use Locale::SubCountry; use YAML::XS qw( Load ); name "SalesTax"; source "http://taxratesapi.avalara.com/"; description 'Returns the sales tax of the specified state or territory in the United States'; primary_example_queries 'Sales tax for pennsylvania', 'Sales tax pa'; secondary_example_queries 'what is sales tax for mississippi'; topics 'special_interest', 'geography', 'travel'; category 'random'; code_url "https://github.com/duckduckgo/zeroclickinfo-spice/blob/master/lib/DDG/Spice/SalesTax.pm"; attribution github => ["MrChrisW", "Chris Wilson"], web => ["http://chrisjwilson.com", "Chris Wilson"], github => ['https://github.com/javathunderman', 'Thomas Denizou']; triggers any => 'sales tax for', 'sales tax', 'sales tax in'; spice from => '(.*)/(.*)'; spice to => 'https://taxrates.api.avalara.com/postal?country=usa&postal=$1&apikey={{ENV{DDG_SPICE_SALESTAX_APIKEY}}}'; spice wrap_jsonp_callback => 1; #Create US SubCountry object my $US = new Locale::SubCountry("US"); #State to Zip Code my $zipcodes = Load(scalar share('zipcodes.yml')->slurp); # Handle statement handle remainder_lc => sub { my ($state,$zip); #Define vars s/^what is (the)?//g; # strip common words return unless $_; # Guard against "no answer" # Washington D.C is a district and is not supported by the SubCountry package. if(m/\b(washington\s(dc|d\.c))\b/i) { $state = "Washington D.C"; } else { # $US->full_name returns the full state name based on the ISO3166 code $state = $US->full_name($_); # Check for state using ISO code (PA) if($state eq "unknown") { $state = $US->full_name($US->code($_)); # If state is "unknown" search for code using full state name (Pennsylvania) } } $zip = $zipcodes->{$state}; # state name=> zip code # error checking return if $state eq "unknown"; return unless (defined $state and defined $zip); return $zip, $state; # return result }; 1;
apache-2.0
sumomoshinqi/tips4mb
README.md
2501
| 文件名 | 描述 | | ------------- | ------------ | |[alfred_workflow.md](https://github.com/urmyfaith/tips4mb/tree/master/alfred_workflow.md)| alfred的几个workflowd | |[bogon_problem.md](https://github.com/urmyfaith/tips4mb/tree/master/bogon_problem.md)| 终端计算机名显示的问题 | |[browser_safari_chrome.md](https://github.com/urmyfaith/tips4mb/tree/master/browser_safari_chrome.md)| 浏览器快捷键 | |[compress_decompress.md](https://github.com/urmyfaith/tips4mb/tree/master/compress_decompress.md)| 压缩,解压缩 | |[diff_compare_file.md](https://github.com/urmyfaith/tips4mb/tree/master/diff_compare_file.md)| 文件比较 | |[disable_enable_dashborad.md](https://github.com/urmyfaith/tips4mb/tree/master/disable_enable_dashborad.md)| dashboar的禁用 | |[filename-chmod.md](https://github.com/urmyfaith/tips4mb/tree/master/filename-chmod.md)| 文件名权限修改 | |[find_file_on_mac_os.md](https://github.com/urmyfaith/tips4mb/tree/master/find_file_on_mac_os.md)| 查找文件具体位置 | |[grep](https://github.com/urmyfaith/tips4mb/tree/master/grep)| 字符查找 | |[jump2folder.md](https://github.com/urmyfaith/tips4mb/tree/master/jump2folder.md)| 快速打开finder所在目录 | |[prepare4md](https://github.com/urmyfaith/tips4mb/tree/master/prepare4md)| 根据目录下文件快速生成md表格 | |[quich_input_symbol.md](https://github.com/urmyfaith/tips4mb/tree/master/quich_input_symbol.md)| 快速输入特殊字符 | |[README.md](https://github.com/urmyfaith/tips4mb/tree/master/README.md)| 读我 | |[recovery_min_windows.md](https://github.com/urmyfaith/tips4mb/tree/master/recovery_min_windows.md)| 最小化后键盘恢复窗口 | |[restart.md](https://github.com/urmyfaith/tips4mb/tree/master/restart.md)| 重启 | |[screencapture_usage.md](https://github.com/urmyfaith/tips4mb/tree/master/screencapture_usage.md)| 截图快捷键 | |[short_command_alias.md](https://github.com/urmyfaith/tips4mb/tree/master/short_command_alias.md)| 重命名命名 | |[showHiddenFiles.md](https://github.com/urmyfaith/tips4mb/tree/master/showHiddenFiles.md)| 显示隐藏文件 | |[showStorageOfDiretory.md](https://github.com/urmyfaith/tips4mb/tree/master/showStorageOfDiretory.md)| 显示文件夹大小 | |[solve_command_not_found.md](https://github.com/urmyfaith/tips4mb/tree/master/solve_command_not_found.md)| 命令找不到怎么办? | |[terminal_tab_usage.md](https://github.com/urmyfaith/tips4mb/tree/master/terminal_tab_usage.md)| 终端移动光标 |
apache-2.0
bootstraponline-archive/gerrit-mirror
gerrit-server/src/test/java/com/google/gerrit/testutil/InMemoryModule.java
8025
// Copyright (C) 2013 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.gerrit.testutil; import static com.google.common.base.Preconditions.checkState; import static com.google.inject.Scopes.SINGLETON; import com.google.common.net.InetAddresses; import com.google.gerrit.common.ChangeHooks; import com.google.gerrit.common.DisabledChangeHooks; import com.google.gerrit.reviewdb.client.AuthType; import com.google.gerrit.reviewdb.server.ReviewDb; import com.google.gerrit.server.GerritPersonIdent; import com.google.gerrit.server.GerritPersonIdentProvider; import com.google.gerrit.server.RemotePeer; import com.google.gerrit.server.cache.h2.DefaultCacheFactory; import com.google.gerrit.server.change.MergeabilityChecksExecutorModule; import com.google.gerrit.server.config.AllProjectsName; import com.google.gerrit.server.config.AllProjectsNameProvider; import com.google.gerrit.server.config.AnonymousCowardName; import com.google.gerrit.server.config.AnonymousCowardNameProvider; import com.google.gerrit.server.config.CanonicalWebUrlModule; import com.google.gerrit.server.config.CanonicalWebUrlProvider; import com.google.gerrit.server.config.FactoryModule; import com.google.gerrit.server.config.GerritGlobalModule; import com.google.gerrit.server.config.GerritServerConfig; import com.google.gerrit.server.config.SitePath; import com.google.gerrit.server.config.TrackingFooters; import com.google.gerrit.server.config.TrackingFootersProvider; import com.google.gerrit.server.git.GitRepositoryManager; import com.google.gerrit.server.git.PerThreadRequestScope; import com.google.gerrit.server.index.ChangeSchemas; import com.google.gerrit.server.index.IndexModule.IndexType; import com.google.gerrit.server.mail.SignedTokenEmailTokenVerifier; import com.google.gerrit.server.mail.SmtpEmailSender; import com.google.gerrit.server.schema.Current; import com.google.gerrit.server.schema.DataSourceType; import com.google.gerrit.server.schema.SchemaCreator; import com.google.gerrit.server.schema.SchemaVersion; import com.google.gerrit.server.ssh.NoSshKeyCache; import com.google.gwtorm.server.OrmException; import com.google.gwtorm.server.SchemaFactory; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.Provider; import com.google.inject.Provides; import com.google.inject.ProvisionException; import com.google.inject.Singleton; import com.google.inject.TypeLiteral; import com.google.inject.servlet.RequestScoped; import org.eclipse.jgit.lib.Config; import org.eclipse.jgit.lib.PersonIdent; import java.io.File; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.net.InetSocketAddress; import java.net.SocketAddress; public class InMemoryModule extends FactoryModule { public static Config newDefaultConfig() { Config cfg = new Config(); cfg.setEnum("auth", null, "type", AuthType.DEVELOPMENT_BECOME_ANY_ACCOUNT); cfg.setString("gerrit", null, "basePath", "git"); cfg.setString("gerrit", null, "allProjects", "Test-Projects"); cfg.setString("user", null, "name", "Gerrit Code Review"); cfg.setString("user", null, "email", "gerrit@localhost"); cfg.setBoolean("sendemail", null, "enable", false); cfg.setString("cache", null, "directory", null); cfg.setString("index", null, "type", "lucene"); cfg.setBoolean("index", "lucene", "testInmemory", true); cfg.setInt("index", "lucene", "testVersion", ChangeSchemas.getLatest().getVersion()); return cfg; } private final Config cfg; public InMemoryModule() { this(newDefaultConfig()); } public InMemoryModule(Config cfg) { this.cfg = cfg; } public void inject(Object instance) { Guice.createInjector(this).injectMembers(instance); } @Override protected void configure() { // For simplicity, don't create child injectors, just use this one to get a // few required modules. Injector cfgInjector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(Config.class).annotatedWith(GerritServerConfig.class) .toInstance(cfg); } }); install(cfgInjector.getInstance(GerritGlobalModule.class)); bindScope(RequestScoped.class, PerThreadRequestScope.REQUEST); install(new SchemaVersion.Module()); bind(File.class).annotatedWith(SitePath.class).toInstance(new File(".")); bind(Config.class).annotatedWith(GerritServerConfig.class).toInstance(cfg); bind(SocketAddress.class).annotatedWith(RemotePeer.class).toInstance( new InetSocketAddress(InetAddresses.forString("127.0.0.1"), 1234)); bind(PersonIdent.class) .annotatedWith(GerritPersonIdent.class) .toProvider(GerritPersonIdentProvider.class); bind(String.class) .annotatedWith(AnonymousCowardName.class) .toProvider(AnonymousCowardNameProvider.class); bind(AllProjectsName.class) .toProvider(AllProjectsNameProvider.class); bind(GitRepositoryManager.class) .to(InMemoryRepositoryManager.class); bind(InMemoryRepositoryManager.class).in(SINGLETON); bind(TrackingFooters.class).toProvider(TrackingFootersProvider.class) .in(SINGLETON); bind(DataSourceType.class) .to(InMemoryH2Type.class); bind(new TypeLiteral<SchemaFactory<ReviewDb>>() {}) .to(InMemoryDatabase.class); bind(ChangeHooks.class).to(DisabledChangeHooks.class); install(NoSshKeyCache.module()); install(new CanonicalWebUrlModule() { @Override protected Class<? extends Provider<String>> provider() { return CanonicalWebUrlProvider.class; } }); install(new DefaultCacheFactory.Module()); install(new SmtpEmailSender.Module()); install(new SignedTokenEmailTokenVerifier.Module()); install(new MergeabilityChecksExecutorModule()); IndexType indexType = null; try { indexType = cfg.getEnum("index", null, "type", IndexType.LUCENE); } catch (IllegalArgumentException e) { // Custom index type, caller must provide their own module. } if (indexType != null) { switch (indexType) { case LUCENE: install(luceneIndexModule()); break; default: throw new ProvisionException( "index type unsupported in tests: " + indexType); } } } @Provides @Singleton InMemoryDatabase getInMemoryDatabase(@Current SchemaVersion schemaVersion, SchemaCreator schemaCreator) throws OrmException { return new InMemoryDatabase(schemaVersion, schemaCreator); } private Module luceneIndexModule() { try { int version = cfg.getInt("index", "lucene", "testVersion", -1); checkState(ChangeSchemas.ALL.containsKey(version), "invalid index.lucene.testVersion %s", version); Class<?> clazz = Class.forName("com.google.gerrit.lucene.LuceneIndexModule"); Constructor<?> c = clazz.getConstructor(Integer.class, int.class, String.class); return (Module) c.newInstance(version, 0, null); } catch (ClassNotFoundException | SecurityException | NoSuchMethodException | IllegalArgumentException | InstantiationException | IllegalAccessException | InvocationTargetException e) { ProvisionException pe = new ProvisionException(e.getMessage()); pe.initCause(e); throw pe; } } }
apache-2.0
hpcloud/stackato-go
server/config_node.go
586
package server import ( "sync" "github.com/hpcloud/log" ) type NodeInfo struct { Roles map[string]string `json:"roles"` // role name -> role status } // NodeConfig corresponds to Kato's /node config, which is a hash of ipaddr => NodeInfo type NodeConfig map[string]NodeInfo var nodeConfig *Config var onceNodeConfig sync.Once func GetNodeConfig() *NodeConfig { onceNodeConfig.Do(createNodeConfig) return nodeConfig.GetConfig().(*NodeConfig) } func createNodeConfig() { var err error nodeConfig, err = NewConfig("node", NodeConfig{}) if err != nil { log.Fatal(err) } }
apache-2.0
umadevik/log4j-android
target/apidocs/org/apache/log4j/spi/TriggeringEventEvaluator.html
9397
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_32) on Tue Jul 10 11:40:50 MST 2012 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> TriggeringEventEvaluator (Apache Log4j 1.2.17-1 API) </TITLE> <META NAME="date" CONTENT="2012-07-10"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="TriggeringEventEvaluator (Apache Log4j 1.2.17-1 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/TriggeringEventEvaluator.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../org/apache/log4j/spi/ThrowableRendererSupport.html" title="interface in org.apache.log4j.spi"><B>PREV CLASS</B></A>&nbsp; &nbsp;NEXT CLASS</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/apache/log4j/spi/TriggeringEventEvaluator.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="TriggeringEventEvaluator.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> org.apache.log4j.spi</FONT> <BR> Interface TriggeringEventEvaluator</H2> <HR> <DL> <DT><PRE>public interface <B>TriggeringEventEvaluator</B></DL> </PRE> <P> Implementions of this interface allow certain appenders to decide when to perform an appender specific action. <p>For example the <CODE>org.apache.log4j.net.SMTPAppender</CODE> sends an email when the <A HREF="../../../../org/apache/log4j/spi/TriggeringEventEvaluator.html#isTriggeringEvent(org.apache.log4j.spi.LoggingEvent)"><CODE>isTriggeringEvent(org.apache.log4j.spi.LoggingEvent)</CODE></A> method returns <code>true</code> and adds the event to an internal buffer when the returned result is <code>false</code>. <P> <P> <DL> <DT><B>Since:</B></DT> <DD>version 1.0</DD> <DT><B>Author:</B></DT> <DD>Ceki G&uuml;lc&uuml;</DD> </DL> <HR> <P> <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;boolean</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../org/apache/log4j/spi/TriggeringEventEvaluator.html#isTriggeringEvent(org.apache.log4j.spi.LoggingEvent)">isTriggeringEvent</A></B>(<A HREF="../../../../org/apache/log4j/spi/LoggingEvent.html" title="class in org.apache.log4j.spi">LoggingEvent</A>&nbsp;event)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Is this the triggering event?</TD> </TR> </TABLE> &nbsp; <P> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="isTriggeringEvent(org.apache.log4j.spi.LoggingEvent)"><!-- --></A><H3> isTriggeringEvent</H3> <PRE> boolean <B>isTriggeringEvent</B>(<A HREF="../../../../org/apache/log4j/spi/LoggingEvent.html" title="class in org.apache.log4j.spi">LoggingEvent</A>&nbsp;event)</PRE> <DL> <DD>Is this the triggering event? <P> <DD><DL> </DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/TriggeringEventEvaluator.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../org/apache/log4j/spi/ThrowableRendererSupport.html" title="interface in org.apache.log4j.spi"><B>PREV CLASS</B></A>&nbsp; &nbsp;NEXT CLASS</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?org/apache/log4j/spi/TriggeringEventEvaluator.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="TriggeringEventEvaluator.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;CONSTR&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &#169; 1999-2012 <a href="http://www.apache.org">Apache Software Foundation</a>. All Rights Reserved. </BODY> </HTML>
apache-2.0
Epi-Info/Epi-Info-iOS
BoxContentSDK.xcframework/ios-i386_x86_64-simulator/BoxContentSDK.framework/Headers/BOXUser.h
5872
// // BOXUser.h // BoxContentSDK // // #import "BOXModel.h" #import "BOXEnterprise.h" NS_ASSUME_NONNULL_BEGIN @protocol UniqueSDKUser /** * Unique id for the user. */ @property (nonnull, nonatomic, readonly, copy) NSString *uniqueId; /** * Optional Name of the user. */ @property (nullable, nonatomic, readonly, copy) NSString *name; /** * Optional Login of the user. */ @property (nullable, nonatomic, readonly, copy) NSString *login; @end /** * An implementation of the UniqueSDKUser protocol that is used in scenarios involving server-based auth (App Users, downscoped tokens, service accounts). */ @interface ServerAuthUser : BOXModel <UniqueSDKUser> @property (nonatomic, readwrite, copy) NSString *uniqueId; @property (nonatomic, readwrite, copy) NSString *name; @property (nonatomic, readwrite, copy) NSString *login; - (instancetype)initWithUniqueID:(NSString *)uniqueID; - (instancetype)initWithUniqueID:(NSString *)uniqueID name:(nullable NSString *)name login:(nullable NSString *)login; @end /** * A compact representation of a User with only a few properties. * Some API requests will return these representations to reduce bandiwdth, especially when many * instances are being returned. */ @interface BOXUserMini : BOXModel <UniqueSDKUser> /** * Name of the user. May be nil if the user has not set the name in Box. */ @property (nonatomic, readwrite, copy) NSString *name; /** * Login of the user, usually an email address but not always. */ @property (nonatomic, readwrite, copy) NSString *login; @end /** * Represents a User on Box. */ @interface BOXUser : BOXUserMini /** * Date the user was created. */ @property (nonatomic, readwrite, strong) NSDate *createdDate; /** * Date the user was modified. */ @property (nonatomic, readwrite, strong) NSDate *modifiedDate; /** * Language of the user. */ @property (nonatomic, readwrite, strong) NSString *language; /** * Timezone of the user. */ @property (nonatomic, readwrite, strong) NSString *timeZone; /** * The user’s total available space amount in bytes. */ @property (nonatomic, readwrite, strong) NSNumber *spaceAmount; /** * The amount of space in use by the user in bytes. */ @property (nonatomic, readwrite, strong) NSNumber *spaceUsed; /** * The maximum individual file size in bytes this user can have in bytes. */ @property (nonatomic, readwrite, strong) NSNumber *maxUploadSize; /** * Can be active, inactive. cannot_delete_edit, or cannot_delete_edit_upload. */ @property (nonatomic, readwrite, strong) NSString *status; /** * The user's job title. */ @property (nonatomic, readwrite, strong) NSString *jobTitle; /** * The user's phone number. */ @property (nonatomic, readwrite, strong) NSString *phone; /** * The user's address. */ @property (nonatomic, readwrite, strong) NSString *address; /** * URL of the user's avatar image. */ @property (nonatomic, readwrite, strong) NSURL *avatarURL; /** * Whether this user has a custom avatar set. */ @property (nonatomic, readwrite, assign) BOXAPIBoolean hasCustomAvatar; /** * This user’s enterprise role. Can be admin, coadmin, or user. * Warning: By default, the Box API does not return this value, and it will be nil. * You must request it by setting the "fields" of the request. */ @property (nonatomic, readwrite, strong) NSString *role; /** * An array of key/value pairs set by the user’s admin. * Warning: By default, the Box API does not return this value, and it will be nil. * You must request it by setting the "fields" of the request. */ @property (nonatomic, readwrite, strong) NSArray *trackingCodes; /** * Whether this user can see other enterprise users in her contact list. * Warning: By default, the Box API does not return this value, and it will be BOXAPIBooleanUnknown. * You must request it by setting the "fields" of the request. */ @property (nonatomic, readwrite, assign) BOXAPIBoolean canSeeManagedUsers; /** * Whether or not this user can use Box Sync. * Warning: By default, the Box API does not return this value, and it will be BOXAPIBooleanUnknown. * You must request it by setting the "fields" of the request. */ @property (nonatomic, readwrite, assign) BOXAPIBoolean isSyncEnabled; /** * Whether this user is allowed to collaborate with users outside her enterprise. * Warning: By default, the Box API does not return this value, and it will be BOXAPIBooleanUnknown. * You must request it by setting the "fields" of the request. */ @property (nonatomic, readwrite, assign) BOXAPIBoolean isExternalCollabRestricted; /** * Whether to exempt this user from Enterprise device limits. * Warning: By default, the Box API does not return this value, and it will be BOXAPIBooleanUnknown. * You must request it by setting the "fields" of the request. */ @property (nonatomic, readwrite, assign) BOXAPIBoolean isExemptFromDeviceLimits; /** * Whether or not this user must use two-factor authentication. * Warning: By default, the Box API does not return this value, and it will be BOXAPIBooleanUnknown. * You must request it by setting the "fields" of the request. */ @property (nonatomic, readwrite, assign) BOXAPIBoolean isExemptFromLoginVerification; /** * The enterprise the user belongs to. * Warning: By default, the Box API does not return this value, and it will be nil. * You must request it by setting the "fields" of the request. */ @property (nonatomic, readwrite, strong) BOXEnterpriseMini *enterprise; /** * Whether or not this user can create BoxNotes. * Warning: By default, the Box API does not return this value, and it will be BOXAPIBooleanUnknown. * You must request it by setting the "fields" of the request. */ @property (nonatomic, readwrite, assign) BOXAPIBoolean isBoxNotesCreationEnabled; @end NS_ASSUME_NONNULL_END
apache-2.0
cedral/aws-sdk-cpp
aws-cpp-sdk-config/source/model/DeliverConfigSnapshotResult.cpp
1479
/* * 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/DeliverConfigSnapshotResult.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; DeliverConfigSnapshotResult::DeliverConfigSnapshotResult() { } DeliverConfigSnapshotResult::DeliverConfigSnapshotResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } DeliverConfigSnapshotResult& DeliverConfigSnapshotResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("configSnapshotId")) { m_configSnapshotId = jsonValue.GetString("configSnapshotId"); } return *this; }
apache-2.0