code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
/*
This file is part of GNUnet.
(C) 2012 Christian Grothoff (and other contributing authors)
GNUnet 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, or (at your
option) any later version.
GNUnet 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 GNUnet; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
/**
* @file util/gnunet-config.c
* @brief tool to access and manipulate GNUnet configuration files
* @author Christian Grothoff
*/
#include "platform.h"
#include "gnunet_util_lib.h"
/**
* Name of the section
*/
static char *section;
/**
* Name of the option
*/
static char *option;
/**
* Value to set
*/
static char *value;
/**
* Treat option as a filename.
*/
static int is_filename;
/**
* Return value from 'main'.
*/
static int ret;
/**
* Print each option in a given section.
*
* @param cls closure
* @param section name of the section
* @param option name of the option
* @param value value of the option
*/
static void
print_option (void *cls, const char *section,
const char *option,
const char *value)
{
fprintf (stdout,
"%s = %s\n", option, value);
}
/**
* Main function that will be run by the scheduler.
*
* @param cls closure
* @param args remaining command-line arguments
* @param cfgfile name of the configuration file used (for saving, can be NULL!)
* @param cfg configuration
*/
static void
run (void *cls, char *const *args, const char *cfgfile,
const struct GNUNET_CONFIGURATION_Handle *cfg)
{
struct GNUNET_CONFIGURATION_Handle *out;
if (NULL == section)
{
fprintf (stderr, _("--section argument is required\n"));
ret = 1;
return;
}
if (NULL == value)
{
if (NULL == option)
{
GNUNET_CONFIGURATION_iterate_section_values (cfg, section,
&print_option, NULL);
}
else
{
if (is_filename)
{
if (GNUNET_OK !=
GNUNET_CONFIGURATION_get_value_filename (cfg, section, option, &value))
{
GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
section, option);
ret = 3;
return;
}
}
else
{
if (GNUNET_OK !=
GNUNET_CONFIGURATION_get_value_string (cfg, section, option, &value))
{
GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
section, option);
ret = 3;
return;
}
}
fprintf (stdout, "%s\n", value);
}
}
else
{
if (NULL == option)
{
fprintf (stderr, _("--option argument required to set value\n"));
ret = 1;
return;
}
out = GNUNET_CONFIGURATION_dup (cfg);
GNUNET_CONFIGURATION_set_value_string (out, section, option, value);
if (GNUNET_OK !=
GNUNET_CONFIGURATION_write (out, cfgfile))
ret = 2;
GNUNET_CONFIGURATION_destroy (out);
return;
}
}
/**
* Program to manipulate configuration files.
*
* @param argc number of arguments from the command line
* @param argv command line arguments
* @return 0 ok, 1 on error
*/
int
main (int argc, char *const *argv)
{
static const struct GNUNET_GETOPT_CommandLineOption options[] = {
{ 'f', "filename", NULL,
gettext_noop ("obtain option of value as a filename (with $-expansion)"),
0, &GNUNET_GETOPT_set_one, &is_filename },
{ 's', "section", "SECTION",
gettext_noop ("name of the section to access"),
1, &GNUNET_GETOPT_set_string, §ion },
{ 'o', "option", "OPTION",
gettext_noop ("name of the option to access"),
1, &GNUNET_GETOPT_set_string, &option },
{ 'V', "value", "VALUE",
gettext_noop ("value to set"),
1, &GNUNET_GETOPT_set_string, &value },
GNUNET_GETOPT_OPTION_END
};
if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
return 2;
ret = (GNUNET_OK ==
GNUNET_PROGRAM_run (argc, argv, "gnunet-config [OPTIONS]",
gettext_noop ("Manipulate GNUnet configuration files"),
options, &run, NULL)) ? 0 : ret;
GNUNET_free ((void*) argv);
return ret;
}
/* end of gnunet-config.c */
| zlatebogdan/gnunet | src/util/gnunet-config.c | C | gpl-3.0 | 4,486 |
/**
******************************************************************************
* @file stm32f4xx_hal_spi.c
* @author MCD Application Team
* @version V1.2.0
* @date 26-December-2014
* @brief SPI HAL module driver.
*
* This file provides firmware functions to manage the following
* functionalities of the Serial Peripheral Interface (SPI) peripheral:
* + Initialization and de-initialization functions
* + IO operation functions
* + Peripheral Control functions
* + Peripheral State functions
@verbatim
==============================================================================
##### How to use this driver #####
==============================================================================
[..]
The SPI HAL driver can be used as follows:
(#) Declare a SPI_HandleTypeDef handle structure, for example:
SPI_HandleTypeDef hspi;
(#)Initialize the SPI low level resources by implementing the HAL_SPI_MspInit ()API:
(##) Enable the SPIx interface clock
(##) SPI pins configuration
(+++) Enable the clock for the SPI GPIOs
(+++) Configure these SPI pins as alternate function push-pull
(##) NVIC configuration if you need to use interrupt process
(+++) Configure the SPIx interrupt priority
(+++) Enable the NVIC SPI IRQ handle
(##) DMA Configuration if you need to use DMA process
(+++) Declare a DMA_HandleTypeDef handle structure for the transmit or receive stream
(+++) Enable the DMAx interface clock using
(+++) Configure the DMA handle parameters
(+++) Configure the DMA Tx or Rx Stream
(+++) Associate the initialized hdma_tx handle to the hspi DMA Tx or Rx handle
(+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx or Rx Stream
(#) Program the Mode, Direction , Data size, Baudrate Prescaler, NSS
management, Clock polarity and phase, FirstBit and CRC configuration in the hspi Init structure.
(#) Initialize the SPI registers by calling the HAL_SPI_Init() API:
(++) This API configures also the low level Hardware GPIO, CLOCK, CORTEX...etc)
by calling the customized HAL_SPI_MspInit() API.
[..]
Circular mode restriction:
(#) The DMA circular mode cannot be used when the SPI is configured in these modes:
(##) Master 2Lines RxOnly
(##) Master 1Line Rx
(#) The CRC feature is not managed when the DMA circular mode is enabled
(#) When the SPI DMA Pause/Stop features are used, we must use the following APIs
the HAL_SPI_DMAPause()/ HAL_SPI_DMAStop() only under the SPI callbacks
@endverbatim
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2014 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics 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 HOLDER 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.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx_hal.h"
/** @addtogroup STM32F4xx_HAL_Driver
* @{
*/
/** @defgroup SPI SPI
* @brief SPI HAL module driver
* @{
*/
#ifdef HAL_SPI_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
#define SPI_TIMEOUT_VALUE 10
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/** @addtogroup SPI_Private_Functions
* @{
*/
static void SPI_TxCloseIRQHandler(SPI_HandleTypeDef *hspi);
static void SPI_TxISR(SPI_HandleTypeDef *hspi);
static void SPI_RxCloseIRQHandler(SPI_HandleTypeDef *hspi);
static void SPI_2LinesRxISR(SPI_HandleTypeDef *hspi);
static void SPI_RxISR(SPI_HandleTypeDef *hspi);
static void SPI_DMATransmitCplt(DMA_HandleTypeDef *hdma);
static void SPI_DMAReceiveCplt(DMA_HandleTypeDef *hdma);
static void SPI_DMATransmitReceiveCplt(DMA_HandleTypeDef *hdma);
static void SPI_DMAHalfTransmitCplt(DMA_HandleTypeDef *hdma);
static void SPI_DMAHalfReceiveCplt(DMA_HandleTypeDef *hdma);
static void SPI_DMAHalfTransmitReceiveCplt(DMA_HandleTypeDef *hdma);
static void SPI_DMAError(DMA_HandleTypeDef *hdma);
static HAL_StatusTypeDef SPI_WaitOnFlagUntilTimeout(SPI_HandleTypeDef *hspi, uint32_t Flag, FlagStatus Status, uint32_t Timeout);
/**
* @}
*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup SPI_Exported_Functions SPI Exported Functions
* @{
*/
/** @defgroup SPI_Exported_Functions_Group1 Initialization and de-initialization functions
* @brief Initialization and Configuration functions
*
@verbatim
===============================================================================
##### Initialization and de-initialization functions #####
===============================================================================
[..] This subsection provides a set of functions allowing to initialize and
de-initialize the SPIx peripheral:
(+) User must implement HAL_SPI_MspInit() function in which he configures
all related peripherals resources (CLOCK, GPIO, DMA, IT and NVIC ).
(+) Call the function HAL_SPI_Init() to configure the selected device with
the selected configuration:
(++) Mode
(++) Direction
(++) Data Size
(++) Clock Polarity and Phase
(++) NSS Management
(++) BaudRate Prescaler
(++) FirstBit
(++) TIMode
(++) CRC Calculation
(++) CRC Polynomial if CRC enabled
(+) Call the function HAL_SPI_DeInit() to restore the default configuration
of the selected SPIx peripheral.
@endverbatim
* @{
*/
/**
* @brief Initializes the SPI according to the specified parameters
* in the SPI_InitTypeDef and create the associated handle.
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPI_Init(SPI_HandleTypeDef *hspi)
{
/* Check the SPI handle allocation */
if(hspi == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_SPI_MODE(hspi->Init.Mode));
assert_param(IS_SPI_DIRECTION_MODE(hspi->Init.Direction));
assert_param(IS_SPI_DATASIZE(hspi->Init.DataSize));
assert_param(IS_SPI_CPOL(hspi->Init.CLKPolarity));
assert_param(IS_SPI_CPHA(hspi->Init.CLKPhase));
assert_param(IS_SPI_NSS(hspi->Init.NSS));
assert_param(IS_SPI_BAUDRATE_PRESCALER(hspi->Init.BaudRatePrescaler));
assert_param(IS_SPI_FIRST_BIT(hspi->Init.FirstBit));
assert_param(IS_SPI_TIMODE(hspi->Init.TIMode));
assert_param(IS_SPI_CRC_CALCULATION(hspi->Init.CRCCalculation));
assert_param(IS_SPI_CRC_POLYNOMIAL(hspi->Init.CRCPolynomial));
if(hspi->State == HAL_SPI_STATE_RESET)
{
/* Init the low level hardware : GPIO, CLOCK, NVIC... */
HAL_SPI_MspInit(hspi);
}
hspi->State = HAL_SPI_STATE_BUSY;
/* Disable the selected SPI peripheral */
__HAL_SPI_DISABLE(hspi);
/*----------------------- SPIx CR1 & CR2 Configuration ---------------------*/
/* Configure : SPI Mode, Communication Mode, Data size, Clock polarity and phase, NSS management,
Communication speed, First bit and CRC calculation state */
hspi->Instance->CR1 = (hspi->Init.Mode | hspi->Init.Direction | hspi->Init.DataSize |
hspi->Init.CLKPolarity | hspi->Init.CLKPhase | (hspi->Init.NSS & SPI_CR1_SSM) |
hspi->Init.BaudRatePrescaler | hspi->Init.FirstBit | hspi->Init.CRCCalculation);
/* Configure : NSS management */
hspi->Instance->CR2 = (((hspi->Init.NSS >> 16) & SPI_CR2_SSOE) | hspi->Init.TIMode);
/*---------------------------- SPIx CRCPOLY Configuration ------------------*/
/* Configure : CRC Polynomial */
hspi->Instance->CRCPR = hspi->Init.CRCPolynomial;
/* Activate the SPI mode (Make sure that I2SMOD bit in I2SCFGR register is reset) */
hspi->Instance->I2SCFGR &= (uint32_t)(~SPI_I2SCFGR_I2SMOD);
hspi->ErrorCode = HAL_SPI_ERROR_NONE;
hspi->State = HAL_SPI_STATE_READY;
return HAL_OK;
}
/**
* @brief DeInitializes the SPI peripheral
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPI_DeInit(SPI_HandleTypeDef *hspi)
{
/* Check the SPI handle allocation */
if(hspi == NULL)
{
return HAL_ERROR;
}
/* Disable the SPI Peripheral Clock */
__HAL_SPI_DISABLE(hspi);
/* DeInit the low level hardware: GPIO, CLOCK, NVIC... */
HAL_SPI_MspDeInit(hspi);
hspi->ErrorCode = HAL_SPI_ERROR_NONE;
hspi->State = HAL_SPI_STATE_RESET;
/* Release Lock */
__HAL_UNLOCK(hspi);
return HAL_OK;
}
/**
* @brief SPI MSP Init
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval None
*/
__weak void HAL_SPI_MspInit(SPI_HandleTypeDef *hspi)
{
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_SPI_MspInit could be implemented in the user file
*/
}
/**
* @brief SPI MSP DeInit
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval None
*/
__weak void HAL_SPI_MspDeInit(SPI_HandleTypeDef *hspi)
{
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_SPI_MspDeInit could be implemented in the user file
*/
}
/**
* @}
*/
/** @defgroup SPI_Exported_Functions_Group2 IO operation functions
* @brief Data transfers functions
*
@verbatim
==============================================================================
##### IO operation functions #####
===============================================================================
This subsection provides a set of functions allowing to manage the SPI
data transfers.
[..] The SPI supports master and slave mode :
(#) There are two modes of transfer:
(++) Blocking mode: The communication is performed in polling mode.
The HAL status of all data processing is returned by the same function
after finishing transfer.
(++) No-Blocking mode: The communication is performed using Interrupts
or DMA, These APIs return the HAL status.
The end of the data processing will be indicated through the
dedicated SPI IRQ when using Interrupt mode or the DMA IRQ when
using DMA mode.
The HAL_SPI_TxCpltCallback(), HAL_SPI_RxCpltCallback() and HAL_SPI_TxRxCpltCallback() user callbacks
will be executed respectively at the end of the transmit or Receive process
The HAL_SPI_ErrorCallback()user callback will be executed when a communication error is detected
(#) Blocking mode APIs are :
(++) HAL_SPI_Transmit()in 1Line (simplex) and 2Lines (full duplex) mode
(++) HAL_SPI_Receive() in 1Line (simplex) and 2Lines (full duplex) mode
(++) HAL_SPI_TransmitReceive() in full duplex mode
(#) Non Blocking mode API's with Interrupt are :
(++) HAL_SPI_Transmit_IT()in 1Line (simplex) and 2Lines (full duplex) mode
(++) HAL_SPI_Receive_IT() in 1Line (simplex) and 2Lines (full duplex) mode
(++) HAL_SPI_TransmitReceive_IT()in full duplex mode
(++) HAL_SPI_IRQHandler()
(#) Non Blocking mode functions with DMA are :
(++) HAL_SPI_Transmit_DMA()in 1Line (simplex) and 2Lines (full duplex) mode
(++) HAL_SPI_Receive_DMA() in 1Line (simplex) and 2Lines (full duplex) mode
(++) HAL_SPI_TransmitReceie_DMA() in full duplex mode
(#) A set of Transfer Complete Callbacks are provided in non Blocking mode:
(++) HAL_SPI_TxCpltCallback()
(++) HAL_SPI_RxCpltCallback()
(++) HAL_SPI_ErrorCallback()
(++) HAL_SPI_TxRxCpltCallback()
@endverbatim
* @{
*/
/**
* @brief Transmit an amount of data in blocking mode
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @param pData: pointer to data buffer
* @param Size: amount of data to be sent
* @param Timeout: Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout)
{
if(hspi->State == HAL_SPI_STATE_READY)
{
if((pData == NULL ) || (Size == 0))
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction));
/* Process Locked */
__HAL_LOCK(hspi);
/* Configure communication */
hspi->State = HAL_SPI_STATE_BUSY_TX;
hspi->ErrorCode = HAL_SPI_ERROR_NONE;
hspi->pTxBuffPtr = pData;
hspi->TxXferSize = Size;
hspi->TxXferCount = Size;
/*Init field not used in handle to zero */
hspi->TxISR = 0;
hspi->RxISR = 0;
hspi->RxXferSize = 0;
hspi->RxXferCount = 0;
/* Reset CRC Calculation */
if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
SPI_RESET_CRC(hspi);
}
if(hspi->Init.Direction == SPI_DIRECTION_1LINE)
{
/* Configure communication direction : 1Line */
SPI_1LINE_TX(hspi);
}
/* Check if the SPI is already enabled */
if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE)
{
/* Enable SPI peripheral */
__HAL_SPI_ENABLE(hspi);
}
/* Transmit data in 8 Bit mode */
if(hspi->Init.DataSize == SPI_DATASIZE_8BIT)
{
if((hspi->Init.Mode == SPI_MODE_SLAVE)|| (hspi->TxXferCount == 0x01))
{
hspi->Instance->DR = (*hspi->pTxBuffPtr++);
hspi->TxXferCount--;
}
while(hspi->TxXferCount > 0)
{
/* Wait until TXE flag is set to send data */
if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
hspi->Instance->DR = (*hspi->pTxBuffPtr++);
hspi->TxXferCount--;
}
/* Enable CRC Transmission */
if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
hspi->Instance->CR1 |= SPI_CR1_CRCNEXT;
}
}
/* Transmit data in 16 Bit mode */
else
{
if((hspi->Init.Mode == SPI_MODE_SLAVE) || (hspi->TxXferCount == 0x01))
{
hspi->Instance->DR = *((uint16_t*)hspi->pTxBuffPtr);
hspi->pTxBuffPtr+=2;
hspi->TxXferCount--;
}
while(hspi->TxXferCount > 0)
{
/* Wait until TXE flag is set to send data */
if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
hspi->Instance->DR = *((uint16_t*)hspi->pTxBuffPtr);
hspi->pTxBuffPtr+=2;
hspi->TxXferCount--;
}
/* Enable CRC Transmission */
if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
hspi->Instance->CR1 |= SPI_CR1_CRCNEXT;
}
}
/* Wait until TXE flag is set to send data */
if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, Timeout) != HAL_OK)
{
hspi->ErrorCode |= HAL_SPI_ERROR_FLAG;
return HAL_TIMEOUT;
}
/* Wait until Busy flag is reset before disabling SPI */
if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_BSY, SET, Timeout) != HAL_OK)
{
hspi->ErrorCode |= HAL_SPI_ERROR_FLAG;
return HAL_TIMEOUT;
}
/* Clear OVERRUN flag in 2 Lines communication mode because received is not read */
if(hspi->Init.Direction == SPI_DIRECTION_2LINES)
{
__HAL_SPI_CLEAR_OVRFLAG(hspi);
}
hspi->State = HAL_SPI_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hspi);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receive an amount of data in blocking mode
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @param pData: pointer to data buffer
* @param Size: amount of data to be sent
* @param Timeout: Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout)
{
__IO uint16_t tmpreg;
uint32_t tmp = 0;
if(hspi->State == HAL_SPI_STATE_READY)
{
if((pData == NULL ) || (Size == 0))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hspi);
/* Configure communication */
hspi->State = HAL_SPI_STATE_BUSY_RX;
hspi->ErrorCode = HAL_SPI_ERROR_NONE;
hspi->pRxBuffPtr = pData;
hspi->RxXferSize = Size;
hspi->RxXferCount = Size;
/*Init field not used in handle to zero */
hspi->RxISR = 0;
hspi->TxISR = 0;
hspi->TxXferSize = 0;
hspi->TxXferCount = 0;
/* Configure communication direction : 1Line */
if(hspi->Init.Direction == SPI_DIRECTION_1LINE)
{
SPI_1LINE_RX(hspi);
}
/* Reset CRC Calculation */
if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
SPI_RESET_CRC(hspi);
}
if((hspi->Init.Mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES))
{
/* Process Unlocked */
__HAL_UNLOCK(hspi);
/* Call transmit-receive function to send Dummy data on Tx line and generate clock on CLK line */
return HAL_SPI_TransmitReceive(hspi, pData, pData, Size, Timeout);
}
/* Check if the SPI is already enabled */
if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE)
{
/* Enable SPI peripheral */
__HAL_SPI_ENABLE(hspi);
}
/* Receive data in 8 Bit mode */
if(hspi->Init.DataSize == SPI_DATASIZE_8BIT)
{
while(hspi->RxXferCount > 1)
{
/* Wait until RXNE flag is set */
if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
(*hspi->pRxBuffPtr++) = hspi->Instance->DR;
hspi->RxXferCount--;
}
/* Enable CRC Transmission */
if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
hspi->Instance->CR1 |= SPI_CR1_CRCNEXT;
}
}
/* Receive data in 16 Bit mode */
else
{
while(hspi->RxXferCount > 1)
{
/* Wait until RXNE flag is set to read data */
if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
*((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR;
hspi->pRxBuffPtr+=2;
hspi->RxXferCount--;
}
/* Enable CRC Transmission */
if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
hspi->Instance->CR1 |= SPI_CR1_CRCNEXT;
}
}
/* Wait until RXNE flag is set */
if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
/* Receive last data in 8 Bit mode */
if(hspi->Init.DataSize == SPI_DATASIZE_8BIT)
{
(*hspi->pRxBuffPtr++) = hspi->Instance->DR;
}
/* Receive last data in 16 Bit mode */
else
{
*((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR;
hspi->pRxBuffPtr+=2;
}
hspi->RxXferCount--;
/* Wait until RXNE flag is set: CRC Received */
if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK)
{
hspi->ErrorCode |= HAL_SPI_ERROR_CRC;
return HAL_TIMEOUT;
}
/* Read CRC to Flush RXNE flag */
tmpreg = hspi->Instance->DR;
UNUSED(tmpreg);
}
if((hspi->Init.Mode == SPI_MODE_MASTER)&&((hspi->Init.Direction == SPI_DIRECTION_1LINE)||(hspi->Init.Direction == SPI_DIRECTION_2LINES_RXONLY)))
{
/* Disable SPI peripheral */
__HAL_SPI_DISABLE(hspi);
}
hspi->State = HAL_SPI_STATE_READY;
tmp = __HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR);
/* Check if CRC error occurred */
if((hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) && (tmp != RESET))
{
hspi->ErrorCode |= HAL_SPI_ERROR_CRC;
/* Reset CRC Calculation */
SPI_RESET_CRC(hspi);
/* Process Unlocked */
__HAL_UNLOCK(hspi);
return HAL_ERROR;
}
/* Process Unlocked */
__HAL_UNLOCK(hspi);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Transmit and Receive an amount of data in blocking mode
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @param pTxData: pointer to transmission data buffer
* @param pRxData: pointer to reception data buffer to be
* @param Size: amount of data to be sent
* @param Timeout: Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size, uint32_t Timeout)
{
__IO uint16_t tmpreg;
uint32_t tmpstate = 0, tmp = 0;
tmpstate = hspi->State;
if((tmpstate == HAL_SPI_STATE_READY) || (tmpstate == HAL_SPI_STATE_BUSY_RX))
{
if((pTxData == NULL ) || (pRxData == NULL ) || (Size == 0))
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction));
/* Process Locked */
__HAL_LOCK(hspi);
/* Don't overwrite in case of HAL_SPI_STATE_BUSY_RX */
if(hspi->State == HAL_SPI_STATE_READY)
{
hspi->State = HAL_SPI_STATE_BUSY_TX_RX;
}
/* Configure communication */
hspi->ErrorCode = HAL_SPI_ERROR_NONE;
hspi->pRxBuffPtr = pRxData;
hspi->RxXferSize = Size;
hspi->RxXferCount = Size;
hspi->pTxBuffPtr = pTxData;
hspi->TxXferSize = Size;
hspi->TxXferCount = Size;
/*Init field not used in handle to zero */
hspi->RxISR = 0;
hspi->TxISR = 0;
/* Reset CRC Calculation */
if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
SPI_RESET_CRC(hspi);
}
/* Check if the SPI is already enabled */
if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE)
{
/* Enable SPI peripheral */
__HAL_SPI_ENABLE(hspi);
}
/* Transmit and Receive data in 16 Bit mode */
if(hspi->Init.DataSize == SPI_DATASIZE_16BIT)
{
if((hspi->Init.Mode == SPI_MODE_SLAVE) || ((hspi->Init.Mode == SPI_MODE_MASTER) && (hspi->TxXferCount == 0x01)))
{
hspi->Instance->DR = *((uint16_t*)hspi->pTxBuffPtr);
hspi->pTxBuffPtr+=2;
hspi->TxXferCount--;
}
if(hspi->TxXferCount == 0)
{
/* Enable CRC Transmission */
if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
hspi->Instance->CR1 |= SPI_CR1_CRCNEXT;
}
/* Wait until RXNE flag is set */
if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
*((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR;
hspi->pRxBuffPtr+=2;
hspi->RxXferCount--;
}
else
{
while(hspi->TxXferCount > 0)
{
/* Wait until TXE flag is set to send data */
if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
hspi->Instance->DR = *((uint16_t*)hspi->pTxBuffPtr);
hspi->pTxBuffPtr+=2;
hspi->TxXferCount--;
/* Enable CRC Transmission */
if((hspi->TxXferCount == 0) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE))
{
hspi->Instance->CR1 |= SPI_CR1_CRCNEXT;
}
/* Wait until RXNE flag is set */
if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
*((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR;
hspi->pRxBuffPtr+=2;
hspi->RxXferCount--;
}
/* Receive the last byte */
if(hspi->Init.Mode == SPI_MODE_SLAVE)
{
/* Wait until RXNE flag is set */
if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
*((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR;
hspi->pRxBuffPtr+=2;
hspi->RxXferCount--;
}
}
}
/* Transmit and Receive data in 8 Bit mode */
else
{
if((hspi->Init.Mode == SPI_MODE_SLAVE) || ((hspi->Init.Mode == SPI_MODE_MASTER) && (hspi->TxXferCount == 0x01)))
{
hspi->Instance->DR = (*hspi->pTxBuffPtr++);
hspi->TxXferCount--;
}
if(hspi->TxXferCount == 0)
{
/* Enable CRC Transmission */
if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
hspi->Instance->CR1 |= SPI_CR1_CRCNEXT;
}
/* Wait until RXNE flag is set */
if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
(*hspi->pRxBuffPtr) = hspi->Instance->DR;
hspi->RxXferCount--;
}
else
{
while(hspi->TxXferCount > 0)
{
/* Wait until TXE flag is set to send data */
if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
hspi->Instance->DR = (*hspi->pTxBuffPtr++);
hspi->TxXferCount--;
/* Enable CRC Transmission */
if((hspi->TxXferCount == 0) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE))
{
hspi->Instance->CR1 |= SPI_CR1_CRCNEXT;
}
/* Wait until RXNE flag is set */
if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
(*hspi->pRxBuffPtr++) = hspi->Instance->DR;
hspi->RxXferCount--;
}
if(hspi->Init.Mode == SPI_MODE_SLAVE)
{
/* Wait until RXNE flag is set */
if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
(*hspi->pRxBuffPtr++) = hspi->Instance->DR;
hspi->RxXferCount--;
}
}
}
/* Read CRC from DR to close CRC calculation process */
if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
/* Wait until RXNE flag is set */
if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK)
{
hspi->ErrorCode |= HAL_SPI_ERROR_CRC;
return HAL_TIMEOUT;
}
/* Read CRC */
tmpreg = hspi->Instance->DR;
UNUSED(tmpreg);
}
/* Wait until Busy flag is reset before disabling SPI */
if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_BSY, SET, Timeout) != HAL_OK)
{
hspi->ErrorCode |= HAL_SPI_ERROR_FLAG;
return HAL_TIMEOUT;
}
hspi->State = HAL_SPI_STATE_READY;
tmp = __HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR);
/* Check if CRC error occurred */
if((hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE) && (tmp != RESET))
{
hspi->ErrorCode |= HAL_SPI_ERROR_CRC;
/* Reset CRC Calculation */
if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
SPI_RESET_CRC(hspi);
}
/* Process Unlocked */
__HAL_UNLOCK(hspi);
return HAL_ERROR;
}
/* Process Unlocked */
__HAL_UNLOCK(hspi);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Transmit an amount of data in no-blocking mode with Interrupt
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @param pData: pointer to data buffer
* @param Size: amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size)
{
if(hspi->State == HAL_SPI_STATE_READY)
{
if((pData == NULL) || (Size == 0))
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction));
/* Process Locked */
__HAL_LOCK(hspi);
/* Configure communication */
hspi->State = HAL_SPI_STATE_BUSY_TX;
hspi->ErrorCode = HAL_SPI_ERROR_NONE;
hspi->TxISR = &SPI_TxISR;
hspi->pTxBuffPtr = pData;
hspi->TxXferSize = Size;
hspi->TxXferCount = Size;
/*Init field not used in handle to zero */
hspi->RxISR = 0;
hspi->RxXferSize = 0;
hspi->RxXferCount = 0;
/* Configure communication direction : 1Line */
if(hspi->Init.Direction == SPI_DIRECTION_1LINE)
{
SPI_1LINE_TX(hspi);
}
/* Reset CRC Calculation */
if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
SPI_RESET_CRC(hspi);
}
if (hspi->Init.Direction == SPI_DIRECTION_2LINES)
{
__HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE));
}else
{
/* Enable TXE and ERR interrupt */
__HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_ERR));
}
/* Process Unlocked */
__HAL_UNLOCK(hspi);
/* Check if the SPI is already enabled */
if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE)
{
/* Enable SPI peripheral */
__HAL_SPI_ENABLE(hspi);
}
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receive an amount of data in no-blocking mode with Interrupt
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @param pData: pointer to data buffer
* @param Size: amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size)
{
if(hspi->State == HAL_SPI_STATE_READY)
{
if((pData == NULL) || (Size == 0))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hspi);
/* Configure communication */
hspi->State = HAL_SPI_STATE_BUSY_RX;
hspi->ErrorCode = HAL_SPI_ERROR_NONE;
hspi->RxISR = &SPI_RxISR;
hspi->pRxBuffPtr = pData;
hspi->RxXferSize = Size;
hspi->RxXferCount = Size ;
/*Init field not used in handle to zero */
hspi->TxISR = 0;
hspi->TxXferSize = 0;
hspi->TxXferCount = 0;
/* Configure communication direction : 1Line */
if(hspi->Init.Direction == SPI_DIRECTION_1LINE)
{
SPI_1LINE_RX(hspi);
}
else if((hspi->Init.Direction == SPI_DIRECTION_2LINES) && (hspi->Init.Mode == SPI_MODE_MASTER))
{
/* Process Unlocked */
__HAL_UNLOCK(hspi);
/* Call transmit-receive function to send Dummy data on Tx line and generate clock on CLK line */
return HAL_SPI_TransmitReceive_IT(hspi, pData, pData, Size);
}
/* Reset CRC Calculation */
if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
SPI_RESET_CRC(hspi);
}
/* Enable TXE and ERR interrupt */
__HAL_SPI_ENABLE_IT(hspi, (SPI_IT_RXNE | SPI_IT_ERR));
/* Process Unlocked */
__HAL_UNLOCK(hspi);
/* Note : The SPI must be enabled after unlocking current process
to avoid the risk of SPI interrupt handle execution before current
process unlock */
/* Check if the SPI is already enabled */
if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE)
{
/* Enable SPI peripheral */
__HAL_SPI_ENABLE(hspi);
}
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Transmit and Receive an amount of data in no-blocking mode with Interrupt
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @param pTxData: pointer to transmission data buffer
* @param pRxData: pointer to reception data buffer to be
* @param Size: amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size)
{
uint32_t tmpstate = 0;
tmpstate = hspi->State;
if((tmpstate == HAL_SPI_STATE_READY) || \
((hspi->Init.Mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && (tmpstate == HAL_SPI_STATE_BUSY_RX)))
{
if((pTxData == NULL ) || (pRxData == NULL ) || (Size == 0))
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction));
/* Process locked */
__HAL_LOCK(hspi);
/* Don't overwrite in case of HAL_SPI_STATE_BUSY_RX */
if(hspi->State != HAL_SPI_STATE_BUSY_RX)
{
hspi->State = HAL_SPI_STATE_BUSY_TX_RX;
}
/* Configure communication */
hspi->ErrorCode = HAL_SPI_ERROR_NONE;
hspi->TxISR = &SPI_TxISR;
hspi->pTxBuffPtr = pTxData;
hspi->TxXferSize = Size;
hspi->TxXferCount = Size;
hspi->RxISR = &SPI_2LinesRxISR;
hspi->pRxBuffPtr = pRxData;
hspi->RxXferSize = Size;
hspi->RxXferCount = Size;
/* Reset CRC Calculation */
if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
SPI_RESET_CRC(hspi);
}
/* Enable TXE, RXNE and ERR interrupt */
__HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR));
/* Process Unlocked */
__HAL_UNLOCK(hspi);
/* Check if the SPI is already enabled */
if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE)
{
/* Enable SPI peripheral */
__HAL_SPI_ENABLE(hspi);
}
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Transmit an amount of data in no-blocking mode with DMA
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @param pData: pointer to data buffer
* @param Size: amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size)
{
if(hspi->State == HAL_SPI_STATE_READY)
{
if((pData == NULL) || (Size == 0))
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction));
/* Process Locked */
__HAL_LOCK(hspi);
/* Configure communication */
hspi->State = HAL_SPI_STATE_BUSY_TX;
hspi->ErrorCode = HAL_SPI_ERROR_NONE;
hspi->pTxBuffPtr = pData;
hspi->TxXferSize = Size;
hspi->TxXferCount = Size;
/*Init field not used in handle to zero */
hspi->TxISR = 0;
hspi->RxISR = 0;
hspi->RxXferSize = 0;
hspi->RxXferCount = 0;
/* Configure communication direction : 1Line */
if(hspi->Init.Direction == SPI_DIRECTION_1LINE)
{
SPI_1LINE_TX(hspi);
}
/* Reset CRC Calculation */
if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
SPI_RESET_CRC(hspi);
}
/* Set the SPI TxDMA Half transfer complete callback */
hspi->hdmatx->XferHalfCpltCallback = SPI_DMAHalfTransmitCplt;
/* Set the SPI TxDMA transfer complete callback */
hspi->hdmatx->XferCpltCallback = SPI_DMATransmitCplt;
/* Set the DMA error callback */
hspi->hdmatx->XferErrorCallback = SPI_DMAError;
/* Enable the Tx DMA Stream */
HAL_DMA_Start_IT(hspi->hdmatx, (uint32_t)hspi->pTxBuffPtr, (uint32_t)&hspi->Instance->DR, hspi->TxXferCount);
/* Enable Tx DMA Request */
hspi->Instance->CR2 |= SPI_CR2_TXDMAEN;
/* Process Unlocked */
__HAL_UNLOCK(hspi);
/* Check if the SPI is already enabled */
if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE)
{
/* Enable SPI peripheral */
__HAL_SPI_ENABLE(hspi);
}
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receive an amount of data in no-blocking mode with DMA
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @param pData: pointer to data buffer
* @note When the CRC feature is enabled the pData Length must be Size + 1.
* @param Size: amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size)
{
if(hspi->State == HAL_SPI_STATE_READY)
{
if((pData == NULL) || (Size == 0))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hspi);
/* Configure communication */
hspi->State = HAL_SPI_STATE_BUSY_RX;
hspi->ErrorCode = HAL_SPI_ERROR_NONE;
hspi->pRxBuffPtr = pData;
hspi->RxXferSize = Size;
hspi->RxXferCount = Size;
/*Init field not used in handle to zero */
hspi->RxISR = 0;
hspi->TxISR = 0;
hspi->TxXferSize = 0;
hspi->TxXferCount = 0;
/* Configure communication direction : 1Line */
if(hspi->Init.Direction == SPI_DIRECTION_1LINE)
{
SPI_1LINE_RX(hspi);
}
else if((hspi->Init.Direction == SPI_DIRECTION_2LINES)&&(hspi->Init.Mode == SPI_MODE_MASTER))
{
/* Process Unlocked */
__HAL_UNLOCK(hspi);
/* Call transmit-receive function to send Dummy data on Tx line and generate clock on CLK line */
return HAL_SPI_TransmitReceive_DMA(hspi, pData, pData, Size);
}
/* Reset CRC Calculation */
if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
SPI_RESET_CRC(hspi);
}
/* Set the SPI RxDMA Half transfer complete callback */
hspi->hdmarx->XferHalfCpltCallback = SPI_DMAHalfReceiveCplt;
/* Set the SPI Rx DMA transfer complete callback */
hspi->hdmarx->XferCpltCallback = SPI_DMAReceiveCplt;
/* Set the DMA error callback */
hspi->hdmarx->XferErrorCallback = SPI_DMAError;
/* Enable the Rx DMA Stream */
HAL_DMA_Start_IT(hspi->hdmarx, (uint32_t)&hspi->Instance->DR, (uint32_t)hspi->pRxBuffPtr, hspi->RxXferCount);
/* Enable Rx DMA Request */
hspi->Instance->CR2 |= SPI_CR2_RXDMAEN;
/* Process Unlocked */
__HAL_UNLOCK(hspi);
/* Check if the SPI is already enabled */
if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE)
{
/* Enable SPI peripheral */
__HAL_SPI_ENABLE(hspi);
}
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Transmit and Receive an amount of data in no-blocking mode with DMA
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @param pTxData: pointer to transmission data buffer
* @param pRxData: pointer to reception data buffer
* @note When the CRC feature is enabled the pRxData Length must be Size + 1
* @param Size: amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size)
{
uint32_t tmpstate = 0;
tmpstate = hspi->State;
if((tmpstate == HAL_SPI_STATE_READY) || ((hspi->Init.Mode == SPI_MODE_MASTER) && \
(hspi->Init.Direction == SPI_DIRECTION_2LINES) && (tmpstate == HAL_SPI_STATE_BUSY_RX)))
{
if((pTxData == NULL ) || (pRxData == NULL ) || (Size == 0))
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction));
/* Process locked */
__HAL_LOCK(hspi);
/* Don't overwrite in case of HAL_SPI_STATE_BUSY_RX */
if(hspi->State != HAL_SPI_STATE_BUSY_RX)
{
hspi->State = HAL_SPI_STATE_BUSY_TX_RX;
}
/* Configure communication */
hspi->ErrorCode = HAL_SPI_ERROR_NONE;
hspi->pTxBuffPtr = (uint8_t*)pTxData;
hspi->TxXferSize = Size;
hspi->TxXferCount = Size;
hspi->pRxBuffPtr = (uint8_t*)pRxData;
hspi->RxXferSize = Size;
hspi->RxXferCount = Size;
/*Init field not used in handle to zero */
hspi->RxISR = 0;
hspi->TxISR = 0;
/* Reset CRC Calculation */
if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
SPI_RESET_CRC(hspi);
}
/* Check if we are in Rx only or in Rx/Tx Mode and configure the DMA transfer complete callback */
if(hspi->State == HAL_SPI_STATE_BUSY_RX)
{
/* Set the SPI Rx DMA Half transfer complete callback */
hspi->hdmarx->XferHalfCpltCallback = SPI_DMAHalfReceiveCplt;
hspi->hdmarx->XferCpltCallback = SPI_DMAReceiveCplt;
}
else
{
/* Set the SPI Tx/Rx DMA Half transfer complete callback */
hspi->hdmarx->XferHalfCpltCallback = SPI_DMAHalfTransmitReceiveCplt;
hspi->hdmarx->XferCpltCallback = SPI_DMATransmitReceiveCplt;
}
/* Set the DMA error callback */
hspi->hdmarx->XferErrorCallback = SPI_DMAError;
/* Enable the Rx DMA Stream */
HAL_DMA_Start_IT(hspi->hdmarx, (uint32_t)&hspi->Instance->DR, (uint32_t)hspi->pRxBuffPtr, hspi->RxXferCount);
/* Enable Rx DMA Request */
hspi->Instance->CR2 |= SPI_CR2_RXDMAEN;
/* Set the SPI Tx DMA transfer complete callback as NULL because the communication closing
is performed in DMA reception complete callback */
hspi->hdmatx->XferCpltCallback = NULL;
if(hspi->State == HAL_SPI_STATE_BUSY_TX_RX)
{
/* Set the DMA error callback */
hspi->hdmatx->XferErrorCallback = SPI_DMAError;
}
else
{
hspi->hdmatx->XferErrorCallback = NULL;
}
/* Enable the Tx DMA Stream */
HAL_DMA_Start_IT(hspi->hdmatx, (uint32_t)hspi->pTxBuffPtr, (uint32_t)&hspi->Instance->DR, hspi->TxXferCount);
/* Check if the SPI is already enabled */
if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE)
{
/* Enable SPI peripheral */
__HAL_SPI_ENABLE(hspi);
}
/* Enable Tx DMA Request */
hspi->Instance->CR2 |= SPI_CR2_TXDMAEN;
/* Process Unlocked */
__HAL_UNLOCK(hspi);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Pauses the DMA Transfer.
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for the specified SPI module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPI_DMAPause(SPI_HandleTypeDef *hspi)
{
/* Process Locked */
__HAL_LOCK(hspi);
/* Disable the SPI DMA Tx & Rx requests */
hspi->Instance->CR2 &= (uint32_t)(~SPI_CR2_TXDMAEN);
hspi->Instance->CR2 &= (uint32_t)(~SPI_CR2_RXDMAEN);
/* Process Unlocked */
__HAL_UNLOCK(hspi);
return HAL_OK;
}
/**
* @brief Resumes the DMA Transfer.
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for the specified SPI module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPI_DMAResume(SPI_HandleTypeDef *hspi)
{
/* Process Locked */
__HAL_LOCK(hspi);
/* Enable the SPI DMA Tx & Rx requests */
hspi->Instance->CR2 |= SPI_CR2_TXDMAEN;
hspi->Instance->CR2 |= SPI_CR2_RXDMAEN;
/* Process Unlocked */
__HAL_UNLOCK(hspi);
return HAL_OK;
}
/**
* @brief Stops the DMA Transfer.
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for the specified SPI module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_SPI_DMAStop(SPI_HandleTypeDef *hspi)
{
/* The Lock is not implemented on this API to allow the user application
to call the HAL SPI API under callbacks HAL_SPI_TxCpltCallback() or HAL_SPI_RxCpltCallback() or HAL_SPI_TxRxCpltCallback():
when calling HAL_DMA_Abort() API the DMA TX/RX Transfer complete interrupt is generated
and the correspond call back is executed HAL_SPI_TxCpltCallback() or HAL_SPI_RxCpltCallback() or HAL_SPI_TxRxCpltCallback()
*/
/* Abort the SPI DMA tx Stream */
if(hspi->hdmatx != NULL)
{
HAL_DMA_Abort(hspi->hdmatx);
}
/* Abort the SPI DMA rx Stream */
if(hspi->hdmarx != NULL)
{
HAL_DMA_Abort(hspi->hdmarx);
}
/* Disable the SPI DMA Tx & Rx requests */
hspi->Instance->CR2 &= (uint32_t)(~SPI_CR2_TXDMAEN);
hspi->Instance->CR2 &= (uint32_t)(~SPI_CR2_RXDMAEN);
hspi->State = HAL_SPI_STATE_READY;
return HAL_OK;
}
/**
* @brief This function handles SPI interrupt request.
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval HAL status
*/
void HAL_SPI_IRQHandler(SPI_HandleTypeDef *hspi)
{
uint32_t tmp1 = 0, tmp2 = 0, tmp3 = 0;
tmp1 = __HAL_SPI_GET_FLAG(hspi, SPI_FLAG_RXNE);
tmp2 = __HAL_SPI_GET_IT_SOURCE(hspi, SPI_IT_RXNE);
tmp3 = __HAL_SPI_GET_FLAG(hspi, SPI_FLAG_OVR);
/* SPI in mode Receiver and Overrun not occurred ---------------------------*/
if((tmp1 != RESET) && (tmp2 != RESET) && (tmp3 == RESET))
{
hspi->RxISR(hspi);
return;
}
tmp1 = __HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE);
tmp2 = __HAL_SPI_GET_IT_SOURCE(hspi, SPI_IT_TXE);
/* SPI in mode Transmitter ---------------------------------------------------*/
if((tmp1 != RESET) && (tmp2 != RESET))
{
hspi->TxISR(hspi);
return;
}
if(__HAL_SPI_GET_IT_SOURCE(hspi, SPI_IT_ERR) != RESET)
{
/* SPI CRC error interrupt occurred ---------------------------------------*/
if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET)
{
hspi->ErrorCode |= HAL_SPI_ERROR_CRC;
__HAL_SPI_CLEAR_CRCERRFLAG(hspi);
}
/* SPI Mode Fault error interrupt occurred --------------------------------*/
if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_MODF) != RESET)
{
hspi->ErrorCode |= HAL_SPI_ERROR_MODF;
__HAL_SPI_CLEAR_MODFFLAG(hspi);
}
/* SPI Overrun error interrupt occurred -----------------------------------*/
if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_OVR) != RESET)
{
if(hspi->State != HAL_SPI_STATE_BUSY_TX)
{
hspi->ErrorCode |= HAL_SPI_ERROR_OVR;
__HAL_SPI_CLEAR_OVRFLAG(hspi);
}
}
/* SPI Frame error interrupt occurred -------------------------------------*/
if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_FRE) != RESET)
{
hspi->ErrorCode |= HAL_SPI_ERROR_FRE;
__HAL_SPI_CLEAR_FREFLAG(hspi);
}
/* Call the Error call Back in case of Errors */
if(hspi->ErrorCode!=HAL_SPI_ERROR_NONE)
{
hspi->State = HAL_SPI_STATE_READY;
HAL_SPI_ErrorCallback(hspi);
}
}
}
/**
* @brief Tx Transfer completed callbacks
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval None
*/
__weak void HAL_SPI_TxCpltCallback(SPI_HandleTypeDef *hspi)
{
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_SPI_TxCpltCallback could be implemented in the user file
*/
}
/**
* @brief Rx Transfer completed callbacks
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval None
*/
__weak void HAL_SPI_RxCpltCallback(SPI_HandleTypeDef *hspi)
{
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_SPI_RxCpltCallback() could be implemented in the user file
*/
}
/**
* @brief Tx and Rx Transfer completed callbacks
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval None
*/
__weak void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *hspi)
{
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_SPI_TxRxCpltCallback() could be implemented in the user file
*/
}
/**
* @brief Tx Half Transfer completed callbacks
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval None
*/
__weak void HAL_SPI_TxHalfCpltCallback(SPI_HandleTypeDef *hspi)
{
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_SPI_TxHalfCpltCallback could be implemented in the user file
*/
}
/**
* @brief Rx Half Transfer completed callbacks
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval None
*/
__weak void HAL_SPI_RxHalfCpltCallback(SPI_HandleTypeDef *hspi)
{
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_SPI_RxHalfCpltCallback() could be implemented in the user file
*/
}
/**
* @brief Tx and Rx Transfer completed callbacks
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval None
*/
__weak void HAL_SPI_TxRxHalfCpltCallback(SPI_HandleTypeDef *hspi)
{
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_SPI_TxRxHalfCpltCallback() could be implemented in the user file
*/
}
/**
* @brief SPI error callbacks
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval None
*/
__weak void HAL_SPI_ErrorCallback(SPI_HandleTypeDef *hspi)
{
/* NOTE : - This function Should not be modified, when the callback is needed,
the HAL_SPI_ErrorCallback() could be implemented in the user file.
- The ErrorCode parameter in the hspi handle is updated by the SPI processes
and user can use HAL_SPI_GetError() API to check the latest error occurred.
*/
}
/**
* @}
*/
/** @defgroup SPI_Exported_Functions_Group3 Peripheral State and Errors functions
* @brief SPI control functions
*
@verbatim
===============================================================================
##### Peripheral State and Errors functions #####
===============================================================================
[..]
This subsection provides a set of functions allowing to control the SPI.
(+) HAL_SPI_GetState() API can be helpful to check in run-time the state of the SPI peripheral
(+) HAL_SPI_GetError() check in run-time Errors occurring during communication
@endverbatim
* @{
*/
/**
* @brief Return the SPI state
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval HAL state
*/
HAL_SPI_StateTypeDef HAL_SPI_GetState(SPI_HandleTypeDef *hspi)
{
return hspi->State;
}
/**
* @brief Return the SPI error code
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval SPI Error Code
*/
uint32_t HAL_SPI_GetError(SPI_HandleTypeDef *hspi)
{
return hspi->ErrorCode;
}
/**
* @}
*/
/**
* @brief Interrupt Handler to close Tx transfer
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval void
*/
static void SPI_TxCloseIRQHandler(SPI_HandleTypeDef *hspi)
{
/* Wait until TXE flag is set to send data */
if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, SPI_TIMEOUT_VALUE) != HAL_OK)
{
hspi->ErrorCode |= HAL_SPI_ERROR_FLAG;
}
/* Disable TXE interrupt */
__HAL_SPI_DISABLE_IT(hspi, (SPI_IT_TXE ));
/* Disable ERR interrupt if Receive process is finished */
if(__HAL_SPI_GET_IT_SOURCE(hspi, SPI_IT_RXNE) == RESET)
{
__HAL_SPI_DISABLE_IT(hspi, (SPI_IT_ERR));
/* Wait until Busy flag is reset before disabling SPI */
if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_BSY, SET, SPI_TIMEOUT_VALUE) != HAL_OK)
{
hspi->ErrorCode |= HAL_SPI_ERROR_FLAG;
}
/* Clear OVERRUN flag in 2 Lines communication mode because received is not read */
if(hspi->Init.Direction == SPI_DIRECTION_2LINES)
{
__HAL_SPI_CLEAR_OVRFLAG(hspi);
}
/* Check if Errors has been detected during transfer */
if(hspi->ErrorCode == HAL_SPI_ERROR_NONE)
{
/* Check if we are in Tx or in Rx/Tx Mode */
if(hspi->State == HAL_SPI_STATE_BUSY_TX_RX)
{
/* Set state to READY before run the Callback Complete */
hspi->State = HAL_SPI_STATE_READY;
HAL_SPI_TxRxCpltCallback(hspi);
}
else
{
/* Set state to READY before run the Callback Complete */
hspi->State = HAL_SPI_STATE_READY;
HAL_SPI_TxCpltCallback(hspi);
}
}
else
{
/* Set state to READY before run the Callback Complete */
hspi->State = HAL_SPI_STATE_READY;
/* Call Error call back in case of Error */
HAL_SPI_ErrorCallback(hspi);
}
}
}
/**
* @brief Interrupt Handler to transmit amount of data in no-blocking mode
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval void
*/
static void SPI_TxISR(SPI_HandleTypeDef *hspi)
{
/* Transmit data in 8 Bit mode */
if(hspi->Init.DataSize == SPI_DATASIZE_8BIT)
{
hspi->Instance->DR = (*hspi->pTxBuffPtr++);
}
/* Transmit data in 16 Bit mode */
else
{
hspi->Instance->DR = *((uint16_t*)hspi->pTxBuffPtr);
hspi->pTxBuffPtr+=2;
}
hspi->TxXferCount--;
if(hspi->TxXferCount == 0)
{
if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
/* calculate and transfer CRC on Tx line */
hspi->Instance->CR1 |= SPI_CR1_CRCNEXT;
}
SPI_TxCloseIRQHandler(hspi);
}
}
/**
* @brief Interrupt Handler to close Rx transfer
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval void
*/
static void SPI_RxCloseIRQHandler(SPI_HandleTypeDef *hspi)
{
__IO uint16_t tmpreg;
if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
/* Wait until RXNE flag is set to send data */
if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, SPI_TIMEOUT_VALUE) != HAL_OK)
{
hspi->ErrorCode |= HAL_SPI_ERROR_FLAG;
}
/* Read CRC to reset RXNE flag */
tmpreg = hspi->Instance->DR;
UNUSED(tmpreg);
/* Wait until RXNE flag is set to send data */
if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, SET, SPI_TIMEOUT_VALUE) != HAL_OK)
{
hspi->ErrorCode |= HAL_SPI_ERROR_FLAG;
}
/* Check if CRC error occurred */
if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET)
{
hspi->ErrorCode |= HAL_SPI_ERROR_CRC;
/* Reset CRC Calculation */
SPI_RESET_CRC(hspi);
}
}
/* Disable RXNE and ERR interrupt */
__HAL_SPI_DISABLE_IT(hspi, (SPI_IT_RXNE));
/* if Transmit process is finished */
if(__HAL_SPI_GET_IT_SOURCE(hspi, SPI_IT_TXE) == RESET)
{
/* Disable ERR interrupt */
__HAL_SPI_DISABLE_IT(hspi, (SPI_IT_ERR));
if((hspi->Init.Mode == SPI_MODE_MASTER)&&((hspi->Init.Direction == SPI_DIRECTION_1LINE)||(hspi->Init.Direction == SPI_DIRECTION_2LINES_RXONLY)))
{
/* Disable SPI peripheral */
__HAL_SPI_DISABLE(hspi);
}
/* Check if Errors has been detected during transfer */
if(hspi->ErrorCode == HAL_SPI_ERROR_NONE)
{
/* Check if we are in Rx or in Rx/Tx Mode */
if(hspi->State == HAL_SPI_STATE_BUSY_TX_RX)
{
/* Set state to READY before run the Callback Complete */
hspi->State = HAL_SPI_STATE_READY;
HAL_SPI_TxRxCpltCallback(hspi);
}
else
{
/* Set state to READY before run the Callback Complete */
hspi->State = HAL_SPI_STATE_READY;
HAL_SPI_RxCpltCallback(hspi);
}
}
else
{
/* Set state to READY before run the Callback Complete */
hspi->State = HAL_SPI_STATE_READY;
/* Call Error call back in case of Error */
HAL_SPI_ErrorCallback(hspi);
}
}
}
/**
* @brief Interrupt Handler to receive amount of data in 2Lines mode
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval void
*/
static void SPI_2LinesRxISR(SPI_HandleTypeDef *hspi)
{
/* Receive data in 8 Bit mode */
if(hspi->Init.DataSize == SPI_DATASIZE_8BIT)
{
(*hspi->pRxBuffPtr++) = hspi->Instance->DR;
}
/* Receive data in 16 Bit mode */
else
{
*((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR;
hspi->pRxBuffPtr+=2;
}
hspi->RxXferCount--;
if(hspi->RxXferCount==0)
{
SPI_RxCloseIRQHandler(hspi);
}
}
/**
* @brief Interrupt Handler to receive amount of data in no-blocking mode
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @retval void
*/
static void SPI_RxISR(SPI_HandleTypeDef *hspi)
{
/* Receive data in 8 Bit mode */
if(hspi->Init.DataSize == SPI_DATASIZE_8BIT)
{
(*hspi->pRxBuffPtr++) = hspi->Instance->DR;
}
/* Receive data in 16 Bit mode */
else
{
*((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR;
hspi->pRxBuffPtr+=2;
}
hspi->RxXferCount--;
/* Enable CRC Transmission */
if((hspi->RxXferCount == 1) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE))
{
/* Set CRC Next to calculate CRC on Rx side */
hspi->Instance->CR1 |= SPI_CR1_CRCNEXT;
}
if(hspi->RxXferCount == 0)
{
SPI_RxCloseIRQHandler(hspi);
}
}
/**
* @brief DMA SPI transmit process complete callback
* @param hdma: pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void SPI_DMATransmitCplt(DMA_HandleTypeDef *hdma)
{
SPI_HandleTypeDef* hspi = ( SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
/* DMA Normal Mode */
if((hdma->Instance->CR & DMA_SxCR_CIRC) == 0)
{
/* Wait until TXE flag is set to send data */
if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, SPI_TIMEOUT_VALUE) != HAL_OK)
{
hspi->ErrorCode |= HAL_SPI_ERROR_FLAG;
}
/* Disable Tx DMA Request */
hspi->Instance->CR2 &= (uint32_t)(~SPI_CR2_TXDMAEN);
/* Wait until Busy flag is reset before disabling SPI */
if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_BSY, SET, SPI_TIMEOUT_VALUE) != HAL_OK)
{
hspi->ErrorCode |= HAL_SPI_ERROR_FLAG;
}
hspi->TxXferCount = 0;
hspi->State = HAL_SPI_STATE_READY;
}
/* Clear OVERRUN flag in 2 Lines communication mode because received is not read */
if(hspi->Init.Direction == SPI_DIRECTION_2LINES)
{
__HAL_SPI_CLEAR_OVRFLAG(hspi);
}
/* Check if Errors has been detected during transfer */
if(hspi->ErrorCode != HAL_SPI_ERROR_NONE)
{
HAL_SPI_ErrorCallback(hspi);
}
else
{
HAL_SPI_TxCpltCallback(hspi);
}
}
/**
* @brief DMA SPI receive process complete callback
* @param hdma: pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void SPI_DMAReceiveCplt(DMA_HandleTypeDef *hdma)
{
__IO uint16_t tmpreg;
SPI_HandleTypeDef* hspi = ( SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
/* DMA Normal mode */
if((hdma->Instance->CR & DMA_SxCR_CIRC) == 0)
{
if((hspi->Init.Mode == SPI_MODE_MASTER)&&((hspi->Init.Direction == SPI_DIRECTION_1LINE)||(hspi->Init.Direction == SPI_DIRECTION_2LINES_RXONLY)))
{
/* Disable SPI peripheral */
__HAL_SPI_DISABLE(hspi);
}
/* Disable Rx DMA Request */
hspi->Instance->CR2 &= (uint32_t)(~SPI_CR2_RXDMAEN);
/* Disable Tx DMA Request (done by default to handle the case Master RX direction 2 lines) */
hspi->Instance->CR2 &= (uint32_t)(~SPI_CR2_TXDMAEN);
hspi->RxXferCount = 0;
hspi->State = HAL_SPI_STATE_READY;
/* Reset CRC Calculation */
if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
/* Wait until RXNE flag is set to send data */
if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, SPI_TIMEOUT_VALUE) != HAL_OK)
{
hspi->ErrorCode |= HAL_SPI_ERROR_FLAG;
}
/* Read CRC */
tmpreg = hspi->Instance->DR;
UNUSED(tmpreg);
/* Wait until RXNE flag is set */
if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, SET, SPI_TIMEOUT_VALUE) != HAL_OK)
{
hspi->ErrorCode |= HAL_SPI_ERROR_FLAG;
}
/* Check if CRC error occurred */
if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET)
{
hspi->ErrorCode |= HAL_SPI_ERROR_CRC;
__HAL_SPI_CLEAR_CRCERRFLAG(hspi);
}
}
/* Check if Errors has been detected during transfer */
if(hspi->ErrorCode != HAL_SPI_ERROR_NONE)
{
HAL_SPI_ErrorCallback(hspi);
}
else
{
HAL_SPI_RxCpltCallback(hspi);
}
}
else
{
HAL_SPI_RxCpltCallback(hspi);
}
}
/**
* @brief DMA SPI transmit receive process complete callback
* @param hdma: pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void SPI_DMATransmitReceiveCplt(DMA_HandleTypeDef *hdma)
{
__IO uint16_t tmpreg;
SPI_HandleTypeDef* hspi = ( SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
if((hdma->Instance->CR & DMA_SxCR_CIRC) == 0)
{
/* Reset CRC Calculation */
if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
/* Check if CRC is done on going (RXNE flag set) */
if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, SET, SPI_TIMEOUT_VALUE) == HAL_OK)
{
/* Wait until RXNE flag is set to send data */
if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, SPI_TIMEOUT_VALUE) != HAL_OK)
{
hspi->ErrorCode |= HAL_SPI_ERROR_FLAG;
}
}
/* Read CRC */
tmpreg = hspi->Instance->DR;
UNUSED(tmpreg);
/* Check if CRC error occurred */
if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET)
{
hspi->ErrorCode |= HAL_SPI_ERROR_CRC;
__HAL_SPI_CLEAR_CRCERRFLAG(hspi);
}
}
/* Wait until TXE flag is set to send data */
if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, SPI_TIMEOUT_VALUE) != HAL_OK)
{
hspi->ErrorCode |= HAL_SPI_ERROR_FLAG;
}
/* Disable Tx DMA Request */
hspi->Instance->CR2 &= (uint32_t)(~SPI_CR2_TXDMAEN);
/* Wait until Busy flag is reset before disabling SPI */
if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_BSY, SET, SPI_TIMEOUT_VALUE) != HAL_OK)
{
hspi->ErrorCode |= HAL_SPI_ERROR_FLAG;
}
/* Disable Rx DMA Request */
hspi->Instance->CR2 &= (uint32_t)(~SPI_CR2_RXDMAEN);
hspi->TxXferCount = 0;
hspi->RxXferCount = 0;
hspi->State = HAL_SPI_STATE_READY;
/* Check if Errors has been detected during transfer */
if(hspi->ErrorCode != HAL_SPI_ERROR_NONE)
{
HAL_SPI_ErrorCallback(hspi);
}
else
{
HAL_SPI_TxRxCpltCallback(hspi);
}
}
else
{
HAL_SPI_TxRxCpltCallback(hspi);
}
}
/**
* @brief DMA SPI half transmit process complete callback
* @param hdma: pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void SPI_DMAHalfTransmitCplt(DMA_HandleTypeDef *hdma)
{
SPI_HandleTypeDef* hspi = ( SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
HAL_SPI_TxHalfCpltCallback(hspi);
}
/**
* @brief DMA SPI half receive process complete callback
* @param hdma: pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void SPI_DMAHalfReceiveCplt(DMA_HandleTypeDef *hdma)
{
SPI_HandleTypeDef* hspi = ( SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
HAL_SPI_RxHalfCpltCallback(hspi);
}
/**
* @brief DMA SPI Half transmit receive process complete callback
* @param hdma: pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void SPI_DMAHalfTransmitReceiveCplt(DMA_HandleTypeDef *hdma)
{
SPI_HandleTypeDef* hspi = ( SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
HAL_SPI_TxRxHalfCpltCallback(hspi);
}
/**
* @brief DMA SPI communication error callback
* @param hdma: pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void SPI_DMAError(DMA_HandleTypeDef *hdma)
{
SPI_HandleTypeDef* hspi = (SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
hspi->TxXferCount = 0;
hspi->RxXferCount = 0;
hspi->State= HAL_SPI_STATE_READY;
hspi->ErrorCode |= HAL_SPI_ERROR_DMA;
HAL_SPI_ErrorCallback(hspi);
}
/**
* @brief This function handles SPI Communication Timeout.
* @param hspi: pointer to a SPI_HandleTypeDef structure that contains
* the configuration information for SPI module.
* @param Flag: SPI flag to check
* @param Status: Flag status to check: RESET or set
* @param Timeout: Timeout duration
* @retval HAL status
*/
static HAL_StatusTypeDef SPI_WaitOnFlagUntilTimeout(SPI_HandleTypeDef *hspi, uint32_t Flag, FlagStatus Status, uint32_t Timeout)
{
uint32_t tickstart = 0;
/* Get tick */
tickstart = HAL_GetTick();
/* Wait until flag is set */
if(Status == RESET)
{
while(__HAL_SPI_GET_FLAG(hspi, Flag) == RESET)
{
if(Timeout != HAL_MAX_DELAY)
{
if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout))
{
/* Disable the SPI and reset the CRC: the CRC value should be cleared
on both master and slave sides in order to resynchronize the master
and slave for their respective CRC calculation */
/* Disable TXE, RXNE and ERR interrupts for the interrupt process */
__HAL_SPI_DISABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR));
/* Disable SPI peripheral */
__HAL_SPI_DISABLE(hspi);
/* Reset CRC Calculation */
if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
SPI_RESET_CRC(hspi);
}
hspi->State= HAL_SPI_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hspi);
return HAL_TIMEOUT;
}
}
}
}
else
{
while(__HAL_SPI_GET_FLAG(hspi, Flag) != RESET)
{
if(Timeout != HAL_MAX_DELAY)
{
if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout))
{
/* Disable the SPI and reset the CRC: the CRC value should be cleared
on both master and slave sides in order to resynchronize the master
and slave for their respective CRC calculation */
/* Disable TXE, RXNE and ERR interrupts for the interrupt process */
__HAL_SPI_DISABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR));
/* Disable SPI peripheral */
__HAL_SPI_DISABLE(hspi);
/* Reset CRC Calculation */
if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLE)
{
SPI_RESET_CRC(hspi);
}
hspi->State= HAL_SPI_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hspi);
return HAL_TIMEOUT;
}
}
}
}
return HAL_OK;
}
/**
* @}
*/
#endif /* HAL_SPI_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| St3dPrinter/Marlin4ST | stm32_cube/STM32/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_spi.c | C | gpl-3.0 | 70,497 |
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2017 - ROLI Ltd.
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 5 End-User License
Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
27th April 2017).
End User License Agreement: www.juce.com/juce-5-licence
Privacy Policy: www.juce.com/juce-5-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
namespace PropertyFileConstants
{
static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
static const char* const fileTag = "PROPERTIES";
static const char* const valueTag = "VALUE";
static const char* const nameAttribute = "name";
static const char* const valueAttribute = "val";
}
//==============================================================================
PropertiesFile::Options::Options()
: commonToAllUsers (false),
ignoreCaseOfKeyNames (false),
doNotSave (false),
millisecondsBeforeSaving (3000),
storageFormat (PropertiesFile::storeAsXML),
processLock (nullptr)
{
}
File PropertiesFile::Options::getDefaultFile() const
{
// mustn't have illegal characters in this name..
jassert (applicationName == File::createLegalFileName (applicationName));
#if JUCE_MAC || JUCE_IOS
File dir (commonToAllUsers ? "/Library/"
: "~/Library/");
if (osxLibrarySubFolder != "Preferences" && ! osxLibrarySubFolder.startsWith ("Application Support"))
{
/* The PropertiesFile class always used to put its settings files in "Library/Preferences", but Apple
have changed their advice, and now stipulate that settings should go in "Library/Application Support".
Because older apps would be broken by a silent change in this class's behaviour, you must now
explicitly set the osxLibrarySubFolder value to indicate which path you want to use.
In newer apps, you should always set this to "Application Support"
or "Application Support/YourSubFolderName".
If your app needs to load settings files that were created by older versions of juce and
you want to maintain backwards-compatibility, then you can set this to "Preferences".
But.. for better Apple-compliance, the recommended approach would be to write some code that
finds your old settings files in ~/Library/Preferences, moves them to ~/Library/Application Support,
and then uses the new path.
*/
jassertfalse;
dir = dir.getChildFile ("Application Support");
}
else
{
dir = dir.getChildFile (osxLibrarySubFolder);
}
if (folderName.isNotEmpty())
dir = dir.getChildFile (folderName);
#elif JUCE_LINUX || JUCE_ANDROID
const File dir (File (commonToAllUsers ? "/var" : "~")
.getChildFile (folderName.isNotEmpty() ? folderName
: ("." + applicationName)));
#elif JUCE_WINDOWS
File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
: File::userApplicationDataDirectory));
if (dir == File())
return {};
dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
: applicationName);
#endif
return (filenameSuffix.startsWithChar (L'.')
? dir.getChildFile (applicationName).withFileExtension (filenameSuffix)
: dir.getChildFile (applicationName + "." + filenameSuffix));
}
//==============================================================================
PropertiesFile::PropertiesFile (const File& f, const Options& o)
: PropertySet (o.ignoreCaseOfKeyNames),
file (f), options (o),
loadedOk (false), needsWriting (false)
{
reload();
}
PropertiesFile::PropertiesFile (const Options& o)
: PropertySet (o.ignoreCaseOfKeyNames),
file (o.getDefaultFile()), options (o),
loadedOk (false), needsWriting (false)
{
reload();
}
bool PropertiesFile::reload()
{
ProcessScopedLock pl (createProcessLock());
if (pl != nullptr && ! pl->isLocked())
return false; // locking failure..
loadedOk = (! file.exists()) || loadAsBinary() || loadAsXml();
return loadedOk;
}
PropertiesFile::~PropertiesFile()
{
saveIfNeeded();
}
InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
{
return options.processLock != nullptr ? new InterProcessLock::ScopedLockType (*options.processLock) : nullptr;
}
bool PropertiesFile::saveIfNeeded()
{
const ScopedLock sl (getLock());
return (! needsWriting) || save();
}
bool PropertiesFile::needsToBeSaved() const
{
const ScopedLock sl (getLock());
return needsWriting;
}
void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
{
const ScopedLock sl (getLock());
needsWriting = needsToBeSaved_;
}
bool PropertiesFile::save()
{
const ScopedLock sl (getLock());
stopTimer();
if (options.doNotSave
|| file == File()
|| file.isDirectory()
|| ! file.getParentDirectory().createDirectory())
return false;
if (options.storageFormat == storeAsXML)
return saveAsXml();
return saveAsBinary();
}
bool PropertiesFile::loadAsXml()
{
XmlDocument parser (file);
ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
if (doc != nullptr && doc->hasTagName (PropertyFileConstants::fileTag))
{
doc = parser.getDocumentElement();
if (doc != nullptr)
{
forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
{
const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
if (name.isNotEmpty())
{
getAllProperties().set (name,
e->getFirstChildElement() != nullptr
? e->getFirstChildElement()->createDocument ("", true)
: e->getStringAttribute (PropertyFileConstants::valueAttribute));
}
}
return true;
}
// must be a pretty broken XML file we're trying to parse here,
// or a sign that this object needs an InterProcessLock,
// or just a failure reading the file. This last reason is why
// we don't jassertfalse here.
}
return false;
}
bool PropertiesFile::saveAsXml()
{
XmlElement doc (PropertyFileConstants::fileTag);
const StringPairArray& props = getAllProperties();
for (int i = 0; i < props.size(); ++i)
{
XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
e->setAttribute (PropertyFileConstants::nameAttribute, props.getAllKeys() [i]);
// if the value seems to contain xml, store it as such..
if (XmlElement* const childElement = XmlDocument::parse (props.getAllValues() [i]))
e->addChildElement (childElement);
else
e->setAttribute (PropertyFileConstants::valueAttribute, props.getAllValues() [i]);
}
ProcessScopedLock pl (createProcessLock());
if (pl != nullptr && ! pl->isLocked())
return false; // locking failure..
if (doc.writeToFile (file, String()))
{
needsWriting = false;
return true;
}
return false;
}
bool PropertiesFile::loadAsBinary()
{
FileInputStream fileStream (file);
if (fileStream.openedOk())
{
const int magicNumber = fileStream.readInt();
if (magicNumber == PropertyFileConstants::magicNumberCompressed)
{
SubregionStream subStream (&fileStream, 4, -1, false);
GZIPDecompressorInputStream gzip (subStream);
return loadAsBinary (gzip);
}
if (magicNumber == PropertyFileConstants::magicNumber)
return loadAsBinary (fileStream);
}
return false;
}
bool PropertiesFile::loadAsBinary (InputStream& input)
{
BufferedInputStream in (input, 2048);
int numValues = in.readInt();
while (--numValues >= 0 && ! in.isExhausted())
{
const String key (in.readString());
const String value (in.readString());
jassert (key.isNotEmpty());
if (key.isNotEmpty())
getAllProperties().set (key, value);
}
return true;
}
bool PropertiesFile::saveAsBinary()
{
ProcessScopedLock pl (createProcessLock());
if (pl != nullptr && ! pl->isLocked())
return false; // locking failure..
TemporaryFile tempFile (file);
ScopedPointer<OutputStream> out (tempFile.getFile().createOutputStream());
if (out != nullptr)
{
if (options.storageFormat == storeAsCompressedBinary)
{
out->writeInt (PropertyFileConstants::magicNumberCompressed);
out->flush();
out = new GZIPCompressorOutputStream (out.release(), 9, true);
}
else
{
// have you set up the storage option flags correctly?
jassert (options.storageFormat == storeAsBinary);
out->writeInt (PropertyFileConstants::magicNumber);
}
const StringPairArray& props = getAllProperties();
const int numProperties = props.size();
const StringArray& keys = props.getAllKeys();
const StringArray& values = props.getAllValues();
out->writeInt (numProperties);
for (int i = 0; i < numProperties; ++i)
{
out->writeString (keys[i]);
out->writeString (values[i]);
}
out = nullptr;
if (tempFile.overwriteTargetFileWithTemporary())
{
needsWriting = false;
return true;
}
}
return false;
}
void PropertiesFile::timerCallback()
{
saveIfNeeded();
}
void PropertiesFile::propertyChanged()
{
sendChangeMessage();
needsWriting = true;
if (options.millisecondsBeforeSaving > 0)
startTimer (options.millisecondsBeforeSaving);
else if (options.millisecondsBeforeSaving == 0)
saveIfNeeded();
}
| TheTechnobear/MEC | mec-vst/JuceLibraryCode/modules/juce_data_structures/app_properties/juce_PropertiesFile.cpp | C++ | gpl-3.0 | 11,261 |
#region License
// Copyright (c) 2013, ClearCanvas Inc.
// All rights reserved.
// http://www.ClearCanvas.ca
//
// This file is part of the ClearCanvas RIS/PACS open source project.
//
// The ClearCanvas RIS/PACS open source project 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.
//
// The ClearCanvas RIS/PACS open source project 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
// the ClearCanvas RIS/PACS open source project. If not, see
// <http://www.gnu.org/licenses/>.
#endregion
using Macro.Dicom;
using Macro.ImageServer.Model;
namespace Macro.ImageServer.Core
{
/// <summary>
/// Defines the interface of the Pre-Processors to execute on a file
/// </summary>
internal interface IStudyPreProcessor
{
/// <summary>
/// Called to process a DICOM file.
/// </summary>
/// <param name="file"></param>
/// <returns>An instance of <see cref="InstancePreProcessingResult"/> containing the result of the processing. NULL if
/// the change has been made to the file.</returns>
InstancePreProcessingResult Process(DicomFile file);
/// <summary>
/// Gets or sets the <see cref="StudyStorageLocation"/> of the study which the
/// DICOM file(s) belong to.
/// </summary>
StudyStorageLocation StorageLocation { get; set;}
/// <summary>
/// Gets or sets the description of the pre-processor.
/// </summary>
string Description
{
get;
set;
}
}
} | mayioit/MacroMedicalSystem | ImageServer/Core/IStudyPreProcessor.cs | C# | gpl-3.0 | 1,992 |
#ifndef GLOBAL_H_
#define GLOBAL_H_
/**
* 공용 필수 라이브러리 포함 부분
*/
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <map>
#include <pthread.h>
using namespace std;
/**
* 리눅스 네트워크 통신 공용 라이브러리 포함 부분
*/
#include <sys/epoll.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <netdb.h>
#include <errno.h>
#include <unistd.h>
/**
* 이 다음 부분에 사용자 정의 라이브러리들을 포함
*/
#endif
| kbu1564/SecurityBootloader | server/include/Global.h | C | gpl-3.0 | 558 |
"""Generate test data for IDTxl network comparison unit and system tests.
Generate test data for IDTxl network comparison unit and system tests. Simulate
discrete and continous data from three correlated Gaussian data sets. Perform
network inference using bivariate/multivariate mutual information (MI)/transfer
entropy (TE) analysis. Results are saved used for unit and system testing of
network comparison (systemtest_network_comparison.py).
A coupling is simulated as a lagged, linear correlation between three Gaussian
variables and looks like this:
1 -> 2 -> 3 with a delay of 1 sample for each coupling
"""
import pickle
import numpy as np
from idtxl.multivariate_te import MultivariateTE
from idtxl.bivariate_te import BivariateTE
from idtxl.multivariate_mi import MultivariateMI
from idtxl.bivariate_mi import BivariateMI
from idtxl.estimators_jidt import JidtDiscreteCMI
from idtxl.data import Data
# path = os.path.join(os.path.dirname(__file__) + '/data/')
path = 'data/'
def analyse_mute_te_data():
# Generate example data: the following was ran once to generate example
# data, which is now in the data sub-folder of the test-folder.
data = Data()
data.generate_mute_data(100, 5)
# analysis settings
settings = {
'cmi_estimator': 'JidtKraskovCMI',
'n_perm_max_stat': 50,
'n_perm_min_stat': 50,
'n_perm_omnibus': 200,
'n_perm_max_seq': 50,
'max_lag_target': 5,
'max_lag_sources': 5,
'min_lag_sources': 1,
'permute_in_time': True
}
# network inference for individual data sets
nw_0 = MultivariateTE()
res_0 = nw_0.analyse_network(
settings, data, targets=[0, 1], sources='all')
pickle.dump(res_0, open(path + 'mute_results_0.p', 'wb'))
res_1 = nw_0.analyse_network(
settings, data, targets=[1, 2], sources='all')
pickle.dump(res_1, open(path + 'mute_results_1.p', 'wb'))
res_2 = nw_0.analyse_network(
settings, data, targets=[0, 2], sources='all')
pickle.dump(res_2, open(path + 'mute_results_2.p', 'wb'))
res_3 = nw_0.analyse_network(
settings, data, targets=[0, 1, 2], sources='all')
pickle.dump(res_3, open(path + 'mute_results_3.p', 'wb'))
res_4 = nw_0.analyse_network(
settings, data, targets=[1, 2], sources='all')
pickle.dump(res_4, open(path + 'mute_results_4.p', 'wb'))
res_5 = nw_0.analyse_network(settings, data)
pickle.dump(res_5, open(path + 'mute_results_full.p', 'wb'))
def generate_discrete_data(n_replications=1):
"""Generate Gaussian test data: 1 -> 2 -> 3, delay 1."""
d = generate_gauss_data(n_replications=n_replications, discrete=True)
data = Data(d, dim_order='psr', normalise=False)
return data
def generate_continuous_data(n_replications=1):
"""Generate Gaussian test data: 1 -> 2 -> 3, delay 1."""
d = generate_gauss_data(n_replications=n_replications, discrete=False)
data = Data(d, dim_order='psr', normalise=True)
return data
def generate_gauss_data(n_replications=1, discrete=False):
settings = {'discretise_method': 'equal',
'n_discrete_bins': 5}
est = JidtDiscreteCMI(settings)
covariance_1 = 0.4
covariance_2 = 0.3
n = 10000
delay = 1
if discrete:
d = np.zeros((3, n - 2*delay, n_replications), dtype=int)
else:
d = np.zeros((3, n - 2*delay, n_replications))
for r in range(n_replications):
proc_1 = np.random.normal(0, 1, size=n)
proc_2 = (covariance_1 * proc_1 + (1 - covariance_1) *
np.random.normal(0, 1, size=n))
proc_3 = (covariance_2 * proc_2 + (1 - covariance_2) *
np.random.normal(0, 1, size=n))
proc_1 = proc_1[(2*delay):]
proc_2 = proc_2[delay:-delay]
proc_3 = proc_3[:-(2*delay)]
if discrete: # discretise data
proc_1_dis, proc_2_dis = est._discretise_vars(
var1=proc_1, var2=proc_2)
proc_1_dis, proc_3_dis = est._discretise_vars(
var1=proc_1, var2=proc_3)
d[0, :, r] = proc_1_dis
d[1, :, r] = proc_2_dis
d[2, :, r] = proc_3_dis
else:
d[0, :, r] = proc_1
d[1, :, r] = proc_2
d[2, :, r] = proc_3
return d
def analyse_discrete_data():
"""Run network inference on discrete data."""
data = generate_discrete_data()
settings = {
'cmi_estimator': 'JidtDiscreteCMI',
'discretise_method': 'none',
'n_discrete_bins': 5, # alphabet size of the variables analysed
'min_lag_sources': 1,
'max_lag_sources': 3,
'max_lag_target': 1}
nw = MultivariateTE()
res = nw.analyse_network(settings=settings, data=data)
pickle.dump(res, open('{0}discrete_results_mte_{1}.p'.format(
path, settings['cmi_estimator']), 'wb'))
nw = BivariateTE()
res = nw.analyse_network(settings=settings, data=data)
pickle.dump(res, open('{0}discrete_results_bte_{1}.p'.format(
path, settings['cmi_estimator']), 'wb'))
nw = MultivariateMI()
res = nw.analyse_network(settings=settings, data=data)
pickle.dump(res, open('{0}discrete_results_mmi_{1}.p'.format(
path, settings['cmi_estimator']), 'wb'))
nw = BivariateMI()
res = nw.analyse_network(settings=settings, data=data)
pickle.dump(res, open('{0}discrete_results_bmi_{1}.p'.format(
path, settings['cmi_estimator']), 'wb'))
def analyse_continuous_data():
"""Run network inference on continuous data."""
data = generate_continuous_data()
settings = {
'min_lag_sources': 1,
'max_lag_sources': 3,
'max_lag_target': 1}
nw = MultivariateTE()
for estimator in ['JidtGaussianCMI', 'JidtKraskovCMI']:
settings['cmi_estimator'] = estimator
res = nw.analyse_network(settings=settings, data=data)
pickle.dump(res, open('{0}continuous_results_mte_{1}.p'.format(
path, estimator), 'wb'))
nw = BivariateTE()
for estimator in ['JidtGaussianCMI', 'JidtKraskovCMI']:
settings['cmi_estimator'] = estimator
res = nw.analyse_network(settings=settings, data=data)
pickle.dump(res, open('{0}continuous_results_bte_{1}.p'.format(
path, estimator), 'wb'))
nw = MultivariateMI()
for estimator in ['JidtGaussianCMI', 'JidtKraskovCMI']:
settings['cmi_estimator'] = estimator
res = nw.analyse_network(settings=settings, data=data)
pickle.dump(res, open('{0}continuous_results_mmi_{1}.p'.format(
path, estimator), 'wb'))
nw = BivariateMI()
for estimator in ['JidtGaussianCMI', 'JidtKraskovCMI']:
settings['cmi_estimator'] = estimator
res = nw.analyse_network(settings=settings, data=data)
pickle.dump(res, open('{0}continuous_results_bmi_{1}.p'.format(
path, estimator), 'wb'))
def assert_results():
for algo in ['mmi', 'mte', 'bmi', 'bte']:
# Test continuous data:
for estimator in ['JidtGaussianCMI', 'JidtKraskovCMI']:
res = pickle.load(open(
'data/continuous_results_{0}_{1}.p'.format(
algo, estimator), 'rb'))
print('\nInference algorithm: {0} (estimator: {1})'.format(
algo, estimator))
_print_result(res)
# Test discrete data:
estimator = 'JidtDiscreteCMI'
res = pickle.load(open(
'data/discrete_results_{0}_{1}.p'.format(
algo, estimator), 'rb'))
print('\nInference algorithm: {0} (estimator: {1})'.format(
algo, estimator))
_print_result(res)
def _print_result(res):
res.adjacency_matrix.print_matrix()
tp = 0
fp = 0
if res.adjacency_matrix._edge_matrix[0, 1] == True: tp += 1
if res.adjacency_matrix._edge_matrix[1, 2] == True: tp += 1
if res.adjacency_matrix._edge_matrix[0, 2] == True: fp += 1
fn = 2 - tp
print('TP: {0}, FP: {1}, FN: {2}'.format(tp, fp, fn))
if __name__ == '__main__':
analyse_discrete_data()
analyse_mute_te_data()
analyse_continuous_data()
assert_results()
| pwollstadt/IDTxl | test/generate_test_data.py | Python | gpl-3.0 | 8,187 |
# Author: Nic Wolfe <nic@wolfeden.ca>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of SickRage.
#
# SickRage 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.
#
# SickRage 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 SickRage. If not, see <http://www.gnu.org/licenses/>.
from __future__ import with_statement
import os
import re
import threading
import datetime
import traceback
import sickbeard
from common import SNATCHED, SNATCHED_PROPER, SNATCHED_BEST, Quality, SEASON_RESULT, MULTI_EP_RESULT
from sickbeard import logger, db, show_name_helpers, exceptions, helpers
from sickbeard import sab
from sickbeard import nzbget
from sickbeard import clients
from sickbeard import history
from sickbeard import notifiers
from sickbeard import nzbSplitter
from sickbeard import ui
from sickbeard import encodingKludge as ek
from sickbeard import failed_history
from sickbeard.exceptions import ex
from sickbeard.providers.generic import GenericProvider
from sickbeard import common
def _downloadResult(result):
"""
Downloads a result to the appropriate black hole folder.
Returns a bool representing success.
result: SearchResult instance to download.
"""
resProvider = result.provider
if resProvider == None:
logger.log(u"Invalid provider name - this is a coding error, report it please", logger.ERROR)
return False
# nzbs with an URL can just be downloaded from the provider
if result.resultType == "nzb":
newResult = resProvider.downloadResult(result)
# if it's an nzb data result
elif result.resultType == "nzbdata":
# get the final file path to the nzb
fileName = ek.ek(os.path.join, sickbeard.NZB_DIR, result.name + ".nzb")
logger.log(u"Saving NZB to " + fileName)
newResult = True
# save the data to disk
try:
with ek.ek(open, fileName, 'w') as fileOut:
fileOut.write(result.extraInfo[0])
helpers.chmodAsParent(fileName)
except EnvironmentError, e:
logger.log(u"Error trying to save NZB to black hole: " + ex(e), logger.ERROR)
newResult = False
elif resProvider.providerType == "torrent":
newResult = resProvider.downloadResult(result)
else:
logger.log(u"Invalid provider type - this is a coding error, report it please", logger.ERROR)
newResult = False
return newResult
def snatchEpisode(result, endStatus=SNATCHED):
"""
Contains the internal logic necessary to actually "snatch" a result that
has been found.
Returns a bool representing success.
result: SearchResult instance to be snatched.
endStatus: the episode status that should be used for the episode object once it's snatched.
"""
if result is None:
return False
result.priority = 0 # -1 = low, 0 = normal, 1 = high
if sickbeard.ALLOW_HIGH_PRIORITY:
# if it aired recently make it high priority
for curEp in result.episodes:
if datetime.date.today() - curEp.airdate <= datetime.timedelta(days=7):
result.priority = 1
if re.search('(^|[\. _-])(proper|repack)([\. _-]|$)', result.name, re.I) != None:
endStatus = SNATCHED_PROPER
# NZBs can be sent straight to SAB or saved to disk
if result.resultType in ("nzb", "nzbdata"):
if sickbeard.NZB_METHOD == "blackhole":
dlResult = _downloadResult(result)
elif sickbeard.NZB_METHOD == "sabnzbd":
dlResult = sab.sendNZB(result)
elif sickbeard.NZB_METHOD == "nzbget":
is_proper = True if endStatus == SNATCHED_PROPER else False
dlResult = nzbget.sendNZB(result, is_proper)
else:
logger.log(u"Unknown NZB action specified in config: " + sickbeard.NZB_METHOD, logger.ERROR)
dlResult = False
# TORRENTs can be sent to clients or saved to disk
elif result.resultType == "torrent":
# torrents are saved to disk when blackhole mode
if sickbeard.TORRENT_METHOD == "blackhole":
dlResult = _downloadResult(result)
else:
if not result.content and not result.url.startswith('magnet'):
result.content = result.provider.getURL(result.url)
if result.content or result.url.startswith('magnet'):
client = clients.getClientIstance(sickbeard.TORRENT_METHOD)()
dlResult = client.sendTORRENT(result)
else:
logger.log(u"Torrent file content is empty", logger.WARNING)
dlResult = False
else:
logger.log(u"Unknown result type, unable to download it", logger.ERROR)
dlResult = False
if not dlResult:
return False
if sickbeard.USE_FAILED_DOWNLOADS:
failed_history.logSnatch(result)
ui.notifications.message('Episode snatched', result.name)
history.logSnatch(result)
# don't notify when we re-download an episode
sql_l = []
trakt_data = []
for curEpObj in result.episodes:
with curEpObj.lock:
if isFirstBestMatch(result):
curEpObj.status = Quality.compositeStatus(SNATCHED_BEST, result.quality)
else:
curEpObj.status = Quality.compositeStatus(endStatus, result.quality)
sql_l.append(curEpObj.get_sql())
if curEpObj.status not in Quality.DOWNLOADED:
notifiers.notify_snatch(curEpObj._format_pattern('%SN - %Sx%0E - %EN - %QN') + " from " + result.provider.name)
trakt_data.append((curEpObj.season, curEpObj.episode))
data = notifiers.trakt_notifier.trakt_episode_data_generate(trakt_data)
if sickbeard.USE_TRAKT and sickbeard.TRAKT_SYNC_WATCHLIST:
logger.log(u"Add episodes, showid: indexerid " + str(result.show.indexerid) + ", Title " + str(result.show.name) + " to Traktv Watchlist", logger.DEBUG)
if data:
notifiers.trakt_notifier.update_watchlist(result.show, data_episode=data, update="add")
if len(sql_l) > 0:
myDB = db.DBConnection()
myDB.mass_action(sql_l)
return True
def pickBestResult(results, show):
results = results if isinstance(results, list) else [results]
logger.log(u"Picking the best result out of " + str([x.name for x in results]), logger.DEBUG)
bestResult = None
# find the best result for the current episode
for cur_result in results:
if show and cur_result.show is not show:
continue
# build the black And white list
if show.is_anime:
if not show.release_groups.is_valid(cur_result):
continue
logger.log("Quality of " + cur_result.name + " is " + Quality.qualityStrings[cur_result.quality])
anyQualities, bestQualities = Quality.splitQuality(show.quality)
if cur_result.quality not in anyQualities + bestQualities:
logger.log(cur_result.name + " is a quality we know we don't want, rejecting it", logger.DEBUG)
continue
if show.rls_ignore_words and show_name_helpers.containsAtLeastOneWord(cur_result.name, cur_result.show.rls_ignore_words):
logger.log(u"Ignoring " + cur_result.name + " based on ignored words filter: " + show.rls_ignore_words,
logger.INFO)
continue
if show.rls_require_words and not show_name_helpers.containsAtLeastOneWord(cur_result.name, cur_result.show.rls_require_words):
logger.log(u"Ignoring " + cur_result.name + " based on required words filter: " + show.rls_require_words,
logger.INFO)
continue
if not show_name_helpers.filterBadReleases(cur_result.name, parse=False):
logger.log(u"Ignoring " + cur_result.name + " because its not a valid scene release that we want, ignoring it",
logger.INFO)
continue
if hasattr(cur_result, 'size'):
if sickbeard.USE_FAILED_DOWNLOADS and failed_history.hasFailed(cur_result.name, cur_result.size,
cur_result.provider.name):
logger.log(cur_result.name + u" has previously failed, rejecting it")
continue
if not bestResult:
bestResult = cur_result
elif cur_result.quality in bestQualities and (bestResult.quality < cur_result.quality or bestResult not in bestQualities):
bestResult = cur_result
elif cur_result.quality in anyQualities and bestResult not in bestQualities and bestResult.quality < cur_result.quality:
bestResult = cur_result
elif bestResult.quality == cur_result.quality:
if "proper" in cur_result.name.lower() or "repack" in cur_result.name.lower():
bestResult = cur_result
elif "internal" in bestResult.name.lower() and "internal" not in cur_result.name.lower():
bestResult = cur_result
elif "xvid" in bestResult.name.lower() and "x264" in cur_result.name.lower():
logger.log(u"Preferring " + cur_result.name + " (x264 over xvid)")
bestResult = cur_result
if bestResult:
logger.log(u"Picked " + bestResult.name + " as the best", logger.DEBUG)
else:
logger.log(u"No result picked.", logger.DEBUG)
return bestResult
def isFinalResult(result):
"""
Checks if the given result is good enough quality that we can stop searching for other ones.
If the result is the highest quality in both the any/best quality lists then this function
returns True, if not then it's False
"""
logger.log(u"Checking if we should keep searching after we've found " + result.name, logger.DEBUG)
show_obj = result.episodes[0].show
any_qualities, best_qualities = Quality.splitQuality(show_obj.quality)
# if there is a redownload that's higher than this then we definitely need to keep looking
if best_qualities and result.quality < max(best_qualities):
return False
# if it does not match the shows black and white list its no good
elif show_obj.is_anime and show_obj.release_groups.is_valid(result):
return False
# if there's no redownload that's higher (above) and this is the highest initial download then we're good
elif any_qualities and result.quality in any_qualities:
return True
elif best_qualities and result.quality == max(best_qualities):
return True
# if we got here than it's either not on the lists, they're empty, or it's lower than the highest required
else:
return False
def isFirstBestMatch(result):
"""
Checks if the given result is a best quality match and if we want to archive the episode on first match.
"""
logger.log(u"Checking if we should archive our first best quality match for for episode " + result.name,
logger.DEBUG)
show_obj = result.episodes[0].show
any_qualities, best_qualities = Quality.splitQuality(show_obj.quality)
# if there is a redownload that's a match to one of our best qualities and we want to archive the episode then we are done
if best_qualities and show_obj.archive_firstmatch and result.quality in best_qualities:
return True
return False
def wantedEpisodes(show, fromDate):
anyQualities, bestQualities = common.Quality.splitQuality(show.quality) # @UnusedVariable
allQualities = list(set(anyQualities + bestQualities))
logger.log(u"Seeing if we need anything from " + show.name, logger.DEBUG)
myDB = db.DBConnection()
sqlResults = myDB.select("SELECT status, season, episode FROM tv_episodes WHERE showid = ? AND season > 0 and airdate > ?",
[show.indexerid, fromDate.toordinal()])
# check through the list of statuses to see if we want any
wanted = []
for result in sqlResults:
curCompositeStatus = int(result["status"] or -1)
curStatus, curQuality = common.Quality.splitCompositeStatus(curCompositeStatus)
if bestQualities:
highestBestQuality = max(allQualities)
else:
highestBestQuality = 0
# if we need a better one then say yes
if (curStatus in (common.DOWNLOADED, common.SNATCHED, common.SNATCHED_PROPER) and curQuality < highestBestQuality) or curStatus == common.WANTED:
epObj = show.getEpisode(int(result["season"]), int(result["episode"]))
epObj.wantedQuality = [i for i in allQualities if (i > curQuality and i != common.Quality.UNKNOWN)]
wanted.append(epObj)
return wanted
def searchForNeededEpisodes():
foundResults = {}
didSearch = False
origThreadName = threading.currentThread().name
threads = []
show_list = sickbeard.showList
fromDate = datetime.date.fromordinal(1)
episodes = []
for curShow in show_list:
if not curShow.paused:
episodes.extend(wantedEpisodes(curShow, fromDate))
providers = [x for x in sickbeard.providers.sortedProviderList(sickbeard.RANDOMIZE_PROVIDERS) if x.isActive() and x.enable_daily]
for curProvider in providers:
threads += [threading.Thread(target=curProvider.cache.updateCache, name=origThreadName + " :: [" + curProvider.name + "]")]
# start the thread we just created
for t in threads:
t.start()
# wait for all threads to finish
for t in threads:
t.join()
for curProvider in providers:
threading.currentThread().name = origThreadName + " :: [" + curProvider.name + "]"
curFoundResults = {}
try:
curFoundResults = curProvider.searchRSS(episodes)
except exceptions.AuthException, e:
logger.log(u"Authentication error: " + ex(e), logger.ERROR)
continue
except Exception, e:
logger.log(u"Error while searching " + curProvider.name + ", skipping: " + ex(e), logger.ERROR)
logger.log(traceback.format_exc(), logger.DEBUG)
continue
didSearch = True
# pick a single result for each episode, respecting existing results
for curEp in curFoundResults:
if not curEp.show or curEp.show.paused:
logger.log(u"Skipping %s because the show is paused " % curEp.prettyName(), logger.DEBUG)
continue
bestResult = pickBestResult(curFoundResults[curEp], curEp.show)
# if all results were rejected move on to the next episode
if not bestResult:
logger.log(u"All found results for " + curEp.prettyName() + " were rejected.", logger.DEBUG)
continue
# if it's already in the list (from another provider) and the newly found quality is no better then skip it
if curEp in foundResults and bestResult.quality <= foundResults[curEp].quality:
continue
foundResults[curEp] = bestResult
threading.currentThread().name = origThreadName
if not didSearch:
logger.log(
u"No NZB/Torrent providers found or enabled in the sickrage config for daily searches. Please check your settings.",
logger.WARNING)
return foundResults.values()
def searchProviders(show, episodes, manualSearch=False, downCurQuality=False):
foundResults = {}
finalResults = []
didSearch = False
threads = []
# build name cache for show
sickbeard.name_cache.buildNameCache(show)
origThreadName = threading.currentThread().name
providers = [x for x in sickbeard.providers.sortedProviderList(sickbeard.RANDOMIZE_PROVIDERS) if x.isActive() and x.enable_backlog]
for curProvider in providers:
threads += [threading.Thread(target=curProvider.cache.updateCache,
name=origThreadName + " :: [" + curProvider.name + "]")]
# start the thread we just created
for t in threads:
t.start()
# wait for all threads to finish
for t in threads:
t.join()
for providerNum, curProvider in enumerate(providers):
if curProvider.anime_only and not show.is_anime:
logger.log(u"" + str(show.name) + " is not an anime, skiping", logger.DEBUG)
continue
threading.currentThread().name = origThreadName + " :: [" + curProvider.name + "]"
foundResults[curProvider.name] = {}
searchCount = 0
search_mode = curProvider.search_mode
# Always search for episode when manually searching when in sponly
if search_mode == 'sponly' and manualSearch == True:
search_mode = 'eponly'
while(True):
searchCount += 1
if search_mode == 'eponly':
logger.log(u"Performing episode search for " + show.name)
else:
logger.log(u"Performing season pack search for " + show.name)
try:
searchResults = curProvider.findSearchResults(show, episodes, search_mode, manualSearch, downCurQuality)
except exceptions.AuthException, e:
logger.log(u"Authentication error: " + ex(e), logger.ERROR)
break
except Exception, e:
logger.log(u"Error while searching " + curProvider.name + ", skipping: " + ex(e), logger.ERROR)
logger.log(traceback.format_exc(), logger.DEBUG)
break
didSearch = True
if len(searchResults):
# make a list of all the results for this provider
for curEp in searchResults:
if curEp in foundResults:
foundResults[curProvider.name][curEp] += searchResults[curEp]
else:
foundResults[curProvider.name][curEp] = searchResults[curEp]
break
elif not curProvider.search_fallback or searchCount == 2:
break
if search_mode == 'sponly':
logger.log(u"Fallback episode search initiated", logger.DEBUG)
search_mode = 'eponly'
else:
logger.log(u"Fallback season pack search initiate", logger.DEBUG)
search_mode = 'sponly'
# skip to next provider if we have no results to process
if not len(foundResults[curProvider.name]):
continue
# pick the best season NZB
bestSeasonResult = None
if SEASON_RESULT in foundResults[curProvider.name]:
bestSeasonResult = pickBestResult(foundResults[curProvider.name][SEASON_RESULT], show)
highest_quality_overall = 0
for cur_episode in foundResults[curProvider.name]:
for cur_result in foundResults[curProvider.name][cur_episode]:
if cur_result.quality != Quality.UNKNOWN and cur_result.quality > highest_quality_overall:
highest_quality_overall = cur_result.quality
logger.log(u"The highest quality of any match is " + Quality.qualityStrings[highest_quality_overall],
logger.DEBUG)
# see if every episode is wanted
if bestSeasonResult:
searchedSeasons = [str(x.season) for x in episodes]
# get the quality of the season nzb
seasonQual = bestSeasonResult.quality
logger.log(
u"The quality of the season " + bestSeasonResult.provider.providerType + " is " + Quality.qualityStrings[
seasonQual], logger.DEBUG)
myDB = db.DBConnection()
allEps = [int(x["episode"])
for x in myDB.select("SELECT episode FROM tv_episodes WHERE showid = ? AND ( season IN ( " + ','.join(searchedSeasons) + " ) )",
[show.indexerid])]
logger.log(u"Executed query: [SELECT episode FROM tv_episodes WHERE showid = %s AND season in %s]" % (show.indexerid, ','.join(searchedSeasons)))
logger.log(u"Episode list: " + str(allEps), logger.DEBUG)
allWanted = True
anyWanted = False
for curEpNum in allEps:
for season in set([x.season for x in episodes]):
if not show.wantEpisode(season, curEpNum, seasonQual, downCurQuality):
allWanted = False
else:
anyWanted = True
# if we need every ep in the season and there's nothing better then just download this and be done with it (unless single episodes are preferred)
if allWanted and bestSeasonResult.quality == highest_quality_overall:
logger.log(
u"Every ep in this season is needed, downloading the whole " + bestSeasonResult.provider.providerType + " " + bestSeasonResult.name)
epObjs = []
for curEpNum in allEps:
for season in set([x.season for x in episodes]):
epObjs.append(show.getEpisode(season, curEpNum))
bestSeasonResult.episodes = epObjs
return [bestSeasonResult]
elif not anyWanted:
logger.log(
u"No eps from this season are wanted at this quality, ignoring the result of " + bestSeasonResult.name,
logger.DEBUG)
else:
if bestSeasonResult.provider.providerType == GenericProvider.NZB:
logger.log(u"Breaking apart the NZB and adding the individual ones to our results", logger.DEBUG)
# if not, break it apart and add them as the lowest priority results
individualResults = nzbSplitter.splitResult(bestSeasonResult)
for curResult in individualResults:
if len(curResult.episodes) == 1:
epNum = curResult.episodes[0].episode
elif len(curResult.episodes) > 1:
epNum = MULTI_EP_RESULT
if epNum in foundResults[curProvider.name]:
foundResults[curProvider.name][epNum].append(curResult)
else:
foundResults[curProvider.name][epNum] = [curResult]
# If this is a torrent all we can do is leech the entire torrent, user will have to select which eps not do download in his torrent client
else:
# Season result from Torrent Provider must be a full-season torrent, creating multi-ep result for it.
logger.log(
u"Adding multi-ep result for full-season torrent. Set the episodes you don't want to 'don't download' in your torrent client if desired!")
epObjs = []
for curEpNum in allEps:
for season in set([x.season for x in episodes]):
epObjs.append(show.getEpisode(season, curEpNum))
bestSeasonResult.episodes = epObjs
if MULTI_EP_RESULT in foundResults[curProvider.name]:
foundResults[curProvider.name][MULTI_EP_RESULT].append(bestSeasonResult)
else:
foundResults[curProvider.name][MULTI_EP_RESULT] = [bestSeasonResult]
# go through multi-ep results and see if we really want them or not, get rid of the rest
multiResults = {}
if MULTI_EP_RESULT in foundResults[curProvider.name]:
for _multiResult in foundResults[curProvider.name][MULTI_EP_RESULT]:
logger.log(u"Seeing if we want to bother with multi-episode result " + _multiResult.name, logger.DEBUG)
# Filter result by ignore/required/whitelist/blacklist/quality, etc
multiResult = pickBestResult(_multiResult, show)
if not multiResult:
continue
# see how many of the eps that this result covers aren't covered by single results
neededEps = []
notNeededEps = []
for epObj in multiResult.episodes:
# if we have results for the episode
if epObj.episode in foundResults[curProvider.name] and len(foundResults[curProvider.name][epObj.episode]) > 0:
notNeededEps.append(epObj.episode)
else:
neededEps.append(epObj.episode)
logger.log(
u"Single-ep check result is neededEps: " + str(neededEps) + ", notNeededEps: " + str(notNeededEps),
logger.DEBUG)
if not neededEps:
logger.log(u"All of these episodes were covered by single episode results, ignoring this multi-episode result", logger.DEBUG)
continue
# check if these eps are already covered by another multi-result
multiNeededEps = []
multiNotNeededEps = []
for epObj in multiResult.episodes:
if epObj.episode in multiResults:
multiNotNeededEps.append(epObj.episode)
else:
multiNeededEps.append(epObj.episode)
logger.log(
u"Multi-ep check result is multiNeededEps: " + str(multiNeededEps) + ", multiNotNeededEps: " + str(
multiNotNeededEps), logger.DEBUG)
if not multiNeededEps:
logger.log(
u"All of these episodes were covered by another multi-episode nzbs, ignoring this multi-ep result",
logger.DEBUG)
continue
# don't bother with the single result if we're going to get it with a multi result
for epObj in multiResult.episodes:
multiResults[epObj.episode] = multiResult
if epObj.episode in foundResults[curProvider.name]:
logger.log(
u"A needed multi-episode result overlaps with a single-episode result for ep #" + str(
epObj.episode) + ", removing the single-episode results from the list", logger.DEBUG)
del foundResults[curProvider.name][epObj.episode]
# of all the single ep results narrow it down to the best one for each episode
finalResults += set(multiResults.values())
for curEp in foundResults[curProvider.name]:
if curEp in (MULTI_EP_RESULT, SEASON_RESULT):
continue
if not len(foundResults[curProvider.name][curEp]) > 0:
continue
# if all results were rejected move on to the next episode
bestResult = pickBestResult(foundResults[curProvider.name][curEp], show)
if not bestResult:
continue
# add result if its not a duplicate and
found = False
for i, result in enumerate(finalResults):
for bestResultEp in bestResult.episodes:
if bestResultEp in result.episodes:
if result.quality < bestResult.quality:
finalResults.pop(i)
else:
found = True
if not found:
finalResults += [bestResult]
# check that we got all the episodes we wanted first before doing a match and snatch
wantedEpCount = 0
for wantedEp in episodes:
for result in finalResults:
if wantedEp in result.episodes and isFinalResult(result):
wantedEpCount += 1
# make sure we search every provider for results unless we found everything we wanted
if wantedEpCount == len(episodes):
break
if not didSearch:
logger.log(u"No NZB/Torrent providers found or enabled in the sickrage config for backlog searches. Please check your settings.",
logger.WARNING)
return finalResults
| dannyboi104/SickRage | sickbeard/search.py | Python | gpl-3.0 | 28,682 |
/* This file is part of Plaine.
*
* Plaine 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.
*
* Plaine 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 Plaine. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MATH_H
#define MATH_H
#include <irrlicht.h>
#include <btBulletDynamicsCommon.h>
using namespace irr;
template<typename T>
constexpr T PI = T(3.1415926535897932385);
// shit making it possible to compile with TDM-GCC under Windows
template<>
constexpr float PI<float> = 3.1415926535897932385;
core::vector3df quatToEulerRad(const btQuaternion &quat);
core::vector3df quatToEulerDeg(const btQuaternion &quat);
template <typename Number>
int sign(Number num)
{
if (num < 0)
return -1;
else if (num > 0)
return 1;
else
return 0;
}
#endif // MATH_H
| Kotolegokot/PlaneRunner | include/util/math.h | C | gpl-3.0 | 1,262 |
/* ----------------------------------------------------------------------------------------
Vodigi - Open Source Interactive Digital Signage
Copyright (C) 2005-2013 JMC Publications, LLC
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/>.
---------------------------------------------------------------------------------------- */
using System;
namespace osVodigiWeb6x.Models
{
public interface IActivityLogRepository
{
void CreateActivityLog(ActivityLog activitylog);
DateTime GetLastPlayerHeartbeat(int playerid);
int SaveChanges();
}
} | kholodovitch/vodigi | SourceCode/osVodigiWeb/osVodigiWeb6x/Models/Interfaces/IActivityLogRepository.cs | C# | gpl-3.0 | 1,189 |
<?php
class com_wiris_quizzes_api_ui_QuizzesUIConstants {
public function __construct(){}
static $TEXT_FIELD;
static $INLINE_EDITOR;
static $POPUP_EDITOR;
static $STUDIO = "studio";
static $INLINE_STUDIO = "inlineStudio";
static $EMBEDDED_ANSWERS_EDITOR = "embeddedAnswersEditor";
static $AUTHORING = "authoring";
static $DELIVERY = "delivery";
static $REVIEW = "review";
function __toString() { return 'com.wiris.quizzes.api.ui.QuizzesUIConstants'; }
}
com_wiris_quizzes_api_ui_QuizzesUIConstants::$TEXT_FIELD = com_wiris_quizzes_api_QuizzesConstants::$ANSWER_FIELD_TYPE_TEXT;
com_wiris_quizzes_api_ui_QuizzesUIConstants::$INLINE_EDITOR = com_wiris_quizzes_api_QuizzesConstants::$ANSWER_FIELD_TYPE_INLINE_EDITOR;
com_wiris_quizzes_api_ui_QuizzesUIConstants::$POPUP_EDITOR = com_wiris_quizzes_api_QuizzesConstants::$ANSWER_FIELD_TYPE_POPUP_EDITOR;
| nitro2010/moodle | question/type/wq/quizzes/lib/com/wiris/quizzes/api/ui/QuizzesUIConstants.class.php | PHP | gpl-3.0 | 860 |
/*
* Copyright (C) 2010 {Apertum}Projects. web: www.apertum.ru email: info@apertum.ru
*
* 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/>.
*/
package ru.apertum.qsystem.server.model.calendar;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedList;
import java.util.List;
import javax.swing.table.AbstractTableModel;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Property;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import ru.apertum.qsystem.common.QLog;
import ru.apertum.qsystem.common.exceptions.ClientException;
import ru.apertum.qsystem.server.Spring;
/**
* Модель для отображения сетки календаля
*
* @author Evgeniy Egorov
*/
public class CalendarTableModel extends AbstractTableModel {
private final List<FreeDay> days;
/**
* В каком календаре сейчас работаем
*/
final private long calcId;
private List<FreeDay> days_del;
public CalendarTableModel(long calcId) {
QLog.l().logger().debug("Create a model for the calendar");
this.calcId = calcId;
days = getFreeDays(calcId);
days_del = new ArrayList<>(days);
}
/**
* Выборка из БД требуемых данных.
*
* @param calcId id календаря
* @return список выходных дней определенного календаря
*/
public synchronized static LinkedList<FreeDay> getFreeDays(final Long calcId) {
final DetachedCriteria criteria = DetachedCriteria.forClass(FreeDay.class);
criteria.add(Property.forName("calendarId").eq(calcId));
return new LinkedList<>(Spring.getInstance().getHt().findByCriteria(criteria));
}
/**
* Добавляем дату. Если Такая уже есть то инвертируем
*
* @param noInvert true - при обнаружении выходного оставлять его выходным
* @return Добавлена как свободная или как рабочая/ true = свободная
*/
public boolean addDay(Date date, boolean noInvert) {
final FreeDay day = isFreeDate(date);
if (day != null) {
if (noInvert) {
return true;
} else {
days.remove(day);
}
return false;
} else {
days.add(new FreeDay(date, calcId));
return true;
}
}
/**
* Проверяем добавлена ли в выходные уже
*/
public FreeDay isFreeDate(Date date) {
for (FreeDay day : days) {
if (day.equals(date)) {
return day;
}
}
return null;
}
@Override
public int getRowCount() {
return 12;
}
@Override
public int getColumnCount() {
return 32;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return "X";
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return columnIndex == 0 ? super.getColumnClass(columnIndex) : FreeDay.class;
}
@Override
public String getColumnName(int column) {
return column == 0 ? "" : Integer.toString(column);
}
/**
* Сбросить выделенные дни в календаре
*/
public void dropCalendar(int year) {
QLog.l().logger().debug("Reset the calendar");
final ArrayList<FreeDay> del = new ArrayList<>();
final GregorianCalendar gc = new GregorianCalendar();
for (FreeDay freeDay : days) {
gc.setTime(freeDay.getDate());
if (gc.get(GregorianCalendar.YEAR) == year) {
del.add(freeDay);
}
}
days.removeAll(del);
fireTableDataChanged();
}
/**
* Пометить все субботы выходными
*/
public void checkSaturday(int year) {
QLog.l().logger().debug("Mark all Saturdays");
final GregorianCalendar gc = new GregorianCalendar();
gc.set(GregorianCalendar.YEAR, year);
final int ye = year % 4 == 0 ? 366 : 365;
for (int d = 1; d <= ye; d++) {
gc.set(GregorianCalendar.DAY_OF_YEAR, d);
if (gc.get(GregorianCalendar.DAY_OF_WEEK) == 7) {
addDay(gc.getTime(), true);
}
}
fireTableDataChanged();
}
/**
* Пометить все воскресенья выходными
*/
public void checkSunday(int year) {
QLog.l().logger().debug("Mark all Sundays");
final GregorianCalendar gc = new GregorianCalendar();
gc.set(GregorianCalendar.YEAR, year);
final int ye = year % 4 == 0 ? 366 : 365;
for (int d = 1; d <= ye; d++) {
gc.set(GregorianCalendar.DAY_OF_YEAR, d);
if (gc.get(GregorianCalendar.DAY_OF_WEEK) == 1) {
addDay(gc.getTime(), true);
}
}
fireTableDataChanged();
}
/**
* Сохранить календарь.
*/
public void save() {
QLog.l().logger().info("Save the calendar ID = " + calcId);
final DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setName("SomeTxName");
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
TransactionStatus status = Spring.getInstance().getTxManager().getTransaction(def);
try {
final LinkedList<FreeDay> dels = new LinkedList<>();
for (FreeDay bad : days_del) {
boolean f = true;
for (FreeDay good : days) {
if (good.equals(bad)) {
f = false;
}
}
if (f) {
dels.add(bad);
}
}
Spring.getInstance().getHt().deleteAll(dels);
Spring.getInstance().getHt().saveOrUpdateAll(days);
} catch (Exception ex) {
Spring.getInstance().getTxManager().rollback(status);
throw new ClientException(
"Error performing the operation of modifying data in the database (JDBC).\nPerhaps you added a new calendar, changed it, tried to save the contents of the calendar, but did not save the overall configuration.\nSave the entire configuration (Ctrl + S) and try again to save the contents of the calendar.\n\n["
+ ex.getLocalizedMessage() + "]\n(" + ex.toString() + ")");
}
Spring.getInstance().getTxManager().commit(status);
QLog.l().logger().debug("Saved a new calendar");
//Type so that there are actual internal data
days_del = new ArrayList<>(days);
}
/**
* Checking for the preservation of the calendar
*/
public boolean isSaved() {
for (FreeDay day : days) {
if (day.getId() == null) {
return false;
}
}
if (days_del.size() != days.size()) {
return false;
}
return true;
}
}
| mark-walle/sbc-qsystem | QSystem/src/ru/apertum/qsystem/server/model/calendar/CalendarTableModel.java | Java | gpl-3.0 | 8,009 |
/*
* Copyright (C) 2005-2012 MaNGOS <http://www.getmangos.com/>
* Copyright (C) 2008-2012 Trinity <http://www.trinitycore.org/>
* Copyright (C) 2010-2012 Project SkyFire <http://www.projectskyfire.org/>
* Copyright (C) 2011-2012 Darkpeninsula Project <http://www.darkpeninsula.eu/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef DARKCORE_DISABLEMGR_H
#define DARKCORE_DISABLEMGR_H
#include <ace/Singleton.h>
class Unit;
enum DisableType
{
DISABLE_TYPE_SPELL = 0,
DISABLE_TYPE_QUEST = 1,
DISABLE_TYPE_MAP = 2,
DISABLE_TYPE_BATTLEGROUND = 3,
DISABLE_TYPE_ACHIEVEMENT_CRITERIA = 4,
DISABLE_TYPE_OUTDOORPVP = 5,
};
enum SpellDisableTypes
{
SPELL_DISABLE_PLAYER = 0x1,
SPELL_DISABLE_CREATURE = 0x2,
SPELL_DISABLE_PET = 0x4,
SPELL_DISABLE_DEPRECATED_SPELL = 0x8,
SPELL_DISABLE_MAP = 0x10,
SPELL_DISABLE_AREA = 0x20,
MAX_SPELL_DISABLE_TYPE = ( SPELL_DISABLE_PLAYER | SPELL_DISABLE_CREATURE | SPELL_DISABLE_PET |
SPELL_DISABLE_DEPRECATED_SPELL | SPELL_DISABLE_MAP | SPELL_DISABLE_AREA),
};
#define MAX_DISABLE_TYPES 6
struct DisableData
{
uint8 flags;
std::set<uint32> params[2]; // params0, params1
};
typedef std::map<uint32, DisableData> DisableTypeMap; // single disables here with optional data
typedef std::map<DisableType, DisableTypeMap> DisableMap; // global disable map by source
class DisableMgr
{
friend class ACE_Singleton<DisableMgr, ACE_Null_Mutex>;
DisableMgr();
~DisableMgr();
public:
void LoadDisables();
bool IsDisabledFor(DisableType type, uint32 entry, Unit const* pUnit);
void CheckQuestDisables();
protected:
DisableMap m_DisableMap;
};
#define sDisableMgr ACE_Singleton<DisableMgr, ACE_Null_Mutex>::instance()
#endif //DARKCORE_DISABLEMGR_H | Drethek/Darkpeninsula-Cata-Old | src/server/game/Conditions/DisableMgr.h | C | gpl-3.0 | 2,672 |
<!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"/>
<title>ublas: boost::numeric::ublas::c_matrix< T, N, M > Class Template Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<!-- Generated by Doxygen 1.6.1 -->
<div class="navigation" id="top">
<div class="tabs">
<ul>
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div class="tabs">
<ul>
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<div class="navpath"><b>boost</b>::<b>numeric</b>::<b>ublas</b>::<a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix.html">c_matrix</a>
</div>
</div>
<div class="contents">
<h1>boost::numeric::ublas::c_matrix< T, N, M > Class Template Reference</h1><!-- doxytag: class="boost::numeric::ublas::c_matrix" --><!-- doxytag: inherits="matrix_container< c_matrix< T, N, M > >" -->
<p>An array based <a class="el" href="classboost_1_1numeric_1_1ublas_1_1matrix.html" title="A dense matrix of values of type T.">matrix</a> class which size is defined at type specification or object instanciation.
<a href="#_details">More...</a></p>
<p>Inherits <a class="el" href="classboost_1_1numeric_1_1ublas_1_1matrix__container.html">matrix_container< c_matrix< T, N, M > ></a>.</p>
<p><a href="classboost_1_1numeric_1_1ublas_1_1c__matrix-members.html">List of all members.</a></p>
<table border="0" cellpadding="0" cellspacing="0">
<tr><td colspan="2"><h2>Classes</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">class </td><td class="memItemRight" valign="bottom"><a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix_1_1const__iterator1.html">const_iterator1</a></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">class </td><td class="memItemRight" valign="bottom"><a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix_1_1const__iterator2.html">const_iterator2</a></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">class </td><td class="memItemRight" valign="bottom"><a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix_1_1iterator1.html">iterator1</a></td></tr>
<tr><td class="memItemLeft" align="right" valign="top">class </td><td class="memItemRight" valign="bottom"><a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix_1_1iterator2.html">iterator2</a></td></tr>
<tr><td colspan="2"><h2>Public Types</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a0cbab1b891729a10eeed145da660e368"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::size_type" ref="a0cbab1b891729a10eeed145da660e368" args="" -->
typedef std::size_t </td><td class="memItemRight" valign="bottom"><b>size_type</b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a2821918c63ff1e0130d5cdf05152deb6"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::difference_type" ref="a2821918c63ff1e0130d5cdf05152deb6" args="" -->
typedef std::ptrdiff_t </td><td class="memItemRight" valign="bottom"><b>difference_type</b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aca7ff3158e5c9a67508e566211330f07"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::value_type" ref="aca7ff3158e5c9a67508e566211330f07" args="" -->
typedef T </td><td class="memItemRight" valign="bottom"><b>value_type</b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="adb0fa9175d4c6a3bad76adbb2633bfa8"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::const_reference" ref="adb0fa9175d4c6a3bad76adbb2633bfa8" args="" -->
typedef const T & </td><td class="memItemRight" valign="bottom"><b>const_reference</b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="abbf56a14341b9a2bd99e2db52cdf7cdc"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::reference" ref="abbf56a14341b9a2bd99e2db52cdf7cdc" args="" -->
typedef T & </td><td class="memItemRight" valign="bottom"><b>reference</b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a4e7b96399c643ec55dbdb6ee0eaadc78"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::const_pointer" ref="a4e7b96399c643ec55dbdb6ee0eaadc78" args="" -->
typedef const T * </td><td class="memItemRight" valign="bottom"><b>const_pointer</b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a76b62eaa2334a69532f9bffa8c8015ae"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::pointer" ref="a76b62eaa2334a69532f9bffa8c8015ae" args="" -->
typedef T * </td><td class="memItemRight" valign="bottom"><b>pointer</b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a52e14b3cbc280e2f38e61bd907ea1ead"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::const_closure_type" ref="a52e14b3cbc280e2f38e61bd907ea1ead" args="" -->
typedef const <a class="el" href="classboost_1_1numeric_1_1ublas_1_1matrix__reference.html">matrix_reference</a><br class="typebreak"/>
< const <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix.html">self_type</a> > </td><td class="memItemRight" valign="bottom"><b>const_closure_type</b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ac18b1a7bc35878dfd1bb64a1bf5a5e50"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::closure_type" ref="ac18b1a7bc35878dfd1bb64a1bf5a5e50" args="" -->
typedef <a class="el" href="classboost_1_1numeric_1_1ublas_1_1matrix__reference.html">matrix_reference</a><br class="typebreak"/>
< <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix.html">self_type</a> > </td><td class="memItemRight" valign="bottom"><b>closure_type</b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a4c71419d3203096ece9c776aa2faaad9"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::vector_temporary_type" ref="a4c71419d3203096ece9c776aa2faaad9" args="" -->
typedef <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__vector.html">c_vector</a>< T, N *M > </td><td class="memItemRight" valign="bottom"><b>vector_temporary_type</b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a4559ded28167378c4ac144ba9242b2a4"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::matrix_temporary_type" ref="a4559ded28167378c4ac144ba9242b2a4" args="" -->
typedef <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix.html">self_type</a> </td><td class="memItemRight" valign="bottom"><b>matrix_temporary_type</b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a0564e1ebd31a97475d30e8bcd1ca972a"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::storage_category" ref="a0564e1ebd31a97475d30e8bcd1ca972a" args="" -->
typedef <a class="el" href="structboost_1_1numeric_1_1ublas_1_1dense__tag.html">dense_tag</a> </td><td class="memItemRight" valign="bottom"><b>storage_category</b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a62705670e91fbf92e1823352a0be9683"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::orientation_category" ref="a62705670e91fbf92e1823352a0be9683" args="" -->
typedef <a class="el" href="structboost_1_1numeric_1_1ublas_1_1row__major__tag.html">row_major_tag</a> </td><td class="memItemRight" valign="bottom"><b>orientation_category</b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a5f0967467103eaef04ff4a2d970fd3f5"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::const_reverse_iterator1" ref="a5f0967467103eaef04ff4a2d970fd3f5" args="" -->
typedef reverse_iterator_base1<br class="typebreak"/>
< <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix_1_1const__iterator1.html">const_iterator1</a> > </td><td class="memItemRight" valign="bottom"><b>const_reverse_iterator1</b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a29d39049d96289df72360fdd9c8bedb7"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::reverse_iterator1" ref="a29d39049d96289df72360fdd9c8bedb7" args="" -->
typedef reverse_iterator_base1<br class="typebreak"/>
< <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix_1_1iterator1.html">iterator1</a> > </td><td class="memItemRight" valign="bottom"><b>reverse_iterator1</b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aab92c6fee5aab840541326908ba54440"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::const_reverse_iterator2" ref="aab92c6fee5aab840541326908ba54440" args="" -->
typedef reverse_iterator_base2<br class="typebreak"/>
< <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix_1_1const__iterator2.html">const_iterator2</a> > </td><td class="memItemRight" valign="bottom"><b>const_reverse_iterator2</b></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="afdaebf178493e5a31745bbd62fed58de"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::reverse_iterator2" ref="afdaebf178493e5a31745bbd62fed58de" args="" -->
typedef reverse_iterator_base2<br class="typebreak"/>
< <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix_1_1iterator2.html">iterator2</a> > </td><td class="memItemRight" valign="bottom"><b>reverse_iterator2</b></td></tr>
<tr><td colspan="2"><h2>Public Member Functions</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ab0e517c229821da311bedbe6e7d5f774"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::c_matrix" ref="ab0e517c229821da311bedbe6e7d5f774" args="(size_type size1, size_type size2)" -->
BOOST_UBLAS_INLINE </td><td class="memItemRight" valign="bottom"><b>c_matrix</b> (size_type size1, size_type size2)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aedf83144b8435209b97a584b9db99d5e"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::c_matrix" ref="aedf83144b8435209b97a584b9db99d5e" args="(const c_matrix &m)" -->
BOOST_UBLAS_INLINE </td><td class="memItemRight" valign="bottom"><b>c_matrix</b> (const <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix.html">c_matrix</a> &m)</td></tr>
<tr><td class="memTemplParams" colspan="2"><a class="anchor" id="a8a0fbf49da967e52a97b3e19aedfb25e"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::c_matrix" ref="a8a0fbf49da967e52a97b3e19aedfb25e" args="(const matrix_expression< AE > &ae)" -->
template<class AE > </td></tr>
<tr><td class="memTemplItemLeft" align="right" valign="top">BOOST_UBLAS_INLINE </td><td class="memTemplItemRight" valign="bottom"><b>c_matrix</b> (const <a class="el" href="classboost_1_1numeric_1_1ublas_1_1matrix__expression.html">matrix_expression</a>< AE > &ae)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a66f570eb86bfd7e090d45eeca90f2142"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::size1" ref="a66f570eb86bfd7e090d45eeca90f2142" args="() const " -->
BOOST_UBLAS_INLINE size_type </td><td class="memItemRight" valign="bottom"><b>size1</b> () const </td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a0598e640f769a4fa15b908444bbaeebd"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::size2" ref="a0598e640f769a4fa15b908444bbaeebd" args="() const " -->
BOOST_UBLAS_INLINE size_type </td><td class="memItemRight" valign="bottom"><b>size2</b> () const </td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a96760d02b59ee2d966614ce3b0377839"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::data" ref="a96760d02b59ee2d966614ce3b0377839" args="() const " -->
BOOST_UBLAS_INLINE const_pointer </td><td class="memItemRight" valign="bottom"><b>data</b> () const </td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ad157582153b9e7e51c3792feeb01f932"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::data" ref="ad157582153b9e7e51c3792feeb01f932" args="()" -->
BOOST_UBLAS_INLINE pointer </td><td class="memItemRight" valign="bottom"><b>data</b> ()</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a31a3fc016cb2c1cb467d5ceec3213d55"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::resize" ref="a31a3fc016cb2c1cb467d5ceec3213d55" args="(size_type size1, size_type size2, bool preserve=true)" -->
BOOST_UBLAS_INLINE void </td><td class="memItemRight" valign="bottom"><b>resize</b> (size_type size1, size_type size2, bool preserve=true)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="acd5f6d80a5db78b5b4a2d7b041187873"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::operator()" ref="acd5f6d80a5db78b5b4a2d7b041187873" args="(size_type i, size_type j) const " -->
BOOST_UBLAS_INLINE const_reference </td><td class="memItemRight" valign="bottom"><b>operator()</b> (size_type i, size_type j) const </td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a9c70957c80ccebb0130a6d6aac45a4a7"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::at_element" ref="a9c70957c80ccebb0130a6d6aac45a4a7" args="(size_type i, size_type j)" -->
BOOST_UBLAS_INLINE reference </td><td class="memItemRight" valign="bottom"><b>at_element</b> (size_type i, size_type j)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ab4b4bd9ce4bf2acd03d8dbe843b05365"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::operator()" ref="ab4b4bd9ce4bf2acd03d8dbe843b05365" args="(size_type i, size_type j)" -->
BOOST_UBLAS_INLINE reference </td><td class="memItemRight" valign="bottom"><b>operator()</b> (size_type i, size_type j)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aed5e44a920cc56b6ac55a6dfbb76b9be"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::insert_element" ref="aed5e44a920cc56b6ac55a6dfbb76b9be" args="(size_type i, size_type j, const_reference t)" -->
BOOST_UBLAS_INLINE reference </td><td class="memItemRight" valign="bottom"><b>insert_element</b> (size_type i, size_type j, const_reference t)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ae1ff6634803d76fb6c9856ee6abbe98b"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::clear" ref="ae1ff6634803d76fb6c9856ee6abbe98b" args="()" -->
BOOST_UBLAS_INLINE void </td><td class="memItemRight" valign="bottom"><b>clear</b> ()</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a144d0c2c55f6347dcddd7e2250952abb"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::operator=" ref="a144d0c2c55f6347dcddd7e2250952abb" args="(const c_matrix &m)" -->
BOOST_UBLAS_INLINE <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix.html">c_matrix</a> & </td><td class="memItemRight" valign="bottom"><b>operator=</b> (const <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix.html">c_matrix</a> &m)</td></tr>
<tr><td class="memTemplParams" colspan="2"><a class="anchor" id="a7ccdbf7b4f9f28f16c6d6d15304ae8a4"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::operator=" ref="a7ccdbf7b4f9f28f16c6d6d15304ae8a4" args="(const matrix_container< C > &m)" -->
template<class C > </td></tr>
<tr><td class="memTemplItemLeft" align="right" valign="top">BOOST_UBLAS_INLINE <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix.html">c_matrix</a> & </td><td class="memTemplItemRight" valign="bottom"><b>operator=</b> (const <a class="el" href="classboost_1_1numeric_1_1ublas_1_1matrix__container.html">matrix_container</a>< C > &m)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="aa299bf72a4ce04ef301d80d6adb68616"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::assign_temporary" ref="aa299bf72a4ce04ef301d80d6adb68616" args="(c_matrix &m)" -->
BOOST_UBLAS_INLINE <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix.html">c_matrix</a> & </td><td class="memItemRight" valign="bottom"><b>assign_temporary</b> (<a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix.html">c_matrix</a> &m)</td></tr>
<tr><td class="memTemplParams" colspan="2"><a class="anchor" id="ae16097f8e082b83cf1100ce3ca827562"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::operator=" ref="ae16097f8e082b83cf1100ce3ca827562" args="(const matrix_expression< AE > &ae)" -->
template<class AE > </td></tr>
<tr><td class="memTemplItemLeft" align="right" valign="top">BOOST_UBLAS_INLINE <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix.html">c_matrix</a> & </td><td class="memTemplItemRight" valign="bottom"><b>operator=</b> (const <a class="el" href="classboost_1_1numeric_1_1ublas_1_1matrix__expression.html">matrix_expression</a>< AE > &ae)</td></tr>
<tr><td class="memTemplParams" colspan="2"><a class="anchor" id="a73ce2b046a8bc2a8c703f5454fc4d11e"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::assign" ref="a73ce2b046a8bc2a8c703f5454fc4d11e" args="(const matrix_expression< AE > &ae)" -->
template<class AE > </td></tr>
<tr><td class="memTemplItemLeft" align="right" valign="top">BOOST_UBLAS_INLINE <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix.html">c_matrix</a> & </td><td class="memTemplItemRight" valign="bottom"><b>assign</b> (const <a class="el" href="classboost_1_1numeric_1_1ublas_1_1matrix__expression.html">matrix_expression</a>< AE > &ae)</td></tr>
<tr><td class="memTemplParams" colspan="2"><a class="anchor" id="a96d99f19a57beb435b6c458d885e3ae3"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::operator+=" ref="a96d99f19a57beb435b6c458d885e3ae3" args="(const matrix_expression< AE > &ae)" -->
template<class AE > </td></tr>
<tr><td class="memTemplItemLeft" align="right" valign="top">BOOST_UBLAS_INLINE <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix.html">c_matrix</a> & </td><td class="memTemplItemRight" valign="bottom"><b>operator+=</b> (const <a class="el" href="classboost_1_1numeric_1_1ublas_1_1matrix__expression.html">matrix_expression</a>< AE > &ae)</td></tr>
<tr><td class="memTemplParams" colspan="2"><a class="anchor" id="a50818eb59bbc9c7d4c9a79b958321618"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::operator+=" ref="a50818eb59bbc9c7d4c9a79b958321618" args="(const matrix_container< C > &m)" -->
template<class C > </td></tr>
<tr><td class="memTemplItemLeft" align="right" valign="top">BOOST_UBLAS_INLINE <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix.html">c_matrix</a> & </td><td class="memTemplItemRight" valign="bottom"><b>operator+=</b> (const <a class="el" href="classboost_1_1numeric_1_1ublas_1_1matrix__container.html">matrix_container</a>< C > &m)</td></tr>
<tr><td class="memTemplParams" colspan="2"><a class="anchor" id="a385d39864182fb8a61a5c9c7c15568a8"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::plus_assign" ref="a385d39864182fb8a61a5c9c7c15568a8" args="(const matrix_expression< AE > &ae)" -->
template<class AE > </td></tr>
<tr><td class="memTemplItemLeft" align="right" valign="top">BOOST_UBLAS_INLINE <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix.html">c_matrix</a> & </td><td class="memTemplItemRight" valign="bottom"><b>plus_assign</b> (const <a class="el" href="classboost_1_1numeric_1_1ublas_1_1matrix__expression.html">matrix_expression</a>< AE > &ae)</td></tr>
<tr><td class="memTemplParams" colspan="2"><a class="anchor" id="a14ac8dba3b8989558e2036c6d32c0f35"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::operator-=" ref="a14ac8dba3b8989558e2036c6d32c0f35" args="(const matrix_expression< AE > &ae)" -->
template<class AE > </td></tr>
<tr><td class="memTemplItemLeft" align="right" valign="top">BOOST_UBLAS_INLINE <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix.html">c_matrix</a> & </td><td class="memTemplItemRight" valign="bottom"><b>operator-=</b> (const <a class="el" href="classboost_1_1numeric_1_1ublas_1_1matrix__expression.html">matrix_expression</a>< AE > &ae)</td></tr>
<tr><td class="memTemplParams" colspan="2"><a class="anchor" id="a875652b33b1cb1df4bd59a1a218354d2"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::operator-=" ref="a875652b33b1cb1df4bd59a1a218354d2" args="(const matrix_container< C > &m)" -->
template<class C > </td></tr>
<tr><td class="memTemplItemLeft" align="right" valign="top">BOOST_UBLAS_INLINE <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix.html">c_matrix</a> & </td><td class="memTemplItemRight" valign="bottom"><b>operator-=</b> (const <a class="el" href="classboost_1_1numeric_1_1ublas_1_1matrix__container.html">matrix_container</a>< C > &m)</td></tr>
<tr><td class="memTemplParams" colspan="2"><a class="anchor" id="a05417581be929cc278b1024fea629dfd"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::minus_assign" ref="a05417581be929cc278b1024fea629dfd" args="(const matrix_expression< AE > &ae)" -->
template<class AE > </td></tr>
<tr><td class="memTemplItemLeft" align="right" valign="top">BOOST_UBLAS_INLINE <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix.html">c_matrix</a> & </td><td class="memTemplItemRight" valign="bottom"><b>minus_assign</b> (const <a class="el" href="classboost_1_1numeric_1_1ublas_1_1matrix__expression.html">matrix_expression</a>< AE > &ae)</td></tr>
<tr><td class="memTemplParams" colspan="2"><a class="anchor" id="a6d4cd6aab5ffe461961095a53c6aadf4"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::operator*=" ref="a6d4cd6aab5ffe461961095a53c6aadf4" args="(const AT &at)" -->
template<class AT > </td></tr>
<tr><td class="memTemplItemLeft" align="right" valign="top">BOOST_UBLAS_INLINE <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix.html">c_matrix</a> & </td><td class="memTemplItemRight" valign="bottom"><b>operator*=</b> (const AT &at)</td></tr>
<tr><td class="memTemplParams" colspan="2"><a class="anchor" id="ae1ee7728464157e574c3c7431b9ae9c3"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::operator/=" ref="ae1ee7728464157e574c3c7431b9ae9c3" args="(const AT &at)" -->
template<class AT > </td></tr>
<tr><td class="memTemplItemLeft" align="right" valign="top">BOOST_UBLAS_INLINE <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix.html">c_matrix</a> & </td><td class="memTemplItemRight" valign="bottom"><b>operator/=</b> (const AT &at)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a27b19c7b15308cc02d9c638f4375efa9"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::swap" ref="a27b19c7b15308cc02d9c638f4375efa9" args="(c_matrix &m)" -->
BOOST_UBLAS_INLINE void </td><td class="memItemRight" valign="bottom"><b>swap</b> (<a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix.html">c_matrix</a> &m)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a69391c10981d16d652ff240efe3bc287"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::find1" ref="a69391c10981d16d652ff240efe3bc287" args="(int rank, size_type i, size_type j) const " -->
BOOST_UBLAS_INLINE <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix_1_1const__iterator1.html">const_iterator1</a> </td><td class="memItemRight" valign="bottom"><b>find1</b> (int rank, size_type i, size_type j) const </td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="afa4b97d3b8ceaf6611093e9fc09f4ff0"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::find1" ref="afa4b97d3b8ceaf6611093e9fc09f4ff0" args="(int rank, size_type i, size_type j)" -->
BOOST_UBLAS_INLINE <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix_1_1iterator1.html">iterator1</a> </td><td class="memItemRight" valign="bottom"><b>find1</b> (int rank, size_type i, size_type j)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a4cb0ce358e4bc8b31e1b3e4e7b0f1b47"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::find2" ref="a4cb0ce358e4bc8b31e1b3e4e7b0f1b47" args="(int rank, size_type i, size_type j) const " -->
BOOST_UBLAS_INLINE <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix_1_1const__iterator2.html">const_iterator2</a> </td><td class="memItemRight" valign="bottom"><b>find2</b> (int rank, size_type i, size_type j) const </td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ae79af5d15fa7e7a19ca77bdbc21a7fcc"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::find2" ref="ae79af5d15fa7e7a19ca77bdbc21a7fcc" args="(int rank, size_type i, size_type j)" -->
BOOST_UBLAS_INLINE <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix_1_1iterator2.html">iterator2</a> </td><td class="memItemRight" valign="bottom"><b>find2</b> (int rank, size_type i, size_type j)</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a5cafcadd7ba75a08a99d58f948b65148"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::begin1" ref="a5cafcadd7ba75a08a99d58f948b65148" args="() const " -->
BOOST_UBLAS_INLINE <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix_1_1const__iterator1.html">const_iterator1</a> </td><td class="memItemRight" valign="bottom"><b>begin1</b> () const </td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a1f1610d1998f617d84eb9440d3152f0c"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::end1" ref="a1f1610d1998f617d84eb9440d3152f0c" args="() const " -->
BOOST_UBLAS_INLINE <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix_1_1const__iterator1.html">const_iterator1</a> </td><td class="memItemRight" valign="bottom"><b>end1</b> () const </td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a8a65eb186367a7cf456ed75f3663f6bd"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::begin1" ref="a8a65eb186367a7cf456ed75f3663f6bd" args="()" -->
BOOST_UBLAS_INLINE <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix_1_1iterator1.html">iterator1</a> </td><td class="memItemRight" valign="bottom"><b>begin1</b> ()</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a8092edf9bbed9d9a6ae634148b19a9cf"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::end1" ref="a8092edf9bbed9d9a6ae634148b19a9cf" args="()" -->
BOOST_UBLAS_INLINE <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix_1_1iterator1.html">iterator1</a> </td><td class="memItemRight" valign="bottom"><b>end1</b> ()</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a0fd391a6246302b0185628e76ca1301f"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::begin2" ref="a0fd391a6246302b0185628e76ca1301f" args="() const " -->
BOOST_UBLAS_INLINE <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix_1_1const__iterator2.html">const_iterator2</a> </td><td class="memItemRight" valign="bottom"><b>begin2</b> () const </td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a06cb00d556aa303a354025c120e0a58e"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::end2" ref="a06cb00d556aa303a354025c120e0a58e" args="() const " -->
BOOST_UBLAS_INLINE <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix_1_1const__iterator2.html">const_iterator2</a> </td><td class="memItemRight" valign="bottom"><b>end2</b> () const </td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a407611fd63b3cf7802f7b1e965658c9e"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::begin2" ref="a407611fd63b3cf7802f7b1e965658c9e" args="()" -->
BOOST_UBLAS_INLINE <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix_1_1iterator2.html">iterator2</a> </td><td class="memItemRight" valign="bottom"><b>begin2</b> ()</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a08f9d3540435e74a17301e97fe884cd9"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::end2" ref="a08f9d3540435e74a17301e97fe884cd9" args="()" -->
BOOST_UBLAS_INLINE <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix_1_1iterator2.html">iterator2</a> </td><td class="memItemRight" valign="bottom"><b>end2</b> ()</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a71a39d4f570bdec8021386535473fa17"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::rbegin1" ref="a71a39d4f570bdec8021386535473fa17" args="() const " -->
BOOST_UBLAS_INLINE <br class="typebreak"/>
const_reverse_iterator1 </td><td class="memItemRight" valign="bottom"><b>rbegin1</b> () const </td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a29f66b78247395e1e45d840b8a993df6"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::rend1" ref="a29f66b78247395e1e45d840b8a993df6" args="() const " -->
BOOST_UBLAS_INLINE <br class="typebreak"/>
const_reverse_iterator1 </td><td class="memItemRight" valign="bottom"><b>rend1</b> () const </td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a2d97ea4b14db7af683d527470b30eab6"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::rbegin1" ref="a2d97ea4b14db7af683d527470b30eab6" args="()" -->
BOOST_UBLAS_INLINE <br class="typebreak"/>
reverse_iterator1 </td><td class="memItemRight" valign="bottom"><b>rbegin1</b> ()</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a676185a9b9d89eb2f83c111e4851c3f0"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::rend1" ref="a676185a9b9d89eb2f83c111e4851c3f0" args="()" -->
BOOST_UBLAS_INLINE <br class="typebreak"/>
reverse_iterator1 </td><td class="memItemRight" valign="bottom"><b>rend1</b> ()</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a68c8333e84f9f8d6f62d20efce880f1e"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::rbegin2" ref="a68c8333e84f9f8d6f62d20efce880f1e" args="() const " -->
BOOST_UBLAS_INLINE <br class="typebreak"/>
const_reverse_iterator2 </td><td class="memItemRight" valign="bottom"><b>rbegin2</b> () const </td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="adc7b01ba4faf2955d931be8ec03052e7"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::rend2" ref="adc7b01ba4faf2955d931be8ec03052e7" args="() const " -->
BOOST_UBLAS_INLINE <br class="typebreak"/>
const_reverse_iterator2 </td><td class="memItemRight" valign="bottom"><b>rend2</b> () const </td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a4492fb92061cf0ef4206ec33795ce9e3"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::rbegin2" ref="a4492fb92061cf0ef4206ec33795ce9e3" args="()" -->
BOOST_UBLAS_INLINE <br class="typebreak"/>
reverse_iterator2 </td><td class="memItemRight" valign="bottom"><b>rbegin2</b> ()</td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="af1e21e12a65e6ff10d5ef6aeeed186b4"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::rend2" ref="af1e21e12a65e6ff10d5ef6aeeed186b4" args="()" -->
BOOST_UBLAS_INLINE <br class="typebreak"/>
reverse_iterator2 </td><td class="memItemRight" valign="bottom"><b>rend2</b> ()</td></tr>
<tr><td class="memTemplParams" colspan="2"><a class="anchor" id="afef9dc77c8ca3cdaf8dd875079c4be93"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::serialize" ref="afef9dc77c8ca3cdaf8dd875079c4be93" args="(Archive &ar, const unsigned int)" -->
template<class Archive > </td></tr>
<tr><td class="memTemplItemLeft" align="right" valign="top">void </td><td class="memTemplItemRight" valign="bottom"><b>serialize</b> (Archive &ar, const unsigned int)</td></tr>
<tr><td colspan="2"><h2>Friends</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a23d22479d737a8358ad0035af2094cc0"></a><!-- doxytag: member="boost::numeric::ublas::c_matrix::swap" ref="a23d22479d737a8358ad0035af2094cc0" args="(c_matrix &m1, c_matrix &m2)" -->
BOOST_UBLAS_INLINE friend void </td><td class="memItemRight" valign="bottom"><b>swap</b> (<a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix.html">c_matrix</a> &m1, <a class="el" href="classboost_1_1numeric_1_1ublas_1_1c__matrix.html">c_matrix</a> &m2)</td></tr>
</table>
<hr/><a name="_details"></a><h2>Detailed Description</h2>
<h3>template<class T, std::size_t N, std::size_t M><br/>
class boost::numeric::ublas::c_matrix< T, N, M ></h3>
<p>This <a class="el" href="classboost_1_1numeric_1_1ublas_1_1matrix.html" title="A dense matrix of values of type T.">matrix</a> is directly based on a predefined C-style arry of data, thus providing the fastest implementation possible. The constraint is that dimensions of the <a class="el" href="classboost_1_1numeric_1_1ublas_1_1matrix.html" title="A dense matrix of values of type T.">matrix</a> must be specified at the instanciation or the type specification.</p>
<p>For instance, </p>
<div class="fragment"><pre class="fragment"> <span class="keyword">typedef</span> c_matrix<double,4,4> my_4by4_matrix
</pre></div><p> defines a 4 by 4 double-precision <a class="el" href="classboost_1_1numeric_1_1ublas_1_1matrix.html" title="A dense matrix of values of type T.">matrix</a>. You can also instantiate it directly with </p>
<div class="fragment"><pre class="fragment"> c_matrix<int,8,5> my_fast_matrix
</pre></div><p>. This will make a 8 by 5 integer <a class="el" href="classboost_1_1numeric_1_1ublas_1_1matrix.html" title="A dense matrix of values of type T.">matrix</a>. The price to pay for this speed is that you cannot resize it to a size larger than the one defined in the template parameters. In the previous example, a size of 4 by 5 or 3 by 2 is acceptable, but a new size of 9 by 5 or even 10 by 10 will raise a bad_size() exception.</p>
<dl><dt><b>Template Parameters:</b></dt><dd>
<table border="0" cellspacing="2" cellpadding="0">
<tr><td valign="top"></td><td valign="top"><em>T</em> </td><td>the type of object stored in the <a class="el" href="classboost_1_1numeric_1_1ublas_1_1matrix.html" title="A dense matrix of values of type T.">matrix</a> (like double, float, complex, etc...) </td></tr>
<tr><td valign="top"></td><td valign="top"><em>N</em> </td><td>the default maximum number of rows </td></tr>
<tr><td valign="top"></td><td valign="top"><em>M</em> </td><td>the default maximum number of columns </td></tr>
</table>
</dd>
</dl>
</div>
<hr size="1"/><address style="text-align: right;"><small>Generated on Sun Jul 4 20:31:06 2010 for ublas by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.6.1 </small></address>
</body>
</html>
| cppisfun/GameEngine | foreign/boost/libs/numeric/ublas/doc/html/classboost_1_1numeric_1_1ublas_1_1c__matrix.html | HTML | gpl-3.0 | 36,752 |
/**
* Marlin 3D Printer Firmware
* Copyright (C) 2019 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
*
* 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/>.
*
*/
#pragma once
/**
* Configuration_adv.h
*
* Advanced settings.
* Only change these if you know exactly what you're doing.
* Some of these settings can damage your printer if improperly set!
*
* Basic settings can be found in Configuration.h
*
*/
#define CONFIGURATION_ADV_H_VERSION 020000
// @section temperature
//===========================================================================
//=============================Thermal Settings ============================
//===========================================================================
//
// Custom Thermistor 1000 parameters
//
#if TEMP_SENSOR_0 == 1000
#define HOTEND0_PULLUP_RESISTOR_OHMS 4700 // Pullup resistor
#define HOTEND0_RESISTANCE_25C_OHMS 100000 // Resistance at 25C
#define HOTEND0_BETA 3950 // Beta value
#endif
#if TEMP_SENSOR_1 == 1000
#define HOTEND1_PULLUP_RESISTOR_OHMS 4700 // Pullup resistor
#define HOTEND1_RESISTANCE_25C_OHMS 100000 // Resistance at 25C
#define HOTEND1_BETA 3950 // Beta value
#endif
#if TEMP_SENSOR_2 == 1000
#define HOTEND2_PULLUP_RESISTOR_OHMS 4700 // Pullup resistor
#define HOTEND2_RESISTANCE_25C_OHMS 100000 // Resistance at 25C
#define HOTEND2_BETA 3950 // Beta value
#endif
#if TEMP_SENSOR_3 == 1000
#define HOTEND3_PULLUP_RESISTOR_OHMS 4700 // Pullup resistor
#define HOTEND3_RESISTANCE_25C_OHMS 100000 // Resistance at 25C
#define HOTEND3_BETA 3950 // Beta value
#endif
#if TEMP_SENSOR_4 == 1000
#define HOTEND4_PULLUP_RESISTOR_OHMS 4700 // Pullup resistor
#define HOTEND4_RESISTANCE_25C_OHMS 100000 // Resistance at 25C
#define HOTEND4_BETA 3950 // Beta value
#endif
#if TEMP_SENSOR_5 == 1000
#define HOTEND5_PULLUP_RESISTOR_OHMS 4700 // Pullup resistor
#define HOTEND5_RESISTANCE_25C_OHMS 100000 // Resistance at 25C
#define HOTEND5_BETA 3950 // Beta value
#endif
#if TEMP_SENSOR_BED == 1000
#define BED_PULLUP_RESISTOR_OHMS 4700 // Pullup resistor
#define BED_RESISTANCE_25C_OHMS 100000 // Resistance at 25C
#define BED_BETA 3950 // Beta value
#endif
#if TEMP_SENSOR_CHAMBER == 1000
#define CHAMBER_PULLUP_RESISTOR_OHMS 4700 // Pullup resistor
#define CHAMBER_RESISTANCE_25C_OHMS 100000 // Resistance at 25C
#define CHAMBER_BETA 3950 // Beta value
#endif
//
// Hephestos 2 24V heated bed upgrade kit.
// https://store.bq.com/en/heated-bed-kit-hephestos2
//
//#define HEPHESTOS2_HEATED_BED_KIT
#if ENABLED(HEPHESTOS2_HEATED_BED_KIT)
#undef TEMP_SENSOR_BED
#define TEMP_SENSOR_BED 70
#define HEATER_BED_INVERTING true
#endif
/**
* Heated Chamber settings
*/
#if TEMP_SENSOR_CHAMBER
#define CHAMBER_MINTEMP 5
#define CHAMBER_MAXTEMP 60
#define TEMP_CHAMBER_HYSTERESIS 1 // (°C) Temperature proximity considered "close enough" to the target
//#define CHAMBER_LIMIT_SWITCHING
//#define HEATER_CHAMBER_PIN 44 // Chamber heater on/off pin
//#define HEATER_CHAMBER_INVERTING false
#endif
#if DISABLED(PIDTEMPBED)
#define BED_CHECK_INTERVAL 5000 // ms between checks in bang-bang control
#if ENABLED(BED_LIMIT_SWITCHING)
#define BED_HYSTERESIS 2 // Only disable heating if T>target+BED_HYSTERESIS and enable heating if T>target-BED_HYSTERESIS
#endif
#endif
/**
* Thermal Protection provides additional protection to your printer from damage
* and fire. Marlin always includes safe min and max temperature ranges which
* protect against a broken or disconnected thermistor wire.
*
* The issue: If a thermistor falls out, it will report the much lower
* temperature of the air in the room, and the the firmware will keep
* the heater on.
*
* The solution: Once the temperature reaches the target, start observing.
* If the temperature stays too far below the target (hysteresis) for too
* long (period), the firmware will halt the machine as a safety precaution.
*
* If you get false positives for "Thermal Runaway", increase
* THERMAL_PROTECTION_HYSTERESIS and/or THERMAL_PROTECTION_PERIOD
*/
#if ENABLED(THERMAL_PROTECTION_HOTENDS)
#define THERMAL_PROTECTION_PERIOD 40 // Seconds
#define THERMAL_PROTECTION_HYSTERESIS 4 // Degrees Celsius
//#define ADAPTIVE_FAN_SLOWING // Slow part cooling fan if temperature drops
#if BOTH(ADAPTIVE_FAN_SLOWING, PIDTEMP)
//#define NO_FAN_SLOWING_IN_PID_TUNING // Don't slow fan speed during M303
#endif
/**
* Whenever an M104, M109, or M303 increases the target temperature, the
* firmware will wait for the WATCH_TEMP_PERIOD to expire. If the temperature
* hasn't increased by WATCH_TEMP_INCREASE degrees, the machine is halted and
* requires a hard reset. This test restarts with any M104/M109/M303, but only
* if the current temperature is far enough below the target for a reliable
* test.
*
* If you get false positives for "Heating failed", increase WATCH_TEMP_PERIOD
* and/or decrease WATCH_TEMP_INCREASE. WATCH_TEMP_INCREASE should not be set
* below 2.
*/
#define WATCH_TEMP_PERIOD 20 // Seconds
#define WATCH_TEMP_INCREASE 2 // Degrees Celsius
#endif
/**
* Thermal Protection parameters for the bed are just as above for hotends.
*/
#if ENABLED(THERMAL_PROTECTION_BED)
#define THERMAL_PROTECTION_BED_PERIOD 20 // Seconds
#define THERMAL_PROTECTION_BED_HYSTERESIS 2 // Degrees Celsius
/**
* As described above, except for the bed (M140/M190/M303).
*/
#define WATCH_BED_TEMP_PERIOD 60 // Seconds
#define WATCH_BED_TEMP_INCREASE 2 // Degrees Celsius
#endif
/**
* Thermal Protection parameters for the heated chamber.
*/
#if ENABLED(THERMAL_PROTECTION_CHAMBER)
#define THERMAL_PROTECTION_CHAMBER_PERIOD 20 // Seconds
#define THERMAL_PROTECTION_CHAMBER_HYSTERESIS 2 // Degrees Celsius
/**
* Heated chamber watch settings (M141/M191).
*/
#define WATCH_CHAMBER_TEMP_PERIOD 60 // Seconds
#define WATCH_CHAMBER_TEMP_INCREASE 2 // Degrees Celsius
#endif
#if ENABLED(PIDTEMP)
// Add an experimental additional term to the heater power, proportional to the extrusion speed.
// A well-chosen Kc value should add just enough power to melt the increased material volume.
//#define PID_EXTRUSION_SCALING
#if ENABLED(PID_EXTRUSION_SCALING)
#define DEFAULT_Kc (100) //heating power=Kc*(e_speed)
#define LPQ_MAX_LEN 50
#endif
#endif
/**
* Automatic Temperature:
* The hotend target temperature is calculated by all the buffered lines of gcode.
* The maximum buffered steps/sec of the extruder motor is called "se".
* Start autotemp mode with M109 S<mintemp> B<maxtemp> F<factor>
* The target temperature is set to mintemp+factor*se[steps/sec] and is limited by
* mintemp and maxtemp. Turn this off by executing M109 without F*
* Also, if the temperature is set to a value below mintemp, it will not be changed by autotemp.
* On an Ultimaker, some initial testing worked with M109 S215 B260 F1 in the start.gcode
*/
#define AUTOTEMP
#if ENABLED(AUTOTEMP)
#define AUTOTEMP_OLDWEIGHT 0.98
#endif
// Show extra position information in M114
//#define M114_DETAIL
// Show Temperature ADC value
// Enable for M105 to include ADC values read from temperature sensors.
//#define SHOW_TEMP_ADC_VALUES
/**
* High Temperature Thermistor Support
*
* Thermistors able to support high temperature tend to have a hard time getting
* good readings at room and lower temperatures. This means HEATER_X_RAW_LO_TEMP
* will probably be caught when the heating element first turns on during the
* preheating process, which will trigger a min_temp_error as a safety measure
* and force stop everything.
* To circumvent this limitation, we allow for a preheat time (during which,
* min_temp_error won't be triggered) and add a min_temp buffer to handle
* aberrant readings.
*
* If you want to enable this feature for your hotend thermistor(s)
* uncomment and set values > 0 in the constants below
*/
// The number of consecutive low temperature errors that can occur
// before a min_temp_error is triggered. (Shouldn't be more than 10.)
//#define MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED 0
// The number of milliseconds a hotend will preheat before starting to check
// the temperature. This value should NOT be set to the time it takes the
// hot end to reach the target temperature, but the time it takes to reach
// the minimum temperature your thermistor can read. The lower the better/safer.
// This shouldn't need to be more than 30 seconds (30000)
//#define MILLISECONDS_PREHEAT_TIME 0
// @section extruder
// Extruder runout prevention.
// If the machine is idle and the temperature over MINTEMP
// then extrude some filament every couple of SECONDS.
//#define EXTRUDER_RUNOUT_PREVENT
#if ENABLED(EXTRUDER_RUNOUT_PREVENT)
#define EXTRUDER_RUNOUT_MINTEMP 190
#define EXTRUDER_RUNOUT_SECONDS 30
#define EXTRUDER_RUNOUT_SPEED 1500 // (mm/m)
#define EXTRUDER_RUNOUT_EXTRUDE 5 // (mm)
#endif
// @section temperature
// Calibration for AD595 / AD8495 sensor to adjust temperature measurements.
// The final temperature is calculated as (measuredTemp * GAIN) + OFFSET.
#define TEMP_SENSOR_AD595_OFFSET 0.0
#define TEMP_SENSOR_AD595_GAIN 1.0
#define TEMP_SENSOR_AD8495_OFFSET 0.0
#define TEMP_SENSOR_AD8495_GAIN 1.0
/**
* Controller Fan
* To cool down the stepper drivers and MOSFETs.
*
* The fan will turn on automatically whenever any stepper is enabled
* and turn off after a set period after all steppers are turned off.
*/
//#define USE_CONTROLLER_FAN
#if ENABLED(USE_CONTROLLER_FAN)
//#define CONTROLLER_FAN_PIN -1 // Set a custom pin for the controller fan
#define CONTROLLERFAN_SECS 60 // Duration in seconds for the fan to run after all motors are disabled
#define CONTROLLERFAN_SPEED 255 // 255 == full speed
#endif
// When first starting the main fan, run it at full speed for the
// given number of milliseconds. This gets the fan spinning reliably
// before setting a PWM value. (Does not work with software PWM for fan on Sanguinololu)
//#define FAN_KICKSTART_TIME 100
/**
* PWM Fan Scaling
*
* Define the min/max speeds for PWM fans (as set with M106).
*
* With these options the M106 0-255 value range is scaled to a subset
* to ensure that the fan has enough power to spin, or to run lower
* current fans with higher current. (e.g., 5V/12V fans with 12V/24V)
* Value 0 always turns off the fan.
*
* Define one or both of these to override the default 0-255 range.
*/
//#define FAN_MIN_PWM 50
//#define FAN_MAX_PWM 128
/**
* FAST PWM FAN Settings
*
* Use to change the FAST FAN PWM frequency (if enabled in Configuration.h)
* Combinations of PWM Modes, prescale values and TOP resolutions are used internally to produce a
* frequency as close as possible to the desired frequency.
*
* FAST_PWM_FAN_FREQUENCY [undefined by default]
* Set this to your desired frequency.
* If left undefined this defaults to F = F_CPU/(2*255*1)
* ie F = 31.4 Khz on 16 MHz microcontrollers or F = 39.2 KHz on 20 MHz microcontrollers
* These defaults are the same as with the old FAST_PWM_FAN implementation - no migration is required
* NOTE: Setting very low frequencies (< 10 Hz) may result in unexpected timer behavior.
*
* USE_OCR2A_AS_TOP [undefined by default]
* Boards that use TIMER2 for PWM have limitations resulting in only a few possible frequencies on TIMER2:
* 16MHz MCUs: [62.5KHz, 31.4KHz (default), 7.8KHz, 3.92KHz, 1.95KHz, 977Hz, 488Hz, 244Hz, 60Hz, 122Hz, 30Hz]
* 20MHz MCUs: [78.1KHz, 39.2KHz (default), 9.77KHz, 4.9KHz, 2.44KHz, 1.22KHz, 610Hz, 305Hz, 153Hz, 76Hz, 38Hz]
* A greater range can be achieved by enabling USE_OCR2A_AS_TOP. But note that this option blocks the use of
* PWM on pin OC2A. Only use this option if you don't need PWM on 0C2A. (Check your schematic.)
* USE_OCR2A_AS_TOP sacrifices duty cycle control resolution to achieve this broader range of frequencies.
*/
#if ENABLED(FAST_PWM_FAN)
//#define FAST_PWM_FAN_FREQUENCY 31400
//#define USE_OCR2A_AS_TOP
#endif
// @section extruder
/**
* Extruder cooling fans
*
* Extruder auto fans automatically turn on when their extruders'
* temperatures go above EXTRUDER_AUTO_FAN_TEMPERATURE.
*
* Your board's pins file specifies the recommended pins. Override those here
* or set to -1 to disable completely.
*
* Multiple extruders can be assigned to the same pin in which case
* the fan will turn on when any selected extruder is above the threshold.
*/
#define E0_AUTO_FAN_PIN -1
#define E1_AUTO_FAN_PIN -1
#define E2_AUTO_FAN_PIN -1
#define E3_AUTO_FAN_PIN -1
#define E4_AUTO_FAN_PIN -1
#define E5_AUTO_FAN_PIN -1
#define CHAMBER_AUTO_FAN_PIN -1
#define EXTRUDER_AUTO_FAN_TEMPERATURE 50
#define EXTRUDER_AUTO_FAN_SPEED 255 // 255 == full speed
/**
* Part-Cooling Fan Multiplexer
*
* This feature allows you to digitally multiplex the fan output.
* The multiplexer is automatically switched at tool-change.
* Set FANMUX[012]_PINs below for up to 2, 4, or 8 multiplexed fans.
*/
#define FANMUX0_PIN -1
#define FANMUX1_PIN -1
#define FANMUX2_PIN -1
/**
* M355 Case Light on-off / brightness
*/
//#define CASE_LIGHT_ENABLE
#if ENABLED(CASE_LIGHT_ENABLE)
//#define CASE_LIGHT_PIN 4 // Override the default pin if needed
#define INVERT_CASE_LIGHT false // Set true if Case Light is ON when pin is LOW
#define CASE_LIGHT_DEFAULT_ON true // Set default power-up state on
#define CASE_LIGHT_DEFAULT_BRIGHTNESS 105 // Set default power-up brightness (0-255, requires PWM pin)
//#define MENU_ITEM_CASE_LIGHT // Add a Case Light option to the LCD main menu
//#define CASE_LIGHT_USE_NEOPIXEL // Use Neopixel LED as case light, requires NEOPIXEL_LED.
#if ENABLED(CASE_LIGHT_USE_NEOPIXEL)
#define CASE_LIGHT_NEOPIXEL_COLOR { 255, 255, 255, 255 } // { Red, Green, Blue, White }
#endif
#endif
// @section homing
// If you want endstops to stay on (by default) even when not homing
// enable this option. Override at any time with M120, M121.
//#define ENDSTOPS_ALWAYS_ON_DEFAULT
// @section extras
//#define Z_LATE_ENABLE // Enable Z the last moment. Needed if your Z driver overheats.
// Employ an external closed loop controller. Override pins here if needed.
//#define EXTERNAL_CLOSED_LOOP_CONTROLLER
#if ENABLED(EXTERNAL_CLOSED_LOOP_CONTROLLER)
//#define CLOSED_LOOP_ENABLE_PIN -1
//#define CLOSED_LOOP_MOVE_COMPLETE_PIN -1
#endif
/**
* Dual Steppers / Dual Endstops
*
* This section will allow you to use extra E drivers to drive a second motor for X, Y, or Z axes.
*
* For example, set X_DUAL_STEPPER_DRIVERS setting to use a second motor. If the motors need to
* spin in opposite directions set INVERT_X2_VS_X_DIR. If the second motor needs its own endstop
* set X_DUAL_ENDSTOPS. This can adjust for "racking." Use X2_USE_ENDSTOP to set the endstop plug
* that should be used for the second endstop. Extra endstops will appear in the output of 'M119'.
*
* Use X_DUAL_ENDSTOP_ADJUSTMENT to adjust for mechanical imperfection. After homing both motors
* this offset is applied to the X2 motor. To find the offset home the X axis, and measure the error
* in X2. Dual endstop offsets can be set at runtime with 'M666 X<offset> Y<offset> Z<offset>'.
*/
//#define X_DUAL_STEPPER_DRIVERS
#if ENABLED(X_DUAL_STEPPER_DRIVERS)
#define INVERT_X2_VS_X_DIR true // Set 'true' if X motors should rotate in opposite directions
//#define X_DUAL_ENDSTOPS
#if ENABLED(X_DUAL_ENDSTOPS)
#define X2_USE_ENDSTOP _XMAX_
#define X_DUAL_ENDSTOPS_ADJUSTMENT 0
#endif
#endif
//#define Y_DUAL_STEPPER_DRIVERS
#if ENABLED(Y_DUAL_STEPPER_DRIVERS)
#define INVERT_Y2_VS_Y_DIR true // Set 'true' if Y motors should rotate in opposite directions
//#define Y_DUAL_ENDSTOPS
#if ENABLED(Y_DUAL_ENDSTOPS)
#define Y2_USE_ENDSTOP _YMAX_
#define Y_DUAL_ENDSTOPS_ADJUSTMENT 0
#endif
#endif
//#define Z_DUAL_STEPPER_DRIVERS
#if ENABLED(Z_DUAL_STEPPER_DRIVERS)
//#define Z_DUAL_ENDSTOPS
#if ENABLED(Z_DUAL_ENDSTOPS)
#define Z2_USE_ENDSTOP _XMAX_
#define Z_DUAL_ENDSTOPS_ADJUSTMENT 0
#endif
#endif
//#define Z_TRIPLE_STEPPER_DRIVERS
#if ENABLED(Z_TRIPLE_STEPPER_DRIVERS)
//#define Z_TRIPLE_ENDSTOPS
#if ENABLED(Z_TRIPLE_ENDSTOPS)
#define Z2_USE_ENDSTOP _XMAX_
#define Z3_USE_ENDSTOP _YMAX_
#define Z_TRIPLE_ENDSTOPS_ADJUSTMENT2 0
#define Z_TRIPLE_ENDSTOPS_ADJUSTMENT3 0
#endif
#endif
/**
* Dual X Carriage
*
* This setup has two X carriages that can move independently, each with its own hotend.
* The carriages can be used to print an object with two colors or materials, or in
* "duplication mode" it can print two identical or X-mirrored objects simultaneously.
* The inactive carriage is parked automatically to prevent oozing.
* X1 is the left carriage, X2 the right. They park and home at opposite ends of the X axis.
* By default the X2 stepper is assigned to the first unused E plug on the board.
*
* The following Dual X Carriage modes can be selected with M605 S<mode>:
*
* 0 : (FULL_CONTROL) The slicer has full control over both X-carriages and can achieve optimal travel
* results as long as it supports dual X-carriages. (M605 S0)
*
* 1 : (AUTO_PARK) The firmware automatically parks and unparks the X-carriages on tool-change so
* that additional slicer support is not required. (M605 S1)
*
* 2 : (DUPLICATION) The firmware moves the second X-carriage and extruder in synchronization with
* the first X-carriage and extruder, to print 2 copies of the same object at the same time.
* Set the constant X-offset and temperature differential with M605 S2 X[offs] R[deg] and
* follow with M605 S2 to initiate duplicated movement.
*
* 3 : (MIRRORED) Formbot/Vivedino-inspired mirrored mode in which the second extruder duplicates
* the movement of the first except the second extruder is reversed in the X axis.
* Set the initial X offset and temperature differential with M605 S2 X[offs] R[deg] and
* follow with M605 S3 to initiate mirrored movement.
*/
//#define DUAL_X_CARRIAGE
#if ENABLED(DUAL_X_CARRIAGE)
#define X1_MIN_POS X_MIN_POS // Set to X_MIN_POS
#define X1_MAX_POS X_BED_SIZE // Set a maximum so the first X-carriage can't hit the parked second X-carriage
#define X2_MIN_POS 80 // Set a minimum to ensure the second X-carriage can't hit the parked first X-carriage
#define X2_MAX_POS 353 // Set this to the distance between toolheads when both heads are homed
#define X2_HOME_DIR 1 // Set to 1. The second X-carriage always homes to the maximum endstop position
#define X2_HOME_POS X2_MAX_POS // Default X2 home position. Set to X2_MAX_POS.
// However: In this mode the HOTEND_OFFSET_X value for the second extruder provides a software
// override for X2_HOME_POS. This also allow recalibration of the distance between the two endstops
// without modifying the firmware (through the "M218 T1 X???" command).
// Remember: you should set the second extruder x-offset to 0 in your slicer.
// This is the default power-up mode which can be later using M605.
#define DEFAULT_DUAL_X_CARRIAGE_MODE DXC_AUTO_PARK_MODE
// Default x offset in duplication mode (typically set to half print bed width)
#define DEFAULT_DUPLICATION_X_OFFSET 100
#endif // DUAL_X_CARRIAGE
// Activate a solenoid on the active extruder with M380. Disable all with M381.
// Define SOL0_PIN, SOL1_PIN, etc., for each extruder that has a solenoid.
//#define EXT_SOLENOID
// @section homing
// Homing hits each endstop, retracts by these distances, then does a slower bump.
#define X_HOME_BUMP_MM 5
#define Y_HOME_BUMP_MM 5
#define Z_HOME_BUMP_MM 2
#define HOMING_BUMP_DIVISOR { 2, 2, 4 } // Re-Bump Speed Divisor (Divides the Homing Feedrate)
//#define QUICK_HOME // If homing includes X and Y, do a diagonal move initially
//#define HOMING_BACKOFF_MM { 2, 2, 2 } // (mm) Move away from the endstops after homing
// When G28 is called, this option will make Y home before X
//#define HOME_Y_BEFORE_X
// Enable this if X or Y can't home without homing the other axis first.
//#define CODEPENDENT_XY_HOMING
/**
* Z Steppers Auto-Alignment
* Add the G34 command to align multiple Z steppers using a bed probe.
*/
//#define Z_STEPPER_AUTO_ALIGN
#if ENABLED(Z_STEPPER_AUTO_ALIGN)
// Define probe X and Y positions for Z1, Z2 [, Z3]
#define Z_STEPPER_ALIGN_X { 10, 150, 290 }
#define Z_STEPPER_ALIGN_Y { 290, 10, 290 }
// Set number of iterations to align
#define Z_STEPPER_ALIGN_ITERATIONS 3
// Enable to restore leveling setup after operation
#define RESTORE_LEVELING_AFTER_G34
// Use the amplification factor to de-/increase correction step.
// In case the stepper (spindle) position is further out than the test point
// Use a value > 1. NOTE: This may cause instability
#define Z_STEPPER_ALIGN_AMP 1.0
// Stop criterion. If the accuracy is better than this stop iterating early
#define Z_STEPPER_ALIGN_ACC 0.02
#endif
// @section machine
#define AXIS_RELATIVE_MODES {false, false, false, false}
// Add a Duplicate option for well-separated conjoined nozzles
//#define MULTI_NOZZLE_DUPLICATION
// By default pololu step drivers require an active high signal. However, some high power drivers require an active low signal as step.
#define INVERT_X_STEP_PIN false
#define INVERT_Y_STEP_PIN false
#define INVERT_Z_STEP_PIN false
#define INVERT_E_STEP_PIN false
// Default stepper release if idle. Set to 0 to deactivate.
// Steppers will shut down DEFAULT_STEPPER_DEACTIVE_TIME seconds after the last move when DISABLE_INACTIVE_? is true.
// Time can be set by M18 and M84.
#define DEFAULT_STEPPER_DEACTIVE_TIME 60
#define DISABLE_INACTIVE_X true
#define DISABLE_INACTIVE_Y true
#define DISABLE_INACTIVE_Z true // set to false if the nozzle will fall down on your printed part when print has finished.
#define DISABLE_INACTIVE_E true
#define DEFAULT_MINIMUMFEEDRATE 0.0 // minimum feedrate
#define DEFAULT_MINTRAVELFEEDRATE 0.0
//#define HOME_AFTER_DEACTIVATE // Require rehoming after steppers are deactivated
// @section lcd
#if EITHER(ULTIPANEL, EXTENSIBLE_UI)
#define MANUAL_FEEDRATE {120*60, 120*60, 18*60, 60} // Feedrates for manual moves along X, Y, Z, E from panel
#endif
#if ENABLED(ULTIPANEL)
#define MANUAL_E_MOVES_RELATIVE // Show LCD extruder moves as relative rather than absolute positions
#define ULTIPANEL_FEEDMULTIPLY // Comment to disable setting feedrate multiplier via encoder
#endif
// @section extras
// minimum time in microseconds that a movement needs to take if the buffer is emptied.
#define DEFAULT_MINSEGMENTTIME 20000
// If defined the movements slow down when the look ahead buffer is only half full
#define SLOWDOWN
// Frequency limit
// See nophead's blog for more info
// Not working O
//#define XY_FREQUENCY_LIMIT 15
// Minimum planner junction speed. Sets the default minimum speed the planner plans for at the end
// of the buffer and all stops. This should not be much greater than zero and should only be changed
// if unwanted behavior is observed on a user's machine when running at very slow speeds.
#define MINIMUM_PLANNER_SPEED 0.05 // (mm/s)
//
// Backlash Compensation
// Adds extra movement to axes on direction-changes to account for backlash.
//
//#define BACKLASH_COMPENSATION
#if ENABLED(BACKLASH_COMPENSATION)
// Define values for backlash distance and correction.
// If BACKLASH_GCODE is enabled these values are the defaults.
#define BACKLASH_DISTANCE_MM { 0, 0, 0 } // (mm)
#define BACKLASH_CORRECTION 0.0 // 0.0 = no correction; 1.0 = full correction
// Set BACKLASH_SMOOTHING_MM to spread backlash correction over multiple segments
// to reduce print artifacts. (Enabling this is costly in memory and computation!)
//#define BACKLASH_SMOOTHING_MM 3 // (mm)
// Add runtime configuration and tuning of backlash values (M425)
//#define BACKLASH_GCODE
#if ENABLED(BACKLASH_GCODE)
// Measure the Z backlash when probing (G29) and set with "M425 Z"
#define MEASURE_BACKLASH_WHEN_PROBING
#if ENABLED(MEASURE_BACKLASH_WHEN_PROBING)
// When measuring, the probe will move up to BACKLASH_MEASUREMENT_LIMIT
// mm away from point of contact in BACKLASH_MEASUREMENT_RESOLUTION
// increments while checking for the contact to be broken.
#define BACKLASH_MEASUREMENT_LIMIT 0.5 // (mm)
#define BACKLASH_MEASUREMENT_RESOLUTION 0.005 // (mm)
#define BACKLASH_MEASUREMENT_FEEDRATE Z_PROBE_SPEED_SLOW // (mm/m)
#endif
#endif
#endif
/**
* Automatic backlash, position and hotend offset calibration
*
* Enable G425 to run automatic calibration using an electrically-
* conductive cube, bolt, or washer mounted on the bed.
*
* G425 uses the probe to touch the top and sides of the calibration object
* on the bed and measures and/or correct positional offsets, axis backlash
* and hotend offsets.
*
* Note: HOTEND_OFFSET and CALIBRATION_OBJECT_CENTER must be set to within
* ±5mm of true values for G425 to succeed.
*/
//#define CALIBRATION_GCODE
#if ENABLED(CALIBRATION_GCODE)
#define CALIBRATION_MEASUREMENT_RESOLUTION 0.01 // mm
#define CALIBRATION_FEEDRATE_SLOW 60 // mm/m
#define CALIBRATION_FEEDRATE_FAST 1200 // mm/m
#define CALIBRATION_FEEDRATE_TRAVEL 3000 // mm/m
// The following parameters refer to the conical section of the nozzle tip.
#define CALIBRATION_NOZZLE_TIP_HEIGHT 1.0 // mm
#define CALIBRATION_NOZZLE_OUTER_DIAMETER 2.0 // mm
// Uncomment to enable reporting (required for "G425 V", but consumes PROGMEM).
//#define CALIBRATION_REPORTING
// The true location and dimension the cube/bolt/washer on the bed.
#define CALIBRATION_OBJECT_CENTER { 264.0, -22.0, -2.0} // mm
#define CALIBRATION_OBJECT_DIMENSIONS { 10.0, 10.0, 10.0} // mm
// Comment out any sides which are unreachable by the probe. For best
// auto-calibration results, all sides must be reachable.
#define CALIBRATION_MEASURE_RIGHT
#define CALIBRATION_MEASURE_FRONT
#define CALIBRATION_MEASURE_LEFT
#define CALIBRATION_MEASURE_BACK
// Probing at the exact top center only works if the center is flat. If
// probing on a screwhead or hollow washer, probe near the edges.
//#define CALIBRATION_MEASURE_AT_TOP_EDGES
// Define pin which is read during calibration
#ifndef CALIBRATION_PIN
#define CALIBRATION_PIN -1 // Override in pins.h or set to -1 to use your Z endstop
#define CALIBRATION_PIN_INVERTING false // set to true to invert the pin
//#define CALIBRATION_PIN_PULLDOWN
#define CALIBRATION_PIN_PULLUP
#endif
#endif
/**
* Adaptive Step Smoothing increases the resolution of multi-axis moves, particularly at step frequencies
* below 1kHz (for AVR) or 10kHz (for ARM), where aliasing between axes in multi-axis moves causes audible
* vibration and surface artifacts. The algorithm adapts to provide the best possible step smoothing at the
* lowest stepping frequencies.
*/
//#define ADAPTIVE_STEP_SMOOTHING
/**
* Custom Microstepping
* Override as-needed for your setup. Up to 3 MS pins are supported.
*/
//#define MICROSTEP1 LOW,LOW,LOW
//#define MICROSTEP2 HIGH,LOW,LOW
//#define MICROSTEP4 LOW,HIGH,LOW
//#define MICROSTEP8 HIGH,HIGH,LOW
//#define MICROSTEP16 LOW,LOW,HIGH
//#define MICROSTEP32 HIGH,LOW,HIGH
// Microstep setting (Only functional when stepper driver microstep pins are connected to MCU.
#define MICROSTEP_MODES { 16, 16, 16, 16, 16, 16 } // [1,2,4,8,16]
/**
* @section stepper motor current
*
* Some boards have a means of setting the stepper motor current via firmware.
*
* The power on motor currents are set by:
* PWM_MOTOR_CURRENT - used by MINIRAMBO & ULTIMAIN_2
* known compatible chips: A4982
* DIGIPOT_MOTOR_CURRENT - used by BQ_ZUM_MEGA_3D, RAMBO & SCOOVO_X9H
* known compatible chips: AD5206
* DAC_MOTOR_CURRENT_DEFAULT - used by PRINTRBOARD_REVF & RIGIDBOARD_V2
* known compatible chips: MCP4728
* DIGIPOT_I2C_MOTOR_CURRENTS - used by 5DPRINT, AZTEEG_X3_PRO, AZTEEG_X5_MINI_WIFI, MIGHTYBOARD_REVE
* known compatible chips: MCP4451, MCP4018
*
* Motor currents can also be set by M907 - M910 and by the LCD.
* M907 - applies to all.
* M908 - BQ_ZUM_MEGA_3D, RAMBO, PRINTRBOARD_REVF, RIGIDBOARD_V2 & SCOOVO_X9H
* M909, M910 & LCD - only PRINTRBOARD_REVF & RIGIDBOARD_V2
*/
//#define PWM_MOTOR_CURRENT { 1300, 1300, 1250 } // Values in milliamps
//#define DIGIPOT_MOTOR_CURRENT { 135,135,135,135,135 } // Values 0-255 (RAMBO 135 = ~0.75A, 185 = ~1A)
//#define DAC_MOTOR_CURRENT_DEFAULT { 70, 80, 90, 80 } // Default drive percent - X, Y, Z, E axis
// Use an I2C based DIGIPOT (e.g., Azteeg X3 Pro)
//#define DIGIPOT_I2C
#if ENABLED(DIGIPOT_I2C) && !defined(DIGIPOT_I2C_ADDRESS_A)
/**
* Common slave addresses:
*
* A (A shifted) B (B shifted) IC
* Smoothie 0x2C (0x58) 0x2D (0x5A) MCP4451
* AZTEEG_X3_PRO 0x2C (0x58) 0x2E (0x5C) MCP4451
* AZTEEG_X5_MINI 0x2C (0x58) 0x2E (0x5C) MCP4451
* AZTEEG_X5_MINI_WIFI 0x58 0x5C MCP4451
* MIGHTYBOARD_REVE 0x2F (0x5E) MCP4018
*/
#define DIGIPOT_I2C_ADDRESS_A 0x2C // unshifted slave address for first DIGIPOT
#define DIGIPOT_I2C_ADDRESS_B 0x2D // unshifted slave address for second DIGIPOT
#endif
//#define DIGIPOT_MCP4018 // Requires library from https://github.com/stawel/SlowSoftI2CMaster
#define DIGIPOT_I2C_NUM_CHANNELS 8 // 5DPRINT: 4 AZTEEG_X3_PRO: 8 MKS SBASE: 5
// Actual motor currents in Amps. The number of entries must match DIGIPOT_I2C_NUM_CHANNELS.
// These correspond to the physical drivers, so be mindful if the order is changed.
#define DIGIPOT_I2C_MOTOR_CURRENTS { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 } // AZTEEG_X3_PRO
//===========================================================================
//=============================Additional Features===========================
//===========================================================================
// @section lcd
// Change values more rapidly when the encoder is rotated faster
#define ENCODER_RATE_MULTIPLIER
#if ENABLED(ENCODER_RATE_MULTIPLIER)
#define ENCODER_10X_STEPS_PER_SEC 30 // (steps/s) Encoder rate for 10x speed
#define ENCODER_100X_STEPS_PER_SEC 80 // (steps/s) Encoder rate for 100x speed
#endif
// Play a beep when the feedrate is changed from the Status Screen
//#define BEEP_ON_FEEDRATE_CHANGE
#if ENABLED(BEEP_ON_FEEDRATE_CHANGE)
#define FEEDRATE_CHANGE_BEEP_DURATION 10
#define FEEDRATE_CHANGE_BEEP_FREQUENCY 440
#endif
// Include a page of printer information in the LCD Main Menu
//#define LCD_INFO_MENU
// Scroll a longer status message into view
//#define STATUS_MESSAGE_SCROLLING
// On the Info Screen, display XY with one decimal place when possible
//#define LCD_DECIMAL_SMALL_XY
// The timeout (in ms) to return to the status screen from sub-menus
//#define LCD_TIMEOUT_TO_STATUS 15000
// Add an 'M73' G-code to set the current percentage
//#define LCD_SET_PROGRESS_MANUALLY
#if HAS_CHARACTER_LCD && HAS_PRINT_PROGRESS
//#define LCD_PROGRESS_BAR // Show a progress bar on HD44780 LCDs for SD printing
#if ENABLED(LCD_PROGRESS_BAR)
#define PROGRESS_BAR_BAR_TIME 2000 // (ms) Amount of time to show the bar
#define PROGRESS_BAR_MSG_TIME 3000 // (ms) Amount of time to show the status message
#define PROGRESS_MSG_EXPIRE 0 // (ms) Amount of time to retain the status message (0=forever)
//#define PROGRESS_MSG_ONCE // Show the message for MSG_TIME then clear it
//#define LCD_PROGRESS_BAR_TEST // Add a menu item to test the progress bar
#endif
#endif
/**
* LED Control Menu
* Enable this feature to add LED Control to the LCD menu
*/
//#define LED_CONTROL_MENU
#if ENABLED(LED_CONTROL_MENU)
#define LED_COLOR_PRESETS // Enable the Preset Color menu option
#if ENABLED(LED_COLOR_PRESETS)
#define LED_USER_PRESET_RED 255 // User defined RED value
#define LED_USER_PRESET_GREEN 128 // User defined GREEN value
#define LED_USER_PRESET_BLUE 0 // User defined BLUE value
#define LED_USER_PRESET_WHITE 255 // User defined WHITE value
#define LED_USER_PRESET_BRIGHTNESS 255 // User defined intensity
//#define LED_USER_PRESET_STARTUP // Have the printer display the user preset color on startup
#endif
#endif // LED_CONTROL_MENU
#if ENABLED(SDSUPPORT)
// Some RAMPS and other boards don't detect when an SD card is inserted. You can work
// around this by connecting a push button or single throw switch to the pin defined
// as SD_DETECT_PIN in your board's pins definitions.
// This setting should be disabled unless you are using a push button, pulling the pin to ground.
// Note: This is always disabled for ULTIPANEL (except ELB_FULL_GRAPHIC_CONTROLLER).
#define SD_DETECT_INVERTED
#define SD_FINISHED_STEPPERRELEASE true // Disable steppers when SD Print is finished
#define SD_FINISHED_RELEASECOMMAND "M84 X Y Z E" // You might want to keep the Z enabled so your bed stays in place.
// Reverse SD sort to show "more recent" files first, according to the card's FAT.
// Since the FAT gets out of order with usage, SDCARD_SORT_ALPHA is recommended.
#define SDCARD_RATHERRECENTFIRST
#define SD_MENU_CONFIRM_START // Confirm the selected SD file before printing
//#define MENU_ADDAUTOSTART // Add a menu option to run auto#.g files
#define EVENT_GCODE_SD_STOP "G28XY" // G-code to run on Stop Print (e.g., "G28XY" or "G27")
/**
* Continue after Power-Loss (Creality3D)
*
* Store the current state to the SD Card at the start of each layer
* during SD printing. If the recovery file is found at boot time, present
* an option on the LCD screen to continue the print from the last-known
* point in the file.
*/
//#define POWER_LOSS_RECOVERY
#if ENABLED(POWER_LOSS_RECOVERY)
//#define POWER_LOSS_PIN 44 // Pin to detect power loss
//#define POWER_LOSS_STATE HIGH // State of pin indicating power loss
//#define POWER_LOSS_PURGE_LEN 20 // (mm) Length of filament to purge on resume
//#define POWER_LOSS_RETRACT_LEN 10 // (mm) Length of filament to retract on fail. Requires backup power.
// Without a POWER_LOSS_PIN the following option helps reduce wear on the SD card,
// especially with "vase mode" printing. Set too high and vases cannot be continued.
#define POWER_LOSS_MIN_Z_CHANGE 0.05 // (mm) Minimum Z change before saving power-loss data
#endif
/**
* Sort SD file listings in alphabetical order.
*
* With this option enabled, items on SD cards will be sorted
* by name for easier navigation.
*
* By default...
*
* - Use the slowest -but safest- method for sorting.
* - Folders are sorted to the top.
* - The sort key is statically allocated.
* - No added G-code (M34) support.
* - 40 item sorting limit. (Items after the first 40 are unsorted.)
*
* SD sorting uses static allocation (as set by SDSORT_LIMIT), allowing the
* compiler to calculate the worst-case usage and throw an error if the SRAM
* limit is exceeded.
*
* - SDSORT_USES_RAM provides faster sorting via a static directory buffer.
* - SDSORT_USES_STACK does the same, but uses a local stack-based buffer.
* - SDSORT_CACHE_NAMES will retain the sorted file listing in RAM. (Expensive!)
* - SDSORT_DYNAMIC_RAM only uses RAM when the SD menu is visible. (Use with caution!)
*/
//#define SDCARD_SORT_ALPHA
// SD Card Sorting options
#if ENABLED(SDCARD_SORT_ALPHA)
#define SDSORT_LIMIT 40 // Maximum number of sorted items (10-256). Costs 27 bytes each.
#define FOLDER_SORTING -1 // -1=above 0=none 1=below
#define SDSORT_GCODE false // Allow turning sorting on/off with LCD and M34 g-code.
#define SDSORT_USES_RAM false // Pre-allocate a static array for faster pre-sorting.
#define SDSORT_USES_STACK false // Prefer the stack for pre-sorting to give back some SRAM. (Negated by next 2 options.)
#define SDSORT_CACHE_NAMES false // Keep sorted items in RAM longer for speedy performance. Most expensive option.
#define SDSORT_DYNAMIC_RAM false // Use dynamic allocation (within SD menus). Least expensive option. Set SDSORT_LIMIT before use!
#define SDSORT_CACHE_VFATS 2 // Maximum number of 13-byte VFAT entries to use for sorting.
// Note: Only affects SCROLL_LONG_FILENAMES with SDSORT_CACHE_NAMES but not SDSORT_DYNAMIC_RAM.
#endif
// This allows hosts to request long names for files and folders with M33
//#define LONG_FILENAME_HOST_SUPPORT
// Enable this option to scroll long filenames in the SD card menu
//#define SCROLL_LONG_FILENAMES
/**
* This option allows you to abort SD printing when any endstop is triggered.
* This feature must be enabled with "M540 S1" or from the LCD menu.
* To have any effect, endstops must be enabled during SD printing.
*/
//#define ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
/**
* This option makes it easier to print the same SD Card file again.
* On print completion the LCD Menu will open with the file selected.
* You can just click to start the print, or navigate elsewhere.
*/
//#define SD_REPRINT_LAST_SELECTED_FILE
/**
* Auto-report SdCard status with M27 S<seconds>
*/
//#define AUTO_REPORT_SD_STATUS
/**
* Support for USB thumb drives using an Arduino USB Host Shield or
* equivalent MAX3421E breakout board. The USB thumb drive will appear
* to Marlin as an SD card.
*
* The MAX3421E must be assigned the same pins as the SD card reader, with
* the following pin mapping:
*
* SCLK, MOSI, MISO --> SCLK, MOSI, MISO
* INT --> SD_DETECT_PIN
* SS --> SDSS
*/
//#define USB_FLASH_DRIVE_SUPPORT
#if ENABLED(USB_FLASH_DRIVE_SUPPORT)
#define USB_CS_PIN SDSS
#define USB_INTR_PIN SD_DETECT_PIN
#endif
/**
* When using a bootloader that supports SD-Firmware-Flashing,
* add a menu item to activate SD-FW-Update on the next reboot.
*
* Requires ATMEGA2560 (Arduino Mega)
*
* Tested with this bootloader:
* https://github.com/FleetProbe/MicroBridge-Arduino-ATMega2560
*/
//#define SD_FIRMWARE_UPDATE
#if ENABLED(SD_FIRMWARE_UPDATE)
#define SD_FIRMWARE_UPDATE_EEPROM_ADDR 0x1FF
#define SD_FIRMWARE_UPDATE_ACTIVE_VALUE 0xF0
#define SD_FIRMWARE_UPDATE_INACTIVE_VALUE 0xFF
#endif
// Add an optimized binary file transfer mode, initiated with 'M28 B1'
//#define BINARY_FILE_TRANSFER
// LPC-based boards have on-board SD Card options. Override here or defaults apply.
#ifdef TARGET_LPC1768
//#define LPC_SD_LCD // Use the SD drive in the external LCD controller.
//#define LPC_SD_ONBOARD // Use the SD drive on the control board. (No SD_DETECT_PIN. M21 to init.)
//#define LPC_SD_CUSTOM_CABLE // Use a custom cable to access the SD (as defined in a pins file).
//#define USB_SD_DISABLED // Disable SD Card access over USB (for security).
#if ENABLED(LPC_SD_ONBOARD)
//#define USB_SD_ONBOARD // Provide the onboard SD card to the host as a USB mass storage device.
#endif
#endif
#endif // SDSUPPORT
/**
* Additional options for Graphical Displays
*
* Use the optimizations here to improve printing performance,
* which can be adversely affected by graphical display drawing,
* especially when doing several short moves, and when printing
* on DELTA and SCARA machines.
*
* Some of these options may result in the display lagging behind
* controller events, as there is a trade-off between reliable
* printing performance versus fast display updates.
*/
#if HAS_GRAPHICAL_LCD
// Show SD percentage next to the progress bar
//#define DOGM_SD_PERCENT
// Enable to save many cycles by drawing a hollow frame on the Info Screen
#define XYZ_HOLLOW_FRAME
// Enable to save many cycles by drawing a hollow frame on Menu Screens
#define MENU_HOLLOW_FRAME
// A bigger font is available for edit items. Costs 3120 bytes of PROGMEM.
// Western only. Not available for Cyrillic, Kana, Turkish, Greek, or Chinese.
//#define USE_BIG_EDIT_FONT
// A smaller font may be used on the Info Screen. Costs 2300 bytes of PROGMEM.
// Western only. Not available for Cyrillic, Kana, Turkish, Greek, or Chinese.
//#define USE_SMALL_INFOFONT
// Enable this option and reduce the value to optimize screen updates.
// The normal delay is 10µs. Use the lowest value that still gives a reliable display.
//#define DOGM_SPI_DELAY_US 5
// Swap the CW/CCW indicators in the graphics overlay
//#define OVERLAY_GFX_REVERSE
/**
* ST7920-based LCDs can emulate a 16 x 4 character display using
* the ST7920 character-generator for very fast screen updates.
* Enable LIGHTWEIGHT_UI to use this special display mode.
*
* Since LIGHTWEIGHT_UI has limited space, the position and status
* message occupy the same line. Set STATUS_EXPIRE_SECONDS to the
* length of time to display the status message before clearing.
*
* Set STATUS_EXPIRE_SECONDS to zero to never clear the status.
* This will prevent position updates from being displayed.
*/
#if ENABLED(U8GLIB_ST7920)
//#define LIGHTWEIGHT_UI
#if ENABLED(LIGHTWEIGHT_UI)
#define STATUS_EXPIRE_SECONDS 20
#endif
#endif
/**
* Status (Info) Screen customizations
* These options may affect code size and screen render time.
* Custom status screens can forcibly override these settings.
*/
//#define STATUS_COMBINE_HEATERS // Use combined heater images instead of separate ones
//#define STATUS_HOTEND_NUMBERLESS // Use plain hotend icons instead of numbered ones (with 2+ hotends)
#define STATUS_HOTEND_INVERTED // Show solid nozzle bitmaps when heating (Requires STATUS_HOTEND_ANIM)
#define STATUS_HOTEND_ANIM // Use a second bitmap to indicate hotend heating
#define STATUS_BED_ANIM // Use a second bitmap to indicate bed heating
#define STATUS_CHAMBER_ANIM // Use a second bitmap to indicate chamber heating
//#define STATUS_ALT_BED_BITMAP // Use the alternative bed bitmap
//#define STATUS_ALT_FAN_BITMAP // Use the alternative fan bitmap
//#define STATUS_FAN_FRAMES 3 // :[0,1,2,3,4] Number of fan animation frames
//#define STATUS_HEAT_PERCENT // Show heating in a progress bar
//#define BOOT_MARLIN_LOGO_SMALL // Show a smaller Marlin logo on the Boot Screen (saving 399 bytes of flash)
// Frivolous Game Options
//#define MARLIN_BRICKOUT
//#define MARLIN_INVADERS
//#define MARLIN_SNAKE
#endif // HAS_GRAPHICAL_LCD
// @section safety
/**
* The watchdog hardware timer will do a reset and disable all outputs
* if the firmware gets too overloaded to read the temperature sensors.
*
* If you find that watchdog reboot causes your AVR board to hang forever,
* enable WATCHDOG_RESET_MANUAL to use a custom timer instead of WDTO.
* NOTE: This method is less reliable as it can only catch hangups while
* interrupts are enabled.
*/
#define USE_WATCHDOG
#if ENABLED(USE_WATCHDOG)
//#define WATCHDOG_RESET_MANUAL
#endif
// @section lcd
/**
* Babystepping enables movement of the axes by tiny increments without changing
* the current position values. This feature is used primarily to adjust the Z
* axis in the first layer of a print in real-time.
*
* Warning: Does not respect endstops!
*/
//#define BABYSTEPPING
#if ENABLED(BABYSTEPPING)
//#define BABYSTEP_WITHOUT_HOMING
//#define BABYSTEP_XY // Also enable X/Y Babystepping. Not supported on DELTA!
#define BABYSTEP_INVERT_Z false // Change if Z babysteps should go the other way
#define BABYSTEP_MULTIPLICATOR 1 // Babysteps are very small. Increase for faster motion.
//#define DOUBLECLICK_FOR_Z_BABYSTEPPING // Double-click on the Status Screen for Z Babystepping.
#if ENABLED(DOUBLECLICK_FOR_Z_BABYSTEPPING)
#define DOUBLECLICK_MAX_INTERVAL 1250 // Maximum interval between clicks, in milliseconds.
// Note: Extra time may be added to mitigate controller latency.
//#define BABYSTEP_ALWAYS_AVAILABLE // Allow babystepping at all times (not just during movement).
//#define MOVE_Z_WHEN_IDLE // Jump to the move Z menu on doubleclick when printer is idle.
#if ENABLED(MOVE_Z_WHEN_IDLE)
#define MOVE_Z_IDLE_MULTIPLICATOR 1 // Multiply 1mm by this factor for the move step size.
#endif
#endif
//#define BABYSTEP_DISPLAY_TOTAL // Display total babysteps since last G28
//#define BABYSTEP_ZPROBE_OFFSET // Combine M851 Z and Babystepping
#if ENABLED(BABYSTEP_ZPROBE_OFFSET)
//#define BABYSTEP_HOTEND_Z_OFFSET // For multiple hotends, babystep relative Z offsets
//#define BABYSTEP_ZPROBE_GFX_OVERLAY // Enable graphical overlay on Z-offset editor
#endif
#endif
// @section extruder
/**
* Linear Pressure Control v1.5
*
* Assumption: advance [steps] = k * (delta velocity [steps/s])
* K=0 means advance disabled.
*
* NOTE: K values for LIN_ADVANCE 1.5 differ from earlier versions!
*
* Set K around 0.22 for 3mm PLA Direct Drive with ~6.5cm between the drive gear and heatbreak.
* Larger K values will be needed for flexible filament and greater distances.
* If this algorithm produces a higher speed offset than the extruder can handle (compared to E jerk)
* print acceleration will be reduced during the affected moves to keep within the limit.
*
* See http://marlinfw.org/docs/features/lin_advance.html for full instructions.
* Mention @Sebastianv650 on GitHub to alert the author of any issues.
*/
//#define LIN_ADVANCE
#if ENABLED(LIN_ADVANCE)
//#define EXTRA_LIN_ADVANCE_K // Enable for second linear advance constants
#define LIN_ADVANCE_K 0.22 // Unit: mm compression per 1mm/s extruder speed
//#define LA_DEBUG // If enabled, this will generate debug information output over USB.
#endif
// @section leveling
#if EITHER(MESH_BED_LEVELING, AUTO_BED_LEVELING_UBL)
// Override the mesh area if the automatic (max) area is too large
//#define MESH_MIN_X MESH_INSET
//#define MESH_MIN_Y MESH_INSET
//#define MESH_MAX_X X_BED_SIZE - (MESH_INSET)
//#define MESH_MAX_Y Y_BED_SIZE - (MESH_INSET)
#endif
/**
* Repeatedly attempt G29 leveling until it succeeds.
* Stop after G29_MAX_RETRIES attempts.
*/
//#define G29_RETRY_AND_RECOVER
#if ENABLED(G29_RETRY_AND_RECOVER)
#define G29_MAX_RETRIES 3
#define G29_HALT_ON_FAILURE
/**
* Specify the GCODE commands that will be executed when leveling succeeds,
* between attempts, and after the maximum number of retries have been tried.
*/
#define G29_SUCCESS_COMMANDS "M117 Bed leveling done."
#define G29_RECOVER_COMMANDS "M117 Probe failed. Rewiping.\nG28\nG12 P0 S12 T0"
#define G29_FAILURE_COMMANDS "M117 Bed leveling failed.\nG0 Z10\nM300 P25 S880\nM300 P50 S0\nM300 P25 S880\nM300 P50 S0\nM300 P25 S880\nM300 P50 S0\nG4 S1"
#endif
// @section extras
//
// G2/G3 Arc Support
//
#define ARC_SUPPORT // Disable this feature to save ~3226 bytes
#if ENABLED(ARC_SUPPORT)
#define MM_PER_ARC_SEGMENT 1 // Length of each arc segment
#define MIN_ARC_SEGMENTS 24 // Minimum number of segments in a complete circle
#define N_ARC_CORRECTION 25 // Number of interpolated segments between corrections
//#define ARC_P_CIRCLES // Enable the 'P' parameter to specify complete circles
//#define CNC_WORKSPACE_PLANES // Allow G2/G3 to operate in XY, ZX, or YZ planes
#endif
// Support for G5 with XYZE destination and IJPQ offsets. Requires ~2666 bytes.
//#define BEZIER_CURVE_SUPPORT
/**
* G38 Probe Target
*
* This option adds G38.2 and G38.3 (probe towards target)
* and optionally G38.4 and G38.5 (probe away from target).
* Set MULTIPLE_PROBING for G38 to probe more than once.
*/
//#define G38_PROBE_TARGET
#if ENABLED(G38_PROBE_TARGET)
//#define G38_PROBE_AWAY // Include G38.4 and G38.5 to probe away from target
#define G38_MINIMUM_MOVE 0.0275 // (mm) Minimum distance that will produce a move.
#endif
// Moves (or segments) with fewer steps than this will be joined with the next move
#define MIN_STEPS_PER_SEGMENT 6
/**
* Minimum delay after setting the stepper DIR (in ns)
* 0 : No delay (Expect at least 10µS since one Stepper ISR must transpire)
* 20 : Minimum for TMC2xxx drivers
* 200 : Minimum for A4988 drivers
* 400 : Minimum for A5984 drivers
* 500 : Minimum for LV8729 drivers (guess, no info in datasheet)
* 650 : Minimum for DRV8825 drivers
* 1500 : Minimum for TB6600 drivers (guess, no info in datasheet)
* 15000 : Minimum for TB6560 drivers (guess, no info in datasheet)
*
* Override the default value based on the driver type set in Configuration.h.
*/
//#define MINIMUM_STEPPER_DIR_DELAY 650
/**
* Minimum stepper driver pulse width (in µs)
* 0 : Smallest possible width the MCU can produce, compatible with TMC2xxx drivers
* 0 : Minimum 500ns for LV8729, adjusted in stepper.h
* 1 : Minimum for A4988 and A5984 stepper drivers
* 2 : Minimum for DRV8825 stepper drivers
* 3 : Minimum for TB6600 stepper drivers
* 30 : Minimum for TB6560 stepper drivers
*
* Override the default value based on the driver type set in Configuration.h.
*/
//#define MINIMUM_STEPPER_PULSE 2
/**
* Maximum stepping rate (in Hz) the stepper driver allows
* If undefined, defaults to 1MHz / (2 * MINIMUM_STEPPER_PULSE)
* 500000 : Maximum for A4988 stepper driver
* 400000 : Maximum for TMC2xxx stepper drivers
* 250000 : Maximum for DRV8825 stepper driver
* 200000 : Maximum for LV8729 stepper driver
* 150000 : Maximum for TB6600 stepper driver
* 15000 : Maximum for TB6560 stepper driver
*
* Override the default value based on the driver type set in Configuration.h.
*/
//#define MAXIMUM_STEPPER_RATE 250000
// @section temperature
// Control heater 0 and heater 1 in parallel.
//#define HEATERS_PARALLEL
//===========================================================================
//================================= Buffers =================================
//===========================================================================
// @section hidden
// The number of linear motions that can be in the plan at any give time.
// THE BLOCK_BUFFER_SIZE NEEDS TO BE A POWER OF 2 (e.g. 8, 16, 32) because shifts and ors are used to do the ring-buffering.
#if ENABLED(SDSUPPORT)
#define BLOCK_BUFFER_SIZE 16 // SD,LCD,Buttons take more memory, block buffer needs to be smaller
#else
#define BLOCK_BUFFER_SIZE 16 // maximize block buffer
#endif
// @section serial
// The ASCII buffer for serial input
#define MAX_CMD_SIZE 96
#define BUFSIZE 4
// Transmission to Host Buffer Size
// To save 386 bytes of PROGMEM (and TX_BUFFER_SIZE+3 bytes of RAM) set to 0.
// To buffer a simple "ok" you need 4 bytes.
// For ADVANCED_OK (M105) you need 32 bytes.
// For debug-echo: 128 bytes for the optimal speed.
// Other output doesn't need to be that speedy.
// :[0, 2, 4, 8, 16, 32, 64, 128, 256]
#define TX_BUFFER_SIZE 0
// Host Receive Buffer Size
// Without XON/XOFF flow control (see SERIAL_XON_XOFF below) 32 bytes should be enough.
// To use flow control, set this buffer size to at least 1024 bytes.
// :[0, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048]
//#define RX_BUFFER_SIZE 1024
#if RX_BUFFER_SIZE >= 1024
// Enable to have the controller send XON/XOFF control characters to
// the host to signal the RX buffer is becoming full.
//#define SERIAL_XON_XOFF
#endif
#if ENABLED(SDSUPPORT)
// Enable this option to collect and display the maximum
// RX queue usage after transferring a file to SD.
//#define SERIAL_STATS_MAX_RX_QUEUED
// Enable this option to collect and display the number
// of dropped bytes after a file transfer to SD.
//#define SERIAL_STATS_DROPPED_RX
#endif
// Enable an emergency-command parser to intercept certain commands as they
// enter the serial receive buffer, so they cannot be blocked.
// Currently handles M108, M112, M410
// Does not work on boards using AT90USB (USBCON) processors!
//#define EMERGENCY_PARSER
// Bad Serial-connections can miss a received command by sending an 'ok'
// Therefore some clients abort after 30 seconds in a timeout.
// Some other clients start sending commands while receiving a 'wait'.
// This "wait" is only sent when the buffer is empty. 1 second is a good value here.
//#define NO_TIMEOUTS 1000 // Milliseconds
// Some clients will have this feature soon. This could make the NO_TIMEOUTS unnecessary.
//#define ADVANCED_OK
// Printrun may have trouble receiving long strings all at once.
// This option inserts short delays between lines of serial output.
#define SERIAL_OVERRUN_PROTECTION
// @section extras
/**
* Extra Fan Speed
* Adds a secondary fan speed for each print-cooling fan.
* 'M106 P<fan> T3-255' : Set a secondary speed for <fan>
* 'M106 P<fan> T2' : Use the set secondary speed
* 'M106 P<fan> T1' : Restore the previous fan speed
*/
//#define EXTRA_FAN_SPEED
/**
* Firmware-based and LCD-controlled retract
*
* Add G10 / G11 commands for automatic firmware-based retract / recover.
* Use M207 and M208 to define parameters for retract / recover.
*
* Use M209 to enable or disable auto-retract.
* With auto-retract enabled, all G1 E moves within the set range
* will be converted to firmware-based retract/recover moves.
*
* Be sure to turn off auto-retract during filament change.
*
* Note that M207 / M208 / M209 settings are saved to EEPROM.
*
*/
//#define FWRETRACT
#if ENABLED(FWRETRACT)
#define FWRETRACT_AUTORETRACT // costs ~500 bytes of PROGMEM
#if ENABLED(FWRETRACT_AUTORETRACT)
#define MIN_AUTORETRACT 0.1 // When auto-retract is on, convert E moves of this length and over
#define MAX_AUTORETRACT 10.0 // Upper limit for auto-retract conversion
#endif
#define RETRACT_LENGTH 3 // Default retract length (positive mm)
#define RETRACT_LENGTH_SWAP 13 // Default swap retract length (positive mm), for extruder change
#define RETRACT_FEEDRATE 45 // Default feedrate for retracting (mm/s)
#define RETRACT_ZRAISE 0 // Default retract Z-raise (mm)
#define RETRACT_RECOVER_LENGTH 0 // Default additional recover length (mm, added to retract length when recovering)
#define RETRACT_RECOVER_LENGTH_SWAP 0 // Default additional swap recover length (mm, added to retract length when recovering from extruder change)
#define RETRACT_RECOVER_FEEDRATE 8 // Default feedrate for recovering from retraction (mm/s)
#define RETRACT_RECOVER_FEEDRATE_SWAP 8 // Default feedrate for recovering from swap retraction (mm/s)
#if ENABLED(MIXING_EXTRUDER)
//#define RETRACT_SYNC_MIXING // Retract and restore all mixing steppers simultaneously
#endif
#endif
/**
* Universal tool change settings.
* Applies to all types of extruders except where explicitly noted.
*/
#if EXTRUDERS > 1
// Z raise distance for tool-change, as needed for some extruders
#define TOOLCHANGE_ZRAISE 2 // (mm)
// Retract and prime filament on tool-change
//#define TOOLCHANGE_FILAMENT_SWAP
#if ENABLED(TOOLCHANGE_FILAMENT_SWAP)
#define TOOLCHANGE_FIL_SWAP_LENGTH 12 // (mm)
#define TOOLCHANGE_FIL_EXTRA_PRIME 2 // (mm)
#define TOOLCHANGE_FIL_SWAP_RETRACT_SPEED 3600 // (mm/m)
#define TOOLCHANGE_FIL_SWAP_PRIME_SPEED 3600 // (mm/m)
#endif
/**
* Position to park head during tool change.
* Doesn't apply to SWITCHING_TOOLHEAD, DUAL_X_CARRIAGE, or PARKING_EXTRUDER
*/
//#define TOOLCHANGE_PARK
#if ENABLED(TOOLCHANGE_PARK)
#define TOOLCHANGE_PARK_XY { X_MIN_POS + 10, Y_MIN_POS + 10 }
#define TOOLCHANGE_PARK_XY_FEEDRATE 6000 // (mm/m)
#endif
#endif
/**
* Advanced Pause
* Experimental feature for filament change support and for parking the nozzle when paused.
* Adds the GCode M600 for initiating filament change.
* If PARK_HEAD_ON_PAUSE enabled, adds the GCode M125 to pause printing and park the nozzle.
*
* Requires an LCD display.
* Requires NOZZLE_PARK_FEATURE.
* This feature is required for the default FILAMENT_RUNOUT_SCRIPT.
*/
//#define ADVANCED_PAUSE_FEATURE
#if ENABLED(ADVANCED_PAUSE_FEATURE)
#define PAUSE_PARK_RETRACT_FEEDRATE 60 // (mm/s) Initial retract feedrate.
#define PAUSE_PARK_RETRACT_LENGTH 2 // (mm) Initial retract.
// This short retract is done immediately, before parking the nozzle.
#define FILAMENT_CHANGE_UNLOAD_FEEDRATE 10 // (mm/s) Unload filament feedrate. This can be pretty fast.
#define FILAMENT_CHANGE_UNLOAD_ACCEL 25 // (mm/s^2) Lower acceleration may allow a faster feedrate.
#define FILAMENT_CHANGE_UNLOAD_LENGTH 100 // (mm) The length of filament for a complete unload.
// For Bowden, the full length of the tube and nozzle.
// For direct drive, the full length of the nozzle.
// Set to 0 for manual unloading.
#define FILAMENT_CHANGE_SLOW_LOAD_FEEDRATE 6 // (mm/s) Slow move when starting load.
#define FILAMENT_CHANGE_SLOW_LOAD_LENGTH 0 // (mm) Slow length, to allow time to insert material.
// 0 to disable start loading and skip to fast load only
#define FILAMENT_CHANGE_FAST_LOAD_FEEDRATE 6 // (mm/s) Load filament feedrate. This can be pretty fast.
#define FILAMENT_CHANGE_FAST_LOAD_ACCEL 25 // (mm/s^2) Lower acceleration may allow a faster feedrate.
#define FILAMENT_CHANGE_FAST_LOAD_LENGTH 0 // (mm) Load length of filament, from extruder gear to nozzle.
// For Bowden, the full length of the tube and nozzle.
// For direct drive, the full length of the nozzle.
//#define ADVANCED_PAUSE_CONTINUOUS_PURGE // Purge continuously up to the purge length until interrupted.
#define ADVANCED_PAUSE_PURGE_FEEDRATE 3 // (mm/s) Extrude feedrate (after loading). Should be slower than load feedrate.
#define ADVANCED_PAUSE_PURGE_LENGTH 50 // (mm) Length to extrude after loading.
// Set to 0 for manual extrusion.
// Filament can be extruded repeatedly from the Filament Change menu
// until extrusion is consistent, and to purge old filament.
#define ADVANCED_PAUSE_RESUME_PRIME 0 // (mm) Extra distance to prime nozzle after returning from park.
//#define ADVANCED_PAUSE_FANS_PAUSE // Turn off print-cooling fans while the machine is paused.
// Filament Unload does a Retract, Delay, and Purge first:
#define FILAMENT_UNLOAD_RETRACT_LENGTH 13 // (mm) Unload initial retract length.
#define FILAMENT_UNLOAD_DELAY 5000 // (ms) Delay for the filament to cool after retract.
#define FILAMENT_UNLOAD_PURGE_LENGTH 8 // (mm) An unretract is done, then this length is purged.
#define PAUSE_PARK_NOZZLE_TIMEOUT 45 // (seconds) Time limit before the nozzle is turned off for safety.
#define FILAMENT_CHANGE_ALERT_BEEPS 10 // Number of alert beeps to play when a response is needed.
#define PAUSE_PARK_NO_STEPPER_TIMEOUT // Enable for XYZ steppers to stay powered on during filament change.
//#define PARK_HEAD_ON_PAUSE // Park the nozzle during pause and filament change.
//#define HOME_BEFORE_FILAMENT_CHANGE // Ensure homing has been completed prior to parking for filament change
//#define FILAMENT_LOAD_UNLOAD_GCODES // Add M701/M702 Load/Unload G-codes, plus Load/Unload in the LCD Prepare menu.
//#define FILAMENT_UNLOAD_ALL_EXTRUDERS // Allow M702 to unload all extruders above a minimum target temp (as set by M302)
#endif
// @section tmc
/**
* TMC26X Stepper Driver options
*
* The TMC26XStepper library is required for this stepper driver.
* https://github.com/trinamic/TMC26XStepper
*/
#if HAS_DRIVER(TMC26X)
#if AXIS_DRIVER_TYPE_X(TMC26X)
#define X_MAX_CURRENT 1000 // (mA)
#define X_SENSE_RESISTOR 91 // (mOhms)
#define X_MICROSTEPS 16 // Number of microsteps
#endif
#if AXIS_DRIVER_TYPE_X2(TMC26X)
#define X2_MAX_CURRENT 1000
#define X2_SENSE_RESISTOR 91
#define X2_MICROSTEPS 16
#endif
#if AXIS_DRIVER_TYPE_Y(TMC26X)
#define Y_MAX_CURRENT 1000
#define Y_SENSE_RESISTOR 91
#define Y_MICROSTEPS 16
#endif
#if AXIS_DRIVER_TYPE_Y2(TMC26X)
#define Y2_MAX_CURRENT 1000
#define Y2_SENSE_RESISTOR 91
#define Y2_MICROSTEPS 16
#endif
#if AXIS_DRIVER_TYPE_Z(TMC26X)
#define Z_MAX_CURRENT 1000
#define Z_SENSE_RESISTOR 91
#define Z_MICROSTEPS 16
#endif
#if AXIS_DRIVER_TYPE_Z2(TMC26X)
#define Z2_MAX_CURRENT 1000
#define Z2_SENSE_RESISTOR 91
#define Z2_MICROSTEPS 16
#endif
#if AXIS_DRIVER_TYPE_Z3(TMC26X)
#define Z3_MAX_CURRENT 1000
#define Z3_SENSE_RESISTOR 91
#define Z3_MICROSTEPS 16
#endif
#if AXIS_DRIVER_TYPE_E0(TMC26X)
#define E0_MAX_CURRENT 1000
#define E0_SENSE_RESISTOR 91
#define E0_MICROSTEPS 16
#endif
#if AXIS_DRIVER_TYPE_E1(TMC26X)
#define E1_MAX_CURRENT 1000
#define E1_SENSE_RESISTOR 91
#define E1_MICROSTEPS 16
#endif
#if AXIS_DRIVER_TYPE_E2(TMC26X)
#define E2_MAX_CURRENT 1000
#define E2_SENSE_RESISTOR 91
#define E2_MICROSTEPS 16
#endif
#if AXIS_DRIVER_TYPE_E3(TMC26X)
#define E3_MAX_CURRENT 1000
#define E3_SENSE_RESISTOR 91
#define E3_MICROSTEPS 16
#endif
#if AXIS_DRIVER_TYPE_E4(TMC26X)
#define E4_MAX_CURRENT 1000
#define E4_SENSE_RESISTOR 91
#define E4_MICROSTEPS 16
#endif
#if AXIS_DRIVER_TYPE_E5(TMC26X)
#define E5_MAX_CURRENT 1000
#define E5_SENSE_RESISTOR 91
#define E5_MICROSTEPS 16
#endif
#endif // TMC26X
// @section tmc_smart
/**
* To use TMC2130, TMC2160, TMC2660, TMC5130, TMC5160 stepper drivers in SPI mode
* connect your SPI pins to the hardware SPI interface on your board and define
* the required CS pins in your `pins_MYBOARD.h` file. (e.g., RAMPS 1.4 uses AUX3
* pins `X_CS_PIN 53`, `Y_CS_PIN 49`, etc.).
* You may also use software SPI if you wish to use general purpose IO pins.
*
* To use TMC2208 stepper UART-configurable stepper drivers connect #_SERIAL_TX_PIN
* to the driver side PDN_UART pin with a 1K resistor.
* To use the reading capabilities, also connect #_SERIAL_RX_PIN to PDN_UART without
* a resistor.
* The drivers can also be used with hardware serial.
*
* TMCStepper library is required to use TMC stepper drivers.
* https://github.com/teemuatlut/TMCStepper
*/
#if HAS_TRINAMIC
#define HOLD_MULTIPLIER 0.5 // Scales down the holding current from run current
#define INTERPOLATE true // Interpolate X/Y/Z_MICROSTEPS to 256
#if AXIS_IS_TMC(X)
#define X_CURRENT 800 // (mA) RMS current. Multiply by 1.414 for peak current.
#define X_MICROSTEPS 16 // 0..256
#define X_RSENSE 0.11
#endif
#if AXIS_IS_TMC(X2)
#define X2_CURRENT 800
#define X2_MICROSTEPS 16
#define X2_RSENSE 0.11
#endif
#if AXIS_IS_TMC(Y)
#define Y_CURRENT 800
#define Y_MICROSTEPS 16
#define Y_RSENSE 0.11
#endif
#if AXIS_IS_TMC(Y2)
#define Y2_CURRENT 800
#define Y2_MICROSTEPS 16
#define Y2_RSENSE 0.11
#endif
#if AXIS_IS_TMC(Z)
#define Z_CURRENT 800
#define Z_MICROSTEPS 16
#define Z_RSENSE 0.11
#endif
#if AXIS_IS_TMC(Z2)
#define Z2_CURRENT 800
#define Z2_MICROSTEPS 16
#define Z2_RSENSE 0.11
#endif
#if AXIS_IS_TMC(Z3)
#define Z3_CURRENT 800
#define Z3_MICROSTEPS 16
#define Z3_RSENSE 0.11
#endif
#if AXIS_IS_TMC(E0)
#define E0_CURRENT 800
#define E0_MICROSTEPS 16
#define E0_RSENSE 0.11
#endif
#if AXIS_IS_TMC(E1)
#define E1_CURRENT 800
#define E1_MICROSTEPS 16
#define E1_RSENSE 0.11
#endif
#if AXIS_IS_TMC(E2)
#define E2_CURRENT 800
#define E2_MICROSTEPS 16
#define E2_RSENSE 0.11
#endif
#if AXIS_IS_TMC(E3)
#define E3_CURRENT 800
#define E3_MICROSTEPS 16
#define E3_RSENSE 0.11
#endif
#if AXIS_IS_TMC(E4)
#define E4_CURRENT 800
#define E4_MICROSTEPS 16
#define E4_RSENSE 0.11
#endif
#if AXIS_IS_TMC(E5)
#define E5_CURRENT 800
#define E5_MICROSTEPS 16
#define E5_RSENSE 0.11
#endif
/**
* Override default SPI pins for TMC2130, TMC2160, TMC2660, TMC5130 and TMC5160 drivers here.
* The default pins can be found in your board's pins file.
*/
//#define X_CS_PIN -1
//#define Y_CS_PIN -1
//#define Z_CS_PIN -1
//#define X2_CS_PIN -1
//#define Y2_CS_PIN -1
//#define Z2_CS_PIN -1
//#define Z3_CS_PIN -1
//#define E0_CS_PIN -1
//#define E1_CS_PIN -1
//#define E2_CS_PIN -1
//#define E3_CS_PIN -1
//#define E4_CS_PIN -1
//#define E5_CS_PIN -1
/**
* Use software SPI for TMC2130.
* Software option for SPI driven drivers (TMC2130, TMC2160, TMC2660, TMC5130 and TMC5160).
* The default SW SPI pins are defined the respective pins files,
* but you can override or define them here.
*/
//#define TMC_USE_SW_SPI
//#define TMC_SW_MOSI -1
//#define TMC_SW_MISO -1
//#define TMC_SW_SCK -1
/**
* Software enable
*
* Use for drivers that do not use a dedicated enable pin, but rather handle the same
* function through a communication line such as SPI or UART.
*/
//#define SOFTWARE_DRIVER_ENABLE
/**
* TMC2130, TMC2160, TMC2208, TMC5130 and TMC5160 only
* Use Trinamic's ultra quiet stepping mode.
* When disabled, Marlin will use spreadCycle stepping mode.
*/
#define STEALTHCHOP_XY
#define STEALTHCHOP_Z
#define STEALTHCHOP_E
/**
* Optimize spreadCycle chopper parameters by using predefined parameter sets
* or with the help of an example included in the library.
* Provided parameter sets are
* CHOPPER_DEFAULT_12V
* CHOPPER_DEFAULT_19V
* CHOPPER_DEFAULT_24V
* CHOPPER_DEFAULT_36V
* CHOPPER_PRUSAMK3_24V // Imported parameters from the official Prusa firmware for MK3 (24V)
* CHOPPER_MARLIN_119 // Old defaults from Marlin v1.1.9
*
* Define you own with
* { <off_time[1..15]>, <hysteresis_end[-3..12]>, hysteresis_start[1..8] }
*/
#define CHOPPER_TIMING CHOPPER_DEFAULT_12V
/**
* Monitor Trinamic drivers for error conditions,
* like overtemperature and short to ground. TMC2208 requires hardware serial.
* In the case of overtemperature Marlin can decrease the driver current until error condition clears.
* Other detected conditions can be used to stop the current print.
* Relevant g-codes:
* M906 - Set or get motor current in milliamps using axis codes X, Y, Z, E. Report values if no axis codes given.
* M911 - Report stepper driver overtemperature pre-warn condition.
* M912 - Clear stepper driver overtemperature pre-warn condition flag.
* M122 - Report driver parameters (Requires TMC_DEBUG)
*/
//#define MONITOR_DRIVER_STATUS
#if ENABLED(MONITOR_DRIVER_STATUS)
#define CURRENT_STEP_DOWN 50 // [mA]
#define REPORT_CURRENT_CHANGE
#define STOP_ON_ERROR
#endif
/**
* TMC2130, TMC2160, TMC2208, TMC5130 and TMC5160 only
* The driver will switch to spreadCycle when stepper speed is over HYBRID_THRESHOLD.
* This mode allows for faster movements at the expense of higher noise levels.
* STEALTHCHOP_(XY|Z|E) must be enabled to use HYBRID_THRESHOLD.
* M913 X/Y/Z/E to live tune the setting
*/
//#define HYBRID_THRESHOLD
#define X_HYBRID_THRESHOLD 100 // [mm/s]
#define X2_HYBRID_THRESHOLD 100
#define Y_HYBRID_THRESHOLD 100
#define Y2_HYBRID_THRESHOLD 100
#define Z_HYBRID_THRESHOLD 3
#define Z2_HYBRID_THRESHOLD 3
#define Z3_HYBRID_THRESHOLD 3
#define E0_HYBRID_THRESHOLD 30
#define E1_HYBRID_THRESHOLD 30
#define E2_HYBRID_THRESHOLD 30
#define E3_HYBRID_THRESHOLD 30
#define E4_HYBRID_THRESHOLD 30
#define E5_HYBRID_THRESHOLD 30
/**
* Use StallGuard2 to home/probe X, Y, Z.
*
* TMC2130, TMC2160, TMC2660, TMC5130, and TMC5160 only
* Connect the stepper driver's DIAG1 pin to the X/Y endstop pin.
* X, Y, and Z homing will always be done in spreadCycle mode.
*
* X/Y/Z_STALL_SENSITIVITY is used to tune the trigger sensitivity.
* Use M914 X Y Z to live-adjust the sensitivity.
* Higher: LESS sensitive. (Too high => failure to trigger)
* Lower: MORE sensitive. (Too low => false positives)
*
* It is recommended to set [XYZ]_HOME_BUMP_MM to 0.
*
* SPI_ENDSTOPS *** Beta feature! *** TMC 2130 Only ***
* Poll the driver through SPI to determine load when homing.
* Removes the need for a wire from DIAG1 to an endstop pin.
*
* IMPROVE_HOMING_RELIABILITY tunes acceleration and jerk when homing
* and adds a guard period for endstop triggering.
*/
//#define SENSORLESS_HOMING // TMC2130 only
/**
* Use StallGuard2 to probe the bed with the nozzle.
*
* CAUTION: This could cause damage to machines that use a lead screw or threaded rod
* to move the Z axis. Take extreme care when attempting to enable this feature.
*/
//#define SENSORLESS_PROBING // TMC2130 only
#if EITHER(SENSORLESS_HOMING, SENSORLESS_PROBING)
#define X_STALL_SENSITIVITY 8
#define Y_STALL_SENSITIVITY 8
//#define Z_STALL_SENSITIVITY 8
//#define SPI_ENDSTOPS
//#define IMPROVE_HOMING_RELIABILITY
#endif
/**
* Enable M122 debugging command for TMC stepper drivers.
* M122 S0/1 will enable continous reporting.
*/
//#define TMC_DEBUG
/**
* You can set your own advanced settings by filling in predefined functions.
* A list of available functions can be found on the library github page
* https://github.com/teemuatlut/TMCStepper
*
* Example:
* #define TMC_ADV() { \
* stepperX.diag0_temp_prewarn(1); \
* stepperY.interpolate(0); \
* }
*/
#define TMC_ADV() { }
#endif // HAS_TRINAMIC
// @section L6470
/**
* L6470 Stepper Driver options
*
* Arduino-L6470 library (0.7.0 or higher) is required for this stepper driver.
* https://github.com/ameyer/Arduino-L6470
*
* Requires the following to be defined in your pins_YOUR_BOARD file
* L6470_CHAIN_SCK_PIN
* L6470_CHAIN_MISO_PIN
* L6470_CHAIN_MOSI_PIN
* L6470_CHAIN_SS_PIN
* L6470_RESET_CHAIN_PIN (optional)
*/
#if HAS_DRIVER(L6470)
//#define L6470_CHITCHAT // Display additional status info
#if AXIS_DRIVER_TYPE_X(L6470)
#define X_MICROSTEPS 128 // Number of microsteps (VALID: 1, 2, 4, 8, 16, 32, 128)
#define X_OVERCURRENT 2000 // (mA) Current where the driver detects an over current (VALID: 375 x (1 - 16) - 6A max - rounds down)
#define X_STALLCURRENT 1500 // (mA) Current where the driver detects a stall (VALID: 31.25 * (1-128) - 4A max - rounds down)
#define X_MAX_VOLTAGE 127 // 0-255, Maximum effective voltage seen by stepper
#define X_CHAIN_POS 0 // Position in SPI chain, 0=Not in chain, 1=Nearest MOSI
#endif
#if AXIS_DRIVER_TYPE_X2(L6470)
#define X2_MICROSTEPS 128
#define X2_OVERCURRENT 2000
#define X2_STALLCURRENT 1500
#define X2_MAX_VOLTAGE 127
#define X2_CHAIN_POS 0
#endif
#if AXIS_DRIVER_TYPE_Y(L6470)
#define Y_MICROSTEPS 128
#define Y_OVERCURRENT 2000
#define Y_STALLCURRENT 1500
#define Y_MAX_VOLTAGE 127
#define Y_CHAIN_POS 0
#endif
#if AXIS_DRIVER_TYPE_Y2(L6470)
#define Y2_MICROSTEPS 128
#define Y2_OVERCURRENT 2000
#define Y2_STALLCURRENT 1500
#define Y2_MAX_VOLTAGE 127
#define Y2_CHAIN_POS 0
#endif
#if AXIS_DRIVER_TYPE_Z(L6470)
#define Z_MICROSTEPS 128
#define Z_OVERCURRENT 2000
#define Z_STALLCURRENT 1500
#define Z_MAX_VOLTAGE 127
#define Z_CHAIN_POS 0
#endif
#if AXIS_DRIVER_TYPE_Z2(L6470)
#define Z2_MICROSTEPS 128
#define Z2_OVERCURRENT 2000
#define Z2_STALLCURRENT 1500
#define Z2_MAX_VOLTAGE 127
#define Z2_CHAIN_POS 0
#endif
#if AXIS_DRIVER_TYPE_Z3(L6470)
#define Z3_MICROSTEPS 128
#define Z3_OVERCURRENT 2000
#define Z3_STALLCURRENT 1500
#define Z3_MAX_VOLTAGE 127
#define Z3_CHAIN_POS 0
#endif
#if AXIS_DRIVER_TYPE_E0(L6470)
#define E0_MICROSTEPS 128
#define E0_OVERCURRENT 2000
#define E0_STALLCURRENT 1500
#define E0_MAX_VOLTAGE 127
#define E0_CHAIN_POS 0
#endif
#if AXIS_DRIVER_TYPE_E1(L6470)
#define E1_MICROSTEPS 128
#define E1_OVERCURRENT 2000
#define E1_STALLCURRENT 1500
#define E1_MAX_VOLTAGE 127
#define E1_CHAIN_POS 0
#endif
#if AXIS_DRIVER_TYPE_E2(L6470)
#define E2_MICROSTEPS 128
#define E2_OVERCURRENT 2000
#define E2_STALLCURRENT 1500
#define E2_MAX_VOLTAGE 127
#define E2_CHAIN_POS 0
#endif
#if AXIS_DRIVER_TYPE_E3(L6470)
#define E3_MICROSTEPS 128
#define E3_OVERCURRENT 2000
#define E3_STALLCURRENT 1500
#define E3_MAX_VOLTAGE 127
#define E3_CHAIN_POS 0
#endif
#if AXIS_DRIVER_TYPE_E4(L6470)
#define E4_MICROSTEPS 128
#define E4_OVERCURRENT 2000
#define E4_STALLCURRENT 1500
#define E4_MAX_VOLTAGE 127
#define E4_CHAIN_POS 0
#endif
#if AXIS_DRIVER_TYPE_E5(L6470)
#define E5_MICROSTEPS 128
#define E5_OVERCURRENT 2000
#define E5_STALLCURRENT 1500
#define E5_MAX_VOLTAGE 127
#define E5_CHAIN_POS 0
#endif
/**
* Monitor L6470 drivers for error conditions like over temperature and over current.
* In the case of over temperature Marlin can decrease the drive until the error condition clears.
* Other detected conditions can be used to stop the current print.
* Relevant g-codes:
* M906 - I1/2/3/4/5 Set or get motor drive level using axis codes X, Y, Z, E. Report values if no axis codes given.
* I not present or I0 or I1 - X, Y, Z or E0
* I2 - X2, Y2, Z2 or E1
* I3 - Z3 or E3
* I4 - E4
* I5 - E5
* M916 - Increase drive level until get thermal warning
* M917 - Find minimum current thresholds
* M918 - Increase speed until max or error
* M122 S0/1 - Report driver parameters
*/
//#define MONITOR_L6470_DRIVER_STATUS
#if ENABLED(MONITOR_L6470_DRIVER_STATUS)
#define KVAL_HOLD_STEP_DOWN 1
//#define L6470_STOP_ON_ERROR
#endif
#endif // L6470
/**
* TWI/I2C BUS
*
* This feature is an EXPERIMENTAL feature so it shall not be used on production
* machines. Enabling this will allow you to send and receive I2C data from slave
* devices on the bus.
*
* ; Example #1
* ; This macro send the string "Marlin" to the slave device with address 0x63 (99)
* ; It uses multiple M260 commands with one B<base 10> arg
* M260 A99 ; Target slave address
* M260 B77 ; M
* M260 B97 ; a
* M260 B114 ; r
* M260 B108 ; l
* M260 B105 ; i
* M260 B110 ; n
* M260 S1 ; Send the current buffer
*
* ; Example #2
* ; Request 6 bytes from slave device with address 0x63 (99)
* M261 A99 B5
*
* ; Example #3
* ; Example serial output of a M261 request
* echo:i2c-reply: from:99 bytes:5 data:hello
*/
// @section i2cbus
//#define EXPERIMENTAL_I2CBUS
#define I2C_SLAVE_ADDRESS 0 // Set a value from 8 to 127 to act as a slave
// @section extras
/**
* Photo G-code
* Add the M240 G-code to take a photo.
* The photo can be triggered by a digital pin or a physical movement.
*/
//#define PHOTO_GCODE
#if ENABLED(PHOTO_GCODE)
// A position to move to (and raise Z) before taking the photo
//#define PHOTO_POSITION { X_MAX_POS - 5, Y_MAX_POS, 0 } // { xpos, ypos, zraise } (M240 X Y Z)
//#define PHOTO_DELAY_MS 100 // (ms) Duration to pause before moving back (M240 P)
//#define PHOTO_RETRACT_MM 6.5 // (mm) E retract/recover for the photo move (M240 R S)
// Canon RC-1 or homebrew digital camera trigger
// Data from: http://www.doc-diy.net/photo/rc-1_hacked/
//#define PHOTOGRAPH_PIN 23
// Canon Hack Development Kit
// http://captain-slow.dk/2014/03/09/3d-printing-timelapses/
//#define CHDK_PIN 4
// Optional second move with delay to trigger the camera shutter
//#define PHOTO_SWITCH_POSITION { X_MAX_POS, Y_MAX_POS } // { xpos, ypos } (M240 I J)
// Duration to hold the switch or keep CHDK_PIN high
//#define PHOTO_SWITCH_MS 50 // (ms) (M240 D)
#endif
/**
* Spindle & Laser control
*
* Add the M3, M4, and M5 commands to turn the spindle/laser on and off, and
* to set spindle speed, spindle direction, and laser power.
*
* SuperPid is a router/spindle speed controller used in the CNC milling community.
* Marlin can be used to turn the spindle on and off. It can also be used to set
* the spindle speed from 5,000 to 30,000 RPM.
*
* You'll need to select a pin for the ON/OFF function and optionally choose a 0-5V
* hardware PWM pin for the speed control and a pin for the rotation direction.
*
* See http://marlinfw.org/docs/configuration/laser_spindle.html for more config details.
*/
//#define SPINDLE_LASER_ENABLE
#if ENABLED(SPINDLE_LASER_ENABLE)
#define SPINDLE_LASER_ENABLE_INVERT false // set to "true" if the on/off function is reversed
#define SPINDLE_LASER_PWM true // set to true if your controller supports setting the speed/power
#define SPINDLE_LASER_PWM_INVERT true // set to "true" if the speed/power goes up when you want it to go slower
#define SPINDLE_LASER_POWERUP_DELAY 5000 // delay in milliseconds to allow the spindle/laser to come up to speed/power
#define SPINDLE_LASER_POWERDOWN_DELAY 5000 // delay in milliseconds to allow the spindle to stop
#define SPINDLE_DIR_CHANGE true // set to true if your spindle controller supports changing spindle direction
#define SPINDLE_INVERT_DIR false
#define SPINDLE_STOP_ON_DIR_CHANGE true // set to true if Marlin should stop the spindle before changing rotation direction
/**
* The M3 & M4 commands use the following equation to convert PWM duty cycle to speed/power
*
* SPEED/POWER = PWM duty cycle * SPEED_POWER_SLOPE + SPEED_POWER_INTERCEPT
* where PWM duty cycle varies from 0 to 255
*
* set the following for your controller (ALL MUST BE SET)
*/
#define SPEED_POWER_SLOPE 118.4
#define SPEED_POWER_INTERCEPT 0
#define SPEED_POWER_MIN 5000
#define SPEED_POWER_MAX 30000 // SuperPID router controller 0 - 30,000 RPM
//#define SPEED_POWER_SLOPE 0.3922
//#define SPEED_POWER_INTERCEPT 0
//#define SPEED_POWER_MIN 10
//#define SPEED_POWER_MAX 100 // 0-100%
#endif
/**
* Filament Width Sensor
*
* Measures the filament width in real-time and adjusts
* flow rate to compensate for any irregularities.
*
* Also allows the measured filament diameter to set the
* extrusion rate, so the slicer only has to specify the
* volume.
*
* Only a single extruder is supported at this time.
*
* 34 RAMPS_14 : Analog input 5 on the AUX2 connector
* 81 PRINTRBOARD : Analog input 2 on the Exp1 connector (version B,C,D,E)
* 301 RAMBO : Analog input 3
*
* Note: May require analog pins to be defined for other boards.
*/
//#define FILAMENT_WIDTH_SENSOR
#if ENABLED(FILAMENT_WIDTH_SENSOR)
#define FILAMENT_SENSOR_EXTRUDER_NUM 0 // Index of the extruder that has the filament sensor. :[0,1,2,3,4]
#define MEASUREMENT_DELAY_CM 14 // (cm) The distance from the filament sensor to the melting chamber
#define FILWIDTH_ERROR_MARGIN 1.0 // (mm) If a measurement differs too much from nominal width ignore it
#define MAX_MEASUREMENT_DELAY 20 // (bytes) Buffer size for stored measurements (1 byte per cm). Must be larger than MEASUREMENT_DELAY_CM.
#define DEFAULT_MEASURED_FILAMENT_DIA DEFAULT_NOMINAL_FILAMENT_DIA // Set measured to nominal initially
// Display filament width on the LCD status line. Status messages will expire after 5 seconds.
//#define FILAMENT_LCD_DISPLAY
#endif
/**
* CNC Coordinate Systems
*
* Enables G53 and G54-G59.3 commands to select coordinate systems
* and G92.1 to reset the workspace to native machine space.
*/
//#define CNC_COORDINATE_SYSTEMS
/**
* Auto-report temperatures with M155 S<seconds>
*/
#define AUTO_REPORT_TEMPERATURES
/**
* Include capabilities in M115 output
*/
#define EXTENDED_CAPABILITIES_REPORT
/**
* Disable all Volumetric extrusion options
*/
//#define NO_VOLUMETRICS
#if DISABLED(NO_VOLUMETRICS)
/**
* Volumetric extrusion default state
* Activate to make volumetric extrusion the default method,
* with DEFAULT_NOMINAL_FILAMENT_DIA as the default diameter.
*
* M200 D0 to disable, M200 Dn to set a new diameter.
*/
//#define VOLUMETRIC_DEFAULT_ON
#endif
/**
* Enable this option for a leaner build of Marlin that removes all
* workspace offsets, simplifying coordinate transformations, leveling, etc.
*
* - M206 and M428 are disabled.
* - G92 will revert to its behavior from Marlin 1.0.
*/
//#define NO_WORKSPACE_OFFSETS
/**
* Set the number of proportional font spaces required to fill up a typical character space.
* This can help to better align the output of commands like `G29 O` Mesh Output.
*
* For clients that use a fixed-width font (like OctoPrint), leave this set to 1.0.
* Otherwise, adjust according to your client and font.
*/
#define PROPORTIONAL_FONT_RATIO 1.0
/**
* Spend 28 bytes of SRAM to optimize the GCode parser
*/
#define FASTER_GCODE_PARSER
/**
* CNC G-code options
* Support CNC-style G-code dialects used by laser cutters, drawing machine cams, etc.
* Note that G0 feedrates should be used with care for 3D printing (if used at all).
* High feedrates may cause ringing and harm print quality.
*/
//#define PAREN_COMMENTS // Support for parentheses-delimited comments
//#define GCODE_MOTION_MODES // Remember the motion mode (G0 G1 G2 G3 G5 G38.X) and apply for X Y Z E F, etc.
// Enable and set a (default) feedrate for all G0 moves
//#define G0_FEEDRATE 3000 // (mm/m)
#ifdef G0_FEEDRATE
//#define VARIABLE_G0_FEEDRATE // The G0 feedrate is set by F in G0 motion mode
#endif
/**
* G-code Macros
*
* Add G-codes M810-M819 to define and run G-code macros.
* Macros are not saved to EEPROM.
*/
//#define GCODE_MACROS
#if ENABLED(GCODE_MACROS)
#define GCODE_MACROS_SLOTS 5 // Up to 10 may be used
#define GCODE_MACROS_SLOT_SIZE 50 // Maximum length of a single macro
#endif
/**
* User-defined menu items that execute custom GCode
*/
//#define CUSTOM_USER_MENUS
#if ENABLED(CUSTOM_USER_MENUS)
//#define CUSTOM_USER_MENU_TITLE "Custom Commands"
#define USER_SCRIPT_DONE "M117 User Script Done"
#define USER_SCRIPT_AUDIBLE_FEEDBACK
//#define USER_SCRIPT_RETURN // Return to status screen after a script
#define USER_DESC_1 "Home & UBL Info"
#define USER_GCODE_1 "G28\nG29 W"
#define USER_DESC_2 "Preheat for " PREHEAT_1_LABEL
#define USER_GCODE_2 "M140 S" STRINGIFY(PREHEAT_1_TEMP_BED) "\nM104 S" STRINGIFY(PREHEAT_1_TEMP_HOTEND)
#define USER_DESC_3 "Preheat for " PREHEAT_2_LABEL
#define USER_GCODE_3 "M140 S" STRINGIFY(PREHEAT_2_TEMP_BED) "\nM104 S" STRINGIFY(PREHEAT_2_TEMP_HOTEND)
#define USER_DESC_4 "Heat Bed/Home/Level"
#define USER_GCODE_4 "M140 S" STRINGIFY(PREHEAT_2_TEMP_BED) "\nG28\nG29"
//#define USER_DESC_5 "Home & Info"
//#define USER_GCODE_5 "G28\nM503"
#endif
/**
* Host Action Commands
*
* Define host streamer action commands in compliance with the standard.
*
* See https://reprap.org/wiki/G-code#Action_commands
* Common commands ........ poweroff, pause, paused, resume, resumed, cancel
* G29_RETRY_AND_RECOVER .. probe_rewipe, probe_failed
*
* Some features add reason codes to extend these commands.
*
* Host Prompt Support enables Marlin to use the host for user prompts so
* filament runout and other processes can be managed from the host side.
*/
//#define HOST_ACTION_COMMANDS
#if ENABLED(HOST_ACTION_COMMANDS)
//#define HOST_PROMPT_SUPPORT
#endif
//===========================================================================
//====================== I2C Position Encoder Settings ======================
//===========================================================================
/**
* I2C position encoders for closed loop control.
* Developed by Chris Barr at Aus3D.
*
* Wiki: http://wiki.aus3d.com.au/Magnetic_Encoder
* Github: https://github.com/Aus3D/MagneticEncoder
*
* Supplier: http://aus3d.com.au/magnetic-encoder-module
* Alternative Supplier: http://reliabuild3d.com/
*
* Reliabuild encoders have been modified to improve reliability.
*/
//#define I2C_POSITION_ENCODERS
#if ENABLED(I2C_POSITION_ENCODERS)
#define I2CPE_ENCODER_CNT 1 // The number of encoders installed; max of 5
// encoders supported currently.
#define I2CPE_ENC_1_ADDR I2CPE_PRESET_ADDR_X // I2C address of the encoder. 30-200.
#define I2CPE_ENC_1_AXIS X_AXIS // Axis the encoder module is installed on. <X|Y|Z|E>_AXIS.
#define I2CPE_ENC_1_TYPE I2CPE_ENC_TYPE_LINEAR // Type of encoder: I2CPE_ENC_TYPE_LINEAR -or-
// I2CPE_ENC_TYPE_ROTARY.
#define I2CPE_ENC_1_TICKS_UNIT 2048 // 1024 for magnetic strips with 2mm poles; 2048 for
// 1mm poles. For linear encoders this is ticks / mm,
// for rotary encoders this is ticks / revolution.
//#define I2CPE_ENC_1_TICKS_REV (16 * 200) // Only needed for rotary encoders; number of stepper
// steps per full revolution (motor steps/rev * microstepping)
//#define I2CPE_ENC_1_INVERT // Invert the direction of axis travel.
#define I2CPE_ENC_1_EC_METHOD I2CPE_ECM_MICROSTEP // Type of error error correction.
#define I2CPE_ENC_1_EC_THRESH 0.10 // Threshold size for error (in mm) above which the
// printer will attempt to correct the error; errors
// smaller than this are ignored to minimize effects of
// measurement noise / latency (filter).
#define I2CPE_ENC_2_ADDR I2CPE_PRESET_ADDR_Y // Same as above, but for encoder 2.
#define I2CPE_ENC_2_AXIS Y_AXIS
#define I2CPE_ENC_2_TYPE I2CPE_ENC_TYPE_LINEAR
#define I2CPE_ENC_2_TICKS_UNIT 2048
//#define I2CPE_ENC_2_TICKS_REV (16 * 200)
//#define I2CPE_ENC_2_INVERT
#define I2CPE_ENC_2_EC_METHOD I2CPE_ECM_MICROSTEP
#define I2CPE_ENC_2_EC_THRESH 0.10
#define I2CPE_ENC_3_ADDR I2CPE_PRESET_ADDR_Z // Encoder 3. Add additional configuration options
#define I2CPE_ENC_3_AXIS Z_AXIS // as above, or use defaults below.
#define I2CPE_ENC_4_ADDR I2CPE_PRESET_ADDR_E // Encoder 4.
#define I2CPE_ENC_4_AXIS E_AXIS
#define I2CPE_ENC_5_ADDR 34 // Encoder 5.
#define I2CPE_ENC_5_AXIS E_AXIS
// Default settings for encoders which are enabled, but without settings configured above.
#define I2CPE_DEF_TYPE I2CPE_ENC_TYPE_LINEAR
#define I2CPE_DEF_ENC_TICKS_UNIT 2048
#define I2CPE_DEF_TICKS_REV (16 * 200)
#define I2CPE_DEF_EC_METHOD I2CPE_ECM_NONE
#define I2CPE_DEF_EC_THRESH 0.1
//#define I2CPE_ERR_THRESH_ABORT 100.0 // Threshold size for error (in mm) error on any given
// axis after which the printer will abort. Comment out to
// disable abort behavior.
#define I2CPE_TIME_TRUSTED 10000 // After an encoder fault, there must be no further fault
// for this amount of time (in ms) before the encoder
// is trusted again.
/**
* Position is checked every time a new command is executed from the buffer but during long moves,
* this setting determines the minimum update time between checks. A value of 100 works well with
* error rolling average when attempting to correct only for skips and not for vibration.
*/
#define I2CPE_MIN_UPD_TIME_MS 4 // (ms) Minimum time between encoder checks.
// Use a rolling average to identify persistant errors that indicate skips, as opposed to vibration and noise.
#define I2CPE_ERR_ROLLING_AVERAGE
#endif // I2C_POSITION_ENCODERS
/**
* MAX7219 Debug Matrix
*
* Add support for a low-cost 8x8 LED Matrix based on the Max7219 chip as a realtime status display.
* Requires 3 signal wires. Some useful debug options are included to demonstrate its usage.
*/
//#define MAX7219_DEBUG
#if ENABLED(MAX7219_DEBUG)
#define MAX7219_CLK_PIN 64
#define MAX7219_DIN_PIN 57
#define MAX7219_LOAD_PIN 44
//#define MAX7219_GCODE // Add the M7219 G-code to control the LED matrix
#define MAX7219_INIT_TEST 2 // Do a test pattern at initialization (Set to 2 for spiral)
#define MAX7219_NUMBER_UNITS 1 // Number of Max7219 units in chain.
#define MAX7219_ROTATE 0 // Rotate the display clockwise (in multiples of +/- 90°)
// connector at: right=0 bottom=-90 top=90 left=180
//#define MAX7219_REVERSE_ORDER // The individual LED matrix units may be in reversed order
/**
* Sample debug features
* If you add more debug displays, be careful to avoid conflicts!
*/
#define MAX7219_DEBUG_PRINTER_ALIVE // Blink corner LED of 8x8 matrix to show that the firmware is functioning
#define MAX7219_DEBUG_PLANNER_HEAD 3 // Show the planner queue head position on this and the next LED matrix row
#define MAX7219_DEBUG_PLANNER_TAIL 5 // Show the planner queue tail position on this and the next LED matrix row
#define MAX7219_DEBUG_PLANNER_QUEUE 0 // Show the current planner queue depth on this and the next LED matrix row
// If you experience stuttering, reboots, etc. this option can reveal how
// tweaks made to the configuration are affecting the printer in real-time.
#endif
/**
* NanoDLP Sync support
*
* Add support for Synchronized Z moves when using with NanoDLP. G0/G1 axis moves will output "Z_move_comp"
* string to enable synchronization with DLP projector exposure. This change will allow to use
* [[WaitForDoneMessage]] instead of populating your gcode with M400 commands
*/
//#define NANODLP_Z_SYNC
#if ENABLED(NANODLP_Z_SYNC)
//#define NANODLP_ALL_AXIS // Enables "Z_move_comp" output on any axis move.
// Default behavior is limited to Z axis only.
#endif
/**
* WiFi Support (Espressif ESP32 WiFi)
*/
//#define WIFISUPPORT
#if ENABLED(WIFISUPPORT)
#define WIFI_SSID "Wifi SSID"
#define WIFI_PWD "Wifi Password"
//#define WEBSUPPORT // Start a webserver with auto-discovery
//#define OTASUPPORT // Support over-the-air firmware updates
#endif
/**
* Prusa Multi-Material Unit v2
* Enable in Configuration.h
*/
#if ENABLED(PRUSA_MMU2)
// Serial port used for communication with MMU2.
// For AVR enable the UART port used for the MMU. (e.g., internalSerial)
// For 32-bit boards check your HAL for available serial ports. (e.g., Serial2)
#define INTERNAL_SERIAL_PORT 2
#define MMU2_SERIAL internalSerial
// Use hardware reset for MMU if a pin is defined for it
//#define MMU2_RST_PIN 23
// Enable if the MMU2 has 12V stepper motors (MMU2 Firmware 1.0.2 and up)
//#define MMU2_MODE_12V
// G-code to execute when MMU2 F.I.N.D.A. probe detects filament runout
#define MMU2_FILAMENT_RUNOUT_SCRIPT "M600"
// Add an LCD menu for MMU2
//#define MMU2_MENUS
#if ENABLED(MMU2_MENUS)
// Settings for filament load / unload from the LCD menu.
// This is for Prusa MK3-style extruders. Customize for your hardware.
#define MMU2_FILAMENTCHANGE_EJECT_FEED 80.0
#define MMU2_LOAD_TO_NOZZLE_SEQUENCE \
{ 7.2, 562 }, \
{ 14.4, 871 }, \
{ 36.0, 1393 }, \
{ 14.4, 871 }, \
{ 50.0, 198 }
#define MMU2_RAMMING_SEQUENCE \
{ 1.0, 1000 }, \
{ 1.0, 1500 }, \
{ 2.0, 2000 }, \
{ 1.5, 3000 }, \
{ 2.5, 4000 }, \
{ -15.0, 5000 }, \
{ -14.0, 1200 }, \
{ -6.0, 600 }, \
{ 10.0, 700 }, \
{ -10.0, 400 }, \
{ -50.0, 2000 }
#endif
//#define MMU2_DEBUG // Write debug info to serial output
#endif // PRUSA_MMU2
/**
* Advanced Print Counter settings
*/
#if ENABLED(PRINTCOUNTER)
#define SERVICE_WARNING_BUZZES 3
// Activate up to 3 service interval watchdogs
//#define SERVICE_NAME_1 "Service S"
//#define SERVICE_INTERVAL_1 100 // print hours
//#define SERVICE_NAME_2 "Service L"
//#define SERVICE_INTERVAL_2 200 // print hours
//#define SERVICE_NAME_3 "Service 3"
//#define SERVICE_INTERVAL_3 1 // print hours
#endif
// @section develop
/**
* M43 - display pin status, watch pins for changes, watch endstops & toggle LED, Z servo probe test, toggle pins
*/
//#define PINS_DEBUGGING
// Enable Marlin dev mode which adds some special commands
//#define MARLIN_DEV_MODE
| teemuatlut/Marlin | config/examples/BQ/WITBOX/Configuration_adv.h | C | gpl-3.0 | 96,700 |
package uk.ac.exeter.QuinCe.data.Dataset;
import java.sql.Connection;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import uk.ac.exeter.QuinCe.data.Instrument.Instrument;
import uk.ac.exeter.QuinCe.data.Instrument.SensorDefinition.SensorType;
import uk.ac.exeter.QuinCe.data.Instrument.SensorDefinition.Variable;
public class RunTypeMeasurementLocator extends MeasurementLocator {
@Override
public List<Measurement> locateMeasurements(Connection conn,
Instrument instrument, DataSet dataset) throws MeasurementLocatorException {
try {
// Get the run types for the dataset, along with the times that they are
// set
TreeMap<LocalDateTime, String> runTypes = new TreeMap<LocalDateTime, String>();
List<SensorValue> runTypeSensorValues = DataSetDataDB
.getSensorValuesForColumns(conn, dataset.getId(),
instrument.getSensorAssignments().getRunTypeColumnIDs());
runTypeSensorValues.forEach(v -> runTypes.put(v.getTime(), v.getValue()));
Set<Long> measurementColumnIds = new HashSet<Long>();
for (Variable variable : instrument.getVariables()) {
if (variable.hasInternalCalibrations()) {
List<SensorType> coreSensorTypes = variable.getCoreSensorTypes();
if (coreSensorTypes.size() > 0) {
List<Long> columns = instrument.getSensorAssignments()
.getColumnIds(coreSensorTypes);
measurementColumnIds.addAll(columns);
} else {
// If there's no core sensor type, use any of the sensor values
for (SensorType sensorType : variable.getAllSensorTypes(false)) {
List<Long> columns = instrument.getSensorAssignments()
.getColumnIds(sensorType);
measurementColumnIds.addAll(columns);
}
}
}
}
List<SensorValue> sensorValues = DataSetDataDB.getSensorValuesForColumns(
conn, dataset.getId(), new ArrayList<Long>(measurementColumnIds));
// Now log all the times as new measurements, with the run type from the
// same time or immediately before.
List<Measurement> measurements = new ArrayList<Measurement>(
sensorValues.size());
ArrayList<LocalDateTime> runTypeTimes = null;
if (null != runTypes) {
runTypeTimes = new ArrayList<LocalDateTime>(runTypes.keySet());
}
int currentRunTypeTime = 0;
for (SensorValue sensorValue : sensorValues) {
if (null != sensorValue.getValue()) {
LocalDateTime measurementTime = sensorValue.getTime();
// Get the run type for this measurement
String runType = null;
if (null != runTypes) {
// Find the run type immediately before or at the same time as the
// measurement
if (runTypeTimes.get(currentRunTypeTime).isAfter(measurementTime)) {
// There is no run type for this measurement. This isn't allowed!
throw new MeasurementLocatorException(
"No run type available in Dataset " + dataset.getId()
+ " at time " + measurementTime.toString());
} else {
while (currentRunTypeTime < runTypeTimes.size() - 1
&& runTypeTimes.get(currentRunTypeTime)
.isBefore(measurementTime)) {
currentRunTypeTime++;
}
runType = runTypes.get(runTypeTimes.get(currentRunTypeTime));
}
}
Map<Long, String> runTypeMap = new HashMap<Long, String>();
runTypeMap.put(Measurement.GENERIC_RUN_TYPE_VARIABLE, runType);
measurements
.add(new Measurement(dataset.getId(), measurementTime, runTypeMap));
}
}
return measurements;
} catch (Exception e) {
throw new MeasurementLocatorException(e);
}
}
}
| squaregoldfish/QuinCe | WebApp/src/uk/ac/exeter/QuinCe/data/Dataset/RunTypeMeasurementLocator.java | Java | gpl-3.0 | 4,041 |
###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) Crossbar.io Technologies GmbH
#
# 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.
#
###############################################################################
from __future__ import absolute_import
import os
# we need to select a txaio subsystem because we're importing the base
# protocol classes here for testing purposes. "normally" you'd import
# from autobahn.twisted.wamp or autobahn.asyncio.wamp explicitly.
import txaio
if os.environ.get('USE_TWISTED', False):
txaio.use_twisted()
else:
txaio.use_asyncio()
from autobahn import wamp
from autobahn.wamp import message
from autobahn.wamp import exception
from autobahn.wamp import protocol
import unittest2 as unittest
class TestPeerExceptions(unittest.TestCase):
def test_exception_from_message(self):
session = protocol.BaseSession()
@wamp.error(u"com.myapp.error1")
class AppError1(Exception):
pass
@wamp.error(u"com.myapp.error2")
class AppError2(Exception):
pass
session.define(AppError1)
session.define(AppError2)
# map defined errors to user exceptions
emsg = message.Error(message.Call.MESSAGE_TYPE, 123456, u'com.myapp.error1')
exc = session._exception_from_message(emsg)
self.assertIsInstance(exc, AppError1)
self.assertEqual(exc.args, ())
emsg = message.Error(message.Call.MESSAGE_TYPE, 123456, u'com.myapp.error2')
exc = session._exception_from_message(emsg)
self.assertIsInstance(exc, AppError2)
self.assertEqual(exc.args, ())
# map undefined error to (generic) exception
emsg = message.Error(message.Call.MESSAGE_TYPE, 123456, u'com.myapp.error3')
exc = session._exception_from_message(emsg)
self.assertIsInstance(exc, exception.ApplicationError)
self.assertEqual(exc.error, u'com.myapp.error3')
self.assertEqual(exc.args, ())
self.assertEqual(exc.kwargs, {})
emsg = message.Error(message.Call.MESSAGE_TYPE, 123456, u'com.myapp.error3', args=[1, 2, u'hello'])
exc = session._exception_from_message(emsg)
self.assertIsInstance(exc, exception.ApplicationError)
self.assertEqual(exc.error, u'com.myapp.error3')
self.assertEqual(exc.args, (1, 2, u'hello'))
self.assertEqual(exc.kwargs, {})
emsg = message.Error(message.Call.MESSAGE_TYPE, 123456, u'com.myapp.error3', args=[1, 2, u'hello'], kwargs={u'foo': 23, u'bar': u'baz'})
exc = session._exception_from_message(emsg)
self.assertIsInstance(exc, exception.ApplicationError)
self.assertEqual(exc.error, u'com.myapp.error3')
self.assertEqual(exc.args, (1, 2, u'hello'))
self.assertEqual(exc.kwargs, {u'foo': 23, u'bar': u'baz'})
def test_message_from_exception(self):
session = protocol.BaseSession()
@wamp.error(u"com.myapp.error1")
class AppError1(Exception):
pass
@wamp.error(u"com.myapp.error2")
class AppError2(Exception):
pass
session.define(AppError1)
session.define(AppError2)
exc = AppError1()
msg = session._message_from_exception(message.Call.MESSAGE_TYPE, 123456, exc)
self.assertEqual(msg.marshal(), [message.Error.MESSAGE_TYPE, message.Call.MESSAGE_TYPE, 123456, {}, "com.myapp.error1"])
| technologiescollege/Blockly-rduino-communication | scripts_XP/Lib/site-packages/autobahn/wamp/test/test_protocol_peer.py | Python | gpl-3.0 | 4,497 |
/*
* Bonjour based service discovery
* Copyright (C) 2009 Mattias Wadman
*
* 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/>.
*/
#ifndef BONJOUR_H__
#define BONJOUR_H__
void bonjour_init(void);
#endif | daedalus/showtime | src/sd/bonjour.h | C | gpl-3.0 | 814 |
package breakDancer;
###################################################################################################################################
#
# Copyright 2014-2018 IRD-CIRAD-INRA-ADNid
#
# 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/> or
# write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
# You should have received a copy of the CeCILL-C license with this program.
#If not see <http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.txt>
#
# Intellectual property belongs to IRD, CIRAD and South Green developpement plateform for all versions also for ADNid for v2 and v3 and INRA for v3
# Version 1 written by Cecile Monat, Ayite Kougbeadjo, Christine Tranchant, Cedric Farcy, Mawusse Agbessi, Maryline Summo, and Francois Sabot
# Version 2 written by Cecile Monat, Christine Tranchant, Cedric Farcy, Enrique Ortega-Abboud, Julie Orjuela-Bouniol, Sebastien Ravel, Souhila Amanzougarene, and Francois Sabot
# Version 3 written by Cecile Monat, Christine Tranchant, Laura Helou, Abdoulaye Diallo, Julie Orjuela-Bouniol, Sebastien Ravel, Gautier Sarah, and Francois Sabot
#
###################################################################################################################################
use strict;
use warnings;
use localConfig;
use toolbox;
use checkFormat;
use Data::Dumper;
use Switch;
sub bam2cfg
{
my($listOfBam,$breakDancerConfigFile,$optionsHachees)=@_;
##debug toolbox::exportLog("FILES: ".Dumper($listOfBam), 2);
if (@{$listOfBam})
{ ##Check if entry file exist and is not empty
my $bamFiles_names="";
foreach my $file (@{$listOfBam}) # for each BAM file(s)
{
##DEBUG
toolbox::exportLog("FILE: $file", 2);
if (checkFormat::checkFormatSamOrBam($file)==2 and toolbox::sizeFile($file)==1) # if current file is not empty
{
$bamFiles_names.=" ".$file." "; # recovery of informations fo command line used later
}
else # if current file is empty
{
toolbox::exportLog("ERROR: breakDancer::bam2cfg : The file $file is uncorrect\n", 0); # returns the error message
return 0;
}
}
my $options="";
if ($optionsHachees) {
$options=toolbox::extractOptions($optionsHachees); ##Get given options
}
my $command=$bam2cfg." ".$options." ".$bamFiles_names." > ".$breakDancerConfigFile;
#toolbox::exportLog($command."\n",1);
#Execute command
if(toolbox::run($command)==1)
{
return 1;#Command Ok
}
else
{
toolbox::exportLog("ERROR: breakDancer::bam2cfg : Uncorrectly done\n",0);
return 0;#Command not Ok
}
}
else
{
toolbox::exportLog("ERROR: breakDancer::bam2cfg : The list of bam is uncorrect\n",0);
return 0;#File not Ok
}
}
sub breakDancer
{
my($breakDancerConfigFile,$outputFile, $optionsHachees)=@_;
if (toolbox::sizeFile($breakDancerConfigFile)==1)
{ ##Check if entry file exist and is not empty
my $options="";
if ($optionsHachees)
{
$options=toolbox::extractOptions($optionsHachees); ##Get given options
}
my $command=$breakDancer." ".$options." ".$breakDancerConfigFile." > ".$outputFile ;
#toolbox::exportLog($command."\n",1);
#Execute command
if(toolbox::run($command)==1)
{
return 1;#Command Ok
}
else
{
toolbox::exportLog("ERROR: breakDancer::breakDancer : Uncorrectly done\n",0);
return 0;#Command not Ok
}
}
else
{
toolbox::exportLog("ERROR: breakDancer::breakDancer : The file $breakDancerConfigFile is uncorrect\n",0);
return 0;#File not Ok
}
}
1; | SouthGreenPlatform/TOGGLE-DEV | modules/breakDancer.pm | Perl | gpl-3.0 | 4,595 |
<?php
/**
* MyBB 1.8
* Copyright 2014 MyBB Group, All Rights Reserved
*
* Website: http://www.mybb.com
* License: http://www.mybb.com/about/license
*
*/
/**
* APC Cache Handler
*/
class apcCacheHandler
{
/**
* Unique identifier representing this copy of MyBB
*/
public $unique_id;
function __construct($silent=false)
{
global $mybb;
if(!function_exists("apc_fetch"))
{
// Check if our DB engine is loaded
if(!extension_loaded("apc"))
{
// Throw our super awesome cache loading error
$mybb->trigger_generic_error("apc_load_error");
die;
}
}
return false;
}
/**
* Connect and initialize this handler.
*
* @return boolean True if successful, false on failure
*/
function connect()
{
global $mybb;
// Set a unique identifier for all queries in case other forums on this server also use this cache handler
$this->unique_id = md5(MYBB_ROOT);
return true;
}
/**
* Connect and initialize this handler.
*
* @return boolean True if successful, false on failure
*/
function fetch($name, $hard_refresh=false)
{
if(apc_exists($this->unique_id."_".$name))
{
$data = apc_fetch($this->unique_id."_".$name);
return unserialize($data);
}
return false;
}
/**
* Write an item to the cache.
*
* @param string The name of the cache
* @param mixed The data to write to the cache item
* @return boolean True on success, false on failure
*/
function put($name, $contents)
{
$status = apc_store($this->unique_id."_".$name, serialize($contents));
return $status;
}
/**
* Delete a cache
*
* @param string The name of the cache
* @return boolean True on success, false on failure
*/
function delete($name)
{
return apc_delete($this->unique_id."_".$name);
}
/**
* Disconnect from the cache
*/
function disconnect()
{
return true;
}
function size_of($name)
{
global $lang;
return $lang->na;
}
}
| Dhahl/ii_live | forum/inc/cachehandlers/apc.php | PHP | gpl-3.0 | 1,929 |
-----------------------------------
--
-- Zone: Chocobo_Circuit
--
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Chocobo_Circuit/TextIDs"] = nil;
require("scripts/zones/Chocobo_Circuit/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(102,0,-77,247);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Chocobo_Circuit/Zone.lua | Lua | gpl-3.0 | 1,203 |
/* -*- c++ -*- */
/*
* Copyright 2016 <+YOU OR YOUR COMPANY+>.
*
* This 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, or (at your option)
* any later version.
*
* This software 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 software; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street,
* Boston, MA 02110-1301, USA.
*/
#ifndef INCLUDED_XCORR_CAPON_CCF_H
#define INCLUDED_XCORR_CAPON_CCF_H
#include <xcorr/api.h>
#include <gnuradio/sync_block.h>
namespace gr {
namespace xcorr {
/*!
* \brief <+description of block+>
* \ingroup xcorr
*
*/
class XCORR_API capon_ccf : virtual public gr::sync_block
{
public:
typedef boost::shared_ptr<capon_ccf> sptr;
/*!
* \brief Return a shared_ptr to a new instance of xcorr::capon_ccf.
*
* To avoid accidental use of raw pointers, xcorr::capon_ccf's
* constructor is in a private implementation
* class. xcorr::capon_ccf::make is the public interface for
* creating new instances.
*/
static sptr make(int vector_size);
};
} // namespace xcorr
} // namespace gr
#endif /* INCLUDED_XCORR_CAPON_CCF_H */
| jakapoor/AMRUPT | Software/Angle of Arrival/gr-xcorr/include/xcorr/capon_ccf.h | C | gpl-3.0 | 1,623 |
/*
--------------------------------------------------------------------------------
SPADE - Support for Provenance Auditing in Distributed Environments.
Copyright (C) 2015 SRI International
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/>.
--------------------------------------------------------------------------------
*/
package spade.core;
import java.io.Serializable;
import java.util.Map;
/**
* This is the base class for sketches.
*
* @author Dawood Tariq
*/
public abstract class AbstractSketch implements Serializable {
/**
* The matrix filter belonging to this sketch.
*/
public MatrixFilter matrixFilter;
/**
* A generic map used to store objects for various purposes (querying, etc.)
*/
public Map<String, Object> objects;
/**
* This method is triggered when the sketch receives a vertex.
*
* @param incomingVertex The vertex received by this sketch.
*/
public abstract void putVertex(AbstractVertex incomingVertex);
/**
* This method is triggered when the sketch receives an edge.
*
* @param incomingEdge The edge received by this sketch.
*/
public abstract void putEdge(AbstractEdge incomingEdge);
}
| sranasir/SPADE | src/spade/core/AbstractSketch.java | Java | gpl-3.0 | 1,792 |
from service import ccnet_rpc, monitor_rpc, seafserv_rpc, \
seafserv_threaded_rpc, ccnet_threaded_rpc
"""
WebAccess:
string repo_id
string obj_id
string op
string username
"""
class SeafileAPI(object):
def __init__(self):
pass
# fileserver token
def get_fileserver_access_token(self, repo_id, obj_id, op, username):
"""Generate token for access file/dir in fileserver
op: the operation, 'view', 'download', 'download-dir'
Return: the access token in string
"""
return seafserv_rpc.web_get_access_token(repo_id, obj_id, op, username)
def query_fileserver_access_token(self, token):
"""Get the WebAccess object
token: the access token in string
Return: the WebAccess object
"""
return seafserv_rpc.web_query_access_token(token)
# password
def is_password_set(self, repo_id, username):
return seafserv_rpc.is_passwd_set(repo_id, username)
def get_decrypt_key(self, repo_id, username):
return seafserv_rpc.get_decrypt_key(repo_id, username)
# repo manipulation
def create_repo(self, name, desc, username, passwd):
return seafserv_threaded_rpc.create_repo(name, desc, username, passwd)
def create_enc_repo(self, repo_id, name, desc, username, magic, random_key, enc_version):
return seafserv_threaded_rpc.create_enc_repo(repo_id, name, desc, username, magic, random_key, enc_version)
def get_repo(self, repo_id):
return seafserv_threaded_rpc.get_repo(repo_id)
def remove_repo(self, repo_id):
return seafserv_threaded_rpc.remove_repo(repo_id)
def get_repo_list(self, start, limit):
return seafserv_threaded_rpc.get_repo_list(start, limit)
def edit_repo(self, repo_id, name, description, username):
return seafserv_threaded_rpc.edit_repo(repo_id, name, description, username)
def is_repo_owner(self, username, repo_id):
return seafserv_threaded_rpc.is_repo_owner(username, repo_id)
def set_repo_owner(self, email, repo_id):
return seafserv_threaded_rpc.set_repo_owner(email, repo_id)
def get_repo_owner(self, repo_id):
return seafserv_threaded_rpc.get_repo_owner(repo_id)
def get_owned_repo_list(self, username):
return seafserv_threaded_rpc.list_owned_repos(username)
def get_orphan_repo_list(self):
return seafserv_threaded_rpc.get_orphan_repo_list()
def get_repo_size(self, repo_id):
return seafserv_threaded_rpc.server_repo_size(repo_id)
def revert_repo(self, repo_id, commit_id, username):
return seafserv_threaded_rpc.revert_on_server(repo_id, commit_id, username)
def diff_commits(self, repo_id, old_commit, new_commit):
return seafserv_threaded_rpc.get_diff(repo_id, old_commit, new_commit)
def get_commit_list(self, repo_id, offset, limit):
return seafserv_threaded_rpc.get_commit_list(repo_id, offset, limit)
# repo permission checking
def check_repo_access_permission(self, repo_id, username):
"""
Returns 'rw', 'r' or None
"""
return seafserv_threaded_rpc.check_permission(repo_id, username)
# file/dir
def post_file(self, repo_id, tmp_file_path, parent_dir, filename, username):
"""Add a file to a directory"""
return seafserv_threaded_rpc.post_file(repo_id, tmp_file_path, parent_dir,
filename, username)
def post_empty_file(self, repo_id, parent_dir, filename, username):
return seafserv_threaded_rpc.post_empty_file(repo_id, parent_dir,
filename, username)
def put_file(self, repo_id, tmp_file_path, parent_dir, filename,
username, head_id):
"""Update an existing file
head_id: the original commit id of the old file
"""
return seafserv_threaded_rpc.put_file(repo_id, tmp_file_path, parent_dir,
filename, username, head_id)
def del_file(self, repo_id, parent_dir, filename, username):
return seafserv_threaded_rpc.del_file(repo_id, parent_dir, filename, username)
def copy_file(self, src_repo, src_dir, src_filename, dst_repo,
dst_dir, dst_filename, username, need_progress, synchronous=0):
return seafserv_threaded_rpc.copy_file(src_repo, src_dir, src_filename,
dst_repo, dst_dir, dst_filename,
username, need_progress, synchronous)
def move_file(self, src_repo, src_dir, src_filename, dst_repo, dst_dir,
dst_filename, username, need_progress, synchronous=0):
return seafserv_threaded_rpc.move_file(src_repo, src_dir, src_filename,
dst_repo, dst_dir, dst_filename,
username, need_progress, synchronous)
def get_copy_task(self, task_id):
return seafserv_rpc.get_copy_task(task_id)
def cancel_copy_task(self, task_id):
return seafserv_rpc.cancel_copy_task(task_id)
def rename_file(self, repo_id, parent_dir, oldname, newname, username):
return seafserv_threaded_rpc.rename_file(repo_id, parent_dir,
oldname, newname, username)
def is_valid_filename(self, repo_id, filename):
return seafserv_threaded_rpc.is_valid_filename(repo_id, filename)
def get_file_size(self, store_id, version, file_id):
return seafserv_threaded_rpc.get_file_size(store_id, version, file_id)
def get_file_id_by_path(self, repo_id, path):
return seafserv_threaded_rpc.get_file_id_by_path(repo_id, path)
def get_file_id_by_commit_and_path(self, repo_id, commit_id, path):
return seafserv_threaded_rpc.get_file_id_by_commit_and_path(repo_id,
commit_id, path)
def get_file_revisions(self, repo_id, path, max_revision, limit):
return seafserv_threaded_rpc.list_file_revisions(repo_id, path,
max_revision, limit)
def get_files_last_modified(self, repo_id, parent_dir, limit):
"""Get last modification time for files in a dir
limit: the max number of commits to analyze
"""
return seafserv_threaded_rpc.calc_files_last_modified(repo_id,
parent_dir, limit)
def post_dir(self, repo_id, parent_dir, dirname, username):
"""Add a directory"""
return seafserv_threaded_rpc.post_dir(repo_id, parent_dir, dirname, username)
def list_file_by_file_id(self, repo_id, file_id, offset=-1, limit=-1):
return seafserv_threaded_rpc.list_file(repo_id, file_id, offset, limit)
def get_dir_id_by_path(self, repo_id, path):
return seafserv_threaded_rpc.get_dir_id_by_path(repo_id, path)
def list_dir_by_dir_id(self, repo_id, dir_id, offset=-1, limit=-1):
return seafserv_threaded_rpc.list_dir(repo_id, dir_id, offset, limit)
def list_dir_by_path(self, repo_id, path, offset=-1, limit=-1):
dir_id = seafserv_threaded_rpc.get_dir_id_by_path(repo_id, path)
return seafserv_threaded_rpc.list_dir(repo_id, dir_id, offset, limit)
def list_dir_by_commit_and_path(self, repo_id,
commit_id, path, offset=-1, limit=-1):
dir_id = seafserv_threaded_rpc.get_dirid_by_path(repo_id, commit_id, path)
return seafserv_threaded_rpc.list_dir(repo_id, dir_id, offset, limit)
def get_dir_id_by_commit_and_path(self, repo_id, commit_id, path):
return seafserv_threaded_rpc.get_dirid_by_path(repo_id, commit_id, path)
def revert_file(self, repo_id, commit_id, path, username):
return seafserv_threaded_rpc.revert_file(repo_id, commit_id, path, username)
def revert_dir(self, repo_id, commit_id, path, username):
return seafserv_threaded_rpc.revert_dir(repo_id, commit_id, path, username)
def get_deleted(self, repo_id, show_days):
return seafserv_threaded_rpc.get_deleted(repo_id, show_days)
# share repo to user
def share_repo(self, repo_id, from_username, to_username, permission):
return seafserv_threaded_rpc.add_share(repo_id, from_username,
to_username, permission)
def get_share_out_repo_list(self, username, start, limit):
return seafserv_threaded_rpc.list_share_repos(username, "from_email",
start, limit)
def get_share_in_repo_list(self, username, start, limit):
return seafserv_threaded_rpc.list_share_repos(username, "to_email",
start, limit)
def remove_share(self, repo_id, from_username, to_username):
return seafserv_threaded_rpc.remove_share(repo_id, from_username,
to_username)
def set_share_permission(self, repo_id, from_username, to_username, permission):
return seafserv_threaded_rpc.set_share_permission(repo_id, from_username,
to_username, permission)
# share repo to group
def group_share_repo(self, repo_id, group_id, username, permission):
# deprecated, use ``set_group_repo``
return seafserv_threaded_rpc.group_share_repo(repo_id, group_id,
username, permission)
def set_group_repo(self, repo_id, group_id, username, permission):
return seafserv_threaded_rpc.group_share_repo(repo_id, group_id,
username, permission)
def group_unshare_repo(self, repo_id, group_id, username):
# deprecated, use ``unset_group_repo``
return seafserv_threaded_rpc.group_unshare_repo(repo_id, group_id, username)
def unset_group_repo(self, repo_id, group_id, username):
return seafserv_threaded_rpc.group_unshare_repo(repo_id, group_id, username)
def get_shared_groups_by_repo(self, repo_id):
return seafserv_threaded_rpc.get_shared_groups_by_repo(repo_id)
def get_group_repoids(self, group_id):
"""
Return the list of group repo ids
"""
repo_ids = seafserv_threaded_rpc.get_group_repoids(group_id)
if not repo_ids:
return []
l = []
for repo_id in repo_ids.split("\n"):
if repo_id == '':
continue
l.append(repo_id)
return l
def get_group_repo_list(self, group_id):
ret = []
for repo_id in self.get_group_repoids(group_id):
r = self.get_repo(repo_id)
if r is None:
continue
ret.append(r)
return ret
def get_group_repos_by_owner(self, username):
return seafserv_threaded_rpc.get_group_repos_by_owner(username)
def set_group_repo_permission(self, group_id, repo_id, permission):
return seafserv_threaded_rpc.set_group_repo_permission(group_id, repo_id,
permission)
# token
def generate_repo_token(self, repo_id, username):
"""Generate a token for sync a repo
"""
return seafserv_threaded_rpc.generate_repo_token(repo_id, username)
def delete_repo_token(self, repo_id, token, user):
return seafserv_threaded_rpc.delete_repo_token(repo_id, token, user)
def list_repo_tokens(self, repo_id):
return seafserv_threaded_rpc.list_repo_tokens(repo_id)
def list_repo_tokens_by_email(self, username):
return seafserv_threaded_rpc.list_repo_tokens_by_email(username)
# quota
def get_user_self_usage(self, username):
"""Get the sum of repos' size of the user"""
return seafserv_threaded_rpc.get_user_quota_usage(username)
def get_user_share_usage(self, username):
return seafserv_threaded_rpc.get_user_share_usage(username)
def get_user_quota(self, username):
return seafserv_threaded_rpc.get_user_quota(username)
def set_user_quota(self, username, quota):
return seafserv_threaded_rpc.set_user_quota(username, quota)
def check_quota(self, repo_id):
pass
# password management
def check_passwd(self, repo_id, magic):
return seafserv_threaded_rpc.check_passwd(repo_id, magic)
def set_passwd(self, repo_id, user, passwd):
return seafserv_threaded_rpc.set_passwd(repo_id, user, passwd)
def unset_passwd(self, repo_id, user, passwd):
return seafserv_threaded_rpc.unset_passwd(repo_id, user, passwd)
# organization wide repo
def add_inner_pub_repo(self, repo_id, permission):
return seafserv_threaded_rpc.set_inner_pub_repo(repo_id, permission)
def remove_inner_pub_repo(self, repo_id):
return seafserv_threaded_rpc.unset_inner_pub_repo(repo_id)
def get_inner_pub_repo_list(self):
return seafserv_threaded_rpc.list_inner_pub_repos()
def count_inner_pub_repos(self):
return seafserv_threaded_rpc.count_inner_pub_repos()
def is_inner_pub_repo(self, repo_id):
return seafserv_threaded_rpc.is_inner_pub_repo(repo_id)
# permission
def check_permission(self, repo_id, user):
return seafserv_threaded_rpc.check_permission(repo_id, user)
# virtual repo
def create_virtual_repo(self, origin_repo_id, path, repo_name, repo_desc, owner):
return seafserv_threaded_rpc.create_virtual_repo(origin_repo_id,
path,
repo_name,
repo_desc,
owner)
def get_virtual_repos_by_owner(self, owner):
return seafserv_threaded_rpc.get_virtual_repos_by_owner(owner)
# @path must begin with '/', e.g. '/example'
def get_virtual_repo(self, origin_repo, path, owner):
return seafserv_threaded_rpc.get_virtual_repo(origin_repo, path, owner)
def change_repo_passwd(self, repo_id, old_passwd, new_passwd, user):
return seafserv_threaded_rpc.change_repo_passwd(repo_id, old_passwd,
new_passwd, user)
def delete_repo_tokens_by_peer_id(self, username, device_id):
return seafserv_threaded_rpc.delete_repo_tokens_by_peer_id(username, device_id)
seafile_api = SeafileAPI()
| yubobo/seafile | python/seaserv/api.py | Python | gpl-3.0 | 14,807 |
/**
* tinymce.js
*
* Copyright 2009, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
(function(win) {
var whiteSpaceRe = /^\s*|\s*$/g,
undefined, isRegExpBroken = 'B'.replace(/A(.)|B/, '$1') === '$1';
/**
* Core namespace with core functionality for the TinyMCE API all sub classes will be added to this namespace/object.
*
* @static
* @class tinymce
* @example
* // Using each method
* tinymce.each([1, 2, 3], function(v, i) {
* console.log(i + '=' + v);
* });
*
* // Checking for a specific browser
* if (tinymce.isIE)
* console.log("IE");
*/
var tinymce = {
/**
* Major version of TinyMCE build.
*
* @property majorVersion
* @type String
*/
majorVersion : '@@tinymce_major_version@@',
/**
* Major version of TinyMCE build.
*
* @property minorVersion
* @type String
*/
minorVersion : '@@tinymce_minor_version@@',
/**
* Release date of TinyMCE build.
*
* @property releaseDate
* @type String
*/
releaseDate : '@@tinymce_release_date@@',
/**
* Initializes the TinyMCE global namespace this will setup browser detection and figure out where TinyMCE is running from.
*/
_init : function() {
var t = this, d = document, na = navigator, ua = na.userAgent, i, nl, n, base, p, v;
/**
* Constant that is true if the browser is Opera.
*
* @property isOpera
* @type Boolean
* @final
*/
t.isOpera = win.opera && opera.buildNumber;
/**
* Constant that is true if the browser is WebKit (Safari/Chrome).
*
* @property isWebKit
* @type Boolean
* @final
*/
t.isWebKit = /WebKit/.test(ua);
/**
* Constant that is true if the browser is IE.
*
* @property isIE
* @type Boolean
* @final
*/
t.isIE = !t.isWebKit && !t.isOpera && (/MSIE/gi).test(ua) && (/Explorer/gi).test(na.appName);
/**
* Constant that is true if the browser is IE 6 or older.
*
* @property isIE6
* @type Boolean
* @final
*/
t.isIE6 = t.isIE && /MSIE [56]/.test(ua);
/**
* Constant that is true if the browser is Gecko.
*
* @property isGecko
* @type Boolean
* @final
*/
t.isGecko = !t.isWebKit && /Gecko/.test(ua);
/**
* Constant that is true if the os is Mac OS.
*
* @property isMac
* @type Boolean
* @final
*/
t.isMac = ua.indexOf('Mac') != -1;
/**
* Constant that is true if the runtime is Adobe Air.
*
* @property isAir
* @type Boolean
* @final
*/
t.isAir = /adobeair/i.test(ua);
/**
* Constant that tells if the current browser is an iPhone or iPad.
*
* @property isIDevice
* @type Boolean
* @final
*/
t.isIDevice = /(iPad|iPhone)/.test(ua);
// TinyMCE .NET webcontrol might be setting the values for TinyMCE
if (win.tinyMCEPreInit) {
t.suffix = tinyMCEPreInit.suffix;
t.baseURL = tinyMCEPreInit.base;
t.query = tinyMCEPreInit.query;
return;
}
// Get suffix and base
t.suffix = '';
// If base element found, add that infront of baseURL
nl = d.getElementsByTagName('base');
for (i=0; i<nl.length; i++) {
if (v = nl[i].href) {
// Host only value like http://site.com or http://site.com:8008
if (/^https?:\/\/[^\/]+$/.test(v))
v += '/';
base = v ? v.match(/.*\//)[0] : ''; // Get only directory
}
}
function getBase(n) {
if (n.src && /tiny_mce(|_gzip|_jquery|_prototype|_full)(_dev|_src)?.js/.test(n.src)) {
if (/_(src|dev)\.js/g.test(n.src))
t.suffix = '_src';
if ((p = n.src.indexOf('?')) != -1)
t.query = n.src.substring(p + 1);
t.baseURL = n.src.substring(0, n.src.lastIndexOf('/'));
// If path to script is relative and a base href was found add that one infront
// the src property will always be an absolute one on non IE browsers and IE 8
// so this logic will basically only be executed on older IE versions
if (base && t.baseURL.indexOf('://') == -1 && t.baseURL.indexOf('/') !== 0)
t.baseURL = base + t.baseURL;
return t.baseURL;
}
return null;
};
// Check document
nl = d.getElementsByTagName('script');
for (i=0; i<nl.length; i++) {
if (getBase(nl[i]))
return;
}
// Check head
n = d.getElementsByTagName('head')[0];
if (n) {
nl = n.getElementsByTagName('script');
for (i=0; i<nl.length; i++) {
if (getBase(nl[i]))
return;
}
}
return;
},
/**
* Checks if a object is of a specific type for example an array.
*
* @method is
* @param {Object} o Object to check type of.
* @param {string} t Optional type to check for.
* @return {Boolean} true/false if the object is of the specified type.
*/
is : function(o, t) {
if (!t)
return o !== undefined;
if (t == 'array' && (o.hasOwnProperty && o instanceof Array))
return true;
return typeof(o) == t;
},
/**
* Performs an iteration of all items in a collection such as an object or array. This method will execure the
* callback function for each item in the collection, if the callback returns false the iteration will terminate.
* The callback has the following format: cb(value, key_or_index).
*
* @method each
* @param {Object} o Collection to iterate.
* @param {function} cb Callback function to execute for each item.
* @param {Object} s Optional scope to execute the callback in.
* @example
* tinymce.each([1, 2, 3], function(v, i) {
* console.log(i + '=' + v);
* });
*/
each : function(o, cb, s) {
var n, l;
if (!o)
return 0;
s = s || o;
if (o.length !== undefined) {
// Indexed arrays, needed for Safari
for (n=0, l = o.length; n < l; n++) {
if (cb.call(s, o[n], n, o) === false)
return 0;
}
} else {
// Hashtables
for (n in o) {
if (o.hasOwnProperty(n)) {
if (cb.call(s, o[n], n, o) === false)
return 0;
}
}
}
return 1;
},
// #ifndef jquery
/**
* Creates a new array by the return value of each iteration function call. This enables you to convert
* one array list into another.
*
* @method map
* @param {Array} a Array of items to iterate.
* @param {function} f Function to call for each item. It's return value will be the new value.
* @return {Array} Array with new values based on function return values.
*/
map : function(a, f) {
var o = [];
tinymce.each(a, function(v) {
o.push(f(v));
});
return o;
},
/**
* Filters out items from the input array by calling the specified function for each item.
* If the function returns false the item will be excluded if it returns true it will be included.
*
* @method grep
* @param {Array} a Array of items to loop though.
* @param {function} f Function to call for each item. Include/exclude depends on it's return value.
* @return {Array} New array with values imported and filtered based in input.
*/
grep : function(a, f) {
var o = [];
tinymce.each(a, function(v) {
if (!f || f(v))
o.push(v);
});
return o;
},
/**
* Returns the index of a value in an array, this method will return -1 if the item wasn't found.
*
* @method inArray
* @param {Array} a Array/Object to search for value in.
* @param {Object} v Value to check for inside the array.
* @return {Number/String} Index of item inside the array inside an object. Or -1 if it wasn't found.
*/
inArray : function(a, v) {
var i, l;
if (a) {
for (i = 0, l = a.length; i < l; i++) {
if (a[i] === v)
return i;
}
}
return -1;
},
/**
* Extends an object with the specified other object(s).
*
* @method extend
* @param {Object} o Object to extend with new items.
* @param {Object} e..n Object(s) to extend the specified object with.
* @return {Object} o New extended object, same reference as the input object.
*/
extend : function(o, e) {
var i, l, a = arguments;
for (i = 1, l = a.length; i < l; i++) {
e = a[i];
tinymce.each(e, function(v, n) {
if (v !== undefined)
o[n] = v;
});
}
return o;
},
// #endif
/**
* Removes whitespace from the beginning and end of a string.
*
* @method trim
* @param {String} s String to remove whitespace from.
* @return {String} New string with removed whitespace.
*/
trim : function(s) {
return (s ? '' + s : '').replace(whiteSpaceRe, '');
},
/**
* Creates a class, subclass or static singleton.
* More details on this method can be found in the Wiki.
*
* @method create
* @param {String} s Class name, inheritage and prefix.
* @param {Object} o Collection of methods to add to the class.
*/
create : function(s, p) {
var t = this, sp, ns, cn, scn, c, de = 0;
// Parse : <prefix> <class>:<super class>
s = /^((static) )?([\w.]+)(:([\w.]+))?/.exec(s);
cn = s[3].match(/(^|\.)(\w+)$/i)[2]; // Class name
// Create namespace for new class
ns = t.createNS(s[3].replace(/\.\w+$/, ''));
// Class already exists
if (ns[cn])
return;
// Make pure static class
if (s[2] == 'static') {
ns[cn] = p;
if (this.onCreate)
this.onCreate(s[2], s[3], ns[cn]);
return;
}
// Create default constructor
if (!p[cn]) {
p[cn] = function() {};
de = 1;
}
// Add constructor and methods
ns[cn] = p[cn];
t.extend(ns[cn].prototype, p);
// Extend
if (s[5]) {
sp = t.resolve(s[5]).prototype;
scn = s[5].match(/\.(\w+)$/i)[1]; // Class name
// Extend constructor
c = ns[cn];
if (de) {
// Add passthrough constructor
ns[cn] = function() {
return sp[scn].apply(this, arguments);
};
} else {
// Add inherit constructor
ns[cn] = function() {
this.parent = sp[scn];
return c.apply(this, arguments);
};
}
ns[cn].prototype[cn] = ns[cn];
// Add super methods
t.each(sp, function(f, n) {
ns[cn].prototype[n] = sp[n];
});
// Add overridden methods
t.each(p, function(f, n) {
// Extend methods if needed
if (sp[n]) {
ns[cn].prototype[n] = function() {
this.parent = sp[n];
return f.apply(this, arguments);
};
} else {
if (n != cn)
ns[cn].prototype[n] = f;
}
});
}
// Add static methods
t.each(p['static'], function(f, n) {
ns[cn][n] = f;
});
if (this.onCreate)
this.onCreate(s[2], s[3], ns[cn].prototype);
},
/**
* Executed the specified function for each item in a object tree.
*
* @method walk
* @param {Object} o Object tree to walk though.
* @param {function} f Function to call for each item.
* @param {String} n Optional name of collection inside the objects to walk for example childNodes.
* @param {String} s Optional scope to execute the function in.
*/
walk : function(o, f, n, s) {
s = s || this;
if (o) {
if (n)
o = o[n];
tinymce.each(o, function(o, i) {
if (f.call(s, o, i, n) === false)
return false;
tinymce.walk(o, f, n, s);
});
}
},
/**
* Creates a namespace on a specific object.
*
* @method createNS
* @param {String} n Namespace to create for example a.b.c.d.
* @param {Object} o Optional object to add namespace to, defaults to window.
* @return {Object} New namespace object the last item in path.
*/
createNS : function(n, o) {
var i, v;
o = o || win;
n = n.split('.');
for (i=0; i<n.length; i++) {
v = n[i];
if (!o[v])
o[v] = {};
o = o[v];
}
return o;
},
/**
* Resolves a string and returns the object from a specific structure.
*
* @method resolve
* @param {String} n Path to resolve for example a.b.c.d.
* @param {Object} o Optional object to search though, defaults to window.
* @return {Object} Last object in path or null if it couldn't be resolved.
*/
resolve : function(n, o) {
var i, l;
o = o || win;
n = n.split('.');
for (i = 0, l = n.length; i < l; i++) {
o = o[n[i]];
if (!o)
break;
}
return o;
},
/**
* Adds an unload handler to the document. This handler will be executed when the document gets unloaded.
* This method is useful for dealing with browser memory leaks where it might be vital to remove DOM references etc.
*
* @method addUnload
* @param {function} f Function to execute before the document gets unloaded.
* @param {Object} s Optional scope to execute the function in.
* @return {function} Returns the specified unload handler function.
*/
addUnload : function(f, s) {
var t = this;
f = {func : f, scope : s || this};
if (!t.unloads) {
function unload() {
var li = t.unloads, o, n;
if (li) {
// Call unload handlers
for (n in li) {
o = li[n];
if (o && o.func)
o.func.call(o.scope, 1); // Send in one arg to distinct unload and user destroy
}
// Detach unload function
if (win.detachEvent) {
win.detachEvent('onbeforeunload', fakeUnload);
win.detachEvent('onunload', unload);
} else if (win.removeEventListener)
win.removeEventListener('unload', unload, false);
// Destroy references
t.unloads = o = li = w = unload = 0;
// Run garbarge collector on IE
if (win.CollectGarbage)
CollectGarbage();
}
};
function fakeUnload() {
var d = document;
// Is there things still loading, then do some magic
if (d.readyState == 'interactive') {
function stop() {
// Prevent memory leak
d.detachEvent('onstop', stop);
// Call unload handler
if (unload)
unload();
d = 0;
};
// Fire unload when the currently loading page is stopped
if (d)
d.attachEvent('onstop', stop);
// Remove onstop listener after a while to prevent the unload function
// to execute if the user presses cancel in an onbeforeunload
// confirm dialog and then presses the browser stop button
win.setTimeout(function() {
if (d)
d.detachEvent('onstop', stop);
}, 0);
}
};
// Attach unload handler
if (win.attachEvent) {
win.attachEvent('onunload', unload);
win.attachEvent('onbeforeunload', fakeUnload);
} else if (win.addEventListener)
win.addEventListener('unload', unload, false);
// Setup initial unload handler array
t.unloads = [f];
} else
t.unloads.push(f);
return f;
},
/**
* Removes the specified function form the unload handler list.
*
* @method removeUnload
* @param {function} f Function to remove from unload handler list.
* @return {function} Removed function name or null if it wasn't found.
*/
removeUnload : function(f) {
var u = this.unloads, r = null;
tinymce.each(u, function(o, i) {
if (o && o.func == f) {
u.splice(i, 1);
r = f;
return false;
}
});
return r;
},
/**
* Splits a string but removes the whitespace before and after each value.
*
* @method explode
* @param {string} s String to split.
* @param {string} d Delimiter to split by.
*/
explode : function(s, d) {
return s ? tinymce.map(s.split(d || ','), tinymce.trim) : s;
},
_addVer : function(u) {
var v;
if (!this.query)
return u;
v = (u.indexOf('?') == -1 ? '?' : '&') + this.query;
if (u.indexOf('#') == -1)
return u + v;
return u.replace('#', v + '#');
},
// Fix function for IE 9 where regexps isn't working correctly
// Todo: remove me once MS fixes the bug
_replace : function(find, replace, str) {
// On IE9 we have to fake $x replacement
if (isRegExpBroken) {
return str.replace(find, function() {
var val = replace, args = arguments, i;
for (i = 0; i < args.length - 2; i++) {
if (args[i] === undefined) {
val = val.replace(new RegExp('\\$' + i, 'g'), '');
} else {
val = val.replace(new RegExp('\\$' + i, 'g'), args[i]);
}
}
return val;
});
}
return str.replace(find, replace);
}
/**#@-*/
};
// Initialize the API
tinymce._init();
// Expose tinymce namespace to the global namespace (window)
win.tinymce = win.tinyMCE = tinymce;
})(window); | saintbyte/stalker-gis-php | stalker-gis.ru/js/tiny_mce/classes/tinymce.js | JavaScript | gpl-3.0 | 17,197 |
/**************************************************************************************
Copyright (C) Gerardo Huck, 2011
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/>.
**************************************************************************************/
package cytoscape.plugins.igraph;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
import com.sun.jna.ptr.DoubleByReference;
import com.sun.jna.Structure;
/**
*
*/
public class IgraphInterface {
static{
//load the dynamic library
Native.register("igraphWrapper");
}
public static native int nativeAdd(int a, int b);
// Create an igraph's graph
public static native void createGraph(int edgeArray[], int length, int directed);
// Test whether the graph is connected
public static native boolean isConnected();
// Simplify the graph
public static native void simplify();
// Circle layout
public static native void layoutCircle(double x[], double y[]);
// Star Layout
public static native void starLayout(double x[], double y[], int centerId);
// Fruchterman - Reingold Layout
public static native void layoutFruchterman(double x[],
double y[],
int iter,
double maxDelta,
double area,
double coolExp,
double repulserad,
boolean useSeed,
boolean isWeighted,
double weights[]);
// Fruchterman - Reingold Grid Layout
public static native void layoutFruchtermanGrid(double x[],
double y[],
int iter,
double maxDelta,
double area,
double coolExp,
double repulserad,
boolean useSeed,
boolean isWeighted,
double weights[],
double cellSize);
// lgl Layout
public static native void layoutLGL(double x[],
double y[],
int maxIt,
double maxDelta,
double area,
double coolExp,
double repulserad,
double cellSize);
// Minimum spanning tree - unweighted
public static native int minimum_spanning_tree_unweighted(int res[]);
// Minimum spanning tree - weighted
public static native int minimum_spanning_tree_weighted(int res[], double weights[]);
}
| nrnb/gsoc2011gerardo | src/cytoscape/plugins/igraph/IgraphInterface.java | Java | gpl-3.0 | 2,838 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('changeset', '0022_auto_20160222_2358'),
]
operations = [
migrations.AddField(
model_name='userdetail',
name='contributor_uid',
field=models.IntegerField(db_index=True, null=True, blank=True),
),
]
| batpad/osmcha-django | osmchadjango/changeset/migrations/0023_userdetail_contributor_uid.py | Python | gpl-3.0 | 441 |
/*
* DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-cen-xr-w32-bld/build/netwerk/base/public/nsIProtocolProxyCallback.idl
*/
#ifndef __gen_nsIProtocolProxyCallback_h__
#define __gen_nsIProtocolProxyCallback_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class nsIURI; /* forward declaration */
class nsIProxyInfo; /* forward declaration */
class nsICancelable; /* forward declaration */
/* starting interface: nsIProtocolProxyCallback */
#define NS_IPROTOCOLPROXYCALLBACK_IID_STR "a9967200-f95e-45c2-beb3-9b060d874bfd"
#define NS_IPROTOCOLPROXYCALLBACK_IID \
{0xa9967200, 0xf95e, 0x45c2, \
{ 0xbe, 0xb3, 0x9b, 0x06, 0x0d, 0x87, 0x4b, 0xfd }}
/**
* This interface serves as a closure for nsIProtocolProxyService's
* asyncResolve method.
*/
class NS_NO_VTABLE NS_SCRIPTABLE nsIProtocolProxyCallback : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IPROTOCOLPROXYCALLBACK_IID)
/**
* This method is called when proxy info is available or when an error
* in the proxy resolution occurs.
*
* @param aRequest
* The value returned from asyncResolve.
* @param aURI
* The URI passed to asyncResolve.
* @param aProxyInfo
* The resulting proxy info or null if there is no associated proxy
* info for aURI. As with the result of nsIProtocolProxyService's
* resolve method, a null result implies that a direct connection
* should be used.
* @param aStatus
* The status of the callback. This is a failure code if the request
* could not be satisfied, in which case the value of aStatus
* indicates the reason for the failure and aProxyInfo will be null.
*/
/* void onProxyAvailable (in nsICancelable aRequest, in nsIURI aURI, in nsIProxyInfo aProxyInfo, in nsresult aStatus); */
NS_SCRIPTABLE NS_IMETHOD OnProxyAvailable(nsICancelable *aRequest, nsIURI *aURI, nsIProxyInfo *aProxyInfo, nsresult aStatus) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIProtocolProxyCallback, NS_IPROTOCOLPROXYCALLBACK_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIPROTOCOLPROXYCALLBACK \
NS_SCRIPTABLE NS_IMETHOD OnProxyAvailable(nsICancelable *aRequest, nsIURI *aURI, nsIProxyInfo *aProxyInfo, nsresult aStatus);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIPROTOCOLPROXYCALLBACK(_to) \
NS_SCRIPTABLE NS_IMETHOD OnProxyAvailable(nsICancelable *aRequest, nsIURI *aURI, nsIProxyInfo *aProxyInfo, nsresult aStatus) { return _to OnProxyAvailable(aRequest, aURI, aProxyInfo, aStatus); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIPROTOCOLPROXYCALLBACK(_to) \
NS_SCRIPTABLE NS_IMETHOD OnProxyAvailable(nsICancelable *aRequest, nsIURI *aURI, nsIProxyInfo *aProxyInfo, nsresult aStatus) { return !_to ? NS_ERROR_NULL_POINTER : _to->OnProxyAvailable(aRequest, aURI, aProxyInfo, aStatus); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsProtocolProxyCallback : public nsIProtocolProxyCallback
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIPROTOCOLPROXYCALLBACK
nsProtocolProxyCallback();
private:
~nsProtocolProxyCallback();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsProtocolProxyCallback, nsIProtocolProxyCallback)
nsProtocolProxyCallback::nsProtocolProxyCallback()
{
/* member initializers and constructor code */
}
nsProtocolProxyCallback::~nsProtocolProxyCallback()
{
/* destructor code */
}
/* void onProxyAvailable (in nsICancelable aRequest, in nsIURI aURI, in nsIProxyInfo aProxyInfo, in nsresult aStatus); */
NS_IMETHODIMP nsProtocolProxyCallback::OnProxyAvailable(nsICancelable *aRequest, nsIURI *aURI, nsIProxyInfo *aProxyInfo, nsresult aStatus)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIProtocolProxyCallback_h__ */
| DragonZX/fdm | Gecko.SDK/2.0/include/nsIProtocolProxyCallback.h | C | gpl-3.0 | 4,378 |
#region License
// ====================================================
// Project Porcupine Copyright(C) 2016 Team Porcupine
// This program comes with ABSOLUTELY NO WARRANTY; This is free software,
// and you are welcome to redistribute it under certain conditions; See
// file LICENSE, which is part of this source code package, for details.
// ====================================================
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using MoonSharp.Interpreter;
using ProjectPorcupine.Pathfinding;
using UnityEngine;
[MoonSharpUserData]
public class InventoryManager
{
private static readonly string InventoryManagerLogChanel = "InventoryManager";
public InventoryManager()
{
Inventories = new Dictionary<string, List<Inventory>>();
}
public event Action<Inventory> InventoryCreated;
public Dictionary<string, List<Inventory>> Inventories { get; private set; }
public Tile GetFirstTileWithValidInventoryPlacement(int maxOffset, Tile inTile, Inventory inv)
{
for (int offset = 0; offset <= maxOffset; offset++)
{
int offsetX = 0;
int offsetY = 0;
Tile tile;
// searching top & bottom line of the square
for (offsetX = -offset; offsetX <= offset; offsetX++)
{
offsetY = offset;
tile = World.Current.GetTileAt(inTile.X + offsetX, inTile.Y + offsetY, inTile.Z);
if (CanPlaceInventoryAt(tile, inv))
{
return tile;
}
offsetY = -offset;
tile = World.Current.GetTileAt(inTile.X + offsetX, inTile.Y + offsetY, inTile.Z);
if (CanPlaceInventoryAt(tile, inv))
{
return tile;
}
}
// searching left & right line of the square
for (offsetY = -offset; offsetY <= offset; offsetY++)
{
offsetX = offset;
tile = World.Current.GetTileAt(inTile.X + offsetX, inTile.Y + offsetY, inTile.Z);
if (CanPlaceInventoryAt(tile, inv))
{
return tile;
}
offsetX = -offset;
tile = World.Current.GetTileAt(inTile.X + offsetX, inTile.Y + offsetY, inTile.Z);
if (CanPlaceInventoryAt(tile, inv))
{
return tile;
}
}
}
return null;
}
public bool PlaceInventoryAround(Tile tile, Inventory inventory, int radius = 3)
{
tile = GetFirstTileWithValidInventoryPlacement(radius, tile, inventory);
if (tile == null)
{
return false;
}
return PlaceInventory(tile, inventory);
}
public bool PlaceInventory(Tile tile, Inventory inventory)
{
bool tileWasEmpty = tile.Inventory == null;
if (tile.PlaceInventory(inventory) == false)
{
// The tile did not accept the inventory for whatever reason, therefore stop.
return false;
}
CleanupInventory(inventory);
// We may also created a new stack on the tile, if the startTile was previously empty.
if (tileWasEmpty)
{
if (Inventories.ContainsKey(tile.Inventory.Type) == false)
{
Inventories[tile.Inventory.Type] = new List<Inventory>();
}
Inventories[tile.Inventory.Type].Add(tile.Inventory);
InvokeInventoryCreated(tile.Inventory);
}
return true;
}
public bool PlaceInventory(Job job, Character character)
{
Inventory sourceInventory = character.inventory;
// Check that it's wanted by the job
if (job.RequestedItems.ContainsKey(sourceInventory.Type) == false)
{
Debug.ULogErrorChannel(InventoryManagerLogChanel, "Trying to add inventory to a job that it doesn't want.");
return false;
}
// Check that there is a target to transfer to
if (job.HeldInventory.ContainsKey(sourceInventory.Type) == false)
{
job.HeldInventory[sourceInventory.Type] = new Inventory(sourceInventory.Type, 0, sourceInventory.MaxStackSize);
}
Inventory targetInventory = job.HeldInventory[sourceInventory.Type];
int transferAmount = Mathf.Min(targetInventory.MaxStackSize - targetInventory.StackSize, sourceInventory.StackSize);
sourceInventory.StackSize -= transferAmount;
targetInventory.StackSize += transferAmount;
CleanupInventory(character);
return true;
}
public bool PlaceInventory(Character character, Inventory sourceInventory, int amount = -1)
{
amount = amount < 0 ? sourceInventory.StackSize : Math.Min(amount, sourceInventory.StackSize);
if (character.inventory == null)
{
character.inventory = sourceInventory.Clone();
character.inventory.StackSize = 0;
Inventories[character.inventory.Type].Add(character.inventory);
}
else if (character.inventory.Type != sourceInventory.Type)
{
Debug.ULogErrorChannel(InventoryManagerLogChanel, "Character is trying to pick up a mismatched inventory object type.");
return false;
}
character.inventory.StackSize += amount;
if (character.inventory.MaxStackSize < character.inventory.StackSize)
{
sourceInventory.StackSize = character.inventory.StackSize - character.inventory.MaxStackSize;
character.inventory.StackSize = character.inventory.MaxStackSize;
}
else
{
sourceInventory.StackSize -= amount;
}
CleanupInventory(sourceInventory);
return true;
}
/// <summary>
/// Gets <see cref="Inventory"/> closest to <see cref="tile"/>.
/// </summary>
/// <returns>The closest inventory of type.</returns>
public Inventory GetClosestInventoryOfType(string type, Tile tile, bool canTakeFromStockpile)
{
List<Tile> path = GetPathToClosestInventoryOfType(type, tile, canTakeFromStockpile);
return path != null ? path.Last().Inventory : null;
}
public bool RemoveInventoryOfType(string type, int quantity, bool onlyFromStockpiles)
{
if (!HasInventoryOfType(type, true))
{
return quantity == 0;
}
foreach (Inventory inventory in Inventories[type].ToList())
{
if (onlyFromStockpiles)
{
if (inventory.Tile == null ||
inventory.Tile.Furniture == null ||
inventory.Tile.Furniture.Type != "Stockpile" ||
inventory.Tile.Furniture.HasTypeTag("Stockpile"))
{
continue;
}
}
if (quantity <= 0)
{
break;
}
int removedFromStack = Math.Min(inventory.StackSize, quantity);
quantity -= removedFromStack;
inventory.StackSize -= removedFromStack;
CleanupInventory(inventory);
}
return quantity == 0;
}
public bool HasInventoryOfType(string type, bool canTakeFromStockpile)
{
if (Inventories.ContainsKey(type) == false || Inventories[type].Count == 0)
{
return false;
}
return Inventories[type].Find(inventory => inventory.CanBePickedUp(canTakeFromStockpile)) != null;
}
public bool HasInventoryOfType(string[] types, bool canTakeFromStockpile)
{
// Test that we have records for any of the types
List<string> filteredTypes = types
.ToList()
.FindAll(type => Inventories.ContainsKey(type) && Inventories[type].Count > 0);
if (filteredTypes.Count == 0)
{
return false;
}
foreach (string objectType in filteredTypes)
{
if (Inventories[objectType].Find(inventory => inventory.CanBePickedUp(canTakeFromStockpile)) != null)
{
return true;
}
}
return false;
}
public List<Tile> GetPathToClosestInventoryOfType(string type, Tile tile, bool canTakeFromStockpile)
{
if (HasInventoryOfType(type, canTakeFromStockpile) == false)
{
return null;
}
// We know the objects are out there, now find the closest.
return Pathfinder.FindPathToInventory(tile, type, canTakeFromStockpile);
}
public List<Tile> GetPathToClosestInventoryOfType(string[] objectTypes, Tile tile, bool canTakeFromStockpile)
{
if (HasInventoryOfType(objectTypes, canTakeFromStockpile) == false)
{
return null;
}
// We know the objects are out there, now find the closest.
return Pathfinder.FindPathToInventory(tile, objectTypes, canTakeFromStockpile);
}
private void CleanupInventory(Inventory inventory)
{
if (inventory.StackSize != 0)
{
return;
}
if (Inventories.ContainsKey(inventory.Type))
{
Inventories[inventory.Type].Remove(inventory);
}
if (inventory.Tile != null)
{
inventory.Tile.Inventory = null;
inventory.Tile = null;
}
}
private void CleanupInventory(Character character)
{
CleanupInventory(character.inventory);
if (character.inventory.StackSize == 0)
{
character.inventory = null;
}
}
private void InvokeInventoryCreated(Inventory inventory)
{
Action<Inventory> handler = InventoryCreated;
if (handler != null)
{
handler(inventory);
}
}
private bool CanPlaceInventoryAt(Tile tile, Inventory inv)
{
return (tile.Inventory == null && tile.Furniture == null && tile.IsEnterable() == Enterability.Yes) ||
(tile.Inventory != null && tile.Inventory.CanAccept(inv));
}
}
| Dan54/ProjectPorcupine | Assets/Scripts/Models/Inventory/InventoryManager.cs | C# | gpl-3.0 | 10,220 |
/* hpsound.c: HP-UX sound I/O
Copyright (c) 2002-2004 Alexander Yurchenko, Russell Marks, Philip Kendall
Matan Ziv-Av, Stuart Brady
$Id: hpsound.c 3115 2007-08-19 02:49:14Z fredm $
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <config.h>
#ifdef AUDIO_FORMAT_LINEAR16BIT
#include <sys/types.h>
#include <sys/audio.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include "settings.h"
#include "sound.h"
#include "ui/ui.h"
static int soundfd = -1;
static int sixteenbit = 1;
int sound_lowlevel_init( const char *device, int *freqptr, int *stereoptr )
{
int flags, tmp, frag;
/* select a default device if we weren't explicitly given one */
if( device == NULL ) device = "/dev/audio";
/* Open the sound device non-blocking to avoid hangs if it is being
* used by something else, but then set it blocking again as that's what
* we actually want */
if( ( soundfd = open( device, O_WRONLY | O_NONBLOCK ) ) == -1 ) {
settings_current.sound = 0;
ui_error( UI_ERROR_ERROR, "Couldn't open sound device '%s'", device );
return 1;
}
if( ( flags = fcntl( soundfd, F_GETFL ) ) == -1 ) {
settings_current.sound = 0;
ui_error( UI_ERROR_ERROR, "Couldn't fcntl sound device '%s'", device );
close( soundfd );
return 1;
}
flags &= ~O_NONBLOCK;
if( fcntl( soundfd, F_SETFL, flags ) == -1 ) {
settings_current.sound = 0;
ui_error( UI_ERROR_ERROR, "Couldn't set sound device '%s' blocking",
device );
close( soundfd );
return 1;
}
tmp = AUDIO_FORMAT_LINEAR16BIT;
if( settings_current.sound_force_8bit ||
ioctl( soundfd, AUDIO_SET_DATA_FORMAT, tmp ) < 0 ) {
/* try 8-bit - may be an 8-bit only device */
tmp = AUDIO_FORMAT_LINEAR8BIT;
if( ioctl( soundfd, AUDIO_SET_DATA_FORMAT, tmp ) < 0 ) {
settings_current.sound = 0;
if( settings_current.sound_force_8bit ) {
ui_error( UI_ERROR_ERROR,
"Couldn't set sound device '%s' into 8-bit mode", device );
} else {
ui_error(
UI_ERROR_ERROR,
"Couldn't set sound device '%s' in either 16-bit or 8-bit mode",
device
);
}
close( soundfd );
return 1;
}
sixteenbit = 0;
}
tmp = ( *stereoptr ) ? 2 : 1;
if( ioctl( soundfd, AUDIO_SET_CHANNELS, tmp ) < 0 ) {
tmp = ( *stereoptr ) ? 1 : 2;
if( ioctl( soundfd, AUDIO_SET_CHANNELS, tmp ) < 0 ) {
settings_current.sound = 0;
ui_error(
UI_ERROR_ERROR,
"Couldn't set sound device '%s' into either mono or stereo mode",
device
);
close( soundfd );
return 1;
}
*stereoptr = tmp;
}
if( ioctl( soundfd, AUDIO_SET_SAMPLE_RATE, *freqptr ) < 0 ) {
settings_current.sound = 0;
ui_error( UI_ERROR_ERROR,"Couldn't set sound device '%s' speed to %d",
device, *freqptr );
close( soundfd );
return 1;
}
frag = 16384;
ioctl( soundfd, AUDIO_SET_FRAGMENT, frag );
return 0;
}
void
sound_lowlevel_end( void )
{
if( soundfd != -1 ) close( soundfd );
}
void
sound_lowlevel_frame( libspectrum_signed_word *data, int len )
{
static unsigned char buf8[4096];
unsigned char *data8=(unsigned char *)data;
int ret=0, ofs=0;
len <<= 1; /* now in bytes */
if( !sixteenbit ) {
libspectrum_signed_word *src;
unsigned char *dst;
int f;
src = data; dst = buf8;
len >>= 1;
/* TODO: confirm byteorder on IA64 */
for( f = 0; f < len; f++ )
*dst++ = 128 + (int)( (*src++) / 256 );
data8 = buf8;
}
while( len ) {
ret = write( soundfd, data8 + ofs, len );
if( ret > 0 ) {
ofs += ret;
len -= ret;
}
}
}
#endif /* #ifdef AUDIO_FORMAT_LINEAR16BIT */
| matthewbauer/fuse-libretro | fuse/sound/hpsound.c | C | gpl-3.0 | 4,392 |
<section>
<div class="underline">
<h2>Serviço - <span></span></h2>
</div>
<div id="subpageloader"></div>
<script type="text/javascript">
if (session.user)
View.loadPage("book_service.html", "#subpageloader");
else View.loadPage("book_service_deny.html", "#subpageloader");
$(".underline span").text(session.selectedService.name);
</script>
</section> | robsonpessoa/petshop | service.html | HTML | gpl-3.0 | 421 |
// Copyright 2015-2021, University of Colorado Boulder
/**
* This type defines a rectangular shape that encloses a segment of the mRNA. These segments, connected together, are
* used to define the outer bounds of the mRNA strand. The path of the strand within these shape segments is worked out
* elsewhere.
*
* Shape segments keep track of the length of mRNA that they contain, but they don't explicitly contain references to
* the points that define the shape.
*
* @author John Blanco
* @author Mohamed Safi
* @author Aadish Gupta
*/
import Bounds2 from '../../../../dot/js/Bounds2.js';
import Vector2 from '../../../../dot/js/Vector2.js';
import geneExpressionEssentials from '../../geneExpressionEssentials.js';
import AttachmentSite from './AttachmentSite.js';
// constants
const FLOATING_POINT_COMP_FACTOR = 1E-7; // Factor to use to avoid issues with floating point resolution.
class ShapeSegment {
/**
* @param {Object} owner - the model object that this shape segment is a portion of
*/
constructor( owner ) {
// @public (read-only) {Bounds2} - Bounds of this shape segment
this.bounds = new Bounds2( 0, 0, 0, 0 );
// Attachment point where anything that attached to this segment would attach. Affinity is arbitrary in this case.
this.attachmentSite = new AttachmentSite( owner, new Vector2( 0, 0 ), 1 ); // @private
// Max length of mRNA that this segment can contain.
this.capacity = Number.MAX_VALUE; // @protected
}
/**
* Sets the capacity
* @param {number} capacity
* @public
*/
setCapacity( capacity ) {
this.capacity = capacity;
}
/**
* Returns the remaining capacity
* @returns {number}
* @public
*/
getRemainingCapacity() {
return this.capacity - this.getContainedLength();
}
/**
* Returns the lower right position of the segment
* @returns {Vector2}
* @public
*/
getLowerRightCornerPosition() {
return new Vector2( this.bounds.getMaxX(), this.bounds.getMinY() );
}
/**
* Sets the lower right position of the segment
* @param {number} x
* @param {number} y
* @public
*/
setLowerRightCornerPositionXY( x, y ) {
this.bounds.setMinMax( x - this.bounds.width, y, x, y + this.bounds.height );
this.updateAttachmentSitePosition();
}
/**
* @param {Vector2} p
* @public
*/
setLowerRightCornerPosition( p ) {
this.setLowerRightCornerPositionXY( p.x, p.y );
}
/**
* Returns the upper left position of the segment
* @returns {Vector2}
* @public
*/
getUpperLeftCornerPosition() {
return new Vector2( this.bounds.getMinX(), this.bounds.getMaxY() );
}
/**
* Sets the upper left position of the segment
* @param {number} x
* @param {number} y
* @public
*/
setUpperLeftCornerPositionXY( x, y ) {
this.bounds.setMinMax( x, y - this.bounds.height, x + this.bounds.width, y );
this.updateAttachmentSitePosition();
}
/**
* Translates the segment
* @param {number} x
* @param {number} y
* @public
*/
translate( x, y ) {
this.bounds.shiftXY( x, y );
this.updateAttachmentSitePosition();
}
/**
* Returns the bounds
* @returns {Bounds2}
* @public
*/
getBounds() {
return this.bounds;
}
/**
* Returns whether the shape segment is flat or not. A shape segment is flat if the height is zero.
* @returns {boolean}
* @public
*/
isFlat() {
return this.getBounds().height === 0;
}
/**
* Updates the Attachment Site Position which is the upper left corner of the segment
* @public
*/
updateAttachmentSitePosition() {
this.attachmentSite.positionProperty.set( this.getUpperLeftCornerPosition() );
}
/**
* Get the length of the mRNA contained by this segment.
* @returns {number}
* @public
*/
getContainedLength() {
throw new Error( 'getContainedLength should be implemented in descendant classes of ShapeSegment' );
}
/**
* Add the specified length of mRNA to the segment. This will generally cause the segment to grow. By design, flat
* segments grow to the left, square segments grow up and left. The shape segment list is also passed in so that new
* segments can be added if needed.
*
* @param {number} length
* @param {WindingBiomolecule} windingBiomolecule
* @param {Array.<ShapeSegment>} shapeSegmentList
* @public
*/
add( length, windingBiomolecule, shapeSegmentList ) {
throw new Error( 'add should be implemented in descendant classes of ShapeSegment' );
}
/**
* Remove the specified amount of mRNA from the segment. This will generally cause a segment to shrink. Flat segments
* shrink in from the right, square segments shrink from the lower right corner towards the upper left. The shape
* segment list is also a parameter so that shape segments can be removed if necessary.
*
* @param {number} length
* @param {Array.<ShapeSegment>} shapeSegmentList
* @public
*/
remove( length, shapeSegmentList ) {
throw new Error( 'remove should be implemented in descendant classes of ShapeSegment' );
}
/**
* Advance the mRNA through this shape segment. This is what happens when the mRNA is being translated by a ribosome
* into a protein. The list of shape segments is also a parameter in case segments need to be added or removed.
*
* @param {number} length
* @param {WindingBiomolecule} windingBiomolecule
* @param {Array.<ShapeSegment>} shapeSegmentList
* @public
*/
advance( length, windingBiomolecule, shapeSegmentList ) {
throw new Error( 'advance should be implemented in descendant classes of ShapeSegment' );
}
/**
* Advance the mRNA through this segment but also reduce the segment contents by the given length. This is used when
* the mRNA is being destroyed.
*
* @param {number} length
* @param {WindingBiomolecule} windingBiomolecule
* @param {Array.<ShapeSegment>} shapeSegmentList
* @public
*/
advanceAndRemove( length, windingBiomolecule, shapeSegmentList ) {
throw new Error( 'advance should be implemented in descendant classes of ShapeSegment' );
}
}
ShapeSegment.FLOATING_POINT_COMP_FACTOR = FLOATING_POINT_COMP_FACTOR;
geneExpressionEssentials.register( 'ShapeSegment', ShapeSegment );
export default ShapeSegment;
| phetsims/gene-expression-basics | js/common/model/ShapeSegment.js | JavaScript | gpl-3.0 | 6,318 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/tr/html4/loose.dtd">
<html>
<head>
<!-- Generated by chxdoc (build 752) on 2012-12-26 -->
<title>Array (Firmament Game Engine API)</title>
<meta name="date" content="2012-12-26"/>
<meta name="keywords" content="Array class"/>
<link href="../stylesheet.css" type="text/css" rel="stylesheet"/>
<script type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Array (Firmament Game Engine API)";
}
}
</script>
<noscript></noscript>
</head>
<body onload="windowTitle();">
<script type="text/javascript" language="javascript" src="../chxdoc.js"></script>
<div class="type-frame" id="class-frame">
<!-- ======== START OF class DATA ======== -->
<h1 class="class">Array<T></h1>
<dl>
<dt>type</dt>
<dd>class</dd>
</dl>
<div class="doc">
<!-- Comment block -->
An Array is a storage for values. You can access it using indexes or
with its API. On the server side, it's often better to use a <code>List</code> which
is less memory and CPU consuming, unless you really need indexed access.
</div>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<div class="members-panel">
<h2><a name="constructor_detail"></a>Constructor</h2>
<div class="members">
<div class="member">
<div class="header">
<a name="new()"></a>
<span class="name">new</span>()
</div>
<div class="body">
<dl>
<!-- deprecated -->
<!-- type params -->
<!-- method call parameters -->
<!-- method return types comments -->
<!-- method throws -->
<!-- requires -->
<!-- see -->
<!-- todo -->
<!-- authors -->
<!-- meta -->
<!-- platforms -->
</dl>
<!-- Comment block -->
<div class="comment">Creates a new Array.</div>
</div>
</div>
</div>
</div>
<!-- ============ FIELD field_detail =========== -->
<div class="members-panel">
<h2><a name="member_var_detail"></a>Instance Variables
</h2>
<div class="members">
<span class="showVar">
<div class="member">
<div class="header">
<h3>
<a name="length"></a>
<span class="name">length</span>(default,null) : <a href="Int.html" class="type">Int</a>
</h3>
</div>
<div class="body">
<!-- platforms -->
<dl>
</dl>
<!-- meta -->
<!-- Comment block -->
<div class="comment">The length of the Array</div>
</div>
</div>
</span>
</div>
</div>
<!-- ============ METHOD DETAIL ========== -->
<div class="members-panel">
<h2><a name="method_detail"></a>Instance Methods
</h2>
<div class="members">
<span class="showMethod">
<div class="member">
<div class="header">
<h3>
<a name="concat()"></a>
<span class="name">concat</span>(a : <a href="Array.html" class="type">Array</a><T>) : <a href="Array.html" class="type">Array</a><T>
</h3>
</div>
<div class="body">
<dl>
<!-- deprecated -->
<!-- type params -->
<!-- method call parameters -->
<!-- method return types comments -->
<!-- method throws -->
<!-- requires -->
<!-- see -->
<!-- todo -->
<!-- authors -->
<!-- meta -->
<!-- platforms -->
</dl>
<!-- Comment block -->
<div class="comment">Returns a new Array by appending <code>a</code> to <code>this</code>.</div>
</div>
</div>
</span>
<span class="showMethod">
<div class="member">
<div class="header">
<h3>
<a name="copy()"></a>
<span class="name">copy</span>() : <a href="Array.html" class="type">Array</a><T>
</h3>
</div>
<div class="body">
<dl>
<!-- deprecated -->
<!-- type params -->
<!-- method call parameters -->
<!-- method return types comments -->
<!-- method throws -->
<!-- requires -->
<!-- see -->
<!-- todo -->
<!-- authors -->
<!-- meta -->
<!-- platforms -->
</dl>
<!-- Comment block -->
<div class="comment">Returns a copy of the Array. The values are not
copied, only the Array structure.</div>
</div>
</div>
</span>
<span class="showMethod">
<div class="member">
<div class="header">
<h3>
<a name="insert()"></a>
<span class="name">insert</span>(pos : <a href="Int.html" class="type">Int</a>, x : T) : <a href="Void.html" class="type">Void</a>
</h3>
</div>
<div class="body">
<dl>
<!-- deprecated -->
<!-- type params -->
<!-- method call parameters -->
<!-- method return types comments -->
<!-- method throws -->
<!-- requires -->
<!-- see -->
<!-- todo -->
<!-- authors -->
<!-- meta -->
<!-- platforms -->
</dl>
<!-- Comment block -->
<div class="comment">Inserts the element <code>x</code> at the position <code>pos</code>.
All elements after <code>pos</code> are moved one index ahead.</div>
</div>
</div>
</span>
<span class="showMethod">
<div class="member">
<div class="header">
<h3>
<a name="iterator()"></a>
<span class="name">iterator</span>() : <a href="Iterator.html" class="type">Iterator</a><T>
</h3>
</div>
<div class="body">
<dl>
<!-- deprecated -->
<!-- type params -->
<!-- method call parameters -->
<!-- method return types comments -->
<!-- method throws -->
<!-- requires -->
<!-- see -->
<!-- todo -->
<!-- authors -->
<!-- meta -->
<!-- platforms -->
</dl>
<!-- Comment block -->
<div class="comment">Returns an iterator of the Array values.</div>
</div>
</div>
</span>
<span class="showMethod">
<div class="member">
<div class="header">
<h3>
<a name="join()"></a>
<span class="name">join</span>(sep : <a href="String.html" class="type">String</a>) : <a href="String.html" class="type">String</a>
</h3>
</div>
<div class="body">
<dl>
<!-- deprecated -->
<!-- type params -->
<!-- method call parameters -->
<!-- method return types comments -->
<!-- method throws -->
<!-- requires -->
<!-- see -->
<!-- todo -->
<!-- authors -->
<!-- meta -->
<!-- platforms -->
</dl>
<!-- Comment block -->
<div class="comment">Returns a representation of an array with <code>sep</code> for separating each element.</div>
</div>
</div>
</span>
<span class="showMethod">
<div class="member">
<div class="header">
<h3>
<a name="pop()"></a>
<span class="name">pop</span>() : <a href="Null.html" class="type">Null</a><T>
</h3>
</div>
<div class="body">
<dl>
<!-- deprecated -->
<!-- type params -->
<!-- method call parameters -->
<!-- method return types comments -->
<!-- method throws -->
<!-- requires -->
<!-- see -->
<!-- todo -->
<!-- authors -->
<!-- meta -->
<!-- platforms -->
</dl>
<!-- Comment block -->
<div class="comment">Removes the last element of the array and returns it.</div>
</div>
</div>
</span>
<span class="showMethod">
<div class="member">
<div class="header">
<h3>
<a name="push()"></a>
<span class="name">push</span>(x : T) : <a href="Int.html" class="type">Int</a>
</h3>
</div>
<div class="body">
<dl>
<!-- deprecated -->
<!-- type params -->
<!-- method call parameters -->
<!-- method return types comments -->
<!-- method throws -->
<!-- requires -->
<!-- see -->
<!-- todo -->
<!-- authors -->
<!-- meta -->
<!-- platforms -->
</dl>
<!-- Comment block -->
<div class="comment">Adds the element <code>x</code> at the end of the array.</div>
</div>
</div>
</span>
<span class="showMethod">
<div class="member">
<div class="header">
<h3>
<a name="remove()"></a>
<span class="name">remove</span>(x : T) : <a href="Bool.html" class="type">Bool</a>
</h3>
</div>
<div class="body">
<dl>
<!-- deprecated -->
<!-- type params -->
<!-- method call parameters -->
<!-- method return types comments -->
<!-- method throws -->
<!-- requires -->
<!-- see -->
<!-- todo -->
<!-- authors -->
<!-- meta -->
<!-- platforms -->
</dl>
<!-- Comment block -->
<div class="comment">Removes the first occurence of <code>x</code>.
Returns false if <code>x</code> was not present.
Elements are compared by using standard equality.</div>
</div>
</div>
</span>
<span class="showMethod">
<div class="member">
<div class="header">
<h3>
<a name="reverse()"></a>
<span class="name">reverse</span>() : <a href="Void.html" class="type">Void</a>
</h3>
</div>
<div class="body">
<dl>
<!-- deprecated -->
<!-- type params -->
<!-- method call parameters -->
<!-- method return types comments -->
<!-- method throws -->
<!-- requires -->
<!-- see -->
<!-- todo -->
<!-- authors -->
<!-- meta -->
<!-- platforms -->
</dl>
<!-- Comment block -->
<div class="comment">Reverse the order of elements of the Array.</div>
</div>
</div>
</span>
<span class="showMethod">
<div class="member">
<div class="header">
<h3>
<a name="shift()"></a>
<span class="name">shift</span>() : <a href="Null.html" class="type">Null</a><T>
</h3>
</div>
<div class="body">
<dl>
<!-- deprecated -->
<!-- type params -->
<!-- method call parameters -->
<!-- method return types comments -->
<!-- method throws -->
<!-- requires -->
<!-- see -->
<!-- todo -->
<!-- authors -->
<!-- meta -->
<!-- platforms -->
</dl>
<!-- Comment block -->
<div class="comment">Removes the first element and returns it.</div>
</div>
</div>
</span>
<span class="showMethod">
<div class="member">
<div class="header">
<h3>
<a name="slice()"></a>
<span class="name">slice</span>(pos : <a href="Int.html" class="type">Int</a>, ?end : <a href="Int.html" class="type">Int</a>) : <a href="Array.html" class="type">Array</a><T>
</h3>
</div>
<div class="body">
<dl>
<!-- deprecated -->
<!-- type params -->
<!-- method call parameters -->
<!-- method return types comments -->
<!-- method throws -->
<!-- requires -->
<!-- see -->
<!-- todo -->
<!-- authors -->
<!-- meta -->
<!-- platforms -->
</dl>
<!-- Comment block -->
<div class="comment">Copies the range of the array starting at <code>pos</code> up to,
but not including, <code>end</code>. Both <code>pos</code> and <code>end</code> can be
negative to count from the end: -1 is the last item in
the array.</div>
</div>
</div>
</span>
<span class="showMethod">
<div class="member">
<div class="header">
<h3>
<a name="sort()"></a>
<span class="name">sort</span>(f : T -> T -> <a href="Int.html" class="type">Int</a>) : <a href="Void.html" class="type">Void</a>
</h3>
</div>
<div class="body">
<dl>
<!-- deprecated -->
<!-- type params -->
<!-- method call parameters -->
<!-- method return types comments -->
<!-- method throws -->
<!-- requires -->
<!-- see -->
<!-- todo -->
<!-- authors -->
<!-- meta -->
<!-- platforms -->
</dl>
<!-- Comment block -->
<div class="comment">Sort the Array according to the comparison function <code>f</code>.
<code>f(x,y)</code> should return <code>0</code> if <code>x == y</code>, <code>>0</code> if <code>x > y</code>
and <code><0</code> if <code>x < y</code>.</div>
</div>
</div>
</span>
<span class="showMethod">
<div class="member">
<div class="header">
<h3>
<a name="splice()"></a>
<span class="name">splice</span>(pos : <a href="Int.html" class="type">Int</a>, len : <a href="Int.html" class="type">Int</a>) : <a href="Array.html" class="type">Array</a><T>
</h3>
</div>
<div class="body">
<dl>
<!-- deprecated -->
<!-- type params -->
<!-- method call parameters -->
<!-- method return types comments -->
<!-- method throws -->
<!-- requires -->
<!-- see -->
<!-- todo -->
<!-- authors -->
<!-- meta -->
<!-- platforms -->
</dl>
<!-- Comment block -->
<div class="comment">Removes <code>len</code> elements starting from <code>pos</code> an returns them.</div>
</div>
</div>
</span>
<span class="showMethod">
<div class="member">
<div class="header">
<h3>
<a name="toString()"></a>
<span class="name">toString</span>() : <a href="String.html" class="type">String</a>
</h3>
</div>
<div class="body">
<dl>
<!-- deprecated -->
<!-- type params -->
<!-- method call parameters -->
<!-- method return types comments -->
<!-- method throws -->
<!-- requires -->
<!-- see -->
<!-- todo -->
<!-- authors -->
<!-- meta -->
<!-- platforms -->
</dl>
<!-- Comment block -->
<div class="comment">Returns a displayable representation of the Array content.</div>
</div>
</div>
</span>
<span class="showMethod">
<div class="member">
<div class="header">
<h3>
<a name="unshift()"></a>
<span class="name">unshift</span>(x : T) : <a href="Void.html" class="type">Void</a>
</h3>
</div>
<div class="body">
<dl>
<!-- deprecated -->
<!-- type params -->
<!-- method call parameters -->
<!-- method return types comments -->
<!-- method throws -->
<!-- requires -->
<!-- see -->
<!-- todo -->
<!-- authors -->
<!-- meta -->
<!-- platforms -->
</dl>
<!-- Comment block -->
<div class="comment">Adds the element <code>x</code> at the start of the array.</div>
</div>
</div>
</span>
</div>
</div>
</div>
<!-- ========= END OF class DATA ========= -->
<div id="footer"></div>
</body>
</html>
| martamius/Obsolete-Firmament-haxe2 | docs/types/Array.html | HTML | gpl-3.0 | 13,911 |
<?php
/**
* Copyright 2010 Zikula Foundation
*
* This work is contributed to the Zikula Foundation under one or more
* Contributor Agreements and licensed to You under the following license:
*
* @license GNU/LGPLv3 (or at your option, any later version).
* @package Security_Token
* @subpackage Validate
*
* Please see the NOTICE file distributed with this source code for further
* information regarding copyright and licensing.
*/
/**
* Zikula_Token_Validate class.
*/
class Zikula_Token_Validate
{
/**
* Token generator.
*
* @var Zikula_Token_Generator
*/
protected $tokenGenerator;
/**
* Secret.
*
* @var string
*/
protected $secret;
/**
* Max life of a token.
*
* @var integer
*/
protected $maxlifetime;
/**
* Storage driver.
*
* @var Zikula_Token_Storage
*/
protected $storage;
/**
* Constructor.
*
* @param Zikula_Token_Generator $tokenGenerator Token generator.
* @param integer $maxlifetime Max lifetime in seconds (default = 86400).
*/
public function __construct(Zikula_Token_Generator $tokenGenerator, $maxlifetime = 86400)
{
$this->tokenGenerator = $tokenGenerator;
$this->storage = $tokenGenerator->getStorage();
$this->secret = $tokenGenerator->getSecret();
$this->maxlifetime = (int)$maxlifetime;
}
/**
* Validate a token.
*
* Tokens should be deleted if they are generated as one-time tokens
* with a unique ID each time. If the are per-session, then they should be
* generated with the same unique ID and not deleted when validated here.
*
* @param string $token Token to validate.
* @param boolean $delete Whether to delete the token if valid.
* @param boolean $checkExpire Whether to check for token expiry.
*
* @return boolean
*/
public function validate($token, $delete=true, $checkExpire=true)
{
if (!$token) {
return false;
}
list($id, $hash, $timestamp) = $this->tokenGenerator->decode($token);
$decoded = array('id' => $id, 'timestamp' => $timestamp);
// Check if token ID exists first.
$stored = $this->storage->get($decoded['id']);
if (!$stored) {
return false;
}
// Check if the token has been tampered with.
$duplicateToken = $this->tokenGenerator->generate($decoded['id'], $decoded['timestamp'])->getToken();
if ($stored['token'] !== $duplicateToken) {
$this->storage->delete($decoded['id']);
return false;
}
// Check if token has expired.
if ($checkExpire) {
$timeDiff = ((int)$decoded['timestamp'] + $this->maxlifetime) - time();
if ($timeDiff < 0) {
$this->storage->delete($decoded['id']);
return false;
}
}
// All checked out, delete the token and return true.
if ($delete) {
$this->storage->delete($decoded['id']);
}
return true;
}
}
| projectestac/intraweb | intranet/lib/Zikula/Token/Validate.php | PHP | gpl-3.0 | 3,170 |
/****************************************************************\
* *
* Nucleotide Translation Code *
* *
* Guy St.C. Slater.. mailto:guy@ebi.ac.uk *
* Copyright (C) 2000-2008. All Rights Reserved. *
* *
* This source code is distributed under the terms of the *
* GNU General Public License, version 3. See the file COPYING *
* or http://www.gnu.org/licenses/gpl.txt for details *
* *
* If you use this code, please keep this notice intact. *
* *
\****************************************************************/
#ifndef INCLUDED_TRANSLATE_H
#define INCLUDED_TRANSLATE_H
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/**/
#include <glib.h>
#include "argument.h"
typedef struct {
gchar *genetic_code;
} Translate_ArgumentSet;
Translate_ArgumentSet *Translate_ArgumentSet_create(Argument *arg);
#define Translate_AA_SET_SIZE 40
#define Translate_NT_SET_SIZE (1<<4)
#define Translate_PIMA_SET_SIZE 18
#define Translate_ALPHABET_SIZE (1<<8)
#define Translate_TRANSLATION_SIZE 4096
typedef struct {
guint ref_count;
guchar *nt;
guchar *aa;
guchar *code;
guchar nt2d[Translate_ALPHABET_SIZE];
guchar aa2d[Translate_ALPHABET_SIZE];
gint aamask[Translate_AA_SET_SIZE];
guchar trans[Translate_TRANSLATION_SIZE];
GPtrArray *revtrans[Translate_ALPHABET_SIZE];
} Translate;
Translate *Translate_create(gboolean use_pima);
Translate *Translate_share(Translate *t);
void Translate_destroy(Translate *t);
gint Translate_sequence(Translate *t, gchar *dna,
gint dna_length, gint frame, gchar *aaseq,
guchar *filter);
/* Sequence_translate frame is 1, 2, 3 for forward,
* or -1,-2,-3 for reverse.
* Sufficient space for translated sequence must provided in aaseq
* Translated seq is NULL terminated.
* Length of translated sequence is returned
*/
typedef void (*Translate_reverse_func)(gchar *dna, gint length,
gpointer user_data);
void Translate_reverse(Translate *t, gchar *aaseq, gint length,
Translate_reverse_func trf, gpointer user_data);
#define Translate_codon(t, codon) \
((gchar)((t)->aa[(t)->trans[((t)->nt2d[(guchar)(codon)[0]]) \
|((t)->nt2d[(guchar)(codon)[1]]<<4) \
|((t)->nt2d[(guchar)(codon)[2]]<<8)]]))
#define Translate_base(t, a, b, c) \
((t)->aa[(t)->trans[((t)->nt2d[(guchar)(a)]) \
|((t)->nt2d[(guchar)(b)]<<4) \
|((t)->nt2d[(guchar)(c)]<<8)]])
/**/
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* INCLUDED_TRANSLATE_H */
| hotdogee/exonerate-gff3 | src/sequence/translate.h | C | gpl-3.0 | 3,238 |
{-# LANGUAGE ViewPatterns #-}
module Run.Test (runTest) where
import Prelude hiding (writeFile, length)
import Data.ByteString.Lazy hiding (putStrLn)
import Data.List hiding (length)
import Data.Maybe
import Control.Monad
import System.Directory
import Test.QuickFuzz.Gen.FormatInfo
import Args
import Debug
import Exception
import Process
import Utils
-- |Return a lazy list of steps to execute
getSteps :: QFCommand -> [Int]
getSteps (maxTries -> Nothing) = [1..]
getSteps (maxTries -> Just n) = [1..n]
-- Run test subcommand
runTest :: (Show actions, Show base) =>
QFCommand -> FormatInfo base actions -> IO ()
runTest cmd fmt = do
debug (show cmd)
when (hasActions fmt)
(putStrLn "Selected format supports actions based generation/shrinking!")
createDirectoryIfMissing True (outDir cmd)
mkName <- nameMaker cmd fmt
(shcmd, testname) <- prepareCli cmd fmt
let cleanup = when (usesFile cmd) $ removeFile testname
-- Generation-execution-report loop
forM_ (getSteps cmd) $ \n -> handleSigInt cleanup $ do
let size = sawSize cmd n
-- Generate a value and encode it in a bytestring.
-- This fully evaluates the generated value, and retry
-- the generation if the value cant be encoded.
(mbacts, encoded, seed) <- strictGenerate cmd fmt size
-- Fuzz the generated value if required.
fuzzed <- if usesFuzzer cmd
then fuzz (fromJust (fuzzer cmd)) encoded seed
else return encoded
-- Execute the command using either a file or stdin.
exitcode <- if usesFile cmd
then writeFile testname fuzzed >> execute (verbose cmd) shcmd
else executeFromStdin (verbose cmd) shcmd fuzzed
-- Report and move failed test cases.
when (hasFailed exitcode) $ do
let failname = mkName n seed size
mapM_ putStrLn [ "Test case number " ++ show n ++ " has failed. "
, "Moving to " ++ failname ]
if usesFile cmd
then renameFile testname failname
else writeFile failname fuzzed
-- Shrink if necessary
when (hasFailed exitcode && shrinking cmd) $ do
-- Execute a shrinking stategy acordingly to the -a/--actions flag
(smallest, nshrinks, nfails) <- if hasActions fmt
then runShrinkActions cmd fmt shcmd testname
(fromJust mbacts) (diff encoded fuzzed)
else runShrinkByteString cmd shcmd testname fuzzed
printShrinkingFinished
-- Report the shrinking results
let shrinkName = mkName n seed size ++ ".reduced"
mapM_ putStrLn
[ "Reduced from " ++ show (length fuzzed) ++ " bytes"
++ " to " ++ show (length smallest) ++ " bytes"
, "After executing " ++ show nshrinks ++ " shrinks with "
++ show nfails ++ " failing shrinks. "
, "Saving to " ++ shrinkName ]
writeFile shrinkName smallest
when (not $ verbose cmd) (printTestStep n)
-- Clean up the mess
cleanup
printFinished
| elopez/QuickFuzz | app/Run/Test.hs | Haskell | gpl-3.0 | 3,314 |
Option Explicit
Option Strict
' Dynamic Bandwidth Monitor
' Leak detection method implemented in a real-time data historian
' Copyright (C) 2014-2021 J.H. Fitié, Vitens N.V.
'
' This file is part of DBM.
'
' DBM 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.
'
' DBM 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 DBM. If not, see <http://www.gnu.org/licenses/>.
Imports System
Imports System.Double
Imports System.Math
Imports Vitens.DynamicBandwidthMonitor.DBMParameters
Namespace Vitens.DynamicBandwidthMonitor
Public Class DBMMath
' Contains mathematical and statistical functions.
Public Shared Function NormSInv(p As Double) As Double
' Returns the inverse of the standard normal cumulative distribution.
' The distribution has a mean of zero and a standard deviation of one.
' Approximation of inverse standard normal CDF developed by
' Peter J. Acklam
Dim q, r As Double
Dim f As Integer
If p < 0.02425 Then ' Left tail
q = Sqrt(-2*Log(p))
f = 1
ElseIf p <= 0.97575 Then
q = p-0.5
r = q*q
Return (((((-3.96968302866538E+01*r+2.20946098424521E+02)*r-
2.75928510446969E+02)*r+1.38357751867269E+02)*r-3.06647980661472E+01)*
r+2.50662827745924)*q/(((((-5.44760987982241E+01*r+
1.61585836858041E+02)*r-1.55698979859887E+02)*r+6.68013118877197E+01)*
r-1.32806815528857E+01)*r+1)
Else ' Right tail
q = Sqrt(-2*Log(1-p))
f = -1
End If
Return f*(((((-7.78489400243029E-03*q-3.22396458041136E-01)*q-
2.40075827716184)*q-2.54973253934373)*q+4.37466414146497)*q+
2.93816398269878)/((((7.78469570904146E-03*q+3.2246712907004E-01)*q+
2.445134137143)*q+3.75440866190742)*q+1)
End Function
Public Shared Function TInv2T(p As Double, dof As Integer) As Double
' Returns the two-tailed inverse of the Student's t-distribution.
' Hill's approx. inverse t-dist.: Comm. of A.C.M Vol.13 No.10 1970 pg 620
Dim a, b, c, d, x, y As Double
If dof = 1 Then
p *= PI/2
Return Cos(p)/Sin(p)
ElseIf dof = 2 Then
Return Sqrt(2/(p*(2-p))-2)
Else
a = 1/(dof-0.5)
b = 48/(a^2)
c = ((20700*a/b-98)*a-16)*a+96.36
d = ((94.5/(b+c)-3)/b+1)*Sqrt(a*PI/2)*dof
x = d*p
y = x^(2/dof)
If y > a+0.05 Then
x = NormSInv(p/2)
y = x^2
If dof < 5 Then
c += 0.3*(dof-4.5)*(x+0.6)
End If
c = (((d/2*x-0.5)*x-7)*x-2)*x+b+c
y = (((((0.4*y+6.3)*y+36)*y+94.5)/c-y-3)/b+1)*x
y = Exp(a*y^2)-1
Else
y = ((1/(((dof+6)/(dof*y)-0.089*d-0.822)*(dof+2)*3)+0.5/(dof+4))*y-1)*
(dof+1)/(dof+2)+1/y
End If
Return Sqrt(dof*y)
End If
End Function
Public Shared Function TInv(p As Double, dof As Integer) As Double
' Returns the left-tailed inverse of the Student's t-distribution.
Return Sign(p-0.5)*TInv2T(1-Abs(p-0.5)*2, dof)
End Function
Public Shared Function MeanAbsoluteDeviationScaleFactor As Double
' Estimator; scale factor k
' For normally distributed data, multiply MAD by scale factor k to
' obtain an estimate of the normal scale parameter sigma.
' R.C. Geary. The Ratio of the Mean Deviation to the Standard Deviation
' as a Test of Normality. Biometrika, 1935. Cited on page 8.
Return Sqrt(PI/2)
End Function
Public Shared Function MedianAbsoluteDeviationScaleFactor(
n As Integer) As Double ' Estimator; scale factor k
' k is a constant scale factor, which depends on the distribution.
' For a symmetric distribution with zero mean, the population MAD is the
' 75th percentile of the distribution.
' Huber, P. J. (1981). Robust statistics. New York: John Wiley.
If n < 30 Then
Return 1/TInv(0.75, n) ' n < 30 Student's t-distribution
Else
Return 1/NormSInv(0.75) ' n >= 30 Standard normal distribution
End If
End Function
Public Shared Function ControlLimitRejectionCriterion(p As Double,
n As Integer) As Double
' Return two-sided critical z-values for confidence interval p.
' Student's t-distribution approaches the normal z distribution at
' 30 samples.
' Student. 1908. Probable error of a correlation
' coefficient. Biometrika 6, 2-3, 302–310.
' Hogg and Tanis' Probability and Statistical Inference (7e).
If n < 30 Then
Return TInv((p+1)/2, n) ' n < 30 Student's t-distribution
Else
Return NormSInv((p+1)/2) ' n >= 30 Standard normal distribution
End If
End Function
Public Shared Function NonNaNCount(Values() As Double) As Integer
' Returns number of values in the array excluding NaNs.
Dim Value As Double
Dim Count As Integer
For Each Value In Values
If Not IsNaN(Value) Then
Count += 1
End If
Next
Return Count
End Function
Public Shared Function Mean(Values() As Double) As Double
' Returns the arithmetic mean; the sum of the sampled values divided
' by the number of items in the sample. NaNs are excluded.
Dim Value, Sum As Double
Dim Count As Integer
For Each Value In Values
If Not IsNaN(Value) Then
Sum += Value
Count += 1
End If
Next
Return Sum/Count
End Function
Public Shared Function Median(Values() As Double) As Double
' The median is the value separating the higher half of a data sample,
' a population, or a probability distribution, from the lower half. In
' simple terms, it may be thought of as the "middle" value of a data set.
' NaNs are excluded.
Dim MedianValues(NonNaNCount(Values)-1), Value As Double
Dim Count As Integer
If MedianValues.Length = 0 Then Return NaN ' No non-NaN values.
For Each Value In Values
If Not IsNaN(Value) Then
MedianValues(Count) = Value
Count += 1
End If
Next
Array.Sort(MedianValues)
If MedianValues.Length Mod 2 = 0 Then
Return (MedianValues(MedianValues.Length\2)+
MedianValues(MedianValues.Length\2-1))/2
Else
Return MedianValues(MedianValues.Length\2)
End If
End Function
Public Shared Function StDevP(Values() As Double) As Double
' In statistics, the standard deviation is a measure of the amount of
' variation or dispersion of a set of values. A low standard deviation
' indicates that the values tend to be close to the mean (also called the
' expected value) of the set, while a high standard deviation indicates
' that the values are spread out over a wider range.
Dim MeanValues, Value As Double
Dim Count As Integer
MeanValues = Mean(Values)
For Each Value In Values
If Not IsNaN(Value) Then
StDevP += (Value-MeanValues)^2
Count += 1
End If
Next
StDevP /= Count
StDevP = Sqrt(StDevP)
Return StDevP
End Function
Public Shared Function AbsoluteDeviation(Values() As Double,
From As Double) As Double()
' Returns an array which contains the absolute values of the input
' array from which the central tendency has been subtracted.
Dim i As Integer
Dim AbsDev(Values.Length-1) As Double
For i = 0 to Values.Length-1
AbsDev(i) = Abs(Values(i)-From)
Next i
Return AbsDev
End Function
Public Shared Function MeanAbsoluteDeviation(Values() As Double) As Double
' The mean absolute deviation (MAD) of a set of data
' is the average distance between each data value and the mean.
Return Mean(AbsoluteDeviation(Values, Mean(Values)))
End Function
Public Shared Function MedianAbsoluteDeviation(Values() As Double) As Double
' The median absolute deviation (MAD) is a robust measure of the
' variability of a univariate sample of quantitative data.
Return Median(AbsoluteDeviation(Values, Median(Values)))
End Function
Public Shared Function UseMeanAbsoluteDeviation(
Values() As Double) As Boolean
' Returns true if the Mean Absolute Deviation has to be used instead of
' the Median Absolute Deviation to detect outliers. Median absolute
' deviation has a 50% breakdown point.
Return MedianAbsoluteDeviation(Values) = 0
End Function
Public Shared Function CentralTendency(Values() As Double) As Double
' Returns the central tendency for the data series, based on either the
' mean or median absolute deviation. In statistics, a central tendency
' (or measure of central tendency) is a central or typical value for a
' probability distribution.
If UseMeanAbsoluteDeviation(Values) Then
Return Mean(Values)
Else
Return Median(Values)
End If
End Function
Public Shared Function ControlLimit(Values() As Double,
p As Double) As Double
' Returns the control limits for the data series, based on either the
' mean or median absolute deviation, scale factor and rejection criterion.
' Control limits are used to detect signals in process data that indicate
' that a process is not in control and, therefore, not operating
' predictably.
Dim Count As Integer = NonNaNCount(Values)
If UseMeanAbsoluteDeviation(Values) Then
Return MeanAbsoluteDeviation(Values)*
MeanAbsoluteDeviationScaleFactor*
ControlLimitRejectionCriterion(p, Count-1)
Else
Return MedianAbsoluteDeviation(Values)*
MedianAbsoluteDeviationScaleFactor(Count-1)*
ControlLimitRejectionCriterion(p, Count-1)
End If
End Function
Public Shared Function RemoveOutliers(Values() As Double) As Double()
' Returns an array which contains the input data from which outliers
' are filtered (replaced with NaNs) using either the mean or median
' absolute deviation function.
Dim ValuesCentralTendency, ValuesControlLimit,
FilteredValues(Values.Length-1) As Double
Dim i As Integer
ValuesCentralTendency = CentralTendency(Values)
ValuesControlLimit = ControlLimit(Values, OutlierCI)
For i = 0 to Values.Length-1
If Abs(Values(i)-ValuesCentralTendency) > ValuesControlLimit Then
FilteredValues(i) = NaN ' Filter outlier
Else
FilteredValues(i) = Values(i) ' Keep inlier
End If
Next i
Return FilteredValues
End Function
Public Shared Function ExponentialWeights(Count As Integer) As Double()
Dim Alpha, Weight, Weights(Count-1), TotalWeight As Double
Dim i As Integer
Alpha = 2/(Count+1) ' Smoothing factor
Weight = 1 ' Initial weight
For i = 0 To Count-1
Weights(i) = Weight
TotalWeight += Weight
Weight /= 1-Alpha ' Increase weight
Next i
For i = 0 To Count-1
Weights(i) /= TotalWeight ' Normalise weights
Next i
Return Weights
End Function
Public Shared Function ExponentialMovingAverage(
Values() As Double) As Double
' Filter high frequency variation
' An exponential moving average (EMA), is a type of infinite impulse
' response filter that applies weighting factors which increase
' exponentially.
Dim i As Integer
Dim Weights() As Double = ExponentialWeights(Values.Length)
Dim TotalWeight As Double
For i = 0 To Values.Length-1
If Not IsNaN(Values(i)) Then ' Exclude NaN values.
ExponentialMovingAverage += Values(i)*Weights(i)
TotalWeight += Weights(i) ' Used to correct for NaN values.
End If
Next i
' Return NaN if there are no non-NaN values, or if the most recent value
' is NaN.
If TotalWeight = 0 Or IsNaN(Values(Values.Length-1)) Then Return NaN
ExponentialMovingAverage /= TotalWeight
Return ExponentialMovingAverage
End Function
Public Shared Function SlopeToAngle(Slope As Double) As Double
' Returns angle in degrees for Slope.
Return Atan(Slope)/(2*PI)*360
End Function
Public Shared Function Lerp(v0 As Double, v1 As Double,
t As Double) As Double
' In mathematics, linear interpolation is a method of curve fitting using
' linear polynomials to construct new data points within the range of a
' discrete set of known data points.
' Imprecise method, which does not guarantee v = v1 when t = 1, due to
' floating-point arithmetic error. This method is monotonic. This form may
' be used when the hardware has a native fused multiply-add instruction.
'Return v0+t*(v1-v0)
' Precise method, which guarantees v = v1 when t = 1. This method is
' monotonic only when v0 * v1 < 0. Lerping between same values might not
' produce the same value
Return (1-t)*v0+t*v1
End Function
End Class
End Namespace
| Vitens/DBM | src/dbm/DBMMath.vb | Visual Basic | gpl-3.0 | 14,149 |
//
// PopTableViewController.h
// CoCode
//
// Created by wuxueqian on 15/11/9.
// Copyright (c) 2015年 wuxueqian. All rights reserved.
//
@interface CCFilterViewController : UIViewController
@property (nonatomic, copy) void (^onItemSelected)(NSDictionary *);
@property (nonatomic, copy) void (^onCancel)();
@property (nonatomic, strong) NSArray *filters;
@property (nonatomic, assign) NSInteger tag;
@property (nonatomic, strong) NSString *filterTitle;
@end
| thundernet8/CoCode | CoCode/Controllers/Utilities/CCFilterViewController.h | C | gpl-3.0 | 468 |
from core import messages
from core.weexceptions import FatalException
from mako import template
from core.config import sessions_path, sessions_ext
from core.loggers import log, stream_handler
from core.module import Status
import os
import yaml
import glob
import logging
import urlparse
import atexit
import ast
print_filters = [
'debug',
'channel'
]
set_filters = [
'debug',
'channel'
]
class Session(dict):
def _session_save_atexit(self):
yaml.dump(
dict(self),
open(self['path'], 'w'),
default_flow_style = False
)
def print_to_user(self, module_filter = ''):
for mod_name, mod_value in self.items():
if isinstance(mod_value, dict):
mod_args = mod_value.get('stored_args')
# Is a module, print all the storable stored_arguments
for argument, arg_value in mod_args.items():
if not module_filter or ("%s.%s" % (mod_name, argument)).startswith(module_filter):
log.info("%s.%s = '%s'" % (mod_name, argument, arg_value))
else:
# If is not a module, just print if matches with print_filters
if any(f for f in print_filters if f == mod_name):
log.info("%s = '%s'" % (mod_name, mod_value))
def get_connection_info(self):
return template.Template(messages.sessions.connection_info).render(
url = self['url'],
user = self['system_info']['results'].get('whoami', ''),
host = self['system_info']['results'].get('hostname', ''),
path = self['file_cd']['results'].get('cwd', '.')
)
def action_debug(self, module_argument, value):
if value:
stream_handler.setLevel(logging.DEBUG)
else:
stream_handler.setLevel(logging.INFO)
def set(self, module_argument, value):
"""Called by user to set or show the session variables"""
# I safely evaluate the value type to avoid to save only
# strings type. Dirty but effective.
# TODO: the actual type of the argument could be acquired
# from modules[module].argparser.
try:
value = ast.literal_eval(value)
except Exception as e:
# If is not evalued, just keep it as string
pass
# If action_<module_argument> function exists, trigger the action
action_name = 'action_%s' % (module_argument.replace('.','_'))
if hasattr(self, action_name):
action_func = getattr(self, action_name)
if hasattr(action_func, '__call__'):
action_func(module_argument, value)
if module_argument.count('.') == 1:
module_name, arg_name = module_argument.split('.')
if arg_name not in self[module_name]['stored_args']:
log.warn(messages.sessions.error_storing_s_not_found % ( '%s.%s' % (module_name, arg_name) ))
else:
self[module_name]['stored_args'][arg_name] = value
log.info("%s.%s = '%s'" % (module_name, arg_name, value))
else:
module_name = module_argument
if module_name not in self or module_name not in set_filters:
log.warn(messages.sessions.error_storing_s_not_found % (module_name))
else:
self[module_name] = value
log.info("%s = %s" % (module_name, value))
# If the channel is changed, the basic shell_php is moved
# to IDLE and must be setup again.
if module_name == 'channel':
self['shell_php']['status'] = Status.IDLE
class SessionFile(Session):
def __init__(self, dbpath, volatile = False):
try:
sessiondb = yaml.load(open(dbpath, 'r').read())
except Exception as e:
log.warn(
messages.generic.error_loading_file_s_s %
(dbpath, str(e)))
raise FatalException(messages.sessions.error_loading_sessions)
saved_url = sessiondb.get('url')
saved_password = sessiondb.get('password')
if saved_url and saved_password:
if not volatile:
# Register dump at exit and return
atexit.register(self._session_save_atexit)
self.update(sessiondb)
return
log.warn(
messages.sessions.error_loading_file_s %
(dbpath, 'no url or password'))
raise FatalException(messages.sessions.error_loading_sessions)
class SessionURL(Session):
def __init__(self, url, password, volatile = False):
if not os.path.isdir(sessions_path):
os.makedirs(sessions_path)
# Guess a generic hostfolder/dbname
hostname = urlparse.urlparse(url).hostname
if not hostname:
raise FatalException(messages.generic.error_url_format)
hostfolder = os.path.join(sessions_path, hostname)
dbname = os.path.splitext(os.path.basename(urlparse.urlsplit(url).path))[0]
# Check if session already exists
sessions_available = glob.glob(
os.path.join(
hostfolder,
'*%s' %
sessions_ext))
for dbpath in sessions_available:
try:
sessiondb = yaml.load(open(dbpath, 'r').read())
except Exception as e:
log.warn(
messages.generic.error_loading_file_s_s %
(dbpath, str(e)))
else:
saved_url = sessiondb.get('url')
saved_password = sessiondb.get('password')
if not saved_url or not saved_password:
log.warn(
messages.generic.error_loading_file_s_s %
(dbpath, 'no url or password'))
if saved_url == url and saved_password == password:
# Found correspondent session file.
# Register dump at exit and return
if not volatile:
atexit.register(self._session_save_atexit)
self.update(sessiondb)
return
# If no session was found, create a new one with first available filename
index = 0
while True:
dbpath = os.path.join(
hostfolder, '%s_%i%s' %
(dbname, index, sessions_ext))
if not os.path.isdir(hostfolder):
os.makedirs(hostfolder)
if not os.path.exists(dbpath):
sessiondb = {}
sessiondb.update(
{ 'path': dbpath,
'url': url,
'password': password,
'debug': False,
'channel' : None,
'default_shell' : None
}
)
# Register dump at exit and return
if not volatile:
atexit.register(self._session_save_atexit)
self.update(sessiondb)
return
else:
index += 1
raise FatalException(messages.sessions.error_loading_sessions)
| jorik041/weevely3 | core/sessions.py | Python | gpl-3.0 | 7,336 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Google.Protobuf;
using PokemonGo.RocketAPI.Extensions;
using PokemonGo.RocketAPI.Helpers;
using POGOProtos.Networking.Requests;
using POGOProtos.Networking.Requests.Messages;
using POGOProtos.Networking.Responses;
namespace PokemonGo.RocketAPI.Rpc
{
public class Map : BaseRpc
{
public Map(Client client) : base(client)
{
}
public async Task<Tuple<GetMapObjectsResponse, GetHatchedEggsResponse, GetInventoryResponse, CheckAwardedBadgesResponse, DownloadSettingsResponse>> GetMapObjects()
{
#region Messages
var getMapObjectsMessage = new GetMapObjectsMessage
{
CellId = { S2Helper.GetNearbyCellIds(_client.CurrentLongitude, _client.CurrentLatitude) },
SinceTimestampMs = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
Latitude = _client.CurrentLatitude,
Longitude = _client.CurrentLongitude
};
var getHatchedEggsMessage = new GetHatchedEggsMessage();
var getInventoryMessage = new GetInventoryMessage
{
LastTimestampMs = DateTime.UtcNow.ToUnixTime()
};
var checkAwardedBadgesMessage = new CheckAwardedBadgesMessage();
var downloadSettingsMessage = new DownloadSettingsMessage
{
Hash = "b8fa9757195897aae92c53dbcf8a60fb3d86d745"
};
#endregion
var request = RequestBuilder.GetRequestEnvelope(
new Request
{
RequestType = RequestType.GetMapObjects,
RequestMessage = getMapObjectsMessage.ToByteString()
},
new Request
{
RequestType = RequestType.GetHatchedEggs,
RequestMessage = getHatchedEggsMessage.ToByteString()
}, new Request
{
RequestType = RequestType.GetInventory,
RequestMessage = getInventoryMessage.ToByteString()
}, new Request
{
RequestType = RequestType.CheckAwardedBadges,
RequestMessage = checkAwardedBadgesMessage.ToByteString()
}, new Request
{
RequestType = RequestType.DownloadSettings,
RequestMessage = downloadSettingsMessage.ToByteString()
});
return await PostProtoPayload<Request, GetMapObjectsResponse, GetHatchedEggsResponse, GetInventoryResponse, CheckAwardedBadgesResponse, DownloadSettingsResponse>(request);
}
public async Task<GetIncensePokemonResponse> GetIncensePokemons()
{
var message = new GetIncensePokemonMessage()
{
PlayerLatitude = _client.CurrentLatitude,
PlayerLongitude = _client.CurrentLongitude
};
return await PostProtoPayload<Request, GetIncensePokemonResponse>(RequestType.GetIncensePokemon, message);
}
}
}
| YoBii/PokemonGo-Bot | PokemonGo.RocketAPI/Rpc/Map.cs | C# | gpl-3.0 | 3,237 |
from distutils.core import setup
import py2exe
opts = {
"py2exe": {
"compressed": 1,
"optimize": 2,
"ascii": 1,
"bundle_files": 1,
"packages": ["encodings"],
"dist_dir": "dist"
}
}
setup (name = "Gomoz",
fullname = "Gomoz web scanner",
version = "1.0.1",
description = "Gomoz scanner web application",
author = "Handrix",
author_email = "securfox@gmail.com",
url = "http://www.sourceforge.net/projects/gomoz/",
license = "GPL",
keywords = ["scanner", "web application", "securfox", "wxPython"],
windows = [{"script": "gomoz"}],
options = opts,
zipfile = None
)
| eyecatchup/gomoz | win/winsetup.py | Python | gpl-3.0 | 689 |
/*
SSSD
Tests if IPA and LDAP backend options are in sync
Authors:
Jakub Hrozek <jhrozek@redhat.com>
Copyright (C) 2010 Red Hat
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 <check.h>
#include <stdlib.h>
#include <talloc.h>
#include "providers/ipa/ipa_common.h"
#include "providers/ipa/ipa_opts.h"
#include "providers/ldap/sdap.h"
#include "providers/ldap/ldap_opts.h"
#include "providers/krb5/krb5_opts.h"
#include "providers/krb5/krb5_common.h"
#include "providers/ad/ad_opts.h"
#include "providers/dp_dyndns.h"
#include "tests/common.h"
struct test_domain {
const char *domain;
const char *basedn;
};
struct test_domain test_domains[] = {
{ "abc", "dc=abc"},
{ "a.b.c", "dc=a,dc=b,dc=c"},
{ "A.B.C", "dc=a,dc=b,dc=c"},
{ NULL, NULL}
};
START_TEST(test_domain_to_basedn)
{
int ret;
int i;
TALLOC_CTX *tmp_ctx;
char *basedn;
tmp_ctx = talloc_new(NULL);
fail_unless(tmp_ctx != NULL, "talloc_new failed");
ret = domain_to_basedn(tmp_ctx, NULL, &basedn);
fail_unless(ret == EINVAL,
"domain_to_basedn does not fail with EINVAL if domain is NULL");
ret = domain_to_basedn(tmp_ctx, "abc", NULL);
fail_unless(ret == EINVAL,
"domain_to_basedn does not fail with EINVAL if basedn is NULL");
for(i=0; test_domains[i].domain != NULL; i++) {
ret = domain_to_basedn(tmp_ctx, test_domains[i].domain, &basedn);
fail_unless(ret == EOK, "domain_to_basedn failed");
fail_unless(strcmp(basedn, test_domains[i].basedn) == 0,
"domain_to_basedn returned wrong basedn, "
"get [%s], expected [%s]", basedn, test_domains[i].basedn);
talloc_free(basedn);
}
talloc_free(tmp_ctx);
}
END_TEST
START_TEST(test_compare_opts)
{
errno_t ret;
ret = compare_dp_options(default_basic_opts, SDAP_OPTS_BASIC,
ipa_def_ldap_opts);
fail_unless(ret == EOK, "[%s]", strerror(ret));
ret = compare_dp_options(default_krb5_opts, KRB5_OPTS,
ipa_def_krb5_opts);
fail_unless(ret == EOK, "[%s]", strerror(ret));
ret = compare_dp_options(ipa_dyndns_opts, DP_OPT_DYNDNS,
ad_dyndns_opts);
fail_unless(ret == EOK, "[%s]", strerror(ret));
}
END_TEST
START_TEST(test_compare_sdap_attrs)
{
errno_t ret;
/* General Attributes */
ret = compare_sdap_attr_maps(generic_attr_map, SDAP_AT_GENERAL,
ipa_attr_map);
fail_unless(ret == EOK, "[%s]", strerror(ret));
/* User Attributes */
ret = compare_sdap_attr_maps(rfc2307_user_map, SDAP_OPTS_USER,
ipa_user_map);
fail_unless(ret == EOK, "[%s]", strerror(ret));
/* Group Attributes */
ret = compare_sdap_attr_maps(rfc2307_group_map, SDAP_OPTS_GROUP,
ipa_group_map);
fail_unless(ret == EOK, "[%s]", strerror(ret));
/* Service Attributes */
ret = compare_sdap_attr_maps(service_map, SDAP_OPTS_SERVICES,
ipa_service_map);
fail_unless(ret == EOK, "[%s]", strerror(ret));
/* AutoFS Attributes */
ret = compare_sdap_attr_maps(rfc2307_autofs_mobject_map,
SDAP_OPTS_AUTOFS_MAP,
ipa_autofs_mobject_map);
fail_unless(ret == EOK, "[%s]", strerror(ret));
ret = compare_sdap_attr_maps(rfc2307_autofs_entry_map,
SDAP_OPTS_AUTOFS_ENTRY,
ipa_autofs_entry_map);
fail_unless(ret == EOK, "[%s]", strerror(ret));
}
END_TEST
START_TEST(test_compare_2307_with_2307bis)
{
errno_t ret;
/* User Attributes */
ret = compare_sdap_attr_maps(rfc2307_user_map, SDAP_OPTS_USER,
rfc2307bis_user_map);
fail_unless(ret == EOK, "[%s]", strerror(ret));
/* Group Attributes */
ret = compare_sdap_attr_maps(rfc2307_group_map, SDAP_OPTS_GROUP,
rfc2307bis_group_map);
fail_unless(ret == EOK, "[%s]", strerror(ret));
/* AutoFS Attributes */
ret = compare_sdap_attr_maps(rfc2307_autofs_mobject_map,
SDAP_OPTS_AUTOFS_MAP,
rfc2307bis_autofs_mobject_map);
fail_unless(ret == EOK, "[%s]", strerror(ret));
ret = compare_sdap_attr_maps(rfc2307_autofs_entry_map,
SDAP_OPTS_AUTOFS_ENTRY,
rfc2307bis_autofs_entry_map);
fail_unless(ret == EOK, "[%s]", strerror(ret));
}
END_TEST
START_TEST(test_copy_opts)
{
errno_t ret;
TALLOC_CTX *tmp_ctx;
struct dp_option *opts;
tmp_ctx = talloc_new(NULL);
fail_unless(tmp_ctx != NULL, "talloc_new failed");
ret = dp_copy_options(tmp_ctx, ad_def_ldap_opts, SDAP_OPTS_BASIC, &opts);
fail_unless(ret == EOK, "[%s]", strerror(ret));
for (int i=0; i < SDAP_OPTS_BASIC; i++) {
char *s1, *s2;
bool b1, b2;
int i1, i2;
struct dp_opt_blob bl1, bl2;
switch (opts[i].type) {
case DP_OPT_STRING:
s1 = dp_opt_get_string(opts, i);
s2 = opts[i].def_val.string;
if (s1 != NULL || s2 != NULL) {
fail_unless(strcmp(s1, s2) == 0,
"Option %s does not have default value after copy\n",
opts[i].opt_name);
}
break;
case DP_OPT_NUMBER:
i1 = dp_opt_get_int(opts, i);
i2 = opts[i].def_val.number;
fail_unless(i1 == i2,
"Option %s does not have default value after copy\n",
opts[i].opt_name);
break;
case DP_OPT_BOOL:
b1 = dp_opt_get_bool(opts, i);
b2 = opts[i].def_val.boolean;
fail_unless(b1 == b2,
"Option %s does not have default value after copy\n",
opts[i].opt_name);
break;
case DP_OPT_BLOB:
bl1 = dp_opt_get_blob(opts, i);
bl2 = opts[i].def_val.blob;
fail_unless(bl1.length == bl2.length,
"Blobs differ in size for option %s\n",
opts[i].opt_name);
fail_unless(memcmp(bl1.data, bl2.data, bl1.length) == 0,
"Blobs differ in value for option %s\n",
opts[i].opt_name);
}
}
talloc_free(tmp_ctx);
}
END_TEST
Suite *ipa_ldap_opt_suite (void)
{
Suite *s = suite_create ("ipa_ldap_opt");
TCase *tc_ipa_ldap_opt = tcase_create ("ipa_ldap_opt");
tcase_add_test (tc_ipa_ldap_opt, test_compare_opts);
tcase_add_test (tc_ipa_ldap_opt, test_compare_sdap_attrs);
tcase_add_test (tc_ipa_ldap_opt, test_compare_2307_with_2307bis);
suite_add_tcase (s, tc_ipa_ldap_opt);
TCase *tc_ipa_utils = tcase_create ("ipa_utils");
tcase_add_test (tc_ipa_utils, test_domain_to_basedn);
suite_add_tcase (s, tc_ipa_utils);
TCase *tc_dp_opts = tcase_create ("dp_opts");
tcase_add_test (tc_dp_opts, test_copy_opts);
suite_add_tcase (s, tc_dp_opts);
return s;
}
int main(void)
{
int number_failed;
tests_set_cwd();
Suite *s = ipa_ldap_opt_suite ();
SRunner *sr = srunner_create (s);
/* If CK_VERBOSITY is set, use that, otherwise it defaults to CK_NORMAL */
srunner_run_all(sr, CK_ENV);
number_failed = srunner_ntests_failed (sr);
srunner_free (sr);
return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
}
| PallaviKumariJha/SSSD | src/tests/ipa_ldap_opt-tests.c | C | gpl-3.0 | 8,261 |
#ifndef STRINGUTIL_H_
#define STRINGUTIL_H_
#include <vector>
#include <string>
#define MAX_DIGITS_IN_INT 12 // max number of digits in an int (-2147483647 = 11 digits, +1 for the '\0')
// Removes leading white space
extern void TrimLeft(std::string &s);
// Counts the number of lines in a block of text
extern int CountLines(const std::wstring &s);
// Does a classic * & ? pattern match on a file name - this is case sensitive!
extern bool WildcardMatch(const char *pat, const char *str);
extern std::string ToStr(int num, int base = 10);
extern std::string ToStr(unsigned int num, int base = 10);
extern std::string ToStr(unsigned long num, int base = 10);
extern std::string ToStr(float num);
extern std::string ToStr(double num);
extern std::string ToStr(bool val);
extern std::string ToStr(char* val);
extern std::string ToStr(const char* val);
extern std::string ToStr(std::string str);
// Splits a string by the delimeter into a vector of strings. For example, say you have the following string:
// std::string test("one,two,three");
// You could call Split() like this:
// Split(test, outVec, ',');
// outVec will have the following values:
// "one", "two", "three"
void Split(const std::string& str, std::vector<std::string>& vec, char delimiter);
unsigned long HashName(char const* identStr);
std::string GetBaseName(const std::string& path);
std::string RemoveExtension(const std::string& fileName);
std::string StripPathAndExtension(const std::string& fullFilePath);
inline bool StringContains(std::string& str, std::string& what)
{
return str.find(what) != std::string::npos;
}
#endif | pjasicek/OpenClaw | OpenClaw/Engine/Util/StringUtil.h | C | gpl-3.0 | 1,660 |
/*
Highcharts JS v3.0.0 (2013-03-22)
(c) 2009-2013 Torstein Hønsi
License: www.highcharts.com/license
*/
(function(){function u(a,b){var c;a||(a={});for(c in b)a[c]=b[c];return a}function x(){var a,b=arguments.length,c={},d=function(a,b){var c,h;for(h in b)b.hasOwnProperty(h)&&(c=b[h],typeof a!=="object"&&(a={}),a[h]=c&&typeof c==="object"&&Object.prototype.toString.call(c)!=="[object Array]"&&typeof c.nodeType!=="number"?d(a[h]||{},c):b[h]);return a};for(a=0;a<b;a++)c=d(c,arguments[a]);return c}function v(a,b){return parseInt(a,b||10)}function fa(a){return typeof a==="string"}function V(a){return typeof a===
"object"}function Ca(a){return Object.prototype.toString.call(a)==="[object Array]"}function ua(a){return typeof a==="number"}function na(a){return N.log(a)/N.LN10}function da(a){return N.pow(10,a)}function ga(a,b){for(var c=a.length;c--;)if(a[c]===b){a.splice(c,1);break}}function s(a){return a!==w&&a!==null}function C(a,b,c){var d,e;if(fa(b))s(c)?a.setAttribute(b,c):a&&a.getAttribute&&(e=a.getAttribute(b));else if(s(b)&&V(b))for(d in b)a.setAttribute(d,b[d]);return e}function ha(a){return Ca(a)?
a:[a]}function o(){var a=arguments,b,c,d=a.length;for(b=0;b<d;b++)if(c=a[b],typeof c!=="undefined"&&c!==null)return c}function M(a,b){if(Da&&b&&b.opacity!==w)b.filter="alpha(opacity="+b.opacity*100+")";u(a.style,b)}function U(a,b,c,d,e){a=z.createElement(a);b&&u(a,b);e&&M(a,{padding:0,border:O,margin:0});c&&M(a,c);d&&d.appendChild(a);return a}function ea(a,b){var c=function(){};c.prototype=new a;u(c.prototype,b);return c}function Na(a,b,c,d){var e=P.lang,f=a;b===-1?(b=(a||0).toString(),a=b.indexOf(".")>
-1?b.split(".")[1].length:0):a=isNaN(b=R(b))?2:b;var b=a,c=c===void 0?e.decimalPoint:c,d=d===void 0?e.thousandsSep:d,e=f<0?"-":"",a=String(v(f=R(+f||0).toFixed(b))),g=a.length>3?a.length%3:0;return e+(g?a.substr(0,g)+d:"")+a.substr(g).replace(/(\d{3})(?=\d)/g,"$1"+d)+(b?c+R(f-a).toFixed(b).slice(2):"")}function va(a,b){return Array((b||2)+1-String(a).length).join(0)+a}function Ea(a,b){for(var c="{",d=!1,e,f,g,h,i,j=[];(c=a.indexOf(c))!==-1;){e=a.slice(0,c);if(d){f=e.split(":");g=f.shift().split(".");
i=g.length;e=b;for(h=0;h<i;h++)e=e[g[h]];if(f.length)f=f.join(":"),g=/\.([0-9])/,h=P.lang,i=void 0,/f$/.test(f)?(i=(i=f.match(g))?i[1]:6,e=Na(e,i,h.decimalPoint,f.indexOf(",")>-1?h.thousandsSep:"")):e=Ua(f,e)}j.push(e);a=a.slice(c+1);c=(d=!d)?"}":"{"}j.push(a);return j.join("")}function ib(a,b,c,d){var e,c=o(c,1);e=a/c;b||(b=[1,2,2.5,5,10],d&&d.allowDecimals===!1&&(c===1?b=[1,2,5,10]:c<=0.1&&(b=[1/c])));for(d=0;d<b.length;d++)if(a=b[d],e<=(b[d]+(b[d+1]||b[d]))/2)break;a*=c;return a}function yb(a,
b){var c=b||[[zb,[1,2,5,10,20,25,50,100,200,500]],[jb,[1,2,5,10,15,30]],[Va,[1,2,5,10,15,30]],[Oa,[1,2,3,4,6,8,12]],[oa,[1,2]],[Wa,[1,2]],[Pa,[1,2,3,4,6]],[wa,null]],d=c[c.length-1],e=A[d[0]],f=d[1],g;for(g=0;g<c.length;g++)if(d=c[g],e=A[d[0]],f=d[1],c[g+1]&&a<=(e*f[f.length-1]+A[c[g+1][0]])/2)break;e===A[wa]&&a<5*e&&(f=[1,2,5]);e===A[wa]&&a<5*e&&(f=[1,2,5]);c=ib(a/e,f);return{unitRange:e,count:c,unitName:d[0]}}function Ab(a,b,c,d){var e=[],f={},g=P.global.useUTC,h,i=new Date(b),j=a.unitRange,k=a.count;
if(s(b)){j>=A[jb]&&(i.setMilliseconds(0),i.setSeconds(j>=A[Va]?0:k*T(i.getSeconds()/k)));if(j>=A[Va])i[Bb](j>=A[Oa]?0:k*T(i[kb]()/k));if(j>=A[Oa])i[Cb](j>=A[oa]?0:k*T(i[lb]()/k));if(j>=A[oa])i[mb](j>=A[Pa]?1:k*T(i[Qa]()/k));j>=A[Pa]&&(i[Db](j>=A[wa]?0:k*T(i[Xa]()/k)),h=i[Ya]());j>=A[wa]&&(h-=h%k,i[Eb](h));if(j===A[Wa])i[mb](i[Qa]()-i[nb]()+o(d,1));b=1;h=i[Ya]();for(var d=i.getTime(),m=i[Xa](),l=i[Qa](),i=g?0:(864E5+i.getTimezoneOffset()*6E4)%864E5;d<c;)e.push(d),j===A[wa]?d=Za(h+b*k,0):j===A[Pa]?
d=Za(h,m+b*k):!g&&(j===A[oa]||j===A[Wa])?d=Za(h,m,l+b*k*(j===A[oa]?1:7)):(d+=j*k,j<=A[Oa]&&d%A[oa]===i&&(f[d]=oa)),b++;e.push(d)}e.info=u(a,{higherRanks:f,totalRange:j*k});return e}function Fb(){this.symbol=this.color=0}function Gb(a,b){var c=a.length,d,e;for(e=0;e<c;e++)a[e].ss_i=e;a.sort(function(a,c){d=b(a,c);return d===0?a.ss_i-c.ss_i:d});for(e=0;e<c;e++)delete a[e].ss_i}function Fa(a){for(var b=a.length,c=a[0];b--;)a[b]<c&&(c=a[b]);return c}function pa(a){for(var b=a.length,c=a[0];b--;)a[b]>
c&&(c=a[b]);return c}function Ga(a,b){for(var c in a)a[c]&&a[c]!==b&&a[c].destroy&&a[c].destroy(),delete a[c]}function Ra(a){$a||($a=U(xa));a&&$a.appendChild(a);$a.innerHTML=""}function qa(a,b){var c="Highcharts error #"+a+": www.highcharts.com/errors/"+a;if(b)throw c;else E.console&&console.log(c)}function ia(a){return parseFloat(a.toPrecision(14))}function Ha(a,b){ya=o(a,b.animation)}function Hb(){var a=P.global.useUTC,b=a?"getUTC":"get",c=a?"setUTC":"set";Za=a?Date.UTC:function(a,b,c,g,h,i){return(new Date(a,
b,o(c,1),o(g,0),o(h,0),o(i,0))).getTime()};kb=b+"Minutes";lb=b+"Hours";nb=b+"Day";Qa=b+"Date";Xa=b+"Month";Ya=b+"FullYear";Bb=c+"Minutes";Cb=c+"Hours";mb=c+"Date";Db=c+"Month";Eb=c+"FullYear"}function ra(){}function Ia(a,b,c,d){this.axis=a;this.pos=b;this.type=c||"";this.isNew=!0;!c&&!d&&this.addLabel()}function ob(a,b){this.axis=a;if(b)this.options=b,this.id=b.id}function Ib(a,b,c,d,e,f){var g=a.chart.inverted;this.axis=a;this.isNegative=c;this.options=b;this.x=d;this.stack=e;this.percent=f==="percent";
this.alignOptions={align:b.align||(g?c?"left":"right":"center"),verticalAlign:b.verticalAlign||(g?"middle":c?"bottom":"top"),y:o(b.y,g?4:c?14:-6),x:o(b.x,g?c?-6:6:0)};this.textAlign=b.textAlign||(g?c?"right":"left":"center")}function ab(){this.init.apply(this,arguments)}function pb(){this.init.apply(this,arguments)}function qb(a,b){this.init(a,b)}function rb(a,b){this.init(a,b)}function sb(){this.init.apply(this,arguments)}var w,z=document,E=window,N=Math,t=N.round,T=N.floor,ja=N.ceil,q=N.max,F=N.min,
R=N.abs,Y=N.cos,ca=N.sin,Ja=N.PI,bb=Ja*2/360,za=navigator.userAgent,Jb=E.opera,Da=/msie/i.test(za)&&!Jb,cb=z.documentMode===8,db=/AppleWebKit/.test(za),eb=/Firefox/.test(za),Kb=/(Mobile|Android|Windows Phone)/.test(za),sa="http://www.w3.org/2000/svg",Z=!!z.createElementNS&&!!z.createElementNS(sa,"svg").createSVGRect,Rb=eb&&parseInt(za.split("Firefox/")[1],10)<4,$=!Z&&!Da&&!!z.createElement("canvas").getContext,Sa,fb=z.documentElement.ontouchstart!==w,Lb={},tb=0,$a,P,Ua,ya,ub,A,ta=function(){},Aa=
[],xa="div",O="none",Mb="rgba(192,192,192,"+(Z?1.0E-4:0.002)+")",zb="millisecond",jb="second",Va="minute",Oa="hour",oa="day",Wa="week",Pa="month",wa="year",Nb="stroke-width",Za,kb,lb,nb,Qa,Xa,Ya,Bb,Cb,mb,Db,Eb,aa={};E.Highcharts=E.Highcharts?qa(16,!0):{};Ua=function(a,b,c){if(!s(b)||isNaN(b))return"Invalid date";var a=o(a,"%Y-%m-%d %H:%M:%S"),d=new Date(b),e,f=d[lb](),g=d[nb](),h=d[Qa](),i=d[Xa](),j=d[Ya](),k=P.lang,m=k.weekdays,d=u({a:m[g].substr(0,3),A:m[g],d:va(h),e:h,b:k.shortMonths[i],B:k.months[i],
m:va(i+1),y:j.toString().substr(2,2),Y:j,H:va(f),I:va(f%12||12),l:f%12||12,M:va(d[kb]()),p:f<12?"AM":"PM",P:f<12?"am":"pm",S:va(d.getSeconds()),L:va(t(b%1E3),3)},Highcharts.dateFormats);for(e in d)for(;a.indexOf("%"+e)!==-1;)a=a.replace("%"+e,typeof d[e]==="function"?d[e](b):d[e]);return c?a.substr(0,1).toUpperCase()+a.substr(1):a};Fb.prototype={wrapColor:function(a){if(this.color>=a)this.color=0},wrapSymbol:function(a){if(this.symbol>=a)this.symbol=0}};A=function(){for(var a=0,b=arguments,c=b.length,
d={};a<c;a++)d[b[a++]]=b[a];return d}(zb,1,jb,1E3,Va,6E4,Oa,36E5,oa,864E5,Wa,6048E5,Pa,26784E5,wa,31556952E3);ub={init:function(a,b,c){var b=b||"",d=a.shift,e=b.indexOf("C")>-1,f=e?7:3,g,b=b.split(" "),c=[].concat(c),h,i,j=function(a){for(g=a.length;g--;)a[g]==="M"&&a.splice(g+1,0,a[g+1],a[g+2],a[g+1],a[g+2])};e&&(j(b),j(c));a.isArea&&(h=b.splice(b.length-6,6),i=c.splice(c.length-6,6));if(d<=c.length/f)for(;d--;)c=[].concat(c).splice(0,f).concat(c);a.shift=0;if(b.length)for(a=c.length;b.length<a;)d=
[].concat(b).splice(b.length-f,f),e&&(d[f-6]=d[f-2],d[f-5]=d[f-1]),b=b.concat(d);h&&(b=b.concat(h),c=c.concat(i));return[b,c]},step:function(a,b,c,d){var e=[],f=a.length;if(c===1)e=d;else if(f===b.length&&c<1)for(;f--;)d=parseFloat(a[f]),e[f]=isNaN(d)?a[f]:c*parseFloat(b[f]-d)+d;else e=b;return e}};(function(a){E.HighchartsAdapter=E.HighchartsAdapter||a&&{init:function(b){var c=a.fx,d=c.step,e,f=a.Tween,g=f&&f.propHooks;a.extend(a.easing,{easeOutQuad:function(a,b,c,d,e){return-d*(b/=e)*(b-2)+c}});
a.each(["cur","_default","width","height","opacity"],function(a,b){var e=d,k,m;b==="cur"?e=c.prototype:b==="_default"&&f&&(e=g[b],b="set");(k=e[b])&&(e[b]=function(c){c=a?c:this;m=c.elem;return m.attr?m.attr(c.prop,b==="cur"?w:c.now):k.apply(this,arguments)})});e=function(a){var c=a.elem,d;if(!a.started)d=b.init(c,c.d,c.toD),a.start=d[0],a.end=d[1],a.started=!0;c.attr("d",b.step(a.start,a.end,a.pos,c.toD))};f?g.d={set:e}:d.d=e;this.each=Array.prototype.forEach?function(a,b){return Array.prototype.forEach.call(a,
b)}:function(a,b){for(var c=0,d=a.length;c<d;c++)if(b.call(a[c],a[c],c,a)===!1)return c};a.fn.highcharts=function(){var a="Chart",b=arguments,c,d;fa(b[0])&&(a=b[0],b=Array.prototype.slice.call(b,1));c=b[0];if(c!==w)c.chart=c.chart||{},c.chart.renderTo=this[0],new Highcharts[a](c,b[1]),d=this;c===w&&(d=Aa[C(this[0],"data-highcharts-chart")]);return d}},getScript:a.getScript,inArray:a.inArray,adapterRun:function(b,c){return a(b)[c]()},grep:a.grep,map:function(a,c){for(var d=[],e=0,f=a.length;e<f;e++)d[e]=
c.call(a[e],a[e],e,a);return d},offset:function(b){return a(b).offset()},addEvent:function(b,c,d){a(b).bind(c,d)},removeEvent:function(b,c,d){var e=z.removeEventListener?"removeEventListener":"detachEvent";z[e]&&!b[e]&&(b[e]=function(){});a(b).unbind(c,d)},fireEvent:function(b,c,d,e){var f=a.Event(c),g="detached"+c,h;!Da&&d&&(delete d.layerX,delete d.layerY);u(f,d);b[c]&&(b[g]=b[c],b[c]=null);a.each(["preventDefault","stopPropagation"],function(a,b){var c=f[b];f[b]=function(){try{c.call(f)}catch(a){b===
"preventDefault"&&(h=!0)}}});a(b).trigger(f);b[g]&&(b[c]=b[g],b[g]=null);e&&!f.isDefaultPrevented()&&!h&&e(f)},washMouseEvent:function(a){var c=a.originalEvent||a;if(c.pageX===w)c.pageX=a.pageX,c.pageY=a.pageY;return c},animate:function(b,c,d){var e=a(b);if(c.d)b.toD=c.d,c.d=1;e.stop();c.opacity!==w&&b.attr&&(c.opacity+="px");e.animate(c,d)},stop:function(b){a(b).stop()}}})(E.jQuery);var W=E.HighchartsAdapter,L=W||{};W&&W.init.call(W,ub);var gb=L.adapterRun,Sb=L.getScript,ka=L.inArray,n=L.each,Ob=
L.grep,Tb=L.offset,Ka=L.map,J=L.addEvent,ba=L.removeEvent,G=L.fireEvent,Pb=L.washMouseEvent,vb=L.animate,Ta=L.stop,L={enabled:!0,align:"center",x:0,y:15,style:{color:"#666",cursor:"default",fontSize:"11px",lineHeight:"14px"}};P={colors:"#2f7ed8,#0d233a,#8bbc21,#910000,#1aadce,#492970,#f28f43,#77a1e5,#c42525,#a6c96a".split(","),symbols:["circle","diamond","square","triangle","triangle-down"],lang:{loading:"Loading...",months:"January,February,March,April,May,June,July,August,September,October,November,December".split(","),
shortMonths:"Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec".split(","),weekdays:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday".split(","),decimalPoint:".",numericSymbols:"k,M,G,T,P,E".split(","),resetZoom:"Reset zoom",resetZoomTitle:"Reset zoom level 1:1",thousandsSep:","},global:{useUTC:!0,canvasToolsURL:"http://code.highcharts.com/3.0.0/modules/canvas-tools.js",VMLRadialGradientURL:"http://code.highcharts.com/3.0.0/gfx/vml-radial-gradient.png"},chart:{borderColor:"#4572A7",borderRadius:5,
defaultSeriesType:"line",ignoreHiddenSeries:!0,spacingTop:10,spacingRight:10,spacingBottom:15,spacingLeft:10,style:{fontFamily:'"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif',fontSize:"12px"},backgroundColor:"#FFFFFF",plotBorderColor:"#C0C0C0",resetZoomButton:{theme:{zIndex:20},position:{align:"right",x:-10,y:10}}},title:{text:"Chart title",align:"center",y:15,style:{color:"#274b6d",fontSize:"16px"}},subtitle:{text:"",align:"center",y:30,style:{color:"#4d759e"}},plotOptions:{line:{allowPointSelect:!1,
showCheckbox:!1,animation:{duration:1E3},events:{},lineWidth:2,marker:{enabled:!0,lineWidth:0,radius:4,lineColor:"#FFFFFF",states:{hover:{enabled:!0},select:{fillColor:"#FFFFFF",lineColor:"#000000",lineWidth:2}}},point:{events:{}},dataLabels:x(L,{enabled:!1,formatter:function(){return this.y},verticalAlign:"bottom",y:0}),cropThreshold:300,pointRange:0,showInLegend:!0,states:{hover:{marker:{}},select:{marker:{}}},stickyTracking:!0}},labels:{style:{position:"absolute",color:"#3E576F"}},legend:{enabled:!0,
align:"center",layout:"horizontal",labelFormatter:function(){return this.name},borderWidth:1,borderColor:"#909090",borderRadius:5,navigation:{activeColor:"#274b6d",inactiveColor:"#CCC"},shadow:!1,itemStyle:{cursor:"pointer",color:"#274b6d",fontSize:"12px"},itemHoverStyle:{color:"#000"},itemHiddenStyle:{color:"#CCC"},itemCheckboxStyle:{position:"absolute",width:"13px",height:"13px"},symbolWidth:16,symbolPadding:5,verticalAlign:"bottom",x:0,y:0,title:{style:{fontWeight:"bold"}}},loading:{labelStyle:{fontWeight:"bold",
position:"relative",top:"1em"},style:{position:"absolute",backgroundColor:"white",opacity:0.5,textAlign:"center"}},tooltip:{enabled:!0,animation:Z,backgroundColor:"rgba(255, 255, 255, .85)",borderWidth:1,borderRadius:3,dateTimeLabelFormats:{millisecond:"%A, %b %e, %H:%M:%S.%L",second:"%A, %b %e, %H:%M:%S",minute:"%A, %b %e, %H:%M",hour:"%A, %b %e, %H:%M",day:"%A, %b %e, %Y",week:"Week from %A, %b %e, %Y",month:"%B %Y",year:"%Y"},headerFormat:'<span style="font-size: 10px">{point.key}</span><br/>',
pointFormat:'<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b><br/>',shadow:!0,snap:Kb?25:10,style:{color:"#333333",cursor:"default",fontSize:"12px",padding:"8px",whiteSpace:"nowrap"}},credits:{}};var X=P.plotOptions,W=X.line;Hb();var la=function(a){var b=[],c,d;(function(a){a&&a.stops?d=Ka(a.stops,
function(a){return la(a[1])}):(c=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/.exec(a))?b=[v(c[1]),v(c[2]),v(c[3]),parseFloat(c[4],10)]:(c=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(a))?b=[v(c[1],16),v(c[2],16),v(c[3],16),1]:(c=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(a))&&(b=[v(c[1]),v(c[2]),v(c[3]),1])})(a);return{get:function(c){var f;d?(f=x(a),f.stops=[].concat(f.stops),n(d,function(a,b){f.stops[b]=[f.stops[b][0],
a.get(c)]})):f=b&&!isNaN(b[0])?c==="rgb"?"rgb("+b[0]+","+b[1]+","+b[2]+")":c==="a"?b[3]:"rgba("+b.join(",")+")":a;return f},brighten:function(a){if(d)n(d,function(b){b.brighten(a)});else if(ua(a)&&a!==0){var c;for(c=0;c<3;c++)b[c]+=v(a*255),b[c]<0&&(b[c]=0),b[c]>255&&(b[c]=255)}return this},rgba:b,setOpacity:function(a){b[3]=a;return this}}};ra.prototype={init:function(a,b){this.element=b==="span"?U(b):z.createElementNS(sa,b);this.renderer=a;this.attrSetters={}},opacity:1,animate:function(a,b,c){b=
o(b,ya,!0);Ta(this);if(b){b=x(b);if(c)b.complete=c;vb(this,a,b)}else this.attr(a),c&&c()},attr:function(a,b){var c,d,e,f,g=this.element,h=g.nodeName.toLowerCase(),i=this.renderer,j,k=this.attrSetters,m=this.shadows,l,p,r=this;fa(a)&&s(b)&&(c=a,a={},a[c]=b);if(fa(a))c=a,h==="circle"?c={x:"cx",y:"cy"}[c]||c:c==="strokeWidth"&&(c="stroke-width"),r=C(g,c)||this[c]||0,c!=="d"&&c!=="visibility"&&(r=parseFloat(r));else{for(c in a)if(j=!1,d=a[c],e=k[c]&&k[c].call(this,d,c),e!==!1){e!==w&&(d=e);if(c==="d")d&&
d.join&&(d=d.join(" ")),/(NaN| {2}|^$)/.test(d)&&(d="M 0 0");else if(c==="x"&&h==="text")for(e=0;e<g.childNodes.length;e++)f=g.childNodes[e],C(f,"x")===C(g,"x")&&C(f,"x",d);else if(this.rotation&&(c==="x"||c==="y"))p=!0;else if(c==="fill")d=i.color(d,g,c);else if(h==="circle"&&(c==="x"||c==="y"))c={x:"cx",y:"cy"}[c]||c;else if(h==="rect"&&c==="r")C(g,{rx:d,ry:d}),j=!0;else if(c==="translateX"||c==="translateY"||c==="rotation"||c==="verticalAlign"||c==="scaleX"||c==="scaleY")j=p=!0;else if(c==="stroke")d=
i.color(d,g,c);else if(c==="dashstyle")if(c="stroke-dasharray",d=d&&d.toLowerCase(),d==="solid")d=O;else{if(d){d=d.replace("shortdashdotdot","3,1,1,1,1,1,").replace("shortdashdot","3,1,1,1").replace("shortdot","1,1,").replace("shortdash","3,1,").replace("longdash","8,3,").replace(/dot/g,"1,3,").replace("dash","4,3,").replace(/,$/,"").split(",");for(e=d.length;e--;)d[e]=v(d[e])*a["stroke-width"];d=d.join(",")}}else if(c==="width")d=v(d);else if(c==="align")c="text-anchor",d={left:"start",center:"middle",
right:"end"}[d];else if(c==="title")e=g.getElementsByTagName("title")[0],e||(e=z.createElementNS(sa,"title"),g.appendChild(e)),e.textContent=d;c==="strokeWidth"&&(c="stroke-width");if(c==="stroke-width"||c==="stroke"){this[c]=d;if(this.stroke&&this["stroke-width"])C(g,"stroke",this.stroke),C(g,"stroke-width",this["stroke-width"]),this.hasStroke=!0;else if(c==="stroke-width"&&d===0&&this.hasStroke)g.removeAttribute("stroke"),this.hasStroke=!1;j=!0}this.symbolName&&/^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(c)&&
(l||(this.symbolAttr(a),l=!0),j=!0);if(m&&/^(width|height|visibility|x|y|d|transform)$/.test(c))for(e=m.length;e--;)C(m[e],c,c==="height"?q(d-(m[e].cutHeight||0),0):d);if((c==="width"||c==="height")&&h==="rect"&&d<0)d=0;this[c]=d;c==="text"?(d!==this.textStr&&delete this.bBox,this.textStr=d,this.added&&i.buildText(this)):j||C(g,c,d)}p&&this.updateTransform()}return r},addClass:function(a){C(this.element,"class",C(this.element,"class")+" "+a);return this},symbolAttr:function(a){var b=this;n("x,y,r,start,end,width,height,innerR,anchorX,anchorY".split(","),
function(c){b[c]=o(a[c],b[c])});b.attr({d:b.renderer.symbols[b.symbolName](b.x,b.y,b.width,b.height,b)})},clip:function(a){return this.attr("clip-path",a?"url("+this.renderer.url+"#"+a.id+")":O)},crisp:function(a,b,c,d,e){var f,g={},h={},i,a=a||this.strokeWidth||this.attr&&this.attr("stroke-width")||0;i=t(a)%2/2;h.x=T(b||this.x||0)+i;h.y=T(c||this.y||0)+i;h.width=T((d||this.width||0)-2*i);h.height=T((e||this.height||0)-2*i);h.strokeWidth=a;for(f in h)this[f]!==h[f]&&(this[f]=g[f]=h[f]);return g},
css:function(a){var b=this.element,b=a&&a.width&&b.nodeName.toLowerCase()==="text",c,d="",e=function(a,b){return"-"+b.toLowerCase()};if(a&&a.color)a.fill=a.color;this.styles=a=u(this.styles,a);$&&b&&delete a.width;if(Da&&!Z)b&&delete a.width,M(this.element,a);else{for(c in a)d+=c.replace(/([A-Z])/g,e)+":"+a[c]+";";this.attr({style:d})}b&&this.added&&this.renderer.buildText(this);return this},on:function(a,b){if(fb&&a==="click")this.element.ontouchstart=function(a){a.preventDefault();b()};this.element["on"+
a]=b;return this},setRadialReference:function(a){this.element.radialReference=a;return this},translate:function(a,b){return this.attr({translateX:a,translateY:b})},invert:function(){this.inverted=!0;this.updateTransform();return this},htmlCss:function(a){var b=this.element;if(b=a&&b.tagName==="SPAN"&&a.width)delete a.width,this.textWidth=b,this.updateTransform();this.styles=u(this.styles,a);M(this.element,a);return this},htmlGetBBox:function(){var a=this.element,b=this.bBox;if(!b){if(a.nodeName===
"text")a.style.position="absolute";b=this.bBox={x:a.offsetLeft,y:a.offsetTop,width:a.offsetWidth,height:a.offsetHeight}}return b},htmlUpdateTransform:function(){if(this.added){var a=this.renderer,b=this.element,c=this.translateX||0,d=this.translateY||0,e=this.x||0,f=this.y||0,g=this.textAlign||"left",h={left:0,center:0.5,right:1}[g],i=g&&g!=="left",j=this.shadows;if(c||d)M(b,{marginLeft:c,marginTop:d}),j&&n(j,function(a){M(a,{marginLeft:c+1,marginTop:d+1})});this.inverted&&n(b.childNodes,function(c){a.invertChild(c,
b)});if(b.tagName==="SPAN"){var k,m,j=this.rotation,l,p=0,r=1,p=0,wb;l=v(this.textWidth);var B=this.xCorr||0,y=this.yCorr||0,I=[j,g,b.innerHTML,this.textWidth].join(",");k={};if(I!==this.cTT){if(s(j))a.isSVG?(B=Da?"-ms-transform":db?"-webkit-transform":eb?"MozTransform":Jb?"-o-transform":"",k[B]=k.transform="rotate("+j+"deg)"):(p=j*bb,r=Y(p),p=ca(p),k.filter=j?["progid:DXImageTransform.Microsoft.Matrix(M11=",r,", M12=",-p,", M21=",p,", M22=",r,", sizingMethod='auto expand')"].join(""):O),M(b,k);k=
o(this.elemWidth,b.offsetWidth);m=o(this.elemHeight,b.offsetHeight);if(k>l&&/[ \-]/.test(b.textContent||b.innerText))M(b,{width:l+"px",display:"block",whiteSpace:"normal"}),k=l;l=a.fontMetrics(b.style.fontSize).b;B=r<0&&-k;y=p<0&&-m;wb=r*p<0;B+=p*l*(wb?1-h:h);y-=r*l*(j?wb?h:1-h:1);i&&(B-=k*h*(r<0?-1:1),j&&(y-=m*h*(p<0?-1:1)),M(b,{textAlign:g}));this.xCorr=B;this.yCorr=y}M(b,{left:e+B+"px",top:f+y+"px"});if(db)m=b.offsetHeight;this.cTT=I}}else this.alignOnAdd=!0},updateTransform:function(){var a=this.translateX||
0,b=this.translateY||0,c=this.scaleX,d=this.scaleY,e=this.inverted,f=this.rotation,g=[];e&&(a+=this.attr("width"),b+=this.attr("height"));(a||b)&&g.push("translate("+a+","+b+")");e?g.push("rotate(90) scale(-1,1)"):f&&g.push("rotate("+f+" "+(this.x||0)+" "+(this.y||0)+")");(s(c)||s(d))&&g.push("scale("+o(c,1)+" "+o(d,1)+")");g.length&&C(this.element,"transform",g.join(" "))},toFront:function(){var a=this.element;a.parentNode.appendChild(a);return this},align:function(a,b,c){var d,e,f,g,h={};e=this.renderer;
f=e.alignedObjects;if(a){if(this.alignOptions=a,this.alignByTranslate=b,!c||fa(c))this.alignTo=d=c||"renderer",ga(f,this),f.push(this),c=null}else a=this.alignOptions,b=this.alignByTranslate,d=this.alignTo;c=o(c,e[d],e);d=a.align;e=a.verticalAlign;f=(c.x||0)+(a.x||0);g=(c.y||0)+(a.y||0);if(d==="right"||d==="center")f+=(c.width-(a.width||0))/{right:1,center:2}[d];h[b?"translateX":"x"]=t(f);if(e==="bottom"||e==="middle")g+=(c.height-(a.height||0))/({bottom:1,middle:2}[e]||1);h[b?"translateY":"y"]=t(g);
this[this.placed?"animate":"attr"](h);this.placed=!0;this.alignAttr=h;return this},getBBox:function(){var a=this.bBox,b=this.renderer,c,d=this.rotation;c=this.element;var e=this.styles,f=d*bb;if(!a){if(c.namespaceURI===sa||b.forExport){try{a=c.getBBox?u({},c.getBBox()):{width:c.offsetWidth,height:c.offsetHeight}}catch(g){}if(!a||a.width<0)a={width:0,height:0}}else a=this.htmlGetBBox();if(b.isSVG){b=a.width;c=a.height;if(Da&&e&&e.fontSize==="11px"&&c.toPrecision(3)===22.7)a.height=c=14;if(d)a.width=
R(c*ca(f))+R(b*Y(f)),a.height=R(c*Y(f))+R(b*ca(f))}this.bBox=a}return a},show:function(){return this.attr({visibility:"visible"})},hide:function(){return this.attr({visibility:"hidden"})},fadeOut:function(a){var b=this;b.animate({opacity:0},{duration:a||150,complete:function(){b.hide()}})},add:function(a){var b=this.renderer,c=a||b,d=c.element||b.box,e=d.childNodes,f=this.element,g=C(f,"zIndex"),h;if(a)this.parentGroup=a;this.parentInverted=a&&a.inverted;this.textStr!==void 0&&b.buildText(this);if(g)c.handleZ=
!0,g=v(g);if(c.handleZ)for(c=0;c<e.length;c++)if(a=e[c],b=C(a,"zIndex"),a!==f&&(v(b)>g||!s(g)&&s(b))){d.insertBefore(f,a);h=!0;break}h||d.appendChild(f);this.added=!0;G(this,"add");return this},safeRemoveChild:function(a){var b=a.parentNode;b&&b.removeChild(a)},destroy:function(){var a=this,b=a.element||{},c=a.shadows,d,e;b.onclick=b.onmouseout=b.onmouseover=b.onmousemove=b.point=null;Ta(a);if(a.clipPath)a.clipPath=a.clipPath.destroy();if(a.stops){for(e=0;e<a.stops.length;e++)a.stops[e]=a.stops[e].destroy();
a.stops=null}a.safeRemoveChild(b);c&&n(c,function(b){a.safeRemoveChild(b)});a.alignTo&&ga(a.renderer.alignedObjects,a);for(d in a)delete a[d];return null},shadow:function(a,b,c){var d=[],e,f,g=this.element,h,i,j,k;if(a){i=o(a.width,3);j=(a.opacity||0.15)/i;k=this.parentInverted?"(-1,-1)":"("+o(a.offsetX,1)+", "+o(a.offsetY,1)+")";for(e=1;e<=i;e++){f=g.cloneNode(0);h=i*2+1-2*e;C(f,{isShadow:"true",stroke:a.color||"black","stroke-opacity":j*e,"stroke-width":h,transform:"translate"+k,fill:O});if(c)C(f,
"height",q(C(f,"height")-h,0)),f.cutHeight=h;b?b.element.appendChild(f):g.parentNode.insertBefore(f,g);d.push(f)}this.shadows=d}return this}};var Ba=function(){this.init.apply(this,arguments)};Ba.prototype={Element:ra,init:function(a,b,c,d){var e=location,f;f=this.createElement("svg").attr({xmlns:sa,version:"1.1"});a.appendChild(f.element);this.isSVG=!0;this.box=f.element;this.boxWrapper=f;this.alignedObjects=[];this.url=(eb||db)&&z.getElementsByTagName("base").length?e.href.replace(/#.*?$/,"").replace(/([\('\)])/g,
"\\$1").replace(/ /g,"%20"):"";this.createElement("desc").add().element.appendChild(z.createTextNode("Created with Highcharts 3.0.0"));this.defs=this.createElement("defs").add();this.forExport=d;this.gradients={};this.setSize(b,c,!1);var g;if(eb&&a.getBoundingClientRect)this.subPixelFix=b=function(){M(a,{left:0,top:0});g=a.getBoundingClientRect();M(a,{left:ja(g.left)-g.left+"px",top:ja(g.top)-g.top+"px"})},b(),J(E,"resize",b)},isHidden:function(){return!this.boxWrapper.getBBox().width},destroy:function(){var a=
this.defs;this.box=null;this.boxWrapper=this.boxWrapper.destroy();Ga(this.gradients||{});this.gradients=null;if(a)this.defs=a.destroy();this.subPixelFix&&ba(E,"resize",this.subPixelFix);return this.alignedObjects=null},createElement:function(a){var b=new this.Element;b.init(this,a);return b},draw:function(){},buildText:function(a){for(var b=a.element,c=this,d=c.forExport,e=o(a.textStr,"").toString().replace(/<(b|strong)>/g,'<span style="font-weight:bold">').replace(/<(i|em)>/g,'<span style="font-style:italic">').replace(/<a/g,
"<span").replace(/<\/(b|strong|i|em|a)>/g,"</span>").split(/<br.*?>/g),f=b.childNodes,g=/style="([^"]+)"/,h=/href="([^"]+)"/,i=C(b,"x"),j=a.styles,k=j&&j.width&&v(j.width),m=j&&j.lineHeight,l=f.length;l--;)b.removeChild(f[l]);k&&!a.added&&this.box.appendChild(b);e[e.length-1]===""&&e.pop();n(e,function(e,f){var l,o=0,e=e.replace(/<span/g,"|||<span").replace(/<\/span>/g,"</span>|||");l=e.split("|||");n(l,function(e){if(e!==""||l.length===1){var p={},n=z.createElementNS(sa,"tspan"),q;g.test(e)&&(q=
e.match(g)[1].replace(/(;| |^)color([ :])/,"$1fill$2"),C(n,"style",q));h.test(e)&&!d&&(C(n,"onclick",'location.href="'+e.match(h)[1]+'"'),M(n,{cursor:"pointer"}));e=(e.replace(/<(.|\n)*?>/g,"")||" ").replace(/</g,"<").replace(/>/g,">");n.appendChild(z.createTextNode(e));o?p.dx=0:p.x=i;C(n,p);!o&&f&&(!Z&&d&&M(n,{display:"block"}),C(n,"dy",m||c.fontMetrics(/px$/.test(n.style.fontSize)?n.style.fontSize:j.fontSize).h,db&&n.offsetHeight));b.appendChild(n);o++;if(k)for(var e=e.replace(/([^\^])-/g,
"$1- ").split(" "),s,t=[];e.length||t.length;)delete a.bBox,s=a.getBBox().width,p=s>k,!p||e.length===1?(e=t,t=[],e.length&&(n=z.createElementNS(sa,"tspan"),C(n,{dy:m||16,x:i}),q&&C(n,"style",q),b.appendChild(n),s>k&&(k=s))):(n.removeChild(n.firstChild),t.unshift(e.pop())),e.length&&n.appendChild(z.createTextNode(e.join(" ").replace(/- /g,"-")))}})})},button:function(a,b,c,d,e,f,g){var h=this.label(a,b,c,null,null,null,null,null,"button"),i=0,j,k,m,l,p,a={x1:0,y1:0,x2:0,y2:1},e=x({"stroke-width":1,
stroke:"#CCCCCC",fill:{linearGradient:a,stops:[[0,"#FEFEFE"],[1,"#F6F6F6"]]},r:2,padding:5,style:{color:"black"}},e);m=e.style;delete e.style;f=x(e,{stroke:"#68A",fill:{linearGradient:a,stops:[[0,"#FFF"],[1,"#ACF"]]}},f);l=f.style;delete f.style;g=x(e,{stroke:"#68A",fill:{linearGradient:a,stops:[[0,"#9BD"],[1,"#CDF"]]}},g);p=g.style;delete g.style;J(h.element,"mouseenter",function(){h.attr(f).css(l)});J(h.element,"mouseleave",function(){j=[e,f,g][i];k=[m,l,p][i];h.attr(j).css(k)});h.setState=function(a){(i=
a)?a===2&&h.attr(g).css(p):h.attr(e).css(m)};return h.on("click",function(){d.call(h)}).attr(e).css(u({cursor:"default"},m))},crispLine:function(a,b){a[1]===a[4]&&(a[1]=a[4]=t(a[1])-b%2/2);a[2]===a[5]&&(a[2]=a[5]=t(a[2])+b%2/2);return a},path:function(a){var b={fill:O};Ca(a)?b.d=a:V(a)&&u(b,a);return this.createElement("path").attr(b)},circle:function(a,b,c){a=V(a)?a:{x:a,y:b,r:c};return this.createElement("circle").attr(a)},arc:function(a,b,c,d,e,f){if(V(a))b=a.y,c=a.r,d=a.innerR,e=a.start,f=a.end,
a=a.x;return this.symbol("arc",a||0,b||0,c||0,c||0,{innerR:d||0,start:e||0,end:f||0})},rect:function(a,b,c,d,e,f){e=V(a)?a.r:e;e=this.createElement("rect").attr({rx:e,ry:e,fill:O});return e.attr(V(a)?a:e.crisp(f,a,b,q(c,0),q(d,0)))},setSize:function(a,b,c){var d=this.alignedObjects,e=d.length;this.width=a;this.height=b;for(this.boxWrapper[o(c,!0)?"animate":"attr"]({width:a,height:b});e--;)d[e].align()},g:function(a){var b=this.createElement("g");return s(a)?b.attr({"class":"highcharts-"+a}):b},image:function(a,
b,c,d,e){var f={preserveAspectRatio:O};arguments.length>1&&u(f,{x:b,y:c,width:d,height:e});f=this.createElement("image").attr(f);f.element.setAttributeNS?f.element.setAttributeNS("http://www.w3.org/1999/xlink","href",a):f.element.setAttribute("hc-svg-href",a);return f},symbol:function(a,b,c,d,e,f){var g,h=this.symbols[a],h=h&&h(t(b),t(c),d,e,f),i=/^url\((.*?)\)$/,j,k;h?(g=this.path(h),u(g,{symbolName:a,x:b,y:c,width:d,height:e}),f&&u(g,f)):i.test(a)&&(k=function(a,b){a.element&&(a.attr({width:b[0],
height:b[1]}),a.alignByTranslate||a.translate(t((d-b[0])/2),t((e-b[1])/2)))},j=a.match(i)[1],a=Lb[j],g=this.image(j).attr({x:b,y:c}),a?k(g,a):(g.attr({width:0,height:0}),U("img",{onload:function(){k(g,Lb[j]=[this.width,this.height])},src:j})));return g},symbols:{circle:function(a,b,c,d){var e=0.166*c;return["M",a+c/2,b,"C",a+c+e,b,a+c+e,b+d,a+c/2,b+d,"C",a-e,b+d,a-e,b,a+c/2,b,"Z"]},square:function(a,b,c,d){return["M",a,b,"L",a+c,b,a+c,b+d,a,b+d,"Z"]},triangle:function(a,b,c,d){return["M",a+c/2,b,
"L",a+c,b+d,a,b+d,"Z"]},"triangle-down":function(a,b,c,d){return["M",a,b,"L",a+c,b,a+c/2,b+d,"Z"]},diamond:function(a,b,c,d){return["M",a+c/2,b,"L",a+c,b+d/2,a+c/2,b+d,a,b+d/2,"Z"]},arc:function(a,b,c,d,e){var f=e.start,c=e.r||c||d,g=e.end-0.001,d=e.innerR,h=e.open,i=Y(f),j=ca(f),k=Y(g),g=ca(g),e=e.end-f<Ja?0:1;return["M",a+c*i,b+c*j,"A",c,c,0,e,1,a+c*k,b+c*g,h?"M":"L",a+d*k,b+d*g,"A",d,d,0,e,0,a+d*i,b+d*j,h?"":"Z"]}},clipRect:function(a,b,c,d){var e="highcharts-"+tb++,f=this.createElement("clipPath").attr({id:e}).add(this.defs),
a=this.rect(a,b,c,d,0).add(f);a.id=e;a.clipPath=f;return a},color:function(a,b,c){var d=this,e,f=/^rgba/,g,h,i,j,k,m,l,p=[];a&&a.linearGradient?g="linearGradient":a&&a.radialGradient&&(g="radialGradient");if(g){c=a[g];h=d.gradients;j=a.stops;b=b.radialReference;Ca(c)&&(a[g]=c={x1:c[0],y1:c[1],x2:c[2],y2:c[3],gradientUnits:"userSpaceOnUse"});g==="radialGradient"&&b&&!s(c.gradientUnits)&&(c=x(c,{cx:b[0]-b[2]/2+c.cx*b[2],cy:b[1]-b[2]/2+c.cy*b[2],r:c.r*b[2],gradientUnits:"userSpaceOnUse"}));for(l in c)l!==
"id"&&p.push(l,c[l]);for(l in j)p.push(j[l]);p=p.join(",");h[p]?a=h[p].id:(c.id=a="highcharts-"+tb++,h[p]=i=d.createElement(g).attr(c).add(d.defs),i.stops=[],n(j,function(a){f.test(a[1])?(e=la(a[1]),k=e.get("rgb"),m=e.get("a")):(k=a[1],m=1);a=d.createElement("stop").attr({offset:a[0],"stop-color":k,"stop-opacity":m}).add(i);i.stops.push(a)}));return"url("+d.url+"#"+a+")"}else return f.test(a)?(e=la(a),C(b,c+"-opacity",e.get("a")),e.get("rgb")):(b.removeAttribute(c+"-opacity"),a)},text:function(a,
b,c,d){var e=P.chart.style,f=$||!Z&&this.forExport;if(d&&!this.forExport)return this.html(a,b,c);b=t(o(b,0));c=t(o(c,0));a=this.createElement("text").attr({x:b,y:c,text:a}).css({fontFamily:e.fontFamily,fontSize:e.fontSize});f&&a.css({position:"absolute"});a.x=b;a.y=c;return a},html:function(a,b,c){var d=P.chart.style,e=this.createElement("span"),f=e.attrSetters,g=e.element,h=e.renderer;f.text=function(a){a!==g.innerHTML&&delete this.bBox;g.innerHTML=a;return!1};f.x=f.y=f.align=function(a,b){b==="align"&&
(b="textAlign");e[b]=a;e.htmlUpdateTransform();return!1};e.attr({text:a,x:t(b),y:t(c)}).css({position:"absolute",whiteSpace:"nowrap",fontFamily:d.fontFamily,fontSize:d.fontSize});e.css=e.htmlCss;if(h.isSVG)e.add=function(a){var b,c=h.box.parentNode,d=[];if(a){if(b=a.div,!b){for(;a;)d.push(a),a=a.parentGroup;n(d.reverse(),function(a){var d;b=a.div=a.div||U(xa,{className:C(a.element,"class")},{position:"absolute",left:(a.translateX||0)+"px",top:(a.translateY||0)+"px"},b||c);d=b.style;u(a.attrSetters,
{translateX:function(a){d.left=a+"px"},translateY:function(a){d.top=a+"px"},visibility:function(a,b){d[b]=a}})})}}else b=c;b.appendChild(g);e.added=!0;e.alignOnAdd&&e.htmlUpdateTransform();return e};return e},fontMetrics:function(a){var a=v(a||11),a=a<24?a+4:t(a*1.2),b=t(a*0.8);return{h:a,b:b}},label:function(a,b,c,d,e,f,g,h,i){function j(){var a,b;a=o.element.style;y=(La===void 0||xb===void 0||r.styles.textAlign)&&o.getBBox();r.width=(La||y.width||0)+2*q+hb;r.height=(xb||y.height||0)+2*q;C=q+p.fontMetrics(a&&
a.fontSize).b;if(z){if(!B)a=t(-I*q),b=h?-C:0,r.box=B=d?p.symbol(d,a,b,r.width,r.height):p.rect(a,b,r.width,r.height,0,v[Nb]),B.add(r);B.attr(x({width:r.width,height:r.height},v));v=null}}function k(){var a=r.styles,a=a&&a.textAlign,b=hb+q*(1-I),c;c=h?0:C;if(s(La)&&(a==="center"||a==="right"))b+={center:0.5,right:1}[a]*(La-y.width);(b!==o.x||c!==o.y)&&o.attr({x:b,y:c});o.x=b;o.y=c}function m(a,b){B?B.attr(a,b):v[a]=b}function l(){o.add(r);r.attr({text:a,x:b,y:c});B&&s(e)&&r.attr({anchorX:e,anchorY:f})}
var p=this,r=p.g(i),o=p.text("",0,0,g).attr({zIndex:1}),B,y,I=0,q=3,hb=0,La,xb,Q,H,D=0,v={},C,g=r.attrSetters,z;J(r,"add",l);g.width=function(a){La=a;return!1};g.height=function(a){xb=a;return!1};g.padding=function(a){s(a)&&a!==q&&(q=a,k());return!1};g.paddingLeft=function(a){s(a)&&a!==hb&&(hb=a,k());return!1};g.align=function(a){I={left:0,center:0.5,right:1}[a];return!1};g.text=function(a,b){o.attr(b,a);j();k();return!1};g[Nb]=function(a,b){z=!0;D=a%2/2;m(b,a);return!1};g.stroke=g.fill=g.r=function(a,
b){b==="fill"&&(z=!0);m(b,a);return!1};g.anchorX=function(a,b){e=a;m(b,a+D-Q);return!1};g.anchorY=function(a,b){f=a;m(b,a-H);return!1};g.x=function(a){r.x=a;a-=I*((La||y.width)+q);Q=t(a);r.attr("translateX",Q);return!1};g.y=function(a){H=r.y=t(a);r.attr("translateY",H);return!1};var A=r.css;return u(r,{css:function(a){if(a){var b={},a=x(a);n("fontSize,fontWeight,fontFamily,color,lineHeight,width".split(","),function(c){a[c]!==w&&(b[c]=a[c],delete a[c])});o.css(b)}return A.call(r,a)},getBBox:function(){return{width:y.width+
2*q,height:y.height+2*q,x:y.x-q,y:y.y-q}},shadow:function(a){B&&B.shadow(a);return r},destroy:function(){ba(r,"add",l);ba(r.element,"mouseenter");ba(r.element,"mouseleave");o&&(o=o.destroy());B&&(B=B.destroy());ra.prototype.destroy.call(r);r=p=j=k=m=l=null}})}};Sa=Ba;var K;if(!Z&&!$){Highcharts.VMLElement=K={init:function(a,b){var c=["<",b,' filled="f" stroked="f"'],d=["position: ","absolute",";"],e=b===xa;(b==="shape"||e)&&d.push("left:0;top:0;width:1px;height:1px;");d.push("visibility: ",e?"hidden":
"visible");c.push(' style="',d.join(""),'"/>');if(b)c=e||b==="span"||b==="img"?c.join(""):a.prepVML(c),this.element=U(c);this.renderer=a;this.attrSetters={}},add:function(a){var b=this.renderer,c=this.element,d=b.box,d=a?a.element||a:d;a&&a.inverted&&b.invertChild(c,d);d.appendChild(c);this.added=!0;this.alignOnAdd&&!this.deferUpdateTransform&&this.updateTransform();G(this,"add");return this},updateTransform:ra.prototype.htmlUpdateTransform,attr:function(a,b){var c,d,e,f=this.element||{},g=f.style,
h=f.nodeName,i=this.renderer,j=this.symbolName,k,m=this.shadows,l,p=this.attrSetters,r=this;fa(a)&&s(b)&&(c=a,a={},a[c]=b);if(fa(a))c=a,r=c==="strokeWidth"||c==="stroke-width"?this.strokeweight:this[c];else for(c in a)if(d=a[c],l=!1,e=p[c]&&p[c].call(this,d,c),e!==!1&&d!==null){e!==w&&(d=e);if(j&&/^(x|y|r|start|end|width|height|innerR|anchorX|anchorY)/.test(c))k||(this.symbolAttr(a),k=!0),l=!0;else if(c==="d"){d=d||[];this.d=d.join(" ");e=d.length;for(l=[];e--;)if(ua(d[e]))l[e]=t(d[e]*10)-5;else if(d[e]===
"Z")l[e]="x";else if(l[e]=d[e],d[e]==="wa"||d[e]==="at")l[e+5]===l[e+7]&&(l[e+7]-=1),l[e+6]===l[e+8]&&(l[e+8]-=1);d=l.join(" ")||"x";f.path=d;if(m)for(e=m.length;e--;)m[e].path=m[e].cutOff?this.cutOffPath(d,m[e].cutOff):d;l=!0}else if(c==="visibility"){if(m)for(e=m.length;e--;)m[e].style[c]=d;h==="DIV"&&(d=d==="hidden"?"-999em":0,cb||(g[c]=d?"hidden":"visible"),c="top");g[c]=d;l=!0}else if(c==="zIndex")d&&(g[c]=d),l=!0;else if(ka(c,["x","y","width","height"])!==-1)this[c]=d,c==="x"||c==="y"?c={x:"left",
y:"top"}[c]:d=q(0,d),this.updateClipping?(this[c]=d,this.updateClipping()):g[c]=d,l=!0;else if(c==="class"&&h==="DIV")f.className=d;else if(c==="stroke")d=i.color(d,f,c),c="strokecolor";else if(c==="stroke-width"||c==="strokeWidth")f.stroked=d?!0:!1,c="strokeweight",this[c]=d,ua(d)&&(d+="px");else if(c==="dashstyle")(f.getElementsByTagName("stroke")[0]||U(i.prepVML(["<stroke/>"]),null,null,f))[c]=d||"solid",this.dashstyle=d,l=!0;else if(c==="fill")if(h==="SPAN")g.color=d;else{if(h!=="IMG")f.filled=
d!==O?!0:!1,d=i.color(d,f,c,this),c="fillcolor"}else if(c==="opacity")l=!0;else if(h==="shape"&&c==="rotation")this[c]=d,f.style.left=-t(ca(d*bb)+1)+"px",f.style.top=t(Y(d*bb))+"px";else if(c==="translateX"||c==="translateY"||c==="rotation")this[c]=d,this.updateTransform(),l=!0;else if(c==="text")this.bBox=null,f.innerHTML=d,l=!0;l||(cb?f[c]=d:C(f,c,d))}return r},clip:function(a){var b=this,c;a?(c=a.members,ga(c,b),c.push(b),b.destroyClip=function(){ga(c,b)},a=a.getCSS(b)):(b.destroyClip&&b.destroyClip(),
a={clip:cb?"inherit":"rect(auto)"});return b.css(a)},css:ra.prototype.htmlCss,safeRemoveChild:function(a){a.parentNode&&Ra(a)},destroy:function(){this.destroyClip&&this.destroyClip();return ra.prototype.destroy.apply(this)},on:function(a,b){this.element["on"+a]=function(){var a=E.event;a.target=a.srcElement;b(a)};return this},cutOffPath:function(a,b){var c,a=a.split(/[ ,]/);c=a.length;if(c===9||c===11)a[c-4]=a[c-2]=v(a[c-2])-10*b;return a.join(" ")},shadow:function(a,b,c){var d=[],e,f=this.element,
g=this.renderer,h,i=f.style,j,k=f.path,m,l,p,r;k&&typeof k.value!=="string"&&(k="x");l=k;if(a){p=o(a.width,3);r=(a.opacity||0.15)/p;for(e=1;e<=3;e++){m=p*2+1-2*e;c&&(l=this.cutOffPath(k.value,m+0.5));j=['<shape isShadow="true" strokeweight="',m,'" filled="false" path="',l,'" coordsize="10 10" style="',f.style.cssText,'" />'];h=U(g.prepVML(j),null,{left:v(i.left)+o(a.offsetX,1),top:v(i.top)+o(a.offsetY,1)});if(c)h.cutOff=m+1;j=['<stroke color="',a.color||"black",'" opacity="',r*e,'"/>'];U(g.prepVML(j),
null,null,h);b?b.element.appendChild(h):f.parentNode.insertBefore(h,f);d.push(h)}this.shadows=d}return this}};K=ea(ra,K);var ma={Element:K,isIE8:za.indexOf("MSIE 8.0")>-1,init:function(a,b,c){var d,e;this.alignedObjects=[];d=this.createElement(xa);e=d.element;e.style.position="relative";a.appendChild(d.element);this.isVML=!0;this.box=e;this.boxWrapper=d;this.setSize(b,c,!1);if(!z.namespaces.hcv)z.namespaces.add("hcv","urn:schemas-microsoft-com:vml"),z.createStyleSheet().cssText="hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke{ behavior:url(#default#VML); display: inline-block; } "},
isHidden:function(){return!this.box.offsetWidth},clipRect:function(a,b,c,d){var e=this.createElement(),f=V(a);return u(e,{members:[],left:f?a.x:a,top:f?a.y:b,width:f?a.width:c,height:f?a.height:d,getCSS:function(a){var b=a.element,c=b.nodeName,a=a.inverted,d=this.top-(c==="shape"?b.offsetTop:0),e=this.left,b=e+this.width,f=d+this.height,d={clip:"rect("+t(a?e:d)+"px,"+t(a?f:b)+"px,"+t(a?b:f)+"px,"+t(a?d:e)+"px)"};!a&&cb&&c==="DIV"&&u(d,{width:b+"px",height:f+"px"});return d},updateClipping:function(){n(e.members,
function(a){a.css(e.getCSS(a))})}})},color:function(a,b,c,d){var e=this,f,g=/^rgba/,h,i,j=O;a&&a.linearGradient?i="gradient":a&&a.radialGradient&&(i="pattern");if(i){var k,m,l=a.linearGradient||a.radialGradient,p,r,o,B,y,q="",a=a.stops,s,t=[],w=function(){h=['<fill colors="'+t.join(",")+'" opacity="',o,'" o:opacity2="',r,'" type="',i,'" ',q,'focus="100%" method="any" />'];U(e.prepVML(h),null,null,b)};p=a[0];s=a[a.length-1];p[0]>0&&a.unshift([0,p[1]]);s[0]<1&&a.push([1,s[1]]);n(a,function(a,b){g.test(a[1])?
(f=la(a[1]),k=f.get("rgb"),m=f.get("a")):(k=a[1],m=1);t.push(a[0]*100+"% "+k);b?(o=m,B=k):(r=m,y=k)});if(c==="fill")if(i==="gradient")c=l.x1||l[0]||0,a=l.y1||l[1]||0,p=l.x2||l[2]||0,l=l.y2||l[3]||0,q='angle="'+(90-N.atan((l-a)/(p-c))*180/Ja)+'"',w();else{var j=l.r,u=j*2,Q=j*2,H=l.cx,D=l.cy,x=b.radialReference,v,j=function(){x&&(v=d.getBBox(),H+=(x[0]-v.x)/v.width-0.5,D+=(x[1]-v.y)/v.height-0.5,u*=x[2]/v.width,Q*=x[2]/v.height);q='src="'+P.global.VMLRadialGradientURL+'" size="'+u+","+Q+'" origin="0.5,0.5" position="'+
H+","+D+'" color2="'+y+'" ';w()};d.added?j():J(d,"add",j);j=B}else j=k}else if(g.test(a)&&b.tagName!=="IMG")f=la(a),h=["<",c,' opacity="',f.get("a"),'"/>'],U(this.prepVML(h),null,null,b),j=f.get("rgb");else{j=b.getElementsByTagName(c);if(j.length)j[0].opacity=1,j[0].type="solid";j=a}return j},prepVML:function(a){var b=this.isIE8,a=a.join("");b?(a=a.replace("/>",' xmlns="urn:schemas-microsoft-com:vml" />'),a=a.indexOf('style="')===-1?a.replace("/>",' style="display:inline-block;behavior:url(#default#VML);" />'):
a.replace('style="','style="display:inline-block;behavior:url(#default#VML);')):a=a.replace("<","<hcv:");return a},text:Ba.prototype.html,path:function(a){var b={coordsize:"10 10"};Ca(a)?b.d=a:V(a)&&u(b,a);return this.createElement("shape").attr(b)},circle:function(a,b,c){if(V(a))c=a.r,b=a.y,a=a.x;return this.symbol("circle").attr({x:a-c,y:b-c,width:2*c,height:2*c})},g:function(a){var b;a&&(b={className:"highcharts-"+a,"class":"highcharts-"+a});return this.createElement(xa).attr(b)},image:function(a,
b,c,d,e){var f=this.createElement("img").attr({src:a});arguments.length>1&&f.attr({x:b,y:c,width:d,height:e});return f},rect:function(a,b,c,d,e,f){if(V(a))b=a.y,c=a.width,d=a.height,f=a.strokeWidth,a=a.x;var g=this.symbol("rect");g.r=e;return g.attr(g.crisp(f,a,b,q(c,0),q(d,0)))},invertChild:function(a,b){var c=b.style;M(a,{flip:"x",left:v(c.width)-1,top:v(c.height)-1,rotation:-90})},symbols:{arc:function(a,b,c,d,e){var f=e.start,g=e.end,h=e.r||c||d,c=e.innerR,d=Y(f),i=ca(f),j=Y(g),k=ca(g);if(g-f===
0)return["x"];f=["wa",a-h,b-h,a+h,b+h,a+h*d,b+h*i,a+h*j,b+h*k];e.open&&!c&&f.push("e","M",a,b);f.push("at",a-c,b-c,a+c,b+c,a+c*j,b+c*k,a+c*d,b+c*i,"x","e");return f},circle:function(a,b,c,d){return["wa",a,b,a+c,b+d,a+c,b+d/2,a+c,b+d/2,"e"]},rect:function(a,b,c,d,e){var f=a+c,g=b+d,h;!s(e)||!e.r?f=Ba.prototype.symbols.square.apply(0,arguments):(h=F(e.r,c,d),f=["M",a+h,b,"L",f-h,b,"wa",f-2*h,b,f,b+2*h,f-h,b,f,b+h,"L",f,g-h,"wa",f-2*h,g-2*h,f,g,f,g-h,f-h,g,"L",a+h,g,"wa",a,g-2*h,a+2*h,g,a+h,g,a,g-h,
"L",a,b+h,"wa",a,b,a+2*h,b+2*h,a,b+h,a+h,b,"x","e"]);return f}}};Highcharts.VMLRenderer=K=function(){this.init.apply(this,arguments)};K.prototype=x(Ba.prototype,ma);Sa=K}var Qb;if($)Highcharts.CanVGRenderer=K=function(){sa="http://www.w3.org/1999/xhtml"},K.prototype.symbols={},Qb=function(){function a(){var a=b.length,d;for(d=0;d<a;d++)b[d]();b=[]}var b=[];return{push:function(c,d){b.length===0&&Sb(d,a);b.push(c)}}}(),Sa=K;Ia.prototype={addLabel:function(){var a=this.axis,b=a.options,c=a.chart,d=
a.horiz,e=a.categories,f=a.series[0]&&a.series[0].names,g=this.pos,h=b.labels,i=a.tickPositions,d=d&&e&&!h.step&&!h.staggerLines&&!h.rotation&&c.plotWidth/i.length||!d&&c.plotWidth/2,j=g===i[0],k=g===i[i.length-1],f=e?o(e[g],f&&f[g],g):g,e=this.label,i=i.info,m;a.isDatetimeAxis&&i&&(m=b.dateTimeLabelFormats[i.higherRanks[g]||i.unitName]);this.isFirst=j;this.isLast=k;b=a.labelFormatter.call({axis:a,chart:c,isFirst:j,isLast:k,dateTimeLabelFormat:m,value:a.isLog?ia(da(f)):f});g=d&&{width:q(1,t(d-2*(h.padding||
10)))+"px"};g=u(g,h.style);if(s(e))e&&e.attr({text:b}).css(g);else{d={align:h.align};if(ua(h.rotation))d.rotation=h.rotation;this.label=s(b)&&h.enabled?c.renderer.text(b,0,0,h.useHTML).attr(d).css(g).add(a.labelGroup):null}},getLabelSize:function(){var a=this.label,b=this.axis;return a?(this.labelBBox=a.getBBox())[b.horiz?"height":"width"]:0},getLabelSides:function(){var a=this.axis.options.labels,b=this.labelBBox.width,a=b*{left:0,center:0.5,right:1}[a.align]-a.x;return[-a,b-a]},handleOverflow:function(a,
b){var c=!0,d=this.axis,e=d.chart,f=this.isFirst,g=this.isLast,h=b.x,i=d.reversed,j=d.tickPositions;if(f||g){var k=this.getLabelSides(),m=k[0],k=k[1],e=e.plotLeft,l=e+d.len,j=(d=d.ticks[j[a+(f?1:-1)]])&&d.label.xy&&d.label.xy.x+d.getLabelSides()[f?0:1];f&&!i||g&&i?h+m<e&&(h=e-m,d&&h+k>j&&(c=!1)):h+k>l&&(h=l-k,d&&h+m<j&&(c=!1));b.x=h}return c},getPosition:function(a,b,c,d){var e=this.axis,f=e.chart,g=d&&f.oldChartHeight||f.chartHeight;return{x:a?e.translate(b+c,null,null,d)+e.transB:e.left+e.offset+
(e.opposite?(d&&f.oldChartWidth||f.chartWidth)-e.right-e.left:0),y:a?g-e.bottom+e.offset-(e.opposite?e.height:0):g-e.translate(b+c,null,null,d)-e.transB}},getLabelPosition:function(a,b,c,d,e,f,g,h){var i=this.axis,j=i.transA,k=i.reversed,i=i.staggerLines,a=a+e.x-(f&&d?f*j*(k?-1:1):0),b=b+e.y-(f&&!d?f*j*(k?1:-1):0);s(e.y)||(b+=v(c.styles.lineHeight)*0.9-c.getBBox().height/2);i&&(b+=g/(h||1)%i*16);return{x:a,y:b}},getMarkPath:function(a,b,c,d,e,f){return f.crispLine(["M",a,b,"L",a+(e?0:-c),b+(e?c:0)],
d)},render:function(a,b,c){var d=this.axis,e=d.options,f=d.chart.renderer,g=d.horiz,h=this.type,i=this.label,j=this.pos,k=e.labels,m=this.gridLine,l=h?h+"Grid":"grid",p=h?h+"Tick":"tick",r=e[l+"LineWidth"],n=e[l+"LineColor"],B=e[l+"LineDashStyle"],y=e[p+"Length"],l=e[p+"Width"]||0,q=e[p+"Color"],s=e[p+"Position"],p=this.mark,t=k.step,u=!0,v=d.tickmarkOffset,Q=this.getPosition(g,j,v,b),H=Q.x,Q=Q.y,D=g&&H===d.pos||!g&&Q===d.pos+d.len?-1:1,x=d.staggerLines;this.isActive=!0;if(r){j=d.getPlotLinePath(j+
v,r*D,b,!0);if(m===w){m={stroke:n,"stroke-width":r};if(B)m.dashstyle=B;if(!h)m.zIndex=1;if(b)m.opacity=0;this.gridLine=m=r?f.path(j).attr(m).add(d.gridGroup):null}if(!b&&m&&j)m[this.isNew?"attr":"animate"]({d:j,opacity:c})}if(l&&y)s==="inside"&&(y=-y),d.opposite&&(y=-y),b=this.getMarkPath(H,Q,y,l*D,g,f),p?p.animate({d:b,opacity:c}):this.mark=f.path(b).attr({stroke:q,"stroke-width":l,opacity:c}).add(d.axisGroup);if(i&&!isNaN(H))i.xy=Q=this.getLabelPosition(H,Q,i,g,k,v,a,t),this.isFirst&&!o(e.showFirstLabel,
1)||this.isLast&&!o(e.showLastLabel,1)?u=!1:!x&&g&&k.overflow==="justify"&&!this.handleOverflow(a,Q)&&(u=!1),t&&a%t&&(u=!1),u&&!isNaN(Q.y)?(Q.opacity=c,i[this.isNew?"attr":"animate"](Q),this.isNew=!1):i.attr("y",-9999)},destroy:function(){Ga(this,this.axis)}};ob.prototype={render:function(){var a=this,b=a.axis,c=b.horiz,d=(b.pointRange||0)/2,e=a.options,f=e.label,g=a.label,h=e.width,i=e.to,j=e.from,k=s(j)&&s(i),m=e.value,l=e.dashStyle,p=a.svgElem,r=[],n,B=e.color,y=e.zIndex,I=e.events,t=b.chart.renderer;
b.isLog&&(j=na(j),i=na(i),m=na(m));if(h){if(r=b.getPlotLinePath(m,h),d={stroke:B,"stroke-width":h},l)d.dashstyle=l}else if(k){if(j=q(j,b.min-d),i=F(i,b.max+d),r=b.getPlotBandPath(j,i,e),d={fill:B},e.borderWidth)d.stroke=e.borderColor,d["stroke-width"]=e.borderWidth}else return;if(s(y))d.zIndex=y;if(p)r?p.animate({d:r},null,p.onGetPath):(p.hide(),p.onGetPath=function(){p.show()});else if(r&&r.length&&(a.svgElem=p=t.path(r).attr(d).add(),I))for(n in e=function(b){p.on(b,function(c){I[b].apply(a,[c])})},
I)e(n);if(f&&s(f.text)&&r&&r.length&&b.width>0&&b.height>0){f=x({align:c&&k&&"center",x:c?!k&&4:10,verticalAlign:!c&&k&&"middle",y:c?k?16:10:k?6:-4,rotation:c&&!k&&90},f);if(!g)a.label=g=t.text(f.text,0,0).attr({align:f.textAlign||f.align,rotation:f.rotation,zIndex:y}).css(f.style).add();b=[r[1],r[4],o(r[6],r[1])];r=[r[2],r[5],o(r[7],r[2])];c=Fa(b);k=Fa(r);g.align(f,!1,{x:c,y:k,width:pa(b)-c,height:pa(r)-k});g.show()}else g&&g.hide();return a},destroy:function(){ga(this.axis.plotLinesAndBands,this);
Ga(this,this.axis)}};Ib.prototype={destroy:function(){Ga(this,this.axis)},setTotal:function(a){this.cum=this.total=a},render:function(a){var b=this.options,c=b.formatter.call(this);this.label?this.label.attr({text:c,visibility:"hidden"}):this.label=this.axis.chart.renderer.text(c,0,0,b.useHTML).css(b.style).attr({align:this.textAlign,rotation:b.rotation,visibility:"hidden"}).add(a)},setOffset:function(a,b){var c=this.axis,d=c.chart,e=d.inverted,f=this.isNegative,g=c.translate(this.percent?100:this.total,
0,0,0,1),c=c.translate(0),c=R(g-c),h=d.xAxis[0].translate(this.x)+a,i=d.plotHeight,f={x:e?f?g:g-c:h,y:e?i-h-b:f?i-g-c:i-g,width:e?c:b,height:e?b:c};if(e=this.label)e.align(this.alignOptions,null,f),f=e.alignAttr,e.attr({visibility:this.options.crop===!1||d.isInsidePlot(f.x,f.y)?Z?"inherit":"visible":"hidden"})}};ab.prototype={defaultOptions:{dateTimeLabelFormats:{millisecond:"%H:%M:%S.%L",second:"%H:%M:%S",minute:"%H:%M",hour:"%H:%M",day:"%e. %b",week:"%e. %b",month:"%b '%y",year:"%Y"},endOnTick:!1,
gridLineColor:"#C0C0C0",labels:L,lineColor:"#C0D0E0",lineWidth:1,minPadding:0.01,maxPadding:0.01,minorGridLineColor:"#E0E0E0",minorGridLineWidth:1,minorTickColor:"#A0A0A0",minorTickLength:2,minorTickPosition:"outside",startOfWeek:1,startOnTick:!1,tickColor:"#C0D0E0",tickLength:5,tickmarkPlacement:"between",tickPixelInterval:100,tickPosition:"outside",tickWidth:1,title:{align:"middle",style:{color:"#4d759e",fontWeight:"bold"}},type:"linear"},defaultYAxisOptions:{endOnTick:!0,gridLineWidth:1,tickPixelInterval:72,
showLastLabel:!0,labels:{align:"right",x:-8,y:3},lineWidth:0,maxPadding:0.05,minPadding:0.05,startOnTick:!0,tickWidth:0,title:{rotation:270,text:"Values"},stackLabels:{enabled:!1,formatter:function(){return this.total},style:L.style}},defaultLeftAxisOptions:{labels:{align:"right",x:-8,y:null},title:{rotation:270}},defaultRightAxisOptions:{labels:{align:"left",x:8,y:null},title:{rotation:90}},defaultBottomAxisOptions:{labels:{align:"center",x:0,y:14},title:{rotation:0}},defaultTopAxisOptions:{labels:{align:"center",
x:0,y:-5},title:{rotation:0}},init:function(a,b){var c=b.isX;this.horiz=a.inverted?!c:c;this.xOrY=(this.isXAxis=c)?"x":"y";this.opposite=b.opposite;this.side=this.horiz?this.opposite?0:2:this.opposite?1:3;this.setOptions(b);var d=this.options,e=d.type;this.labelFormatter=d.labels.formatter||this.defaultLabelFormatter;this.staggerLines=this.horiz&&d.labels.staggerLines;this.userOptions=b;this.minPixelPadding=0;this.chart=a;this.reversed=d.reversed;this.zoomEnabled=d.zoomEnabled!==!1;this.categories=
d.categories||e==="category";this.isLog=e==="logarithmic";this.isDatetimeAxis=e==="datetime";this.isLinked=s(d.linkedTo);this.tickmarkOffset=this.categories&&d.tickmarkPlacement==="between"?0.5:0;this.ticks={};this.minorTicks={};this.plotLinesAndBands=[];this.alternateBands={};this.len=0;this.minRange=this.userMinRange=d.minRange||d.maxZoom;this.range=d.range;this.offset=d.offset||0;this.stacks={};this._stacksTouched=0;this.min=this.max=null;var f,d=this.options.events;ka(this,a.axes)===-1&&(a.axes.push(this),
a[c?"xAxis":"yAxis"].push(this));this.series=this.series||[];if(a.inverted&&c&&this.reversed===w)this.reversed=!0;this.removePlotLine=this.removePlotBand=this.removePlotBandOrLine;for(f in d)J(this,f,d[f]);if(this.isLog)this.val2lin=na,this.lin2val=da},setOptions:function(a){this.options=x(this.defaultOptions,this.isXAxis?{}:this.defaultYAxisOptions,[this.defaultTopAxisOptions,this.defaultRightAxisOptions,this.defaultBottomAxisOptions,this.defaultLeftAxisOptions][this.side],x(P[this.isXAxis?"xAxis":
"yAxis"],a))},update:function(a,b){var c=this.chart,a=c.options[this.xOrY+"Axis"][this.options.index]=x(this.userOptions,a);this.destroy();this._addedPlotLB=!1;this.init(c,a);c.isDirtyBox=!0;o(b,!0)&&c.redraw()},remove:function(a){var b=this.chart,c=this.xOrY+"Axis";n(this.series,function(a){a.remove(!1)});ga(b.axes,this);ga(b[c],this);b.options[c].splice(this.options.index,1);this.destroy();b.isDirtyBox=!0;o(a,!0)&&b.redraw()},defaultLabelFormatter:function(){var a=this.axis,b=this.value,c=a.categories,
d=this.dateTimeLabelFormat,e=P.lang.numericSymbols,f=e&&e.length,g,h=a.options.labels.format,a=a.isLog?b:a.tickInterval;if(h)g=Ea(h,this);else if(c)g=b;else if(d)g=Ua(d,b);else if(f&&a>=1E3)for(;f--&&g===w;)c=Math.pow(1E3,f+1),a>=c&&e[f]!==null&&(g=Na(b/c,-1)+e[f]);g===w&&(g=b>=1E3?Na(b,0):Na(b,-1));return g},getSeriesExtremes:function(){var a=this,b=a.chart,c=a.stacks,d=[],e=[],f=a._stacksTouched+=1,g,h;a.hasVisibleSeries=!1;a.dataMin=a.dataMax=null;n(a.series,function(g){if(g.visible||!b.options.chart.ignoreHiddenSeries){var j=
g.options,k,m,l,p,r,n,B,y,I,t=j.threshold,u,v=[],x=0;a.hasVisibleSeries=!0;if(a.isLog&&t<=0)t=j.threshold=null;if(a.isXAxis){if(j=g.xData,j.length)a.dataMin=F(o(a.dataMin,j[0]),Fa(j)),a.dataMax=q(o(a.dataMax,j[0]),pa(j))}else{var Q,H,D,C=g.cropped,z=g.xAxis.getExtremes(),A=!!g.modifyValue;k=j.stacking;a.usePercentage=k==="percent";if(k)r=j.stack,p=g.type+o(r,""),n="-"+p,g.stackKey=p,m=d[p]||[],d[p]=m,l=e[n]||[],e[n]=l;if(a.usePercentage)a.dataMin=0,a.dataMax=99;j=g.processedXData;B=g.processedYData;
u=B.length;for(h=0;h<u;h++){y=j[h];I=B[h];if(k)H=(Q=I<t)?l:m,D=Q?n:p,s(H[y])?(H[y]=ia(H[y]+I),I=[I,H[y]]):H[y]=I,c[D]||(c[D]={}),c[D][y]||(c[D][y]=new Ib(a,a.options.stackLabels,Q,y,r,k)),c[D][y].setTotal(H[y]),c[D][y].touched=f;if(I!==null&&I!==w&&(!a.isLog||I>0))if(A&&(I=g.modifyValue(I)),g.getExtremesFromAll||C||(j[h+1]||y)>=z.min&&(j[h-1]||y)<=z.max)if(y=I.length)for(;y--;)I[y]!==null&&(v[x++]=I[y]);else v[x++]=I}if(!a.usePercentage&&v.length)g.dataMin=k=Fa(v),g.dataMax=g=pa(v),a.dataMin=F(o(a.dataMin,
k),k),a.dataMax=q(o(a.dataMax,g),g);if(s(t))if(a.dataMin>=t)a.dataMin=t,a.ignoreMinPadding=!0;else if(a.dataMax<t)a.dataMax=t,a.ignoreMaxPadding=!0}}});for(g in c)for(h in c[g])c[g][h].touched<f&&(c[g][h].destroy(),delete c[g][h])},translate:function(a,b,c,d,e,f){var g=this.len,h=1,i=0,j=d?this.oldTransA:this.transA,d=d?this.oldMin:this.min,k=this.minPixelPadding,e=(this.options.ordinal||this.isLog&&e)&&this.lin2val;if(!j)j=this.transA;c&&(h*=-1,i=g);this.reversed&&(h*=-1,i-=h*g);b?(a=a*h+i,a-=k,
a=a/j+d,e&&(a=this.lin2val(a))):(e&&(a=this.val2lin(a)),a=h*(a-d)*j+i+h*k+(f?j*this.pointRange/2:0));return a},toPixels:function(a,b){return this.translate(a,!1,!this.horiz,null,!0)+(b?0:this.pos)},toValue:function(a,b){return this.translate(a-(b?0:this.pos),!0,!this.horiz,null,!0)},getPlotLinePath:function(a,b,c,d){var e=this.chart,f=this.left,g=this.top,h,i,j,a=this.translate(a,null,null,c),k=c&&e.oldChartHeight||e.chartHeight,m=c&&e.oldChartWidth||e.chartWidth,l;h=this.transB;c=i=t(a+h);h=j=t(k-
a-h);if(isNaN(a))l=!0;else if(this.horiz){if(h=g,j=k-this.bottom,c<f||c>f+this.width)l=!0}else if(c=f,i=m-this.right,h<g||h>g+this.height)l=!0;return l&&!d?null:e.renderer.crispLine(["M",c,h,"L",i,j],b||0)},getPlotBandPath:function(a,b){var c=this.getPlotLinePath(b),d=this.getPlotLinePath(a);d&&c?d.push(c[4],c[5],c[1],c[2]):d=null;return d},getLinearTickPositions:function(a,b,c){for(var d,b=ia(T(b/a)*a),c=ia(ja(c/a)*a),e=[];b<=c;){e.push(b);b=ia(b+a);if(b===d)break;d=b}return e},getLogTickPositions:function(a,
b,c,d){var e=this.options,f=this.len,g=[];if(!d)this._minorAutoInterval=null;if(a>=0.5)a=t(a),g=this.getLinearTickPositions(a,b,c);else if(a>=0.08)for(var f=T(b),h,i,j,k,m,e=a>0.3?[1,2,4]:a>0.15?[1,2,4,6,8]:[1,2,3,4,5,6,7,8,9];f<c+1&&!m;f++){i=e.length;for(h=0;h<i&&!m;h++)j=na(da(f)*e[h]),j>b&&k<=c&&g.push(k),k>c&&(m=!0),k=j}else if(b=da(b),c=da(c),a=e[d?"minorTickInterval":"tickInterval"],a=o(a==="auto"?null:a,this._minorAutoInterval,(c-b)*(e.tickPixelInterval/(d?5:1))/((d?f/this.tickPositions.length:
f)||1)),a=ib(a,null,N.pow(10,T(N.log(a)/N.LN10))),g=Ka(this.getLinearTickPositions(a,b,c),na),!d)this._minorAutoInterval=a/5;if(!d)this.tickInterval=a;return g},getMinorTickPositions:function(){var a=this.options,b=this.tickPositions,c=this.minorTickInterval,d=[],e;if(this.isLog){e=b.length;for(a=1;a<e;a++)d=d.concat(this.getLogTickPositions(c,b[a-1],b[a],!0))}else if(this.isDatetimeAxis&&a.minorTickInterval==="auto")d=d.concat(Ab(yb(c),this.min,this.max,a.startOfWeek)),d[0]<this.min&&d.shift();else for(b=
this.min+(b[0]-this.min)%c;b<=this.max;b+=c)d.push(b);return d},adjustForMinRange:function(){var a=this.options,b=this.min,c=this.max,d,e=this.dataMax-this.dataMin>=this.minRange,f,g,h,i,j;if(this.isXAxis&&this.minRange===w&&!this.isLog)s(a.min)||s(a.max)?this.minRange=null:(n(this.series,function(a){i=a.xData;for(g=j=a.xIncrement?1:i.length-1;g>0;g--)if(h=i[g]-i[g-1],f===w||h<f)f=h}),this.minRange=F(f*5,this.dataMax-this.dataMin));if(c-b<this.minRange){var k=this.minRange;d=(k-c+b)/2;d=[b-d,o(a.min,
b-d)];if(e)d[2]=this.dataMin;b=pa(d);c=[b+k,o(a.max,b+k)];if(e)c[2]=this.dataMax;c=Fa(c);c-b<k&&(d[0]=c-k,d[1]=o(a.min,c-k),b=pa(d))}this.min=b;this.max=c},setAxisTranslation:function(a){var b=this.max-this.min,c=0,d,e=0,f=0,g=this.linkedParent,h=this.transA;if(this.isXAxis)g?(e=g.minPointOffset,f=g.pointRangePadding):n(this.series,function(a){var g=a.pointRange,h=a.options.pointPlacement,m=a.closestPointRange;g>b&&(g=0);c=q(c,g);e=q(e,h?0:g/2);f=q(f,h==="on"?0:g);!a.noSharedTooltip&&s(m)&&(d=s(d)?
F(d,m):m)}),this.minPointOffset=e,this.pointRangePadding=f,this.pointRange=F(c,b),this.closestPointRange=d;if(a)this.oldTransA=h;this.translationSlope=this.transA=h=this.len/(b+f||1);this.transB=this.horiz?this.left:this.bottom;this.minPixelPadding=h*e},setTickPositions:function(a){var b=this,c=b.chart,d=b.options,e=b.isLog,f=b.isDatetimeAxis,g=b.isXAxis,h=b.isLinked,i=b.options.tickPositioner,j=d.maxPadding,k=d.minPadding,m=d.tickInterval,l=d.minTickInterval,p=d.tickPixelInterval,r=b.categories;
h?(b.linkedParent=c[g?"xAxis":"yAxis"][d.linkedTo],c=b.linkedParent.getExtremes(),b.min=o(c.min,c.dataMin),b.max=o(c.max,c.dataMax),d.type!==b.linkedParent.options.type&&qa(11,1)):(b.min=o(b.userMin,d.min,b.dataMin),b.max=o(b.userMax,d.max,b.dataMax));if(e)!a&&F(b.min,o(b.dataMin,b.min))<=0&&qa(10,1),b.min=ia(na(b.min)),b.max=ia(na(b.max));if(b.range&&(b.userMin=b.min=q(b.min,b.max-b.range),b.userMax=b.max,a))b.range=null;b.beforePadding&&b.beforePadding();b.adjustForMinRange();if(!r&&!b.usePercentage&&
!h&&s(b.min)&&s(b.max)&&(c=b.max-b.min)){if(!s(d.min)&&!s(b.userMin)&&k&&(b.dataMin<0||!b.ignoreMinPadding))b.min-=c*k;if(!s(d.max)&&!s(b.userMax)&&j&&(b.dataMax>0||!b.ignoreMaxPadding))b.max+=c*j}b.tickInterval=b.min===b.max||b.min===void 0||b.max===void 0?1:h&&!m&&p===b.linkedParent.options.tickPixelInterval?b.linkedParent.tickInterval:o(m,r?1:(b.max-b.min)*p/(b.len||1));g&&!a&&n(b.series,function(a){a.processData(b.min!==b.oldMin||b.max!==b.oldMax)});b.setAxisTranslation(!0);b.beforeSetTickPositions&&
b.beforeSetTickPositions();if(b.postProcessTickInterval)b.tickInterval=b.postProcessTickInterval(b.tickInterval);if(!m&&b.tickInterval<l)b.tickInterval=l;if(!f&&!e&&(a=N.pow(10,T(N.log(b.tickInterval)/N.LN10)),!m))b.tickInterval=ib(b.tickInterval,null,a,d);b.minorTickInterval=d.minorTickInterval==="auto"&&b.tickInterval?b.tickInterval/5:d.minorTickInterval;b.tickPositions=i=d.tickPositions?[].concat(d.tickPositions):i&&i.apply(b,[b.min,b.max]);if(!i)i=f?(b.getNonLinearTimeTicks||Ab)(yb(b.tickInterval,
d.units),b.min,b.max,d.startOfWeek,b.ordinalPositions,b.closestPointRange,!0):e?b.getLogTickPositions(b.tickInterval,b.min,b.max):b.getLinearTickPositions(b.tickInterval,b.min,b.max),b.tickPositions=i;if(!h)e=i[0],f=i[i.length-1],h=b.minPointOffset||0,d.startOnTick?b.min=e:b.min-h>e&&i.shift(),d.endOnTick?b.max=f:b.max+h<f&&i.pop(),i.length===1&&(b.min-=0.001,b.max+=0.001)},setMaxTicks:function(){var a=this.chart,b=a.maxTicks||{},c=this.tickPositions,d=this._maxTicksKey=[this.xOrY,this.pos,this.len].join("-");
if(!this.isLinked&&!this.isDatetimeAxis&&c&&c.length>(b[d]||0)&&this.options.alignTicks!==!1)b[d]=c.length;a.maxTicks=b},adjustTickAmount:function(){var a=this._maxTicksKey,b=this.tickPositions,c=this.chart.maxTicks;if(c&&c[a]&&!this.isDatetimeAxis&&!this.categories&&!this.isLinked&&this.options.alignTicks!==!1){var d=this.tickAmount,e=b.length;this.tickAmount=a=c[a];if(e<a){for(;b.length<a;)b.push(ia(b[b.length-1]+this.tickInterval));this.transA*=(e-1)/(a-1);this.max=b[b.length-1]}if(s(d)&&a!==d)this.isDirty=
!0}},setScale:function(){var a=this.stacks,b,c,d,e;this.oldMin=this.min;this.oldMax=this.max;this.oldAxisLength=this.len;this.setAxisSize();e=this.len!==this.oldAxisLength;n(this.series,function(a){if(a.isDirtyData||a.isDirty||a.xAxis.isDirty)d=!0});if(e||d||this.isLinked||this.forceRedraw||this.userMin!==this.oldUserMin||this.userMax!==this.oldUserMax)if(this.forceRedraw=!1,this.getSeriesExtremes(),this.setTickPositions(),this.oldUserMin=this.userMin,this.oldUserMax=this.userMax,!this.isDirty)this.isDirty=
e||this.min!==this.oldMin||this.max!==this.oldMax;if(!this.isXAxis)for(b in a)for(c in a[b])a[b][c].cum=a[b][c].total;this.setMaxTicks()},setExtremes:function(a,b,c,d,e){var f=this,g=f.chart,c=o(c,!0),e=u(e,{min:a,max:b});G(f,"setExtremes",e,function(){f.userMin=a;f.userMax=b;f.isDirtyExtremes=!0;c&&g.redraw(d)})},zoom:function(a,b){a<=this.dataMin&&(a=w);b>=this.dataMax&&(b=w);this.displayBtn=a!==w||b!==w;this.setExtremes(a,b,!1,w,{trigger:"zoom"});return!0},setAxisSize:function(){var a=this.chart,
b=this.options,c=b.offsetLeft||0,d=b.offsetRight||0,e=this.horiz,f,g;this.left=g=o(b.left,a.plotLeft+c);this.top=f=o(b.top,a.plotTop);this.width=c=o(b.width,a.plotWidth-c+d);this.height=b=o(b.height,a.plotHeight);this.bottom=a.chartHeight-b-f;this.right=a.chartWidth-c-g;this.len=q(e?c:b,0);this.pos=e?g:f},getExtremes:function(){var a=this.isLog;return{min:a?ia(da(this.min)):this.min,max:a?ia(da(this.max)):this.max,dataMin:this.dataMin,dataMax:this.dataMax,userMin:this.userMin,userMax:this.userMax}},
getThreshold:function(a){var b=this.isLog,c=b?da(this.min):this.min,b=b?da(this.max):this.max;c>a||a===null?a=c:b<a&&(a=b);return this.translate(a,0,1,0,1)},addPlotBand:function(a){this.addPlotBandOrLine(a,"plotBands")},addPlotLine:function(a){this.addPlotBandOrLine(a,"plotLines")},addPlotBandOrLine:function(a,b){var c=(new ob(this,a)).render(),d=this.userOptions;b&&(d[b]=d[b]||[],d[b].push(a));this.plotLinesAndBands.push(c);return c},getOffset:function(){var a=this,b=a.chart,c=b.renderer,d=a.options,
e=a.tickPositions,f=a.ticks,g=a.horiz,h=a.side,i=b.inverted?[1,0,3,2][h]:h,j,k=0,m,l=0,p=d.title,r=d.labels,t=0,B=b.axisOffset,y=b.clipOffset,I=[-1,1,1,-1][h],u;a.hasData=b=a.hasVisibleSeries||s(a.min)&&s(a.max)&&!!e;a.showAxis=j=b||o(d.showEmpty,!0);if(!a.axisGroup)a.gridGroup=c.g("grid").attr({zIndex:d.gridZIndex||1}).add(),a.axisGroup=c.g("axis").attr({zIndex:d.zIndex||2}).add(),a.labelGroup=c.g("axis-labels").attr({zIndex:r.zIndex||7}).add();if(b||a.isLinked)n(e,function(b){f[b]?f[b].addLabel():
f[b]=new Ia(a,b)}),n(e,function(a){if(h===0||h===2||{1:"left",3:"right"}[h]===r.align)t=q(f[a].getLabelSize(),t)}),a.staggerLines&&(t+=(a.staggerLines-1)*16);else for(u in f)f[u].destroy(),delete f[u];if(p&&p.text&&p.enabled!==!1){if(!a.axisTitle)a.axisTitle=c.text(p.text,0,0,p.useHTML).attr({zIndex:7,rotation:p.rotation||0,align:p.textAlign||{low:"left",middle:"center",high:"right"}[p.align]}).css(p.style).add(a.axisGroup),a.axisTitle.isNew=!0;if(j)k=a.axisTitle.getBBox()[g?"height":"width"],l=o(p.margin,
g?5:10),m=p.offset;a.axisTitle[j?"show":"hide"]()}a.offset=I*o(d.offset,B[h]);a.axisTitleMargin=o(m,t+l+(h!==2&&t&&I*d.labels[g?"y":"x"]));B[h]=q(B[h],a.axisTitleMargin+k+I*a.offset);y[i]=q(y[i],d.lineWidth)},getLinePath:function(a){var b=this.chart,c=this.opposite,d=this.offset,e=this.horiz,f=this.left+(c?this.width:0)+d;this.lineTop=d=b.chartHeight-this.bottom-(c?this.height:0)+d;c||(a*=-1);return b.renderer.crispLine(["M",e?this.left:f,e?d:this.top,"L",e?b.chartWidth-this.right:f,e?d:b.chartHeight-
this.bottom],a)},getTitlePosition:function(){var a=this.horiz,b=this.left,c=this.top,d=this.len,e=this.options.title,f=a?b:c,g=this.opposite,h=this.offset,i=v(e.style.fontSize||12),d={low:f+(a?0:d),middle:f+d/2,high:f+(a?d:0)}[e.align],b=(a?c+this.height:b)+(a?1:-1)*(g?-1:1)*this.axisTitleMargin+(this.side===2?i:0);return{x:a?d:b+(g?this.width:0)+h+(e.x||0),y:a?b-(g?this.height:0)+h:d+(e.y||0)}},render:function(){var a=this,b=a.chart,c=b.renderer,d=a.options,e=a.isLog,f=a.isLinked,g=a.tickPositions,
h=a.axisTitle,i=a.stacks,j=a.ticks,k=a.minorTicks,m=a.alternateBands,l=d.stackLabels,p=d.alternateGridColor,r=a.tickmarkOffset,o=d.lineWidth,B,q=b.hasRendered&&s(a.oldMin)&&!isNaN(a.oldMin),t=a.showAxis,u,v;if(a.hasData||f)if(n([j,k,m],function(a){for(var b in a)a[b].isActive=!1}),a.minorTickInterval&&!a.categories&&n(a.getMinorTickPositions(),function(b){k[b]||(k[b]=new Ia(a,b,"minor"));q&&k[b].isNew&&k[b].render(null,!0);k[b].render(null,!1,1)}),g.length&&(n(g.slice(1).concat([g[0]]),function(b,
c){c=c===g.length-1?0:c+1;if(!f||b>=a.min&&b<=a.max)j[b]||(j[b]=new Ia(a,b)),q&&j[b].isNew&&j[b].render(c,!0),j[b].render(c,!1,1)}),r&&a.min===0&&(j[-1]||(j[-1]=new Ia(a,-1,null,!0)),j[-1].render(-1))),p&&n(g,function(b,c){if(c%2===0&&b<a.max)m[b]||(m[b]=new ob(a)),u=b+r,v=g[c+1]!==w?g[c+1]+r:a.max,m[b].options={from:e?da(u):u,to:e?da(v):v,color:p},m[b].render(),m[b].isActive=!0}),!a._addedPlotLB)n((d.plotLines||[]).concat(d.plotBands||[]),function(b){a.addPlotBandOrLine(b)}),a._addedPlotLB=!0;n([j,
k,m],function(a){var c,d,e=[],f=ya?ya.duration||500:0,g=function(){for(d=e.length;d--;)a[e[d]]&&!a[e[d]].isActive&&(a[e[d]].destroy(),delete a[e[d]])};for(c in a)if(!a[c].isActive)a[c].render(c,!1,0),a[c].isActive=!1,e.push(c);a===m||!b.hasRendered||!f?g():f&&setTimeout(g,f)});if(o)B=a.getLinePath(o),a.axisLine?a.axisLine.animate({d:B}):a.axisLine=c.path(B).attr({stroke:d.lineColor,"stroke-width":o,zIndex:7}).add(a.axisGroup),a.axisLine[t?"show":"hide"]();if(h&&t)h[h.isNew?"attr":"animate"](a.getTitlePosition()),
h.isNew=!1;if(l&&l.enabled){var x,C,d=a.stackTotalGroup;if(!d)a.stackTotalGroup=d=c.g("stack-labels").attr({visibility:"visible",zIndex:6}).add();d.translate(b.plotLeft,b.plotTop);for(x in i)for(C in c=i[x],c)c[C].render(d)}a.isDirty=!1},removePlotBandOrLine:function(a){for(var b=this.plotLinesAndBands,c=b.length;c--;)b[c].id===a&&b[c].destroy()},setTitle:function(a,b){this.update({title:a},b)},redraw:function(){var a=this.chart.pointer;a.reset&&a.reset(!0);this.render();n(this.plotLinesAndBands,
function(a){a.render()});n(this.series,function(a){a.isDirty=!0})},setCategories:function(a,b){this.update({categories:a},b)},destroy:function(){var a=this,b=a.stacks,c;ba(a);for(c in b)Ga(b[c]),b[c]=null;n([a.ticks,a.minorTicks,a.alternateBands,a.plotLinesAndBands],function(a){Ga(a)});n("stackTotalGroup,axisLine,axisGroup,gridGroup,labelGroup,axisTitle".split(","),function(b){a[b]&&(a[b]=a[b].destroy())})}};pb.prototype={init:function(a,b){var c=b.borderWidth,d=b.style,e=v(d.padding);this.chart=
a;this.options=b;this.crosshairs=[];this.now={x:0,y:0};this.isHidden=!0;this.label=a.renderer.label("",0,0,b.shape,null,null,b.useHTML,null,"tooltip").attr({padding:e,fill:b.backgroundColor,"stroke-width":c,r:b.borderRadius,zIndex:8}).css(d).css({padding:0}).hide().add();$||this.label.shadow(b.shadow);this.shared=b.shared},destroy:function(){n(this.crosshairs,function(a){a&&a.destroy()});if(this.label)this.label=this.label.destroy()},move:function(a,b,c,d){var e=this,f=e.now,g=e.options.animation!==
!1&&!e.isHidden;u(f,{x:g?(2*f.x+a)/3:a,y:g?(f.y+b)/2:b,anchorX:g?(2*f.anchorX+c)/3:c,anchorY:g?(f.anchorY+d)/2:d});e.label.attr(f);if(g&&(R(a-f.x)>1||R(b-f.y)>1))clearTimeout(this.tooltipTimeout),this.tooltipTimeout=setTimeout(function(){e&&e.move(a,b,c,d)},32)},hide:function(){var a=this,b;if(!this.isHidden)b=this.chart.hoverPoints,this.hideTimer=setTimeout(function(){a.label.fadeOut();a.isHidden=!0},o(this.options.hideDelay,500)),b&&n(b,function(a){a.setState()}),this.chart.hoverPoints=null},hideCrosshairs:function(){n(this.crosshairs,
function(a){a&&a.hide()})},getAnchor:function(a,b){var c,d=this.chart,e=d.inverted,f=d.plotTop,g=0,h=0,i,a=ha(a);c=a[0].tooltipPos;this.followPointer&&b&&(b.chartX===w&&(b=d.pointer.normalize(b)),c=[b.chartX-d.plotLeft,b.chartY-f]);c||(n(a,function(a){i=a.series.yAxis;g+=a.plotX;h+=(a.plotLow?(a.plotLow+a.plotHigh)/2:a.plotY)+(!e&&i?i.top-f:0)}),g/=a.length,h/=a.length,c=[e?d.plotWidth-h:g,this.shared&&!e&&a.length>1&&b?b.chartY-f:e?d.plotHeight-g:h]);return Ka(c,t)},getPosition:function(a,b,c){var d=
this.chart,e=d.plotLeft,f=d.plotTop,g=d.plotWidth,h=d.plotHeight,i=o(this.options.distance,12),j=c.plotX,c=c.plotY,d=j+e+(d.inverted?i:-a-i),k=c-b+f+15,m;d<7&&(d=e+q(j,0)+i);d+a>e+g&&(d-=d+a-(e+g),k=c-b+f-i,m=!0);k<f+5&&(k=f+5,m&&c>=k&&c<=k+b&&(k=c+f+i));k+b>f+h&&(k=q(f,f+h-b-i));return{x:d,y:k}},defaultFormatter:function(a){var b=this.points||ha(this),c=b[0].series,d;d=[c.tooltipHeaderFormatter(b[0])];n(b,function(a){c=a.series;d.push(c.tooltipFormatter&&c.tooltipFormatter(a)||a.point.tooltipFormatter(c.tooltipOptions.pointFormat))});
d.push(a.options.footerFormat||"");return d.join("")},refresh:function(a,b){var c=this.chart,d=this.label,e=this.options,f,g,h,i={},j,k=[];j=e.formatter||this.defaultFormatter;var i=c.hoverPoints,m,l=e.crosshairs;h=this.shared;clearTimeout(this.hideTimer);this.followPointer=ha(a)[0].series.tooltipOptions.followPointer;g=this.getAnchor(a,b);f=g[0];g=g[1];h&&(!a.series||!a.series.noSharedTooltip)?(c.hoverPoints=a,i&&n(i,function(a){a.setState()}),n(a,function(a){a.setState("hover");k.push(a.getLabelConfig())}),
i={x:a[0].category,y:a[0].y},i.points=k,a=a[0]):i=a.getLabelConfig();j=j.call(i,this);i=a.series;h=h||!i.isCartesian||i.tooltipOutsidePlot||c.isInsidePlot(f,g);j===!1||!h?this.hide():(this.isHidden&&(Ta(d),d.attr("opacity",1).show()),d.attr({text:j}),m=e.borderColor||a.color||i.color||"#606060",d.attr({stroke:m}),this.updatePosition({plotX:f,plotY:g}),this.isHidden=!1);if(l){l=ha(l);for(d=l.length;d--;)if(e=a.series[d?"yAxis":"xAxis"],l[d]&&e)if(e=e.getPlotLinePath(d?o(a.stackY,a.y):a.x,1),this.crosshairs[d])this.crosshairs[d].attr({d:e,
visibility:"visible"});else{h={"stroke-width":l[d].width||1,stroke:l[d].color||"#C0C0C0",zIndex:l[d].zIndex||2};if(l[d].dashStyle)h.dashstyle=l[d].dashStyle;this.crosshairs[d]=c.renderer.path(e).attr(h).add()}}G(c,"tooltipRefresh",{text:j,x:f+c.plotLeft,y:g+c.plotTop,borderColor:m})},updatePosition:function(a){var b=this.chart,c=this.label,c=(this.options.positioner||this.getPosition).call(this,c.width,c.height,a);this.move(t(c.x),t(c.y),a.plotX+b.plotLeft,a.plotY+b.plotTop)}};qb.prototype={init:function(a,
b){var c=$?"":b.chart.zoomType,d=a.inverted,e;this.options=b;this.chart=a;this.zoomX=e=/x/.test(c);this.zoomY=c=/y/.test(c);this.zoomHor=e&&!d||c&&d;this.zoomVert=c&&!d||e&&d;this.pinchDown=[];this.lastValidTouch={};if(b.tooltip.enabled)a.tooltip=new pb(a,b.tooltip);this.setDOMEvents()},normalize:function(a){var b,c,d,a=a||E.event;if(!a.target)a.target=a.srcElement;a=Pb(a);d=a.touches?a.touches.item(0):a;this.chartPosition=b=Tb(this.chart.container);d.pageX===w?(c=a.x,b=a.y):(c=d.pageX-b.left,b=d.pageY-
b.top);return u(a,{chartX:t(c),chartY:t(b)})},getCoordinates:function(a){var b={xAxis:[],yAxis:[]};n(this.chart.axes,function(c){b[c.isXAxis?"xAxis":"yAxis"].push({axis:c,value:c.toValue(a[c.horiz?"chartX":"chartY"])})});return b},getIndex:function(a){var b=this.chart;return b.inverted?b.plotHeight+b.plotTop-a.chartY:a.chartX-b.plotLeft},runPointActions:function(a){var b=this.chart,c=b.series,d=b.tooltip,e,f=b.hoverPoint,g=b.hoverSeries,h,i,j=b.chartWidth,k=this.getIndex(a);if(d&&this.options.tooltip.shared&&
(!g||!g.noSharedTooltip)){e=[];h=c.length;for(i=0;i<h;i++)if(c[i].visible&&c[i].options.enableMouseTracking!==!1&&!c[i].noSharedTooltip&&c[i].tooltipPoints.length&&(b=c[i].tooltipPoints[k],b.series))b._dist=R(k-b.clientX),j=F(j,b._dist),e.push(b);for(h=e.length;h--;)e[h]._dist>j&&e.splice(h,1);if(e.length&&e[0].clientX!==this.hoverX)d.refresh(e,a),this.hoverX=e[0].clientX}if(g&&g.tracker){if((b=g.tooltipPoints[k])&&b!==f)b.onMouseOver(a)}else d&&d.followPointer&&!d.isHidden&&(a=d.getAnchor([{}],a),
d.updatePosition({plotX:a[0],plotY:a[1]}))},reset:function(a){var b=this.chart,c=b.hoverSeries,d=b.hoverPoint,e=b.tooltip,b=e&&e.shared?b.hoverPoints:d;(a=a&&e&&b)&&ha(b)[0].plotX===w&&(a=!1);if(a)e.refresh(b);else{if(d)d.onMouseOut();if(c)c.onMouseOut();e&&(e.hide(),e.hideCrosshairs());this.hoverX=null}},scaleGroups:function(a,b){var c=this.chart;n(c.series,function(d){d.xAxis.zoomEnabled&&(d.group.attr(a),d.markerGroup&&(d.markerGroup.attr(a),d.markerGroup.clip(b?c.clipRect:null)),d.dataLabelsGroup&&
d.dataLabelsGroup.attr(a))});c.clipRect.attr(b||c.clipBox)},pinchTranslateDirection:function(a,b,c,d,e,f,g){var h=this.chart,i=a?"x":"y",j=a?"X":"Y",k="chart"+j,m=a?"width":"height",l=h["plot"+(a?"Left":"Top")],p,r,o=1,n=h.inverted,q=h.bounds[a?"h":"v"],t=b.length===1,s=b[0][k],u=c[0][k],v=!t&&b[1][k],w=!t&&c[1][k],x,c=function(){!t&&R(s-v)>20&&(o=R(u-w)/R(s-v));r=(l-u)/o+s;p=h["plot"+(a?"Width":"Height")]/o};c();b=r;b<q.min?(b=q.min,x=!0):b+p>q.max&&(b=q.max-p,x=!0);x?(u-=0.8*(u-g[i][0]),t||(w-=
0.8*(w-g[i][1])),c()):g[i]=[u,w];n||(f[i]=r-l,f[m]=p);f=n?1/o:o;e[m]=p;e[i]=b;d[n?a?"scaleY":"scaleX":"scale"+j]=o;d["translate"+j]=f*l+(u-f*s)},pinch:function(a){var b=this,c=b.chart,d=b.pinchDown,e=a.touches,f=b.lastValidTouch,g=b.zoomHor||b.pinchHor,h=b.zoomVert||b.pinchVert,i=b.selectionMarker,j={},k={};a.type==="touchstart"&&(b.inClass(a.target,"highcharts-tracker")?c.runTrackerClick||a.preventDefault():c.runChartClick||a.preventDefault());Ka(e,function(a){return b.normalize(a)});if(a.type===
"touchstart")n(e,function(a,b){d[b]={chartX:a.chartX,chartY:a.chartY}}),f.x=[d[0].chartX,d[1]&&d[1].chartX],f.y=[d[0].chartY,d[1]&&d[1].chartY],n(c.axes,function(a){if(a.zoomEnabled){var b=c.bounds[a.horiz?"h":"v"],d=a.minPixelPadding,e=a.toPixels(a.dataMin),f=a.toPixels(a.dataMax),g=F(e,f),e=q(e,f);b.min=F(a.pos,g-d);b.max=q(a.pos+a.len,e+d)}});else if(d.length){if(!i)b.selectionMarker=i=u({destroy:ta},c.plotBox);g&&b.pinchTranslateDirection(!0,d,e,j,i,k,f);h&&b.pinchTranslateDirection(!1,d,e,j,
i,k,f);b.hasPinched=g||h;b.scaleGroups(j,k)}},dragStart:function(a){var b=this.chart;b.mouseIsDown=a.type;b.cancelClick=!1;b.mouseDownX=this.mouseDownX=a.chartX;this.mouseDownY=a.chartY},drag:function(a){var b=this.chart,c=b.options.chart,d=a.chartX,a=a.chartY,e=this.zoomHor,f=this.zoomVert,g=b.plotLeft,h=b.plotTop,i=b.plotWidth,j=b.plotHeight,k,m=this.mouseDownX,l=this.mouseDownY;d<g?d=g:d>g+i&&(d=g+i);a<h?a=h:a>h+j&&(a=h+j);this.hasDragged=Math.sqrt(Math.pow(m-d,2)+Math.pow(l-a,2));if(this.hasDragged>
10){k=b.isInsidePlot(m-g,l-h);if(b.hasCartesianSeries&&(this.zoomX||this.zoomY)&&k&&!this.selectionMarker)this.selectionMarker=b.renderer.rect(g,h,e?1:i,f?1:j,0).attr({fill:c.selectionMarkerFill||"rgba(69,114,167,0.25)",zIndex:7}).add();this.selectionMarker&&e&&(e=d-m,this.selectionMarker.attr({width:R(e),x:(e>0?0:e)+m}));this.selectionMarker&&f&&(e=a-l,this.selectionMarker.attr({height:R(e),y:(e>0?0:e)+l}));k&&!this.selectionMarker&&c.panning&&b.pan(d)}},drop:function(a){var b=this.chart,c=this.hasPinched;
if(this.selectionMarker){var d={xAxis:[],yAxis:[],originalEvent:a.originalEvent||a},e=this.selectionMarker,f=e.x,g=e.y,h;if(this.hasDragged||c)n(b.axes,function(a){if(a.zoomEnabled){var b=a.horiz,c=a.minPixelPadding,m=a.toValue((b?f:g)+c),b=a.toValue((b?f+e.width:g+e.height)-c);!isNaN(m)&&!isNaN(b)&&(d[a.xOrY+"Axis"].push({axis:a,min:F(m,b),max:q(m,b)}),h=!0)}}),h&&G(b,"selection",d,function(a){b.zoom(u(a,c?{animation:!1}:null))});this.selectionMarker=this.selectionMarker.destroy();c&&this.scaleGroups({translateX:b.plotLeft,
translateY:b.plotTop,scaleX:1,scaleY:1})}if(b)M(b.container,{cursor:"auto"}),b.cancelClick=this.hasDragged,b.mouseIsDown=this.hasDragged=this.hasPinched=!1,this.pinchDown=[]},onContainerMouseDown:function(a){a=this.normalize(a);a.preventDefault&&a.preventDefault();this.dragStart(a)},onDocumentMouseUp:function(a){this.drop(a)},onDocumentMouseMove:function(a){var b=this.chart,c=this.chartPosition,d=b.hoverSeries,a=Pb(a);c&&d&&d.isCartesian&&!b.isInsidePlot(a.pageX-c.left-b.plotLeft,a.pageY-c.top-b.plotTop)&&
this.reset()},onContainerMouseLeave:function(){this.reset();this.chartPosition=null},onContainerMouseMove:function(a){var b=this.chart,a=this.normalize(a);a.returnValue=!1;b.mouseIsDown==="mousedown"&&this.drag(a);b.isInsidePlot(a.chartX-b.plotLeft,a.chartY-b.plotTop)&&this.runPointActions(a)},inClass:function(a,b){for(var c;a;){if(c=C(a,"class"))if(c.indexOf(b)!==-1)return!0;else if(c.indexOf("highcharts-container")!==-1)return!1;a=a.parentNode}},onTrackerMouseOut:function(a){var b=this.chart.hoverSeries;
if(b&&!b.options.stickyTracking&&!this.inClass(a.toElement||a.relatedTarget,"highcharts-tooltip"))b.onMouseOut()},onContainerClick:function(a){var b=this.chart,c=b.hoverPoint,d=b.plotLeft,e=b.plotTop,f=b.inverted,g,h,i,a=this.normalize(a);a.cancelBubble=!0;if(!b.cancelClick)c&&this.inClass(a.target,"highcharts-tracker")?(g=this.chartPosition,h=c.plotX,i=c.plotY,u(c,{pageX:g.left+d+(f?b.plotWidth-i:h),pageY:g.top+e+(f?b.plotHeight-h:i)}),G(c.series,"click",u(a,{point:c})),c.firePointEvent("click",
a)):(u(a,this.getCoordinates(a)),b.isInsidePlot(a.chartX-d,a.chartY-e)&&G(b,"click",a))},onContainerTouchStart:function(a){var b=this.chart;a.touches.length===1?(a=this.normalize(a),b.isInsidePlot(a.chartX-b.plotLeft,a.chartY-b.plotTop)&&(this.runPointActions(a),this.pinch(a))):a.touches.length===2&&this.pinch(a)},onContainerTouchMove:function(a){(a.touches.length===1||a.touches.length===2)&&this.pinch(a)},onDocumentTouchEnd:function(a){this.drop(a)},setDOMEvents:function(){var a=this,b=a.chart.container,
c;this._events=c=[[b,"onmousedown","onContainerMouseDown"],[b,"onmousemove","onContainerMouseMove"],[b,"onclick","onContainerClick"],[b,"mouseleave","onContainerMouseLeave"],[z,"mousemove","onDocumentMouseMove"],[z,"mouseup","onDocumentMouseUp"]];fb&&c.push([b,"ontouchstart","onContainerTouchStart"],[b,"ontouchmove","onContainerTouchMove"],[z,"touchend","onDocumentTouchEnd"]);n(c,function(b){a["_"+b[2]]=function(c){a[b[2]](c)};b[1].indexOf("on")===0?b[0][b[1]]=a["_"+b[2]]:J(b[0],b[1],a["_"+b[2]])})},
destroy:function(){var a=this;n(a._events,function(b){b[1].indexOf("on")===0?b[0][b[1]]=null:ba(b[0],b[1],a["_"+b[2]])});delete a._events;clearInterval(a.tooltipTimeout)}};rb.prototype={init:function(a,b){var c=this,d=b.itemStyle,e=o(b.padding,8),f=b.itemMarginTop||0;this.options=b;if(b.enabled)c.baseline=v(d.fontSize)+3+f,c.itemStyle=d,c.itemHiddenStyle=x(d,b.itemHiddenStyle),c.itemMarginTop=f,c.padding=e,c.initialItemX=e,c.initialItemY=e-5,c.maxItemWidth=0,c.chart=a,c.itemHeight=0,c.lastLineHeight=
0,c.render(),J(c.chart,"endResize",function(){c.positionCheckboxes()})},colorizeItem:function(a,b){var c=this.options,d=a.legendItem,e=a.legendLine,f=a.legendSymbol,g=this.itemHiddenStyle.color,c=b?c.itemStyle.color:g,h=b?a.color:g,g=a.options&&a.options.marker,i={stroke:h,fill:h},j;d&&d.css({fill:c,color:c});e&&e.attr({stroke:h});if(f){if(g)for(j in g=a.convertAttribs(g),g)d=g[j],d!==w&&(i[j]=d);f.attr(i)}},positionItem:function(a){var b=this.options,c=b.symbolPadding,b=!b.rtl,d=a._legendItemPos,
e=d[0],d=d[1],f=a.checkbox;a.legendGroup&&a.legendGroup.translate(b?e:this.legendWidth-e-2*c-4,d);if(f)f.x=e,f.y=d},destroyItem:function(a){var b=a.checkbox;n(["legendItem","legendLine","legendSymbol","legendGroup"],function(b){a[b]&&a[b].destroy()});b&&Ra(a.checkbox)},destroy:function(){var a=this.group,b=this.box;if(b)this.box=b.destroy();if(a)this.group=a.destroy()},positionCheckboxes:function(a){var b=this.group.alignAttr,c,d=this.clipHeight||this.legendHeight;if(b)c=b.translateY,n(this.allItems,
function(e){var f=e.checkbox,g;f&&(g=c+f.y+(a||0)+3,M(f,{left:b.translateX+e.legendItemWidth+f.x-20+"px",top:g+"px",display:g>c-6&&g<c+d-6?"":O}))})},renderTitle:function(){var a=this.padding,b=this.options.title,c=0;if(b.text){if(!this.title)this.title=this.chart.renderer.label(b.text,a-3,a-4,null,null,null,null,null,"legend-title").attr({zIndex:1}).css(b.style).add(this.group);c=this.title.getBBox().height;this.contentGroup.attr({translateY:c})}this.titleHeight=c},renderItem:function(a){var y;var b=
this,c=b.chart,d=c.renderer,e=b.options,f=e.layout==="horizontal",g=e.symbolWidth,h=e.symbolPadding,i=b.itemStyle,j=b.itemHiddenStyle,k=b.padding,m=!e.rtl,l=e.width,p=e.itemMarginBottom||0,r=b.itemMarginTop,o=b.initialItemX,n=a.legendItem,t=a.series||a,s=t.options,u=s.showCheckbox,v=e.useHTML;if(!n&&(a.legendGroup=d.g("legend-item").attr({zIndex:1}).add(b.scrollGroup),t.drawLegendSymbol(b,a),a.legendItem=n=d.text(e.labelFormat?Ea(e.labelFormat,a):e.labelFormatter.call(a),m?g+h:-h,b.baseline,v).css(x(a.visible?
i:j)).attr({align:m?"left":"right",zIndex:2}).add(a.legendGroup),(v?n:a.legendGroup).on("mouseover",function(){a.setState("hover");n.css(b.options.itemHoverStyle)}).on("mouseout",function(){n.css(a.visible?i:j);a.setState()}).on("click",function(b){var c=function(){a.setVisible()},b={browserEvent:b};a.firePointEvent?a.firePointEvent("legendItemClick",b,c):G(a,"legendItemClick",b,c)}),b.colorizeItem(a,a.visible),s&&u))a.checkbox=U("input",{type:"checkbox",checked:a.selected,defaultChecked:a.selected},
e.itemCheckboxStyle,c.container),J(a.checkbox,"click",function(b){G(a,"checkboxClick",{checked:b.target.checked},function(){a.select()})});d=n.getBBox();y=a.legendItemWidth=e.itemWidth||g+h+d.width+k+(u?20:0),e=y;b.itemHeight=g=d.height;if(f&&b.itemX-o+e>(l||c.chartWidth-2*k-o))b.itemX=o,b.itemY+=r+b.lastLineHeight+p,b.lastLineHeight=0;b.maxItemWidth=q(b.maxItemWidth,e);b.lastItemY=r+b.itemY+p;b.lastLineHeight=q(g,b.lastLineHeight);a._legendItemPos=[b.itemX,b.itemY];f?b.itemX+=e:(b.itemY+=r+g+p,b.lastLineHeight=
g);b.offsetWidth=l||q(f?b.itemX-o:e,b.offsetWidth)},render:function(){var a=this,b=a.chart,c=b.renderer,d=a.group,e,f,g,h,i=a.box,j=a.options,k=a.padding,m=j.borderWidth,l=j.backgroundColor;a.itemX=a.initialItemX;a.itemY=a.initialItemY;a.offsetWidth=0;a.lastItemY=0;if(!d)a.group=d=c.g("legend").attr({zIndex:7}).add(),a.contentGroup=c.g().attr({zIndex:1}).add(d),a.scrollGroup=c.g().add(a.contentGroup),a.clipRect=c.clipRect(0,0,9999,b.chartHeight),a.contentGroup.clip(a.clipRect);a.renderTitle();e=[];
n(b.series,function(a){var b=a.options;b.showInLegend&&!s(b.linkedTo)&&(e=e.concat(a.legendItems||(b.legendType==="point"?a.data:a)))});Gb(e,function(a,b){return(a.options&&a.options.legendIndex||0)-(b.options&&b.options.legendIndex||0)});j.reversed&&e.reverse();a.allItems=e;a.display=f=!!e.length;n(e,function(b){a.renderItem(b)});g=j.width||a.offsetWidth;h=a.lastItemY+a.lastLineHeight+a.titleHeight;h=a.handleOverflow(h);if(m||l){g+=k;h+=k;if(i){if(g>0&&h>0)i[i.isNew?"attr":"animate"](i.crisp(null,
null,null,g,h)),i.isNew=!1}else a.box=i=c.rect(0,0,g,h,j.borderRadius,m||0).attr({stroke:j.borderColor,"stroke-width":m||0,fill:l||O}).add(d).shadow(j.shadow),i.isNew=!0;i[f?"show":"hide"]()}a.legendWidth=g;a.legendHeight=h;n(e,function(b){a.positionItem(b)});f&&d.align(u({width:g,height:h},j),!0,"spacingBox");b.isResizing||this.positionCheckboxes()},handleOverflow:function(a){var b=this,c=this.chart,d=c.renderer,e=this.options,f=e.y,f=c.spacingBox.height+(e.verticalAlign==="top"?-f:f)-this.padding,
g=e.maxHeight,h=this.clipRect,i=e.navigation,j=o(i.animation,!0),k=i.arrowSize||12,m=this.nav;e.layout==="horizontal"&&(f/=2);g&&(f=F(f,g));if(a>f&&!e.useHTML){this.clipHeight=c=f-20-this.titleHeight;this.pageCount=ja(a/c);this.currentPage=o(this.currentPage,1);this.fullHeight=a;h.attr({height:c});if(!m)this.nav=m=d.g().attr({zIndex:1}).add(this.group),this.up=d.symbol("triangle",0,0,k,k).on("click",function(){b.scroll(-1,j)}).add(m),this.pager=d.text("",15,10).css(i.style).add(m),this.down=d.symbol("triangle-down",
0,0,k,k).on("click",function(){b.scroll(1,j)}).add(m);b.scroll(0);a=f}else if(m)h.attr({height:c.chartHeight}),m.hide(),this.scrollGroup.attr({translateY:1}),this.clipHeight=0;return a},scroll:function(a,b){var c=this.pageCount,d=this.currentPage+a,e=this.clipHeight,f=this.options.navigation,g=f.activeColor,h=f.inactiveColor,f=this.pager,i=this.padding;d>c&&(d=c);if(d>0)b!==w&&Ha(b,this.chart),this.nav.attr({translateX:i,translateY:e+7+this.titleHeight,visibility:"visible"}),this.up.attr({fill:d===
1?h:g}).css({cursor:d===1?"default":"pointer"}),f.attr({text:d+"/"+this.pageCount}),this.down.attr({x:18+this.pager.getBBox().width,fill:d===c?h:g}).css({cursor:d===c?"default":"pointer"}),e=-F(e*(d-1),this.fullHeight-e+i)+1,this.scrollGroup.animate({translateY:e}),f.attr({text:d+"/"+c}),this.currentPage=d,this.positionCheckboxes(e)}};sb.prototype={init:function(a,b){var c,d=a.series;a.series=null;c=x(P,a);c.series=a.series=d;var d=c.chart,e=d.margin,e=V(e)?e:[e,e,e,e];this.optionsMarginTop=o(d.marginTop,
e[0]);this.optionsMarginRight=o(d.marginRight,e[1]);this.optionsMarginBottom=o(d.marginBottom,e[2]);this.optionsMarginLeft=o(d.marginLeft,e[3]);this.runChartClick=(e=d.events)&&!!e.click;this.bounds={h:{},v:{}};this.callback=b;this.isResizing=0;this.options=c;this.axes=[];this.series=[];this.hasCartesianSeries=d.showAxes;var f=this,g;f.index=Aa.length;Aa.push(f);d.reflow!==!1&&J(f,"load",function(){f.initReflow()});if(e)for(g in e)J(f,g,e[g]);f.xAxis=[];f.yAxis=[];f.animation=$?!1:o(d.animation,!0);
f.pointCount=0;f.counters=new Fb;f.firstRender()},initSeries:function(a){var b=this.options.chart;(b=aa[a.type||b.type||b.defaultSeriesType])||qa(17,!0);b=new b;b.init(this,a);return b},addSeries:function(a,b,c){var d,e=this;a&&(b=o(b,!0),G(e,"addSeries",{options:a},function(){d=e.initSeries(a);e.isDirtyLegend=!0;b&&e.redraw(c)}));return d},addAxis:function(a,b,c,d){var b=b?"xAxis":"yAxis",e=this.options;new ab(this,x(a,{index:this[b].length}));e[b]=ha(e[b]||{});e[b].push(a);o(c,!0)&&this.redraw(d)},
isInsidePlot:function(a,b,c){var d=c?b:a,a=c?a:b;return d>=0&&d<=this.plotWidth&&a>=0&&a<=this.plotHeight},adjustTickAmounts:function(){this.options.chart.alignTicks!==!1&&n(this.axes,function(a){a.adjustTickAmount()});this.maxTicks=null},redraw:function(a){var b=this.axes,c=this.series,d=this.pointer,e=this.legend,f=this.isDirtyLegend,g,h=this.isDirtyBox,i=c.length,j=i,k=this.renderer,m=k.isHidden(),l=[];Ha(a,this);for(m&&this.cloneRenderTo();j--;)if(a=c[j],a.isDirty&&a.options.stacking){g=!0;break}if(g)for(j=
i;j--;)if(a=c[j],a.options.stacking)a.isDirty=!0;n(c,function(a){a.isDirty&&a.options.legendType==="point"&&(f=!0)});if(f&&e.options.enabled)e.render(),this.isDirtyLegend=!1;if(this.hasCartesianSeries){if(!this.isResizing)this.maxTicks=null,n(b,function(a){a.setScale()});this.adjustTickAmounts();this.getMargins();n(b,function(a){if(a.isDirtyExtremes)a.isDirtyExtremes=!1,l.push(function(){G(a,"afterSetExtremes",a.getExtremes())});if(a.isDirty||h||g)a.redraw(),h=!0})}h&&this.drawChartBox();n(c,function(a){a.isDirty&&
a.visible&&(!a.isCartesian||a.xAxis)&&a.redraw()});d&&d.reset&&d.reset(!0);k.draw();G(this,"redraw");m&&this.cloneRenderTo(!0);n(l,function(a){a.call()})},showLoading:function(a){var b=this.options,c=this.loadingDiv,d=b.loading;if(!c)this.loadingDiv=c=U(xa,{className:"highcharts-loading"},u(d.style,{left:this.plotLeft+"px",top:this.plotTop+"px",width:this.plotWidth+"px",height:this.plotHeight+"px",zIndex:10,display:O}),this.container),this.loadingSpan=U("span",null,d.labelStyle,c);this.loadingSpan.innerHTML=
a||b.lang.loading;if(!this.loadingShown)M(c,{opacity:0,display:""}),vb(c,{opacity:d.style.opacity},{duration:d.showDuration||0}),this.loadingShown=!0},hideLoading:function(){var a=this.options,b=this.loadingDiv;b&&vb(b,{opacity:0},{duration:a.loading.hideDuration||100,complete:function(){M(b,{display:O})}});this.loadingShown=!1},get:function(a){var b=this.axes,c=this.series,d,e;for(d=0;d<b.length;d++)if(b[d].options.id===a)return b[d];for(d=0;d<c.length;d++)if(c[d].options.id===a)return c[d];for(d=
0;d<c.length;d++){e=c[d].points||[];for(b=0;b<e.length;b++)if(e[b].id===a)return e[b]}return null},getAxes:function(){var a=this,b=this.options,c=b.xAxis=ha(b.xAxis||{}),b=b.yAxis=ha(b.yAxis||{});n(c,function(a,b){a.index=b;a.isX=!0});n(b,function(a,b){a.index=b});c=c.concat(b);n(c,function(b){new ab(a,b)});a.adjustTickAmounts()},getSelectedPoints:function(){var a=[];n(this.series,function(b){a=a.concat(Ob(b.points,function(a){return a.selected}))});return a},getSelectedSeries:function(){return Ob(this.series,
function(a){return a.selected})},showResetZoom:function(){var a=this,b=P.lang,c=a.options.chart.resetZoomButton,d=c.theme,e=d.states,f=c.relativeTo==="chart"?null:"plotBox";this.resetZoomButton=a.renderer.button(b.resetZoom,null,null,function(){a.zoomOut()},d,e&&e.hover).attr({align:c.position.align,title:b.resetZoomTitle}).add().align(c.position,!1,f)},zoomOut:function(){var a=this;G(a,"selection",{resetSelection:!0},function(){a.zoom()})},zoom:function(a){var b,c=this.pointer,d=!1,e;!a||a.resetSelection?
n(this.axes,function(a){b=a.zoom()}):n(a.xAxis.concat(a.yAxis),function(a){var e=a.axis,h=e.isXAxis;if(c[h?"zoomX":"zoomY"]||c[h?"pinchX":"pinchY"])b=e.zoom(a.min,a.max),e.displayBtn&&(d=!0)});e=this.resetZoomButton;if(d&&!e)this.showResetZoom();else if(!d&&V(e))this.resetZoomButton=e.destroy();b&&this.redraw(o(this.options.chart.animation,a&&a.animation,this.pointCount<100))},pan:function(a){var b=this.xAxis[0],c=this.mouseDownX,d=b.pointRange/2,e=b.getExtremes(),f=b.translate(c-a,!0)+d,c=b.translate(c+
this.plotWidth-a,!0)-d;(d=this.hoverPoints)&&n(d,function(a){a.setState()});b.series.length&&f>F(e.dataMin,e.min)&&c<q(e.dataMax,e.max)&&b.setExtremes(f,c,!0,!1,{trigger:"pan"});this.mouseDownX=a;M(this.container,{cursor:"move"})},setTitle:function(a,b){var f;var c=this,d=c.options,e;e=d.title=x(d.title,a);f=d.subtitle=x(d.subtitle,b),d=f;n([["title",a,e],["subtitle",b,d]],function(a){var b=a[0],d=c[b],e=a[1],a=a[2];d&&e&&(c[b]=d=d.destroy());a&&a.text&&!d&&(c[b]=c.renderer.text(a.text,0,0,a.useHTML).attr({align:a.align,
"class":"highcharts-"+b,zIndex:a.zIndex||4}).css(a.style).add().align(a,!1,"spacingBox"))})},getChartSize:function(){var a=this.options.chart,b=this.renderToClone||this.renderTo;this.containerWidth=gb(b,"width");this.containerHeight=gb(b,"height");this.chartWidth=q(0,a.width||this.containerWidth||600);this.chartHeight=q(0,o(a.height,this.containerHeight>19?this.containerHeight:400))},cloneRenderTo:function(a){var b=this.renderToClone,c=this.container;a?b&&(this.renderTo.appendChild(c),Ra(b),delete this.renderToClone):
(c&&this.renderTo.removeChild(c),this.renderToClone=b=this.renderTo.cloneNode(0),M(b,{position:"absolute",top:"-9999px",display:"block"}),z.body.appendChild(b),c&&b.appendChild(c))},getContainer:function(){var a,b=this.options.chart,c,d,e;this.renderTo=a=b.renderTo;e="highcharts-"+tb++;if(fa(a))this.renderTo=a=z.getElementById(a);a||qa(13,!0);c=v(C(a,"data-highcharts-chart"));!isNaN(c)&&Aa[c]&&Aa[c].destroy();C(a,"data-highcharts-chart",this.index);a.innerHTML="";a.offsetWidth||this.cloneRenderTo();
this.getChartSize();c=this.chartWidth;d=this.chartHeight;this.container=a=U(xa,{className:"highcharts-container"+(b.className?" "+b.className:""),id:e},u({position:"relative",overflow:"hidden",width:c+"px",height:d+"px",textAlign:"left",lineHeight:"normal",zIndex:0},b.style),this.renderToClone||a);this.renderer=b.forExport?new Ba(a,c,d,!0):new Sa(a,c,d);$&&this.renderer.create(this,a,c,d)},getMargins:function(){var a=this.options.chart,b=a.spacingTop,c=a.spacingRight,d=a.spacingBottom,a=a.spacingLeft,
e,f=this.legend,g=this.optionsMarginTop,h=this.optionsMarginLeft,i=this.optionsMarginRight,j=this.optionsMarginBottom,k=this.options.title,m=this.options.subtitle,l=this.options.legend,p=o(l.margin,10),r=l.x,t=l.y,B=l.align,y=l.verticalAlign;this.resetMargins();e=this.axisOffset;if((this.title||this.subtitle)&&!s(this.optionsMarginTop))if(m=q(this.title&&!k.floating&&!k.verticalAlign&&k.y||0,this.subtitle&&!m.floating&&!m.verticalAlign&&m.y||0))this.plotTop=q(this.plotTop,m+o(k.margin,15)+b);if(f.display&&
!l.floating)if(B==="right"){if(!s(i))this.marginRight=q(this.marginRight,f.legendWidth-r+p+c)}else if(B==="left"){if(!s(h))this.plotLeft=q(this.plotLeft,f.legendWidth+r+p+a)}else if(y==="top"){if(!s(g))this.plotTop=q(this.plotTop,f.legendHeight+t+p+b)}else if(y==="bottom"&&!s(j))this.marginBottom=q(this.marginBottom,f.legendHeight-t+p+d);this.extraBottomMargin&&(this.marginBottom+=this.extraBottomMargin);this.extraTopMargin&&(this.plotTop+=this.extraTopMargin);this.hasCartesianSeries&&n(this.axes,
function(a){a.getOffset()});s(h)||(this.plotLeft+=e[3]);s(g)||(this.plotTop+=e[0]);s(j)||(this.marginBottom+=e[2]);s(i)||(this.marginRight+=e[1]);this.setChartSize()},initReflow:function(){function a(a){var g=c.width||gb(d,"width"),h=c.height||gb(d,"height"),a=a?a.target:E;if(!b.hasUserSize&&g&&h&&(a===E||a===z)){if(g!==b.containerWidth||h!==b.containerHeight)clearTimeout(e),b.reflowTimeout=e=setTimeout(function(){if(b.container)b.setSize(g,h,!1),b.hasUserSize=null},100);b.containerWidth=g;b.containerHeight=
h}}var b=this,c=b.options.chart,d=b.renderTo,e;J(E,"resize",a);J(b,"destroy",function(){ba(E,"resize",a)})},setSize:function(a,b,c){var d=this,e,f,g;d.isResizing+=1;g=function(){d&&G(d,"endResize",null,function(){d.isResizing-=1})};Ha(c,d);d.oldChartHeight=d.chartHeight;d.oldChartWidth=d.chartWidth;if(s(a))d.chartWidth=e=q(0,t(a)),d.hasUserSize=!!e;if(s(b))d.chartHeight=f=q(0,t(b));M(d.container,{width:e+"px",height:f+"px"});d.setChartSize(!0);d.renderer.setSize(e,f,c);d.maxTicks=null;n(d.axes,function(a){a.isDirty=
!0;a.setScale()});n(d.series,function(a){a.isDirty=!0});d.isDirtyLegend=!0;d.isDirtyBox=!0;d.getMargins();d.redraw(c);d.oldChartHeight=null;G(d,"resize");ya===!1?g():setTimeout(g,ya&&ya.duration||500)},setChartSize:function(a){var b=this.inverted,c=this.renderer,d=this.chartWidth,e=this.chartHeight,f=this.options.chart,g=f.spacingTop,h=f.spacingRight,i=f.spacingBottom,j=f.spacingLeft,k=this.clipOffset,m,l,p,o;this.plotLeft=m=t(this.plotLeft);this.plotTop=l=t(this.plotTop);this.plotWidth=p=q(0,t(d-
m-this.marginRight));this.plotHeight=o=q(0,t(e-l-this.marginBottom));this.plotSizeX=b?o:p;this.plotSizeY=b?p:o;this.plotBorderWidth=b=f.plotBorderWidth||0;this.spacingBox=c.spacingBox={x:j,y:g,width:d-j-h,height:e-g-i};this.plotBox=c.plotBox={x:m,y:l,width:p,height:o};c=ja(q(b,k[3])/2);d=ja(q(b,k[0])/2);this.clipBox={x:c,y:d,width:T(this.plotSizeX-q(b,k[1])/2-c),height:T(this.plotSizeY-q(b,k[2])/2-d)};a||n(this.axes,function(a){a.setAxisSize();a.setAxisTranslation()})},resetMargins:function(){var a=
this.options.chart,b=a.spacingRight,c=a.spacingBottom,d=a.spacingLeft;this.plotTop=o(this.optionsMarginTop,a.spacingTop);this.marginRight=o(this.optionsMarginRight,b);this.marginBottom=o(this.optionsMarginBottom,c);this.plotLeft=o(this.optionsMarginLeft,d);this.axisOffset=[0,0,0,0];this.clipOffset=[0,0,0,0]},drawChartBox:function(){var a=this.options.chart,b=this.renderer,c=this.chartWidth,d=this.chartHeight,e=this.chartBackground,f=this.plotBackground,g=this.plotBorder,h=this.plotBGImage,i=a.borderWidth||
0,j=a.backgroundColor,k=a.plotBackgroundColor,m=a.plotBackgroundImage,l=a.plotBorderWidth||0,p,o=this.plotLeft,n=this.plotTop,t=this.plotWidth,q=this.plotHeight,s=this.plotBox,u=this.clipRect,v=this.clipBox;p=i+(a.shadow?8:0);if(i||j)if(e)e.animate(e.crisp(null,null,null,c-p,d-p));else{e={fill:j||O};if(i)e.stroke=a.borderColor,e["stroke-width"]=i;this.chartBackground=b.rect(p/2,p/2,c-p,d-p,a.borderRadius,i).attr(e).add().shadow(a.shadow)}if(k)f?f.animate(s):this.plotBackground=b.rect(o,n,t,q,0).attr({fill:k}).add().shadow(a.plotShadow);
if(m)h?h.animate(s):this.plotBGImage=b.image(m,o,n,t,q).add();u?u.animate({width:v.width,height:v.height}):this.clipRect=b.clipRect(v);if(l)g?g.animate(g.crisp(null,o,n,t,q)):this.plotBorder=b.rect(o,n,t,q,0,l).attr({stroke:a.plotBorderColor,"stroke-width":l,zIndex:1}).add();this.isDirtyBox=!1},propFromSeries:function(){var a=this,b=a.options.chart,c,d=a.options.series,e,f;n(["inverted","angular","polar"],function(g){c=aa[b.type||b.defaultSeriesType];f=a[g]||b[g]||c&&c.prototype[g];for(e=d&&d.length;!f&&
e--;)(c=aa[d[e].type])&&c.prototype[g]&&(f=!0);a[g]=f})},render:function(){var a=this,b=a.axes,c=a.renderer,d=a.options,e=d.labels,f=d.credits,g;a.setTitle();a.legend=new rb(a,d.legend);n(b,function(a){a.setScale()});a.getMargins();a.maxTicks=null;n(b,function(a){a.setTickPositions(!0);a.setMaxTicks()});a.adjustTickAmounts();a.getMargins();a.drawChartBox();a.hasCartesianSeries&&n(b,function(a){a.render()});if(!a.seriesGroup)a.seriesGroup=c.g("series-group").attr({zIndex:3}).add();n(a.series,function(a){a.translate();
a.setTooltipPoints();a.render()});e.items&&n(e.items,function(b){var d=u(e.style,b.style),f=v(d.left)+a.plotLeft,g=v(d.top)+a.plotTop+12;delete d.left;delete d.top;c.text(b.html,f,g).attr({zIndex:2}).css(d).add()});if(f.enabled&&!a.credits)g=f.href,a.credits=c.text(f.text,0,0).on("click",function(){if(g)location.href=g}).attr({align:f.position.align,zIndex:8}).css(f.style).add().align(f.position);a.hasRendered=!0},destroy:function(){var a=this,b=a.axes,c=a.series,d=a.container,e,f=d&&d.parentNode;
G(a,"destroy");Aa[a.index]=w;a.renderTo.removeAttribute("data-highcharts-chart");ba(a);for(e=b.length;e--;)b[e]=b[e].destroy();for(e=c.length;e--;)c[e]=c[e].destroy();n("title,subtitle,chartBackground,plotBackground,plotBGImage,plotBorder,seriesGroup,clipRect,credits,pointer,scroller,rangeSelector,legend,resetZoomButton,tooltip,renderer".split(","),function(b){var c=a[b];c&&c.destroy&&(a[b]=c.destroy())});if(d)d.innerHTML="",ba(d),f&&Ra(d);for(e in a)delete a[e]},isReadyToRender:function(){var a=
this;return!Z&&E==E.top&&z.readyState!=="complete"||$&&!E.canvg?($?Qb.push(function(){a.firstRender()},a.options.global.canvasToolsURL):z.attachEvent("onreadystatechange",function(){z.detachEvent("onreadystatechange",a.firstRender);z.readyState==="complete"&&a.firstRender()}),!1):!0},firstRender:function(){var a=this,b=a.options,c=a.callback;if(a.isReadyToRender())a.getContainer(),G(a,"init"),a.resetMargins(),a.setChartSize(),a.propFromSeries(),a.getAxes(),n(b.series||[],function(b){a.initSeries(b)}),
G(a,"beforeRender"),a.pointer=new qb(a,b),a.render(),a.renderer.draw(),c&&c.apply(a,[a]),n(a.callbacks,function(b){b.apply(a,[a])}),a.cloneRenderTo(!0),G(a,"load")}};sb.prototype.callbacks=[];var Ma=function(){};Ma.prototype={init:function(a,b,c){this.series=a;this.applyOptions(b,c);this.pointAttr={};if(a.options.colorByPoint&&(b=a.options.colors||a.chart.options.colors,this.color=this.color||b[a.colorCounter++],a.colorCounter===b.length))a.colorCounter=0;a.chart.pointCount++;return this},applyOptions:function(a,
b){var c=this.series,d=c.pointValKey,a=Ma.prototype.optionsToObject.call(this,a);u(this,a);this.options=this.options?u(this.options,a):a;if(d)this.y=this[d];if(this.x===w&&c)this.x=b===w?c.autoIncrement():b;return this},optionsToObject:function(a){var b,c=this.series,d=c.pointArrayMap||["y"],e=d.length,f=0,g=0;if(typeof a==="number"||a===null)b={y:a};else if(Ca(a)){b={};if(a.length>e){c=typeof a[0];if(c==="string")b.name=a[0];else if(c==="number")b.x=a[0];f++}for(;g<e;)b[d[g++]]=a[f++]}else if(typeof a===
"object"){b=a;if(a.dataLabels)c._hasPointLabels=!0;if(a.marker)c._hasPointMarkers=!0}return b},destroy:function(){var a=this.series.chart,b=a.hoverPoints,c;a.pointCount--;if(b&&(this.setState(),ga(b,this),!b.length))a.hoverPoints=null;if(this===a.hoverPoint)this.onMouseOut();if(this.graphic||this.dataLabel)ba(this),this.destroyElements();this.legendItem&&a.legend.destroyItem(this);for(c in this)this[c]=null},destroyElements:function(){for(var a="graphic,dataLabel,dataLabelUpper,group,connector,shadowGroup".split(","),
b,c=6;c--;)b=a[c],this[b]&&(this[b]=this[b].destroy())},getLabelConfig:function(){return{x:this.category,y:this.y,key:this.name||this.category,series:this.series,point:this,percentage:this.percentage,total:this.total||this.stackTotal}},select:function(a,b){var c=this,d=c.series,e=d.chart,a=o(a,!c.selected);c.firePointEvent(a?"select":"unselect",{accumulate:b},function(){c.selected=c.options.selected=a;d.options.data[ka(c,d.data)]=c.options;c.setState(a&&"select");b||n(e.getSelectedPoints(),function(a){if(a.selected&&
a!==c)a.selected=a.options.selected=!1,d.options.data[ka(a,d.data)]=a.options,a.setState(""),a.firePointEvent("unselect")})})},onMouseOver:function(a){var b=this.series,c=b.chart,d=c.tooltip,e=c.hoverPoint;if(e&&e!==this)e.onMouseOut();this.firePointEvent("mouseOver");d&&(!d.shared||b.noSharedTooltip)&&d.refresh(this,a);this.setState("hover");c.hoverPoint=this},onMouseOut:function(){var a=this.series.chart,b=a.hoverPoints;if(!b||ka(this,b)===-1)this.firePointEvent("mouseOut"),this.setState(),a.hoverPoint=
null},tooltipFormatter:function(a){var b=this.series,c=b.tooltipOptions,d=c.valueDecimals,e=c.valuePrefix||"",f=c.valueSuffix||"";n(b.pointArrayMap||["y"],function(b){b="{point."+b;if(e||f)a=a.replace(b+"}",e+b+"}"+f);ua(d)&&(a=a.replace(b+"}",b+":,."+d+"f}"))});return Ea(a,{point:this,series:this.series})},update:function(a,b,c){var d=this,e=d.series,f=d.graphic,g,h=e.data,i=e.chart,b=o(b,!0);d.firePointEvent("update",{options:a},function(){d.applyOptions(a);V(a)&&(e.getAttribs(),f&&f.attr(d.pointAttr[e.state]));
g=ka(d,h);e.xData[g]=d.x;e.yData[g]=e.toYData?e.toYData(d):d.y;e.zData[g]=d.z;e.options.data[g]=d.options;e.isDirty=!0;e.isDirtyData=!0;b&&i.redraw(c)})},remove:function(a,b){var c=this,d=c.series,e=d.chart,f,g=d.data;Ha(b,e);a=o(a,!0);c.firePointEvent("remove",null,function(){f=ka(c,g);g.splice(f,1);d.options.data.splice(f,1);d.xData.splice(f,1);d.yData.splice(f,1);d.zData.splice(f,1);c.destroy();d.isDirty=!0;d.isDirtyData=!0;a&&e.redraw()})},firePointEvent:function(a,b,c){var d=this,e=this.series.options;
(e.point.events[a]||d.options&&d.options.events&&d.options.events[a])&&this.importEvents();a==="click"&&e.allowPointSelect&&(c=function(a){d.select(null,a.ctrlKey||a.metaKey||a.shiftKey)});G(this,a,b,c)},importEvents:function(){if(!this.hasImportedEvents){var a=x(this.series.options.point,this.options).events,b;this.events=a;for(b in a)J(this,b,a[b]);this.hasImportedEvents=!0}},setState:function(a){var b=this.plotX,c=this.plotY,d=this.series,e=d.options.states,f=X[d.type].marker&&d.options.marker,
g=f&&!f.enabled,h=f&&f.states[a],i=h&&h.enabled===!1,j=d.stateMarkerGraphic,k=this.marker||{},m=d.chart,l=this.pointAttr,a=a||"";if(!(a===this.state||this.selected&&a!=="select"||e[a]&&e[a].enabled===!1||a&&(i||g&&!h.enabled))){if(this.graphic)e=f&&this.graphic.symbolName&&l[a].r,this.graphic.attr(x(l[a],e?{x:b-e,y:c-e,width:2*e,height:2*e}:{}));else{if(a&&h)e=h.radius,k=k.symbol||d.symbol,j&&j.currentSymbol!==k&&(j=j.destroy()),j?j.attr({x:b-e,y:c-e}):(d.stateMarkerGraphic=j=m.renderer.symbol(k,
b-e,c-e,2*e,2*e).attr(l[a]).add(d.markerGroup),j.currentSymbol=k);if(j)j[a&&m.isInsidePlot(b,c)?"show":"hide"]()}this.state=a}}};var S=function(){};S.prototype={isCartesian:!0,type:"line",pointClass:Ma,sorted:!0,requireSorting:!0,pointAttrToOptions:{stroke:"lineColor","stroke-width":"lineWidth",fill:"fillColor",r:"radius"},colorCounter:0,init:function(a,b){var c,d,e=a.series;this.chart=a;this.options=b=this.setOptions(b);this.bindAxes();u(this,{name:b.name,state:"",pointAttr:{},visible:b.visible!==
!1,selected:b.selected===!0});if($)b.animation=!1;d=b.events;for(c in d)J(this,c,d[c]);if(d&&d.click||b.point&&b.point.events&&b.point.events.click||b.allowPointSelect)a.runTrackerClick=!0;this.getColor();this.getSymbol();this.setData(b.data,!1);if(this.isCartesian)a.hasCartesianSeries=!0;e.push(this);this._i=e.length-1;Gb(e,function(a,b){return o(a.options.index,a._i)-o(b.options.index,a._i)});n(e,function(a,b){a.index=b;a.name=a.name||"Series "+(b+1)});c=b.linkedTo;this.linkedSeries=[];if(fa(c)&&
(c=c===":previous"?e[this.index-1]:a.get(c)))c.linkedSeries.push(this),this.linkedParent=c},bindAxes:function(){var a=this,b=a.options,c=a.chart,d;a.isCartesian&&n(["xAxis","yAxis"],function(e){n(c[e],function(c){d=c.options;if(b[e]===d.index||b[e]!==w&&b[e]===d.id||b[e]===w&&d.index===0)c.series.push(a),a[e]=c,c.isDirty=!0});a[e]||qa(17,!0)})},autoIncrement:function(){var a=this.options,b=this.xIncrement,b=o(b,a.pointStart,0);this.pointInterval=o(this.pointInterval,a.pointInterval,1);this.xIncrement=
b+this.pointInterval;return b},getSegments:function(){var a=-1,b=[],c,d=this.points,e=d.length;if(e)if(this.options.connectNulls){for(c=e;c--;)d[c].y===null&&d.splice(c,1);d.length&&(b=[d])}else n(d,function(c,g){c.y===null?(g>a+1&&b.push(d.slice(a+1,g)),a=g):g===e-1&&b.push(d.slice(a+1,g+1))});this.segments=b},setOptions:function(a){var b=this.chart.options,c=b.plotOptions,d=c[this.type];this.userOptions=a;a=x(d,c.series,a);this.tooltipOptions=x(b.tooltip,a.tooltip);d.marker===null&&delete a.marker;
return a},getColor:function(){var a=this.options,b=this.userOptions,c=this.chart.options.colors,d=this.chart.counters,e;e=a.color||X[this.type].color;if(!e&&!a.colorByPoint)s(b._colorIndex)?a=b._colorIndex:(b._colorIndex=d.color,a=d.color++),e=c[a];this.color=e;d.wrapColor(c.length)},getSymbol:function(){var a=this.userOptions,b=this.options.marker,c=this.chart,d=c.options.symbols,c=c.counters;this.symbol=b.symbol;if(!this.symbol)s(a._symbolIndex)?a=a._symbolIndex:(a._symbolIndex=c.symbol,a=c.symbol++),
this.symbol=d[a];if(/^url/.test(this.symbol))b.radius=0;c.wrapSymbol(d.length)},drawLegendSymbol:function(a){var b=this.options,c=b.marker,d=a.options.symbolWidth,e=this.chart.renderer,f=this.legendGroup,a=a.baseline,g;if(b.lineWidth){g={"stroke-width":b.lineWidth};if(b.dashStyle)g.dashstyle=b.dashStyle;this.legendLine=e.path(["M",0,a-4,"L",d,a-4]).attr(g).add(f)}if(c&&c.enabled)b=c.radius,this.legendSymbol=e.symbol(this.symbol,d/2-b,a-4-b,2*b,2*b).add(f)},addPoint:function(a,b,c,d){var e=this.options,
f=this.data,g=this.graph,h=this.area,i=this.chart,j=this.xData,k=this.yData,m=this.zData,l=this.names,p=g&&g.shift||0,n=e.data;Ha(d,i);if(g&&c)g.shift=p+1;if(h){if(c)h.shift=p+1;h.isArea=!0}b=o(b,!0);d={series:this};this.pointClass.prototype.applyOptions.apply(d,[a]);j.push(d.x);k.push(this.toYData?this.toYData(d):d.y);m.push(d.z);if(l)l[d.x]=d.name;n.push(a);e.legendType==="point"&&this.generatePoints();c&&(f[0]&&f[0].remove?f[0].remove(!1):(f.shift(),j.shift(),k.shift(),m.shift(),n.shift()));this.getAttribs();
this.isDirtyData=this.isDirty=!0;b&&i.redraw()},setData:function(a,b){var c=this.points,d=this.options,e=this.chart,f=null,g=this.xAxis,h=g&&g.categories&&!g.categories.length?[]:null,i;this.xIncrement=null;this.pointRange=g&&g.categories?1:d.pointRange;this.colorCounter=0;var j=[],k=[],m=[],l=a?a.length:[],p=(i=this.pointArrayMap)&&i.length,n=!!this.toYData;if(l>(d.turboThreshold||1E3)){for(i=0;f===null&&i<l;)f=a[i],i++;if(ua(f)){f=o(d.pointStart,0);d=o(d.pointInterval,1);for(i=0;i<l;i++)j[i]=f,
k[i]=a[i],f+=d;this.xIncrement=f}else if(Ca(f))if(p)for(i=0;i<l;i++)d=a[i],j[i]=d[0],k[i]=d.slice(1,p+1);else for(i=0;i<l;i++)d=a[i],j[i]=d[0],k[i]=d[1]}else for(i=0;i<l;i++)if(a[i]!==w&&(d={series:this},this.pointClass.prototype.applyOptions.apply(d,[a[i]]),j[i]=d.x,k[i]=n?this.toYData(d):d.y,m[i]=d.z,h&&d.name))h[i]=d.name;this.requireSorting&&j.length>1&&j[1]<j[0]&&qa(15);fa(k[0])&&qa(14,!0);this.data=[];this.options.data=a;this.xData=j;this.yData=k;this.zData=m;this.names=h;for(i=c&&c.length||
0;i--;)c[i]&&c[i].destroy&&c[i].destroy();if(g)g.minRange=g.userMinRange;this.isDirty=this.isDirtyData=e.isDirtyBox=!0;o(b,!0)&&e.redraw(!1)},remove:function(a,b){var c=this,d=c.chart,a=o(a,!0);if(!c.isRemoving)c.isRemoving=!0,G(c,"remove",null,function(){c.destroy();d.isDirtyLegend=d.isDirtyBox=!0;a&&d.redraw(b)});c.isRemoving=!1},processData:function(a){var b=this.xData,c=this.yData,d=b.length,e=0,f=d,g,h,i=this.xAxis,j=this.options,k=j.cropThreshold,m=this.isCartesian;if(m&&!this.isDirty&&!i.isDirty&&
!this.yAxis.isDirty&&!a)return!1;if(m&&this.sorted&&(!k||d>k||this.forceCrop))if(a=i.getExtremes(),i=a.min,k=a.max,b[d-1]<i||b[0]>k)b=[],c=[];else if(b[0]<i||b[d-1]>k){for(a=0;a<d;a++)if(b[a]>=i){e=q(0,a-1);break}for(;a<d;a++)if(b[a]>k){f=a+1;break}b=b.slice(e,f);c=c.slice(e,f);g=!0}for(a=b.length-1;a>0;a--)if(d=b[a]-b[a-1],d>0&&(h===w||d<h))h=d;this.cropped=g;this.cropStart=e;this.processedXData=b;this.processedYData=c;if(j.pointRange===null)this.pointRange=h||1;this.closestPointRange=h},generatePoints:function(){var a=
this.options.data,b=this.data,c,d=this.processedXData,e=this.processedYData,f=this.pointClass,g=d.length,h=this.cropStart||0,i,j=this.hasGroupedData,k,m=[],l;if(!b&&!j)b=[],b.length=a.length,b=this.data=b;for(l=0;l<g;l++)i=h+l,j?m[l]=(new f).init(this,[d[l]].concat(ha(e[l]))):(b[i]?k=b[i]:a[i]!==w&&(b[i]=k=(new f).init(this,a[i],d[l])),m[l]=k);if(b&&(g!==(c=b.length)||j))for(l=0;l<c;l++)if(l===h&&!j&&(l+=g),b[l])b[l].destroyElements(),b[l].plotX=w;this.data=b;this.points=m},translate:function(){this.processedXData||
this.processData();this.generatePoints();for(var a=this.options,b=a.stacking,c=this.xAxis,d=c.categories,e=this.yAxis,f=this.points,g=f.length,h=!!this.modifyValue,i,j=e.series,k=j.length,m=a.pointPlacement==="between",a=a.threshold;k--;)if(j[k].visible){j[k]===this&&(i=!0);break}for(k=0;k<g;k++){var j=f[k],l=j.x,p=j.y,n=j.low,q=e.stacks[(p<a?"-":"")+this.stackKey];if(e.isLog&&p<=0)j.y=p=null;j.plotX=c.translate(l,0,0,0,1,m);if(b&&this.visible&&q&&q[l])n=q[l],q=n.total,n.cum=n=n.cum-p,p=n+p,i&&(n=
o(a,e.min)),e.isLog&&n<=0&&(n=null),b==="percent"&&(n=q?n*100/q:0,p=q?p*100/q:0),j.percentage=q?j.y*100/q:0,j.total=j.stackTotal=q,j.stackY=p;j.yBottom=s(n)?e.translate(n,0,1,0,1):null;h&&(p=this.modifyValue(p,j));j.plotY=typeof p==="number"&&p!==Infinity?t(e.translate(p,0,1,0,1)*10)/10:w;j.clientX=m?c.translate(l,0,0,0,1):j.plotX;j.negative=j.y<(a||0);j.category=d&&d[j.x]!==w?d[j.x]:j.x}this.getSegments()},setTooltipPoints:function(a){var b=[],c,d,e=(c=this.xAxis)?c.tooltipLen||c.len:this.chart.plotSizeX,
f,g,h=[];if(this.options.enableMouseTracking!==!1){if(a)this.tooltipPoints=null;n(this.segments||this.points,function(a){b=b.concat(a)});c&&c.reversed&&(b=b.reverse());a=b.length;for(g=0;g<a;g++){f=b[g];c=b[g-1]?d+1:0;for(d=b[g+1]?q(0,T((f.clientX+(b[g+1]?b[g+1].clientX:e))/2)):e;c>=0&&c<=d;)h[c++]=f}this.tooltipPoints=h}},tooltipHeaderFormatter:function(a){var b=this.tooltipOptions,c=b.xDateFormat,d=this.xAxis,e=d&&d.options.type==="datetime",f=b.headerFormat,g;if(e&&!c)for(g in A)if(A[g]>=d.closestPointRange){c=
b.dateTimeLabelFormats[g];break}e&&c&&ua(a.key)&&(f=f.replace("{point.key}","{point.key:"+c+"}"));return Ea(f,{point:a,series:this})},onMouseOver:function(){var a=this.chart,b=a.hoverSeries;if(b&&b!==this)b.onMouseOut();this.options.events.mouseOver&&G(this,"mouseOver");this.setState("hover");a.hoverSeries=this},onMouseOut:function(){var a=this.options,b=this.chart,c=b.tooltip,d=b.hoverPoint;if(d)d.onMouseOut();this&&a.events.mouseOut&&G(this,"mouseOut");c&&!a.stickyTracking&&(!c.shared||this.noSharedTooltip)&&
c.hide();this.setState();b.hoverSeries=null},animate:function(a){var b=this,c=b.chart,d=c.renderer,e;e=b.options.animation;var f=c.clipBox,g=c.inverted,h;if(e&&!V(e))e=X[b.type].animation;h="_sharedClip"+e.duration+e.easing;if(a)a=c[h],e=c[h+"m"],a||(c[h]=a=d.clipRect(u(f,{width:0})),c[h+"m"]=e=d.clipRect(-99,g?-c.plotLeft:-c.plotTop,99,g?c.chartWidth:c.chartHeight)),b.group.clip(a),b.markerGroup.clip(e),b.sharedClipKey=h;else{if(a=c[h])a.animate({width:c.plotSizeX},e),c[h+"m"].animate({width:c.plotSizeX+
99},e);b.animate=null;b.animationTimeout=setTimeout(function(){b.afterAnimate()},e.duration)}},afterAnimate:function(){var a=this.chart,b=this.sharedClipKey,c=this.group;c&&this.options.clip!==!1&&(c.clip(a.clipRect),this.markerGroup.clip());setTimeout(function(){b&&a[b]&&(a[b]=a[b].destroy(),a[b+"m"]=a[b+"m"].destroy())},100)},drawPoints:function(){var a,b=this.points,c=this.chart,d,e,f,g,h,i,j,k,m=this.options.marker,l,n=this.markerGroup;if(m.enabled||this._hasPointMarkers)for(f=b.length;f--;)if(g=
b[f],d=g.plotX,e=g.plotY,k=g.graphic,i=g.marker||{},a=m.enabled&&i.enabled===w||i.enabled,l=c.isInsidePlot(d,e,c.inverted),a&&e!==w&&!isNaN(e)&&g.y!==null)if(a=g.pointAttr[g.selected?"select":""],h=a.r,i=o(i.symbol,this.symbol),j=i.indexOf("url")===0,k)k.attr({visibility:l?Z?"inherit":"visible":"hidden"}).animate(u({x:d-h,y:e-h},k.symbolName?{width:2*h,height:2*h}:{}));else{if(l&&(h>0||j))g.graphic=c.renderer.symbol(i,d-h,e-h,2*h,2*h).attr(a).add(n)}else if(k)g.graphic=k.destroy()},convertAttribs:function(a,
b,c,d){var e=this.pointAttrToOptions,f,g,h={},a=a||{},b=b||{},c=c||{},d=d||{};for(f in e)g=e[f],h[f]=o(a[g],b[f],c[f],d[f]);return h},getAttribs:function(){var a=this,b=a.options,c=X[a.type].marker?b.marker:b,d=c.states,e=d.hover,f,g=a.color,h={stroke:g,fill:g},i=a.points||[],j=[],k,m=a.pointAttrToOptions,l=b.negativeColor,o;b.marker?(e.radius=e.radius||c.radius+2,e.lineWidth=e.lineWidth||c.lineWidth+1):e.color=e.color||la(e.color||g).brighten(e.brightness).get();j[""]=a.convertAttribs(c,h);n(["hover",
"select"],function(b){j[b]=a.convertAttribs(d[b],j[""])});a.pointAttr=j;for(g=i.length;g--;){h=i[g];if((c=h.options&&h.options.marker||h.options)&&c.enabled===!1)c.radius=0;if(h.negative)h.color=h.fillColor=l;f=b.colorByPoint||h.color;if(h.options)for(o in m)s(c[m[o]])&&(f=!0);if(f){c=c||{};k=[];d=c.states||{};f=d.hover=d.hover||{};if(!b.marker)f.color=la(f.color||h.color).brighten(f.brightness||e.brightness).get();k[""]=a.convertAttribs(u({color:h.color},c),j[""]);k.hover=a.convertAttribs(d.hover,
j.hover,k[""]);k.select=a.convertAttribs(d.select,j.select,k[""]);if(h.negative&&b.marker)k[""].fill=k.hover.fill=k.select.fill=a.convertAttribs({fillColor:l}).fill}else k=j;h.pointAttr=k}},update:function(a,b){var c=this.chart,d=this.type,a=x(this.userOptions,{animation:!1,index:this.index,pointStart:this.xData[0]},a);this.remove(!1);u(this,aa[a.type||d].prototype);this.init(c,a);o(b,!0)&&c.redraw(!1)},destroy:function(){var a=this,b=a.chart,c=/AppleWebKit\/533/.test(za),d,e,f=a.data||[],g,h,i;G(a,
"destroy");ba(a);n(["xAxis","yAxis"],function(b){if(i=a[b])ga(i.series,a),i.isDirty=i.forceRedraw=!0});a.legendItem&&a.chart.legend.destroyItem(a);for(e=f.length;e--;)(g=f[e])&&g.destroy&&g.destroy();a.points=null;clearTimeout(a.animationTimeout);n("area,graph,dataLabelsGroup,group,markerGroup,tracker,graphNeg,areaNeg,posClip,negClip".split(","),function(b){a[b]&&(d=c&&b==="group"?"hide":"destroy",a[b][d]())});if(b.hoverSeries===a)b.hoverSeries=null;ga(b.series,a);for(h in a)delete a[h]},drawDataLabels:function(){var a=
this,b=a.options.dataLabels,c=a.points,d,e,f,g;if(b.enabled||a._hasPointLabels)a.dlProcessOptions&&a.dlProcessOptions(b),g=a.plotGroup("dataLabelsGroup","data-labels",a.visible?"visible":"hidden",b.zIndex||6),e=b,n(c,function(c){var i,j=c.dataLabel,k,m,l=c.connector,n=!0;d=c.options&&c.options.dataLabels;i=e.enabled||d&&d.enabled;if(j&&!i)c.dataLabel=j.destroy();else if(i){i=b.rotation;b=x(e,d);k=c.getLabelConfig();f=b.format?Ea(b.format,k):b.formatter.call(k,b);b.style.color=o(b.color,b.style.color,
a.color,"black");if(j)if(s(f))j.attr({text:f}),n=!1;else{if(c.dataLabel=j=j.destroy(),l)c.connector=l.destroy()}else if(s(f)){j={fill:b.backgroundColor,stroke:b.borderColor,"stroke-width":b.borderWidth,r:b.borderRadius||0,rotation:i,padding:b.padding,zIndex:1};for(m in j)j[m]===w&&delete j[m];j=c.dataLabel=a.chart.renderer[i?"text":"label"](f,0,-999,null,null,null,b.useHTML).attr(j).css(b.style).add(g).shadow(b.shadow)}j&&a.alignDataLabel(c,j,b,null,n)}})},alignDataLabel:function(a,b,c,d,e){var f=
this.chart,g=f.inverted,h=o(a.plotX,-999),a=o(a.plotY,-999),i=b.getBBox(),d=u({x:g?f.plotWidth-a:h,y:t(g?f.plotHeight-h:a),width:0,height:0},d);u(c,{width:i.width,height:i.height});c.rotation?(d={align:c.align,x:d.x+c.x+d.width/2,y:d.y+c.y+d.height/2},b[e?"attr":"animate"](d)):b.align(c,null,d);b.attr({visibility:c.crop===!1||f.isInsidePlot(h,a,g)?f.renderer.isSVG?"inherit":"visible":"hidden"})},getSegmentPath:function(a){var b=this,c=[],d=b.options.step;n(a,function(e,f){var g=e.plotX,h=e.plotY,
i;b.getPointSpline?c.push.apply(c,b.getPointSpline(a,e,f)):(c.push(f?"L":"M"),d&&f&&(i=a[f-1],d==="right"?c.push(i.plotX,h):d==="center"?c.push((i.plotX+g)/2,i.plotY,(i.plotX+g)/2,h):c.push(g,i.plotY)),c.push(e.plotX,e.plotY))});return c},getGraphPath:function(){var a=this,b=[],c,d=[];n(a.segments,function(e){c=a.getSegmentPath(e);e.length>1?b=b.concat(c):d.push(e[0])});a.singlePoints=d;return a.graphPath=b},drawGraph:function(){var a=this,b=this.options,c=[["graph",b.lineColor||this.color]],d=b.lineWidth,
e=b.dashStyle,f=this.getGraphPath(),g=b.negativeColor;g&&c.push(["graphNeg",g]);n(c,function(c,g){var j=c[0],k=a[j];if(k)Ta(k),k.animate({d:f});else if(d&&f.length){k={stroke:c[1],"stroke-width":d,zIndex:1};if(e)k.dashstyle=e;a[j]=a.chart.renderer.path(f).attr(k).add(a.group).shadow(!g&&b.shadow)}})},clipNeg:function(){var a=this.options,b=this.chart,c=b.renderer,d=a.negativeColor,e,f=this.posClip,g=this.negClip;e=b.chartWidth;var h=b.chartHeight,i=q(e,h);if(d&&this.graph)d=ja(this.yAxis.len-this.yAxis.translate(a.threshold||
0)),a={x:0,y:0,width:i,height:d},i={x:0,y:d,width:i,height:i-d},b.inverted&&c.isVML&&(a={x:b.plotWidth-d-b.plotLeft,y:0,width:e,height:h},i={x:d+b.plotLeft-e,y:0,width:b.plotLeft+d,height:e}),this.yAxis.reversed?(b=i,e=a):(b=a,e=i),f?(f.animate(b),g.animate(e)):(this.posClip=f=c.clipRect(b),this.graph.clip(f),this.negClip=g=c.clipRect(e),this.graphNeg.clip(g),this.area&&(this.area.clip(f),this.areaNeg.clip(g)))},invertGroups:function(){function a(){var a={width:b.yAxis.len,height:b.xAxis.len};n(["group",
"markerGroup"],function(c){b[c]&&b[c].attr(a).invert()})}var b=this,c=b.chart;J(c,"resize",a);J(b,"destroy",function(){ba(c,"resize",a)});a();b.invertGroups=a},plotGroup:function(a,b,c,d,e){var f=this[a],g=!f,h=this.chart,i=this.xAxis,j=this.yAxis;g&&(this[a]=f=h.renderer.g(b).attr({visibility:c,zIndex:d||0.1}).add(e));f[g?"attr":"animate"]({translateX:i?i.left:h.plotLeft,translateY:j?j.top:h.plotTop});return f},render:function(){var a=this.chart,b,c=this.options,d=c.animation&&!!this.animate&&a.renderer.isSVG,
e=this.visible?"visible":"hidden",f=c.zIndex,g=this.hasRendered,h=a.seriesGroup;b=this.plotGroup("group","series",e,f,h);this.markerGroup=this.plotGroup("markerGroup","markers",e,f,h);d&&this.animate(!0);this.getAttribs();b.inverted=a.inverted;this.drawGraph&&(this.drawGraph(),this.clipNeg());this.drawDataLabels();this.drawPoints();this.options.enableMouseTracking!==!1&&this.drawTracker();a.inverted&&this.invertGroups();c.clip!==!1&&!this.sharedClipKey&&!g&&b.clip(a.clipRect);d?this.animate():g||
this.afterAnimate();this.isDirty=this.isDirtyData=!1;this.hasRendered=!0},redraw:function(){var a=this.chart,b=this.isDirtyData,c=this.group,d=this.xAxis,e=this.yAxis;c&&(a.inverted&&c.attr({width:a.plotWidth,height:a.plotHeight}),c.animate({translateX:o(d&&d.left,a.plotLeft),translateY:o(e&&e.top,a.plotTop)}));this.translate();this.setTooltipPoints(!0);this.render();b&&G(this,"updatedData")},setState:function(a){var b=this.options,c=this.graph,d=this.graphNeg,e=b.states,b=b.lineWidth,a=a||"";if(this.state!==
a)this.state=a,e[a]&&e[a].enabled===!1||(a&&(b=e[a].lineWidth||b+1),c&&!c.dashstyle&&(a={"stroke-width":b},c.attr(a),d&&d.attr(a)))},setVisible:function(a,b){var c=this,d=c.chart,e=c.legendItem,f,g=d.options.chart.ignoreHiddenSeries,h=c.visible;f=(c.visible=a=c.userOptions.visible=a===w?!h:a)?"show":"hide";n(["group","dataLabelsGroup","markerGroup","tracker"],function(a){if(c[a])c[a][f]()});if(d.hoverSeries===c)c.onMouseOut();e&&d.legend.colorizeItem(c,a);c.isDirty=!0;c.options.stacking&&n(d.series,
function(a){if(a.options.stacking&&a.visible)a.isDirty=!0});n(c.linkedSeries,function(b){b.setVisible(a,!1)});if(g)d.isDirtyBox=!0;b!==!1&&d.redraw();G(c,f)},show:function(){this.setVisible(!0)},hide:function(){this.setVisible(!1)},select:function(a){this.selected=a=a===w?!this.selected:a;if(this.checkbox)this.checkbox.checked=a;G(this,a?"select":"unselect")},drawTracker:function(){var a=this,b=a.options,c=b.trackByArea,d=[].concat(c?a.areaPath:a.graphPath),e=d.length,f=a.chart,g=f.pointer,h=f.renderer,
i=f.options.tooltip.snap,j=a.tracker,k=b.cursor,k=k&&{cursor:k},m=a.singlePoints,l,n=function(){if(f.hoverSeries!==a)a.onMouseOver()};if(e&&!c)for(l=e+1;l--;)d[l]==="M"&&d.splice(l+1,0,d[l+1]-i,d[l+2],"L"),(l&&d[l]==="M"||l===e)&&d.splice(l,0,"L",d[l-2]+i,d[l-1]);for(l=0;l<m.length;l++)e=m[l],d.push("M",e.plotX-i,e.plotY,"L",e.plotX+i,e.plotY);if(j)j.attr({d:d});else if(a.tracker=j=h.path(d).attr({"class":"highcharts-tracker","stroke-linejoin":"round",visibility:a.visible?"visible":"hidden",stroke:Mb,
fill:c?Mb:O,"stroke-width":b.lineWidth+(c?0:2*i),zIndex:2}).addClass("highcharts-tracker").on("mouseover",n).on("mouseout",function(a){g.onTrackerMouseOut(a)}).css(k).add(a.markerGroup),fb)j.on("touchstart",n)}};L=ea(S);aa.line=L;X.area=x(W,{threshold:0});L=ea(S,{type:"area",getSegments:function(){var a=[],b=this.yAxis.stacks[this.stackKey],c={},d,e;d=this.points;var f;if(this.options.stacking&&!this.cropped){for(e=0;e<d.length;e++)c[d[e].x]=d[e];for(f in b)c[f]?a.push(c[f]):(d=this.xAxis.translate(f),
e=this.yAxis.toPixels(b[f].cum,!0),a.push({y:null,plotX:d,clientX:d,plotY:e,yBottom:e,onMouseOver:ta}));a=[a]}else S.prototype.getSegments.call(this),a=this.segments;this.segments=a},getSegmentPath:function(a){var b=S.prototype.getSegmentPath.call(this,a),c=[].concat(b),d,e=this.options;b.length===3&&c.push("L",b[1],b[2]);if(e.stacking&&!this.closedStacks)for(d=a.length-1;d>=0;d--)d<a.length-1&&e.step&&c.push(a[d+1].plotX,a[d].yBottom),c.push(a[d].plotX,a[d].yBottom);else this.closeSegment(c,a);this.areaPath=
this.areaPath.concat(c);return b},closeSegment:function(a,b){var c=this.yAxis.getThreshold(this.options.threshold);a.push("L",b[b.length-1].plotX,c,"L",b[0].plotX,c)},drawGraph:function(){this.areaPath=[];S.prototype.drawGraph.apply(this);var a=this,b=this.areaPath,c=this.options,d=[["area",this.color,c.fillColor]];c.negativeColor&&d.push(["areaNeg",c.negativeColor,c.negativeFillColor]);n(d,function(d){var f=d[0],g=a[f];g?g.animate({d:b}):a[f]=a.chart.renderer.path(b).attr({fill:o(d[2],la(d[1]).setOpacity(c.fillOpacity||
0.75).get()),zIndex:0}).add(a.group)})},drawLegendSymbol:function(a,b){b.legendSymbol=this.chart.renderer.rect(0,a.baseline-11,a.options.symbolWidth,12,2).attr({zIndex:3}).add(b.legendGroup)}});aa.area=L;X.spline=x(W);K=ea(S,{type:"spline",getPointSpline:function(a,b,c){var d=b.plotX,e=b.plotY,f=a[c-1],g=a[c+1],h,i,j,k;if(f&&g){a=f.plotY;j=g.plotX;var g=g.plotY,m;h=(1.5*d+f.plotX)/2.5;i=(1.5*e+a)/2.5;j=(1.5*d+j)/2.5;k=(1.5*e+g)/2.5;m=(k-i)*(j-d)/(j-h)+e-k;i+=m;k+=m;i>a&&i>e?(i=q(a,e),k=2*e-i):i<a&&
i<e&&(i=F(a,e),k=2*e-i);k>g&&k>e?(k=q(g,e),i=2*e-k):k<g&&k<e&&(k=F(g,e),i=2*e-k);b.rightContX=j;b.rightContY=k}c?(b=["C",f.rightContX||f.plotX,f.rightContY||f.plotY,h||d,i||e,d,e],f.rightContX=f.rightContY=null):b=["M",d,e];return b}});aa.spline=K;X.areaspline=x(X.area);ma=L.prototype;K=ea(K,{type:"areaspline",closedStacks:!0,getSegmentPath:ma.getSegmentPath,closeSegment:ma.closeSegment,drawGraph:ma.drawGraph});aa.areaspline=K;X.column=x(W,{borderColor:"#FFFFFF",borderWidth:1,borderRadius:0,groupPadding:0.2,
marker:null,pointPadding:0.1,minPointLength:0,cropThreshold:50,pointRange:null,states:{hover:{brightness:0.1,shadow:!1},select:{color:"#C0C0C0",borderColor:"#000000",shadow:!1}},dataLabels:{align:null,verticalAlign:null,y:null},stickyTracking:!1,threshold:0});K=ea(S,{type:"column",tooltipOutsidePlot:!0,requireSorting:!1,pointAttrToOptions:{stroke:"borderColor","stroke-width":"borderWidth",fill:"color",r:"borderRadius"},trackerGroups:["group","dataLabelsGroup"],init:function(){S.prototype.init.apply(this,
arguments);var a=this,b=a.chart;b.hasRendered&&n(b.series,function(b){if(b.type===a.type)b.isDirty=!0})},getColumnMetrics:function(){var a=this,b=a.chart,c=a.options,d=this.xAxis,e=d.reversed,f,g={},h,i=0;c.grouping===!1?i=1:n(b.series,function(b){var c=b.options;if(b.type===a.type&&b.visible&&a.options.group===c.group)c.stacking?(f=b.stackKey,g[f]===w&&(g[f]=i++),h=g[f]):c.grouping!==!1&&(h=i++),b.columnIndex=h});var b=F(R(d.transA)*(d.ordinalSlope||c.pointRange||d.closestPointRange||1),d.len),d=
b*c.groupPadding,j=(b-2*d)/i,k=c.pointWidth,c=s(k)?(j-k)/2:j*c.pointPadding,k=o(k,j-2*c);return a.columnMetrics={width:k,offset:c+(d+((e?i-(a.columnIndex||0):a.columnIndex)||0)*j-b/2)*(e?-1:1)}},translate:function(){var a=this,b=a.chart,c=a.options,d=c.stacking,e=c.borderWidth,f=a.yAxis,g=a.translatedThreshold=f.getThreshold(c.threshold),h=o(c.minPointLength,5),c=a.getColumnMetrics(),i=c.width,j=ja(q(i,1+2*e)),k=c.offset;S.prototype.translate.apply(a);n(a.points,function(c){var l=F(q(-999,c.plotY),
f.len+999),n=o(c.yBottom,g),r=c.plotX+k,t=ja(F(l,n)),l=ja(q(l,n)-t),s=f.stacks[(c.y<0?"-":"")+a.stackKey];d&&a.visible&&s&&s[c.x]&&s[c.x].setOffset(k,j);R(l)<h&&h&&(l=h,t=R(t-g)>h?n-h:g-(f.translate(c.y,0,1,0,1)<=g?h:0));c.barX=r;c.pointWidth=i;c.shapeType="rect";c.shapeArgs=c=b.renderer.Element.prototype.crisp.call(0,e,r,t,j,l);e%2&&(c.y-=1,c.height+=1)})},getSymbol:ta,drawLegendSymbol:L.prototype.drawLegendSymbol,drawGraph:ta,drawPoints:function(){var a=this,b=a.options,c=a.chart.renderer,d;n(a.points,
function(e){var f=e.plotY,g=e.graphic;if(f!==w&&!isNaN(f)&&e.y!==null)d=e.shapeArgs,g?(Ta(g),g.animate(x(d))):e.graphic=c[e.shapeType](d).attr(e.pointAttr[e.selected?"select":""]).add(a.group).shadow(b.shadow,null,b.stacking&&!b.borderRadius);else if(g)e.graphic=g.destroy()})},drawTracker:function(){var a=this,b=a.chart.pointer,c=a.options.cursor,d=c&&{cursor:c},e=function(b){var c=b.target,d;for(a.onMouseOver();c&&!d;)d=c.point,c=c.parentNode;if(d!==w)d.onMouseOver(b)};n(a.points,function(a){if(a.graphic)a.graphic.element.point=
a;if(a.dataLabel)a.dataLabel.element.point=a});a._hasTracking?a._hasTracking=!0:n(a.trackerGroups,function(c){if(a[c]&&(a[c].addClass("highcharts-tracker").on("mouseover",e).on("mouseout",function(a){b.onTrackerMouseOut(a)}).css(d),fb))a[c].on("touchstart",e)})},alignDataLabel:function(a,b,c,d,e){var f=this.chart,g=f.inverted,h=a.dlBox||a.shapeArgs,i=a.below||a.plotY>o(this.translatedThreshold,f.plotSizeY),j=o(c.inside,!!this.options.stacking);if(h&&(d=x(h),g&&(d={x:f.plotWidth-d.y-d.height,y:f.plotHeight-
d.x-d.width,width:d.height,height:d.width}),!j))g?(d.x+=i?0:d.width,d.width=0):(d.y+=i?d.height:0,d.height=0);c.align=o(c.align,!g||j?"center":i?"right":"left");c.verticalAlign=o(c.verticalAlign,g||j?"middle":i?"top":"bottom");S.prototype.alignDataLabel.call(this,a,b,c,d,e)},animate:function(a){var b=this.yAxis,c=this.options,d=this.chart.inverted,e={};if(Z)a?(e.scaleY=0.001,a=F(b.pos+b.len,q(b.pos,b.toPixels(c.threshold))),d?e.translateX=a-b.len:e.translateY=a,this.group.attr(e)):(e.scaleY=1,e[d?
"translateX":"translateY"]=b.pos,this.group.animate(e,this.options.animation),this.animate=null)},remove:function(){var a=this,b=a.chart;b.hasRendered&&n(b.series,function(b){if(b.type===a.type)b.isDirty=!0});S.prototype.remove.apply(a,arguments)}});aa.column=K;X.bar=x(X.column);ma=ea(K,{type:"bar",inverted:!0});aa.bar=ma;X.scatter=x(W,{lineWidth:0,tooltip:{headerFormat:'<span style="font-size: 10px; color:{series.color}">{series.name}</span><br/>',pointFormat:"x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>",
followPointer:!0},stickyTracking:!1});ma=ea(S,{type:"scatter",sorted:!1,requireSorting:!1,noSharedTooltip:!0,trackerGroups:["markerGroup"],drawTracker:K.prototype.drawTracker,setTooltipPoints:ta});aa.scatter=ma;X.pie=x(W,{borderColor:"#FFFFFF",borderWidth:1,center:[null,null],colorByPoint:!0,dataLabels:{distance:30,enabled:!0,formatter:function(){return this.point.name}},ignoreHiddenPoint:!0,legendType:"point",marker:null,size:null,showInLegend:!1,slicedOffset:10,states:{hover:{brightness:0.1,shadow:!1}},
stickyTracking:!1,tooltip:{followPointer:!0}});W={type:"pie",isCartesian:!1,pointClass:ea(Ma,{init:function(){Ma.prototype.init.apply(this,arguments);var a=this,b;if(a.y<0)a.y=null;u(a,{visible:a.visible!==!1,name:o(a.name,"Slice")});b=function(){a.slice()};J(a,"select",b);J(a,"unselect",b);return a},setVisible:function(a){var b=this,c=b.series,d=c.chart,e;b.visible=b.options.visible=a=a===w?!b.visible:a;c.options.data[ka(b,c.data)]=b.options;e=a?"show":"hide";n(["graphic","dataLabel","connector",
"shadowGroup"],function(a){if(b[a])b[a][e]()});b.legendItem&&d.legend.colorizeItem(b,a);if(!c.isDirty&&c.options.ignoreHiddenPoint)c.isDirty=!0,d.redraw()},slice:function(a,b,c){var d=this.series;Ha(c,d.chart);o(b,!0);this.sliced=this.options.sliced=a=s(a)?a:!this.sliced;d.options.data[ka(this,d.data)]=this.options;a=a?this.slicedTranslation:{translateX:0,translateY:0};this.graphic.animate(a);this.shadowGroup&&this.shadowGroup.animate(a)}}),requireSorting:!1,noSharedTooltip:!0,trackerGroups:["group",
"dataLabelsGroup"],pointAttrToOptions:{stroke:"borderColor","stroke-width":"borderWidth",fill:"color"},getColor:ta,animate:function(a){var b=this,c=b.points,d=b.startAngleRad;if(!a)n(c,function(a){var c=a.graphic,a=a.shapeArgs;c&&(c.attr({r:b.center[3]/2,start:d,end:d}),c.animate({r:a.r,start:a.start,end:a.end},b.options.animation))}),b.animate=null},setData:function(a,b){S.prototype.setData.call(this,a,!1);this.processData();this.generatePoints();o(b,!0)&&this.chart.redraw()},getCenter:function(){var a=
this.options,b=this.chart,c=2*(a.dataLabels&&a.dataLabels.enabled?0:a.slicedOffset||0),d=b.plotWidth-2*c,e=b.plotHeight-2*c,b=a.center,a=[o(b[0],"50%"),o(b[1],"50%"),a.size||"100%",a.innerSize||0],f=F(d,e),g;return Ka(a,function(a,b){g=/%$/.test(a);return(g?[d,e,f,f][b]*v(a)/100:a)+(b<3?c:0)})},translate:function(a){this.generatePoints();var b=0,c=0,d=this.options,e=d.slicedOffset,f=e+d.borderWidth,g,h,i,j=this.startAngleRad=Ja/180*((d.startAngle||0)%360-90),k=this.points,m=2*Ja,l=d.dataLabels.distance,
n=d.ignoreHiddenPoint,o,q=k.length,s;if(!a)this.center=a=this.getCenter();this.getX=function(b,c){i=N.asin((b-a[1])/(a[2]/2+l));return a[0]+(c?-1:1)*Y(i)*(a[2]/2+l)};for(o=0;o<q;o++)s=k[o],b+=n&&!s.visible?0:s.y;for(o=0;o<q;o++){s=k[o];d=b?s.y/b:0;g=t((j+c*m)*1E3)/1E3;if(!n||s.visible)c+=d;h=t((j+c*m)*1E3)/1E3;s.shapeType="arc";s.shapeArgs={x:a[0],y:a[1],r:a[2]/2,innerR:a[3]/2,start:g,end:h};i=(h+g)/2;i>0.75*m&&(i-=2*Ja);s.slicedTranslation={translateX:t(Y(i)*e),translateY:t(ca(i)*e)};g=Y(i)*a[2]/
2;h=ca(i)*a[2]/2;s.tooltipPos=[a[0]+g*0.7,a[1]+h*0.7];s.half=i<m/4?0:1;s.angle=i;s.labelPos=[a[0]+g+Y(i)*l,a[1]+h+ca(i)*l,a[0]+g+Y(i)*f,a[1]+h+ca(i)*f,a[0]+g,a[1]+h,l<0?"center":s.half?"right":"left",i];s.percentage=d*100;s.total=b}this.setTooltipPoints()},drawGraph:null,drawPoints:function(){var a=this,b=a.chart.renderer,c,d,e=a.options.shadow,f,g;if(e&&!a.shadowGroup)a.shadowGroup=b.g("shadow").add(a.group);n(a.points,function(h){d=h.graphic;g=h.shapeArgs;f=h.shadowGroup;if(e&&!f)f=h.shadowGroup=
b.g("shadow").add(a.shadowGroup);c=h.sliced?h.slicedTranslation:{translateX:0,translateY:0};f&&f.attr(c);d?d.animate(u(g,c)):h.graphic=d=b.arc(g).setRadialReference(a.center).attr(h.pointAttr[h.selected?"select":""]).attr({"stroke-linejoin":"round"}).attr(c).add(a.group).shadow(e,f);h.visible===!1&&h.setVisible(!1)})},drawDataLabels:function(){var a=this,b=a.data,c,d=a.chart,e=a.options.dataLabels,f=o(e.connectorPadding,10),g=o(e.connectorWidth,1),h=d.plotWidth,d=d.plotHeight,i,j,k=o(e.softConnector,
!0),m=e.distance,l=a.center,p=l[2]/2,r=l[1],s=m>0,u,v,w,x,C=[[],[]],z,A,G,H,D,F=[0,0,0,0],L=function(a,b){return b.y-a.y},M=function(a,b){a.sort(function(a,c){return a.angle!==void 0&&(c.angle-a.angle)*b})};if(e.enabled||a._hasPointLabels){S.prototype.drawDataLabels.apply(a);n(b,function(a){a.dataLabel&&C[a.half].push(a)});for(H=0;!x&&b[H];)x=b[H]&&b[H].dataLabel&&(b[H].dataLabel.getBBox().height||21),H++;for(H=2;H--;){var b=[],N=[],J=C[H],K=J.length,E;M(J,H-0.5);if(m>0){for(D=r-p-m;D<=r+p+m;D+=x)b.push(D);
v=b.length;if(K>v){c=[].concat(J);c.sort(L);for(D=K;D--;)c[D].rank=D;for(D=K;D--;)J[D].rank>=v&&J.splice(D,1);K=J.length}for(D=0;D<K;D++){c=J[D];w=c.labelPos;c=9999;var P,O;for(O=0;O<v;O++)P=R(b[O]-w[1]),P<c&&(c=P,E=O);if(E<D&&b[D]!==null)E=D;else for(v<K-D+E&&b[D]!==null&&(E=v-K+D);b[E]===null;)E++;N.push({i:E,y:b[E]});b[E]=null}N.sort(L)}for(D=0;D<K;D++){c=J[D];w=c.labelPos;u=c.dataLabel;G=c.visible===!1?"hidden":"visible";c=w[1];if(m>0){if(v=N.pop(),E=v.i,A=v.y,c>A&&b[E+1]!==null||c<A&&b[E-1]!==
null)A=c}else A=c;z=e.justify?l[0]+(H?-1:1)*(p+m):a.getX(E===0||E===b.length-1?c:A,H);u._attr={visibility:G,align:w[6]};u._pos={x:z+e.x+({left:f,right:-f}[w[6]]||0),y:A+e.y-10};u.connX=z;u.connY=A;if(this.options.size===null)v=u.width,z-v<f?F[3]=q(t(v-z+f),F[3]):z+v>h-f&&(F[1]=q(t(z+v-h+f),F[1])),A-x/2<0?F[0]=q(t(-A+x/2),F[0]):A+x/2>d&&(F[2]=q(t(A+x/2-d),F[2]))}}if(pa(F)===0||this.verifyDataLabelOverflow(F))this.placeDataLabels(),s&&g&&n(this.points,function(b){i=b.connector;w=b.labelPos;if((u=b.dataLabel)&&
u._pos)z=u.connX,A=u.connY,j=k?["M",z+(w[6]==="left"?5:-5),A,"C",z,A,2*w[2]-w[4],2*w[3]-w[5],w[2],w[3],"L",w[4],w[5]]:["M",z+(w[6]==="left"?5:-5),A,"L",w[2],w[3],"L",w[4],w[5]],i?(i.animate({d:j}),i.attr("visibility",G)):b.connector=i=a.chart.renderer.path(j).attr({"stroke-width":g,stroke:e.connectorColor||b.color||"#606060",visibility:G}).add(a.group);else if(i)b.connector=i.destroy()})}},verifyDataLabelOverflow:function(a){var b=this.center,c=this.options,d=c.center,e=c=c.minSize||80,f;d[0]!==null?
e=q(b[2]-q(a[1],a[3]),c):(e=q(b[2]-a[1]-a[3],c),b[0]+=(a[3]-a[1])/2);d[1]!==null?e=q(F(e,b[2]-q(a[0],a[2])),c):(e=q(F(e,b[2]-a[0]-a[2]),c),b[1]+=(a[0]-a[2])/2);e<b[2]?(b[2]=e,this.translate(b),n(this.points,function(a){if(a.dataLabel)a.dataLabel._pos=null}),this.drawDataLabels()):f=!0;return f},placeDataLabels:function(){n(this.points,function(a){var a=a.dataLabel,b;if(a)(b=a._pos)?(a.attr(a._attr),a[a.moved?"animate":"attr"](b),a.moved=!0):a&&a.attr({y:-999})})},alignDataLabel:ta,drawTracker:K.prototype.drawTracker,
drawLegendSymbol:L.prototype.drawLegendSymbol,getSymbol:ta};W=ea(S,W);aa.pie=W;u(Highcharts,{Axis:ab,Chart:sb,Color:la,Legend:rb,Pointer:qb,Point:Ma,Tick:Ia,Tooltip:pb,Renderer:Sa,Series:S,SVGElement:ra,SVGRenderer:Ba,arrayMin:Fa,arrayMax:pa,charts:Aa,dateFormat:Ua,format:Ea,pathAnim:ub,getOptions:function(){return P},hasBidiBug:Rb,isTouchDevice:Kb,numberFormat:Na,seriesTypes:aa,setOptions:function(a){P=x(P,a);Hb();return P},addEvent:J,removeEvent:ba,createElement:U,discardElement:Ra,css:M,each:n,
extend:u,map:Ka,merge:x,pick:o,splat:ha,extendClass:ea,pInt:v,wrap:function(a,b,c){var d=a[b];a[b]=function(){var a=Array.prototype.slice.call(arguments);a.unshift(d);return c.apply(this,a)}},svg:Z,canvas:$,vml:!Z&&!$})})();
| prihantosimbah/OpenSID-1 | assets/js/highcharts/highcharts.js | JavaScript | gpl-3.0 | 133,583 |
/*
* This file is part of GtkEveMon.
*
* GtkEveMon 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.
*
* You should have received a copy of the GNU General Public License
* along with GtkEveMon. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GUI_EVE_LAUNCHER
#define GUI_EVE_LAUNCHER
#include <string>
#include <vector>
#include "winbase.h"
class GuiEveLauncher : public WinBase
{
private:
void run_command (std::string const& cmd);
protected:
GuiEveLauncher (std::vector<std::string> const& cmds);
public:
static Gtk::Window* launch_eve (void);
};
#endif /* GUI_EVE_LAUNCHER */
| cncfanatics/Gtkevemon | src/guievelauncher.h | C | gpl-3.0 | 805 |
/*----------------------------------------------------------------------
Copyright (c) 1998 Gipsysoft. All Rights Reserved.
Please see the file "licence.txt" for licencing details.
File: htmlparse.cpp
Owner: russf@gipsysoft.com
Purpose: Main HTML parser
The CHTMLParse::Parse() function generates a document, the document
contains all of the elements of the HTML page but broken into
their parts.
The document will then be used to create the display page.
----------------------------------------------------------------------*/
#include "stdafx.h"
#include <WinHelper.h>
#include <ImgLib.h>
#include "QHTM_Includes.h"
#include "AquireImage.h"
#include "DrawContext.h"
#include "defaults.h"
#include "smallstringhash.h"
#include "HTMLParse.h"
extern LPTSTR stristr( LPTSTR pszSource, LPCTSTR pcszSearch );
extern BYTE DecodeCharset( const CStaticString &strCharSet );
static CHTMLParse::Align knDefaultImageAlignment = CHTMLParse::algBottom;
static CHTMLParse::Align knDefaultHRAlignment = CHTMLParse::algLeft;
static CHTMLParse::Align knDefaultParagraphAlignment = CHTMLParse::algLeft;
// richg - 19990224 - Default table alignment changed form algLeft to algTop
static CHTMLParse::Align knDefaultTableAlignment = CHTMLParse::algMiddle;
// richg - 19990224 - Table Cells have their own default
static CHTMLParse::Align knDefaultTableCellAlignment = CHTMLParse::algLeft;
TCHAR g_cCarriageReturn = _T('\r');
static const CStaticString g_strTabSpaces( _T(" ") );
static MapClass< StringClass, bool> g_mapFontName;
CHTMLParse::CHTMLParse( LPCTSTR pcszStream, UINT uLength, HINSTANCE hInstLoadedFrom, LPCTSTR pcszFilePath, CDefaults *pDefaults )
: CHTMLParseBase( pcszStream, uLength )
, m_pProp( NULL )
, m_pDocument( NULL )
, m_hInstLoadedFrom( hInstLoadedFrom )
, m_pcszFilePath( pcszFilePath )
, m_pLastAnchor( NULL )
, m_pDefaults( pDefaults )
{
ASSERT( m_pDefaults );
}
CHTMLParse::~CHTMLParse()
{
CleanupParse();
}
CHTMLDocument * CHTMLParse::Parse()
//
// returns either a fully created document ready to create the display from or
// NULL in the event of failure.
{
CleanupParse();
//
// Create the first properties
m_pProp = new Properties;
m_pProp->m_crFore = m_pDefaults->m_crDefaultForeColour;
_tcscpy( m_pProp->szFaceName, m_pDefaults->m_strFontName );
m_pProp->nSize = m_pDefaults->m_nFontSize;
m_stkProperties.Push( m_pProp );
//
// Create the main document and a paragraph to add to it.
m_pMasterDocument = m_pDocument = new CHTMLDocument( m_pDefaults );
m_pDocument->m_crBack = m_pDefaults->m_crBackground;
CreateNewParagraph( m_pDefaults->m_nParagraphLinesAbove, m_pDefaults->m_nParagraphLinesBelow, knDefaultParagraphAlignment );
if( !ParseBase() )
{
if( m_pMasterDocument )
{
delete m_pMasterDocument;
m_pDocument = NULL;
m_pMasterDocument = NULL;
}
}
return m_pMasterDocument;
}
void CHTMLParse::CleanupParse()
//
// Cleanup anything left over from our previous parsing
{
while( m_stkProperties.GetSize() )
delete m_stkProperties.Pop();
while( m_stkDocument.GetSize() )
m_stkDocument.Pop();
// richg - 19990227 - Clean up the table stack as well
while( m_stkTable.GetSize() )
m_stkTable.Pop();
while( m_stkInTableCell.GetSize() )
m_stkInTableCell.Pop();
// richg - 19990621 - Clean up list stack
while( m_stkList.GetSize() )
m_stkList.Pop();
m_pLastAnchor = NULL;
}
void CHTMLParse::OnGotText( TCHAR ch )
//
// Callback when some text has been interrupted with a tag or end tag.
{
if( ch == _T('\t') )
{
m_strToken.Add( g_strTabSpaces, g_strTabSpaces.GetLength() );
}
else
{
m_strToken.Add( ch );
}
}
void CHTMLParse::OnEndDoc()
{
CreateNewTextObject();
}
void CHTMLParse::OnGotTag( const Token token, const CParameters &pList )
{
switch( token )
{
case tokIgnore:
break;
case tokSub:
CreateNewTextObject();
CreateNewProperties();
if( m_pProp->nSize > 1 )
m_pProp->nSize--;
m_pProp->m_nSub++;
break;
case tokSup:
CreateNewTextObject();
CreateNewProperties();
if( m_pProp->nSize > 1 )
m_pProp->nSize--;
m_pProp->m_nSup++;
break;
case tokPre:
CreateNewProperties();
_tcscpy( m_pProp->szFaceName, m_pDefaults->m_strDefaultPreFontName );
break;
case tokBody:
OnGotBody( pList );
break;
case tokFont:
OnGotFont( pList );
break;
case tokBold:
CreateNewTextObject();
CreateNewProperties();
m_pProp->bBold = true;
break;
case tokUnderline:
CreateNewTextObject();
CreateNewProperties();
m_pProp->bUnderline = true;
break;
case tokItalic:
CreateNewTextObject();
CreateNewProperties();
m_pProp->bItalic = true;
break;
case tokStrikeout:
CreateNewTextObject();
CreateNewProperties();
m_pProp->bStrikeThrough = true;
break;
case tokImage:
OnGotImage( pList );
break;
case tokTableHeading:
case tokTableDef:
OnGotTableCell( pList );
break;
case tokTableRow:
OnGotTableRow( pList );
break;
case tokTable:
CreateNewProperties();
OnGotTable( pList );
break;
case tokHorizontalRule:
OnGotHR( pList );
break;
case tokCenter:
CreateNewProperties();
m_pProp->nAlignment = algCentre;
OnGotParagraph( pList );
break;
case tokDiv:
OnGotParagraph( pList );
break;
case tokParagraph:
OnGotParagraph( pList );
break;
case tokBreak:
m_strToken.Add( g_cCarriageReturn );
break;
case tokAnchor:
OnGotAnchor( pList );
break;
case tokH1:
case tokH2:
case tokH3:
case tokH4:
case tokH5:
case tokH6:
OnGotHeading( token, pList );
break;
case tokOrderedList:
OnGotOrderedList( pList );
break;
case tokUnorderedList:
OnGotUnorderedList( pList );
break;
case tokListItem:
OnGotListItem( pList );
break;
case tokAddress:
OnGotAddress( pList );
break;
case tokBlockQuote:
OnGotBlockQuote( pList );
break;
case tokCode:
CreateNewTextObject();
CreateNewProperties();
_tcscpy( m_pProp->szFaceName, m_pDefaults->m_strDefaultPreFontName );
break;
case tokMeta:
OnGotMeta( pList );
break;
}
}
void CHTMLParse::OnGotEndTag( const Token token )
{
switch( token )
{
case tokCode:
CreateNewTextObject();
PopPreviousProperties();
break;
case tokPre:
CreateNewTextObject();
PopPreviousProperties();
CreateNewParagraph( 0, 0, m_pProp->nAlignment );
break;
case tokCenter:
CreateNewTextObject();
PopPreviousProperties();
CreateNewParagraph( 0, 0, m_pProp->nAlignment );
break;
case tokParagraph:
CreateNewTextObject();
CreateNewParagraph( 0, 0, m_pProp->nAlignment );
break;
case tokImage: // Ignore end images
// There is no end image tag!
ASSERT( FALSE );
break;
case tokDiv:
case tokIgnore:
CreateNewTextObject();
CreateNewParagraph( 0, 0, m_pProp->nAlignment );
break;
case tokFont:
case tokBold:
case tokUnderline:
case tokItalic:
case tokStrikeout:
case tokSub:
case tokSup:
CreateNewTextObject();
PopPreviousProperties();
break;
case tokH1:
case tokH2:
case tokH3:
case tokH4:
case tokH5:
case tokH6:
CreateNewTextObject();
PopPreviousProperties();
CreateNewParagraph( 0, 0, m_pProp->nAlignment );
break;
case tokAnchor:
OnGotEndAnchor();
break;
case tokTableHeading:
case tokTableDef:
OnGotEndTableCell();
break;
case tokTableRow:
OnGotEndTableRow();
break;
//
// IE seems to ne okay about using an end BR (</br>) so we should too.
case tokBreak:
m_strToken.Add( g_cCarriageReturn );
break;
case tokTable:
if( m_stkTable.GetSize() )
{
m_stkTable.Pop();
}
else
{
TRACE( _T("Got an table but no tables left in the stack\n") );
}
// Pop the InACell flag
if (m_stkInTableCell.GetSize())
{
// If the cell is still open... close it!
OnGotEndTableRow(); // Does the same thing.
m_stkInTableCell.Pop();
}
else
{
TRACE( _T("Got an end table but in-cell stack empty.") );
}
PopPreviousProperties();
CreateNewParagraph( 0, 0, m_pProp->nAlignment );
break;
case tokHorizontalRule:
break;
case tokOrderedList:
case tokUnorderedList:
OnGotEndList();
break;
case tokListItem:
OnGotEndListItem();
break;
case tokAddress:
OnGotEndAddress();
break;
case tokBlockQuote:
OnGotEndBlockQuote();
break;
case tokDocumentTitle:
m_strToken.Add( 0 );
m_pMasterDocument->m_strTitle = m_strToken.GetData();
m_strToken.SetSize( 0 );
break;
}
}
void CHTMLParse::OnGotBody( const CParameters &pList )
{
const UINT uParamSize = pList.GetSize();
for( UINT n = 0; n < uParamSize; n++ )
{
const CStaticString &strParam = pList[n].m_strValue;
switch( pList[n].m_param )
{
case pBColor:
m_pDocument->m_crBack = GetColourFromString( strParam, m_pDocument->m_crBack );
break;
case pLink:
m_pDocument->m_crLink = GetColourFromString( strParam, RGB( 141, 7, 102 ) );
break;
case pALink:
m_pDocument->m_crLinkHover = GetColourFromString( strParam, RGB( 29, 49, 149 ) );
break;
case pMarginTop:
m_pDocument->m_nTopMargin = GetNumberParameter( strParam, m_pDocument->m_nTopMargin );
break;
case pMarginBottom:
m_pDocument->m_nBottomMargin = GetNumberParameter( strParam, m_pDocument->m_nBottomMargin );
break;
case pMarginLeft:
m_pDocument->m_nLeftMargin = GetNumberParameter( strParam, m_pDocument->m_nLeftMargin );
break;
case pMarginRight:
m_pDocument->m_nRightMargin = GetNumberParameter( strParam, m_pDocument->m_nRightMargin );
break;
}
}
}
void CHTMLParse::OnGotImage( const CParameters &pList )
{
CreateNewTextObject();
int nHeight = 0;
int nWidth = 0;
int nBorder = 0;
CStaticString strFilename;
Align alg = knDefaultImageAlignment;
const UINT uParamSize = pList.GetSize();
for( UINT n = 0; n < uParamSize; n++ )
{
const CStaticString &strParam = pList[n].m_strValue;
switch( pList[n].m_param )
{
case pWidth:
nWidth = GetNumberParameter( strParam, nWidth );
break;
case pHeight:
nHeight = GetNumberParameter( strParam, nHeight );
break;
case pAlign:
alg = GetAlignmentFromString( strParam, alg );
break;
case pSrc:
strFilename = strParam;
break;
case pBorder:
nBorder = GetNumberParameter( strParam, nBorder );
break;
}
}
CHTMLParagraph *pPara = m_pDocument->CurrentParagraph();
// Before loading the image, see if it already exists in the cache.
StringClass fname( strFilename.GetData(), strFilename.GetLength() );
CImage** ppLoadedImage = m_pMasterDocument->m_mapImages.Lookup(fname);
CImage* pImage;
if (!ppLoadedImage)
{
TRACENL( _T("Image %s not in cache. Attempting Load\n"), (LPCTSTR)fname);
pImage = OnLoadImage( fname );
if( !pImage )
{
TRACENL( _T("Image %s could not be loaded.\n"), (LPCTSTR)fname);
// Consider making this image a global instance.
pImage = new CImage;
VERIFY( pImage->Load( g_hResourceInstance, g_uNoImageBitmapID ) );
}
m_pMasterDocument->m_mapImages.SetAt(fname, pImage);
}
else
{
TRACENL( _T("Image %s loaded from cache.\n"), (LPCTSTR)fname);
pImage = *ppLoadedImage;
}
CHTMLImage *pHTMLImage = new CHTMLImage( nWidth, nHeight, nBorder, fname, alg, pImage );
UpdateItemLinkStatus( pHTMLImage );
pPara->AddItem( pHTMLImage );
}
CImage *CHTMLParse::OnLoadImage( LPCTSTR pcszFilename )
//
// Called when we need an image to be loaded.
{
return AquireImage( m_hInstLoadedFrom, m_pcszFilePath, pcszFilename );
}
void CHTMLParse::UpdateItemLinkStatus( CHTMLParagraphObject *pItem )
{
// Assign the current link pointer to the object
pItem->m_pAnchor = m_pLastAnchor;
}
void CHTMLParse::CreateNewTextObject()
//
// Create a new text block and add it to the current docuemnt-paragraph
{
if( m_strToken.GetSize() )
{
CHTMLParagraph *pPara = m_pDocument->CurrentParagraph();
HTMLFontDef def( m_pProp->szFaceName, m_pProp->nSize, m_pProp->bBold, m_pProp->bItalic, m_pProp->bUnderline, m_pProp->bStrikeThrough, m_pProp->m_nSup, m_pProp->m_nSub );
CStaticString str( m_strToken.GetData(), m_strToken.GetSize() );
CHTMLTextBlock *pText = new CHTMLTextBlock( str, m_pDocument->GetFontDefIndex( def ), m_pProp->m_crFore, IsPreformatted() );
if( m_pLastAnchor )
UpdateItemLinkStatus( pText );
pPara->AddItem( pText );
m_strToken.SetSize( 0 );
}
}
void CHTMLParse::CreateNewProperties()
//
// Create a new properties set and add it to the stack.
{
m_pProp = new Properties( *m_pProp );
m_stkProperties.Push( m_pProp );
}
void CHTMLParse::PopPreviousProperties()
{
if( m_stkProperties.GetSize() > 1 )
{
delete m_stkProperties.Pop();
m_pProp = m_stkProperties.Top();
}
}
void CHTMLParse::CreateNewParagraph( int nLinesAbove, int nLinesBelow, Align alg )
{
if( m_pDocument->CurrentParagraph() && m_pDocument->CurrentParagraph()->IsEmpty() )
{
m_pDocument->CurrentParagraph()->Reset( nLinesAbove, nLinesBelow, alg );
}
else
{
m_pDocument->AddParagraph( new CHTMLParagraph( nLinesAbove, nLinesBelow, alg ) );
}
}
void CHTMLParse::OnGotHR( const CParameters &pList )
{
CreateNewTextObject();
if( !m_pDocument->CurrentParagraph() || !m_pDocument->CurrentParagraph()->IsEmpty() )
{
CreateNewParagraph( m_pDefaults->m_nParagraphLinesAbove, m_pDefaults->m_nParagraphLinesBelow, m_pProp->nAlignment );
}
CHTMLParse::Align alg = knDefaultHRAlignment;
int nSize = 2;
int nWidth = -100;
bool bNoShade = false;
COLORREF crColor = 0;
const UINT uParamSize = pList.GetSize();
for( UINT n = 0; n < uParamSize; n++ )
{
const CStaticString &strParam = pList[n].m_strValue;
switch( pList[n].m_param )
{
case pWidth:
nWidth = GetNumberParameterPercent( strParam, nWidth );
if( nWidth == 0 )
nWidth = -100;
break;
case pSize:
// REVIEW - russf - could allow dan to use point/font sizes here too.
nSize = GetNumberParameter(strParam, nSize);
if( nSize <= 0 )
nSize = 3;
break;
case pNoShade:
bNoShade = true;
break;
case pAlign:
alg = GetAlignmentFromString( strParam, alg );
break;
case pColor:
crColor = GetColourFromString( strParam, crColor );
break;
}
}
CHTMLParagraph *pPara = m_pDocument->CurrentParagraph();
CHTMLHorizontalRule *pHR = new CHTMLHorizontalRule( alg, nSize, nWidth, bNoShade, crColor );
UpdateItemLinkStatus( pHR );
pPara->AddItem( pHR );
CreateNewParagraph( m_pDefaults->m_nParagraphLinesAbove, m_pDefaults->m_nParagraphLinesBelow, m_pProp->nAlignment );
}
void CHTMLParse::OnGotParagraph( const CParameters &pList )
{
CreateNewTextObject();
CHTMLParse::Align alg = m_pProp->nAlignment;
const UINT uParamSize = pList.GetSize();
for( UINT n = 0; n < uParamSize; n++ )
{
const CStaticString &strParam = pList[n].m_strValue;
switch( pList[n].m_param )
{
case pAlign:
alg = GetAlignmentFromString( strParam, alg );
break;
}
}
m_pProp->nAlignment;
CreateNewParagraph( m_pDefaults->m_nParagraphLinesAbove, m_pDefaults->m_nParagraphLinesBelow, alg );
}
void CHTMLParse::OnGotFont( const CParameters &pList )
{
CreateNewTextObject();
CreateNewProperties();
const UINT uParamSize = pList.GetSize();
for( UINT n = 0; n < uParamSize; n++ )
{
const CStaticString &strParam = pList[n].m_strValue;
switch( pList[n].m_param )
{
case pColor:
m_pProp->m_crFore = GetColourFromString( strParam, m_pProp->m_crFore );
break;
case pFace:
GetFontName( m_pProp->szFaceName, countof( m_pProp->szFaceName ), strParam );
break;
case pSize:
{
//
// REVIEW - russf - Could add the ability to have +n and -n font and point sizes here.
m_pProp->nSize = GetFontSize( strParam, m_pProp->nSize );
}
break;
}
}
}
void CHTMLParse::OnGotHeading( const Token token, const CParameters &pList )
{
int nLinesAbove = 1, nLinesBelow = 1;
Align alg = m_pProp->nAlignment;
CreateNewTextObject();
CreateNewProperties();
switch( token )
{
case tokH1:
m_pProp->nSize = 6;
m_pProp->bBold = true;
break;
case tokH2:
m_pProp->nSize = 5;
m_pProp->bBold = true;
break;
case tokH3:
m_pProp->nSize = 4;
m_pProp->bBold = true;
break;
case tokH4:
m_pProp->nSize = 3;
m_pProp->bBold = true;
break;
case tokH5:
m_pProp->nSize = 3;
m_pProp->bBold = true;
break;
case tokH6:
nLinesAbove = 2;
m_pProp->nSize = 1;
m_pProp->bBold = true;
break;
}
const UINT uParamSize = pList.GetSize();
for( UINT n = 0; n < uParamSize; n++ )
{
const CStaticString &strParam = pList[n].m_strValue;
switch( pList[n].m_param )
{
case pAlign:
alg = GetAlignmentFromString( strParam, alg );
break;
}
}
CreateNewParagraph( nLinesAbove, nLinesBelow, alg );
}
void CHTMLParse::OnGotAnchor( const CParameters &pList )
{
// We will no longer store link attributes in the properties.
// They will instead be stored in an inline ParagraphObject
// The sectionCreator will be responsible for keeping the list
// of links and map of named sections
// Since the coloring will change, we will still create a new
// text object. This also ensures that we have a paragraph into which
// we store the HTMLAnchor object.
CreateNewTextObject();
// Anchor information is no longer stored in the properties stack,
// So we don't need new properties.
// CreateNewProperties();
// Create a new Anchor object, then store some data in it.
// This one has a default ctor, which provides empty members.
// We need to specify colors, though.
CHTMLAnchor* pAnchor = new CHTMLAnchor();
const UINT uParamSize = pList.GetSize();
for( UINT n = 0; n < uParamSize; n++ )
{
const CStaticString &strParam = pList[n].m_strValue;
switch( pList[n].m_param )
{
case pName:
pAnchor->m_strLinkName.Set( strParam.GetData(), strParam.GetLength() );
break;
case pHref:
pAnchor->m_strLinkTarget.Set( strParam.GetData(), strParam.GetLength() );
break;
case pTitle:
pAnchor->m_strLinkTitle.Set( strParam.GetData(), strParam.GetLength() );
break;
}
}
// Get the colors from the master document, which is the only place they should be set
pAnchor->m_crLink = m_pMasterDocument->m_crLink;
pAnchor->m_crHover = m_pMasterDocument->m_crLinkHover;
// Signifies to the parser that we are in a anchor tag, and this is it!
// This remains complicated by named tags. i.e. what should happen
// in this case:
// <a href="someTarget">Some text<a name="here">More Text</a> Other Text</a>
// is the Other Text in a link?
// In IE4, the second tag cancels out the first. We will use that behavior.
if (pAnchor->m_strLinkTarget.GetLength())
m_pLastAnchor = pAnchor;
else
m_pLastAnchor = NULL;
CHTMLParagraph *pPara = m_pDocument->CurrentParagraph();
pPara->AddItem( pAnchor );
}
void CHTMLParse::OnGotEndAnchor()
{
// Signify to the parser that we are no longer in an anchor tag.
// If we are truly anding a link, make a new text object.
// Otherwise, it's ignored.
if (m_pLastAnchor)
CreateNewTextObject();
m_pLastAnchor = NULL;
}
void CHTMLParse::OnGotTable( const CParameters &pList )
{
CreateNewTextObject();
int nWidth = 0; // Default width - unspec, -100; // For 100 percent
int nBorder = 0;
int nCellPadding = m_pDefaults->m_nCellPadding;
int nCellSpacing = m_pDefaults->m_nCellSpacing;
bool bTransparent = true;
COLORREF crBorder = RGB(0, 0, 0);
COLORREF crBgColor = RGB( 255, 255, 255 ); // Not really used.
COLORREF crBorderLight = m_pDefaults->m_crBorderLight;
COLORREF crBorderDark = m_pDefaults->m_crBorderDark;
bool bBorderDarkSet = false;
bool bBorderLightSet = false;
CHTMLParse::Align alg = knDefaultTableAlignment;
CHTMLParse::Align valg = knDefaultTableAlignment;
const UINT uParamSize = pList.GetSize();
for( UINT n = 0; n < uParamSize; n++ )
{
const CStaticString &strParam = pList[n].m_strValue;
switch( pList[n].m_param )
{
case pWidth:
nWidth = GetNumberParameterPercent( strParam, nWidth );
break;
case pAlign:
alg = GetAlignmentFromString( strParam, alg );
break;
case pVAlign:
valg = GetAlignmentFromString( strParam, valg );
break;
case pBorder:
nBorder = GetNumberParameter( strParam, nBorder );
break;
case pBColor:
crBgColor = GetColourFromString( strParam, crBgColor );
bTransparent = false;
break;
case pCellSpacing:
nCellSpacing = GetNumberParameter( strParam, nCellSpacing );
break;
case pCellPadding:
nCellPadding = GetNumberParameter( strParam, nCellPadding );
break;
case pBorderColor:
crBorder = GetColourFromString( strParam, crBorder );
if ( !bBorderDarkSet )
crBorderDark = crBorder;
if ( !bBorderLightSet )
crBorderLight = crBorder;
break;
case pBorderColorLight:
crBorderLight = GetColourFromString( strParam, crBorderLight );
bBorderLightSet = true;
break;
case pBorderColorDark:
crBorderDark = GetColourFromString( strParam, crBorderDark );
bBorderDarkSet = true;
break;
}
}
switch( alg )
{
case algLeft: case algRight:
break;
default:
CreateNewParagraph( 0, 0, m_pProp->nAlignment );
}
CHTMLTable *ptab = new CHTMLTable( nWidth, nBorder, alg, valg, nCellSpacing, nCellPadding, bTransparent, crBgColor, crBorderDark, crBorderLight);
m_stkTable.Push( ptab );
m_pDocument->CurrentParagraph()->AddItem( m_stkTable.Top() );
// Push onto the inTableCell stack
m_stkInTableCell.Push(false); // Not in a cell yet!
}
void CHTMLParse::OnGotTableRow( const CParameters &pList )
{
// Close an open cell first.
if (m_stkInTableCell.GetSize() && m_stkInTableCell.Top())
OnGotEndTableCell();
CHTMLParse::Align valg = knDefaultTableAlignment;
if( m_stkTable.GetSize() )
{
valg = m_stkTable.Top()->m_valg;
}
const UINT uParamSize = pList.GetSize();
for( UINT n = 0; n < uParamSize; n++ )
{
const CStaticString &strParam = pList[n].m_strValue;
switch( pList[n].m_param )
{
case pVAlign:
valg = GetAlignmentFromString( strParam, valg );
break;
}
}
if( m_stkTable.GetSize() )
{
m_stkTable.Top()->NewRow( valg );
}
}
void CHTMLParse::OnGotTableCell( const CParameters &pList )
{
// Ensure that we are processing documents properly.
// close the previous cell if it was left open...
if (m_stkInTableCell.GetSize())
{
if (m_stkInTableCell.Top())
OnGotEndTableCell();
m_stkInTableCell.Top() = true;
}
int nWidth = 0;
int nHeight = 0;
bool bNoWrap = false;
bool bTransparent = true;
COLORREF crBorder = RGB(0,0,0);
COLORREF crBgColor = RGB( 255, 255, 255 ); // Not really used.
COLORREF crBorderLight = m_pDefaults->m_crBorderLight;
COLORREF crBorderDark = m_pDefaults->m_crBorderDark;
bool bBorderDarkSet = false;
bool bBorderLightSet = false;
CHTMLParse::Align alg = knDefaultTableCellAlignment;
CHTMLParse::Align valg = m_stkTable.Top()->GetCurrentRow()->m_valg;
// Get defaults from the current table
// Could really ignore everything if we are not in a table!
if( m_stkTable.GetSize() )
{
CHTMLTable* pTab = m_stkTable.Top();
crBorderLight = pTab->m_crBorderLight;
crBorderDark = pTab->m_crBorderDark;
}
const UINT uParamSize = pList.GetSize();
for( UINT n = 0; n < uParamSize; n++ )
{
const CStaticString &strParam = pList[n].m_strValue;
switch( pList[n].m_param )
{
case pWidth:
nWidth = GetNumberParameterPercent( strParam, nWidth );
break;
case pHeight:
nHeight = GetNumberParameter( strParam, nHeight );
break;
case pAlign:
alg = GetAlignmentFromString( strParam, alg );
break;
case pVAlign:
valg = GetAlignmentFromString( strParam, alg );
break;
// richg - 19990224 - Add support for NOWRAP
case pNoWrap:
bNoWrap = true;
break;
case pBColor:
crBgColor = GetColourFromString( strParam, crBgColor );
bTransparent = false;
break;
case pBorderColor:
crBorder = GetColourFromString( strParam, crBorder );
if ( !bBorderDarkSet )
crBorderDark = crBorder;
if ( !bBorderLightSet )
crBorderLight = crBorder;
break;
case pBorderColorLight:
crBorderLight = GetColourFromString( strParam, crBorderLight );
bBorderLightSet = true;
break;
case pBorderColorDark:
crBorderDark = GetColourFromString( strParam, crBorderDark );
bBorderDarkSet = true;
break;
}
}
//
// If there is a table to add our cell to...
if( m_stkTable.GetSize() )
{
CHTMLTableCell *pCell = new CHTMLTableCell( m_pDefaults, nWidth, nHeight, bNoWrap, bTransparent, crBgColor, crBorderDark, crBorderLight, valg );
// Copy the current documents link colors into the new document
pCell->m_crLink = m_pDocument->m_crLink;
pCell->m_crLinkHover = m_pDocument->m_crLinkHover;
// Push it onto the document stack
m_stkDocument.Push( m_pDocument );
// TRACENL("Document Stack Pushed. %d\n", m_stkDocument.GetSize());
m_pDocument = pCell;
m_pProp->nAlignment = alg;
CreateNewParagraph( 0, 0, m_pProp->nAlignment );
m_stkTable.Top()->AddCell( pCell );
}
}
void CHTMLParse::OnGotEndTableCell()
{
CreateNewTextObject();
if( m_stkDocument.GetSize() )
{
m_pDocument = m_stkDocument.Pop();
// TRACENL("Document Stack Popped. %d\n", m_stkDocument.GetSize());
}
else
{
TRACE( _T("Got an end table cell but no document stack left\n") );
}
if (m_stkInTableCell.GetSize())
m_stkInTableCell.Top() = false;
}
void CHTMLParse::OnGotEndTableRow()
{
if( m_stkInTableCell.GetSize() && m_stkInTableCell.Top() )
OnGotEndTableCell();
}
void CHTMLParse::CreateList( bool bOrdered )
{
CreateNewTextObject();
CreateNewParagraph( 0, 0, CHTMLParse::algLeft );
CHTMLList *pList = new CHTMLList( bOrdered );
m_stkList.Push( pList );
m_pDocument->CurrentParagraph()->AddItem( m_stkList.Top() );
// Create the default first item
CHTMLListItem *pItem = new CHTMLListItem( m_pDefaults, false, m_pProp->szFaceName, m_pProp->nSize, m_pProp->bBold, m_pProp->bItalic, m_pProp->bUnderline, m_pProp->bStrikeThrough, m_pProp->m_crFore ); // Not bulleted
// Copy the current documents link colors into the new document
pItem->m_crLink = m_pDocument->m_crLink;
pItem->m_crLinkHover = m_pDocument->m_crLinkHover;
m_stkDocument.Push( m_pDocument );
m_pDocument = pItem;
CreateNewParagraph( 0, 0, CHTMLParse::algLeft );
m_stkList.Top()->AddItem( pItem );
}
void CHTMLParse::OnGotUnorderedList( const CParameters & /* pList */ )
{
CreateList( false );
}
void CHTMLParse::OnGotOrderedList( const CParameters & /* pList */ )
{
CreateList( true );
}
void CHTMLParse::OnGotListItem( const CParameters & /* pList */ )
{
// </li> is completely ignored by IE4, and by NetScape
// Additionally, items occuring after the <ol> or <ul> and
// before the first <li> are positioned as if they were preceeded
// by <li>, but the bullet is not shown. Empty <LI> tags DO show their
// bullets.
// In order to handle these cases, do the following:
// For a new list, create the initial list item, but flag it as
// unbulleted. When a <LI> is reached, determine if there is
// exactly one item in the list. If so, and it is empty, Mark the
// existing item as bulleted, and use it... otherwise, proceed by adding
// another list item.
// See that we are in a list, otherwise, ignore it...
if ( m_stkList.GetSize() )
{
CreateNewTextObject();
// See if we can use the existing item
if ( m_stkList.Top()->m_arrItems.GetSize() == 1 &&
!m_stkList.Top()->m_arrItems[0]->m_bBullet &&
m_stkList.Top()->m_arrItems[0]->IsEmpty() )
{
// There is en emptry entry that is not bulleted
m_stkList.Top()->m_arrItems[0]->m_bBullet = true;
// Nothing more to do!
return;
}
// We are in a list and creating a new item, close the previous item
CreateNewTextObject();
if( m_stkDocument.GetSize() )
{
m_pDocument = m_stkDocument.Pop();
}
// Need to create a new item...
CHTMLListItem *pItem = new CHTMLListItem( m_pDefaults, true, m_pProp->szFaceName, m_pProp->nSize, m_pProp->bBold, m_pProp->bItalic, m_pProp->bUnderline, m_pProp->bStrikeThrough, m_pProp->m_crFore ); // bulleted
// Copy the current documents link colors into the new document
pItem->m_crLink = m_pDocument->m_crLink;
pItem->m_crLinkHover = m_pDocument->m_crLinkHover;
m_stkDocument.Push( m_pDocument );
m_pDocument = pItem;
CreateNewParagraph( 0, 0, CHTMLParse::algLeft );
m_stkList.Top()->AddItem( pItem );
}
}
void CHTMLParse::OnGotEndListItem()
{
// Do nothing.
}
void CHTMLParse::OnGotEndList()
{
// See that we are in a list, otherwise, ignore it...
if ( m_stkList.GetSize() )
{
// Close the last item...
CreateNewTextObject();
if( m_stkDocument.GetSize() )
{
m_pDocument = m_stkDocument.Pop();
}
CreateNewParagraph( 0, 0, CHTMLParse::algLeft );
// Close this list.
m_stkList.Pop();
}
}
void CHTMLParse::OnGotBlockQuote( const CParameters & /* pList */ )
{
/*
A Blockquote is treated as a sub document with different
margins. This is fairly straightforward.
*/
CreateNewTextObject();
CreateNewParagraph( 0, 0, m_pProp->nAlignment );
CHTMLBlockQuote *pBQ = new CHTMLBlockQuote( m_pDefaults );
m_pDocument->CurrentParagraph()->AddItem( pBQ );
// Make the sub document the main document
m_stkDocument.Push( m_pDocument );
m_pDocument = pBQ->m_pDoc;
CreateNewParagraph( 0, 0, m_pProp->nAlignment);
}
void CHTMLParse::OnGotEndBlockQuote()
{
/*
Cause a document stack pop if possible...
*/
CreateNewTextObject();
if( m_stkDocument.GetSize() )
{
m_pDocument = m_stkDocument.Pop();
}
else
{
TRACE( _T("At </BLOCKQUOTE> but document stack is empty.\n") );
}
CreateNewParagraph(0, 0, m_pProp->nAlignment);
}
void CHTMLParse::OnGotAddress( const CParameters & /* pList */ )
//
// Fundtionally the same as BLOCKQUOTE but with italics
{
CreateNewTextObject();
CreateNewParagraph( 0, 0, m_pProp->nAlignment );
CreateNewProperties();
m_pProp->bItalic = true;
CHTMLBlockQuote *pBQ = new CHTMLBlockQuote( m_pDefaults );
m_pDocument->CurrentParagraph()->AddItem( pBQ );
// Make the sub document the main document
m_stkDocument.Push( m_pDocument );
m_pDocument = pBQ->m_pDoc;
CreateNewParagraph( 0, 0, m_pProp->nAlignment);
}
void CHTMLParse::OnGotEndAddress()
{
CreateNewTextObject();
if( m_stkDocument.GetSize() )
{
m_pDocument = m_stkDocument.Pop();
}
else
{
TRACE( _T("At </BLOCKQUOTE> but document stack is empty.\n") );
}
PopPreviousProperties();
CreateNewParagraph(0, 0, m_pProp->nAlignment);
}
void CHTMLParse::GetFontName( LPTSTR pszBuffer, int nBufferSize, const CStaticString &strFontNameSpec )
//
// Get the font name from a font name spec.
// This consists of comma delimited font names "tahoma,arial,helvetica"
// We need to find
{
static const TCHAR cComma = _T(',');
if( strFontNameSpec.GetData() )
{
LPCTSTR pcszFontNameSpec = strFontNameSpec.GetData();
// Set our string to empty
*pszBuffer = _T('\000');
if( strFontNameSpec.Find( cComma ) )
{
//
// Iterate over the passed font names, copying each font name as we go.
LPCTSTR pcszFontNameSpecEnd = strFontNameSpec.GetEndPointer();
LPCTSTR pszFontNameStart, pszFontNameEnd;
pszFontNameStart = pszFontNameEnd = pcszFontNameSpec;
while( pszFontNameStart < pcszFontNameSpecEnd )
{
//
// Find the end of the first font.
while( pszFontNameEnd < pcszFontNameSpecEnd && *pszFontNameEnd != cComma )
pszFontNameEnd++;
if( pszFontNameEnd - pszFontNameStart && pszFontNameEnd - pszFontNameStart < nBufferSize)
{
StringClass strFontName( pszFontNameStart, pszFontNameEnd - pszFontNameStart );
//
// We have our font name, now determine whether the font exists or not.
if( DoesFontExist( strFontName ) )
{
// It does, then we get out of here. If the font doesn't exist then we simply
// continue looping around.
_tcscpy( pszBuffer, strFontName );
return;
}
}
//
// Skip past the white space and commas
while( pszFontNameEnd < pcszFontNameSpecEnd && ( isspace( *pszFontNameEnd ) || *pszFontNameEnd == cComma ) )
pszFontNameEnd++;
pszFontNameStart = pszFontNameEnd;
}
}
else
{
StringClass strFontName( strFontNameSpec.GetData(), strFontNameSpec.GetLength() );
if( DoesFontExist( strFontName ) )
{
// It does, then we get out of here. If the font doesn't exist then we simply
// continue looping around.
_tcscpy( pszBuffer, strFontName );
}
else
{
_tcscpy( pszBuffer, m_pDefaults->m_strFontName );
}
}
}
else
{
_tcscpy( pszBuffer, m_pDefaults->m_strFontName );
}
//
// If we drop out here it means that none of the user requested fonts exist on the system.
}
static int CALLBACK EnumFontFamExProc( ENUMLOGFONTEX * /*lpelfe*/, NEWTEXTMETRICEX * /*lpntme*/, int /*FontType*/, LPARAM /*lParam*/ )
{
return -1;
}
bool CHTMLParse::DoesFontExist( const StringClass &strFontName )
//
// Determine if the font exists in our map and return that result.
// If it doesn't exist in our map then ask the system if the font exists and add
// that known state to our map.
{
bool *pb = g_mapFontName.Lookup( strFontName );
if( pb )
{
return *pb;
}
LOGFONT lf = { 0 };
_tcscpy( lf.lfFaceName, strFontName );
lf.lfCharSet = m_pMasterDocument->m_cCharSet;
CDrawContext dc;
bool bExists = false;
//
// NOTE: If the font doesn't exist EnumFontFamiliesEx returns 1 - originally I had my callbcak return
// true or false. This didn't work if the font didn't exist. Now the callback returns -1 if the font
// exists.
if( EnumFontFamiliesEx( dc.GetSafeHdc(), &lf, (FONTENUMPROC)EnumFontFamExProc, 0, 0 ) == -1 )
bExists = true;
g_mapFontName.SetAt( strFontName, bExists );
#ifdef _DEBUG
if( !bExists )
{
TRACE( "Font doesn't exist '%s'\n", strFontName );
}
#endif // _DEBUG
return bExists;
}
void CHTMLParse::OnGotMeta( const CParameters &pList )
{
const UINT uParamSize = pList.GetSize();
for( UINT n = 0; n < uParamSize; n++ )
{
const CStaticString &strParam = pList[n].m_strValue;
switch( pList[n].m_param )
{
case pContent:
{
LPCTSTR pcszEnd = strParam.GetData() + strParam.GetLength();
static const TCHAR szCharSet[] = _T("charset");
LPCTSTR p = stristr( (LPTSTR)strParam.GetData(), szCharSet );
if( p )
{
//
// We have a charset, so next we need to decode it
p += countof( szCharSet ) - 1;
while( p < pcszEnd && ( isspace( *p ) || *p == _T('=') ) )
p++;
if( p < pcszEnd )
{
const CStaticString str( p, pcszEnd - p );
m_pDocument->m_cCharSet = DecodeCharset( str );
}
}
}
break;
case pHTTPEquiv:
//TRACE( "pHTTPEquiv %s\n", strParam );
break;
}
}
} | RaisingTheDerp/raisingthebar | root/vgui2/QHTM/QHTM/HTMLParse.cpp | C++ | gpl-3.0 | 34,340 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Tue Jan 16 16:58:40 CET 2018 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.openbase.bco.dal.visual.service.PresenceStateServicePanel (BCO DAL 1.5-SNAPSHOT API)</title>
<meta name="date" content="2018-01-16">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.openbase.bco.dal.visual.service.PresenceStateServicePanel (BCO DAL 1.5-SNAPSHOT API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/openbase/bco/dal/visual/service/PresenceStateServicePanel.html" title="class in org.openbase.bco.dal.visual.service">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/openbase/bco/dal/visual/service/class-use/PresenceStateServicePanel.html" target="_top">Frames</a></li>
<li><a href="PresenceStateServicePanel.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.openbase.bco.dal.visual.service.PresenceStateServicePanel" class="title">Uses of Class<br>org.openbase.bco.dal.visual.service.PresenceStateServicePanel</h2>
</div>
<div class="classUseContainer">No usage of org.openbase.bco.dal.visual.service.PresenceStateServicePanel</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/openbase/bco/dal/visual/service/PresenceStateServicePanel.html" title="class in org.openbase.bco.dal.visual.service">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/openbase/bco/dal/visual/service/class-use/PresenceStateServicePanel.html" target="_top">Frames</a></li>
<li><a href="PresenceStateServicePanel.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2014–2018 <a href="https://github.com/openbase">openbase.org</a>. All rights reserved.</small></p>
</body>
</html>
| DivineCooperation/bco.dal | docs/apidocs/org/openbase/bco/dal/visual/service/class-use/PresenceStateServicePanel.html | HTML | gpl-3.0 | 5,001 |
#ifndef __AD_JSON_RPC_MAPPER_H_
#define __AD_JSON_RPC_MAPPER_H_
#include "ADJsonRpcProxy.hpp"
#include "ADThread.hpp"
#include "ADGenericChain.hpp"
/*****************************************************************************/
//common macros for all the mappers of different services
/*****************************************************************************/
//to understand this, read C++ subject observer pattern
class ADJsonRpcMapProducer; //subject
class ADJsonRpcMapConsumer //observer
{
public:
virtual int process_json_to_binary(JsonDataCommObj* pReq)=0;
virtual int process_work(JsonDataCommObj* pReq)=0;
virtual int process_binary_to_json(JsonDataCommObj* pReq)=0;
virtual ~ADJsonRpcMapConsumer(){};
};
/*****************************************************************************/
class ADJsonRpcMapProducer
{
ADJsonRpcMapConsumer *pConsumerMapper;//callback of mapper
ADJsonRpcMapConsumer *pConsumerWorker;//callback of worker
protected:
int process_json_to_binary(JsonDataCommObj* pReq)
{
if(pConsumerMapper!=NULL)
return pConsumerMapper->process_json_to_binary(pReq);
return -1;
}
int process_work(JsonDataCommObj* pReq)
{
if(pConsumerWorker!=NULL)
return pConsumerWorker->process_work(pReq);
return -1;
}
int process_binary_to_json(JsonDataCommObj* pReq)
{
if(pConsumerMapper!=NULL)
return pConsumerMapper->process_binary_to_json(pReq);
return -1;
}
public:
ADJsonRpcMapProducer() {pConsumerMapper=NULL;pConsumerWorker=NULL;}
virtual ~ADJsonRpcMapProducer(){};
int AttachMapper(ADJsonRpcMapConsumer* c)
{
//allow only one mapper to be attached
if(pConsumerMapper==NULL)
{
pConsumerMapper=c;
return 0;
}
else
return -1;//some other mapper has already been attached
}
int AttachWorker(ADJsonRpcMapConsumer* c)
{
//allow only one worker to be attached
if(pConsumerWorker==NULL)
{
pConsumerWorker=c;
return 0;
}
else
return -1;//some other worker has already been attached
}
};
/*****************************************************************************/
class ADJsonRpcMapper : public ADJsonRpcConsumer, public ADThreadConsumer, public ADChainConsumer, public ADJsonRpcMapProducer
{
ADJsonRpcProxy* pJsonProxy;
ADThread ReqThread;//decoupler for incoming requests from ADJsonRpcProxy
ADGenericChain ReqChain;//chain for storing incoming requests
//json proxy callback(json-proxy will call this function on external rpc call)
virtual int rpc_call_notification(api_task_obj* pReqRespObj);//used in this class
//thread-callback functions(This manager needs a thread to process incoming requests)
virtual int monoshot_callback_function(void* pUserData,ADThreadProducer* pObj);//used in this class
virtual int thread_callback_function(void* pUserData,ADThreadProducer* pObj){return 0;};
//Chain-callback functions(this manager keeps the incoming requests in this chain).
virtual int identify_chain_element(void* element,int ident,ADChainProducer* pObj){return -1;};
virtual int double_identify_chain_element(void* element,int ident1,int ident2,ADChainProducer* pObj){return -1;};
virtual int free_chain_element_data(void* element,ADChainProducer* pObj){return 0;};
public:
ADJsonRpcMapper();
~ADJsonRpcMapper();
int AttachProxy(ADJsonRpcProxy* pJProxy);
int attach_rpc_method(int index,char* method_name);
};
#endif
| philippgl/brbox_plus | sources/lib/lib-adav-old/include/ADJsonRpcMapper.hpp | C++ | gpl-3.0 | 3,350 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Defines site config settings for the grader report
*
* @package gradereport_grader
* @copyright 2007 Moodle Pty Ltd (http://moodle.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die;
if ($ADMIN->fulltree) {
$strinherit = get_string('inherit', 'grades');
$strpercentage = get_string('percentage', 'grades');
$strreal = get_string('real', 'grades');
$strletter = get_string('letter', 'grades');
/// Add settings for this module to the $settings object (it's already defined)
$settings->add(new admin_setting_configtext('grade_report_studentsperpage', get_string('studentsperpage', 'grades'),
get_string('studentsperpage_help', 'grades'), 100));
$settings->add(new admin_setting_configtext('grade_report_repeatheaders', get_string('repeatheaders', 'grades'),
get_string('repeatheaders_help', 'grades'), 10));
$settings->add(new admin_setting_configcheckbox('grade_report_quickgrading', get_string('quickgrading', 'grades'),
get_string('quickgrading_help', 'grades'), 1));
$settings->add(new admin_setting_configcheckbox(
'grade_report_integrate_quick_edit',
get_string('quick_edit', 'gradereport_grader'),
get_string('quick_edit_desc', 'gradereport_grader'), 0
));
$settings->add(new admin_setting_configcheckbox('grade_report_showquickfeedback', get_string('quickfeedback', 'grades'),
get_string('showquickfeedback_help', 'grades'), 0));
$settings->add(new admin_setting_configcheckbox('grade_report_fixedstudents', get_string('fixedstudents', 'grades'),
get_string('fixedstudents_help', 'grades'), 0));
$settings->add(new admin_setting_configselect('grade_report_meanselection', get_string('meanselection', 'grades'),
get_string('meanselection_help', 'grades'), GRADE_REPORT_MEAN_GRADED,
array(GRADE_REPORT_MEAN_ALL => get_string('meanall', 'grades'),
GRADE_REPORT_MEAN_GRADED => get_string('meangraded', 'grades'))));
$settings->add(new admin_setting_configcheckbox('grade_report_enableajax', get_string('enableajax', 'grades'),
get_string('enableajax_help', 'grades'), 0));
$settings->add(new admin_setting_configcheckbox('grade_report_showcalculations', get_string('showcalculations', 'grades'),
get_string('showcalculations_help', 'grades'), 0));
$settings->add(new admin_setting_configcheckbox('grade_report_showeyecons', get_string('showeyecons', 'grades'),
get_string('showeyecons_help', 'grades'), 0));
$settings->add(new admin_setting_configcheckbox('grade_report_showaverages', get_string('showaverages', 'grades'),
get_string('showaverages_help', 'grades'), 1));
$settings->add(new admin_setting_configcheckbox('grade_report_showlocks', get_string('showlocks', 'grades'),
get_string('showlocks_help', 'grades'), 0));
$settings->add(new admin_setting_configcheckbox('grade_report_showranges', get_string('showranges', 'grades'),
get_string('showranges_help', 'grades'), 0));
$settings->add(new admin_setting_configcheckbox('grade_report_showanalysisicon', get_string('showanalysisicon', 'core_grades'),
get_string('showanalysisicon_desc', 'core_grades'), 1));
$settings->add(new admin_setting_configcheckbox('grade_report_showweightedpercents', get_string('showweightedpercents', 'grades'),
get_string('showweightedpercents_help', 'grades'), 0));
$settings->add(new admin_setting_configcheckbox('grade_report_showuserimage', get_string('showuserimage', 'grades'),
get_string('showuserimage_help', 'grades'), 1));
$settings->add(new admin_setting_configcheckbox('grade_report_showactivityicons', get_string('showactivityicons', 'grades'),
get_string('showactivityicons_help', 'grades'), 1));
$settings->add(new admin_setting_configcheckbox('grade_report_shownumberofgrades', get_string('shownumberofgrades', 'grades'),
get_string('shownumberofgrades_help', 'grades'), 0));
$settings->add(new admin_setting_configselect('grade_report_averagesdisplaytype', get_string('averagesdisplaytype', 'grades'),
get_string('averagesdisplaytype_help', 'grades'), GRADE_REPORT_PREFERENCE_INHERIT,
array(GRADE_REPORT_PREFERENCE_INHERIT => $strinherit,
GRADE_DISPLAY_TYPE_REAL => $strreal,
GRADE_DISPLAY_TYPE_PERCENTAGE => $strpercentage,
GRADE_DISPLAY_TYPE_LETTER => $strletter)));
$settings->add(new admin_setting_configselect('grade_report_rangesdisplaytype', get_string('rangesdisplaytype', 'grades'),
get_string('rangesdisplaytype_help', 'grades'), GRADE_REPORT_PREFERENCE_INHERIT,
array(GRADE_REPORT_PREFERENCE_INHERIT => $strinherit,
GRADE_DISPLAY_TYPE_REAL => $strreal,
GRADE_DISPLAY_TYPE_PERCENTAGE => $strpercentage,
GRADE_DISPLAY_TYPE_LETTER => $strletter)));
$settings->add(new admin_setting_configselect('grade_report_averagesdecimalpoints', get_string('averagesdecimalpoints', 'grades'),
get_string('averagesdecimalpoints_help', 'grades'), GRADE_REPORT_PREFERENCE_INHERIT,
array(GRADE_REPORT_PREFERENCE_INHERIT => $strinherit,
'0' => '0',
'1' => '1',
'2' => '2',
'3' => '3',
'4' => '4',
'5' => '5')));
$settings->add(new admin_setting_configselect('grade_report_rangesdecimalpoints', get_string('rangesdecimalpoints', 'grades'),
get_string('rangesdecimalpoints_help', 'grades'), GRADE_REPORT_PREFERENCE_INHERIT,
array(GRADE_REPORT_PREFERENCE_INHERIT => $strinherit,
'0' => '0',
'1' => '1',
'2' => '2',
'3' => '3',
'4' => '4',
'5' => '5')));
}
| lsuits/OBSOLETE--DO-NOT-USE--gradebook_moodle | grade/report/grader/settings.php | PHP | gpl-3.0 | 8,307 |
//Copyright (c) 2008-2009 Emil Dotchevski and Reverge Studios, Inc.
//Distributed under the Boost Software License, Version 1.0. (See accompanying
//file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/la/diag_matrix.hpp>
#include <boost/la/diag.hpp>
#include <boost/la/vector_mul_eq_scalar.hpp>
#include <boost/la/array_matrix_traits.hpp>
#include <boost/la/matrix_assign.hpp>
#include "test_la_vector.hpp"
#include "gold.hpp"
namespace
{
template <int Dim>
void
test()
{
using namespace boost::la;
test_la::vector<V1,Dim> x(42,1);
float y[Dim][Dim]; assign(y,x|diag_matrix);
for( int i=0; i!=Dim; ++i )
x.b[i]=y[i][i];
BOOST_TEST_LA_EQ(x.a,x.b);
test_la::scalar_multiply_v(x.b,x.a,2.0f);
x|diag_matrix|diag *= 2;
BOOST_TEST_LA_EQ(x.a,x.b);
}
}
int
main()
{
test<2>();
test<3>();
test<4>();
test<5>();
return boost::report_errors();
}
| kelvindk/Video-Stabilization | la/libs/la/test/diag_matrix_test.cpp | C++ | gpl-3.0 | 908 |
#!/usr/bin/env python
# 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
"""
Module for smallrnaseq configuration file. Used with command line app.
Created Jan 2017
Copyright (C) Damien Farrell
"""
from __future__ import absolute_import, print_function
import sys, os, string, time
import types, re, subprocess, glob, shutil
import pandas as pd
try:
import configparser
except:
import ConfigParser as configparser
path = os.path.dirname(os.path.abspath(__file__))
datadir = os.path.join(path, 'data')
from . import aligners
baseoptions = {'base': [('filenames',''),('path',''),('overwrite',0),
('adapter',''),
('index_path','indexes'),
('libraries',''),
('ref_fasta',''),('features',''),
('output','results'),('add_labels',0),
('aligner','bowtie'),
('mirna',0),('species','hsa'),('pad5',3),('pad3',5),
('verbose', 1),
('cpus',1)],
'aligner': [('default_params','-v 1 --best'),
('mirna_params',aligners.BOWTIE_MIRBASE_PARAMS)],
'novel': [('score_cutoff',.7), ('read_cutoff',100),
('strict',0)],
'de': [('count_file',''),('sample_labels',''),('sep',','),
('sample_col',''),('factors_col',''),
('conditions',''),('logfc_cutoff',1.5),
('de_plot','point')]
}
def write_default_config(conffile='default.conf', defaults={}):
"""Write a default config file"""
if not os.path.exists(conffile):
cp = create_config_parser_from_dict(defaults, ['base','novel','aligner','de'])
cp.write(open(conffile,'w'))
print ('wrote config file %s' %conffile)
return conffile
def create_config_parser_from_dict(data, sections, **kwargs):
"""Helper method to create a ConfigParser from a dict and/or keywords"""
cp = configparser.ConfigParser()
for s in sections:
cp.add_section(s)
if not data.has_key(s):
continue
for i in data[s]:
name,val = i
cp.set(s, name, str(val))
#use kwargs to create specific settings in the appropriate section
for s in cp.sections():
opts = cp.options(s)
for k in kwargs:
if k in opts:
cp.set(s, k, kwargs[k])
return cp
def parse_config(conffile=None):
"""Parse a configparser file"""
f = open(conffile,'r')
cp = configparser.ConfigParser()
try:
cp.read(conffile)
except Exception as e:
print ('failed to read config file! check format')
print ('Error returned:', e)
return
f.close()
return cp
def get_options(cp):
"""Makes sure boolean opts are parsed"""
from collections import OrderedDict
options = OrderedDict()
#options = cp._sections['base']
for section in cp.sections():
options.update( (cp._sections[section]) )
for o in options:
for section in cp.sections():
try:
options[o] = cp.getboolean(section, o)
except:
pass
try:
options[o] = cp.getint(section, o)
except:
pass
return options
def print_options(options):
"""Print option key/value pairs"""
for key in options:
print (key, ':', options[key])
print ()
def check_options(opts):
"""Check for missing default options in dict. Meant to handle
incomplete config files"""
sections = baseoptions.keys()
for s in sections:
defaults = dict(baseoptions[s])
for i in defaults:
if i not in opts:
opts[i] = defaults[i]
return opts
| dmnfarrell/smallrnaseq | smallrnaseq/config.py | Python | gpl-3.0 | 4,475 |
<?php
// This is a SPIP language file -- Ceci est un fichier langue de SPIP
// extrait automatiquement de http://trad.spip.net/tradlang_module/urls?lang_cible=uk
// ** ne pas modifier le fichier **
if (!defined('_ECRIRE_INC_VERSION')) {
return;
}
$GLOBALS[$GLOBALS['idx_lang']] = array(
// A
'actualiser_toutes' => 'Поновити усі URL',
'actualiser_toutes_explication' => 'Ви можете сгенерувати знову усі URL.
Якщо URL було змінено, то буде створено новий (попередній URL буде збережений, а посилання, визначені вручну, не зміняться).',
// B
'bouton_supprimer_url' => 'Видалити URL',
// E
'erreur_arbo_2_segments_max' => 'Неможна використовувати більш ніж 2 URL для одного об’єкту',
'erreur_config_url_forcee' => 'Налаштування формату URL зберігаються в файлі <tt>mes_options.php</tt>.',
'explication_editer' => 'Розширені налаштування дозволяють редагувати URL усіх материалів сайту, а також відстежувати історію їхніх змін.',
// I
'icone_configurer_urls' => 'Налаштування URL сторінок',
'icone_controler_urls' => 'Зрозумілі URL',
'info_1_url' => '1 URL',
'info_id_parent' => '#батько (#parent)',
'info_nb_urls' => '@nb@ URL',
'info_objet' => 'Об’єкт',
// L
'label_tri_date' => 'Дата',
'label_tri_id' => 'Номер',
'label_tri_url' => 'URL',
'label_url' => 'Новий URL',
'label_url_minuscules_0' => 'Зберігати регістр букв',
'label_url_minuscules_1' => 'Виводити URL в нижньому регістрі',
'label_url_permanente' => 'Заборонити зміни URL (посилання не змінюється післе зміннення матеріалу)',
'label_url_sep_id' => 'Розподілювач між додатковими цифрами, який додається, щоб уникнути дублювання URL',
'label_urls_activer_controle_oui' => 'Розширені налаштування генерування URL',
'label_urls_nb_max_car' => 'Максимальна кількість символів',
'label_urls_nb_min_car' => 'Мінімальна кількість символів',
'liberer_url' => 'Очистити',
'liste_des_urls' => 'Усі URL',
// T
'texte_type_urls' => 'Спосіб формування URL',
'texte_type_urls_attention' => 'Увага, ці налаштування будуть працювати тільки якщо файл @htaccess@ з дистрибутиву SPIP встановлено в корінь сайту.',
'texte_urls_nb_max_car' => 'Довгі назви будуть обрізані автоматично.',
'texte_urls_nb_min_car' => 'Короткие назви будуть доповнені автоматично.',
'titre_gestion_des_urls' => 'Управління посиланнями (URL)',
'titre_type_arbo' => 'Деревоподібні посилання (URLs Arborescentes)',
'titre_type_html' => 'Посилання з об’єктами HTML',
'titre_type_libres' => 'Довільний формат URLs',
'titre_type_page' => 'Адреса сторінки (URLs Page)',
'titre_type_propres' => 'Чисті назви (clean URLs )',
'titre_type_propres2' => 'Чисті посилання+<tt>.html</tt>',
'titre_type_propres_qs' => 'Чисті посилання в строці запиту',
'titre_type_simple' => 'Спрощений формат URL',
'titre_type_standard' => 'Історичний формат URL',
'titre_type_urls' => 'Автоматичне формування URL',
'tout_voir' => 'Показати усі URL',
// U
'url_ajout_impossible' => 'Неможливо зберігти URL через технічну помилку.',
'url_ajoutee' => 'URL додано',
// V
'verifier_url_nettoyee' => 'URL було змінено, перевірте правильність перед зберіганням.',
'verrouiller_url' => 'Заблокувати'
);
?>
| ernestovi/ups | spip/plugins-dist/urls_etendues/lang/urls_uk.php | PHP | gpl-3.0 | 4,280 |
/*
* Copyright 2011-2014 Jeroen Meetsma - IJsberg Automatisering BV
*
* This file is part of Iglu.
*
* Iglu 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.
*
* Iglu 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 Iglu. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ijsberg.iglu.access;
/**
*/
public class LoginExpiredException extends SessionExpiredException {
/**
*
*/
public LoginExpiredException() {
super();
}
/**
* @param message
*/
public LoginExpiredException(String message) {
super(message);
}
}
| jmeetsma/Iglu-Common | src/main/java/org/ijsberg/iglu/access/LoginExpiredException.java | Java | gpl-3.0 | 1,064 |
/*
* Copyright 2014 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 android.hardware.camera2.cts.rs;
import android.content.Context;
import android.renderscript.RenderScript;
import android.util.Log;
// TODO : Replace with dependency injection
/**
* Singleton to hold {@link RenderScript} and {@link AllocationCache} objects.
*
* <p>The test method must call {@link #setContext} before attempting to retrieve
* the underlying objects.</p> *
*/
public class RenderScriptSingleton {
private static final String TAG = "RenderScriptSingleton";
private static Context sContext;
private static RenderScript sRS;
private static AllocationCache sCache;
/**
* Initialize the singletons from the given context; the
* {@link RenderScript} and {@link AllocationCache} objects are instantiated.
*
* @param context a non-{@code null} Context.
*
* @throws IllegalStateException If this was called repeatedly without {@link #clearContext}
*/
public static synchronized void setContext(Context context) {
if (context.equals(sContext)) {
return;
} else if (sContext != null) {
Log.v(TAG,
"Trying to set new context " + context +
", before clearing previous "+ sContext);
throw new IllegalStateException(
"Call #clearContext before trying to set a new context");
}
sRS = RenderScript.create(context);
sContext = context;
sCache = new AllocationCache(sRS);
}
/**
* Clean up the singletons from the given context; the
* {@link RenderScript} and {@link AllocationCache} objects are destroyed.
*
* <p>Safe to call multiple times; subsequent invocations have no effect.</p>
*/
public static synchronized void clearContext() {
if (sContext != null) {
sCache.close();
sCache = null;
sRS.destroy();
sRS = null;
sContext = null;
}
}
/**
* Get the current {@link RenderScript} singleton.
*
* @return A non-{@code null} {@link RenderScript} object.
*
* @throws IllegalStateException if {@link #setContext} was not called prior to this
*/
public static synchronized RenderScript getRS() {
if (sRS == null) {
throw new IllegalStateException("Call #setContext before using #get");
}
return sRS;
}
/**
* Get the current {@link AllocationCache} singleton.
*
* @return A non-{@code null} {@link AllocationCache} object.
*
* @throws IllegalStateException if {@link #setContext} was not called prior to this
*/
public static synchronized AllocationCache getCache() {
if (sCache == null) {
throw new IllegalStateException("Call #setContext before using #getCache");
}
return sCache;
}
// Suppress default constructor for noninstantiability
private RenderScriptSingleton() { throw new AssertionError(); }
}
| s20121035/rk3288_android5.1_repo | cts/tests/tests/hardware/src/android/hardware/camera2/cts/rs/RenderScriptSingleton.java | Java | gpl-3.0 | 3,625 |
# -*- coding: utf-8 -*-
import re
import urlparse
from ..internal.misc import json
from ..internal.XFSAccount import XFSAccount
class UptoboxCom(XFSAccount):
__name__ = "UptoboxCom"
__type__ = "account"
__version__ = "0.21"
__status__ = "testing"
__description__ = """Uptobox.com account plugin"""
__license__ = "GPLv3"
__authors__ = [("benbox69", "dev@tollet.me")]
PLUGIN_DOMAIN = "uptobox.com"
PLUGIN_URL = "http://uptobox.com/"
LOGIN_URL = "https://login.uptobox.com/"
def signin(self, user, password, data):
html = self.load(self.LOGIN_URL, cookies=self.COOKIES)
if re.search(self.LOGIN_SKIP_PATTERN, html):
self.skip_login()
html = self.load(urlparse.urljoin(self.LOGIN_URL, "logarithme"),
post={'op': "login",
'redirect': self.PLUGIN_URL,
'login': user,
'password': password},
cookies=self.COOKIES)
if json.loads(html).get('error'):
self.fail_login()
| Velociraptor85/pyload | module/plugins/accounts/UptoboxCom.py | Python | gpl-3.0 | 1,110 |
package org.workcraft.plugins.cpog;
import org.workcraft.dom.Node;
import org.workcraft.observation.HierarchyEvent;
import org.workcraft.observation.HierarchySupervisor;
import org.workcraft.observation.NodesAddedEvent;
import org.workcraft.observation.NodesDeletedEvent;
import org.workcraft.observation.NodesReparentedEvent;
public class ConsistencyEnforcer extends HierarchySupervisor {
private final VisualCpog visualCPOG;
private int vertexCount = 0;
private int variableCount = 0;
public ConsistencyEnforcer(VisualCpog visualCPOG) {
this.visualCPOG = visualCPOG;
}
@Override
public void handleEvent(HierarchyEvent e) {
if ((e instanceof NodesAddedEvent) || (e instanceof NodesReparentedEvent)) {
createDefaultLabels(e);
updateEncoding();
} else if (e instanceof NodesDeletedEvent) {
updateEncoding();
}
}
private void createDefaultLabels(HierarchyEvent e) {
for (Node node : e.getAffectedNodes()) {
if (node instanceof VisualVertex) {
VisualVertex vertex = (VisualVertex) node;
if (vertex.getLabel().isEmpty()) {
vertex.setLabel("v_" + vertexCount++);
}
}
if (node instanceof VisualVariable) {
VisualVariable variable = (VisualVariable) node;
if (variable.getLabel().isEmpty()) {
variable.setLabel("x_" + variableCount++);
}
}
}
}
private void updateEncoding() {
for (VisualScenario group : visualCPOG.getGroups()) {
Encoding oldEncoding = group.getEncoding();
Encoding newEncoding = new Encoding();
for (VisualVariable var : visualCPOG.getVariables()) {
Variable mathVariable = var.getMathVariable();
newEncoding.setState(mathVariable, oldEncoding.getState(mathVariable));
}
group.setEncoding(newEncoding);
}
}
}
| shelllbw/workcraft | CpogPlugin/src/org/workcraft/plugins/cpog/ConsistencyEnforcer.java | Java | gpl-3.0 | 2,055 |
<?php
/*
* This file is part of the Lisem Project.
*
* Copyright (C) 2015-2017 Libre Informatique
*
* This file is licenced under the GNU GPL v3.
* For the full copyright and license information, please view the LICENSE.md
* file that was distributed with this source code.
*/
namespace AppBundle\Entity\OuterExtension\LibrinfoSeedBatchBundle;
trait CertificationTypeExtension
{
use \Librinfo\SonataSyliusUserBundle\Entity\Traits\Traceable;
}
| libre-informatique/LIBioSymfonyProject | src/AppBundle/Entity/OuterExtension/LibrinfoSeedBatchBundle/CertificationTypeExtension.php | PHP | gpl-3.0 | 458 |
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** 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 The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include "clangcompletionassistinterface.h"
#include <texteditor/texteditor.h>
namespace ClangCodeModel {
namespace Internal {
ClangCompletionAssistInterface::ClangCompletionAssistInterface(BackendCommunicator &communicator, CompletionType type,
const TextEditor::TextEditorWidget *textEditorWidget,
int position,
const Utils::FilePath &fileName,
TextEditor::AssistReason reason,
const ProjectExplorer::HeaderPaths &headerPaths,
const CPlusPlus::LanguageFeatures &features)
: AssistInterface(textEditorWidget->document(), position, fileName, reason)
, m_communicator(communicator)
, m_type(type)
, m_headerPaths(headerPaths)
, m_languageFeatures(features)
, m_textEditorWidget(textEditorWidget)
{
}
bool ClangCompletionAssistInterface::objcEnabled() const
{
return true; // TODO:
}
const ProjectExplorer::HeaderPaths &ClangCompletionAssistInterface::headerPaths() const
{
return m_headerPaths;
}
CPlusPlus::LanguageFeatures ClangCompletionAssistInterface::languageFeatures() const
{
return m_languageFeatures;
}
void ClangCompletionAssistInterface::setHeaderPaths(const ProjectExplorer::HeaderPaths &headerPaths)
{
m_headerPaths = headerPaths;
}
const TextEditor::TextEditorWidget *ClangCompletionAssistInterface::textEditorWidget() const
{
return m_textEditorWidget;
}
BackendCommunicator &ClangCompletionAssistInterface::communicator() const
{
return m_communicator;
}
} // namespace Internal
} // namespace ClangCodeModel
| qtproject/qt-creator | src/plugins/clangcodemodel/clangcompletionassistinterface.cpp | C++ | gpl-3.0 | 2,726 |
#!/usr/bin/python3
## @package domomaster
# Master daemon for D3 boxes.
#
# Developed by GreenLeaf.
import sys;
import os;
import random;
import string;
from hashlib import sha1
from subprocess import *
import socket;
sys.path.append("/usr/lib/domoleaf");
from DaemonConfigParser import *;
MASTER_CONF_FILE_BKP = '/etc/domoleaf/master.conf.save';
MASTER_CONF_FILE_TO = '/etc/domoleaf/master.conf';
SLAVE_CONF_FILE = '/etc/domoleaf/slave.conf';
## Copies the conf data from a backup file to a new one.
def master_conf_copy():
file_from = DaemonConfigParser(MASTER_CONF_FILE_BKP);
file_to = DaemonConfigParser(MASTER_CONF_FILE_TO);
#listen
var = file_from.getValueFromSection('listen', 'port_slave');
file_to.writeValueFromSection('listen', 'port_slave', var);
var = file_from.getValueFromSection('listen', 'port_cmd');
file_to.writeValueFromSection('listen', 'port_cmd', var);
#connect
var = file_from.getValueFromSection('connect', 'port');
file_to.writeValueFromSection('connect', 'port', var);
#mysql
var = file_from.getValueFromSection('mysql', 'user');
file_to.writeValueFromSection('mysql', 'user', var);
var = file_from.getValueFromSection('mysql', 'database_name');
file_to.writeValueFromSection('mysql', 'database_name', var);
#greenleaf
var = file_from.getValueFromSection('greenleaf', 'commercial');
file_to.writeValueFromSection('greenleaf', 'commercial', var);
var = file_from.getValueFromSection('greenleaf', 'admin_addr');
file_to.writeValueFromSection('greenleaf', 'admin_addr', var);
## Initializes the conf in database.
def master_conf_initdb():
file = DaemonConfigParser(MASTER_CONF_FILE_TO);
#mysql password
password = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(128))
password = sha1(password.encode('utf-8'))
file.writeValueFromSection('mysql', 'password', password.hexdigest());
os.system('sed -i "s/define(\'DB_PASSWORD\', \'domoleaf\')/define(\'DB_PASSWORD\', \''+password.hexdigest()+'\')/g" /etc/domoleaf/www/config.php')
#mysql user
query1 = 'DELETE FROM user WHERE User="domoleaf"';
query2 = 'DELETE FROM db WHERE User="domoleaf"';
query3 = 'INSERT INTO user (Host, User, Password) VALUES (\'%\', \'domoleaf\', PASSWORD(\''+password.hexdigest()+'\'));';
query4 = 'INSERT INTO db (Host, Db, User, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Grant_priv, References_priv, Index_priv, Alter_priv, Create_tmp_table_priv, Lock_tables_priv, Create_view_priv, Show_view_priv, Create_routine_priv, Alter_routine_priv, Execute_priv, Event_priv, Trigger_priv) VALUES ("%","domoleaf","domoleaf","Y","Y","Y","Y","Y","Y","Y","Y","Y","Y","Y","Y","Y","Y","Y","Y","Y","Y","Y");';
query5 = 'FLUSH PRIVILEGES';
call(['mysql', '--defaults-file=/etc/mysql/debian.cnf', 'mysql', '-e', query1]);
call(['mysql', '--defaults-file=/etc/mysql/debian.cnf', 'mysql', '-e', query2]);
call(['mysql', '--defaults-file=/etc/mysql/debian.cnf', 'mysql', '-e', query3]);
call(['mysql', '--defaults-file=/etc/mysql/debian.cnf', 'mysql', '-e', query4]);
call(['mysql', '--defaults-file=/etc/mysql/debian.cnf', 'mysql', '-e', query5]);
## Initializes the conf in file.
def master_conf_init():
file = DaemonConfigParser(SLAVE_CONF_FILE);
personnal_key = file.getValueFromSection('personnal_key', 'aes');
hostname = socket.gethostname();
#KNX Interface
if os.path.exists('/dev/ttyAMA0'):
knx = "tpuarts"
knx_interface = 'ttyAMA0';
elif os.path.exists('/dev/ttyS0'):
knx = "tpuarts"
knx_interface = 'ttyS0';
else:
knx = "ipt"
knx_interface = '127.0.0.1';
domoslave = os.popen("dpkg-query -W -f='${Version}\n' domoslave").read().split('\n')[0];
query1 = "INSERT INTO daemon (name, serial, secretkey, validation, version) VALUES ('"+hostname+"','"+hostname+"','"+personnal_key+"',1,'"+domoslave+"')"
query2 = "INSERT INTO daemon_protocol (daemon_id, protocol_id, interface, interface_arg) VALUES (1,1,'"+knx+"','"+knx_interface+"')"
call(['mysql', '--defaults-file=/etc/mysql/debian.cnf', 'domoleaf',
'-e', query1]);
call(['mysql', '--defaults-file=/etc/mysql/debian.cnf', 'domoleaf',
'-e', query2]);
if __name__ == "__main__":
#Upgrade
if os.path.exists(MASTER_CONF_FILE_BKP):
master_conf_copy()
os.remove(MASTER_CONF_FILE_BKP);
else:
master_conf_init()
master_conf_initdb()
| V-Paranoiaque/Domoleaf | domomaster/usr/bin/domomaster/domomaster_postinst.py | Python | gpl-3.0 | 4,613 |
jQuery.fn.resolveLetterData = function() {
var letterTypes = [];
letterTypes.push("Peraturan");
letterTypes.push("Pedoman");
letterTypes.push("Petunjuk Pelaksanaan");
letterTypes.push("Instruksi");
letterTypes.push("Prosedur Tetap (SOP)");
letterTypes.push("Surat Edaran");
letterTypes.push("Keputusan");
letterTypes.push("Surat Perintah/Surat Tugas");
letterTypes.push("Nota Dinas");
letterTypes.push("Memorandum");
letterTypes.push("Surat Dinas");
letterTypes.push("Surat Undangan");
letterTypes.push("Surat Perjanjian");
letterTypes.push("Surat Kuasa");
letterTypes.push("Berita Acara");
letterTypes.push("Surat Keterangan");
letterTypes.push("Surat Pengantar");
letterTypes.push("Pengumuman");
letterTypes.push("Laporan");
letterTypes.push("Lain-lain");
var letterPriorities = ["Biasa", "Segera", "Amat Segera"];
var letterPrioritiesClasses = ["success", "warning", "important"];
var letterClassifications = ["Biasa", "Rahasia", "Sangat Rahasia"];
var letterClassificationClasses = ["success", "warning", "important"];
var letterStatus = [
"Dalam proses penulisan",
"Dalam proses pemeriksaan keluar",
"Menunggu proses pengiriman",
"Terkirim",
"Belum dibaca",
"Belum semua penerima telah membaca",
"Penerima telah membaca",
];
var letterStatusClasses = [
"warning",
"warning",
"warning",
"important",
"warning",
"success",
];
var items = $(this);
for (var i = 0; i < items.length; i ++) {
var item = items[i];
var value = $(item).attr("data-value");
var type = $(item).attr("data-type");
var index = parseInt(value);
if (!isNaN(index)) {
if (type == "type")
$(item).text(letterTypes[value]);
else if (type == "classification") {
$(item).text(letterClassifications[value]);
$(item).addClass("label label-" + letterClassificationClasses[value]);
} else if (type == "priority") {
$(item).text(letterPriorities[value]);
$(item).addClass("label label-" + letterPrioritiesClasses[value]);
} else if (type == "status") {
$(item).text(letterStatus[value]);
$(item).addClass("label label-" + letterStatusClasses[value]);
}
} else {
$(item).text("Tidak diketahui");
}
}
}
function updateSearchDateVisibility(e) {
var searchByDate = ($(e).attr("data-type") === "date");
if (searchByDate) {
$(".search-date").removeClass("hidden");
$("#search-string").addClass("hidden");
} else {
$(".search-date").addClass("hidden");
$("#search-string").removeClass("hidden");
}
}
$(document).ready(function() {
$(".resolve-letter-data").resolveLetterData();
$("#search-type").change(function(){
$("select[id='search-type'] option:selected").each(function(){
updateSearchDateVisibility(this);
});
});
});
| simaya/simaya | static/js/letter-data.js | JavaScript | gpl-3.0 | 2,871 |
import {ProjectEditor, EditProject} from "@atomist/rug/operations/ProjectEditor"
import {Project} from "@atomist/rug/model/Project"
import {Edit,Instruction,HandleCommand, Respondable, Execute} from "@atomist/rug/operations/Handlers"
/**
* Build a plan instruction for the given decorated
* editor, extracting its present property values, which
* follow a convention, with names like __name
* @param p project or name of project to edit
* @param ed editor to use
*/
export function editWith(p: Project | string, ed: EditProject | ProjectEditor): Edit {
let obj = instruction(ed, "edit")
let proj = p as any
obj["project"] = proj.name ? proj.name() : p
return obj as Edit
}
export function handleCommand(ed: HandleCommand): Instruction<"command"> {
return instruction(ed, "command")
}
/**
* Emit an instruction for the given decorated operation type
* @param op operation to emit instruction for
* @param kind kind of the instruction, such as "edit"
*/
function instruction(op, kind) {
let params = {}
for (let param of op.__parameters) {
params[param.name] = op[param.name]
}
return {
kind: kind,
name: op.__name,
parameters: params,
}
}
/**
* Build an 'execute' Rug Function
* @param name Rug Function to call
* @param params any params, if any
*/
export function execute(name: string, params?: any) : Respondable<Execute> {
return {instruction: {kind: "execute", name: name, parameters: params}}
} | atomist/rug-cli | src/test/resources/handlers/.atomist/node_modules/@atomist/rugs/operations/PlanUtils.ts | TypeScript | gpl-3.0 | 1,492 |
/* Copyright (c) 2013 by Antonio Santiago <asantiagop_at_gmail_dot_com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of OpenLayers Contributors.
*/
/**
* @requires OpenLayers/Strategy/Cluster.js
*/
/**
* Class: OpenLayers.Strategy.AnimatedCluster
* Cluster strategy for vector layers with animations.
*
* Inherits from:
* - <OpenLayers.Strategy.Cluster>
*/
OpenLayers.Strategy.AnimatedCluster = OpenLayers.Class(OpenLayers.Strategy.Cluster, {
/**
* APIProperty: animationMethod
* {<OpenLayers.Easing>(Function)} Easing equation used for the animation
* Defaultly set to OpenLayers.Easing.Expo.easeOut
*/
animationMethod: OpenLayers.Easing.Expo.easeOut,
/**
* APIProperty: animationDuration
* {Integer} The number of steps to be passed to the OpenLayers.Tween.start()
* method when the clusters are animated.
* Default is 20.
*/
animationDuration: 20,
/**
* Property: animationTween
* {OpenLayers.Tween} Animated panning tween object.
*/
animationTween: null,
/**
* Property: previousResolution
* {Float} The previous resolution of the map.
*/
previousResolution: null,
/**
* Property: previousClusters
* {Array(<OpenLayers.Feature.Vector>)} Clusters of features at previous
* resolution.
*/
previousClusters: null,
/**
* Property: animating
* {Boolean} Indicates if we are in the process of clusters animation.
*/
animating: false,
/**
* Property: zoomIn
* {Boolean} Indicates if we are zooming in or zooming out.
*/
zoomIn: true,
/**
* Constructor: OpenLayers.Strategy.AnimatedCluster
* Create a new animation clustering strategy.
*
* Parameters:
* options - {Object} Optional object whose properties will be set on the
* instance.
*/
initialize: function(options) {
OpenLayers.Strategy.Cluster.prototype.initialize.apply(this, arguments);
if(options.animationMethod) {
this.animationMethod = options.animationMethod;
}
},
/**
* Method: destroy
* Free resources.
*/
destroy: function() {
if(this.animationTween) {
this.animationTween.stop();
this.animationTween = null;
}
},
/**
* Redraw features.
*/
redraw: function() {
// After removeAllFeatures and/or destroyFeatures is called it removes only clusters
// but but they don't affect the original features the clustering strategy holds in cache.
// Changing the clustering strategy resolution forces the addFeatures() to redraw features.
this.resolution = -1;
},
/**
* Method: cluster
* Cluster features based on some threshold distance.
*
* Parameters:
* event - {Object} The event received when cluster is called as a
* result of a moveend event.
*/
cluster: function(event) {
var resolution = this.layer.map.getResolution();
var isPan = (event && event.type=="moveend" && !event.zoomChanged);
// Each time clusters are animated we need to call layer.redraw to show
// position changes. This produces layer will be redrawn and a call to
// cluster is made.
// Because this, ff we are animating clusters and zoom didn't changed, simply return.
if(this.animating && (resolution == this.resolution)) {
return;
}
if((!event || event.zoomChanged || isPan) && this.features) {
if(resolution != this.resolution || !this.clustersExist() || isPan) {
if(resolution != this.resolution) {
this.zoomIn = (!this.resolution || ((resolution <= this.resolution)||(resolution > this.resolution)));
}
// Store previous data if we are changing zoom level
this.previousResolution = this.resolution;
this.previousClusters = this.clusters;
this.resolution = resolution;
var clusters = [];
var feature, clustered, cluster;
for(var i=0; i<this.features.length; ++i) {
feature = this.features[i];
// Check if the feature's geometry is on the map's viewport,
// if so then manages it, otherwise ignore.
if(this.layer && this.layer.map) {
var screenBounds = this.layer.map.getExtent();
var featureBounds = feature.geometry.getBounds();
if(!screenBounds.intersectsBounds(featureBounds)) {
continue;
}
}
if(feature.geometry) {
// Cluster for the current resolution
clustered = false;
for(var j=clusters.length-1; j>=0; --j) {
cluster = clusters[j];
if(this.shouldCluster(cluster, feature)) {
this.addToCluster(cluster, feature);
clustered = true;
break;
}
}
if(!clustered) {
clusters.push(this.createCluster(this.features[i]));
}
}
}
// Apply threshold for cluster at current resolution
if(clusters.length > 0) {
if(this.threshold > 1) {
var clone = clusters.slice();
clusters = [];
var candidate;
for(var i=0, len=clone.length; i<len; ++i) {
candidate = clone[i];
if(candidate.attributes.count < this.threshold) {
Array.prototype.push.apply(clusters, candidate.cluster);
} else {
clusters.push(candidate);
}
}
}
}
this.clusters = clusters;
this.clustering = true;
// Add clusters features to the layer
this.layer.removeAllFeatures();
// A legitimate feature addition could occur during this
// addFeatures call. For clustering to behave well, features
// should be removed from a layer before requesting a new batch.
if(this.zoomIn || !this.previousClusters) {
this.layer.addFeatures(this.clusters);
} else {
this.layer.addFeatures(this.previousClusters);
}
this.clustering = false;
// Get the initial and final position of each cluster required
// make the animation
if(this.clusters.length > 0 && this.previousClusters) {
// Before clustering stop any animation
if(this.animationTween) {
this.animationTween.stop();
}
var clustersA, clustersB;
if(this.zoomIn) {
clustersA = this.clusters;
clustersB = this.previousClusters;
} else {
clustersA = this.previousClusters;
clustersB = this.clusters;
}
for(var i=0; i< clustersA.length; i++) {
var ca = clustersA[i];
var caFeatures = ca.cluster || [ca]; // either a cluster of features or a single feature
var cb = this.findFeaturesInClusters(caFeatures, clustersB);
if(cb) {
ca._geometry = {};
if(this.zoomIn) {
ca._geometry.origx = cb.geometry.x;
ca._geometry.origy = cb.geometry.y;
ca._geometry.destx = ca.geometry.x;
ca._geometry.desty = ca.geometry.y;
ca.geometry.x = ca._geometry.origx;
ca.geometry.y = ca._geometry.origy;
} else {
ca._geometry.origx = ca.geometry.x;
ca._geometry.origy = ca.geometry.y;
ca._geometry.destx = cb.geometry.x;
ca._geometry.desty = cb.geometry.y;
}
}
}
// If we are panning then don't animate the cluster
if(isPan && !this.animating){
// Make sure that layer gets redrawn, even if it is just a pan.
this.layer.redraw();
return;
}
// Make animation
if(!this.animationTween) {
this.animationTween = new OpenLayers.Tween(this.animationMethod);
}
this.animating = true;
this.animationTween.start({
x: 0.0,
y: 0.0
}, {
x: 1.0,
y: 1.0
}, this.animationDuration, {
callbacks: {
eachStep: OpenLayers.Function.bind(this.animate, this),
done: OpenLayers.Function.bind(function(delta){
this.animate(delta);
// Remove the temporal attributes
var clusters = this.zoomIn ? this.clusters : this.previousClusters;
for(var i=0; i< clusters.length; i++) {
// if is this really a cluster and not a feature
if (clusters[i].attributes.count) {
if (clusters[i].cluster._geometry) {
delete clusters[i].cluster._geometry;
} else if (clusters[i]._geometry) {
delete clusters[i]._geometry;
}
}
}
// If zooming out then remove the previous cluster
// and the current one
if(!this.zoomIn) {
this.clustering = true;
this.layer.removeFeatures(this.previousClusters);
this.layer.addFeatures(this.clusters);
this.clustering = false;
}
this.animating = false;
}, this)
}
});
}
}
}
},
/**
* Method: findFeaturesInClusters
* Given a set of features and an array of clusters returns the cluster
* where the features are located.
*
* Parameters:
* features - {Array} An array of <OpenLayers.Feature.Vector>.
* clusters - A cluster as an array of <OpenLayers.Feature.Vector>.
*
* Returns:
* {<OpenLayers.Feature.Vector>} The cluster where the first feature of
* the feature array is found.
*/
findFeaturesInClusters: function(features, clusters) {
for(var i=0; i<features.length; i++) {
var feature = features[i];
for(var j=0; j<clusters.length; j++) {
var cluster = clusters[j];
// if cluster is really cluster not a feature
if (cluster.attributes.count) {
var clusterFeatures = clusters[j].cluster;
for(var k=0; k<clusterFeatures.length; k++) {
if(feature.id == clusterFeatures[k].id) {
return cluster;
}
}
}
}
}
return null;
},
/**
* APIMethod: animate
* Animates the clusters changing its position.
*
* Parameters:
* delta - {Object} Object with x-y values with the new increments to
* be applied.
*/
animate: function(delta) {
var clusters = this.zoomIn ? this.clusters : this.previousClusters;
for(var i=0; i<clusters.length; i++) {
if(!clusters[i]._geometry) continue;
var dx = (clusters[i]._geometry.destx - clusters[i]._geometry.origx) * delta.x;
var dy = (clusters[i]._geometry.desty - clusters[i]._geometry.origy) * delta.y;
// added test for instance when clusters[i].geometry is null
if (clusters[i].hasOwnProperty("geometry") && clusters[i].geometry != null) {
clusters[i].geometry.x = clusters[i]._geometry.origx + dx;
clusters[i].geometry.y = clusters[i]._geometry.origy + dy;
}
else{
clusters[i].geometry = new OpenLayers.Geometry();
clusters[i].geometry.x = clusters[i]._geometry.origx + dx;
clusters[i].geometry.y = clusters[i]._geometry.origy + dy;
}
}
this.layer.redraw();
},
/**
* Method: shouldCluster
* Determine whether to include a feature in a given cluster.
*
* Parameters:
* cluster - {<OpenLayers.Feature.Vector>} A cluster.
* feature - {<OpenLayers.Feature.Vector>} A feature.
* previousResolution - {Boolean} Indicates if the check must be made with
* the current or previous resolution value.
*
* Returns:
* {Boolean} The feature should be included in the cluster.
*/
shouldCluster: function(cluster, feature, previousResolution) {
var res = previousResolution ? this.previousResolution : this.resolution;
var cc = cluster.geometry.getBounds().getCenterLonLat();
var fc = feature.geometry.getBounds().getCenterLonLat();
var distance = (
Math.sqrt(
Math.pow((cc.lon - fc.lon), 2) + Math.pow((cc.lat - fc.lat), 2)
) / res
);
return (distance <= this.distance);
},
CLASS_NAME: "OpenLayers.Strategy.AnimatedCluster"
});
| 2p2r/velobs_web | lib/js/framework/AnimatedCluster.js | JavaScript | gpl-3.0 | 16,688 |
<!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/html; charset=utf-8" />
<title>How to Work with Emails During Development — Symfony2Docs v2.1.0 2.1.0 documentation</title>
<link rel="stylesheet" href="../../_static/default.css" type="text/css" />
<link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../../',
VERSION: '2.1.0',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="../../_static/jquery.js"></script>
<script type="text/javascript" src="../../_static/underscore.js"></script>
<script type="text/javascript" src="../../_static/doctools.js"></script>
<link rel="top" title="Symfony2Docs v2.1.0 2.1.0 documentation" href="../../index.html" />
<link rel="up" title="Email" href="index.html" />
<link rel="next" title="How to Spool Email" href="spool.html" />
<link rel="prev" title="How to use Gmail to send Emails" href="gmail.html" />
</head>
<body>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="spool.html" title="How to Spool Email"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="gmail.html" title="How to use Gmail to send Emails"
accesskey="P">previous</a> |</li>
<li><a href="../../index.html">Symfony2Docs v2.1.0 2.1.0 documentation</a> »</li>
<li><a href="../index.html" >The Cookbook</a> »</li>
<li><a href="index.html" accesskey="U">Email</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body">
<div class="section" id="how-to-work-with-emails-during-development">
<span id="index-0"></span><h1>How to Work with Emails During Development<a class="headerlink" href="#how-to-work-with-emails-during-development" title="Permalink to this headline">¶</a></h1>
<p>When developing an application which sends email, you will often
not want to actually send the email to the specified recipient during
development. If you are using the <tt class="docutils literal"><span class="pre">SwiftmailerBundle</span></tt> with Symfony2, you
can easily achieve this through configuration settings without having to
make any changes to your application’s code at all. There are two main
choices when it comes to handling email during development: (a) disabling the
sending of email altogether or (b) sending all email to a specific
address.</p>
<div class="section" id="disabling-sending">
<h2>Disabling Sending<a class="headerlink" href="#disabling-sending" title="Permalink to this headline">¶</a></h2>
<p>You can disable sending email by setting the <tt class="docutils literal"><span class="pre">disable_delivery</span></tt> option
to <tt class="docutils literal"><span class="pre">true</span></tt>. This is the default in the <tt class="docutils literal"><span class="pre">test</span></tt> environment in the Standard
distribution. If you do this in the <tt class="docutils literal"><span class="pre">test</span></tt> specific config then email
will not be sent when you run tests, but will continue to be sent in the
<tt class="docutils literal"><span class="pre">prod</span></tt> and <tt class="docutils literal"><span class="pre">dev</span></tt> environments:</p>
<div class="configuration-block">
<ul class="simple">
<li><em>YAML</em><div class="highlight-yaml"><div class="highlight"><pre><span class="c1"># app/config/config_test.yml</span>
<span class="l-Scalar-Plain">swiftmailer</span><span class="p-Indicator">:</span>
<span class="l-Scalar-Plain">disable_delivery</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">true</span>
</pre></div>
</div>
</li>
<li><em>XML</em><div class="highlight-xml"><div class="highlight"><pre><span class="c"><!-- app/config/config_test.xml --></span>
<span class="c"><!--</span>
<span class="c"> xmlns:swiftmailer="http://symfony.com/schema/dic/swiftmailer"</span>
<span class="c"> http://symfony.com/schema/dic/swiftmailer http://symfony.com/schema/dic/swiftmailer/swiftmailer-1.0.xsd</span>
<span class="c">--></span>
<span class="nt"><swiftmailer:config</span>
<span class="na">disable-delivery=</span><span class="s">"true"</span> <span class="nt">/></span>
</pre></div>
</div>
</li>
<li><em>PHP</em><div class="highlight-php"><div class="highlight"><pre><span class="c1">// app/config/config_test.php</span>
<span class="nv">$container</span><span class="o">-></span><span class="na">loadFromExtension</span><span class="p">(</span><span class="s1">'swiftmailer'</span><span class="p">,</span> <span class="k">array</span><span class="p">(</span>
<span class="s1">'disable_delivery'</span> <span class="o">=></span> <span class="s2">"true"</span><span class="p">,</span>
<span class="p">));</span>
</pre></div>
</div>
</li>
</ul>
</div>
<p>If you’d also like to disable deliver in the <tt class="docutils literal"><span class="pre">dev</span></tt> environment, simply
add this same configuration to the <tt class="docutils literal"><span class="pre">config_dev.yml</span></tt> file.</p>
</div>
<div class="section" id="sending-to-a-specified-address">
<h2>Sending to a Specified Address<a class="headerlink" href="#sending-to-a-specified-address" title="Permalink to this headline">¶</a></h2>
<p>You can also choose to have all email sent to a specific address, instead
of the address actually specified when sending the message. This can be done
via the <tt class="docutils literal"><span class="pre">delivery_address</span></tt> option:</p>
<div class="configuration-block">
<ul class="simple">
<li><em>YAML</em><div class="highlight-yaml"><div class="highlight"><pre><span class="c1"># app/config/config_dev.yml</span>
<span class="l-Scalar-Plain">swiftmailer</span><span class="p-Indicator">:</span>
<span class="l-Scalar-Plain">delivery_address</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">dev@example.com</span>
</pre></div>
</div>
</li>
<li><em>XML</em><div class="highlight-xml"><div class="highlight"><pre><span class="c"><!-- app/config/config_dev.xml --></span>
<span class="c"><!--</span>
<span class="c"> xmlns:swiftmailer="http://symfony.com/schema/dic/swiftmailer"</span>
<span class="c"> http://symfony.com/schema/dic/swiftmailer http://symfony.com/schema/dic/swiftmailer/swiftmailer-1.0.xsd</span>
<span class="c">--></span>
<span class="nt"><swiftmailer:config</span>
<span class="na">delivery-address=</span><span class="s">"dev@example.com"</span> <span class="nt">/></span>
</pre></div>
</div>
</li>
<li><em>PHP</em><div class="highlight-php"><div class="highlight"><pre><span class="c1">// app/config/config_dev.php</span>
<span class="nv">$container</span><span class="o">-></span><span class="na">loadFromExtension</span><span class="p">(</span><span class="s1">'swiftmailer'</span><span class="p">,</span> <span class="k">array</span><span class="p">(</span>
<span class="s1">'delivery_address'</span> <span class="o">=></span> <span class="s2">"dev@example.com"</span><span class="p">,</span>
<span class="p">));</span>
</pre></div>
</div>
</li>
</ul>
</div>
<p>Now, suppose you’re sending an email to <tt class="docutils literal"><span class="pre">recipient@example.com</span></tt>.</p>
<div class="highlight-php"><div class="highlight"><pre><span class="k">public</span> <span class="k">function</span> <span class="nf">indexAction</span><span class="p">(</span><span class="nv">$name</span><span class="p">)</span>
<span class="p">{</span>
<span class="nv">$message</span> <span class="o">=</span> <span class="nx">\Swift_Message</span><span class="o">::</span><span class="na">newInstance</span><span class="p">()</span>
<span class="o">-></span><span class="na">setSubject</span><span class="p">(</span><span class="s1">'Hello Email'</span><span class="p">)</span>
<span class="o">-></span><span class="na">setFrom</span><span class="p">(</span><span class="s1">'send@example.com'</span><span class="p">)</span>
<span class="o">-></span><span class="na">setTo</span><span class="p">(</span><span class="s1">'recipient@example.com'</span><span class="p">)</span>
<span class="o">-></span><span class="na">setBody</span><span class="p">(</span><span class="nv">$this</span><span class="o">-></span><span class="na">renderView</span><span class="p">(</span><span class="s1">'HelloBundle:Hello:email.txt.twig'</span><span class="p">,</span> <span class="k">array</span><span class="p">(</span><span class="s1">'name'</span> <span class="o">=></span> <span class="nv">$name</span><span class="p">)))</span>
<span class="p">;</span>
<span class="nv">$this</span><span class="o">-></span><span class="na">get</span><span class="p">(</span><span class="s1">'mailer'</span><span class="p">)</span><span class="o">-></span><span class="na">send</span><span class="p">(</span><span class="nv">$message</span><span class="p">);</span>
<span class="k">return</span> <span class="nv">$this</span><span class="o">-></span><span class="na">render</span><span class="p">(</span><span class="o">...</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>In the <tt class="docutils literal"><span class="pre">dev</span></tt> environment, the email will instead be sent to <tt class="docutils literal"><span class="pre">dev@example.com</span></tt>.
Swiftmailer will add an extra header to the email, <tt class="docutils literal"><span class="pre">X-Swift-To</span></tt>, containing
the replaced address, so you can still see who it would have been sent to.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">In addition to the <tt class="docutils literal"><span class="pre">to</span></tt> addresses, this will also stop the email being
sent to any <tt class="docutils literal"><span class="pre">CC</span></tt> and <tt class="docutils literal"><span class="pre">BCC</span></tt> addresses set for it. Swiftmailer will add
additional headers to the email with the overridden addresses in them.
These are <tt class="docutils literal"><span class="pre">X-Swift-Cc</span></tt> and <tt class="docutils literal"><span class="pre">X-Swift-Bcc</span></tt> for the <tt class="docutils literal"><span class="pre">CC</span></tt> and <tt class="docutils literal"><span class="pre">BCC</span></tt>
addresses respectively.</p>
</div>
</div>
<div class="section" id="viewing-from-the-web-debug-toolbar">
<h2>Viewing from the Web Debug Toolbar<a class="headerlink" href="#viewing-from-the-web-debug-toolbar" title="Permalink to this headline">¶</a></h2>
<p>You can view any email sent during a single response when you are in the
<tt class="docutils literal"><span class="pre">dev</span></tt> environment using the Web Debug Toolbar. The email icon in the toolbar
will show how many emails were sent. If you click it, a report will open
showing the details of the sent emails.</p>
<p>If you’re sending an email and then immediately redirecting to another page,
the web debug toolbar will not display an email icon or a report on the next
page.</p>
<p>Instead, you can set the <tt class="docutils literal"><span class="pre">intercept_redirects</span></tt> option to <tt class="docutils literal"><span class="pre">true</span></tt> in the
<tt class="docutils literal"><span class="pre">config_dev.yml</span></tt> file, which will cause the redirect to stop and allow
you to open the report with details of the sent emails.</p>
<div class="admonition tip">
<p class="first admonition-title">Tip</p>
<p class="last">Alternatively, you can open the profiler after the redirect and search
by the submit URL used on previous request (e.g. <tt class="docutils literal"><span class="pre">/contact/handle</span></tt>).
The profiler’s search feature allows you to load the profiler information
for any past requests.</p>
</div>
<div class="configuration-block">
<ul class="simple">
<li><em>YAML</em><div class="highlight-yaml"><div class="highlight"><pre><span class="c1"># app/config/config_dev.yml</span>
<span class="l-Scalar-Plain">web_profiler</span><span class="p-Indicator">:</span>
<span class="l-Scalar-Plain">intercept_redirects</span><span class="p-Indicator">:</span> <span class="l-Scalar-Plain">true</span>
</pre></div>
</div>
</li>
<li><em>XML</em><div class="highlight-xml"><div class="highlight"><pre><span class="c"><!-- app/config/config_dev.xml --></span>
<span class="c"><!--</span>
<span class="c"> xmlns:webprofiler="http://symfony.com/schema/dic/webprofiler"</span>
<span class="c"> xsi:schemaLocation="http://symfony.com/schema/dic/webprofiler</span>
<span class="c"> http://symfony.com/schema/dic/webprofiler/webprofiler-1.0.xsd"></span>
<span class="c">--></span>
<span class="nt"><webprofiler:config</span>
<span class="na">intercept-redirects=</span><span class="s">"true"</span>
<span class="nt">/></span>
</pre></div>
</div>
</li>
<li><em>PHP</em><div class="highlight-php"><div class="highlight"><pre><span class="c1">// app/config/config_dev.php</span>
<span class="nv">$container</span><span class="o">-></span><span class="na">loadFromExtension</span><span class="p">(</span><span class="s1">'web_profiler'</span><span class="p">,</span> <span class="k">array</span><span class="p">(</span>
<span class="s1">'intercept_redirects'</span> <span class="o">=></span> <span class="s1">'true'</span><span class="p">,</span>
<span class="p">));</span>
</pre></div>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar">
<div class="sphinxsidebarwrapper">
<h3><a href="../../index.html">Table Of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">How to Work with Emails During Development</a><ul>
<li><a class="reference internal" href="#disabling-sending">Disabling Sending</a></li>
<li><a class="reference internal" href="#sending-to-a-specified-address">Sending to a Specified Address</a></li>
<li><a class="reference internal" href="#viewing-from-the-web-debug-toolbar">Viewing from the Web Debug Toolbar</a></li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="gmail.html"
title="previous chapter">How to use Gmail to send Emails</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="spool.html"
title="next chapter">How to Spool Email</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../../_sources/cookbook/email/dev_environment.txt"
rel="nofollow">Show Source</a></li>
</ul>
<div id="searchbox" style="display: none">
<h3>Quick search</h3>
<form class="search" action="../../search.html" method="get">
<input type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
<p class="searchtip" style="font-size: 90%">
Enter search terms or a module, class or function name.
</p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../../genindex.html" title="General Index"
>index</a></li>
<li class="right" >
<a href="spool.html" title="How to Spool Email"
>next</a> |</li>
<li class="right" >
<a href="gmail.html" title="How to use Gmail to send Emails"
>previous</a> |</li>
<li><a href="../../index.html">Symfony2Docs v2.1.0 2.1.0 documentation</a> »</li>
<li><a href="../index.html" >The Cookbook</a> »</li>
<li><a href="index.html" >Email</a> »</li>
</ul>
</div>
<div class="footer">
© Copyright 2012, Symfony Team.
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.1.3.
</div>
</body>
</html> | P3PO/the-phpjs-local-docs-collection | symfony2/docs-en/v2.1.0/cookbook/email/dev_environment.html | HTML | gpl-3.0 | 17,028 |
/*
FreeRTOS V7.3.0 - Copyright (C) 2012 Real Time Engineers Ltd.
FEATURES AND PORTS ARE ADDED TO FREERTOS ALL THE TIME. PLEASE VISIT
http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
***************************************************************************
* *
* FreeRTOS tutorial books are available in pdf and paperback. *
* Complete, revised, and edited pdf reference manuals are also *
* available. *
* *
* Purchasing FreeRTOS documentation will not only help you, by *
* ensuring you get running as quickly as possible and with an *
* in-depth knowledge of how to use FreeRTOS, it will also help *
* the FreeRTOS project to continue with its mission of providing *
* professional grade, cross platform, de facto standard solutions *
* for microcontrollers - completely free of charge! *
* *
* >>> See http://www.FreeRTOS.org/Documentation for details. <<< *
* *
* Thank you for using FreeRTOS, and thank you for your support! *
* *
***************************************************************************
This file is part of the FreeRTOS distribution.
FreeRTOS is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License (version 2) as published by the
Free Software Foundation AND MODIFIED BY the FreeRTOS exception.
>>>NOTE<<< The modification to the GPL is included to allow you to
distribute a combined work that includes FreeRTOS without being obliged to
provide the source code for proprietary components outside of the FreeRTOS
kernel. FreeRTOS 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 and the FreeRTOS license exception along with FreeRTOS; if not it
can be viewed here: http://www.freertos.org/a00114.html and also obtained
by writing to Richard Barry, contact details for whom are available on the
FreeRTOS WEB site.
1 tab == 4 spaces!
***************************************************************************
* *
* Having a problem? Start by reading the FAQ "My application does *
* not run, what could be wrong?" *
* *
* http://www.FreeRTOS.org/FAQHelp.html *
* *
***************************************************************************
http://www.FreeRTOS.org - Documentation, training, latest versions, license
and contact details.
http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
including FreeRTOS+Trace - an indispensable productivity tool.
Real Time Engineers ltd license FreeRTOS to High Integrity Systems, who sell
the code with commercial support, indemnification, and middleware, under
the OpenRTOS brand: http://www.OpenRTOS.com. High Integrity Systems also
provide a safety engineered and independently SIL3 certified version under
the SafeRTOS brand: http://www.SafeRTOS.com.
*/
#ifndef PORTMACRO_H
#define PORTMACRO_H
#ifdef __cplusplus
extern "C" {
#endif
/*-----------------------------------------------------------
* Port specific definitions.
*
* The settings in this file configure FreeRTOS correctly for the
* given hardware and compiler.
*
* These settings should not be altered.
*-----------------------------------------------------------
*/
/* Type definitions. */
#define portCHAR char
#define portFLOAT float
#define portDOUBLE double
#define portLONG long
#define portSHORT short
#define portSTACK_TYPE unsigned long
#define portBASE_TYPE long
#if( configUSE_16_BIT_TICKS == 1 )
typedef unsigned portSHORT portTickType;
#define portMAX_DELAY ( portTickType ) 0xffff
#else
typedef unsigned portLONG portTickType;
#define portMAX_DELAY ( portTickType ) 0xffffffff
#endif
/*-----------------------------------------------------------*/
/* Hardware specifics. */
#define portBYTE_ALIGNMENT 4
#define portSTACK_GROWTH -1
#define portTICK_RATE_MS ( ( portTickType ) 1000 / configTICK_RATE_HZ )
/*-----------------------------------------------------------*/
unsigned portLONG ulPortSetIPL( unsigned portLONG );
#define portDISABLE_INTERRUPTS() ulPortSetIPL( configMAX_SYSCALL_INTERRUPT_PRIORITY )
#define portENABLE_INTERRUPTS() ulPortSetIPL( 0 )
extern void vPortEnterCritical( void );
extern void vPortExitCritical( void );
#define portENTER_CRITICAL() vPortEnterCritical()
#define portEXIT_CRITICAL() vPortExitCritical()
extern unsigned portBASE_TYPE uxPortSetInterruptMaskFromISR( void );
extern void vPortClearInterruptMaskFromISR( unsigned portBASE_TYPE );
#define portSET_INTERRUPT_MASK_FROM_ISR() ulPortSetIPL( configMAX_SYSCALL_INTERRUPT_PRIORITY )
#define portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedStatusRegister ) ulPortSetIPL( uxSavedStatusRegister )
/*-----------------------------------------------------------*/
/* Task utilities. */
#define portNOP() asm volatile ( "nop" )
/* Note this will overwrite all other bits in the force register, it is done this way for speed. */
#define portYIELD() MCF_INTC0_INTFRCL = ( 1UL << configYIELD_INTERRUPT_VECTOR ); portNOP(); portNOP()
/*-----------------------------------------------------------*/
/* Task function macros as described on the FreeRTOS.org WEB site. */
#define portTASK_FUNCTION_PROTO( vFunction, pvParameters ) void vFunction( void *pvParameters ) __attribute__((noreturn))
#define portTASK_FUNCTION( vFunction, pvParameters ) void vFunction( void *pvParameters )
/*-----------------------------------------------------------*/
#define portEND_SWITCHING_ISR( xSwitchRequired ) if( xSwitchRequired != pdFALSE ) \
{ \
portYIELD(); \
}
#ifdef __cplusplus
}
#endif
#endif /* PORTMACRO_H */
| ilikecake/Rocket-controller | software/freertos/freertos/Source/portable/GCC/ColdFire_V2/portmacro.h | C | gpl-3.0 | 6,814 |
CREATE SEQUENCE S_J_OUTPUT_COMMANDS_1
MINVALUE 1
MAXVALUE 999999
INCREMENT BY 1
NOCYCLE
ORDER
CACHE 20
/
| snavaneethan1/jaffa-framework | jaffa-components-printing/source/sql/install/oracle/sequences/S_J_OUTPUT_COMMANDS_1.sql | SQL | gpl-3.0 | 117 |
package com.iota.iri.service.tipselection.impl;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.iota.iri.controllers.ApproveeViewModel;
import com.iota.iri.controllers.TransactionViewModel;
import com.iota.iri.model.Hash;
import com.iota.iri.service.snapshot.SnapshotProvider;
import com.iota.iri.service.tipselection.RatingCalculator;
import com.iota.iri.storage.Tangle;
/**
* Implementation of {@link RatingCalculator} that calculates the cumulative weight
* Calculates the weight recursively/on the fly for each transaction referencing {@code entryPoint}. <br>
* Works using DFS search for new hashes and a BFS calculation.
* Uses cached values to prevent double database lookup for approvers
*/
public class CumulativeWeightCalculator implements RatingCalculator {
private final Tangle tangle;
private final SnapshotProvider snapshotProvider;
/**
* Constructor for Cumulative Weight Calculator
*
* @param tangle Tangle object which acts as a database interface
* @param snapshotProvider accesses ledger's snapshots
*/
public CumulativeWeightCalculator(Tangle tangle, SnapshotProvider snapshotProvider) {
this.tangle = tangle;
this.snapshotProvider = snapshotProvider;
}
@Override
public Map<Hash, Integer> calculate(Hash entryPoint) throws Exception {
Map<Hash, Integer> hashWeightMap = calculateRatingDfs(entryPoint);
return hashWeightMap;
}
private Map<Hash, Integer> calculateRatingDfs(Hash entryPoint) throws Exception {
TransactionViewModel tvm = TransactionViewModel.fromHash(tangle, entryPoint);
int depth = tvm.snapshotIndex() > 0
? snapshotProvider.getLatestSnapshot().getIndex() - tvm.snapshotIndex() + 1
: 1;
// Estimated capacity per depth, assumes 5 minute gap in between milestones, at 3tps
Map<Hash, Integer> hashWeightMap = createTxHashToCumulativeWeightMap( 5 * 60 * 3 * depth);
Map<Hash, Set<Hash>> txToDirectApprovers = new HashMap<>();
Deque<Hash> stack = new ArrayDeque<>();
stack.addAll(getTxDirectApproversHashes(entryPoint, txToDirectApprovers));
while (!stack.isEmpty()) {
Hash txHash = stack.pollLast();
Set<Hash> approvers = getTxDirectApproversHashes(txHash, txToDirectApprovers);
// If its empty, its a tip!
if (approvers.isEmpty()) {
hashWeightMap.put(txHash, 1);
// Else we go deeper
} else {
// Add all approvers, given we didnt go there
for (Hash h : approvers) {
if (!hashWeightMap.containsKey(h)) {
stack.add(h);
}
}
// Add the tx to the approvers list to count itself as +1 weight, preventing self-referencing
approvers.add(txHash);
// calculate and add rating. Naturally the first time all approvers need to be looked up. Then its cached.
hashWeightMap.put(txHash, getRating(approvers, txToDirectApprovers));
}
}
// If we have a self-reference, its already added, otherwise we save a big calculation
if (!hashWeightMap.containsKey(entryPoint)) {
hashWeightMap.put(entryPoint, hashWeightMap.size() + 1);
}
return hashWeightMap;
}
/**
* Gets the rating of a set, calculated by checking its approvers
*
* @param startingSet All approvers of a certain hash, including the hash itself.
* Should always start with at least 1 hash.
* @param txToDirectApproversCache The cache of approvers, used to prevent double db lookups
* @return The weight, or rating, of the starting hash
* @throws Exception If we can't get the approvers
*/
private int getRating(Set<Hash> startingSet, Map<Hash, Set<Hash>> txToDirectApproversCache) throws Exception {
Deque<Hash> stack = new ArrayDeque<>(startingSet);
while (!stack.isEmpty()) {
Set<Hash> approvers = getTxDirectApproversHashes(stack.pollLast(), txToDirectApproversCache);
for (Hash hash : approvers) {
if (startingSet.add(hash)) {
stack.add(hash);
}
}
}
return startingSet.size();
}
/**
* Finds the approvers of a transaction, and adds it to the txToDirectApprovers map if they weren't there yet.
*
* @param txHash The tx we find the approvers of
* @param txToDirectApprovers The map we look in, and add to
* @param fallback The map we check in before going in the database, can be <code>null</code>
* @return A set with the direct approvers of the given hash
* @throws Exception
*/
private Set<Hash> getTxDirectApproversHashes(Hash txHash, Map<Hash, Set<Hash>> txToDirectApprovers)
throws Exception {
Set<Hash> txApprovers = txToDirectApprovers.get(txHash);
if (txApprovers == null) {
ApproveeViewModel approvers = ApproveeViewModel.load(tangle, txHash);
Collection<Hash> appHashes;
if (approvers == null || approvers.getHashes() == null) {
appHashes = Collections.emptySet();
} else {
appHashes = approvers.getHashes();
}
txApprovers = new HashSet<>(appHashes.size());
for (Hash appHash : appHashes) {
// if not genesis (the tx that confirms itself)
if (!snapshotProvider.getInitialSnapshot().hasSolidEntryPoint(appHash)) {
txApprovers.add(appHash);
}
}
txToDirectApprovers.put(txHash, txApprovers);
}
return new HashSet<Hash>(txApprovers);
}
private static Map<Hash, Integer> createTxHashToCumulativeWeightMap(int size) {
return new HashMap<Hash, Integer>(size); //new TransformingMap<>(size, HashPrefix::createPrefix, null);
}
}
| jserv/iri | src/main/java/com/iota/iri/service/tipselection/impl/CumulativeWeightCalculator.java | Java | gpl-3.0 | 6,343 |
/*
* Copyright (C) 2009-2010, Pino Toscano <pino@kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef POPPLER_DOCUMENT_H
#define POPPLER_DOCUMENT_H
#include "poppler-global.h"
#include "poppler-font.h"
namespace poppler
{
class document_private;
class embedded_file;
class page;
class toc;
class POPPLER_CPP_EXPORT document : public poppler::noncopyable
{
public:
enum page_mode_enum {
use_none,
use_outlines,
use_thumbs,
fullscreen,
use_oc,
use_attach
};
enum page_layout_enum {
no_layout,
single_page,
one_column,
two_column_left,
two_column_right,
two_page_left,
two_page_right
};
~document();
bool is_locked() const;
bool unlock(const std::string &owner_password, const std::string &user_password);
page_mode_enum page_mode() const;
page_layout_enum page_layout() const;
void get_pdf_version(int *major, int *minor) const;
std::vector<std::string> info_keys() const;
ustring info_key(const std::string &key) const;
time_type info_date(const std::string &key) const;
bool is_encrypted() const;
bool is_linearized() const;
bool has_permission(permission_enum which) const;
ustring metadata() const;
bool get_pdf_id(std::string *permanent_id, std::string *update_id) const;
int pages() const;
page* create_page(const ustring &label) const;
page* create_page(int index) const;
std::vector<font_info> fonts() const;
font_iterator* create_font_iterator(int start_page = 0) const;
toc* create_toc() const;
bool has_embedded_files() const;
std::vector<embedded_file *> embedded_files() const;
static document* load_from_file(const std::string &file_name,
const std::string &owner_password = std::string(),
const std::string &user_password = std::string());
static document* load_from_data(byte_array *file_data,
const std::string &owner_password = std::string(),
const std::string &user_password = std::string());
static document* load_from_raw_data(const char *file_data,
int file_data_length,
const std::string &owner_password = std::string(),
const std::string &user_password = std::string());
private:
document(document_private &dd);
document_private *d;
friend class document_private;
};
}
#endif
| fsouliers/Rekkix | win32_libs/poppler-0.45/include/poppler/cpp/poppler-document.h | C | gpl-3.0 | 3,392 |
#include "searchdialog.h"
#include "ui_searchdialog.h"
#include <QPlainTextEdit>
#include <QDebug>
/**
Object's constructor.
*/
SearchDialog::SearchDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SearchDialog)
{
ui->setupUi(this);
gbReplaceClicked = false;
gbSearchClicked = false;
gbReplaceAllClicked = false;
}
/**
Object's destructor.
*/
SearchDialog::~SearchDialog()
{
delete ui;
}
/**
Action triggered when the search button is clicked.
This will rise a flag, which will be used in the
setTextEdit method.
*/
void SearchDialog::on_searchDialog_searchButton_clicked()
{
gbSearchClicked = true;
emit(search_signal_getTextEditText());
}
/**
Action triggered when the replace button is clicked.
This will rise a flag, which will be used in the
setTextEdit method.
*/
void SearchDialog::on_searchDialog_replaceButton_clicked()
{
gbReplaceClicked = true;
emit(search_signal_getTextEditText());
}
/**
Action triggered when the replace all button is clicked.
This will rise a flag, which will be used in the
setTextEdit method.
*/
void SearchDialog::on_searchDialog_replaceAllButton_clicked()
{
gbReplaceAllClicked = true;
emit(search_signal_getTextEditText());
}
/**
Action triggered when the swap button is clicked.
This will swap the text into the "search" line edit, with the
text into the "reaplace all" line edit.
*/
void SearchDialog::on_gobSwapTextButton_clicked()
{
QString lsReplace;
lsReplace = this->ui->seachDialog_searchLineEdit->text();
this->ui->seachDialog_searchLineEdit->setText(this->ui->searchDialog_replaceLineEdit->text());
this->ui->searchDialog_replaceLineEdit->setText(lsReplace);
}
/**
Creates a copy of the TextEdit object, and dependign on
the clicked button, the according action modifications
will be made. Then, the new object will be send in a signal
to the main UI.
*/
void SearchDialog::search_slot_setTextEdit(QPlainTextEdit *textEdit)
{
this->gobTextEdit = textEdit;
QList<QTextEdit::ExtraSelection> extraSelections;
QTextEdit::ExtraSelection selection;
if(gbReplaceAllClicked){
emit(search_signal_disableFilescan());
gbReplaceAllClicked = false;
gobTextEdit->extraSelections().clear();
gobTextEdit->textCursor().clearSelection();
emit(search_signal_resetCursor());
gsFoundText = ui->seachDialog_searchLineEdit->text();
while(gobTextEdit->find(ui->seachDialog_searchLineEdit->text())){
selection.cursor = gobTextEdit->textCursor();
extraSelections.append(selection);
}
gobTextEdit->setExtraSelections(extraSelections);
QTextCursor cursor;
for(int i=0; i < extraSelections.length(); i++){
cursor = extraSelections.at(i).cursor;
cursor.insertText(ui->searchDialog_replaceLineEdit->text());
}
gsFoundText = "";
gobTextEdit->extraSelections().clear();
extraSelections.clear();
//qDebug() << "search: emitting enableFilescan SIGNAL";
emit(search_signal_enableFilescan());
}else if(gbSearchClicked){
gbSearchClicked = false;
QColor lineColor = QColor(Qt::darkGray).lighter(160);
selection.format.setBackground(lineColor);
selection.format.setForeground(QColor(0,0,0));
gobTextEdit->extraSelections().clear();
if(gsFoundText != ui->seachDialog_searchLineEdit->text()){
giOcurrencesFound = 0;
giLogCursorPos = 0;
//qDebug() << "searchDialog: Emmitting resetCursor SIGNAL";
emit(search_signal_resetCursor());
gsFoundText = ui->seachDialog_searchLineEdit->text();
while(gobTextEdit->find(ui->seachDialog_searchLineEdit->text())){
giOcurrencesFound ++;
selection.cursor = gobTextEdit->textCursor();
extraSelections.append(selection);
}
gobTextEdit->setExtraSelections(extraSelections);
//qDebug() << "searchDialog: Emmitting resetCursor SIGNAL";
emit(search_signal_resetCursor());
if(gobTextEdit->find(ui->seachDialog_searchLineEdit->text())){
ui->searchDialog_replaceButton->setEnabled(true);
giLogCursorPos = 1;
}
ui->ocurrencesCounterLabel->setText(QString("%1/%2").arg(giLogCursorPos).arg(giOcurrencesFound));
}else{
if(!gobTextEdit->find(ui->seachDialog_searchLineEdit->text())){
//qDebug() << "searchDialog: Emmitting resetCursor SIGNAL";
emit(search_signal_resetCursor());
giLogCursorPos = 0;
if(gobTextEdit->find(ui->seachDialog_searchLineEdit->text())){
giLogCursorPos ++;
}
}else{
ui->searchDialog_replaceButton->setEnabled(true);
giLogCursorPos ++;
}
ui->ocurrencesCounterLabel->setText(QString("%1/%2").arg(giLogCursorPos).arg(giOcurrencesFound));
}
}else if(gbReplaceClicked){
gbReplaceClicked = false;
if(gsFoundText == ui->seachDialog_searchLineEdit->text()){
gobTextEdit->textCursor().insertText(ui->searchDialog_replaceLineEdit->text());
}
ui->searchDialog_replaceButton->setEnabled(false);
}
}
| GTRONICK/CopyUtility | searchdialog.cpp | C++ | gpl-3.0 | 5,405 |
/**
* Copyright (c) 2002-2013 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j 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/>.
*/
package org.neo4j.kernel.impl.core;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
class RelationshipProxy implements Relationship
{
private final long relId;
private final NodeManager nm;
RelationshipProxy( long relId, NodeManager nodeManager )
{
this.relId = relId;
this.nm = nodeManager;
}
public long getId()
{
return relId;
}
public GraphDatabaseService getGraphDatabase()
{
return nm.getGraphDbService();
}
public void delete()
{
nm.getRelForProxy( relId ).delete( nm );
}
public Node[] getNodes()
{
return nm.getRelForProxy( relId ).getNodes( nm );
}
public Node getOtherNode( Node node )
{
return nm.getRelForProxy( relId ).getOtherNode( nm, node );
}
public Node getStartNode()
{
return nm.getRelForProxy( relId ).getStartNode( nm );
}
public Node getEndNode()
{
return nm.getRelForProxy( relId ).getEndNode( nm );
}
public RelationshipType getType()
{
return nm.getRelForProxy( relId ).getType( nm );
}
public Iterable<String> getPropertyKeys()
{
return nm.getRelForProxy( relId ).getPropertyKeys( nm );
}
public Iterable<Object> getPropertyValues()
{
return nm.getRelForProxy( relId ).getPropertyValues( nm );
}
public Object getProperty( String key )
{
return nm.getRelForProxy( relId ).getProperty( nm, key );
}
public Object getProperty( String key, Object defaultValue )
{
return nm.getRelForProxy( relId ).getProperty( nm, key, defaultValue );
}
public boolean hasProperty( String key )
{
return nm.getRelForProxy( relId ).hasProperty( nm, key );
}
public void setProperty( String key, Object property )
{
nm.getRelForProxy( relId ).setProperty( nm, key, property );
}
public Object removeProperty( String key )
{
return nm.getRelForProxy( relId ).removeProperty( nm, key );
}
public boolean isType( RelationshipType type )
{
return nm.getRelForProxy( relId ).isType( nm, type );
}
public int compareTo( Object rel )
{
Relationship r = (Relationship) rel;
long ourId = this.getId(), theirId = r.getId();
if ( ourId < theirId )
{
return -1;
}
else if ( ourId > theirId )
{
return 1;
}
else
{
return 0;
}
}
@Override
public boolean equals( Object o )
{
if ( !(o instanceof Relationship) )
{
return false;
}
return this.getId() == ((Relationship) o).getId();
}
@Override
public int hashCode()
{
return (int) (( relId >>> 32 ) ^ relId );
}
@Override
public String toString()
{
return "Relationship[" + this.getId() + "]";
}
} | neo4j-contrib/neo4j-mobile-android | neo4j-android/kernel-src/org/neo4j/kernel/impl/core/RelationshipProxy.java | Java | gpl-3.0 | 3,875 |
-----------------------------------
-- Area: Dynamis - Qufim (41)
-- Mob: Vanguard_s_Hecteyes
-----------------------------------
-- require("scripts/zones/Dynamis-Qufim/MobIDs");
-----------------------------------
-- onMobInitialize
-----------------------------------
function onMobInitialize(mob)
end;
-----------------------------------
-- onMobSpawn
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobFight
-----------------------------------
function onMobFight(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
end;
| Fatalerror66/ffxi-a | scripts/zones/Dynamis-Qufim/mobs/Vanguard_s_Hecteyes.lua | Lua | gpl-3.0 | 815 |
<h1 class="light-header"><span class="gray"><?php echo $GLOBALS["Language"]->New_Directory."</span> ". $absolutePathCurrentDirectory;?></h1>
<div class="panel-body">
<form class="form-horizontal" method="POST" action="?newfolder">
<div class="form-group">
<div class="alert alert-info"><?php
echo $GLOBALS["Language"]->multiple_dirs;
?>
</div>
<label for="pass" class="col-lg-3 control-label"><?php echo $GLOBALS["Language"]->New_Directory_Short;?></label>
<div class="col-lg-9">
<input type="text" class="form-control" name="directory" placeholder="<?php echo $GLOBALS["Language"]->New_Directory_Short;?>">
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-3 col-lg-9">
<input class = 'btn-block btn btn-default' type=submit name=submit value="<?php echo $GLOBALS["Language"]->New_Directory_Button;?>">
</div>
</div>
</form>
</div> | Redundancycloud/redundancy | nys/Views/NewFolder.php | PHP | gpl-3.0 | 883 |
/*****************************************************************************
* Copyright (c) 2014-2018 OpenRCT2 developers
*
* For a complete list of all authors, please refer to contributors.md
* Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2
*
* OpenRCT2 is licensed under the GNU General Public License version 3.
*****************************************************************************/
#pragma once
#include <string>
#include "../common.h"
#include "../peep/Peep.h"
#include "../world/Map.h"
#include "../world/Sprite.h"
class NetworkPacket;
class NetworkPlayer final
{
public:
uint8_t Id = 0;
std::string Name;
uint16_t Ping = 0;
uint8_t Flags = 0;
uint8_t Group = 0;
money32 MoneySpent = MONEY(0, 0);
uint32_t CommandsRan = 0;
int32_t LastAction = -999;
uint32_t LastActionTime = 0;
LocationXYZ16 LastActionCoord = {};
rct_peep* PickupPeep = nullptr;
int32_t PickupPeepOldX = LOCATION_NULL;
std::string KeyHash;
uint32_t LastDemolishRideTime = 0;
uint32_t LastPlaceSceneryTime = 0;
NetworkPlayer() = default;
void SetName(const std::string &name);
void Read(NetworkPacket &packet);
void Write(NetworkPacket &packet);
void AddMoneySpent(money32 cost);
};
| blackhand1001/OpenRCT2 | src/openrct2/network/NetworkPlayer.h | C | gpl-3.0 | 1,503 |
"""
Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com>
This file is part of RockStor.
RockStor is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
RockStor 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/>.
"""
from rest_framework.renderers import JSONRenderer
from rest_framework.response import Response
import rest_framework_custom as rfc
from storageadmin.util import handle_exception
from storageadmin.models import (Plugin, InstalledPlugin)
from storageadmin.serializers import PluginSerializer
import time
import logging
logger = logging.getLogger(__name__)
class PluginView(rfc.GenericView):
serializer_class = PluginSerializer
def get_queryset(self, *args, **kwargs):
return Plugin.objects.all()
#if 'available_plugins' in request.session:
# if request.session['available_plugins'] == None:
# request.session['available_plugins'] = ['backup']
#else:
# request.session['available_plugins'] = ['backup']
#if 'installed_plugins' in request.session:
# if request.session['installed_plugins'] == None:
# request.session['installed_plugins'] = []
#else:
# request.session['installed_plugins'] = []
#data = {
# 'installed': request.session['installed_plugins'],
# 'available': request.session['available_plugins']
# }
#return Response(data)
| kamal-gade/rockstor-core | src/rockstor/storageadmin/views/plugin.py | Python | gpl-3.0 | 1,928 |
/* This file is part of SparQ, a toolbox for qualitative spatial reasoning.
Copyright (C) 2006, 2007 SFB/TR 8 Spatial Cognition, Project R3-[Q-Shape]
More info at http://www.sfbtr8.spatial-cognition.de/project/r3/sparq/
SparQ is free software and has been released under the terms of the GNU
General Public License version 3 or later. 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 <vector>
#include <string>
#include <iostream>
#include <set>
#include "Misc.h"
#include "QTC.h"
using namespace std;
string symbols[] = { "-", "0", "+" };
// upper part of the composition rules table
string crtUpper[][17] = {
{ "00", "00", "00", "00", "00", "00", "00", "00", "00", "00", "00",
"00", "00", "00", "00", "00", "00" },
{ "-0", "-+", "-0", "+0", "--", "-+", "-+", "-+", "-+", "0+", "++",
"+-", "0-", "--", "--", "--", "--" },
{ "--", "-*", "--", "++", "*-", "-*", "-*", "-*", "-*", "-+", "*+",
"+*", "+-", "*-", "*-", "*-", "*-" },
{ "0-", "--", "0-", "0+", "+-", "--", "--", "--", "--", "-0", "-+",
"++", "+0", "+-", "+-", "+-", "+-" },
{ "+-", "*-", "+-", "-+", "+*", "*-", "*-", "*-", "*-", "--", "-*",
"*+", "++", "+*", "+*", "+*", "+*" },
{ "+0", "+-", "+0", "-0", "++", "+-", "+-", "+-", "+-", "0-", "--",
"-+", "0+", "++", "++", "++", "++" },
{ "++", "+*", "++", "--", "*+", "+*", "+*", "+*", "+*", "+-", "*-",
"-*", "-+", "*+", "*+", "*+", "*+" },
{ "0+", "++", "0+", "0-", "-+", "++", "++", "++", "++", "+0", "+-",
"--", "-0", "-+", "-+", "-+", "-+" },
{ "-+", "*+", "-+", "+-", "-*", "*+", "*+", "*+", "*+", "++", "+*",
"*-", "--", "-*", "-*", "-*", "-*" } };
// lower part of the composition rules table
string crtLower[][17] = {
{ "00", "00", "00", "00", "00", "00", "00", "00", "00", "00", "00",
"00", "00", "00", "00", "00", "00" },
{ "+0", "++", "-0", "+0", "+-", "++", "-+", "0+", "++", "++", "++",
"+-", "+-", "+-", "0-", "--", "+-" },
{ "++", "*+", "--", "++", "+*", "*+", "-*", "-+", "*+", "*+", "*+",
"+*", "+*", "+*", "+-", "*-", "+*" },
{ "0+", "-+", "0-", "0+", "++", "-+", "--", "-0", "-+", "-+", "-+",
"++", "++", "++", "+0", "+-", "++" },
{ "-+", "-*", "+-", "-+", "*+", "-*", "*-", "--", "-*", "-*", "-*",
"*+", "*+", "*+", "++", "+*", "*+" },
{ "-0", "--", "+0", "-0", "-+", "--", "+-", "0-", "--", "--", "--",
"-+", "-+", "-+", "0+", "++", "-+" },
{ "--", "*-", "++", "--", "-*", "*-", "+*", "+-", "*-", "*-", "*-",
"-*", "-*", "-*", "-+", "*+", "-*" },
{ "0-", "+-", "0+", "0-", "--", "+-", "++", "+0", "+-", "+-", "+-",
"--", "--", "--", "-0", "-+", "--" },
{ "+-", "+*", "-+", "+-", "*-", "+*", "*+", "++", "+*", "+*", "+*",
"*-", "*-", "*-", "--", "-*", "*-" } };
string figure45[] = { "90-270", "180-270", "180-360", "90-180", // 0-3
"180", "180-270", "0-180", "90-180", "90-270", "90-180", "X", // 4-10
"270-360", "90", "X", "270", "0-90", "X", "180-270", "0-180", // 11-18
"0-90", "-90-90", "0-90", "0", "270-360", " -90-90", "270-360", // 19-25
"180-360", "180-270", "270", "270-360", "X", "X", "X", "0-90", // 26-33
"90", "90-180", "180", "X", "0", "X", "all", "X", "0", "X", "180", // 34-44
"90-180", "90", "0-90", "X", "X", "X", "270-360", "270", "180-270", // 45-53
"180-360", "270-360", "-90-90", "270-360", "0", "0-90", "-90-90", // 54-60
"0-90", "0-180", "180-270", "X", "0-90", "270", "X", "90", // 61-68
"270-360", "X", "90-180", "90-270", "90-180", "0-180", "180-270", // 69-75
"180", "90-180", "180-360", "180-270", "90-270" }; // 76-80
/**
* returns corresponding row number in the upper CR-table for a given pair
* of symbols.
*
* @param s
* @return
*/
int selectRowUpper(string s) {
if (s == "00")
return 0;
else if (s == "-0")
return 1;
else if (s == "--")
return 2;
else if (s == "0-")
return 3;
else if (s == "+-")
return 4;
else if (s == "+0")
return 5;
else if (s == "++")
return 6;
else if (s == "0+")
return 7;
// Fall "-+"
else
return 8;
}
/**
* returns corresponding row number in the lower CR-table for a given pair
* of symbols.
*
* @param s
* @return
*/
int selectRowLower(string s) {
if (s == "00")
return 0;
else if (s == "+0")
return 1;
else if (s == "++")
return 2;
else if (s == "0+")
return 3;
else if (s == "-+")
return 4;
else if (s == "-0")
return 5;
else if (s == "--")
return 6;
else if (s == "0-")
return 7;
// Fall "+-"
else
return 8;
}
/**
* Select the column number of the composition rules table
*
* @param i
* @return
*/
int* selectColumn(string i)
{
if (i == "90-270")
{
static int a[] = { 6, 7, 8, 9, 10, 2, 3, 11, 12, 13, 14, 15, -1 };
int *p = a;
return p;
}
else if (i == "180-270")
{
static int a[] = { 11, 12, 13, 14, 15, -1 };
int *p = a;
return p;
}
else if (i == "180-360")
{
static int a[] = { 11, 12, 13, 14, 15, 4, 16, -1 };
int *p = a;
return p;
}
else if (i == "90-180")
{
static int a[] = { 6, 7, 8, 9, 10, -1 };
int *p = a;
return p;
}
else if (i == "180")
{
static int a[] = { 2, 3, -1 };
int *p = a;
return p;
}
else if (i == "X")
{
static int a[] = {-1};
int *p = a;
return p;
}
else if (i == "270-360")
{
static int a[] = { 16, -1 };
int *p = a;
return p;
}
else if (i == "90")
{
static int a[] = { 1, -1 };
int *p = a;
return p;
}
else if (i == "0-180")
{
static int a[] = { 5, 1, 6, 7, 8, 9, 10, -1 };
int *p = a;
return p;
}
else if (i == "0-90")
{
static int a[] = { 5, -1 };
int *p = a;
return p;
}
else if (i == "-90-90")
{
static int a[] = { 0, 5, 16, -1 };
int *p = a;
return p;
}
else if (i == "270")
{
static int a[] = { 4, -1 };
int *p = a;
return p;
}
else if (i == "all")
{
static int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
14, 15, 16, -1 };
int *p = a;
return p;
}
// Fall "0"
else
{
static int a[] = { 0, -1 };
int *p = a;
return p;
}
}
/**
* -, 0, + are converted to 0, 1, 2 respectively.
*
* @param c
* @return
*/
int toInt(char c) {
if (c == '-')
return 2;
else if (c == '0')
return 1;
else
return 0;
}
/**
* For a given QTC relation this method searches for a matching number in
* the figure 45
*
* @param s
* @return
*/
int findCellNr(string s) {
return 27 * toInt(s[0]) + 9 * toInt(s[1]) + 3
* toInt(s[2]) + toInt(s[3]) + 1;
}
/**
* The core method for the programme.
*
* @param r1
* @param r2
* @return
*/
std::set<string,Misc::conflt> lookUpTable(string r1, string r2) {
std::set<string,Misc::conflt> comp;
string tmpString = "";
int rowU = selectRowUpper(tmpString + r1[0] + r1[2]);
int rowL = selectRowLower(tmpString + r2[1] + r2[3]);
// Beware -1 at the end of the array-index
//printf("Figure 45: %s\n", figure45[findCellNr(tmpString + r1[1] + r2[0] + r1[3] + r2[2]) - 1].c_str());
int *column = selectColumn(figure45[findCellNr(tmpString + r1[1] + r2[0] + r1[3] + r2[2]) - 1]);
int i = 0;
while (column[i] != -1)
{
// d1 d2 are the distance relations of the resulting relation and
// o1, o2 are the orientation relations. The resulting relation
// should therefore look like "d1 d2 o1 o2".
string d_1 = "";
string d_2 = "";
string o_1 = "";
string o_2 = "";
d_1 = (crtUpper[rowU][column[i]])[0];
o_1 = (crtUpper[rowU][column[i]])[1];
d_2 = (crtLower[rowL][column[i]])[0];
o_2 = (crtLower[rowL][column[i]])[1];
vector<string> pool;
// The symbol "*" is expanded to -, 0 and +
if (d_1 == "*") {
for (int k = 0; k < 3; k++) {
pool.push_back(symbols[k]);
}
} else
pool.push_back(d_1);
if (d_2 == "*") {
vector<string> tmp;
for (int k = 0; k < 3; k++) {
for (vector<string>::size_type k1 = 0; k1 < pool.size(); k1++)
tmp.push_back(pool[k1] + symbols[k]);
}
pool = tmp;
} else {
vector<string> tmp;
for (vector<string>::size_type k1 = 0; k1 < pool.size(); k1++)
tmp.push_back(pool[k1] + d_2);
pool = tmp;
}
if (o_1 == "*") {
vector<string> tmp;
for (int k = 0; k < 3; k++) {
for (vector<string>::size_type k1 = 0; k1 < pool.size(); k1++)
tmp.push_back(pool[k1] + symbols[k]);
}
pool = tmp;
} else {
vector<string> tmp;
for (vector<string>::size_type k1 = 0; k1 < pool.size(); k1++)
tmp.push_back(pool[k1] + o_1);
pool = tmp;
}
if (o_2 == "*") {
vector<string> tmp;
for (int k = 0; k < 3; k++) {
for (vector<string>::size_type k1 = 0; k1 < pool.size(); k1++)
tmp.push_back(pool[k1] + symbols[k]);
}
pool = tmp;
} else {
vector<string> tmp;
for (vector<string>::size_type k1 = 0; k1 < pool.size(); k1++)
tmp.push_back(pool[k1] + o_2);
pool = tmp;
}
for (vector<string>::size_type k = 0; k < pool.size(); k++) {
comp.insert(pool[k]);
}
i++;
//printf( "CT (column %i=\"%s\"): %s\n", column[i], printComp(comp).c_str());;
}
return comp;
}
string printComp(std::set<string,Misc::conflt> table)
{
string comp = "";
set<string,Misc::conflt>::iterator pos = table.begin();
while (pos != table.end())
{
comp = comp + *pos + " ";
pos++;
}
return comp;
}
string getQTCcomposition( string r1, string r2 ){
return printComp(lookUpTable(r1,r2));
}
//Now defined in Interface
/*string qtc_c22_composition( string r1, string r2) {
return lookUpTable( r1, r2 );
}
string qtc_c21_composition( string r1, string r2) {
return lookUpTable( r1, r2 );
}
*/
/*
int main( int argc, char ** argv ) {
string r1, r2;
if (argc==3) {
r1 = argv[1];
r2 = argv[2];
cout << printComp(lookUpTable(argv[1], argv[2])) << endl;
}
return 0;
}
*/
| marcovzla/sparq | Lib/Source/qtc/QTC.cpp | C++ | gpl-3.0 | 10,358 |
/*!
* \file string_converter.cc
* \brief Implementation of a class that interprets the contents of a string
* and converts it into different types.
* \author Carlos Aviles, 2010. carlos.avilesr(at)googlemail.com
*
* -----------------------------------------------------------------------------
*
* GNSS-SDR is a Global Navigation Satellite System software-defined receiver.
* This file is part of GNSS-SDR.
*
* Copyright (C) 2010-2020 (see AUTHORS file for a list of contributors)
* SPDX-License-Identifier: GPL-3.0-or-later
*
* -----------------------------------------------------------------------------
*/
#include "string_converter.h"
#include <sstream>
bool StringConverter::convert(const std::string& value, bool default_value)
{
if (value == "true")
{
return true;
}
if (value == "false")
{
return false;
}
return default_value;
}
int64_t StringConverter::convert(const std::string& value, int64_t default_value)
{
std::stringstream stream(value);
int64_t result;
stream >> result;
if (stream.fail())
{
return default_value;
}
return result;
}
uint64_t StringConverter::convert(const std::string& value, uint64_t default_value)
{
std::stringstream stream(value);
uint64_t result;
stream >> result;
if (stream.fail())
{
return default_value;
}
return result;
}
int32_t StringConverter::convert(const std::string& value, int32_t default_value)
{
std::stringstream stream(value);
int result;
stream >> result;
if (stream.fail())
{
return default_value;
}
return result;
}
uint32_t StringConverter::convert(const std::string& value, uint32_t default_value)
{
std::stringstream stream(value);
uint32_t result;
stream >> result;
if (stream.fail())
{
return default_value;
}
return result;
}
uint16_t StringConverter::convert(const std::string& value, uint16_t default_value)
{
std::stringstream stream(value);
uint16_t result;
stream >> result;
if (stream.fail())
{
return default_value;
}
return result;
}
int16_t StringConverter::convert(const std::string& value, int16_t default_value)
{
std::stringstream stream(value);
int16_t result;
stream >> result;
if (stream.fail())
{
return default_value;
}
return result;
}
float StringConverter::convert(const std::string& value, float default_value)
{
std::stringstream stream(value);
float result;
stream >> result;
if (stream.fail())
{
return default_value;
}
return result;
}
double StringConverter::convert(const std::string& value, double default_value)
{
std::stringstream stream(value);
double result;
stream >> result;
if (stream.fail())
{
return default_value;
}
return result;
}
| gnss-sdr/gnss-sdr | src/core/libs/string_converter.cc | C++ | gpl-3.0 | 3,052 |
/*
* Vortex OpenSplice
*
* This software and documentation are Copyright 2006 to TO_YEAR ADLINK
* Technology Limited, its affiliated companies and licensors. All rights
* reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef OSPL_DDS_SUB_LOANEDSAMPLES_HPP_
#define OSPL_DDS_SUB_LOANEDSAMPLES_HPP_
/**
* @file
*/
/*
* OMG PSM class declaration
*/
#include <spec/dds/sub/LoanedSamples.hpp>
// Implementation
namespace dds
{
namespace sub
{
template <typename T, template <typename Q> class DELEGATE>
LoanedSamples<T, DELEGATE>::LoanedSamples() : delegate_(new DELEGATE<T>()) { }
template <typename T, template <typename Q> class DELEGATE>
LoanedSamples<T, DELEGATE>::~LoanedSamples() { }
template <typename T, template <typename Q> class DELEGATE>
LoanedSamples<T, DELEGATE>::LoanedSamples(const LoanedSamples& other)
{
delegate_ = other.delegate_;
}
template <typename T, template <typename Q> class DELEGATE>
typename LoanedSamples<T, DELEGATE>::const_iterator LoanedSamples<T, DELEGATE>::begin() const
{
return delegate()->begin();
}
template <typename T, template <typename Q> class DELEGATE>
typename LoanedSamples<T, DELEGATE>::const_iterator LoanedSamples<T, DELEGATE>::end() const
{
return delegate()->end();
}
template <typename T, template <typename Q> class DELEGATE>
const typename LoanedSamples<T, DELEGATE>::DELEGATE_REF_T& LoanedSamples<T, DELEGATE>::delegate() const
{
return delegate_;
}
template <typename T, template <typename Q> class DELEGATE>
typename LoanedSamples<T, DELEGATE>::DELEGATE_REF_T& LoanedSamples<T, DELEGATE>::delegate()
{
return delegate_;
}
template <typename T, template <typename Q> class DELEGATE>
uint32_t LoanedSamples<T, DELEGATE>::length() const
{
return delegate_->length();
}
}
}
// End of implementation
#endif /* OSPL_DDS_SUB_LOANEDSAMPLES_HPP_ */
| PrismTech/opensplice | src/api/dcps/isocpp/include/dds/sub/LoanedSamples.hpp | C++ | gpl-3.0 | 2,421 |
package com.encens.khipus.action.warehouse;
import com.encens.khipus.action.dashboard.PieGraphic;
import com.encens.khipus.action.dashboard.PieSemaphoreWidgetViewAction;
import com.encens.khipus.dashboard.component.sql.SqlQuery;
import com.encens.khipus.dashboard.module.warehouse.MinProductItemControlWidgetSql;
import com.encens.khipus.dashboard.util.SemaphoreState;
import com.encens.khipus.model.dashboard.Filter;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Create;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
/**
* Action to manage minimal product item control widget
* @author
* @version 3.3
*/
@Name("minProductItemControlWidgetAction")
@Scope(ScopeType.EVENT)
public class MinProductItemControlWidgetAction extends PieSemaphoreWidgetViewAction<PieGraphic> {
public static final String XML_WIDGET_ID = "21";
public static final String WIDGET_NAME = "minProductItemControlWidget";
private Integer businessUnitId;
@Create
public void initialize() {
super.initialize();
}
public void refresh() {
getGraphic();
}
public byte[] createChart() {
return getGraphic().createChart();
}
@Override
protected SqlQuery getSqlQueryInstance() {
return new MinProductItemControlWidgetSql();
}
@Override
protected void applyConfigurationFilter(Filter filter, SqlQuery sqlQuery) {
MinProductItemControlWidgetSql widgetSql = (MinProductItemControlWidgetSql) sqlQuery;
if (0 == filter.getIndex()) {
widgetSql.setSemaphoreState(SemaphoreState.GREEN);
} else if (1 == filter.getIndex()) {
widgetSql.setSemaphoreState(SemaphoreState.YELLOW);
} else if (2 == filter.getIndex()) {
widgetSql.setSemaphoreState(SemaphoreState.RED);
}
}
@Override
protected void setFilters(SqlQuery sqlQuery) {
((MinProductItemControlWidgetSql) sqlQuery).setBusinessUnitId(businessUnitId);
}
@Override
protected String getXmlWidgetId() {
return XML_WIDGET_ID;
}
@Override
public String getWidgetName() {
return WIDGET_NAME;
}
public void disableBusinessUnit() {
businessUnitId = null;
}
public void enableBusinessUnit(Integer businessUnitId) {
this.businessUnitId = businessUnitId;
}
}
| borboton13/sisk13 | src/main/com/encens/khipus/action/warehouse/MinProductItemControlWidgetAction.java | Java | gpl-3.0 | 2,390 |
#include<stdio.h>
#include<stdlib.h>
char a[102][102]={0};
int x,y;
int l[10000][2]={0},i,j=0,k=0,f=0;
int main()
{
int tx,ty,ans=0;
scanf("%d%d%d%d",&x,&y,&tx,&ty);
for(i=y-1;i>=0;i--)
scanf("%s",a[i]);
l[j][1]=tx-1;
l[j][0]=ty-1;
a[l[j][0]][l[j][1]]='/';
j++;
l[j][0]=-1234;
j++;
for(i=0;j>k;)
{
if(l[k][0]==-1234)
{
/*for(f=0;f<y;f++)
printf("%s\n",a[f]);
printf("\n");*/
i++;
k++;
l[j][0]=-1234;
j++;
if(j==k+1)break;
continue;
}
if(l[k][0]-1>=0&&a[l[k][0]-1][l[k][1]]=='.'){a[l[k][0]-1][l[k][1]]='/';l[j][0]=l[k][0]-1;l[j][1]=l[k][1];j++;}
if(l[k][1]-1>=0&&a[l[k][0]][l[k][1]-1]=='.'){a[l[k][0]][l[k][1]-1]='/';l[j][0]=l[k][0];l[j][1]=l[k][1]-1;j++;}
if(a[l[k][0]+1][l[k][1]]=='.'){a[l[k][0]+1][l[k][1]]='/';l[j][0]=l[k][0]+1;l[j][1]=l[k][1];j++;}
if(a[l[k][0]][l[k][1]+1]=='.'){a[l[k][0]][l[k][1]+1]='/';l[j][0]=l[k][0];l[j][1]=l[k][1]+1;j++;}
if(l[k][0]-1>=0&&l[k][1]-1>=0&&a[l[k][0]-1][l[k][1]-1]=='.'){a[l[k][0]-1][l[k][1]-1]='/';l[j][0]=l[k][0]-1;l[j][1]=l[k][1]-1;j++;}
if(l[k][0]-1>=0&&a[l[k][0]-1][l[k][1]+1]=='.'){a[l[k][0]-1][l[k][1]+1]='/';l[j][0]=l[k][0]-1;l[j][1]=l[k][1]+1;j++;}
if(l[k][1]-1>=0&&a[l[k][0]+1][l[k][1]-1]=='.'){a[l[k][0]+1][l[k][1]-1]='/';l[j][0]=l[k][0]+1;l[j][1]=l[k][1]-1;j++;}
if(a[l[k][0]+1][l[k][1]+1]=='.'){a[l[k][0]+1][l[k][1]+1]='/';l[j][0]=l[k][0]+1;l[j][1]=l[k][1]+1;j++;}
k++;
}
printf("%d\n",i-1);
//for(i=0;i<1000;i++)
// printf("%d %d\n",l[i][0],l[i][1]);
system("pause");
return 0;
}
| hxl9654/OI | oj/p1030乳草的入侵.cpp | C++ | gpl-3.0 | 1,841 |
/*
* This file is part of Bedspread, originally promoted and
* developed at CNR-IASI. For more information visit:
* http://leks.iasi.cnr.it/tools/bedspread
*
* This 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 software 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 source. If not, see <http://www.gnu.org/licenses/>.
*/
package it.cnr.iasi.leks.bedspread.rdf.impl;
import it.cnr.iasi.leks.bedspread.rdf.AnyResource;
import it.cnr.iasi.leks.bedspread.rdf.AnyURI;
import it.cnr.iasi.leks.bedspread.rdf.KnowledgeBase;
import it.cnr.iasi.leks.bedspread.rdf.URI;
import java.io.IOException;
import java.io.Reader;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.opencsv.CSVReader;
/**
*
* @author gulyx
*
*/
public class RDFGraph implements KnowledgeBase {
private HashMap<String, Set<RDFTriple>> subjectsMap;
private HashMap<String, Set<RDFTriple>> objectsMap;
private HashMap<String, Set<RDFTriple>> predicatesMap;
private RDFFactory rdfFactory;
private static final String TYPE_PREDICATE = "rdf:type";
public RDFGraph() {
this((Set<RDFTriple>) null);
}
public RDFGraph(RDFTriple triple) {
this(new HashSet<RDFTriple>());
}
public RDFGraph(Set<RDFTriple> s) {
this.rdfFactory = RDFFactory.getInstance();
this.subjectsMap = new HashMap<String, Set<RDFTriple>>();
this.objectsMap = new HashMap<String, Set<RDFTriple>>();
this.predicatesMap = new HashMap<String, Set<RDFTriple>>();
if (s != null) {
for (RDFTriple rdfTriple : s) {
String subject = rdfTriple.getTripleSubject().getResourceID();
String object = rdfTriple.getTripleObject().getResourceID();
String predicate = rdfTriple.getTriplePredicate().getResourceID();
this.populateMap(this.subjectsMap, rdfTriple, subject);
this.populateMap(this.objectsMap, rdfTriple, object);
this.populateMap(this.predicatesMap, rdfTriple, predicate);
}
}
}
public RDFGraph(Reader kbReader) throws IOException {
this();
CSVReader reader = new CSVReader(kbReader);
List<String[]> myEntries = reader.readAll();
AnyURI subject;
URI predicate;
AnyURI object;
for (String[] line : myEntries) {
subject = this.rdfFactory.createBlankNode(line[0]);
predicate = this.rdfFactory.createURI(line[1]);
object = this.rdfFactory.createBlankNode(line[2]);
RDFTriple triple = new RDFTriple(subject, predicate, object);
this.populateMap(this.subjectsMap, triple, subject.getResourceID());
this.populateMap(this.objectsMap, triple, object.getResourceID());
this.populateMap(this.predicatesMap, triple, predicate.getResourceID());
}
reader.close();
}
private void populateMap(HashMap<String, Set<RDFTriple>> map, RDFTriple rdfTriple, String term) {
Set<RDFTriple> set = null;
if (! map.containsKey(term)){
set = Collections.synchronizedSet(new HashSet<RDFTriple>());
map.put(term, set);
}else{
set = map.get(term);
}
set.add(rdfTriple);
}
public int degree(AnyResource resource) {
int count = 0;
String id = resource.getResourceID();
Set<RDFTriple> s = this.subjectsMap.get(id);
if (s != null){
count = s.size();
}
s = this.objectsMap.get(id);
if (s != null){
count += s.size();
}
return count;
}
public int depth(AnyResource resource) {
// TODO Auto-generated method stub
return 0;
}
public boolean isMemberof(AnyResource resource) {
String id = resource.getResourceID();
if (this.subjectsMap.containsKey(id)){
return true;
}
if (this.objectsMap.containsKey(id)){
return true;
}
if (this.predicatesMap.containsKey(id)){
return true;
}
return false;
}
public Set<AnyResource> getNeighborhood(AnyResource resource) {
Set<AnyResource> outputSet = Collections.synchronizedSet(new HashSet<AnyResource>());
String id = resource.getResourceID();
if (this.subjectsMap.containsKey(id)){
for (RDFTriple triple : this.subjectsMap.get(id)) {
if (! triple.getTriplePredicate().getResourceID().equals(TYPE_PREDICATE)){
outputSet.add(triple.getTripleObject());
}
}
}
if (this.objectsMap.containsKey(id)){
for (RDFTriple triple : this.objectsMap.get(id)) {
if (! triple.getTriplePredicate().getResourceID().equals(TYPE_PREDICATE)){
outputSet.add(triple.getTripleSubject());
}
}
}
return outputSet;
}
@Override
public Set<AnyResource> getPredicatesBySubjectAndObject(AnyResource subj, AnyResource obj) {
Set<AnyResource> result = new HashSet<AnyResource>();
Set<RDFTriple> triplesBySubject = subjectsMap.get(subj.getResourceID());
Set<RDFTriple> triplesByObject = objectsMap.get(obj.getResourceID());
if(triplesBySubject!=null && triplesByObject!=null)
for(RDFTriple t:triplesBySubject)
if(triplesByObject.contains(t))
result.add(t.getTriplePredicate());
return result;
}
@Override
public int countAllTriples() {
int result = 0;
for(String s:subjectsMap.keySet())
result = result + subjectsMap.get(s).size();
return result;
}
@Override
public int countTriplesByPredicate(AnyResource resource) {
int result = 0;
Set<RDFTriple> triples = predicatesMap.get(resource.getResourceID());
if(triples!=null)
result = triples.size();
return result;
}
@Override
public int countTriplesBySubjectOrObject(AnyResource resource) {
int result = 0;
Set<RDFTriple> triplesBySubject = subjectsMap.get(resource.getResourceID());
Set<RDFTriple> triplesByObject = objectsMap.get(resource.getResourceID());
if(triplesBySubject!=null)
result = triplesBySubject.size();
if(triplesByObject!=null)
for(RDFTriple t:triplesByObject)
if(triplesBySubject==null)
result ++;
else if(!(triplesBySubject.contains(t)))
result ++;
return result;
}
@Override
public int countTriplesByPredicateAndSubjectOrObject(AnyResource pred, AnyResource resource) {
int result = 0;
Set<RDFTriple> triplesByPredicates = objectsMap.get(resource.getResourceID());
if(triplesByPredicates!=null)
for(RDFTriple t:triplesByPredicates)
if((t.getTripleSubject().getResourceID().equals(resource.getResourceID())) ||
(t.getTripleObject().getResourceID().equals(resource.getResourceID())))
result ++;
return result;
}
@Override
public Set<AnyResource> getAllPredicates() {
Set<AnyResource> result = new HashSet<AnyResource>();
for(String id:predicatesMap.keySet())
result.add(RDFFactory.getInstance().createURI(id));
return result;
}
}
| IASI-LEKS/bedspread | bedspread-core/src/main/java/it/cnr/iasi/leks/bedspread/rdf/impl/RDFGraph.java | Java | gpl-3.0 | 7,034 |
#define tableau_entrer t->te
#define tableau_int t->ti
#define tableau_binaire t->tb
#define taille_tableau t->sot
#define tableau_sortie t->ts
#define taille_sortie t->sots
#define tableau_sortieH t->tsh
#define taille_sortieH t->sotsh
struct tabs_s
{
int sot; // size of tabs
char *te; //tabs entrée
int *ti; //tabs int
int *tb; //tab binaire
char *ts;
int sots;
int* tsh;
int sotsh;
};
typedef struct tabs_s *tabs;
struct code_s{
int* b;
char c;
int sob;
int id;
struct code_s *suivant;
};
typedef struct code_s *code;
typedef void* dont_now_type;
dont_now_type mem_remem_tabs(void *tab, char *type, int size);
tabs mem_taux(tabs t); | lahbabic/crypress | module_mem/module_mem.h | C | gpl-3.0 | 678 |
/*
* Vortex OpenSplice
*
* This software and documentation are Copyright 2006 to TO_YEAR ADLINK
* Technology Limited, its affiliated companies and licensors. All rights
* reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "Constants.h"
#include "os_if.h"
namespace DDS
{
const ::DDS::Duration_t DURATION_ZERO = {0L,0U};
const ::DDS::Duration_t DURATION_INFINITE = {DURATION_INFINITE_SEC, DURATION_INFINITE_NSEC};
const ::DDS::Time_t TIMESTAMP_INVALID = {TIMESTAMP_INVALID_SEC, TIMESTAMP_INVALID_NSEC};
const ::DDS::Time_t TIMESTAMP_CURRENT = {TIMESTAMP_INVALID_SEC, TIMESTAMP_INVALID_NSEC-1};
// Note: ANY_STATUS is deprecated, please use spec version specific constants.
const ::DDS::StatusKind ANY_STATUS = 0x7FFF;
// STATUS_MASK_ANY_V1_2 is all standardised status bits as of V1.2 of the
// specification.
const ::DDS::StatusKind STATUS_MASK_ANY_V1_2 = 0x7FFF;
const ::DDS::StatusKind STATUS_MASK_ANY = 0xFFFFFFFF;
const ::DDS::StatusKind STATUS_MASK_NONE = 0x0;
}
| PrismTech/opensplice | src/api/dcps/c++/common/code/Constants.cpp | C++ | gpl-3.0 | 1,652 |
from django.conf import settings
from django.conf.urls import patterns, url
from haystack.views import SearchView
from elections.forms import ElectionForm
from elections.views import ElectionsSearchByTagView, HomeView, ElectionDetailView,\
CandidateDetailView, SoulMateDetailView, FaceToFaceView, AreaDetailView, \
CandidateFlatPageDetailView, ElectionRankingView, QuestionsPerCandidateView
from sitemaps import *
from django.views.decorators.cache import cache_page
from elections.preguntales_views import MessageDetailView, ElectionAskCreateView, AnswerWebHook
media_root = getattr(settings, 'MEDIA_ROOT', '/')
new_answer_endpoint = r"^new_answer/%s/?$" % (settings.NEW_ANSWER_ENDPOINT)
sitemaps = {
'elections': ElectionsSitemap,
'candidates': CandidatesSitemap,
}
urlpatterns = patterns('',
url(new_answer_endpoint,AnswerWebHook.as_view(), name='new_answer_endpoint' ),
url(r'^/?$', cache_page(60 * settings.CACHE_MINUTES)(HomeView.as_view(template_name='elections/home.html')), name='home'),
url(r'^buscar/?$', SearchView(template='search.html',
form_class=ElectionForm), name='search'),
url(r'^busqueda_tags/?$', ElectionsSearchByTagView.as_view(), name='tags_search'),
url(r'^election/(?P<slug>[-\w]+)/?$',
cache_page(60 * settings.CACHE_MINUTES)(ElectionDetailView.as_view(template_name='elections/election_detail.html')),
name='election_view'),
url(r'^election/(?P<slug>[-\w]+)/questionary/?$',
cache_page(60 * settings.CACHE_MINUTES)(ElectionDetailView.as_view(template_name='elections/election_questionary.html')),
name='questionary_detail_view'),
#compare two candidates
url(r'^election/(?P<slug>[-\w]+)/face-to-face/(?P<slug_candidate_one>[-\w]+)/(?P<slug_candidate_two>[-\w]+)/?$',
cache_page(60 * settings.CACHE_MINUTES)(FaceToFaceView.as_view(template_name='elections/compare_candidates.html')),
name='face_to_face_two_candidates_detail_view'),
#one candidate for compare
url(r'^election/(?P<slug>[-\w]+)/face-to-face/(?P<slug_candidate_one>[-\w]+)/?$',
cache_page(60 * settings.CACHE_MINUTES)(ElectionDetailView.as_view(template_name='elections/compare_candidates.html')),
name='face_to_face_one_candidate_detail_view'),
#no one candidate
url(r'^election/(?P<slug>[-\w]+)/face-to-face/?$',
cache_page(60 * settings.CACHE_MINUTES)(ElectionDetailView.as_view(template_name='elections/compare_candidates.html')),
name='face_to_face_no_candidate_detail_view'),
#soulmate
url(r'^election/(?P<slug>[-\w]+)/soul-mate/?$',
SoulMateDetailView.as_view(template_name='elections/soulmate_candidate.html'),
name='soul_mate_detail_view'),
# Preguntales
url(r'^election/(?P<election_slug>[-\w]+)/messages/(?P<pk>\d+)/?$',
MessageDetailView.as_view(template_name='elections/message_detail.html'),
name='message_detail'),
#ranking
url(r'^election/(?P<slug>[-\w]+)/ranking/?$',
cache_page(60 * settings.CACHE_MINUTES)(ElectionRankingView.as_view(template_name='elections/ranking_candidates.html')),
name='ranking_view'),
url(r'^election/(?P<election_slug>[-\w]+)/(?P<slug>[-\w]+)/questions?$',
QuestionsPerCandidateView.as_view(template_name='elections/questions_per_candidate.html'),
name='questions_per_candidate'
),
#ask
url(r'^election/(?P<slug>[-\w]+)/ask/?$',
ElectionAskCreateView.as_view(template_name='elections/ask_candidate.html'),
name='ask_detail_view'),
url(r'^election/(?P<election_slug>[-\w]+)/(?P<slug>[-\w]+)/?$',
cache_page(60 * settings.CACHE_MINUTES)(CandidateDetailView.as_view(template_name='elections/candidate_detail.html')),
name='candidate_detail_view'
),
# End Preguntales
url(r'^election/(?P<election_slug>[-\w]+)/(?P<slug>[-\w]+)/(?P<url>[-\w]+)/?$',
cache_page(60 * settings.CACHE_MINUTES)(CandidateFlatPageDetailView.as_view()),
name='candidate_flatpage'
),
url(r'^election/(?P<slug>[-\w]+)/extra_info.html$',
ElectionDetailView.as_view(template_name='elections/extra_info.html'),
name='election_extra_info'),
url(r'^area/(?P<slug>[-\w]+)/?$',
AreaDetailView.as_view(template_name='elections/area.html'),
name='area'),
url(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}),
)
urlpatterns += patterns('',
url(r'^cache/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': media_root})
)
| YoQuieroSaber/votainteligente-portal-electoral | elections/urls.py | Python | gpl-3.0 | 4,564 |
/*
* Copyright 2000-2010 JetBrains s.r.o.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.community.intellij.plugins.communitycase.history.wholeTree;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.MultiMap;
/**
* @author irengrig
*/
public interface DetailsLoader {
void load(final MultiMap<VirtualFile,AbstractHash> hashes);
}
| codebling/CommunityCase | src/org/community/intellij/plugins/communitycase/history/wholeTree/DetailsLoader.java | Java | gpl-3.0 | 882 |
package com.taskadapter.redmineapi;
import com.taskadapter.redmineapi.bean.CustomFieldDefinition;
import com.taskadapter.redmineapi.internal.Transport;
import java.util.List;
/**
* Works with Custom Field Definitions (read-only at this moment).
* <p>Obtain it via RedmineManager:
* <pre>
RedmineManager mgr = RedmineManagerFactory.createWithUserAuth(redmineURI, login, password);
CustomFieldManager customFieldManager = mgr.getIssueManager();
* </pre>
*
* The current version only allows loading custom fields definition from the server (Redmine v. 1 through 3).
* You cannot create new Custom Field definitions through Redmine REST API. Please see http://www.redmine.org/issues/9664 for details.
*
* <p>Sample usage:
* <pre>
definitions = customFieldManager.getCustomFieldDefinitions();
* </pre>
*
* @see RedmineManager
*/
public class CustomFieldManager {
private final Transport transport;
CustomFieldManager(Transport transport) {
this.transport = transport;
}
/**
* Fetch custom field definitions from server.
*
* @throws com.taskadapter.redmineapi.RedmineException
* @since Redmine 2.4
* @return List of custom field definitions
*/
public List<CustomFieldDefinition> getCustomFieldDefinitions()
throws RedmineException {
return transport.getObjectsList(CustomFieldDefinition.class);
}
}
| ducyen/RedmineGanttProject | src/com/taskadapter/redmineapi/CustomFieldManager.java | Java | gpl-3.0 | 1,400 |
/*
Copyright (C) 2012 Abrt team.
Copyright (C) 2012 RedHat inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA
*/
#include "common.h"
#include <pygobject.h>
static char module_doc[] = "gnome-abrt's libreport & abrt wrappers";
static PyMethodDef module_methods[] = {
/* method_name, func, flags, doc_string */
{ "show_events_list_dialog", p_show_events_list_dialog, METH_VARARGS, "Open a dialog with event configurations" },
{ "show_problem_details_for_dir", p_show_problem_details_for_dir, METH_VARARGS, "Open a dialog with technical details" },
{ "get_app_for_cmdline", p_get_app_for_cmdline, METH_VARARGS, "Get the application for a specific command-line" },
{ "get_app_for_env", p_get_app_for_env, METH_VARARGS, "Get the application for a specific environment" },
{ NULL }
};
PyMODINIT_FUNC PyInit__wrappers(void)
{
PyObject *m;
static struct PyModuleDef moduledef = {
.m_base = PyModuleDef_HEAD_INIT,
.m_name = "_wrappers",
.m_doc = module_doc,
.m_size = -1,
.m_methods = module_methods,
/*.m_slots = NULL,*/
/*.m_traverse = NULL,*/
/*.m_clear = NULL,*/
/*.m_free = NULL,*/
};
m = PyModule_Create(&moduledef);
if (m == NULL)
return NULL;
Py_Initialize();
pygobject_init(-1, -1, -1);
return m;
}
| rluzynski/gnome-abrt | src/gnome_abrt/wrappers/module.c | C | gpl-3.0 | 2,064 |
../../../../../share/pyshared/twisted/python/urlpath.py | Alberto-Beralix/Beralix | i386-squashfs-root/usr/lib/python2.7/dist-packages/twisted/python/urlpath.py | Python | gpl-3.0 | 55 |
/**
* functions for creating major ui elements
*/
/**
* backbone model for icon buttons
*/
var IconButton = Backbone.Model.extend({
defaults: {
title : "",
icon_class : "",
on_click : null,
menu_options : null,
is_menu_button : true,
id : null,
href : null,
target : null,
enabled : true,
visible : true,
tooltip_config : {}
}
});
/**
* backbone view for icon buttons
*/
var IconButtonView = Backbone.View.extend({
initialize : function(){
// better rendering this way
this.model.attributes.tooltip_config = { placement : 'bottom' };
this.model.bind( 'change', this.render, this );
},
render : function( ){
// hide tooltip
this.$el.tooltip( 'hide' );
var new_elem = this.template( this.model.toJSON() );
// configure tooltip
new_elem.tooltip( this.model.get( 'tooltip_config' ));
this.$el.replaceWith( new_elem );
this.setElement( new_elem );
return this;
},
events : {
'click' : 'click'
},
click : function( event ){
// if on_click pass to that function
if( _.isFunction( this.model.get( 'on_click' ) ) ){
this.model.get( 'on_click' )( event );
return false;
}
// otherwise, bubble up ( to href or whatever )
return true;
},
// generate html element
template: function( options ){
var buffer = 'title="' + options.title + '" class="icon-button';
if( options.is_menu_button ){
buffer += ' menu-button';
}
buffer += ' ' + options.icon_class;
if( !options.enabled ){
buffer += '_disabled';
}
// close class tag
buffer += '"';
if( options.id ){
buffer += ' id="' + options.id + '"';
}
buffer += ' href="' + options.href + '"';
// add target for href
if( options.target ){
buffer += ' target="' + options.target + '"';
}
// set visibility
if( !options.visible ){
buffer += ' style="display: none;"';
}
// enabled/disabled
if ( options.enabled ){
buffer = '<a ' + buffer + '/>';
} else {
buffer = '<span ' + buffer + '/>';
}
// return element
return $( buffer );
}
} );
// define collection
var IconButtonCollection = Backbone.Collection.extend({
model: IconButton
});
/**
* menu with multiple icon buttons
* views are not needed nor used for individual buttons
*/
var IconButtonMenuView = Backbone.View.extend({
tagName: 'div',
initialize: function(){
this.render();
},
render: function(){
// initialize icon buttons
var self = this;
this.collection.each(function(button){
// create and add icon button to menu
var elt = $('<a/>')
.attr('href', 'javascript:void(0)')
.attr('title', button.attributes.title)
.addClass('icon-button menu-button')
.addClass(button.attributes.icon_class)
.appendTo(self.$el)
.click(button.attributes.on_click);
// configure tooltip
if (button.attributes.tooltip_config){
elt.tooltip(button.attributes.tooltip_config);
}
// add popup menu to icon
var menu_options = button.get('options');
if (menu_options){
make_popupmenu(elt, menu_options);
}
});
// return
return this;
}
});
/**
* Returns an IconButtonMenuView for the provided configuration.
* Configuration is a list of dictionaries where each dictionary
* defines an icon button. Each dictionary must have the following
* elements: icon_class, title, and on_click.
*/
var create_icon_buttons_menu = function(config, global_config)
{
// initialize global configuration
if (!global_config) global_config = {};
// create and initialize menu
var buttons = new IconButtonCollection(
_.map(config, function(button_config){
return new IconButton(_.extend(button_config, global_config));
})
);
// return menu
return new IconButtonMenuView( {collection: buttons} );
};
// =============================================================================
/**
*
*/
var Grid = Backbone.Collection.extend({
});
/**
*
*/
var GridView = Backbone.View.extend({
});
// =============================================================================
/**
* view for a popup menu
*/
var PopupMenu = Backbone.View.extend({
//TODO: maybe better as singleton off the Galaxy obj
/** Cache the desired button element and options, set up the button click handler
* NOTE: attaches this view as HTML/jQ data on the button for later use.
*/
initialize: function( $button, options ){
// default settings
this.$button = $button;
if( !this.$button.size() ){
this.$button = $( '<div/>' );
}
this.options = options || [];
// set up button click -> open menu behavior
var menu = this;
this.$button.click( function( event ){
// if there's already a menu open, remove it
$( '.popmenu-wrapper' ).remove();
menu._renderAndShow( event );
return false;
});
},
// render the menu, append to the page body at the click position, and set up the 'click-away' handlers, show
_renderAndShow: function( clickEvent ){
this.render();
this.$el.appendTo( 'body' ).css( this._getShownPosition( clickEvent )).show();
this._setUpCloseBehavior();
},
// render the menu
// this menu doesn't attach itself to the DOM ( see _renderAndShow )
render: function(){
// render the menu body absolute and hidden, fill with template
this.$el.addClass( 'popmenu-wrapper' ).hide()
.css({ position : 'absolute' })
.html( this.template( this.$button.attr( 'id' ), this.options ));
// set up behavior on each link/anchor elem
if( this.options.length ){
var menu = this;
//precondition: there should be one option per li
this.$el.find( 'li' ).each( function( i, li ){
var option = menu.options[i];
// if the option has 'func', call that function when the anchor is clicked
if( option.func ){
$( this ).children( 'a.popupmenu-option' ).click( function( event ){
option.func.call( menu, event, option );
// bubble up so that an option click will call the close behavior
//return false;
});
}
});
}
return this;
},
template : function( id, options ){
return [
'<ul id="', id, '-menu" class="dropdown-menu">', this._templateOptions( options ), '</ul>'
].join( '' );
},
_templateOptions : function( options ){
if( !options.length ){
return '<li>(no options)</li>';
}
return _.map( options, function( option ){
if( option.divider ){
return '<li class="divider"></li>';
} else if( option.header ){
return [ '<li class="head"><a href="javascript:void(0);">', option.html, '</a></li>' ].join( '' );
}
var href = option.href || 'javascript:void(0);',
target = ( option.target )?( ' target="' + option.target + '"' ):( '' ),
check = ( option.checked )?( '<span class="fa fa-check"></span>' ):( '' );
return [
'<li><a class="popupmenu-option" href="', href, '"', target, '>',
check, option.html,
'</a></li>'
].join( '' );
}).join( '' );
},
// get the absolute position/offset for the menu
_getShownPosition : function( clickEvent ){
// display menu horiz. centered on click...
var menuWidth = this.$el.width();
var x = clickEvent.pageX - menuWidth / 2 ;
// adjust to handle horiz. scroll and window dimensions ( draw entirely on visible screen area )
x = Math.min( x, $( document ).scrollLeft() + $( window ).width() - menuWidth - 5 );
x = Math.max( x, $( document ).scrollLeft() + 5 );
return {
top: clickEvent.pageY,
left: x
};
},
// bind an event handler to all available frames so that when anything is clicked
// the menu is removed from the DOM and the event handler unbinds itself
_setUpCloseBehavior: function(){
var menu = this;
//TODO: alternately: focus hack, blocking overlay, jquery.blockui
// function to close popup and unbind itself
function closePopup( event ){
$( document ).off( 'click.close_popup' );
if( window.parent !== window ){
try {
$( window.parent.document ).off( "click.close_popup" );
} catch( err ){}
} else {
try {
$( 'iframe#galaxy_main' ).contents().off( "click.close_popup" );
} catch( err ){}
}
menu.remove();
}
$( 'html' ).one( "click.close_popup", closePopup );
if( window.parent !== window ){
try {
$( window.parent.document ).find( 'html' ).one( "click.close_popup", closePopup );
} catch( err ){}
} else {
try {
$( 'iframe#galaxy_main' ).contents().one( "click.close_popup", closePopup );
} catch( err ){}
}
},
// add a menu option/item at the given index
addItem: function( item, index ){
// append to end if no index
index = ( index >= 0 ) ? index : this.options.length;
this.options.splice( index, 0, item );
return this;
},
// remove a menu option/item at the given index
removeItem: function( index ){
if( index >=0 ){
this.options.splice( index, 1 );
}
return this;
},
// search for a menu option by its html
findIndexByHtml: function( html ){
for( var i = 0; i < this.options.length; i++ ){
if( _.has( this.options[i], 'html' ) && ( this.options[i].html === html )){
return i;
}
}
return null;
},
// search for a menu option by its html
findItemByHtml: function( html ){
return this.options[( this.findIndexByHtml( html ))];
},
// string representation
toString: function(){
return 'PopupMenu';
}
});
/** shortcut to new for when you don't need to preserve the ref */
PopupMenu.create = function _create( $button, options ){
return new PopupMenu( $button, options );
};
// -----------------------------------------------------------------------------
// the following class functions are bridges from the original make_popupmenu and make_popup_menus
// to the newer backbone.js PopupMenu
/** Create a PopupMenu from simple map initial_options activated by clicking button_element.
* Converts initial_options to object array used by PopupMenu.
* @param {jQuery|DOMElement} button_element element which, when clicked, activates menu
* @param {Object} initial_options map of key -> values, where
* key is option text, value is fn to call when option is clicked
* @returns {PopupMenu} the PopupMenu created
*/
PopupMenu.make_popupmenu = function( button_element, initial_options ){
var convertedOptions = [];
_.each( initial_options, function( optionVal, optionKey ){
var newOption = { html: optionKey };
// keys with null values indicate: header
if( optionVal === null ){ // !optionVal? (null only?)
newOption.header = true;
// keys with function values indicate: a menu option
} else if( jQuery.type( optionVal ) === 'function' ){
newOption.func = optionVal;
}
//TODO:?? any other special optionVals?
// there was no divider option originally
convertedOptions.push( newOption );
});
return new PopupMenu( $( button_element ), convertedOptions );
};
/** Find all anchors in $parent (using selector) and covert anchors into a PopupMenu options map.
* @param {jQuery} $parent the element that contains the links to convert to options
* @param {String} selector jq selector string to find links
* @returns {Object[]} the options array to initialize a PopupMenu
*/
//TODO: lose parent and selector, pass in array of links, use map to return options
PopupMenu.convertLinksToOptions = function( $parent, selector ){
$parent = $( $parent );
selector = selector || 'a';
var options = [];
$parent.find( selector ).each( function( elem, i ){
var option = {}, $link = $( elem );
// convert link text to the option text (html) and the href into the option func
option.html = $link.text();
if( $link.attr( 'href' ) ){
var linkHref = $link.attr( 'href' ),
linkTarget = $link.attr( 'target' ),
confirmText = $link.attr( 'confirm' );
option.func = function(){
// if there's a "confirm" attribute, throw up a confirmation dialog, and
// if the user cancels - do nothing
if( ( confirmText ) && ( !confirm( confirmText ) ) ){ return; }
// if there's no confirm attribute, or the user accepted the confirm dialog:
switch( linkTarget ){
// relocate the center panel
case '_parent':
window.parent.location = linkHref;
break;
// relocate the entire window
case '_top':
window.top.location = linkHref;
break;
// relocate this panel
default:
window.location = linkHref;
}
};
}
options.push( option );
});
return options;
};
/** Create a single popupmenu from existing DOM button and anchor elements
* @param {jQuery} $buttonElement the element that when clicked will open the menu
* @param {jQuery} $menuElement the element that contains the anchors to convert into a menu
* @param {String} menuElementLinkSelector jq selector string used to find anchors to be made into menu options
* @returns {PopupMenu} the PopupMenu (Backbone View) that can render, control the menu
*/
PopupMenu.fromExistingDom = function( $buttonElement, $menuElement, menuElementLinkSelector ){
$buttonElement = $( $buttonElement );
$menuElement = $( $menuElement );
var options = PopupMenu.convertLinksToOptions( $menuElement, menuElementLinkSelector );
// we're done with the menu (having converted it to an options map)
$menuElement.remove();
return new PopupMenu( $buttonElement, options );
};
/** Create all popupmenus within a document or a more specific element
* @param {DOMElement} parent the DOM element in which to search for popupmenus to build (defaults to document)
* @param {String} menuSelector jq selector string to find popupmenu menu elements (defaults to "div[popupmenu]")
* @param {Function} buttonSelectorBuildFn the function to build the jq button selector.
* Will be passed $menuElement, parent.
* (Defaults to return '#' + $menuElement.attr( 'popupmenu' ); )
* @returns {PopupMenu[]} array of popupmenus created
*/
PopupMenu.make_popup_menus = function( parent, menuSelector, buttonSelectorBuildFn ){
parent = parent || document;
// orig. Glx popupmenu menus have a (non-std) attribute 'popupmenu'
// which contains the id of the button that activates the menu
menuSelector = menuSelector || 'div[popupmenu]';
// default to (orig. Glx) matching button to menu by using the popupmenu attr of the menu as the id of the button
buttonSelectorBuildFn = buttonSelectorBuildFn || function( $menuElement, parent ){
return '#' + $menuElement.attr( 'popupmenu' );
};
// aggregate and return all PopupMenus
var popupMenusCreated = [];
$( parent ).find( menuSelector ).each( function(){
var $menuElement = $( this ),
$buttonElement = $( parent ).find( buttonSelectorBuildFn( $menuElement, parent ) );
popupMenusCreated.push( PopupMenu.fromDom( $buttonElement, $menuElement ) );
$buttonElement.addClass( 'popup' );
});
return popupMenusCreated;
};
//==============================================================================
var faIconButton = function( options ){
//TODO: move out of global
options = options || {};
options.tooltipConfig = options.tooltipConfig || { placement: 'bottom' };
options.classes = [ 'icon-btn' ].concat( options.classes || [] );
if( options.disabled ){
options.classes.push( 'disabled' );
}
var html = [
'<a class="', options.classes.join( ' ' ), '"',
(( options.title )?( ' title="' + options.title + '"' ):( '' )),
(( !options.disabled && options.target )? ( ' target="' + options.target + '"' ):( '' )),
' href="', (( !options.disabled && options.href )?( options.href ):( 'javascript:void(0);' )), '">',
// could go with something less specific here - like 'html'
'<span class="fa ', options.faIcon, '"></span>',
'</a>'
].join( '' );
var $button = $( html ).tooltip( options.tooltipConfig );
if( _.isFunction( options.onclick ) ){
$button.click( options.onclick );
}
return $button;
};
//==============================================================================
function LoadingIndicator( $where, options ){
//TODO: move out of global
//TODO: too specific to history panel
var self = this;
// defaults
options = jQuery.extend({
cover : false
}, options || {} );
function render(){
var html = [
'<div class="loading-indicator">',
'<div class="loading-indicator-text">',
'<span class="fa fa-spinner fa-spin fa-lg"></span>',
'<span class="loading-indicator-message">loading...</span>',
'</div>',
'</div>'
].join( '\n' );
var $indicator = $( html ).hide().css( options.css || {
position : 'fixed'
}),
$text = $indicator.children( '.loading-indicator-text' );
if( options.cover ){
$indicator.css({
'z-index' : 2,
top : $where.css( 'top' ),
bottom : $where.css( 'bottom' ),
left : $where.css( 'left' ),
right : $where.css( 'right' ),
opacity : 0.5,
'background-color': 'white',
'text-align': 'center'
});
$text = $indicator.children( '.loading-indicator-text' ).css({
'margin-top' : '20px'
});
} else {
$text = $indicator.children( '.loading-indicator-text' ).css({
margin : '12px 0px 0px 10px',
opacity : '0.85',
color : 'grey'
});
$text.children( '.loading-indicator-message' ).css({
margin : '0px 8px 0px 0px',
'font-style' : 'italic'
});
}
return $indicator;
}
self.show = function( msg, speed, callback ){
msg = msg || 'loading...';
speed = speed || 'fast';
// remove previous
$where.parent().find( '.loading-indicator' ).remove();
// since position is fixed - we insert as sibling
self.$indicator = render().insertBefore( $where );
self.message( msg );
self.$indicator.fadeIn( speed, callback );
return self;
};
self.message = function( msg ){
self.$indicator.find( 'i' ).text( msg );
};
self.hide = function( speed, callback ){
speed = speed || 'fast';
if( self.$indicator && self.$indicator.size() ){
self.$indicator.fadeOut( speed, function(){
self.$indicator.remove();
if( callback ){ callback(); }
});
} else {
if( callback ){ callback(); }
}
return self;
};
return self;
}
//==============================================================================
(function(){
/** searchInput: (jQuery plugin)
* Creates a search input, a clear button, and loading indicator
* within the selected node.
*
* When the user either presses return or enters some minimal number
* of characters, a callback is called. Pressing ESC when the input
* is focused will clear the input and call a separate callback.
*/
var _l = window._l || function( s ){ return s; };
// contructor
function searchInput( parentNode, options ){
//TODO: consolidate with tool menu functionality, use there
var KEYCODE_ESC = 27,
KEYCODE_RETURN = 13,
$parentNode = $( parentNode ),
firstSearch = true,
defaults = {
initialVal : '',
name : 'search',
placeholder : 'search',
classes : '',
onclear : function(){},
onfirstsearch : null,
onsearch : function( inputVal ){},
minSearchLen : 0,
escWillClear : true,
oninit : function(){}
};
// .................................................................... input rendering and events
// visually clear the search, trigger an event, and call the callback
function clearSearchInput( event ){
var $input = $( this ).parent().children( 'input' );
//console.debug( this, 'clear', $input );
$input.focus().val( '' ).trigger( 'clear:searchInput' );
options.onclear();
}
// search for searchTerms, trigger an event, call the appropo callback (based on whether this is the first)
function search( event, searchTerms ){
//console.debug( this, 'searching', searchTerms );
$( this ).trigger( 'search:searchInput', searchTerms );
if( typeof options.onfirstsearch === 'function' && firstSearch ){
firstSearch = false;
options.onfirstsearch( searchTerms );
} else {
options.onsearch( searchTerms );
}
}
// .................................................................... input rendering and events
function inputTemplate(){
// class search-query is bootstrap 2.3 style that now lives in base.less
return [ '<input type="text" name="', options.name, '" placeholder="', options.placeholder, '" ',
'class="search-query ', options.classes, '" ', '/>' ].join( '' );
}
// the search input that responds to keyboard events and displays the search value
function $input(){
return $( inputTemplate() )
// select all text on a focus
.focus( function( event ){
$( this ).select();
})
// attach behaviors to esc, return if desired, search on some min len string
.keyup( function( event ){
event.preventDefault();
event.stopPropagation();
//TODO: doesn't work
if( !$( this ).val() ){ $( this ).blur(); }
// esc key will clear if desired
if( event.which === KEYCODE_ESC && options.escWillClear ){
clearSearchInput.call( this, event );
} else {
var searchTerms = $( this ).val();
// return key or the search string len > minSearchLen (if not 0) triggers search
if( ( event.which === KEYCODE_RETURN )
|| ( options.minSearchLen && searchTerms.length >= options.minSearchLen ) ){
search.call( this, event, searchTerms );
} else if( !searchTerms.length ){
clearSearchInput.call( this, event );
}
}
})
.val( options.initialVal );
}
// .................................................................... clear button rendering and events
// a button for clearing the search bar, placed on the right hand side
function $clearBtn(){
return $([ '<span class="search-clear fa fa-times-circle" ',
'title="', _l( 'clear search (esc)' ), '"></span>' ].join('') )
.tooltip({ placement: 'bottom' })
.click( function( event ){
clearSearchInput.call( this, event );
});
}
// .................................................................... loadingIndicator rendering
// a button for clearing the search bar, placed on the right hand side
function $loadingIndicator(){
return $([ '<span class="search-loading fa fa-spinner fa-spin" ',
'title="', _l( 'loading...' ), '"></span>' ].join('') )
.hide().tooltip({ placement: 'bottom' });
}
// .................................................................... commands
// visually swap the load, clear buttons
function toggleLoadingIndicator(){
$parentNode.find( '.search-loading' ).toggle();
$parentNode.find( '.search-clear' ).toggle();
}
// .................................................................... init
// string command (not constructor)
if( jQuery.type( options ) === 'string' ){
if( options === 'toggle-loading' ){
toggleLoadingIndicator();
}
return $parentNode;
}
// initial render
if( jQuery.type( options ) === 'object' ){
options = jQuery.extend( true, {}, defaults, options );
}
//NOTE: prepended
return $parentNode.addClass( 'search-input' ).prepend([ $input(), $clearBtn(), $loadingIndicator() ]);
}
// as jq plugin
jQuery.fn.extend({
searchInput : function $searchInput( options ){
return this.each( function(){
return searchInput( this, options );
});
}
});
}());
//==============================================================================
(function(){
/** Multi 'mode' button (or any element really) that changes the html
* contents of itself when clicked. Pass in an ordered list of
* objects with 'html' and (optional) onclick functions.
*
* When clicked in a particular node, the onclick function will
* be called (with the element as this) and the element will
* switch to the next mode, replacing its html content with
* that mode's html.
*
* If there is no next mode, the element will switch back to
* the first mode.
* @example:
* $( '.myElement' ).modeButton({
* modes : [
* {
* mode: 'bler',
* html: '<h5>Bler</h5>',
* onclick : function(){
* $( 'body' ).css( 'background-color', 'red' );
* }
* },
* {
* mode: 'bloo',
* html: '<h4>Bloo</h4>',
* onclick : function(){
* $( 'body' ).css( 'background-color', 'blue' );
* }
* },
* {
* mode: 'blah',
* html: '<h3>Blah</h3>',
* onclick : function(){
* $( 'body' ).css( 'background-color', 'grey' );
* }
* },
* ]
* });
* $( '.myElement' ).modeButton( 'callModeFn', 'bler' );
*/
/** constructor */
function ModeButton( element, options ){
this.currModeIndex = 0;
return this._init( element, options );
}
/** html5 data key to store this object inside an element */
ModeButton.prototype.DATA_KEY = 'mode-button';
/** default options */
ModeButton.prototype.defaults = {
switchModesOnClick : true
};
// ---- private interface
/** set up options, intial mode, and the click handler */
ModeButton.prototype._init = function _init( element, options ){
//console.debug( 'ModeButton._init:', element, options );
options = options || {};
this.$element = $( element );
this.options = jQuery.extend( true, {}, this.defaults, options );
if( !options.modes ){
throw new Error( 'ModeButton requires a "modes" array' );
}
var modeButton = this;
this.$element.click( function _ModeButtonClick( event ){
// call the curr mode fn
modeButton.callModeFn();
// inc the curr mode index
if( modeButton.options.switchModesOnClick ){ modeButton._incModeIndex(); }
// set the element html
$( this ).html( modeButton.options.modes[ modeButton.currModeIndex ].html );
});
return this.reset();
};
/** increment the mode index to the next in the array, looping back to zero if at the last */
ModeButton.prototype._incModeIndex = function _incModeIndex(){
this.currModeIndex += 1;
if( this.currModeIndex >= this.options.modes.length ){
this.currModeIndex = 0;
}
return this;
};
/** get the mode index in the modes array for the given key (mode name) */
ModeButton.prototype._getModeIndex = function _getModeIndex( modeKey ){
for( var i=0; i<this.options.modes.length; i+=1 ){
if( this.options.modes[ i ].mode === modeKey ){ return i; }
}
throw new Error( 'mode not found: ' + modeKey );
};
/** set the current mode to the one with the given index and set button html */
ModeButton.prototype._setModeByIndex = function _setModeByIndex( index ){
var newMode = this.options.modes[ index ];
if( !newMode ){
throw new Error( 'mode index not found: ' + index );
}
this.currModeIndex = index;
if( newMode.html ){
this.$element.html( newMode.html );
}
return this;
};
// ---- public interface
/** get the current mode object (not just the mode name) */
ModeButton.prototype.currentMode = function currentMode(){
return this.options.modes[ this.currModeIndex ];
};
/** return the mode key of the current mode */
ModeButton.prototype.current = function current(){
// sugar for returning mode name
return this.currentMode().mode;
};
/** get the mode with the given modeKey or the current mode if modeKey is undefined */
ModeButton.prototype.getMode = function getMode( modeKey ){
if( !modeKey ){ return this.currentMode(); }
return this.options.modes[( this._getModeIndex( modeKey ) )];
};
/** T/F if the button has the given mode */
ModeButton.prototype.hasMode = function hasMode( modeKey ){
try {
return !!this.getMode( modeKey );
} catch( err ){}
return false;
};
/** set the current mode to the mode with the given name */
ModeButton.prototype.setMode = function setMode( modeKey ){
return this._setModeByIndex( this._getModeIndex( modeKey ) );
};
/** reset to the initial mode */
ModeButton.prototype.reset = function reset(){
this.currModeIndex = 0;
if( this.options.initialMode ){
this.currModeIndex = this._getModeIndex( this.options.initialMode );
}
return this._setModeByIndex( this.currModeIndex );
};
/** manually call the click handler of the given mode */
ModeButton.prototype.callModeFn = function callModeFn( modeKey ){
var modeFn = this.getMode( modeKey ).onclick;
if( modeFn && jQuery.type( modeFn === 'function' ) ){
// call with the element as context (std jquery pattern)
return modeFn.call( this.$element.get(0) );
}
return undefined;
};
// as jq plugin
jQuery.fn.extend({
modeButton : function $modeButton( options ){
if( !this.size() ){ return this; }
//TODO: does map still work with jq multi selection (i.e. $( '.class-for-many-btns' ).modeButton)?
if( jQuery.type( options ) === 'object' ){
return this.map( function(){
var $this = $( this );
$this.data( 'mode-button', new ModeButton( $this, options ) );
return this;
});
}
var $first = $( this[0] ),
button = $first.data( 'mode-button' );
if( !button ){
throw new Error( 'modeButton needs an options object or string name of a function' );
}
if( button && jQuery.type( options ) === 'string' ){
var fnName = options;
if( button && jQuery.type( button[ fnName ] ) === 'function' ){
return button[ fnName ].apply( button, jQuery.makeArray( arguments ).slice( 1 ) );
}
}
return button;
}
});
}());
//==============================================================================
/**
* Template function that produces a bootstrap dropdown to replace the
* vanilla HTML select input. Pass in an array of options and an initial selection:
* $( '.my-div' ).append( dropDownSelect( [ 'option1', 'option2' ], 'option2' );
*
* When the user changes the selected option a 'change.dropdown-select' event will
* fire with both the jq event and the new selection text as arguments.
*
* Get the currently selected choice using:
* var userChoice = $( '.my-div .dropdown-select .dropdown-select-selected' ).text();
*
*/
function dropDownSelect( options, selected ){
// replacement for vanilla select element using bootstrap dropdowns instead
selected = selected || (( !_.isEmpty( options ) )?( options[0] ):( '' ));
var $select = $([
'<div class="dropdown-select btn-group">',
'<button type="button" class="btn btn-default">',
'<span class="dropdown-select-selected">' + selected + '</span>',
'</button>',
'</div>'
].join( '\n' ));
// if there's only one option, do not style/create as buttons, dropdown - use simple span
// otherwise, a dropdown displaying the current selection
if( options && options.length > 1 ){
$select.find( 'button' )
.addClass( 'dropdown-toggle' ).attr( 'data-toggle', 'dropdown' )
.append( ' <span class="caret"></span>' );
$select.append([
'<ul class="dropdown-menu" role="menu">',
_.map( options, function( option ){
return [
'<li><a href="javascript:void(0)">', option, '</a></li>'
].join( '' );
}).join( '\n' ),
'</ul>'
].join( '\n' ));
}
// trigger 'change.dropdown-select' when a new selection is made using the dropdown
function selectThis( event ){
var $this = $( this ),
$select = $this.parents( '.dropdown-select' ),
newSelection = $this.text();
$select.find( '.dropdown-select-selected' ).text( newSelection );
$select.trigger( 'change.dropdown-select', newSelection );
}
$select.find( 'a' ).click( selectThis );
return $select;
}
//==============================================================================
(function(){
/**
* Creates a three part bootstrap button group (key, op, value) meant to
* allow the user control of filters (e.g. { key: 'name', op: 'contains', value: 'my_history' })
*
* Each field uses a dropDownSelect (from ui.js) to allow selection
* (with the 'value' field appearing as an input when set to do so).
*
* Any change or update in any of the fields will trigger a 'change.filter-control'
* event which will be passed an object containing those fields (as the example above).
*
* Pass in an array of possible filter objects to control what the user can select.
* Each filter object should have:
* key : generally the attribute name on which to filter something
* ops : an array of 1 or more filter operations (e.g. [ 'is', '<', 'contains', '!=' ])
* values (optional) : an array of possible values for the filter (e.g. [ 'true', 'false' ])
* @example:
* $( '.my-div' ).filterControl({
* filters : [
* { key: 'name', ops: [ 'is exactly', 'contains' ] }
* { key: 'deleted', ops: [ 'is' ], values: [ 'true', 'false' ] }
* ]
* });
* // after initialization, you can prog. get the current value using:
* $( '.my-div' ).filterControl( 'val' )
*
*/
function FilterControl( element, options ){
return this.init( element, options );
}
/** the data key that this object will be stored under in the DOM element */
FilterControl.prototype.DATA_KEY = 'filter-control';
/** parses options, sets up instance vars, and does initial render */
FilterControl.prototype.init = function _init( element, options ){
options = options || { filters: [] };
this.$element = $( element ).addClass( 'filter-control btn-group' );
this.options = jQuery.extend( true, {}, this.defaults, options );
this.currFilter = this.options.filters[0];
return this.render();
};
/** render (or re-render) the controls on the element */
FilterControl.prototype.render = function _render(){
this.$element.empty()
.append([ this._renderKeySelect(), this._renderOpSelect(), this._renderValueInput() ]);
return this;
};
/** render the key dropDownSelect, bind a change event to it, and return it */
FilterControl.prototype._renderKeySelect = function __renderKeySelect(){
var filterControl = this;
var keys = this.options.filters.map( function( filter ){
return filter.key;
});
this.$keySelect = dropDownSelect( keys, this.currFilter.key )
.addClass( 'filter-control-key' )
.on( 'change.dropdown-select', function( event, selection ){
filterControl.currFilter = _.findWhere( filterControl.options.filters, { key: selection });
// when the filter/key changes, re-render the control entirely
filterControl.render()._triggerChange();
});
return this.$keySelect;
};
/** render the op dropDownSelect, bind a change event to it, and return it */
FilterControl.prototype._renderOpSelect = function __renderOpSelect(){
var filterControl = this,
ops = this.currFilter.ops;
//TODO: search for currOp in avail. ops: use that for selected if there; otherwise: first op
this.$opSelect = dropDownSelect( ops, ops[0] )
.addClass( 'filter-control-op' )
.on( 'change.dropdown-select', function( event, selection ){
filterControl._triggerChange();
});
return this.$opSelect;
};
/** render the value control, bind a change event to it, and return it */
FilterControl.prototype._renderValueInput = function __renderValueInput(){
var filterControl = this;
// if a values attribute is prov. on the filter - make this a dropdown; otherwise, use an input
if( this.currFilter.values ){
this.$valueSelect = dropDownSelect( this.currFilter.values, this.currFilter.values[0] )
.on( 'change.dropdown-select', function( event, selection ){
filterControl._triggerChange();
});
} else {
//TODO: allow setting a value type (mainly for which html5 input to use: range, number, etc.)
this.$valueSelect = $( '<input/>' ).addClass( 'form-control' )
.on( 'change', function( event, value ){
filterControl._triggerChange();
});
}
this.$valueSelect.addClass( 'filter-control-value' );
return this.$valueSelect;
};
/** return the current state/setting for the filter as a three key object: key, op, value */
FilterControl.prototype.val = function _val(){
var key = this.$element.find( '.filter-control-key .dropdown-select-selected' ).text(),
op = this.$element.find( '.filter-control-op .dropdown-select-selected' ).text(),
// handle either a dropdown or plain input
$value = this.$element.find( '.filter-control-value' ),
value = ( $value.hasClass( 'dropdown-select' ) )?( $value.find( '.dropdown-select-selected' ).text() )
:( $value.val() );
return { key: key, op: op, value: value };
};
// single point of change for change event
FilterControl.prototype._triggerChange = function __triggerChange(){
this.$element.trigger( 'change.filter-control', this.val() );
};
// as jq plugin
jQuery.fn.extend({
filterControl : function $filterControl( options ){
var nonOptionsArgs = jQuery.makeArray( arguments ).slice( 1 );
return this.map( function(){
var $this = $( this ),
data = $this.data( FilterControl.prototype.DATA_KEY );
if( jQuery.type( options ) === 'object' ){
data = new FilterControl( $this, options );
$this.data( FilterControl.prototype.DATA_KEY, data );
}
if( data && jQuery.type( options ) === 'string' ){
var fn = data[ options ];
if( jQuery.type( fn ) === 'function' ){
return fn.apply( data, nonOptionsArgs );
}
}
return this;
});
}
});
}());
//==============================================================================
(function(){
/** Builds (twitter bootstrap styled) pagination controls.
* If the totalDataSize is not null, a horizontal list of page buttons is displayed.
* If totalDataSize is null, two links ('Prev' and 'Next) are displayed.
* When pages are changed, a 'pagination.page-change' event is fired
* sending the event and the (0-based) page requested.
*/
function Pagination( element, options ){
/** the total number of pages */
this.numPages = null;
/** the current, active page */
this.currPage = 0;
return this.init( element, options );
}
/** data key under which this object will be stored in the element */
Pagination.prototype.DATA_KEY = 'pagination';
/** default options */
Pagination.prototype.defaults = {
/** which page to begin at */
startingPage : 0,
/** number of data per page */
perPage : 20,
/** the total number of data (null == unknown) */
totalDataSize : null,
/** size of current data on current page */
currDataSize : null
};
/** init the control, calc numPages if possible, and render
* @param {jQuery} the element that will contain the pagination control
* @param {Object} options a map containing overrides to the pagination default options
*/
Pagination.prototype.init = function _init( $element, options ){
options = options || {};
this.$element = $element;
this.options = jQuery.extend( true, {}, this.defaults, options );
this.currPage = this.options.startingPage;
if( this.options.totalDataSize !== null ){
this.numPages = Math.ceil( this.options.totalDataSize / this.options.perPage );
// limit currPage by numPages
if( this.currPage >= this.numPages ){
this.currPage = this.numPages - 1;
}
}
//console.debug( 'Pagination.prototype.init:', this.$element, this.currPage );
//console.debug( JSON.stringify( this.options ) );
// bind to data of element
this.$element.data( Pagination.prototype.DATA_KEY, this );
this._render();
return this;
};
/** helper to create a simple li + a combo */
function _make$Li( contents ){
return $([
'<li><a href="javascript:void(0);">', contents, '</a></li>'
].join( '' ));
}
/** render previous and next pagination buttons */
Pagination.prototype._render = function __render(){
// no data - no pagination
if( this.options.totalDataSize === 0 ){ return this; }
// only one page
if( this.numPages === 1 ){ return this; }
// when the number of pages are known, render each page as a link
if( this.numPages > 0 ){
this._renderPages();
this._scrollToActivePage();
// when the number of pages is not known, render previous or next
} else {
this._renderPrevNext();
}
return this;
};
/** render previous and next pagination buttons */
Pagination.prototype._renderPrevNext = function __renderPrevNext(){
var pagination = this,
$prev = _make$Li( 'Prev' ),
$next = _make$Li( 'Next' ),
$paginationContainer = $( '<ul/>' ).addClass( 'pagination pagination-prev-next' );
// disable if it either end
if( this.currPage === 0 ){
$prev.addClass( 'disabled' );
} else {
$prev.click( function(){ pagination.prevPage(); });
}
if( ( this.numPages && this.currPage === ( this.numPages - 1 ) )
|| ( this.options.currDataSize && this.options.currDataSize < this.options.perPage ) ){
$next.addClass( 'disabled' );
} else {
$next.click( function(){ pagination.nextPage(); });
}
this.$element.html( $paginationContainer.append([ $prev, $next ]) );
//console.debug( this.$element, this.$element.html() );
return this.$element;
};
/** render page links for each possible page (if we can) */
Pagination.prototype._renderPages = function __renderPages(){
// it's better to scroll the control and let the user see all pages
// than to force her/him to change pages in order to find the one they want (as traditional << >> does)
var pagination = this,
$scrollingContainer = $( '<div>' ).addClass( 'pagination-scroll-container' ),
$paginationContainer = $( '<ul/>' ).addClass( 'pagination pagination-page-list' ),
page$LiClick = function( ev ){
pagination.goToPage( $( this ).data( 'page' ) );
};
for( var i=0; i<this.numPages; i+=1 ){
// add html5 data tag 'page' for later click event handler use
var $pageLi = _make$Li( i + 1 ).attr( 'data-page', i ).click( page$LiClick );
// highlight the current page
if( i === this.currPage ){
$pageLi.addClass( 'active' );
}
//console.debug( '\t', $pageLi );
$paginationContainer.append( $pageLi );
}
return this.$element.html( $scrollingContainer.html( $paginationContainer ) );
};
/** scroll scroll-container (if any) to show the active page */
Pagination.prototype._scrollToActivePage = function __scrollToActivePage(){
// scroll to show active page in center of scrollable area
var $container = this.$element.find( '.pagination-scroll-container' );
// no scroll container : don't scroll
if( !$container.size() ){ return this; }
var $activePage = this.$element.find( 'li.active' ),
midpoint = $container.width() / 2;
//console.debug( $container, $activePage, midpoint );
$container.scrollLeft( $container.scrollLeft() + $activePage.position().left - midpoint );
return this;
};
/** go to a certain page */
Pagination.prototype.goToPage = function goToPage( page ){
if( page <= 0 ){ page = 0; }
if( this.numPages && page >= this.numPages ){ page = this.numPages - 1; }
if( page === this.currPage ){ return this; }
//console.debug( '\t going to page ' + page )
this.currPage = page;
this.$element.trigger( 'pagination.page-change', this.currPage );
//console.info( 'pagination:page-change', this.currPage );
this._render();
return this;
};
/** go to the previous page */
Pagination.prototype.prevPage = function prevPage(){
return this.goToPage( this.currPage - 1 );
};
/** go to the next page */
Pagination.prototype.nextPage = function nextPage(){
return this.goToPage( this.currPage + 1 );
};
/** return the current page */
Pagination.prototype.page = function page(){
return this.currPage;
};
// alternate constructor invocation
Pagination.create = function _create( $element, options ){
return new Pagination( $element, options );
};
// as jq plugin
jQuery.fn.extend({
pagination : function $pagination( options ){
var nonOptionsArgs = jQuery.makeArray( arguments ).slice( 1 );
// if passed an object - use that as an options map to create pagination for each selected
if( jQuery.type( options ) === 'object' ){
return this.map( function(){
Pagination.create( $( this ), options );
return this;
});
}
// (other invocations only work on the first element in selected)
var $firstElement = $( this[0] ),
previousControl = $firstElement.data( Pagination.prototype.DATA_KEY );
// if a pagination control was found for this element, either...
if( previousControl ){
// invoke a function on the pagination object if passed a string (the function name)
if( jQuery.type( options ) === 'string' ){
var fn = previousControl[ options ];
if( jQuery.type( fn ) === 'function' ){
return fn.apply( previousControl, nonOptionsArgs );
}
// if passed nothing, return the previously set control
} else {
return previousControl;
}
}
// if there is no control already set, return undefined
return undefined;
}
});
}());
//==============================================================================
/** Column selection using the peek display as the control.
* Adds rows to the bottom of the peek with clickable areas in each cell
* to allow the user to select columns.
* Column selection can be limited to a single column or multiple.
* (Optionally) adds a left hand column of column selection prompts.
* (Optionally) allows the column headers to be clicked/renamed
* and set to some initial value.
* (Optionally) hides comment rows.
* (Optionally) allows pre-selecting and disabling certain columns for
* each row control.
*
* Construct by selecting a peek table to be used with jQuery and
* calling 'peekControl' with options.
* Options must include a 'controls' array and can include other options
* listed below.
* @example:
* $( 'pre.peek' ).peekControl({
* columnNames : ["Chromosome", "Start", "Base", "", "", "Qual" ],
* controls : [
* { label: 'X Column', id: 'xColumn' },
* { label: 'Y Column', id: 'yColumn', selected: 2 },
* { label: 'ID Column', id: 'idColumn', selected: 4, disabled: [ 1, 5 ] },
* { label: 'Heatmap', id: 'heatmap', selected: [ 2, 4 ], disabled: [ 0, 1 ], multiselect: true,
* selectedText: 'Included', unselectedText: 'Excluded' }
* ],
* renameColumns : true,
* hideCommentRows : true,
* includePrompts : true,
* topLeftContent : 'Data sample:'
* }).on( 'peek-control.change', function( ev, selection ){
* console.info( 'new selection:', selection );
* //{ yColumn: 2 }
* }).on( 'peek-control.rename', function( ev, names ){
* console.info( 'column names', names );
* //[ 'Bler', 'Start', 'Base', '', '', 'Qual' ]
* });
*
* An event is fired when column selection is changed and the event
* is passed an object in the form: { the row id : the new selection value }.
* An event is also fired when the table headers are re-named and
* is passed the new array of column names.
*/
(function(){
/** option defaults */
var defaults = {
/** does this control allow renaming headers? */
renameColumns : false,
/** does this control allow renaming headers? */
columnNames : [],
/** the comment character used by the peek's datatype */
commentChar : '#',
/** should comment rows be shown or hidden in the peek */
hideCommentRows : false,
/** should a column of row control prompts be used */
includePrompts : true,
/** what is the content of the top left cell (often a title) */
topLeftContent : 'Columns:'
},
/** the string of the event fired when a control row changes */
CHANGE_EVENT = 'peek-control.change',
/** the string of the event fired when a column is renamed */
RENAME_EVENT = 'peek-control.rename',
/** class added to the pre.peek element (to allow css on just the control) */
PEEKCONTROL_CLASS = 'peek-control',
/** class added to the control rows */
ROW_CLASS = 'control',
/** class added to the left-hand cells that serve as row prompts */
PROMPT_CLASS = 'control-prompt',
/** class added to selected _cells_/tds */
SELECTED_CLASS = 'selected',
/** class added to disabled/un-clickable cells/tds */
DISABLED_CLASS = 'disabled',
/** class added to the clickable surface within a cell to select it */
BUTTON_CLASS = 'button',
/** class added to peek table header (th) cells to indicate they can be clicked and are renamable */
RENAMABLE_HEADER_CLASS = 'renamable-header',
/** the data key used for each cell to store the column index ('data-...') */
COLUMN_INDEX_DATA_KEY = 'column-index',
/** renamable header data key used to store the column name (w/o the number and dot: '1.Bler') */
COLUMN_NAME_DATA_KEY = 'column-name';
//TODO: not happy with pure functional here - rows should polymorph (multi, single, etc.)
//TODO: needs clean up, move handlers to outer scope
// ........................................................................
/** validate the control data sent in for each row */
function validateControl( control ){
if( control.disabled && jQuery.type( control.disabled ) !== 'array' ){
throw new Error( '"disabled" must be defined as an array of indeces: ' + JSON.stringify( control ) );
}
if( control.multiselect && control.selected && jQuery.type( control.selected ) !== 'array' ){
throw new Error( 'Mulitselect rows need an array for "selected": ' + JSON.stringify( control ) );
}
if( !control.label || !control.id ){
throw new Error( 'Peek controls need a label and id for each control row: ' + JSON.stringify( control ) );
}
if( control.disabled && control.disabled.indexOf( control.selected ) !== -1 ){
throw new Error( 'Selected column is in the list of disabled columns: ' + JSON.stringify( control ) );
}
return control;
}
/** build the inner control surface (i.e. button-like) */
function buildButton( control, columnIndex ){
return $( '<div/>' ).addClass( BUTTON_CLASS ).text( control.label );
}
/** build the basic (shared) cell structure */
function buildControlCell( control, columnIndex ){
var $td = $( '<td/>' )
.html( buildButton( control, columnIndex ) )
.attr( 'data-' + COLUMN_INDEX_DATA_KEY, columnIndex );
// disable if index in disabled array
if( control.disabled && control.disabled.indexOf( columnIndex ) !== -1 ){
$td.addClass( DISABLED_CLASS );
}
return $td;
}
/** set the text of the control based on selected/un */
function setSelectedText( $cell, control, columnIndex ){
var $button = $cell.children( '.' + BUTTON_CLASS );
if( $cell.hasClass( SELECTED_CLASS ) ){
$button.html( ( control.selectedText !== undefined )?( control.selectedText ):( control.label ) );
} else {
$button.html( ( control.unselectedText !== undefined )?( control.unselectedText ):( control.label ) );
}
}
/** build a cell for a row that only allows one selection */
function buildSingleSelectCell( control, columnIndex ){
// only one selection - selected is single index
var $cell = buildControlCell( control, columnIndex );
if( control.selected === columnIndex ){
$cell.addClass( SELECTED_CLASS );
}
setSelectedText( $cell, control, columnIndex );
// only add the handler to non-disabled controls
if( !$cell.hasClass( DISABLED_CLASS ) ){
$cell.click( function selectClick( ev ){
var $cell = $( this );
// don't re-select or fire event if already selected
if( !$cell.hasClass( SELECTED_CLASS ) ){
// only one can be selected - remove selected on all others, add it here
var $otherSelected = $cell.parent().children( '.' + SELECTED_CLASS ).removeClass( SELECTED_CLASS );
$otherSelected.each( function(){
setSelectedText( $( this ), control, columnIndex );
});
$cell.addClass( SELECTED_CLASS );
setSelectedText( $cell, control, columnIndex );
// fire the event from the table itself, passing the id and index of selected
var eventData = {},
key = $cell.parent().attr( 'id' ),
val = $cell.data( COLUMN_INDEX_DATA_KEY );
eventData[ key ] = val;
$cell.parents( '.peek' ).trigger( CHANGE_EVENT, eventData );
}
});
}
return $cell;
}
/** build a cell for a row that allows multiple selections */
function buildMultiSelectCell( control, columnIndex ){
var $cell = buildControlCell( control, columnIndex );
// multiple selection - selected is an array
if( control.selected && control.selected.indexOf( columnIndex ) !== -1 ){
$cell.addClass( SELECTED_CLASS );
}
setSelectedText( $cell, control, columnIndex );
// only add the handler to non-disabled controls
if( !$cell.hasClass( DISABLED_CLASS ) ){
$cell.click( function multiselectClick( ev ){
var $cell = $( this );
// can be more than one selected - toggle selected on this cell
$cell.toggleClass( SELECTED_CLASS );
setSelectedText( $cell, control, columnIndex );
var selectedColumnIndeces = $cell.parent().find( '.' + SELECTED_CLASS ).map( function( i, e ){
return $( e ).data( COLUMN_INDEX_DATA_KEY );
});
// fire the event from the table itself, passing the id and index of selected
var eventData = {},
key = $cell.parent().attr( 'id' ),
val = jQuery.makeArray( selectedColumnIndeces );
eventData[ key ] = val;
$cell.parents( '.peek' ).trigger( CHANGE_EVENT, eventData );
});
}
return $cell;
}
/** iterate over columns in peek and create a control for each */
function buildControlCells( count, control ){
var $cells = [];
// build a control for each column - using a build fn based on control
for( var columnIndex=0; columnIndex<count; columnIndex+=1 ){
$cells.push( control.multiselect? buildMultiSelectCell( control, columnIndex )
: buildSingleSelectCell( control, columnIndex ) );
}
return $cells;
}
/** build a row of controls for the peek */
function buildControlRow( cellCount, control, includePrompts ){
var $controlRow = $( '<tr/>' ).attr( 'id', control.id ).addClass( ROW_CLASS );
if( includePrompts ){
var $promptCell = $( '<td/>' ).addClass( PROMPT_CLASS ).text( control.label + ':' );
$controlRow.append( $promptCell );
}
$controlRow.append( buildControlCells( cellCount, control ) );
return $controlRow;
}
// ........................................................................
/** add to the peek, using options for configuration, return the peek */
function peekControl( options ){
options = jQuery.extend( true, {}, defaults, options );
var $peek = $( this ).addClass( PEEKCONTROL_CLASS ),
$peektable = $peek.find( 'table' ),
// get the size of the tables - width and height, number of comment rows
columnCount = $peektable.find( 'th' ).size(),
rowCount = $peektable.find( 'tr' ).size(),
// get the rows containing text starting with the comment char (also make them grey)
$commentRows = $peektable.find( 'td[colspan]' ).map( function( e, i ){
var $this = $( this );
if( $this.text() && $this.text().match( new RegExp( '^' + options.commentChar ) ) ){
return $( this ).css( 'color', 'grey' ).parent().get(0);
}
return null;
});
// should comment rows in the peek be hidden?
if( options.hideCommentRows ){
$commentRows.hide();
rowCount -= $commentRows.size();
}
//console.debug( 'rowCount:', rowCount, 'columnCount:', columnCount, '$commentRows:', $commentRows );
// should a first column of control prompts be added?
if( options.includePrompts ){
var $topLeft = $( '<th/>' ).addClass( 'top-left' ).text( options.topLeftContent )
.attr( 'rowspan', rowCount );
$peektable.find( 'tr' ).first().prepend( $topLeft );
}
// save either the options column name or the parsed text of each column header in html5 data attr and text
var $headers = $peektable.find( 'th:not(.top-left)' ).each( function( i, e ){
var $this = $( this ),
// can be '1.name' or '1'
text = $this.text().replace( /^\d+\.*/, '' ),
name = options.columnNames[ i ] || text;
$this.attr( 'data-' + COLUMN_NAME_DATA_KEY, name )
.text( ( i + 1 ) + (( name )?( '.' + name ):( '' )) );
});
// allow renaming of columns when the header is clicked
if( options.renameColumns ){
$headers.addClass( RENAMABLE_HEADER_CLASS )
.click( function renameColumn(){
// prompt for new name
var $this = $( this ),
index = $this.index() + ( options.includePrompts? 0: 1 ),
prevName = $this.data( COLUMN_NAME_DATA_KEY ),
newColumnName = prompt( 'New column name:', prevName );
if( newColumnName !== null && newColumnName !== prevName ){
// set the new text and data
$this.text( index + ( newColumnName?( '.' + newColumnName ):'' ) )
.data( COLUMN_NAME_DATA_KEY, newColumnName )
.attr( 'data-', COLUMN_NAME_DATA_KEY, newColumnName );
// fire event for new column names
var columnNames = jQuery.makeArray(
$this.parent().children( 'th:not(.top-left)' ).map( function(){
return $( this ).data( COLUMN_NAME_DATA_KEY );
}));
$this.parents( '.peek' ).trigger( RENAME_EVENT, columnNames );
}
});
}
// build a row for each control
options.controls.forEach( function( control, i ){
validateControl( control );
var $controlRow = buildControlRow( columnCount, control, options.includePrompts );
$peektable.find( 'tbody' ).append( $controlRow );
});
return this;
}
// ........................................................................
// as jq plugin
jQuery.fn.extend({
peekControl : function $peekControl( options ){
return this.map( function(){
return peekControl.call( this, options );
});
}
});
}());
| mikel-egana-aranguren/SADI-Galaxy-Docker | galaxy-dist/static/scripts/mvc/ui.js | JavaScript | gpl-3.0 | 66,639 |
from couchpotato.core.event import addEvent
from couchpotato.core.helpers.variable import tryFloat
from couchpotato.core.logger import CPLog
from couchpotato.core.plugins.base import Plugin
from couchpotato.environment import Env
from urlparse import urlparse
import re
import time
log = CPLog(__name__)
class Provider(Plugin):
type = None # movie, nzb, torrent, subtitle, trailer
http_time_between_calls = 10 # Default timeout for url requests
last_available_check = {}
is_available = {}
def isAvailable(self, test_url):
if Env.get('dev'): return True
now = time.time()
host = urlparse(test_url).hostname
if self.last_available_check.get(host) < now - 900:
self.last_available_check[host] = now
try:
self.urlopen(test_url, 30)
self.is_available[host] = True
except:
log.error('"%s" unavailable, trying again in an 15 minutes.', host)
self.is_available[host] = False
return self.is_available.get(host, False)
class YarrProvider(Provider):
cat_ids = []
sizeGb = ['gb', 'gib']
sizeMb = ['mb', 'mib']
sizeKb = ['kb', 'kib']
def __init__(self):
addEvent('provider.belongs_to', self.belongsTo)
addEvent('%s.search' % self.type, self.search)
addEvent('yarr.search', self.search)
addEvent('nzb.feed', self.feed)
def download(self, url = '', nzb_id = ''):
return self.urlopen(url)
def feed(self):
return []
def search(self, movie, quality):
return []
def belongsTo(self, url, provider = None, host = None):
try:
if provider and provider == self.getName():
return self
hostname = urlparse(url).hostname
if host and hostname in host:
return self
else:
for url_type in self.urls:
download_url = self.urls[url_type]
if hostname in download_url:
return self
except:
log.debug('Url % s doesn\'t belong to %s', (url, self.getName()))
return
def parseSize(self, size):
sizeRaw = size.lower()
size = tryFloat(re.sub(r'[^0-9.]', '', size).strip())
for s in self.sizeGb:
if s in sizeRaw:
return size * 1024
for s in self.sizeMb:
if s in sizeRaw:
return size
for s in self.sizeKb:
if s in sizeRaw:
return size / 1024
return 0
def getCatId(self, identifier):
for cats in self.cat_ids:
ids, qualities = cats
if identifier in qualities:
return ids
return [self.cat_backup_id]
def found(self, new):
log.info('Found: score(%(score)s) on %(provider)s: %(name)s', new)
| darren-rogan/CouchPotatoServer | couchpotato/core/providers/base.py | Python | gpl-3.0 | 2,933 |
/*
* This file is part of HeavySpleef.
* Copyright (c) 2014-2016 Matthias Werning
*
* 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/>.
*/
package de.xaniox.heavyspleef.core.event;
import de.xaniox.heavyspleef.core.game.Game;
public class GameDisableEvent extends GameEvent {
public GameDisableEvent(Game game) {
super(game);
}
} | matzefratze123/HeavySpleef | heavyspleef-core/src/main/java/de/xaniox/heavyspleef/core/event/GameDisableEvent.java | Java | gpl-3.0 | 935 |
/*
This file is part of RailRoad.
RailRoad 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, version 3 of the License.
RailRoad 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 RailRoad. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __LOGIC_H__
#define __LOGIC_H__
#include "MailCar.h"
#include "Track.h"
class Logic {
public:
static void start_thread(void* t);
Logic(MailCar *output, MailCar *input, Track* track, atomic<bool>* exit, int debug);
~Logic();
void LogicLoop();
private:
MailCar* _inCar;
MailCar* _outCar;
Track* _track;
atomic<bool>* _exit;
int _debug;
};
#endif // __LOGIC_H__ | heritage902/railroad | src/Logic.h | C | gpl-3.0 | 1,062 |
<?php
declare(strict_types=1);
namespace League\HTMLToMarkdown\Converter;
use League\HTMLToMarkdown\ElementInterface;
interface ConverterInterface
{
public function convert(ElementInterface $element): string;
/**
* @return string[]
*/
public function getSupportedTags(): array;
}
| benbalter/wordpress-to-jekyll-exporter | vendor/league/html-to-markdown/src/Converter/ConverterInterface.php | PHP | gpl-3.0 | 307 |
// Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org)
import java.net.*;
import java.io.*;
import java.util.*;
import org.xbill.DNS.*;
import org.xbill.DNS.utils.*;
/** @author Brian Wellington <bwelling@xbill.org> */
public class update {
Message query, response;
Resolver res;
String server = null;
Name zone = Name.root;
long defaultTTL;
int defaultClass = DClass.IN;
PrintStream log = null;
void
print(Object o) {
System.out.println(o);
if (log != null)
log.println(o);
}
public
update(InputStream in) throws IOException {
List inputs = new LinkedList();
List istreams = new LinkedList();
query = new Message();
query.getHeader().setOpcode(Opcode.UPDATE);
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
inputs.add(br);
istreams.add(in);
while (true) {
try {
String line = null;
do {
InputStream is;
is = (InputStream)istreams.get(0);
br = (BufferedReader)inputs.get(0);
if (is == System.in)
System.out.print("> ");
line = br.readLine();
if (line == null) {
br.close();
inputs.remove(0);
istreams.remove(0);
if (inputs.isEmpty())
return;
}
} while (line == null);
if (log != null)
log.println("> " + line);
if (line.length() == 0 || line.charAt(0) == '#')
continue;
/* Allows cut and paste from other update sessions */
if (line.charAt(0) == '>')
line = line.substring(1);
Tokenizer st = new Tokenizer(line);
Tokenizer.Token token = st.get();
if (token.isEOL())
continue;
String operation = token.value;
if (operation.equals("server")) {
server = st.getString();
res = new SimpleResolver(server);
token = st.get();
if (token.isString()) {
String portstr = token.value;
res.setPort(Short.parseShort(portstr));
}
}
else if (operation.equals("key")) {
String keyname = st.getString();
String keydata = st.getString();
if (res == null)
res = new SimpleResolver(server);
res.setTSIGKey(keyname, keydata);
}
else if (operation.equals("edns")) {
if (res == null)
res = new SimpleResolver(server);
res.setEDNS(st.getUInt16());
}
else if (operation.equals("port")) {
if (res == null)
res = new SimpleResolver(server);
res.setPort(st.getUInt16());
}
else if (operation.equals("tcp")) {
if (res == null)
res = new SimpleResolver(server);
res.setTCP(true);
}
else if (operation.equals("class")) {
String classStr = st.getString();
int newClass = DClass.value(classStr);
if (newClass > 0)
defaultClass = newClass;
else
print("Invalid class " + classStr);
}
else if (operation.equals("ttl"))
defaultTTL = st.getTTL();
else if (operation.equals("origin") ||
operation.equals("zone"))
{
zone = st.getName(Name.root);
}
else if (operation.equals("require"))
doRequire(st);
else if (operation.equals("prohibit"))
doProhibit(st);
else if (operation.equals("add"))
doAdd(st);
else if (operation.equals("delete"))
doDelete(st);
else if (operation.equals("glue"))
doGlue(st);
else if (operation.equals("help") ||
operation.equals("?"))
{
token = st.get();
if (token.isString())
help(token.value);
else
help(null);
}
else if (operation.equals("echo"))
print(line.substring(4).trim());
else if (operation.equals("send")) {
sendUpdate();
query = new Message();
query.getHeader().setOpcode(Opcode.UPDATE);
}
else if (operation.equals("show")) {
print(query);
}
else if (operation.equals("clear")) {
query = new Message();
query.getHeader().setOpcode(Opcode.UPDATE);
}
else if (operation.equals("query"))
doQuery(st);
else if (operation.equals("quit") ||
operation.equals("q"))
{
if (log != null)
log.close();
Iterator it = inputs.iterator();
while (it.hasNext()) {
BufferedReader tbr;
tbr = (BufferedReader) it.next();
tbr.close();
}
System.exit(0);
}
else if (operation.equals("file"))
doFile(st, inputs, istreams);
else if (operation.equals("log"))
doLog(st);
else if (operation.equals("assert")) {
if (doAssert(st) == false)
return;
}
else if (operation.equals("sleep")) {
long interval = st.getUInt32();
try {
Thread.sleep(interval);
}
catch (InterruptedException e) {
}
}
else if (operation.equals("date")) {
Date now = new Date();
token = st.get();
if (token.isString() &&
token.value.equals("-ms"))
print(Long.toString(now.getTime()));
else
print(now);
}
else
print("invalid keyword: " + operation);
}
catch (TextParseException tpe) {
System.out.println(tpe.getMessage());
}
catch (NullPointerException npe) {
System.out.println("Parse error");
}
catch (InterruptedIOException iioe) {
System.out.println("Operation timed out");
}
catch (SocketException se) {
System.out.println("Socket error");
}
catch (IOException ioe) {
System.out.println(ioe);
}
}
}
void
sendUpdate() throws IOException {
if (query.getHeader().getCount(Section.UPDATE) == 0) {
print("Empty update message. Ignoring.");
return;
}
if (query.getHeader().getCount(Section.ZONE) == 0) {
Name updzone;
updzone = zone;
int dclass = defaultClass;
if (updzone == null) {
Record [] recs = query.getSectionArray(Section.UPDATE);
for (int i = 0; i < recs.length; i++) {
if (updzone == null)
updzone = new Name(recs[i].getName(),
1);
if (recs[i].getDClass() != DClass.NONE &&
recs[i].getDClass() != DClass.ANY)
{
dclass = recs[i].getDClass();
break;
}
}
}
Record soa = Record.newRecord(updzone, Type.SOA, dclass);
query.addRecord(soa, Section.ZONE);
}
if (res == null)
res = new SimpleResolver(server);
response = res.send(query);
print(response);
}
/*
* <name> [ttl] [class] <type> <data>
* Ignore the class, if present.
*/
Record
parseRR(Tokenizer st, int classValue, long TTLValue)
throws IOException
{
Name name = st.getName(zone);
long ttl;
int type;
Record record;
String s = st.getString();
try {
ttl = TTL.parseTTL(s);
s = st.getString();
}
catch (NumberFormatException e) {
ttl = TTLValue;
}
if (DClass.value(s) >= 0) {
classValue = DClass.value(s);
s = st.getString();
}
if ((type = Type.value(s)) < 0)
throw new IOException("Invalid type: " + s);
record = Record.fromString(name, type, classValue, ttl, st, zone);
if (record != null)
return (record);
else
throw new IOException("Parse error");
}
void
doRequire(Tokenizer st) throws IOException {
Tokenizer.Token token;
Name name;
Record record;
int type;
name = st.getName(zone);
token = st.get();
if (token.isString()) {
if ((type = Type.value(token.value)) < 0)
throw new IOException("Invalid type: " + token.value);
token = st.get();
boolean iseol = token.isEOL();
st.unget();
if (!iseol) {
record = Record.fromString(name, type, defaultClass,
0, st, zone);
} else
record = Record.newRecord(name, type,
DClass.ANY, 0);
} else
record = Record.newRecord(name, Type.ANY, DClass.ANY, 0);
query.addRecord(record, Section.PREREQ);
print(record);
}
void
doProhibit(Tokenizer st) throws IOException {
Tokenizer.Token token;
String s;
Name name;
Record record;
int type;
name = st.getName(zone);
token = st.get();
if (token.isString()) {
if ((type = Type.value(token.value)) < 0)
throw new IOException("Invalid type: " + token.value);
} else
type = Type.ANY;
record = Record.newRecord(name, type, DClass.NONE, 0);
query.addRecord(record, Section.PREREQ);
print(record);
}
void
doAdd(Tokenizer st) throws IOException {
Record record = parseRR(st, defaultClass, defaultTTL);
query.addRecord(record, Section.UPDATE);
print(record);
}
void
doDelete(Tokenizer st) throws IOException {
Tokenizer.Token token;
String s;
Name name;
Record record;
int type;
int dclass;
name = st.getName(zone);
token = st.get();
if (token.isString()) {
s = token.value;
if ((dclass = DClass.value(s)) >= 0) {
s = st.getString();
}
if ((type = Type.value(s)) < 0)
throw new IOException("Invalid type: " + s);
token = st.get();
boolean iseol = token.isEOL();
st.unget();
if (!iseol) {
record = Record.fromString(name, type, DClass.NONE,
0, st, zone);
} else
record = Record.newRecord(name, type, DClass.ANY, 0);
}
else
record = Record.newRecord(name, Type.ANY, DClass.ANY, 0);
query.addRecord(record, Section.UPDATE);
print(record);
}
void
doGlue(Tokenizer st) throws IOException {
Record record = parseRR(st, defaultClass, defaultTTL);
query.addRecord(record, Section.ADDITIONAL);
print(record);
}
void
doQuery(Tokenizer st) throws IOException {
Record rec;
Tokenizer.Token token;
Name name = null;
int type = Type.A;
int dclass = defaultClass;
name = st.getName(zone);
token = st.get();
if (token.isString()) {
type = Type.value(token.value);
if (type < 0)
throw new IOException("Invalid type");
token = st.get();
if (token.isString()) {
dclass = DClass.value(token.value);
if (dclass < 0)
throw new IOException("Invalid class");
}
}
rec = Record.newRecord(name, type, dclass);
Message newQuery = Message.newQuery(rec);
if (res == null)
res = new SimpleResolver(server);
response = res.send(newQuery);
print(response);
}
void
doFile(Tokenizer st, List inputs, List istreams) throws IOException {
String s = st.getString();
InputStream is;
try {
if (s.equals("-"))
is = System.in;
else
is = new FileInputStream(s);
istreams.add(0, is);
inputs.add(new BufferedReader(new InputStreamReader(is)));
}
catch (FileNotFoundException e) {
print(s + " not found");
}
}
void
doLog(Tokenizer st) throws IOException {
String s = st.getString();
try {
FileOutputStream fos = new FileOutputStream(s);
log = new PrintStream(fos);
}
catch (Exception e) {
print("Error opening " + s);
}
}
boolean
doAssert(Tokenizer st) throws IOException {
String field = st.getString();
String expected = st.getString();
String value = null;
boolean flag = true;
int section;
if (response == null) {
print("No response has been received");
return true;
}
if (field.equalsIgnoreCase("rcode")) {
int rcode = response.getHeader().getRcode();
if (rcode != Rcode.value(expected)) {
value = Rcode.string(rcode);
flag = false;
}
}
else if (field.equalsIgnoreCase("serial")) {
Record [] answers = response.getSectionArray(Section.ANSWER);
if (answers.length < 1 || !(answers[0] instanceof SOARecord))
print("Invalid response (no SOA)");
else {
SOARecord soa = (SOARecord) answers[0];
long serial = soa.getSerial();
if (serial != Long.parseLong(expected)) {
value = Long.toString(serial);
flag = false;
}
}
}
else if (field.equalsIgnoreCase("tsig")) {
if (response.isSigned()) {
if (response.isVerified())
value = "ok";
else
value = "failed";
}
else
value = "unsigned";
if (!value.equalsIgnoreCase(expected))
flag = false;
}
else if ((section = Section.value(field)) >= 0) {
int count = response.getHeader().getCount(section);
if (count != Integer.parseInt(expected)) {
value = new Integer(count).toString();
flag = false;
}
}
else
print("Invalid assertion keyword: " + field);
if (flag == false) {
print("Expected " + field + " " + expected +
", received " + value);
while (true) {
Tokenizer.Token token = st.get();
if (!token.isString())
break;
print(token.value);
}
st.unget();
}
return flag;
}
static void
help(String topic) {
System.out.println();
if (topic == null)
System.out.println("The following are supported commands:\n" +
"add assert class clear date delete\n" +
"echo file glue help log key\n" +
"edns origin port prohibit query quit\n" +
"require send server show sleep tcp\n" +
"ttl zone #\n");
else if (topic.equalsIgnoreCase("add"))
System.out.println(
"add <name> [ttl] [class] <type> <data>\n\n" +
"specify a record to be added\n");
else if (topic.equalsIgnoreCase("assert"))
System.out.println(
"assert <field> <value> [msg]\n\n" +
"asserts that the value of the field in the last\n" +
"response matches the value specified. If not,\n" +
"the message is printed (if present) and the\n" +
"program exits. The field may be any of <rcode>,\n" +
"<serial>, <tsig>, <qu>, <an>, <au>, or <ad>.\n");
else if (topic.equalsIgnoreCase("class"))
System.out.println(
"class <class>\n\n" +
"class of the zone to be updated (default: IN)\n");
else if (topic.equalsIgnoreCase("clear"))
System.out.println(
"clear\n\n" +
"clears the current update packet\n");
else if (topic.equalsIgnoreCase("date"))
System.out.println(
"date [-ms]\n\n" +
"prints the current date and time in human readable\n" +
"format or as the number of milliseconds since the\n" +
"epoch");
else if (topic.equalsIgnoreCase("delete"))
System.out.println(
"delete <name> [ttl] [class] <type> <data> \n" +
"delete <name> <type> \n" +
"delete <name>\n\n" +
"specify a record or set to be deleted, or that\n" +
"all records at a name should be deleted\n");
else if (topic.equalsIgnoreCase("echo"))
System.out.println(
"echo <text>\n\n" +
"prints the text\n");
else if (topic.equalsIgnoreCase("file"))
System.out.println(
"file <file>\n\n" +
"opens the specified file as the new input source\n" +
"(- represents stdin)\n");
else if (topic.equalsIgnoreCase("glue"))
System.out.println(
"glue <name> [ttl] [class] <type> <data>\n\n" +
"specify an additional record\n");
else if (topic.equalsIgnoreCase("help"))
System.out.println(
"?/help\n" +
"help [topic]\n\n" +
"prints a list of commands or help about a specific\n" +
"command\n");
else if (topic.equalsIgnoreCase("log"))
System.out.println(
"log <file>\n\n" +
"opens the specified file and uses it to log output\n");
else if (topic.equalsIgnoreCase("key"))
System.out.println(
"key <name> <data>\n\n" +
"TSIG key used to sign messages\n");
else if (topic.equalsIgnoreCase("edns"))
System.out.println(
"edns <level>\n\n" +
"EDNS level specified when sending messages\n");
else if (topic.equalsIgnoreCase("origin"))
System.out.println(
"origin <origin>\n\n" +
"<same as zone>\n");
else if (topic.equalsIgnoreCase("port"))
System.out.println(
"port <port>\n\n" +
"UDP/TCP port messages are sent to (default: 53)\n");
else if (topic.equalsIgnoreCase("prohibit"))
System.out.println(
"prohibit <name> <type> \n" +
"prohibit <name>\n\n" +
"require that a set or name is not present\n");
else if (topic.equalsIgnoreCase("query"))
System.out.println(
"query <name> [type [class]] \n\n" +
"issues a query\n");
else if (topic.equalsIgnoreCase("q") ||
topic.equalsIgnoreCase("quit"))
System.out.println(
"q/quit\n\n" +
"quits the program\n");
else if (topic.equalsIgnoreCase("require"))
System.out.println(
"require <name> [ttl] [class] <type> <data> \n" +
"require <name> <type> \n" +
"require <name>\n\n" +
"require that a record, set, or name is present\n");
else if (topic.equalsIgnoreCase("send"))
System.out.println(
"send\n\n" +
"sends and resets the current update packet\n");
else if (topic.equalsIgnoreCase("server"))
System.out.println(
"server <name> [port]\n\n" +
"server that receives send updates/queries\n");
else if (topic.equalsIgnoreCase("show"))
System.out.println(
"show\n\n" +
"shows the current update packet\n");
else if (topic.equalsIgnoreCase("sleep"))
System.out.println(
"sleep <milliseconds>\n\n" +
"pause for interval before next command\n");
else if (topic.equalsIgnoreCase("tcp"))
System.out.println(
"tcp\n\n" +
"TCP should be used to send all messages\n");
else if (topic.equalsIgnoreCase("ttl"))
System.out.println(
"ttl <ttl>\n\n" +
"default ttl of added records (default: 0)\n");
else if (topic.equalsIgnoreCase("zone"))
System.out.println(
"zone <zone>\n\n" +
"zone to update (default: .\n");
else if (topic.equalsIgnoreCase("#"))
System.out.println(
"# <text>\n\n" +
"a comment\n");
else
System.out.println ("Topic '" + topic + "' unrecognized\n");
}
public static void
main(String args[]) throws IOException {
InputStream in = null;
if (args.length >= 1) {
try {
in = new FileInputStream(args[0]);
}
catch (FileNotFoundException e) {
System.out.println(args[0] + " not found.");
System.exit(1);
}
}
else
in = System.in;
update u = new update(in);
}
}
| midnightskinhead/audioboo-android | externals/dnsjava/update.java | Java | gpl-3.0 | 16,887 |
/*
This file is part of LilyPond, the GNU music typesetter.
Copyright (C) 2006--2015 Han-Wen Nienhuys <hanwen@lilypond.org>
LilyPond 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.
LilyPond 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 LilyPond. If not, see <http://www.gnu.org/licenses/>.
*/
#include "engraver.hh"
#include "spanner.hh"
#include "item.hh"
#include "side-position-interface.hh"
#include "stream-event.hh"
#include "warn.hh"
#include "axis-group-interface.hh"
#include "translator.icc"
/*
TODO:
* Detach from pedal specifics,
* Also use this engraver for dynamics.
*/
struct Pedal_align_info
{
Spanner *line_spanner_;
Grob *carrying_item_;
Spanner *carrying_spanner_;
Spanner *finished_carrying_spanner_;
Pedal_align_info ()
{
clear ();
}
void clear ()
{
line_spanner_ = 0;
carrying_spanner_ = 0;
carrying_item_ = 0;
finished_carrying_spanner_ = 0;
}
bool is_finished ()
{
bool do_continue = carrying_item_;
do_continue |= (carrying_spanner_ && !finished_carrying_spanner_);
do_continue |= (carrying_spanner_ && finished_carrying_spanner_ != carrying_spanner_);
return !do_continue;
}
};
class Piano_pedal_align_engraver : public Engraver
{
public:
TRANSLATOR_DECLARATIONS (Piano_pedal_align_engraver);
protected:
virtual void finalize ();
void acknowledge_piano_pedal_script (Grob_info);
void acknowledge_piano_pedal_bracket (Grob_info);
void acknowledge_note_column (Grob_info);
void acknowledge_end_piano_pedal_bracket (Grob_info);
void stop_translation_timestep ();
void start_translation_timestep ();
private:
enum Pedal_type
{
SOSTENUTO,
SUSTAIN,
UNA_CORDA,
NUM_PEDAL_TYPES
};
Pedal_align_info pedal_info_[NUM_PEDAL_TYPES];
vector<Grob *> supports_;
Pedal_type get_grob_pedal_type (Grob_info g);
Spanner *make_line_spanner (Pedal_type t, SCM);
};
Piano_pedal_align_engraver::Piano_pedal_align_engraver (Context *c)
: Engraver (c)
{
}
void
Piano_pedal_align_engraver::start_translation_timestep ()
{
supports_.clear ();
}
void
Piano_pedal_align_engraver::stop_translation_timestep ()
{
for (int i = 0; i < NUM_PEDAL_TYPES; i++)
{
if (pedal_info_[i].line_spanner_)
{
if (pedal_info_[i].carrying_item_)
{
if (!pedal_info_[i].line_spanner_->get_bound (LEFT))
pedal_info_[i].line_spanner_->set_bound (LEFT,
pedal_info_[i].carrying_item_);
pedal_info_[i].line_spanner_->set_bound (RIGHT,
pedal_info_[i].carrying_item_);
}
else if (pedal_info_[i].carrying_spanner_
|| pedal_info_[i].finished_carrying_spanner_
)
{
if (!pedal_info_[i].line_spanner_->get_bound (LEFT)
&& pedal_info_[i].carrying_spanner_->get_bound (LEFT))
pedal_info_[i].line_spanner_->set_bound (LEFT,
pedal_info_[i].carrying_spanner_->get_bound (LEFT));
if (pedal_info_[i].finished_carrying_spanner_)
pedal_info_[i].line_spanner_->set_bound (RIGHT,
pedal_info_[i].finished_carrying_spanner_->get_bound (RIGHT));
}
for (vsize j = 0; j < supports_.size (); j++)
{
Side_position_interface::add_support (pedal_info_[i].line_spanner_, supports_[j]);
}
if (pedal_info_[i].is_finished ())
{
announce_end_grob (pedal_info_[i].line_spanner_, SCM_EOL);
pedal_info_[i].clear ();
}
}
pedal_info_[i].carrying_item_ = 0;
}
}
Piano_pedal_align_engraver::Pedal_type
Piano_pedal_align_engraver::get_grob_pedal_type (Grob_info g)
{
if (g.event_cause ()->in_event_class ("sostenuto-event"))
return SOSTENUTO;
if (g.event_cause ()->in_event_class ("sustain-event"))
return SUSTAIN;
if (g.event_cause ()->in_event_class ("una-corda-event"))
return UNA_CORDA;
programming_error ("Unknown piano pedal type. Defaulting to sustain");
return SUSTAIN;
}
Spanner *
Piano_pedal_align_engraver::make_line_spanner (Pedal_type t, SCM cause)
{
Spanner *sp = pedal_info_[t].line_spanner_;
if (!sp)
{
switch (t)
{
case (SOSTENUTO):
sp = make_spanner ("SostenutoPedalLineSpanner", cause);
break;
case (SUSTAIN):
sp = make_spanner ("SustainPedalLineSpanner", cause);
break;
case (UNA_CORDA):
sp = make_spanner ("UnaCordaPedalLineSpanner", cause);
break;
default:
programming_error ("No pedal type fonud!");
return sp;
}
pedal_info_[t].line_spanner_ = sp;
}
return sp;
}
void
Piano_pedal_align_engraver::acknowledge_note_column (Grob_info gi)
{
supports_.push_back (gi.grob ());
}
void
Piano_pedal_align_engraver::acknowledge_piano_pedal_bracket (Grob_info gi)
{
Pedal_type type = get_grob_pedal_type (gi);
Grob *sp = make_line_spanner (type, gi.grob ()->self_scm ());
Axis_group_interface::add_element (sp, gi.grob ());
pedal_info_[type].carrying_spanner_ = gi.spanner ();
}
void
Piano_pedal_align_engraver::acknowledge_end_piano_pedal_bracket (Grob_info gi)
{
Pedal_type type = get_grob_pedal_type (gi);
pedal_info_[type].finished_carrying_spanner_ = gi.spanner ();
}
void
Piano_pedal_align_engraver::acknowledge_piano_pedal_script (Grob_info gi)
{
Pedal_type type = get_grob_pedal_type (gi);
Grob *sp = make_line_spanner (type, gi.grob ()->self_scm ());
Axis_group_interface::add_element (sp, gi.grob ());
pedal_info_[type].carrying_item_ = gi.grob ();
}
void
Piano_pedal_align_engraver::finalize ()
{
for (int i = 0; i < NUM_PEDAL_TYPES; i++)
{
if (pedal_info_[i].line_spanner_)
{
SCM cc = get_property ("currentCommandColumn");
Item *c = unsmob<Item> (cc);
pedal_info_[i].line_spanner_->set_bound (RIGHT, c);
pedal_info_[i].clear ();
}
}
}
void
Piano_pedal_align_engraver::boot ()
{
ADD_ACKNOWLEDGER (Piano_pedal_align_engraver, note_column);
ADD_ACKNOWLEDGER (Piano_pedal_align_engraver, piano_pedal_bracket);
ADD_ACKNOWLEDGER (Piano_pedal_align_engraver, piano_pedal_script);
ADD_END_ACKNOWLEDGER (Piano_pedal_align_engraver, piano_pedal_bracket);
}
ADD_TRANSLATOR (Piano_pedal_align_engraver,
/* doc */
"Align piano pedal symbols and brackets.",
/* create */
"SostenutoPedalLineSpanner "
"SustainPedalLineSpanner "
"UnaCordaPedalLineSpanner ",
/* read */
"currentCommandColumn ",
/* write */
""
);
| thSoft/lilypond-hu | lily/piano-pedal-align-engraver.cc | C++ | gpl-3.0 | 7,432 |
<?PHP // $Id$
// tex.php - created with Moodle 1.9.2+ (Build: 20080813) (2007101521)
// local modifications from http://localhost/moodle192
$string['filtername'] = 'Ngôn ngữ TeX';
?>
| chinhnh/moodle | lang/vi/tex.php | PHP | gpl-3.0 | 202 |
<!DOCTYPE HTML>
<!--
Dopetrope by HTML5 UP
html5up.net | @ajlkn
Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
-->
<html>
<head>
<title>Dopetrope by HTML5 UP</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!--[if lte IE 8]><script src="assets/js/ie/html5shiv.js"></script><![endif]-->
<link rel="stylesheet" href="assets/css/main.css" />
<!--[if lte IE 8]><link rel="stylesheet" href="assets/css/ie8.css" /><![endif]-->
</head>
<body class="left-sidebar">
<div id="page-wrapper">
<!-- Header -->
<div id="header-wrapper">
<div id="header">
<!-- Logo -->
<h1><a href="index.html">Dopetrope</a></h1>
<!-- Nav -->
<nav id="nav">
<ul>
<li><a href="index.html">Home</a></li>
<li>
<a href="#">Dropdown</a>
<ul>
<li><a href="#">Lorem ipsum dolor</a></li>
<li><a href="#">Magna phasellus</a></li>
<li><a href="#">Etiam dolore nisl</a></li>
<li>
<a href="#">Phasellus consequat</a>
<ul>
<li><a href="#">Magna phasellus</a></li>
<li><a href="#">Etiam dolore nisl</a></li>
<li><a href="#">Veroeros feugiat</a></li>
<li><a href="#">Nisl sed aliquam</a></li>
<li><a href="#">Dolore adipiscing</a></li>
</ul>
</li>
<li><a href="#">Veroeros feugiat</a></li>
</ul>
</li>
<li class="current"><a href="left-sidebar.html">Left Sidebar</a></li>
<li><a href="right-sidebar.html">Right Sidebar</a></li>
<li><a href="no-sidebar.html">No Sidebar</a></li>
</ul>
</nav>
</div>
</div>
<!-- Main -->
<div id="main-wrapper">
<div class="container">
<div class="row">
<div class="4u 12u(mobile)">
<!-- Sidebar -->
<section class="box">
<a href="#" class="image featured"><img src="images/pic09.jpg" alt="" /></a>
<header>
<h3>Sed etiam lorem nulla</h3>
</header>
<p>Lorem ipsum dolor sit amet sit veroeros sed amet blandit consequat veroeros lorem blandit adipiscing et feugiat phasellus tempus dolore ipsum lorem dolore.</p>
<footer>
<a href="#" class="button alt">Magna sed taciti</a>
</footer>
</section>
<section class="box">
<header>
<h3>Feugiat consequat</h3>
</header>
<p>Veroeros sed amet blandit consequat veroeros lorem blandit adipiscing et feugiat sed lorem consequat feugiat lorem dolore.</p>
<ul class="divided">
<li><a href="#">Sed et blandit consequat sed</a></li>
<li><a href="#">Hendrerit tortor vitae sapien dolore</a></li>
<li><a href="#">Sapien id suscipit magna sed felis</a></li>
<li><a href="#">Aptent taciti sociosqu ad litora</a></li>
</ul>
<footer>
<a href="#" class="button alt">Ipsum consequat</a>
</footer>
</section>
</div>
<div class="8u 12u(mobile) important(mobile)">
<!-- Content -->
<article class="box post">
<a href="#" class="image featured"><img src="images/pic01.jpg" alt="" /></a>
<header>
<h2>Left Sidebar</h2>
<p>Lorem ipsum dolor sit amet feugiat</p>
</header>
<p>
Vestibulum scelerisque ultricies libero id hendrerit. Vivamus malesuada quam faucibus ante dignissim auctor
hendrerit libero placerat. Nulla facilisi. Proin aliquam felis non arcu molestie at accumsan turpis commodo.
Proin elementum, nibh non egestas sodales, augue quam aliquet est, id egestas diam justo adipiscing ante.
Pellentesque tempus nulla non urna eleifend ut ultrices nisi faucibus.
</p>
<p>
Praesent a dolor leo. Duis in felis in tortor lobortis volutpat et pretium tellus. Vestibulum ac ante nisl,
a elementum odio. Duis semper risus et lectus commodo fringilla. Maecenas sagittis convallis justo vel mattis.
placerat, nunc diam iaculis massa, et aliquet nibh leo non nisl vitae porta lobortis, enim neque fringilla nunc,
eget faucibus lacus sem quis nunc suspendisse nec lectus sit amet augue rutrum vulputate ut ut mi. Aenean
elementum, mi sit amet porttitor lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor
sit amet nullam consequat feugiat dolore tempus.
</p>
<section>
<header>
<h3>Something else</h3>
</header>
<p>
Elementum odio duis semper risus et lectus commodo fringilla. Maecenas sagittis convallis justo vel mattis.
placerat, nunc diam iaculis massa, et aliquet nibh leo non nisl vitae porta lobortis, enim neque fringilla nunc,
eget faucibus lacus sem quis nunc suspendisse nec lectus sit amet augue rutrum vulputate ut ut mi. Aenean
elementum, mi sit amet porttitor lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor
sit amet nullam consequat feugiat dolore tempus.
</p>
<p>
Nunc diam iaculis massa, et aliquet nibh leo non nisl vitae porta lobortis, enim neque fringilla nunc,
eget faucibus lacus sem quis nunc suspendisse nec lectus sit amet augue rutrum vulputate ut ut mi. Aenean
elementum, mi sit amet porttitor lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor
sit amet nullam consequat feugiat dolore tempus.
</p>
</section>
<section>
<header>
<h3>So in conclusion ...</h3>
</header>
<p>
Nunc diam iaculis massa, et aliquet nibh leo non nisl vitae porta lobortis, enim neque fringilla nunc,
eget faucibus lacus sem quis nunc suspendisse nec lectus sit amet augue rutrum vulputate ut ut mi. Aenean
elementum, mi sit amet porttitor lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor
sit amet nullam consequat feugiat dolore tempus. Elementum odio duis semper risus et lectus commodo fringilla.
Maecenas sagittis convallis justo vel mattis.
</p>
</section>
</article>
</div>
</div>
</div>
</div>
<!-- Footer -->
<div id="footer-wrapper">
<section id="footer" class="container">
<div class="row">
<div class="8u 12u(mobile)">
<section>
<header>
<h2>Blandit nisl adipiscing</h2>
</header>
<ul class="dates">
<li>
<span class="date">Jan <strong>27</strong></span>
<h3><a href="#">Lorem dolor sit amet veroeros</a></h3>
<p>Ipsum dolor sit amet veroeros consequat blandit ipsum phasellus lorem consequat etiam.</p>
</li>
<li>
<span class="date">Jan <strong>23</strong></span>
<h3><a href="#">Ipsum sed blandit nisl consequat</a></h3>
<p>Blandit phasellus lorem ipsum dolor tempor sapien tortor hendrerit adipiscing feugiat lorem.</p>
</li>
<li>
<span class="date">Jan <strong>15</strong></span>
<h3><a href="#">Magna tempus lorem feugiat</a></h3>
<p>Dolore consequat sed phasellus lorem sed etiam nullam dolor etiam sed amet sit consequat.</p>
</li>
<li>
<span class="date">Jan <strong>12</strong></span>
<h3><a href="#">Dolore tempus ipsum feugiat nulla</a></h3>
<p>Feugiat lorem dolor sed nullam tempus lorem ipsum dolor sit amet nullam consequat.</p>
</li>
<li>
<span class="date">Jan <strong>10</strong></span>
<h3><a href="#">Blandit tempus aliquam?</a></h3>
<p>Feugiat sed tempus blandit tempus adipiscing nisl lorem ipsum dolor sit amet dolore.</p>
</li>
</ul>
</section>
</div>
<div class="4u 12u(mobile)">
<section>
<header>
<h2>What's this all about?</h2>
</header>
<a href="#" class="image featured"><img src="images/pic10.jpg" alt="" /></a>
<p>
This is <strong>Dopetrope</strong> a free, fully responsive HTML5 site template by
<a href="http://twitter.com/ajlkn">AJ</a> for <a href="http://html5up.net/">HTML5 UP</a> It's released for free under
the <a href="http://html5up.net/license/">Creative Commons Attribution</a> license so feel free to use it for any personal or commercial project – just don't forget to credit us!
</p>
<footer>
<a href="#" class="button">Find out more</a>
</footer>
</section>
</div>
</div>
<div class="row">
<div class="4u 12u(mobile)">
<section>
<header>
<h2>Tempus consequat</h2>
</header>
<ul class="divided">
<li><a href="#">Lorem ipsum dolor sit amet sit veroeros</a></li>
<li><a href="#">Sed et blandit consequat sed tlorem blandit</a></li>
<li><a href="#">Adipiscing feugiat phasellus sed tempus</a></li>
<li><a href="#">Hendrerit tortor vitae mattis tempor sapien</a></li>
<li><a href="#">Sem feugiat sapien id suscipit magna felis nec</a></li>
<li><a href="#">Elit class aptent taciti sociosqu ad litora</a></li>
</ul>
</section>
</div>
<div class="4u 12u(mobile)">
<section>
<header>
<h2>Ipsum et phasellus</h2>
</header>
<ul class="divided">
<li><a href="#">Lorem ipsum dolor sit amet sit veroeros</a></li>
<li><a href="#">Sed et blandit consequat sed tlorem blandit</a></li>
<li><a href="#">Adipiscing feugiat phasellus sed tempus</a></li>
<li><a href="#">Hendrerit tortor vitae mattis tempor sapien</a></li>
<li><a href="#">Sem feugiat sapien id suscipit magna felis nec</a></li>
<li><a href="#">Elit class aptent taciti sociosqu ad litora</a></li>
</ul>
</section>
</div>
<div class="4u 12u(mobile)">
<section>
<header>
<h2>Vitae tempor lorem</h2>
</header>
<ul class="social">
<li><a class="icon fa-facebook" href="#"><span class="label">Facebook</span></a></li>
<li><a class="icon fa-twitter" href="#"><span class="label">Twitter</span></a></li>
<li><a class="icon fa-dribbble" href="#"><span class="label">Dribbble</span></a></li>
<li><a class="icon fa-linkedin" href="#"><span class="label">LinkedIn</span></a></li>
<li><a class="icon fa-google-plus" href="#"><span class="label">Google+</span></a></li>
</ul>
<ul class="contact">
<li>
<h3>Address</h3>
<p>
Untitled Incorporated<br />
1234 Somewhere Road Suite<br />
Nashville, TN 00000-0000
</p>
</li>
<li>
<h3>Mail</h3>
<p><a href="#">someone@untitled.tld</a></p>
</li>
<li>
<h3>Phone</h3>
<p>(800) 000-0000</p>
</li>
</ul>
</section>
</div>
</div>
<div class="row">
<div class="12u">
<!-- Copyright -->
<div id="copyright">
<ul class="links">
<li>© Untitled. All rights reserved.</li><li>Design: <a href="http://html5up.net">HTML5 UP</a></li>
</ul>
</div>
</div>
</div>
</section>
</div>
</div>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.dropotron.min.js"></script>
<script src="assets/js/skel.min.js"></script>
<script src="assets/js/skel-viewport.min.js"></script>
<script src="assets/js/util.js"></script>
<!--[if lte IE 8]><script src="assets/js/ie/respond.min.js"></script><![endif]-->
<script src="assets/js/main.js"></script>
</body>
</html> | RoberTnf/dcss-analyzer | templates/left-sidebar.html | HTML | gpl-3.0 | 12,598 |
<!DOCTYPE html>
<html>
<head>
<title>Integration with dhtmlxGrid</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<link rel="stylesheet" type="text/css" href="../../../codebase/fonts/font_roboto/roboto.css"/>
<link rel="stylesheet" type="text/css" href="../../../codebase/dhtmlx.css"/>
<script src="../../../codebase/dhtmlx.js"></script>
<style>
div#accObj {
position: relative;
width: 360px;
height: 400px;
box-shadow: 0 1px 3px rgba(0,0,0,0.05), 0 1px 3px rgba(0,0,0,0.09);
}
</style>
<script>
var myAcc, myGrid;
function doOnLoad(){
myAcc = new dhtmlXAccordion({
parent: "accObj",
items: [
{id: "a1", text: "dhtmlxGrid"},
{id: "a2", text: "b"},
{id: "a3", text: "c"}
]
});
myGrid = myAcc.cells("a1").attachGrid();
myGrid.setImagePath("../../../codebase/imgs/");
myGrid.load("../common/grid.xml");
}
</script>
<html>
<body onload="doOnLoad();">
<div id="accObj"></div>
</body>
</html> | vijaysebastian/bill | public/plugins/dhtmlxSuite_v50_std/samples/dhtmlxAccordion/05_components/01_grid.html | HTML | gpl-3.0 | 1,076 |
//
// SuperTuxKart - a fun racing game with go-kart
// Copyright (C) 2016 SuperTuxKart-Team
//
// 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.
#include "karts/controller/arena_ai.hpp"
#include "items/attachment.hpp"
#include "items/item_manager.hpp"
#include "items/powerup.hpp"
#include "items/projectile_manager.hpp"
#include "karts/abstract_kart.hpp"
#include "karts/controller/player_controller.hpp"
#include "karts/controller/ai_properties.hpp"
#include "karts/kart_properties.hpp"
#include "tracks/battle_graph.hpp"
#include "utils/log.hpp"
int ArenaAI::m_test_node_for_banana = BattleGraph::UNKNOWN_POLY;
bool isNodeWithBanana(const std::pair<const Item*, int>& item_pair)
{
return item_pair.second == ArenaAI::m_test_node_for_banana &&
item_pair.first->getType() == Item::ITEM_BANANA &&
!item_pair.first->wasCollected();
}
ArenaAI::ArenaAI(AbstractKart *kart)
: AIBaseController(kart)
{
m_debug_sphere = NULL;
m_debug_sphere_next = NULL;
} // ArenaAI
//-----------------------------------------------------------------------------
/** Resets the AI when a race is restarted.
*/
void ArenaAI::reset()
{
m_target_node = BattleGraph::UNKNOWN_POLY;
m_current_forward_node = BattleGraph::UNKNOWN_POLY;
m_current_forward_point = Vec3(0, 0, 0);
m_adjusting_side = false;
m_closest_kart = NULL;
m_closest_kart_node = BattleGraph::UNKNOWN_POLY;
m_closest_kart_point = Vec3(0, 0, 0);
m_closest_kart_pos_data = {0};
m_cur_kart_pos_data = {0};
m_is_stuck = false;
m_is_uturn = false;
m_avoiding_banana = false;
m_target_point = Vec3(0, 0, 0);
m_time_since_last_shot = 0.0f;
m_time_since_driving = 0.0f;
m_time_since_reversing = 0.0f;
m_time_since_uturn = 0.0f;
m_turn_radius = 0.0f;
m_turn_angle = 0.0f;
m_on_node.clear();
m_aiming_points.clear();
m_aiming_nodes.clear();
m_cur_difficulty = race_manager->getDifficulty();
AIBaseController::reset();
} // reset
//-----------------------------------------------------------------------------
/** This is the main entry point for the AI.
* It is called once per frame for each AI and determines the behaviour of
* the AI, e.g. steering, accelerating/braking, firing.
*/
void ArenaAI::update(float dt)
{
// This is used to enable firing an item backwards.
m_controls->m_look_back = false;
m_controls->m_nitro = false;
m_avoiding_banana = false;
// Don't do anything if there is currently a kart animations shown.
if (m_kart->getKartAnimation())
{
resetAfterStop();
return;
}
if (isWaiting())
{
AIBaseController::update(dt);
return;
}
checkIfStuck(dt);
if (handleArenaUnstuck(dt))
return;
findClosestKart(true);
findTarget();
handleArenaItems(dt);
if (m_kart->getSpeed() > 15.0f && m_turn_angle < 20)
{
// Only use nitro when turn angle is big (180 - angle)
m_controls->m_nitro = true;
}
if (m_is_uturn)
{
resetAfterStop();
handleArenaUTurn(dt);
}
else
{
handleArenaAcceleration(dt);
handleArenaSteering(dt);
handleArenaBraking();
}
AIBaseController::update(dt);
} // update
//-----------------------------------------------------------------------------
bool ArenaAI::updateAimingPosition()
{
// Notice: we use the point ahead of kart to determine next node,
// to compensate the time difference between steering
m_current_forward_point =
m_kart->getTrans()(Vec3(0, 0, m_kart->getKartLength()));
m_current_forward_node = BattleGraph::get()->pointToNode
(m_current_forward_node, m_current_forward_point,
false/*ignore_vertical*/);
// Use current node if forward node is unknown, or near the target
const int forward = (m_current_forward_node == BattleGraph::UNKNOWN_POLY ||
m_current_forward_node == m_target_node ||
getCurrentNode() == m_target_node ? getCurrentNode() :
m_current_forward_node);
if (forward == BattleGraph::UNKNOWN_POLY ||
m_target_node == BattleGraph::UNKNOWN_POLY)
return false;
if (forward == m_target_node)
{
m_aiming_points.push_back(BattleGraph::get()
->getPolyOfNode(forward).getCenter());
m_aiming_points.push_back(m_target_point);
m_aiming_nodes.insert(forward);
m_aiming_nodes.insert(getCurrentNode());
return true;
}
const int next_node = BattleGraph::get()
->getNextShortestPathPoly(forward, m_target_node);
if (next_node == BattleGraph::UNKNOWN_POLY)
{
Log::error("ArenaAI", "Next node is unknown, did you forget to link"
"adjacent face in navmesh?");
return false;
}
m_aiming_points.push_back(BattleGraph::get()
->getPolyOfNode(forward).getCenter());
m_aiming_points.push_back(BattleGraph::get()
->getPolyOfNode(next_node).getCenter());
m_aiming_nodes.insert(forward);
m_aiming_nodes.insert(next_node);
m_aiming_nodes.insert(getCurrentNode());
return true;
} // updateAimingPosition
//-----------------------------------------------------------------------------
/** This function sets the steering.
* \param dt Time step size.
*/
void ArenaAI::handleArenaSteering(const float dt)
{
const int current_node = getCurrentNode();
if (current_node == BattleGraph::UNKNOWN_POLY ||
m_target_node == BattleGraph::UNKNOWN_POLY)
{
return;
}
m_aiming_points.clear();
m_aiming_nodes.clear();
const bool found_position = updateAimingPosition();
if (ignorePathFinding())
{
// Steer directly
checkPosition(m_target_point, &m_cur_kart_pos_data);
#ifdef AI_DEBUG
m_debug_sphere->setPosition(m_target_point.toIrrVector());
#endif
if (m_cur_kart_pos_data.behind)
{
m_adjusting_side = m_cur_kart_pos_data.lhs;
m_is_uturn = true;
}
else
{
float target_angle = steerToPoint(m_target_point);
setSteering(target_angle, dt);
}
return;
}
else if (found_position)
{
updateBananaLocation();
assert(m_aiming_points.size() == 2);
updateTurnRadius(m_kart->getXYZ(), m_aiming_points[0],
m_aiming_points[1]);
m_target_point = m_aiming_points[1];
checkPosition(m_target_point, &m_cur_kart_pos_data);
#ifdef AI_DEBUG
m_debug_sphere->setVisible(true);
m_debug_sphere_next->setVisible(true);
m_debug_sphere->setPosition(m_aiming_points[0].toIrrVector());
m_debug_sphere_next->setPosition(m_aiming_points[1].toIrrVector());
#endif
if (m_cur_kart_pos_data.behind)
{
m_adjusting_side = m_cur_kart_pos_data.lhs;
m_is_uturn = true;
}
else
{
float target_angle = steerToPoint(m_target_point);
setSteering(target_angle, dt);
}
return;
}
else
{
// Do nothing (go straight) if no targets found
setSteering(0.0f, dt);
return;
}
} // handleSteering
//-----------------------------------------------------------------------------
void ArenaAI::checkIfStuck(const float dt)
{
if (m_is_stuck) return;
if (m_kart->getKartAnimation() || isWaiting())
{
m_on_node.clear();
m_time_since_driving = 0.0f;
}
m_on_node.insert(getCurrentNode());
m_time_since_driving += dt;
if ((m_time_since_driving >=
(m_cur_difficulty == RaceManager::DIFFICULTY_EASY ? 2.0f : 1.5f)
&& m_on_node.size() < 2 && !m_is_uturn &&
fabsf(m_kart->getSpeed()) < 3.0f) || isStuck() == true)
{
// Check whether a kart stay on the same node for a period of time
// Or crashed 3 times
m_on_node.clear();
m_time_since_driving = 0.0f;
AIBaseController::reset();
m_is_stuck = true;
}
else if (m_time_since_driving >=
(m_cur_difficulty == RaceManager::DIFFICULTY_EASY ? 2.0f : 1.5f))
{
m_on_node.clear(); // Reset for any correct movement
m_time_since_driving = 0.0f;
}
} // checkIfStuck
//-----------------------------------------------------------------------------
/** Handles acceleration.
* \param dt Time step size.
*/
void ArenaAI::handleArenaAcceleration(const float dt)
{
if (m_controls->m_brake)
{
m_controls->m_accel = 0.0f;
return;
}
const float handicap =
(m_cur_difficulty == RaceManager::DIFFICULTY_EASY ? 0.7f : 1.0f);
m_controls->m_accel = stk_config->m_ai_acceleration * handicap;
} // handleArenaAcceleration
//-----------------------------------------------------------------------------
void ArenaAI::handleArenaUTurn(const float dt)
{
const float turn_side = (m_adjusting_side ? 1.0f : -1.0f);
if (fabsf(m_kart->getSpeed()) >
(m_kart->getKartProperties()->getEngineMaxSpeed() / 5)
&& m_kart->getSpeed() < 0) // Try to emulate reverse like human players
m_controls->m_accel = -0.06f;
else
m_controls->m_accel = -5.0f;
if (m_time_since_uturn >=
(m_cur_difficulty == RaceManager::DIFFICULTY_EASY ? 2.0f : 1.5f))
setSteering(-(turn_side), dt); // Preventing keep going around circle
else
setSteering(turn_side, dt);
m_time_since_uturn += dt;
checkPosition(m_target_point, &m_cur_kart_pos_data);
if (!m_cur_kart_pos_data.behind || m_time_since_uturn >
(m_cur_difficulty == RaceManager::DIFFICULTY_EASY ? 3.5f : 3.0f))
{
m_is_uturn = false;
m_time_since_uturn = 0.0f;
}
else
m_is_uturn = true;
} // handleArenaUTurn
//-----------------------------------------------------------------------------
bool ArenaAI::handleArenaUnstuck(const float dt)
{
if (!m_is_stuck || m_is_uturn) return false;
resetAfterStop();
setSteering(0.0f, dt);
if (fabsf(m_kart->getSpeed()) >
(m_kart->getKartProperties()->getEngineMaxSpeed() / 5)
&& m_kart->getSpeed() < 0)
m_controls->m_accel = -0.06f;
else
m_controls->m_accel = -4.0f;
m_time_since_reversing += dt;
if (m_time_since_reversing >= 1.0f)
{
m_is_stuck = false;
m_time_since_reversing = 0.0f;
}
AIBaseController::update(dt);
return true;
} // handleArenaUnstuck
//-----------------------------------------------------------------------------
void ArenaAI::updateBananaLocation()
{
std::vector<std::pair<const Item*, int>>& item_list =
BattleGraph::get()->getItemList();
std::set<int>::iterator node = m_aiming_nodes.begin();
while (node != m_aiming_nodes.end())
{
m_test_node_for_banana = *node;
std::vector<std::pair<const Item*, int>>::iterator it =
std::find_if(item_list.begin(), item_list.end(), isNodeWithBanana);
if (it != item_list.end())
{
Vec3 banana_lc;
checkPosition(it->first->getXYZ(), NULL, &banana_lc,
true/*use_front_xyz*/);
// If satisfy the below condition, AI should not eat banana:
// banana_lc.z() < 0.0f, behind the kart
if (banana_lc.z() < 0.0f)
{
node++;
continue;
}
// If the node AI will pass has a banana, adjust the aim position
banana_lc = (banana_lc.x() < 0 ? banana_lc + Vec3(5, 0, 0) :
banana_lc - Vec3(5, 0, 0));
m_aiming_points[1] = m_kart->getTrans()(banana_lc);
m_avoiding_banana = true;
// Handle one banana only
return;
}
node++;
}
} // updateBananaLocation
//-----------------------------------------------------------------------------
/** This function handles braking. It used the turn radius found by
* updateTurnRadius(). Depending on the turn radius, it finds out the maximum
* speed. If the current speed is greater than the max speed and a set minimum
* speed, brakes are applied.
*/
void ArenaAI::handleArenaBraking()
{
// A kart will not brake when the speed is already slower than this
// value. This prevents a kart from going too slow (or even backwards)
// in tight curves.
const float MIN_SPEED = 5.0f;
if (forceBraking() && m_kart->getSpeed() > MIN_SPEED)
{
// Brake now
m_controls->m_brake = true;
return;
}
m_controls->m_brake = false;
if (getCurrentNode() == BattleGraph::UNKNOWN_POLY ||
m_target_node == BattleGraph::UNKNOWN_POLY) return;
if (m_aiming_points.empty()) return;
const float max_turn_speed = m_kart->getSpeedForTurnRadius(m_turn_radius);
if (m_kart->getSpeed() > 1.25f * max_turn_speed &&
fabsf(m_controls->m_steer) > 0.95f &&
m_kart->getSpeed() > MIN_SPEED)
{
m_controls->m_brake = true;
}
} // handleArenaBraking
//-----------------------------------------------------------------------------
void ArenaAI::updateTurnRadius(const Vec3& p1, const Vec3& p2,
const Vec3& p3)
{
// First use cosine formula to find out the angle made by the distance
// between kart (point one) to point two and point two between point three
const float a = (p1 - p2).length();
const float b = (p2 - p3).length();
const float c = (p1 - p3).length();
const float angle = 180 - findAngleFrom3Edges(a, b, c);
// Only calculate radius if not almost straight line
if (angle > 1 && angle < 179)
{
// angle
// ^
// a / \ b
// 90/\ /\90
// \ / \ /
// \ /
// \ /
// \ /
// |
// Try to estimate the turn radius with the help of a kite-like
// polygon as shown, find out the lowest angle which is
// (4 - 2) * 180 - 90 - 90 - angle (180 - angle from above)
// Then we use this value as the angle of a sector of circle,
// a + b as the arc length, then the radius can be calculated easily
m_turn_radius = ((a + b) / (angle / 360)) / M_PI / 2;
}
else
{
// Return large radius so no braking is needed otherwise
m_turn_radius = 45.0f;
}
m_turn_angle = angle;
} // updateTurnRadius
//-----------------------------------------------------------------------------
float ArenaAI::findAngleFrom3Edges(float a, float b, float c)
{
// Cosine forumla : c2 = a2 + b2 - 2ab cos C
float test_value = ((c * c) - (a * a) - (b * b)) / (-(2 * a * b));
// Prevent error
if (test_value < -1)
test_value = -1;
else if (test_value > 1)
test_value = 1;
return acosf(test_value) * RAD_TO_DEGREE;
} // findAngleFrom3Edges
//-----------------------------------------------------------------------------
void ArenaAI::handleArenaItems(const float dt)
{
m_controls->m_fire = false;
if (m_kart->getKartAnimation() ||
m_kart->getPowerup()->getType() == PowerupManager::POWERUP_NOTHING)
return;
// Find a closest kart again, this time we ignore difficulty
findClosestKart(false);
if (!m_closest_kart) return;
m_time_since_last_shot += dt;
float min_bubble_time = 2.0f;
const bool difficulty = m_cur_difficulty == RaceManager::DIFFICULTY_EASY ||
m_cur_difficulty == RaceManager::DIFFICULTY_MEDIUM;
const bool fire_behind = m_closest_kart_pos_data.behind && !difficulty;
const bool perfect_aim = m_closest_kart_pos_data.angle < 0.2f;
switch(m_kart->getPowerup()->getType())
{
case PowerupManager::POWERUP_BUBBLEGUM:
{
Attachment::AttachmentType type = m_kart->getAttachment()->getType();
// Don't use shield when we have a swatter.
if (type == Attachment::ATTACH_SWATTER ||
type == Attachment::ATTACH_NOLOKS_SWATTER)
break;
// Check if a flyable (cake, ...) is close or a kart nearby
// has a swatter attachment. If so, use bubblegum
// as shield
if ((!m_kart->isShielded() &&
projectile_manager->projectileIsClose(m_kart,
m_ai_properties->m_shield_incoming_radius)) ||
(m_closest_kart_pos_data.distance < 15.0f &&
((m_closest_kart->getAttachment()->
getType() == Attachment::ATTACH_SWATTER) ||
(m_closest_kart->getAttachment()->
getType() == Attachment::ATTACH_NOLOKS_SWATTER))))
{
m_controls->m_fire = true;
m_controls->m_look_back = false;
break;
}
// Avoid dropping all bubble gums one after another
if (m_time_since_last_shot < 3.0f) break;
// Use bubblegum if the next kart behind is 'close' but not too close,
// or can't find a close kart for too long time
if ((m_closest_kart_pos_data.distance < 15.0f &&
m_closest_kart_pos_data.distance > 3.0f) ||
m_time_since_last_shot > 15.0f)
{
m_controls->m_fire = true;
m_controls->m_look_back = true;
break;
}
break; // POWERUP_BUBBLEGUM
}
case PowerupManager::POWERUP_CAKE:
{
// if the kart has a shield, do not break it by using a cake.
if (m_kart->getShieldTime() > min_bubble_time)
break;
// Leave some time between shots
if (m_time_since_last_shot < 1.0f) break;
if (m_closest_kart_pos_data.distance < 25.0f &&
!m_closest_kart->isInvulnerable())
{
m_controls->m_fire = true;
m_controls->m_look_back = fire_behind;
break;
}
break;
} // POWERUP_CAKE
case PowerupManager::POWERUP_BOWLING:
{
// if the kart has a shield, do not break it by using a bowling ball.
if (m_kart->getShieldTime() > min_bubble_time)
break;
// Leave some time between shots
if (m_time_since_last_shot < 1.0f) break;
if (m_closest_kart_pos_data.distance < 6.0f &&
(difficulty || perfect_aim) &&
!m_closest_kart->isInvulnerable())
{
m_controls->m_fire = true;
m_controls->m_look_back = fire_behind;
break;
}
break;
} // POWERUP_BOWLING
case PowerupManager::POWERUP_SWATTER:
{
// Squared distance for which the swatter works
float d2 = m_kart->getKartProperties()->getSwatterDistance();
// if the kart has a shield, do not break it by using a swatter.
if (m_kart->getShieldTime() > min_bubble_time)
break;
if (!m_closest_kart->isSquashed() &&
m_closest_kart_pos_data.distance < d2 &&
m_closest_kart->getSpeed() < m_kart->getSpeed())
{
m_controls->m_fire = true;
m_controls->m_look_back = false;
break;
}
break;
}
// Below powerups won't appear in arena, so skip them
case PowerupManager::POWERUP_ZIPPER:
break; // POWERUP_ZIPPER
case PowerupManager::POWERUP_PLUNGER:
break; // POWERUP_PLUNGER
case PowerupManager::POWERUP_SWITCH: // Don't handle switch
m_controls->m_fire = true; // (use it no matter what) for now
break; // POWERUP_SWITCH
case PowerupManager::POWERUP_PARACHUTE:
break; // POWERUP_PARACHUTE
case PowerupManager::POWERUP_ANVIL:
break; // POWERUP_ANVIL
case PowerupManager::POWERUP_RUBBERBALL:
break;
default:
Log::error("ArenaAI",
"Invalid or unhandled powerup '%d' in default AI.",
m_kart->getPowerup()->getType());
assert(false);
}
if (m_controls->m_fire)
m_time_since_last_shot = 0.0f;
} // handleArenaItems
//-----------------------------------------------------------------------------
void ArenaAI::collectItemInArena(Vec3* aim_point, int* target_node) const
{
float distance = 99999.9f;
const std::vector< std::pair<const Item*, int> >& item_list =
BattleGraph::get()->getItemList();
const unsigned int items_count = item_list.size();
if (item_list.empty())
{
// Notice: this should not happen, as it makes no sense
// for an arean without items, if so how can attack happen?
Log::fatal ("ArenaAI",
"AI can't find any items in the arena, "
"maybe there is something wrong with the navmesh, "
"make sure it lies closely to the ground.");
return;
}
unsigned int closest_item_num = 0;
for (unsigned int i = 0; i < items_count; ++i)
{
const Item* item = item_list[i].first;
if (item->wasCollected()) continue;
if ((item->getType() == Item::ITEM_NITRO_BIG ||
item->getType() == Item::ITEM_NITRO_SMALL) &&
(m_kart->getEnergy() >
m_kart->getKartProperties()->getNitroSmallContainer()))
continue; // Ignore nitro when already has some
float test_distance = BattleGraph::get()
->getDistance(item_list[i].second, getCurrentNode());
if (test_distance <= distance &&
(item->getType() == Item::ITEM_BONUS_BOX ||
item->getType() == Item::ITEM_NITRO_BIG ||
item->getType() == Item::ITEM_NITRO_SMALL))
{
closest_item_num = i;
distance = test_distance;
}
}
const Item *item_selected = item_list[closest_item_num].first;
if (item_selected->getType() == Item::ITEM_BONUS_BOX ||
item_selected->getType() == Item::ITEM_NITRO_BIG ||
item_selected->getType() == Item::ITEM_NITRO_SMALL)
{
*aim_point = item_selected->getXYZ();
*target_node = item_list[closest_item_num].second;
}
else
{
// Handle when all targets are swapped, which make AIs follow karts
*aim_point = m_closest_kart_point;
*target_node = m_closest_kart_node;
}
} // collectItemInArena
| huimiao638/stk-code | src/karts/controller/arena_ai.cpp | C++ | gpl-3.0 | 23,379 |
/**
* Marlin 3D Printer Firmware
* Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
*
* 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/>.
*
*/
/**
* Minitronics v1.0/1.1 pin assignments
*/
#ifndef __AVR_ATmega1281__
#error "Oops! Make sure you have 'Minitronics' selected from the 'Tools -> Boards' menu."
#endif
#if HOTENDS > 2
#error "Minitronics supports up to 2 hotends. Comment this line to keep going."
#endif
#define BOARD_NAME "Minitronics v1.0 / v1.1"
#define LARGE_FLASH true
//
// Limit Switches
//
#define X_MIN_PIN 5
#define X_MAX_PIN 2
#define Y_MIN_PIN 2
#define Y_MAX_PIN 15
#define Z_MIN_PIN 6
#define Z_MAX_PIN -1
//
// Steppers
//
#define X_STEP_PIN 48
#define X_DIR_PIN 47
#define X_ENABLE_PIN 49
#define Y_STEP_PIN 39 // A6
#define Y_DIR_PIN 40 // A0
#define Y_ENABLE_PIN 38
#define Z_STEP_PIN 42 // A2
#define Z_DIR_PIN 43 // A6
#define Z_ENABLE_PIN 41 // A1
#define E0_STEP_PIN 45
#define E0_DIR_PIN 44
#define E0_ENABLE_PIN 27
#define E1_STEP_PIN 36
#define E1_DIR_PIN 35
#define E1_ENABLE_PIN 37
//
// Temperature Sensors
//
#define SDSS 16
#define LED_PIN 46
#define TEMP_0_PIN 7 // ANALOG NUMBERING
#define TEMP_1_PIN 6 // ANALOG NUMBERING
#define TEMP_BED_PIN 6 // ANALOG NUMBERING
//
// Heaters / Fans
//
#define HEATER_0_PIN 7 // EXTRUDER 1
#define HEATER_1_PIN 8 // EXTRUDER 2
#define HEATER_BED_PIN 3 // BED
#define FAN_PIN 9
//
// LCD / Controller
//
#define BEEPER_PIN -1
#if ENABLED(REPRAPWORLD_GRAPHICAL_LCD)
#define LCD_PINS_RS 15 // CS chip select /SS chip slave select
#define LCD_PINS_ENABLE 11 // SID (MOSI)
#define LCD_PINS_D4 10 // SCK (CLK) clock
#define BTN_EN1 18
#define BTN_EN2 17
#define BTN_ENC 25
#define SD_DETECT_PIN 30
#else
#define LCD_PINS_RS -1
#define LCD_PINS_ENABLE -1
#define LCD_PINS_D4 -1
#define LCD_PINS_D5 -1
#define LCD_PINS_D6 -1
#define LCD_PINS_D7 -1
// Buttons are directly attached using keypad
#define BTN_EN1 -1
#define BTN_EN2 -1
#define BTN_ENC -1
#define SD_DETECT_PIN -1 // Minitronics doesn't use this
#endif
| rdlaner/Marlin_Printrboard_Edits | Marlin/pins_MINITRONICS.h | C | gpl-3.0 | 3,141 |
import argparse, requests, sys, configparser, zipfile, os, shutil
from urllib.parse import urlparse, parse_qs
appname="ConverterUpdater"
author="Leo Durrant (2017)"
builddate="05/10/17"
version="0.1a"
release="alpha"
filesdelete=['ConUpdate.py', 'Converter.py', 'LBT.py', 'ConverterGUI.py', 'LBTGUI.py']
directoriesdelete=['convlib\\', 'LBTLIB\\', "data\\images\\", "data\\text\\"]
def readvaluefromconfig(filename, section, valuename):
try:
config = configparser.ConfigParser()
config.read(filename)
try:
val = config[section][valuename]
return val
except Exception as e:
print("Cannot find value %s in %s. Check %s.\n Exception: %s" % (valuename, section, filename, str(e)))
return None
except Exception as e:
print("Cannot read %s.\n Exception: %s" % (filename, str(e)))
return None
parser = argparse.ArgumentParser(description='Updater for Converter')
parser.add_argument('-cfg', '--config', nargs="?", help="The path to the configuration file. (Usually generated by Converter.)")
args= parser.parse_args()
parameterfile=args.config
if parameterfile == None:
parameterfile="updater.ini"
else:
parameterfile=str(parameterfile)
executeafterupdate=True
updatedownloadurl=urlparse(readvaluefromconfig(parameterfile, "updater", "downloadurl"))
appinstall=readvaluefromconfig(parameterfile, "updater", "appinstall")
executablefile=readvaluefromconfig(parameterfile, "updater", "executablefn")
keepconfig=readvaluefromconfig(parameterfile, "updater", "keepconfig")
if os.path.exists(appinstall):
if os.path.isdir(appinstall):
print("Directory found!")
else:
print("Path is not a directory.")
sys.exit(1)
else:
print("Path doesn't exist.")
sys.exit(1)
if not os.path.exists("{}\\{}".format(appinstall, executablefile)):
executeafterupdate=False
temporaryfile="download.tmp"
# print(str(args.config))
def downloadfile():
try:
with open(temporaryfile, "wb") as f:
print("Connecting...", end="")
response = requests.get(updatedownloadurl.geturl(), stream=True)
print("\rConnected! ")
total_length = response.headers.get('content-length')
if not total_length is None:
print("Downloading %s to %s (%s B)" % (str(updatedownloadurl.geturl()), temporaryfile, total_length))
else:
print("Downloading %s..." % (temporaryfile))
if total_length is None:
f.write(response.content)
else:
total_length=int(total_length)
for data in response.iter_content(chunk_size=4096):
# done = int(50 * dl / total_length)
# print("\r%s/%sB" % (done, total_length))
# dl += len(data)
f.write(data)
cleanfiles()
#print("\r%s/%sB" % (done, total_length))
except Exception as e:
print("\n\nFailed to connect to %s. Check the update parameters or try again later.\nException: %s" % (str(updatedownloadurl.geturl()), str(e)))
def cleanfiles():
for file in filesdelete:
fullpath="{}\\{}".format(appinstall, file)
if not os.path.exists(fullpath):
print("%s does not exist." % (fullpath))
else:
try:
os.remove(fullpath)
print("Deleted %s!" % (fullpath))
except Exception as e:
print("\n\nFailed to delete %s!\nException: %s" % (fullpath, str(e)))
for dirs in directoriesdelete:
fullpath="{}\\{}".format(appinstall, dirs)
if not os.path.exists(fullpath):
print("%s does not exist." % (fullpath))
else:
try:
shutil.rmtree(fullpath)
print("Deleted %s!" % (fullpath))
except Exception as e:
print("\n\nFailed to delete %s!\nException: %s" % (fullpath, str(e)))
extractfile(temporaryfile)
def extractfile(file):
print("Extracting %s to %s. Please wait!" % (str(file), appinstall))
try:
with zipfile.ZipFile(file, "r") as zip_r:
zip_r.extractall(appinstall)
except zipfile.BadZipfile as e:
print("\n\nAttempted to extract a bad zip file '%s'!\nException: %s" % (file, str(e)))
except Exception as e:
print("\n\nAn error occurred while trying to extract '%s'.\nException %s" % (file, str(e)))
print("Cleaning temporary files...")
try:
os.remove(file)
except Exception as e:
print("\n\nAn erro occurred while trying to delete temporary files.\n Exception: %s" % (str(e)))
runapp()
def runapp():
try:
pythonlocation=sys.executable
executablefullpath="{}\\{}".format(appinstall, executablefile)
print("Attempting to run app...")
os.system('{} {}'.format(pythonlocation, executablefullpath))
except Exception as e:
raise e
downloadfile() | ZanyLeonic/LeonicBinaryTool | ConUpdate.py | Python | gpl-3.0 | 5,039 |
<?php
/**
* Copyright (C) 2010 Arie Nugraha (dicarve@yahoo.com)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/* Biblio Author Adding Pop Windows */
// main system configuration
require '../../../ucsysconfig.inc.php';
// start the session
require UCS_BASE_DIR.'admin/default/session.inc.php';
require UCS_BASE_DIR.'admin/default/session_check.inc.php';
require SIMBIO_BASE_DIR.'simbio_GUI/table/simbio_table.inc.php';
require SIMBIO_BASE_DIR.'simbio_GUI/form_maker/simbio_form_table.inc.php';
require SIMBIO_BASE_DIR.'simbio_DB/simbio_dbop.inc.php';
// page title
$page_title = 'Authority List';
// check for biblioID in url
$biblioID = 0;
if (isset($_GET['biblioID']) AND $_GET['biblioID']) {
$biblioID = (integer)$_GET['biblioID'];
}
// utility function to check author name
function checkAuthor($str_author_name)
{
global $dbs;
$_q = $dbs->query('SELECT author_id FROM mst_author WHERE author_name=\''.$str_author_name.'\'');
if ($_q->num_rows > 0) {
$_d = $_q->fetch_row();
// return the author ID
return $_d[0];
}
return false;
}
// start the output buffer
ob_start();
/* main content */
// biblio author save proccess
if (isset($_POST['save']) AND (isset($_POST['authorID']) OR trim($_POST['search_str']))) {
$author_name = trim($dbs->escape_string(strip_tags($_POST['search_str'])));
// create new sql op object
$sql_op = new simbio_dbop($dbs);
// check if biblioID POST var exists
if (isset($_POST['biblioID']) AND !empty($_POST['biblioID'])) {
$data['biblio_id'] = intval($_POST['biblioID']);
// check if the author select list is empty or not
if (isset($_POST['authorID']) AND !empty($_POST['authorID'])) {
$data['author_id'] = $_POST['authorID'];
} else if ($author_name AND empty($_POST['authorID'])) {
// check author
$author_id = checkAuthor($author_name);
if ($author_id !== false) {
$data['author_id'] = $author_id;
} else {
// adding new author
$author_data['author_name'] = $author_name;
$author_data['authority_type'] = $_POST['type'];
$author_data['input_date'] = date('Y-m-d');
$author_data['last_update'] = date('Y-m-d');
// insert new author to author master table
@$sql_op->insert('mst_author', $author_data);
$data['author_id'] = $sql_op->insert_id;
}
}
$data['level'] = intval($_POST['level']);
if ($sql_op->insert('biblio_author', $data)) {
echo '<script type="text/javascript">';
echo 'alert(\''.__('Author succesfully updated!').'\');';
echo 'parent.setIframeContent(\'authorIframe\', \''.MODULES_WEB_ROOT_DIR.'bibliography/iframe_author.php?biblioID='.$data['biblio_id'].'\');';
echo '</script>';
} else {
utility::jsAlert(__('Author FAILED to Add. Please Contact System Administrator')."\n".$sql_op->error);
}
} else {
if (isset($_POST['authorID']) AND !empty($_POST['authorID'])) {
// add to current session
$_SESSION['biblioAuthor'][$_POST['authorID']] = array($_POST['authorID'], intval($_POST['level']));
} else if ($author_name AND empty($_POST['authorID'])) {
// check author
$author_id = checkAuthor($author_name);
if ($author_id !== false) {
$last_id = $author_id;
} else {
// adding new author
$data['author_name'] = $author_name;
$data['authority_type'] = $_POST['type'];
$data['input_date'] = date('Y-m-d');
$data['last_update'] = date('Y-m-d');
// insert new author to author master table
$sql_op->insert('mst_author', $data);
$last_id = $sql_op->insert_id;
}
$_SESSION['biblioAuthor'][$last_id] = array($last_id, intval($_POST['level']));
}
echo '<script type="text/javascript">';
echo 'alert(\''.__('Author added!').'\');';
echo 'parent.setIframeContent(\'authorIframe\', \''.MODULES_WEB_ROOT_DIR.'bibliography/iframe_author.php\');';
echo '</script>';
}
}
?>
<div style="padding: 5px; background: #CCCCCC;">
<form name="mainForm" action="pop_author.php?biblioID=<?php echo $biblioID; ?>" method="post">
<div>
<strong><?php echo __('Add Author'); ?> </strong>
<hr />
<form name="searchAuthor" method="post" style="display: inline;">
<?php
$ajax_exp = "ajaxFillSelect('../../AJAX_lookup_handler.php', 'mst_author', 'author_id:author_name', 'authorID', $('#search_str').val())";
echo __('Author Name'); ?> : <input type="text" name="search_str" id="search_str" style="width: 30%;" onkeyup="<?php echo $ajax_exp; ?>" onchange="<?php echo $ajax_exp; ?>" />
<select name="type" style="width: 20%;"><?php
foreach ($sysconf['authority_type'] as $type_id => $type) {
echo '<option value="'.$type_id.'">'.$type.'</option>';
}
?></select>
<select name="level" style="width: 20%;"><?php
foreach ($sysconf['authority_level'] as $level_id => $level) {
echo '<option value="'.$level_id.'">'.$level.'</option>';
}
?></select>
</div>
<div style="margin-top: 5px;">
<select name="authorID" id="authorID" size="5" style="width: 100%;"><option value="0"><?php echo __('Type to search for existing authors or to add a new one'); ?></option></select>
<?php if ($biblioID) { echo '<input type="hidden" name="biblioID" value="'.$biblioID.'" />'; } ?>
<input type="submit" name="save" value="<?php echo __('Insert To Bibliography'); ?>" style="margin-top: 5px;" />
</div>
</form>
</div>
<?php
/* main content end */
$content = ob_get_clean();
// include the page template
require UCS_BASE_DIR.'/admin/admin_themes/notemplate_page_tpl.php';
?>
| dicarve/slims3-stable15-jquery | ucs/admin/modules/bibliography/pop_author.php | PHP | gpl-3.0 | 6,651 |
<?php
$string['wq'] = 'Matematica e scienza - WIRIS';
$string['pluginname'] = 'Matematica e scienza - WIRIS';
$string['pluginnamesummary'] = '';
$string['wq_help'] = 'Generic WIRIS quizzes Help';
$string['editingwq'] = 'Editing a generic WIRIS question';
$string['addingwq'] = 'Adding a generic WIRIS question';
$string['wqsummary'] = 'This adds a generic WIRIS question. Only for test purpose. It will be hide from here.';
$string['wirisquestionincorrect'] = 'Spiacente. Il sistema non può generare una delle domande del quiz. <br />È possibile che ci sia un problema di connessione temporaneo. <br />È possibile che l\'algoritmo della domanda presenti un errore che a volte causa dei problemi. <br />È possibile che l\'errore si verifichi sempre. <br />In questi casi, <br />puoi riprovare il quiz, senza nessuna penalizzazione, facendo clic semplicemente su Continua. <br />Puoi anche comunicare agli insegnanti che si è verificato un problema con la seguente domanda: \'{$a->questionname}\'';
$string['wirisquizzeserror'] = 'Sorry! There was an error in WIRIS quizzes.';
?> | nitro2010/moodle | question/wq/lang/it/qtype_wq.php | PHP | gpl-3.0 | 1,093 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.