code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
/* Copyright (c) 2012-2013, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/i2c.h> #include <linux/gpio.h> #include <asm/mach-types.h> #include <mach/camera.h> #include <mach/msm_bus_board.h> #include <mach/gpiomux.h> #include <mach/socinfo.h> #include "../devices.h" #include "../board-8064.h" #ifdef CONFIG_MSM_CAMERA static struct gpiomux_setting cam_settings[] = { { .func = GPIOMUX_FUNC_GPIO, /*suspend*/ .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_DOWN, }, { .func = GPIOMUX_FUNC_1, /*active 1*/ .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_NONE, }, { .func = GPIOMUX_FUNC_GPIO, /*active 2*/ .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_NONE, }, { #ifdef CONFIG_ZTEMT_CAMERA_COMMON //config GPIO_2's fuction 4:CAM_MCLK2 as CAM_MCLK for front camera now .func = GPIOMUX_FUNC_4, /*active 3*/ #else .func = GPIOMUX_FUNC_2, /*active 3*/ #endif .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_NONE, }, { .func = GPIOMUX_FUNC_5, /*active 4*/ .drv = GPIOMUX_DRV_8MA, .pull = GPIOMUX_PULL_UP, }, { .func = GPIOMUX_FUNC_6, /*active 5*/ .drv = GPIOMUX_DRV_8MA, .pull = GPIOMUX_PULL_UP, }, { .func = GPIOMUX_FUNC_2, /*active 6*/ .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_UP, }, { .func = GPIOMUX_FUNC_3, /*active 7*/ .drv = GPIOMUX_DRV_8MA, .pull = GPIOMUX_PULL_UP, }, { .func = GPIOMUX_FUNC_GPIO, /*i2c suspend*/ .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_KEEPER, }, { .func = GPIOMUX_FUNC_9, /*active 9*/ .drv = GPIOMUX_DRV_8MA, .pull = GPIOMUX_PULL_NONE, }, { .func = GPIOMUX_FUNC_A, /*active 10*/ .drv = GPIOMUX_DRV_8MA, .pull = GPIOMUX_PULL_NONE, }, { .func = GPIOMUX_FUNC_6, /*active 11*/ .drv = GPIOMUX_DRV_8MA, .pull = GPIOMUX_PULL_NONE, }, { .func = GPIOMUX_FUNC_4, /*active 12*/ .drv = GPIOMUX_DRV_2MA, .pull = GPIOMUX_PULL_NONE, }, }; static struct msm_gpiomux_config apq8064_cam_common_configs[] = { { .gpio = 1, .settings = { [GPIOMUX_ACTIVE] = &cam_settings[2], [GPIOMUX_SUSPENDED] = &cam_settings[0], }, }, { .gpio = 2, .settings = { #ifdef CONFIG_ZTEMT_CAMERA_COMMON [GPIOMUX_ACTIVE] = &cam_settings[3], #else [GPIOMUX_ACTIVE] = &cam_settings[12], #endif [GPIOMUX_SUSPENDED] = &cam_settings[0], }, }, { .gpio = 3, .settings = { [GPIOMUX_ACTIVE] = &cam_settings[2], [GPIOMUX_SUSPENDED] = &cam_settings[0], }, }, #ifdef CONFIG_ZTEMT_CAMERA_COMMON //GPIO4 is configed as "BOOT_CONFIG" now, the original config of //GPIO4 is CAM_MCLK1 for front camera, so remove this config here #else { .gpio = 4, .settings = { [GPIOMUX_ACTIVE] = &cam_settings[3], [GPIOMUX_SUSPENDED] = &cam_settings[0], }, }, #endif { .gpio = 5, .settings = { [GPIOMUX_ACTIVE] = &cam_settings[1], [GPIOMUX_SUSPENDED] = &cam_settings[0], }, }, { .gpio = 34, .settings = { [GPIOMUX_ACTIVE] = &cam_settings[2], [GPIOMUX_SUSPENDED] = &cam_settings[0], }, }, { .gpio = 107, .settings = { [GPIOMUX_ACTIVE] = &cam_settings[2], [GPIOMUX_SUSPENDED] = &cam_settings[0], }, }, { .gpio = 10, .settings = { [GPIOMUX_ACTIVE] = &cam_settings[9], [GPIOMUX_SUSPENDED] = &cam_settings[8], }, }, { .gpio = 11, .settings = { [GPIOMUX_ACTIVE] = &cam_settings[10], [GPIOMUX_SUSPENDED] = &cam_settings[8], }, }, #ifdef CONFIG_ZTEMT_CAMERA_COMMON //GPIO12-13 are not for camera related use #else { .gpio = 12, .settings = { [GPIOMUX_ACTIVE] = &cam_settings[11], [GPIOMUX_SUSPENDED] = &cam_settings[8], }, }, { .gpio = 13, .settings = { [GPIOMUX_ACTIVE] = &cam_settings[11], [GPIOMUX_SUSPENDED] = &cam_settings[8], }, }, #endif }; #ifdef CONFIG_ZTEMT_CAMERA_COMMON #define VFE_CAMIF_TIMER1_GPIO 12 #else #define VFE_CAMIF_TIMER1_GPIO 3 #endif #define VFE_CAMIF_TIMER2_GPIO 1 static struct msm_camera_sensor_flash_src msm_flash_src = { .flash_sr_type = MSM_CAMERA_FLASH_SRC_EXT, ._fsrc.ext_driver_src.led_en = VFE_CAMIF_TIMER1_GPIO, ._fsrc.ext_driver_src.led_flash_en = VFE_CAMIF_TIMER2_GPIO, #ifdef CONFIG_ZTEMT_CAMERA_FLASH_LM3642 ._fsrc.ext_driver_src.flash_id = MAM_CAMERA_EXT_LED_FLASH_LM3642, #else ._fsrc.ext_driver_src.flash_id = MAM_CAMERA_EXT_LED_FLASH_SC628A, #endif }; static struct msm_gpiomux_config apq8064_cam_2d_configs[] = { }; static struct msm_bus_vectors cam_init_vectors[] = { { .src = MSM_BUS_MASTER_VFE, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 0, .ib = 0, }, { .src = MSM_BUS_MASTER_VPE, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 0, .ib = 0, }, { .src = MSM_BUS_MASTER_JPEG_ENC, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 0, .ib = 0, }, }; static struct msm_bus_vectors cam_preview_vectors[] = { { .src = MSM_BUS_MASTER_VFE, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 27648000, .ib = 2656000000UL, }, { .src = MSM_BUS_MASTER_VPE, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 0, .ib = 0, }, { .src = MSM_BUS_MASTER_JPEG_ENC, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 0, .ib = 0, }, }; static struct msm_bus_vectors cam_video_vectors[] = { { .src = MSM_BUS_MASTER_VFE, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 600000000, .ib = 2656000000UL, }, { .src = MSM_BUS_MASTER_VPE, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 206807040, .ib = 488816640, }, { .src = MSM_BUS_MASTER_JPEG_ENC, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 0, .ib = 0, }, }; static struct msm_bus_vectors cam_snapshot_vectors[] = { { .src = MSM_BUS_MASTER_VFE, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 600000000, .ib = 2656000000UL, }, { .src = MSM_BUS_MASTER_VPE, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 0, .ib = 0, }, { .src = MSM_BUS_MASTER_JPEG_ENC, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 540000000, .ib = 1350000000, }, }; static struct msm_bus_vectors cam_zsl_vectors[] = { { .src = MSM_BUS_MASTER_VFE, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 600000000, .ib = 2656000000UL, }, { .src = MSM_BUS_MASTER_VPE, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 0, .ib = 0, }, { .src = MSM_BUS_MASTER_JPEG_ENC, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 540000000, .ib = 1350000000, }, }; static struct msm_bus_vectors cam_video_ls_vectors[] = { { .src = MSM_BUS_MASTER_VFE, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 348192000, .ib = 617103360, }, { .src = MSM_BUS_MASTER_VPE, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 206807040, .ib = 488816640, }, { .src = MSM_BUS_MASTER_JPEG_ENC, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 540000000, .ib = 1350000000, }, }; static struct msm_bus_vectors cam_dual_vectors[] = { { .src = MSM_BUS_MASTER_VFE, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 600000000, .ib = 2656000000UL, }, { .src = MSM_BUS_MASTER_VPE, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 206807040, .ib = 488816640, }, { .src = MSM_BUS_MASTER_JPEG_ENC, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 540000000, .ib = 1350000000, }, { .src = MSM_BUS_MASTER_JPEG_ENC, .dst = MSM_BUS_SLAVE_MM_IMEM, .ab = 43200000, .ib = 69120000, }, { .src = MSM_BUS_MASTER_VFE, .dst = MSM_BUS_SLAVE_MM_IMEM, .ab = 43200000, .ib = 69120000, }, }; static struct msm_bus_vectors cam_low_power_vectors[] = { { .src = MSM_BUS_MASTER_VFE, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 1451520, .ib = 3870720, }, { .src = MSM_BUS_MASTER_VPE, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 0, .ib = 0, }, { .src = MSM_BUS_MASTER_JPEG_ENC, .dst = MSM_BUS_SLAVE_EBI_CH0, .ab = 0, .ib = 0, }, }; static struct msm_bus_paths cam_bus_client_config[] = { { ARRAY_SIZE(cam_init_vectors), cam_init_vectors, }, { ARRAY_SIZE(cam_preview_vectors), cam_preview_vectors, }, { ARRAY_SIZE(cam_video_vectors), cam_video_vectors, }, { ARRAY_SIZE(cam_snapshot_vectors), cam_snapshot_vectors, }, { ARRAY_SIZE(cam_zsl_vectors), cam_zsl_vectors, }, { ARRAY_SIZE(cam_video_ls_vectors), cam_video_ls_vectors, }, { ARRAY_SIZE(cam_dual_vectors), cam_dual_vectors, }, { ARRAY_SIZE(cam_low_power_vectors), cam_low_power_vectors, }, }; static struct msm_bus_scale_pdata cam_bus_client_pdata = { cam_bus_client_config, ARRAY_SIZE(cam_bus_client_config), .name = "msm_camera", }; static struct msm_camera_device_platform_data msm_camera_csi_device_data[] = { { .csid_core = 0, .is_vpe = 1, .cam_bus_scale_table = &cam_bus_client_pdata, }, { .csid_core = 1, .is_vpe = 1, .cam_bus_scale_table = &cam_bus_client_pdata, }, }; static struct camera_vreg_t apq_8064_cam_vreg[] = { #ifdef CONFIG_IMX135 {"cam_vdig", REG_LDO, 1050000, 1050000, 105000}, #else {"cam_vdig", REG_LDO, 1200000, 1200000, 105000}, #endif {"cam_vio", REG_VS, 0, 0, 0}, {"cam_vana", REG_LDO, 2800000, 2850000, 85600}, {"cam_vaf", REG_LDO, 2800000, 2850000, 300000}, }; #ifdef CONFIG_OV5648 static struct camera_vreg_t apq_8064_cam_vreg_ov5648[] = { {"cam_vio", REG_VS, 0, 0, 0,10}, {"cam_vana", REG_LDO, 2800000, 2850000, 85600,10}, }; #endif #define CAML_RSTN PM8921_GPIO_PM_TO_SYS(28) #define CAMR_RSTN 34 #ifdef CONFIG_OV5648 #define CAMR_PWD 36 //The PWD of front camera OV5648 for Z5MINI #endif #ifdef CONFIG_ZTEMT_IMX091_VCM_ENABLE #define BACK_CAM_PWDN_VCM 37 #endif static struct gpio apq8064_common_cam_gpio[] = { }; static struct gpio apq8064_back_cam_gpio[] = { {5, GPIOF_DIR_IN, "CAMIF_MCLK"}, {CAML_RSTN, GPIOF_DIR_OUT, "CAM_RESET"}, #ifdef CONFIG_ZTEMT_IMX091_VCM_ENABLE {BACK_CAM_PWDN_VCM,GPIOF_DIR_OUT,"BACK_CAM_PWDN_VCM"}, #endif }; static struct msm_gpio_set_tbl apq8064_back_cam_gpio_set_tbl[] = { {CAML_RSTN, GPIOF_OUT_INIT_LOW, 10000}, {CAML_RSTN, GPIOF_OUT_INIT_HIGH, 10000}, #ifdef CONFIG_ZTEMT_IMX091_VCM_ENABLE {BACK_CAM_PWDN_VCM, GPIOF_OUT_INIT_LOW, 10000}, {BACK_CAM_PWDN_VCM, GPIOF_OUT_INIT_HIGH, 10000}, #endif }; static struct msm_camera_gpio_conf apq8064_back_cam_gpio_conf = { .cam_gpiomux_conf_tbl = apq8064_cam_2d_configs, .cam_gpiomux_conf_tbl_size = ARRAY_SIZE(apq8064_cam_2d_configs), .cam_gpio_common_tbl = apq8064_common_cam_gpio, .cam_gpio_common_tbl_size = ARRAY_SIZE(apq8064_common_cam_gpio), .cam_gpio_req_tbl = apq8064_back_cam_gpio, .cam_gpio_req_tbl_size = ARRAY_SIZE(apq8064_back_cam_gpio), .cam_gpio_set_tbl = apq8064_back_cam_gpio_set_tbl, .cam_gpio_set_tbl_size = ARRAY_SIZE(apq8064_back_cam_gpio_set_tbl), }; static struct gpio apq8064_front_cam_gpio[] = { #ifdef CONFIG_ZTEMT_CAMERA_COMMON {2, GPIOF_DIR_IN, "CAMIF_MCLK"}, #else {4, GPIOF_DIR_IN, "CAMIF_MCLK"}, {12, GPIOF_DIR_IN, "CAMIF_I2C_DATA"}, {13, GPIOF_DIR_IN, "CAMIF_I2C_CLK"}, #endif {CAMR_RSTN, GPIOF_DIR_OUT, "CAM_RESET"}, #ifdef CONFIG_OV5648 {CAMR_PWD,GPIOF_DIR_OUT,"CAM_PWD"}, #endif }; static struct msm_gpio_set_tbl apq8064_front_cam_gpio_set_tbl[] = { #ifdef CONFIG_OV5648 {CAMR_PWD, GPIOF_OUT_INIT_LOW, 10000}, {CAMR_PWD, GPIOF_OUT_INIT_HIGH, 10000}, #endif {CAMR_RSTN, GPIOF_OUT_INIT_LOW, 10000}, {CAMR_RSTN, GPIOF_OUT_INIT_HIGH, 10000}, }; static struct msm_camera_gpio_conf apq8064_front_cam_gpio_conf = { .cam_gpiomux_conf_tbl = apq8064_cam_2d_configs, .cam_gpiomux_conf_tbl_size = ARRAY_SIZE(apq8064_cam_2d_configs), .cam_gpio_common_tbl = apq8064_common_cam_gpio, .cam_gpio_common_tbl_size = ARRAY_SIZE(apq8064_common_cam_gpio), .cam_gpio_req_tbl = apq8064_front_cam_gpio, .cam_gpio_req_tbl_size = ARRAY_SIZE(apq8064_front_cam_gpio), .cam_gpio_set_tbl = apq8064_front_cam_gpio_set_tbl, .cam_gpio_set_tbl_size = ARRAY_SIZE(apq8064_front_cam_gpio_set_tbl), }; static struct msm_camera_i2c_conf apq8064_back_cam_i2c_conf = { .use_i2c_mux = 1, .mux_dev = &msm8960_device_i2c_mux_gsbi4, .i2c_mux_mode = MODE_L, }; static struct i2c_board_info msm_act_main_cam_i2c_info = { I2C_BOARD_INFO("msm_actuator", 0x11), }; static struct msm_actuator_info msm_act_main_cam_0_info = { .board_info = &msm_act_main_cam_i2c_info, .cam_name = MSM_ACTUATOR_MAIN_CAM_0, .bus_id = APQ_8064_GSBI4_QUP_I2C_BUS_ID, .vcm_pwd = 0, .vcm_enable = 0, }; static struct i2c_board_info msm_act_main_cam1_i2c_info = { I2C_BOARD_INFO("msm_actuator", 0x18), }; static struct msm_actuator_info msm_act_main_cam_1_info = { .board_info = &msm_act_main_cam1_i2c_info, .cam_name = MSM_ACTUATOR_MAIN_CAM_1, .bus_id = APQ_8064_GSBI4_QUP_I2C_BUS_ID, .vcm_pwd = 0, .vcm_enable = 0, }; static struct msm_camera_i2c_conf apq8064_front_cam_i2c_conf = { .use_i2c_mux = 1, .mux_dev = &msm8960_device_i2c_mux_gsbi4, .i2c_mux_mode = MODE_L, }; static struct msm_camera_sensor_flash_data flash_imx135 = { #ifdef CONFIG_ZTEMT_CAMERA_FLASH_LM3642 .flash_type = MSM_CAMERA_FLASH_LED, .flash_src = &msm_flash_src, #else .flash_type = MSM_CAMERA_FLASH_NONE, #endif }; static struct msm_camera_csi_lane_params imx135_csi_lane_params = { .csi_lane_assign = 0xE4, .csi_lane_mask = 0xF, }; static struct msm_camera_sensor_platform_info sensor_board_info_imx135 = { .mount_angle = 90, .cam_vreg = apq_8064_cam_vreg, .num_vreg = ARRAY_SIZE(apq_8064_cam_vreg), .gpio_conf = &apq8064_back_cam_gpio_conf, .i2c_conf = &apq8064_back_cam_i2c_conf, .csi_lane_params = &imx135_csi_lane_params, }; static struct msm_camera_sensor_info msm_camera_sensor_imx135_data = { .sensor_name = "imx135", .pdata = &msm_camera_csi_device_data[0], .flash_data = &flash_imx135, .sensor_platform_info = &sensor_board_info_imx135, .csi_if = 1, .camera_type = BACK_CAMERA_2D, .sensor_type = BAYER_SENSOR, .actuator_info = &msm_act_main_cam_0_info, }; static struct msm_camera_sensor_flash_data flash_imx074 = { .flash_type = MSM_CAMERA_FLASH_LED, .flash_src = &msm_flash_src }; static struct msm_camera_csi_lane_params imx074_csi_lane_params = { .csi_lane_assign = 0xE4, .csi_lane_mask = 0xF, }; static struct msm_camera_sensor_platform_info sensor_board_info_imx074 = { .mount_angle = 90, .cam_vreg = apq_8064_cam_vreg, .num_vreg = ARRAY_SIZE(apq_8064_cam_vreg), .gpio_conf = &apq8064_back_cam_gpio_conf, .i2c_conf = &apq8064_back_cam_i2c_conf, .csi_lane_params = &imx074_csi_lane_params, }; static struct i2c_board_info imx074_eeprom_i2c_info = { I2C_BOARD_INFO("imx074_eeprom", 0x34 << 1), }; static struct msm_eeprom_info imx074_eeprom_info = { .board_info = &imx074_eeprom_i2c_info, .bus_id = APQ_8064_GSBI4_QUP_I2C_BUS_ID, }; static struct msm_camera_sensor_info msm_camera_sensor_imx074_data = { .sensor_name = "imx074", .pdata = &msm_camera_csi_device_data[0], .flash_data = &flash_imx074, .sensor_platform_info = &sensor_board_info_imx074, .csi_if = 1, .camera_type = BACK_CAMERA_2D, .sensor_type = BAYER_SENSOR, .actuator_info = &msm_act_main_cam_0_info, .eeprom_info = &imx074_eeprom_info, }; static struct msm_camera_csi_lane_params imx091_csi_lane_params = { .csi_lane_assign = 0xE4, .csi_lane_mask = 0xF, }; static struct msm_camera_sensor_flash_data flash_imx091 = { #ifdef CONFIG_ZTEMT_CAMERA_FLASH_LM3642 .flash_type = MSM_CAMERA_FLASH_LED, .flash_src = &msm_flash_src, #else .flash_type = MSM_CAMERA_FLASH_NONE, #endif }; static struct msm_camera_sensor_platform_info sensor_board_info_imx091 = { #ifdef CONFIG_ZTEMT_CAMERA_COMMON .mount_angle = 90, #else .mount_angle = 0, #endif .cam_vreg = apq_8064_cam_vreg, .num_vreg = ARRAY_SIZE(apq_8064_cam_vreg), .gpio_conf = &apq8064_back_cam_gpio_conf, .i2c_conf = &apq8064_back_cam_i2c_conf, .csi_lane_params = &imx091_csi_lane_params, }; static struct i2c_board_info imx091_eeprom_i2c_info = { I2C_BOARD_INFO("imx091_eeprom", 0x21), }; static struct msm_eeprom_info imx091_eeprom_info = { .board_info = &imx091_eeprom_i2c_info, .bus_id = APQ_8064_GSBI4_QUP_I2C_BUS_ID, }; static struct msm_camera_sensor_info msm_camera_sensor_imx091_data = { .sensor_name = "imx091", .pdata = &msm_camera_csi_device_data[0], .flash_data = &flash_imx091, .sensor_platform_info = &sensor_board_info_imx091, .csi_if = 1, .camera_type = BACK_CAMERA_2D, .sensor_type = BAYER_SENSOR, .actuator_info = &msm_act_main_cam_1_info, .eeprom_info = &imx091_eeprom_info, }; static struct msm_camera_sensor_flash_data flash_s5k3l1yx = { .flash_type = MSM_CAMERA_FLASH_NONE, }; static struct msm_camera_csi_lane_params s5k3l1yx_csi_lane_params = { .csi_lane_assign = 0xE4, .csi_lane_mask = 0xF, }; static struct msm_camera_sensor_platform_info sensor_board_info_s5k3l1yx = { .mount_angle = 90, .cam_vreg = apq_8064_cam_vreg, .num_vreg = ARRAY_SIZE(apq_8064_cam_vreg), .gpio_conf = &apq8064_back_cam_gpio_conf, .i2c_conf = &apq8064_back_cam_i2c_conf, .csi_lane_params = &s5k3l1yx_csi_lane_params, }; static struct msm_camera_sensor_info msm_camera_sensor_s5k3l1yx_data = { .sensor_name = "s5k3l1yx", .pdata = &msm_camera_csi_device_data[0], .flash_data = &flash_s5k3l1yx, .sensor_platform_info = &sensor_board_info_s5k3l1yx, .csi_if = 1, .camera_type = BACK_CAMERA_2D, .sensor_type = BAYER_SENSOR, }; static struct msm_camera_sensor_flash_data flash_mt9m114 = { .flash_type = MSM_CAMERA_FLASH_NONE }; static struct msm_camera_csi_lane_params mt9m114_csi_lane_params = { .csi_lane_assign = 0xE4, .csi_lane_mask = 0x1, }; static struct msm_camera_sensor_platform_info sensor_board_info_mt9m114 = { .mount_angle = 90, .cam_vreg = apq_8064_cam_vreg, .num_vreg = ARRAY_SIZE(apq_8064_cam_vreg), .gpio_conf = &apq8064_front_cam_gpio_conf, .i2c_conf = &apq8064_front_cam_i2c_conf, .csi_lane_params = &mt9m114_csi_lane_params, }; static struct msm_camera_sensor_info msm_camera_sensor_mt9m114_data = { .sensor_name = "mt9m114", .pdata = &msm_camera_csi_device_data[1], .flash_data = &flash_mt9m114, .sensor_platform_info = &sensor_board_info_mt9m114, .csi_if = 1, .camera_type = FRONT_CAMERA_2D, .sensor_type = YUV_SENSOR, }; static struct msm_camera_sensor_flash_data flash_ov2720 = { .flash_type = MSM_CAMERA_FLASH_NONE, }; static struct msm_camera_csi_lane_params ov2720_csi_lane_params = { .csi_lane_assign = 0xE4, .csi_lane_mask = 0x3, }; static struct msm_camera_sensor_platform_info sensor_board_info_ov2720 = { .mount_angle = 0, .cam_vreg = apq_8064_cam_vreg, .num_vreg = ARRAY_SIZE(apq_8064_cam_vreg), .gpio_conf = &apq8064_front_cam_gpio_conf, .i2c_conf = &apq8064_front_cam_i2c_conf, .csi_lane_params = &ov2720_csi_lane_params, }; static struct msm_camera_sensor_info msm_camera_sensor_ov2720_data = { .sensor_name = "ov2720", .pdata = &msm_camera_csi_device_data[1], .flash_data = &flash_ov2720, .sensor_platform_info = &sensor_board_info_ov2720, .csi_if = 1, .camera_type = FRONT_CAMERA_2D, .sensor_type = BAYER_SENSOR, }; #ifdef CONFIG_IMX132 static struct msm_camera_sensor_flash_data flash_imx132 = { .flash_type = MSM_CAMERA_FLASH_NONE, }; static struct msm_camera_csi_lane_params imx132_csi_lane_params = { .csi_lane_assign = 0xE4, .csi_lane_mask = 0x3, }; static struct msm_camera_sensor_platform_info sensor_board_info_imx132 = { .mount_angle = 270, .cam_vreg = apq_8064_cam_vreg, .num_vreg = ARRAY_SIZE(apq_8064_cam_vreg), .gpio_conf = &apq8064_front_cam_gpio_conf, .i2c_conf = &apq8064_front_cam_i2c_conf, .csi_lane_params = &imx132_csi_lane_params, }; static struct msm_camera_sensor_info msm_camera_sensor_imx132_data = { .sensor_name = "imx132", .pdata = &msm_camera_csi_device_data[1], .flash_data = &flash_imx132, .sensor_platform_info = &sensor_board_info_imx132, .csi_if = 1, .camera_type = FRONT_CAMERA_2D, .sensor_type = BAYER_SENSOR, }; #endif #ifdef CONFIG_OV5648 static struct msm_camera_sensor_flash_data flash_ov5648 = { .flash_type = MSM_CAMERA_FLASH_NONE, }; static struct msm_camera_csi_lane_params ov5648_csi_lane_params = { .csi_lane_assign = 0xE4, .csi_lane_mask = 0x3, }; static struct msm_camera_sensor_platform_info sensor_board_info_ov5648 = { .mount_angle = 270, .cam_vreg = apq_8064_cam_vreg_ov5648, .num_vreg = ARRAY_SIZE(apq_8064_cam_vreg_ov5648), .gpio_conf = &apq8064_front_cam_gpio_conf, .i2c_conf = &apq8064_front_cam_i2c_conf, .csi_lane_params = &ov5648_csi_lane_params, }; static struct msm_camera_sensor_info msm_camera_sensor_ov5648_data = { .sensor_name = "ov5648", .pdata = &msm_camera_csi_device_data[1], .flash_data = &flash_ov5648, .sensor_platform_info = &sensor_board_info_ov5648, .csi_if = 1, .camera_type = FRONT_CAMERA_2D, .sensor_type = BAYER_SENSOR, }; #endif static struct platform_device msm_camera_server = { .name = "msm_cam_server", .id = 0, }; void __init apq8064_init_cam(void) { /* for SGLTE2 platform, do not configure i2c/gpiomux gsbi4 is used for * some other purpose */ if (socinfo_get_platform_subtype() != PLATFORM_SUBTYPE_SGLTE2) { msm_gpiomux_install(apq8064_cam_common_configs, ARRAY_SIZE(apq8064_cam_common_configs)); } if (machine_is_apq8064_cdp()) { sensor_board_info_imx074.mount_angle = 0; sensor_board_info_mt9m114.mount_angle = 0; } else if (machine_is_apq8064_liquid()) sensor_board_info_imx074.mount_angle = 180; platform_device_register(&msm_camera_server); if (socinfo_get_platform_subtype() != PLATFORM_SUBTYPE_SGLTE2) platform_device_register(&msm8960_device_i2c_mux_gsbi4); platform_device_register(&msm8960_device_csiphy0); platform_device_register(&msm8960_device_csiphy1); platform_device_register(&msm8960_device_csid0); platform_device_register(&msm8960_device_csid1); platform_device_register(&msm8960_device_ispif); platform_device_register(&msm8960_device_vfe); platform_device_register(&msm8960_device_vpe); } #ifdef CONFIG_I2C static struct i2c_board_info apq8064_camera_i2c_boardinfo[] = { { I2C_BOARD_INFO("imx074", 0x1A), .platform_data = &msm_camera_sensor_imx074_data, }, { I2C_BOARD_INFO("imx135", 0x20), .platform_data = &msm_camera_sensor_imx135_data, }, { I2C_BOARD_INFO("mt9m114", 0x48), .platform_data = &msm_camera_sensor_mt9m114_data, }, { I2C_BOARD_INFO("ov2720", 0x6C), .platform_data = &msm_camera_sensor_ov2720_data, }, { I2C_BOARD_INFO("sc628a", 0x6E), }, #ifdef CONFIG_ZTEMT_CAMERA_FLASH_LM3642 { I2C_BOARD_INFO("lm3642", 0x63),//camera flash led driver ic }, #endif { I2C_BOARD_INFO("imx091", 0x34), .platform_data = &msm_camera_sensor_imx091_data, }, { I2C_BOARD_INFO("s5k3l1yx", 0x21), //conflict with imx135, change from 0x20 to 0x21, tanyijun .platform_data = &msm_camera_sensor_s5k3l1yx_data, }, #ifdef CONFIG_IMX132 { I2C_BOARD_INFO("imx132", 0x6D),//use i2c slave write addr .platform_data = &msm_camera_sensor_imx132_data, }, #endif #ifdef CONFIG_OV5648 { I2C_BOARD_INFO("ov5648", 0x6d),//use i2c slave write addr .platform_data = &msm_camera_sensor_ov5648_data, }, #endif }; struct msm_camera_board_info apq8064_camera_board_info = { .board_info = apq8064_camera_i2c_boardinfo, .num_i2c_board_info = ARRAY_SIZE(apq8064_camera_i2c_boardinfo), }; #endif #endif
ztemt/Z5mini_H112_kernel
arch/arm/mach-msm/board/zte-camera.c
C
gpl-2.0
23,184
/* * linux/lib/vsprintf.c * * Copyright (C) 1991, 1992 Linus Torvalds * (C) Copyright 2000-2009 * Wolfgang Denk, DENX Software Engineering, wd@denx.de. */ /* vsprintf.c -- Lars Wirzenius & Linus Torvalds. */ /* * Wirzenius wrote this portably, Torvalds fucked it up :-) * * from hush: simple_itoa() was lifted from boa-0.93.15 */ #include <common.h> #include <charset.h> #include <efi_loader.h> #include <div64.h> #include <hexdump.h> #include <stdarg.h> #include <uuid.h> #include <vsprintf.h> #include <linux/ctype.h> #include <linux/err.h> #include <linux/types.h> #include <linux/string.h> /* we use this so that we can do without the ctype library */ #define is_digit(c) ((c) >= '0' && (c) <= '9') static int skip_atoi(const char **s) { int i = 0; while (is_digit(**s)) i = i * 10 + *((*s)++) - '0'; return i; } /* Decimal conversion is by far the most typical, and is used * for /proc and /sys data. This directly impacts e.g. top performance * with many processes running. We optimize it for speed * using code from * http://www.cs.uiowa.edu/~jones/bcd/decimal.html * (with permission from the author, Douglas W. Jones). */ /* Formats correctly any integer in [0,99999]. * Outputs from one to five digits depending on input. * On i386 gcc 4.1.2 -O2: ~250 bytes of code. */ static char *put_dec_trunc(char *buf, unsigned q) { unsigned d3, d2, d1, d0; d1 = (q>>4) & 0xf; d2 = (q>>8) & 0xf; d3 = (q>>12); d0 = 6*(d3 + d2 + d1) + (q & 0xf); q = (d0 * 0xcd) >> 11; d0 = d0 - 10*q; *buf++ = d0 + '0'; /* least significant digit */ d1 = q + 9*d3 + 5*d2 + d1; if (d1 != 0) { q = (d1 * 0xcd) >> 11; d1 = d1 - 10*q; *buf++ = d1 + '0'; /* next digit */ d2 = q + 2*d2; if ((d2 != 0) || (d3 != 0)) { q = (d2 * 0xd) >> 7; d2 = d2 - 10*q; *buf++ = d2 + '0'; /* next digit */ d3 = q + 4*d3; if (d3 != 0) { q = (d3 * 0xcd) >> 11; d3 = d3 - 10*q; *buf++ = d3 + '0'; /* next digit */ if (q != 0) *buf++ = q + '0'; /* most sign. digit */ } } } return buf; } /* Same with if's removed. Always emits five digits */ static char *put_dec_full(char *buf, unsigned q) { /* BTW, if q is in [0,9999], 8-bit ints will be enough, */ /* but anyway, gcc produces better code with full-sized ints */ unsigned d3, d2, d1, d0; d1 = (q>>4) & 0xf; d2 = (q>>8) & 0xf; d3 = (q>>12); /* * Possible ways to approx. divide by 10 * gcc -O2 replaces multiply with shifts and adds * (x * 0xcd) >> 11: 11001101 - shorter code than * 0x67 (on i386) * (x * 0x67) >> 10: 1100111 * (x * 0x34) >> 9: 110100 - same * (x * 0x1a) >> 8: 11010 - same * (x * 0x0d) >> 7: 1101 - same, shortest code (on i386) */ d0 = 6*(d3 + d2 + d1) + (q & 0xf); q = (d0 * 0xcd) >> 11; d0 = d0 - 10*q; *buf++ = d0 + '0'; d1 = q + 9*d3 + 5*d2 + d1; q = (d1 * 0xcd) >> 11; d1 = d1 - 10*q; *buf++ = d1 + '0'; d2 = q + 2*d2; q = (d2 * 0xd) >> 7; d2 = d2 - 10*q; *buf++ = d2 + '0'; d3 = q + 4*d3; q = (d3 * 0xcd) >> 11; /* - shorter code */ /* q = (d3 * 0x67) >> 10; - would also work */ d3 = d3 - 10*q; *buf++ = d3 + '0'; *buf++ = q + '0'; return buf; } /* No inlining helps gcc to use registers better */ static noinline char *put_dec(char *buf, uint64_t num) { while (1) { unsigned rem; if (num < 100000) return put_dec_trunc(buf, num); rem = do_div(num, 100000); buf = put_dec_full(buf, rem); } } #define ZEROPAD 1 /* pad with zero */ #define SIGN 2 /* unsigned/signed long */ #define PLUS 4 /* show plus */ #define SPACE 8 /* space if plus */ #define LEFT 16 /* left justified */ #define SMALL 32 /* Must be 32 == 0x20 */ #define SPECIAL 64 /* 0x */ /* * Macro to add a new character to our output string, but only if it will * fit. The macro moves to the next character position in the output string. */ #define ADDCH(str, ch) do { \ if ((str) < end) \ *(str) = (ch); \ ++str; \ } while (0) static char *number(char *buf, char *end, u64 num, int base, int size, int precision, int type) { /* we are called with base 8, 10 or 16, only, thus don't need "G..." */ static const char digits[16] = "0123456789ABCDEF"; char tmp[66]; char sign; char locase; int need_pfx = ((type & SPECIAL) && base != 10); int i; /* locase = 0 or 0x20. ORing digits or letters with 'locase' * produces same digits or (maybe lowercased) letters */ locase = (type & SMALL); if (type & LEFT) type &= ~ZEROPAD; sign = 0; if (type & SIGN) { if ((s64) num < 0) { sign = '-'; num = -(s64) num; size--; } else if (type & PLUS) { sign = '+'; size--; } else if (type & SPACE) { sign = ' '; size--; } } if (need_pfx) { size--; if (base == 16) size--; } /* generate full string in tmp[], in reverse order */ i = 0; if (num == 0) tmp[i++] = '0'; /* Generic code, for any base: else do { tmp[i++] = (digits[do_div(num,base)] | locase); } while (num != 0); */ else if (base != 10) { /* 8 or 16 */ int mask = base - 1; int shift = 3; if (base == 16) shift = 4; do { tmp[i++] = (digits[((unsigned char)num) & mask] | locase); num >>= shift; } while (num); } else { /* base 10 */ i = put_dec(tmp, num) - tmp; } /* printing 100 using %2d gives "100", not "00" */ if (i > precision) precision = i; /* leading space padding */ size -= precision; if (!(type & (ZEROPAD + LEFT))) { while (--size >= 0) ADDCH(buf, ' '); } /* sign */ if (sign) ADDCH(buf, sign); /* "0x" / "0" prefix */ if (need_pfx) { ADDCH(buf, '0'); if (base == 16) ADDCH(buf, 'X' | locase); } /* zero or space padding */ if (!(type & LEFT)) { char c = (type & ZEROPAD) ? '0' : ' '; while (--size >= 0) ADDCH(buf, c); } /* hmm even more zero padding? */ while (i <= --precision) ADDCH(buf, '0'); /* actual digits of result */ while (--i >= 0) ADDCH(buf, tmp[i]); /* trailing space padding */ while (--size >= 0) ADDCH(buf, ' '); return buf; } static char *string(char *buf, char *end, char *s, int field_width, int precision, int flags) { int len, i; if (s == NULL) s = "<NULL>"; len = strnlen(s, precision); if (!(flags & LEFT)) while (len < field_width--) ADDCH(buf, ' '); for (i = 0; i < len; ++i) ADDCH(buf, *s++); while (len < field_width--) ADDCH(buf, ' '); return buf; } /* U-Boot uses UTF-16 strings in the EFI context only. */ #if CONFIG_IS_ENABLED(EFI_LOADER) && !defined(API_BUILD) static char *string16(char *buf, char *end, u16 *s, int field_width, int precision, int flags) { const u16 *str = s ? s : L"<NULL>"; ssize_t i, len = utf16_strnlen(str, precision); if (!(flags & LEFT)) for (; len < field_width; --field_width) ADDCH(buf, ' '); for (i = 0; i < len && buf + utf16_utf8_strnlen(str, 1) <= end; ++i) { s32 s = utf16_get(&str); if (s < 0) s = '?'; utf8_put(s, &buf); } for (; len < field_width; --field_width) ADDCH(buf, ' '); return buf; } #if CONFIG_IS_ENABLED(EFI_DEVICE_PATH_TO_TEXT) static char *device_path_string(char *buf, char *end, void *dp, int field_width, int precision, int flags) { u16 *str; /* If dp == NULL output the string '<NULL>' */ if (!dp) return string16(buf, end, dp, field_width, precision, flags); str = efi_dp_str((struct efi_device_path *)dp); if (!str) return ERR_PTR(-ENOMEM); buf = string16(buf, end, str, field_width, precision, flags); efi_free_pool(str); return buf; } #endif #endif static char *mac_address_string(char *buf, char *end, u8 *addr, int field_width, int precision, int flags) { /* (6 * 2 hex digits), 5 colons and trailing zero */ char mac_addr[6 * 3]; char *p = mac_addr; int i; for (i = 0; i < 6; i++) { p = hex_byte_pack(p, addr[i]); if (!(flags & SPECIAL) && i != 5) *p++ = ':'; } *p = '\0'; return string(buf, end, mac_addr, field_width, precision, flags & ~SPECIAL); } static char *ip6_addr_string(char *buf, char *end, u8 *addr, int field_width, int precision, int flags) { /* (8 * 4 hex digits), 7 colons and trailing zero */ char ip6_addr[8 * 5]; char *p = ip6_addr; int i; for (i = 0; i < 8; i++) { p = hex_byte_pack(p, addr[2 * i]); p = hex_byte_pack(p, addr[2 * i + 1]); if (!(flags & SPECIAL) && i != 7) *p++ = ':'; } *p = '\0'; return string(buf, end, ip6_addr, field_width, precision, flags & ~SPECIAL); } static char *ip4_addr_string(char *buf, char *end, u8 *addr, int field_width, int precision, int flags) { /* (4 * 3 decimal digits), 3 dots and trailing zero */ char ip4_addr[4 * 4]; char temp[3]; /* hold each IP quad in reverse order */ char *p = ip4_addr; int i, digits; for (i = 0; i < 4; i++) { digits = put_dec_trunc(temp, addr[i]) - temp; /* reverse the digits in the quad */ while (digits--) *p++ = temp[digits]; if (i != 3) *p++ = '.'; } *p = '\0'; return string(buf, end, ip4_addr, field_width, precision, flags & ~SPECIAL); } #ifdef CONFIG_LIB_UUID /* * This works (roughly) the same way as Linux's. * * %pUb: 01020304-0506-0708-090a-0b0c0d0e0f10 * %pUB: 01020304-0506-0708-090A-0B0C0D0E0F10 * %pUl: 04030201-0605-0807-090a-0b0c0d0e0f10 * %pUL: 04030201-0605-0807-090A-0B0C0D0E0F10 */ static char *uuid_string(char *buf, char *end, u8 *addr, int field_width, int precision, int flags, const char *fmt) { char uuid[UUID_STR_LEN + 1]; int str_format; switch (*(++fmt)) { case 'L': str_format = UUID_STR_FORMAT_GUID | UUID_STR_UPPER_CASE; break; case 'l': str_format = UUID_STR_FORMAT_GUID; break; case 'B': str_format = UUID_STR_FORMAT_STD | UUID_STR_UPPER_CASE; break; default: str_format = UUID_STR_FORMAT_STD; break; } if (addr) uuid_bin_to_str(addr, uuid, str_format); else strcpy(uuid, "<NULL>"); return string(buf, end, uuid, field_width, precision, flags); } #endif /* * Show a '%p' thing. A kernel extension is that the '%p' is followed * by an extra set of alphanumeric characters that are extended format * specifiers. * * Right now we handle: * * - 'M' For a 6-byte MAC address, it prints the address in the * usual colon-separated hex notation * - 'I' [46] for IPv4/IPv6 addresses printed in the usual way (dot-separated * decimal for v4 and colon separated network-order 16 bit hex for v6) * - 'i' [46] for 'raw' IPv4/IPv6 addresses, IPv6 omits the colons, IPv4 is * currently the same * * Note: The difference between 'S' and 'F' is that on ia64 and ppc64 * function pointers are really function descriptors, which contain a * pointer to the real address. */ static char *pointer(const char *fmt, char *buf, char *end, void *ptr, int field_width, int precision, int flags) { u64 num = (uintptr_t)ptr; /* * Being a boot loader, we explicitly allow pointers to * (physical) address null. */ #if 0 if (!ptr) return string(buf, end, "(null)", field_width, precision, flags); #endif switch (*fmt) { /* Device paths only exist in the EFI context. */ #if CONFIG_IS_ENABLED(EFI_DEVICE_PATH_TO_TEXT) && !defined(API_BUILD) case 'D': return device_path_string(buf, end, ptr, field_width, precision, flags); #endif case 'a': flags |= SPECIAL | ZEROPAD; switch (fmt[1]) { case 'p': default: field_width = sizeof(phys_addr_t) * 2 + 2; num = *(phys_addr_t *)ptr; break; } break; case 'm': flags |= SPECIAL; /* Fallthrough */ case 'M': return mac_address_string(buf, end, ptr, field_width, precision, flags); case 'i': flags |= SPECIAL; /* Fallthrough */ case 'I': if (fmt[1] == '6') return ip6_addr_string(buf, end, ptr, field_width, precision, flags); if (fmt[1] == '4') return ip4_addr_string(buf, end, ptr, field_width, precision, flags); flags &= ~SPECIAL; break; #ifdef CONFIG_LIB_UUID case 'U': return uuid_string(buf, end, ptr, field_width, precision, flags, fmt); #endif default: break; } flags |= SMALL; if (field_width == -1) { field_width = 2*sizeof(void *); flags |= ZEROPAD; } return number(buf, end, num, 16, field_width, precision, flags); } static int vsnprintf_internal(char *buf, size_t size, const char *fmt, va_list args) { u64 num; int base; char *str; int flags; /* flags to number() */ int field_width; /* width of output field */ int precision; /* min. # of digits for integers; max number of chars for from string */ int qualifier; /* 'h', 'l', or 'L' for integer fields */ /* 'z' support added 23/7/1999 S.H. */ /* 'z' changed to 'Z' --davidm 1/25/99 */ /* 't' added for ptrdiff_t */ char *end = buf + size; /* Make sure end is always >= buf - do we want this in U-Boot? */ if (end < buf) { end = ((void *)-1); size = end - buf; } str = buf; for (; *fmt ; ++fmt) { if (*fmt != '%') { ADDCH(str, *fmt); continue; } /* process flags */ flags = 0; repeat: ++fmt; /* this also skips first '%' */ switch (*fmt) { case '-': flags |= LEFT; goto repeat; case '+': flags |= PLUS; goto repeat; case ' ': flags |= SPACE; goto repeat; case '#': flags |= SPECIAL; goto repeat; case '0': flags |= ZEROPAD; goto repeat; } /* get field width */ field_width = -1; if (is_digit(*fmt)) field_width = skip_atoi(&fmt); else if (*fmt == '*') { ++fmt; /* it's the next argument */ field_width = va_arg(args, int); if (field_width < 0) { field_width = -field_width; flags |= LEFT; } } /* get the precision */ precision = -1; if (*fmt == '.') { ++fmt; if (is_digit(*fmt)) precision = skip_atoi(&fmt); else if (*fmt == '*') { ++fmt; /* it's the next argument */ precision = va_arg(args, int); } if (precision < 0) precision = 0; } /* get the conversion qualifier */ qualifier = -1; if (*fmt == 'h' || *fmt == 'l' || *fmt == 'L' || *fmt == 'Z' || *fmt == 'z' || *fmt == 't') { qualifier = *fmt; ++fmt; if (qualifier == 'l' && *fmt == 'l') { qualifier = 'L'; ++fmt; } } /* default base */ base = 10; switch (*fmt) { case 'c': if (!(flags & LEFT)) { while (--field_width > 0) ADDCH(str, ' '); } ADDCH(str, (unsigned char) va_arg(args, int)); while (--field_width > 0) ADDCH(str, ' '); continue; case 's': /* U-Boot uses UTF-16 strings in the EFI context only. */ #if CONFIG_IS_ENABLED(EFI_LOADER) && !defined(API_BUILD) if (qualifier == 'l') { str = string16(str, end, va_arg(args, u16 *), field_width, precision, flags); } else #endif { str = string(str, end, va_arg(args, char *), field_width, precision, flags); } continue; case 'p': str = pointer(fmt + 1, str, end, va_arg(args, void *), field_width, precision, flags); if (IS_ERR(str)) return PTR_ERR(str); /* Skip all alphanumeric pointer suffixes */ while (isalnum(fmt[1])) fmt++; continue; case 'n': if (qualifier == 'l') { long *ip = va_arg(args, long *); *ip = (str - buf); } else { int *ip = va_arg(args, int *); *ip = (str - buf); } continue; case '%': ADDCH(str, '%'); continue; /* integer number formats - set up the flags and "break" */ case 'o': base = 8; break; case 'x': flags |= SMALL; case 'X': base = 16; break; case 'd': case 'i': flags |= SIGN; case 'u': break; default: ADDCH(str, '%'); if (*fmt) ADDCH(str, *fmt); else --fmt; continue; } if (qualifier == 'L') /* "quad" for 64 bit variables */ num = va_arg(args, unsigned long long); else if (qualifier == 'l') { num = va_arg(args, unsigned long); if (flags & SIGN) num = (signed long) num; } else if (qualifier == 'Z' || qualifier == 'z') { num = va_arg(args, size_t); } else if (qualifier == 't') { num = va_arg(args, ptrdiff_t); } else if (qualifier == 'h') { num = (unsigned short) va_arg(args, int); if (flags & SIGN) num = (signed short) num; } else { num = va_arg(args, unsigned int); if (flags & SIGN) num = (signed int) num; } str = number(str, end, num, base, field_width, precision, flags); } if (size > 0) { ADDCH(str, '\0'); if (str > end) end[-1] = '\0'; --str; } /* the trailing null byte doesn't count towards the total */ return str - buf; } int vsnprintf(char *buf, size_t size, const char *fmt, va_list args) { return vsnprintf_internal(buf, size, fmt, args); } int vscnprintf(char *buf, size_t size, const char *fmt, va_list args) { int i; i = vsnprintf(buf, size, fmt, args); if (likely(i < size)) return i; if (size != 0) return size - 1; return 0; } int snprintf(char *buf, size_t size, const char *fmt, ...) { va_list args; int i; va_start(args, fmt); i = vsnprintf(buf, size, fmt, args); va_end(args); return i; } int scnprintf(char *buf, size_t size, const char *fmt, ...) { va_list args; int i; va_start(args, fmt); i = vscnprintf(buf, size, fmt, args); va_end(args); return i; } /** * Format a string and place it in a buffer (va_list version) * * @param buf The buffer to place the result into * @param fmt The format string to use * @param args Arguments for the format string * * The function returns the number of characters written * into @buf. Use vsnprintf() or vscnprintf() in order to avoid * buffer overflows. * * If you're not already dealing with a va_list consider using sprintf(). */ int vsprintf(char *buf, const char *fmt, va_list args) { return vsnprintf_internal(buf, INT_MAX, fmt, args); } int sprintf(char *buf, const char *fmt, ...) { va_list args; int i; va_start(args, fmt); i = vsprintf(buf, fmt, args); va_end(args); return i; } #if CONFIG_IS_ENABLED(PRINTF) int printf(const char *fmt, ...) { va_list args; uint i; char printbuffer[CONFIG_SYS_PBSIZE]; va_start(args, fmt); /* * For this to work, printbuffer must be larger than * anything we ever want to print. */ i = vscnprintf(printbuffer, sizeof(printbuffer), fmt, args); va_end(args); /* Handle error */ if (i <= 0) return i; /* Print the string */ puts(printbuffer); return i; } int vprintf(const char *fmt, va_list args) { uint i; char printbuffer[CONFIG_SYS_PBSIZE]; /* * For this to work, printbuffer must be larger than * anything we ever want to print. */ i = vscnprintf(printbuffer, sizeof(printbuffer), fmt, args); /* Handle error */ if (i <= 0) return i; /* Print the string */ puts(printbuffer); return i; } #endif char *simple_itoa(ulong i) { /* 21 digits plus null terminator, good for 64-bit or smaller ints */ static char local[22]; char *p = &local[21]; *p-- = '\0'; do { *p-- = '0' + i % 10; i /= 10; } while (i > 0); return p + 1; } /* We don't seem to have %'d in U-Boot */ void print_grouped_ull(unsigned long long int_val, int digits) { char str[21], *s; int grab = 3; digits = (digits + 2) / 3; sprintf(str, "%*llu", digits * 3, int_val); for (s = str; *s; s += grab) { if (s != str) putc(s[-1] != ' ' ? ',' : ' '); printf("%.*s", grab, s); grab = 3; } } bool str2off(const char *p, loff_t *num) { char *endptr; *num = simple_strtoull(p, &endptr, 16); return *p != '\0' && *endptr == '\0'; } bool str2long(const char *p, ulong *num) { char *endptr; *num = simple_strtoul(p, &endptr, 16); return *p != '\0' && *endptr == '\0'; } char *strmhz(char *buf, unsigned long hz) { long l, n; long m; n = DIV_ROUND_CLOSEST(hz, 1000) / 1000L; l = sprintf(buf, "%ld", n); hz -= n * 1000000L; m = DIV_ROUND_CLOSEST(hz, 1000L); if (m != 0) sprintf(buf + l, ".%03ld", m); return buf; }
Digilent/u-boot-digilent
lib/vsprintf.c
C
gpl-2.0
19,676
require 'migrate' class RenameBugsToNotes < ActiveRecord::Migration def self.up rename_enumeration "map_bug_status_enum", "note_status_enum" rename_enumeration "map_bug_event_enum", "note_event_enum" rename_table :map_bugs, :notes rename_index :notes, "map_bugs_pkey", "notes_pkey" rename_index :notes, "map_bugs_changed_idx", "notes_updated_at_idx" rename_index :notes, "map_bugs_created_idx", "notes_created_at_idx" rename_index :notes, "map_bugs_tile_idx", "notes_tile_status_idx" remove_foreign_key :map_bug_comment, [:bug_id], :map_bugs, [:id] rename_column :map_bug_comment, :author_id, :commenter_id remove_foreign_key :map_bug_comment, [:commenter_id], :users, [:id] rename_column :map_bug_comment, :commenter_id, :author_id rename_table :map_bug_comment, :note_comments rename_column :note_comments, :bug_id, :note_id rename_index :note_comments, "map_bug_comment_pkey", "note_comments_pkey" rename_index :note_comments, "map_bug_comment_id_idx", "note_comments_note_id_idx" add_foreign_key :note_comments, [:note_id], :notes, [:id] add_foreign_key :note_comments, [:author_id], :users, [:id] end def self.down remove_foreign_key :note_comments, [:author_id], :users, [:id] remove_foreign_key :note_comments, [:note_id], :notes, [:id] rename_index :note_comments, "note_comments_note_id_idx", "map_bug_comment_id_idx" rename_index :notes, "note_comments_pkey", "map_bug_comment_pkey" rename_column :note_comments, :note_id, :bug_id rename_table :note_comments, :map_bug_comment rename_column :map_bug_comment, :author_id, :commenter_id add_foreign_key :map_bug_comment, [:commenter_id], :users, [:id] rename_column :map_bug_comment, :commenter_id, :author_id add_foreign_key :map_bug_comment, [:bug_id], :notes, [:id] rename_index :notes, "notes_tile_status_idx", "map_bugs_tile_idx" rename_index :notes, "notes_created_at_idx", "map_bugs_created_idx" rename_index :notes, "notes_updated_at_idx", "map_bugs_changed_idx" rename_index :notes, "notes_pkey", "map_bugs_pkey" rename_table :notes, :map_bugs rename_enumeration "note_event_enum", "map_bug_event_enum" rename_enumeration "note_status_enum", "map_bug_status_enum" end end
anatoliegolovco/grmdemo
db/migrate/20110521142405_rename_bugs_to_notes.rb
Ruby
gpl-2.0
2,293
/* The IGEN simulator generator for GDB, the GNU Debugger. Copyright 2002 Free Software Foundation, Inc. Contributed by Andrew Cagney. This file is part of GDB. 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. */ extern void gen_model_h (lf *file, insn_table *isa); extern void gen_model_c (lf *file, insn_table *isa);
ipwndev/DSLinux-Mirror
user/gdb/sim/igen/gen-model.h
C
gpl-2.0
1,001
/* * Copyright (C) 2009 Apple Inc. 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 APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. */ #if TARGET_OS_IPHONE #import <CoreGraphics/CoreGraphics.h> #import <Foundation/Foundation.h> #import <WebKitLegacy/WebFrameIOS.h> @interface WebSelectionRect : NSObject <NSCopying> { CGRect m_rect; WKWritingDirection m_writingDirection; BOOL m_isLineBreak; BOOL m_isFirstOnLine; BOOL m_isLastOnLine; BOOL m_containsStart; BOOL m_containsEnd; BOOL m_isInFixedPosition; BOOL m_isHorizontal; } @property (nonatomic, assign) CGRect rect; @property (nonatomic, assign) WKWritingDirection writingDirection; @property (nonatomic, assign) BOOL isLineBreak; @property (nonatomic, assign) BOOL isFirstOnLine; @property (nonatomic, assign) BOOL isLastOnLine; @property (nonatomic, assign) BOOL containsStart; @property (nonatomic, assign) BOOL containsEnd; @property (nonatomic, assign) BOOL isInFixedPosition; @property (nonatomic, assign) BOOL isHorizontal; + (WebSelectionRect *)selectionRect; + (CGRect)startEdge:(NSArray *)rects; + (CGRect)endEdge:(NSArray *)rects; @end #endif // TARGET_OS_IPHONE
Debian/openjfx
modules/web/src/main/native/Source/WebKit/ios/WebCoreSupport/WebSelectionRect.h
C
gpl-2.0
2,391
<?php /* V4.98 13 Feb 2008 (c) 2000-2008 John Lim (jlim#natsoft.com.my). All rights reserved. Released under both BSD license and Lesser GPL library license. Whenever there is any discrepancy between the two licenses, the BSD license will take precedence. See License.txt. Set tabs to 4 for best viewing. Latest version is available at http://adodb.sourceforge.net Library for basic performance monitoring and tuning */ // security - hide paths if (!defined('ADODB_DIR')) die(); /* MSSQL has moved most performance info to Performance Monitor */ class perf_mssql extends adodb_perf{ var $sql1 = 'cast(sql1 as text)'; var $createTableSQL = "CREATE TABLE adodb_logsql ( created datetime NOT NULL, sql0 varchar(250) NOT NULL, sql1 varchar(4000) NOT NULL, params varchar(3000) NOT NULL, tracer varchar(500) NOT NULL, timer decimal(16,6) NOT NULL )"; var $settings = array( 'Ratios', 'data cache hit ratio' => array('RATIO', "select round((a.cntr_value*100.0)/b.cntr_value,2) from master.dbo.sysperfinfo a, master.dbo.sysperfinfo b where a.counter_name = 'Buffer cache hit ratio' and b.counter_name='Buffer cache hit ratio base'", '=WarnCacheRatio'), 'prepared sql hit ratio' => array('RATIO', array('dbcc cachestats','Prepared',1,100), ''), 'adhoc sql hit ratio' => array('RATIO', array('dbcc cachestats','Adhoc',1,100), ''), 'IO', 'data reads' => array('IO', "select cntr_value from master.dbo.sysperfinfo where counter_name = 'Page reads/sec'"), 'data writes' => array('IO', "select cntr_value from master.dbo.sysperfinfo where counter_name = 'Page writes/sec'"), 'Data Cache', 'data cache size' => array('DATAC', "select cntr_value*8192 from master.dbo.sysperfinfo where counter_name = 'Total Pages' and object_name='SQLServer:Buffer Manager'", '' ), 'data cache blocksize' => array('DATAC', "select 8192",'page size'), 'Connections', 'current connections' => array('SESS', '=sp_who', ''), 'max connections' => array('SESS', "SELECT @@MAX_CONNECTIONS", ''), false ); function perf_mssql(&$conn) { if ($conn->dataProvider == 'odbc') { $this->sql1 = 'sql1'; //$this->explain = false; } $this->conn =& $conn; } function Explain($sql,$partial=false) { $save = $this->conn->LogSQL(false); if ($partial) { $sqlq = $this->conn->qstr($sql.'%'); $arr = $this->conn->GetArray("select distinct sql1 from adodb_logsql where sql1 like $sqlq"); if ($arr) { foreach($arr as $row) { $sql = reset($row); if (crc32($sql) == $partial) break; } } } $s = '<p><b>Explain</b>: '.htmlspecialchars($sql).'</p>'; $this->conn->Execute("SET SHOWPLAN_ALL ON;"); $sql = str_replace('?',"''",$sql); global $ADODB_FETCH_MODE; $save = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; $rs =& $this->conn->Execute($sql); //adodb_printr($rs); $ADODB_FETCH_MODE = $save; if ($rs) { $rs->MoveNext(); $s .= '<table bgcolor=white border=0 cellpadding="1" callspacing=0><tr><td nowrap align=center> Rows<td nowrap align=center> IO<td nowrap align=center> CPU<td align=left> &nbsp; &nbsp; Plan</tr>'; while (!$rs->EOF) { $s .= '<tr><td>'.round($rs->fields[8],1).'<td>'.round($rs->fields[9],3).'<td align=right>'.round($rs->fields[10],3).'<td nowrap><pre>'.htmlspecialchars($rs->fields[0])."</td></pre></tr>\n"; ## NOTE CORRUPT </td></pre> tag is intentional!!!! $rs->MoveNext(); } $s .= '</table>'; $rs->NextRecordSet(); } $this->conn->Execute("SET SHOWPLAN_ALL OFF;"); $this->conn->LogSQL($save); $s .= $this->Tracer($sql); return $s; } function Tables() { global $ADODB_FETCH_MODE; $save = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; //$this->conn->debug=1; $s = '<table border=1 bgcolor=white><tr><td><b>tablename</b></td><td><b>size_in_k</b></td><td><b>index size</b></td><td><b>reserved size</b></td></tr>'; $rs1 = $this->conn->Execute("select distinct name from sysobjects where xtype='U'"); if ($rs1) { while (!$rs1->EOF) { $tab = $rs1->fields[0]; $tabq = $this->conn->qstr($tab); $rs2 = $this->conn->Execute("sp_spaceused $tabq"); if ($rs2) { $s .= '<tr><td>'.$tab.'</td><td align=right>'.$rs2->fields[3].'</td><td align=right>'.$rs2->fields[4].'</td><td align=right>'.$rs2->fields[2].'</td></tr>'; $rs2->Close(); } $rs1->MoveNext(); } $rs1->Close(); } $ADODB_FETCH_MODE = $save; return $s.'</table>'; } function sp_who() { $arr = $this->conn->GetArray('sp_who'); return sizeof($arr); } function HealthCheck($cli=false) { $this->conn->Execute('dbcc traceon(3604)'); $html = adodb_perf::HealthCheck($cli); $this->conn->Execute('dbcc traceoff(3604)'); return $html; } } ?>
jcannava/bleedcrimson.net
photos/lib/adodb/perf/perf-mssql.inc.php
PHP
gpl-2.0
4,822
/* * SPU file system -- SPU context management * * (C) Copyright IBM Deutschland Entwicklung GmbH 2005 * * Author: Arnd Bergmann <arndb@de.ibm.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, 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <linux/fs.h> #include <linux/mm.h> #include <linux/slab.h> #include <asm/spu.h> #include <asm/spu_csa.h> #include "spufs.h" struct spu_context *alloc_spu_context(void) { struct spu_context *ctx; ctx = kzalloc(sizeof *ctx, GFP_KERNEL); if (!ctx) goto out; /* Binding to physical processor deferred * until spu_activate(). */ spu_init_csa(&ctx->csa); if (!ctx->csa.lscsa) { goto out_free; } spin_lock_init(&ctx->mmio_lock); kref_init(&ctx->kref); init_rwsem(&ctx->state_sema); init_MUTEX(&ctx->run_sema); init_waitqueue_head(&ctx->ibox_wq); init_waitqueue_head(&ctx->wbox_wq); init_waitqueue_head(&ctx->stop_wq); init_waitqueue_head(&ctx->mfc_wq); ctx->state = SPU_STATE_SAVED; ctx->ops = &spu_backing_ops; ctx->owner = get_task_mm(current); goto out; out_free: kfree(ctx); ctx = NULL; out: return ctx; } void destroy_spu_context(struct kref *kref) { struct spu_context *ctx; ctx = container_of(kref, struct spu_context, kref); down_write(&ctx->state_sema); spu_deactivate(ctx); up_write(&ctx->state_sema); spu_fini_csa(&ctx->csa); kfree(ctx); } struct spu_context * get_spu_context(struct spu_context *ctx) { kref_get(&ctx->kref); return ctx; } int put_spu_context(struct spu_context *ctx) { return kref_put(&ctx->kref, &destroy_spu_context); } /* give up the mm reference when the context is about to be destroyed */ void spu_forget(struct spu_context *ctx) { struct mm_struct *mm; spu_acquire_saved(ctx); mm = ctx->owner; ctx->owner = NULL; mmput(mm); spu_release(ctx); } void spu_acquire(struct spu_context *ctx) { down_read(&ctx->state_sema); } void spu_release(struct spu_context *ctx) { up_read(&ctx->state_sema); } void spu_unmap_mappings(struct spu_context *ctx) { if (ctx->local_store) unmap_mapping_range(ctx->local_store, 0, LS_SIZE, 1); if (ctx->mfc) unmap_mapping_range(ctx->mfc, 0, 0x4000, 1); if (ctx->cntl) unmap_mapping_range(ctx->cntl, 0, 0x4000, 1); if (ctx->signal1) unmap_mapping_range(ctx->signal1, 0, 0x4000, 1); if (ctx->signal2) unmap_mapping_range(ctx->signal2, 0, 0x4000, 1); } int spu_acquire_runnable(struct spu_context *ctx) { int ret = 0; down_read(&ctx->state_sema); if (ctx->state == SPU_STATE_RUNNABLE) { ctx->spu->prio = current->prio; return 0; } up_read(&ctx->state_sema); down_write(&ctx->state_sema); /* ctx is about to be freed, can't acquire any more */ if (!ctx->owner) { ret = -EINVAL; goto out; } if (ctx->state == SPU_STATE_SAVED) { ret = spu_activate(ctx, 0); if (ret) goto out; ctx->state = SPU_STATE_RUNNABLE; } downgrade_write(&ctx->state_sema); /* On success, we return holding the lock */ return ret; out: /* Release here, to simplify calling code. */ up_write(&ctx->state_sema); return ret; } void spu_acquire_saved(struct spu_context *ctx) { down_read(&ctx->state_sema); if (ctx->state == SPU_STATE_SAVED) return; up_read(&ctx->state_sema); down_write(&ctx->state_sema); if (ctx->state == SPU_STATE_RUNNABLE) { spu_deactivate(ctx); ctx->state = SPU_STATE_SAVED; } downgrade_write(&ctx->state_sema); }
zhoupeng/spice4xen
linux-2.6.18-xen.hg/arch/powerpc/platforms/cell/spufs/context.c
C
gpl-2.0
3,935
/* * Copyright (C) 2008-2017 TrinityCore <http://www.trinitycore.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 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 "ScriptMgr.h" #include "Chat.h" #include "DatabaseEnv.h" #include "Item.h" #include "Language.h" #include "Mail.h" #include "ObjectMgr.h" #include "Pet.h" #include "Player.h" #include "RBAC.h" #include "WorldSession.h" class send_commandscript : public CommandScript { public: send_commandscript() : CommandScript("send_commandscript") { } std::vector<ChatCommand> GetCommands() const override { static std::vector<ChatCommand> sendCommandTable = { { "items", rbac::RBAC_PERM_COMMAND_SEND_ITEMS, true, &HandleSendItemsCommand, "" }, { "mail", rbac::RBAC_PERM_COMMAND_SEND_MAIL, true, &HandleSendMailCommand, "" }, { "message", rbac::RBAC_PERM_COMMAND_SEND_MESSAGE, true, &HandleSendMessageCommand, "" }, { "money", rbac::RBAC_PERM_COMMAND_SEND_MONEY, true, &HandleSendMoneyCommand, "" }, }; static std::vector<ChatCommand> commandTable = { { "send", rbac::RBAC_PERM_COMMAND_SEND, false, nullptr, "", sendCommandTable }, }; return commandTable; } // Send mail by command static bool HandleSendMailCommand(ChatHandler* handler, char const* args) { // format: name "subject text" "mail text" Player* target; ObjectGuid targetGuid; std::string targetName; if (!handler->extractPlayerTarget((char*)args, &target, &targetGuid, &targetName)) return false; char* tail1 = strtok(nullptr, ""); if (!tail1) return false; char const* msgSubject = handler->extractQuotedArg(tail1); if (!msgSubject) return false; char* tail2 = strtok(nullptr, ""); if (!tail2) return false; char const* msgText = handler->extractQuotedArg(tail2); if (!msgText) return false; // msgSubject, msgText isn't NUL after prev. check std::string subject = msgSubject; std::string text = msgText; // from console, use non-existing sender MailSender sender(MAIL_NORMAL, handler->GetSession() ? handler->GetSession()->GetPlayer()->GetGUID().GetCounter() : 0, MAIL_STATIONERY_GM); /// @todo Fix poor design SQLTransaction trans = CharacterDatabase.BeginTransaction(); MailDraft(subject, text) .SendMailTo(trans, MailReceiver(target, targetGuid.GetCounter()), sender); CharacterDatabase.CommitTransaction(trans); std::string nameLink = handler->playerLink(targetName); handler->PSendSysMessage(LANG_MAIL_SENT, nameLink.c_str()); return true; } // Send items by mail static bool HandleSendItemsCommand(ChatHandler* handler, char const* args) { // format: name "subject text" "mail text" item1[:count1] item2[:count2] ... item12[:count12] Player* receiver; ObjectGuid receiverGuid; std::string receiverName; if (!handler->extractPlayerTarget((char*)args, &receiver, &receiverGuid, &receiverName)) return false; char* tail1 = strtok(nullptr, ""); if (!tail1) return false; char const* msgSubject = handler->extractQuotedArg(tail1); if (!msgSubject) return false; char* tail2 = strtok(nullptr, ""); if (!tail2) return false; char const* msgText = handler->extractQuotedArg(tail2); if (!msgText) return false; // msgSubject, msgText isn't NUL after prev. check std::string subject = msgSubject; std::string text = msgText; // extract items typedef std::pair<uint32, uint32> ItemPair; typedef std::list< ItemPair > ItemPairs; ItemPairs items; // get all tail string char* tail = strtok(nullptr, ""); // get from tail next item str while (char* itemStr = strtok(tail, " ")) { // and get new tail tail = strtok(nullptr, ""); // parse item str char const* itemIdStr = strtok(itemStr, ":"); char const* itemCountStr = strtok(nullptr, " "); uint32 itemId = atoi(itemIdStr); if (!itemId) return false; ItemTemplate const* item_proto = sObjectMgr->GetItemTemplate(itemId); if (!item_proto) { handler->PSendSysMessage(LANG_COMMAND_ITEMIDINVALID, itemId); handler->SetSentErrorMessage(true); return false; } uint32 itemCount = itemCountStr ? atoi(itemCountStr) : 1; if (itemCount < 1 || (item_proto->MaxCount > 0 && itemCount > uint32(item_proto->MaxCount))) { handler->PSendSysMessage(LANG_COMMAND_INVALID_ITEM_COUNT, itemCount, itemId); handler->SetSentErrorMessage(true); return false; } while (itemCount > item_proto->GetMaxStackSize()) { items.push_back(ItemPair(itemId, item_proto->GetMaxStackSize())); itemCount -= item_proto->GetMaxStackSize(); } items.push_back(ItemPair(itemId, itemCount)); if (items.size() > MAX_MAIL_ITEMS) { handler->PSendSysMessage(LANG_COMMAND_MAIL_ITEMS_LIMIT, MAX_MAIL_ITEMS); handler->SetSentErrorMessage(true); return false; } } // from console show nonexisting sender MailSender sender(MAIL_NORMAL, handler->GetSession() ? handler->GetSession()->GetPlayer()->GetGUID().GetCounter() : 0, MAIL_STATIONERY_GM); // fill mail MailDraft draft(subject, text); SQLTransaction trans = CharacterDatabase.BeginTransaction(); for (ItemPairs::const_iterator itr = items.begin(); itr != items.end(); ++itr) { if (Item* item = Item::CreateItem(itr->first, itr->second, handler->GetSession() ? handler->GetSession()->GetPlayer() : 0)) { item->SaveToDB(trans); // Save to prevent being lost at next mail load. If send fails, the item will be deleted. draft.AddItem(item); } } draft.SendMailTo(trans, MailReceiver(receiver, receiverGuid.GetCounter()), sender); CharacterDatabase.CommitTransaction(trans); std::string nameLink = handler->playerLink(receiverName); handler->PSendSysMessage(LANG_MAIL_SENT, nameLink.c_str()); return true; } /// Send money by mail static bool HandleSendMoneyCommand(ChatHandler* handler, char const* args) { /// format: name "subject text" "mail text" money Player* receiver; ObjectGuid receiverGuid; std::string receiverName; if (!handler->extractPlayerTarget((char*)args, &receiver, &receiverGuid, &receiverName)) return false; char* tail1 = strtok(nullptr, ""); if (!tail1) return false; char* msgSubject = handler->extractQuotedArg(tail1); if (!msgSubject) return false; char* tail2 = strtok(nullptr, ""); if (!tail2) return false; char* msgText = handler->extractQuotedArg(tail2); if (!msgText) return false; char* moneyStr = strtok(nullptr, ""); int32 money = moneyStr ? atoi(moneyStr) : 0; if (money <= 0) return false; // msgSubject, msgText isn't NUL after prev. check std::string subject = msgSubject; std::string text = msgText; // from console show nonexisting sender MailSender sender(MAIL_NORMAL, handler->GetSession() ? handler->GetSession()->GetPlayer()->GetGUID().GetCounter() : 0, MAIL_STATIONERY_GM); SQLTransaction trans = CharacterDatabase.BeginTransaction(); MailDraft(subject, text) .AddMoney(money) .SendMailTo(trans, MailReceiver(receiver, receiverGuid.GetCounter()), sender); CharacterDatabase.CommitTransaction(trans); std::string nameLink = handler->playerLink(receiverName); handler->PSendSysMessage(LANG_MAIL_SENT, nameLink.c_str()); return true; } /// Send a message to a player in game static bool HandleSendMessageCommand(ChatHandler* handler, char const* args) { /// - Find the player Player* player; if (!handler->extractPlayerTarget((char*)args, &player)) return false; char* msgStr = strtok(nullptr, ""); if (!msgStr) return false; /// - Check if player is logging out. if (player->GetSession()->isLogingOut()) { handler->SendSysMessage(LANG_PLAYER_NOT_FOUND); handler->SetSentErrorMessage(true); return false; } /// - Send the message // Use SendAreaTriggerMessage for fastest delivery. player->GetSession()->SendAreaTriggerMessage("%s", msgStr); player->GetSession()->SendAreaTriggerMessage("|cffff0000[Message from administrator]:|r"); // Confirmation message std::string nameLink = handler->GetNameLink(player); handler->PSendSysMessage(LANG_SENDMESSAGE, nameLink.c_str(), msgStr); return true; } }; void AddSC_send_commandscript() { new send_commandscript(); }
Effec7/Adamantium
src/server/scripts/Commands/cs_send.cpp
C++
gpl-2.0
10,199
## This file is part of Invenio. ## Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 CERN. ## ## Invenio 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. ## ## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """Invenio Access Control Config. """ __revision__ = \ "$Id$" # pylint: disable=C0301 from invenio import config from invenio.config import CFG_SITE_NAME, CFG_SITE_URL, CFG_SITE_LANG, \ CFG_SITE_SECURE_URL, CFG_SITE_SUPPORT_EMAIL, CFG_CERN_SITE, \ CFG_OPENAIRE_SITE, CFG_SITE_RECORD, CFG_INSPIRE_SITE, \ CFG_SITE_ADMIN_EMAIL from invenio.messages import gettext_set_language class InvenioWebAccessFireroleError(Exception): """Just an Exception to discover if it's a FireRole problem""" pass # VALUES TO BE EXPORTED # CURRENTLY USED BY THE FILES access_control_engine.py access_control_admin.py webaccessadmin_lib.py # name of the role giving superadmin rights SUPERADMINROLE = 'superadmin' # name of the webaccess webadmin role WEBACCESSADMINROLE = 'webaccessadmin' # name of the action allowing roles to access the web administrator interface WEBACCESSACTION = 'cfgwebaccess' # name of the action allowing roles to access the web administrator interface VIEWRESTRCOLL = 'viewrestrcoll' # name of the action allowing roles to delegate the rights to other roles # ex: libraryadmin to delegate libraryworker DELEGATEADDUSERROLE = 'accdelegaterole' # max number of users to display in the drop down selects MAXSELECTUSERS = 25 # max number of users to display in a page (mainly for user area) MAXPAGEUSERS = 25 # default role definition, source: CFG_ACC_EMPTY_ROLE_DEFINITION_SRC = 'deny all' # default role definition, compiled: CFG_ACC_EMPTY_ROLE_DEFINITION_OBJ = (False, ()) # default role definition, compiled and serialized: CFG_ACC_EMPTY_ROLE_DEFINITION_SER = None # List of tags containing (multiple) emails of users who should authorize # to access the corresponding record regardless of collection restrictions. if CFG_CERN_SITE: CFG_ACC_GRANT_AUTHOR_RIGHTS_TO_EMAILS_IN_TAGS = ['859__f', '270__m'] else: CFG_ACC_GRANT_AUTHOR_RIGHTS_TO_EMAILS_IN_TAGS = ['8560_f'] if CFG_CERN_SITE: CFG_ACC_GRANT_VIEWER_RIGHTS_TO_EMAILS_IN_TAGS = ['506__m'] else: CFG_ACC_GRANT_VIEWER_RIGHTS_TO_EMAILS_IN_TAGS = [] # Use external source for access control? # CFG_EXTERNAL_AUTHENTICATION -- this is a dictionary with the enabled login method. # The key is the name of the login method and the value is an instance of # of the login method (see /help/admin/webaccess-admin-guide#5). Set the value # to None if you wish to use the local Invenio authentication method. # CFG_EXTERNAL_AUTH_DEFAULT -- set this to the key in CFG_EXTERNAL_AUTHENTICATION # that should be considered as default login method # CFG_EXTERNAL_AUTH_USING_SSO -- set this to the login method name of an SSO # login method, if any, otherwise set this to None. # CFG_EXTERNAL_AUTH_LOGOUT_SSO -- if CFG_EXTERNAL_AUTH_USING_SSO was not None # set this to the URL that should be contacted to perform an SSO logout from invenio.external_authentication_robot import ExternalAuthRobot if CFG_CERN_SITE: from invenio import external_authentication_sso as ea_sso CFG_EXTERNAL_AUTH_USING_SSO = "CERN" CFG_EXTERNAL_AUTH_DEFAULT = CFG_EXTERNAL_AUTH_USING_SSO CFG_EXTERNAL_AUTH_LOGOUT_SSO = 'https://login.cern.ch/adfs/ls/?wa=wsignout1.0' CFG_EXTERNAL_AUTHENTICATION = { CFG_EXTERNAL_AUTH_USING_SSO : ea_sso.ExternalAuthSSO(), } elif CFG_OPENAIRE_SITE: CFG_EXTERNAL_AUTH_DEFAULT = 'Local' CFG_EXTERNAL_AUTH_USING_SSO = False CFG_EXTERNAL_AUTH_LOGOUT_SSO = None CFG_EXTERNAL_AUTHENTICATION = { "Local": None, "OpenAIRE": ExternalAuthRobot(enforce_external_nicknames=True, use_zlib=False, external_id_attribute_name="id"), } elif CFG_INSPIRE_SITE: # INSPIRE specific robot configuration CFG_EXTERNAL_AUTH_DEFAULT = 'Local' CFG_EXTERNAL_AUTH_USING_SSO = False CFG_EXTERNAL_AUTH_LOGOUT_SSO = None CFG_EXTERNAL_AUTHENTICATION = { "Local": None, "Robot": ExternalAuthRobot(enforce_external_nicknames=True, use_zlib=False, check_user_ip=2, external_id_attribute_name='personid'), "ZRobot": ExternalAuthRobot(enforce_external_nicknames=True, use_zlib=True, check_user_ip=2, external_id_attribute_name='personid') } else: CFG_EXTERNAL_AUTH_DEFAULT = 'Local' CFG_EXTERNAL_AUTH_USING_SSO = False CFG_EXTERNAL_AUTH_LOGOUT_SSO = None CFG_EXTERNAL_AUTHENTICATION = { "Local": None, "Robot": ExternalAuthRobot(enforce_external_nicknames=True, use_zlib=False), "ZRobot": ExternalAuthRobot(enforce_external_nicknames=True, use_zlib=True) } # CFG_TEMP_EMAIL_ADDRESS # Temporary email address for logging in with an OpenID/OAuth provider which # doesn't supply email address CFG_TEMP_EMAIL_ADDRESS = "%s@NOEMAIL" # CFG_OPENID_PROVIDERS # CFG_OAUTH1_PROVIDERS # CFG_OAUTH2_PROVIDERS # Choose which providers you want to use. Some providers don't supply e mail # address, if you choose them, the users will be registered with an temporary # email address like CFG_TEMP_EMAIL_ADDRESS % randomstring # # Order of the login buttons can be changed by CFG_EXTERNAL_LOGIN_BUTTON_ORDER # in invenio.websession_config CFG_OPENID_PROVIDERS = [ 'google', 'yahoo', 'aol', 'wordpress', 'myvidoop', 'openid', 'verisign', 'myopenid', 'myspace', 'livejournal', 'blogger' ] CFG_OAUTH1_PROVIDERS = [ 'twitter', 'linkedin', 'flickr' ] CFG_OAUTH2_PROVIDERS = [ 'facebook', 'yammer', 'foursquare', 'googleoauth2', 'instagram', 'orcid' ] # CFG_OPENID_CONFIGURATIONS # identifier: (required) identifier url. {0} will be replaced by username (an # input). # trust_email: (optional, default: False) Some providers let their users # change their emails on login page. If the provider doesn't let the user, # set it True. CFG_OPENID_CONFIGURATIONS = { 'openid': { 'identifier': '{0}' }, 'myvidoop': { 'identifier': '{0}.myvidoop.com' }, 'google': { 'identifier': 'https://www.google.com/accounts/o8/id', 'trust_email': True }, 'wordpress': { 'identifier': '{0}.wordpress.com' }, 'aol': { 'identifier': 'openid.aol.com/{0}', 'trust_email': True }, 'myopenid': { 'identifier': '{0}.myopenid.com' }, 'yahoo': { 'identifier': 'yahoo.com', 'trust_email': True }, 'verisign': { 'identifier': '{0}.pip.verisignlabs.com' }, 'myspace': { 'identifier': 'www.myspace.com/{0}' }, 'livejournal': { 'identifier': '{0}.livejournal.com' }, 'blogger': { 'identifier': '{0}' } } # CFG_OAUTH1_CONFIGURATIONS # # !!IMPORTANT!! # While creating an app in the provider site, the callback uri (redirect uri) # must be in the form of : # CFG_SITE_SECURE_URL/youraccount/login?login_method=oauth1&provider=PROVIDERNAME # # consumer_key: required # Consumer key taken from provider. # # consumer_secret: required # Consumer secret taken from provider. # # authorize_url: required # The url to redirect the user for authorization # # authorize_parameters: optional # Additional parameters for authorize_url (ie. scope) # # request_token_url: required # The url to get request token # # access_token_url: required # The url to exchange the request token with the access token # # request_url: optional # The url to gather the user information # # request_parameters: optional # Additional parameters for request_url # # email, nickname: optional # id: required # The location where these properties in the response returned from the # provider. # example: # if the response is: # { # 'user': { # 'user_name': 'ABC', # 'contact': [ # { # 'email': 'abc@def.com' # } # ] # }, # 'user_id': 'XXX', # } # then: # email must be : ['user', 'contact', 0, 'email'] # id must be: ['user_id'] # nickname must be: ['user', 'user_name'] # # debug: optional # When debug key is set to 1, after login process, the json object # returned from provider is displayed on the screen. It may be used # for finding where the id, email or nickname is. CFG_OAUTH1_CONFIGURATIONS = { 'twitter': { 'consumer_key' : '', 'consumer_secret' : '', 'request_token_url' : 'https://api.twitter.com/oauth/request_token', 'access_token_url' : 'https://api.twitter.com/oauth/access_token', 'authorize_url' : 'https://api.twitter.com/oauth/authorize', 'id': ['user_id'], 'nickname': ['screen_name'] }, 'flickr': { 'consumer_key' : '', 'consumer_secret' : '', 'request_token_url' : 'http://www.flickr.com/services/oauth/request_token', 'access_token_url' : 'http://www.flickr.com/services/oauth/access_token', 'authorize_url' : 'http://www.flickr.com/services/oauth/authorize', 'authorize_parameters': { 'perms': 'read' }, 'nickname': ['username'], 'id': ['user_nsid'] }, 'linkedin': { 'consumer_key' : '', 'consumer_secret' : '', 'request_token_url' : 'https://api.linkedin.com/uas/oauth/requestToken', 'access_token_url' : 'https://api.linkedin.com/uas/oauth/accessToken', 'authorize_url' : 'https://www.linkedin.com/uas/oauth/authorize', 'request_url': 'http://api.linkedin.com/v1/people/~:(id)', 'request_parameters': { 'format': 'json' }, 'id': ['id'] } } # CFG_OAUTH2_CONFIGURATIONS # # !!IMPORTANT!! # While creating an app in the provider site, the callback uri (redirect uri) # must be in the form of : # CFG_SITE_SECURE_URL/youraccount/login?login_method=oauth2&provider=PROVIDERNAME # # consumer_key: required # Consumer key taken from provider. # # consumer_secret: required # Consumer secret taken from provider. # # authorize_url: required # The url to redirect the user for authorization # # authorize_parameters: # Additional parameters for authorize_url (like scope) # # access_token_url: required # The url to get the access token. # # request_url: required # The url to gather the user information. # {access_token} will be replaced by access token # # email, nickname: optional # id: required # The location where these properties in the response returned from the # provider. # !! See the example in CFG_OAUTH1_CONFIGURATIONS !! # # debug: optional # When debug key is set to 1, after login process, the json object # returned from provider is displayed on the screen. It may be used # for finding where the id, email or nickname is. CFG_OAUTH2_CONFIGURATIONS = { 'facebook': { 'consumer_key': '118319526393', 'consumer_secret': '8d675eb0ef89f2f8fbbe4ee56ab473c6', 'access_token_url': 'https://graph.facebook.com/oauth/access_token', 'authorize_url': 'https://www.facebook.com/dialog/oauth', 'authorize_parameters': { 'scope': 'email' }, 'request_url' : 'https://graph.facebook.com/me?access_token={access_token}', 'email': ['email'], 'id': ['id'], 'nickname': ['username'] }, 'foursquare': { 'consumer_key': '', 'consumer_secret': '', 'access_token_url': 'https://foursquare.com/oauth2/access_token', 'authorize_url': 'https://foursquare.com/oauth2/authorize', 'request_url': 'https://api.foursquare.com/v2/users/self?oauth_token={access_token}', 'id': ['response', 'user', 'id'], 'email': ['response', 'user', 'contact' ,'email'] }, 'yammer': { 'consumer_key': '', 'consumer_secret': '', 'access_token_url': 'https://www.yammer.com/oauth2/access_token.json', 'authorize_url': 'https://www.yammer.com/dialog/oauth', 'request_url': 'https://www.yammer.com/oauth2/access_token.json?access_token={access_token}', 'email':['user', 'contact', 'email_addresses', 0, 'address'], 'id': ['user', 'id'], 'nickname': ['user', 'name'] }, 'googleoauth2': { 'consumer_key': '', 'consumer_secret': '', 'access_token_url': 'https://accounts.google.com/o/oauth2/token', 'authorize_url': 'https://accounts.google.com/o/oauth2/auth', 'authorize_parameters': { 'scope': 'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email' }, 'request_url': 'https://www.googleapis.com/oauth2/v1/userinfo?access_token={access_token}', 'email':['email'], 'id': ['id'] }, 'instagram': { 'consumer_key': '', 'consumer_secret': '', 'access_token_url': 'https://api.instagram.com/oauth/access_token', 'authorize_url': 'https://api.instagram.com/oauth/authorize/', 'authorize_parameters': { 'scope': 'basic' }, 'id': ['user', 'id'], 'nickname': ['user', 'username'] }, 'orcid': { 'consumer_key': '', 'consumer_secret': '', 'authorize_url': 'http://sandbox-1.orcid.org/oauth/authorize', 'access_token_url': 'http://api.sandbox-1.orcid.org/oauth/token', 'request_url': 'http://api.sandbox-1.orcid.org/{id}/orcid-profile', 'authorize_parameters': { 'scope': '/orcid-profile/read-limited', 'response_type': 'code', 'access_type': 'offline', }, 'id': ['orcid'], } } ## Let's override OpenID/OAuth1/OAuth2 configuration from invenio(-local).conf CFG_OPENID_PROVIDERS = config.CFG_OPENID_PROVIDERS CFG_OAUTH1_PROVIDERS = config.CFG_OAUTH1_PROVIDERS CFG_OAUTH2_PROVIDERS = config.CFG_OAUTH2_PROVIDERS if config.CFG_OPENID_CONFIGURATIONS: for provider, configuration in config.CFG_OPENID_CONFIGURATIONS.items(): if provider in CFG_OPENID_CONFIGURATIONS: CFG_OPENID_CONFIGURATIONS[provider].update(configuration) else: CFG_OPENID_CONFIGURATIONS[provider] = configuration if config.CFG_OAUTH1_CONFIGURATIONS: for provider, configuration in config.CFG_OAUTH1_CONFIGURATIONS.items(): if provider in CFG_OAUTH1_CONFIGURATIONS: CFG_OAUTH1_CONFIGURATIONS[provider].update(configuration) else: CFG_OAUTH1_CONFIGURATIONS[provider] = configuration if config.CFG_OAUTH2_CONFIGURATIONS: for provider, configuration in config.CFG_OAUTH2_CONFIGURATIONS.items(): if provider in CFG_OAUTH2_CONFIGURATIONS: CFG_OAUTH2_CONFIGURATIONS[provider].update(configuration) else: CFG_OAUTH2_CONFIGURATIONS[provider] = configuration # If OpenID authentication is enabled, add 'openid' to login methods CFG_OPENID_AUTHENTICATION = bool(CFG_OPENID_PROVIDERS) if CFG_OPENID_AUTHENTICATION: from invenio.external_authentication_openid import ExternalOpenID CFG_EXTERNAL_AUTHENTICATION['openid'] = ExternalOpenID(enforce_external_nicknames=True) # If OAuth1 authentication is enabled, add 'oauth1' to login methods. CFG_OAUTH1_AUTHENTICATION = bool(CFG_OAUTH1_PROVIDERS) if CFG_OAUTH1_PROVIDERS: from invenio.external_authentication_oauth1 import ExternalOAuth1 CFG_EXTERNAL_AUTHENTICATION['oauth1'] = ExternalOAuth1(enforce_external_nicknames=True) # If OAuth2 authentication is enabled, add 'oauth2' to login methods. CFG_OAUTH2_AUTHENTICATION = bool(CFG_OAUTH2_PROVIDERS) if CFG_OAUTH2_AUTHENTICATION: from invenio.external_authentication_oauth2 import ExternalOAuth2 CFG_EXTERNAL_AUTHENTICATION['oauth2'] = ExternalOAuth2(enforce_external_nicknames=True) ## If using SSO, this is the number of seconds after which the keep-alive ## SSO handler is pinged again to provide fresh SSO information. CFG_EXTERNAL_AUTH_SSO_REFRESH = 600 # default data for the add_default_settings function # Note: by default the definition is set to deny any. This won't be a problem # because userid directly connected with roles will still be allowed. # roles # name description definition DEF_ROLES = ((SUPERADMINROLE, 'superuser with all rights', 'deny any'), (WEBACCESSADMINROLE, 'WebAccess administrator', 'deny any'), ('anyuser', 'Any user', 'allow any'), ('basketusers', 'Users who can use baskets', 'allow any'), ('loanusers', 'Users who can use loans', 'allow any'), ('groupusers', 'Users who can use groups', 'allow any'), ('alertusers', 'Users who can use alerts', 'allow any'), ('messageusers', 'Users who can use messages', 'allow any'), ('holdingsusers', 'Users who can view holdings', 'allow any'), ('statisticsusers', 'Users who can view statistics', 'allow any'), ('claimpaperusers', 'Users who can perform changes to their own paper attributions without the need for an operator\'s approval', 'allow any'), ('claimpaperoperators', 'Users who can perform changes to _all_ paper attributions without the need for an operator\'s approval', 'deny any'), ('paperclaimviewers', 'Users who can view "claim my paper" facilities.', 'allow all'), ('paperattributionviewers', 'Users who can view "attribute this paper" facilities', 'allow all'), ('paperattributionlinkviewers', 'Users who can see attribution links in the search', 'allow all'), ) # Demo site roles DEF_DEMO_ROLES = (('photocurator', 'Photo collection curator', 'deny any'), ('thesesviewer', 'Theses and Drafts viewer', 'allow group "Theses and Drafts viewers"'), ('ALEPHviewer', 'ALEPH viewer', 'allow group "ALEPH viewers"'), ('ISOLDEnotesviewer', 'ISOLDE Internal Notes viewer', 'allow group "ISOLDE Internal Notes viewers"'), ('thesescurator', 'Theses collection curator', 'deny any'), ('swordcurator', 'BibSword client curator', 'deny any'), ('referee_DEMOBOO_*', 'Book collection curator', 'deny any'), ('restrictedpicturesviewer', 'Restricted pictures viewer', 'deny any'), ('curator', 'Curator', 'deny any'), ('basketusers', 'Users who can use baskets', 'deny email "hyde@cds.cern.ch"\nallow any'), ('claimpaperusers', 'Users who can perform changes to their own paper attributions without the need for an operator\'s approval', 'deny email "hyde@cds.cern.ch"\nallow any'), ('submit_DEMOJRN_*', 'Users who can submit (and modify) "Atlantis Times" articles', 'deny all'), ('atlantiseditor', 'Users who can configure "Atlantis Times" journal', 'deny all'), ('commentmoderator', 'Users who can moderate comments', 'deny all'), ('poetrycommentreader', 'Users who can view comments in Poetry collection', 'deny all')) DEF_DEMO_USER_ROLES = (('jekyll@cds.cern.ch', 'thesesviewer'), ('balthasar.montague@cds.cern.ch', 'ALEPHviewer'), ('dorian.gray@cds.cern.ch', 'ISOLDEnotesviewer'), ('jekyll@cds.cern.ch', 'swordcurator'), ('jekyll@cds.cern.ch', 'claimpaperusers'), ('dorian.gray@cds.cern.ch', 'referee_DEMOBOO_*'), ('balthasar.montague@cds.cern.ch', 'curator'), ('romeo.montague@cds.cern.ch', 'restrictedpicturesviewer'), ('romeo.montague@cds.cern.ch', 'swordcurator'), ('romeo.montague@cds.cern.ch', 'thesescurator'), ('juliet.capulet@cds.cern.ch', 'restrictedpicturesviewer'), ('juliet.capulet@cds.cern.ch', 'photocurator'), ('romeo.montague@cds.cern.ch', 'submit_DEMOJRN_*'), ('juliet.capulet@cds.cern.ch', 'submit_DEMOJRN_*'), ('balthasar.montague@cds.cern.ch', 'atlantiseditor'), ('romeo.montague@cds.cern.ch', 'poetrycommentreader')) # users # list of e-mail addresses DEF_USERS = [] # actions # name desc allowedkeywords optional DEF_ACTIONS = ( ('cfgwebsearch', 'configure WebSearch', '', 'no'), ('cfgbibformat', 'configure BibFormat', '', 'no'), ('cfgbibknowledge', 'configure BibKnowledge', '', 'no'), ('cfgwebsubmit', 'configure WebSubmit', '', 'no'), ('cfgbibrank', 'configure BibRank', '', 'no'), ('cfgwebcomment', 'configure WebComment', '', 'no'), ('cfgweblinkback', 'configure WebLinkback' , '', 'no'), ('cfgoaiharvest', 'configure OAI Harvest', '', 'no'), ('cfgoairepository', 'configure OAI Repository', '', 'no'), ('cfgbibindex', 'configure BibIndex', '', 'no'), ('cfgbibexport', 'configure BibExport', '', 'no'), ('cfgrobotkeys', 'configure Robot keys', 'login_method,robot', 'yes'), ('cfgbibsort', 'configure BibSort', '', 'no'), ('runbibindex', 'run BibIndex', '', 'no'), ('runbibupload', 'run BibUpload', '', 'no'), ('runwebcoll', 'run webcoll', 'collection', 'yes'), ('runbibformat', 'run BibFormat', 'format', 'yes'), ('runbibclassify', 'run BibClassify', 'taxonomy', 'yes'), ('runbibtaskex', 'run BibTaskEx example', '', 'no'), ('runbibrank', 'run BibRank', '', 'no'), ('runoaiharvest', 'run oaiharvest task', '', 'no'), ('runoairepository', 'run oairepositoryupdater task', '', 'no'), ('runbibedit', 'run Record Editor', 'collection', 'yes'), ('runbibeditmulti', 'run Multi-Record Editor', '', 'no'), ('runbibdocfile', 'run Document File Manager', '', 'no'), ('runbibmerge', 'run Record Merger', '', 'no'), ('runbibswordclient', 'run BibSword client', '', 'no'), ('runwebstatadmin', 'run WebStadAdmin', '', 'no'), ('runinveniogc', 'run InvenioGC', '', 'no'), ('runbibexport', 'run BibExport', '', 'no'), ('referee', 'referee document type doctype/category categ', 'doctype,categ', 'yes'), ('submit', 'use webSubmit', 'doctype,act,categ', 'yes'), ('viewrestrdoc', 'view restricted document', 'status', 'no'), ('viewrestrcomment', 'view restricted comment', 'status', 'no'), (WEBACCESSACTION, 'configure WebAccess', '', 'no'), (DELEGATEADDUSERROLE, 'delegate subroles inside WebAccess', 'role', 'no'), (VIEWRESTRCOLL, 'view restricted collection', 'collection', 'no'), ('cfgwebjournal', 'configure WebJournal', 'name,with_editor_rights', 'no'), ('viewcomment', 'view comments', 'collection', 'no'), ('viewlinkbacks', 'view linkbacks', 'collection', 'no'), ('sendcomment', 'send comments', 'collection', 'no'), ('attachcommentfile', 'attach files to comments', 'collection', 'no'), ('attachsubmissionfile', 'upload files to drop box during submission', '', 'no'), ('cfgbibexport', 'configure BibExport', '', 'no'), ('runbibexport', 'run BibExport', '', 'no'), ('usebaskets', 'use baskets', '', 'no'), ('useloans', 'use loans', '', 'no'), ('usegroups', 'use groups', '', 'no'), ('usealerts', 'use alerts', '', 'no'), ('usemessages', 'use messages', '', 'no'), ('viewholdings', 'view holdings', 'collection', 'yes'), ('viewstatistics', 'view statistics', 'collection', 'yes'), ('runbibcirculation', 'run BibCirculation', '', 'no'), ('moderatecomments', 'moderate comments', 'collection', 'no'), ('moderatelinkbacks', 'moderate linkbacks', 'collection', 'no'), ('runbatchuploader', 'run batchuploader', 'collection', 'yes'), ('runbibtasklet', 'run BibTaskLet', '', 'no'), ('claimpaper_view_pid_universe', 'View the Claim Paper interface', '', 'no'), ('claimpaper_claim_own_papers', 'Clam papers to his own personID', '', 'no'), ('claimpaper_claim_others_papers', 'Claim papers for others', '', 'no'), ('claimpaper_change_own_data', 'Change data associated to his own person ID', '', 'no'), ('claimpaper_change_others_data', 'Change data of any person ID', '', 'no'), ('runbibtasklet', 'run BibTaskLet', '', 'no'), ('cfgbibsched', 'configure BibSched', '', 'no') ) # Default authorizations # role action arguments DEF_AUTHS = (('basketusers', 'usebaskets', {}), ('loanusers', 'useloans', {}), ('groupusers', 'usegroups', {}), ('alertusers', 'usealerts', {}), ('messageusers', 'usemessages', {}), ('holdingsusers', 'viewholdings', {}), ('statisticsusers', 'viewstatistics', {}), ('claimpaperusers', 'claimpaper_view_pid_universe', {}), ('claimpaperoperators', 'claimpaper_view_pid_universe', {}), ('claimpaperusers', 'claimpaper_claim_own_papers', {}), ('claimpaperoperators', 'claimpaper_claim_own_papers', {}), ('claimpaperoperators', 'claimpaper_claim_others_papers', {}), ('claimpaperusers', 'claimpaper_change_own_data', {}), ('claimpaperoperators', 'claimpaper_change_own_data', {}), ('claimpaperoperators', 'claimpaper_change_others_data', {}), ) # Demo site authorizations # role action arguments DEF_DEMO_AUTHS = ( ('photocurator', 'runwebcoll', {'collection': 'Pictures'}), ('restrictedpicturesviewer', 'viewrestrdoc', {'status': 'restricted_picture'}), ('thesesviewer', VIEWRESTRCOLL, {'collection': 'Theses'}), ('thesesviewer', VIEWRESTRCOLL, {'collection': 'Drafts'}), ('ALEPHviewer', VIEWRESTRCOLL, {'collection': 'ALEPH Theses'}), ('ALEPHviewer', VIEWRESTRCOLL, {'collection': 'ALEPH Internal Notes'}), ('ISOLDEnotesviewer', VIEWRESTRCOLL, {'collection': 'ISOLDE Internal Notes'}), ('referee_DEMOBOO_*', 'referee', {'doctype': 'DEMOBOO', 'categ': '*'}), ('curator', 'cfgbibknowledge', {}), ('curator', 'runbibedit', {}), ('curator', 'runbibeditmulti', {}), ('curator', 'runbibmerge', {}), ('swordcurator', 'runbibswordclient', {}), ('thesescurator', 'runbibedit', {'collection': 'Theses'}), ('thesescurator', VIEWRESTRCOLL, {'collection': 'Theses'}), ('photocurator', 'runbibedit', {'collection': 'Pictures'}), ('referee_DEMOBOO_*', 'runbibedit', {'collection': 'Books'}), ('submit_DEMOJRN_*', 'submit', {'doctype': 'DEMOJRN', 'act': 'SBI', 'categ': '*'}), ('submit_DEMOJRN_*', 'submit', {'doctype': 'DEMOJRN', 'act': 'MBI', 'categ': '*'}), ('submit_DEMOJRN_*', 'cfgwebjournal', {'name': 'AtlantisTimes', 'with_editor_rights': 'no'}), ('atlantiseditor', 'cfgwebjournal', {'name': 'AtlantisTimes', 'with_editor_rights': 'yes'}), ('referee_DEMOBOO_*', 'runbatchuploader', {'collection': 'Books'}), ('poetrycommentreader', 'viewcomment', {'collection': 'Poetry'}), ('atlantiseditor', VIEWRESTRCOLL, {'collection': 'Atlantis Times Drafts'}), ('anyuser', 'submit', {'doctype': 'DEMOART', 'act': 'SBI', 'categ': 'ARTICLE'}), ) _ = gettext_set_language(CFG_SITE_LANG) # Activities (i.e. actions) for which exists an administrative web interface. CFG_ACC_ACTIVITIES_URLS = { 'runbibedit' : (_("Run Record Editor"), "%s/%s/edit/?ln=%%s" % (CFG_SITE_URL, CFG_SITE_RECORD)), 'runbibeditmulti' : (_("Run Multi-Record Editor"), "%s/%s/multiedit/?ln=%%s" % (CFG_SITE_URL, CFG_SITE_RECORD)), 'runbibdocfile' : (_("Run Document File Manager"), "%s/%s/managedocfiles?ln=%%s" % (CFG_SITE_URL, CFG_SITE_RECORD)), 'runbibmerge' : (_("Run Record Merger"), "%s/%s/merge/?ln=%%s" % (CFG_SITE_URL, CFG_SITE_RECORD)), 'runbibswordclient' : (_("Run BibSword client"), "%s/bibsword/?ln=%%s" % CFG_SITE_URL), 'cfgbibknowledge' : (_("Configure BibKnowledge"), "%s/kb?ln=%%s" % CFG_SITE_URL), 'cfgbibformat' : (_("Configure BibFormat"), "%s/admin/bibformat/bibformatadmin.py?ln=%%s" % CFG_SITE_URL), 'cfgoaiharvest' : (_("Configure OAI Harvest"), "%s/admin/oaiharvest/oaiharvestadmin.py?ln=%%s" % CFG_SITE_URL), 'cfgoairepository' : (_("Configure OAI Repository"), "%s/admin/oairepository/oairepositoryadmin.py?ln=%%s" % CFG_SITE_URL), 'cfgbibindex' : (_("Configure BibIndex"), "%s/admin/bibindex/bibindexadmin.py?ln=%%s" % CFG_SITE_URL), 'cfgbibrank' : (_("Configure BibRank"), "%s/admin/bibrank/bibrankadmin.py?ln=%%s" % CFG_SITE_URL), 'cfgwebaccess' : (_("Configure WebAccess"), "%s/admin/webaccess/webaccessadmin.py?ln=%%s" % CFG_SITE_URL), 'cfgwebcomment' : (_("Configure WebComment"), "%s/admin/webcomment/webcommentadmin.py?ln=%%s" % CFG_SITE_URL), 'cfgweblinkback' : (_("Configure WebLinkback"), "%s/admin/weblinkback/weblinkbackadmin.py?ln=%%s" % CFG_SITE_URL), 'cfgwebsearch' : (_("Configure WebSearch"), "%s/admin/websearch/websearchadmin.py?ln=%%s" % CFG_SITE_URL), 'cfgwebsubmit' : (_("Configure WebSubmit"), "%s/admin/websubmit/websubmitadmin.py?ln=%%s" % CFG_SITE_URL), 'cfgwebjournal' : (_("Configure WebJournal"), "%s/admin/webjournal/webjournaladmin.py?ln=%%s" % CFG_SITE_URL), 'cfgbibsort' : (_("Configure BibSort"), "%s/admin/bibsort/bibsortadmin.py?ln=%%s" % CFG_SITE_URL), 'runbibcirculation' : (_("Run BibCirculation"), "%s/admin/bibcirculation/bibcirculationadmin.py?ln=%%s" % CFG_SITE_URL), 'runbatchuploader' : (_("Run Batch Uploader"), "%s/batchuploader/metadata?ln=%%s" % CFG_SITE_URL), 'claimpaper_claim_others_papers' : (_("Run Person/Author Manager"), "%s/person/search?ln=%%s" % CFG_SITE_URL) } CFG_WEBACCESS_MSGS = { 0: 'Try to <a href="%s/youraccount/login?referer=%%s">login</a> with another account.' % (CFG_SITE_SECURE_URL), 1: '<br />If you think this is not correct, please contact: <a href="mailto:%s">%s</a>' % (CFG_SITE_SUPPORT_EMAIL, CFG_SITE_SUPPORT_EMAIL), 2: '<br />If you have any questions, please write to <a href="mailto:%s">%s</a>' % (CFG_SITE_SUPPORT_EMAIL, CFG_SITE_SUPPORT_EMAIL), 3: 'Guest users are not allowed, please <a href="%s/youraccount/login">login</a>.' % CFG_SITE_SECURE_URL, 4: 'The site is temporarily closed for maintenance. Please come back soon.', 5: 'Authorization failure', 6: '%s temporarily closed' % CFG_SITE_NAME, 7: 'This functionality is temporarily closed due to server maintenance. Please use only the search engine in the meantime.', 8: 'Functionality temporarily closed' } CFG_WEBACCESS_WARNING_MSGS = { 0: 'Authorization granted', 1: 'You are not authorized to perform this action.', 2: 'You are not authorized to perform any action.', 3: 'The action %s does not exist.', 4: 'Unexpected error occurred.', 5: 'Missing mandatory keyword argument(s) for this action.', 6: 'Guest accounts are not authorized to perform this action.', 7: 'Not enough arguments, user ID and action name required.', 8: 'Incorrect keyword argument(s) for this action.', 9: """Account '%s' is not yet activated.""", 10: """You were not authorized by the authentication method '%s'.""", 11: """The selected login method '%s' is not the default method for this account, please try another one.""", 12: """Selected login method '%s' does not exist.""", 13: """Could not register '%s' account.""", 14: """Could not login using '%s', because this user is unknown.""", 15: """Could not login using your '%s' account, because you have introduced a wrong password.""", 16: """External authentication troubles using '%s' (maybe temporary network problems).""", 17: """You have not yet confirmed the email address for the '%s' authentication method.""", 18: """The administrator has not yet activated your account for the '%s' authentication method.""", 19: """The site is having troubles in sending you an email for confirming your email address. The error has been logged and will be taken care of as soon as possible.""", 20: """No roles are authorized to perform action %s with the given parameters.""", 21: """Verification cancelled""", 22: """Verification failed. Please try again or use another provider to login""", 23: """Verification failed. It is probably because the configuration isn't set properly. Please contact with the <a href="mailto:%s">administator</a>""" % CFG_SITE_ADMIN_EMAIL } #There are three status key that must be here: OK, REMOVED and REVOKED #the value doesn't matter at all CFG_WEB_API_KEY_STATUS = { 'OK':'OK', 'REMOVED':'REMOVED', 'REVOKED':'REVOKED', 'WARNING':'WARNING' }
AlbertoPeon/invenio
modules/webaccess/lib/access_control_config.py
Python
gpl-2.0
35,364
<?php namespace TYPO3\CMS\Workspaces\Tests\Unit\Controller\Remote; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use Prophecy\Argument; use Prophecy\Prophecy\ObjectProphecy; use TYPO3\CMS\Core\Resource\File; use TYPO3\CMS\Core\Resource\FileReference; use TYPO3\CMS\Core\Resource\ProcessedFile; use TYPO3\CMS\Core\Utility\GeneralUtility; /** * RemoteServer test */ class RemoteServerTest extends \TYPO3\TestingFramework\Core\Unit\UnitTestCase { /** * @var \TYPO3\CMS\Workspaces\Controller\Remote\RemoteServer */ protected $subject; /** * @var FileReference[]|ObjectProphecy[] */ protected $fileReferenceProphecies; /** * Set up */ protected function setUp() { parent::setUp(); $this->subject = $this->getAccessibleMock(\TYPO3\CMS\Workspaces\Controller\Remote\RemoteServer::class, ['__none']); } /** * Tear down. */ protected function tearDown() { parent::tearDown(); unset($this->subject); unset($this->fileReferenceProphecies); } /** * @return array */ public function prepareFileReferenceDifferencesAreCorrectDataProvider() { return [ // without thumbnails 'unchanged wo/thumbnails' => ['1,2,3,4', '1,2,3,4', false, null], 'front addition wo/thumbnails' => ['1,2,3,4', '99,1,2,3,4', false, [ 'live' => '/img/1.png /img/2.png /img/3.png /img/4.png', 'differences' => '<ins>/img/99.png </ins>/img/1.png /img/2.png /img/3.png /img/4.png', ]], 'end addition wo/thumbnails' => ['1,2,3,4', '1,2,3,4,99', false, [ 'live' => '/img/1.png /img/2.png /img/3.png /img/4.png', 'differences' => '/img/1.png /img/2.png /img/3.png /img/4.png <ins>/img/99.png </ins>', ]], 'reorder wo/thumbnails' => ['1,2,3,4', '1,3,2,4', false, [ 'live' => '/img/1.png /img/2.png /img/3.png /img/4.png', 'differences' => '/img/1.png <ins>/img/3.png </ins>/img/2.png <del>/img/3.png </del>/img/4.png', ]], 'move to end wo/thumbnails' => ['1,2,3,4', '2,3,4,1', false, [ 'live' => '/img/1.png /img/2.png /img/3.png /img/4.png', 'differences' => '<del>/img/1.png </del>/img/2.png /img/3.png /img/4.png <ins>/img/1.png </ins>', ]], 'move to front wo/thumbnails' => ['1,2,3,4', '4,1,2,3', false, [ 'live' => '/img/1.png /img/2.png /img/3.png /img/4.png', 'differences' => '<ins>/img/4.png </ins>/img/1.png /img/2.png /img/3.png <del>/img/4.png </del>', ]], 'keep last wo/thumbnails' => ['1,2,3,4', '4', false, [ 'live' => '/img/1.png /img/2.png /img/3.png /img/4.png', 'differences' => '<del>/img/1.png /img/2.png /img/3.png </del>/img/4.png', ]], // with thumbnails 'unchanged w/thumbnails' => ['1,2,3,4', '1,2,3,4', true, null], 'front addition w/thumbnails' => ['1,2,3,4', '99,1,2,3,4', true, [ 'live' => '<img src="/tmb/1.png" /> <img src="/tmb/2.png" /> <img src="/tmb/3.png" /> <img src="/tmb/4.png" />', 'differences' => '<ins><img src="/tmb/99.png" /> </ins><img src="/tmb/1.png" /> <img src="/tmb/2.png" /> <img src="/tmb/3.png" /> <img src="/tmb/4.png" />', ]], 'end addition w/thumbnails' => ['1,2,3,4', '1,2,3,4,99', true, [ 'live' => '<img src="/tmb/1.png" /> <img src="/tmb/2.png" /> <img src="/tmb/3.png" /> <img src="/tmb/4.png" />', 'differences' => '<img src="/tmb/1.png" /> <img src="/tmb/2.png" /> <img src="/tmb/3.png" /> <img src="/tmb/4.png" /> <ins><img src="/tmb/99.png" /> </ins>', ]], 'reorder w/thumbnails' => ['1,2,3,4', '1,3,2,4', true, [ 'live' => '<img src="/tmb/1.png" /> <img src="/tmb/2.png" /> <img src="/tmb/3.png" /> <img src="/tmb/4.png" />', 'differences' => '<img src="/tmb/1.png" /> <ins><img src="/tmb/3.png" /> </ins><img src="/tmb/2.png" /> <del><img src="/tmb/3.png" /> </del><img src="/tmb/4.png" />', ]], 'move to end w/thumbnails' => ['1,2,3,4', '2,3,4,1', true, [ 'live' => '<img src="/tmb/1.png" /> <img src="/tmb/2.png" /> <img src="/tmb/3.png" /> <img src="/tmb/4.png" />', 'differences' => '<del><img src="/tmb/1.png" /> </del><img src="/tmb/2.png" /> <img src="/tmb/3.png" /> <img src="/tmb/4.png" /> <ins><img src="/tmb/1.png" /> </ins>', ]], 'move to front w/thumbnails' => ['1,2,3,4', '4,1,2,3', true, [ 'live' => '<img src="/tmb/1.png" /> <img src="/tmb/2.png" /> <img src="/tmb/3.png" /> <img src="/tmb/4.png" />', 'differences' => '<ins><img src="/tmb/4.png" /> </ins><img src="/tmb/1.png" /> <img src="/tmb/2.png" /> <img src="/tmb/3.png" /> <del><img src="/tmb/4.png" /> </del>', ]], 'keep last w/thumbnails' => ['1,2,3,4', '4', true, [ 'live' => '<img src="/tmb/1.png" /> <img src="/tmb/2.png" /> <img src="/tmb/3.png" /> <img src="/tmb/4.png" />', 'differences' => '<del><img src="/tmb/1.png" /> <img src="/tmb/2.png" /> <img src="/tmb/3.png" /> </del><img src="/tmb/4.png" />', ]], ]; } /** * @param string $fileFileReferenceList * @param string $versionFileReferenceList * @param $useThumbnails * @param array|null $expected * @dataProvider prepareFileReferenceDifferencesAreCorrectDataProvider * @test */ public function prepareFileReferenceDifferencesAreCorrect($fileFileReferenceList, $versionFileReferenceList, $useThumbnails, array $expected = null) { $liveFileReferences = $this->getFileReferenceProphecies($fileFileReferenceList); $versionFileReferences = $this->getFileReferenceProphecies($versionFileReferenceList); $result = $this->subject->_call( 'prepareFileReferenceDifferences', $liveFileReferences, $versionFileReferences, $useThumbnails ); $this->assertSame($expected, $result); } /** * @param string $idList List of ids * @return FileReference[]|ObjectProphecy[] */ protected function getFileReferenceProphecies($idList) { $fileReferenceProphecies = []; $ids = GeneralUtility::trimExplode(',', $idList, true); foreach ($ids as $id) { $fileReferenceProphecies[$id] = $this->getFileReferenceProphecy($id); } return $fileReferenceProphecies; } /** * @param int $id * @return ObjectProphecy|FileReference */ protected function getFileReferenceProphecy($id) { if (isset($this->fileReferenceProphecies[$id])) { return $this->fileReferenceProphecies[$id]; } $processedFileProphecy = $this->prophesize(ProcessedFile::class); $processedFileProphecy->getPublicUrl(Argument::cetera())->willReturn('/tmb/' . $id . '.png'); $fileProphecy = $this->prophesize(File::class); $fileProphecy->process(Argument::cetera())->willReturn($processedFileProphecy->reveal()); $fileReferenceProphecy = $this->prophesize(FileReference::class); $fileReferenceProphecy->getUid()->willReturn($id); $fileReferenceProphecy->getOriginalFile()->willReturn($fileProphecy->reveal()); $fileReferenceProphecy->getPublicUrl(Argument::cetera())->willReturn('/img/' . $id . '.png'); $this->fileReferenceProphecies[$id] = $fileReferenceProphecy->reveal(); return $this->fileReferenceProphecies[$id]; } }
morinfa/TYPO3.CMS
typo3/sysext/workspaces/Tests/Unit/Controller/Remote/RemoteServerTest.php
PHP
gpl-2.0
8,153
# cgi-lib.pl # Common functions for writing http headers #---------------------------------------------------------- # # @APPLE_LICENSE_HEADER_START@ # # # Copyright (c) 1999-2008 Apple Inc. All Rights Reserved. # # This file contains Original Code and/or Modifications of Original Code # as defined in and that are subject to the Apple Public Source License # Version 2.0 (the 'License'). You may not use this file except in # compliance with the License. Please obtain a copy of the License at # http://www.opensource.apple.com/apsl/ and read it before using this # file. # # The Original Code and all software distributed under the License are # distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER # EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, # INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. # Please see the License for the specific language governing rights and # limitations under the License. # # @APPLE_LICENSE_HEADER_END@ # # #--------------------------------------------------------- package cgilib; # init days and months my $ssl = $ENV{"HTTPS"}; @weekday = ( "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ); @month = ( "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ); %status = ( '200' => "OK", '302' => "Temporarily Unavailable", '401' => "Unauthorized", '403' => "Forbidden", '404' => "File Not Found", ); # PrintOKTextHeader(servername, cookie) # changed 7/25/01 by JAA to add support for cookies sub PrintOKTextHeader { my $datestr = HttpDate(time()); my $charsetstr = ''; if($ENV{"LANGUAGE"} eq "ja") { $charsetstr = ';charset=Shift_JIS'; } my $headerstr = "HTTP/1.0 200 OK\r\nServer: $_[0]\r\nContent-Type: text/html$charsetstr\r\nConnection:close\r\n"; $headerstr .= "Set-Cookie: $_[1]\r\n" if ($_[1] ne ""); # Safari cache control $headerstr .= "Expires: Mon, 26 Jul 1997 05:00:00 GMT\r\n"; $headerstr .= "Last-Modified: $datestr\r\n"; $headerstr .= "Cache-Control: no-store, no-cache, must-revalidate\r\n"; $headerstr .= "Cache-Control: post-check=0, pre-check=0, false\r\n"; $headerstr .= "Pragma: no-cache\r\n"; $headerstr .= "\r\n"; print $headerstr; } # PrintFileDownloadHeader(servername) # added 4/25/02 by JAA to allow content downloads sub PrintFileDownloadHeader { my $datestr = HttpDate(time()); my $charsetstr = ''; if($ENV{"LANGUAGE"} eq "ja") { $charsetstr = ';charset=Shift_JIS'; } my $headerstr = "HTTP/1.0 200 OK\r\nDate: $datestr\r\nServer: $_[0]\r\nContent-Type: application/octet-stream\r\nConnection:close\r\n"; print $headerstr; } # PrintRedirectHeader(servername, redirectpath) # changed from PrintRedirectHeader(servername, serverip, serverport, redirectpage) sub PrintRedirectHeader { my $datestr = HttpDate(time()); print "HTTP/1.0 302 Temporarily Unavailable\r\nDate: $datestr\r\nServer: $_[0]\r\n" . "Location: $_[1]\r\nConnection:close\r\n\r\n"; } # PrintChallengeHeader(servername, challengeheader) sub PrintChallengeHeader { my $datestr = HttpDate(time()); print "HTTP/1.0 401 Unauthorized\r\nDate: $datestr\r\nServer: $_[0]\r\n" . "Content-Type: text/html\r\nConnection:close\r\n$_[1]\r\n\r\n"; } # PrintChallengeResponse(servername, challengeheader, messageHash) sub PrintChallengeResponse { PrintChallengeHeader($_[0], $_[1]); PrintUnauthorizedHtml($_[2]); } # PrintForbiddenHeader(servername) sub PrintForbiddenHeader { my $datestr = HttpDate(time()); print "HTTP/1.0 403 Forbidden\r\nDate: $datestr\r\nServer: $_[0]\r\nContent-Type: text/html\r\nConnection:close\r\n\r\n"; } # PrintForbiddenResponse(servername, filename, messageHash) sub PrintForbiddenResponse { PrintForbiddenHeader($_[0]); PrintForbiddenHtml($_[1], $_[2]); } # PrintForbiddenHtml(filename, messageHash) sub PrintForbiddenHtml { my $messHash = $_[1]; my %messages = %$messHash; print "<HTML><HEAD><TITLE>$messages{'Http403Status'}</TITLE></HEAD>" . "<BODY><H1>$messages{'Http403Status'}</H1><P>$messages{'Http403Body'} : $_[0]</P></BODY></HTML>"; } # PrintNotFoundHeader(servername) sub PrintNotFoundHeader { my $datestr = HttpDate(time()); print "HTTP/1.0 404 File Not Found\r\nDate: $datestr\r\nServer: $_[0]\r\nContent-Type: text/html\r\nConnection:close\r\n\r\n"; } # PrintNotFoundResponse(servername, filename, messageHash) sub PrintNotFoundResponse { PrintNotFoundHeader($_[0]); PrintNotFoundHtml($_[1], $_[2]); } # PrintNotFoundHtml(filename, messageHash) sub PrintNotFoundHtml { my $messHash = $_[1]; my %messages = %$messHash; print "<HTML><HEAD><TITLE>$messages{'Http404Status'}</TITLE></HEAD>" . "<BODY><H1>$messages{'Http404Status'}</H1><P>$messages{'Http404Body'} : $_[0]</P></BODY></HTML>"; } # PrintStatusLine(num) sub PrintStatusLine { print "HTTP/1.0 $_[0] $status{$_[0]}\r\n"; } # PrintDateAndServerStr(server) sub PrintDateAndServerStr { my $datestr = HttpDate(time()); print "Date: $datestr\r\nServer: $_[0]\r\n"; } # PrintTextTypeAndCloseStr() sub PrintTextTypeAndCloseStr { print "Content-Type: text/html\r\nConnection: close\r\n\r\n"; } # PrintUnauthorizedHeader(servername, realm) sub PrintUnauthorizedHeader { my $datestr = HttpDate(time()); print "HTTP/1.0 401 Unauthorized\r\nServer:$_[0]\r\nDate: $datestr\r\n" . "WWW-authenticate: Basic realm=\"$_[1]\"\r\n" . "Content-Type: text/html\r\nConnection: close\r\n\r\n"; } # PrintServerNotRunningHtml(messageHash) sub PrintServerNotRunningHtml { my $messHash = $_[0]; my %messages = %$messHash; print "<HTML><HEAD><TITLE>$messages{'ServerNotRunningMessage'}</TITLE></HEAD>" . "<BODY><BR><H3>&nbsp;&nbsp;$messages{'StartServerMessage'}</H3>" . "</BODY></HTML>"; } # PrintUnauthorizedHtml(messageHash) sub PrintUnauthorizedHtml { my $messHash = $_[0]; my %messages = %$messHash; print "<HTML><HEAD><TITLE> $messages{'Http401Status'}</TITLE></HEAD>" . "<BODY><H1> $messages{'Http401Status'}</H1><P> $messages{'Http401Body'}.\n" . "</P></BODY></HTML>"; } # PrintUnauthorizedResponse(servername, realm, messageHash) sub PrintUnauthorizedResponse { PrintUnauthorizedHeader($_[0], $_[1]); PrintUnauthorizedHtml($_[2]); } # HttpDate(timeinsecfrom1970) sub HttpDate { local @tm = gmtime($_[0]); return sprintf "%s, %d %s %d %2.2d:%2.2d:%2.2d GMT", $weekday[$tm[6]], $tm[3], $month[$tm[4]], $tm[5]+1900, $tm[2], $tm[1], $tm[0]; } 1; #return true
zkf-qwj/Relay-Wasu-NoBalance
DarwinStreamingSrvr6.0.3-Source-relay-wasu-sx/WebAdmin/WebAdminHtml/cgi-lib.pl
Perl
gpl-2.0
6,514
<?php /** * Summon record fallback loader * * PHP version 7 * * Copyright (C) Villanova University 2018. * * This program 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. * * 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 * * @category VuFind * @package Record * @author Demian Katz <demian.katz@villanova.edu> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://vufind.org Main Site */ namespace VuFind\Record\FallbackLoader; use SerialsSolutions\Summon\Zend2 as Connector; use VuFind\Db\Table\Resource; use VuFindSearch\Backend\Summon\Backend; use VuFindSearch\ParamBag; /** * Summon record fallback loader * * @category VuFind * @package Record * @author Demian Katz <demian.katz@villanova.edu> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://vufind.org Main Site */ class Summon implements FallbackLoaderInterface { /** * Resource table * * @var Resource */ protected $table; /** * Summon backend * * @var Backend */ protected $backend; /** * Constructor * * @param Resource $table Resource database table object * @param Backend $backend Summon search backend */ public function __construct(Resource $table, Backend $backend) { $this->table = $table; $this->backend = $backend; } /** * Given an array of IDs that failed to load, try to find them using a * fallback mechanism. * * @param array $ids IDs to load * * @return array */ public function load($ids) { $retVal = []; foreach ($ids as $id) { foreach ($this->fetchSingleRecord($id) as $record) { $this->updateRecord($record, $id); $retVal[] = $record; } } return $retVal; } /** * Fetch a single record (null if not found). * * @param string $id ID to load * * @return \VuFindSearch\Response\RecordCollectionInterface */ protected function fetchSingleRecord($id) { $resource = $this->table->findResource($id, 'Summon'); if ($resource && ($extra = json_decode($resource->extra_metadata, true))) { $bookmark = $extra['bookmark'] ?? ''; if (strlen($bookmark) > 0) { $params = new ParamBag( ['summonIdType' => Connector::IDENTIFIER_BOOKMARK] ); return $this->backend->retrieve($bookmark, $params); } } return new \VuFindSearch\Backend\Summon\Response\RecordCollection([]); } /** * When a record ID has changed, update the record driver and database to * reflect the changes. * * @param \VuFind\RecordDriver\AbstractBase $record Record to update * @param string $previousId Old ID of record * * @return void */ protected function updateRecord($record, $previousId) { // Update the record driver with knowledge of the previous identifier... $record->setPreviousUniqueId($previousId); // Update the database to replace the obsolete identifier... $this->table->updateRecordId($previousId, $record->getUniqueId(), 'Summon'); } }
samueloph/vufind
module/VuFind/src/VuFind/Record/FallbackLoader/Summon.php
PHP
gpl-2.0
3,913
<?php /** * Side Box Template * * @copyright Copyright 2003-2020 Zen Cart Development Team * @copyright Portions Copyright 2003 osCommerce * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0 * @version $Id: DrByte 2020 Jun 19 Modified in v1.5.7 $ */ $content = ""; $content .= '<div id="' . str_replace('_', '-', $box_id . 'Content') . '" class="sideBoxContent">' . "\n"; $content .= '<ul class="list-links orderHistList">' . "\n" ; foreach ($customer_orders as $row) { $content .= ' <li> <a href="' . zen_href_link(zen_get_info_page($row['id']), 'products_id=' . $row['id']) . '">' . $row['name'] . '</a> <a href="' . zen_href_link($_GET['main_page'], zen_get_all_get_params(array('action')) . 'action=cust_order&pid=' . $row['id']) . '"><i class="fa fa-cart-arrow-down"></i></a> </li> '; } $content .= '</ul>' . "\n" ; $content .= '</div>';
barco57/zencart
includes/templates/responsive_classic/sideboxes/tpl_order_history.php
PHP
gpl-2.0
879
#include "expire-tiles.hpp" #include "options.hpp" #include <iterator> #include <stdio.h> #include <string.h> #include <stdarg.h> #include <stdlib.h> #include <stdexcept> #include <boost/format.hpp> #include <set> #define EARTH_CIRCUMFERENCE (40075016.68) namespace { void run_test(const char* test_name, void (*testfunc)()) { try { fprintf(stderr, "%s\n", test_name); testfunc(); } catch(const std::exception& e) { fprintf(stderr, "%s\n", e.what()); fprintf(stderr, "FAIL\n"); exit(EXIT_FAILURE); } fprintf(stderr, "PASS\n"); } #define RUN_TEST(x) run_test(#x, &(x)) #define ASSERT_EQ(a, b) { if (!((a) == (b))) { throw std::runtime_error((boost::format("Expecting %1% == %2%, but %3% != %4%") % #a % #b % (a) % (b)).str()); } } struct xyz { int z, x, y; xyz(int z_, int x_, int y_) : z(z_), x(x_), y(y_) {} bool operator==(const xyz &other) const { return ((z == other.z) && (x == other.x) && (y == other.y)); } bool operator<(const xyz &other) const { return ((z < other.z) || ((z == other.z) && ((x < other.x) || ((x == other.x) && (y < other.y))))); } void to_bbox(double &x0, double &y0, double &x1, double &y1) const { const double datum = 0.5 * (1 << z); const double scale = EARTH_CIRCUMFERENCE / (1 << z); x0 = (x - datum) * scale; y0 = (datum - (y + 1)) * scale; x1 = ((x + 1) - datum) * scale; y1 = (datum - y) * scale; } void to_centroid(double &x0, double &y0) const { const double datum = 0.5 * (1 << z); const double scale = EARTH_CIRCUMFERENCE / (1 << z); x0 = ((x + 0.5) - datum) * scale; y0 = (datum - (y + 0.5)) * scale; } }; std::ostream &operator<<(std::ostream &out, const xyz &tile) { out << tile.z << "/" << tile.x << "/" << tile.y; return out; } struct tile_output_set : public expire_tiles::tile_output { tile_output_set() {} virtual ~tile_output_set() {} virtual void output_dirty_tile(int x, int y, int zoom, int min_zoom) { int y_min, x_iter, y_iter, x_max, y_max, out_zoom, zoom_diff; if (zoom > min_zoom) out_zoom = zoom; else out_zoom = min_zoom; zoom_diff = out_zoom - zoom; y_min = y << zoom_diff; x_max = (x + 1) << zoom_diff; y_max = (y + 1) << zoom_diff; for (x_iter = x << zoom_diff; x_iter < x_max; x_iter++) { for (y_iter = y_min; y_iter < y_max; y_iter++) { m_tiles.insert(xyz(out_zoom, x_iter, y_iter)); } } } std::set<xyz> m_tiles; }; void test_expire_simple_z1() { options_t opt; opt.expire_tiles_zoom = 1; opt.expire_tiles_zoom_min = 1; expire_tiles et(&opt); tile_output_set set; // as big a bbox as possible at the origin to dirty all four // quadrants of the world. et.from_bbox(-10000, -10000, 10000, 10000); et.output_and_destroy(&set); ASSERT_EQ(set.m_tiles.size(), 4); std::set<xyz>::iterator itr = set.m_tiles.begin(); ASSERT_EQ(*itr, xyz(1, 0, 0)); ++itr; ASSERT_EQ(*itr, xyz(1, 0, 1)); ++itr; ASSERT_EQ(*itr, xyz(1, 1, 0)); ++itr; ASSERT_EQ(*itr, xyz(1, 1, 1)); ++itr; } void test_expire_simple_z3() { options_t opt; opt.expire_tiles_zoom = 3; opt.expire_tiles_zoom_min = 3; expire_tiles et(&opt); tile_output_set set; // as big a bbox as possible at the origin to dirty all four // quadrants of the world. et.from_bbox(-10000, -10000, 10000, 10000); et.output_and_destroy(&set); ASSERT_EQ(set.m_tiles.size(), 4); std::set<xyz>::iterator itr = set.m_tiles.begin(); ASSERT_EQ(*itr, xyz(3, 3, 3)); ++itr; ASSERT_EQ(*itr, xyz(3, 3, 4)); ++itr; ASSERT_EQ(*itr, xyz(3, 4, 3)); ++itr; ASSERT_EQ(*itr, xyz(3, 4, 4)); ++itr; } void test_expire_simple_z18() { options_t opt; opt.expire_tiles_zoom = 18; opt.expire_tiles_zoom_min = 18; expire_tiles et(&opt); tile_output_set set; // dirty a smaller bbox this time, as at z18 the scale is // pretty small. et.from_bbox(-1, -1, 1, 1); et.output_and_destroy(&set); ASSERT_EQ(set.m_tiles.size(), 4); std::set<xyz>::iterator itr = set.m_tiles.begin(); ASSERT_EQ(*itr, xyz(18, 131071, 131071)); ++itr; ASSERT_EQ(*itr, xyz(18, 131071, 131072)); ++itr; ASSERT_EQ(*itr, xyz(18, 131072, 131071)); ++itr; ASSERT_EQ(*itr, xyz(18, 131072, 131072)); ++itr; } std::set<xyz> generate_random(int zoom, size_t count) { size_t num = 0; std::set<xyz> set; const int coord_mask = (1 << zoom) - 1; while (num < count) { xyz item(zoom, rand() & coord_mask, rand() & coord_mask); if (set.count(item) == 0) { set.insert(item); ++num; } } return set; } void assert_tilesets_equal(const std::set<xyz> &a, const std::set<xyz> &b) { ASSERT_EQ(a.size(), b.size()); std::set<xyz>::const_iterator a_itr = a.begin(); std::set<xyz>::const_iterator b_itr = b.begin(); while ((a_itr != a.end()) && (b_itr != b.end())) { ASSERT_EQ(*a_itr, *b_itr); ++a_itr; ++b_itr; } } void expire_centroids(const std::set<xyz> &check_set, expire_tiles &et) { for (std::set<xyz>::const_iterator itr = check_set.begin(); itr != check_set.end(); ++itr) { double x0 = 0.0, y0 = 0.0; itr->to_centroid(x0, y0); et.from_bbox(x0, y0, x0, y0); } } // tests that expiring a set of tile centroids means that // those tiles get expired. void test_expire_set() { options_t opt; int zoom = 18; opt.expire_tiles_zoom = zoom; opt.expire_tiles_zoom_min = zoom; for (int i = 0; i < 100; ++i) { expire_tiles et(&opt); tile_output_set set; std::set<xyz> check_set = generate_random(zoom, 100); expire_centroids(check_set, et); et.output_and_destroy(&set); assert_tilesets_equal(set.m_tiles, check_set); } } // this tests that, after expiring a random set of tiles // in one expire_tiles object and a different set in // another, when they are merged together they are the // same as if the union of the sets of tiles had been // expired. void test_expire_merge() { options_t opt; int zoom = 18; opt.expire_tiles_zoom = zoom; opt.expire_tiles_zoom_min = zoom; for (int i = 0; i < 100; ++i) { expire_tiles et(&opt), et1(&opt), et2(&opt); tile_output_set set; std::set<xyz> check_set1 = generate_random(zoom, 100); expire_centroids(check_set1, et1); std::set<xyz> check_set2 = generate_random(zoom, 100); expire_centroids(check_set2, et2); et.merge_and_destroy(et1); et.merge_and_destroy(et2); std::set<xyz> check_set; std::set_union(check_set1.begin(), check_set1.end(), check_set2.begin(), check_set2.end(), std::inserter(check_set, check_set.end())); et.output_and_destroy(&set); assert_tilesets_equal(set.m_tiles, check_set); } } // tests that merging two identical sets results in // the same set. this guarantees that we check some // pathways of the merging which possibly could be // skipped by the random tile set in the previous // test. void test_expire_merge_same() { options_t opt; int zoom = 18; opt.expire_tiles_zoom = zoom; opt.expire_tiles_zoom_min = zoom; for (int i = 0; i < 100; ++i) { expire_tiles et(&opt), et1(&opt), et2(&opt); tile_output_set set; std::set<xyz> check_set = generate_random(zoom, 100); expire_centroids(check_set, et1); expire_centroids(check_set, et2); et.merge_and_destroy(et1); et.merge_and_destroy(et2); et.output_and_destroy(&set); assert_tilesets_equal(set.m_tiles, check_set); } } // makes sure that we're testing the case where some // tiles are in both. void test_expire_merge_overlap() { options_t opt; int zoom = 18; opt.expire_tiles_zoom = zoom; opt.expire_tiles_zoom_min = zoom; for (int i = 0; i < 100; ++i) { expire_tiles et(&opt), et1(&opt), et2(&opt); tile_output_set set; std::set<xyz> check_set1 = generate_random(zoom, 100); expire_centroids(check_set1, et1); std::set<xyz> check_set2 = generate_random(zoom, 100); expire_centroids(check_set2, et2); std::set<xyz> check_set3 = generate_random(zoom, 100); expire_centroids(check_set3, et1); expire_centroids(check_set3, et2); et.merge_and_destroy(et1); et.merge_and_destroy(et2); std::set<xyz> check_set; std::set_union(check_set1.begin(), check_set1.end(), check_set2.begin(), check_set2.end(), std::inserter(check_set, check_set.end())); std::set_union(check_set1.begin(), check_set1.end(), check_set3.begin(), check_set3.end(), std::inserter(check_set, check_set.end())); et.output_and_destroy(&set); assert_tilesets_equal(set.m_tiles, check_set); } } // checks that the set union still works when we expire // large contiguous areas of tiles (i.e: ensure that we // handle the "complete" flag correctly). void test_expire_merge_complete() { options_t opt; int zoom = 18; opt.expire_tiles_zoom = zoom; opt.expire_tiles_zoom_min = zoom; for (int i = 0; i < 100; ++i) { expire_tiles et(&opt), et1(&opt), et2(&opt), et0(&opt); tile_output_set set, set0; // et1&2 are two halves of et0's box et0.from_bbox(-10000, -10000, 10000, 10000); et1.from_bbox(-10000, -10000, 0, 10000); et2.from_bbox( 0, -10000, 10000, 10000); et.merge_and_destroy(et1); et.merge_and_destroy(et2); et.output_and_destroy(&set); et0.output_and_destroy(&set0); assert_tilesets_equal(set.m_tiles, set0.m_tiles); } } } // anonymous namespace int main(int argc, char *argv[]) { srand(0); //try each test if any fail we will exit RUN_TEST(test_expire_simple_z1); RUN_TEST(test_expire_simple_z3); RUN_TEST(test_expire_simple_z18); RUN_TEST(test_expire_set); RUN_TEST(test_expire_merge); RUN_TEST(test_expire_merge_same); RUN_TEST(test_expire_merge_overlap); RUN_TEST(test_expire_merge_complete); //passed return 0; }
MaxSem/osm2pgsql
tests/test-expire-tiles.cpp
C++
gpl-2.0
10,053
#if defined HAVE_FMA4_SUPPORT || defined HAVE_AVX_SUPPORT # include <init-arch.h> # include <math.h> # include <math_private.h> extern double __ieee754_atan2_sse2 (double, double); extern double __ieee754_atan2_avx (double, double); # ifdef HAVE_FMA4_SUPPORT extern double __ieee754_atan2_fma4 (double, double); # else # undef HAS_FMA4 # define HAS_FMA4 0 # define __ieee754_atan2_fma4 ((void *) 0) # endif libm_ifunc (__ieee754_atan2, HAS_FMA4 ? __ieee754_atan2_fma4 : (HAS_AVX ? __ieee754_atan2_avx : __ieee754_atan2_sse2)); strong_alias (__ieee754_atan2, __atan2_finite) # define __ieee754_atan2 __ieee754_atan2_sse2 #endif #include <sysdeps/ieee754/dbl-64/e_atan2.c>
tripleee/glibc-en-150
sysdeps/x86_64/fpu/multiarch/e_atan2.c
C
gpl-2.0
689
#!/bin/bash # # Test the init code # source "$REG_DIR/scaffold" function opts { cat << DONE -a -n DONE } cmd setup_git_repo opts | while read opt ; do cmd reset_git_repo cmd guilt init $opt cmd list_files shouldfail guilt init $opt cmd list_files done cmd git branch other cmd git checkout other cmd guilt init cmd list_files shouldfail guilt init cmd list_files
jmesmon/guilt
regression/t-010.sh
Shell
gpl-2.0
378
<?php /** * Customizer settings for this theme. * * @package WordPress * @subpackage Twenty_Twenty * @since Twenty Twenty 1.0 */ if ( ! class_exists( 'TwentyTwenty_Customize' ) ) { /** * CUSTOMIZER SETTINGS * * @since Twenty Twenty 1.0 */ class TwentyTwenty_Customize { /** * Register customizer options. * * @since Twenty Twenty 1.0 * * @param WP_Customize_Manager $wp_customize Theme Customizer object. */ public static function register( $wp_customize ) { /** * Site Title & Description. * */ $wp_customize->get_setting( 'blogname' )->transport = 'postMessage'; $wp_customize->get_setting( 'blogdescription' )->transport = 'postMessage'; $wp_customize->selective_refresh->add_partial( 'blogname', array( 'selector' => '.site-title a', 'render_callback' => 'twentytwenty_customize_partial_blogname', ) ); $wp_customize->selective_refresh->add_partial( 'blogdescription', array( 'selector' => '.site-description', 'render_callback' => 'twentytwenty_customize_partial_blogdescription', ) ); $wp_customize->selective_refresh->add_partial( 'custom_logo', array( 'selector' => '.header-titles [class*=site-]:not(.site-description)', 'render_callback' => 'twentytwenty_customize_partial_site_logo', ) ); $wp_customize->selective_refresh->add_partial( 'retina_logo', array( 'selector' => '.header-titles [class*=site-]:not(.site-description)', 'render_callback' => 'twentytwenty_customize_partial_site_logo', ) ); /** * Site Identity */ /* 2X Header Logo ---------------- */ $wp_customize->add_setting( 'retina_logo', array( 'capability' => 'edit_theme_options', 'sanitize_callback' => array( __CLASS__, 'sanitize_checkbox' ), 'transport' => 'postMessage', ) ); $wp_customize->add_control( 'retina_logo', array( 'type' => 'checkbox', 'section' => 'title_tagline', 'priority' => 10, 'label' => __( 'Retina logo', 'twentytwenty' ), 'description' => __( 'Scales the logo to half its uploaded size, making it sharp on high-res screens.', 'twentytwenty' ), ) ); // Header & Footer Background Color. $wp_customize->add_setting( 'header_footer_background_color', array( 'default' => '#ffffff', 'sanitize_callback' => 'sanitize_hex_color', 'transport' => 'postMessage', ) ); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'header_footer_background_color', array( 'label' => __( 'Header &amp; Footer Background Color', 'twentytwenty' ), 'section' => 'colors', ) ) ); // Enable picking an accent color. $wp_customize->add_setting( 'accent_hue_active', array( 'capability' => 'edit_theme_options', 'sanitize_callback' => array( __CLASS__, 'sanitize_select' ), 'transport' => 'postMessage', 'default' => 'default', ) ); $wp_customize->add_control( 'accent_hue_active', array( 'type' => 'radio', 'section' => 'colors', 'label' => __( 'Primary Color', 'twentytwenty' ), 'choices' => array( 'default' => _x( 'Default', 'color', 'twentytwenty' ), 'custom' => _x( 'Custom', 'color', 'twentytwenty' ), ), ) ); /** * Implementation for the accent color. * This is different to all other color options because of the accessibility enhancements. * The control is a hue-only colorpicker, and there is a separate setting that holds values * for other colors calculated based on the selected hue and various background-colors on the page. * * @since Twenty Twenty 1.0 */ // Add the setting for the hue colorpicker. $wp_customize->add_setting( 'accent_hue', array( 'default' => 344, 'type' => 'theme_mod', 'sanitize_callback' => 'absint', 'transport' => 'postMessage', ) ); // Add setting to hold colors derived from the accent hue. $wp_customize->add_setting( 'accent_accessible_colors', array( 'default' => array( 'content' => array( 'text' => '#000000', 'accent' => '#cd2653', 'secondary' => '#6d6d6d', 'borders' => '#dcd7ca', ), 'header-footer' => array( 'text' => '#000000', 'accent' => '#cd2653', 'secondary' => '#6d6d6d', 'borders' => '#dcd7ca', ), ), 'type' => 'theme_mod', 'transport' => 'postMessage', 'sanitize_callback' => array( __CLASS__, 'sanitize_accent_accessible_colors' ), ) ); // Add the hue-only colorpicker for the accent color. $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'accent_hue', array( 'section' => 'colors', 'settings' => 'accent_hue', 'description' => __( 'Apply a custom color for links, buttons, featured images.', 'twentytwenty' ), 'mode' => 'hue', 'active_callback' => function() use ( $wp_customize ) { return ( 'custom' === $wp_customize->get_setting( 'accent_hue_active' )->value() ); }, ) ) ); // Update background color with postMessage, so inline CSS output is updated as well. $wp_customize->get_setting( 'background_color' )->transport = 'postMessage'; /** * Theme Options */ $wp_customize->add_section( 'options', array( 'title' => __( 'Theme Options', 'twentytwenty' ), 'priority' => 40, 'capability' => 'edit_theme_options', ) ); /* Enable Header Search ----------------------------------------------- */ $wp_customize->add_setting( 'enable_header_search', array( 'capability' => 'edit_theme_options', 'default' => true, 'sanitize_callback' => array( __CLASS__, 'sanitize_checkbox' ), ) ); $wp_customize->add_control( 'enable_header_search', array( 'type' => 'checkbox', 'section' => 'options', 'priority' => 10, 'label' => __( 'Show search in header', 'twentytwenty' ), ) ); /* Show author bio ---------------------------------------------------- */ $wp_customize->add_setting( 'show_author_bio', array( 'capability' => 'edit_theme_options', 'default' => true, 'sanitize_callback' => array( __CLASS__, 'sanitize_checkbox' ), ) ); $wp_customize->add_control( 'show_author_bio', array( 'type' => 'checkbox', 'section' => 'options', 'priority' => 10, 'label' => __( 'Show author bio', 'twentytwenty' ), ) ); /* Display full content or excerpts on the blog and archives --------- */ $wp_customize->add_setting( 'blog_content', array( 'capability' => 'edit_theme_options', 'default' => 'full', 'sanitize_callback' => array( __CLASS__, 'sanitize_select' ), ) ); $wp_customize->add_control( 'blog_content', array( 'type' => 'radio', 'section' => 'options', 'priority' => 10, 'label' => __( 'On archive pages, posts show:', 'twentytwenty' ), 'choices' => array( 'full' => __( 'Full text', 'twentytwenty' ), 'summary' => __( 'Summary', 'twentytwenty' ), ), ) ); /** * Template: Cover Template. */ $wp_customize->add_section( 'cover_template_options', array( 'title' => __( 'Cover Template', 'twentytwenty' ), 'capability' => 'edit_theme_options', 'description' => __( 'Settings for the "Cover Template" page template. Add a featured image to use as background.', 'twentytwenty' ), 'priority' => 42, ) ); /* Overlay Fixed Background ------ */ $wp_customize->add_setting( 'cover_template_fixed_background', array( 'capability' => 'edit_theme_options', 'default' => true, 'sanitize_callback' => array( __CLASS__, 'sanitize_checkbox' ), 'transport' => 'postMessage', ) ); $wp_customize->add_control( 'cover_template_fixed_background', array( 'type' => 'checkbox', 'section' => 'cover_template_options', 'label' => __( 'Fixed Background Image', 'twentytwenty' ), 'description' => __( 'Creates a parallax effect when the visitor scrolls.', 'twentytwenty' ), ) ); $wp_customize->selective_refresh->add_partial( 'cover_template_fixed_background', array( 'selector' => '.cover-header', 'type' => 'cover_fixed', ) ); /* Separator --------------------- */ $wp_customize->add_setting( 'cover_template_separator_1', array( 'sanitize_callback' => 'wp_filter_nohtml_kses', ) ); $wp_customize->add_control( new TwentyTwenty_Separator_Control( $wp_customize, 'cover_template_separator_1', array( 'section' => 'cover_template_options', ) ) ); /* Overlay Background Color ------ */ $wp_customize->add_setting( 'cover_template_overlay_background_color', array( 'default' => twentytwenty_get_color_for_area( 'content', 'accent' ), 'sanitize_callback' => 'sanitize_hex_color', ) ); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'cover_template_overlay_background_color', array( 'label' => __( 'Overlay Background Color', 'twentytwenty' ), 'description' => __( 'The color used for the overlay. Defaults to the accent color.', 'twentytwenty' ), 'section' => 'cover_template_options', ) ) ); /* Overlay Text Color ------------ */ $wp_customize->add_setting( 'cover_template_overlay_text_color', array( 'default' => '#ffffff', 'sanitize_callback' => 'sanitize_hex_color', ) ); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'cover_template_overlay_text_color', array( 'label' => __( 'Overlay Text Color', 'twentytwenty' ), 'description' => __( 'The color used for the text in the overlay.', 'twentytwenty' ), 'section' => 'cover_template_options', ) ) ); /* Overlay Color Opacity --------- */ $wp_customize->add_setting( 'cover_template_overlay_opacity', array( 'default' => 80, 'sanitize_callback' => 'absint', 'transport' => 'postMessage', ) ); $wp_customize->add_control( 'cover_template_overlay_opacity', array( 'label' => __( 'Overlay Opacity', 'twentytwenty' ), 'description' => __( 'Make sure that the contrast is high enough so that the text is readable.', 'twentytwenty' ), 'section' => 'cover_template_options', 'type' => 'range', 'input_attrs' => twentytwenty_customize_opacity_range(), ) ); $wp_customize->selective_refresh->add_partial( 'cover_template_overlay_opacity', array( 'selector' => '.cover-color-overlay', 'type' => 'cover_opacity', ) ); } /** * Sanitization callback for the "accent_accessible_colors" setting. * * @since Twenty Twenty 1.0 * * @param array $value The value we want to sanitize. * @return array Returns sanitized value. Each item in the array gets sanitized separately. */ public static function sanitize_accent_accessible_colors( $value ) { // Make sure the value is an array. Do not typecast, use empty array as fallback. $value = is_array( $value ) ? $value : array(); // Loop values. foreach ( $value as $area => $values ) { foreach ( $values as $context => $color_val ) { $value[ $area ][ $context ] = sanitize_hex_color( $color_val ); } } return $value; } /** * Sanitize select. * * @since Twenty Twenty 1.0 * * @param string $input The input from the setting. * @param object $setting The selected setting. * @return string The input from the setting or the default setting. */ public static function sanitize_select( $input, $setting ) { $input = sanitize_key( $input ); $choices = $setting->manager->get_control( $setting->id )->choices; return ( array_key_exists( $input, $choices ) ? $input : $setting->default ); } /** * Sanitize boolean for checkbox. * * @since Twenty Twenty 1.0 * * @param bool $checked Whether or not a box is checked. * @return bool */ public static function sanitize_checkbox( $checked ) { return ( ( isset( $checked ) && true === $checked ) ? true : false ); } } // Setup the Theme Customizer settings and controls. add_action( 'customize_register', array( 'TwentyTwenty_Customize', 'register' ) ); } /** * PARTIAL REFRESH FUNCTIONS * */ if ( ! function_exists( 'twentytwenty_customize_partial_blogname' ) ) { /** * Render the site title for the selective refresh partial. * * @since Twenty Twenty 1.0 */ function twentytwenty_customize_partial_blogname() { bloginfo( 'name' ); } } if ( ! function_exists( 'twentytwenty_customize_partial_blogdescription' ) ) { /** * Render the site description for the selective refresh partial. * * @since Twenty Twenty 1.0 */ function twentytwenty_customize_partial_blogdescription() { bloginfo( 'description' ); } } if ( ! function_exists( 'twentytwenty_customize_partial_site_logo' ) ) { /** * Render the site logo for the selective refresh partial. * * Doing it this way so we don't have issues with `render_callback`'s arguments. * * @since Twenty Twenty 1.0 */ function twentytwenty_customize_partial_site_logo() { twentytwenty_site_logo(); } } /** * Input attributes for cover overlay opacity option. * * @since Twenty Twenty 1.0 * * @return array Array containing attribute names and their values. */ function twentytwenty_customize_opacity_range() { /** * Filters the input attributes for opacity. * * @since Twenty Twenty 1.0 * * @param array $attrs { * The attributes. * * @type int $min Minimum value. * @type int $max Maximum value. * @type int $step Interval between numbers. * } */ return apply_filters( 'twentytwenty_customize_opacity_range', array( 'min' => 0, 'max' => 90, 'step' => 5, ) ); }
rasken2003/fuga-it-business
wp-content/themes/twentytwenty/classes/class-twentytwenty-customize.php
PHP
gpl-2.0
14,593
/****************************************************************************** * * * * Copyright (C) 1997-2014 by Dimitri van Heesch. * * Permission to use, copy, modify, and distribute this software and its * documentation under the terms of the GNU General Public License is hereby * granted. No representations are made about the suitability of this software * for any purpose. It is provided "as is" without express or implied warranty. * See the GNU General Public License for more details. * * Documents produced by Doxygen are derivative works derived from the * input used in their production; they are not affected by this license. * */ #ifndef DECLINFO_H #define DECLINFO_H #include <stdio.h> #include <qcstring.h> extern void parseFuncDecl(const QCString &decl, bool objC, QCString &clName, QCString &type, QCString &name, QCString &args, QCString &funcTempList, QCString &exceptions ); #endif
andyque/doxygen
src/declinfo.h
C
gpl-2.0
1,134
class CreateArticlePage include PageObject page_url '<%=params[:article_name]%>' a(:doesnotexist_msg, text: 'Look for pages within Wikipedia that link to this title') end
paladox/mediawiki-extensions-MobileFrontend
tests/browser/features/support/pages/create_article_page.rb
Ruby
gpl-2.0
179
/* * Bt8xx based DVB adapter driver * * Copyright (C) 2002,2003 Florian Schirmer <jolt@tuxbox.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 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., 675 Mass Ave, Cambridge, MA 02139, USA. * */ #include <linux/bitops.h> #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/init.h> #include <linux/device.h> #include <linux/delay.h> #include <linux/slab.h> #include <linux/i2c.h> #include "dmxdev.h" #include "dvbdev.h" #include "dvb_demux.h" #include "dvb_frontend.h" #include "dvb-bt8xx.h" #include "bt878.h" static int debug; module_param(debug, int, 0644); MODULE_PARM_DESC(debug, "Turn on/off debugging (default:off)."); #define dprintk( args... ) \ do { \ if (debug) printk(KERN_DEBUG args); \ } while (0) static void dvb_bt8xx_task(unsigned long data) { struct dvb_bt8xx_card *card = (struct dvb_bt8xx_card *)data; //printk("%d ", card->bt->finished_block); while (card->bt->last_block != card->bt->finished_block) { (card->bt->TS_Size ? dvb_dmx_swfilter_204 : dvb_dmx_swfilter) (&card->demux, &card->bt->buf_cpu[card->bt->last_block * card->bt->block_bytes], card->bt->block_bytes); card->bt->last_block = (card->bt->last_block + 1) % card->bt->block_count; } } static int dvb_bt8xx_start_feed(struct dvb_demux_feed *dvbdmxfeed) { struct dvb_demux *dvbdmx = dvbdmxfeed->demux; struct dvb_bt8xx_card *card = dvbdmx->priv; int rc; dprintk("dvb_bt8xx: start_feed\n"); if (!dvbdmx->dmx.frontend) return -EINVAL; down(&card->lock); card->nfeeds++; rc = card->nfeeds; if (card->nfeeds == 1) bt878_start(card->bt, card->gpio_mode, card->op_sync_orin, card->irq_err_ignore); up(&card->lock); return rc; } static int dvb_bt8xx_stop_feed(struct dvb_demux_feed *dvbdmxfeed) { struct dvb_demux *dvbdmx = dvbdmxfeed->demux; struct dvb_bt8xx_card *card = dvbdmx->priv; dprintk("dvb_bt8xx: stop_feed\n"); if (!dvbdmx->dmx.frontend) return -EINVAL; down(&card->lock); card->nfeeds--; if (card->nfeeds == 0) bt878_stop(card->bt); up(&card->lock); return 0; } static int is_pci_slot_eq(struct pci_dev* adev, struct pci_dev* bdev) { if ((adev->subsystem_vendor == bdev->subsystem_vendor) && (adev->subsystem_device == bdev->subsystem_device) && (adev->bus->number == bdev->bus->number) && (PCI_SLOT(adev->devfn) == PCI_SLOT(bdev->devfn))) return 1; return 0; } static struct bt878 __init *dvb_bt8xx_878_match(unsigned int bttv_nr, struct pci_dev* bttv_pci_dev) { unsigned int card_nr; /* Hmm, n squared. Hope n is small */ for (card_nr = 0; card_nr < bt878_num; card_nr++) { if (is_pci_slot_eq(bt878[card_nr].dev, bttv_pci_dev)) return &bt878[card_nr]; } return NULL; } static int thomson_dtt7579_demod_init(struct dvb_frontend* fe) { static u8 mt352_clock_config [] = { 0x89, 0x38, 0x38 }; static u8 mt352_reset [] = { 0x50, 0x80 }; static u8 mt352_adc_ctl_1_cfg [] = { 0x8E, 0x40 }; static u8 mt352_agc_cfg [] = { 0x67, 0x28, 0x20 }; static u8 mt352_gpp_ctl_cfg [] = { 0x8C, 0x33 }; static u8 mt352_capt_range_cfg[] = { 0x75, 0x32 }; mt352_write(fe, mt352_clock_config, sizeof(mt352_clock_config)); udelay(2000); mt352_write(fe, mt352_reset, sizeof(mt352_reset)); mt352_write(fe, mt352_adc_ctl_1_cfg, sizeof(mt352_adc_ctl_1_cfg)); mt352_write(fe, mt352_agc_cfg, sizeof(mt352_agc_cfg)); mt352_write(fe, mt352_gpp_ctl_cfg, sizeof(mt352_gpp_ctl_cfg)); mt352_write(fe, mt352_capt_range_cfg, sizeof(mt352_capt_range_cfg)); return 0; } static int thomson_dtt7579_pll_set(struct dvb_frontend* fe, struct dvb_frontend_parameters* params, u8* pllbuf) { u32 div; unsigned char bs = 0; unsigned char cp = 0; #define IF_FREQUENCYx6 217 /* 6 * 36.16666666667MHz */ div = (((params->frequency + 83333) * 3) / 500000) + IF_FREQUENCYx6; if (params->frequency < 542000000) cp = 0xb4; else if (params->frequency < 771000000) cp = 0xbc; else cp = 0xf4; if (params->frequency == 0) bs = 0x03; else if (params->frequency < 443250000) bs = 0x02; else bs = 0x08; pllbuf[0] = 0xc0; // Note: non-linux standard PLL i2c address pllbuf[1] = div >> 8; pllbuf[2] = div & 0xff; pllbuf[3] = cp; pllbuf[4] = bs; return 0; } static struct mt352_config thomson_dtt7579_config = { .demod_address = 0x0f, .demod_init = thomson_dtt7579_demod_init, .pll_set = thomson_dtt7579_pll_set, }; static int cx24108_pll_set(struct dvb_frontend* fe, struct dvb_frontend_parameters* params) { u32 freq = params->frequency; int i, a, n, pump; u32 band, pll; u32 osci[]={950000,1019000,1075000,1178000,1296000,1432000, 1576000,1718000,1856000,2036000,2150000}; u32 bandsel[]={0,0x00020000,0x00040000,0x00100800,0x00101000, 0x00102000,0x00104000,0x00108000,0x00110000, 0x00120000,0x00140000}; #define XTAL 1011100 /* Hz, really 1.0111 MHz and a /10 prescaler */ printk("cx24108 debug: entering SetTunerFreq, freq=%d\n",freq); /* This is really the bit driving the tuner chip cx24108 */ if(freq<950000) freq=950000; /* kHz */ if(freq>2150000) freq=2150000; /* satellite IF is 950..2150MHz */ /* decide which VCO to use for the input frequency */ for(i=1;(i<sizeof(osci)/sizeof(osci[0]))&&(osci[i]<freq);i++); printk("cx24108 debug: select vco #%d (f=%d)\n",i,freq); band=bandsel[i]; /* the gain values must be set by SetSymbolrate */ /* compute the pll divider needed, from Conexant data sheet, resolved for (n*32+a), remember f(vco) is f(receive) *2 or *4, depending on the divider bit. It is set to /4 on the 2 lowest bands */ n=((i<=2?2:1)*freq*10L)/(XTAL/100); a=n%32; n/=32; if(a==0) n--; pump=(freq<(osci[i-1]+osci[i])/2); pll=0xf8000000| ((pump?1:2)<<(14+11))| ((n&0x1ff)<<(5+11))| ((a&0x1f)<<11); /* everything is shifted left 11 bits to left-align the bits in the 32bit word. Output to the tuner goes MSB-aligned, after all */ printk("cx24108 debug: pump=%d, n=%d, a=%d\n",pump,n,a); cx24110_pll_write(fe,band); /* set vga and vca to their widest-band settings, as a precaution. SetSymbolrate might not be called to set this up */ cx24110_pll_write(fe,0x500c0000); cx24110_pll_write(fe,0x83f1f800); cx24110_pll_write(fe,pll); /* writereg(client,0x56,0x7f);*/ return 0; } static int pinnsat_pll_init(struct dvb_frontend* fe) { return 0; } static struct cx24110_config pctvsat_config = { .demod_address = 0x55, .pll_init = pinnsat_pll_init, .pll_set = cx24108_pll_set, }; static int microtune_mt7202dtf_pll_set(struct dvb_frontend* fe, struct dvb_frontend_parameters* params) { struct dvb_bt8xx_card *card = (struct dvb_bt8xx_card *) fe->dvb->priv; u8 cfg, cpump, band_select; u8 data[4]; u32 div; struct i2c_msg msg = { .addr = 0x60, .flags = 0, .buf = data, .len = sizeof(data) }; div = (36000000 + params->frequency + 83333) / 166666; cfg = 0x88; if (params->frequency < 175000000) cpump = 2; else if (params->frequency < 390000000) cpump = 1; else if (params->frequency < 470000000) cpump = 2; else if (params->frequency < 750000000) cpump = 2; else cpump = 3; if (params->frequency < 175000000) band_select = 0x0e; else if (params->frequency < 470000000) band_select = 0x05; else band_select = 0x03; data[0] = (div >> 8) & 0x7f; data[1] = div & 0xff; data[2] = ((div >> 10) & 0x60) | cfg; data[3] = cpump | band_select; i2c_transfer(card->i2c_adapter, &msg, 1); return (div * 166666 - 36000000); } static int microtune_mt7202dtf_request_firmware(struct dvb_frontend* fe, const struct firmware **fw, char* name) { struct dvb_bt8xx_card* bt = (struct dvb_bt8xx_card*) fe->dvb->priv; return request_firmware(fw, name, &bt->bt->dev->dev); } static struct sp887x_config microtune_mt7202dtf_config = { .demod_address = 0x70, .pll_set = microtune_mt7202dtf_pll_set, .request_firmware = microtune_mt7202dtf_request_firmware, }; static int advbt771_samsung_tdtc9251dh0_demod_init(struct dvb_frontend* fe) { static u8 mt352_clock_config [] = { 0x89, 0x38, 0x2d }; static u8 mt352_reset [] = { 0x50, 0x80 }; static u8 mt352_adc_ctl_1_cfg [] = { 0x8E, 0x40 }; static u8 mt352_agc_cfg [] = { 0x67, 0x10, 0x23, 0x00, 0xFF, 0xFF, 0x00, 0xFF, 0x00, 0x40, 0x40 }; static u8 mt352_av771_extra[] = { 0xB5, 0x7A }; static u8 mt352_capt_range_cfg[] = { 0x75, 0x32 }; mt352_write(fe, mt352_clock_config, sizeof(mt352_clock_config)); udelay(2000); mt352_write(fe, mt352_reset, sizeof(mt352_reset)); mt352_write(fe, mt352_adc_ctl_1_cfg, sizeof(mt352_adc_ctl_1_cfg)); mt352_write(fe, mt352_agc_cfg,sizeof(mt352_agc_cfg)); udelay(2000); mt352_write(fe, mt352_av771_extra,sizeof(mt352_av771_extra)); mt352_write(fe, mt352_capt_range_cfg, sizeof(mt352_capt_range_cfg)); return 0; } static int advbt771_samsung_tdtc9251dh0_pll_set(struct dvb_frontend* fe, struct dvb_frontend_parameters* params, u8* pllbuf) { u32 div; unsigned char bs = 0; unsigned char cp = 0; #define IF_FREQUENCYx6 217 /* 6 * 36.16666666667MHz */ div = (((params->frequency + 83333) * 3) / 500000) + IF_FREQUENCYx6; if (params->frequency < 150000000) cp = 0xB4; else if (params->frequency < 173000000) cp = 0xBC; else if (params->frequency < 250000000) cp = 0xB4; else if (params->frequency < 400000000) cp = 0xBC; else if (params->frequency < 420000000) cp = 0xF4; else if (params->frequency < 470000000) cp = 0xFC; else if (params->frequency < 600000000) cp = 0xBC; else if (params->frequency < 730000000) cp = 0xF4; else cp = 0xFC; if (params->frequency < 150000000) bs = 0x01; else if (params->frequency < 173000000) bs = 0x01; else if (params->frequency < 250000000) bs = 0x02; else if (params->frequency < 400000000) bs = 0x02; else if (params->frequency < 420000000) bs = 0x02; else if (params->frequency < 470000000) bs = 0x02; else if (params->frequency < 600000000) bs = 0x08; else if (params->frequency < 730000000) bs = 0x08; else bs = 0x08; pllbuf[0] = 0xc2; // Note: non-linux standard PLL i2c address pllbuf[1] = div >> 8; pllbuf[2] = div & 0xff; pllbuf[3] = cp; pllbuf[4] = bs; return 0; } static struct mt352_config advbt771_samsung_tdtc9251dh0_config = { .demod_address = 0x0f, .demod_init = advbt771_samsung_tdtc9251dh0_demod_init, .pll_set = advbt771_samsung_tdtc9251dh0_pll_set, }; static struct dst_config dst_config = { .demod_address = 0x55, }; static int or51211_request_firmware(struct dvb_frontend* fe, const struct firmware **fw, char* name) { struct dvb_bt8xx_card* bt = (struct dvb_bt8xx_card*) fe->dvb->priv; return request_firmware(fw, name, &bt->bt->dev->dev); } static void or51211_setmode(struct dvb_frontend * fe, int mode) { struct dvb_bt8xx_card *bt = fe->dvb->priv; bttv_write_gpio(bt->bttv_nr, 0x0002, mode); /* Reset */ msleep(20); } static void or51211_reset(struct dvb_frontend * fe) { struct dvb_bt8xx_card *bt = fe->dvb->priv; /* RESET DEVICE * reset is controled by GPIO-0 * when set to 0 causes reset and when to 1 for normal op * must remain reset for 128 clock cycles on a 50Mhz clock * also PRM1 PRM2 & PRM4 are controled by GPIO-1,GPIO-2 & GPIO-4 * We assume that the reset has be held low long enough or we * have been reset by a power on. When the driver is unloaded * reset set to 0 so if reloaded we have been reset. */ /* reset & PRM1,2&4 are outputs */ int ret = bttv_gpio_enable(bt->bttv_nr, 0x001F, 0x001F); if (ret != 0) { printk(KERN_WARNING "or51211: Init Error - Can't Reset DVR " "(%i)\n", ret); } bttv_write_gpio(bt->bttv_nr, 0x001F, 0x0000); /* Reset */ msleep(20); /* Now set for normal operation */ bttv_write_gpio(bt->bttv_nr, 0x0001F, 0x0001); /* wait for operation to begin */ msleep(500); } static void or51211_sleep(struct dvb_frontend * fe) { struct dvb_bt8xx_card *bt = fe->dvb->priv; bttv_write_gpio(bt->bttv_nr, 0x0001, 0x0000); } static struct or51211_config or51211_config = { .demod_address = 0x15, .request_firmware = or51211_request_firmware, .setmode = or51211_setmode, .reset = or51211_reset, .sleep = or51211_sleep, }; static int vp3021_alps_tded4_pll_set(struct dvb_frontend* fe, struct dvb_frontend_parameters* params) { struct dvb_bt8xx_card *card = (struct dvb_bt8xx_card *) fe->dvb->priv; u8 buf[4]; u32 div; struct i2c_msg msg = { .addr = 0x60, .flags = 0, .buf = buf, .len = sizeof(buf) }; div = (params->frequency + 36166667) / 166667; buf[0] = (div >> 8) & 0x7F; buf[1] = div & 0xFF; buf[2] = 0x85; if ((params->frequency >= 47000000) && (params->frequency < 153000000)) buf[3] = 0x01; else if ((params->frequency >= 153000000) && (params->frequency < 430000000)) buf[3] = 0x02; else if ((params->frequency >= 430000000) && (params->frequency < 824000000)) buf[3] = 0x0C; else if ((params->frequency >= 824000000) && (params->frequency < 863000000)) buf[3] = 0x8C; else return -EINVAL; i2c_transfer(card->i2c_adapter, &msg, 1); return 0; } static struct nxt6000_config vp3021_alps_tded4_config = { .demod_address = 0x0a, .clock_inversion = 1, .pll_set = vp3021_alps_tded4_pll_set, }; static void frontend_init(struct dvb_bt8xx_card *card, u32 type) { int ret; struct dst_state* state = NULL; switch(type) { #ifdef BTTV_DVICO_DVBT_LITE case BTTV_DVICO_DVBT_LITE: card->fe = mt352_attach(&thomson_dtt7579_config, card->i2c_adapter); if (card->fe != NULL) { card->fe->ops->info.frequency_min = 174000000; card->fe->ops->info.frequency_max = 862000000; break; } break; #endif #ifdef BTTV_TWINHAN_VP3021 case BTTV_TWINHAN_VP3021: #else case BTTV_NEBULA_DIGITV: #endif card->fe = nxt6000_attach(&vp3021_alps_tded4_config, card->i2c_adapter); if (card->fe != NULL) { break; } break; case BTTV_AVDVBT_761: card->fe = sp887x_attach(&microtune_mt7202dtf_config, card->i2c_adapter); if (card->fe != NULL) { break; } break; case BTTV_AVDVBT_771: card->fe = mt352_attach(&advbt771_samsung_tdtc9251dh0_config, card->i2c_adapter); if (card->fe != NULL) { card->fe->ops->info.frequency_min = 174000000; card->fe->ops->info.frequency_max = 862000000; break; } break; case BTTV_TWINHAN_DST: /* DST is not a frontend driver !!! */ state = (struct dst_state *) kmalloc(sizeof (struct dst_state), GFP_KERNEL); /* Setup the Card */ state->config = &dst_config; state->i2c = card->i2c_adapter; state->bt = card->bt; /* DST is not a frontend, attaching the ASIC */ if ((dst_attach(state, &card->dvb_adapter)) == NULL) { printk("%s: Could not find a Twinhan DST.\n", __FUNCTION__); break; } card->fe = &state->frontend; /* Attach other DST peripherals if any */ /* Conditional Access device */ if (state->dst_hw_cap & DST_TYPE_HAS_CA) { ret = dst_ca_attach(state, &card->dvb_adapter); } if (card->fe != NULL) { break; } break; case BTTV_PINNACLESAT: card->fe = cx24110_attach(&pctvsat_config, card->i2c_adapter); if (card->fe != NULL) { break; } break; case BTTV_PC_HDTV: card->fe = or51211_attach(&or51211_config, card->i2c_adapter); if (card->fe != NULL) { break; } break; } if (card->fe == NULL) { printk("dvb-bt8xx: A frontend driver was not found for device %04x/%04x subsystem %04x/%04x\n", card->bt->dev->vendor, card->bt->dev->device, card->bt->dev->subsystem_vendor, card->bt->dev->subsystem_device); } else { if (dvb_register_frontend(&card->dvb_adapter, card->fe)) { printk("dvb-bt8xx: Frontend registration failed!\n"); if (card->fe->ops->release) card->fe->ops->release(card->fe); card->fe = NULL; } } } static int __init dvb_bt8xx_load_card(struct dvb_bt8xx_card *card, u32 type) { int result; if ((result = dvb_register_adapter(&card->dvb_adapter, card->card_name, THIS_MODULE)) < 0) { printk("dvb_bt8xx: dvb_register_adapter failed (errno = %d)\n", result); return result; } card->dvb_adapter.priv = card; card->bt->adapter = card->i2c_adapter; memset(&card->demux, 0, sizeof(struct dvb_demux)); card->demux.dmx.capabilities = DMX_TS_FILTERING | DMX_SECTION_FILTERING | DMX_MEMORY_BASED_FILTERING; card->demux.priv = card; card->demux.filternum = 256; card->demux.feednum = 256; card->demux.start_feed = dvb_bt8xx_start_feed; card->demux.stop_feed = dvb_bt8xx_stop_feed; card->demux.write_to_decoder = NULL; if ((result = dvb_dmx_init(&card->demux)) < 0) { printk("dvb_bt8xx: dvb_dmx_init failed (errno = %d)\n", result); dvb_unregister_adapter(&card->dvb_adapter); return result; } card->dmxdev.filternum = 256; card->dmxdev.demux = &card->demux.dmx; card->dmxdev.capabilities = 0; if ((result = dvb_dmxdev_init(&card->dmxdev, &card->dvb_adapter)) < 0) { printk("dvb_bt8xx: dvb_dmxdev_init failed (errno = %d)\n", result); dvb_dmx_release(&card->demux); dvb_unregister_adapter(&card->dvb_adapter); return result; } card->fe_hw.source = DMX_FRONTEND_0; if ((result = card->demux.dmx.add_frontend(&card->demux.dmx, &card->fe_hw)) < 0) { printk("dvb_bt8xx: dvb_dmx_init failed (errno = %d)\n", result); dvb_dmxdev_release(&card->dmxdev); dvb_dmx_release(&card->demux); dvb_unregister_adapter(&card->dvb_adapter); return result; } card->fe_mem.source = DMX_MEMORY_FE; if ((result = card->demux.dmx.add_frontend(&card->demux.dmx, &card->fe_mem)) < 0) { printk("dvb_bt8xx: dvb_dmx_init failed (errno = %d)\n", result); card->demux.dmx.remove_frontend(&card->demux.dmx, &card->fe_hw); dvb_dmxdev_release(&card->dmxdev); dvb_dmx_release(&card->demux); dvb_unregister_adapter(&card->dvb_adapter); return result; } if ((result = card->demux.dmx.connect_frontend(&card->demux.dmx, &card->fe_hw)) < 0) { printk("dvb_bt8xx: dvb_dmx_init failed (errno = %d)\n", result); card->demux.dmx.remove_frontend(&card->demux.dmx, &card->fe_mem); card->demux.dmx.remove_frontend(&card->demux.dmx, &card->fe_hw); dvb_dmxdev_release(&card->dmxdev); dvb_dmx_release(&card->demux); dvb_unregister_adapter(&card->dvb_adapter); return result; } dvb_net_init(&card->dvb_adapter, &card->dvbnet, &card->demux.dmx); tasklet_init(&card->bt->tasklet, dvb_bt8xx_task, (unsigned long) card); frontend_init(card, type); return 0; } static int dvb_bt8xx_probe(struct device *dev) { struct bttv_sub_device *sub = to_bttv_sub_dev(dev); struct dvb_bt8xx_card *card; struct pci_dev* bttv_pci_dev; int ret; if (!(card = kmalloc(sizeof(struct dvb_bt8xx_card), GFP_KERNEL))) return -ENOMEM; memset(card, 0, sizeof(*card)); init_MUTEX(&card->lock); card->bttv_nr = sub->core->nr; strncpy(card->card_name, sub->core->name, sizeof(sub->core->name)); card->i2c_adapter = &sub->core->i2c_adap; switch(sub->core->type) { case BTTV_PINNACLESAT: card->gpio_mode = 0x0400c060; /* should be: BT878_A_GAIN=0,BT878_A_PWRDN,BT878_DA_DPM,BT878_DA_SBR, BT878_DA_IOM=1,BT878_DA_APP to enable serial highspeed mode. */ card->op_sync_orin = 0; card->irq_err_ignore = 0; break; #ifdef BTTV_DVICO_DVBT_LITE case BTTV_DVICO_DVBT_LITE: #endif card->gpio_mode = 0x0400C060; card->op_sync_orin = 0; card->irq_err_ignore = 0; /* 26, 15, 14, 6, 5 * A_PWRDN DA_DPM DA_SBR DA_IOM_DA * DA_APP(parallel) */ break; #ifdef BTTV_TWINHAN_VP3021 case BTTV_TWINHAN_VP3021: #else case BTTV_NEBULA_DIGITV: #endif case BTTV_AVDVBT_761: card->gpio_mode = (1 << 26) | (1 << 14) | (1 << 5); card->op_sync_orin = 0; card->irq_err_ignore = 0; /* A_PWRDN DA_SBR DA_APP (high speed serial) */ break; case BTTV_AVDVBT_771: //case 0x07711461: card->gpio_mode = 0x0400402B; card->op_sync_orin = BT878_RISC_SYNC_MASK; card->irq_err_ignore = 0; /* A_PWRDN DA_SBR DA_APP[0] PKTP=10 RISC_ENABLE FIFO_ENABLE*/ break; case BTTV_TWINHAN_DST: card->gpio_mode = 0x2204f2c; card->op_sync_orin = BT878_RISC_SYNC_MASK; card->irq_err_ignore = BT878_APABORT | BT878_ARIPERR | BT878_APPERR | BT878_AFBUS; /* 25,21,14,11,10,9,8,3,2 then * 0x33 = 5,4,1,0 * A_SEL=SML, DA_MLB, DA_SBR, * DA_SDR=f, fifo trigger = 32 DWORDS * IOM = 0 == audio A/D * DPM = 0 == digital audio mode * == async data parallel port * then 0x33 (13 is set by start_capture) * DA_APP = async data parallel port, * ACAP_EN = 1, * RISC+FIFO ENABLE */ break; case BTTV_PC_HDTV: card->gpio_mode = 0x0100EC7B; card->op_sync_orin = 0; card->irq_err_ignore = 0; break; default: printk(KERN_WARNING "dvb_bt8xx: Unknown bttv card type: %d.\n", sub->core->type); kfree(card); return -ENODEV; } dprintk("dvb_bt8xx: identified card%d as %s\n", card->bttv_nr, card->card_name); if (!(bttv_pci_dev = bttv_get_pcidev(card->bttv_nr))) { printk("dvb_bt8xx: no pci device for card %d\n", card->bttv_nr); kfree(card); return -EFAULT; } if (!(card->bt = dvb_bt8xx_878_match(card->bttv_nr, bttv_pci_dev))) { printk("dvb_bt8xx: unable to determine DMA core of card %d,\n", card->bttv_nr); printk("dvb_bt8xx: if you have the ALSA bt87x audio driver " "installed, try removing it.\n"); kfree(card); return -EFAULT; } init_MUTEX(&card->bt->gpio_lock); card->bt->bttv_nr = sub->core->nr; if ( (ret = dvb_bt8xx_load_card(card, sub->core->type)) ) { kfree(card); return ret; } dev_set_drvdata(dev, card); return 0; } static int dvb_bt8xx_remove(struct device *dev) { struct dvb_bt8xx_card *card = dev_get_drvdata(dev); dprintk("dvb_bt8xx: unloading card%d\n", card->bttv_nr); bt878_stop(card->bt); tasklet_kill(&card->bt->tasklet); dvb_net_release(&card->dvbnet); card->demux.dmx.remove_frontend(&card->demux.dmx, &card->fe_mem); card->demux.dmx.remove_frontend(&card->demux.dmx, &card->fe_hw); dvb_dmxdev_release(&card->dmxdev); dvb_dmx_release(&card->demux); if (card->fe) dvb_unregister_frontend(card->fe); dvb_unregister_adapter(&card->dvb_adapter); kfree(card); return 0; } static struct bttv_sub_driver driver = { .drv = { .name = "dvb-bt8xx", .probe = dvb_bt8xx_probe, .remove = dvb_bt8xx_remove, /* FIXME: * .shutdown = dvb_bt8xx_shutdown, * .suspend = dvb_bt8xx_suspend, * .resume = dvb_bt8xx_resume, */ }, }; static int __init dvb_bt8xx_init(void) { return bttv_sub_register(&driver, "dvb"); } static void __exit dvb_bt8xx_exit(void) { bttv_sub_unregister(&driver); } module_init(dvb_bt8xx_init); module_exit(dvb_bt8xx_exit); MODULE_DESCRIPTION("Bt8xx based DVB adapter driver"); MODULE_AUTHOR("Florian Schirmer <jolt@tuxbox.org>"); MODULE_LICENSE("GPL");
kzlin129/tt-gpl
go9/linux-s3c24xx/drivers/media/dvb/bt8xx/dvb-bt8xx.c
C
gpl-2.0
23,010
/** @internal ** @file vl_siftdescriptor_python.cpp ** @author Andrea Vedaldi ** @author Mikael Rousson (Python wrapping) ** @brief SIFT descriptor - MEX **/ #include "../py_vlfeat.h" extern "C" { #include <vl/mathop.h> #include <vl/sift.h> } #include <math.h> #include <assert.h> #include <iostream> /* option codes */ enum { opt_magnif, opt_verbose }; /** ------------------------------------------------------------------ ** @internal ** @brief Transpose descriptor ** ** @param dst destination buffer. ** @param src source buffer. ** ** The function writes to @a dst the transpose of the SIFT descriptor ** @a src. The transpose is defined as the descriptor that one ** obtains from computing the normal descriptor on the transposed ** image. **/ VL_INLINE void transpose_descriptor(vl_sift_pix* dst, vl_sift_pix* src) { int const BO = 8; /* number of orientation bins */ int const BP = 4; /* number of spatial bins */ int i, j, t; for (j = 0; j < BP; ++j) { int jp = BP - 1 - j; for (i = 0; i < BP; ++i) { int o = BO * i + BP * BO * j; int op = BO * i + BP * BO * jp; dst[op] = src[o]; for (t = 1; t < BO; ++t) dst[BO - t + op] = src[t + o]; } } } /** ------------------------------------------------------------------ ** @brief MEX entry point **/ PyObject * vl_siftdescriptor_python( PyArrayObject & in_grad, PyArrayObject & in_frames) { // TODO: check types and dim // "GRAD must be a 2xMxN matrix of class SINGLE." assert(in_grad.descr->type_num == PyArray_FLOAT); assert(in_frames.descr->type_num == PyArray_FLOAT64); assert(in_grad.flags & NPY_FORTRAN); assert(in_frames.flags & NPY_FORTRAN); int verbose = 0; int opt; // TODO: check if we need to do a copy of the grad array float * grad_array; vl_sift_pix *grad; int M, N; double magnif = -1; double *ikeys = 0; int nikeys = 0; int i, j; /* ----------------------------------------------------------------- * Check the arguments * -------------------------------------------------------------- */ // get frames nb and data pointer nikeys = in_frames.dimensions[1]; ikeys = (double *) in_frames.data; // TODO: deal with optional params // while ((opt = uNextOption(in, nin, options, &next, &optarg)) >= 0) { // switch (opt) { // // case opt_verbose : // ++ verbose ; // break ; // // case opt_magnif : // if (!uIsRealScalar(optarg) || (magnif = *mxGetPr(optarg)) < 0) { // mexErrMsgTxt("MAGNIF must be a non-negative scalar.") ; // } // break ; // // default : // assert(0) ; // break ; // } // } // TODO: convert to Python //grad_array = mxDuplicateArray(in[IN_GRAD]); (copy?) grad = (float*) in_grad.data; //mxGetData(grad_array); M = in_grad.dimensions[1]; N = in_grad.dimensions[2]; /* transpose angles */ for (i = 1; i < 2 * M * N; i += 2) { grad[i] = VL_PI / 2 - grad[i]; } /* ----------------------------------------------------------------- * Do job * -------------------------------------------------------------- */ PyArrayObject * _descr; { VlSiftFilt *filt = 0; vl_uint8 *descr = 0; /* create a filter to process the image */ filt = vl_sift_new(M, N, -1, -1, 0); if (magnif >= 0) vl_sift_set_magnif(filt, magnif); if (verbose) { printf("siftdescriptor: filter settings:\n"); printf( "siftdescriptor: magnif = %g\n", vl_sift_get_magnif(filt)); printf("siftdescriptor: num of frames = %d\n", nikeys); } { npy_intp dims[2]; dims[0] = 128; dims[1] = nikeys; _descr = (PyArrayObject*) PyArray_NewFromDescr( &PyArray_Type, PyArray_DescrFromType(PyArray_UBYTE), 2, dims, NULL, NULL, NPY_F_CONTIGUOUS, NULL); descr = (vl_uint8*) _descr->data; } /* ............................................................... * Process each octave * ............................................................ */ for (i = 0; i < nikeys; ++i) { vl_sift_pix buf[128], rbuf[128]; double y = *ikeys++; double x = *ikeys++; double s = *ikeys++; double th = VL_PI / 2 - *ikeys++; vl_sift_calc_raw_descriptor(filt, grad, buf, M, N, x, y, s, th); transpose_descriptor(rbuf, buf); for (j = 0; j < 128; ++j) { double x = 512.0 * rbuf[j]; x = (x < 255.0) ? x : 255.0; *descr++ = (vl_uint8) (x); } } /* cleanup */ // mxDestroyArray(grad_array); vl_sift_delete(filt); } /* job done */ return PyArray_Return(_descr); }
DerThorsten/pyvlfeat
vlfeat/sift/vl_siftdescriptor.cpp
C++
gpl-2.0
4,699
/*! * jQuery Form Plugin * version: 3.33.0-2013.05.02 * @requires jQuery v1.5 or later * Copyright (c) 2013 M. Alsup * Examples and documentation at: http://malsup.com/jquery/form/ * Project repository: https://github.com/malsup/form * Dual licensed under the MIT and GPL licenses. * https://github.com/malsup/form#copyright-and-license */ /*global ActiveXObject */ ;(function($) { "use strict"; /* Usage Note: ----------- Do not use both ajaxSubmit and ajaxForm on the same form. These functions are mutually exclusive. Use ajaxSubmit if you want to bind your own submit handler to the form. For example, $(document).ready(function() { $('#myForm').on('submit', function(e) { e.preventDefault(); // <-- important $(this).ajaxSubmit({ target: '#output' }); }); }); Use ajaxForm when you want the plugin to manage all the event binding for you. For example, $(document).ready(function() { $('#myForm').ajaxForm({ target: '#output' }); }); You can also use ajaxForm with delegation (requires jQuery v1.7+), so the form does not have to exist when you invoke ajaxForm: $('#myForm').ajaxForm({ delegation: true, target: '#output' }); When using ajaxForm, the ajaxSubmit function will be invoked for you at the appropriate time. */ /** * Feature detection */ var feature = {}; feature.fileapi = $("<input type='file'/>").get(0).files !== undefined; feature.formdata = window.FormData !== undefined; var hasProp = !!$.fn.prop; // attr2 uses prop when it can but checks the return type for // an expected string. this accounts for the case where a form // contains inputs with names like "action" or "method"; in those // cases "prop" returns the element $.fn.attr2 = function() { if ( ! hasProp ) return this.attr.apply(this, arguments); var val = this.prop.apply(this, arguments); if ( ( val && val.jquery ) || typeof val === 'string' ) return val; return this.attr.apply(this, arguments); }; /** * ajaxSubmit() provides a mechanism for immediately submitting * an HTML form using AJAX. */ $.fn.ajaxSubmit = function(options) { /*jshint scripturl:true */ // fast fail if nothing selected (http://dev.jquery.com/ticket/2752) if (!this.length) { log('ajaxSubmit: skipping submit process - no element selected'); return this; } var method, action, url, $form = this; if (typeof options == 'function') { options = { success: options }; } method = this.attr2('method'); action = this.attr2('action'); url = (typeof action === 'string') ? $.trim(action) : ''; url = url || window.location.href || ''; if (url) { // clean url (don't include hash vaue) url = (url.match(/^([^#]+)/)||[])[1]; } options = $.extend(true, { url: url, success: $.ajaxSettings.success, type: method || 'GET', iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank' }, options); // hook for manipulating the form data before it is extracted; // convenient for use with rich editors like tinyMCE or FCKEditor var veto = {}; this.trigger('form-pre-serialize', [this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-pre-serialize trigger'); return this; } // provide opportunity to alter form data before it is serialized if (options.beforeSerialize && options.beforeSerialize(this, options) === false) { log('ajaxSubmit: submit aborted via beforeSerialize callback'); return this; } var traditional = options.traditional; if ( traditional === undefined ) { traditional = $.ajaxSettings.traditional; } var elements = []; var qx, a = this.formToArray(options.semantic, elements); if (options.data) { options.extraData = options.data; qx = $.param(options.data, traditional); } // give pre-submit callback an opportunity to abort the submit if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) { log('ajaxSubmit: submit aborted via beforeSubmit callback'); return this; } // fire vetoable 'validate' event this.trigger('form-submit-validate', [a, this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-submit-validate trigger'); return this; } var q = $.param(a, traditional); if (qx) { q = ( q ? (q + '&' + qx) : qx ); } if (options.type.toUpperCase() == 'GET') { options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q; options.data = null; // data is null for 'get' } else { options.data = q; // data is the query string for 'post' } var callbacks = []; if (options.resetForm) { callbacks.push(function() { $form.resetForm(); }); } if (options.clearForm) { callbacks.push(function() { $form.clearForm(options.includeHidden); }); } // perform a load on the target only if dataType is not provided if (!options.dataType && options.target) { var oldSuccess = options.success || function(){}; callbacks.push(function(data) { var fn = options.replaceTarget ? 'replaceWith' : 'html'; $(options.target)[fn](data).each(oldSuccess, arguments); }); } else if (options.success) { callbacks.push(options.success); } options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg var context = options.context || this ; // jQuery 1.4+ supports scope context for (var i=0, max=callbacks.length; i < max; i++) { callbacks[i].apply(context, [data, status, xhr || $form, $form]); } }; if (options.error) { var oldError = options.error; options.error = function(xhr, status, error) { var context = options.context || this; oldError.apply(context, [xhr, status, error, $form]); }; } if (options.complete) { var oldComplete = options.complete; options.complete = function(xhr, status) { var context = options.context || this; oldComplete.apply(context, [xhr, status, $form]); }; } // are there files to upload? // [value] (issue #113), also see comment: // https://github.com/malsup/form/commit/588306aedba1de01388032d5f42a60159eea9228#commitcomment-2180219 var fileInputs = $('input[type=file]:enabled[value!=""]', this); var hasFileInputs = fileInputs.length > 0; var mp = 'multipart/form-data'; var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp); var fileAPI = feature.fileapi && feature.formdata; log("fileAPI :" + fileAPI); var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI; var jqxhr; // options.iframe allows user to force iframe mode // 06-NOV-09: now defaulting to iframe mode if file input is detected if (options.iframe !== false && (options.iframe || shouldUseFrame)) { // hack to fix Safari hang (thanks to Tim Molendijk for this) // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d if (options.closeKeepAlive) { $.get(options.closeKeepAlive, function() { jqxhr = fileUploadIframe(a); }); } else { jqxhr = fileUploadIframe(a); } } else if ((hasFileInputs || multipart) && fileAPI) { jqxhr = fileUploadXhr(a); } else { jqxhr = $.ajax(options); } $form.removeData('jqxhr').data('jqxhr', jqxhr); // clear element array for (var k=0; k < elements.length; k++) elements[k] = null; // fire 'notify' event this.trigger('form-submit-notify', [this, options]); return this; // utility fn for deep serialization function deepSerialize(extraData){ var serialized = $.param(extraData).split('&'); var len = serialized.length; var result = []; var i, part; for (i=0; i < len; i++) { // #252; undo param space replacement serialized[i] = serialized[i].replace(/\+/g,' '); part = serialized[i].split('='); // #278; use array instead of object storage, favoring array serializations result.push([decodeURIComponent(part[0]), decodeURIComponent(part[1])]); } return result; } // XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz) function fileUploadXhr(a) { var formdata = new FormData(); for (var i=0; i < a.length; i++) { formdata.append(a[i].name, a[i].value); } if (options.extraData) { var serializedData = deepSerialize(options.extraData); for (i=0; i < serializedData.length; i++) if (serializedData[i]) formdata.append(serializedData[i][0], serializedData[i][1]); } options.data = null; var s = $.extend(true, {}, $.ajaxSettings, options, { contentType: false, processData: false, cache: false, type: method || 'POST' }); if (options.uploadProgress) { // workaround because jqXHR does not expose upload property s.xhr = function() { var xhr = jQuery.ajaxSettings.xhr(); if (xhr.upload) { xhr.upload.addEventListener('progress', function(event) { var percent = 0; var position = event.loaded || event.position; /*event.position is deprecated*/ var total = event.total; if (event.lengthComputable) { percent = Math.ceil(position / total * 100); } options.uploadProgress(event, position, total, percent); }, false); } return xhr; }; } s.data = null; var beforeSend = s.beforeSend; s.beforeSend = function(xhr, o) { o.data = formdata; if(beforeSend) beforeSend.call(this, xhr, o); }; return $.ajax(s); } // private function for handling file uploads (hat tip to YAHOO!) function fileUploadIframe(a) { var form = $form[0], el, i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle; var deferred = $.Deferred(); if (a) { // ensure that every serialized input is still enabled for (i=0; i < elements.length; i++) { el = $(elements[i]); if ( hasProp ) el.prop('disabled', false); else el.removeAttr('disabled'); } } s = $.extend(true, {}, $.ajaxSettings, options); s.context = s.context || s; id = 'jqFormIO' + (new Date().getTime()); if (s.iframeTarget) { $io = $(s.iframeTarget); n = $io.attr2('name'); if (!n) $io.attr2('name', id); else id = n; } else { $io = $('<iframe name="' + id + '" src="'+ s.iframeSrc +'" />'); $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' }); } io = $io[0]; xhr = { // mock object aborted: 0, responseText: null, responseXML: null, status: 0, statusText: 'n/a', getAllResponseHeaders: function() {}, getResponseHeader: function() {}, setRequestHeader: function() {}, abort: function(status) { var e = (status === 'timeout' ? 'timeout' : 'aborted'); log('aborting upload... ' + e); this.aborted = 1; try { // #214, #257 if (io.contentWindow.document.execCommand) { io.contentWindow.document.execCommand('Stop'); } } catch(ignore) {} $io.attr('src', s.iframeSrc); // abort op in progress xhr.error = e; if (s.error) s.error.call(s.context, xhr, e, status); if (g) $.event.trigger("ajaxError", [xhr, s, e]); if (s.complete) s.complete.call(s.context, xhr, e); } }; g = s.global; // trigger ajax global events so that activity/block indicators work like normal if (g && 0 === $.active++) { $.event.trigger("ajaxStart"); } if (g) { $.event.trigger("ajaxSend", [xhr, s]); } if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) { if (s.global) { $.active--; } deferred.reject(); return deferred; } if (xhr.aborted) { deferred.reject(); return deferred; } // add submitting element to data if we know it sub = form.clk; if (sub) { n = sub.name; if (n && !sub.disabled) { s.extraData = s.extraData || {}; s.extraData[n] = sub.value; if (sub.type == "image") { s.extraData[n+'.x'] = form.clk_x; s.extraData[n+'.y'] = form.clk_y; } } } var CLIENT_TIMEOUT_ABORT = 1; var SERVER_ABORT = 2; function getDoc(frame) { /* it looks like contentWindow or contentDocument do not * carry the protocol property in ie8, when running under ssl * frame.document is the only valid response document, since * the protocol is know but not on the other two objects. strange? * "Same origin policy" http://en.wikipedia.org/wiki/Same_origin_policy */ var doc = null; // IE8 cascading access check try { if (frame.contentWindow) { doc = frame.contentWindow.document; } } catch(err) { // IE8 access denied under ssl & missing protocol log('cannot get iframe.contentWindow document: ' + err); } if (doc) { // successful getting content return doc; } try { // simply checking may throw in ie8 under ssl or mismatched protocol doc = frame.contentDocument ? frame.contentDocument : frame.document; } catch(err) { // last attempt log('cannot get iframe.contentDocument: ' + err); doc = frame.document; } return doc; } // Rails CSRF hack (thanks to Yvan Barthelemy) var csrf_token = $('meta[name=csrf-token]').attr('content'); var csrf_param = $('meta[name=csrf-param]').attr('content'); if (csrf_param && csrf_token) { s.extraData = s.extraData || {}; s.extraData[csrf_param] = csrf_token; } // take a breath so that pending repaints get some cpu time before the upload starts function doSubmit() { // make sure form attrs are set var t = $form.attr2('target'), a = $form.attr2('action'); // update form attrs in IE friendly way form.setAttribute('target',id); if (!method) { form.setAttribute('method', 'POST'); } if (a != s.url) { form.setAttribute('action', s.url); } // ie borks in some cases when setting encoding if (! s.skipEncodingOverride && (!method || /post/i.test(method))) { $form.attr({ encoding: 'multipart/form-data', enctype: 'multipart/form-data' }); } // support timout if (s.timeout) { timeoutHandle = setTimeout(function() { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout); } // look for server aborts function checkState() { try { var state = getDoc(io).readyState; log('state = ' + state); if (state && state.toLowerCase() == 'uninitialized') setTimeout(checkState,50); } catch(e) { log('Server abort: ' , e, ' (', e.name, ')'); cb(SERVER_ABORT); if (timeoutHandle) clearTimeout(timeoutHandle); timeoutHandle = undefined; } } // add "extra" data to form if provided in options var extraInputs = []; try { if (s.extraData) { for (var n in s.extraData) { if (s.extraData.hasOwnProperty(n)) { // if using the $.param format that allows for multiple values with the same name if($.isPlainObject(s.extraData[n]) && s.extraData[n].hasOwnProperty('name') && s.extraData[n].hasOwnProperty('value')) { extraInputs.push( $('<input type="hidden" name="'+s.extraData[n].name+'">').val(s.extraData[n].value) .appendTo(form)[0]); } else { extraInputs.push( $('<input type="hidden" name="'+n+'">').val(s.extraData[n]) .appendTo(form)[0]); } } } } if (!s.iframeTarget) { // add iframe to doc and submit the form $io.appendTo('body'); if (io.attachEvent) io.attachEvent('onload', cb); else io.addEventListener('load', cb, false); } setTimeout(checkState,15); try { form.submit(); } catch(err) { // just in case form has element with name/id of 'submit' var submitFn = document.createElement('form').submit; submitFn.apply(form); } } finally { // reset attrs and remove "extra" input elements form.setAttribute('action',a); if(t) { form.setAttribute('target', t); } else { $form.removeAttr('target'); } $(extraInputs).remove(); } } if (s.forceSync) { doSubmit(); } else { setTimeout(doSubmit, 10); // this lets dom updates render } var data, doc, domCheckCount = 50, callbackProcessed; function cb(e) { if (xhr.aborted || callbackProcessed) { return; } doc = getDoc(io); if(!doc) { log('cannot access response document'); e = SERVER_ABORT; } if (e === CLIENT_TIMEOUT_ABORT && xhr) { xhr.abort('timeout'); deferred.reject(xhr, 'timeout'); return; } else if (e == SERVER_ABORT && xhr) { xhr.abort('server abort'); deferred.reject(xhr, 'error', 'server abort'); return; } if (!doc || doc.location.href == s.iframeSrc) { // response not received yet if (!timedOut) return; } if (io.detachEvent) io.detachEvent('onload', cb); else io.removeEventListener('load', cb, false); var status = 'success', errMsg; try { if (timedOut) { throw 'timeout'; } var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc); log('isXml='+isXml); if (!isXml && window.opera && (doc.body === null || !doc.body.innerHTML)) { if (--domCheckCount) { // in some browsers (Opera) the iframe DOM is not always traversable when // the onload callback fires, so we loop a bit to accommodate log('requeing onLoad callback, DOM not available'); setTimeout(cb, 250); return; } // let this fall through because server response could be an empty document //log('Could not access iframe DOM after mutiple tries.'); //throw 'DOMException: not available'; } //log('response detected'); var docRoot = doc.body ? doc.body : doc.documentElement; xhr.responseText = docRoot ? docRoot.innerHTML : null; xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc; if (isXml) s.dataType = 'xml'; xhr.getResponseHeader = function(header){ var headers = {'content-type': s.dataType}; return headers[header]; }; // support for XHR 'status' & 'statusText' emulation : if (docRoot) { xhr.status = Number( docRoot.getAttribute('status') ) || xhr.status; xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText; } var dt = (s.dataType || '').toLowerCase(); var scr = /(json|script|text)/.test(dt); if (scr || s.textarea) { // see if user embedded response in textarea var ta = doc.getElementsByTagName('textarea')[0]; if (ta) { xhr.responseText = ta.value; // support for XHR 'status' & 'statusText' emulation : xhr.status = Number( ta.getAttribute('status') ) || xhr.status; xhr.statusText = ta.getAttribute('statusText') || xhr.statusText; } else if (scr) { // account for browsers injecting pre around json response var pre = doc.getElementsByTagName('pre')[0]; var b = doc.getElementsByTagName('body')[0]; if (pre) { xhr.responseText = pre.textContent ? pre.textContent : pre.innerText; } else if (b) { xhr.responseText = b.textContent ? b.textContent : b.innerText; } } } else if (dt == 'xml' && !xhr.responseXML && xhr.responseText) { xhr.responseXML = toXml(xhr.responseText); } try { data = httpData(xhr, dt, s); } catch (err) { status = 'parsererror'; xhr.error = errMsg = (err || status); } } catch (err) { log('error caught: ',err); status = 'error'; xhr.error = errMsg = (err || status); } if (xhr.aborted) { log('upload aborted'); status = null; } if (xhr.status) { // we've set xhr.status status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error'; } // ordering of these callbacks/triggers is odd, but that's how $.ajax does it if (status === 'success') { if (s.success) s.success.call(s.context, data, 'success', xhr); deferred.resolve(xhr.responseText, 'success', xhr); if (g) $.event.trigger("ajaxSuccess", [xhr, s]); } else if (status) { if (errMsg === undefined) errMsg = xhr.statusText; if (s.error) s.error.call(s.context, xhr, status, errMsg); deferred.reject(xhr, 'error', errMsg); if (g) $.event.trigger("ajaxError", [xhr, s, errMsg]); } if (g) $.event.trigger("ajaxComplete", [xhr, s]); if (g && ! --$.active) { $.event.trigger("ajaxStop"); } if (s.complete) s.complete.call(s.context, xhr, status); callbackProcessed = true; if (s.timeout) clearTimeout(timeoutHandle); // clean up setTimeout(function() { if (!s.iframeTarget) $io.remove(); xhr.responseXML = null; }, 100); } var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+) if (window.ActiveXObject) { doc = new ActiveXObject('Microsoft.XMLDOM'); doc.async = 'false'; doc.loadXML(s); } else { doc = (new DOMParser()).parseFromString(s, 'text/xml'); } return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null; }; var parseJSON = $.parseJSON || function(s) { /*jslint evil:true */ return window['eval']('(' + s + ')'); }; var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4 var ct = xhr.getResponseHeader('content-type') || '', xml = type === 'xml' || !type && ct.indexOf('xml') >= 0, data = xml ? xhr.responseXML : xhr.responseText; if (xml && data.documentElement.nodeName === 'parsererror') { if ($.error) $.error('parsererror'); } if (s && s.dataFilter) { data = s.dataFilter(data, type); } if (typeof data === 'string') { if (type === 'json' || !type && ct.indexOf('json') >= 0) { data = parseJSON(data); } else if (type === "script" || !type && ct.indexOf("javascript") >= 0) { $.globalEval(data); } } return data; }; return deferred; } }; /** * ajaxForm() provides a mechanism for fully automating form submission. * * The advantages of using this method instead of ajaxSubmit() are: * * 1: This method will include coordinates for <input type="image" /> elements (if the element * is used to submit the form). * 2. This method will include the submit element's name/value data (for the element that was * used to submit the form). * 3. This method binds the submit() method to the form for you. * * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely * passes the options argument along after properly binding events for submit elements and * the form itself. */ $.fn.ajaxForm = function(options) { options = options || {}; options.delegation = options.delegation && $.isFunction($.fn.on); // in jQuery 1.3+ we can fix mistakes with the ready state if (!options.delegation && this.length === 0) { var o = { s: this.selector, c: this.context }; if (!$.isReady && o.s) { log('DOM not ready, queuing ajaxForm'); $(function() { $(o.s,o.c).ajaxForm(options); }); return this; } // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready() log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)')); return this; } if ( options.delegation ) { $(document) .off('submit.form-plugin', this.selector, doAjaxSubmit) .off('click.form-plugin', this.selector, captureSubmittingElement) .on('submit.form-plugin', this.selector, options, doAjaxSubmit) .on('click.form-plugin', this.selector, options, captureSubmittingElement); return this; } return this.ajaxFormUnbind() .bind('submit.form-plugin', options, doAjaxSubmit) .bind('click.form-plugin', options, captureSubmittingElement); }; // private event handlers function doAjaxSubmit(e) { /*jshint validthis:true */ var options = e.data; if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed e.preventDefault(); $(this).ajaxSubmit(options); } } function captureSubmittingElement(e) { /*jshint validthis:true */ var target = e.target; var $el = $(target); if (!($el.is("[type=submit],[type=image]"))) { // is this a child element of the submit el? (ex: a span within a button) var t = $el.closest('[type=submit]'); if (t.length === 0) { return; } target = t[0]; } var form = this; form.clk = target; if (target.type == 'image') { if (e.offsetX !== undefined) { form.clk_x = e.offsetX; form.clk_y = e.offsetY; } else if (typeof $.fn.offset == 'function') { var offset = $el.offset(); form.clk_x = e.pageX - offset.left; form.clk_y = e.pageY - offset.top; } else { form.clk_x = e.pageX - target.offsetLeft; form.clk_y = e.pageY - target.offsetTop; } } // clear form vars setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100); } // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm $.fn.ajaxFormUnbind = function() { return this.unbind('submit.form-plugin click.form-plugin'); }; /** * formToArray() gathers form element data into an array of objects that can * be passed to any of the following ajax functions: $.get, $.post, or load. * Each object in the array has both a 'name' and 'value' property. An example of * an array for a simple login form might be: * * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ] * * It is this array that is passed to pre-submit callback functions provided to the * ajaxSubmit() and ajaxForm() methods. */ $.fn.formToArray = function(semantic, elements) { var a = []; if (this.length === 0) { return a; } var form = this[0]; var els = semantic ? form.getElementsByTagName('*') : form.elements; if (!els) { return a; } var i,j,n,v,el,max,jmax; for(i=0, max=els.length; i < max; i++) { el = els[i]; n = el.name; if (!n || el.disabled) { continue; } if (semantic && form.clk && el.type == "image") { // handle image inputs on the fly when semantic == true if(form.clk == el) { a.push({name: n, value: $(el).val(), type: el.type }); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } continue; } v = $.fieldValue(el, true); if (v && v.constructor == Array) { if (elements) elements.push(el); for(j=0, jmax=v.length; j < jmax; j++) { a.push({name: n, value: v[j]}); } } else if (feature.fileapi && el.type == 'file') { if (elements) elements.push(el); var files = el.files; if (files.length) { for (j=0; j < files.length; j++) { a.push({name: n, value: files[j], type: el.type}); } } else { // #180 a.push({ name: n, value: '', type: el.type }); } } else if (v !== null && typeof v != 'undefined') { if (elements) elements.push(el); a.push({name: n, value: v, type: el.type, required: el.required}); } } if (!semantic && form.clk) { // input type=='image' are not found in elements array! handle it here var $input = $(form.clk), input = $input[0]; n = input.name; if (n && !input.disabled && input.type == 'image') { a.push({name: n, value: $input.val()}); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } } return a; }; /** * Serializes form data into a 'submittable' string. This method will return a string * in the format: name1=value1&amp;name2=value2 */ $.fn.formSerialize = function(semantic) { //hand off to jQuery.param for proper encoding return $.param(this.formToArray(semantic)); }; /** * Serializes all field elements in the jQuery object into a query string. * This method will return a string in the format: name1=value1&amp;name2=value2 */ $.fn.fieldSerialize = function(successful) { var a = []; this.each(function() { var n = this.name; if (!n) { return; } var v = $.fieldValue(this, successful); if (v && v.constructor == Array) { for (var i=0,max=v.length; i < max; i++) { a.push({name: n, value: v[i]}); } } else if (v !== null && typeof v != 'undefined') { a.push({name: this.name, value: v}); } }); //hand off to jQuery.param for proper encoding return $.param(a); }; /** * Returns the value(s) of the element in the matched set. For example, consider the following form: * * <form><fieldset> * <input name="A" type="text" /> * <input name="A" type="text" /> * <input name="B" type="checkbox" value="B1" /> * <input name="B" type="checkbox" value="B2"/> * <input name="C" type="radio" value="C1" /> * <input name="C" type="radio" value="C2" /> * </fieldset></form> * * var v = $('input[type=text]').fieldValue(); * // if no values are entered into the text inputs * v == ['',''] * // if values entered into the text inputs are 'foo' and 'bar' * v == ['foo','bar'] * * var v = $('input[type=checkbox]').fieldValue(); * // if neither checkbox is checked * v === undefined * // if both checkboxes are checked * v == ['B1', 'B2'] * * var v = $('input[type=radio]').fieldValue(); * // if neither radio is checked * v === undefined * // if first radio is checked * v == ['C1'] * * The successful argument controls whether or not the field element must be 'successful' * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls). * The default value of the successful argument is true. If this value is false the value(s) * for each element is returned. * * Note: This method *always* returns an array. If no valid value can be determined the * array will be empty, otherwise it will contain one or more values. */ $.fn.fieldValue = function(successful) { for (var val=[], i=0, max=this.length; i < max; i++) { var el = this[i]; var v = $.fieldValue(el, successful); if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) { continue; } if (v.constructor == Array) $.merge(val, v); else val.push(v); } return val; }; /** * Returns the value of the field element. */ $.fieldValue = function(el, successful) { var n = el.name, t = el.type, tag = el.tagName.toLowerCase(); if (successful === undefined) { successful = true; } if (successful && (!n || el.disabled || t == 'reset' || t == 'button' || (t == 'checkbox' || t == 'radio') && !el.checked || (t == 'submit' || t == 'image') && el.form && el.form.clk != el || tag == 'select' && el.selectedIndex == -1)) { return null; } if (tag == 'select') { var index = el.selectedIndex; if (index < 0) { return null; } var a = [], ops = el.options; var one = (t == 'select-one'); var max = (one ? index+1 : ops.length); for(var i=(one ? index : 0); i < max; i++) { var op = ops[i]; if (op.selected) { var v = op.value; if (!v) { // extra pain for IE... v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value; } if (one) { return v; } a.push(v); } } return a; } return $(el).val(); }; /** * Clears the form data. Takes the following actions on the form's input fields: * - input text fields will have their 'value' property set to the empty string * - select elements will have their 'selectedIndex' property set to -1 * - checkbox and radio inputs will have their 'checked' property set to false * - inputs of type submit, button, reset, and hidden will *not* be effected * - button elements will *not* be effected */ $.fn.clearForm = function(includeHidden) { return this.each(function() { $('input,select,textarea', this).clearFields(includeHidden); }); }; /** * Clears the selected form elements. */ $.fn.clearFields = $.fn.clearInputs = function(includeHidden) { var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list return this.each(function() { var t = this.type, tag = this.tagName.toLowerCase(); if (re.test(t) || tag == 'textarea') { this.value = ''; } else if (t == 'checkbox' || t == 'radio') { this.checked = false; } else if (tag == 'select') { this.selectedIndex = -1; } else if (t == "file") { if (/MSIE/.test(navigator.userAgent)) { $(this).replaceWith($(this).clone(true)); } else { $(this).val(''); } } else if (includeHidden) { // includeHidden can be the value true, or it can be a selector string // indicating a special test; for example: // $('#myForm').clearForm('.special:hidden') // the above would clean hidden inputs that have the class of 'special' if ( (includeHidden === true && /hidden/.test(t)) || (typeof includeHidden == 'string' && $(this).is(includeHidden)) ) this.value = ''; } }); }; /** * Resets the form data. Causes all form elements to be reset to their original value. */ $.fn.resetForm = function() { return this.each(function() { // guard against an input with the name of 'reset' // note that IE reports the reset function as an 'object' if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) { this.reset(); } }); }; /** * Enables or disables any matching elements. */ $.fn.enable = function(b) { if (b === undefined) { b = true; } return this.each(function() { this.disabled = !b; }); }; /** * Checks/unchecks any matching checkboxes or radio buttons and * selects/deselects and matching option elements. */ $.fn.selected = function(select) { if (select === undefined) { select = true; } return this.each(function() { var t = this.type; if (t == 'checkbox' || t == 'radio') { this.checked = select; } else if (this.tagName.toLowerCase() == 'option') { var $sel = $(this).parent('select'); if (select && $sel[0] && $sel[0].type == 'select-one') { // deselect all other options $sel.find('option').selected(false); } this.selected = select; } }); }; // expose debug var $.fn.ajaxSubmit.debug = false; // helper fn for console logging function log() { if (!$.fn.ajaxSubmit.debug) return; var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,''); if (window.console && window.console.log) { window.console.log(msg); } else if (window.opera && window.opera.postError) { window.opera.postError(msg); } } })(jQuery);
12sm/erinmyers
wp-content/plugins/wp-toolbar-editor/js/jquery.form.js
JavaScript
gpl-2.0
41,603
<?php if (isset($_POST['gdsr_action']) && $_POST['gdsr_action'] == 'save') { $gdsr_options["bot_message"] = $_POST['gdsr_bot_message']; $gdsr_options["no_votes_percentage"] = $_POST['gdsr_no_votes_percentage']; $gdsr_options["cached_loading"] = isset($_POST['gdsr_cached_loading']) ? 1 : 0; $gdsr_options["include_opacity"] = isset($_POST['gdsr_include_opacity']) ? 1 : 0; $gdsr_options["comments_integration_articles_active"] = isset($_POST['gdsr_cmmintartactive']) ? 1 : 0; $gdsr_options["update_report_usage"] = isset($_POST['gdsr_update_report_usage']) ? 1 : 0; $gdsr_options["int_comment_std_zero"] = isset($_POST['gdsr_int_comment_std_zero']) ? 1 : 0; $gdsr_options["int_comment_mur_zero"] = isset($_POST['gdsr_int_comment_mur_zero']) ? 1 : 0; $gdsr_options["thumbs_active"] = isset($_POST['gdsr_thumbs_act']) ? 1 : 0; $gdsr_options["wp_query_handler"] = isset($_POST['gdsr_wp_query_handler']) ? 1 : 0; $gdsr_options["disable_ie6_check"] = isset($_POST['gdsr_disable_ie6_check']) ? 1 : 0; $gdsr_options["news_feed_active"] = isset($_POST['gdsr_news_feed_active']) ? 1 : 0; $gdsr_options["widgets_hidempty"] = isset($_POST['gdsr_widgets_hidempty']) ? 1 : 0; $gdsr_options["encoding"] = $_POST['gdsr_encoding']; $gdsr_options["admin_rows"] = $_POST['gdsr_admin_rows']; $gdsr_options["gfx_generator_auto"] = isset($_POST['gdsr_gfx_generator_auto']) ? 1 : 0; $gdsr_options["gfx_prevent_leeching"] = isset($_POST['gdsr_gfx_prevent_leeching']) ? 1 : 0; $gdsr_options["external_rating_css"] = isset($_POST['gdsr_external_rating_css']) ? 1 : 0; $gdsr_options["css_cache_active"] = isset($_POST['gdsr_css_cache_active']) ? 1 : 0; $gdsr_options["external_css"] = isset($_POST['gdsr_external_css']) ? 1 : 0; $gdsr_options["cmm_integration_replay_hide_review"] = isset($_POST['gdsr_cmm_integration_replay_hide_review']) ? 1 : 0; $gdsr_options["cmm_integration_prevent_duplicates"] = isset($_POST['gdsr_cmm_integration_prevent_duplicates']) ? 1 : 0; $gdsr_options["admin_advanced"] = isset($_POST['gdsr_admin_advanced']) ? 1 : 0; $gdsr_options["admin_placement"] = isset($_POST['gdsr_admin_placement']) ? 1 : 0; $gdsr_options["admin_defaults"] = isset($_POST['gdsr_admin_defaults']) ? 1 : 0; $gdsr_options["admin_import"] = isset($_POST['gdsr_admin_import']) ? 1 : 0; $gdsr_options["admin_export"] = isset($_POST['gdsr_admin_export']) ? 1 : 0; $gdsr_options["admin_setup"] = isset($_POST['gdsr_admin_setup']) ? 1 : 0; $gdsr_options["admin_ips"] = isset($_POST['gdsr_admin_ips']) ? 1 : 0; $gdsr_options["admin_views"] = isset($_POST['gdsr_admin_views']) ? 1 : 0; $gdsr_options["prefetch_data"] = isset($_POST['gdsr_prefetch_data']) ? 1 : 0; $gdsr_options["allow_mixed_ip_votes"] = isset($_POST['gdsr_allow_mixed_ip_votes']) ? 1 : 0; $gdsr_options["cmm_allow_mixed_ip_votes"] = isset($_POST['gdsr_cmm_allow_mixed_ip_votes']) ? 1 : 0; $gdsr_options["mur_allow_mixed_ip_votes"] = isset($_POST['gdsr_mur_allow_mixed_ip_votes']) ? 1 : 0; $gdsr_options["cache_active"] = isset($_POST['gdsr_cache_active']) ? 1 : 0; $gdsr_options["cache_forced"] = isset($_POST['gdsr_cache_forced']) ? 1 : 0; $gdsr_options["cache_cleanup_auto"] = isset($_POST['gdsr_cache_cleanup_auto']) ? 1 : 0; $gdsr_options["cache_cleanup_days"] = $_POST['gdsr_cache_cleanup_days']; $gdsr_options["wait_show_article"] = isset($_POST['gdsr_wait_show_article']) ? 1 : 0; $gdsr_options["wait_show_comment"] = isset($_POST['gdsr_wait_show_comment']) ? 1 : 0; $gdsr_options["wait_show_multis"] = isset($_POST['gdsr_wait_show_multis']) ? 1 : 0; $gdsr_options["wait_loader_article"] = $_POST['gdsr_wait_loader_article']; $gdsr_options["wait_loader_comment"] = $_POST['gdsr_wait_loader_comment']; $gdsr_options["wait_loader_multis"] = $_POST['gdsr_wait_loader_multis']; $gdsr_options["wait_text_article"] = $_POST['gdsr_wait_text_article']; $gdsr_options["wait_text_comment"] = $_POST['gdsr_wait_text_comment']; $gdsr_options["wait_text_multis"] = $_POST['gdsr_wait_text_multis']; $gdsr_options["wait_class_article"] = $_POST['gdsr_wait_class_article']; $gdsr_options["wait_class_comment"] = $_POST['gdsr_wait_class_comment']; $gdsr_options["wait_class_multis"] = $_POST['gdsr_wait_class_multis']; $gdsr_options["wait_loader_artthumb"] = $_POST['gdsr_wait_loader_artthumb']; $gdsr_options["wait_loader_cmmthumb"] = $_POST['gdsr_wait_loader_cmmthumb']; $gdsr_options["security_showdashboard_user_level"] = $_POST['gdsr_security_showdashboard_user_level']; $gdsr_options["security_showip_user_level"] = $_POST['gdsr_security_showip_user_level']; $gdsr_options["google_rich_snippets_format"] = $_POST['gdsr_grs_format']; $gdsr_options["google_rich_snippets_location"] = $_POST['gdsr_grs_location']; $gdsr_options["google_rich_snippets_datasource"] = $_POST['gdsr_grs_datasource']; $gdsr_options["google_rich_snippets_active"] = isset($_POST['gdsr_grs']) ? 1 : 0; $gdsr_options["debug_wpquery"] = isset($_POST['gdsr_debug_wpquery']) ? 1 : 0; $gdsr_options["debug_active"] = isset($_POST['gdsr_debug_active']) ? 1 : 0; $gdsr_options["debug_inline"] = isset($_POST['gdsr_debug_inline']) ? 1 : 0; $gdsr_options["use_nonce"] = isset($_POST['gdsr_use_nonce']) ? 1 : 0; $gdsr_options["ajax_jsonp"] = isset($_POST['gdsr_ajax_jsonp']) ? 1 : 0; $gdsr_options["ip_filtering"] = isset($_POST['gdsr_ip_filtering']) ? 1 : 0; $gdsr_options["ip_filtering_restrictive"] = isset($_POST['gdsr_ip_filtering_restrictive']) ? 1 : 0; $gdsr_options["widget_articles"] = isset($_POST['gdsr_widget_articles']) ? 1 : 0; $gdsr_options["widget_top"] = isset($_POST['gdsr_widget_top']) ? 1 : 0; $gdsr_options["widget_comments"] = isset($_POST['gdsr_widget_comments']) ? 1 : 0; $gdsr_options["display_pages"] = isset($_POST['gdsr_pages']) ? 1 : 0; $gdsr_options["display_posts"] = isset($_POST['gdsr_posts']) ? 1 : 0; $gdsr_options["display_archive"] = isset($_POST['gdsr_archive']) ? 1 : 0; $gdsr_options["display_home"] = isset($_POST['gdsr_home']) ? 1 : 0; $gdsr_options["display_search"] = isset($_POST['gdsr_search']) ? 1 : 0; $gdsr_options["display_comment"] = isset($_POST['gdsr_dispcomment']) ? 1 : 0; $gdsr_options["display_comment_page"] = isset($_POST['gdsr_dispcomment_pages']) ? 1 : 0; $gdsr_options["moderation_active"] = isset($_POST['gdsr_modactive']) ? 1 : 0; $gdsr_options["multis_active"] = isset($_POST['gdsr_multis']) ? 1 : 0; $gdsr_options["timer_active"] = isset($_POST['gdsr_timer']) ? 1 : 0; $gdsr_options["rss_active"] = isset($_POST['gdsr_rss']) ? 1 : 0; $gdsr_options["save_user_agent"] = isset($_POST['gdsr_save_user_agent']) ? 1 : 0; $gdsr_options["save_cookies"] = isset($_POST['gdsr_save_cookies']) ? 1 : 0; $gdsr_options["ie_opacity_fix"] = isset($_POST['gdsr_ieopacityfix']) ? 1 : 0; $gdsr_options["override_display_comment"] = isset($_POST['gdsr_override_display_comment']) ? 1 : 0; $gdsr_options["override_thumb_display_comment"] = isset($_POST['gdsr_override_thumb_display_comment']) ? 1 : 0; $gdsr_options["integrate_dashboard"] = isset($_POST['gdsr_integrate_dashboard']) ? 1 : 0; $gdsr_options["integrate_dashboard_latest"] = isset($_POST['gdsr_integrate_dashboard_latest']) ? 1 : 0; $gdsr_options["integrate_dashboard_latest_filter_thumb_std"] = isset($_POST['gdsr_integrate_dashboard_latest_filter_thumb_std']) ? 1 : 0; $gdsr_options["integrate_dashboard_latest_filter_thumb_cmm"] = isset($_POST['gdsr_integrate_dashboard_latest_filter_thumb_cmm']) ? 1 : 0; $gdsr_options["integrate_dashboard_latest_filter_stars_std"] = isset($_POST['gdsr_integrate_dashboard_latest_filter_stars_std']) ? 1 : 0; $gdsr_options["integrate_dashboard_latest_filter_stars_cmm"] = isset($_POST['gdsr_integrate_dashboard_latest_filter_stars_cmm']) ? 1 : 0; $gdsr_options["integrate_dashboard_latest_filter_stars_mur"] = isset($_POST['gdsr_integrate_dashboard_latest_filter_stars_mur']) ? 1 : 0; $gdsr_options["integrate_dashboard_latest_count"] = $_POST['gdsr_integrate_dashboard_latest_count']; $gdsr_options["integrate_post_edit"] = isset($_POST['gdsr_integrate_post_edit']) ? 1 : 0; $gdsr_options["integrate_post_edit_mur"] = isset($_POST['gdsr_integrate_post_edit_mur']) ? 1 : 0; $gdsr_options["integrate_tinymce"] = isset($_POST['gdsr_integrate_tinymce']) ? 1 : 0; $gdsr_options["integrate_rss_powered"] = isset($_POST['gdsr_integrate_rss_powered']) ? 1 : 0; $gdsr_options["trend_last"] = $_POST['gdsr_trend_last']; $gdsr_options["trend_over"] = $_POST['gdsr_trend_over']; $gdsr_options["bayesian_minimal"] = $_POST['gdsr_bayesian_minimal']; $gdsr_options["bayesian_mean"] = $_POST['gdsr_bayesian_mean']; $gdsr_options["auto_display_position"] = $_POST['gdsr_auto_display_position']; $gdsr_options["auto_display_comment_position"] = $_POST['gdsr_auto_display_comment_position']; $gdsr_options["default_timer_type"] = isset($_POST['gdsr_default_timer_type']) ? $_POST['gdsr_default_timer_type'] : "N"; $gdsr_options["default_timer_countdown_value"] = isset($_POST['gdsr_default_timer_countdown_value']) ? $_POST['gdsr_default_timer_countdown_value'] : 30; $gdsr_options["default_timer_countdown_type"] = isset($_POST['gdsr_default_timer_countdown_type']) ? $_POST['gdsr_default_timer_countdown_type'] : "D"; $gdsr_options["default_timer_value"] = $gdsr_options["default_timer_countdown_type"].$gdsr_options["default_timer_countdown_value"]; $gdsr_options["default_mur_timer_type"] = isset($_POST['gdsr_default_mur_timer_type']) ? $_POST['gdsr_default_mur_timer_type'] : "N"; $gdsr_options["default_mur_timer_countdown_value"] = isset($_POST['gdsr_default_mur_timer_countdown_value']) ? $_POST['gdsr_default_mur_timer_countdown_value'] : 30; $gdsr_options["default_mur_timer_countdown_type"] = isset($_POST['gdsr_default_mur_timer_countdown_type']) ? $_POST['gdsr_default_mur_timer_countdown_type'] : "D"; $gdsr_options["default_mur_timer_value"] = $gdsr_options["default_mur_timer_countdown_type"].$gdsr_options["default_mur_timer_countdown_value"]; $gdsr_options["review_active"] = isset($_POST['gdsr_reviewactive']) ? 1 : 0; $gdsr_options["comments_active"] = isset($_POST['gdsr_commentsactive']) ? 1 : 0; $gdsr_options["comments_review_active"] = isset($_POST['gdsr_cmmreviewactive']) ? 1 : 0; $gdsr_options["hide_empty_rating"] = isset($_POST['gdsr_haderating']) ? 1 : 0; $gdsr_options["cookies"] = isset($_POST['gdsr_cookies']) ? 1 : 0; $gdsr_options["cmm_cookies"] = isset($_POST['gdsr_cmm_cookies']) ? 1 : 0; $gdsr_options["author_vote"] = isset($_POST['gdsr_authorvote']) ? 1 : 0; $gdsr_options["cmm_author_vote"] = isset($_POST['gdsr_cmm_authorvote']) ? 1 : 0; $gdsr_options["logged"] = isset($_POST['gdsr_logged']) ? 1 : 0; $gdsr_options["cmm_logged"] = isset($_POST['gdsr_cmm_logged']) ? 1 : 0; $gdsr_options["rss_datasource"] = $_POST['gdsr_rss_datasource']; $gdsr_options["rss_style"] = $_POST['gdsr_rss_style']; $gdsr_options["rss_size"] = $_POST['gdsr_rss_size']; $gdsr_options["thumb_rss_style"] = $_POST['gdsr_thumb_rss_style']; $gdsr_options["thumb_rss_size"] = $_POST['gdsr_thumb_rss_size']; $gdsr_options["rss_header_text"] = stripslashes(htmlentities($_POST['gdsr_rss_header_text'], ENT_QUOTES, STARRATING_ENCODING)); $gdsr_options["style"] = $_POST['gdsr_style']; $gdsr_options["style_ie6"] = $_POST['gdsr_style_ie6']; $gdsr_options["size"] = $_POST['gdsr_size']; $gdsr_options["header_text"] = stripslashes(htmlentities($_POST['gdsr_header_text'], ENT_QUOTES, STARRATING_ENCODING)); $gdsr_options["thumb_style"] = $_POST['gdsr_thumb_style']; $gdsr_options["thumb_style_ie6"] = $_POST['gdsr_thumb_style_ie6']; $gdsr_options["thumb_size"] = $_POST['gdsr_thumb_size']; $gdsr_options["thumb_header_text"] = stripslashes(htmlentities($_POST['gdsr_thumb_header_text'], ENT_QUOTES, STARRATING_ENCODING)); $gdsr_options["thumb_cmm_style"] = $_POST['gdsr_thumb_cmm_style']; $gdsr_options["thumb_cmm_style_ie6"] = $_POST['gdsr_thumb_cmm_style_ie6']; $gdsr_options["thumb_cmm_size"] = $_POST['gdsr_thumb_cmm_size']; $gdsr_options["thumb_cmm_header_text"] = stripslashes(htmlentities($_POST['gdsr_thumb_cmm_header_text'], ENT_QUOTES, STARRATING_ENCODING)); $gdsr_options["default_srb_template"] = $_POST['gdsr_default_srb_template']; $gdsr_options["default_crb_template"] = $_POST['gdsr_default_crb_template']; $gdsr_options["default_ssb_template"] = $_POST['gdsr_default_ssb_template']; $gdsr_options["default_mrb_template"] = $_POST['gdsr_default_mrb_template']; $gdsr_options["default_tab_template"] = $_POST['gdsr_default_tab_template']; $gdsr_options["default_tcb_template"] = $_POST['gdsr_default_tcb_template']; $gdsr_options["srb_class_block"] = $_POST['gdsr_classblock']; $gdsr_options["srb_class_text"] = $_POST['gdsr_classtext']; $gdsr_options["srb_class_header"] = $_POST['gdsr_classheader']; $gdsr_options["srb_class_stars"] = $_POST['gdsr_classstars']; $gdsr_options["cmm_class_block"] = $_POST['gdsr_cmm_classblock']; $gdsr_options["cmm_class_text"] = $_POST['gdsr_cmm_classtext']; $gdsr_options["cmm_class_header"] = $_POST['gdsr_cmm_classheader']; $gdsr_options["cmm_class_stars"] = $_POST['gdsr_cmm_classstars']; $gdsr_options["mur_style"] = $_POST['gdsr_mur_style']; $gdsr_options["mur_style_ie6"] = $_POST['gdsr_mur_style_ie6']; $gdsr_options["mur_size"] = $_POST['gdsr_mur_size']; $gdsr_options["mur_header_text"] = stripslashes(htmlentities($_POST['gdsr_mur_header_text'], ENT_QUOTES, STARRATING_ENCODING)); $gdsr_options["mur_class_block"] = $_POST['gdsr_mur_classblock']; $gdsr_options["mur_class_text"] = $_POST['gdsr_mur_classtext']; $gdsr_options["mur_class_header"] = $_POST['gdsr_mur_classheader']; $gdsr_options["mur_class_button"] = $_POST['gdsr_mur_classbutton']; $gdsr_options["mur_button_text"] = $_POST['gdsr_mur_submittext']; $gdsr_options["mur_button_active"] = isset($_POST['gdsr_mur_submitactive']) ? 1 : 0; $gdsr_options["cmm_aggr_style"] = $_POST['gdsr_cmm_aggr_style']; $gdsr_options["cmm_aggr_style_ie6"] = $_POST['gdsr_cmm_aggr_style_ie6']; $gdsr_options["cmm_aggr_size"] = $_POST['gdsr_cmm_aggr_size']; $gdsr_options["cmm_style"] = $_POST['gdsr_cmm_style']; $gdsr_options["cmm_style_ie6"] = $_POST['gdsr_cmm_style_ie6']; $gdsr_options["cmm_size"] = $_POST['gdsr_cmm_size']; $gdsr_options["cmm_header_text"] = stripslashes(htmlentities($_POST['gdsr_cmm_header_text'], ENT_QUOTES, STARRATING_ENCODING)); $gdsr_options["review_style"] = $_POST['gdsr_review_style']; $gdsr_options["review_style_ie6"] = $_POST['gdsr_review_style_ie6']; $gdsr_options["review_size"] = $_POST['gdsr_review_size']; $gdsr_options["review_stars"] = $_POST['gdsr_review_stars']; $gdsr_options["review_header_text"] = stripslashes(htmlentities($_POST['gdsr_review_header_text'], ENT_QUOTES, STARRATING_ENCODING)); $gdsr_options["review_class_block"] = $_POST['gdsr_review_classblock']; $gdsr_options["cmm_review_style"] = isset($_POST['gdsr_cmm_review_style']) ? $_POST['gdsr_cmm_review_style'] : "oxyen"; $gdsr_options["cmm_review_style_ie6"] = isset($_POST['gdsr_cmm_review_style_ie6']) ? $_POST['gdsr_cmm_review_style_ie6'] : "oxyen_gif"; $gdsr_options["cmm_review_size"] = isset($_POST['gdsr_cmm_review_size']) ? $_POST['gdsr_cmm_review_size'] : 20; $gdsr_options["default_voterules_multis"] = $_POST['gdsr_default_vote_multis']; $gdsr_options["default_voterules_articles"] = $_POST['gdsr_default_vote_articles']; $gdsr_options["default_voterules_comments"] = $_POST['gdsr_default_vote_comments']; $gdsr_options["recc_default_voterules_articles"] = $_POST['gdsr_recc_default_vote_articles']; $gdsr_options["recc_default_voterules_comments"] = $_POST['gdsr_recc_default_vote_comments']; $gdsr_options["default_moderation_multis"] = isset($_POST['gdsr_default_mod_multis']) ? $_POST['gdsr_default_mod_multis'] : ""; $gdsr_options["default_moderation_articles"] = isset($_POST['gdsr_default_mod_articles']) ? $_POST['gdsr_default_mod_articles'] : ""; $gdsr_options["default_moderation_comments"] = isset($_POST['gdsr_default_mod_comments']) ? $_POST['gdsr_default_mod_comments'] : ""; $gdsr_options["recc_default_moderation_articles"] = isset($_POST['gdsr_recc_default_mod_articles']) ? $_POST['gdsr_recc_default_mod_articles'] : ""; $gdsr_options["recc_default_moderation_comments"] = isset($_POST['gdsr_recc_default_mod_comments']) ? $_POST['gdsr_recc_default_mod_comments'] : ""; $gdsr_options["thumb_display_pages"] = isset($_POST['gdsr_thumb_pages']) ? 1 : 0; $gdsr_options["thumb_display_posts"] = isset($_POST['gdsr_thumb_posts']) ? 1 : 0; $gdsr_options["thumb_display_archive"] = isset($_POST['gdsr_thumb_archive']) ? 1 : 0; $gdsr_options["thumb_display_home"] = isset($_POST['gdsr_thumb_home']) ? 1 : 0; $gdsr_options["thumb_display_search"] = isset($_POST['gdsr_thumb_search']) ? 1 : 0; $gdsr_options["thumb_display_comment"] = isset($_POST['gdsr_thumb_dispcomment']) ? 1 : 0; $gdsr_options["thumb_display_comment_page"] = isset($_POST['gdsr_thumb_dispcomment_pages']) ? 1 : 0; $gdsr_options["thumb_auto_display_position"] = $_POST['gdsr_thumb_auto_display_position']; $gdsr_options["thumb_auto_display_comment_position"] = $_POST['gdsr_thumb_auto_display_comment_position']; $gdsr_options["css_last_changed"] = time(); update_option("gd-star-rating", $gdsr_options); $bots = explode("\r\n", $_POST["gdsr_bots"]); foreach($bots as $key => $value) { if(trim($value) == "") { unset($bots[$key]); } } $bots = array_values($bots); update_option("gd-star-rating-bots", $bots); } ?>
imshashank/The-Perfect-Self
wp-content/plugins/gd-star-rating/code/adm/save_settings.php
PHP
gpl-2.0
18,252
/* * Samsung EXYNOS FIMC-LITE (camera host interface) driver * * Copyright (C) 2012 - 2013 Samsung Electronics Co., Ltd. * Author: Sylwester Nawrocki <s.nawrocki@samsung.com> * * This program 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. */ #define pr_fmt(fmt) "%s:%d " fmt, __func__, __LINE__ #include <linux/bug.h> #include <linux/clk.h> #include <linux/device.h> #include <linux/errno.h> #include <linux/interrupt.h> #include <linux/kernel.h> #include <linux/list.h> #include <linux/module.h> #include <linux/of.h> #include <linux/types.h> #include <linux/platform_device.h> #include <linux/pm_runtime.h> #include <linux/slab.h> #include <linux/videodev2.h> #include <media/v4l2-device.h> #include <media/v4l2-ioctl.h> #include <media/v4l2-mem2mem.h> #include <media/videobuf2-core.h> #include <media/videobuf2-dma-contig.h> #include <media/exynos-fimc.h> #include "common.h" #include "fimc-core.h" #include "fimc-lite.h" #include "fimc-lite-reg.h" static int debug; module_param(debug, int, 0644); static const struct fimc_fmt fimc_lite_formats[] = { { .name = "YUV 4:2:2 packed, YCbYCr", .fourcc = V4L2_PIX_FMT_YUYV, .colorspace = V4L2_COLORSPACE_JPEG, .depth = { 16 }, .color = FIMC_FMT_YCBYCR422, .memplanes = 1, .mbus_code = MEDIA_BUS_FMT_YUYV8_2X8, .flags = FMT_FLAGS_YUV, }, { .name = "YUV 4:2:2 packed, CbYCrY", .fourcc = V4L2_PIX_FMT_UYVY, .colorspace = V4L2_COLORSPACE_JPEG, .depth = { 16 }, .color = FIMC_FMT_CBYCRY422, .memplanes = 1, .mbus_code = MEDIA_BUS_FMT_UYVY8_2X8, .flags = FMT_FLAGS_YUV, }, { .name = "YUV 4:2:2 packed, CrYCbY", .fourcc = V4L2_PIX_FMT_VYUY, .colorspace = V4L2_COLORSPACE_JPEG, .depth = { 16 }, .color = FIMC_FMT_CRYCBY422, .memplanes = 1, .mbus_code = MEDIA_BUS_FMT_VYUY8_2X8, .flags = FMT_FLAGS_YUV, }, { .name = "YUV 4:2:2 packed, YCrYCb", .fourcc = V4L2_PIX_FMT_YVYU, .colorspace = V4L2_COLORSPACE_JPEG, .depth = { 16 }, .color = FIMC_FMT_YCRYCB422, .memplanes = 1, .mbus_code = MEDIA_BUS_FMT_YVYU8_2X8, .flags = FMT_FLAGS_YUV, }, { .name = "RAW8 (GRBG)", .fourcc = V4L2_PIX_FMT_SGRBG8, .colorspace = V4L2_COLORSPACE_SRGB, .depth = { 8 }, .color = FIMC_FMT_RAW8, .memplanes = 1, .mbus_code = MEDIA_BUS_FMT_SGRBG8_1X8, .flags = FMT_FLAGS_RAW_BAYER, }, { .name = "RAW10 (GRBG)", .fourcc = V4L2_PIX_FMT_SGRBG10, .colorspace = V4L2_COLORSPACE_SRGB, .depth = { 16 }, .color = FIMC_FMT_RAW10, .memplanes = 1, .mbus_code = MEDIA_BUS_FMT_SGRBG10_1X10, .flags = FMT_FLAGS_RAW_BAYER, }, { .name = "RAW12 (GRBG)", .fourcc = V4L2_PIX_FMT_SGRBG12, .colorspace = V4L2_COLORSPACE_SRGB, .depth = { 16 }, .color = FIMC_FMT_RAW12, .memplanes = 1, .mbus_code = MEDIA_BUS_FMT_SGRBG12_1X12, .flags = FMT_FLAGS_RAW_BAYER, }, }; /** * fimc_lite_find_format - lookup fimc color format by fourcc or media bus code * @pixelformat: fourcc to match, ignored if null * @mbus_code: media bus code to match, ignored if null * @mask: the color format flags to match * @index: index to the fimc_lite_formats array, ignored if negative */ static const struct fimc_fmt *fimc_lite_find_format(const u32 *pixelformat, const u32 *mbus_code, unsigned int mask, int index) { const struct fimc_fmt *fmt, *def_fmt = NULL; unsigned int i; int id = 0; if (index >= (int)ARRAY_SIZE(fimc_lite_formats)) return NULL; for (i = 0; i < ARRAY_SIZE(fimc_lite_formats); ++i) { fmt = &fimc_lite_formats[i]; if (mask && !(fmt->flags & mask)) continue; if (pixelformat && fmt->fourcc == *pixelformat) return fmt; if (mbus_code && fmt->mbus_code == *mbus_code) return fmt; if (index == id) def_fmt = fmt; id++; } return def_fmt; } static int fimc_lite_hw_init(struct fimc_lite *fimc, bool isp_output) { struct fimc_source_info *si; unsigned long flags; if (fimc->sensor == NULL) return -ENXIO; if (fimc->inp_frame.fmt == NULL || fimc->out_frame.fmt == NULL) return -EINVAL; /* Get sensor configuration data from the sensor subdev */ si = v4l2_get_subdev_hostdata(fimc->sensor); if (!si) return -EINVAL; spin_lock_irqsave(&fimc->slock, flags); flite_hw_set_camera_bus(fimc, si); flite_hw_set_source_format(fimc, &fimc->inp_frame); flite_hw_set_window_offset(fimc, &fimc->inp_frame); flite_hw_set_dma_buf_mask(fimc, 0); flite_hw_set_output_dma(fimc, &fimc->out_frame, !isp_output); flite_hw_set_interrupt_mask(fimc); flite_hw_set_test_pattern(fimc, fimc->test_pattern->val); if (debug > 0) flite_hw_dump_regs(fimc, __func__); spin_unlock_irqrestore(&fimc->slock, flags); return 0; } /* * Reinitialize the driver so it is ready to start the streaming again. * Set fimc->state to indicate stream off and the hardware shut down state. * If not suspending (@suspend is false), return any buffers to videobuf2. * Otherwise put any owned buffers onto the pending buffers queue, so they * can be re-spun when the device is being resumed. Also perform FIMC * software reset and disable streaming on the whole pipeline if required. */ static int fimc_lite_reinit(struct fimc_lite *fimc, bool suspend) { struct flite_buffer *buf; unsigned long flags; bool streaming; spin_lock_irqsave(&fimc->slock, flags); streaming = fimc->state & (1 << ST_SENSOR_STREAM); fimc->state &= ~(1 << ST_FLITE_RUN | 1 << ST_FLITE_OFF | 1 << ST_FLITE_STREAM | 1 << ST_SENSOR_STREAM); if (suspend) fimc->state |= (1 << ST_FLITE_SUSPENDED); else fimc->state &= ~(1 << ST_FLITE_PENDING | 1 << ST_FLITE_SUSPENDED); /* Release unused buffers */ while (!suspend && !list_empty(&fimc->pending_buf_q)) { buf = fimc_lite_pending_queue_pop(fimc); vb2_buffer_done(&buf->vb, VB2_BUF_STATE_ERROR); } /* If suspending put unused buffers onto pending queue */ while (!list_empty(&fimc->active_buf_q)) { buf = fimc_lite_active_queue_pop(fimc); if (suspend) fimc_lite_pending_queue_add(fimc, buf); else vb2_buffer_done(&buf->vb, VB2_BUF_STATE_ERROR); } spin_unlock_irqrestore(&fimc->slock, flags); flite_hw_reset(fimc); if (!streaming) return 0; return fimc_pipeline_call(&fimc->ve, set_stream, 0); } static int fimc_lite_stop_capture(struct fimc_lite *fimc, bool suspend) { unsigned long flags; if (!fimc_lite_active(fimc)) return 0; spin_lock_irqsave(&fimc->slock, flags); set_bit(ST_FLITE_OFF, &fimc->state); flite_hw_capture_stop(fimc); spin_unlock_irqrestore(&fimc->slock, flags); wait_event_timeout(fimc->irq_queue, !test_bit(ST_FLITE_OFF, &fimc->state), (2*HZ/10)); /* 200 ms */ return fimc_lite_reinit(fimc, suspend); } /* Must be called with fimc.slock spinlock held. */ static void fimc_lite_config_update(struct fimc_lite *fimc) { flite_hw_set_window_offset(fimc, &fimc->inp_frame); flite_hw_set_dma_window(fimc, &fimc->out_frame); flite_hw_set_test_pattern(fimc, fimc->test_pattern->val); clear_bit(ST_FLITE_CONFIG, &fimc->state); } static irqreturn_t flite_irq_handler(int irq, void *priv) { struct fimc_lite *fimc = priv; struct flite_buffer *vbuf; unsigned long flags; struct timeval *tv; struct timespec ts; u32 intsrc; spin_lock_irqsave(&fimc->slock, flags); intsrc = flite_hw_get_interrupt_source(fimc); flite_hw_clear_pending_irq(fimc); if (test_and_clear_bit(ST_FLITE_OFF, &fimc->state)) { wake_up(&fimc->irq_queue); goto done; } if (intsrc & FLITE_REG_CISTATUS_IRQ_SRC_OVERFLOW) { clear_bit(ST_FLITE_RUN, &fimc->state); fimc->events.data_overflow++; } if (intsrc & FLITE_REG_CISTATUS_IRQ_SRC_LASTCAPEND) { flite_hw_clear_last_capture_end(fimc); clear_bit(ST_FLITE_STREAM, &fimc->state); wake_up(&fimc->irq_queue); } if (atomic_read(&fimc->out_path) != FIMC_IO_DMA) goto done; if ((intsrc & FLITE_REG_CISTATUS_IRQ_SRC_FRMSTART) && test_bit(ST_FLITE_RUN, &fimc->state) && !list_empty(&fimc->pending_buf_q)) { vbuf = fimc_lite_pending_queue_pop(fimc); flite_hw_set_dma_buffer(fimc, vbuf); fimc_lite_active_queue_add(fimc, vbuf); } if ((intsrc & FLITE_REG_CISTATUS_IRQ_SRC_FRMEND) && test_bit(ST_FLITE_RUN, &fimc->state) && !list_empty(&fimc->active_buf_q)) { vbuf = fimc_lite_active_queue_pop(fimc); ktime_get_ts(&ts); tv = &vbuf->vb.v4l2_buf.timestamp; tv->tv_sec = ts.tv_sec; tv->tv_usec = ts.tv_nsec / NSEC_PER_USEC; vbuf->vb.v4l2_buf.sequence = fimc->frame_count++; flite_hw_mask_dma_buffer(fimc, vbuf->index); vb2_buffer_done(&vbuf->vb, VB2_BUF_STATE_DONE); } if (test_bit(ST_FLITE_CONFIG, &fimc->state)) fimc_lite_config_update(fimc); if (list_empty(&fimc->pending_buf_q)) { flite_hw_capture_stop(fimc); clear_bit(ST_FLITE_STREAM, &fimc->state); } done: set_bit(ST_FLITE_RUN, &fimc->state); spin_unlock_irqrestore(&fimc->slock, flags); return IRQ_HANDLED; } static int start_streaming(struct vb2_queue *q, unsigned int count) { struct fimc_lite *fimc = q->drv_priv; unsigned long flags; int ret; spin_lock_irqsave(&fimc->slock, flags); fimc->buf_index = 0; fimc->frame_count = 0; spin_unlock_irqrestore(&fimc->slock, flags); ret = fimc_lite_hw_init(fimc, false); if (ret) { fimc_lite_reinit(fimc, false); return ret; } set_bit(ST_FLITE_PENDING, &fimc->state); if (!list_empty(&fimc->active_buf_q) && !test_and_set_bit(ST_FLITE_STREAM, &fimc->state)) { flite_hw_capture_start(fimc); if (!test_and_set_bit(ST_SENSOR_STREAM, &fimc->state)) fimc_pipeline_call(&fimc->ve, set_stream, 1); } if (debug > 0) flite_hw_dump_regs(fimc, __func__); return 0; } static void stop_streaming(struct vb2_queue *q) { struct fimc_lite *fimc = q->drv_priv; if (!fimc_lite_active(fimc)) return; fimc_lite_stop_capture(fimc, false); } static int queue_setup(struct vb2_queue *vq, const struct v4l2_format *pfmt, unsigned int *num_buffers, unsigned int *num_planes, unsigned int sizes[], void *allocators[]) { const struct v4l2_pix_format_mplane *pixm = NULL; struct fimc_lite *fimc = vq->drv_priv; struct flite_frame *frame = &fimc->out_frame; const struct fimc_fmt *fmt = frame->fmt; unsigned long wh; int i; if (pfmt) { pixm = &pfmt->fmt.pix_mp; fmt = fimc_lite_find_format(&pixm->pixelformat, NULL, 0, -1); wh = pixm->width * pixm->height; } else { wh = frame->f_width * frame->f_height; } if (fmt == NULL) return -EINVAL; *num_planes = fmt->memplanes; for (i = 0; i < fmt->memplanes; i++) { unsigned int size = (wh * fmt->depth[i]) / 8; if (pixm) sizes[i] = max(size, pixm->plane_fmt[i].sizeimage); else sizes[i] = size; allocators[i] = fimc->alloc_ctx; } return 0; } static int buffer_prepare(struct vb2_buffer *vb) { struct vb2_queue *vq = vb->vb2_queue; struct fimc_lite *fimc = vq->drv_priv; int i; if (fimc->out_frame.fmt == NULL) return -EINVAL; for (i = 0; i < fimc->out_frame.fmt->memplanes; i++) { unsigned long size = fimc->payload[i]; if (vb2_plane_size(vb, i) < size) { v4l2_err(&fimc->ve.vdev, "User buffer too small (%ld < %ld)\n", vb2_plane_size(vb, i), size); return -EINVAL; } vb2_set_plane_payload(vb, i, size); } return 0; } static void buffer_queue(struct vb2_buffer *vb) { struct flite_buffer *buf = container_of(vb, struct flite_buffer, vb); struct fimc_lite *fimc = vb2_get_drv_priv(vb->vb2_queue); unsigned long flags; spin_lock_irqsave(&fimc->slock, flags); buf->paddr = vb2_dma_contig_plane_dma_addr(vb, 0); buf->index = fimc->buf_index++; if (fimc->buf_index >= fimc->reqbufs_count) fimc->buf_index = 0; if (!test_bit(ST_FLITE_SUSPENDED, &fimc->state) && !test_bit(ST_FLITE_STREAM, &fimc->state) && list_empty(&fimc->active_buf_q)) { flite_hw_set_dma_buffer(fimc, buf); fimc_lite_active_queue_add(fimc, buf); } else { fimc_lite_pending_queue_add(fimc, buf); } if (vb2_is_streaming(&fimc->vb_queue) && !list_empty(&fimc->pending_buf_q) && !test_and_set_bit(ST_FLITE_STREAM, &fimc->state)) { flite_hw_capture_start(fimc); spin_unlock_irqrestore(&fimc->slock, flags); if (!test_and_set_bit(ST_SENSOR_STREAM, &fimc->state)) fimc_pipeline_call(&fimc->ve, set_stream, 1); return; } spin_unlock_irqrestore(&fimc->slock, flags); } static const struct vb2_ops fimc_lite_qops = { .queue_setup = queue_setup, .buf_prepare = buffer_prepare, .buf_queue = buffer_queue, .wait_prepare = vb2_ops_wait_prepare, .wait_finish = vb2_ops_wait_finish, .start_streaming = start_streaming, .stop_streaming = stop_streaming, }; static void fimc_lite_clear_event_counters(struct fimc_lite *fimc) { unsigned long flags; spin_lock_irqsave(&fimc->slock, flags); memset(&fimc->events, 0, sizeof(fimc->events)); spin_unlock_irqrestore(&fimc->slock, flags); } static int fimc_lite_open(struct file *file) { struct fimc_lite *fimc = video_drvdata(file); struct media_entity *me = &fimc->ve.vdev.entity; int ret; mutex_lock(&fimc->lock); if (atomic_read(&fimc->out_path) != FIMC_IO_DMA) { ret = -EBUSY; goto unlock; } set_bit(ST_FLITE_IN_USE, &fimc->state); ret = pm_runtime_get_sync(&fimc->pdev->dev); if (ret < 0) goto unlock; ret = v4l2_fh_open(file); if (ret < 0) goto err_pm; if (!v4l2_fh_is_singular_file(file) || atomic_read(&fimc->out_path) != FIMC_IO_DMA) goto unlock; mutex_lock(&me->parent->graph_mutex); ret = fimc_pipeline_call(&fimc->ve, open, me, true); /* Mark video pipeline ending at this video node as in use. */ if (ret == 0) me->use_count++; mutex_unlock(&me->parent->graph_mutex); if (!ret) { fimc_lite_clear_event_counters(fimc); goto unlock; } v4l2_fh_release(file); err_pm: pm_runtime_put_sync(&fimc->pdev->dev); clear_bit(ST_FLITE_IN_USE, &fimc->state); unlock: mutex_unlock(&fimc->lock); return ret; } static int fimc_lite_release(struct file *file) { struct fimc_lite *fimc = video_drvdata(file); struct media_entity *entity = &fimc->ve.vdev.entity; mutex_lock(&fimc->lock); if (v4l2_fh_is_singular_file(file) && atomic_read(&fimc->out_path) == FIMC_IO_DMA) { if (fimc->streaming) { media_entity_pipeline_stop(entity); fimc->streaming = false; } fimc_lite_stop_capture(fimc, false); fimc_pipeline_call(&fimc->ve, close); clear_bit(ST_FLITE_IN_USE, &fimc->state); mutex_lock(&entity->parent->graph_mutex); entity->use_count--; mutex_unlock(&entity->parent->graph_mutex); } _vb2_fop_release(file, NULL); pm_runtime_put(&fimc->pdev->dev); clear_bit(ST_FLITE_SUSPENDED, &fimc->state); mutex_unlock(&fimc->lock); return 0; } static const struct v4l2_file_operations fimc_lite_fops = { .owner = THIS_MODULE, .open = fimc_lite_open, .release = fimc_lite_release, .poll = vb2_fop_poll, .unlocked_ioctl = video_ioctl2, .mmap = vb2_fop_mmap, }; /* * Format and crop negotiation helpers */ static const struct fimc_fmt *fimc_lite_subdev_try_fmt(struct fimc_lite *fimc, struct v4l2_subdev_fh *fh, struct v4l2_subdev_format *format) { struct flite_drvdata *dd = fimc->dd; struct v4l2_mbus_framefmt *mf = &format->format; const struct fimc_fmt *fmt = NULL; if (format->pad == FLITE_SD_PAD_SINK) { v4l_bound_align_image(&mf->width, 8, dd->max_width, ffs(dd->out_width_align) - 1, &mf->height, 0, dd->max_height, 0, 0); fmt = fimc_lite_find_format(NULL, &mf->code, 0, 0); if (WARN_ON(!fmt)) return NULL; mf->colorspace = fmt->colorspace; mf->code = fmt->mbus_code; } else { struct flite_frame *sink = &fimc->inp_frame; struct v4l2_mbus_framefmt *sink_fmt; struct v4l2_rect *rect; if (format->which == V4L2_SUBDEV_FORMAT_TRY) { sink_fmt = v4l2_subdev_get_try_format(fh, FLITE_SD_PAD_SINK); mf->code = sink_fmt->code; mf->colorspace = sink_fmt->colorspace; rect = v4l2_subdev_get_try_crop(fh, FLITE_SD_PAD_SINK); } else { mf->code = sink->fmt->mbus_code; mf->colorspace = sink->fmt->colorspace; rect = &sink->rect; } /* Allow changing format only on sink pad */ mf->width = rect->width; mf->height = rect->height; } mf->field = V4L2_FIELD_NONE; v4l2_dbg(1, debug, &fimc->subdev, "code: %#x (%d), %dx%d\n", mf->code, mf->colorspace, mf->width, mf->height); return fmt; } static void fimc_lite_try_crop(struct fimc_lite *fimc, struct v4l2_rect *r) { struct flite_frame *frame = &fimc->inp_frame; v4l_bound_align_image(&r->width, 0, frame->f_width, 0, &r->height, 0, frame->f_height, 0, 0); /* Adjust left/top if cropping rectangle got out of bounds */ r->left = clamp_t(u32, r->left, 0, frame->f_width - r->width); r->left = round_down(r->left, fimc->dd->win_hor_offs_align); r->top = clamp_t(u32, r->top, 0, frame->f_height - r->height); v4l2_dbg(1, debug, &fimc->subdev, "(%d,%d)/%dx%d, sink fmt: %dx%d\n", r->left, r->top, r->width, r->height, frame->f_width, frame->f_height); } static void fimc_lite_try_compose(struct fimc_lite *fimc, struct v4l2_rect *r) { struct flite_frame *frame = &fimc->out_frame; struct v4l2_rect *crop_rect = &fimc->inp_frame.rect; /* Scaling is not supported so we enforce compose rectangle size same as size of the sink crop rectangle. */ r->width = crop_rect->width; r->height = crop_rect->height; /* Adjust left/top if the composing rectangle got out of bounds */ r->left = clamp_t(u32, r->left, 0, frame->f_width - r->width); r->left = round_down(r->left, fimc->dd->out_hor_offs_align); r->top = clamp_t(u32, r->top, 0, fimc->out_frame.f_height - r->height); v4l2_dbg(1, debug, &fimc->subdev, "(%d,%d)/%dx%d, source fmt: %dx%d\n", r->left, r->top, r->width, r->height, frame->f_width, frame->f_height); } /* * Video node ioctl operations */ static int fimc_lite_querycap(struct file *file, void *priv, struct v4l2_capability *cap) { struct fimc_lite *fimc = video_drvdata(file); strlcpy(cap->driver, FIMC_LITE_DRV_NAME, sizeof(cap->driver)); strlcpy(cap->card, FIMC_LITE_DRV_NAME, sizeof(cap->card)); snprintf(cap->bus_info, sizeof(cap->bus_info), "platform:%s", dev_name(&fimc->pdev->dev)); cap->device_caps = V4L2_CAP_STREAMING; cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS; return 0; } static int fimc_lite_enum_fmt_mplane(struct file *file, void *priv, struct v4l2_fmtdesc *f) { const struct fimc_fmt *fmt; if (f->index >= ARRAY_SIZE(fimc_lite_formats)) return -EINVAL; fmt = &fimc_lite_formats[f->index]; strlcpy(f->description, fmt->name, sizeof(f->description)); f->pixelformat = fmt->fourcc; return 0; } static int fimc_lite_g_fmt_mplane(struct file *file, void *fh, struct v4l2_format *f) { struct fimc_lite *fimc = video_drvdata(file); struct v4l2_pix_format_mplane *pixm = &f->fmt.pix_mp; struct v4l2_plane_pix_format *plane_fmt = &pixm->plane_fmt[0]; struct flite_frame *frame = &fimc->out_frame; const struct fimc_fmt *fmt = frame->fmt; plane_fmt->bytesperline = (frame->f_width * fmt->depth[0]) / 8; plane_fmt->sizeimage = plane_fmt->bytesperline * frame->f_height; pixm->num_planes = fmt->memplanes; pixm->pixelformat = fmt->fourcc; pixm->width = frame->f_width; pixm->height = frame->f_height; pixm->field = V4L2_FIELD_NONE; pixm->colorspace = fmt->colorspace; return 0; } static int fimc_lite_try_fmt(struct fimc_lite *fimc, struct v4l2_pix_format_mplane *pixm, const struct fimc_fmt **ffmt) { u32 bpl = pixm->plane_fmt[0].bytesperline; struct flite_drvdata *dd = fimc->dd; const struct fimc_fmt *inp_fmt = fimc->inp_frame.fmt; const struct fimc_fmt *fmt; if (WARN_ON(inp_fmt == NULL)) return -EINVAL; /* * We allow some flexibility only for YUV formats. In case of raw * raw Bayer the FIMC-LITE's output format must match its camera * interface input format. */ if (inp_fmt->flags & FMT_FLAGS_YUV) fmt = fimc_lite_find_format(&pixm->pixelformat, NULL, inp_fmt->flags, 0); else fmt = inp_fmt; if (WARN_ON(fmt == NULL)) return -EINVAL; if (ffmt) *ffmt = fmt; v4l_bound_align_image(&pixm->width, 8, dd->max_width, ffs(dd->out_width_align) - 1, &pixm->height, 0, dd->max_height, 0, 0); if ((bpl == 0 || ((bpl * 8) / fmt->depth[0]) < pixm->width)) pixm->plane_fmt[0].bytesperline = (pixm->width * fmt->depth[0]) / 8; if (pixm->plane_fmt[0].sizeimage == 0) pixm->plane_fmt[0].sizeimage = (pixm->width * pixm->height * fmt->depth[0]) / 8; pixm->num_planes = fmt->memplanes; pixm->pixelformat = fmt->fourcc; pixm->colorspace = fmt->colorspace; pixm->field = V4L2_FIELD_NONE; return 0; } static int fimc_lite_try_fmt_mplane(struct file *file, void *fh, struct v4l2_format *f) { struct fimc_lite *fimc = video_drvdata(file); return fimc_lite_try_fmt(fimc, &f->fmt.pix_mp, NULL); } static int fimc_lite_s_fmt_mplane(struct file *file, void *priv, struct v4l2_format *f) { struct v4l2_pix_format_mplane *pixm = &f->fmt.pix_mp; struct fimc_lite *fimc = video_drvdata(file); struct flite_frame *frame = &fimc->out_frame; const struct fimc_fmt *fmt = NULL; int ret; if (vb2_is_busy(&fimc->vb_queue)) return -EBUSY; ret = fimc_lite_try_fmt(fimc, &f->fmt.pix_mp, &fmt); if (ret < 0) return ret; frame->fmt = fmt; fimc->payload[0] = max((pixm->width * pixm->height * fmt->depth[0]) / 8, pixm->plane_fmt[0].sizeimage); frame->f_width = pixm->width; frame->f_height = pixm->height; return 0; } static int fimc_pipeline_validate(struct fimc_lite *fimc) { struct v4l2_subdev *sd = &fimc->subdev; struct v4l2_subdev_format sink_fmt, src_fmt; struct media_pad *pad; int ret; while (1) { /* Retrieve format at the sink pad */ pad = &sd->entity.pads[0]; if (!(pad->flags & MEDIA_PAD_FL_SINK)) break; /* Don't call FIMC subdev operation to avoid nested locking */ if (sd == &fimc->subdev) { struct flite_frame *ff = &fimc->out_frame; sink_fmt.format.width = ff->f_width; sink_fmt.format.height = ff->f_height; sink_fmt.format.code = fimc->inp_frame.fmt->mbus_code; } else { sink_fmt.pad = pad->index; sink_fmt.which = V4L2_SUBDEV_FORMAT_ACTIVE; ret = v4l2_subdev_call(sd, pad, get_fmt, NULL, &sink_fmt); if (ret < 0 && ret != -ENOIOCTLCMD) return -EPIPE; } /* Retrieve format at the source pad */ pad = media_entity_remote_pad(pad); if (pad == NULL || media_entity_type(pad->entity) != MEDIA_ENT_T_V4L2_SUBDEV) break; sd = media_entity_to_v4l2_subdev(pad->entity); src_fmt.pad = pad->index; src_fmt.which = V4L2_SUBDEV_FORMAT_ACTIVE; ret = v4l2_subdev_call(sd, pad, get_fmt, NULL, &src_fmt); if (ret < 0 && ret != -ENOIOCTLCMD) return -EPIPE; if (src_fmt.format.width != sink_fmt.format.width || src_fmt.format.height != sink_fmt.format.height || src_fmt.format.code != sink_fmt.format.code) return -EPIPE; } return 0; } static int fimc_lite_streamon(struct file *file, void *priv, enum v4l2_buf_type type) { struct fimc_lite *fimc = video_drvdata(file); struct media_entity *entity = &fimc->ve.vdev.entity; int ret; if (fimc_lite_active(fimc)) return -EBUSY; ret = media_entity_pipeline_start(entity, &fimc->ve.pipe->mp); if (ret < 0) return ret; ret = fimc_pipeline_validate(fimc); if (ret < 0) goto err_p_stop; fimc->sensor = fimc_find_remote_sensor(&fimc->subdev.entity); ret = vb2_ioctl_streamon(file, priv, type); if (!ret) { fimc->streaming = true; return ret; } err_p_stop: media_entity_pipeline_stop(entity); return 0; } static int fimc_lite_streamoff(struct file *file, void *priv, enum v4l2_buf_type type) { struct fimc_lite *fimc = video_drvdata(file); int ret; ret = vb2_ioctl_streamoff(file, priv, type); if (ret < 0) return ret; media_entity_pipeline_stop(&fimc->ve.vdev.entity); fimc->streaming = false; return 0; } static int fimc_lite_reqbufs(struct file *file, void *priv, struct v4l2_requestbuffers *reqbufs) { struct fimc_lite *fimc = video_drvdata(file); int ret; reqbufs->count = max_t(u32, FLITE_REQ_BUFS_MIN, reqbufs->count); ret = vb2_ioctl_reqbufs(file, priv, reqbufs); if (!ret) fimc->reqbufs_count = reqbufs->count; return ret; } /* Return 1 if rectangle a is enclosed in rectangle b, or 0 otherwise. */ static int enclosed_rectangle(struct v4l2_rect *a, struct v4l2_rect *b) { if (a->left < b->left || a->top < b->top) return 0; if (a->left + a->width > b->left + b->width) return 0; if (a->top + a->height > b->top + b->height) return 0; return 1; } static int fimc_lite_g_selection(struct file *file, void *fh, struct v4l2_selection *sel) { struct fimc_lite *fimc = video_drvdata(file); struct flite_frame *f = &fimc->out_frame; if (sel->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) return -EINVAL; switch (sel->target) { case V4L2_SEL_TGT_COMPOSE_BOUNDS: case V4L2_SEL_TGT_COMPOSE_DEFAULT: sel->r.left = 0; sel->r.top = 0; sel->r.width = f->f_width; sel->r.height = f->f_height; return 0; case V4L2_SEL_TGT_COMPOSE: sel->r = f->rect; return 0; } return -EINVAL; } static int fimc_lite_s_selection(struct file *file, void *fh, struct v4l2_selection *sel) { struct fimc_lite *fimc = video_drvdata(file); struct flite_frame *f = &fimc->out_frame; struct v4l2_rect rect = sel->r; unsigned long flags; if (sel->type != V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE || sel->target != V4L2_SEL_TGT_COMPOSE) return -EINVAL; fimc_lite_try_compose(fimc, &rect); if ((sel->flags & V4L2_SEL_FLAG_LE) && !enclosed_rectangle(&rect, &sel->r)) return -ERANGE; if ((sel->flags & V4L2_SEL_FLAG_GE) && !enclosed_rectangle(&sel->r, &rect)) return -ERANGE; sel->r = rect; spin_lock_irqsave(&fimc->slock, flags); f->rect = rect; set_bit(ST_FLITE_CONFIG, &fimc->state); spin_unlock_irqrestore(&fimc->slock, flags); return 0; } static const struct v4l2_ioctl_ops fimc_lite_ioctl_ops = { .vidioc_querycap = fimc_lite_querycap, .vidioc_enum_fmt_vid_cap_mplane = fimc_lite_enum_fmt_mplane, .vidioc_try_fmt_vid_cap_mplane = fimc_lite_try_fmt_mplane, .vidioc_s_fmt_vid_cap_mplane = fimc_lite_s_fmt_mplane, .vidioc_g_fmt_vid_cap_mplane = fimc_lite_g_fmt_mplane, .vidioc_g_selection = fimc_lite_g_selection, .vidioc_s_selection = fimc_lite_s_selection, .vidioc_reqbufs = fimc_lite_reqbufs, .vidioc_querybuf = vb2_ioctl_querybuf, .vidioc_prepare_buf = vb2_ioctl_prepare_buf, .vidioc_create_bufs = vb2_ioctl_create_bufs, .vidioc_qbuf = vb2_ioctl_qbuf, .vidioc_dqbuf = vb2_ioctl_dqbuf, .vidioc_streamon = fimc_lite_streamon, .vidioc_streamoff = fimc_lite_streamoff, }; /* Capture subdev media entity operations */ static int fimc_lite_link_setup(struct media_entity *entity, const struct media_pad *local, const struct media_pad *remote, u32 flags) { struct v4l2_subdev *sd = media_entity_to_v4l2_subdev(entity); struct fimc_lite *fimc = v4l2_get_subdevdata(sd); unsigned int remote_ent_type = media_entity_type(remote->entity); int ret = 0; if (WARN_ON(fimc == NULL)) return 0; v4l2_dbg(1, debug, sd, "%s: %s --> %s, flags: 0x%x. source_id: 0x%x\n", __func__, remote->entity->name, local->entity->name, flags, fimc->source_subdev_grp_id); switch (local->index) { case FLITE_SD_PAD_SINK: if (remote_ent_type != MEDIA_ENT_T_V4L2_SUBDEV) { ret = -EINVAL; break; } if (flags & MEDIA_LNK_FL_ENABLED) { if (fimc->source_subdev_grp_id == 0) fimc->source_subdev_grp_id = sd->grp_id; else ret = -EBUSY; } else { fimc->source_subdev_grp_id = 0; fimc->sensor = NULL; } break; case FLITE_SD_PAD_SOURCE_DMA: if (!(flags & MEDIA_LNK_FL_ENABLED)) atomic_set(&fimc->out_path, FIMC_IO_NONE); else if (remote_ent_type == MEDIA_ENT_T_DEVNODE) atomic_set(&fimc->out_path, FIMC_IO_DMA); else ret = -EINVAL; break; case FLITE_SD_PAD_SOURCE_ISP: if (!(flags & MEDIA_LNK_FL_ENABLED)) atomic_set(&fimc->out_path, FIMC_IO_NONE); else if (remote_ent_type == MEDIA_ENT_T_V4L2_SUBDEV) atomic_set(&fimc->out_path, FIMC_IO_ISP); else ret = -EINVAL; break; default: v4l2_err(sd, "Invalid pad index\n"); ret = -EINVAL; } mb(); return ret; } static const struct media_entity_operations fimc_lite_subdev_media_ops = { .link_setup = fimc_lite_link_setup, }; static int fimc_lite_subdev_enum_mbus_code(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh, struct v4l2_subdev_mbus_code_enum *code) { const struct fimc_fmt *fmt; fmt = fimc_lite_find_format(NULL, NULL, 0, code->index); if (!fmt) return -EINVAL; code->code = fmt->mbus_code; return 0; } static struct v4l2_mbus_framefmt *__fimc_lite_subdev_get_try_fmt( struct v4l2_subdev_fh *fh, unsigned int pad) { if (pad != FLITE_SD_PAD_SINK) pad = FLITE_SD_PAD_SOURCE_DMA; return v4l2_subdev_get_try_format(fh, pad); } static int fimc_lite_subdev_get_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh, struct v4l2_subdev_format *fmt) { struct fimc_lite *fimc = v4l2_get_subdevdata(sd); struct v4l2_mbus_framefmt *mf = &fmt->format; struct flite_frame *f = &fimc->inp_frame; if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) { mf = __fimc_lite_subdev_get_try_fmt(fh, fmt->pad); fmt->format = *mf; return 0; } mutex_lock(&fimc->lock); mf->colorspace = f->fmt->colorspace; mf->code = f->fmt->mbus_code; if (fmt->pad == FLITE_SD_PAD_SINK) { /* full camera input frame size */ mf->width = f->f_width; mf->height = f->f_height; } else { /* crop size */ mf->width = f->rect.width; mf->height = f->rect.height; } mutex_unlock(&fimc->lock); return 0; } static int fimc_lite_subdev_set_fmt(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh, struct v4l2_subdev_format *fmt) { struct fimc_lite *fimc = v4l2_get_subdevdata(sd); struct v4l2_mbus_framefmt *mf = &fmt->format; struct flite_frame *sink = &fimc->inp_frame; struct flite_frame *source = &fimc->out_frame; const struct fimc_fmt *ffmt; v4l2_dbg(1, debug, sd, "pad%d: code: 0x%x, %dx%d\n", fmt->pad, mf->code, mf->width, mf->height); mutex_lock(&fimc->lock); if ((atomic_read(&fimc->out_path) == FIMC_IO_ISP && sd->entity.stream_count > 0) || (atomic_read(&fimc->out_path) == FIMC_IO_DMA && vb2_is_busy(&fimc->vb_queue))) { mutex_unlock(&fimc->lock); return -EBUSY; } ffmt = fimc_lite_subdev_try_fmt(fimc, fh, fmt); if (fmt->which == V4L2_SUBDEV_FORMAT_TRY) { struct v4l2_mbus_framefmt *src_fmt; mf = __fimc_lite_subdev_get_try_fmt(fh, fmt->pad); *mf = fmt->format; if (fmt->pad == FLITE_SD_PAD_SINK) { unsigned int pad = FLITE_SD_PAD_SOURCE_DMA; src_fmt = __fimc_lite_subdev_get_try_fmt(fh, pad); *src_fmt = *mf; } mutex_unlock(&fimc->lock); return 0; } if (fmt->pad == FLITE_SD_PAD_SINK) { sink->f_width = mf->width; sink->f_height = mf->height; sink->fmt = ffmt; /* Set sink crop rectangle */ sink->rect.width = mf->width; sink->rect.height = mf->height; sink->rect.left = 0; sink->rect.top = 0; /* Reset source format and crop rectangle */ source->rect = sink->rect; source->f_width = mf->width; source->f_height = mf->height; } mutex_unlock(&fimc->lock); return 0; } static int fimc_lite_subdev_get_selection(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh, struct v4l2_subdev_selection *sel) { struct fimc_lite *fimc = v4l2_get_subdevdata(sd); struct flite_frame *f = &fimc->inp_frame; if ((sel->target != V4L2_SEL_TGT_CROP && sel->target != V4L2_SEL_TGT_CROP_BOUNDS) || sel->pad != FLITE_SD_PAD_SINK) return -EINVAL; if (sel->which == V4L2_SUBDEV_FORMAT_TRY) { sel->r = *v4l2_subdev_get_try_crop(fh, sel->pad); return 0; } mutex_lock(&fimc->lock); if (sel->target == V4L2_SEL_TGT_CROP) { sel->r = f->rect; } else { sel->r.left = 0; sel->r.top = 0; sel->r.width = f->f_width; sel->r.height = f->f_height; } mutex_unlock(&fimc->lock); v4l2_dbg(1, debug, sd, "%s: (%d,%d) %dx%d, f_w: %d, f_h: %d\n", __func__, f->rect.left, f->rect.top, f->rect.width, f->rect.height, f->f_width, f->f_height); return 0; } static int fimc_lite_subdev_set_selection(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh, struct v4l2_subdev_selection *sel) { struct fimc_lite *fimc = v4l2_get_subdevdata(sd); struct flite_frame *f = &fimc->inp_frame; int ret = 0; if (sel->target != V4L2_SEL_TGT_CROP || sel->pad != FLITE_SD_PAD_SINK) return -EINVAL; mutex_lock(&fimc->lock); fimc_lite_try_crop(fimc, &sel->r); if (sel->which == V4L2_SUBDEV_FORMAT_TRY) { *v4l2_subdev_get_try_crop(fh, sel->pad) = sel->r; } else { unsigned long flags; spin_lock_irqsave(&fimc->slock, flags); f->rect = sel->r; /* Same crop rectangle on the source pad */ fimc->out_frame.rect = sel->r; set_bit(ST_FLITE_CONFIG, &fimc->state); spin_unlock_irqrestore(&fimc->slock, flags); } mutex_unlock(&fimc->lock); v4l2_dbg(1, debug, sd, "%s: (%d,%d) %dx%d, f_w: %d, f_h: %d\n", __func__, f->rect.left, f->rect.top, f->rect.width, f->rect.height, f->f_width, f->f_height); return ret; } static int fimc_lite_subdev_s_stream(struct v4l2_subdev *sd, int on) { struct fimc_lite *fimc = v4l2_get_subdevdata(sd); unsigned long flags; int ret; /* * Find sensor subdev linked to FIMC-LITE directly or through * MIPI-CSIS. This is required for configuration where FIMC-LITE * is used as a subdev only and feeds data internally to FIMC-IS. * The pipeline links are protected through entity.stream_count * so there is no need to take the media graph mutex here. */ fimc->sensor = fimc_find_remote_sensor(&sd->entity); if (atomic_read(&fimc->out_path) != FIMC_IO_ISP) return -ENOIOCTLCMD; mutex_lock(&fimc->lock); if (on) { flite_hw_reset(fimc); ret = fimc_lite_hw_init(fimc, true); if (!ret) { spin_lock_irqsave(&fimc->slock, flags); flite_hw_capture_start(fimc); spin_unlock_irqrestore(&fimc->slock, flags); } } else { set_bit(ST_FLITE_OFF, &fimc->state); spin_lock_irqsave(&fimc->slock, flags); flite_hw_capture_stop(fimc); spin_unlock_irqrestore(&fimc->slock, flags); ret = wait_event_timeout(fimc->irq_queue, !test_bit(ST_FLITE_OFF, &fimc->state), msecs_to_jiffies(200)); if (ret == 0) v4l2_err(sd, "s_stream(0) timeout\n"); clear_bit(ST_FLITE_RUN, &fimc->state); } mutex_unlock(&fimc->lock); return ret; } static int fimc_lite_log_status(struct v4l2_subdev *sd) { struct fimc_lite *fimc = v4l2_get_subdevdata(sd); flite_hw_dump_regs(fimc, __func__); return 0; } static int fimc_lite_subdev_registered(struct v4l2_subdev *sd) { struct fimc_lite *fimc = v4l2_get_subdevdata(sd); struct vb2_queue *q = &fimc->vb_queue; struct video_device *vfd = &fimc->ve.vdev; int ret; memset(vfd, 0, sizeof(*vfd)); atomic_set(&fimc->out_path, FIMC_IO_DMA); snprintf(vfd->name, sizeof(vfd->name), "fimc-lite.%d.capture", fimc->index); vfd->fops = &fimc_lite_fops; vfd->ioctl_ops = &fimc_lite_ioctl_ops; vfd->v4l2_dev = sd->v4l2_dev; vfd->minor = -1; vfd->release = video_device_release_empty; vfd->queue = q; fimc->reqbufs_count = 0; INIT_LIST_HEAD(&fimc->pending_buf_q); INIT_LIST_HEAD(&fimc->active_buf_q); memset(q, 0, sizeof(*q)); q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; q->io_modes = VB2_MMAP | VB2_USERPTR; q->ops = &fimc_lite_qops; q->mem_ops = &vb2_dma_contig_memops; q->buf_struct_size = sizeof(struct flite_buffer); q->drv_priv = fimc; q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC; q->lock = &fimc->lock; ret = vb2_queue_init(q); if (ret < 0) return ret; fimc->vd_pad.flags = MEDIA_PAD_FL_SINK; ret = media_entity_init(&vfd->entity, 1, &fimc->vd_pad, 0); if (ret < 0) return ret; video_set_drvdata(vfd, fimc); fimc->ve.pipe = v4l2_get_subdev_hostdata(sd); ret = video_register_device(vfd, VFL_TYPE_GRABBER, -1); if (ret < 0) { media_entity_cleanup(&vfd->entity); fimc->ve.pipe = NULL; return ret; } v4l2_info(sd->v4l2_dev, "Registered %s as /dev/%s\n", vfd->name, video_device_node_name(vfd)); return 0; } static void fimc_lite_subdev_unregistered(struct v4l2_subdev *sd) { struct fimc_lite *fimc = v4l2_get_subdevdata(sd); if (fimc == NULL) return; mutex_lock(&fimc->lock); if (video_is_registered(&fimc->ve.vdev)) { video_unregister_device(&fimc->ve.vdev); media_entity_cleanup(&fimc->ve.vdev.entity); fimc->ve.pipe = NULL; } mutex_unlock(&fimc->lock); } static const struct v4l2_subdev_internal_ops fimc_lite_subdev_internal_ops = { .registered = fimc_lite_subdev_registered, .unregistered = fimc_lite_subdev_unregistered, }; static const struct v4l2_subdev_pad_ops fimc_lite_subdev_pad_ops = { .enum_mbus_code = fimc_lite_subdev_enum_mbus_code, .get_selection = fimc_lite_subdev_get_selection, .set_selection = fimc_lite_subdev_set_selection, .get_fmt = fimc_lite_subdev_get_fmt, .set_fmt = fimc_lite_subdev_set_fmt, }; static const struct v4l2_subdev_video_ops fimc_lite_subdev_video_ops = { .s_stream = fimc_lite_subdev_s_stream, }; static const struct v4l2_subdev_core_ops fimc_lite_core_ops = { .log_status = fimc_lite_log_status, }; static struct v4l2_subdev_ops fimc_lite_subdev_ops = { .core = &fimc_lite_core_ops, .video = &fimc_lite_subdev_video_ops, .pad = &fimc_lite_subdev_pad_ops, }; static int fimc_lite_s_ctrl(struct v4l2_ctrl *ctrl) { struct fimc_lite *fimc = container_of(ctrl->handler, struct fimc_lite, ctrl_handler); set_bit(ST_FLITE_CONFIG, &fimc->state); return 0; } static const struct v4l2_ctrl_ops fimc_lite_ctrl_ops = { .s_ctrl = fimc_lite_s_ctrl, }; static const struct v4l2_ctrl_config fimc_lite_ctrl = { .ops = &fimc_lite_ctrl_ops, .id = V4L2_CTRL_CLASS_USER | 0x1001, .type = V4L2_CTRL_TYPE_BOOLEAN, .name = "Test Pattern 640x480", .step = 1, }; static void fimc_lite_set_default_config(struct fimc_lite *fimc) { struct flite_frame *sink = &fimc->inp_frame; struct flite_frame *source = &fimc->out_frame; sink->fmt = &fimc_lite_formats[0]; sink->f_width = FLITE_DEFAULT_WIDTH; sink->f_height = FLITE_DEFAULT_HEIGHT; sink->rect.width = FLITE_DEFAULT_WIDTH; sink->rect.height = FLITE_DEFAULT_HEIGHT; sink->rect.left = 0; sink->rect.top = 0; *source = *sink; } static int fimc_lite_create_capture_subdev(struct fimc_lite *fimc) { struct v4l2_ctrl_handler *handler = &fimc->ctrl_handler; struct v4l2_subdev *sd = &fimc->subdev; int ret; v4l2_subdev_init(sd, &fimc_lite_subdev_ops); sd->flags |= V4L2_SUBDEV_FL_HAS_DEVNODE; snprintf(sd->name, sizeof(sd->name), "FIMC-LITE.%d", fimc->index); fimc->subdev_pads[FLITE_SD_PAD_SINK].flags = MEDIA_PAD_FL_SINK; fimc->subdev_pads[FLITE_SD_PAD_SOURCE_DMA].flags = MEDIA_PAD_FL_SOURCE; fimc->subdev_pads[FLITE_SD_PAD_SOURCE_ISP].flags = MEDIA_PAD_FL_SOURCE; ret = media_entity_init(&sd->entity, FLITE_SD_PADS_NUM, fimc->subdev_pads, 0); if (ret) return ret; v4l2_ctrl_handler_init(handler, 1); fimc->test_pattern = v4l2_ctrl_new_custom(handler, &fimc_lite_ctrl, NULL); if (handler->error) { media_entity_cleanup(&sd->entity); return handler->error; } sd->ctrl_handler = handler; sd->internal_ops = &fimc_lite_subdev_internal_ops; sd->entity.ops = &fimc_lite_subdev_media_ops; sd->owner = THIS_MODULE; v4l2_set_subdevdata(sd, fimc); return 0; } static void fimc_lite_unregister_capture_subdev(struct fimc_lite *fimc) { struct v4l2_subdev *sd = &fimc->subdev; v4l2_device_unregister_subdev(sd); media_entity_cleanup(&sd->entity); v4l2_ctrl_handler_free(&fimc->ctrl_handler); v4l2_set_subdevdata(sd, NULL); } static void fimc_lite_clk_put(struct fimc_lite *fimc) { if (IS_ERR(fimc->clock)) return; clk_unprepare(fimc->clock); clk_put(fimc->clock); fimc->clock = ERR_PTR(-EINVAL); } static int fimc_lite_clk_get(struct fimc_lite *fimc) { int ret; fimc->clock = clk_get(&fimc->pdev->dev, FLITE_CLK_NAME); if (IS_ERR(fimc->clock)) return PTR_ERR(fimc->clock); ret = clk_prepare(fimc->clock); if (ret < 0) { clk_put(fimc->clock); fimc->clock = ERR_PTR(-EINVAL); } return ret; } static const struct of_device_id flite_of_match[]; static int fimc_lite_probe(struct platform_device *pdev) { struct flite_drvdata *drv_data = NULL; struct device *dev = &pdev->dev; const struct of_device_id *of_id; struct fimc_lite *fimc; struct resource *res; int ret; if (!dev->of_node) return -ENODEV; fimc = devm_kzalloc(dev, sizeof(*fimc), GFP_KERNEL); if (!fimc) return -ENOMEM; of_id = of_match_node(flite_of_match, dev->of_node); if (of_id) drv_data = (struct flite_drvdata *)of_id->data; fimc->index = of_alias_get_id(dev->of_node, "fimc-lite"); if (!drv_data || fimc->index >= drv_data->num_instances || fimc->index < 0) { dev_err(dev, "Wrong %s node alias\n", dev->of_node->full_name); return -EINVAL; } fimc->dd = drv_data; fimc->pdev = pdev; init_waitqueue_head(&fimc->irq_queue); spin_lock_init(&fimc->slock); mutex_init(&fimc->lock); res = platform_get_resource(pdev, IORESOURCE_MEM, 0); fimc->regs = devm_ioremap_resource(dev, res); if (IS_ERR(fimc->regs)) return PTR_ERR(fimc->regs); res = platform_get_resource(pdev, IORESOURCE_IRQ, 0); if (res == NULL) { dev_err(dev, "Failed to get IRQ resource\n"); return -ENXIO; } ret = fimc_lite_clk_get(fimc); if (ret) return ret; ret = devm_request_irq(dev, res->start, flite_irq_handler, 0, dev_name(dev), fimc); if (ret) { dev_err(dev, "Failed to install irq (%d)\n", ret); goto err_clk_put; } /* The video node will be created within the subdev's registered() op */ ret = fimc_lite_create_capture_subdev(fimc); if (ret) goto err_clk_put; platform_set_drvdata(pdev, fimc); pm_runtime_enable(dev); if (!pm_runtime_enabled(dev)) { ret = clk_enable(fimc->clock); if (ret < 0) goto err_sd; } fimc->alloc_ctx = vb2_dma_contig_init_ctx(dev); if (IS_ERR(fimc->alloc_ctx)) { ret = PTR_ERR(fimc->alloc_ctx); goto err_clk_dis; } fimc_lite_set_default_config(fimc); dev_dbg(dev, "FIMC-LITE.%d registered successfully\n", fimc->index); return 0; err_clk_dis: if (!pm_runtime_enabled(dev)) clk_disable(fimc->clock); err_sd: fimc_lite_unregister_capture_subdev(fimc); err_clk_put: fimc_lite_clk_put(fimc); return ret; } #ifdef CONFIG_PM_RUNTIME static int fimc_lite_runtime_resume(struct device *dev) { struct fimc_lite *fimc = dev_get_drvdata(dev); clk_enable(fimc->clock); return 0; } static int fimc_lite_runtime_suspend(struct device *dev) { struct fimc_lite *fimc = dev_get_drvdata(dev); clk_disable(fimc->clock); return 0; } #endif #ifdef CONFIG_PM_SLEEP static int fimc_lite_resume(struct device *dev) { struct fimc_lite *fimc = dev_get_drvdata(dev); struct flite_buffer *buf; unsigned long flags; int i; spin_lock_irqsave(&fimc->slock, flags); if (!test_and_clear_bit(ST_LPM, &fimc->state) || !test_bit(ST_FLITE_IN_USE, &fimc->state)) { spin_unlock_irqrestore(&fimc->slock, flags); return 0; } flite_hw_reset(fimc); spin_unlock_irqrestore(&fimc->slock, flags); if (!test_and_clear_bit(ST_FLITE_SUSPENDED, &fimc->state)) return 0; INIT_LIST_HEAD(&fimc->active_buf_q); fimc_pipeline_call(&fimc->ve, open, &fimc->ve.vdev.entity, false); fimc_lite_hw_init(fimc, atomic_read(&fimc->out_path) == FIMC_IO_ISP); clear_bit(ST_FLITE_SUSPENDED, &fimc->state); for (i = 0; i < fimc->reqbufs_count; i++) { if (list_empty(&fimc->pending_buf_q)) break; buf = fimc_lite_pending_queue_pop(fimc); buffer_queue(&buf->vb); } return 0; } static int fimc_lite_suspend(struct device *dev) { struct fimc_lite *fimc = dev_get_drvdata(dev); bool suspend = test_bit(ST_FLITE_IN_USE, &fimc->state); int ret; if (test_and_set_bit(ST_LPM, &fimc->state)) return 0; ret = fimc_lite_stop_capture(fimc, suspend); if (ret < 0 || !fimc_lite_active(fimc)) return ret; return fimc_pipeline_call(&fimc->ve, close); } #endif /* CONFIG_PM_SLEEP */ static int fimc_lite_remove(struct platform_device *pdev) { struct fimc_lite *fimc = platform_get_drvdata(pdev); struct device *dev = &pdev->dev; pm_runtime_disable(dev); pm_runtime_set_suspended(dev); fimc_lite_unregister_capture_subdev(fimc); vb2_dma_contig_cleanup_ctx(fimc->alloc_ctx); fimc_lite_clk_put(fimc); dev_info(dev, "Driver unloaded\n"); return 0; } static const struct dev_pm_ops fimc_lite_pm_ops = { SET_SYSTEM_SLEEP_PM_OPS(fimc_lite_suspend, fimc_lite_resume) SET_RUNTIME_PM_OPS(fimc_lite_runtime_suspend, fimc_lite_runtime_resume, NULL) }; /* EXYNOS4212, EXYNOS4412 */ static struct flite_drvdata fimc_lite_drvdata_exynos4 = { .max_width = 8192, .max_height = 8192, .out_width_align = 8, .win_hor_offs_align = 2, .out_hor_offs_align = 8, .max_dma_bufs = 1, .num_instances = 2, }; /* EXYNOS5250 */ static struct flite_drvdata fimc_lite_drvdata_exynos5 = { .max_width = 8192, .max_height = 8192, .out_width_align = 8, .win_hor_offs_align = 2, .out_hor_offs_align = 8, .max_dma_bufs = 32, .num_instances = 3, }; static const struct of_device_id flite_of_match[] = { { .compatible = "samsung,exynos4212-fimc-lite", .data = &fimc_lite_drvdata_exynos4, }, { .compatible = "samsung,exynos5250-fimc-lite", .data = &fimc_lite_drvdata_exynos5, }, { /* sentinel */ }, }; MODULE_DEVICE_TABLE(of, flite_of_match); static struct platform_driver fimc_lite_driver = { .probe = fimc_lite_probe, .remove = fimc_lite_remove, .driver = { .of_match_table = flite_of_match, .name = FIMC_LITE_DRV_NAME, .owner = THIS_MODULE, .pm = &fimc_lite_pm_ops, } }; module_platform_driver(fimc_lite_driver); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:" FIMC_LITE_DRV_NAME);
Barracuda09/media_build-bst
linux/drivers/media/platform/exynos4-is/fimc-lite.c
C
gpl-2.0
45,548
/* * PROJECT: ReactOS Kernel * LICENSE: GPL - See COPYING in the top level directory * FILE: ntoskrnl/config/cmcheck.c * PURPOSE: Configuration Manager - Hive and Key Validation * PROGRAMMERS: Alex Ionescu (alex.ionescu@reactos.org) */ /* INCLUDES ******************************************************************/ #include "ntoskrnl.h" #define NDEBUG #include "debug.h" /* GLOBALS *******************************************************************/ /* FUNCTIONS *****************************************************************/ ULONG NTAPI CmCheckRegistry(IN PCMHIVE RegistryHive, IN ULONG Flags) { /* FIXME: HACK! */ DPRINT1("CmCheckRegistry(0x%p, %lu) is UNIMPLEMENTED!\n", RegistryHive, Flags); return 0; }
sunnyden/reactos
ntoskrnl/config/cmcheck.c
C
gpl-2.0
792
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ /* * Copyright (C) 2006 Imendio AB * * 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 St, Fifth Floor, * Boston, MA 02110-1301 USA * * Authors: Richard Hult <richard@imendio.com> */ #include "config.h" #include <string.h> #include <gconf/gconf-client.h> #include <libempathy/empathy-utils.h> #include "empathy-conf.h" #define DEBUG_FLAG EMPATHY_DEBUG_OTHER #include <libempathy/empathy-debug.h> #define EMPATHY_CONF_ROOT "/apps/empathy" #define DESKTOP_INTERFACE_ROOT "/desktop/gnome/interface" #define GET_PRIV(obj) EMPATHY_GET_PRIV (obj, EmpathyConf) typedef struct { GConfClient *gconf_client; } EmpathyConfPriv; typedef struct { EmpathyConf *conf; EmpathyConfNotifyFunc func; gpointer user_data; } EmpathyConfNotifyData; static void conf_finalize (GObject *object); G_DEFINE_TYPE (EmpathyConf, empathy_conf, G_TYPE_OBJECT); static EmpathyConf *global_conf = NULL; static void empathy_conf_class_init (EmpathyConfClass *class) { GObjectClass *object_class; object_class = G_OBJECT_CLASS (class); object_class->finalize = conf_finalize; g_type_class_add_private (object_class, sizeof (EmpathyConfPriv)); } static void empathy_conf_init (EmpathyConf *conf) { EmpathyConfPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (conf, EMPATHY_TYPE_CONF, EmpathyConfPriv); conf->priv = priv; priv->gconf_client = gconf_client_get_default (); gconf_client_add_dir (priv->gconf_client, EMPATHY_CONF_ROOT, GCONF_CLIENT_PRELOAD_ONELEVEL, NULL); gconf_client_add_dir (priv->gconf_client, DESKTOP_INTERFACE_ROOT, GCONF_CLIENT_PRELOAD_NONE, NULL); } static void conf_finalize (GObject *object) { EmpathyConfPriv *priv; priv = GET_PRIV (object); gconf_client_remove_dir (priv->gconf_client, EMPATHY_CONF_ROOT, NULL); gconf_client_remove_dir (priv->gconf_client, DESKTOP_INTERFACE_ROOT, NULL); g_object_unref (priv->gconf_client); G_OBJECT_CLASS (empathy_conf_parent_class)->finalize (object); } EmpathyConf * empathy_conf_get (void) { if (!global_conf) { global_conf = g_object_new (EMPATHY_TYPE_CONF, NULL); } return global_conf; } void empathy_conf_shutdown (void) { if (global_conf) { g_object_unref (global_conf); global_conf = NULL; } } gboolean empathy_conf_set_int (EmpathyConf *conf, const gchar *key, gint value) { EmpathyConfPriv *priv; g_return_val_if_fail (EMPATHY_IS_CONF (conf), FALSE); DEBUG ("Setting int:'%s' to %d", key, value); priv = GET_PRIV (conf); return gconf_client_set_int (priv->gconf_client, key, value, NULL); } gboolean empathy_conf_get_int (EmpathyConf *conf, const gchar *key, gint *value) { EmpathyConfPriv *priv; GError *error = NULL; *value = 0; g_return_val_if_fail (EMPATHY_IS_CONF (conf), FALSE); g_return_val_if_fail (value != NULL, FALSE); priv = GET_PRIV (conf); *value = gconf_client_get_int (priv->gconf_client, key, &error); if (error) { g_error_free (error); return FALSE; } return TRUE; } gboolean empathy_conf_set_bool (EmpathyConf *conf, const gchar *key, gboolean value) { EmpathyConfPriv *priv; g_return_val_if_fail (EMPATHY_IS_CONF (conf), FALSE); DEBUG ("Setting bool:'%s' to %d ---> %s", key, value, value ? "true" : "false"); priv = GET_PRIV (conf); return gconf_client_set_bool (priv->gconf_client, key, value, NULL); } gboolean empathy_conf_get_bool (EmpathyConf *conf, const gchar *key, gboolean *value) { EmpathyConfPriv *priv; GError *error = NULL; *value = FALSE; g_return_val_if_fail (EMPATHY_IS_CONF (conf), FALSE); g_return_val_if_fail (value != NULL, FALSE); priv = GET_PRIV (conf); *value = gconf_client_get_bool (priv->gconf_client, key, &error); if (error) { g_error_free (error); return FALSE; } return TRUE; } gboolean empathy_conf_set_string (EmpathyConf *conf, const gchar *key, const gchar *value) { EmpathyConfPriv *priv; g_return_val_if_fail (EMPATHY_IS_CONF (conf), FALSE); DEBUG ("Setting string:'%s' to '%s'", key, value); priv = GET_PRIV (conf); return gconf_client_set_string (priv->gconf_client, key, value, NULL); } gboolean empathy_conf_get_string (EmpathyConf *conf, const gchar *key, gchar **value) { EmpathyConfPriv *priv; GError *error = NULL; *value = NULL; g_return_val_if_fail (EMPATHY_IS_CONF (conf), FALSE); priv = GET_PRIV (conf); *value = gconf_client_get_string (priv->gconf_client, key, &error); if (error) { g_error_free (error); return FALSE; } return TRUE; } gboolean empathy_conf_set_string_list (EmpathyConf *conf, const gchar *key, GSList *value) { EmpathyConfPriv *priv; g_return_val_if_fail (EMPATHY_IS_CONF (conf), FALSE); priv = GET_PRIV (conf); return gconf_client_set_list (priv->gconf_client, key, GCONF_VALUE_STRING, value, NULL); } gboolean empathy_conf_get_string_list (EmpathyConf *conf, const gchar *key, GSList **value) { EmpathyConfPriv *priv; GError *error = NULL; *value = NULL; g_return_val_if_fail (EMPATHY_IS_CONF (conf), FALSE); priv = GET_PRIV (conf); *value = gconf_client_get_list (priv->gconf_client, key, GCONF_VALUE_STRING, &error); if (error) { g_error_free (error); return FALSE; } return TRUE; } static void conf_notify_data_free (EmpathyConfNotifyData *data) { g_object_unref (data->conf); g_slice_free (EmpathyConfNotifyData, data); } static void conf_notify_func (GConfClient *client, guint id, GConfEntry *entry, gpointer user_data) { EmpathyConfNotifyData *data; data = user_data; data->func (data->conf, gconf_entry_get_key (entry), data->user_data); } guint empathy_conf_notify_add (EmpathyConf *conf, const gchar *key, EmpathyConfNotifyFunc func, gpointer user_data) { EmpathyConfPriv *priv; guint id; EmpathyConfNotifyData *data; g_return_val_if_fail (EMPATHY_IS_CONF (conf), 0); priv = GET_PRIV (conf); data = g_slice_new (EmpathyConfNotifyData); data->func = func; data->user_data = user_data; data->conf = g_object_ref (conf); id = gconf_client_notify_add (priv->gconf_client, key, conf_notify_func, data, (GFreeFunc) conf_notify_data_free, NULL); return id; } gboolean empathy_conf_notify_remove (EmpathyConf *conf, guint id) { EmpathyConfPriv *priv; g_return_val_if_fail (EMPATHY_IS_CONF (conf), FALSE); priv = GET_PRIV (conf); gconf_client_notify_remove (priv->gconf_client, id); return TRUE; }
jmansar/empathy
libempathy-gtk/empathy-conf.c
C
gpl-2.0
7,566
<?php require_once('../conexiones/conexione.php'); mysql_select_db($base_datos, $conectar); date_default_timezone_set("America/Bogota"); include ("../registro_movimientos/registro_movimientos.php"); //$cod_factura = $_GET['cod_factura']; $fecha_ini = $_GET['fecha_ini']; $fecha_fin = $_GET['fecha_fin']; $tabla = $_GET['tabla']; $tipo = $_GET['tipo']; $fecha = date("Y/m/d"); $hora = date("H:i:s"); $salida = ""; $nombre = $tabla.'_'.$fecha.'_Hora_'.$hora.'-'.$tipo.'-'.$fecha_ini.'-'.$fecha_fin.'.csv'; $sql = mysql_query("SELECT * FROM $tabla WHERE fecha_anyo BETWEEN '$fecha_ini' AND '$fecha_fin'"); $total_columnas = mysql_num_fields($sql); // Obtener El Nombre de Campo /* for ($i = 0; $i < $total_columnas; $i++) { $encabezado = mysql_field_name($sql, $i); $salida .= '"'.$encabezado.'",'; } $salida .="\n"; */ // Obtener los Registros de la tabla while ($datos = mysql_fetch_array($sql)) { for ($i = 0; $i < $total_columnas; $i++) { $salida .=''.$datos["$i"].','; //$salida .='"'.$datos["$i"].'",'; } $salida .="\n"; } // DESCARGAR ARCHIVO header('Content-type: application/csv'); header('Content-Disposition: attachment; filename='.$nombre); echo $salida; exit; ?>
dataxe/proyectos
panashopping/admin/descargar_factura_externa_temporal_archivo_csv_por_dias.php
PHP
gpl-3.0
1,184
<html lang="en"> <head> <title>GDB/MI Ada Tasking Commands - Debugging with GDB</title> <meta http-equiv="Content-Type" content="text/html"> <meta name="description" content="Debugging with GDB"> <meta name="generator" content="makeinfo 4.11"> <link title="Top" rel="start" href="index.html#Top"> <link rel="up" href="GDB_002fMI.html#GDB_002fMI" title="GDB/MI"> <link rel="prev" href="GDB_002fMI-Thread-Commands.html#GDB_002fMI-Thread-Commands" title="GDB/MI Thread Commands"> <link rel="next" href="GDB_002fMI-Program-Execution.html#GDB_002fMI-Program-Execution" title="GDB/MI Program Execution"> <link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage"> <!-- Copyright (C) 1988-2015 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with the Invariant Sections being ``Free Software'' and ``Free Software Needs Free Documentation'', with the Front-Cover Texts being ``A GNU Manual,'' and with the Back-Cover Texts as in (a) below. (a) The FSF's Back-Cover Text is: ``You are free to copy and modify this GNU Manual. Buying copies from GNU Press supports the FSF in developing GNU and promoting software freedom.'' --> <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"><!-- pre.display { font-family:inherit } pre.format { font-family:inherit } pre.smalldisplay { font-family:inherit; font-size:smaller } pre.smallformat { font-family:inherit; font-size:smaller } pre.smallexample { font-size:smaller } pre.smalllisp { font-size:smaller } span.sc { font-variant:small-caps } span.roman { font-family:serif; font-weight:normal; } span.sansserif { font-family:sans-serif; font-weight:normal; } --></style> </head> <body> <div class="node"> <p> <a name="GDB%2fMI-Ada-Tasking-Commands"></a> <a name="GDB_002fMI-Ada-Tasking-Commands"></a> Next:&nbsp;<a rel="next" accesskey="n" href="GDB_002fMI-Program-Execution.html#GDB_002fMI-Program-Execution">GDB/MI Program Execution</a>, Previous:&nbsp;<a rel="previous" accesskey="p" href="GDB_002fMI-Thread-Commands.html#GDB_002fMI-Thread-Commands">GDB/MI Thread Commands</a>, Up:&nbsp;<a rel="up" accesskey="u" href="GDB_002fMI.html#GDB_002fMI">GDB/MI</a> <hr> </div> <h3 class="section">27.12 <span class="sc">gdb/mi</span> Ada Tasking Commands</h3> <h4 class="subheading">The <code>-ada-task-info</code> Command</h4> <p><a name="index-g_t_002dada_002dtask_002dinfo-2898"></a> <h5 class="subsubheading">Synopsis</h5> <pre class="smallexample"> -ada-task-info [ <var>task-id</var> ] </pre> <p>Reports information about either a specific Ada task, if the <var>task-id</var> parameter is present, or about all Ada tasks. <h5 class="subsubheading"><span class="sc">gdb</span> Command</h5> <p>The &lsquo;<samp><span class="samp">info tasks</span></samp>&rsquo; command prints the same information about all Ada tasks (see <a href="Ada-Tasks.html#Ada-Tasks">Ada Tasks</a>). <h5 class="subsubheading">Result</h5> <p>The result is a table of Ada tasks. The following columns are defined for each Ada task: <dl> <dt>&lsquo;<samp><span class="samp">current</span></samp>&rsquo;<dd>This field exists only for the current thread. It has the value &lsquo;<samp><span class="samp">*</span></samp>&rsquo;. <br><dt>&lsquo;<samp><span class="samp">id</span></samp>&rsquo;<dd>The identifier that <span class="sc">gdb</span> uses to refer to the Ada task. <br><dt>&lsquo;<samp><span class="samp">task-id</span></samp>&rsquo;<dd>The identifier that the target uses to refer to the Ada task. <br><dt>&lsquo;<samp><span class="samp">thread-id</span></samp>&rsquo;<dd>The identifier of the thread corresponding to the Ada task. <p>This field should always exist, as Ada tasks are always implemented on top of a thread. But if <span class="sc">gdb</span> cannot find this corresponding thread for any reason, the field is omitted. <br><dt>&lsquo;<samp><span class="samp">parent-id</span></samp>&rsquo;<dd>This field exists only when the task was created by another task. In this case, it provides the ID of the parent task. <br><dt>&lsquo;<samp><span class="samp">priority</span></samp>&rsquo;<dd>The base priority of the task. <br><dt>&lsquo;<samp><span class="samp">state</span></samp>&rsquo;<dd>The current state of the task. For a detailed description of the possible states, see <a href="Ada-Tasks.html#Ada-Tasks">Ada Tasks</a>. <br><dt>&lsquo;<samp><span class="samp">name</span></samp>&rsquo;<dd>The name of the task. </dl> <h5 class="subsubheading">Example</h5> <pre class="smallexample"> -ada-task-info ^done,tasks={nr_rows="3",nr_cols="8", hdr=[{width="1",alignment="-1",col_name="current",colhdr=""}, {width="3",alignment="1",col_name="id",colhdr="ID"}, {width="9",alignment="1",col_name="task-id",colhdr="TID"}, {width="4",alignment="1",col_name="thread-id",colhdr=""}, {width="4",alignment="1",col_name="parent-id",colhdr="P-ID"}, {width="3",alignment="1",col_name="priority",colhdr="Pri"}, {width="22",alignment="-1",col_name="state",colhdr="State"}, {width="1",alignment="2",col_name="name",colhdr="Name"}], body=[{current="*",id="1",task-id=" 644010",thread-id="1",priority="48", state="Child Termination Wait",name="main_task"}]} (gdb) </pre> <!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%% SECTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% --> </body></html>
FabianKnapp/nexmon
buildtools/gcc-arm-none-eabi-5_4-2016q2-linux-x86/share/doc/gcc-arm-none-eabi/html/gdb/GDB_002fMI-Ada-Tasking-Commands.html
HTML
gpl-3.0
5,607
<html lang="en"> <head> <title>sin - Untitled</title> <meta http-equiv="Content-Type" content="text/html"> <meta name="description" content="Untitled"> <meta name="generator" content="makeinfo 4.11"> <link title="Top" rel="start" href="index.html#Top"> <link rel="up" href="Math.html#Math" title="Math"> <link rel="prev" href="signbit.html#signbit" title="signbit"> <link rel="next" href="sinh.html#sinh" title="sinh"> <link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage"> <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"><!-- pre.display { font-family:inherit } pre.format { font-family:inherit } pre.smalldisplay { font-family:inherit; font-size:smaller } pre.smallformat { font-family:inherit; font-size:smaller } pre.smallexample { font-size:smaller } pre.smalllisp { font-size:smaller } span.sc { font-variant:small-caps } span.roman { font-family:serif; font-weight:normal; } span.sansserif { font-family:sans-serif; font-weight:normal; } --></style> </head> <body> <div class="node"> <p> <a name="sin"></a> Next:&nbsp;<a rel="next" accesskey="n" href="sinh.html#sinh">sinh</a>, Previous:&nbsp;<a rel="previous" accesskey="p" href="signbit.html#signbit">signbit</a>, Up:&nbsp;<a rel="up" accesskey="u" href="Math.html#Math">Math</a> <hr> </div> <h3 class="section">1.54 <code>sin</code>, <code>sinf</code>, <code>cos</code>, <code>cosf</code>&mdash;sine or cosine</h3> <p><a name="index-sin-144"></a><a name="index-sinf-145"></a><a name="index-cos-146"></a><a name="index-cosf-147"></a><strong>Synopsis</strong> <pre class="example"> #include &lt;math.h&gt; double sin(double <var>x</var>); float sinf(float <var>x</var>); double cos(double <var>x</var>); float cosf(float <var>x</var>); </pre> <p><strong>Description</strong><br> <code>sin</code> and <code>cos</code> compute (respectively) the sine and cosine of the argument <var>x</var>. Angles are specified in radians. <p><code>sinf</code> and <code>cosf</code> are identical, save that they take and return <code>float</code> values. <pre class="sp"> </pre> <strong>Returns</strong><br> The sine or cosine of <var>x</var> is returned. <pre class="sp"> </pre> <strong>Portability</strong><br> <code>sin</code> and <code>cos</code> are ANSI C. <code>sinf</code> and <code>cosf</code> are extensions. <pre class="sp"> </pre> </body></html>
seemoo-lab/nexmon
buildtools/gcc-arm-none-eabi-5_4-2016q2-linux-x86/share/doc/gcc-arm-none-eabi/html/libm/sin.html
HTML
gpl-3.0
2,465
/* GIMP - The GNU Image Manipulation Program * Copyright (C) 1995-2002 Spencer Kimball, Peter Mattis, and others * * gimp-gradients.c * Copyright (C) 2002 Michael Natterer <mitch@gimp.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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "config.h" #include <gegl.h> #include "core-types.h" #include "gimp.h" #include "gimp-gradients.h" #include "gimpcontext.h" #include "gimpcontainer.h" #include "gimpdatafactory.h" #include "gimpgradient.h" #include "gimp-intl.h" #define FG_BG_RGB_KEY "gimp-gradient-fg-bg-rgb" #define FG_BG_HARDEDGE_KEY "gimp-gradient-fg-bg-rgb" #define FG_BG_HSV_CCW_KEY "gimp-gradient-fg-bg-hsv-ccw" #define FG_BG_HSV_CW_KEY "gimp-gradient-fg-bg-hsv-cw" #define FG_TRANSPARENT_KEY "gimp-gradient-fg-transparent" /* local function prototypes */ static GimpGradient * gimp_gradients_add_gradient (Gimp *gimp, const gchar *name, const gchar *id); /* public functions */ void gimp_gradients_init (Gimp *gimp) { GimpGradient *gradient; g_return_if_fail (GIMP_IS_GIMP (gimp)); /* FG to BG (RGB) */ gradient = gimp_gradients_add_gradient (gimp, _("FG to BG (RGB)"), FG_BG_RGB_KEY); gradient->segments->left_color_type = GIMP_GRADIENT_COLOR_FOREGROUND; gradient->segments->right_color_type = GIMP_GRADIENT_COLOR_BACKGROUND; gimp_context_set_gradient (gimp->user_context, gradient); /* FG to BG (Hardedge) */ gradient = gimp_gradients_add_gradient (gimp, _("FG to BG (Hardedge)"), FG_BG_HARDEDGE_KEY); gradient->segments->left = 0.00; gradient->segments->middle = 0.25; gradient->segments->right = 0.50; gradient->segments->left_color_type = GIMP_GRADIENT_COLOR_FOREGROUND; gradient->segments->right_color_type = GIMP_GRADIENT_COLOR_FOREGROUND; gradient->segments->next = gimp_gradient_segment_new (); gradient->segments->next->prev = gradient->segments; gradient->segments->next->left = 0.50; gradient->segments->next->middle = 0.75; gradient->segments->next->right = 1.00; gradient->segments->next->left_color_type = GIMP_GRADIENT_COLOR_BACKGROUND; gradient->segments->next->right_color_type = GIMP_GRADIENT_COLOR_BACKGROUND; /* FG to BG (HSV counter-clockwise) */ gradient = gimp_gradients_add_gradient (gimp, _("FG to BG (HSV counter-clockwise)"), FG_BG_HSV_CCW_KEY); gradient->segments->left_color_type = GIMP_GRADIENT_COLOR_FOREGROUND; gradient->segments->right_color_type = GIMP_GRADIENT_COLOR_BACKGROUND; gradient->segments->color = GIMP_GRADIENT_SEGMENT_HSV_CCW; /* FG to BG (HSV clockwise hue) */ gradient = gimp_gradients_add_gradient (gimp, _("FG to BG (HSV clockwise hue)"), FG_BG_HSV_CW_KEY); gradient->segments->left_color_type = GIMP_GRADIENT_COLOR_FOREGROUND; gradient->segments->right_color_type = GIMP_GRADIENT_COLOR_BACKGROUND; gradient->segments->color = GIMP_GRADIENT_SEGMENT_HSV_CW; /* FG to Transparent */ gradient = gimp_gradients_add_gradient (gimp, _("FG to Transparent"), FG_TRANSPARENT_KEY); gradient->segments->left_color_type = GIMP_GRADIENT_COLOR_FOREGROUND; gradient->segments->right_color_type = GIMP_GRADIENT_COLOR_FOREGROUND_TRANSPARENT; } /* private functions */ static GimpGradient * gimp_gradients_add_gradient (Gimp *gimp, const gchar *name, const gchar *id) { GimpGradient *gradient; gradient = GIMP_GRADIENT (gimp_gradient_new (gimp_get_user_context (gimp), name)); gimp_data_make_internal (GIMP_DATA (gradient), id); gimp_container_add (gimp_data_factory_get_container (gimp->gradient_factory), GIMP_OBJECT (gradient)); g_object_unref (gradient); g_object_set_data (G_OBJECT (gimp), id, gradient); return gradient; }
mskala/noxcf-gimp
app/core/gimp-gradients.c
C
gpl-3.0
5,035
obj-$(CONFIG_ECS_DRIVER) += ecs-core.o obj-$(CONFIG_ECS_DRIVER_SUBDEV) += ecs-subdev.o ecs-helper.o obj-$(CONFIG_SOC_CAMERA_OV5640_ECS) += ov5640.o obj-$(CONFIG_SOC_CAMERA_SP0A20_ECS) += sp0a20.o
AKuHAK/xcover3ltexx_custom_kernel
drivers/media/i2c/ecs/Makefile
Makefile
gpl-3.0
198
# # functions to use with HP Hardware RAID (Smart Array and compatible) # # function define_HPSSACLI() { # HP Smart Storage Administrator CLI is either hpacucli, hpssacli or ssacli if has_binary hpacucli ; then HPSSACLI=hpacucli elif has_binary hpssacli ; then HPSSACLI=hpssacli elif has_binary ssacli ; then HPSSACLI=ssacli fi } function find_array_from_drive() { # call $HPSSACLI for the slot $1 and find the array that contains the drive $2 while read ; do case $REPLY in *array*) ARRAY="${REPLY##*array }" ARRAY="${ARRAY%% *}" ;; *drive*$2*) echo $ARRAY return 0 ;; esac done < <($HPSSACLI ctrl slot=$1 show config) return 1 # here we come only if we did not find the drive }
phracek/rear
usr/share/rear/lib/hp_raid-functions.sh
Shell
gpl-3.0
871
# (C) British Crown Copyright 2014 - 2015, Met Office # # This file is part of Iris. # # Iris 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. # # Iris 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 Iris. If not, see <http://www.gnu.org/licenses/>. """Unit tests for the `iris.quickplot.points` function.""" from __future__ import (absolute_import, division, print_function) from six.moves import (filter, input, map, range, zip) # noqa # Import iris.tests first so that some things can be initialised before # importing anything else. import iris.tests as tests from iris.tests.unit.plot import TestGraphicStringCoord if tests.MPL_AVAILABLE: import iris.quickplot as qplt @tests.skip_plot class TestStringCoordPlot(TestGraphicStringCoord): def test_yaxis_labels(self): qplt.points(self.cube, coords=('bar', 'str_coord')) self.assertBoundsTickLabels('yaxis') def test_xaxis_labels(self): qplt.points(self.cube, coords=('str_coord', 'bar')) self.assertBoundsTickLabels('xaxis') if __name__ == "__main__": tests.main()
decvalts/iris
lib/iris/tests/unit/quickplot/test_points.py
Python
gpl-3.0
1,543
package com.laytonsmith.abstraction; import com.laytonsmith.abstraction.enums.MCDisplaySlot; import java.util.Set; public interface MCScoreboard { public void clearSlot(MCDisplaySlot slot); public MCObjective getObjective(MCDisplaySlot slot); public MCObjective getObjective(String name); /** * * @return Set of all objectives on this scoreboard */ public Set<MCObjective> getObjectives(); public Set<MCObjective> getObjectivesByCriteria(String criteria); /** * * @return Set of all players tracked by this scoreboard */ public Set<String> getEntries(); public MCTeam getPlayerTeam(MCOfflinePlayer player); public Set<MCScore> getScores(String entry); public MCTeam getTeam(String teamName); public Set<MCTeam> getTeams(); public MCObjective registerNewObjective(String name, String criteria); public MCTeam registerNewTeam(String name); public void resetScores(String entry); }
Murreey/CommandHelper
src/main/java/com/laytonsmith/abstraction/MCScoreboard.java
Java
gpl-3.0
908
#pragma once #include <wrl.h> namespace DX { // Helper class for animation and simulation timing. class StepTimer { public: StepTimer() : m_elapsedTicks(0), m_totalTicks(0), m_leftOverTicks(0), m_frameCount(0), m_framesPerSecond(0), m_framesThisSecond(0), m_qpcSecondCounter(0), m_isFixedTimeStep(false), m_targetElapsedTicks(TicksPerSecond / 60) { if (!QueryPerformanceFrequency(&m_qpcFrequency)) { throw ref new Platform::FailureException(); } if (!QueryPerformanceCounter(&m_qpcLastTime)) { throw ref new Platform::FailureException(); } // Initialize max delta to 1/10 of a second. m_qpcMaxDelta = m_qpcFrequency.QuadPart / 10; } // Get elapsed time since the previous Update call. uint64 GetElapsedTicks() const { return m_elapsedTicks; } double GetElapsedSeconds() const { return TicksToSeconds(m_elapsedTicks); } // Get total time since the start of the program. uint64 GetTotalTicks() const { return m_totalTicks; } double GetTotalSeconds() const { return TicksToSeconds(m_totalTicks); } // Get total number of updates since start of the program. uint32 GetFrameCount() const { return m_frameCount; } // Get the current framerate. uint32 GetFramesPerSecond() const { return m_framesPerSecond; } // Set whether to use fixed or variable timestep mode. void SetFixedTimeStep(bool isFixedTimestep) { m_isFixedTimeStep = isFixedTimestep; } // Set how often to call Update when in fixed timestep mode. void SetTargetElapsedTicks(uint64 targetElapsed) { m_targetElapsedTicks = targetElapsed; } void SetTargetElapsedSeconds(double targetElapsed) { m_targetElapsedTicks = SecondsToTicks(targetElapsed); } // Integer format represents time using 10,000,000 ticks per second. static const uint64 TicksPerSecond = 10000000; static double TicksToSeconds(uint64 ticks) { return static_cast<double>(ticks) / TicksPerSecond; } static uint64 SecondsToTicks(double seconds) { return static_cast<uint64>(seconds * TicksPerSecond); } // After an intentional timing discontinuity (for instance a blocking IO operation) // call this to avoid having the fixed timestep logic attempt a set of catch-up // Update calls. void ResetElapsedTime() { if (!QueryPerformanceCounter(&m_qpcLastTime)) { throw ref new Platform::FailureException(); } m_leftOverTicks = 0; m_framesPerSecond = 0; m_framesThisSecond = 0; m_qpcSecondCounter = 0; } // Update timer state, calling the specified Update function the appropriate number of times. template<typename TUpdate> void Tick(const TUpdate& update) { // Query the current time. LARGE_INTEGER currentTime; if (!QueryPerformanceCounter(&currentTime)) { throw ref new Platform::FailureException(); } uint64 timeDelta = currentTime.QuadPart - m_qpcLastTime.QuadPart; m_qpcLastTime = currentTime; m_qpcSecondCounter += timeDelta; // Clamp excessively large time deltas (e.g. after paused in the debugger). if (timeDelta > m_qpcMaxDelta) { timeDelta = m_qpcMaxDelta; } // Convert QPC units into a canonical tick format. This cannot overflow due to the previous clamp. timeDelta *= TicksPerSecond; timeDelta /= m_qpcFrequency.QuadPart; uint32 lastFrameCount = m_frameCount; if (m_isFixedTimeStep) { // Fixed timestep update logic // If the app is running very close to the target elapsed time (within 1/4 of a millisecond) just clamp // the clock to exactly match the target value. This prevents tiny and irrelevant errors // from accumulating over time. Without this clamping, a game that requested a 60 fps // fixed update, running with vsync enabled on a 59.94 NTSC display, would eventually // accumulate enough tiny errors that it would drop a frame. It is better to just round // small deviations down to zero to leave things running smoothly. if (abs(static_cast<int64>(timeDelta - m_targetElapsedTicks)) < TicksPerSecond / 4000) { timeDelta = m_targetElapsedTicks; } m_leftOverTicks += timeDelta; while (m_leftOverTicks >= m_targetElapsedTicks) { m_elapsedTicks = m_targetElapsedTicks; m_totalTicks += m_targetElapsedTicks; m_leftOverTicks -= m_targetElapsedTicks; m_frameCount++; update(); } } else { // Variable timestep update logic. m_elapsedTicks = timeDelta; m_totalTicks += timeDelta; m_leftOverTicks = 0; m_frameCount++; update(); } // Track the current framerate. if (m_frameCount != lastFrameCount) { m_framesThisSecond++; } if (m_qpcSecondCounter >= static_cast<uint64>(m_qpcFrequency.QuadPart)) { m_framesPerSecond = m_framesThisSecond; m_framesThisSecond = 0; m_qpcSecondCounter %= m_qpcFrequency.QuadPart; } } private: // Source timing data uses QPC units. LARGE_INTEGER m_qpcFrequency; LARGE_INTEGER m_qpcLastTime; uint64 m_qpcMaxDelta; // Derived timing data uses a canonical tick format. uint64 m_elapsedTicks; uint64 m_totalTicks; uint64 m_leftOverTicks; // Members for tracking the framerate. uint32 m_frameCount; uint32 m_framesPerSecond; uint32 m_framesThisSecond; uint64 m_qpcSecondCounter; // Members for configuring fixed timestep mode. bool m_isFixedTimeStep; uint64 m_targetElapsedTicks; }; }
ruzzgames/BlindFate
windows/Common/StepTimer.h
C
gpl-3.0
5,607
/* This file is part of cpp-ethereum. cpp-ethereum 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. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Christian <c@ethdev.com> * @date 2014 * Solidity AST to EVM bytecode compiler. */ #pragma once #include <ostream> #include <functional> #include <libsolidity/ASTVisitor.h> #include <libsolidity/CompilerContext.h> #include <libevmasm/Assembly.h> namespace dev { namespace solidity { class Compiler: private ASTConstVisitor { public: explicit Compiler(bool _optimize = false, unsigned _runs = 200): m_optimize(_optimize), m_optimizeRuns(_runs), m_context(), m_returnTag(m_context.newTag()) { } void compileContract(ContractDefinition const& _contract, std::map<ContractDefinition const*, bytes const*> const& _contracts); bytes getAssembledBytecode() { return m_context.getAssembledBytecode(); } bytes getRuntimeBytecode() { return m_context.getAssembledRuntimeBytecode(m_runtimeSub); } /// @arg _sourceCodes is the map of input files to source code strings /// @arg _inJsonFromat shows whether the out should be in Json format Json::Value streamAssembly(std::ostream& _stream, StringMap const& _sourceCodes = StringMap(), bool _inJsonFormat = false) const { return m_context.streamAssembly(_stream, _sourceCodes, _inJsonFormat); } /// @returns Assembly items of the normal compiler context eth::AssemblyItems const& getAssemblyItems() const { return m_context.getAssembly().getItems(); } /// @returns Assembly items of the runtime compiler context eth::AssemblyItems const& getRuntimeAssemblyItems() const { return m_context.getAssembly().getSub(m_runtimeSub).getItems(); } /// @returns the entry label of the given function. Might return an AssemblyItem of type /// UndefinedItem if it does not exist yet. eth::AssemblyItem getFunctionEntryLabel(FunctionDefinition const& _function) const; private: /// Registers the non-function objects inside the contract with the context. void initializeContext(ContractDefinition const& _contract, std::map<ContractDefinition const*, bytes const*> const& _contracts); /// Adds the code that is run at creation time. Should be run after exchanging the run-time context /// with a new and initialized context. Adds the constructor code. void packIntoContractCreator(ContractDefinition const& _contract, CompilerContext const& _runtimeContext); void appendBaseConstructor(FunctionDefinition const& _constructor); void appendConstructor(FunctionDefinition const& _constructor); void appendFunctionSelector(ContractDefinition const& _contract); /// Creates code that unpacks the arguments for the given function represented by a vector of TypePointers. /// From memory if @a _fromMemory is true, otherwise from call data. /// Expects source offset on the stack. void appendCalldataUnpacker( TypePointers const& _typeParameters, bool _fromMemory = false, u256 _startOffset = u256(-1) ); void appendReturnValuePacker(TypePointers const& _typeParameters); void registerStateVariables(ContractDefinition const& _contract); void initializeStateVariables(ContractDefinition const& _contract); /// Initialises all memory arrays in the local variables to point to an empty location. void initialiseMemoryArrays(std::vector<VariableDeclaration const*> _variables); /// Pushes the initialised value of the given type to the stack. If the type is a memory /// reference type, allocates memory and pushes the memory pointer. /// Not to be used for storage references. void initialiseInMemory(Type const& _type); virtual bool visit(VariableDeclaration const& _variableDeclaration) override; virtual bool visit(FunctionDefinition const& _function) override; virtual bool visit(IfStatement const& _ifStatement) override; virtual bool visit(WhileStatement const& _whileStatement) override; virtual bool visit(ForStatement const& _forStatement) override; virtual bool visit(Continue const& _continue) override; virtual bool visit(Break const& _break) override; virtual bool visit(Return const& _return) override; virtual bool visit(VariableDeclarationStatement const& _variableDeclarationStatement) override; virtual bool visit(ExpressionStatement const& _expressionStatement) override; virtual bool visit(PlaceholderStatement const&) override; /// Appends one layer of function modifier code of the current function, or the function /// body itself if the last modifier was reached. void appendModifierOrFunctionCode(); void appendStackVariableInitialisation(VariableDeclaration const& _variable); void compileExpression(Expression const& _expression, TypePointer const& _targetType = TypePointer()); bool const m_optimize; unsigned const m_optimizeRuns; CompilerContext m_context; size_t m_runtimeSub = size_t(-1); ///< Identifier of the runtime sub-assembly CompilerContext m_runtimeContext; std::vector<eth::AssemblyItem> m_breakTags; ///< tag to jump to for a "break" statement std::vector<eth::AssemblyItem> m_continueTags; ///< tag to jump to for a "continue" statement eth::AssemblyItem m_returnTag; ///< tag to jump to for a "return" statement unsigned m_modifierDepth = 0; FunctionDefinition const* m_currentFunction = nullptr; unsigned m_stackCleanupForReturn = 0; ///< this number of stack elements need to be removed before jump to m_returnTag // arguments for base constructors, filled in derived-to-base order std::map<FunctionDefinition const*, std::vector<ASTPointer<Expression>> const*> m_baseArguments; }; } }
BreemsEmporiumMensToiletriesFragrances/cpp-ethereum
libsolidity/Compiler.h
C
gpl-3.0
6,043
SET(CTEST_PROJECT_NAME "hikob-git-${PLATFORM}") SET(CTEST_NIGHTLY_START_TIME "00:00:00 EST") IF(NOT DEFINED CTEST_DROP_METHOD) SET(CTEST_DROP_METHOD "http") ENDIF(NOT DEFINED CTEST_DROP_METHOD) IF(CTEST_DROP_METHOD STREQUAL "http") SET(CTEST_DROP_SITE "tools.vpn.hikob.com") SET(CTEST_DROP_LOCATION "/cdash/submit.php?project=hikob-git-${PLATFORM}") SET(CTEST_TRIGGER_SITE "tools.vpn.hikob.com") ENDIF(CTEST_DROP_METHOD STREQUAL "http")
dbohn/openlab
CTestConfig.cmake
CMake
gpl-3.0
447
--------------------------------------------- -- Decussate -- -- Description: Performs a cross attack on nearby targets. -- Type: Magical -- Utsusemi/Blink absorb: 2-3 shadows? -- Range: Less than or equal to 10.0 -- Notes: Only used by Gulool Ja Ja when below 35% health. --------------------------------------------- require("/scripts/globals/settings"); require("/scripts/globals/status"); require("/scripts/globals/monstertpmoves"); --------------------------------------------- function OnMobSkillCheck(target,mob,skill) local check = 1; if(mob:getID() == 17043875 and mob:getHP() < mob:getMaxHP()/100 * 35) then check = 0; end return check; end; function OnMobWeaponSkill(target, mob, skill) local dmgmod = 1.2; local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,ELE_EARTH,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_EARTH,math.random(2,3)*info.hitslanded); target:delHP(dmg); return dmg; end;
FFXIOrgins/FFXIOrgins
scripts/globals/mobskills/Decussate.lua
Lua
gpl-3.0
1,029
#Region "Microsoft.VisualBasic::8450d02c5fe4c4f80f81a9880e0f8dc0, Data_science\MachineLearning\MachineLearning\Darwinism\Models\FitnessPool.vb" ' Author: ' ' asuka (amethyst.asuka@gcmodeller.org) ' xie (genetics@smrucc.org) ' xieguigang (xie.guigang@live.com) ' ' Copyright (c) 2018 GPL3 Licensed ' ' ' GNU GENERAL PUBLIC LICENSE (GPL3) ' ' ' 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/>. ' /********************************************************************************/ ' Summaries: ' Class FitnessPool ' ' Properties: Cacheable, evaluateFitness ' ' Constructor: (+2 Overloads) Sub New ' ' Function: Fitness, getOrCacheOfFitness ' ' Sub: Clear ' ' ' /********************************************************************************/ #End Region Imports System.Runtime.CompilerServices Imports Microsoft.VisualBasic.Language.Default Imports Microsoft.VisualBasic.MachineLearning.Darwinism.GAF Namespace Darwinism.Models ''' <summary> ''' Compute fitness and cache the result data in this pool. ''' </summary> ''' <typeparam name="Individual"></typeparam> Public Class FitnessPool(Of Individual) : Implements Fitness(Of Individual) ''' <summary> ''' Get unique id of each genome ''' </summary> Protected Friend indivToString As Func(Of Individual, String) Protected Friend maxCapacity% Protected Friend ReadOnly cache As New Dictionary(Of String, Double) Friend Shared ReadOnly defaultCacheSize As [Default](Of Integer) = 10000 Public ReadOnly Property Cacheable As Boolean Implements Fitness(Of Individual).Cacheable Get Return evaluateFitness.Cacheable End Get End Property Public ReadOnly Property evaluateFitness As Fitness(Of Individual) ''' <summary> ''' 因为这个缓存对象是默认通过``ToString``方法来生成键名的,所以假设<paramref name="toString"/>参数是空值的话,则必须要重写 ''' 目标<typeparamref name="Individual"/>的``ToString``方法 ''' </summary> ''' <param name="cacl">Expression for descript how to calculate the fitness.</param> ''' <param name="toString">Obj to dictionary key</param> Sub New(cacl As Fitness(Of Individual), capacity%, toString As Func(Of Individual, String)) evaluateFitness = cacl indivToString = toString maxCapacity = capacity Or defaultCacheSize If capacity <= 0 AndAlso cacl.Cacheable Then Call $"Target environment marked as cacheable, but cache size is invalid...".Warning Call $"Use default cache size for fitness: {defaultCacheSize.DefaultValue}".__INFO_ECHO ElseIf cacl.Cacheable Then Call $"Fitness was marked as cacheable with cache table size {capacity}".__INFO_ECHO End If End Sub Sub New() End Sub ''' <summary> ''' This function tells how well given individual performs at given problem. ''' </summary> ''' <param name="[in]"></param> ''' <returns></returns> Public Function Fitness([in] As Individual, parallel As Boolean) As Double Implements Fitness(Of Individual).Calculate ' 20200827 ' the synlock will stop the parallel computing in GA engine 'SyncLock evaluateFitness If Not evaluateFitness.Cacheable Then Return evaluateFitness.Calculate([in], parallel) Else Return getOrCacheOfFitness([in], parallel) End If 'End SyncLock End Function Private Function getOrCacheOfFitness([in] As Individual, parallel As Boolean) As Double Dim key$ = indivToString([in]) Dim fit As Double SyncLock cache If cache.ContainsKey(key$) Then fit = cache(key$) Else fit = evaluateFitness.Calculate([in], parallel) cache.Add(key$, fit) If cache.Count >= maxCapacity Then Dim asc = From fitValue In cache Order By fitValue.Value Ascending Take CInt(maxCapacity * 0.9) Select ID = fitValue.Key With asc.Indexing For Each key In cache.Keys.ToArray If .NotExists(key) Then Call cache.Remove(key) End If Next End With End If End If End SyncLock Return fit End Function ''' <summary> ''' Clear all cache data. ''' </summary> <MethodImpl(MethodImplOptions.AggressiveInlining)> Public Sub Clear() Call cache.Clear() End Sub End Class End Namespace
SMRUCC/GCModeller
src/runtime/sciBASIC#/Data_science/MachineLearning/MachineLearning/Darwinism/Models/FitnessPool.vb
Visual Basic
gpl-3.0
5,914
package cn.nukkit.block; import cn.nukkit.Player; import cn.nukkit.item.Item; import cn.nukkit.item.ItemTool; import cn.nukkit.level.Level; import cn.nukkit.level.sound.NoteBoxSound; import cn.nukkit.network.protocol.BlockEventPacket; /** * Created by Snake1999 on 2016/1/17. * Package cn.nukkit.block in project nukkit. */ public class BlockNoteblock extends BlockSolid { public BlockNoteblock() { this(0); } public BlockNoteblock(int meta) { super(meta); } @Override public String getName() { return "Note Block"; } @Override public int getId() { return NOTEBLOCK; } @Override public int getToolType() { return ItemTool.TYPE_AXE; } @Override public double getHardness() { return 0.8D; } @Override public double getResistance() { return 4D; } public boolean canBeActivated() { return true; } public int getStrength() { return this.meta; } public void increaseStrength() { if (this.meta < 24) { this.meta++; } else { this.meta = 0; } } public int getInstrument() { Block below = this.down(); switch (below.getId()) { case WOODEN_PLANK: case NOTEBLOCK: case CRAFTING_TABLE: return NoteBoxSound.INSTRUMENT_BASS; case SAND: case SANDSTONE: case SOUL_SAND: return NoteBoxSound.INSTRUMENT_TABOUR; case GLASS: case GLASS_PANEL: case GLOWSTONE_BLOCK: return NoteBoxSound.INSTRUMENT_CLICK; case COAL_ORE: case DIAMOND_ORE: case EMERALD_ORE: case GLOWING_REDSTONE_ORE: case GOLD_ORE: case IRON_ORE: case LAPIS_ORE: case REDSTONE_ORE: return NoteBoxSound.INSTRUMENT_BASS_DRUM; default: return NoteBoxSound.INSTRUMENT_PIANO; } } public void emitSound() { BlockEventPacket pk = new BlockEventPacket(); pk.x = (int) this.x; pk.y = (int) this.y; pk.z = (int) this.z; pk.case1 = this.getInstrument(); pk.case2 = this.getStrength(); this.getLevel().addChunkPacket((int) this.x >> 4, (int) this.z >> 4, pk); this.getLevel().addSound(new NoteBoxSound(this, this.getInstrument(), this.getStrength())); } public boolean onActivate(Item item) { return this.onActivate(item, null); } public boolean onActivate(Item item, Player player) { Block up = this.up(); if (up.getId() == Block.AIR) { this.increaseStrength(); this.emitSound(); return true; } else { return false; } } @Override public int onUpdate(int type) { if (type == Level.BLOCK_UPDATE_NORMAL || type == Level.BLOCK_UPDATE_REDSTONE) { //TODO: redstone } return 0; } }
yescallop/Nukkit
src/main/java/cn/nukkit/block/BlockNoteblock.java
Java
gpl-3.0
3,101
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.cts.verifier.p2p.testcase; import java.util.ArrayList; import java.util.List; import android.net.wifi.p2p.WifiP2pDevice; import android.net.wifi.p2p.WifiP2pManager.DnsSdServiceResponseListener; import android.util.Log; /** * The utility class for testing * android.net.wifi.p2p.WifiP2pManager.DnsSdServiceResponseListener callback function. */ public class DnsSdResponseListenerTest extends ListenerTest implements DnsSdServiceResponseListener { private static final String TAG = "DnsSdResponseListenerTest"; public static final List<ListenerArgument> NO_DNS_PTR = new ArrayList<ListenerArgument>(); public static final List<ListenerArgument> ALL_DNS_PTR = new ArrayList<ListenerArgument>(); public static final List<ListenerArgument> IPP_DNS_PTR = new ArrayList<ListenerArgument>(); public static final List<ListenerArgument> AFP_DNS_PTR = new ArrayList<ListenerArgument>(); /** * The target device address. */ private String mTargetAddr; static { initialize(); } public DnsSdResponseListenerTest(String targetAddr) { mTargetAddr = targetAddr; } @Override public void onDnsSdServiceAvailable(String instanceName, String registrationType, WifiP2pDevice srcDevice) { Log.d(TAG, instanceName + " " + registrationType + " received from " + srcDevice.deviceAddress); /* * Check only the response from the target device. * The response from other devices are ignored. */ if (srcDevice.deviceAddress.equalsIgnoreCase(mTargetAddr)) { receiveCallback(new Argument(instanceName, registrationType)); } } private static void initialize() { String ippInstanceName = "MyPrinter"; String ippRegistrationType = "_ipp._tcp.local."; String afpInstanceName = "Example"; String afpRegistrationType = "_afpovertcp._tcp.local."; IPP_DNS_PTR.add(new Argument(ippInstanceName, ippRegistrationType)); AFP_DNS_PTR.add(new Argument(afpInstanceName, afpRegistrationType)); ALL_DNS_PTR.add(new Argument(ippInstanceName, ippRegistrationType)); ALL_DNS_PTR.add(new Argument(afpInstanceName, afpRegistrationType)); } /** * The container of the argument of {@link #onDnsSdServiceAvailable}. */ static class Argument extends ListenerArgument { private String mInstanceName; private String mRegistrationType; /** * Set the argument of {@link #onDnsSdServiceAvailable}. * * @param instanceName instance name. * @param registrationType registration type. */ Argument(String instanceName, String registrationType) { mInstanceName = instanceName; mRegistrationType = registrationType; } @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof Argument)) { return false; } Argument arg = (Argument)obj; return equals(mInstanceName, arg.mInstanceName) && equals(mRegistrationType, arg.mRegistrationType); } private boolean equals(String s1, String s2) { if (s1 == null && s2 == null) { return true; } if (s1 == null || s2 == null) { return false; } return s1.equals(s2); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("[type=dns_ptr instant_name="); sb.append(mInstanceName); sb.append(" registration type="); sb.append(mRegistrationType); sb.append("\n"); return "instanceName=" + mInstanceName + " registrationType=" + mRegistrationType; } } }
s20121035/rk3288_android5.1_repo
cts/apps/CtsVerifier/src/com/android/cts/verifier/p2p/testcase/DnsSdResponseListenerTest.java
Java
gpl-3.0
4,616
#!/usr/bin/perl use strict; use warnings; use Test::More tests => 34; BEGIN { use_ok('li_carrays') } require_ok('li_carrays'); # array_class { my $length = 5; my $xyArray = new li_carrays::XYArray($length); for (my $i=0; $i<$length; $i++) { my $xy = $xyArray->getitem($i); $xy->{x} = $i*10; $xy->{y} = $i*100; $xyArray->setitem($i, $xy); } for (my $i=0; $i<$length; $i++) { is($xyArray->getitem($i)->{x}, $i*10); is($xyArray->getitem($i)->{y}, $i*100); } } { # global array variable my $length = 3; my $xyArrayPointer = $li_carrays::globalXYArray; my $xyArray = li_carrays::XYArray::frompointer($xyArrayPointer); for (my $i=0; $i<$length; $i++) { my $xy = $xyArray->getitem($i); $xy->{x} = $i*10; $xy->{y} = $i*100; $xyArray->setitem($i, $xy); } for (my $i=0; $i<$length; $i++) { is($xyArray->getitem($i)->{x}, $i*10); is($xyArray->getitem($i)->{y}, $i*100); } } # array_functions { my $length = 5; my $abArray = li_carrays::new_ABArray($length); for (my $i=0; $i<$length; $i++) { my $ab = li_carrays::ABArray_getitem($abArray, $i); $ab->{a} = $i*10; $ab->{b} = $i*100; li_carrays::ABArray_setitem($abArray, $i, $ab); } for (my $i=0; $i<$length; $i++) { is(li_carrays::ABArray_getitem($abArray, $i)->{a}, $i*10); is(li_carrays::ABArray_getitem($abArray, $i)->{b}, $i*100); } li_carrays::delete_ABArray($abArray); } { # global array variable my $length = 3; my $abArray = $li_carrays::globalABArray; for (my $i=0; $i<$length; $i++) { my $ab = li_carrays::ABArray_getitem($abArray, $i); $ab->{a} = $i*10; $ab->{b} = $i*100; li_carrays::ABArray_setitem($abArray, $i, $ab); } for (my $i=0; $i<$length; $i++) { is(li_carrays::ABArray_getitem($abArray, $i)->{a}, $i*10); is(li_carrays::ABArray_getitem($abArray, $i)->{b}, $i*100); } }
DGA-MI-SSI/YaCo
deps/swig-3.0.7/Examples/test-suite/perl5/li_carrays_runme.pl
Perl
gpl-3.0
1,879
/* Copyright (c) 2001-2008, The HSQL Development Group * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the HSQL Development Group 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 HSQL DEVELOPMENT GROUP, HSQLDB.ORG, * 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. */ package org.hsqldb.util; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; /* $Id: SqlTool.java,v 1.72 2007/06/29 12:23:47 unsaved Exp $ */ /** * Sql Tool. A command-line and/or interactive SQL tool. * (Note: For every Javadoc block comment, I'm using a single blank line * immediately after the description, just like's Sun's examples in * their Coding Conventions document). * * See JavaDocs for the main method for syntax of how to run. * This class is mostly used in a static (a.o.t. object) way, because most * of the work is done in the static main class. * This class should be refactored so that the main work is done in an * object method, and the static main invokes the object method. * Then programmatic users could use instances of this class in the normal * Java way. * * @see #main() * @version $Revision: 1.72 $ * @author Blaine Simpson unsaved@users */ public class SqlTool { private static final String DEFAULT_RCFILE = System.getProperty("user.home") + "/sqltool.rc"; // N.b. the following is static! private static String revnum = null; public static final int SQLTOOLERR_EXITVAL = 1; public static final int SYNTAXERR_EXITVAL = 11; public static final int RCERR_EXITVAL = 2; public static final int SQLERR_EXITVAL = 3; public static final int IOERR_EXITVAL = 4; public static final int FILEERR_EXITVAL = 5; public static final int INPUTERR_EXITVAL = 6; public static final int CONNECTERR_EXITVAL = 7; /** * The configuration identifier to use when connection parameters are * specified on the command line */ private static String CMDLINE_ID = "cmdline"; static private SqltoolRB rb = null; // Must use a shared static RB object, since we need to get messages // inside of static methods. // This means that the locale will be set the first time this class // is accessed. Subsequent calls will not update the RB if the locale // changes (could have it check and reload the RB if this becomes an // issue). static { revnum = "333"; try { rb = new SqltoolRB(); rb.validate(); rb.setMissingPosValueBehavior( ValidatingResourceBundle.NOOP_BEHAVIOR); rb.setMissingPropertyBehavior( ValidatingResourceBundle.NOOP_BEHAVIOR); } catch (RuntimeException re) { System.err.println("Failed to initialize resource bundle"); throw re; } } public static String LS = System.getProperty("line.separator"); /** Utility nested class for internal use. */ private static class BadCmdline extends Exception { static final long serialVersionUID = -2134764796788108325L; BadCmdline() {} } /** Utility object for internal use. */ private static BadCmdline bcl = new BadCmdline(); /** For trapping of exceptions inside this class. * These are always handled inside this class. */ private static class PrivateException extends Exception { static final long serialVersionUID = -7765061479594523462L; PrivateException() { super(); } PrivateException(String s) { super(s); } } public static class SqlToolException extends Exception { static final long serialVersionUID = 1424909871915188519L; int exitValue = 1; SqlToolException(String message, int exitValue) { super(message); this.exitValue = exitValue; } SqlToolException(int exitValue, String message) { this(message, exitValue); } SqlToolException(int exitValue) { super(); this.exitValue = exitValue; } } /** * Prompt the user for a password. * * @param username The user the password is for * @return The password the user entered */ private static String promptForPassword(String username) throws PrivateException { BufferedReader console; String password; password = null; try { console = new BufferedReader(new InputStreamReader(System.in)); // Prompt for password System.out.print(rb.getString(SqltoolRB.PASSWORDFOR_PROMPT, RCData.expandSysPropVars(username))); // Read the password from the command line password = console.readLine(); if (password == null) { password = ""; } else { password = password.trim(); } } catch (IOException e) { throw new PrivateException(e.getMessage()); } return password; } /** * Parses a comma delimited string of name value pairs into a * <code>Map</code> object. * * @param varString The string to parse * @param varMap The map to save the paired values into * @param lowerCaseKeys Set to <code>true</code> if the map keys should be * converted to lower case */ private static void varParser(String varString, Map varMap, boolean lowerCaseKeys) throws PrivateException { int equals; String var; String val; String[] allvars; if ((varMap == null) || (varString == null)) { throw new IllegalArgumentException( "varMap or varString are null in SqlTool.varParser call"); } allvars = varString.split("\\s*,\\s*"); for (int i = 0; i < allvars.length; i++) { equals = allvars[i].indexOf('='); if (equals < 1) { throw new PrivateException( rb.getString(SqltoolRB.SQLTOOL_VARSET_BADFORMAT)); } var = allvars[i].substring(0, equals).trim(); val = allvars[i].substring(equals + 1).trim(); if (var.length() < 1) { throw new PrivateException( rb.getString(SqltoolRB.SQLTOOL_VARSET_BADFORMAT)); } if (lowerCaseKeys) { var = var.toLowerCase(); } varMap.put(var, val); } } /** * A static wrapper for objectMain, so that that method may be executed * as a Java "program". * * Throws only RuntimExceptions or Errors, because this method is intended * to System.exit() for all but disasterous system problems, for which * the inconvenience of a a stack trace would be the least of your worries. * * If you don't want SqlTool to System.exit(), then use the method * objectMain() instead of this method. * * @see objectMain(String[]) */ public static void main(String[] args) { try { SqlTool.objectMain(args); } catch (SqlToolException fr) { if (fr.getMessage() != null) { System.err.println(fr.getMessage()); } System.exit(fr.exitValue); } System.exit(0); } /** * Connect to a JDBC Database and execute the commands given on * stdin or in SQL file(s). * * This method is changed for HSQLDB 1.8.0.8 and 1.9.0.x to never * System.exit(). * * @param arg Run "java... org.hsqldb.util.SqlTool --help" for syntax. * @throws SqlToolException Upon any fatal error, with useful * reason as the exception's message. */ static public void objectMain(String[] arg) throws SqlToolException { /* * The big picture is, we parse input args; load a RCData; * get a JDBC Connection with the RCData; instantiate and * execute as many SqlFiles as we need to. */ String rcFile = null; File tmpFile = null; String sqlText = null; String driver = null; String targetDb = null; String varSettings = null; boolean debug = false; File[] scriptFiles = null; int i = -1; boolean listMode = false; boolean interactive = false; boolean noinput = false; boolean noautoFile = false; boolean autoCommit = false; Boolean coeOverride = null; Boolean stdinputOverride = null; String rcParams = null; String rcUrl = null; String rcUsername = null; String rcPassword = null; String rcCharset = null; String rcTruststore = null; Map rcFields = null; String parameter; try { while ((i + 1 < arg.length) && arg[i + 1].startsWith("--")) { i++; if (arg[i].length() == 2) { break; // "--" } parameter = arg[i].substring(2).toLowerCase(); if (parameter.equals("help")) { System.out.println(rb.getString(SqltoolRB.SQLTOOL_SYNTAX, revnum, RCData.DEFAULT_JDBC_DRIVER)); return; } if (parameter.equals("abortonerr")) { if (coeOverride != null) { throw new SqlToolException(SYNTAXERR_EXITVAL, rb.getString( SqltoolRB.SQLTOOL_ABORTCONTINUE_MUTUALLYEXCLUSIVE)); } coeOverride = Boolean.FALSE; } else if (parameter.equals("continueonerr")) { if (coeOverride != null) { throw new SqlToolException(SYNTAXERR_EXITVAL, rb.getString( SqltoolRB.SQLTOOL_ABORTCONTINUE_MUTUALLYEXCLUSIVE)); } coeOverride = Boolean.TRUE; } else if (parameter.equals("list")) { listMode = true; } else if (parameter.equals("rcfile")) { if (++i == arg.length) { throw bcl; } rcFile = arg[i]; } else if (parameter.equals("setvar")) { if (++i == arg.length) { throw bcl; } varSettings = arg[i]; } else if (parameter.equals("sql")) { noinput = true; // but turn back on if file "-" specd. if (++i == arg.length) { throw bcl; } sqlText = arg[i]; } else if (parameter.equals("debug")) { debug = true; } else if (parameter.equals("noautofile")) { noautoFile = true; } else if (parameter.equals("autocommit")) { autoCommit = true; } else if (parameter.equals("stdinput")) { noinput = false; stdinputOverride = Boolean.TRUE; } else if (parameter.equals("noinput")) { noinput = true; stdinputOverride = Boolean.FALSE; } else if (parameter.equals("driver")) { if (++i == arg.length) { throw bcl; } driver = arg[i]; } else if (parameter.equals("inlinerc")) { if (++i == arg.length) { throw bcl; } rcParams = arg[i]; } else { throw bcl; } } if (!listMode) { // If an inline RC file was specified, don't worry about the targetDb if (rcParams == null) { if (++i == arg.length) { throw bcl; } targetDb = arg[i]; } } int scriptIndex = 0; if (sqlText != null) { try { tmpFile = File.createTempFile("sqltool-", ".sql"); //(new java.io.FileWriter(tmpFile)).write(sqlText); java.io.FileWriter fw = new java.io.FileWriter(tmpFile); try { fw.write("/* " + (new java.util.Date()) + ". " + SqlTool.class.getName() + " command-line SQL. */" + LS + LS); fw.write(sqlText + LS); fw.flush(); } finally { fw.close(); } } catch (IOException ioe) { throw new SqlToolException(IOERR_EXITVAL, rb.getString(SqltoolRB.SQLTEMPFILE_FAIL, ioe.toString())); } } if (stdinputOverride != null) { noinput = !stdinputOverride.booleanValue(); } interactive = (!noinput) && (arg.length <= i + 1); if (arg.length == i + 2 && arg[i + 1].equals("-")) { if (stdinputOverride == null) { noinput = false; } } else if (arg.length > i + 1) { // I.e., if there are any SQL files specified. scriptFiles = new File[arg.length - i - 1 + ((stdinputOverride == null ||!stdinputOverride.booleanValue()) ? 0 : 1)]; if (debug) { System.err.println("scriptFiles has " + scriptFiles.length + " elements"); } while (i + 1 < arg.length) { scriptFiles[scriptIndex++] = new File(arg[++i]); } if (stdinputOverride != null && stdinputOverride.booleanValue()) { scriptFiles[scriptIndex++] = null; noinput = true; } } } catch (BadCmdline bcl) { throw new SqlToolException(SYNTAXERR_EXITVAL, rb.getString(SqltoolRB.SQLTOOL_SYNTAX, revnum, RCData.DEFAULT_JDBC_DRIVER)); } RCData conData = null; // Use the inline RC file if it was specified if (rcParams != null) { rcFields = new HashMap(); try { varParser(rcParams, rcFields, true); } catch (PrivateException e) { throw new SqlToolException(SYNTAXERR_EXITVAL, e.getMessage()); } rcUrl = (String) rcFields.remove("url"); rcUsername = (String) rcFields.remove("user"); rcCharset = (String) rcFields.remove("charset"); rcTruststore = (String) rcFields.remove("truststore"); rcPassword = (String) rcFields.remove("password"); // Don't ask for password if what we have already is invalid! if (rcUrl == null || rcUrl.length() < 1) throw new SqlToolException(RCERR_EXITVAL, rb.getString( SqltoolRB.RCDATA_INLINEURL_MISSING)); if (rcUsername == null || rcUsername.length() < 1) throw new SqlToolException(RCERR_EXITVAL, rb.getString( SqltoolRB.RCDATA_INLINEUSERNAME_MISSING)); if (rcPassword != null && rcPassword.length() > 0) throw new SqlToolException(RCERR_EXITVAL, rb.getString( SqltoolRB.RCDATA_PASSWORD_VISIBLE)); if (rcFields.size() > 0) { throw new SqlToolException(INPUTERR_EXITVAL, rb.getString(SqltoolRB.RCDATA_INLINE_EXTRAVARS, rcFields.keySet().toString())); } if (rcPassword == null) try { rcPassword = promptForPassword(rcUsername); } catch (PrivateException e) { throw new SqlToolException(INPUTERR_EXITVAL, rb.getString(SqltoolRB.PASSWORD_READFAIL, e.getMessage())); } try { conData = new RCData(CMDLINE_ID, rcUrl, rcUsername, rcPassword, driver, rcCharset, rcTruststore); } catch (Exception e) { throw new SqlToolException(RCERR_EXITVAL, rb.getString( SqltoolRB.RCDATA_GENFROMVALUES_FAIL, e.getMessage())); } } else { try { conData = new RCData(new File((rcFile == null) ? DEFAULT_RCFILE : rcFile), targetDb); } catch (Exception e) { throw new SqlToolException(RCERR_EXITVAL, rb.getString( SqltoolRB.CONNDATA_RETRIEVAL_FAIL, targetDb, e.getMessage())); } } if (listMode) { return; } if (debug) { conData.report(); } Connection conn = null; try { conn = conData.getConnection( driver, System.getProperty("sqlfile.charset"), System.getProperty("javax.net.ssl.trustStore")); conn.setAutoCommit(autoCommit); DatabaseMetaData md = null; if (interactive && (md = conn.getMetaData()) != null) { System.out.println( rb.getString(SqltoolRB.JDBC_ESTABLISHED, md.getDatabaseProductName(), md.getDatabaseProductVersion(), md.getUserName())); } } catch (Exception e) { //e.printStackTrace(); // Let's not continue as if nothing is wrong. throw new SqlToolException(CONNECTERR_EXITVAL, rb.getString(SqltoolRB.CONNECTION_FAIL, conData.url, conData.username, e.getMessage())); } File[] emptyFileArray = {}; File[] singleNullFileArray = { null }; File autoFile = null; if (interactive &&!noautoFile) { autoFile = new File(System.getProperty("user.home") + "/auto.sql"); if ((!autoFile.isFile()) ||!autoFile.canRead()) { autoFile = null; } } if (scriptFiles == null) { // I.e., if no SQL files given on command-line. // Input file list is either nothing or {null} to read stdin. scriptFiles = (noinput ? emptyFileArray : singleNullFileArray); } int numFiles = scriptFiles.length; if (tmpFile != null) { numFiles += 1; } if (autoFile != null) { numFiles += 1; } SqlFile[] sqlFiles = new SqlFile[numFiles]; Map userVars = new HashMap(); if (varSettings != null) try { varParser(varSettings, userVars, false); } catch (PrivateException pe) { throw new SqlToolException(RCERR_EXITVAL, pe.getMessage()); } // We print version before execing this one. int interactiveFileIndex = -1; try { int fileIndex = 0; if (autoFile != null) { sqlFiles[fileIndex++] = new SqlFile(autoFile, false, userVars); } if (tmpFile != null) { sqlFiles[fileIndex++] = new SqlFile(tmpFile, false, userVars); } for (int j = 0; j < scriptFiles.length; j++) { if (interactiveFileIndex < 0 && interactive) { interactiveFileIndex = fileIndex; } sqlFiles[fileIndex++] = new SqlFile(scriptFiles[j], interactive, userVars); } } catch (IOException ioe) { try { conn.close(); } catch (Exception e) {} throw new SqlToolException(FILEERR_EXITVAL, ioe.getMessage()); } try { for (int j = 0; j < sqlFiles.length; j++) { if (j == interactiveFileIndex) { System.out.print("SqlTool v. " + revnum + ". "); } sqlFiles[j].execute(conn, coeOverride); } // Following two Exception types are handled properly inside of // SqlFile. We just need to return an appropriate error status. } catch (SqlToolError ste) { throw new SqlToolException(SQLTOOLERR_EXITVAL); } catch (SQLException se) { // SqlTool will only throw an SQLException if it is in // "\c false" mode. throw new SqlToolException(SQLERR_EXITVAL); } finally { try { conn.close(); } catch (Exception e) {} } // Taking file removal out of final block because this is good debug // info to keep around if the program aborts. if (tmpFile != null && !tmpFile.delete()) { System.err.println(conData.url + rb.getString( SqltoolRB.TEMPFILE_REMOVAL_FAIL, tmpFile.toString())); } } }
danielbejaranogonzalez/Mobile-Network-Designer
db/hsqldb/src/org/hsqldb/util/SqlTool.java
Java
gpl-3.0
23,912
package App::Prove::State; use strict; use warnings; use File::Find; use File::Spec; use Carp; use App::Prove::State::Result; use TAP::Parser::YAMLish::Reader (); use TAP::Parser::YAMLish::Writer (); use base 'TAP::Base'; BEGIN { __PACKAGE__->mk_methods('result_class'); } use constant IS_WIN32 => ( $^O =~ /^(MS)?Win32$/ ); use constant NEED_GLOB => IS_WIN32; =head1 NAME App::Prove::State - State storage for the C<prove> command. =head1 VERSION Version 3.38 =cut our $VERSION = '3.38'; =head1 DESCRIPTION The C<prove> command supports a C<--state> option that instructs it to store persistent state across runs. This module implements that state and the operations that may be performed on it. =head1 SYNOPSIS # Re-run failed tests $ prove --state=failed,save -rbv =cut =head1 METHODS =head2 Class Methods =head3 C<new> Accepts a hashref with the following key/value pairs: =over 4 =item * C<store> The filename of the data store holding the data that App::Prove::State reads. =item * C<extensions> (optional) The test name extensions. Defaults to C<.t>. =item * C<result_class> (optional) The name of the C<result_class>. Defaults to C<App::Prove::State::Result>. =back =cut # override TAP::Base::new: sub new { my $class = shift; my %args = %{ shift || {} }; my $self = bless { select => [], seq => 1, store => delete $args{store}, extensions => ( delete $args{extensions} || ['.t'] ), result_class => ( delete $args{result_class} || 'App::Prove::State::Result' ), }, $class; $self->{_} = $self->result_class->new( { tests => {}, generation => 1, } ); my $store = $self->{store}; $self->load($store) if defined $store && -f $store; return $self; } =head2 C<result_class> Getter/setter for the name of the class used for tracking test results. This class should either subclass from C<App::Prove::State::Result> or provide an identical interface. =cut =head2 C<extensions> Get or set the list of extensions that files must have in order to be considered tests. Defaults to ['.t']. =cut sub extensions { my $self = shift; $self->{extensions} = shift if @_; return $self->{extensions}; } =head2 C<results> Get the results of the last test run. Returns a C<result_class()> instance. =cut sub results { my $self = shift; $self->{_} || $self->result_class->new; } =head2 C<commit> Save the test results. Should be called after all tests have run. =cut sub commit { my $self = shift; if ( $self->{should_save} ) { $self->save; } } =head2 Instance Methods =head3 C<apply_switch> $self->apply_switch('failed,save'); Apply a list of switch options to the state, updating the internal object state as a result. Nothing is returned. Diagnostics: - "Illegal state option: %s" =over =item C<last> Run in the same order as last time =item C<failed> Run only the failed tests from last time =item C<passed> Run only the passed tests from last time =item C<all> Run all tests in normal order =item C<hot> Run the tests that most recently failed first =item C<todo> Run the tests ordered by number of todos. =item C<slow> Run the tests in slowest to fastest order. =item C<fast> Run test tests in fastest to slowest order. =item C<new> Run the tests in newest to oldest order. =item C<old> Run the tests in oldest to newest order. =item C<save> Save the state on exit. =back =cut sub apply_switch { my $self = shift; my @opts = @_; my $last_gen = $self->results->generation - 1; my $last_run_time = $self->results->last_run_time; my $now = $self->get_time; my @switches = map { split /,/ } @opts; my %handler = ( last => sub { $self->_select( limit => shift, where => sub { $_->generation >= $last_gen }, order => sub { $_->sequence } ); }, failed => sub { $self->_select( limit => shift, where => sub { $_->result != 0 }, order => sub { -$_->result } ); }, passed => sub { $self->_select( limit => shift, where => sub { $_->result == 0 } ); }, all => sub { $self->_select( limit => shift ); }, todo => sub { $self->_select( limit => shift, where => sub { $_->num_todo != 0 }, order => sub { -$_->num_todo; } ); }, hot => sub { $self->_select( limit => shift, where => sub { defined $_->last_fail_time }, order => sub { $now - $_->last_fail_time } ); }, slow => sub { $self->_select( limit => shift, order => sub { -$_->elapsed } ); }, fast => sub { $self->_select( limit => shift, order => sub { $_->elapsed } ); }, new => sub { $self->_select( limit => shift, order => sub { -$_->mtime } ); }, old => sub { $self->_select( limit => shift, order => sub { $_->mtime } ); }, fresh => sub { $self->_select( limit => shift, where => sub { $_->mtime >= $last_run_time } ); }, save => sub { $self->{should_save}++; }, adrian => sub { unshift @switches, qw( hot all save ); }, ); while ( defined( my $ele = shift @switches ) ) { my ( $opt, $arg ) = ( $ele =~ /^([^:]+):(.*)/ ) ? ( $1, $2 ) : ( $ele, undef ); my $code = $handler{$opt} || croak "Illegal state option: $opt"; $code->($arg); } return; } sub _select { my ( $self, %spec ) = @_; push @{ $self->{select} }, \%spec; } =head3 C<get_tests> Given a list of args get the names of tests that should run =cut sub get_tests { my $self = shift; my $recurse = shift; my @argv = @_; my %seen; my @selected = $self->_query; unless ( @argv || @{ $self->{select} } ) { @argv = $recurse ? '.' : 't'; croak qq{No tests named and '@argv' directory not found} unless -d $argv[0]; } push @selected, $self->_get_raw_tests( $recurse, @argv ) if @argv; return grep { !$seen{$_}++ } @selected; } sub _query { my $self = shift; if ( my @sel = @{ $self->{select} } ) { warn "No saved state, selection will be empty\n" unless $self->results->num_tests; return map { $self->_query_clause($_) } @sel; } return; } sub _query_clause { my ( $self, $clause ) = @_; my @got; my $results = $self->results; my $where = $clause->{where} || sub {1}; # Select for my $name ( $results->test_names ) { next unless -f $name; local $_ = $results->test($name); push @got, $name if $where->(); } # Sort if ( my $order = $clause->{order} ) { @got = map { $_->[0] } sort { ( defined $b->[1] <=> defined $a->[1] ) || ( ( $a->[1] || 0 ) <=> ( $b->[1] || 0 ) ) } map { [ $_, do { local $_ = $results->test($_); $order->() } ] } @got; } if ( my $limit = $clause->{limit} ) { @got = splice @got, 0, $limit if @got > $limit; } return @got; } sub _get_raw_tests { my $self = shift; my $recurse = shift; my @argv = @_; my @tests; # Do globbing on Win32. if (NEED_GLOB) { eval "use File::Glob::Windows"; # [49732] @argv = map { glob "$_" } @argv; } my $extensions = $self->{extensions}; for my $arg (@argv) { if ( '-' eq $arg ) { push @argv => <STDIN>; chomp(@argv); next; } push @tests, sort -d $arg ? $recurse ? $self->_expand_dir_recursive( $arg, $extensions ) : map { glob( File::Spec->catfile( $arg, "*$_" ) ) } @{$extensions} : $arg; } return @tests; } sub _expand_dir_recursive { my ( $self, $dir, $extensions ) = @_; my @tests; my $ext_string = join( '|', map {quotemeta} @{$extensions} ); find( { follow => 1, #21938 follow_skip => 2, wanted => sub { -f && /(?:$ext_string)$/ && push @tests => $File::Find::name; } }, $dir ); return @tests; } =head3 C<observe_test> Store the results of a test. =cut # Store: # last fail time # last pass time # last run time # most recent result # most recent todos # total failures # total passes # state generation # parser sub observe_test { my ( $self, $test_info, $parser ) = @_; my $name = $test_info->[0]; my $fail = scalar( $parser->failed ) + ( $parser->has_problems ? 1 : 0 ); my $todo = scalar( $parser->todo ); my $start_time = $parser->start_time; my $end_time = $parser->end_time, my $test = $self->results->test($name); $test->sequence( $self->{seq}++ ); $test->generation( $self->results->generation ); $test->run_time($end_time); $test->result($fail); $test->num_todo($todo); $test->elapsed( $end_time - $start_time ); $test->parser($parser); if ($fail) { $test->total_failures( $test->total_failures + 1 ); $test->last_fail_time($end_time); } else { $test->total_passes( $test->total_passes + 1 ); $test->last_pass_time($end_time); } } =head3 C<save> Write the state to a file. =cut sub save { my ($self) = @_; my $store = $self->{store} or return; $self->results->last_run_time( $self->get_time ); my $writer = TAP::Parser::YAMLish::Writer->new; local *FH; open FH, ">$store" or croak "Can't write $store ($!)"; $writer->write( $self->results->raw, \*FH ); close FH; } =head3 C<load> Load the state from a file =cut sub load { my ( $self, $name ) = @_; my $reader = TAP::Parser::YAMLish::Reader->new; local *FH; open FH, "<$name" or croak "Can't read $name ($!)"; # XXX this is temporary $self->{_} = $self->result_class->new( $reader->read( sub { my $line = <FH>; defined $line && chomp $line; return $line; } ) ); # $writer->write( $self->{tests} || {}, \*FH ); close FH; $self->_regen_seq; $self->_prune_and_stamp; $self->results->generation( $self->results->generation + 1 ); } sub _prune_and_stamp { my $self = shift; my $results = $self->results; my @tests = $self->results->tests; for my $test (@tests) { my $name = $test->name; if ( my @stat = stat $name ) { $test->mtime( $stat[9] ); } else { $results->remove($name); } } } sub _regen_seq { my $self = shift; for my $test ( $self->results->tests ) { $self->{seq} = $test->sequence + 1 if defined $test->sequence && $test->sequence >= $self->{seq}; } } 1;
mgood7123/UPM
perl-5.26.1/perl5.26.1/lib/5.26.1/App/Prove/State.pm
Perl
gpl-3.0
11,689
<?php namespace Drupal\language\Form; use Drupal\Core\Block\BlockManagerInterface; use Drupal\Component\Utility\Unicode; use Drupal\Core\Config\ConfigFactoryInterface; use Drupal\Core\Entity\EntityStorageInterface; use Drupal\Core\Extension\ThemeHandlerInterface; use Drupal\Core\Form\ConfigFormBase; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Url; use Drupal\language\ConfigurableLanguageManagerInterface; use Drupal\language\LanguageNegotiatorInterface; use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationSelected; use Symfony\Component\DependencyInjection\ContainerInterface; /** * Configure the selected language negotiation method for this site. */ class NegotiationConfigureForm extends ConfigFormBase { /** * Stores the configuration object for language.types. * * @var \Drupal\Core\Config\Config */ protected $languageTypes; /** * The language manager. * * @var \Drupal\language\ConfigurableLanguageManagerInterface */ protected $languageManager; /** * The language negotiator. * * @var \Drupal\language\LanguageNegotiatorInterface */ protected $negotiator; /** * The block manager. * * @var \Drupal\Core\Block\BlockManagerInterface */ protected $blockManager; /** * The block storage. * * @var \Drupal\Core\Entity\EntityStorageInterface|null */ protected $blockStorage; /** * The theme handler. * * @var \Drupal\Core\Extension\ThemeHandlerInterface */ protected $themeHandler; /** * Constructs a NegotiationConfigureForm object. * * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory * The factory for configuration objects. * @param \Drupal\language\ConfigurableLanguageManagerInterface $language_manager * The language manager. * @param \Drupal\language\LanguageNegotiatorInterface $negotiator * The language negotiation methods manager. * @param \Drupal\Core\Block\BlockManagerInterface $block_manager * The block manager. * @param \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler * The theme handler. * @param \Drupal\Core\Entity\EntityStorageInterface $block_storage * The block storage, or NULL if not available. */ public function __construct(ConfigFactoryInterface $config_factory, ConfigurableLanguageManagerInterface $language_manager, LanguageNegotiatorInterface $negotiator, BlockManagerInterface $block_manager, ThemeHandlerInterface $theme_handler, EntityStorageInterface $block_storage = NULL) { parent::__construct($config_factory); $this->languageTypes = $this->config('language.types'); $this->languageManager = $language_manager; $this->negotiator = $negotiator; $this->blockManager = $block_manager; $this->themeHandler = $theme_handler; $this->blockStorage = $block_storage; } /** * {@inheritdoc} */ public static function create(ContainerInterface $container) { $entity_manager = $container->get('entity.manager'); $block_storage = $entity_manager->hasHandler('block', 'storage') ? $entity_manager->getStorage('block') : NULL; return new static( $container->get('config.factory'), $container->get('language_manager'), $container->get('language_negotiator'), $container->get('plugin.manager.block'), $container->get('theme_handler'), $block_storage ); } /** * {@inheritdoc} */ public function getFormId() { return 'language_negotiation_configure_form'; } /** * {@inheritdoc} */ protected function getEditableConfigNames() { return ['language.types']; } /** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $configurable = $this->languageTypes->get('configurable'); $form = [ '#theme' => 'language_negotiation_configure_form', '#language_types_info' => $this->languageManager->getDefinedLanguageTypesInfo(), '#language_negotiation_info' => $this->negotiator->getNegotiationMethods(), ]; $form['#language_types'] = []; foreach ($form['#language_types_info'] as $type => $info) { // Show locked language types only if they are configurable. if (empty($info['locked']) || in_array($type, $configurable)) { $form['#language_types'][] = $type; } } foreach ($form['#language_types'] as $type) { $this->configureFormTable($form, $type); } $form['actions'] = ['#type' => 'actions']; $form['actions']['submit'] = [ '#type' => 'submit', '#button_type' => 'primary', '#value' => $this->t('Save settings'), ]; return $form; } /** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { $configurable_types = $form['#language_types']; $stored_values = $this->languageTypes->get('configurable'); $customized = []; $method_weights_type = []; foreach ($configurable_types as $type) { $customized[$type] = in_array($type, $stored_values); $method_weights = []; $enabled_methods = $form_state->getValue([$type, 'enabled']); $enabled_methods[LanguageNegotiationSelected::METHOD_ID] = TRUE; $method_weights_input = $form_state->getValue([$type, 'weight']); if ($form_state->hasValue([$type, 'configurable'])) { $customized[$type] = !$form_state->isValueEmpty([$type, 'configurable']); } foreach ($method_weights_input as $method_id => $weight) { if ($enabled_methods[$method_id]) { $method_weights[$method_id] = $weight; } } $method_weights_type[$type] = $method_weights; $this->languageTypes->set('negotiation.' . $type . '.method_weights', $method_weights_input)->save(); } // Update non-configurable language types and the related language // negotiation configuration. $this->negotiator->updateConfiguration(array_keys(array_filter($customized))); // Update the language negotiations after setting the configurability. foreach ($method_weights_type as $type => $method_weights) { $this->negotiator->saveConfiguration($type, $method_weights); } // Clear block definitions cache since the available blocks and their names // may have been changed based on the configurable types. if ($this->blockStorage) { // If there is an active language switcher for a language type that has // been made not configurable, deactivate it first. $non_configurable = array_keys(array_diff($customized, array_filter($customized))); $this->disableLanguageSwitcher($non_configurable); } $this->blockManager->clearCachedDefinitions(); $form_state->setRedirect('language.negotiation'); drupal_set_message($this->t('Language detection configuration saved.')); } /** * Builds a language negotiation method configuration table. * * @param array $form * The language negotiation configuration form. * @param string $type * The language type to generate the table for. */ protected function configureFormTable(array &$form, $type) { $info = $form['#language_types_info'][$type]; $table_form = [ '#title' => $this->t('@type language detection', ['@type' => $info['name']]), '#tree' => TRUE, '#description' => $info['description'], '#language_negotiation_info' => [], '#show_operations' => FALSE, 'weight' => ['#tree' => TRUE], ]; // Only show configurability checkbox for the unlocked language types. if (empty($info['locked'])) { $configurable = $this->languageTypes->get('configurable'); $table_form['configurable'] = [ '#type' => 'checkbox', '#title' => $this->t('Customize %language_name language detection to differ from Interface text language detection settings', ['%language_name' => $info['name']]), '#default_value' => in_array($type, $configurable), '#attributes' => ['class' => ['language-customization-checkbox']], '#attached' => [ 'library' => [ 'language/drupal.language.admin' ], ], ]; } $negotiation_info = $form['#language_negotiation_info']; $enabled_methods = $this->languageTypes->get('negotiation.' . $type . '.enabled') ?: []; $methods_weight = $this->languageTypes->get('negotiation.' . $type . '.method_weights') ?: []; // Add missing data to the methods lists. foreach ($negotiation_info as $method_id => $method) { if (!isset($methods_weight[$method_id])) { $methods_weight[$method_id] = isset($method['weight']) ? $method['weight'] : 0; } } // Order methods list by weight. asort($methods_weight); foreach ($methods_weight as $method_id => $weight) { // A language method might be no more available if the defining module has // been disabled after the last configuration saving. if (!isset($negotiation_info[$method_id])) { continue; } $enabled = isset($enabled_methods[$method_id]); $method = $negotiation_info[$method_id]; // List the method only if the current type is defined in its 'types' key. // If it is not defined default to all the configurable language types. $types = array_flip(isset($method['types']) ? $method['types'] : $form['#language_types']); if (isset($types[$type])) { $table_form['#language_negotiation_info'][$method_id] = $method; $method_name = $method['name']; $table_form['weight'][$method_id] = [ '#type' => 'weight', '#title' => $this->t('Weight for @title language detection method', ['@title' => Unicode::strtolower($method_name)]), '#title_display' => 'invisible', '#default_value' => $weight, '#attributes' => ['class' => ["language-method-weight-$type"]], '#delta' => 20, ]; $table_form['title'][$method_id] = ['#plain_text' => $method_name]; $table_form['enabled'][$method_id] = [ '#type' => 'checkbox', '#title' => $this->t('Enable @title language detection method', ['@title' => Unicode::strtolower($method_name)]), '#title_display' => 'invisible', '#default_value' => $enabled, ]; if ($method_id === LanguageNegotiationSelected::METHOD_ID) { $table_form['enabled'][$method_id]['#default_value'] = TRUE; $table_form['enabled'][$method_id]['#attributes'] = ['disabled' => 'disabled']; } $table_form['description'][$method_id] = ['#markup' => $method['description']]; $config_op = []; if (isset($method['config_route_name'])) { $config_op['configure'] = [ 'title' => $this->t('Configure'), 'url' => Url::fromRoute($method['config_route_name']), ]; // If there is at least one operation enabled show the operation // column. $table_form['#show_operations'] = TRUE; } $table_form['operation'][$method_id] = [ '#type' => 'operations', '#links' => $config_op, ]; } } $form[$type] = $table_form; } /** * Disables the language switcher blocks. * * @param array $language_types * An array containing all language types whose language switchers need to * be disabled. */ protected function disableLanguageSwitcher(array $language_types) { $theme = $this->themeHandler->getDefault(); $blocks = $this->blockStorage->loadByProperties(['theme' => $theme]); foreach ($language_types as $language_type) { foreach ($blocks as $block) { if ($block->getPluginId() == 'language_block:' . $language_type) { $block->delete(); } } } } }
oeru/techblog
drupal8/core/modules/language/src/Form/NegotiationConfigureForm.php
PHP
gpl-3.0
11,818
<?php class Appconfig extends CI_Model { public function exists($key) { $this->db->from('app_config'); $this->db->where('app_config.key', $key); return ($this->db->get()->num_rows() == 1); } public function get_all() { $this->db->from('app_config'); $this->db->order_by('key', 'asc'); return $this->db->get(); } public function get($key) { $query = $this->db->get_where('app_config', array('key' => $key), 1); if($query->num_rows() == 1) { return $query->row()->value; } return ''; } public function save($key, $value) { $config_data = array( 'key' => $key, 'value' => $value ); if(!$this->exists($key)) { return $this->db->insert('app_config', $config_data); } $this->db->where('key', $key); return $this->db->update('app_config', $config_data); } public function batch_save($data) { $success = TRUE; //Run these queries as a transaction, we want to make sure we do all or nothing $this->db->trans_start(); foreach($data as $key=>$value) { $success &= $this->save($key, $value); } $this->db->trans_complete(); $success &= $this->db->trans_status(); return $success; } public function delete($key) { return $this->db->delete('app_config', array('key' => $key)); } public function delete_all() { return $this->db->empty_table('app_config'); } } ?>
digyna/digyna-CMS
application/models/mypanel/Appconfig.php
PHP
gpl-3.0
1,375
/* sdsl - succinct data structures library Copyright (C) 2010 Simon Gog 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/ . */ /*! \file algorithms_for_string_matching.hpp \brief algorithms_for_string_matching.hpp contains algorithms for string matching like backward_search, ... \author Simon Gog */ #ifndef INCLUDED_SDSL_ALGORITHMS_FOR_STRING_MATCHING #define INCLUDED_SDSL_ALGORITHMS_FOR_STRING_MATCHING #include "int_vector.hpp" #include <stdexcept> // for exceptions #include <iostream> #include <cassert> #include <stack> #include <utility> namespace sdsl { /*! \author Simon Gog */ namespace algorithm { //! Backward search for a character c on an interval \f$[\ell..r]\f$ of the suffix array. /*! * \param csa The csa in which the backward_search should be done. * \param l Left border of the lcp-interval \f$ [\ell..r]\f$. * \param r Right border of the lcp-interval \f$ [\ell..r]\f$. * \param c The character c which is the starting character of the suffixes in the resulting interval \f$ [\ell_{new}..r_{new}] \f$ . * \param l_res Reference to the resulting left border. * \param r_res Reference to the resulting right border. * \return The size of the new interval [\ell_{new}..r_{new}]. * \pre \f$ 0 \leq \ell \leq r < csa.size() \f$ * * \par Time complexity * \f$ \Order{ t_{rank\_bwt} } \f$ * \par References * Ferragina, P. and Manzini, G. 2000. Opportunistic data structures with applications. FOCS 2000. */ template<class Csa> static typename Csa::csa_size_type backward_search( const Csa& csa, typename Csa::size_type l, typename Csa::size_type r, typename Csa::char_type c, typename Csa::size_type& l_res, typename Csa::size_type& r_res ) { assert(l <= r); assert(r < csa.size()); typename Csa::size_type c_begin = csa.C[csa.char2comp[c]]; l_res = c_begin + csa.rank_bwt(l, c); // count c in bwt[0..l-1] r_res = c_begin + csa.rank_bwt(r+1, c) - 1; // count c in bwt[0..r] assert(r_res+1-l_res >= 0); return r_res+1-l_res; } //! Backward search for a pattern pat on an interval \f$[\ell..r]\f$ of the suffix array. /*! * \param csa The csa in which the backward_search should be done. * \param l Left border of the lcp-interval \f$ [\ell..r]\f$. * \param r Right border of the lcp-interval \f$ [\ell..r]\f$. * \param pat The string which is the prefix of the suffixes in the resulting interval \f$ [\ell_{new}..r_{new}] \f$ . * \param len The length of pat. * \param l_res Reference to the resulting left border. * \param r_res Reference to the resulting right border. * \return The size of the new interval [\ell_{new}..r_{new}]. * \pre \f$ 0 \leq \ell \leq r < csa.size() \f$ * * \par Time complexity * \f$ \Order{ len \cdot t_{rank\_bwt} } \f$ * \par References * Ferragina, P. and Manzini, G. 2000. Opportunistic data structures with applications. FOCS 2000. */ template<class Csa> static typename Csa::csa_size_type backward_search(const Csa& csa, typename Csa::size_type l, typename Csa::size_type r, typename Csa::pattern_type pat, typename Csa::size_type len, typename Csa::size_type& l_res, typename Csa::size_type& r_res) { typename Csa::size_type i = 0; l_res = l; r_res = r; while (i < len and backward_search(csa, l_res, r_res, pat[len-i-1], l_res, r_res)) { ++i; } return r_res+1-l_res; } // TODO: forward search. Include original text??? //! Counts the number of occurences of pattern pat in the string of the compressed suffix array csa. /*! * \param csa The compressed suffix array. * \param pat The pattern for which we count the occurences in the string of the compressed suffix array. * \param len The length of the pattern. * \return The number of occurences of pattern pat in the string of the compressed suffix array. * * \par Time complexity * \f$ \Order{ t_{backward\_search} } \f$ */ template<class Csa> static typename Csa::csa_size_type count(const Csa& csa, typename Csa::pattern_type pat, typename Csa::size_type len) { if (len > csa.size()) return 0; typename Csa::size_type t1,t2; t1=t2=0; // dummy varaiable for the backward_search call return backward_search(csa, 0, csa.size()-1, pat, len, t1, t2); } //! Calculates all occurences of pattern pat in the string of the compressed suffix array csa. /*! * \param csa The compressed suffix array. * \param pat The pattern for which we get the occurences in the string of the compressed suffix array. * \param len The length of the pattern. * \param occ A resizable random access container in which the occurences are stored. * \return The number of occurences of pattern pat of lenght len in the string of the compressed suffix array. * * \par Time complexity * \f$ \Order{ t_{backward\_search} + z \cdot t_{SA} } \f$, where \f$z\f$ is the number of * occurences of pat in the text of the compressed suffix array. */ template<class Csa, class RandomAccessContainer> static typename Csa::csa_size_type locate(const Csa& csa, typename Csa::pattern_type pattern, typename Csa::size_type pattern_len, RandomAccessContainer& occ) { typename Csa::size_type occ_begin, occ_end, occs; occs = backward_search(csa, 0, csa.size()-1, pattern, pattern_len, occ_begin, occ_end); occ.resize(occs); for (typename Csa::size_type i=0; i < occs; ++i) { occ[i] = csa[occ_begin+i]; } return occs; } //! Returns the substring T[begin..end] of the original text T from the corresponding compressed suffix array. /*! * \param csa The compressed suffix array. * \param begin Index of the starting position (inclusive) of the substring in the original text. * \param end Index of the end position (inclusive) of the substring in the original text. * \param text A pointer to the extracted text. The memory has to be initialized before the call of the function! * \pre text has to be initialized with enough memory (end-begin+2 bytes) to hold the extracted text. * \pre \f$begin <= end\f$ and \f$ end < csa.size() \f$ * \par Time complexity * \f$ \Order{ (end-begin+1) \cdot t_{\Psi} + t_{SA^{-1}} } \f$ */ // Is it cheaper to call T[i] = BWT[iSA[i+1]]??? Additional ranks but H_0 average access // TODO: extract backward!!! is faster in most cases! template<class Csa> static void extract(const Csa& csa, typename Csa::size_type begin, typename Csa::size_type end, unsigned char* text) { assert(end <= csa.size()); assert(begin <= end); for (typename Csa::size_type i=begin, order = csa(begin); i<=end; ++i, order = csa.psi[order]) { uint16_t c_begin = 1, c_end = 257, mid; while (c_begin < c_end) { mid = (c_begin+c_end)>>1; if (csa.C[mid] <= order) { c_begin = mid+1; } else { c_end = mid; } } text[i-begin] = csa.comp2char[c_begin-1]; } if (text[end-begin]!=0) text[end-begin+1] = 0; // set terminal character } //! Reconstructs the text from position \f$begin\f$ to position \f$end\f$ (inclusive) from the compressed suffix array. /*! * \param csa The compressed suffix array. * \param begin Starting position (inclusive) of the text to extract. * \param end End position (inclusive) of the text to extract. * \return A std::string holding the extracted text. * \pre \f$begin <= end\f$ and \f$ end < csa.size() \f$ * \par Time complexity * \f$ \Order{ (end-begin+1) \cdot t_{\Psi} + t_{SA^{-1}} } \f$ */ // TODO: use extract with four parameters to implement this method template<class Csa> static std::string extract(const Csa& csa, typename Csa::size_type begin, typename Csa::size_type end) { assert(end <= csa.size()); assert(begin <= end); std::string result(end-begin+1,' '); for (typename Csa::size_type i=begin, order = csa(begin); i<=end; ++i, order = csa.psi[order]) { uint16_t c_begin = 1, c_end = 257, mid; while (c_begin < c_end) { mid = (c_begin+c_end)>>1; if (csa.C[mid] <= order) { c_begin = mid+1; } else { c_end = mid; } } result[i-begin] = csa.comp2char[c_begin-1]; } return result; } //! Forward search for a character c on the path on depth \f$d\f$ to node \f$v\f$. /*! * \param cst The compressed suffix tree. * \param v The node at the endpoint of the current edge. * \param d The current depth of the path. 0 = first character on each edge of the root node. * \param c The character c which should be matched at the path on depth \f$d\f$ to node \f$v\f$. * \param char_pos One position in the text, which corresponds to the text that is already matched. If v=cst.root() and d=0 => char_pos=0. * * \par Time complexity * \f$ \Order{ t_{\Psi} } \f$ or \f$ \Order{t_{cst.child}} \f$ */ template<class Cst> typename Cst::cst_size_type forward_search(const Cst& cst, typename Cst::node_type& v, const typename Cst::size_type d, const typename Cst::char_type c, typename Cst::size_type& char_pos) { unsigned char cc = cst.csa.char2comp[c]; // check if c occures in the text of the csa if (cc==0 and cc!=c) // " " " " " " " " " " return 0; typename Cst::size_type depth_node = cst.depth(v); if (d < depth_node) { // char_pos = cst.csa.psi[char_pos]; if (char_pos < cst.csa.C[cc] or char_pos >= cst.csa.C[cc+1]) return 0; return cst.leaves_in_the_subtree(v); } else if (d == depth_node) { // v = cst.child(v, c, char_pos); if (v == cst.root()) return 0; else return cst.leaves_in_the_subtree(v); } else { throw std::invalid_argument("depth d should be smaller or equal than node depth of v!"); return 0; } } //! Forward search for a pattern pat on the path on depth \f$d\f$ to node \f$v\f$. /*! * \param cst The compressed suffix tree. * \param v The node at the endpoint of the current edge. * \param d The current depth of the path. 0 = first character on each edge of the root node. * \param pat The character c which should be matched at the path on depth \f$d\f$ to node \f$v\f$. * \param len The length of the pattern. * \param char_pos One position in the text, which corresponds to the text that is already matched. If v=cst.root() and d=0 => char_pos=0. * * \par Time complexity * \f$ \Order{ t_{\Psi} } \f$ or \f$ \Order{t_{cst.child}} \f$ */ template<class Cst> typename Cst::cst_size_type forward_search(const Cst& cst, typename Cst::node_type& v, typename Cst::size_type d, typename Cst::pattern_type pat, typename Cst::size_type len, typename Cst::size_type& char_pos ) { if (len==0) return cst.leaves_in_the_subtree(v); typename Cst::size_type i=0, size=0; while (i < len and (size=forward_search(cst, v, d, pat[i], char_pos))) { ++d; ++i; } return size; } //! Calculates the count method for a (compressed) suffix tree of type Cst. /*! \param cst A const reference to the (compressed) suffix tree. * \param pat The pattern we seach the number of occurences. * \param len The length of the pattern. * \return Number of occurences of the pattern in the text of the (compressed) suffix tree. */ template<class Cst> typename Cst::cst_size_type count(const Cst& cst, typename Cst::pattern_type pat, typename Cst::size_type len) { typename Cst::node_type v = cst.root(); typename Cst::size_type char_pos = 0; return forward_search(cst, v, 0, pat, len, char_pos); } //! Calculates the locate method for a (compressed) suffix tree of type Cst. /*! \param cst A const reference to the (compressed) suffix tree. * \param pat The pattern for which we seach the occurences for. * \param len The length of the pattern. * \param occ A reference to a random access container in which we store the occurences of pattern in the text of the (compressed suffix array). * \return Number of occurences of the pattern in the text of the (compressed) suffix tree. */ template<class Cst, class RandomAccessContainer> typename Cst::cst_size_type locate(const Cst& cst, typename Cst::pattern_type pat, typename Cst::size_type len, RandomAccessContainer& occ) { typedef typename Cst::size_type size_type; typename Cst::node_type v = cst.root(); size_type char_pos = 0; typename Cst::cst_size_type occs = forward_search(cst, v, 0, pat, len, char_pos); occ.resize(occs); if (occs == 0) return 0; // because v equals cst.root() size_type left = cst.lb(v); // get range in the size_type right = cst.rb(v); for (size_type i=left; i <= right; ++i) occ[i-left] = cst.csa[i]; return occs; } //! Calculate the concatenation of edge labels from the root to the node v of the (compressed) suffix tree of type Cst. /*! * \param cst A const reference to the compressed suffix tree. * \param v The node where the concatenation of the edge labels ends. * \param text A pointer in which the string representing the concatenation of edge labels form the root to the node v will be stored. * \pre text has to be initialized with enough memory (\f$ cst.depth(v)+1\f$ bytes) to hold the extracted text. */ template<class Cst> void extract(const Cst& cst, const typename Cst::node_type& v, unsigned char* text) { if (v == cst.root()) { text[0] = 0; return; } // first get the suffix array entry of the leftmost leaf in the subtree rooted at v typename Cst::size_type begin = cst.csa[cst.lb(v)]; // then call the extract method on the compressed suffix array extract(cst.csa, begin, begin + cst.depth(v) - 1, text); } //! Calculate the concatenation of edge labels from the root to the node v of the (compressed) suffix tree of type Cst. /*! * \param cst A const reference to the compressed suffix tree. * \param v The node where the concatenation of the edge labels ends. * \return The string of the concatenated edge labels from the root to the node v. */ template<class Cst> std::string extract(const Cst& cst, const typename Cst::node_type& v) { if (v==cst.root()) { return std::string(); } // first get the suffix array entry of the leftmost leaf in the subtree rooted at v typename Cst::size_type begin = cst.csa[cst.lb(v)]; // then call the extract method on the compressed suffix array return extract(cst.csa, begin, begin + cst.depth(v) - 1); } /* template<class Cst> typename Cst::size_type count( const Cst &cst, typename Cst::pattern_type pattern, typename Cst::size_type pattern_len){ if(pattern_len==0){ return 0; } typedef typename Cst::size_type size_type; typedef typename Cst::node_type node_type; node_type node = cst.root(); for(size_type i=0, char_pos=0; cst.depth(node) < pattern_len; ++i){ node_type newnode = cst.child(node, (unsigned char)pattern[cst.depth(node)], char_pos); if( newnode == cst.root() )// root node, no match found return 0; // else the first character of the newnode matches the pattern at position depth(node) for(size_type j=cst.depth(node)+1; j < cst.depth(newnode) and j < pattern_len; ++j){ char_pos = cst.csa.psi[char_pos]; size_type cc = cst.csa.char2comp[pattern[j]]; if(char_pos < cst.csa.C[cc] or char_pos >= cst.csa.C[cc+1] ) return 0; } node = newnode; } return cst.leaves_in_the_subtree(node); } */ /* template<class Cst, class RandomAccessContainer> typename Cst::size_type locate( const Cst &cst, typename Cst::pattern_type pattern, typename Cst::size_type pattern_len, RandomAccessContainer &occ){ occ.resize(0); typedef typename Cst::size_type size_type; typedef typename Cst::node_type node_type; node_type node = cst.root(); for(size_type i=0, char_pos=0; cst.depth(node) < pattern_len; ++i){ node_type newnode = cst.child(node, (unsigned char)pattern[cst.depth(node)], char_pos); if( newnode == cst.root() )// root node, no match found return 0; // else the first character of the newnode matches the pattern at position depth(node) for(size_type j=cst.depth(node)+1; j < cst.depth(newnode) and j < pattern_len; ++j){ char_pos = cst.csa.psi[char_pos]; size_type cc = cst.csa.char2comp[pattern[j]]; if(char_pos < cst.csa.C[cc] or char_pos >= cst.csa.C[cc+1] ) return 0; } node = newnode; } size_type occs = cst.leaves_in_the_subtree(node); occ.resize(occs); size_type left = cst.leftmost_suffix_array_index_in_the_subtree(node); size_type right = cst.rightmost_suffix_array_index_in_the_subtree(node); for(size_type i=left; i <= right; ++i) occ[i-left] = cst.csa[i]; return occs; } */ /* template<class Csa, class Lcp, class Bp_support> typename cst_sct<Csa, Lcp, Bp_support>::size_type count( const cst_sct<Csa, Lcp, Bp_support> &cst, typename cst_sct<Csa, Lcp, Bp_support>::pattern_type pattern, typename cst_sct<Csa, Lcp, Bp_support>::size_type pattern_len){ if(pattern_len==0){ return 0; } typedef typename cst_sct<Csa, Lcp, Bp_support>::size_type size_type; typedef typename cst_sct<Csa, Lcp, Bp_support>::node_type node_type; node_type node = cst.root(); for(size_type i=0, char_pos=0; node.l < pattern_len; ++i){ node_type newnode = cst.child(node, (unsigned char)pattern[node.l], char_pos); if( newnode.l == 0 )// root node, no match found return 0; // else the first character of the newnode matches the pattern at position node.l for(size_type j=node.l+1; j < newnode.l and j< pattern_len; ++j){ char_pos = cst.csa.psi[char_pos]; size_type cc = cst.csa.char2comp[pattern[j]]; if(char_pos < cst.csa.C[cc] or char_pos >= cst.csa.C[cc+1] ) return 0; } node = newnode; } return cst.leaves_in_the_subtree(node); } */ } // end namespace algorithm } // end namespace sdsl #endif
andmaj/unrank-bottleneck-bench
sdsl_linear/include/sdsl/algorithms_for_string_matching.hpp
C++
gpl-3.0
18,541
/* * Copyright (C) 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 com.google.android.exoplayer.text.tx3g; import com.google.android.exoplayer.text.Cue; import com.google.android.exoplayer.text.Subtitle; import com.google.android.exoplayer.text.SubtitleParser; import com.google.android.exoplayer.util.MimeTypes; import com.google.android.exoplayer.util.ParsableByteArray; /** * A {@link SubtitleParser} for tx3g. * <p> * Currently only supports parsing of a single text track. */ public final class Tx3gParser implements SubtitleParser { private final ParsableByteArray parsableByteArray; public Tx3gParser() { parsableByteArray = new ParsableByteArray(); } @Override public boolean canParse(String mimeType) { return MimeTypes.APPLICATION_TX3G.equals(mimeType); } @Override public Subtitle parse(byte[] bytes, int offset, int length) { parsableByteArray.reset(bytes, length); int textLength = parsableByteArray.readUnsignedShort(); if (textLength == 0) { return Tx3gSubtitle.EMPTY; } String cueText = parsableByteArray.readString(textLength); return new Tx3gSubtitle(new Cue(cueText)); } }
Lee-Wills/-tv
mmd/library/src/main/java/com/google/android/exoplayer/text/tx3g/Tx3gParser.java
Java
gpl-3.0
1,720
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. goog.provide('goog.editor.plugins.LinkBubbleTest'); goog.setTestOnly('goog.editor.plugins.LinkBubbleTest'); goog.require('goog.dom'); goog.require('goog.dom.Range'); goog.require('goog.dom.TagName'); goog.require('goog.editor.Command'); goog.require('goog.editor.Link'); goog.require('goog.editor.plugins.LinkBubble'); goog.require('goog.events.BrowserEvent'); goog.require('goog.events.Event'); goog.require('goog.events.EventType'); goog.require('goog.events.KeyCodes'); goog.require('goog.string'); goog.require('goog.style'); goog.require('goog.testing.FunctionMock'); goog.require('goog.testing.PropertyReplacer'); goog.require('goog.testing.editor.FieldMock'); goog.require('goog.testing.editor.TestHelper'); goog.require('goog.testing.events'); goog.require('goog.testing.jsunit'); goog.require('goog.userAgent'); var fieldDiv; var FIELDMOCK; var linkBubble; var link; var linkChild; var mockWindowOpen; var stubs; var testHelper; function setUpPage() { fieldDiv = goog.dom.$('field'); stubs = new goog.testing.PropertyReplacer(); testHelper = new goog.testing.editor.TestHelper(goog.dom.getElement('field')); } function setUp() { testHelper.setUpEditableElement(); FIELDMOCK = new goog.testing.editor.FieldMock(); linkBubble = new goog.editor.plugins.LinkBubble(); linkBubble.fieldObject = FIELDMOCK; link = fieldDiv.firstChild; linkChild = link.lastChild; mockWindowOpen = new goog.testing.FunctionMock('open'); stubs.set(window, 'open', mockWindowOpen); } function tearDown() { linkBubble.closeBubble(); testHelper.tearDownEditableElement(); stubs.reset(); } function testLinkSelected() { FIELDMOCK.$replay(); linkBubble.enable(FIELDMOCK); goog.dom.Range.createFromNodeContents(link).select(); linkBubble.handleSelectionChange(); assertBubble(); FIELDMOCK.$verify(); } function testLinkClicked() { FIELDMOCK.$replay(); linkBubble.enable(FIELDMOCK); linkBubble.handleSelectionChange(createMouseEvent(link)); assertBubble(); FIELDMOCK.$verify(); } function testImageLink() { FIELDMOCK.$replay(); linkBubble.enable(FIELDMOCK); link.setAttribute('imageanchor', 1); linkBubble.handleSelectionChange(createMouseEvent(link)); assertBubble(); FIELDMOCK.$verify(); } function closeBox() { var closeBox = goog.dom.getElementsByTagNameAndClass(goog.dom.TagName.DIV, 'tr_bubble_closebox'); assertEquals('Should find only one close box', 1, closeBox.length); assertNotNull('Found close box', closeBox[0]); goog.testing.events.fireClickSequence(closeBox[0]); } function testCloseBox() { testLinkClicked(); closeBox(); assertNoBubble(); FIELDMOCK.$verify(); } function testChangeClicked() { FIELDMOCK.execCommand(goog.editor.Command.MODAL_LINK_EDITOR, new goog.editor.Link(link, false)); FIELDMOCK.$registerArgumentListVerifier('execCommand', function(arr1, arr2) { return arr1.length == arr2.length && arr1.length == 2 && arr1[0] == goog.editor.Command.MODAL_LINK_EDITOR && arr2[0] == goog.editor.Command.MODAL_LINK_EDITOR && arr1[1] instanceof goog.editor.Link && arr2[1] instanceof goog.editor.Link; }); FIELDMOCK.$times(1); FIELDMOCK.$returns(true); FIELDMOCK.$replay(); linkBubble.enable(FIELDMOCK); linkBubble.handleSelectionChange(createMouseEvent(link)); assertBubble(); goog.testing.events.fireClickSequence( goog.dom.$(goog.editor.plugins.LinkBubble.CHANGE_LINK_ID_)); assertNoBubble(); FIELDMOCK.$verify(); } function testChangePressed() { FIELDMOCK.execCommand(goog.editor.Command.MODAL_LINK_EDITOR, new goog.editor.Link(link, false)); FIELDMOCK.$registerArgumentListVerifier('execCommand', function(arr1, arr2) { return arr1.length == arr2.length && arr1.length == 2 && arr1[0] == goog.editor.Command.MODAL_LINK_EDITOR && arr2[0] == goog.editor.Command.MODAL_LINK_EDITOR && arr1[1] instanceof goog.editor.Link && arr2[1] instanceof goog.editor.Link; }); FIELDMOCK.$times(1); FIELDMOCK.$returns(true); FIELDMOCK.$replay(); linkBubble.enable(FIELDMOCK); linkBubble.handleSelectionChange(createMouseEvent(link)); assertBubble(); var defaultPrevented = !goog.testing.events.fireKeySequence( goog.dom.$(goog.editor.plugins.LinkBubble.CHANGE_LINK_ID_), goog.events.KeyCodes.ENTER); assertTrue(defaultPrevented); assertNoBubble(); FIELDMOCK.$verify(); } function testDeleteClicked() { FIELDMOCK.dispatchBeforeChange(); FIELDMOCK.$times(1); FIELDMOCK.dispatchChange(); FIELDMOCK.$times(1); FIELDMOCK.focus(); FIELDMOCK.$times(1); FIELDMOCK.$replay(); linkBubble.enable(FIELDMOCK); linkBubble.handleSelectionChange(createMouseEvent(link)); assertBubble(); goog.testing.events.fireClickSequence( goog.dom.$(goog.editor.plugins.LinkBubble.DELETE_LINK_ID_)); var element = goog.userAgent.GECKO ? document.body : fieldDiv; assertNotEquals('Link removed', element.firstChild.nodeName, goog.dom.TagName.A); assertNoBubble(); var range = goog.dom.Range.createFromWindow(); assertEquals('Link selection on link text', linkChild, range.getEndNode()); assertEquals('Link selection on link text end', goog.dom.getRawTextContent(linkChild).length, range.getEndOffset()); FIELDMOCK.$verify(); } function testDeletePressed() { FIELDMOCK.dispatchBeforeChange(); FIELDMOCK.$times(1); FIELDMOCK.dispatchChange(); FIELDMOCK.$times(1); FIELDMOCK.focus(); FIELDMOCK.$times(1); FIELDMOCK.$replay(); linkBubble.enable(FIELDMOCK); linkBubble.handleSelectionChange(createMouseEvent(link)); assertBubble(); var defaultPrevented = !goog.testing.events.fireKeySequence( goog.dom.$(goog.editor.plugins.LinkBubble.DELETE_LINK_ID_), goog.events.KeyCodes.ENTER); assertTrue(defaultPrevented); var element = goog.userAgent.GECKO ? document.body : fieldDiv; assertNotEquals('Link removed', element.firstChild.nodeName, goog.dom.TagName.A); assertNoBubble(); var range = goog.dom.Range.createFromWindow(); assertEquals('Link selection on link text', linkChild, range.getEndNode()); assertEquals('Link selection on link text end', goog.dom.getRawTextContent(linkChild).length, range.getEndOffset()); FIELDMOCK.$verify(); } function testActionClicked() { var SPAN = 'actionSpanId'; var LINK = 'actionLinkId'; var toShowCount = 0; var actionCount = 0; var linkAction = new goog.editor.plugins.LinkBubble.Action( SPAN, LINK, 'message', function() { toShowCount++; return toShowCount == 1; // Show it the first time. }, function() { actionCount++; }); linkBubble = new goog.editor.plugins.LinkBubble(linkAction); linkBubble.fieldObject = FIELDMOCK; FIELDMOCK.$replay(); linkBubble.enable(FIELDMOCK); // The first time the bubble is shown, show our custom action. linkBubble.handleSelectionChange(createMouseEvent(link)); assertBubble(); assertEquals('Should check showing the action', 1, toShowCount); assertEquals('Action should not have fired yet', 0, actionCount); assertTrue('Action should be visible 1st time', goog.style.isElementShown( goog.dom.$(SPAN))); goog.testing.events.fireClickSequence(goog.dom.$(LINK)); assertEquals('Should not check showing again yet', 1, toShowCount); assertEquals('Action should be fired', 1, actionCount); closeBox(); assertNoBubble(); // The action won't be shown the second time around. linkBubble.handleSelectionChange(createMouseEvent(link)); assertBubble(); assertEquals('Should check showing again', 2, toShowCount); assertEquals('Action should not fire again', 1, actionCount); assertFalse('Action should not be shown 2nd time', goog.style.isElementShown( goog.dom.$(SPAN))); FIELDMOCK.$verify(); } function testLinkTextClicked() { mockWindowOpen('http://www.google.com/', '_blank', ''); mockWindowOpen.$replay(); FIELDMOCK.$replay(); linkBubble.enable(FIELDMOCK); linkBubble.handleSelectionChange(createMouseEvent(link)); assertBubble(); goog.testing.events.fireClickSequence( goog.dom.$(goog.editor.plugins.LinkBubble.TEST_LINK_ID_)); assertBubble(); mockWindowOpen.$verify(); FIELDMOCK.$verify(); } function testLinkTextClickedCustomUrlFn() { mockWindowOpen('http://images.google.com/', '_blank', ''); mockWindowOpen.$replay(); FIELDMOCK.$replay(); linkBubble.enable(FIELDMOCK); linkBubble.setTestLinkUrlFn(function(url) { return url.replace('www', 'images'); }); linkBubble.handleSelectionChange(createMouseEvent(link)); assertBubble(); goog.testing.events.fireClickSequence( goog.dom.$(goog.editor.plugins.LinkBubble.TEST_LINK_ID_)); assertBubble(); mockWindowOpen.$verify(); FIELDMOCK.$verify(); } /** * Urls with invalid schemes shouldn't be linkified. * @bug 2585360 */ function testDontLinkifyInvalidScheme() { mockWindowOpen.$replay(); FIELDMOCK.$replay(); linkBubble.enable(FIELDMOCK); var badLink = document.createElement(goog.dom.TagName.A); badLink.href = 'javascript:alert(1)'; badLink.innerHTML = 'bad link'; linkBubble.handleSelectionChange(createMouseEvent(badLink)); assertBubble(); // The link shouldn't exist at all assertNull(goog.dom.$(goog.editor.plugins.LinkBubble.TEST_LINK_ID_)); assertBubble(); mockWindowOpen.$verify(); FIELDMOCK.$verify(); } function testIsSafeSchemeToOpen() { // Urls with no scheme at all are ok too since 'http://' will be prepended. var good = [ 'http://google.com', 'http://google.com/', 'https://google.com', 'null@google.com', 'http://www.google.com', 'http://site.com', 'google.com', 'google', 'http://google', 'HTTP://GOOGLE.COM', 'HtTp://www.google.com' ]; var bad = [ 'javascript:google.com', 'httpp://google.com', 'data:foo', 'javascript:alert(\'hi\');', 'abc:def' ]; for (var i = 0; i < good.length; i++) { assertTrue(good[i] + ' should have a safe scheme', linkBubble.isSafeSchemeToOpen_(good[i])); } for (i = 0; i < bad.length; i++) { assertFalse(bad[i] + ' should have an unsafe scheme', linkBubble.isSafeSchemeToOpen_(bad[i])); } } function testShouldOpenWithWhitelist() { linkBubble.setSafeToOpenSchemes(['abc']); assertTrue('Scheme should be safe', linkBubble.shouldOpenUrl('abc://google.com')); assertFalse('Scheme should be unsafe', linkBubble.shouldOpenUrl('http://google.com')); linkBubble.setBlockOpeningUnsafeSchemes(false); assertTrue('Non-whitelisted should now be safe after disabling blocking', linkBubble.shouldOpenUrl('http://google.com')); } /** * @bug 763211 * @bug 2182147 */ function testLongUrlTestLinkAnchorTextCorrect() { FIELDMOCK.$replay(); linkBubble.enable(FIELDMOCK); var longUrl = 'http://www.reallylonglinkthatshouldbetruncated' + 'becauseitistoolong.com'; var truncatedLongUrl = goog.string.truncateMiddle(longUrl, 48); var longLink = document.createElement(goog.dom.TagName.A); longLink.href = longUrl; longLink.innerHTML = 'Google'; fieldDiv.appendChild(longLink); linkBubble.handleSelectionChange(createMouseEvent(longLink)); assertBubble(); var testLinkEl = goog.dom.$(goog.editor.plugins.LinkBubble.TEST_LINK_ID_); assertEquals( 'The test link\'s anchor text should be the truncated URL.', truncatedLongUrl, testLinkEl.innerHTML); fieldDiv.removeChild(longLink); FIELDMOCK.$verify(); } /** * @bug 2416024 */ function testOverridingCreateBubbleContentsDoesntNpeGetTargetUrl() { FIELDMOCK.$replay(); linkBubble.enable(FIELDMOCK); stubs.set(linkBubble, 'createBubbleContents', function(elem) { // getTargetUrl would cause an NPE if urlUtil_ wasn't defined yet. linkBubble.getTargetUrl(); }); assertNotThrows('Accessing this.urlUtil_ should not NPE', goog.bind(linkBubble.handleSelectionChange, linkBubble, createMouseEvent(link))); FIELDMOCK.$verify(); } /** * @bug 15379294 */ function testUpdateLinkCommandDoesNotTriggerAnException() { FIELDMOCK.$replay(); linkBubble.enable(FIELDMOCK); // At this point, the bubble was not created yet using its createBubble // public method. assertNotThrows( 'Executing goog.editor.Command.UPDATE_LINK_BUBBLE should not trigger ' + 'an exception even if the bubble was not created yet using its ' + 'createBubble method.', goog.bind(linkBubble.execCommandInternal, linkBubble, goog.editor.Command.UPDATE_LINK_BUBBLE)); FIELDMOCK.$verify(); } function assertBubble() { assertTrue('Link bubble visible', linkBubble.isVisible()); assertNotNull('Link bubble created', goog.dom.$(goog.editor.plugins.LinkBubble.LINK_DIV_ID_)); } function assertNoBubble() { assertFalse('Link bubble not visible', linkBubble.isVisible()); assertNull('Link bubble not created', goog.dom.$(goog.editor.plugins.LinkBubble.LINK_DIV_ID_)); } function createMouseEvent(target) { var eventObj = new goog.events.Event(goog.events.EventType.MOUSEUP, target); eventObj.button = goog.events.BrowserEvent.MouseButton.LEFT; return new goog.events.BrowserEvent(eventObj, target); }
Nestor94Gonzalez/robot_blockly
frontend/closure-library/closure/goog/editor/plugins/linkbubble_test.js
JavaScript
gpl-3.0
13,917
#region Copyright & License Information /* * Copyright 2007-2015 The OpenRA Developers (see AUTHORS) * This file is part of OpenRA, which is free software. It is made * available to you under the terms of the GNU General Public License * as published by the Free Software Foundation. For more information, * see COPYING. */ #endregion using System; using OpenRA.Network; using OpenRA.Widgets; namespace OpenRA.Mods.Common.Widgets.Logic { public class GameTimerLogic { [ObjectCreator.UseCtor] public GameTimerLogic(Widget widget, OrderManager orderManager, World world) { var timer = widget.GetOrNull<LabelWidget>("GAME_TIMER"); var status = widget.GetOrNull<LabelWidget>("GAME_TIMER_STATUS"); var startTick = Ui.LastTickTime; Func<bool> shouldShowStatus = () => (world.Paused || world.Timestep != Game.Timestep) && (Ui.LastTickTime - startTick) / 1000 % 2 == 0; Func<string> statusText = () => { if (world.Paused || world.Timestep == 0) return "Paused"; if (world.Timestep == 1) return "Max Speed"; return "{0}% Speed".F(Game.Timestep * 100 / world.Timestep); }; if (timer != null) { timer.GetText = () => { if (status == null && shouldShowStatus()) return statusText(); return WidgetUtils.FormatTime(world.WorldTick); }; } if (status != null) { // Blink the status line status.IsVisible = shouldShowStatus; status.GetText = statusText; } var percentage = widget.GetOrNull<LabelWidget>("GAME_TIMER_PERCENTAGE"); if (percentage != null) { var connection = orderManager.Connection as ReplayConnection; if (connection != null && connection.TickCount != 0) percentage.GetText = () => "({0}%)".F(orderManager.NetFrameNumber * 100 / connection.TickCount); else timer.Bounds.Width += percentage.Bounds.Width; } } } }
Sithil-F/OpenRA
OpenRA.Mods.Common/Widgets/Logic/Ingame/GameTimerLogic.cs
C#
gpl-3.0
1,876
# # Copyright 2006,2007 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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. # # GNU Radio 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 GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, optfir from gnuradio.blks2impl.fm_emph import fm_deemph from math import pi class fm_demod_cf(gr.hier_block2): """ Generalized FM demodulation block with deemphasis and audio filtering. This block demodulates a band-limited, complex down-converted FM channel into the the original baseband signal, optionally applying deemphasis. Low pass filtering is done on the resultant signal. It produces an output float strem in the range of [-1.0, +1.0]. @param channel_rate: incoming sample rate of the FM baseband @type sample_rate: integer @param deviation: maximum FM deviation (default = 5000) @type deviation: float @param audio_decim: input to output decimation rate @type audio_decim: integer @param audio_pass: audio low pass filter passband frequency @type audio_pass: float @param audio_stop: audio low pass filter stop frequency @type audio_stop: float @param gain: gain applied to audio output (default = 1.0) @type gain: float @param tau: deemphasis time constant (default = 75e-6), specify 'None' to prevent deemphasis """ def __init__(self, channel_rate, audio_decim, deviation, audio_pass, audio_stop, gain=1.0, tau=75e-6): gr.hier_block2.__init__(self, "fm_demod_cf", gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature gr.io_signature(1, 1, gr.sizeof_float)) # Output signature k = channel_rate/(2*pi*deviation) QUAD = gr.quadrature_demod_cf(k) audio_taps = optfir.low_pass(gain, # Filter gain channel_rate, # Sample rate audio_pass, # Audio passband audio_stop, # Audio stopband 0.1, # Passband ripple 60) # Stopband attenuation LPF = gr.fir_filter_fff(audio_decim, audio_taps) if tau is not None: DEEMPH = fm_deemph(channel_rate, tau) self.connect(self, QUAD, DEEMPH, LPF, self) else: self.connect(self, QUAD, LPF, self) class demod_20k0f3e_cf(fm_demod_cf): """ NBFM demodulation block, 20 KHz channels This block demodulates a complex, downconverted, narrowband FM channel conforming to 20K0F3E emission standards, outputting floats in the range [-1.0, +1.0]. @param sample_rate: incoming sample rate of the FM baseband @type sample_rate: integer @param audio_decim: input to output decimation rate @type audio_decim: integer """ def __init__(self, channel_rate, audio_decim): fm_demod_cf.__init__(self, channel_rate, audio_decim, 5000, # Deviation 3000, # Audio passband frequency 4500) # Audio stopband frequency class demod_200kf3e_cf(fm_demod_cf): """ WFM demodulation block, mono. This block demodulates a complex, downconverted, wideband FM channel conforming to 200KF3E emission standards, outputting floats in the range [-1.0, +1.0]. @param sample_rate: incoming sample rate of the FM baseband @type sample_rate: integer @param audio_decim: input to output decimation rate @type audio_decim: integer """ def __init__(self, channel_rate, audio_decim): fm_demod_cf.__init__(self, channel_rate, audio_decim, 75000, # Deviation 15000, # Audio passband 16000, # Audio stopband 20.0) # Audio gain
n4hy/gnuradio
gnuradio-core/src/python/gnuradio/blks2impl/fm_demod.py
Python
gpl-3.0
4,236
class PortalGroup::Admin::Piece::SiteAreasController < Cms::Admin::Piece::BaseController end
tao-k/zomeki
app/controllers/portal_group/admin/piece/site_areas_controller.rb
Ruby
gpl-3.0
93
<?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 the base class for question import and export formats. * * @package moodlecore * @subpackage questionbank * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); /** * Base class for question import and export formats. * * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class qformat_default { public $displayerrors = true; public $category = null; public $questions = array(); public $course = null; public $filename = ''; public $realfilename = ''; public $matchgrades = 'error'; public $catfromfile = 0; public $contextfromfile = 0; public $cattofile = 0; public $contexttofile = 0; public $questionids = array(); public $importerrors = 0; public $stoponerror = true; public $translator = null; public $canaccessbackupdata = true; protected $importcontext = null; // functions to indicate import/export functionality // override to return true if implemented /** @return bool whether this plugin provides import functionality. */ public function provide_import() { return false; } /** @return bool whether this plugin provides export functionality. */ public function provide_export() { return false; } /** The string mime-type of the files that this plugin reads or writes. */ public function mime_type() { return mimeinfo('type', $this->export_file_extension()); } /** * @return string the file extension (including .) that is normally used for * files handled by this plugin. */ public function export_file_extension() { return '.txt'; } /** * Check if the given file is capable of being imported by this plugin. * * Note that expensive or detailed integrity checks on the file should * not be performed by this method. Simple file type or magic-number tests * would be suitable. * * @param stored_file $file the file to check * @return bool whether this plugin can import the file */ public function can_import_file($file) { return ($file->get_mimetype() == $this->mime_type()); } // Accessor methods /** * set the category * @param object category the category object */ public function setCategory($category) { if (count($this->questions)) { debugging('You shouldn\'t call setCategory after setQuestions'); } $this->category = $category; $this->importcontext = context::instance_by_id($this->category->contextid); } /** * Set the specific questions to export. Should not include questions with * parents (sub questions of cloze question type). * Only used for question export. * @param array of question objects */ public function setQuestions($questions) { if ($this->category !== null) { debugging('You shouldn\'t call setQuestions after setCategory'); } $this->questions = $questions; } /** * set the course class variable * @param course object Moodle course variable */ public function setCourse($course) { $this->course = $course; } /** * set an array of contexts. * @param array $contexts Moodle course variable */ public function setContexts($contexts) { $this->contexts = $contexts; $this->translator = new context_to_string_translator($this->contexts); } /** * set the filename * @param string filename name of file to import/export */ public function setFilename($filename) { $this->filename = $filename; } /** * set the "real" filename * (this is what the user typed, regardless of wha happened next) * @param string realfilename name of file as typed by user */ public function setRealfilename($realfilename) { $this->realfilename = $realfilename; } /** * set matchgrades * @param string matchgrades error or nearest for grades */ public function setMatchgrades($matchgrades) { $this->matchgrades = $matchgrades; } /** * set catfromfile * @param bool catfromfile allow categories embedded in import file */ public function setCatfromfile($catfromfile) { $this->catfromfile = $catfromfile; } /** * set contextfromfile * @param bool $contextfromfile allow contexts embedded in import file */ public function setContextfromfile($contextfromfile) { $this->contextfromfile = $contextfromfile; } /** * set cattofile * @param bool cattofile exports categories within export file */ public function setCattofile($cattofile) { $this->cattofile = $cattofile; } /** * set contexttofile * @param bool cattofile exports categories within export file */ public function setContexttofile($contexttofile) { $this->contexttofile = $contexttofile; } /** * set stoponerror * @param bool stoponerror stops database write if any errors reported */ public function setStoponerror($stoponerror) { $this->stoponerror = $stoponerror; } /** * @param bool $canaccess Whether the current use can access the backup data folder. Determines * where export files are saved. */ public function set_can_access_backupdata($canaccess) { $this->canaccessbackupdata = $canaccess; } /*********************** * IMPORTING FUNCTIONS ***********************/ /** * Handle parsing error */ protected function error($message, $text='', $questionname='') { $importerrorquestion = get_string('importerrorquestion', 'question'); echo "<div class=\"importerror\">\n"; echo "<strong>$importerrorquestion $questionname</strong>"; if (!empty($text)) { $text = s($text); echo "<blockquote>$text</blockquote>\n"; } echo "<strong>$message</strong>\n"; echo "</div>"; $this->importerrors++; } /** * Import for questiontype plugins * Do not override. * @param data mixed The segment of data containing the question * @param question object processed (so far) by standard import code if appropriate * @param extra mixed any additional format specific data that may be passed by the format * @param qtypehint hint about a question type from format * @return object question object suitable for save_options() or false if cannot handle */ public function try_importing_using_qtypes($data, $question = null, $extra = null, $qtypehint = '') { // work out what format we are using $formatname = substr(get_class($this), strlen('qformat_')); $methodname = "import_from_$formatname"; //first try importing using a hint from format if (!empty($qtypehint)) { $qtype = question_bank::get_qtype($qtypehint, false); if (is_object($qtype) && method_exists($qtype, $methodname)) { $question = $qtype->$methodname($data, $question, $this, $extra); if ($question) { return $question; } } } // loop through installed questiontypes checking for // function to handle this question foreach (question_bank::get_all_qtypes() as $qtype) { if (method_exists($qtype, $methodname)) { if ($question = $qtype->$methodname($data, $question, $this, $extra)) { return $question; } } } return false; } /** * Perform any required pre-processing * @return bool success */ public function importpreprocess() { return true; } /** * Process the file * This method should not normally be overidden * @param object $category * @return bool success */ public function importprocess($category) { global $USER, $CFG, $DB, $OUTPUT; // reset the timer in case file upload was slow set_time_limit(0); // STAGE 1: Parse the file echo $OUTPUT->notification(get_string('parsingquestions', 'question'), 'notifysuccess'); if (! $lines = $this->readdata($this->filename)) { echo $OUTPUT->notification(get_string('cannotread', 'question')); return false; } if (!$questions = $this->readquestions($lines)) { // Extract all the questions echo $OUTPUT->notification(get_string('noquestionsinfile', 'question')); return false; } // STAGE 2: Write data to database echo $OUTPUT->notification(get_string('importingquestions', 'question', $this->count_questions($questions)), 'notifysuccess'); // check for errors before we continue if ($this->stoponerror and ($this->importerrors>0)) { echo $OUTPUT->notification(get_string('importparseerror', 'question')); return true; } // get list of valid answer grades $gradeoptionsfull = question_bank::fraction_options_full(); // check answer grades are valid // (now need to do this here because of 'stop on error': MDL-10689) $gradeerrors = 0; $goodquestions = array(); foreach ($questions as $question) { if (!empty($question->fraction) and (is_array($question->fraction))) { $fractions = $question->fraction; $invalidfractions = array(); foreach ($fractions as $key => $fraction) { $newfraction = match_grade_options($gradeoptionsfull, $fraction, $this->matchgrades); if ($newfraction === false) { $invalidfractions[] = $fraction; } else { $fractions[$key] = $newfraction; } } if ($invalidfractions) { echo $OUTPUT->notification(get_string('invalidgrade', 'question', implode(', ', $invalidfractions))); ++$gradeerrors; continue; } else { $question->fraction = $fractions; } } $goodquestions[] = $question; } $questions = $goodquestions; // check for errors before we continue if ($this->stoponerror && $gradeerrors > 0) { return false; } // count number of questions processed $count = 0; foreach ($questions as $question) { // Process and store each question // reset the php timeout set_time_limit(0); // check for category modifiers if ($question->qtype == 'category') { if ($this->catfromfile) { // find/create category object $catpath = $question->category; $newcategory = $this->create_category_path($catpath); if (!empty($newcategory)) { $this->category = $newcategory; } } continue; } $question->context = $this->importcontext; $count++; echo "<hr /><p><b>$count</b>. ".$this->format_question_text($question)."</p>"; $question->category = $this->category->id; $question->stamp = make_unique_id_code(); // Set the unique code (not to be changed) $question->createdby = $USER->id; $question->timecreated = time(); $question->modifiedby = $USER->id; $question->timemodified = time(); $fileoptions = array( 'subdirs' => true, 'maxfiles' => -1, 'maxbytes' => 0, ); $question->id = $DB->insert_record('question', $question); if (isset($question->questiontextitemid)) { $question->questiontext = file_save_draft_area_files($question->questiontextitemid, $this->importcontext->id, 'question', 'questiontext', $question->id, $fileoptions, $question->questiontext); } else if (isset($question->questiontextfiles)) { foreach ($question->questiontextfiles as $file) { question_bank::get_qtype($question->qtype)->import_file( $this->importcontext, 'question', 'questiontext', $question->id, $file); } } if (isset($question->generalfeedbackitemid)) { $question->generalfeedback = file_save_draft_area_files($question->generalfeedbackitemid, $this->importcontext->id, 'question', 'generalfeedback', $question->id, $fileoptions, $question->generalfeedback); } else if (isset($question->generalfeedbackfiles)) { foreach ($question->generalfeedbackfiles as $file) { question_bank::get_qtype($question->qtype)->import_file( $this->importcontext, 'question', 'generalfeedback', $question->id, $file); } } $DB->update_record('question', $question); $this->questionids[] = $question->id; // Now to save all the answers and type-specific options $result = question_bank::get_qtype($question->qtype)->save_question_options($question); if (!empty($CFG->usetags) && isset($question->tags)) { require_once($CFG->dirroot . '/tag/lib.php'); tag_set('question', $question->id, $question->tags); } if (!empty($result->error)) { echo $OUTPUT->notification($result->error); return false; } if (!empty($result->notice)) { echo $OUTPUT->notification($result->notice); return true; } // Give the question a unique version stamp determined by question_hash() $DB->set_field('question', 'version', question_hash($question), array('id' => $question->id)); } return true; } /** * Count all non-category questions in the questions array. * * @param array questions An array of question objects. * @return int The count. * */ protected function count_questions($questions) { $count = 0; if (!is_array($questions)) { return $count; } foreach ($questions as $question) { if (!is_object($question) || !isset($question->qtype) || ($question->qtype == 'category')) { continue; } $count++; } return $count; } /** * find and/or create the category described by a delimited list * e.g. $course$/tom/dick/harry or tom/dick/harry * * removes any context string no matter whether $getcontext is set * but if $getcontext is set then ignore the context and use selected category context. * * @param string catpath delimited category path * @param int courseid course to search for categories * @return mixed category object or null if fails */ protected function create_category_path($catpath) { global $DB; $catnames = $this->split_category_path($catpath); $parent = 0; $category = null; // check for context id in path, it might not be there in pre 1.9 exports $matchcount = preg_match('/^\$([a-z]+)\$$/', $catnames[0], $matches); if ($matchcount == 1) { $contextid = $this->translator->string_to_context($matches[1]); array_shift($catnames); } else { $contextid = false; } if ($this->contextfromfile && $contextid !== false) { $context = context::instance_by_id($contextid); require_capability('moodle/question:add', $context); } else { $context = context::instance_by_id($this->category->contextid); } $this->importcontext = $context; // Now create any categories that need to be created. foreach ($catnames as $catname) { if ($category = $DB->get_record('question_categories', array('name' => $catname, 'contextid' => $context->id, 'parent' => $parent))) { $parent = $category->id; } else { require_capability('moodle/question:managecategory', $context); // create the new category $category = new stdClass(); $category->contextid = $context->id; $category->name = $catname; $category->info = ''; $category->parent = $parent; $category->sortorder = 999; $category->stamp = make_unique_id_code(); $id = $DB->insert_record('question_categories', $category); $category->id = $id; $parent = $id; } } return $category; } /** * Return complete file within an array, one item per line * @param string filename name of file * @return mixed contents array or false on failure */ protected function readdata($filename) { if (is_readable($filename)) { $filearray = file($filename); // If the first line of the file starts with a UTF-8 BOM, remove it. $filearray[0] = core_text::trim_utf8_bom($filearray[0]); // Check for Macintosh OS line returns (ie file on one line), and fix. if (preg_match("~\r~", $filearray[0]) AND !preg_match("~\n~", $filearray[0])) { return explode("\r", $filearray[0]); } else { return $filearray; } } return false; } /** * Parses an array of lines into an array of questions, * where each item is a question object as defined by * readquestion(). Questions are defined as anything * between blank lines. * * NOTE this method used to take $context as a second argument. However, at * the point where this method was called, it was impossible to know what * context the quetsions were going to be saved into, so the value could be * wrong. Also, none of the standard question formats were using this argument, * so it was removed. See MDL-32220. * * If your format does not use blank lines as a delimiter * then you will need to override this method. Even then * try to use readquestion for each question * @param array lines array of lines from readdata * @return array array of question objects */ protected function readquestions($lines) { $questions = array(); $currentquestion = array(); foreach ($lines as $line) { $line = trim($line); if (empty($line)) { if (!empty($currentquestion)) { if ($question = $this->readquestion($currentquestion)) { $questions[] = $question; } $currentquestion = array(); } } else { $currentquestion[] = $line; } } if (!empty($currentquestion)) { // There may be a final question if ($question = $this->readquestion($currentquestion)) { $questions[] = $question; } } return $questions; } /** * return an "empty" question * Somewhere to specify question parameters that are not handled * by import but are required db fields. * This should not be overridden. * @return object default question */ protected function defaultquestion() { global $CFG; static $defaultshuffleanswers = null; if (is_null($defaultshuffleanswers)) { $defaultshuffleanswers = get_config('quiz', 'shuffleanswers'); } $question = new stdClass(); $question->shuffleanswers = $defaultshuffleanswers; $question->defaultmark = 1; $question->image = ""; $question->usecase = 0; $question->multiplier = array(); $question->questiontextformat = FORMAT_MOODLE; $question->generalfeedback = ''; $question->generalfeedbackformat = FORMAT_MOODLE; $question->correctfeedback = ''; $question->partiallycorrectfeedback = ''; $question->incorrectfeedback = ''; $question->answernumbering = 'abc'; $question->penalty = 0.3333333; $question->length = 1; // this option in case the questiontypes class wants // to know where the data came from $question->export_process = true; $question->import_process = true; return $question; } /** * Construct a reasonable default question name, based on the start of the question text. * @param string $questiontext the question text. * @param string $default default question name to use if the constructed one comes out blank. * @return string a reasonable question name. */ public function create_default_question_name($questiontext, $default) { $name = $this->clean_question_name(shorten_text($questiontext, 80)); if ($name) { return $name; } else { return $default; } } /** * Ensure that a question name does not contain anything nasty, and will fit in the DB field. * @param string $name the raw question name. * @return string a safe question name. */ public function clean_question_name($name) { $name = clean_param($name, PARAM_TEXT); // Matches what the question editing form does. $name = trim($name); $trimlength = 251; while (core_text::strlen($name) > 255 && $trimlength > 0) { $name = shorten_text($name, $trimlength); $trimlength -= 10; } return $name; } /** * Add a blank combined feedback to a question object. * @param object question * @return object question */ protected function add_blank_combined_feedback($question) { $question->correctfeedback['text'] = ''; $question->correctfeedback['format'] = $question->questiontextformat; $question->correctfeedback['files'] = array(); $question->partiallycorrectfeedback['text'] = ''; $question->partiallycorrectfeedback['format'] = $question->questiontextformat; $question->partiallycorrectfeedback['files'] = array(); $question->incorrectfeedback['text'] = ''; $question->incorrectfeedback['format'] = $question->questiontextformat; $question->incorrectfeedback['files'] = array(); return $question; } /** * Given the data known to define a question in * this format, this function converts it into a question * object suitable for processing and insertion into Moodle. * * If your format does not use blank lines to delimit questions * (e.g. an XML format) you must override 'readquestions' too * @param $lines mixed data that represents question * @return object question object */ protected function readquestion($lines) { $formatnotimplemented = get_string('formatnotimplemented', 'question'); echo "<p>$formatnotimplemented</p>"; return null; } /** * Override if any post-processing is required * @return bool success */ public function importpostprocess() { return true; } /******************* * EXPORT FUNCTIONS *******************/ /** * Provide export functionality for plugin questiontypes * Do not override * @param name questiontype name * @param question object data to export * @param extra mixed any addition format specific data needed * @return string the data to append to export or false if error (or unhandled) */ protected function try_exporting_using_qtypes($name, $question, $extra=null) { // work out the name of format in use $formatname = substr(get_class($this), strlen('qformat_')); $methodname = "export_to_$formatname"; $qtype = question_bank::get_qtype($name, false); if (method_exists($qtype, $methodname)) { return $qtype->$methodname($question, $this, $extra); } return false; } /** * Do any pre-processing that may be required * @param bool success */ public function exportpreprocess() { return true; } /** * Enable any processing to be done on the content * just prior to the file being saved * default is to do nothing * @param string output text * @param string processed output text */ protected function presave_process($content) { return $content; } /** * Do the export * For most types this should not need to be overrided * @return stored_file */ public function exportprocess() { global $CFG, $OUTPUT, $DB, $USER; // get the questions (from database) in this category // only get q's with no parents (no cloze subquestions specifically) if ($this->category) { $questions = get_questions_category($this->category, true); } else { $questions = $this->questions; } $count = 0; // results are first written into string (and then to a file) // so create/initialize the string here $expout = ""; // track which category questions are in // if it changes we will record the category change in the output // file if selected. 0 means that it will get printed before the 1st question $trackcategory = 0; // iterate through questions foreach ($questions as $question) { // used by file api $contextid = $DB->get_field('question_categories', 'contextid', array('id' => $question->category)); $question->contextid = $contextid; // do not export hidden questions if (!empty($question->hidden)) { continue; } // do not export random questions if ($question->qtype == 'random') { continue; } // check if we need to record category change if ($this->cattofile) { if ($question->category != $trackcategory) { $trackcategory = $question->category; $categoryname = $this->get_category_path($trackcategory, $this->contexttofile); // create 'dummy' question for category export $dummyquestion = new stdClass(); $dummyquestion->qtype = 'category'; $dummyquestion->category = $categoryname; $dummyquestion->name = 'Switch category to ' . $categoryname; $dummyquestion->id = 0; $dummyquestion->questiontextformat = ''; $dummyquestion->contextid = 0; $expout .= $this->writequestion($dummyquestion) . "\n"; } } // export the question displaying message $count++; if (question_has_capability_on($question, 'view', $question->category)) { $expout .= $this->writequestion($question, $contextid) . "\n"; } } // continue path for following error checks $course = $this->course; $continuepath = "$CFG->wwwroot/question/export.php?courseid=$course->id"; // did we actually process anything if ($count==0) { print_error('noquestions', 'question', $continuepath); } // final pre-process on exported data $expout = $this->presave_process($expout); return $expout; } /** * get the category as a path (e.g., tom/dick/harry) * @param int id the id of the most nested catgory * @return string the path */ protected function get_category_path($id, $includecontext = true) { global $DB; if (!$category = $DB->get_record('question_categories', array('id' => $id))) { print_error('cannotfindcategory', 'error', '', $id); } $contextstring = $this->translator->context_to_string($category->contextid); $pathsections = array(); do { $pathsections[] = $category->name; $id = $category->parent; } while ($category = $DB->get_record('question_categories', array('id' => $id))); if ($includecontext) { $pathsections[] = '$' . $contextstring . '$'; } $path = $this->assemble_category_path(array_reverse($pathsections)); return $path; } /** * Convert a list of category names, possibly preceeded by one of the * context tokens like $course$, into a string representation of the * category path. * * Names are separated by / delimiters. And /s in the name are replaced by //. * * To reverse the process and split the paths into names, use * {@link split_category_path()}. * * @param array $names * @return string */ protected function assemble_category_path($names) { $escapednames = array(); foreach ($names as $name) { $escapedname = str_replace('/', '//', $name); if (substr($escapedname, 0, 1) == '/') { $escapedname = ' ' . $escapedname; } if (substr($escapedname, -1) == '/') { $escapedname = $escapedname . ' '; } $escapednames[] = $escapedname; } return implode('/', $escapednames); } /** * Convert a string, as returned by {@link assemble_category_path()}, * back into an array of category names. * * Each category name is cleaned by a call to clean_param(, PARAM_TEXT), * which matches the cleaning in question/category_form.php. * * @param string $path * @return array of category names. */ protected function split_category_path($path) { $rawnames = preg_split('~(?<!/)/(?!/)~', $path); $names = array(); foreach ($rawnames as $rawname) { $names[] = clean_param(trim(str_replace('//', '/', $rawname)), PARAM_TEXT); } return $names; } /** * Do an post-processing that may be required * @return bool success */ protected function exportpostprocess() { return true; } /** * convert a single question object into text output in the given * format. * This must be overriden * @param object question question object * @return mixed question export text or null if not implemented */ protected function writequestion($question) { // if not overidden, then this is an error. $formatnotimplemented = get_string('formatnotimplemented', 'question'); echo "<p>$formatnotimplemented</p>"; return null; } /** * Convert the question text to plain text, so it can safely be displayed * during import to let the user see roughly what is going on. */ protected function format_question_text($question) { return question_utils::to_plain_text($question->questiontext, $question->questiontextformat); } } class qformat_based_on_xml extends qformat_default { /** * A lot of imported files contain unwanted entities. * This method tries to clean up all known problems. * @param string str string to correct * @return string the corrected string */ public function cleaninput($str) { $html_code_list = array( "&#039;" => "'", "&#8217;" => "'", "&#8220;" => "\"", "&#8221;" => "\"", "&#8211;" => "-", "&#8212;" => "-", ); $str = strtr($str, $html_code_list); // Use core_text entities_to_utf8 function to convert only numerical entities. $str = core_text::entities_to_utf8($str, false); return $str; } /** * Return the array moodle is expecting * for an HTML text. No processing is done on $text. * qformat classes that want to process $text * for instance to import external images files * and recode urls in $text must overwrite this method. * @param array $text some HTML text string * @return array with keys text, format and files. */ public function text_field($text) { return array( 'text' => trim($text), 'format' => FORMAT_HTML, 'files' => array(), ); } /** * Return the value of a node, given a path to the node * if it doesn't exist return the default value. * @param array xml data to read * @param array path path to node expressed as array * @param mixed default * @param bool istext process as text * @param string error if set value must exist, return false and issue message if not * @return mixed value */ public function getpath($xml, $path, $default, $istext=false, $error='') { foreach ($path as $index) { if (!isset($xml[$index])) { if (!empty($error)) { $this->error($error); return false; } else { return $default; } } $xml = $xml[$index]; } if ($istext) { if (!is_string($xml)) { $this->error(get_string('invalidxml', 'qformat_xml')); } $xml = trim($xml); } return $xml; } }
dslab-epfl/accessibility-checker
question/format.php
PHP
gpl-3.0
35,327
<?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/>. /** * Classes representing HTML elements, used by $OUTPUT methods * * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML * for an overview. * * @package core * @category output * @copyright 2009 Tim Hunt * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); /** * Interface marking other classes as suitable for renderer_base::render() * * @copyright 2010 Petr Skoda (skodak) info@skodak.org * @package core * @category output */ interface renderable { // intentionally empty } /** * Data structure representing a file picker. * * @copyright 2010 Dongsheng Cai * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class file_picker implements renderable { /** * @var stdClass An object containing options for the file picker */ public $options; /** * Constructs a file picker object. * * The following are possible options for the filepicker: * - accepted_types (*) * - return_types (FILE_INTERNAL) * - env (filepicker) * - client_id (uniqid) * - itemid (0) * - maxbytes (-1) * - maxfiles (1) * - buttonname (false) * * @param stdClass $options An object containing options for the file picker. */ public function __construct(stdClass $options) { global $CFG, $USER, $PAGE; require_once($CFG->dirroot. '/repository/lib.php'); $defaults = array( 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL, 'env' => 'filepicker', 'client_id' => uniqid(), 'itemid' => 0, 'maxbytes'=>-1, 'maxfiles'=>1, 'buttonname'=>false ); foreach ($defaults as $key=>$value) { if (empty($options->$key)) { $options->$key = $value; } } $options->currentfile = ''; if (!empty($options->itemid)) { $fs = get_file_storage(); $usercontext = context_user::instance($USER->id); if (empty($options->filename)) { if ($files = $fs->get_area_files($usercontext->id, 'user', 'draft', $options->itemid, 'id DESC', false)) { $file = reset($files); } } else { $file = $fs->get_file($usercontext->id, 'user', 'draft', $options->itemid, $options->filepath, $options->filename); } if (!empty($file)) { $options->currentfile = html_writer::link(moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename()), $file->get_filename()); } } // initilise options, getting files in root path $this->options = initialise_filepicker($options); // copying other options foreach ($options as $name=>$value) { if (!isset($this->options->$name)) { $this->options->$name = $value; } } } } /** * Data structure representing a user picture. * * @copyright 2009 Nicolas Connault, 2010 Petr Skoda * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Modle 2.0 * @package core * @category output */ class user_picture implements renderable { /** * @var array List of mandatory fields in user record here. (do not include * TEXT columns because it would break SELECT DISTINCT in MSSQL and ORACLE) */ protected static $fields = array('id', 'picture', 'firstname', 'lastname', 'firstnamephonetic', 'lastnamephonetic', 'middlename', 'alternatename', 'imagealt', 'email'); /** * @var stdClass A user object with at least fields all columns specified * in $fields array constant set. */ public $user; /** * @var int The course id. Used when constructing the link to the user's * profile, page course id used if not specified. */ public $courseid; /** * @var bool Add course profile link to image */ public $link = true; /** * @var int Size in pixels. Special values are (true/1 = 100px) and * (false/0 = 35px) * for backward compatibility. */ public $size = 35; /** * @var bool Add non-blank alt-text to the image. * Default true, set to false when image alt just duplicates text in screenreaders. */ public $alttext = true; /** * @var bool Whether or not to open the link in a popup window. */ public $popup = false; /** * @var string Image class attribute */ public $class = 'userpicture'; /** * @var bool Whether to be visible to screen readers. */ public $visibletoscreenreaders = true; /** * User picture constructor. * * @param stdClass $user user record with at least id, picture, imagealt, firstname and lastname set. * It is recommended to add also contextid of the user for performance reasons. */ public function __construct(stdClass $user) { global $DB; if (empty($user->id)) { throw new coding_exception('User id is required when printing user avatar image.'); } // only touch the DB if we are missing data and complain loudly... $needrec = false; foreach (self::$fields as $field) { if (!array_key_exists($field, $user)) { $needrec = true; debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. ' .'Please use user_picture::fields() to get the full list of required fields.', DEBUG_DEVELOPER); break; } } if ($needrec) { $this->user = $DB->get_record('user', array('id'=>$user->id), self::fields(), MUST_EXIST); } else { $this->user = clone($user); } } /** * Returns a list of required user fields, useful when fetching required user info from db. * * In some cases we have to fetch the user data together with some other information, * the idalias is useful there because the id would otherwise override the main * id of the result record. Please note it has to be converted back to id before rendering. * * @param string $tableprefix name of database table prefix in query * @param array $extrafields extra fields to be included in result (do not include TEXT columns because it would break SELECT DISTINCT in MSSQL and ORACLE) * @param string $idalias alias of id field * @param string $fieldprefix prefix to add to all columns in their aliases, does not apply to 'id' * @return string */ public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id', $fieldprefix = '') { if (!$tableprefix and !$extrafields and !$idalias) { return implode(',', self::$fields); } if ($tableprefix) { $tableprefix .= '.'; } foreach (self::$fields as $field) { if ($field === 'id' and $idalias and $idalias !== 'id') { $fields[$field] = "$tableprefix$field AS $idalias"; } else { if ($fieldprefix and $field !== 'id') { $fields[$field] = "$tableprefix$field AS $fieldprefix$field"; } else { $fields[$field] = "$tableprefix$field"; } } } // add extra fields if not already there if ($extrafields) { foreach ($extrafields as $e) { if ($e === 'id' or isset($fields[$e])) { continue; } if ($fieldprefix) { $fields[$e] = "$tableprefix$e AS $fieldprefix$e"; } else { $fields[$e] = "$tableprefix$e"; } } } return implode(',', $fields); } /** * Extract the aliased user fields from a given record * * Given a record that was previously obtained using {@link self::fields()} with aliases, * this method extracts user related unaliased fields. * * @param stdClass $record containing user picture fields * @param array $extrafields extra fields included in the $record * @param string $idalias alias of the id field * @param string $fieldprefix prefix added to all columns in their aliases, does not apply to 'id' * @return stdClass object with unaliased user fields */ public static function unalias(stdClass $record, array $extrafields = null, $idalias = 'id', $fieldprefix = '') { if (empty($idalias)) { $idalias = 'id'; } $return = new stdClass(); foreach (self::$fields as $field) { if ($field === 'id') { if (property_exists($record, $idalias)) { $return->id = $record->{$idalias}; } } else { if (property_exists($record, $fieldprefix.$field)) { $return->{$field} = $record->{$fieldprefix.$field}; } } } // add extra fields if not already there if ($extrafields) { foreach ($extrafields as $e) { if ($e === 'id' or property_exists($return, $e)) { continue; } $return->{$e} = $record->{$fieldprefix.$e}; } } return $return; } /** * Works out the URL for the users picture. * * This method is recommended as it avoids costly redirects of user pictures * if requests are made for non-existent files etc. * * @param moodle_page $page * @param renderer_base $renderer * @return moodle_url */ public function get_url(moodle_page $page, renderer_base $renderer = null) { global $CFG; if (is_null($renderer)) { $renderer = $page->get_renderer('core'); } // Sort out the filename and size. Size is only required for the gravatar // implementation presently. if (empty($this->size)) { $filename = 'f2'; $size = 35; } else if ($this->size === true or $this->size == 1) { $filename = 'f1'; $size = 100; } else if ($this->size > 100) { $filename = 'f3'; $size = (int)$this->size; } else if ($this->size >= 50) { $filename = 'f1'; $size = (int)$this->size; } else { $filename = 'f2'; $size = (int)$this->size; } $defaulturl = $renderer->pix_url('u/'.$filename); // default image if ((!empty($CFG->forcelogin) and !isloggedin()) || (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) { // Protect images if login required and not logged in; // also if login is required for profile images and is not logged in or guest // do not use require_login() because it is expensive and not suitable here anyway. return $defaulturl; } // First try to detect deleted users - but do not read from database for performance reasons! if (!empty($this->user->deleted) or strpos($this->user->email, '@') === false) { // All deleted users should have email replaced by md5 hash, // all active users are expected to have valid email. return $defaulturl; } // Did the user upload a picture? if ($this->user->picture > 0) { if (!empty($this->user->contextid)) { $contextid = $this->user->contextid; } else { $context = context_user::instance($this->user->id, IGNORE_MISSING); if (!$context) { // This must be an incorrectly deleted user, all other users have context. return $defaulturl; } $contextid = $context->id; } $path = '/'; if (clean_param($page->theme->name, PARAM_THEME) == $page->theme->name) { // We append the theme name to the file path if we have it so that // in the circumstance that the profile picture is not available // when the user actually requests it they still get the profile // picture for the correct theme. $path .= $page->theme->name.'/'; } // Set the image URL to the URL for the uploaded file and return. $url = moodle_url::make_pluginfile_url($contextid, 'user', 'icon', NULL, $path, $filename); $url->param('rev', $this->user->picture); return $url; } if ($this->user->picture == 0 and !empty($CFG->enablegravatar)) { // Normalise the size variable to acceptable bounds if ($size < 1 || $size > 512) { $size = 35; } // Hash the users email address $md5 = md5(strtolower(trim($this->user->email))); // Build a gravatar URL with what we know. // Find the best default image URL we can (MDL-35669) if (empty($CFG->gravatardefaulturl)) { $absoluteimagepath = $page->theme->resolve_image_location('u/'.$filename, 'core'); if (strpos($absoluteimagepath, $CFG->dirroot) === 0) { $gravatardefault = $CFG->wwwroot . substr($absoluteimagepath, strlen($CFG->dirroot)); } else { $gravatardefault = $CFG->wwwroot . '/pix/u/' . $filename . '.png'; } } else { $gravatardefault = $CFG->gravatardefaulturl; } // If the currently requested page is https then we'll return an // https gravatar page. if (is_https()) { $gravatardefault = str_replace($CFG->wwwroot, $CFG->httpswwwroot, $gravatardefault); // Replace by secure url. return new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault)); } else { return new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault)); } } return $defaulturl; } } /** * Data structure representing a help icon. * * @copyright 2010 Petr Skoda (info@skodak.org) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class help_icon implements renderable { /** * @var string lang pack identifier (without the "_help" suffix), * both get_string($identifier, $component) and get_string($identifier.'_help', $component) * must exist. */ public $identifier; /** * @var string Component name, the same as in get_string() */ public $component; /** * @var string Extra descriptive text next to the icon */ public $linktext = null; /** * Constructor * * @param string $identifier string for help page title, * string with _help suffix is used for the actual help text. * string with _link suffix is used to create a link to further info (if it exists) * @param string $component */ public function __construct($identifier, $component) { $this->identifier = $identifier; $this->component = $component; } /** * Verifies that both help strings exists, shows debug warnings if not */ public function diag_strings() { $sm = get_string_manager(); if (!$sm->string_exists($this->identifier, $this->component)) { debugging("Help title string does not exist: [$this->identifier, $this->component]"); } if (!$sm->string_exists($this->identifier.'_help', $this->component)) { debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]"); } } } /** * Data structure representing an icon. * * @copyright 2010 Petr Skoda * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class pix_icon implements renderable { /** * @var string The icon name */ var $pix; /** * @var string The component the icon belongs to. */ var $component; /** * @var array An array of attributes to use on the icon */ var $attributes = array(); /** * Constructor * * @param string $pix short icon name * @param string $alt The alt text to use for the icon * @param string $component component name * @param array $attributes html attributes */ public function __construct($pix, $alt, $component='moodle', array $attributes = null) { $this->pix = $pix; $this->component = $component; $this->attributes = (array)$attributes; $this->attributes['alt'] = $alt; if (empty($this->attributes['class'])) { $this->attributes['class'] = 'smallicon'; } if (!isset($this->attributes['title'])) { $this->attributes['title'] = $this->attributes['alt']; } else if (empty($this->attributes['title'])) { // Remove the title attribute if empty, we probably want to use the parent node's title // and some browsers might overwrite it with an empty title. unset($this->attributes['title']); } } } /** * Data structure representing an emoticon image * * @copyright 2010 David Mudrak * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class pix_emoticon extends pix_icon implements renderable { /** * Constructor * @param string $pix short icon name * @param string $alt alternative text * @param string $component emoticon image provider * @param array $attributes explicit HTML attributes */ public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) { if (empty($attributes['class'])) { $attributes['class'] = 'emoticon'; } parent::__construct($pix, $alt, $component, $attributes); } } /** * Data structure representing a simple form with only one button. * * @copyright 2009 Petr Skoda * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class single_button implements renderable { /** * @var moodle_url Target url */ var $url; /** * @var string Button label */ var $label; /** * @var string Form submit method post or get */ var $method = 'post'; /** * @var string Wrapping div class */ var $class = 'singlebutton'; /** * @var bool True if button disabled, false if normal */ var $disabled = false; /** * @var string Button tooltip */ var $tooltip = null; /** * @var string Form id */ var $formid; /** * @var array List of attached actions */ var $actions = array(); /** * Constructor * @param moodle_url $url * @param string $label button text * @param string $method get or post submit method */ public function __construct(moodle_url $url, $label, $method='post') { $this->url = clone($url); $this->label = $label; $this->method = $method; } /** * Shortcut for adding a JS confirm dialog when the button is clicked. * The message must be a yes/no question. * * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur. */ public function add_confirm_action($confirmmessage) { $this->add_action(new confirm_action($confirmmessage)); } /** * Add action to the button. * @param component_action $action */ public function add_action(component_action $action) { $this->actions[] = $action; } } /** * Simple form with just one select field that gets submitted automatically. * * If JS not enabled small go button is printed too. * * @copyright 2009 Petr Skoda * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class single_select implements renderable { /** * @var moodle_url Target url - includes hidden fields */ var $url; /** * @var string Name of the select element. */ var $name; /** * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two) * it is also possible to specify optgroup as complex label array ex.: * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two'))) * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three'))) */ var $options; /** * @var string Selected option */ var $selected; /** * @var array Nothing selected */ var $nothing; /** * @var array Extra select field attributes */ var $attributes = array(); /** * @var string Button label */ var $label = ''; /** * @var array Button label's attributes */ var $labelattributes = array(); /** * @var string Form submit method post or get */ var $method = 'get'; /** * @var string Wrapping div class */ var $class = 'singleselect'; /** * @var bool True if button disabled, false if normal */ var $disabled = false; /** * @var string Button tooltip */ var $tooltip = null; /** * @var string Form id */ var $formid = null; /** * @var array List of attached actions */ var $helpicon = null; /** * Constructor * @param moodle_url $url form action target, includes hidden fields * @param string $name name of selection field - the changing parameter in url * @param array $options list of options * @param string $selected selected element * @param array $nothing * @param string $formid */ public function __construct(moodle_url $url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) { $this->url = $url; $this->name = $name; $this->options = $options; $this->selected = $selected; $this->nothing = $nothing; $this->formid = $formid; } /** * Shortcut for adding a JS confirm dialog when the button is clicked. * The message must be a yes/no question. * * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur. */ public function add_confirm_action($confirmmessage) { $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage))); } /** * Add action to the button. * * @param component_action $action */ public function add_action(component_action $action) { $this->actions[] = $action; } /** * Adds help icon. * * @deprecated since Moodle 2.0 */ public function set_old_help_icon($helppage, $title, $component = 'moodle') { throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().'); } /** * Adds help icon. * * @param string $identifier The keyword that defines a help page * @param string $component */ public function set_help_icon($identifier, $component = 'moodle') { $this->helpicon = new help_icon($identifier, $component); } /** * Sets select's label * * @param string $label * @param array $attributes (optional) */ public function set_label($label, $attributes = array()) { $this->label = $label; $this->labelattributes = $attributes; } } /** * Simple URL selection widget description. * * @copyright 2009 Petr Skoda * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class url_select implements renderable { /** * @var array $urls associative array value=>label ex.: array(1=>'One, 2=>Two) * it is also possible to specify optgroup as complex label array ex.: * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two'))) * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three'))) */ var $urls; /** * @var string Selected option */ var $selected; /** * @var array Nothing selected */ var $nothing; /** * @var array Extra select field attributes */ var $attributes = array(); /** * @var string Button label */ var $label = ''; /** * @var array Button label's attributes */ var $labelattributes = array(); /** * @var string Wrapping div class */ var $class = 'urlselect'; /** * @var bool True if button disabled, false if normal */ var $disabled = false; /** * @var string Button tooltip */ var $tooltip = null; /** * @var string Form id */ var $formid = null; /** * @var array List of attached actions */ var $helpicon = null; /** * @var string If set, makes button visible with given name for button */ var $showbutton = null; /** * Constructor * @param array $urls list of options * @param string $selected selected element * @param array $nothing * @param string $formid * @param string $showbutton Set to text of button if it should be visible * or null if it should be hidden (hidden version always has text 'go') */ public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) { $this->urls = $urls; $this->selected = $selected; $this->nothing = $nothing; $this->formid = $formid; $this->showbutton = $showbutton; } /** * Adds help icon. * * @deprecated since Moodle 2.0 */ public function set_old_help_icon($helppage, $title, $component = 'moodle') { throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().'); } /** * Adds help icon. * * @param string $identifier The keyword that defines a help page * @param string $component */ public function set_help_icon($identifier, $component = 'moodle') { $this->helpicon = new help_icon($identifier, $component); } /** * Sets select's label * * @param string $label * @param array $attributes (optional) */ public function set_label($label, $attributes = array()) { $this->label = $label; $this->labelattributes = $attributes; } } /** * Data structure describing html link with special action attached. * * @copyright 2010 Petr Skoda * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class action_link implements renderable { /** * @var moodle_url Href url */ public $url; /** * @var string Link text HTML fragment */ public $text; /** * @var array HTML attributes */ public $attributes; /** * @var array List of actions attached to link */ public $actions; /** * @var pix_icon Optional pix icon to render with the link */ public $icon; /** * Constructor * @param moodle_url $url * @param string $text HTML fragment * @param component_action $action * @param array $attributes associative array of html link attributes + disabled * @param pix_icon $icon optional pix_icon to render with the link text */ public function __construct(moodle_url $url, $text, component_action $action=null, array $attributes=null, pix_icon $icon=null) { $this->url = clone($url); $this->text = $text; $this->attributes = (array)$attributes; if ($action) { $this->add_action($action); } $this->icon = $icon; } /** * Add action to the link. * * @param component_action $action */ public function add_action(component_action $action) { $this->actions[] = $action; } /** * Adds a CSS class to this action link object * @param string $class */ public function add_class($class) { if (empty($this->attributes['class'])) { $this->attributes['class'] = $class; } else { $this->attributes['class'] .= ' ' . $class; } } /** * Returns true if the specified class has been added to this link. * @param string $class * @return bool */ public function has_class($class) { return strpos(' ' . $this->attributes['class'] . ' ', ' ' . $class . ' ') !== false; } } /** * Simple html output class * * @copyright 2009 Tim Hunt, 2010 Petr Skoda * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class html_writer { /** * Outputs a tag with attributes and contents * * @param string $tagname The name of tag ('a', 'img', 'span' etc.) * @param string $contents What goes between the opening and closing tags * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.) * @return string HTML fragment */ public static function tag($tagname, $contents, array $attributes = null) { return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname); } /** * Outputs an opening tag with attributes * * @param string $tagname The name of tag ('a', 'img', 'span' etc.) * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.) * @return string HTML fragment */ public static function start_tag($tagname, array $attributes = null) { return '<' . $tagname . self::attributes($attributes) . '>'; } /** * Outputs a closing tag * * @param string $tagname The name of tag ('a', 'img', 'span' etc.) * @return string HTML fragment */ public static function end_tag($tagname) { return '</' . $tagname . '>'; } /** * Outputs an empty tag with attributes * * @param string $tagname The name of tag ('input', 'img', 'br' etc.) * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.) * @return string HTML fragment */ public static function empty_tag($tagname, array $attributes = null) { return '<' . $tagname . self::attributes($attributes) . ' />'; } /** * Outputs a tag, but only if the contents are not empty * * @param string $tagname The name of tag ('a', 'img', 'span' etc.) * @param string $contents What goes between the opening and closing tags * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.) * @return string HTML fragment */ public static function nonempty_tag($tagname, $contents, array $attributes = null) { if ($contents === '' || is_null($contents)) { return ''; } return self::tag($tagname, $contents, $attributes); } /** * Outputs a HTML attribute and value * * @param string $name The name of the attribute ('src', 'href', 'class' etc.) * @param string $value The value of the attribute. The value will be escaped with {@link s()} * @return string HTML fragment */ public static function attribute($name, $value) { if ($value instanceof moodle_url) { return ' ' . $name . '="' . $value->out() . '"'; } // special case, we do not want these in output if ($value === null) { return ''; } // no sloppy trimming here! return ' ' . $name . '="' . s($value) . '"'; } /** * Outputs a list of HTML attributes and values * * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.) * The values will be escaped with {@link s()} * @return string HTML fragment */ public static function attributes(array $attributes = null) { $attributes = (array)$attributes; $output = ''; foreach ($attributes as $name => $value) { $output .= self::attribute($name, $value); } return $output; } /** * Generates a simple image tag with attributes. * * @param string $src The source of image * @param string $alt The alternate text for image * @param array $attributes The tag attributes (array('height' => $max_height, 'class' => 'class1') etc.) * @return string HTML fragment */ public static function img($src, $alt, array $attributes = null) { $attributes = (array)$attributes; $attributes['src'] = $src; $attributes['alt'] = $alt; return self::empty_tag('img', $attributes); } /** * Generates random html element id. * * @staticvar int $counter * @staticvar type $uniq * @param string $base A string fragment that will be included in the random ID. * @return string A unique ID */ public static function random_id($base='random') { static $counter = 0; static $uniq; if (!isset($uniq)) { $uniq = uniqid(); } $counter++; return $base.$uniq.$counter; } /** * Generates a simple html link * * @param string|moodle_url $url The URL * @param string $text The text * @param array $attributes HTML attributes * @return string HTML fragment */ public static function link($url, $text, array $attributes = null) { $attributes = (array)$attributes; $attributes['href'] = $url; return self::tag('a', $text, $attributes); } /** * Generates a simple checkbox with optional label * * @param string $name The name of the checkbox * @param string $value The value of the checkbox * @param bool $checked Whether the checkbox is checked * @param string $label The label for the checkbox * @param array $attributes Any attributes to apply to the checkbox * @return string html fragment */ public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) { $attributes = (array)$attributes; $output = ''; if ($label !== '' and !is_null($label)) { if (empty($attributes['id'])) { $attributes['id'] = self::random_id('checkbox_'); } } $attributes['type'] = 'checkbox'; $attributes['value'] = $value; $attributes['name'] = $name; $attributes['checked'] = $checked ? 'checked' : null; $output .= self::empty_tag('input', $attributes); if ($label !== '' and !is_null($label)) { $output .= self::tag('label', $label, array('for'=>$attributes['id'])); } return $output; } /** * Generates a simple select yes/no form field * * @param string $name name of select element * @param bool $selected * @param array $attributes - html select element attributes * @return string HTML fragment */ public static function select_yes_no($name, $selected=true, array $attributes = null) { $options = array('1'=>get_string('yes'), '0'=>get_string('no')); return self::select($options, $name, $selected, null, $attributes); } /** * Generates a simple select form field * * @param array $options associative array value=>label ex.: * array(1=>'One, 2=>Two) * it is also possible to specify optgroup as complex label array ex.: * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two'))) * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three'))) * @param string $name name of select element * @param string|array $selected value or array of values depending on multiple attribute * @param array|bool $nothing add nothing selected option, or false of not added * @param array $attributes html select element attributes * @return string HTML fragment */ public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) { $attributes = (array)$attributes; if (is_array($nothing)) { foreach ($nothing as $k=>$v) { if ($v === 'choose' or $v === 'choosedots') { $nothing[$k] = get_string('choosedots'); } } $options = $nothing + $options; // keep keys, do not override } else if (is_string($nothing) and $nothing !== '') { // BC $options = array(''=>$nothing) + $options; } // we may accept more values if multiple attribute specified $selected = (array)$selected; foreach ($selected as $k=>$v) { $selected[$k] = (string)$v; } if (!isset($attributes['id'])) { $id = 'menu'.$name; // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading $id = str_replace('[', '', $id); $id = str_replace(']', '', $id); $attributes['id'] = $id; } if (!isset($attributes['class'])) { $class = 'menu'.$name; // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading $class = str_replace('[', '', $class); $class = str_replace(']', '', $class); $attributes['class'] = $class; } $attributes['class'] = 'select ' . $attributes['class']; // Add 'select' selector always $attributes['name'] = $name; if (!empty($attributes['disabled'])) { $attributes['disabled'] = 'disabled'; } else { unset($attributes['disabled']); } $output = ''; foreach ($options as $value=>$label) { if (is_array($label)) { // ignore key, it just has to be unique $output .= self::select_optgroup(key($label), current($label), $selected); } else { $output .= self::select_option($label, $value, $selected); } } return self::tag('select', $output, $attributes); } /** * Returns HTML to display a select box option. * * @param string $label The label to display as the option. * @param string|int $value The value the option represents * @param array $selected An array of selected options * @return string HTML fragment */ private static function select_option($label, $value, array $selected) { $attributes = array(); $value = (string)$value; if (in_array($value, $selected, true)) { $attributes['selected'] = 'selected'; } $attributes['value'] = $value; return self::tag('option', $label, $attributes); } /** * Returns HTML to display a select box option group. * * @param string $groupname The label to use for the group * @param array $options The options in the group * @param array $selected An array of selected values. * @return string HTML fragment. */ private static function select_optgroup($groupname, $options, array $selected) { if (empty($options)) { return ''; } $attributes = array('label'=>$groupname); $output = ''; foreach ($options as $value=>$label) { $output .= self::select_option($label, $value, $selected); } return self::tag('optgroup', $output, $attributes); } /** * This is a shortcut for making an hour selector menu. * * @param string $type The type of selector (years, months, days, hours, minutes) * @param string $name fieldname * @param int $currenttime A default timestamp in GMT * @param int $step minute spacing * @param array $attributes - html select element attributes * @return HTML fragment */ public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) { if (!$currenttime) { $currenttime = time(); } $currentdate = usergetdate($currenttime); $userdatetype = $type; $timeunits = array(); switch ($type) { case 'years': for ($i=1970; $i<=2020; $i++) { $timeunits[$i] = $i; } $userdatetype = 'year'; break; case 'months': for ($i=1; $i<=12; $i++) { $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B"); } $userdatetype = 'month'; $currentdate['month'] = (int)$currentdate['mon']; break; case 'days': for ($i=1; $i<=31; $i++) { $timeunits[$i] = $i; } $userdatetype = 'mday'; break; case 'hours': for ($i=0; $i<=23; $i++) { $timeunits[$i] = sprintf("%02d",$i); } break; case 'minutes': if ($step != 1) { $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step; } for ($i=0; $i<=59; $i+=$step) { $timeunits[$i] = sprintf("%02d",$i); } break; default: throw new coding_exception("Time type $type is not supported by html_writer::select_time()."); } if (empty($attributes['id'])) { $attributes['id'] = self::random_id('ts_'); } $timerselector = self::select($timeunits, $name, $currentdate[$userdatetype], null, $attributes); $label = self::tag('label', get_string(substr($type, 0, -1), 'form'), array('for'=>$attributes['id'], 'class'=>'accesshide')); return $label.$timerselector; } /** * Shortcut for quick making of lists * * Note: 'list' is a reserved keyword ;-) * * @param array $items * @param array $attributes * @param string $tag ul or ol * @return string */ public static function alist(array $items, array $attributes = null, $tag = 'ul') { $output = html_writer::start_tag($tag, $attributes)."\n"; foreach ($items as $item) { $output .= html_writer::tag('li', $item)."\n"; } $output .= html_writer::end_tag($tag); return $output; } /** * Returns hidden input fields created from url parameters. * * @param moodle_url $url * @param array $exclude list of excluded parameters * @return string HTML fragment */ public static function input_hidden_params(moodle_url $url, array $exclude = null) { $exclude = (array)$exclude; $params = $url->params(); foreach ($exclude as $key) { unset($params[$key]); } $output = ''; foreach ($params as $key => $value) { $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value); $output .= self::empty_tag('input', $attributes)."\n"; } return $output; } /** * Generate a script tag containing the the specified code. * * @param string $jscode the JavaScript code * @param moodle_url|string $url optional url of the external script, $code ignored if specified * @return string HTML, the code wrapped in <script> tags. */ public static function script($jscode, $url=null) { if ($jscode) { $attributes = array('type'=>'text/javascript'); return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n"; } else if ($url) { $attributes = array('type'=>'text/javascript', 'src'=>$url); return self::tag('script', '', $attributes) . "\n"; } else { return ''; } } /** * Renders HTML table * * This method may modify the passed instance by adding some default properties if they are not set yet. * If this is not what you want, you should make a full clone of your data before passing them to this * method. In most cases this is not an issue at all so we do not clone by default for performance * and memory consumption reasons. * * Please do not use .r0/.r1 for css, as they will be removed in Moodle 2.9. * @todo MDL-43902 , remove r0 and r1 from tr classes. * * @param html_table $table data to be rendered * @return string HTML code */ public static function table(html_table $table) { // prepare table data and populate missing properties with reasonable defaults if (!empty($table->align)) { foreach ($table->align as $key => $aa) { if ($aa) { $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages } else { $table->align[$key] = null; } } } if (!empty($table->size)) { foreach ($table->size as $key => $ss) { if ($ss) { $table->size[$key] = 'width:'. $ss .';'; } else { $table->size[$key] = null; } } } if (!empty($table->wrap)) { foreach ($table->wrap as $key => $ww) { if ($ww) { $table->wrap[$key] = 'white-space:nowrap;'; } else { $table->wrap[$key] = ''; } } } if (!empty($table->head)) { foreach ($table->head as $key => $val) { if (!isset($table->align[$key])) { $table->align[$key] = null; } if (!isset($table->size[$key])) { $table->size[$key] = null; } if (!isset($table->wrap[$key])) { $table->wrap[$key] = null; } } } if (empty($table->attributes['class'])) { $table->attributes['class'] = 'generaltable'; } if (!empty($table->tablealign)) { $table->attributes['class'] .= ' boxalign' . $table->tablealign; } // explicitly assigned properties override those defined via $table->attributes $table->attributes['class'] = trim($table->attributes['class']); $attributes = array_merge($table->attributes, array( 'id' => $table->id, 'width' => $table->width, 'summary' => $table->summary, 'cellpadding' => $table->cellpadding, 'cellspacing' => $table->cellspacing, )); $output = html_writer::start_tag('table', $attributes) . "\n"; $countcols = 0; if (!empty($table->head)) { $countcols = count($table->head); $output .= html_writer::start_tag('thead', array()) . "\n"; $output .= html_writer::start_tag('tr', array()) . "\n"; $keys = array_keys($table->head); $lastkey = end($keys); foreach ($table->head as $key => $heading) { // Convert plain string headings into html_table_cell objects if (!($heading instanceof html_table_cell)) { $headingtext = $heading; $heading = new html_table_cell(); $heading->text = $headingtext; $heading->header = true; } if ($heading->header !== false) { $heading->header = true; } if ($heading->header && empty($heading->scope)) { $heading->scope = 'col'; } $heading->attributes['class'] .= ' header c' . $key; if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) { $heading->colspan = $table->headspan[$key]; $countcols += $table->headspan[$key] - 1; } if ($key == $lastkey) { $heading->attributes['class'] .= ' lastcol'; } if (isset($table->colclasses[$key])) { $heading->attributes['class'] .= ' ' . $table->colclasses[$key]; } $heading->attributes['class'] = trim($heading->attributes['class']); $attributes = array_merge($heading->attributes, array( 'style' => $table->align[$key] . $table->size[$key] . $heading->style, 'scope' => $heading->scope, 'colspan' => $heading->colspan, )); $tagtype = 'td'; if ($heading->header === true) { $tagtype = 'th'; } $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n"; } $output .= html_writer::end_tag('tr') . "\n"; $output .= html_writer::end_tag('thead') . "\n"; if (empty($table->data)) { // For valid XHTML strict every table must contain either a valid tr // or a valid tbody... both of which must contain a valid td $output .= html_writer::start_tag('tbody', array('class' => 'empty')); $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head)))); $output .= html_writer::end_tag('tbody'); } } if (!empty($table->data)) { $oddeven = 1; $keys = array_keys($table->data); $lastrowkey = end($keys); $output .= html_writer::start_tag('tbody', array()); foreach ($table->data as $key => $row) { if (($row === 'hr') && ($countcols)) { $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols)); } else { // Convert array rows to html_table_rows and cell strings to html_table_cell objects if (!($row instanceof html_table_row)) { $newrow = new html_table_row(); foreach ($row as $cell) { if (!($cell instanceof html_table_cell)) { $cell = new html_table_cell($cell); } $newrow->cells[] = $cell; } $row = $newrow; } $oddeven = $oddeven ? 0 : 1; if (isset($table->rowclasses[$key])) { $row->attributes['class'] .= ' ' . $table->rowclasses[$key]; } $row->attributes['class'] .= ' r' . $oddeven; if ($key == $lastrowkey) { $row->attributes['class'] .= ' lastrow'; } // Explicitly assigned properties should override those defined in the attributes. $row->attributes['class'] = trim($row->attributes['class']); $trattributes = array_merge($row->attributes, array( 'id' => $row->id, 'style' => $row->style, )); $output .= html_writer::start_tag('tr', $trattributes) . "\n"; $keys2 = array_keys($row->cells); $lastkey = end($keys2); $gotlastkey = false; //flag for sanity checking foreach ($row->cells as $key => $cell) { if ($gotlastkey) { //This should never happen. Why do we have a cell after the last cell? mtrace("A cell with key ($key) was found after the last key ($lastkey)"); } if (!($cell instanceof html_table_cell)) { $mycell = new html_table_cell(); $mycell->text = $cell; $cell = $mycell; } if (($cell->header === true) && empty($cell->scope)) { $cell->scope = 'row'; } if (isset($table->colclasses[$key])) { $cell->attributes['class'] .= ' ' . $table->colclasses[$key]; } $cell->attributes['class'] .= ' cell c' . $key; if ($key == $lastkey) { $cell->attributes['class'] .= ' lastcol'; $gotlastkey = true; } $tdstyle = ''; $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : ''; $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : ''; $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : ''; $cell->attributes['class'] = trim($cell->attributes['class']); $tdattributes = array_merge($cell->attributes, array( 'style' => $tdstyle . $cell->style, 'colspan' => $cell->colspan, 'rowspan' => $cell->rowspan, 'id' => $cell->id, 'abbr' => $cell->abbr, 'scope' => $cell->scope, )); $tagtype = 'td'; if ($cell->header === true) { $tagtype = 'th'; } $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n"; } } $output .= html_writer::end_tag('tr') . "\n"; } $output .= html_writer::end_tag('tbody') . "\n"; } $output .= html_writer::end_tag('table') . "\n"; return $output; } /** * Renders form element label * * By default, the label is suffixed with a label separator defined in the * current language pack (colon by default in the English lang pack). * Adding the colon can be explicitly disabled if needed. Label separators * are put outside the label tag itself so they are not read by * screenreaders (accessibility). * * Parameter $for explicitly associates the label with a form control. When * set, the value of this attribute must be the same as the value of * the id attribute of the form control in the same document. When null, * the label being defined is associated with the control inside the label * element. * * @param string $text content of the label tag * @param string|null $for id of the element this label is associated with, null for no association * @param bool $colonize add label separator (colon) to the label text, if it is not there yet * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a') * @return string HTML of the label element */ public static function label($text, $for, $colonize = true, array $attributes=array()) { if (!is_null($for)) { $attributes = array_merge($attributes, array('for' => $for)); } $text = trim($text); $label = self::tag('label', $text, $attributes); // TODO MDL-12192 $colonize disabled for now yet // if (!empty($text) and $colonize) { // // the $text may end with the colon already, though it is bad string definition style // $colon = get_string('labelsep', 'langconfig'); // if (!empty($colon)) { // $trimmed = trim($colon); // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) { // //debugging('The label text should not end with colon or other label separator, // // please fix the string definition.', DEBUG_DEVELOPER); // } else { // $label .= $colon; // } // } // } return $label; } /** * Combines a class parameter with other attributes. Aids in code reduction * because the class parameter is very frequently used. * * If the class attribute is specified both in the attributes and in the * class parameter, the two values are combined with a space between. * * @param string $class Optional CSS class (or classes as space-separated list) * @param array $attributes Optional other attributes as array * @return array Attributes (or null if still none) */ private static function add_class($class = '', array $attributes = null) { if ($class !== '') { $classattribute = array('class' => $class); if ($attributes) { if (array_key_exists('class', $attributes)) { $attributes['class'] = trim($attributes['class'] . ' ' . $class); } else { $attributes = $classattribute + $attributes; } } else { $attributes = $classattribute; } } return $attributes; } /** * Creates a <div> tag. (Shortcut function.) * * @param string $content HTML content of tag * @param string $class Optional CSS class (or classes as space-separated list) * @param array $attributes Optional other attributes as array * @return string HTML code for div */ public static function div($content, $class = '', array $attributes = null) { return self::tag('div', $content, self::add_class($class, $attributes)); } /** * Starts a <div> tag. (Shortcut function.) * * @param string $class Optional CSS class (or classes as space-separated list) * @param array $attributes Optional other attributes as array * @return string HTML code for open div tag */ public static function start_div($class = '', array $attributes = null) { return self::start_tag('div', self::add_class($class, $attributes)); } /** * Ends a <div> tag. (Shortcut function.) * * @return string HTML code for close div tag */ public static function end_div() { return self::end_tag('div'); } /** * Creates a <span> tag. (Shortcut function.) * * @param string $content HTML content of tag * @param string $class Optional CSS class (or classes as space-separated list) * @param array $attributes Optional other attributes as array * @return string HTML code for span */ public static function span($content, $class = '', array $attributes = null) { return self::tag('span', $content, self::add_class($class, $attributes)); } /** * Starts a <span> tag. (Shortcut function.) * * @param string $class Optional CSS class (or classes as space-separated list) * @param array $attributes Optional other attributes as array * @return string HTML code for open span tag */ public static function start_span($class = '', array $attributes = null) { return self::start_tag('span', self::add_class($class, $attributes)); } /** * Ends a <span> tag. (Shortcut function.) * * @return string HTML code for close span tag */ public static function end_span() { return self::end_tag('span'); } } /** * Simple javascript output class * * @copyright 2010 Petr Skoda * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class js_writer { /** * Returns javascript code calling the function * * @param string $function function name, can be complex like Y.Event.purgeElement * @param array $arguments parameters * @param int $delay execution delay in seconds * @return string JS code fragment */ public static function function_call($function, array $arguments = null, $delay=0) { if ($arguments) { $arguments = array_map('json_encode', convert_to_array($arguments)); $arguments = implode(', ', $arguments); } else { $arguments = ''; } $js = "$function($arguments);"; if ($delay) { $delay = $delay * 1000; // in miliseconds $js = "setTimeout(function() { $js }, $delay);"; } return $js . "\n"; } /** * Special function which adds Y as first argument of function call. * * @param string $function The function to call * @param array $extraarguments Any arguments to pass to it * @return string Some JS code */ public static function function_call_with_Y($function, array $extraarguments = null) { if ($extraarguments) { $extraarguments = array_map('json_encode', convert_to_array($extraarguments)); $arguments = 'Y, ' . implode(', ', $extraarguments); } else { $arguments = 'Y'; } return "$function($arguments);\n"; } /** * Returns JavaScript code to initialise a new object * * @param string $var If it is null then no var is assigned the new object. * @param string $class The class to initialise an object for. * @param array $arguments An array of args to pass to the init method. * @param array $requirements Any modules required for this class. * @param int $delay The delay before initialisation. 0 = no delay. * @return string Some JS code */ public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) { if (is_array($arguments)) { $arguments = array_map('json_encode', convert_to_array($arguments)); $arguments = implode(', ', $arguments); } if ($var === null) { $js = "new $class(Y, $arguments);"; } else if (strpos($var, '.')!==false) { $js = "$var = new $class(Y, $arguments);"; } else { $js = "var $var = new $class(Y, $arguments);"; } if ($delay) { $delay = $delay * 1000; // in miliseconds $js = "setTimeout(function() { $js }, $delay);"; } if (count($requirements) > 0) { $requirements = implode("', '", $requirements); $js = "Y.use('$requirements', function(Y){ $js });"; } return $js."\n"; } /** * Returns code setting value to variable * * @param string $name * @param mixed $value json serialised value * @param bool $usevar add var definition, ignored for nested properties * @return string JS code fragment */ public static function set_variable($name, $value, $usevar = true) { $output = ''; if ($usevar) { if (strpos($name, '.')) { $output .= ''; } else { $output .= 'var '; } } $output .= "$name = ".json_encode($value).";"; return $output; } /** * Writes event handler attaching code * * @param array|string $selector standard YUI selector for elements, may be * array or string, element id is in the form "#idvalue" * @param string $event A valid DOM event (click, mousedown, change etc.) * @param string $function The name of the function to call * @param array $arguments An optional array of argument parameters to pass to the function * @return string JS code fragment */ public static function event_handler($selector, $event, $function, array $arguments = null) { $selector = json_encode($selector); $output = "Y.on('$event', $function, $selector, null"; if (!empty($arguments)) { $output .= ', ' . json_encode($arguments); } return $output . ");\n"; } } /** * Holds all the information required to render a <table> by {@link core_renderer::table()} * * Example of usage: * $t = new html_table(); * ... // set various properties of the object $t as described below * echo html_writer::table($t); * * @copyright 2009 David Mudrak <david.mudrak@gmail.com> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class html_table { /** * @var string Value to use for the id attribute of the table */ public $id = null; /** * @var array Attributes of HTML attributes for the <table> element */ public $attributes = array(); /** * @var array An array of headings. The n-th array item is used as a heading of the n-th column. * For more control over the rendering of the headers, an array of html_table_cell objects * can be passed instead of an array of strings. * * Example of usage: * $t->head = array('Student', 'Grade'); */ public $head; /** * @var array An array that can be used to make a heading span multiple columns. * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns, * the same heading is used. Therefore, {@link html_table::$head} should consist of two items. * * Example of usage: * $t->headspan = array(2,1); */ public $headspan; /** * @var array An array of column alignments. * The value is used as CSS 'text-align' property. Therefore, possible * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective * of a left-to-right (LTR) language. For RTL, the values are flipped automatically. * * Examples of usage: * $t->align = array(null, 'right'); * or * $t->align[1] = 'right'; */ public $align; /** * @var array The value is used as CSS 'size' property. * * Examples of usage: * $t->size = array('50%', '50%'); * or * $t->size[1] = '120px'; */ public $size; /** * @var array An array of wrapping information. * The only possible value is 'nowrap' that sets the * CSS property 'white-space' to the value 'nowrap' in the given column. * * Example of usage: * $t->wrap = array(null, 'nowrap'); */ public $wrap; /** * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have * $head specified, the string 'hr' (for horizontal ruler) can be used * instead of an array of cells data resulting in a divider rendered. * * Example of usage with array of arrays: * $row1 = array('Harry Potter', '76 %'); * $row2 = array('Hermione Granger', '100 %'); * $t->data = array($row1, $row2); * * Example with array of html_table_row objects: (used for more fine-grained control) * $cell1 = new html_table_cell(); * $cell1->text = 'Harry Potter'; * $cell1->colspan = 2; * $row1 = new html_table_row(); * $row1->cells[] = $cell1; * $cell2 = new html_table_cell(); * $cell2->text = 'Hermione Granger'; * $cell3 = new html_table_cell(); * $cell3->text = '100 %'; * $row2 = new html_table_row(); * $row2->cells = array($cell2, $cell3); * $t->data = array($row1, $row2); */ public $data; /** * @deprecated since Moodle 2.0. Styling should be in the CSS. * @var string Width of the table, percentage of the page preferred. */ public $width = null; /** * @deprecated since Moodle 2.0. Styling should be in the CSS. * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default). */ public $tablealign = null; /** * @deprecated since Moodle 2.0. Styling should be in the CSS. * @var int Padding on each cell, in pixels */ public $cellpadding = null; /** * @var int Spacing between cells, in pixels * @deprecated since Moodle 2.0. Styling should be in the CSS. */ public $cellspacing = null; /** * @var array Array of classes to add to particular rows, space-separated string. * Classes 'r0' or 'r1' are added automatically for every odd or even row, * respectively. Class 'lastrow' is added automatically for the last row * in the table. * * Example of usage: * $t->rowclasses[9] = 'tenth' */ public $rowclasses; /** * @var array An array of classes to add to every cell in a particular column, * space-separated string. Class 'cell' is added automatically by the renderer. * Classes 'c0' or 'c1' are added automatically for every odd or even column, * respectively. Class 'lastcol' is added automatically for all last cells * in a row. * * Example of usage: * $t->colclasses = array(null, 'grade'); */ public $colclasses; /** * @var string Description of the contents for screen readers. */ public $summary; /** * Constructor */ public function __construct() { $this->attributes['class'] = ''; } } /** * Component representing a table row. * * @copyright 2009 Nicolas Connault * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class html_table_row { /** * @var string Value to use for the id attribute of the row. */ public $id = null; /** * @var array Array of html_table_cell objects */ public $cells = array(); /** * @var string Value to use for the style attribute of the table row */ public $style = null; /** * @var array Attributes of additional HTML attributes for the <tr> element */ public $attributes = array(); /** * Constructor * @param array $cells */ public function __construct(array $cells=null) { $this->attributes['class'] = ''; $cells = (array)$cells; foreach ($cells as $cell) { if ($cell instanceof html_table_cell) { $this->cells[] = $cell; } else { $this->cells[] = new html_table_cell($cell); } } } } /** * Component representing a table cell. * * @copyright 2009 Nicolas Connault * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class html_table_cell { /** * @var string Value to use for the id attribute of the cell. */ public $id = null; /** * @var string The contents of the cell. */ public $text; /** * @var string Abbreviated version of the contents of the cell. */ public $abbr = null; /** * @var int Number of columns this cell should span. */ public $colspan = null; /** * @var int Number of rows this cell should span. */ public $rowspan = null; /** * @var string Defines a way to associate header cells and data cells in a table. */ public $scope = null; /** * @var bool Whether or not this cell is a header cell. */ public $header = null; /** * @var string Value to use for the style attribute of the table cell */ public $style = null; /** * @var array Attributes of additional HTML attributes for the <td> element */ public $attributes = array(); /** * Constructs a table cell * * @param string $text */ public function __construct($text = null) { $this->text = $text; $this->attributes['class'] = ''; } } /** * Component representing a paging bar. * * @copyright 2009 Nicolas Connault * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class paging_bar implements renderable { /** * @var int The maximum number of pagelinks to display. */ public $maxdisplay = 18; /** * @var int The total number of entries to be pages through.. */ public $totalcount; /** * @var int The page you are currently viewing. */ public $page; /** * @var int The number of entries that should be shown per page. */ public $perpage; /** * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar, * an equals sign and the page number. * If this is a moodle_url object then the pagevar param will be replaced by * the page no, for each page. */ public $baseurl; /** * @var string This is the variable name that you use for the pagenumber in your * code (ie. 'tablepage', 'blogpage', etc) */ public $pagevar; /** * @var string A HTML link representing the "previous" page. */ public $previouslink = null; /** * @var string A HTML link representing the "next" page. */ public $nextlink = null; /** * @var string A HTML link representing the first page. */ public $firstlink = null; /** * @var string A HTML link representing the last page. */ public $lastlink = null; /** * @var array An array of strings. One of them is just a string: the current page */ public $pagelinks = array(); /** * Constructor paging_bar with only the required params. * * @param int $totalcount The total number of entries available to be paged through * @param int $page The page you are currently viewing * @param int $perpage The number of entries that should be shown per page * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added * @param string $pagevar name of page parameter that holds the page number */ public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') { $this->totalcount = $totalcount; $this->page = $page; $this->perpage = $perpage; $this->baseurl = $baseurl; $this->pagevar = $pagevar; } /** * Prepares the paging bar for output. * * This method validates the arguments set up for the paging bar and then * produces fragments of HTML to assist display later on. * * @param renderer_base $output * @param moodle_page $page * @param string $target * @throws coding_exception */ public function prepare(renderer_base $output, moodle_page $page, $target) { if (!isset($this->totalcount) || is_null($this->totalcount)) { throw new coding_exception('paging_bar requires a totalcount value.'); } if (!isset($this->page) || is_null($this->page)) { throw new coding_exception('paging_bar requires a page value.'); } if (empty($this->perpage)) { throw new coding_exception('paging_bar requires a perpage value.'); } if (empty($this->baseurl)) { throw new coding_exception('paging_bar requires a baseurl value.'); } if ($this->totalcount > $this->perpage) { $pagenum = $this->page - 1; if ($this->page > 0) { $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous')); } if ($this->perpage > 0) { $lastpage = ceil($this->totalcount / $this->perpage); } else { $lastpage = 1; } if ($this->page > round(($this->maxdisplay/3)*2)) { $currpage = $this->page - round($this->maxdisplay/3); $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first')); } else { $currpage = 0; } $displaycount = $displaypage = 0; while ($displaycount < $this->maxdisplay and $currpage < $lastpage) { $displaypage = $currpage + 1; if ($this->page == $currpage) { $this->pagelinks[] = html_writer::span($displaypage, 'current-page'); } else { $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage); $this->pagelinks[] = $pagelink; } $displaycount++; $currpage++; } if ($currpage < $lastpage) { $lastpageactual = $lastpage - 1; $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last')); } $pagenum = $this->page + 1; if ($pagenum != $displaypage) { $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next')); } } } } /** * This class represents how a block appears on a page. * * During output, each block instance is asked to return a block_contents object, * those are then passed to the $OUTPUT->block function for display. * * contents should probably be generated using a moodle_block_..._renderer. * * Other block-like things that need to appear on the page, for example the * add new block UI, are also represented as block_contents objects. * * @copyright 2009 Tim Hunt * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class block_contents { /** Used when the block cannot be collapsed **/ const NOT_HIDEABLE = 0; /** Used when the block can be collapsed but currently is not **/ const VISIBLE = 1; /** Used when the block has been collapsed **/ const HIDDEN = 2; /** * @var int Used to set $skipid. */ protected static $idcounter = 1; /** * @var int All the blocks (or things that look like blocks) printed on * a page are given a unique number that can be used to construct id="" attributes. * This is set automatically be the {@link prepare()} method. * Do not try to set it manually. */ public $skipid; /** * @var int If this is the contents of a real block, this should be set * to the block_instance.id. Otherwise this should be set to 0. */ public $blockinstanceid = 0; /** * @var int If this is a real block instance, and there is a corresponding * block_position.id for the block on this page, this should be set to that id. * Otherwise it should be 0. */ public $blockpositionid = 0; /** * @var array An array of attribute => value pairs that are put on the outer div of this * block. {@link $id} and {@link $classes} attributes should be set separately. */ public $attributes; /** * @var string The title of this block. If this came from user input, it should already * have had format_string() processing done on it. This will be output inside * <h2> tags. Please do not cause invalid XHTML. */ public $title = ''; /** * @var string The label to use when the block does not, or will not have a visible title. * You should never set this as well as title... it will just be ignored. */ public $arialabel = ''; /** * @var string HTML for the content */ public $content = ''; /** * @var array An alternative to $content, it you want a list of things with optional icons. */ public $footer = ''; /** * @var string Any small print that should appear under the block to explain * to the teacher about the block, for example 'This is a sticky block that was * added in the system context.' */ public $annotation = ''; /** * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether * the user can toggle whether this block is visible. */ public $collapsible = self::NOT_HIDEABLE; /** * Set this to true if the block is dockable. * @var bool */ public $dockable = false; /** * @var array A (possibly empty) array of editing controls. Each element of * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption). * $icon is the icon name. Fed to $OUTPUT->pix_url. */ public $controls = array(); /** * Create new instance of block content * @param array $attributes */ public function __construct(array $attributes = null) { $this->skipid = self::$idcounter; self::$idcounter += 1; if ($attributes) { // standard block $this->attributes = $attributes; } else { // simple "fake" blocks used in some modules and "Add new block" block $this->attributes = array('class'=>'block'); } } /** * Add html class to block * * @param string $class */ public function add_class($class) { $this->attributes['class'] .= ' '.$class; } } /** * This class represents a target for where a block can go when it is being moved. * * This needs to be rendered as a form with the given hidden from fields, and * clicking anywhere in the form should submit it. The form action should be * $PAGE->url. * * @copyright 2009 Tim Hunt * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class block_move_target { /** * @var moodle_url Move url */ public $url; /** * Constructor * @param moodle_url $url */ public function __construct(moodle_url $url) { $this->url = $url; } } /** * Custom menu item * * This class is used to represent one item within a custom menu that may or may * not have children. * * @copyright 2010 Sam Hemelryk * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class custom_menu_item implements renderable { /** * @var string The text to show for the item */ protected $text; /** * @var moodle_url The link to give the icon if it has no children */ protected $url; /** * @var string A title to apply to the item. By default the text */ protected $title; /** * @var int A sort order for the item, not necessary if you order things in * the CFG var. */ protected $sort; /** * @var custom_menu_item A reference to the parent for this item or NULL if * it is a top level item */ protected $parent; /** * @var array A array in which to store children this item has. */ protected $children = array(); /** * @var int A reference to the sort var of the last child that was added */ protected $lastsort = 0; /** * Constructs the new custom menu item * * @param string $text * @param moodle_url $url A moodle url to apply as the link for this item [Optional] * @param string $title A title to apply to this item [Optional] * @param int $sort A sort or to use if we need to sort differently [Optional] * @param custom_menu_item $parent A reference to the parent custom_menu_item this child * belongs to, only if the child has a parent. [Optional] */ public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent = null) { $this->text = $text; $this->url = $url; $this->title = $title; $this->sort = (int)$sort; $this->parent = $parent; } /** * Adds a custom menu item as a child of this node given its properties. * * @param string $text * @param moodle_url $url * @param string $title * @param int $sort * @return custom_menu_item */ public function add($text, moodle_url $url = null, $title = null, $sort = null) { $key = count($this->children); if (empty($sort)) { $sort = $this->lastsort + 1; } $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this); $this->lastsort = (int)$sort; return $this->children[$key]; } /** * Removes a custom menu item that is a child or descendant to the current menu. * * Returns true if child was found and removed. * * @param custom_menu_item $menuitem * @return bool */ public function remove_child(custom_menu_item $menuitem) { $removed = false; if (($key = array_search($menuitem, $this->children)) !== false) { unset($this->children[$key]); $this->children = array_values($this->children); $removed = true; } else { foreach ($this->children as $child) { if ($removed = $child->remove_child($menuitem)) { break; } } } return $removed; } /** * Returns the text for this item * @return string */ public function get_text() { return $this->text; } /** * Returns the url for this item * @return moodle_url */ public function get_url() { return $this->url; } /** * Returns the title for this item * @return string */ public function get_title() { return $this->title; } /** * Sorts and returns the children for this item * @return array */ public function get_children() { $this->sort(); return $this->children; } /** * Gets the sort order for this child * @return int */ public function get_sort_order() { return $this->sort; } /** * Gets the parent this child belong to * @return custom_menu_item */ public function get_parent() { return $this->parent; } /** * Sorts the children this item has */ public function sort() { usort($this->children, array('custom_menu','sort_custom_menu_items')); } /** * Returns true if this item has any children * @return bool */ public function has_children() { return (count($this->children) > 0); } /** * Sets the text for the node * @param string $text */ public function set_text($text) { $this->text = (string)$text; } /** * Sets the title for the node * @param string $title */ public function set_title($title) { $this->title = (string)$title; } /** * Sets the url for the node * @param moodle_url $url */ public function set_url(moodle_url $url) { $this->url = $url; } } /** * Custom menu class * * This class is used to operate a custom menu that can be rendered for the page. * The custom menu is built using $CFG->custommenuitems and is a structured collection * of custom_menu_item nodes that can be rendered by the core renderer. * * To configure the custom menu: * Settings: Administration > Appearance > Themes > Theme settings * * @copyright 2010 Sam Hemelryk * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.0 * @package core * @category output */ class custom_menu extends custom_menu_item { /** * @var string The language we should render for, null disables multilang support. */ protected $currentlanguage = null; /** * Creates the custom menu * * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()} * @param string $currentlanguage the current language code, null disables multilang support */ public function __construct($definition = '', $currentlanguage = null) { $this->currentlanguage = $currentlanguage; parent::__construct('root'); // create virtual root element of the menu if (!empty($definition)) { $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage)); } } /** * Overrides the children of this custom menu. Useful when getting children * from $CFG->custommenuitems * * @param array $children */ public function override_children(array $children) { $this->children = array(); foreach ($children as $child) { if ($child instanceof custom_menu_item) { $this->children[] = $child; } } } /** * Converts a string into a structured array of custom_menu_items which can * then be added to a custom menu. * * Structure: * text|url|title|langs * The number of hyphens at the start determines the depth of the item. The * languages are optional, comma separated list of languages the line is for. * * Example structure: * First level first item|http://www.moodle.com/ * -Second level first item|http://www.moodle.com/partners/ * -Second level second item|http://www.moodle.com/hq/ * --Third level first item|http://www.moodle.com/jobs/ * -Second level third item|http://www.moodle.com/development/ * First level second item|http://www.moodle.com/feedback/ * First level third item * English only|http://moodle.com|English only item|en * German only|http://moodle.de|Deutsch|de,de_du,de_kids * * * @static * @param string $text the menu items definition * @param string $language the language code, null disables multilang support * @return array */ public static function convert_text_to_menu_nodes($text, $language = null) { $root = new custom_menu(); $lastitem = $root; $lastdepth = 0; $hiddenitems = array(); $lines = explode("\n", $text); foreach ($lines as $linenumber => $line) { $line = trim($line); if (strlen($line) == 0) { continue; } // Parse item settings. $itemtext = null; $itemurl = null; $itemtitle = null; $itemvisible = true; $settings = explode('|', $line); foreach ($settings as $i => $setting) { $setting = trim($setting); if (!empty($setting)) { switch ($i) { case 0: $itemtext = ltrim($setting, '-'); $itemtitle = $itemtext; break; case 1: $itemurl = new moodle_url($setting); break; case 2: $itemtitle = $setting; break; case 3: if (!empty($language)) { $itemlanguages = array_map('trim', explode(',', $setting)); $itemvisible &= in_array($language, $itemlanguages); } break; } } } // Get depth of new item. preg_match('/^(\-*)/', $line, $match); $itemdepth = strlen($match[1]) + 1; // Find parent item for new item. while (($lastdepth - $itemdepth) >= 0) { $lastitem = $lastitem->get_parent(); $lastdepth--; } $lastitem = $lastitem->add($itemtext, $itemurl, $itemtitle, $linenumber + 1); $lastdepth++; if (!$itemvisible) { $hiddenitems[] = $lastitem; } } foreach ($hiddenitems as $item) { $item->parent->remove_child($item); } return $root->get_children(); } /** * Sorts two custom menu items * * This function is designed to be used with the usort method * usort($this->children, array('custom_menu','sort_custom_menu_items')); * * @static * @param custom_menu_item $itema * @param custom_menu_item $itemb * @return int */ public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) { $itema = $itema->get_sort_order(); $itemb = $itemb->get_sort_order(); if ($itema == $itemb) { return 0; } return ($itema > $itemb) ? +1 : -1; } } /** * Stores one tab * * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @package core */ class tabobject implements renderable { /** @var string unique id of the tab in this tree, it is used to find selected and/or inactive tabs */ var $id; /** @var moodle_url|string link */ var $link; /** @var string text on the tab */ var $text; /** @var string title under the link, by defaul equals to text */ var $title; /** @var bool whether to display a link under the tab name when it's selected */ var $linkedwhenselected = false; /** @var bool whether the tab is inactive */ var $inactive = false; /** @var bool indicates that this tab's child is selected */ var $activated = false; /** @var bool indicates that this tab is selected */ var $selected = false; /** @var array stores children tabobjects */ var $subtree = array(); /** @var int level of tab in the tree, 0 for root (instance of tabtree), 1 for the first row of tabs */ var $level = 1; /** * Constructor * * @param string $id unique id of the tab in this tree, it is used to find selected and/or inactive tabs * @param string|moodle_url $link * @param string $text text on the tab * @param string $title title under the link, by defaul equals to text * @param bool $linkedwhenselected whether to display a link under the tab name when it's selected */ public function __construct($id, $link = null, $text = '', $title = '', $linkedwhenselected = false) { $this->id = $id; $this->link = $link; $this->text = $text; $this->title = $title ? $title : $text; $this->linkedwhenselected = $linkedwhenselected; } /** * Travels through tree and finds the tab to mark as selected, all parents are automatically marked as activated * * @param string $selected the id of the selected tab (whatever row it's on), * if null marks all tabs as unselected * @return bool whether this tab is selected or contains selected tab in its subtree */ protected function set_selected($selected) { if ((string)$selected === (string)$this->id) { $this->selected = true; // This tab is selected. No need to travel through subtree. return true; } foreach ($this->subtree as $subitem) { if ($subitem->set_selected($selected)) { // This tab has child that is selected. Mark it as activated. No need to check other children. $this->activated = true; return true; } } return false; } /** * Travels through tree and finds a tab with specified id * * @param string $id * @return tabtree|null */ public function find($id) { if ((string)$this->id === (string)$id) { return $this; } foreach ($this->subtree as $tab) { if ($obj = $tab->find($id)) { return $obj; } } return null; } /** * Allows to mark each tab's level in the tree before rendering. * * @param int $level */ protected function set_level($level) { $this->level = $level; foreach ($this->subtree as $tab) { $tab->set_level($level + 1); } } } /** * Stores tabs list * * Example how to print a single line tabs: * $rows = array( * new tabobject(...), * new tabobject(...) * ); * echo $OUTPUT->tabtree($rows, $selectedid); * * Multiple row tabs may not look good on some devices but if you want to use them * you can specify ->subtree for the active tabobject. * * @copyright 2013 Marina Glancy * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @since Moodle 2.5 * @package core * @category output */ class tabtree extends tabobject { /** * Constuctor * * It is highly recommended to call constructor when list of tabs is already * populated, this way you ensure that selected and inactive tabs are located * and attribute level is set correctly. * * @param array $tabs array of tabs, each of them may have it's own ->subtree * @param string|null $selected which tab to mark as selected, all parent tabs will * automatically be marked as activated * @param array|string|null $inactive list of ids of inactive tabs, regardless of * their level. Note that you can as weel specify tabobject::$inactive for separate instances */ public function __construct($tabs, $selected = null, $inactive = null) { $this->subtree = $tabs; if ($selected !== null) { $this->set_selected($selected); } if ($inactive !== null) { if (is_array($inactive)) { foreach ($inactive as $id) { if ($tab = $this->find($id)) { $tab->inactive = true; } } } else if ($tab = $this->find($inactive)) { $tab->inactive = true; } } $this->set_level(0); } } /** * An action menu. * * This action menu component takes a series of primary and secondary actions. * The primary actions are displayed permanently and the secondary attributes are displayed within a drop * down menu. * * @package core * @category output * @copyright 2013 Sam Hemelryk * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class action_menu implements renderable { /** * Top right alignment. */ const TL = 1; /** * Top right alignment. */ const TR = 2; /** * Top right alignment. */ const BL = 3; /** * Top right alignment. */ const BR = 4; /** * The instance number. This is unique to this instance of the action menu. * @var int */ protected $instance = 0; /** * An array of primary actions. Please use {@link action_menu::add_primary_action()} to add actions. * @var array */ protected $primaryactions = array(); /** * An array of secondary actions. Please use {@link action_menu::add_secondary_action()} to add actions. * @var array */ protected $secondaryactions = array(); /** * An array of attributes added to the container of the action menu. * Initialised with defaults during construction. * @var array */ public $attributes = array(); /** * An array of attributes added to the container of the primary actions. * Initialised with defaults during construction. * @var array */ public $attributesprimary = array(); /** * An array of attributes added to the container of the secondary actions. * Initialised with defaults during construction. * @var array */ public $attributessecondary = array(); /** * The string to use next to the icon for the action icon relating to the secondary (dropdown) menu. * @var array */ public $actiontext = null; /** * An icon to use for the toggling the secondary menu (dropdown). * @var actionicon */ public $actionicon; /** * Any text to use for the toggling the secondary menu (dropdown). * @var menutrigger */ public $menutrigger = ''; /** * Place the action menu before all other actions. * @var prioritise */ public $prioritise = false; /** * Constructs the action menu with the given items. * * @param array $actions An array of actions. */ public function __construct(array $actions = array()) { static $initialised = 0; $this->instance = $initialised; $initialised++; $this->attributes = array( 'id' => 'action-menu-'.$this->instance, 'class' => 'moodle-actionmenu', 'data-enhance' => 'moodle-core-actionmenu' ); $this->attributesprimary = array( 'id' => 'action-menu-'.$this->instance.'-menubar', 'class' => 'menubar', 'role' => 'menubar' ); $this->attributessecondary = array( 'id' => 'action-menu-'.$this->instance.'-menu', 'class' => 'menu', 'data-rel' => 'menu-content', 'aria-labelledby' => 'action-menu-toggle-'.$this->instance, 'role' => 'menu' ); $this->set_alignment(self::TR, self::BR); foreach ($actions as $action) { $this->add($action); } } public function set_menu_trigger($trigger) { $this->menutrigger = $trigger; } /** * Initialises JS required fore the action menu. * The JS is only required once as it manages all action menu's on the page. * * @param moodle_page $page */ public function initialise_js(moodle_page $page) { static $initialised = false; if (!$initialised) { $page->requires->yui_module('moodle-core-actionmenu', 'M.core.actionmenu.init'); $initialised = true; } } /** * Adds an action to this action menu. * * @param action_menu_link|pix_icon|string $action */ public function add($action) { if ($action instanceof action_link) { if ($action->primary) { $this->add_primary_action($action); } else { $this->add_secondary_action($action); } } else if ($action instanceof pix_icon) { $this->add_primary_action($action); } else { $this->add_secondary_action($action); } } /** * Adds a primary action to the action menu. * * @param action_menu_link|action_link|pix_icon|string $action */ public function add_primary_action($action) { if ($action instanceof action_link || $action instanceof pix_icon) { $action->attributes['role'] = 'menuitem'; if ($action instanceof action_menu_link) { $action->actionmenu = $this; } } $this->primaryactions[] = $action; } /** * Adds a secondary action to the action menu. * * @param action_link|pix_icon|string $action */ public function add_secondary_action($action) { if ($action instanceof action_link || $action instanceof pix_icon) { $action->attributes['role'] = 'menuitem'; if ($action instanceof action_menu_link) { $action->actionmenu = $this; } } $this->secondaryactions[] = $action; } /** * Returns the primary actions ready to be rendered. * * @param core_renderer $output The renderer to use for getting icons. * @return array */ public function get_primary_actions(core_renderer $output = null) { global $OUTPUT; if ($output === null) { $output = $OUTPUT; } $pixicon = $this->actionicon; $linkclasses = array('toggle-display'); $title = ''; if (!empty($this->menutrigger)) { $pixicon = '<b class="caret"></b>'; $linkclasses[] = 'textmenu'; } else { $title = new lang_string('actions', 'moodle'); $this->actionicon = new pix_icon( 't/edit_menu', '', 'moodle', array('class' => 'iconsmall actionmenu', 'title' => '') ); $pixicon = $this->actionicon; } if ($pixicon instanceof renderable) { $pixicon = $output->render($pixicon); if ($pixicon instanceof pix_icon && isset($pixicon->attributes['alt'])) { $title = $pixicon->attributes['alt']; } } $string = ''; if ($this->actiontext) { $string = $this->actiontext; } $actions = $this->primaryactions; $attributes = array( 'class' => implode(' ', $linkclasses), 'title' => $title, 'id' => 'action-menu-toggle-'.$this->instance, 'role' => 'menuitem' ); $link = html_writer::link('#', $string . $this->menutrigger . $pixicon, $attributes); if ($this->prioritise) { array_unshift($actions, $link); } else { $actions[] = $link; } return $actions; } /** * Returns the secondary actions ready to be rendered. * @return array */ public function get_secondary_actions() { return $this->secondaryactions; } /** * Sets the selector that should be used to find the owning node of this menu. * @param string $selector A CSS/YUI selector to identify the owner of the menu. */ public function set_owner_selector($selector) { $this->attributes['data-owner'] = $selector; } /** * Sets the alignment of the dialogue in relation to button used to toggle it. * * @param int $dialogue One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR. * @param int $button One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR. */ public function set_alignment($dialogue, $button) { if (isset($this->attributessecondary['data-align'])) { // We've already got one set, lets remove the old class so as to avoid troubles. $class = $this->attributessecondary['class']; $search = 'align-'.$this->attributessecondary['data-align']; $this->attributessecondary['class'] = str_replace($search, '', $class); } $align = $this->get_align_string($dialogue) . '-' . $this->get_align_string($button); $this->attributessecondary['data-align'] = $align; $this->attributessecondary['class'] .= ' align-'.$align; } /** * Returns a string to describe the alignment. * * @param int $align One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR. * @return string */ protected function get_align_string($align) { switch ($align) { case self::TL : return 'tl'; case self::TR : return 'tr'; case self::BL : return 'bl'; case self::BR : return 'br'; default : return 'tl'; } } /** * Sets a constraint for the dialogue. * * The constraint is applied when the dialogue is shown and limits the display of the dialogue to within the * element the constraint identifies. * * @param string $ancestorselector A snippet of CSS used to identify the ancestor to contrain the dialogue to. */ public function set_constraint($ancestorselector) { $this->attributessecondary['data-constraint'] = $ancestorselector; } /** * If you call this method the action menu will be displayed but will not be enhanced. * * By not displaying the menu enhanced all items will be displayed in a single row. */ public function do_not_enhance() { unset($this->attributes['data-enhance']); } /** * Returns true if this action menu will be enhanced. * * @return bool */ public function will_be_enhanced() { return isset($this->attributes['data-enhance']); } /** * Sets nowrap on items. If true menu items should not wrap lines if they are longer than the available space. * * This property can be useful when the action menu is displayed within a parent element that is either floated * or relatively positioned. * In that situation the width of the menu is determined by the width of the parent element which may not be large * enough for the menu items without them wrapping. * This disables the wrapping so that the menu takes on the width of the longest item. * * @param bool $value If true nowrap gets set, if false it gets removed. Defaults to true. */ public function set_nowrap_on_items($value = true) { $class = 'nowrap-items'; if (!empty($this->attributes['class'])) { $pos = strpos($this->attributes['class'], $class); if ($value === true && $pos === false) { // The value is true and the class has not been set yet. Add it. $this->attributes['class'] .= ' '.$class; } else if ($value === false && $pos !== false) { // The value is false and the class has been set. Remove it. $this->attributes['class'] = substr($this->attributes['class'], $pos, strlen($class)); } } else if ($value) { // The value is true and the class has not been set yet. Add it. $this->attributes['class'] = $class; } } } /** * An action menu filler * * @package core * @category output * @copyright 2013 Andrew Nicols * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class action_menu_filler extends action_link implements renderable { /** * True if this is a primary action. False if not. * @var bool */ public $primary = true; /** * Constructs the object. */ public function __construct() { } } /** * An action menu action * * @package core * @category output * @copyright 2013 Sam Hemelryk * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class action_menu_link extends action_link implements renderable { /** * True if this is a primary action. False if not. * @var bool */ public $primary = true; /** * The action menu this link has been added to. * @var action_menu */ public $actionmenu = null; /** * Constructs the object. * * @param moodle_url $url The URL for the action. * @param pix_icon $icon The icon to represent the action. * @param string $text The text to represent the action. * @param bool $primary Whether this is a primary action or not. * @param array $attributes Any attribtues associated with the action. */ public function __construct(moodle_url $url, pix_icon $icon = null, $text, $primary = true, array $attributes = array()) { parent::__construct($url, $text, null, $attributes, $icon); $this->primary = (bool)$primary; $this->add_class('menu-action'); $this->attributes['role'] = 'menuitem'; } } /** * A primary action menu action * * @package core * @category output * @copyright 2013 Sam Hemelryk * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class action_menu_link_primary extends action_menu_link { /** * Constructs the object. * * @param moodle_url $url * @param pix_icon $icon * @param string $text * @param array $attributes */ public function __construct(moodle_url $url, pix_icon $icon = null, $text, array $attributes = array()) { parent::__construct($url, $icon, $text, true, $attributes); } } /** * A secondary action menu action * * @package core * @category output * @copyright 2013 Sam Hemelryk * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class action_menu_link_secondary extends action_menu_link { /** * Constructs the object. * * @param moodle_url $url * @param pix_icon $icon * @param string $text * @param array $attributes */ public function __construct(moodle_url $url, pix_icon $icon = null, $text, array $attributes = array()) { parent::__construct($url, $icon, $text, false, $attributes); } }
VNageswararao/lms28
lib/outputcomponents.php
PHP
gpl-3.0
115,993
=pod =head1 NAME Locale::Currency - standard codes for currency identification =head1 SYNOPSIS use Locale::Currency; $curr = code2currency('usd'); # $curr gets 'US Dollar' $code = currency2code('Euro'); # $code gets 'eur' @codes = all_currency_codes(); @names = all_currency_names(); =head1 DESCRIPTION This module provides access to standard codes used for identifying currencies and funds, such as those defined in ISO 4217. Most of the routines take an optional additional argument which specifies the code set to use. If not specified, the default ISO 4217 three-letter codes will be used. =head1 SUPPORTED CODE SETS There are several different code sets you can use for identifying currencies. A code set may be specified using either a name, or a constant that is automatically exported by this module. For example, the two are equivalent: $curr = code2currency('usd','alpha'); $curr = code2currency('usd',LOCALE_CURR_ALPHA); The codesets currently supported are: =over 4 =item B<alpha, LOCALE_CURR_ALPHA> This is a set of three-letter (uppercase) codes from ISO 4217 such as EUR for Euro. Two of the codes specified by the standard (XTS which is reserved for testing purposes and XXX which is for transactions where no currency is involved) are omitted. This is the default code set. =item B<num, LOCALE_CURR_NUMERIC> This is the set of three-digit numeric codes from ISO 4217. =back =head1 ROUTINES =over 4 =item B<code2currency(CODE [,CODESET] [,'retired'])> =item B<currency2code(NAME [,CODESET] [,'retired'])> =item B<currency_code2code(CODE ,CODESET ,CODESET2)> =item B<all_currency_codes([CODESET] [,'retired'])> =item B<all_currency_names([CODESET] [,'retired'])> =item B<Locale::Currency::rename_currency(CODE ,NEW_NAME [,CODESET])> =item B<Locale::Currency::add_currency(CODE ,NAME [,CODESET])> =item B<Locale::Currency::delete_currency(CODE [,CODESET])> =item B<Locale::Currency::add_currency_alias(NAME ,NEW_NAME)> =item B<Locale::Currency::delete_currency_alias(NAME)> =item B<Locale::Currency::rename_currency_code(CODE ,NEW_CODE [,CODESET])> =item B<Locale::Currency::add_currency_code_alias(CODE ,NEW_CODE [,CODESET])> =item B<Locale::Currency::delete_currency_code_alias( CODE [,CODESET])> These routines are all documented in the L<Locale::Codes::API> man page. =back =head1 SEE ALSO =over 4 =item L<Locale::Codes> The Locale-Codes distribution. =item L<Locale::Codes::API> The list of functions supported by this module. =item L<http://www.iso.org/iso/support/currency_codes_list-1.htm> The ISO 4217 data. =back =head1 AUTHOR See Locale::Codes for full author history. Currently maintained by Sullivan Beck (sbeck@cpan.org). =head1 COPYRIGHT Copyright (c) 1997-2001 Canon Research Centre Europe (CRE). Copyright (c) 2001 Michael Hennecke Copyright (c) 2001-2010 Neil Bowers Copyright (c) 2010-2016 Sullivan Beck This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
mgood7123/UPM
perl-5.26.1/perl5.26.1/lib/5.26.1/Locale/Currency.pod
Perl
gpl-3.0
3,059
/// Copyright (c) 2008-2021 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/qvm/gen/vec_mat_operations2.hpp>
rneiss/PocketTorah
ios/Pods/Flipper-Boost-iOSX/boost/qvm/vec_mat_operations2.hpp
C++
gpl-3.0
276
--------------------------------------------- -- Double Kick -- -- Description: Deals damage to a single target. Additional effect: Stun -- Type: Physical -- Utsusemi/Blink absorb: 1 shadow -- Range: Melee -- Notes: Stun may or may not take effect. --------------------------------------------- require("/scripts/globals/settings"); require("/scripts/globals/status"); require("/scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local numhits = 1; local accmod = 1; local dmgmod = 2.8; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,info.hitslanded); target:delHP(dmg); local typeEffect = EFFECT_STUN; MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, 4); return dmg; end;
b03605079/darkstar
scripts/globals/mobskills/Double_Kick.lua
Lua
gpl-3.0
1,008
"use strict"; tutao.provide('tutao.entity.base.PersistenceResourcePostReturn'); /** * @constructor * @param {Object=} data The json data to store in this entity. */ tutao.entity.base.PersistenceResourcePostReturn = function(data) { if (data) { this.updateData(data); } else { this.__format = "0"; this._generatedId = null; this._permissionListId = null; } this._entityHelper = new tutao.entity.EntityHelper(this); this.prototype = tutao.entity.base.PersistenceResourcePostReturn.prototype; }; /** * Updates the data of this entity. * @param {Object=} data The json data to store in this entity. */ tutao.entity.base.PersistenceResourcePostReturn.prototype.updateData = function(data) { this.__format = data._format; this._generatedId = data.generatedId; this._permissionListId = data.permissionListId; }; /** * The version of the model this type belongs to. * @const */ tutao.entity.base.PersistenceResourcePostReturn.MODEL_VERSION = '1'; /** * The encrypted flag. * @const */ tutao.entity.base.PersistenceResourcePostReturn.prototype.ENCRYPTED = false; /** * Provides the data of this instances as an object that can be converted to json. * @return {Object} The json object. */ tutao.entity.base.PersistenceResourcePostReturn.prototype.toJsonData = function() { return { _format: this.__format, generatedId: this._generatedId, permissionListId: this._permissionListId }; }; /** * The id of the PersistenceResourcePostReturn type. */ tutao.entity.base.PersistenceResourcePostReturn.prototype.TYPE_ID = 0; /** * The id of the generatedId attribute. */ tutao.entity.base.PersistenceResourcePostReturn.prototype.GENERATEDID_ATTRIBUTE_ID = 2; /** * The id of the permissionListId attribute. */ tutao.entity.base.PersistenceResourcePostReturn.prototype.PERMISSIONLISTID_ATTRIBUTE_ID = 3; /** * Sets the format of this PersistenceResourcePostReturn. * @param {string} format The format of this PersistenceResourcePostReturn. */ tutao.entity.base.PersistenceResourcePostReturn.prototype.setFormat = function(format) { this.__format = format; return this; }; /** * Provides the format of this PersistenceResourcePostReturn. * @return {string} The format of this PersistenceResourcePostReturn. */ tutao.entity.base.PersistenceResourcePostReturn.prototype.getFormat = function() { return this.__format; }; /** * Sets the generatedId of this PersistenceResourcePostReturn. * @param {string} generatedId The generatedId of this PersistenceResourcePostReturn. */ tutao.entity.base.PersistenceResourcePostReturn.prototype.setGeneratedId = function(generatedId) { this._generatedId = generatedId; return this; }; /** * Provides the generatedId of this PersistenceResourcePostReturn. * @return {string} The generatedId of this PersistenceResourcePostReturn. */ tutao.entity.base.PersistenceResourcePostReturn.prototype.getGeneratedId = function() { return this._generatedId; }; /** * Sets the permissionListId of this PersistenceResourcePostReturn. * @param {string} permissionListId The permissionListId of this PersistenceResourcePostReturn. */ tutao.entity.base.PersistenceResourcePostReturn.prototype.setPermissionListId = function(permissionListId) { this._permissionListId = permissionListId; return this; }; /** * Provides the permissionListId of this PersistenceResourcePostReturn. * @return {string} The permissionListId of this PersistenceResourcePostReturn. */ tutao.entity.base.PersistenceResourcePostReturn.prototype.getPermissionListId = function() { return this._permissionListId; }; /** * Provides the entity helper of this entity. * @return {tutao.entity.EntityHelper} The entity helper. */ tutao.entity.base.PersistenceResourcePostReturn.prototype.getEntityHelper = function() { return this._entityHelper; };
msoftware/tutanota-1
web/js/generated/entity/base/PersistenceResourcePostReturn.js
JavaScript
gpl-3.0
3,838
/* * Minecraft Forge * Copyright (c) 2016. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation version 2.1 * of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package net.minecraftforge.event.terraingen; import java.util.Random; import net.minecraft.block.BlockSapling; import net.minecraft.block.state.IBlockState; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.eventhandler.Cancelable; import net.minecraftforge.fml.common.eventhandler.Event.HasResult; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.event.world.WorldEvent; /** * SaplingGrowTreeEvent is fired when a sapling grows into a tree.<br> * This event is fired during sapling growth in * {@link BlockSapling#generateTree(World, BlockPos, IBlockState, Random)}.<br> * <br> * {@link #pos} contains the coordinates of the growing sapling. <br> * {@link #rand} contains an instance of Random for use. <br> * <br> * This event is not {@link Cancelable}.<br> * <br> * This event has a result. {@link HasResult} <br> * This result determines if the sapling is allowed to grow. <br> * <br> * This event is fired on the {@link MinecraftForge#TERRAIN_GEN_BUS}.<br> **/ @HasResult public class SaplingGrowTreeEvent extends WorldEvent { private final BlockPos pos; private final Random rand; public SaplingGrowTreeEvent(World world, Random rand, BlockPos pos) { super(world); this.rand = rand; this.pos = pos; } public BlockPos getPos() { return pos; } public Random getRand() { return rand; } }
Severed-Infinity/technium
build/tmp/recompileMc/sources/net/minecraftforge/event/terraingen/SaplingGrowTreeEvent.java
Java
gpl-3.0
2,229
# -*- coding: utf-8 -*- # Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.utils import flt, add_months, cint, nowdate, getdate from frappe.model.document import Document from erpnext.accounts.doctype.purchase_invoice.purchase_invoice import get_fixed_asset_account from erpnext.accounts.doctype.asset.depreciation \ import get_disposal_account_and_cost_center, get_depreciation_accounts class Asset(Document): def validate(self): self.status = self.get_status() self.validate_item() self.set_missing_values() self.validate_asset_values() self.make_depreciation_schedule() self.set_accumulated_depreciation() if self.get("schedules"): self.validate_expected_value_after_useful_life() # Validate depreciation related accounts get_depreciation_accounts(self) def on_submit(self): self.set_status() def on_cancel(self): self.validate_cancellation() self.delete_depreciation_entries() self.set_status() def validate_item(self): item = frappe.db.get_value("Item", self.item_code, ["is_fixed_asset", "is_stock_item", "disabled"], as_dict=1) if not item: frappe.throw(_("Item {0} does not exist").format(self.item_code)) elif item.disabled: frappe.throw(_("Item {0} has been disabled").format(self.item_code)) elif not item.is_fixed_asset: frappe.throw(_("Item {0} must be a Fixed Asset Item").format(self.item_code)) elif item.is_stock_item: frappe.throw(_("Item {0} must be a non-stock item").format(self.item_code)) def set_missing_values(self): if self.item_code: item_details = get_item_details(self.item_code) for field, value in item_details.items(): if not self.get(field): self.set(field, value) self.value_after_depreciation = (flt(self.gross_purchase_amount) - flt(self.opening_accumulated_depreciation)) def validate_asset_values(self): if flt(self.expected_value_after_useful_life) >= flt(self.gross_purchase_amount): frappe.throw(_("Expected Value After Useful Life must be less than Gross Purchase Amount")) if not flt(self.gross_purchase_amount): frappe.throw(_("Gross Purchase Amount is mandatory"), frappe.MandatoryError) if not self.is_existing_asset: self.opening_accumulated_depreciation = 0 self.number_of_depreciations_booked = 0 if not self.next_depreciation_date: frappe.throw(_("Next Depreciation Date is mandatory for new asset")) else: depreciable_amount = flt(self.gross_purchase_amount) - flt(self.expected_value_after_useful_life) if flt(self.opening_accumulated_depreciation) > depreciable_amount: frappe.throw(_("Opening Accumulated Depreciation must be less than equal to {0}") .format(depreciable_amount)) if self.opening_accumulated_depreciation: if not self.number_of_depreciations_booked: frappe.throw(_("Please set Number of Depreciations Booked")) else: self.number_of_depreciations_booked = 0 if cint(self.number_of_depreciations_booked) > cint(self.total_number_of_depreciations): frappe.throw(_("Number of Depreciations Booked cannot be greater than Total Number of Depreciations")) if self.next_depreciation_date and getdate(self.next_depreciation_date) < getdate(nowdate()): frappe.msgprint(_("Next Depreciation Date is entered as past date"), title=_('Warning'), indicator='red') if self.next_depreciation_date and getdate(self.next_depreciation_date) < getdate(self.purchase_date): frappe.throw(_("Next Depreciation Date cannot be before Purchase Date")) if (flt(self.value_after_depreciation) > flt(self.expected_value_after_useful_life) and not self.next_depreciation_date): frappe.throw(_("Please set Next Depreciation Date")) def make_depreciation_schedule(self): if self.depreciation_method != 'Manual': self.schedules = [] if not self.get("schedules") and self.next_depreciation_date: value_after_depreciation = flt(self.value_after_depreciation) number_of_pending_depreciations = cint(self.total_number_of_depreciations) - \ cint(self.number_of_depreciations_booked) if number_of_pending_depreciations: for n in xrange(number_of_pending_depreciations): schedule_date = add_months(self.next_depreciation_date, n * cint(self.frequency_of_depreciation)) depreciation_amount = self.get_depreciation_amount(value_after_depreciation) value_after_depreciation -= flt(depreciation_amount) self.append("schedules", { "schedule_date": schedule_date, "depreciation_amount": depreciation_amount }) def set_accumulated_depreciation(self): accumulated_depreciation = flt(self.opening_accumulated_depreciation) value_after_depreciation = flt(self.value_after_depreciation) for i, d in enumerate(self.get("schedules")): depreciation_amount = flt(d.depreciation_amount, d.precision("depreciation_amount")) value_after_depreciation -= flt(depreciation_amount) if i==len(self.get("schedules"))-1 and self.depreciation_method == "Straight Line": depreciation_amount += flt(value_after_depreciation - flt(self.expected_value_after_useful_life), d.precision("depreciation_amount")) d.depreciation_amount = depreciation_amount accumulated_depreciation += d.depreciation_amount d.accumulated_depreciation_amount = flt(accumulated_depreciation, d.precision("accumulated_depreciation_amount")) def get_depreciation_amount(self, depreciable_value): if self.depreciation_method in ("Straight Line", "Manual"): depreciation_amount = (flt(self.value_after_depreciation) - flt(self.expected_value_after_useful_life)) / (cint(self.total_number_of_depreciations) - cint(self.number_of_depreciations_booked)) else: factor = 200.0 / self.total_number_of_depreciations depreciation_amount = flt(depreciable_value * factor / 100, 0) value_after_depreciation = flt(depreciable_value) - depreciation_amount if value_after_depreciation < flt(self.expected_value_after_useful_life): depreciation_amount = flt(depreciable_value) - flt(self.expected_value_after_useful_life) return depreciation_amount def validate_expected_value_after_useful_life(self): accumulated_depreciation_after_full_schedule = \ max([d.accumulated_depreciation_amount for d in self.get("schedules")]) asset_value_after_full_schedule = (flt(self.gross_purchase_amount) - flt(accumulated_depreciation_after_full_schedule)) if self.expected_value_after_useful_life < asset_value_after_full_schedule: frappe.throw(_("Expected value after useful life must be greater than or equal to {0}") .format(asset_value_after_full_schedule)) def validate_cancellation(self): if self.status not in ("Submitted", "Partially Depreciated", "Fully Depreciated"): frappe.throw(_("Asset cannot be cancelled, as it is already {0}").format(self.status)) if self.purchase_invoice: frappe.throw(_("Please cancel Purchase Invoice {0} first").format(self.purchase_invoice)) def delete_depreciation_entries(self): for d in self.get("schedules"): if d.journal_entry: frappe.get_doc("Journal Entry", d.journal_entry).cancel() d.db_set("journal_entry", None) self.db_set("value_after_depreciation", (flt(self.gross_purchase_amount) - flt(self.opening_accumulated_depreciation))) def set_status(self, status=None): '''Get and update status''' if not status: status = self.get_status() self.db_set("status", status) def get_status(self): '''Returns status based on whether it is draft, submitted, scrapped or depreciated''' if self.docstatus == 0: status = "Draft" elif self.docstatus == 1: status = "Submitted" if self.journal_entry_for_scrap: status = "Scrapped" elif flt(self.value_after_depreciation) <= flt(self.expected_value_after_useful_life): status = "Fully Depreciated" elif flt(self.value_after_depreciation) < flt(self.gross_purchase_amount): status = 'Partially Depreciated' elif self.docstatus == 2: status = "Cancelled" return status @frappe.whitelist() def make_purchase_invoice(asset, item_code, gross_purchase_amount, company, posting_date): pi = frappe.new_doc("Purchase Invoice") pi.company = company pi.currency = frappe.db.get_value("Company", company, "default_currency") pi.set_posting_time = 1 pi.posting_date = posting_date pi.append("items", { "item_code": item_code, "is_fixed_asset": 1, "asset": asset, "expense_account": get_fixed_asset_account(asset), "qty": 1, "price_list_rate": gross_purchase_amount, "rate": gross_purchase_amount }) pi.set_missing_values() return pi @frappe.whitelist() def make_sales_invoice(asset, item_code, company): si = frappe.new_doc("Sales Invoice") si.company = company si.currency = frappe.db.get_value("Company", company, "default_currency") disposal_account, depreciation_cost_center = get_disposal_account_and_cost_center(company) si.append("items", { "item_code": item_code, "is_fixed_asset": 1, "asset": asset, "income_account": disposal_account, "cost_center": depreciation_cost_center, "qty": 1 }) si.set_missing_values() return si @frappe.whitelist() def transfer_asset(args): import json args = json.loads(args) movement_entry = frappe.new_doc("Asset Movement") movement_entry.update(args) movement_entry.insert() movement_entry.submit() frappe.db.commit() frappe.msgprint(_("Asset Movement record {0} created").format("<a href='#Form/Asset Movement/{0}'>{0}</a>".format(movement_entry.name))) @frappe.whitelist() def get_item_details(item_code): asset_category = frappe.db.get_value("Item", item_code, "asset_category") if not asset_category: frappe.throw(_("Please enter Asset Category in Item {0}").format(item_code)) ret = frappe.db.get_value("Asset Category", asset_category, ["depreciation_method", "total_number_of_depreciations", "frequency_of_depreciation"], as_dict=1) ret.update({ "asset_category": asset_category }) return ret
emakis/erpnext
erpnext/accounts/doctype/asset/asset.py
Python
gpl-3.0
10,030
/* Calculate the size of physical memory. Copyright (C) 2000-2001, 2003, 2005-2006, 2009-2013 Free Software Foundation, 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 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/>. */ /* Written by Paul Eggert. */ #include <config.h> #include "physmem.h" #include <unistd.h> #if HAVE_SYS_PSTAT_H # include <sys/pstat.h> #endif #if HAVE_SYS_SYSMP_H # include <sys/sysmp.h> #endif #if HAVE_SYS_SYSINFO_H && HAVE_MACHINE_HAL_SYSINFO_H # include <sys/sysinfo.h> # include <machine/hal_sysinfo.h> #endif #if HAVE_SYS_TABLE_H # include <sys/table.h> #endif #include <sys/types.h> #if HAVE_SYS_PARAM_H # include <sys/param.h> #endif #if HAVE_SYS_SYSCTL_H # include <sys/sysctl.h> #endif #if HAVE_SYS_SYSTEMCFG_H # include <sys/systemcfg.h> #endif #ifdef _WIN32 # define WIN32_LEAN_AND_MEAN # include <windows.h> /* MEMORYSTATUSEX is missing from older windows headers, so define a local replacement. */ typedef struct { DWORD dwLength; DWORD dwMemoryLoad; DWORDLONG ullTotalPhys; DWORDLONG ullAvailPhys; DWORDLONG ullTotalPageFile; DWORDLONG ullAvailPageFile; DWORDLONG ullTotalVirtual; DWORDLONG ullAvailVirtual; DWORDLONG ullAvailExtendedVirtual; } lMEMORYSTATUSEX; typedef WINBOOL (WINAPI *PFN_MS_EX) (lMEMORYSTATUSEX*); #endif #define ARRAY_SIZE(a) (sizeof (a) / sizeof ((a)[0])) /* Return the total amount of physical memory. */ double physmem_total (void) { #if defined _SC_PHYS_PAGES && defined _SC_PAGESIZE { /* This works on linux-gnu, solaris2 and cygwin. */ double pages = sysconf (_SC_PHYS_PAGES); double pagesize = sysconf (_SC_PAGESIZE); if (0 <= pages && 0 <= pagesize) return pages * pagesize; } #endif #if HAVE_PSTAT_GETSTATIC { /* This works on hpux11. */ struct pst_static pss; if (0 <= pstat_getstatic (&pss, sizeof pss, 1, 0)) { double pages = pss.physical_memory; double pagesize = pss.page_size; if (0 <= pages && 0 <= pagesize) return pages * pagesize; } } #endif #if HAVE_SYSMP && defined MP_SAGET && defined MPSA_RMINFO && defined _SC_PAGESIZE { /* This works on irix6. */ struct rminfo realmem; if (sysmp (MP_SAGET, MPSA_RMINFO, &realmem, sizeof realmem) == 0) { double pagesize = sysconf (_SC_PAGESIZE); double pages = realmem.physmem; if (0 <= pages && 0 <= pagesize) return pages * pagesize; } } #endif #if HAVE_GETSYSINFO && defined GSI_PHYSMEM { /* This works on Tru64 UNIX V4/5. */ int physmem; if (getsysinfo (GSI_PHYSMEM, (caddr_t) &physmem, sizeof (physmem), NULL, NULL, NULL) == 1) { double kbytes = physmem; if (0 <= kbytes) return kbytes * 1024.0; } } #endif #if HAVE_SYSCTL && defined HW_PHYSMEM { /* This works on *bsd and darwin. */ unsigned int physmem; size_t len = sizeof physmem; static int mib[2] = { CTL_HW, HW_PHYSMEM }; if (sysctl (mib, ARRAY_SIZE (mib), &physmem, &len, NULL, 0) == 0 && len == sizeof (physmem)) return (double) physmem; } #endif #if HAVE__SYSTEM_CONFIGURATION /* This works on AIX. */ return _system_configuration.physmem; #endif #if defined _WIN32 { /* this works on windows */ PFN_MS_EX pfnex; HMODULE h = GetModuleHandle ("kernel32.dll"); if (!h) return 0.0; /* Use GlobalMemoryStatusEx if available. */ if ((pfnex = (PFN_MS_EX) GetProcAddress (h, "GlobalMemoryStatusEx"))) { lMEMORYSTATUSEX lms_ex; lms_ex.dwLength = sizeof lms_ex; if (!pfnex (&lms_ex)) return 0.0; return (double) lms_ex.ullTotalPhys; } /* Fall back to GlobalMemoryStatus which is always available. but returns wrong results for physical memory > 4GB. */ else { MEMORYSTATUS ms; GlobalMemoryStatus (&ms); return (double) ms.dwTotalPhys; } } #endif /* Guess 64 MB. It's probably an older host, so guess small. */ return 64 * 1024 * 1024; } /* Return the amount of physical memory available. */ double physmem_available (void) { #if defined _SC_AVPHYS_PAGES && defined _SC_PAGESIZE { /* This works on linux-gnu, solaris2 and cygwin. */ double pages = sysconf (_SC_AVPHYS_PAGES); double pagesize = sysconf (_SC_PAGESIZE); if (0 <= pages && 0 <= pagesize) return pages * pagesize; } #endif #if HAVE_PSTAT_GETSTATIC && HAVE_PSTAT_GETDYNAMIC { /* This works on hpux11. */ struct pst_static pss; struct pst_dynamic psd; if (0 <= pstat_getstatic (&pss, sizeof pss, 1, 0) && 0 <= pstat_getdynamic (&psd, sizeof psd, 1, 0)) { double pages = psd.psd_free; double pagesize = pss.page_size; if (0 <= pages && 0 <= pagesize) return pages * pagesize; } } #endif #if HAVE_SYSMP && defined MP_SAGET && defined MPSA_RMINFO && defined _SC_PAGESIZE { /* This works on irix6. */ struct rminfo realmem; if (sysmp (MP_SAGET, MPSA_RMINFO, &realmem, sizeof realmem) == 0) { double pagesize = sysconf (_SC_PAGESIZE); double pages = realmem.availrmem; if (0 <= pages && 0 <= pagesize) return pages * pagesize; } } #endif #if HAVE_TABLE && defined TBL_VMSTATS { /* This works on Tru64 UNIX V4/5. */ struct tbl_vmstats vmstats; if (table (TBL_VMSTATS, 0, &vmstats, 1, sizeof (vmstats)) == 1) { double pages = vmstats.free_count; double pagesize = vmstats.pagesize; if (0 <= pages && 0 <= pagesize) return pages * pagesize; } } #endif #if HAVE_SYSCTL && defined HW_USERMEM { /* This works on *bsd and darwin. */ unsigned int usermem; size_t len = sizeof usermem; static int mib[2] = { CTL_HW, HW_USERMEM }; if (sysctl (mib, ARRAY_SIZE (mib), &usermem, &len, NULL, 0) == 0 && len == sizeof (usermem)) return (double) usermem; } #endif #if defined _WIN32 { /* this works on windows */ PFN_MS_EX pfnex; HMODULE h = GetModuleHandle ("kernel32.dll"); if (!h) return 0.0; /* Use GlobalMemoryStatusEx if available. */ if ((pfnex = (PFN_MS_EX) GetProcAddress (h, "GlobalMemoryStatusEx"))) { lMEMORYSTATUSEX lms_ex; lms_ex.dwLength = sizeof lms_ex; if (!pfnex (&lms_ex)) return 0.0; return (double) lms_ex.ullAvailPhys; } /* Fall back to GlobalMemoryStatus which is always available. but returns wrong results for physical memory > 4GB */ else { MEMORYSTATUS ms; GlobalMemoryStatus (&ms); return (double) ms.dwAvailPhys; } } #endif /* Guess 25% of physical memory. */ return physmem_total () / 4; } #if DEBUG # include <stdio.h> # include <stdlib.h> int main (void) { printf ("%12.f %12.f\n", physmem_total (), physmem_available ()); exit (0); } #endif /* DEBUG */ /* Local Variables: compile-command: "gcc -DDEBUG -g -O -Wall -W physmem.c" End: */
geminy/aidear
oss/shell/coreutils/coreutils-8.21/lib/physmem.c
C
gpl-3.0
7,604
# encoding: utf-8 class Laby::Content::Base < Cms::Content end
tao-k/zomeki
app/models/laby/content/base.rb
Ruby
gpl-3.0
64
/* * Copyright (C) 1997-2013 JDERobot Developers 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 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 Library 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/>. * * Authors : Borja Menéndez <borjamonserrano@gmail.com> * */ #ifndef IMPORTDIALOG_H #define IMPORTDIALOG_H #include "../guisubautomata.h" // Definition of this class class ImportDialog { public: // Constructor ImportDialog ( GuiSubautomata* gsubautomata ); // Destructor virtual ~ImportDialog (); // Popup initializer void init (); protected: // Data structure GuiSubautomata* gsubautomata; Gtk::Dialog* dialog; Gtk::Button* button_accept; Gtk::Button* button_cancel; Gtk::CheckButton *checkbutton_laser, *checkbutton_sonar, *checkbutton_camera; Gtk::CheckButton *checkbutton_pose3dencoders, *checkbutton_pose3dmotors; // Private methods void on_button_accept (); void on_button_cancel (); bool on_key_released ( GdkEventKey* event ); }; #endif // IMPORTDIALOG_H
ojgarciab/JdeRobot
src/stable/tools/visualHFSM/popups/importdialog.h
C
gpl-3.0
1,517
<?php // autoload.php @generated by Composer require_once __DIR__ . '/composer' . '/autoload_real.php'; return ComposerAutoloaderInit8a8b7c48f14663b8905d3aebf4678cc4::getLoader();
oliverds/openclassifieds2
oc/vendor/pusher/autoload.php
PHP
gpl-3.0
183
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2017, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # This is a virtual module that is entirely implemented as an action plugin and runs on the controller from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = r''' --- module: fetch short_description: Fetch files from remote nodes description: - This module works like M(copy), but in reverse. - It is used for fetching files from remote machines and storing them locally in a file tree, organized by hostname. - Files that already exist at I(dest) will be overwritten if they are different than the I(src). - This module is also supported for Windows targets. version_added: '0.2' options: src: description: - The file on the remote system to fetch. - This I(must) be a file, not a directory. - Recursive fetching may be supported in a later release. required: yes dest: description: - A directory to save the file into. - For example, if the I(dest) directory is C(/backup) a I(src) file named C(/etc/profile) on host C(host.example.com), would be saved into C(/backup/host.example.com/etc/profile). The host name is based on the inventory name. required: yes fail_on_missing: version_added: '1.1' description: - When set to C(yes), the task will fail if the remote file cannot be read for any reason. - Prior to Ansible 2.5, setting this would only fail if the source file was missing. - The default was changed to C(yes) in Ansible 2.5. type: bool default: yes validate_checksum: version_added: '1.4' description: - Verify that the source and destination checksums match after the files are fetched. type: bool default: yes flat: version_added: '1.2' description: - Allows you to override the default behavior of appending hostname/path/to/file to the destination. - If C(dest) ends with '/', it will use the basename of the source file, similar to the copy module. - This can be useful if working with a single host, or if retrieving files that are uniquely named per host. - If using multiple hosts with the same filename, the file will be overwritten for each host. type: bool default: no notes: - When running fetch with C(become), the M(slurp) module will also be used to fetch the contents of the file for determining the remote checksum. This effectively doubles the transfer size, and depending on the file size can consume all available memory on the remote or local hosts causing a C(MemoryError). Due to this it is advisable to run this module without C(become) whenever possible. - Prior to Ansible 2.5 this module would not fail if reading the remote file was impossible unless C(fail_on_missing) was set. - In Ansible 2.5 or later, playbook authors are encouraged to use C(fail_when) or C(ignore_errors) to get this ability. They may also explicitly set C(fail_on_missing) to C(no) to get the non-failing behaviour. - This module is also supported for Windows targets. seealso: - module: copy - module: slurp author: - Ansible Core Team - Michael DeHaan ''' EXAMPLES = r''' - name: Store file into /tmp/fetched/host.example.com/tmp/somefile fetch: src: /tmp/somefile dest: /tmp/fetched - name: Specifying a path directly fetch: src: /tmp/somefile dest: /tmp/prefix-{{ inventory_hostname }} flat: yes - name: Specifying a destination path fetch: src: /tmp/uniquefile dest: /tmp/special/ flat: yes - name: Storing in a path relative to the playbook fetch: src: /tmp/uniquefile dest: special/prefix-{{ inventory_hostname }} flat: yes '''
indrajitr/ansible
lib/ansible/modules/fetch.py
Python
gpl-3.0
3,790
/* Provide a working getlogin for systems which lack it. Copyright (C) 2010-2013 Free Software Foundation, 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 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/>. */ /* Written by Bruno Haible, 2010. */ #include <config.h> /* Specification. */ #include <unistd.h> #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__ # define WIN32_LEAN_AND_MEAN # include <windows.h> #endif char * getlogin (void) { #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__ static char login_name[1024]; DWORD sz = sizeof (login_name); if (GetUserName (login_name, &sz)) return login_name; #endif return NULL; }
geminy/aidear
oss/shell/coreutils/coreutils-8.21/lib/getlogin.c
C
gpl-3.0
1,234
// |jit-test| error: TestComplete // onPop can change a normal return into a throw. load(libdir + "asserts.js"); var g = newGlobal('new-compartment'); var dbg = new Debugger(g); function test(type, provocation) { var log; // Help people figure out which 'test' call failed. print("type: " + uneval(type)); print("provocation: " + uneval(provocation)); dbg.onDebuggerStatement = function handleDebuggerStatement(f) { log += 'd'; }; dbg.onEnterFrame = function handleEnterFrame(f) { log += '('; assertEq(f.type, type); f.onPop = function handlePop(c) { log += ')'; assertEq(c.return, 'compliment'); return { throw: 'snow' }; }; }; log = ''; assertThrowsValue(provocation, 'snow'); assertEq(log, "(d)"); print(); } g.eval("function f() { debugger; return 'compliment'; }"); test("call", g.f); test("call", function () { return new g.f; }); test("eval", function () { return g.eval("debugger; \'compliment\';"); }); test("global", function () { return g.evaluate("debugger; \'compliment\';"); }); throw 'TestComplete';
SlateScience/MozillaJS
js/src/jit-test/tests/debug/Frame-onPop-return-throw.js
JavaScript
mpl-2.0
1,154
<!DOCTYPE html> <!-- Distributed under both the W3C Test Suite License [1] and the W3C 3-clause BSD License [2]. To contribute to a W3C Test Suite, see the policies and contribution forms [3]. [1] http://www.w3.org/Consortium/Legal/2008/04-testsuite-license [2] http://www.w3.org/Consortium/Legal/2008/03-bsd-license [3] http://www.w3.org/2004/10/27-testcases --> <html> <head> <title>Shadow DOM Test: A_05_01_01</title> <link rel="author" title="Sergey G. Grekhov" href="mailto:sgrekhov@unipro.ru"> <link rel="help" href="http://www.w3.org/TR/2013/WD-shadow-dom-20130514/#event-retargeting"> <meta name="assert" content="Event Retargeting:test that event.target is retargeted when event crosses shadow boundary and vice versa"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="../../../../html/resources/common.js"></script> </head> <body> <div id="log"></div> <script> var A_05_01_01_T1 = async_test('A_05_01_01_T1'); A_05_01_01_T1.step(function () { var iframe = document.createElement('iframe'); iframe.src = '../../resources/blank.html'; document.body.appendChild(iframe); iframe.onload = A_05_01_01_T1.step_func(function () { try { var d = iframe.contentDocument; var div = d.createElement('div'); d.body.appendChild(div); var s = div.createShadowRoot(); var div2 = d.createElement('div'); s.appendChild(div2); var inp = d.createElement('input'); inp.setAttribute('type', 'text'); inp.setAttribute('id', 'inpid'); div2.appendChild(inp); div2.addEventListener('click', A_05_01_01_T1.step_func(function (event) { assert_equals(event.target.tagName, 'INPUT', 'Information about target of the event that ' + 'doesn\'t cross the shadow boundaries should not be adjusted'); }), false); var event = d.createEvent('HTMLEvents'); event.initEvent ("click", true, false); inp.dispatchEvent(event); } finally { iframe.parentNode.removeChild(iframe); } A_05_01_01_T1.done(); }); }); var A_05_01_01_T2 = async_test('A_05_01_01_T2'); A_05_01_01_T2.step(function () { var iframe = document.createElement('iframe'); iframe.src = '../../resources/blank.html'; document.body.appendChild(iframe); iframe.onload = A_05_01_01_T2.step_func(function () { try { var d = iframe.contentDocument; var div = d.createElement('div'); d.body.appendChild(div); var s = div.createShadowRoot(); var div2 = d.createElement('div'); s.appendChild(div2); var inp = d.createElement('input'); inp.setAttribute('type', 'text'); inp.setAttribute('id', 'inpid'); div2.appendChild(inp); div.addEventListener('click', A_05_01_01_T2.step_func(function (event) { assert_equals(event.target.tagName, 'DIV', 'Information about event target crossing ' + 'the shadow boundaries should be adjusted'); }), false); var event = d.createEvent('HTMLEvents'); event.initEvent ("click", true, false); inp.dispatchEvent(event); } finally { iframe.parentNode.removeChild(iframe); } A_05_01_01_T2.done(); }); }); </script> </body> </html>
Shiroy/servo
tests/wpt/web-platform-tests/shadow-dom/untriaged/events/event-retargeting/test-001.html
HTML
mpl-2.0
3,365
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Memory profiling functions. use crate::time::duration_from_seconds; use ipc_channel::ipc::{self, IpcReceiver}; use ipc_channel::router::ROUTER; use profile_traits::mem::ReportsChan; use profile_traits::mem::{ProfilerChan, ProfilerMsg, ReportKind, Reporter, ReporterRequest}; use std::borrow::ToOwned; use std::cmp::Ordering; use std::collections::HashMap; use std::thread; use std::time::Instant; pub struct Profiler { /// The port through which messages are received. pub port: IpcReceiver<ProfilerMsg>, /// Registered memory reporters. reporters: HashMap<String, Reporter>, /// Instant at which this profiler was created. created: Instant, } const JEMALLOC_HEAP_ALLOCATED_STR: &'static str = "jemalloc-heap-allocated"; const SYSTEM_HEAP_ALLOCATED_STR: &'static str = "system-heap-allocated"; impl Profiler { pub fn create(period: Option<f64>) -> ProfilerChan { let (chan, port) = ipc::channel().unwrap(); // Create the timer thread if a period was provided. if let Some(period) = period { let chan = chan.clone(); thread::Builder::new() .name("Memory profiler timer".to_owned()) .spawn(move || loop { thread::sleep(duration_from_seconds(period)); if chan.send(ProfilerMsg::Print).is_err() { break; } }) .expect("Thread spawning failed"); } // Always spawn the memory profiler. If there is no timer thread it won't receive regular // `Print` events, but it will still receive the other events. thread::Builder::new() .name("Memory profiler".to_owned()) .spawn(move || { let mut mem_profiler = Profiler::new(port); mem_profiler.start(); }) .expect("Thread spawning failed"); let mem_profiler_chan = ProfilerChan(chan); // Register the system memory reporter, which will run on its own thread. It never needs to // be unregistered, because as long as the memory profiler is running the system memory // reporter can make measurements. let (system_reporter_sender, system_reporter_receiver) = ipc::channel().unwrap(); ROUTER.add_route( system_reporter_receiver.to_opaque(), Box::new(|message| { let request: ReporterRequest = message.to().unwrap(); system_reporter::collect_reports(request) }), ); mem_profiler_chan.send(ProfilerMsg::RegisterReporter( "system".to_owned(), Reporter(system_reporter_sender), )); mem_profiler_chan } pub fn new(port: IpcReceiver<ProfilerMsg>) -> Profiler { Profiler { port: port, reporters: HashMap::new(), created: Instant::now(), } } pub fn start(&mut self) { while let Ok(msg) = self.port.recv() { if !self.handle_msg(msg) { break; } } } fn handle_msg(&mut self, msg: ProfilerMsg) -> bool { match msg { ProfilerMsg::RegisterReporter(name, reporter) => { // Panic if it has already been registered. let name_clone = name.clone(); match self.reporters.insert(name, reporter) { None => true, Some(_) => panic!(format!( "RegisterReporter: '{}' name is already in use", name_clone )), } }, ProfilerMsg::UnregisterReporter(name) => { // Panic if it hasn't previously been registered. match self.reporters.remove(&name) { Some(_) => true, None => panic!(format!("UnregisterReporter: '{}' name is unknown", &name)), } }, ProfilerMsg::Print => { self.handle_print_msg(); true }, ProfilerMsg::Exit => false, } } fn handle_print_msg(&self) { let elapsed = self.created.elapsed(); println!("Begin memory reports {}", elapsed.as_secs()); println!("|"); // Collect reports from memory reporters. // // This serializes the report-gathering. It might be worth creating a new scoped thread for // each reporter once we have enough of them. // // If anything goes wrong with a reporter, we just skip it. // // We also track the total memory reported on the jemalloc heap and the system heap, and // use that to compute the special "jemalloc-heap-unclassified" and // "system-heap-unclassified" values. let mut forest = ReportsForest::new(); let mut jemalloc_heap_reported_size = 0; let mut system_heap_reported_size = 0; let mut jemalloc_heap_allocated_size: Option<usize> = None; let mut system_heap_allocated_size: Option<usize> = None; for reporter in self.reporters.values() { let (chan, port) = ipc::channel().unwrap(); reporter.collect_reports(ReportsChan(chan)); if let Ok(mut reports) = port.recv() { for report in &mut reports { // Add "explicit" to the start of the path, when appropriate. match report.kind { ReportKind::ExplicitJemallocHeapSize | ReportKind::ExplicitSystemHeapSize | ReportKind::ExplicitNonHeapSize | ReportKind::ExplicitUnknownLocationSize => { report.path.insert(0, String::from("explicit")) }, ReportKind::NonExplicitSize => {}, } // Update the reported fractions of the heaps, when appropriate. match report.kind { ReportKind::ExplicitJemallocHeapSize => { jemalloc_heap_reported_size += report.size }, ReportKind::ExplicitSystemHeapSize => { system_heap_reported_size += report.size }, _ => {}, } // Record total size of the heaps, when we see them. if report.path.len() == 1 { if report.path[0] == JEMALLOC_HEAP_ALLOCATED_STR { assert!(jemalloc_heap_allocated_size.is_none()); jemalloc_heap_allocated_size = Some(report.size); } else if report.path[0] == SYSTEM_HEAP_ALLOCATED_STR { assert!(system_heap_allocated_size.is_none()); system_heap_allocated_size = Some(report.size); } } // Insert the report. forest.insert(&report.path, report.size); } } } // Compute and insert the heap-unclassified values. if let Some(jemalloc_heap_allocated_size) = jemalloc_heap_allocated_size { forest.insert( &path!["explicit", "jemalloc-heap-unclassified"], jemalloc_heap_allocated_size - jemalloc_heap_reported_size, ); } if let Some(system_heap_allocated_size) = system_heap_allocated_size { forest.insert( &path!["explicit", "system-heap-unclassified"], system_heap_allocated_size - system_heap_reported_size, ); } forest.print(); println!("|"); println!("End memory reports"); println!(""); } } /// A collection of one or more reports with the same initial path segment. A ReportsTree /// containing a single node is described as "degenerate". struct ReportsTree { /// For leaf nodes, this is the sum of the sizes of all reports that mapped to this location. /// For interior nodes, this is the sum of the sizes of all its child nodes. size: usize, /// For leaf nodes, this is the count of all reports that mapped to this location. /// For interor nodes, this is always zero. count: u32, /// The segment from the report path that maps to this node. path_seg: String, /// Child nodes. children: Vec<ReportsTree>, } impl ReportsTree { fn new(path_seg: String) -> ReportsTree { ReportsTree { size: 0, count: 0, path_seg: path_seg, children: vec![], } } // Searches the tree's children for a path_seg match, and returns the index if there is a // match. fn find_child(&self, path_seg: &str) -> Option<usize> { for (i, child) in self.children.iter().enumerate() { if child.path_seg == *path_seg { return Some(i); } } None } // Insert the path and size into the tree, adding any nodes as necessary. fn insert(&mut self, path: &[String], size: usize) { let mut t: &mut ReportsTree = self; for path_seg in path { let i = match t.find_child(&path_seg) { Some(i) => i, None => { let new_t = ReportsTree::new(path_seg.clone()); t.children.push(new_t); t.children.len() - 1 }, }; let tmp = t; // this temporary is needed to satisfy the borrow checker t = &mut tmp.children[i]; } t.size += size; t.count += 1; } // Fill in sizes for interior nodes and sort sub-trees accordingly. Should only be done once // all the reports have been inserted. fn compute_interior_node_sizes_and_sort(&mut self) -> usize { if !self.children.is_empty() { // Interior node. Derive its size from its children. if self.size != 0 { // This will occur if e.g. we have paths ["a", "b"] and ["a", "b", "c"]. panic!("one report's path is a sub-path of another report's path"); } for child in &mut self.children { self.size += child.compute_interior_node_sizes_and_sort(); } // Now that child sizes have been computed, we can sort the children. self.children.sort_by(|t1, t2| t2.size.cmp(&t1.size)); } self.size } fn print(&self, depth: i32) { if !self.children.is_empty() { assert_eq!(self.count, 0); } let mut indent_str = String::new(); for _ in 0..depth { indent_str.push_str(" "); } let mebi = 1024f64 * 1024f64; let count_str = if self.count > 1 { format!(" [{}]", self.count) } else { "".to_owned() }; println!( "|{}{:8.2} MiB -- {}{}", indent_str, (self.size as f64) / mebi, self.path_seg, count_str ); for child in &self.children { child.print(depth + 1); } } } /// A collection of ReportsTrees. It represents the data from multiple memory reports in a form /// that's good to print. struct ReportsForest { trees: HashMap<String, ReportsTree>, } impl ReportsForest { fn new() -> ReportsForest { ReportsForest { trees: HashMap::new(), } } // Insert the path and size into the forest, adding any trees and nodes as necessary. fn insert(&mut self, path: &[String], size: usize) { let (head, tail) = path.split_first().unwrap(); // Get the right tree, creating it if necessary. if !self.trees.contains_key(head) { self.trees .insert(head.clone(), ReportsTree::new(head.clone())); } let t = self.trees.get_mut(head).unwrap(); // Use tail because the 0th path segment was used to find the right tree in the forest. t.insert(tail, size); } fn print(&mut self) { // Fill in sizes of interior nodes, and recursively sort the sub-trees. for (_, tree) in &mut self.trees { tree.compute_interior_node_sizes_and_sort(); } // Put the trees into a sorted vector. Primary sort: degenerate trees (those containing a // single node) come after non-degenerate trees. Secondary sort: alphabetical order of the // root node's path_seg. let mut v = vec![]; for (_, tree) in &self.trees { v.push(tree); } v.sort_by(|a, b| { if a.children.is_empty() && !b.children.is_empty() { Ordering::Greater } else if !a.children.is_empty() && b.children.is_empty() { Ordering::Less } else { a.path_seg.cmp(&b.path_seg) } }); // Print the forest. for tree in &v { tree.print(0); // Print a blank line after non-degenerate trees. if !tree.children.is_empty() { println!("|"); } } } } //--------------------------------------------------------------------------- mod system_reporter { use super::{JEMALLOC_HEAP_ALLOCATED_STR, SYSTEM_HEAP_ALLOCATED_STR}; #[cfg(target_os = "linux")] use libc::c_int; #[cfg(all(feature = "unstable", not(target_os = "windows")))] use libc::{c_void, size_t}; use profile_traits::mem::{Report, ReportKind, ReporterRequest}; #[cfg(all(feature = "unstable", not(target_os = "windows")))] use std::ffi::CString; #[cfg(all(feature = "unstable", not(target_os = "windows")))] use std::mem::size_of; #[cfg(all(feature = "unstable", not(target_os = "windows")))] use std::ptr::null_mut; #[cfg(target_os = "macos")] use task_info::task_basic_info::{resident_size, virtual_size}; /// Collects global measurements from the OS and heap allocators. pub fn collect_reports(request: ReporterRequest) { let mut reports = vec![]; { let mut report = |path, size| { if let Some(size) = size { reports.push(Report { path: path, kind: ReportKind::NonExplicitSize, size: size, }); } }; // Virtual and physical memory usage, as reported by the OS. report(path!["vsize"], vsize()); report(path!["resident"], resident()); // Memory segments, as reported by the OS. for seg in resident_segments() { report(path!["resident-according-to-smaps", seg.0], Some(seg.1)); } // Total number of bytes allocated by the application on the system // heap. report(path![SYSTEM_HEAP_ALLOCATED_STR], system_heap_allocated()); // The descriptions of the following jemalloc measurements are taken // directly from the jemalloc documentation. // "Total number of bytes allocated by the application." report( path![JEMALLOC_HEAP_ALLOCATED_STR], jemalloc_stat("stats.allocated"), ); // "Total number of bytes in active pages allocated by the application. // This is a multiple of the page size, and greater than or equal to // |stats.allocated|." report(path!["jemalloc-heap-active"], jemalloc_stat("stats.active")); // "Total number of bytes in chunks mapped on behalf of the application. // This is a multiple of the chunk size, and is at least as large as // |stats.active|. This does not include inactive chunks." report(path!["jemalloc-heap-mapped"], jemalloc_stat("stats.mapped")); } request.reports_channel.send(reports); } #[cfg(target_os = "linux")] extern "C" { fn mallinfo() -> struct_mallinfo; } #[cfg(target_os = "linux")] #[repr(C)] pub struct struct_mallinfo { arena: c_int, ordblks: c_int, smblks: c_int, hblks: c_int, hblkhd: c_int, usmblks: c_int, fsmblks: c_int, uordblks: c_int, fordblks: c_int, keepcost: c_int, } #[cfg(target_os = "linux")] fn system_heap_allocated() -> Option<usize> { let info: struct_mallinfo = unsafe { mallinfo() }; // The documentation in the glibc man page makes it sound like |uordblks| would suffice, // but that only gets the small allocations that are put in the brk heap. We need |hblkhd| // as well to get the larger allocations that are mmapped. // // These fields are unfortunately |int| and so can overflow (becoming negative) if memory // usage gets high enough. So don't report anything in that case. In the non-overflow case // we cast the two values to usize before adding them to make sure the sum also doesn't // overflow. if info.hblkhd < 0 || info.uordblks < 0 { None } else { Some(info.hblkhd as usize + info.uordblks as usize) } } #[cfg(not(target_os = "linux"))] fn system_heap_allocated() -> Option<usize> { None } #[cfg(all(feature = "unstable", not(target_os = "windows")))] use servo_allocator::jemalloc_sys::mallctl; #[cfg(all(feature = "unstable", not(target_os = "windows")))] fn jemalloc_stat(value_name: &str) -> Option<usize> { // Before we request the measurement of interest, we first send an "epoch" // request. Without that jemalloc gives cached statistics(!) which can be // highly inaccurate. let epoch_name = "epoch"; let epoch_c_name = CString::new(epoch_name).unwrap(); let mut epoch: u64 = 0; let epoch_ptr = &mut epoch as *mut _ as *mut c_void; let mut epoch_len = size_of::<u64>() as size_t; let value_c_name = CString::new(value_name).unwrap(); let mut value: size_t = 0; let value_ptr = &mut value as *mut _ as *mut c_void; let mut value_len = size_of::<size_t>() as size_t; // Using the same values for the `old` and `new` parameters is enough // to get the statistics updated. let rv = unsafe { mallctl( epoch_c_name.as_ptr(), epoch_ptr, &mut epoch_len, epoch_ptr, epoch_len, ) }; if rv != 0 { return None; } let rv = unsafe { mallctl( value_c_name.as_ptr(), value_ptr, &mut value_len, null_mut(), 0, ) }; if rv != 0 { return None; } Some(value as usize) } #[cfg(any(target_os = "windows", not(feature = "unstable")))] fn jemalloc_stat(_value_name: &str) -> Option<usize> { None } #[cfg(target_os = "linux")] fn page_size() -> usize { unsafe { ::libc::sysconf(::libc::_SC_PAGESIZE) as usize } } #[cfg(target_os = "linux")] fn proc_self_statm_field(field: usize) -> Option<usize> { use std::fs::File; use std::io::Read; let mut f = File::open("/proc/self/statm").ok()?; let mut contents = String::new(); f.read_to_string(&mut contents).ok()?; let s = contents.split_whitespace().nth(field)?; let npages = s.parse::<usize>().ok()?; Some(npages * page_size()) } #[cfg(target_os = "linux")] fn vsize() -> Option<usize> { proc_self_statm_field(0) } #[cfg(target_os = "linux")] fn resident() -> Option<usize> { proc_self_statm_field(1) } #[cfg(target_os = "macos")] fn vsize() -> Option<usize> { virtual_size() } #[cfg(target_os = "macos")] fn resident() -> Option<usize> { resident_size() } #[cfg(not(any(target_os = "linux", target_os = "macos")))] fn vsize() -> Option<usize> { None } #[cfg(not(any(target_os = "linux", target_os = "macos")))] fn resident() -> Option<usize> { None } #[cfg(target_os = "linux")] fn resident_segments() -> Vec<(String, usize)> { use regex::Regex; use std::collections::hash_map::Entry; use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader}; // The first line of an entry in /proc/<pid>/smaps looks just like an entry // in /proc/<pid>/maps: // // address perms offset dev inode pathname // 02366000-025d8000 rw-p 00000000 00:00 0 [heap] // // Each of the following lines contains a key and a value, separated // by ": ", where the key does not contain either of those characters. // For example: // // Rss: 132 kB let f = match File::open("/proc/self/smaps") { Ok(f) => BufReader::new(f), Err(_) => return vec![], }; let seg_re = Regex::new( r"^[:xdigit:]+-[:xdigit:]+ (....) [:xdigit:]+ [:xdigit:]+:[:xdigit:]+ \d+ +(.*)", ) .unwrap(); let rss_re = Regex::new(r"^Rss: +(\d+) kB").unwrap(); // We record each segment's resident size. let mut seg_map: HashMap<String, usize> = HashMap::new(); #[derive(PartialEq)] enum LookingFor { Segment, Rss, } let mut looking_for = LookingFor::Segment; let mut curr_seg_name = String::new(); // Parse the file. for line in f.lines() { let line = match line { Ok(line) => line, Err(_) => continue, }; if looking_for == LookingFor::Segment { // Look for a segment info line. let cap = match seg_re.captures(&line) { Some(cap) => cap, None => continue, }; let perms = cap.get(1).unwrap().as_str(); let pathname = cap.get(2).unwrap().as_str(); // Construct the segment name from its pathname and permissions. curr_seg_name.clear(); if pathname == "" || pathname.starts_with("[stack:") { // Anonymous memory. Entries marked with "[stack:nnn]" // look like thread stacks but they may include other // anonymous mappings, so we can't trust them and just // treat them as entirely anonymous. curr_seg_name.push_str("anonymous"); } else { curr_seg_name.push_str(pathname); } curr_seg_name.push_str(" ("); curr_seg_name.push_str(perms); curr_seg_name.push_str(")"); looking_for = LookingFor::Rss; } else { // Look for an "Rss:" line. let cap = match rss_re.captures(&line) { Some(cap) => cap, None => continue, }; let rss = cap.get(1).unwrap().as_str().parse::<usize>().unwrap() * 1024; if rss > 0 { // Aggregate small segments into "other". let seg_name = if rss < 512 * 1024 { "other".to_owned() } else { curr_seg_name.clone() }; match seg_map.entry(seg_name) { Entry::Vacant(entry) => { entry.insert(rss); }, Entry::Occupied(mut entry) => *entry.get_mut() += rss, } } looking_for = LookingFor::Segment; } } // Note that the sum of all these segments' RSS values differs from the "resident" // measurement obtained via /proc/<pid>/statm in resident(). It's unclear why this // difference occurs; for some processes the measurements match, but for Servo they do not. seg_map.into_iter().collect() } #[cfg(not(target_os = "linux"))] fn resident_segments() -> Vec<(String, usize)> { vec![] } }
danlrobertson/servo
components/profile/mem.rs
Rust
mpl-2.0
25,128
# encoding: utf-8 # # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. # # Author: Kyle Lahnakoski (kyle@lahnakoski.com) # from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import import smtplib import sys from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from mo_logs import Log from mo_dots import listwrap from mo_dots import coalesce from mo_kwargs import override class Emailer: @override def __init__( self, from_address, to_address, host, username, password, subject="catchy title", port=465, use_ssl=1, kwargs=None ): self.settings = kwargs self.server = None def __enter__(self): if self.server is not None: Log.error("Got a problem") if self.settings.use_ssl: self.server = smtplib.SMTP_SSL(self.settings.host, self.settings.port) else: self.server = smtplib.SMTP(self.settings.host, self.settings.port) if self.settings.username and self.settings.password: self.server.login(self.settings.username, self.settings.password) return self def __exit__(self, type, value, traceback): try: self.server.quit() except Exception as e: Log.warning("Problem with smtp server quit(), ignoring problem", e) self.server = None def send_email(self, from_address=None, to_address=None, subject=None, text_data=None, html_data=None ): """Sends an email. from_addr is an email address; to_addrs is a list of email adresses. Addresses can be plain (e.g. "jsmith@example.com") or with real names (e.g. "John Smith <jsmith@example.com>"). text_data and html_data are both strings. You can specify one or both. If you specify both, the email will be sent as a MIME multipart alternative, i.e., the recipient will see the HTML content if his viewer supports it; otherwise he'll see the text content. """ settings = self.settings from_address = coalesce(from_address, settings["from"], settings.from_address) to_address = listwrap(coalesce(to_address, settings.to_address, settings.to_addrs)) if not from_address or not to_address: raise Exception("Both from_addr and to_addrs must be specified") if not text_data and not html_data: raise Exception("Must specify either text_data or html_data") if not html_data: msg = MIMEText(text_data) elif not text_data: msg = MIMEText(html_data, 'html') else: msg = MIMEMultipart('alternative') msg.attach(MIMEText(text_data, 'plain')) msg.attach(MIMEText(html_data, 'html')) msg['Subject'] = coalesce(subject, settings.subject) msg['From'] = from_address msg['To'] = ', '.join(to_address) if self.server: # CALL AS PART OF A SMTP SESSION self.server.sendmail(from_address, to_address, msg.as_string()) else: # CALL AS STAND-ALONE with self: self.server.sendmail(from_address, to_address, msg.as_string()) if sys.hexversion < 0x020603f0: # versions earlier than 2.6.3 have a bug in smtplib when sending over SSL: # http://bugs.python.org/issue4066 # Unfortunately the stock version of Python in Snow Leopard is 2.6.1, so # we patch it here to avoid having to install an updated Python version. import socket import ssl def _get_socket_fixed(self, host, port, timeout): if self.debuglevel > 0: print>> sys.stderr, 'connect:', (host, port) new_socket = socket.create_connection((host, port), timeout) new_socket = ssl.wrap_socket(new_socket, self.keyfile, self.certfile) self.file = smtplib.SSLFakeFile(new_socket) return new_socket smtplib.SMTP_SSL._get_socket = _get_socket_fixed
klahnakoski/Bugzilla-ETL
vendor/pyLibrary/env/emailer.py
Python
mpl-2.0
4,306
<!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>external.argparse &mdash; IPython v0.10 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: '0.10', COLLAPSE_MODINDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="../../_static/jquery.js"></script> <script type="text/javascript" src="../../_static/doctools.js"></script> <link rel="top" title="IPython v0.10 documentation" href="../../index.html" /> <link rel="up" title="The IPython API" href="../index.html" /> <link rel="next" title="external.configobj" href="IPython.external.configobj.html" /> <link rel="prev" title="external.Itpl" href="IPython.external.Itpl.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="../../modindex.html" title="Global Module Index" accesskey="M">modules</a> |</li> <li class="right" > <a href="IPython.external.configobj.html" title="external.configobj" accesskey="N">next</a> |</li> <li class="right" > <a href="IPython.external.Itpl.html" title="external.Itpl" accesskey="P">previous</a> |</li> <li><a href="../../index.html">IPython v0.10 documentation</a> &raquo;</li> <li><a href="../index.html" accesskey="U">The IPython API</a> &raquo;</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body"> <div class="section" id="external-argparse"> <h1>external.argparse<a class="headerlink" href="#external-argparse" title="Permalink to this headline">¶</a></h1> <div class="section" id="module-IPython.external.argparse"> <h2>Module: <tt class="xref docutils literal"><span class="pre">external.argparse</span></tt><a class="headerlink" href="#module-IPython.external.argparse" title="Permalink to this headline">¶</a></h2> <p>Inheritance diagram for <tt class="docutils literal"><span class="pre">IPython.external.argparse</span></tt>:</p> <img src="../../_images/inheritancedd88f50245.png" usemap="#inheritancedd88f50245" class="inheritance"/><map id="inheritancedd88f50245" name="inheritancedd88f50245"> <area shape="rect" href="#IPython.external.argparse.Action" title="external.argparse.Action" alt="" coords="231,196,336,212"/> <area shape="rect" href="#IPython.external.argparse.RawDescriptionHelpFormatter" title="external.argparse.RawDescriptionHelpFormatter" alt="" coords="188,48,380,63"/> <area shape="rect" href="#IPython.external.argparse.RawTextHelpFormatter" title="external.argparse.RawTextHelpFormatter" alt="" coords="419,48,583,63"/> <area shape="rect" href="#IPython.external.argparse.HelpFormatter" title="external.argparse.HelpFormatter" alt="" coords="10,63,146,78"/> <area shape="rect" href="#IPython.external.argparse.ArgumentDefaultsHelpFormatter" title="external.argparse.ArgumentDefaultsHelpFormatter" alt="" coords="182,77,386,93"/> <area shape="rect" href="#IPython.external.argparse.ArgumentParser" title="external.argparse.ArgumentParser" alt="" coords="213,267,355,282"/> <area shape="rect" href="#IPython.external.argparse.Namespace" title="external.argparse.Namespace" alt="" coords="221,230,347,246"/> <area shape="rect" href="#IPython.external.argparse.FileType" title="external.argparse.FileType" alt="" coords="23,33,133,48"/> <area shape="rect" href="#IPython.external.argparse.ArgumentError" title="external.argparse.ArgumentError" alt="" coords="10,3,146,19"/> </map> <p>Command-line parsing library</p> <p>This module is an optparse-inspired command-line parsing library that:</p> <blockquote> <ul class="simple"> <li>handles both optional and positional arguments</li> <li>produces highly informative usage messages</li> <li>supports parsers that dispatch to sub-parsers</li> </ul> </blockquote> <p>The following is a simple usage example that sums integers from the command-line and writes the result to a file:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span> <span class="n">description</span><span class="o">=</span><span class="s">&#39;sum the integers at the command line&#39;</span><span class="p">)</span> <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span> <span class="s">&#39;integers&#39;</span><span class="p">,</span> <span class="n">metavar</span><span class="o">=</span><span class="s">&#39;int&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s">&#39;+&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s">&#39;an integer to be summed&#39;</span><span class="p">)</span> <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span> <span class="s">&#39;--log&#39;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="n">argparse</span><span class="o">.</span><span class="n">FileType</span><span class="p">(</span><span class="s">&#39;w&#39;</span><span class="p">),</span> <span class="n">help</span><span class="o">=</span><span class="s">&#39;the file where the sum should be written&#39;</span><span class="p">)</span> <span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span> <span class="n">args</span><span class="o">.</span><span class="n">log</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s">&#39;</span><span class="si">%s</span><span class="s">&#39;</span> <span class="o">%</span> <span class="nb">sum</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">integers</span><span class="p">))</span> <span class="n">args</span><span class="o">.</span><span class="n">log</span><span class="o">.</span><span class="n">close</span><span class="p">()</span> </pre></div> </div> <p>The module contains the following public classes:</p> <blockquote> <ul> <li><dl class="first docutils"> <dt>ArgumentParser &#8211; The main entry point for command-line parsing. As the</dt> <dd><p class="first last">example above shows, the add_argument() method is used to populate the parser with actions for optional and positional arguments. Then the parse_args() method is invoked to convert the args at the command-line into an object with attributes.</p> </dd> </dl> </li> <li><dl class="first docutils"> <dt>ArgumentError &#8211; The exception raised by ArgumentParser objects when</dt> <dd><p class="first last">there are errors with the parser&#8217;s actions. Errors raised while parsing the command-line are caught by ArgumentParser and emitted as command-line messages.</p> </dd> </dl> </li> <li><dl class="first docutils"> <dt>FileType &#8211; A factory for defining types of files to be created. As the</dt> <dd><p class="first last">example above shows, instances of FileType are typically passed as the type= argument of add_argument() calls.</p> </dd> </dl> </li> <li><dl class="first docutils"> <dt>Action &#8211; The base class for parser actions. Typically actions are</dt> <dd><p class="first last">selected by passing strings like &#8216;store_true&#8217; or &#8216;append_const&#8217; to the action= argument of add_argument(). However, for greater customization of ArgumentParser actions, subclasses of Action may be defined and passed as the action= argument.</p> </dd> </dl> </li> <li><dl class="first docutils"> <dt>HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,</dt> <dd><p class="first last">ArgumentDefaultsHelpFormatter &#8211; Formatter classes which may be passed as the formatter_class= argument to the ArgumentParser constructor. HelpFormatter is the default, RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser not to change the formatting for help text, and ArgumentDefaultsHelpFormatter adds information about argument defaults to the help.</p> </dd> </dl> </li> </ul> </blockquote> <p>All other classes in this module are considered implementation details. (Also note that HelpFormatter and RawDescriptionHelpFormatter are only considered public as object names &#8211; the API of the formatter objects is still considered an implementation detail.)</p> </div> <div class="section" id="classes"> <h2>Classes<a class="headerlink" href="#classes" title="Permalink to this headline">¶</a></h2> <div class="section" id="action"> <h3><a title="IPython.external.argparse.Action" class="reference internal" href="#IPython.external.argparse.Action"><tt class="xref docutils literal"><span class="pre">Action</span></tt></a><a class="headerlink" href="#action" title="Permalink to this headline">¶</a></h3> <dl class="class"> <dt id="IPython.external.argparse.Action"> <!--[IPython.external.argparse.Action]-->class <tt class="descclassname">IPython.external.argparse.</tt><tt class="descname">Action</tt><big>(</big><em>option_strings</em>, <em>dest</em>, <em>nargs=None</em>, <em>const=None</em>, <em>default=None</em>, <em>type=None</em>, <em>choices=None</em>, <em>required=False</em>, <em>help=None</em>, <em>metavar=None</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.Action" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <tt class="xref docutils literal"><span class="pre">IPython.external.argparse._AttributeHolder</span></tt></p> <p>Information about how to convert command line strings to Python objects.</p> <p>Action objects are used by an ArgumentParser to represent the information needed to parse a single argument from one or more strings from the command line. The keyword arguments to the Action constructor are also all attributes of Action instances.</p> <p>Keyword Arguments:</p> <blockquote> <ul> <li><dl class="first docutils"> <dt>option_strings &#8211; A list of command-line option strings which</dt> <dd><p class="first last">should be associated with this action.</p> </dd> </dl> </li> <li><p class="first">dest &#8211; The name of the attribute to hold the created object(s)</p> </li> <li><dl class="first docutils"> <dt>nargs &#8211; The number of command-line arguments that should be</dt> <dd><p class="first">consumed. By default, one argument will be consumed and a single value will be produced. Other values include:</p> <blockquote> <ul class="simple"> <li>N (an integer) consumes N arguments (and produces a list)</li> <li>&#8216;?&#8217; consumes zero or one arguments</li> <li>&#8216;*&#8217; consumes zero or more arguments (and produces a list)</li> <li>&#8216;+&#8217; consumes one or more arguments (and produces a list)</li> </ul> </blockquote> <p class="last">Note that the difference between the default and nargs=1 is that with the default, a single value will be produced, while with nargs=1, a list containing a single value will be produced.</p> </dd> </dl> </li> <li><dl class="first docutils"> <dt>const &#8211; The value to be produced if the option is specified and the</dt> <dd><p class="first last">option uses an action that takes no values.</p> </dd> </dl> </li> <li><p class="first">default &#8211; The value to be produced if the option is not specified.</p> </li> <li><dl class="first docutils"> <dt>type &#8211; The type which the command-line arguments should be converted</dt> <dd><p class="first last">to, should be one of &#8216;string&#8217;, &#8216;int&#8217;, &#8216;float&#8217;, &#8216;complex&#8217; or a callable object that accepts a single string argument. If None, &#8216;string&#8217; is assumed.</p> </dd> </dl> </li> <li><dl class="first docutils"> <dt>choices &#8211; A container of values that should be allowed. If not None,</dt> <dd><p class="first last">after a command-line argument has been converted to the appropriate type, an exception will be raised if it is not a member of this collection.</p> </dd> </dl> </li> <li><dl class="first docutils"> <dt>required &#8211; True if the action must always be specified at the</dt> <dd><p class="first last">command line. This is only meaningful for optional command-line arguments.</p> </dd> </dl> </li> <li><p class="first">help &#8211; The help string describing the argument.</p> </li> <li><dl class="first docutils"> <dt>metavar &#8211; The name to be used for the option&#8217;s argument with the</dt> <dd><p class="first last">help string. If None, the &#8216;dest&#8217; value will be used as the name.</p> </dd> </dl> </li> </ul> </blockquote> <dl class="method"> <dt id="IPython.external.argparse.Action.__init__"> <!--[IPython.external.argparse.Action.__init__]--><tt class="descname">__init__</tt><big>(</big><em>option_strings</em>, <em>dest</em>, <em>nargs=None</em>, <em>const=None</em>, <em>default=None</em>, <em>type=None</em>, <em>choices=None</em>, <em>required=False</em>, <em>help=None</em>, <em>metavar=None</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.Action.__init__" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </dd></dl> </div> <div class="section" id="argumentdefaultshelpformatter"> <h3><a title="IPython.external.argparse.ArgumentDefaultsHelpFormatter" class="reference internal" href="#IPython.external.argparse.ArgumentDefaultsHelpFormatter"><tt class="xref docutils literal"><span class="pre">ArgumentDefaultsHelpFormatter</span></tt></a><a class="headerlink" href="#argumentdefaultshelpformatter" title="Permalink to this headline">¶</a></h3> <dl class="class"> <dt id="IPython.external.argparse.ArgumentDefaultsHelpFormatter"> <!--[IPython.external.argparse.ArgumentDefaultsHelpFormatter]-->class <tt class="descclassname">IPython.external.argparse.</tt><tt class="descname">ArgumentDefaultsHelpFormatter</tt><big>(</big><em>prog</em>, <em>indent_increment=2</em>, <em>max_help_position=24</em>, <em>width=None</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.ArgumentDefaultsHelpFormatter" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <a title="IPython.external.argparse.HelpFormatter" class="reference internal" href="#IPython.external.argparse.HelpFormatter"><tt class="xref docutils literal"><span class="pre">IPython.external.argparse.HelpFormatter</span></tt></a></p> <p>Help message formatter which adds default values to argument help.</p> <p>Only the name of this class is considered a public API. All the methods provided by the class are considered an implementation detail.</p> <dl class="method"> <dt id="IPython.external.argparse.ArgumentDefaultsHelpFormatter.__init__"> <!--[IPython.external.argparse.ArgumentDefaultsHelpFormatter.__init__]--><tt class="descname">__init__</tt><big>(</big><em>prog</em>, <em>indent_increment=2</em>, <em>max_help_position=24</em>, <em>width=None</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.ArgumentDefaultsHelpFormatter.__init__" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </dd></dl> </div> <div class="section" id="argumenterror"> <h3><a title="IPython.external.argparse.ArgumentError" class="reference internal" href="#IPython.external.argparse.ArgumentError"><tt class="xref docutils literal"><span class="pre">ArgumentError</span></tt></a><a class="headerlink" href="#argumenterror" title="Permalink to this headline">¶</a></h3> <dl class="class"> <dt id="IPython.external.argparse.ArgumentError"> <!--[IPython.external.argparse.ArgumentError]-->class <tt class="descclassname">IPython.external.argparse.</tt><tt class="descname">ArgumentError</tt><big>(</big><em>argument</em>, <em>message</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.ArgumentError" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <tt class="xref docutils literal"><span class="pre">exceptions.Exception</span></tt></p> <p>An error from creating or using an argument (optional or positional).</p> <p>The string value of this exception is the message, augmented with information about the argument that caused it.</p> <dl class="method"> <dt id="IPython.external.argparse.ArgumentError.__init__"> <!--[IPython.external.argparse.ArgumentError.__init__]--><tt class="descname">__init__</tt><big>(</big><em>argument</em>, <em>message</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.ArgumentError.__init__" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </dd></dl> </div> <div class="section" id="argumentparser"> <h3><a title="IPython.external.argparse.ArgumentParser" class="reference internal" href="#IPython.external.argparse.ArgumentParser"><tt class="xref docutils literal"><span class="pre">ArgumentParser</span></tt></a><a class="headerlink" href="#argumentparser" title="Permalink to this headline">¶</a></h3> <dl class="class"> <dt id="IPython.external.argparse.ArgumentParser"> <!--[IPython.external.argparse.ArgumentParser]-->class <tt class="descclassname">IPython.external.argparse.</tt><tt class="descname">ArgumentParser</tt><big>(</big><em>prog=None</em>, <em>usage=None</em>, <em>description=None</em>, <em>epilog=None</em>, <em>version=None</em>, <em>parents=</em><span class="optional">[</span><span class="optional">]</span>, <em>formatter_class=&lt;class 'IPython.external.argparse.HelpFormatter'&gt;</em>, <em>prefix_chars='-'</em>, <em>fromfile_prefix_chars=None</em>, <em>argument_default=None</em>, <em>conflict_handler='error'</em>, <em>add_help=True</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.ArgumentParser" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <tt class="xref docutils literal"><span class="pre">IPython.external.argparse._AttributeHolder</span></tt>, <tt class="xref docutils literal"><span class="pre">IPython.external.argparse._ActionsContainer</span></tt></p> <p>Object for parsing command line strings into Python objects.</p> <dl class="docutils"> <dt>Keyword Arguments:</dt> <dd><ul class="first last"> <li><p class="first">prog &#8211; The name of the program (default: sys.argv[0])</p> </li> <li><p class="first">usage &#8211; A usage message (default: auto-generated from arguments)</p> </li> <li><p class="first">description &#8211; A description of what the program does</p> </li> <li><p class="first">epilog &#8211; Text following the argument descriptions</p> </li> <li><p class="first">version &#8211; Add a -v/&#8211;version option with the given version string</p> </li> <li><p class="first">parents &#8211; Parsers whose arguments should be copied into this one</p> </li> <li><p class="first">formatter_class &#8211; HelpFormatter class for printing help messages</p> </li> <li><p class="first">prefix_chars &#8211; Characters that prefix optional arguments</p> </li> <li><dl class="first docutils"> <dt>fromfile_prefix_chars &#8211; Characters that prefix files containing</dt> <dd><p class="first last">additional arguments</p> </dd> </dl> </li> <li><p class="first">argument_default &#8211; The default value for all arguments</p> </li> <li><p class="first">conflict_handler &#8211; String indicating how to handle conflicts</p> </li> <li><p class="first">add_help &#8211; Add a -h/-help option</p> </li> </ul> </dd> </dl> <dl class="method"> <dt id="IPython.external.argparse.ArgumentParser.__init__"> <!--[IPython.external.argparse.ArgumentParser.__init__]--><tt class="descname">__init__</tt><big>(</big><em>prog=None</em>, <em>usage=None</em>, <em>description=None</em>, <em>epilog=None</em>, <em>version=None</em>, <em>parents=</em><span class="optional">[</span><span class="optional">]</span>, <em>formatter_class=&lt;class 'IPython.external.argparse.HelpFormatter'&gt;</em>, <em>prefix_chars='-'</em>, <em>fromfile_prefix_chars=None</em>, <em>argument_default=None</em>, <em>conflict_handler='error'</em>, <em>add_help=True</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.ArgumentParser.__init__" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="method"> <dt id="IPython.external.argparse.ArgumentParser.add_subparsers"> <!--[IPython.external.argparse.ArgumentParser.add_subparsers]--><tt class="descname">add_subparsers</tt><big>(</big><em>**kwargs</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.ArgumentParser.add_subparsers" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="method"> <dt id="IPython.external.argparse.ArgumentParser.error"> <!--[IPython.external.argparse.ArgumentParser.error]--><tt class="descname">error</tt><big>(</big><em>message: string</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.ArgumentParser.error" title="Permalink to this definition">¶</a></dt> <dd><p>Prints a usage message incorporating the message to stderr and exits.</p> <p>If you override this in a subclass, it should not return &#8211; it should either exit or raise an exception.</p> </dd></dl> <dl class="method"> <dt id="IPython.external.argparse.ArgumentParser.exit"> <!--[IPython.external.argparse.ArgumentParser.exit]--><tt class="descname">exit</tt><big>(</big><em>status=0</em>, <em>message=None</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.ArgumentParser.exit" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="method"> <dt id="IPython.external.argparse.ArgumentParser.format_help"> <!--[IPython.external.argparse.ArgumentParser.format_help]--><tt class="descname">format_help</tt><big>(</big><big>)</big><a class="headerlink" href="#IPython.external.argparse.ArgumentParser.format_help" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="method"> <dt id="IPython.external.argparse.ArgumentParser.format_usage"> <!--[IPython.external.argparse.ArgumentParser.format_usage]--><tt class="descname">format_usage</tt><big>(</big><big>)</big><a class="headerlink" href="#IPython.external.argparse.ArgumentParser.format_usage" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="method"> <dt id="IPython.external.argparse.ArgumentParser.format_version"> <!--[IPython.external.argparse.ArgumentParser.format_version]--><tt class="descname">format_version</tt><big>(</big><big>)</big><a class="headerlink" href="#IPython.external.argparse.ArgumentParser.format_version" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="method"> <dt id="IPython.external.argparse.ArgumentParser.parse_args"> <!--[IPython.external.argparse.ArgumentParser.parse_args]--><tt class="descname">parse_args</tt><big>(</big><em>args=None</em>, <em>namespace=None</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.ArgumentParser.parse_args" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="method"> <dt id="IPython.external.argparse.ArgumentParser.parse_known_args"> <!--[IPython.external.argparse.ArgumentParser.parse_known_args]--><tt class="descname">parse_known_args</tt><big>(</big><em>args=None</em>, <em>namespace=None</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.ArgumentParser.parse_known_args" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="method"> <dt id="IPython.external.argparse.ArgumentParser.print_help"> <!--[IPython.external.argparse.ArgumentParser.print_help]--><tt class="descname">print_help</tt><big>(</big><em>file=None</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.ArgumentParser.print_help" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="method"> <dt id="IPython.external.argparse.ArgumentParser.print_usage"> <!--[IPython.external.argparse.ArgumentParser.print_usage]--><tt class="descname">print_usage</tt><big>(</big><em>file=None</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.ArgumentParser.print_usage" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="method"> <dt id="IPython.external.argparse.ArgumentParser.print_version"> <!--[IPython.external.argparse.ArgumentParser.print_version]--><tt class="descname">print_version</tt><big>(</big><em>file=None</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.ArgumentParser.print_version" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </dd></dl> </div> <div class="section" id="filetype"> <h3><a title="IPython.external.argparse.FileType" class="reference internal" href="#IPython.external.argparse.FileType"><tt class="xref docutils literal"><span class="pre">FileType</span></tt></a><a class="headerlink" href="#filetype" title="Permalink to this headline">¶</a></h3> <dl class="class"> <dt id="IPython.external.argparse.FileType"> <!--[IPython.external.argparse.FileType]-->class <tt class="descclassname">IPython.external.argparse.</tt><tt class="descname">FileType</tt><big>(</big><em>mode='r'</em>, <em>bufsize=None</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.FileType" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <tt class="xref docutils literal"><span class="pre">object</span></tt></p> <p>Factory for creating file object types</p> <p>Instances of FileType are typically passed as type= arguments to the ArgumentParser add_argument() method.</p> <dl class="docutils"> <dt>Keyword Arguments:</dt> <dd><ul class="first last"> <li><dl class="first docutils"> <dt>mode &#8211; A string indicating how the file is to be opened. Accepts the</dt> <dd><p class="first last">same values as the builtin open() function.</p> </dd> </dl> </li> <li><dl class="first docutils"> <dt>bufsize &#8211; The file&#8217;s desired buffer size. Accepts the same values as</dt> <dd><p class="first last">the builtin open() function.</p> </dd> </dl> </li> </ul> </dd> </dl> <dl class="method"> <dt id="IPython.external.argparse.FileType.__init__"> <!--[IPython.external.argparse.FileType.__init__]--><tt class="descname">__init__</tt><big>(</big><em>mode='r'</em>, <em>bufsize=None</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.FileType.__init__" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </dd></dl> </div> <div class="section" id="helpformatter"> <h3><a title="IPython.external.argparse.HelpFormatter" class="reference internal" href="#IPython.external.argparse.HelpFormatter"><tt class="xref docutils literal"><span class="pre">HelpFormatter</span></tt></a><a class="headerlink" href="#helpformatter" title="Permalink to this headline">¶</a></h3> <dl class="class"> <dt id="IPython.external.argparse.HelpFormatter"> <!--[IPython.external.argparse.HelpFormatter]-->class <tt class="descclassname">IPython.external.argparse.</tt><tt class="descname">HelpFormatter</tt><big>(</big><em>prog</em>, <em>indent_increment=2</em>, <em>max_help_position=24</em>, <em>width=None</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.HelpFormatter" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <tt class="xref docutils literal"><span class="pre">object</span></tt></p> <p>Formatter for generating usage messages and argument help strings.</p> <p>Only the name of this class is considered a public API. All the methods provided by the class are considered an implementation detail.</p> <dl class="method"> <dt id="IPython.external.argparse.HelpFormatter.__init__"> <!--[IPython.external.argparse.HelpFormatter.__init__]--><tt class="descname">__init__</tt><big>(</big><em>prog</em>, <em>indent_increment=2</em>, <em>max_help_position=24</em>, <em>width=None</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.HelpFormatter.__init__" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="method"> <dt id="IPython.external.argparse.HelpFormatter.add_argument"> <!--[IPython.external.argparse.HelpFormatter.add_argument]--><tt class="descname">add_argument</tt><big>(</big><em>action</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.HelpFormatter.add_argument" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="method"> <dt id="IPython.external.argparse.HelpFormatter.add_arguments"> <!--[IPython.external.argparse.HelpFormatter.add_arguments]--><tt class="descname">add_arguments</tt><big>(</big><em>actions</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.HelpFormatter.add_arguments" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="method"> <dt id="IPython.external.argparse.HelpFormatter.add_text"> <!--[IPython.external.argparse.HelpFormatter.add_text]--><tt class="descname">add_text</tt><big>(</big><em>text</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.HelpFormatter.add_text" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="method"> <dt id="IPython.external.argparse.HelpFormatter.add_usage"> <!--[IPython.external.argparse.HelpFormatter.add_usage]--><tt class="descname">add_usage</tt><big>(</big><em>usage</em>, <em>actions</em>, <em>groups</em>, <em>prefix=None</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.HelpFormatter.add_usage" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="method"> <dt id="IPython.external.argparse.HelpFormatter.end_section"> <!--[IPython.external.argparse.HelpFormatter.end_section]--><tt class="descname">end_section</tt><big>(</big><big>)</big><a class="headerlink" href="#IPython.external.argparse.HelpFormatter.end_section" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="method"> <dt id="IPython.external.argparse.HelpFormatter.format_help"> <!--[IPython.external.argparse.HelpFormatter.format_help]--><tt class="descname">format_help</tt><big>(</big><big>)</big><a class="headerlink" href="#IPython.external.argparse.HelpFormatter.format_help" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <dl class="method"> <dt id="IPython.external.argparse.HelpFormatter.start_section"> <!--[IPython.external.argparse.HelpFormatter.start_section]--><tt class="descname">start_section</tt><big>(</big><em>heading</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.HelpFormatter.start_section" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </dd></dl> </div> <div class="section" id="namespace"> <h3><a title="IPython.external.argparse.Namespace" class="reference internal" href="#IPython.external.argparse.Namespace"><tt class="xref docutils literal"><span class="pre">Namespace</span></tt></a><a class="headerlink" href="#namespace" title="Permalink to this headline">¶</a></h3> <dl class="class"> <dt id="IPython.external.argparse.Namespace"> <!--[IPython.external.argparse.Namespace]-->class <tt class="descclassname">IPython.external.argparse.</tt><tt class="descname">Namespace</tt><big>(</big><em>**kwargs</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.Namespace" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <tt class="xref docutils literal"><span class="pre">IPython.external.argparse._AttributeHolder</span></tt></p> <p>Simple object for storing attributes.</p> <p>Implements equality by attribute names and values, and provides a simple string representation.</p> <dl class="method"> <dt id="IPython.external.argparse.Namespace.__init__"> <!--[IPython.external.argparse.Namespace.__init__]--><tt class="descname">__init__</tt><big>(</big><em>**kwargs</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.Namespace.__init__" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </dd></dl> </div> <div class="section" id="rawdescriptionhelpformatter"> <h3><a title="IPython.external.argparse.RawDescriptionHelpFormatter" class="reference internal" href="#IPython.external.argparse.RawDescriptionHelpFormatter"><tt class="xref docutils literal"><span class="pre">RawDescriptionHelpFormatter</span></tt></a><a class="headerlink" href="#rawdescriptionhelpformatter" title="Permalink to this headline">¶</a></h3> <dl class="class"> <dt id="IPython.external.argparse.RawDescriptionHelpFormatter"> <!--[IPython.external.argparse.RawDescriptionHelpFormatter]-->class <tt class="descclassname">IPython.external.argparse.</tt><tt class="descname">RawDescriptionHelpFormatter</tt><big>(</big><em>prog</em>, <em>indent_increment=2</em>, <em>max_help_position=24</em>, <em>width=None</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.RawDescriptionHelpFormatter" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <a title="IPython.external.argparse.HelpFormatter" class="reference internal" href="#IPython.external.argparse.HelpFormatter"><tt class="xref docutils literal"><span class="pre">IPython.external.argparse.HelpFormatter</span></tt></a></p> <p>Help message formatter which retains any formatting in descriptions.</p> <p>Only the name of this class is considered a public API. All the methods provided by the class are considered an implementation detail.</p> <dl class="method"> <dt id="IPython.external.argparse.RawDescriptionHelpFormatter.__init__"> <!--[IPython.external.argparse.RawDescriptionHelpFormatter.__init__]--><tt class="descname">__init__</tt><big>(</big><em>prog</em>, <em>indent_increment=2</em>, <em>max_help_position=24</em>, <em>width=None</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.RawDescriptionHelpFormatter.__init__" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </dd></dl> </div> <div class="section" id="rawtexthelpformatter"> <h3><a title="IPython.external.argparse.RawTextHelpFormatter" class="reference internal" href="#IPython.external.argparse.RawTextHelpFormatter"><tt class="xref docutils literal"><span class="pre">RawTextHelpFormatter</span></tt></a><a class="headerlink" href="#rawtexthelpformatter" title="Permalink to this headline">¶</a></h3> <dl class="class"> <dt id="IPython.external.argparse.RawTextHelpFormatter"> <!--[IPython.external.argparse.RawTextHelpFormatter]-->class <tt class="descclassname">IPython.external.argparse.</tt><tt class="descname">RawTextHelpFormatter</tt><big>(</big><em>prog</em>, <em>indent_increment=2</em>, <em>max_help_position=24</em>, <em>width=None</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.RawTextHelpFormatter" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <a title="IPython.external.argparse.RawDescriptionHelpFormatter" class="reference internal" href="#IPython.external.argparse.RawDescriptionHelpFormatter"><tt class="xref docutils literal"><span class="pre">IPython.external.argparse.RawDescriptionHelpFormatter</span></tt></a></p> <p>Help message formatter which retains formatting of all help text.</p> <p>Only the name of this class is considered a public API. All the methods provided by the class are considered an implementation detail.</p> <dl class="method"> <dt id="IPython.external.argparse.RawTextHelpFormatter.__init__"> <!--[IPython.external.argparse.RawTextHelpFormatter.__init__]--><tt class="descname">__init__</tt><big>(</big><em>prog</em>, <em>indent_increment=2</em>, <em>max_help_position=24</em>, <em>width=None</em><big>)</big><a class="headerlink" href="#IPython.external.argparse.RawTextHelpFormatter.__init__" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </dd></dl> </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 external" href="">external.argparse</a><ul> <li><a class="reference external" href="#module-IPython.external.argparse">Module: <tt class="docutils literal"><span class="pre">external.argparse</span></tt></a></li> <li><a class="reference external" href="#classes">Classes</a><ul> <li><a class="reference external" href="#action"><tt class="docutils literal"><span class="pre">Action</span></tt></a></li> <li><a class="reference external" href="#argumentdefaultshelpformatter"><tt class="docutils literal"><span class="pre">ArgumentDefaultsHelpFormatter</span></tt></a></li> <li><a class="reference external" href="#argumenterror"><tt class="docutils literal"><span class="pre">ArgumentError</span></tt></a></li> <li><a class="reference external" href="#argumentparser"><tt class="docutils literal"><span class="pre">ArgumentParser</span></tt></a></li> <li><a class="reference external" href="#filetype"><tt class="docutils literal"><span class="pre">FileType</span></tt></a></li> <li><a class="reference external" href="#helpformatter"><tt class="docutils literal"><span class="pre">HelpFormatter</span></tt></a></li> <li><a class="reference external" href="#namespace"><tt class="docutils literal"><span class="pre">Namespace</span></tt></a></li> <li><a class="reference external" href="#rawdescriptionhelpformatter"><tt class="docutils literal"><span class="pre">RawDescriptionHelpFormatter</span></tt></a></li> <li><a class="reference external" href="#rawtexthelpformatter"><tt class="docutils literal"><span class="pre">RawTextHelpFormatter</span></tt></a></li> </ul> </li> </ul> </li> </ul> <h4>Previous topic</h4> <p class="topless"><a href="IPython.external.Itpl.html" title="previous chapter">external.Itpl</a></p> <h4>Next topic</h4> <p class="topless"><a href="IPython.external.configobj.html" title="next chapter">external.configobj</a></p> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../../_sources/api/generated/IPython.external.argparse.txt">Show Source</a></li> </ul> <h3>Quick search</h3> <form class="search" action="../../search.html" method="get"> <input type="text" name="q" size="18" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </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" accesskey="I">index</a></li> <li class="right" > <a href="../../modindex.html" title="Global Module Index" accesskey="M">modules</a> |</li> <li class="right" > <a href="IPython.external.configobj.html" title="external.configobj" accesskey="N">next</a> |</li> <li class="right" > <a href="IPython.external.Itpl.html" title="external.Itpl" accesskey="P">previous</a> |</li> <li><a href="../../index.html">IPython v0.10 documentation</a> &raquo;</li> <li><a href="../index.html" accesskey="U">The IPython API</a> &raquo;</li> </ul> </div> <div class="footer"> &copy; Copyright 2008, The IPython Development Team. Last updated on Aug 04, 2009. Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 0.5.2. </div> </body> </html>
mastizada/kuma
vendor/packages/ipython/docs/dist/html/api/generated/IPython.external.argparse.html
HTML
mpl-2.0
40,287
# -*- coding: utf-8 -*- from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('catalog', '0001_initial'), ] operations = [ migrations.AddField( model_name='catalogintegration', name='service_username', field=models.CharField(default=u'lms_catalog_service_user', help_text='Username created for Course Catalog Integration, e.g. lms_catalog_service_user.', max_length=100), ), ]
edx-solutions/edx-platform
openedx/core/djangoapps/catalog/migrations/0002_catalogintegration_username.py
Python
agpl-3.0
503
#ifndef DYNET_NODES_LSTM_H_ #define DYNET_NODES_LSTM_H_ #include "dynet/dynet.h" #include "dynet/nodes-def-macros.h" namespace dynet { struct VanillaLSTMGates : public Node { explicit VanillaLSTMGates(const std::vector<VariableIndex>& a, bool dropout, real weightnoise_std) : Node(a), dropout(dropout), weightnoise_std(weightnoise_std), forget_gate_bias(1.0) {} virtual bool supports_multibatch() const override { return true; } virtual int autobatch_sig(const ComputationGraph &cg, SigMap &sm) const override; virtual std::vector<int> autobatch_concat(const ComputationGraph & cg) const override; virtual void autobatch_reshape(const ComputationGraph & cg, const std::vector<VariableIndex> & batch_ids, const std::vector<int> & concat, std::vector<const Tensor*>& xs, Tensor& fx) const override { autobatch_reshape_concatonly(cg, batch_ids, concat, xs, fx); } bool dropout; real weightnoise_std; const real forget_gate_bias; DYNET_NODE_DEFINE_DEV_IMPL() }; struct VanillaLSTMC : public Node { explicit VanillaLSTMC(const std::initializer_list<VariableIndex>& a) : Node(a) {} virtual bool supports_multibatch() const override { return true; } virtual int autobatch_sig(const ComputationGraph &cg, SigMap &sm) const override; virtual std::vector<int> autobatch_concat(const ComputationGraph & cg) const override; virtual void autobatch_reshape(const ComputationGraph & cg, const std::vector<VariableIndex> & batch_ids, const std::vector<int> & concat, std::vector<const Tensor*>& xs, Tensor& fx) const override { autobatch_reshape_concatonly(cg, batch_ids, concat, xs, fx); } DYNET_NODE_DEFINE_DEV_IMPL() }; struct VanillaLSTMH : public Node { explicit VanillaLSTMH(const std::initializer_list<VariableIndex>& a) : Node(a) {} virtual bool supports_multibatch() const override { return true; } virtual int autobatch_sig(const ComputationGraph &cg, SigMap &sm) const override; virtual std::vector<int> autobatch_concat(const ComputationGraph & cg) const override; virtual void autobatch_reshape(const ComputationGraph & cg, const std::vector<VariableIndex> & batch_ids, const std::vector<int> & concat, std::vector<const Tensor*>& xs, Tensor& fx) const override { autobatch_reshape_concatonly(cg, batch_ids, concat, xs, fx); } DYNET_NODE_DEFINE_DEV_IMPL() }; } // namespace dynet #endif
TALP-UPC/freeling
src/libdynet/dynet/nodes-lstm.h
C
agpl-3.0
2,748
from __future__ import unicode_literals def execute(): """Make standard print formats readonly for system manager""" import webnotes.model.doc new_perms = [ { 'parent': 'Print Format', 'parentfield': 'permissions', 'parenttype': 'DocType', 'role': 'System Manager', 'permlevel': 1, 'read': 1, }, { 'parent': 'Print Format', 'parentfield': 'permissions', 'parenttype': 'DocType', 'role': 'Administrator', 'permlevel': 1, 'read': 1, 'write': 1 }, ] for perms in new_perms: doc = webnotes.model.doc.Document('DocPerm') doc.fields.update(perms) doc.save() webnotes.conn.commit() webnotes.conn.begin() webnotes.reload_doc('core', 'doctype', 'print_format')
gangadhar-kadam/mtn-erpnext
patches/may_2012/std_pf_readonly.py
Python
agpl-3.0
718
<?php /** * When appropriate, displays a plugin upgrade message "inline" within the plugin * admin screen. * * This is drawn from the Upgrade Notice section of the plugin readme.txt file (ie, * the one belonging to the current stable accessible via WP SVN - at least by * default). */ class Tribe__Admin__Notice__Plugin_Upgrade_Notice { /** * Currently installed version of the plugin * * @var string */ protected $current_version = ''; /** * The plugin path as it is within the plugins directory, ie * "some-plugin/main-file.php". * * @var string */ protected $plugin_path = ''; /** * Contains the plugin upgrade notice (empty if none are available). * * @var string */ protected $upgrade_notice = ''; /** * Test for and display any plugin upgrade messages (if any are available) inline * beside the plugin listing itself. * * The optional third param is the object which actually checks to see if there * are any upgrade notices worth displaying. If not provided, an object of the * default type will be created (which connects to WP SVN). * * @param string $current_version * @param string $plugin_path (ie "plugin-dir/main-file.php") */ public function __construct( $current_version, $plugin_path ) { $this->current_version = $current_version; $this->plugin_path = $plugin_path; add_action( "in_plugin_update_message-$plugin_path", array( $this, 'maybe_run' ) ); } /** * Test if there is a plugin upgrade notice and displays it if so. * * Expects to fire during "in_plugin_update_message-{plugin_path}", therefore * this should only run if WordPress has detected that an upgrade is indeed * available. */ public function maybe_run() { $this->test_for_upgrade_notice(); if ( $this->upgrade_notice ) { $this->display_message(); } } /** * Tests to see if an upgrade notice is available. */ protected function test_for_upgrade_notice() { $cache_key = $this->cache_key(); $this->upgrade_notice = get_transient( $cache_key ); if ( false === $this->upgrade_notice ) { $this->discover_upgrade_notice(); } set_transient( $cache_key, $this->upgrade_notice, $this->cache_expiration() ); } /** * Returns a cache key unique to the current plugin path and version, that * still fits within the 45-char limit of regular WP transient keys. * * @return string */ protected function cache_key() { return 'tribe_plugin_upgrade_notice-' . hash( 'crc32b', $this->plugin_path . $this->current_version ); } /** * Returns the period of time (in seconds) for which to cache plugin upgrade messages. * * @return int */ protected function cache_expiration() { /** * Number of seconds to cache plugin upgrade messages for. * * Defaults to one day, which provides a decent balance between efficiency savings * and allowing for the possibility that some upgrade messages may be changed or * rescinded. * * @var int $cache_expiration */ return (int) apply_filters( 'tribe_plugin_upgrade_notice_expiration', DAY_IN_SECONDS, $this->plugin_path ); } /** * Looks at the current stable plugin readme.txt and parses to try and find the first * available upgrade notice relating to a plugin version higher than this one. * * By default, WP SVN is the source. */ protected function discover_upgrade_notice() { /** * The URL for the current plugin readme.txt file. * * @var string $url * @var string $plugin_path */ $readme_url = apply_filters( 'tribe_plugin_upgrade_readme_url', $this->form_wp_svn_readme_url(), $this->plugin_path ); if ( ! empty( $readme_url ) ) { $response = wp_safe_remote_get( $readme_url ); } if ( ! empty( $response ) && ! is_wp_error( $response ) ) { $readme = $response['body']; } if ( ! empty( $readme ) ) { $this->parse_for_upgrade_notice( $readme ); $this->format_upgrade_notice(); } /** * The upgrade notice for the current plugin (may be empty). * * @var string $upgrade_notice * @var string $plugin_path */ return apply_filters( 'tribe_plugin_upgrade_notice', $this->upgrade_notice, $this->plugin_path ); } /** * Forms the expected URL to the trunk readme.txt file as it is on WP SVN * or an empty string if for any reason it cannot be determined. * * @return string */ protected function form_wp_svn_readme_url() { $parts = explode( '/', $this->plugin_path ); $slug = empty( $parts[0] ) ? '' : $parts[0]; return esc_url( "https://plugins.svn.wordpress.org/$slug/trunk/readme.txt" ); } /** * Given a standard Markdown-format WP readme.txt file, finds the first upgrade * notice (if any) for a version higher than $this->current_version. * * @param string $readme * @return string */ protected function parse_for_upgrade_notice( $readme ) { $in_upgrade_notice = false; $in_version_notice = false; $readme_lines = explode( "\n", $readme ); foreach ( $readme_lines as $line ) { // Once we leave the Upgrade Notice section (ie, we encounter a new section header), bail if ( $in_upgrade_notice && 0 === strpos( $line, '==' ) ) { break; } // Look out for the start of the Upgrade Notice section if ( ! $in_upgrade_notice && preg_match( '/^==\s*Upgrade\s+Notice\s*==/i', $line ) ) { $in_upgrade_notice = true; } // Also test to see if we have left the version specific note (ie, we encounter a new sub heading or header) if ( $in_upgrade_notice && $in_version_notice && 0 === strpos( $line, '=' ) ) { break; } // Look out for the first applicable version-specific note within the Upgrade Notice section if ( $in_upgrade_notice && ! $in_version_notice && preg_match( '/^=\s*\[?([0-9\.]{3,})\]?\s*=/', $line, $matches ) ) { // Is this a higher version than currently installed? if ( version_compare( $matches[1], $this->current_version, '>' ) ) { $in_version_notice = true; } } // Copy the details of the upgrade notice for the first higher version we find if ( $in_upgrade_notice && $in_version_notice ) { $this->upgrade_notice .= $line . "\n"; } } } /** * Convert the plugin version header and any links from Markdown to HTML. */ protected function format_upgrade_notice() { // Convert [links](http://...) to <a href="..."> tags $this->upgrade_notice = preg_replace( '/\[([^\]]*)\]\(([^\)]*)\)/', '<a href="${2}">${1}</a>', $this->upgrade_notice ); // Convert =4.0= headings to <h4 class="version">4.0</h4> tags $this->upgrade_notice = preg_replace( '/=\s*([a-zA-Z0-9\.]{3,})\s*=/', '<h4 class="version">${1}</h4>', $this->upgrade_notice ); } /** * Render the actual upgrade notice. * * Please note if plugin-specific styling is required for the message, you can * use an ID generated by WordPress for one of the message's parent elements * which takes the form "{plugin_name}-update". Example: * * #the-events-calendar-update .tribe-plugin-update-message { ... } */ public function display_message() { $notice = wp_kses_post( $this->upgrade_notice ); echo "<div class='tribe-plugin-update-message'> $notice </div>"; } }
akvo/akvo-sites-zz-template
code/wp-content/plugins/the-events-calendar/common/src/Tribe/Admin/Notice/Plugin_Upgrade_Notice.php
PHP
agpl-3.0
7,190
-- Key assertion, -- inner select clause binds departmentid to department.departmentid select * from department JOIN employee USING(departmentid) WHERE departmentid = (SELECT z FROM t1 WHERE t1.x = departmentid)
wfxiang08/sql-layer-1
fdb-sql-layer-core/src/test/resources/com/foundationdb/sql/optimizer/binding/join-using-14.sql
SQL
agpl-3.0
211
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero 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 Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.generalmedical.vo; /** * Linked to core.clinical.EpworthSleepAssessment business object (ID: 1003100055). */ public class EpworthSleepAssessmentVo extends ims.core.clinical.vo.EpworthSleepAssessmentRefVo implements ims.vo.ImsCloneable, Comparable { private static final long serialVersionUID = 1L; public EpworthSleepAssessmentVo() { } public EpworthSleepAssessmentVo(Integer id, int version) { super(id, version); } public EpworthSleepAssessmentVo(ims.generalmedical.vo.beans.EpworthSleepAssessmentVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.chanceofsleep = bean.getChanceOfSleep() == null ? null : ims.spinalinjuries.vo.lookups.SleepEpworthChanceOfSleep.buildLookup(bean.getChanceOfSleep()); this.sleepscore = bean.getSleepScore() == null ? null : ims.spinalinjuries.vo.lookups.SleepEpworthScore.buildLookup(bean.getSleepScore()); } public void populate(ims.vo.ValueObjectBeanMap map, ims.generalmedical.vo.beans.EpworthSleepAssessmentVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.chanceofsleep = bean.getChanceOfSleep() == null ? null : ims.spinalinjuries.vo.lookups.SleepEpworthChanceOfSleep.buildLookup(bean.getChanceOfSleep()); this.sleepscore = bean.getSleepScore() == null ? null : ims.spinalinjuries.vo.lookups.SleepEpworthScore.buildLookup(bean.getSleepScore()); } public ims.vo.ValueObjectBean getBean() { return this.getBean(new ims.vo.ValueObjectBeanMap()); } public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map) { ims.generalmedical.vo.beans.EpworthSleepAssessmentVoBean bean = null; if(map != null) bean = (ims.generalmedical.vo.beans.EpworthSleepAssessmentVoBean)map.getValueObjectBean(this); if (bean == null) { bean = new ims.generalmedical.vo.beans.EpworthSleepAssessmentVoBean(); map.addValueObjectBean(this, bean); bean.populate(map, this); } return bean; } public Object getFieldValueByFieldName(String fieldName) { if(fieldName == null) throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name"); fieldName = fieldName.toUpperCase(); if(fieldName.equals("CHANCEOFSLEEP")) return getChanceOfSleep(); if(fieldName.equals("SLEEPSCORE")) return getSleepScore(); return super.getFieldValueByFieldName(fieldName); } public boolean getChanceOfSleepIsNotNull() { return this.chanceofsleep != null; } public ims.spinalinjuries.vo.lookups.SleepEpworthChanceOfSleep getChanceOfSleep() { return this.chanceofsleep; } public void setChanceOfSleep(ims.spinalinjuries.vo.lookups.SleepEpworthChanceOfSleep value) { this.isValidated = false; this.chanceofsleep = value; } public boolean getSleepScoreIsNotNull() { return this.sleepscore != null; } public ims.spinalinjuries.vo.lookups.SleepEpworthScore getSleepScore() { return this.sleepscore; } public void setSleepScore(ims.spinalinjuries.vo.lookups.SleepEpworthScore value) { this.isValidated = false; this.sleepscore = value; } public boolean isValidated() { if(this.isBusy) return true; this.isBusy = true; if(!this.isValidated) { this.isBusy = false; return false; } this.isBusy = false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(this.isBusy) return null; this.isBusy = true; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } int errorCount = listOfErrors.size(); if(errorCount == 0) { this.isBusy = false; this.isValidated = true; return null; } String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); this.isBusy = false; this.isValidated = false; return result; } public void clearIDAndVersion() { this.id = null; this.version = 0; } public Object clone() { if(this.isBusy) return this; this.isBusy = true; EpworthSleepAssessmentVo clone = new EpworthSleepAssessmentVo(this.id, this.version); if(this.chanceofsleep == null) clone.chanceofsleep = null; else clone.chanceofsleep = (ims.spinalinjuries.vo.lookups.SleepEpworthChanceOfSleep)this.chanceofsleep.clone(); if(this.sleepscore == null) clone.sleepscore = null; else clone.sleepscore = (ims.spinalinjuries.vo.lookups.SleepEpworthScore)this.sleepscore.clone(); clone.isValidated = this.isValidated; this.isBusy = false; return clone; } public int compareTo(Object obj) { return compareTo(obj, true); } public int compareTo(Object obj, boolean caseInsensitive) { if (obj == null) { return -1; } if(caseInsensitive); // this is to avoid eclipse warning only. if (!(EpworthSleepAssessmentVo.class.isAssignableFrom(obj.getClass()))) { throw new ClassCastException("A EpworthSleepAssessmentVo object cannot be compared an Object of type " + obj.getClass().getName()); } EpworthSleepAssessmentVo compareObj = (EpworthSleepAssessmentVo)obj; int retVal = 0; if (retVal == 0) { if(this.getID_EpworthSleepAssessment() == null && compareObj.getID_EpworthSleepAssessment() != null) return -1; if(this.getID_EpworthSleepAssessment() != null && compareObj.getID_EpworthSleepAssessment() == null) return 1; if(this.getID_EpworthSleepAssessment() != null && compareObj.getID_EpworthSleepAssessment() != null) retVal = this.getID_EpworthSleepAssessment().compareTo(compareObj.getID_EpworthSleepAssessment()); } return retVal; } public synchronized static int generateValueObjectUniqueID() { return ims.vo.ValueObject.generateUniqueID(); } public int countFieldsWithValue() { int count = 0; if(this.chanceofsleep != null) count++; if(this.sleepscore != null) count++; return count; } public int countValueObjectFields() { return 2; } protected ims.spinalinjuries.vo.lookups.SleepEpworthChanceOfSleep chanceofsleep; protected ims.spinalinjuries.vo.lookups.SleepEpworthScore sleepscore; private boolean isValidated = false; private boolean isBusy = false; }
open-health-hub/openMAXIMS
openmaxims_workspace/ValueObjects/src/ims/generalmedical/vo/EpworthSleepAssessmentVo.java
Java
agpl-3.0
7,901
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero 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 Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.nursing.vo.beans; public class MRSATreatmentVoBean extends ims.vo.ValueObjectBean { public MRSATreatmentVoBean() { } public MRSATreatmentVoBean(ims.nursing.vo.MRSATreatmentVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.startdate = vo.getStartDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getStartDate().getBean(); this.rescreendate = vo.getRescreenDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getRescreenDate().getBean(); this.treatmentnumber = vo.getTreatmentNumber(); this.treatmentdetails = vo.getTreatmentDetails() == null ? null : vo.getTreatmentDetails().getBeanCollection(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.nursing.vo.MRSATreatmentVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.startdate = vo.getStartDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getStartDate().getBean(); this.rescreendate = vo.getRescreenDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getRescreenDate().getBean(); this.treatmentnumber = vo.getTreatmentNumber(); this.treatmentdetails = vo.getTreatmentDetails() == null ? null : vo.getTreatmentDetails().getBeanCollection(); } public ims.nursing.vo.MRSATreatmentVo buildVo() { return this.buildVo(new ims.vo.ValueObjectBeanMap()); } public ims.nursing.vo.MRSATreatmentVo buildVo(ims.vo.ValueObjectBeanMap map) { ims.nursing.vo.MRSATreatmentVo vo = null; if(map != null) vo = (ims.nursing.vo.MRSATreatmentVo)map.getValueObject(this); if(vo == null) { vo = new ims.nursing.vo.MRSATreatmentVo(); map.addValueObject(this, vo); vo.populate(map, this); } return vo; } public Integer getId() { return this.id; } public void setId(Integer value) { this.id = value; } public int getVersion() { return this.version; } public void setVersion(int value) { this.version = value; } public ims.framework.utils.beans.DateBean getStartDate() { return this.startdate; } public void setStartDate(ims.framework.utils.beans.DateBean value) { this.startdate = value; } public ims.framework.utils.beans.DateBean getRescreenDate() { return this.rescreendate; } public void setRescreenDate(ims.framework.utils.beans.DateBean value) { this.rescreendate = value; } public Integer getTreatmentNumber() { return this.treatmentnumber; } public void setTreatmentNumber(Integer value) { this.treatmentnumber = value; } public ims.nursing.vo.beans.MRSATreatmentDetailsVoBean[] getTreatmentDetails() { return this.treatmentdetails; } public void setTreatmentDetails(ims.nursing.vo.beans.MRSATreatmentDetailsVoBean[] value) { this.treatmentdetails = value; } private Integer id; private int version; private ims.framework.utils.beans.DateBean startdate; private ims.framework.utils.beans.DateBean rescreendate; private Integer treatmentnumber; private ims.nursing.vo.beans.MRSATreatmentDetailsVoBean[] treatmentdetails; }
open-health-hub/openMAXIMS
openmaxims_workspace/ValueObjects/src/ims/nursing/vo/beans/MRSATreatmentVoBean.java
Java
agpl-3.0
4,677
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero 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 Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.nursing.vo; /** * Linked to nursing.assessment.Transfers business object (ID: 1015100016). */ public class Transfers extends ims.nursing.assessment.vo.TransfersRefVo implements ims.vo.ImsCloneable, Comparable { private static final long serialVersionUID = 1L; public Transfers() { } public Transfers(Integer id, int version) { super(id, version); } public Transfers(ims.nursing.vo.beans.TransfersBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.patienttransfers = bean.getPatientTransfers() == null ? null : ims.nursing.vo.lookups.Transfers.buildLookup(bean.getPatientTransfers()); this.assistancerequired = bean.getAssistanceRequired() == null ? null : ims.nursing.vo.lookups.Ability.buildLookup(bean.getAssistanceRequired()); } public void populate(ims.vo.ValueObjectBeanMap map, ims.nursing.vo.beans.TransfersBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.patienttransfers = bean.getPatientTransfers() == null ? null : ims.nursing.vo.lookups.Transfers.buildLookup(bean.getPatientTransfers()); this.assistancerequired = bean.getAssistanceRequired() == null ? null : ims.nursing.vo.lookups.Ability.buildLookup(bean.getAssistanceRequired()); } public ims.vo.ValueObjectBean getBean() { return this.getBean(new ims.vo.ValueObjectBeanMap()); } public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map) { ims.nursing.vo.beans.TransfersBean bean = null; if(map != null) bean = (ims.nursing.vo.beans.TransfersBean)map.getValueObjectBean(this); if (bean == null) { bean = new ims.nursing.vo.beans.TransfersBean(); map.addValueObjectBean(this, bean); bean.populate(map, this); } return bean; } public Object getFieldValueByFieldName(String fieldName) { if(fieldName == null) throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name"); fieldName = fieldName.toUpperCase(); if(fieldName.equals("PATIENTTRANSFERS")) return getPatientTransfers(); if(fieldName.equals("ASSISTANCEREQUIRED")) return getAssistanceRequired(); return super.getFieldValueByFieldName(fieldName); } public boolean getPatientTransfersIsNotNull() { return this.patienttransfers != null; } public ims.nursing.vo.lookups.Transfers getPatientTransfers() { return this.patienttransfers; } public void setPatientTransfers(ims.nursing.vo.lookups.Transfers value) { this.isValidated = false; this.patienttransfers = value; } public boolean getAssistanceRequiredIsNotNull() { return this.assistancerequired != null; } public ims.nursing.vo.lookups.Ability getAssistanceRequired() { return this.assistancerequired; } public void setAssistanceRequired(ims.nursing.vo.lookups.Ability value) { this.isValidated = false; this.assistancerequired = value; } public boolean isValidated() { if(this.isBusy) return true; this.isBusy = true; if(!this.isValidated) { this.isBusy = false; return false; } this.isBusy = false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(this.isBusy) return null; this.isBusy = true; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } int errorCount = listOfErrors.size(); if(errorCount == 0) { this.isBusy = false; this.isValidated = true; return null; } String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); this.isBusy = false; this.isValidated = false; return result; } public void clearIDAndVersion() { this.id = null; this.version = 0; } public Object clone() { if(this.isBusy) return this; this.isBusy = true; Transfers clone = new Transfers(this.id, this.version); if(this.patienttransfers == null) clone.patienttransfers = null; else clone.patienttransfers = (ims.nursing.vo.lookups.Transfers)this.patienttransfers.clone(); if(this.assistancerequired == null) clone.assistancerequired = null; else clone.assistancerequired = (ims.nursing.vo.lookups.Ability)this.assistancerequired.clone(); clone.isValidated = this.isValidated; this.isBusy = false; return clone; } public int compareTo(Object obj) { return compareTo(obj, true); } public int compareTo(Object obj, boolean caseInsensitive) { if (obj == null) { return -1; } if(caseInsensitive); // this is to avoid eclipse warning only. if (!(Transfers.class.isAssignableFrom(obj.getClass()))) { throw new ClassCastException("A Transfers object cannot be compared an Object of type " + obj.getClass().getName()); } Transfers compareObj = (Transfers)obj; int retVal = 0; if (retVal == 0) { if(this.getID_Transfers() == null && compareObj.getID_Transfers() != null) return -1; if(this.getID_Transfers() != null && compareObj.getID_Transfers() == null) return 1; if(this.getID_Transfers() != null && compareObj.getID_Transfers() != null) retVal = this.getID_Transfers().compareTo(compareObj.getID_Transfers()); } return retVal; } public synchronized static int generateValueObjectUniqueID() { return ims.vo.ValueObject.generateUniqueID(); } public int countFieldsWithValue() { int count = 0; if(this.patienttransfers != null) count++; if(this.assistancerequired != null) count++; return count; } public int countValueObjectFields() { return 2; } protected ims.nursing.vo.lookups.Transfers patienttransfers; protected ims.nursing.vo.lookups.Ability assistancerequired; private boolean isValidated = false; private boolean isBusy = false; }
open-health-hub/openMAXIMS
openmaxims_workspace/ValueObjects/src/ims/nursing/vo/Transfers.java
Java
agpl-3.0
7,494
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.RefMan.vo; /** * Linked to RefMan.CatsReferral business object (ID: 1004100035). */ public class CatsReferralForSessionManagementVo extends ims.RefMan.vo.CatsReferralRefVo implements ims.vo.ImsCloneable, Comparable { private static final long serialVersionUID = 1L; public CatsReferralForSessionManagementVo() { } public CatsReferralForSessionManagementVo(Integer id, int version) { super(id, version); } public CatsReferralForSessionManagementVo(ims.RefMan.vo.beans.CatsReferralForSessionManagementVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.referraldetails = bean.getReferralDetails() == null ? null : bean.getReferralDetails().buildVo(); this.currentstatus = bean.getCurrentStatus() == null ? null : bean.getCurrentStatus().buildVo(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.RefMan.vo.beans.CatsReferralForSessionManagementVoBean bean) { this.id = bean.getId(); this.version = bean.getVersion(); this.referraldetails = bean.getReferralDetails() == null ? null : bean.getReferralDetails().buildVo(map); this.currentstatus = bean.getCurrentStatus() == null ? null : bean.getCurrentStatus().buildVo(map); } public ims.vo.ValueObjectBean getBean() { return this.getBean(new ims.vo.ValueObjectBeanMap()); } public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map) { ims.RefMan.vo.beans.CatsReferralForSessionManagementVoBean bean = null; if(map != null) bean = (ims.RefMan.vo.beans.CatsReferralForSessionManagementVoBean)map.getValueObjectBean(this); if (bean == null) { bean = new ims.RefMan.vo.beans.CatsReferralForSessionManagementVoBean(); map.addValueObjectBean(this, bean); bean.populate(map, this); } return bean; } public Object getFieldValueByFieldName(String fieldName) { if(fieldName == null) throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name"); fieldName = fieldName.toUpperCase(); if(fieldName.equals("REFERRALDETAILS")) return getReferralDetails(); if(fieldName.equals("CURRENTSTATUS")) return getCurrentStatus(); return super.getFieldValueByFieldName(fieldName); } public boolean getReferralDetailsIsNotNull() { return this.referraldetails != null; } public ims.RefMan.vo.ReferralLetterForSessionManagementVo getReferralDetails() { return this.referraldetails; } public void setReferralDetails(ims.RefMan.vo.ReferralLetterForSessionManagementVo value) { this.isValidated = false; this.referraldetails = value; } public boolean getCurrentStatusIsNotNull() { return this.currentstatus != null; } public ims.RefMan.vo.CatsReferralStatusLiteVo getCurrentStatus() { return this.currentstatus; } public void setCurrentStatus(ims.RefMan.vo.CatsReferralStatusLiteVo value) { this.isValidated = false; this.currentstatus = value; } public boolean isValidated() { if(this.isBusy) return true; this.isBusy = true; if(!this.isValidated) { this.isBusy = false; return false; } this.isBusy = false; return true; } public String[] validate() { return validate(null); } public String[] validate(String[] existingErrors) { if(this.isBusy) return null; this.isBusy = true; java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>(); if(existingErrors != null) { for(int x = 0; x < existingErrors.length; x++) { listOfErrors.add(existingErrors[x]); } } int errorCount = listOfErrors.size(); if(errorCount == 0) { this.isBusy = false; this.isValidated = true; return null; } String[] result = new String[errorCount]; for(int x = 0; x < errorCount; x++) result[x] = (String)listOfErrors.get(x); this.isBusy = false; this.isValidated = false; return result; } public void clearIDAndVersion() { this.id = null; this.version = 0; } public Object clone() { if(this.isBusy) return this; this.isBusy = true; CatsReferralForSessionManagementVo clone = new CatsReferralForSessionManagementVo(this.id, this.version); if(this.referraldetails == null) clone.referraldetails = null; else clone.referraldetails = (ims.RefMan.vo.ReferralLetterForSessionManagementVo)this.referraldetails.clone(); if(this.currentstatus == null) clone.currentstatus = null; else clone.currentstatus = (ims.RefMan.vo.CatsReferralStatusLiteVo)this.currentstatus.clone(); clone.isValidated = this.isValidated; this.isBusy = false; return clone; } public int compareTo(Object obj) { return compareTo(obj, true); } public int compareTo(Object obj, boolean caseInsensitive) { if (obj == null) { return -1; } if(caseInsensitive); // this is to avoid eclipse warning only. if (!(CatsReferralForSessionManagementVo.class.isAssignableFrom(obj.getClass()))) { throw new ClassCastException("A CatsReferralForSessionManagementVo object cannot be compared an Object of type " + obj.getClass().getName()); } if (this.id == null) return 1; if (((CatsReferralForSessionManagementVo)obj).getBoId() == null) return -1; return this.id.compareTo(((CatsReferralForSessionManagementVo)obj).getBoId()); } public synchronized static int generateValueObjectUniqueID() { return ims.vo.ValueObject.generateUniqueID(); } public int countFieldsWithValue() { int count = 0; if(this.referraldetails != null) count++; if(this.currentstatus != null) count++; return count; } public int countValueObjectFields() { return 2; } protected ims.RefMan.vo.ReferralLetterForSessionManagementVo referraldetails; protected ims.RefMan.vo.CatsReferralStatusLiteVo currentstatus; private boolean isValidated = false; private boolean isBusy = false; }
open-health-hub/openMAXIMS
openmaxims_workspace/ValueObjects/src/ims/RefMan/vo/CatsReferralForSessionManagementVo.java
Java
agpl-3.0
5,952
<?php /********************************************************************************* * Zurmo is a customer relationship management program developed by * Zurmo, Inc. Copyright (C) 2015 Zurmo Inc. * * Zurmo is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * Zurmo 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 Affero General Public License for more * details. * * You should have received a copy of the GNU Affero 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 can contact Zurmo, Inc. with a mailing address at 27 North Wacker Drive * Suite 370 Chicago, IL 60606. or at email address contact@zurmo.com. * * The interactive user interfaces in original and modified versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the Zurmo * logo and Zurmo copyright notice. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display the words * "Copyright Zurmo Inc. 2015. All rights reserved". ********************************************************************************/ /** * Class for defining the badge associated with creating a new note */ class CreateNoteGameBadgeRules extends GameBadgeRules { public static $valuesIndexedByGrade = array( 1 => 1, 2 => 10, 3 => 25, 4 => 50, 5 => 75, 6 => 100, 7 => 125, 8 => 150, 9 => 175, 10 => 200, 11 => 225, 12 => 250, 13 => 300 ); public static function getPassiveDisplayLabel($value) { return Zurmo::t('NotesModule', '{n} NotesModuleSingularLabel created|{n} NotesModulePluralLabel created', array_merge(array($value), LabelUtil::getTranslationParamsForAllModules())); } /** * @param array $userPointsByType * @param array $userScoresByType * @return int|string */ public static function badgeGradeUserShouldHaveByPointsAndScores($userPointsByType, $userScoresByType) { assert('is_array($userPointsByType)'); assert('is_array($userScoresByType)'); if (isset($userScoresByType['CreateNote'])) { return static::getBadgeGradeByValue((int)$userScoresByType['CreateNote']->value); } return 0; } } ?>
raymondlamwu/zurmotest
app/protected/modules/notes/rules/badges/CreateNoteGameBadgeRules.php
PHP
agpl-3.0
3,520
<?php /** * Dummy theme. */ function i18n_theme_test() { return __( 'This is a dummy theme', 'internationalized-theme' ); }
medialab-ufg/wp-rhs
tests/wordpress-tests-lib/data/themedir1/internationalized-theme/functions.php
PHP
agpl-3.0
128
<!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" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Unit Testing Class : CodeIgniter User Guide</title> <style type='text/css' media='all'>@import url('../userguide.css');</style> <link rel='stylesheet' type='text/css' media='all' href='../userguide.css' /> <script type="text/javascript" src="../nav/nav.js"></script> <script type="text/javascript" src="../nav/prototype.lite.js"></script> <script type="text/javascript" src="../nav/moo.fx.js"></script> <script type="text/javascript" src="../nav/user_guide_menu.js"></script> <meta http-equiv='expires' content='-1' /> <meta http-equiv= 'pragma' content='no-cache' /> <meta name='robots' content='all' /> <meta name='author' content='ExpressionEngine Dev Team' /> <meta name='description' content='CodeIgniter User Guide' /> </head> <body> <!-- START NAVIGATION --> <div id="nav"><div id="nav_inner"><script type="text/javascript">create_menu('../');</script></div></div> <div id="nav2"><a name="top"></a><a href="javascript:void(0);" onclick="myHeight.toggle();"><img src="../images/nav_toggle_darker.jpg" width="154" height="43" border="0" title="Toggle Table of Contents" alt="Toggle Table of Contents" /></a></div> <div id="masthead"> <table cellpadding="0" cellspacing="0" border="0" style="width:100%"> <tr> <td><h1>CodeIgniter User Guide Version 1.7.2</h1></td> <td id="breadcrumb_right"><a href="../toc.html">Table of Contents Page</a></td> </tr> </table> </div> <!-- END NAVIGATION --> <!-- START BREADCRUMB --> <table cellpadding="0" cellspacing="0" border="0" style="width:100%"> <tr> <td id="breadcrumb"> <a href="http://codeigniter.com/">CodeIgniter Home</a> &nbsp;&#8250;&nbsp; <a href="../index.html">User Guide Home</a> &nbsp;&#8250;&nbsp; Unit Testing Class </td> <td id="searchbox"><form method="get" action="http://www.google.com/search"><input type="hidden" name="as_sitesearch" id="as_sitesearch" value="codeigniter.com/user_guide/" />Search User Guide&nbsp; <input type="text" class="input" style="width:200px;" name="q" id="q" size="31" maxlength="255" value="" />&nbsp;<input type="submit" class="submit" name="sa" value="Go" /></form></td> </tr> </table> <!-- END BREADCRUMB --> <br clear="all" /> <!-- START CONTENT --> <div id="content"> <h1>Unit Testing Class</h1> <p>Unit testing is an approach to software development in which tests are written for each function in your application. If you are not familiar with the concept you might do a little googling on the subject.</p> <p>CodeIgniter's Unit Test class is quite simple, consisting of an evaluation function and two result functions. It's not intended to be a full-blown test suite but rather a simple mechanism to evaluate your code to determine if it is producing the correct data type and result. </p> <h2>Initializing the Class</h2> <p>Like most other classes in CodeIgniter, the Unit Test class is initialized in your controller using the <dfn>$this->load->library</dfn> function:</p> <code>$this->load->library('unit_test');</code> <p>Once loaded, the Unit Test object will be available using: <dfn>$this->unit</dfn></p> <h2>Running Tests</h2> <p>Running a test involves supplying a test and an expected result to the following function:</p> <h2>$this->unit->run( <var>test</var>, <var>expected result</var>, '<var>test name</var>' );</h2> <p>Where <var>test</var> is the result of the code you wish to test, <var>expected result</var> is the data type you expect, and <var>test name</var> is an optional name you can give your test. Example:</p> <code>$test = 1 + 1;<br /> <br /> $expected_result = 2;<br /> <br /> $test_name = 'Adds one plus one';<br /> <br /> $this->unit->run($test, $expected_result, $test_name);</code> <p>The expected result you supply can either be a literal match, or a data type match. Here's an example of a literal:</p> <code>$this->unit->run('Foo', 'Foo');</code> <p>Here is an example of a data type match:</p> <code>$this->unit->run('Foo', 'is_string');</code> <p>Notice the use of "is_string" in the second parameter? This tells the function to evaluate whether your test is producing a string as the result. Here is a list of allowed comparison types:</p> <ul> <li>is_string</li> <li>is_bool</li> <li>is_true</li> <li>is_false</li> <li>is_int</li> <li>is_numeric</li> <li>is_float</li> <li>is_double</li> <li>is_array</li> <li>is_null</li> </ul> <h2>Generating Reports</h2> <p>You can either display results after each test, or your can run several tests and generate a report at the end. To show a report directly simply echo or return the <var>run</var> function:</p> <code>echo $this->unit->run($test, $expected_result);</code> <p>To run a full report of all tests, use this:</p> <code>echo $this->unit->report();</code> <p>The report will be formatted in an HTML table for viewing. If you prefer the raw data you can retrieve an array using:</p> <code>echo $this->unit->result();</code> <h2>Strict Mode</h2> <p>By default the unit test class evaluates literal matches loosely. Consider this example:</p> <code>$this->unit->run(1, TRUE);</code> <p>The test is evaluating an integer, but the expected result is a boolean. PHP, however, due to it's loose data-typing will evaluate the above code as TRUE using a normal equality test:</p> <code>if (1 == TRUE) echo 'This evaluates as true';</code> <p>If you prefer, you can put the unit test class in to strict mode, which will compare the data type as well as the value:</p> <code>if (1 === TRUE) echo 'This evaluates as FALSE';</code> <p>To enable strict mode use this:</p> <code>$this->unit->use_strict(TRUE);</code> <h2>Enabling/Disabling Unit Testing</h2> <p>If you would like to leave some testing in place in your scripts, but not have it run unless you need it, you can disable unit testing using:</p> <code>$this->unit->active(FALSE)</code> <h2>Creating a Template</h2> <p>If you would like your test results formatted differently then the default you can set your own template. Here is an example of a simple template. Note the required pseudo-variables:</p> <code> $str = '<br /> &lt;table border="0" cellpadding="4" cellspacing="1"><br /> &nbsp;&nbsp;&nbsp;&nbsp;<kbd>{rows}</kbd><br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;tr><br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;td><kbd>{item}</kbd>&lt;/td><br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;td><kbd>{result}</kbd>&lt;/td><br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/tr><br /> &nbsp;&nbsp;&nbsp;&nbsp;<kbd>{/rows}</kbd><br /> &lt;/table>';<br /> <br /> $this->unit->set_template($str); </code> <p class="important"><strong>Note:</strong> Your template must be declared <strong>before</strong> running the unit test process.</p> </div> <!-- END CONTENT --> <div id="footer"> <p> Previous Topic:&nbsp;&nbsp;<a href="typography.html">Typography Class</a> &nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp; <a href="#top">Top of Page</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp; <a href="../index.html">User Guide Home</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp; Next Topic:&nbsp;&nbsp;<a href="uri.html">URI Class</a> </p> <p><a href="http://codeigniter.com">CodeIgniter</a> &nbsp;&middot;&nbsp; Copyright &#169; 2006-2010 &nbsp;&middot;&nbsp; <a href="http://ellislab.com/">Ellislab, Inc.</a></p> </div> </body> </html>
greencorecr/phone_campaigns
user_guide/libraries/unit_testing.html
HTML
agpl-3.0
7,545
// Copyright (C) 2007-2015 CEA/DEN, EDF R&D, OPEN CASCADE // // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN, // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com // #include "SMESH_ControlsDef.hxx" #include "SMDS_BallElement.hxx" #include "SMDS_Iterator.hxx" #include "SMDS_Mesh.hxx" #include "SMDS_MeshElement.hxx" #include "SMDS_MeshNode.hxx" #include "SMDS_QuadraticEdge.hxx" #include "SMDS_QuadraticFaceOfNodes.hxx" #include "SMDS_VolumeTool.hxx" #include "SMESHDS_GroupBase.hxx" #include "SMESHDS_GroupOnFilter.hxx" #include "SMESHDS_Mesh.hxx" #include "SMESH_MeshAlgos.hxx" #include "SMESH_OctreeNode.hxx" #include <Basics_Utils.hxx> #include <BRepAdaptor_Surface.hxx> #include <BRepClass_FaceClassifier.hxx> #include <BRep_Tool.hxx> #include <Geom_CylindricalSurface.hxx> #include <Geom_Plane.hxx> #include <Geom_Surface.hxx> #include <Precision.hxx> #include <TColStd_MapIteratorOfMapOfInteger.hxx> #include <TColStd_MapOfInteger.hxx> #include <TColStd_SequenceOfAsciiString.hxx> #include <TColgp_Array1OfXYZ.hxx> #include <TopAbs.hxx> #include <TopExp.hxx> #include <TopoDS.hxx> #include <TopoDS_Edge.hxx> #include <TopoDS_Face.hxx> #include <TopoDS_Iterator.hxx> #include <TopoDS_Shape.hxx> #include <TopoDS_Vertex.hxx> #include <gp_Ax3.hxx> #include <gp_Cylinder.hxx> #include <gp_Dir.hxx> #include <gp_Pln.hxx> #include <gp_Pnt.hxx> #include <gp_Vec.hxx> #include <gp_XYZ.hxx> #include <vtkMeshQuality.h> #include <set> #include <limits> /* AUXILIARY METHODS */ namespace { const double theEps = 1e-100; const double theInf = 1e+100; inline gp_XYZ gpXYZ(const SMDS_MeshNode* aNode ) { return gp_XYZ(aNode->X(), aNode->Y(), aNode->Z() ); } inline double getAngle( const gp_XYZ& P1, const gp_XYZ& P2, const gp_XYZ& P3 ) { gp_Vec v1( P1 - P2 ), v2( P3 - P2 ); return v1.Magnitude() < gp::Resolution() || v2.Magnitude() < gp::Resolution() ? 0 : v1.Angle( v2 ); } inline double getArea( const gp_XYZ& P1, const gp_XYZ& P2, const gp_XYZ& P3 ) { gp_Vec aVec1( P2 - P1 ); gp_Vec aVec2( P3 - P1 ); return ( aVec1 ^ aVec2 ).Magnitude() * 0.5; } inline double getArea( const gp_Pnt& P1, const gp_Pnt& P2, const gp_Pnt& P3 ) { return getArea( P1.XYZ(), P2.XYZ(), P3.XYZ() ); } inline double getDistance( const gp_XYZ& P1, const gp_XYZ& P2 ) { double aDist = gp_Pnt( P1 ).Distance( gp_Pnt( P2 ) ); return aDist; } int getNbMultiConnection( const SMDS_Mesh* theMesh, const int theId ) { if ( theMesh == 0 ) return 0; const SMDS_MeshElement* anEdge = theMesh->FindElement( theId ); if ( anEdge == 0 || anEdge->GetType() != SMDSAbs_Edge/* || anEdge->NbNodes() != 2 */) return 0; // for each pair of nodes in anEdge (there are 2 pairs in a quadratic edge) // count elements containing both nodes of the pair. // Note that there may be such cases for a quadratic edge (a horizontal line): // // Case 1 Case 2 // | | | | | // | | | | | // +-----+------+ +-----+------+ // | | | | // | | | | // result sould be 2 in both cases // int aResult0 = 0, aResult1 = 0; // last node, it is a medium one in a quadratic edge const SMDS_MeshNode* aLastNode = anEdge->GetNode( anEdge->NbNodes() - 1 ); const SMDS_MeshNode* aNode0 = anEdge->GetNode( 0 ); const SMDS_MeshNode* aNode1 = anEdge->GetNode( 1 ); if ( aNode1 == aLastNode ) aNode1 = 0; SMDS_ElemIteratorPtr anElemIter = aLastNode->GetInverseElementIterator(); while( anElemIter->more() ) { const SMDS_MeshElement* anElem = anElemIter->next(); if ( anElem != 0 && anElem->GetType() != SMDSAbs_Edge ) { SMDS_ElemIteratorPtr anIter = anElem->nodesIterator(); while ( anIter->more() ) { if ( const SMDS_MeshElement* anElemNode = anIter->next() ) { if ( anElemNode == aNode0 ) { aResult0++; if ( !aNode1 ) break; // not a quadratic edge } else if ( anElemNode == aNode1 ) aResult1++; } } } } int aResult = std::max ( aResult0, aResult1 ); return aResult; } gp_XYZ getNormale( const SMDS_MeshFace* theFace, bool* ok=0 ) { int aNbNode = theFace->NbNodes(); gp_XYZ q1 = gpXYZ( theFace->GetNode(1)) - gpXYZ( theFace->GetNode(0)); gp_XYZ q2 = gpXYZ( theFace->GetNode(2)) - gpXYZ( theFace->GetNode(0)); gp_XYZ n = q1 ^ q2; if ( aNbNode > 3 ) { gp_XYZ q3 = gpXYZ( theFace->GetNode(3)) - gpXYZ( theFace->GetNode(0)); n += q2 ^ q3; } double len = n.Modulus(); bool zeroLen = ( len <= numeric_limits<double>::min()); if ( !zeroLen ) n /= len; if (ok) *ok = !zeroLen; return n; } } using namespace SMESH::Controls; /* * FUNCTORS */ //================================================================================ /* Class : NumericalFunctor Description : Base class for numerical functors */ //================================================================================ NumericalFunctor::NumericalFunctor(): myMesh(NULL) { myPrecision = -1; } void NumericalFunctor::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } bool NumericalFunctor::GetPoints(const int theId, TSequenceOfXYZ& theRes ) const { theRes.clear(); if ( myMesh == 0 ) return false; const SMDS_MeshElement* anElem = myMesh->FindElement( theId ); if ( !anElem || anElem->GetType() != this->GetType() ) return false; return GetPoints( anElem, theRes ); } bool NumericalFunctor::GetPoints(const SMDS_MeshElement* anElem, TSequenceOfXYZ& theRes ) { theRes.clear(); if ( anElem == 0 ) return false; theRes.reserve( anElem->NbNodes() ); theRes.setElement( anElem ); // Get nodes of the element SMDS_ElemIteratorPtr anIter; if ( anElem->IsQuadratic() ) { switch ( anElem->GetType() ) { case SMDSAbs_Edge: anIter = dynamic_cast<const SMDS_VtkEdge*> (anElem)->interlacedNodesElemIterator(); break; case SMDSAbs_Face: anIter = dynamic_cast<const SMDS_VtkFace*> (anElem)->interlacedNodesElemIterator(); break; default: anIter = anElem->nodesIterator(); } } else { anIter = anElem->nodesIterator(); } if ( anIter ) { double xyz[3]; while( anIter->more() ) { if ( const SMDS_MeshNode* aNode = static_cast<const SMDS_MeshNode*>( anIter->next() )) { aNode->GetXYZ( xyz ); theRes.push_back( gp_XYZ( xyz[0], xyz[1], xyz[2] )); } } } return true; } long NumericalFunctor::GetPrecision() const { return myPrecision; } void NumericalFunctor::SetPrecision( const long thePrecision ) { myPrecision = thePrecision; myPrecisionValue = pow( 10., (double)( myPrecision ) ); } double NumericalFunctor::GetValue( long theId ) { double aVal = 0; myCurrElement = myMesh->FindElement( theId ); TSequenceOfXYZ P; if ( GetPoints( theId, P )) // elem type is checked here aVal = Round( GetValue( P )); return aVal; } double NumericalFunctor::Round( const double & aVal ) { return ( myPrecision >= 0 ) ? floor( aVal * myPrecisionValue + 0.5 ) / myPrecisionValue : aVal; } //================================================================================ /*! * \brief Return histogram of functor values * \param nbIntervals - number of intervals * \param nbEvents - number of mesh elements having values within i-th interval * \param funValues - boundaries of intervals * \param elements - elements to check vulue of; empty list means "of all" * \param minmax - boundaries of diapason of values to divide into intervals */ //================================================================================ void NumericalFunctor::GetHistogram(int nbIntervals, std::vector<int>& nbEvents, std::vector<double>& funValues, const vector<int>& elements, const double* minmax, const bool isLogarithmic) { if ( nbIntervals < 1 || !myMesh || !myMesh->GetMeshInfo().NbElements( GetType() )) return; nbEvents.resize( nbIntervals, 0 ); funValues.resize( nbIntervals+1 ); // get all values sorted std::multiset< double > values; if ( elements.empty() ) { SMDS_ElemIteratorPtr elemIt = myMesh->elementsIterator( GetType() ); while ( elemIt->more() ) values.insert( GetValue( elemIt->next()->GetID() )); } else { vector<int>::const_iterator id = elements.begin(); for ( ; id != elements.end(); ++id ) values.insert( GetValue( *id )); } if ( minmax ) { funValues[0] = minmax[0]; funValues[nbIntervals] = minmax[1]; } else { funValues[0] = *values.begin(); funValues[nbIntervals] = *values.rbegin(); } // case nbIntervals == 1 if ( nbIntervals == 1 ) { nbEvents[0] = values.size(); return; } // case of 1 value if (funValues.front() == funValues.back()) { nbEvents.resize( 1 ); nbEvents[0] = values.size(); funValues[1] = funValues.back(); funValues.resize( 2 ); } // generic case std::multiset< double >::iterator min = values.begin(), max; for ( int i = 0; i < nbIntervals; ++i ) { // find end value of i-th interval double r = (i+1) / double(nbIntervals); if (isLogarithmic && funValues.front() > 1e-07 && funValues.back() > 1e-07) { double logmin = log10(funValues.front()); double lval = logmin + r * (log10(funValues.back()) - logmin); funValues[i+1] = pow(10.0, lval); } else { funValues[i+1] = funValues.front() * (1-r) + funValues.back() * r; } // count values in the i-th interval if there are any if ( min != values.end() && *min <= funValues[i+1] ) { // find the first value out of the interval max = values.upper_bound( funValues[i+1] ); // max is greater than funValues[i+1], or end() nbEvents[i] = std::distance( min, max ); min = max; } } // add values larger than minmax[1] nbEvents.back() += std::distance( min, values.end() ); } //======================================================================= /* Class : Volume Description : Functor calculating volume of a 3D element */ //================================================================================ double Volume::GetValue( long theElementId ) { if ( theElementId && myMesh ) { SMDS_VolumeTool aVolumeTool; if ( aVolumeTool.Set( myMesh->FindElement( theElementId ))) return aVolumeTool.GetSize(); } return 0; } double Volume::GetBadRate( double Value, int /*nbNodes*/ ) const { return Value; } SMDSAbs_ElementType Volume::GetType() const { return SMDSAbs_Volume; } //======================================================================= /* Class : MaxElementLength2D Description : Functor calculating maximum length of 2D element */ //================================================================================ double MaxElementLength2D::GetValue( const TSequenceOfXYZ& P ) { if(P.size() == 0) return 0.; double aVal = 0; int len = P.size(); if( len == 3 ) { // triangles double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 1 )); aVal = Max(L1,Max(L2,L3)); } else if( len == 4 ) { // quadrangles double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 1 )); double D1 = getDistance(P( 1 ),P( 3 )); double D2 = getDistance(P( 2 ),P( 4 )); aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(D1,D2)); } else if( len == 6 ) { // quadratic triangles double L1 = getDistance(P( 1 ),P( 2 )) + getDistance(P( 2 ),P( 3 )); double L2 = getDistance(P( 3 ),P( 4 )) + getDistance(P( 4 ),P( 5 )); double L3 = getDistance(P( 5 ),P( 6 )) + getDistance(P( 6 ),P( 1 )); aVal = Max(L1,Max(L2,L3)); } else if( len == 8 || len == 9 ) { // quadratic quadrangles double L1 = getDistance(P( 1 ),P( 2 )) + getDistance(P( 2 ),P( 3 )); double L2 = getDistance(P( 3 ),P( 4 )) + getDistance(P( 4 ),P( 5 )); double L3 = getDistance(P( 5 ),P( 6 )) + getDistance(P( 6 ),P( 7 )); double L4 = getDistance(P( 7 ),P( 8 )) + getDistance(P( 8 ),P( 1 )); double D1 = getDistance(P( 1 ),P( 5 )); double D2 = getDistance(P( 3 ),P( 7 )); aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(D1,D2)); } // Diagonals are undefined for concave polygons // else if ( P.getElementEntity() == SMDSEntity_Quad_Polygon && P.size() > 2 ) // quad polygon // { // // sides // aVal = getDistance( P( 1 ), P( P.size() )) + getDistance( P( P.size() ), P( P.size()-1 )); // for ( size_t i = 1; i < P.size()-1; i += 2 ) // { // double L = getDistance( P( i ), P( i+1 )) + getDistance( P( i+1 ), P( i+2 )); // aVal = Max( aVal, L ); // } // // diagonals // for ( int i = P.size()-5; i > 0; i -= 2 ) // for ( int j = i + 4; j < P.size() + i - 2; i += 2 ) // { // double D = getDistance( P( i ), P( j )); // aVal = Max( aVal, D ); // } // } // { // polygons // } if( myPrecision >= 0 ) { double prec = pow( 10., (double)myPrecision ); aVal = floor( aVal * prec + 0.5 ) / prec; } return aVal; } double MaxElementLength2D::GetValue( long theElementId ) { TSequenceOfXYZ P; return GetPoints( theElementId, P ) ? GetValue(P) : 0.0; } double MaxElementLength2D::GetBadRate( double Value, int /*nbNodes*/ ) const { return Value; } SMDSAbs_ElementType MaxElementLength2D::GetType() const { return SMDSAbs_Face; } //======================================================================= /* Class : MaxElementLength3D Description : Functor calculating maximum length of 3D element */ //================================================================================ double MaxElementLength3D::GetValue( long theElementId ) { TSequenceOfXYZ P; if( GetPoints( theElementId, P ) ) { double aVal = 0; const SMDS_MeshElement* aElem = myMesh->FindElement( theElementId ); SMDSAbs_ElementType aType = aElem->GetType(); int len = P.size(); switch( aType ) { case SMDSAbs_Volume: if( len == 4 ) { // tetras double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 1 )); double L4 = getDistance(P( 1 ),P( 4 )); double L5 = getDistance(P( 2 ),P( 4 )); double L6 = getDistance(P( 3 ),P( 4 )); aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6)); break; } else if( len == 5 ) { // pyramids double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 1 )); double L5 = getDistance(P( 1 ),P( 5 )); double L6 = getDistance(P( 2 ),P( 5 )); double L7 = getDistance(P( 3 ),P( 5 )); double L8 = getDistance(P( 4 ),P( 5 )); aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6)); aVal = Max(aVal,Max(L7,L8)); break; } else if( len == 6 ) { // pentas double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 1 )); double L4 = getDistance(P( 4 ),P( 5 )); double L5 = getDistance(P( 5 ),P( 6 )); double L6 = getDistance(P( 6 ),P( 4 )); double L7 = getDistance(P( 1 ),P( 4 )); double L8 = getDistance(P( 2 ),P( 5 )); double L9 = getDistance(P( 3 ),P( 6 )); aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6)); aVal = Max(aVal,Max(Max(L7,L8),L9)); break; } else if( len == 8 ) { // hexas double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 1 )); double L5 = getDistance(P( 5 ),P( 6 )); double L6 = getDistance(P( 6 ),P( 7 )); double L7 = getDistance(P( 7 ),P( 8 )); double L8 = getDistance(P( 8 ),P( 5 )); double L9 = getDistance(P( 1 ),P( 5 )); double L10= getDistance(P( 2 ),P( 6 )); double L11= getDistance(P( 3 ),P( 7 )); double L12= getDistance(P( 4 ),P( 8 )); double D1 = getDistance(P( 1 ),P( 7 )); double D2 = getDistance(P( 2 ),P( 8 )); double D3 = getDistance(P( 3 ),P( 5 )); double D4 = getDistance(P( 4 ),P( 6 )); aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6)); aVal = Max(aVal,Max(Max(L7,L8),Max(L9,L10))); aVal = Max(aVal,Max(L11,L12)); aVal = Max(aVal,Max(Max(D1,D2),Max(D3,D4))); break; } else if( len == 12 ) { // hexagonal prism for ( int i1 = 1; i1 < 12; ++i1 ) for ( int i2 = i1+1; i1 <= 12; ++i1 ) aVal = Max( aVal, getDistance(P( i1 ),P( i2 ))); break; } else if( len == 10 ) { // quadratic tetras double L1 = getDistance(P( 1 ),P( 5 )) + getDistance(P( 5 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 6 )) + getDistance(P( 6 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 7 )) + getDistance(P( 7 ),P( 1 )); double L4 = getDistance(P( 1 ),P( 8 )) + getDistance(P( 8 ),P( 4 )); double L5 = getDistance(P( 2 ),P( 9 )) + getDistance(P( 9 ),P( 4 )); double L6 = getDistance(P( 3 ),P( 10 )) + getDistance(P( 10 ),P( 4 )); aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6)); break; } else if( len == 13 ) { // quadratic pyramids double L1 = getDistance(P( 1 ),P( 6 )) + getDistance(P( 6 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 7 )) + getDistance(P( 7 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 8 )) + getDistance(P( 8 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 9 )) + getDistance(P( 9 ),P( 1 )); double L5 = getDistance(P( 1 ),P( 10 )) + getDistance(P( 10 ),P( 5 )); double L6 = getDistance(P( 2 ),P( 11 )) + getDistance(P( 11 ),P( 5 )); double L7 = getDistance(P( 3 ),P( 12 )) + getDistance(P( 12 ),P( 5 )); double L8 = getDistance(P( 4 ),P( 13 )) + getDistance(P( 13 ),P( 5 )); aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6)); aVal = Max(aVal,Max(L7,L8)); break; } else if( len == 15 ) { // quadratic pentas double L1 = getDistance(P( 1 ),P( 7 )) + getDistance(P( 7 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 8 )) + getDistance(P( 8 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 9 )) + getDistance(P( 9 ),P( 1 )); double L4 = getDistance(P( 4 ),P( 10 )) + getDistance(P( 10 ),P( 5 )); double L5 = getDistance(P( 5 ),P( 11 )) + getDistance(P( 11 ),P( 6 )); double L6 = getDistance(P( 6 ),P( 12 )) + getDistance(P( 12 ),P( 4 )); double L7 = getDistance(P( 1 ),P( 13 )) + getDistance(P( 13 ),P( 4 )); double L8 = getDistance(P( 2 ),P( 14 )) + getDistance(P( 14 ),P( 5 )); double L9 = getDistance(P( 3 ),P( 15 )) + getDistance(P( 15 ),P( 6 )); aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6)); aVal = Max(aVal,Max(Max(L7,L8),L9)); break; } else if( len == 20 || len == 27 ) { // quadratic hexas double L1 = getDistance(P( 1 ),P( 9 )) + getDistance(P( 9 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 10 )) + getDistance(P( 10 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 11 )) + getDistance(P( 11 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 12 )) + getDistance(P( 12 ),P( 1 )); double L5 = getDistance(P( 5 ),P( 13 )) + getDistance(P( 13 ),P( 6 )); double L6 = getDistance(P( 6 ),P( 14 )) + getDistance(P( 14 ),P( 7 )); double L7 = getDistance(P( 7 ),P( 15 )) + getDistance(P( 15 ),P( 8 )); double L8 = getDistance(P( 8 ),P( 16 )) + getDistance(P( 16 ),P( 5 )); double L9 = getDistance(P( 1 ),P( 17 )) + getDistance(P( 17 ),P( 5 )); double L10= getDistance(P( 2 ),P( 18 )) + getDistance(P( 18 ),P( 6 )); double L11= getDistance(P( 3 ),P( 19 )) + getDistance(P( 19 ),P( 7 )); double L12= getDistance(P( 4 ),P( 20 )) + getDistance(P( 20 ),P( 8 )); double D1 = getDistance(P( 1 ),P( 7 )); double D2 = getDistance(P( 2 ),P( 8 )); double D3 = getDistance(P( 3 ),P( 5 )); double D4 = getDistance(P( 4 ),P( 6 )); aVal = Max(Max(Max(L1,L2),Max(L3,L4)),Max(L5,L6)); aVal = Max(aVal,Max(Max(L7,L8),Max(L9,L10))); aVal = Max(aVal,Max(L11,L12)); aVal = Max(aVal,Max(Max(D1,D2),Max(D3,D4))); break; } else if( len > 1 && aElem->IsPoly() ) { // polys // get the maximum distance between all pairs of nodes for( int i = 1; i <= len; i++ ) { for( int j = 1; j <= len; j++ ) { if( j > i ) { // optimization of the loop double D = getDistance( P(i), P(j) ); aVal = Max( aVal, D ); } } } } } if( myPrecision >= 0 ) { double prec = pow( 10., (double)myPrecision ); aVal = floor( aVal * prec + 0.5 ) / prec; } return aVal; } return 0.; } double MaxElementLength3D::GetBadRate( double Value, int /*nbNodes*/ ) const { return Value; } SMDSAbs_ElementType MaxElementLength3D::GetType() const { return SMDSAbs_Volume; } //======================================================================= /* Class : MinimumAngle Description : Functor for calculation of minimum angle */ //================================================================================ double MinimumAngle::GetValue( const TSequenceOfXYZ& P ) { double aMin; if (P.size() <3) return 0.; aMin = getAngle(P( P.size() ), P( 1 ), P( 2 )); aMin = Min(aMin,getAngle(P( P.size()-1 ), P( P.size() ), P( 1 ))); for ( int i = 2; i < P.size(); i++ ) { double A0 = getAngle( P( i-1 ), P( i ), P( i+1 ) ); aMin = Min(aMin,A0); } return aMin * 180.0 / M_PI; } double MinimumAngle::GetBadRate( double Value, int nbNodes ) const { //const double aBestAngle = PI / nbNodes; const double aBestAngle = 180.0 - ( 360.0 / double(nbNodes) ); return ( fabs( aBestAngle - Value )); } SMDSAbs_ElementType MinimumAngle::GetType() const { return SMDSAbs_Face; } //================================================================================ /* Class : AspectRatio Description : Functor for calculating aspect ratio */ //================================================================================ double AspectRatio::GetValue( long theId ) { double aVal = 0; myCurrElement = myMesh->FindElement( theId ); if ( myCurrElement && myCurrElement->GetVtkType() == VTK_QUAD ) { // issue 21723 vtkUnstructuredGrid* grid = SMDS_Mesh::_meshList[myCurrElement->getMeshId()]->getGrid(); if ( vtkCell* avtkCell = grid->GetCell( myCurrElement->getVtkId() )) aVal = Round( vtkMeshQuality::QuadAspectRatio( avtkCell )); } else { TSequenceOfXYZ P; if ( GetPoints( myCurrElement, P )) aVal = Round( GetValue( P )); } return aVal; } double AspectRatio::GetValue( const TSequenceOfXYZ& P ) { // According to "Mesh quality control" by Nadir Bouhamau referring to // Pascal Jean Frey and Paul-Louis George. Maillages, applications aux elements finis. // Hermes Science publications, Paris 1999 ISBN 2-7462-0024-4 // PAL10872 int nbNodes = P.size(); if ( nbNodes < 3 ) return 0; // Compute aspect ratio if ( nbNodes == 3 ) { // Compute lengths of the sides std::vector< double > aLen (nbNodes); for ( int i = 0; i < nbNodes - 1; i++ ) aLen[ i ] = getDistance( P( i + 1 ), P( i + 2 ) ); aLen[ nbNodes - 1 ] = getDistance( P( 1 ), P( nbNodes ) ); // Q = alfa * h * p / S, where // // alfa = sqrt( 3 ) / 6 // h - length of the longest edge // p - half perimeter // S - triangle surface const double alfa = sqrt( 3. ) / 6.; double maxLen = Max( aLen[ 0 ], Max( aLen[ 1 ], aLen[ 2 ] ) ); double half_perimeter = ( aLen[0] + aLen[1] + aLen[2] ) / 2.; double anArea = getArea( P( 1 ), P( 2 ), P( 3 ) ); if ( anArea <= theEps ) return theInf; return alfa * maxLen * half_perimeter / anArea; } else if ( nbNodes == 6 ) { // quadratic triangles // Compute lengths of the sides std::vector< double > aLen (3); aLen[0] = getDistance( P(1), P(3) ); aLen[1] = getDistance( P(3), P(5) ); aLen[2] = getDistance( P(5), P(1) ); // Q = alfa * h * p / S, where // // alfa = sqrt( 3 ) / 6 // h - length of the longest edge // p - half perimeter // S - triangle surface const double alfa = sqrt( 3. ) / 6.; double maxLen = Max( aLen[ 0 ], Max( aLen[ 1 ], aLen[ 2 ] ) ); double half_perimeter = ( aLen[0] + aLen[1] + aLen[2] ) / 2.; double anArea = getArea( P(1), P(3), P(5) ); if ( anArea <= theEps ) return theInf; return alfa * maxLen * half_perimeter / anArea; } else if( nbNodes == 4 ) { // quadrangle // Compute lengths of the sides std::vector< double > aLen (4); aLen[0] = getDistance( P(1), P(2) ); aLen[1] = getDistance( P(2), P(3) ); aLen[2] = getDistance( P(3), P(4) ); aLen[3] = getDistance( P(4), P(1) ); // Compute lengths of the diagonals std::vector< double > aDia (2); aDia[0] = getDistance( P(1), P(3) ); aDia[1] = getDistance( P(2), P(4) ); // Compute areas of all triangles which can be built // taking three nodes of the quadrangle std::vector< double > anArea (4); anArea[0] = getArea( P(1), P(2), P(3) ); anArea[1] = getArea( P(1), P(2), P(4) ); anArea[2] = getArea( P(1), P(3), P(4) ); anArea[3] = getArea( P(2), P(3), P(4) ); // Q = alpha * L * C1 / C2, where // // alpha = sqrt( 1/32 ) // L = max( L1, L2, L3, L4, D1, D2 ) // C1 = sqrt( ( L1^2 + L1^2 + L1^2 + L1^2 ) / 4 ) // C2 = min( S1, S2, S3, S4 ) // Li - lengths of the edges // Di - lengths of the diagonals // Si - areas of the triangles const double alpha = sqrt( 1 / 32. ); double L = Max( aLen[ 0 ], Max( aLen[ 1 ], Max( aLen[ 2 ], Max( aLen[ 3 ], Max( aDia[ 0 ], aDia[ 1 ] ) ) ) ) ); double C1 = sqrt( ( aLen[0] * aLen[0] + aLen[1] * aLen[1] + aLen[2] * aLen[2] + aLen[3] * aLen[3] ) / 4. ); double C2 = Min( anArea[ 0 ], Min( anArea[ 1 ], Min( anArea[ 2 ], anArea[ 3 ] ) ) ); if ( C2 <= theEps ) return theInf; return alpha * L * C1 / C2; } else if( nbNodes == 8 || nbNodes == 9 ) { // nbNodes==8 - quadratic quadrangle // Compute lengths of the sides std::vector< double > aLen (4); aLen[0] = getDistance( P(1), P(3) ); aLen[1] = getDistance( P(3), P(5) ); aLen[2] = getDistance( P(5), P(7) ); aLen[3] = getDistance( P(7), P(1) ); // Compute lengths of the diagonals std::vector< double > aDia (2); aDia[0] = getDistance( P(1), P(5) ); aDia[1] = getDistance( P(3), P(7) ); // Compute areas of all triangles which can be built // taking three nodes of the quadrangle std::vector< double > anArea (4); anArea[0] = getArea( P(1), P(3), P(5) ); anArea[1] = getArea( P(1), P(3), P(7) ); anArea[2] = getArea( P(1), P(5), P(7) ); anArea[3] = getArea( P(3), P(5), P(7) ); // Q = alpha * L * C1 / C2, where // // alpha = sqrt( 1/32 ) // L = max( L1, L2, L3, L4, D1, D2 ) // C1 = sqrt( ( L1^2 + L1^2 + L1^2 + L1^2 ) / 4 ) // C2 = min( S1, S2, S3, S4 ) // Li - lengths of the edges // Di - lengths of the diagonals // Si - areas of the triangles const double alpha = sqrt( 1 / 32. ); double L = Max( aLen[ 0 ], Max( aLen[ 1 ], Max( aLen[ 2 ], Max( aLen[ 3 ], Max( aDia[ 0 ], aDia[ 1 ] ) ) ) ) ); double C1 = sqrt( ( aLen[0] * aLen[0] + aLen[1] * aLen[1] + aLen[2] * aLen[2] + aLen[3] * aLen[3] ) / 4. ); double C2 = Min( anArea[ 0 ], Min( anArea[ 1 ], Min( anArea[ 2 ], anArea[ 3 ] ) ) ); if ( C2 <= theEps ) return theInf; return alpha * L * C1 / C2; } return 0; } double AspectRatio::GetBadRate( double Value, int /*nbNodes*/ ) const { // the aspect ratio is in the range [1.0,infinity] // < 1.0 = very bad, zero area // 1.0 = good // infinity = bad return ( Value < 0.9 ) ? 1000 : Value / 1000.; } SMDSAbs_ElementType AspectRatio::GetType() const { return SMDSAbs_Face; } //================================================================================ /* Class : AspectRatio3D Description : Functor for calculating aspect ratio */ //================================================================================ namespace{ inline double getHalfPerimeter(double theTria[3]){ return (theTria[0] + theTria[1] + theTria[2])/2.0; } inline double getArea(double theHalfPerim, double theTria[3]){ return sqrt(theHalfPerim* (theHalfPerim-theTria[0])* (theHalfPerim-theTria[1])* (theHalfPerim-theTria[2])); } inline double getVolume(double theLen[6]){ double a2 = theLen[0]*theLen[0]; double b2 = theLen[1]*theLen[1]; double c2 = theLen[2]*theLen[2]; double d2 = theLen[3]*theLen[3]; double e2 = theLen[4]*theLen[4]; double f2 = theLen[5]*theLen[5]; double P = 4.0*a2*b2*d2; double Q = a2*(b2+d2-e2)-b2*(a2+d2-f2)-d2*(a2+b2-c2); double R = (b2+d2-e2)*(a2+d2-f2)*(a2+d2-f2); return sqrt(P-Q+R)/12.0; } inline double getVolume2(double theLen[6]){ double a2 = theLen[0]*theLen[0]; double b2 = theLen[1]*theLen[1]; double c2 = theLen[2]*theLen[2]; double d2 = theLen[3]*theLen[3]; double e2 = theLen[4]*theLen[4]; double f2 = theLen[5]*theLen[5]; double P = a2*e2*(b2+c2+d2+f2-a2-e2); double Q = b2*f2*(a2+c2+d2+e2-b2-f2); double R = c2*d2*(a2+b2+e2+f2-c2-d2); double S = a2*b2*d2+b2*c2*e2+a2*c2*f2+d2*e2*f2; return sqrt(P+Q+R-S)/12.0; } inline double getVolume(const TSequenceOfXYZ& P){ gp_Vec aVec1( P( 2 ) - P( 1 ) ); gp_Vec aVec2( P( 3 ) - P( 1 ) ); gp_Vec aVec3( P( 4 ) - P( 1 ) ); gp_Vec anAreaVec( aVec1 ^ aVec2 ); return fabs(aVec3 * anAreaVec) / 6.0; } inline double getMaxHeight(double theLen[6]) { double aHeight = std::max(theLen[0],theLen[1]); aHeight = std::max(aHeight,theLen[2]); aHeight = std::max(aHeight,theLen[3]); aHeight = std::max(aHeight,theLen[4]); aHeight = std::max(aHeight,theLen[5]); return aHeight; } } double AspectRatio3D::GetValue( long theId ) { double aVal = 0; myCurrElement = myMesh->FindElement( theId ); if ( myCurrElement && myCurrElement->GetVtkType() == VTK_TETRA ) { // Action from CoTech | ACTION 31.3: // EURIWARE BO: Homogenize the formulas used to calculate the Controls in SMESH to fit with // those of ParaView. The library used by ParaView for those calculations can be reused in SMESH. vtkUnstructuredGrid* grid = SMDS_Mesh::_meshList[myCurrElement->getMeshId()]->getGrid(); if ( vtkCell* avtkCell = grid->GetCell( myCurrElement->getVtkId() )) aVal = Round( vtkMeshQuality::TetAspectRatio( avtkCell )); } else { TSequenceOfXYZ P; if ( GetPoints( myCurrElement, P )) aVal = Round( GetValue( P )); } return aVal; } double AspectRatio3D::GetValue( const TSequenceOfXYZ& P ) { double aQuality = 0.0; if(myCurrElement->IsPoly()) return aQuality; int nbNodes = P.size(); if(myCurrElement->IsQuadratic()) { if(nbNodes==10) nbNodes=4; // quadratic tetrahedron else if(nbNodes==13) nbNodes=5; // quadratic pyramid else if(nbNodes==15) nbNodes=6; // quadratic pentahedron else if(nbNodes==20) nbNodes=8; // quadratic hexahedron else if(nbNodes==27) nbNodes=8; // quadratic hexahedron else return aQuality; } switch(nbNodes) { case 4:{ double aLen[6] = { getDistance(P( 1 ),P( 2 )), // a getDistance(P( 2 ),P( 3 )), // b getDistance(P( 3 ),P( 1 )), // c getDistance(P( 2 ),P( 4 )), // d getDistance(P( 3 ),P( 4 )), // e getDistance(P( 1 ),P( 4 )) // f }; double aTria[4][3] = { {aLen[0],aLen[1],aLen[2]}, // abc {aLen[0],aLen[3],aLen[5]}, // adf {aLen[1],aLen[3],aLen[4]}, // bde {aLen[2],aLen[4],aLen[5]} // cef }; double aSumArea = 0.0; double aHalfPerimeter = getHalfPerimeter(aTria[0]); double anArea = getArea(aHalfPerimeter,aTria[0]); aSumArea += anArea; aHalfPerimeter = getHalfPerimeter(aTria[1]); anArea = getArea(aHalfPerimeter,aTria[1]); aSumArea += anArea; aHalfPerimeter = getHalfPerimeter(aTria[2]); anArea = getArea(aHalfPerimeter,aTria[2]); aSumArea += anArea; aHalfPerimeter = getHalfPerimeter(aTria[3]); anArea = getArea(aHalfPerimeter,aTria[3]); aSumArea += anArea; double aVolume = getVolume(P); //double aVolume = getVolume(aLen); double aHeight = getMaxHeight(aLen); static double aCoeff = sqrt(2.0)/12.0; if ( aVolume > DBL_MIN ) aQuality = aCoeff*aHeight*aSumArea/aVolume; break; } case 5:{ { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 3 ),P( 5 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 3 ),P( 4 ),P( 5 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 4 ),P( 5 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 2 ),P( 3 ),P( 4 ),P( 5 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } break; } case 6:{ { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 4 ),P( 6 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 4 ),P( 3 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 6 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 3 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 2 ),P( 5 ),P( 4 ),P( 6 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 2 ),P( 5 ),P( 4 ),P( 3 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } break; } case 8:{ { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 3 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 4 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 7 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 5 ),P( 8 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 6 ),P( 3 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 6 ),P( 4 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 6 ),P( 7 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 6 ),P( 8 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 2 ),P( 6 ),P( 5 ),P( 3 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 2 ),P( 6 ),P( 5 ),P( 4 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 2 ),P( 6 ),P( 5 ),P( 7 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 2 ),P( 6 ),P( 5 ),P( 8 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 8 ),P( 1 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 8 ),P( 2 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 8 ),P( 5 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 8 ),P( 6 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 7 ),P( 1 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 7 ),P( 2 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 7 ),P( 5 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 7 ),P( 6 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 4 ),P( 8 ),P( 7 ),P( 1 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 4 ),P( 8 ),P( 7 ),P( 2 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 4 ),P( 8 ),P( 7 ),P( 5 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 4 ),P( 8 ),P( 7 ),P( 6 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 4 ),P( 8 ),P( 7 ),P( 2 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 4 ),P( 5 ),P( 8 ),P( 2 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 4 ),P( 5 ),P( 3 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 3 ),P( 6 ),P( 7 ),P( 1 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 2 ),P( 3 ),P( 6 ),P( 4 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 5 ),P( 6 ),P( 8 ),P( 3 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 7 ),P( 8 ),P( 6 ),P( 1 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 1 ),P( 2 ),P( 4 ),P( 7 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } { gp_XYZ aXYZ[4] = {P( 3 ),P( 4 ),P( 2 ),P( 5 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[4])),aQuality); } break; } case 12: { gp_XYZ aXYZ[8] = {P( 1 ),P( 2 ),P( 4 ),P( 5 ),P( 7 ),P( 8 ),P( 10 ),P( 11 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[8])),aQuality); } { gp_XYZ aXYZ[8] = {P( 2 ),P( 3 ),P( 5 ),P( 6 ),P( 8 ),P( 9 ),P( 11 ),P( 12 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[8])),aQuality); } { gp_XYZ aXYZ[8] = {P( 3 ),P( 4 ),P( 6 ),P( 1 ),P( 9 ),P( 10 ),P( 12 ),P( 7 )}; aQuality = std::max(GetValue(TSequenceOfXYZ(&aXYZ[0],&aXYZ[8])),aQuality); } break; } // switch(nbNodes) if ( nbNodes > 4 ) { // avaluate aspect ratio of quadranle faces AspectRatio aspect2D; SMDS_VolumeTool::VolumeType type = SMDS_VolumeTool::GetType( nbNodes ); int nbFaces = SMDS_VolumeTool::NbFaces( type ); TSequenceOfXYZ points(4); for ( int i = 0; i < nbFaces; ++i ) { // loop on faces of a volume if ( SMDS_VolumeTool::NbFaceNodes( type, i ) != 4 ) continue; const int* pInd = SMDS_VolumeTool::GetFaceNodesIndices( type, i, true ); for ( int p = 0; p < 4; ++p ) // loop on nodes of a quadranle face points( p + 1 ) = P( pInd[ p ] + 1 ); aQuality = std::max( aQuality, aspect2D.GetValue( points )); } } return aQuality; } double AspectRatio3D::GetBadRate( double Value, int /*nbNodes*/ ) const { // the aspect ratio is in the range [1.0,infinity] // 1.0 = good // infinity = bad return Value / 1000.; } SMDSAbs_ElementType AspectRatio3D::GetType() const { return SMDSAbs_Volume; } //================================================================================ /* Class : Warping Description : Functor for calculating warping */ //================================================================================ double Warping::GetValue( const TSequenceOfXYZ& P ) { if ( P.size() != 4 ) return 0; gp_XYZ G = ( P( 1 ) + P( 2 ) + P( 3 ) + P( 4 ) ) / 4.; double A1 = ComputeA( P( 1 ), P( 2 ), P( 3 ), G ); double A2 = ComputeA( P( 2 ), P( 3 ), P( 4 ), G ); double A3 = ComputeA( P( 3 ), P( 4 ), P( 1 ), G ); double A4 = ComputeA( P( 4 ), P( 1 ), P( 2 ), G ); double val = Max( Max( A1, A2 ), Max( A3, A4 ) ); const double eps = 0.1; // val is in degrees return val < eps ? 0. : val; } double Warping::ComputeA( const gp_XYZ& thePnt1, const gp_XYZ& thePnt2, const gp_XYZ& thePnt3, const gp_XYZ& theG ) const { double aLen1 = gp_Pnt( thePnt1 ).Distance( gp_Pnt( thePnt2 ) ); double aLen2 = gp_Pnt( thePnt2 ).Distance( gp_Pnt( thePnt3 ) ); double L = Min( aLen1, aLen2 ) * 0.5; if ( L < theEps ) return theInf; gp_XYZ GI = ( thePnt2 + thePnt1 ) / 2. - theG; gp_XYZ GJ = ( thePnt3 + thePnt2 ) / 2. - theG; gp_XYZ N = GI.Crossed( GJ ); if ( N.Modulus() < gp::Resolution() ) return M_PI / 2; N.Normalize(); double H = ( thePnt2 - theG ).Dot( N ); return asin( fabs( H / L ) ) * 180. / M_PI; } double Warping::GetBadRate( double Value, int /*nbNodes*/ ) const { // the warp is in the range [0.0,PI/2] // 0.0 = good (no warp) // PI/2 = bad (face pliee) return Value; } SMDSAbs_ElementType Warping::GetType() const { return SMDSAbs_Face; } //================================================================================ /* Class : Taper Description : Functor for calculating taper */ //================================================================================ double Taper::GetValue( const TSequenceOfXYZ& P ) { if ( P.size() != 4 ) return 0.; // Compute taper double J1 = getArea( P( 4 ), P( 1 ), P( 2 ) ); double J2 = getArea( P( 3 ), P( 1 ), P( 2 ) ); double J3 = getArea( P( 2 ), P( 3 ), P( 4 ) ); double J4 = getArea( P( 3 ), P( 4 ), P( 1 ) ); double JA = 0.25 * ( J1 + J2 + J3 + J4 ); if ( JA <= theEps ) return theInf; double T1 = fabs( ( J1 - JA ) / JA ); double T2 = fabs( ( J2 - JA ) / JA ); double T3 = fabs( ( J3 - JA ) / JA ); double T4 = fabs( ( J4 - JA ) / JA ); double val = Max( Max( T1, T2 ), Max( T3, T4 ) ); const double eps = 0.01; return val < eps ? 0. : val; } double Taper::GetBadRate( double Value, int /*nbNodes*/ ) const { // the taper is in the range [0.0,1.0] // 0.0 = good (no taper) // 1.0 = bad (les cotes opposes sont allignes) return Value; } SMDSAbs_ElementType Taper::GetType() const { return SMDSAbs_Face; } //================================================================================ /* Class : Skew Description : Functor for calculating skew in degrees */ //================================================================================ static inline double skewAngle( const gp_XYZ& p1, const gp_XYZ& p2, const gp_XYZ& p3 ) { gp_XYZ p12 = ( p2 + p1 ) / 2.; gp_XYZ p23 = ( p3 + p2 ) / 2.; gp_XYZ p31 = ( p3 + p1 ) / 2.; gp_Vec v1( p31 - p2 ), v2( p12 - p23 ); return v1.Magnitude() < gp::Resolution() || v2.Magnitude() < gp::Resolution() ? 0. : v1.Angle( v2 ); } double Skew::GetValue( const TSequenceOfXYZ& P ) { if ( P.size() != 3 && P.size() != 4 ) return 0.; // Compute skew const double PI2 = M_PI / 2.; if ( P.size() == 3 ) { double A0 = fabs( PI2 - skewAngle( P( 3 ), P( 1 ), P( 2 ) ) ); double A1 = fabs( PI2 - skewAngle( P( 1 ), P( 2 ), P( 3 ) ) ); double A2 = fabs( PI2 - skewAngle( P( 2 ), P( 3 ), P( 1 ) ) ); return Max( A0, Max( A1, A2 ) ) * 180. / M_PI; } else { gp_XYZ p12 = ( P( 1 ) + P( 2 ) ) / 2.; gp_XYZ p23 = ( P( 2 ) + P( 3 ) ) / 2.; gp_XYZ p34 = ( P( 3 ) + P( 4 ) ) / 2.; gp_XYZ p41 = ( P( 4 ) + P( 1 ) ) / 2.; gp_Vec v1( p34 - p12 ), v2( p23 - p41 ); double A = v1.Magnitude() <= gp::Resolution() || v2.Magnitude() <= gp::Resolution() ? 0. : fabs( PI2 - v1.Angle( v2 ) ); double val = A * 180. / M_PI; const double eps = 0.1; // val is in degrees return val < eps ? 0. : val; } } double Skew::GetBadRate( double Value, int /*nbNodes*/ ) const { // the skew is in the range [0.0,PI/2]. // 0.0 = good // PI/2 = bad return Value; } SMDSAbs_ElementType Skew::GetType() const { return SMDSAbs_Face; } //================================================================================ /* Class : Area Description : Functor for calculating area */ //================================================================================ double Area::GetValue( const TSequenceOfXYZ& P ) { double val = 0.0; if ( P.size() > 2 ) { gp_Vec aVec1( P(2) - P(1) ); gp_Vec aVec2( P(3) - P(1) ); gp_Vec SumVec = aVec1 ^ aVec2; for (int i=4; i<=P.size(); i++) { gp_Vec aVec1( P(i-1) - P(1) ); gp_Vec aVec2( P(i) - P(1) ); gp_Vec tmp = aVec1 ^ aVec2; SumVec.Add(tmp); } val = SumVec.Magnitude() * 0.5; } return val; } double Area::GetBadRate( double Value, int /*nbNodes*/ ) const { // meaningless as it is not a quality control functor return Value; } SMDSAbs_ElementType Area::GetType() const { return SMDSAbs_Face; } //================================================================================ /* Class : Length Description : Functor for calculating length of edge */ //================================================================================ double Length::GetValue( const TSequenceOfXYZ& P ) { switch ( P.size() ) { case 2: return getDistance( P( 1 ), P( 2 ) ); case 3: return getDistance( P( 1 ), P( 2 ) ) + getDistance( P( 2 ), P( 3 ) ); default: return 0.; } } double Length::GetBadRate( double Value, int /*nbNodes*/ ) const { // meaningless as it is not quality control functor return Value; } SMDSAbs_ElementType Length::GetType() const { return SMDSAbs_Edge; } //================================================================================ /* Class : Length2D Description : Functor for calculating minimal length of edge */ //================================================================================ double Length2D::GetValue( long theElementId ) { TSequenceOfXYZ P; if ( GetPoints( theElementId, P )) { double aVal = 0; int len = P.size(); SMDSAbs_EntityType aType = P.getElementEntity(); switch (aType) { case SMDSEntity_Edge: if (len == 2) aVal = getDistance( P( 1 ), P( 2 ) ); break; case SMDSEntity_Quad_Edge: if (len == 3) // quadratic edge aVal = getDistance(P( 1 ),P( 3 )) + getDistance(P( 3 ),P( 2 )); break; case SMDSEntity_Triangle: if (len == 3){ // triangles double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 1 )); aVal = Min(L1,Min(L2,L3)); } break; case SMDSEntity_Quadrangle: if (len == 4){ // quadrangles double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 1 )); aVal = Min(Min(L1,L2),Min(L3,L4)); } break; case SMDSEntity_Quad_Triangle: case SMDSEntity_BiQuad_Triangle: if (len >= 6){ // quadratic triangles double L1 = getDistance(P( 1 ),P( 2 )) + getDistance(P( 2 ),P( 3 )); double L2 = getDistance(P( 3 ),P( 4 )) + getDistance(P( 4 ),P( 5 )); double L3 = getDistance(P( 5 ),P( 6 )) + getDistance(P( 6 ),P( 1 )); aVal = Min(L1,Min(L2,L3)); } break; case SMDSEntity_Quad_Quadrangle: case SMDSEntity_BiQuad_Quadrangle: if (len >= 8){ // quadratic quadrangles double L1 = getDistance(P( 1 ),P( 2 )) + getDistance(P( 2 ),P( 3 )); double L2 = getDistance(P( 3 ),P( 4 )) + getDistance(P( 4 ),P( 5 )); double L3 = getDistance(P( 5 ),P( 6 )) + getDistance(P( 6 ),P( 7 )); double L4 = getDistance(P( 7 ),P( 8 )) + getDistance(P( 8 ),P( 1 )); aVal = Min(Min(L1,L2),Min(L3,L4)); } break; case SMDSEntity_Tetra: if (len == 4){ // tetrahedra double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 1 )); double L4 = getDistance(P( 1 ),P( 4 )); double L5 = getDistance(P( 2 ),P( 4 )); double L6 = getDistance(P( 3 ),P( 4 )); aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6)); } break; case SMDSEntity_Pyramid: if (len == 5){ // piramids double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 1 )); double L5 = getDistance(P( 1 ),P( 5 )); double L6 = getDistance(P( 2 ),P( 5 )); double L7 = getDistance(P( 3 ),P( 5 )); double L8 = getDistance(P( 4 ),P( 5 )); aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6)); aVal = Min(aVal,Min(L7,L8)); } break; case SMDSEntity_Penta: if (len == 6) { // pentaidres double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 1 )); double L4 = getDistance(P( 4 ),P( 5 )); double L5 = getDistance(P( 5 ),P( 6 )); double L6 = getDistance(P( 6 ),P( 4 )); double L7 = getDistance(P( 1 ),P( 4 )); double L8 = getDistance(P( 2 ),P( 5 )); double L9 = getDistance(P( 3 ),P( 6 )); aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6)); aVal = Min(aVal,Min(Min(L7,L8),L9)); } break; case SMDSEntity_Hexa: if (len == 8){ // hexahedron double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 1 )); double L5 = getDistance(P( 5 ),P( 6 )); double L6 = getDistance(P( 6 ),P( 7 )); double L7 = getDistance(P( 7 ),P( 8 )); double L8 = getDistance(P( 8 ),P( 5 )); double L9 = getDistance(P( 1 ),P( 5 )); double L10= getDistance(P( 2 ),P( 6 )); double L11= getDistance(P( 3 ),P( 7 )); double L12= getDistance(P( 4 ),P( 8 )); aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6)); aVal = Min(aVal,Min(Min(L7,L8),Min(L9,L10))); aVal = Min(aVal,Min(L11,L12)); } break; case SMDSEntity_Quad_Tetra: if (len == 10){ // quadratic tetraidrs double L1 = getDistance(P( 1 ),P( 5 )) + getDistance(P( 5 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 6 )) + getDistance(P( 6 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 7 )) + getDistance(P( 7 ),P( 1 )); double L4 = getDistance(P( 1 ),P( 8 )) + getDistance(P( 8 ),P( 4 )); double L5 = getDistance(P( 2 ),P( 9 )) + getDistance(P( 9 ),P( 4 )); double L6 = getDistance(P( 3 ),P( 10 )) + getDistance(P( 10 ),P( 4 )); aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6)); } break; case SMDSEntity_Quad_Pyramid: if (len == 13){ // quadratic piramids double L1 = getDistance(P( 1 ),P( 6 )) + getDistance(P( 6 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 7 )) + getDistance(P( 7 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 8 )) + getDistance(P( 8 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 9 )) + getDistance(P( 9 ),P( 1 )); double L5 = getDistance(P( 1 ),P( 10 )) + getDistance(P( 10 ),P( 5 )); double L6 = getDistance(P( 2 ),P( 11 )) + getDistance(P( 11 ),P( 5 )); double L7 = getDistance(P( 3 ),P( 12 )) + getDistance(P( 12 ),P( 5 )); double L8 = getDistance(P( 4 ),P( 13 )) + getDistance(P( 13 ),P( 5 )); aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6)); aVal = Min(aVal,Min(L7,L8)); } break; case SMDSEntity_Quad_Penta: if (len == 15){ // quadratic pentaidres double L1 = getDistance(P( 1 ),P( 7 )) + getDistance(P( 7 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 8 )) + getDistance(P( 8 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 9 )) + getDistance(P( 9 ),P( 1 )); double L4 = getDistance(P( 4 ),P( 10 )) + getDistance(P( 10 ),P( 5 )); double L5 = getDistance(P( 5 ),P( 11 )) + getDistance(P( 11 ),P( 6 )); double L6 = getDistance(P( 6 ),P( 12 )) + getDistance(P( 12 ),P( 4 )); double L7 = getDistance(P( 1 ),P( 13 )) + getDistance(P( 13 ),P( 4 )); double L8 = getDistance(P( 2 ),P( 14 )) + getDistance(P( 14 ),P( 5 )); double L9 = getDistance(P( 3 ),P( 15 )) + getDistance(P( 15 ),P( 6 )); aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6)); aVal = Min(aVal,Min(Min(L7,L8),L9)); } break; case SMDSEntity_Quad_Hexa: case SMDSEntity_TriQuad_Hexa: if (len >= 20) { // quadratic hexaider double L1 = getDistance(P( 1 ),P( 9 )) + getDistance(P( 9 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 10 )) + getDistance(P( 10 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 11 )) + getDistance(P( 11 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 12 )) + getDistance(P( 12 ),P( 1 )); double L5 = getDistance(P( 5 ),P( 13 )) + getDistance(P( 13 ),P( 6 )); double L6 = getDistance(P( 6 ),P( 14 )) + getDistance(P( 14 ),P( 7 )); double L7 = getDistance(P( 7 ),P( 15 )) + getDistance(P( 15 ),P( 8 )); double L8 = getDistance(P( 8 ),P( 16 )) + getDistance(P( 16 ),P( 5 )); double L9 = getDistance(P( 1 ),P( 17 )) + getDistance(P( 17 ),P( 5 )); double L10= getDistance(P( 2 ),P( 18 )) + getDistance(P( 18 ),P( 6 )); double L11= getDistance(P( 3 ),P( 19 )) + getDistance(P( 19 ),P( 7 )); double L12= getDistance(P( 4 ),P( 20 )) + getDistance(P( 20 ),P( 8 )); aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6)); aVal = Min(aVal,Min(Min(L7,L8),Min(L9,L10))); aVal = Min(aVal,Min(L11,L12)); } break; case SMDSEntity_Polygon: if ( len > 1 ) { aVal = getDistance( P(1), P( P.size() )); for ( size_t i = 1; i < P.size(); ++i ) aVal = Min( aVal, getDistance( P( i ), P( i+1 ))); } break; #ifndef VTK_NO_QUAD_POLY case SMDSEntity_Quad_Polygon: if ( len > 2 ) { aVal = getDistance( P(1), P( P.size() )) + getDistance( P(P.size()), P( P.size()-1 )); for ( size_t i = 1; i < P.size()-1; i += 2 ) aVal = Min( aVal, getDistance( P( i ), P( i+1 )) + getDistance( P( i+1 ), P( i+2 ))); } break; #endif case SMDSEntity_Hexagonal_Prism: if (len == 12) { // hexagonal prism double L1 = getDistance(P( 1 ),P( 2 )); double L2 = getDistance(P( 2 ),P( 3 )); double L3 = getDistance(P( 3 ),P( 4 )); double L4 = getDistance(P( 4 ),P( 5 )); double L5 = getDistance(P( 5 ),P( 6 )); double L6 = getDistance(P( 6 ),P( 1 )); double L7 = getDistance(P( 7 ), P( 8 )); double L8 = getDistance(P( 8 ), P( 9 )); double L9 = getDistance(P( 9 ), P( 10 )); double L10= getDistance(P( 10 ),P( 11 )); double L11= getDistance(P( 11 ),P( 12 )); double L12= getDistance(P( 12 ),P( 7 )); double L13 = getDistance(P( 1 ),P( 7 )); double L14 = getDistance(P( 2 ),P( 8 )); double L15 = getDistance(P( 3 ),P( 9 )); double L16 = getDistance(P( 4 ),P( 10 )); double L17 = getDistance(P( 5 ),P( 11 )); double L18 = getDistance(P( 6 ),P( 12 )); aVal = Min(Min(Min(L1,L2),Min(L3,L4)),Min(L5,L6)); aVal = Min(aVal, Min(Min(Min(L7,L8),Min(L9,L10)),Min(L11,L12))); aVal = Min(aVal, Min(Min(Min(L13,L14),Min(L15,L16)),Min(L17,L18))); } break; case SMDSEntity_Polyhedra: { } break; default: return 0; } if (aVal < 0 ) { return 0.; } if ( myPrecision >= 0 ) { double prec = pow( 10., (double)( myPrecision ) ); aVal = floor( aVal * prec + 0.5 ) / prec; } return aVal; } return 0.; } double Length2D::GetBadRate( double Value, int /*nbNodes*/ ) const { // meaningless as it is not a quality control functor return Value; } SMDSAbs_ElementType Length2D::GetType() const { return SMDSAbs_Face; } Length2D::Value::Value(double theLength,long thePntId1, long thePntId2): myLength(theLength) { myPntId[0] = thePntId1; myPntId[1] = thePntId2; if(thePntId1 > thePntId2){ myPntId[1] = thePntId1; myPntId[0] = thePntId2; } } bool Length2D::Value::operator<(const Length2D::Value& x) const { if(myPntId[0] < x.myPntId[0]) return true; if(myPntId[0] == x.myPntId[0]) if(myPntId[1] < x.myPntId[1]) return true; return false; } void Length2D::GetValues(TValues& theValues) { TValues aValues; SMDS_FaceIteratorPtr anIter = myMesh->facesIterator(); for(; anIter->more(); ){ const SMDS_MeshFace* anElem = anIter->next(); if(anElem->IsQuadratic()) { const SMDS_VtkFace* F = dynamic_cast<const SMDS_VtkFace*>(anElem); // use special nodes iterator SMDS_ElemIteratorPtr anIter = F->interlacedNodesElemIterator(); long aNodeId[4]; gp_Pnt P[4]; double aLength; const SMDS_MeshElement* aNode; if(anIter->more()){ aNode = anIter->next(); const SMDS_MeshNode* aNodes = (SMDS_MeshNode*) aNode; P[0] = P[1] = gp_Pnt(aNodes->X(),aNodes->Y(),aNodes->Z()); aNodeId[0] = aNodeId[1] = aNode->GetID(); aLength = 0; } for(; anIter->more(); ){ const SMDS_MeshNode* N1 = static_cast<const SMDS_MeshNode*> (anIter->next()); P[2] = gp_Pnt(N1->X(),N1->Y(),N1->Z()); aNodeId[2] = N1->GetID(); aLength = P[1].Distance(P[2]); if(!anIter->more()) break; const SMDS_MeshNode* N2 = static_cast<const SMDS_MeshNode*> (anIter->next()); P[3] = gp_Pnt(N2->X(),N2->Y(),N2->Z()); aNodeId[3] = N2->GetID(); aLength += P[2].Distance(P[3]); Value aValue1(aLength,aNodeId[1],aNodeId[2]); Value aValue2(aLength,aNodeId[2],aNodeId[3]); P[1] = P[3]; aNodeId[1] = aNodeId[3]; theValues.insert(aValue1); theValues.insert(aValue2); } aLength += P[2].Distance(P[0]); Value aValue1(aLength,aNodeId[1],aNodeId[2]); Value aValue2(aLength,aNodeId[2],aNodeId[0]); theValues.insert(aValue1); theValues.insert(aValue2); } else { SMDS_ElemIteratorPtr aNodesIter = anElem->nodesIterator(); long aNodeId[2]; gp_Pnt P[3]; double aLength; const SMDS_MeshElement* aNode; if(aNodesIter->more()){ aNode = aNodesIter->next(); const SMDS_MeshNode* aNodes = (SMDS_MeshNode*) aNode; P[0] = P[1] = gp_Pnt(aNodes->X(),aNodes->Y(),aNodes->Z()); aNodeId[0] = aNodeId[1] = aNode->GetID(); aLength = 0; } for(; aNodesIter->more(); ){ aNode = aNodesIter->next(); const SMDS_MeshNode* aNodes = (SMDS_MeshNode*) aNode; long anId = aNode->GetID(); P[2] = gp_Pnt(aNodes->X(),aNodes->Y(),aNodes->Z()); aLength = P[1].Distance(P[2]); Value aValue(aLength,aNodeId[1],anId); aNodeId[1] = anId; P[1] = P[2]; theValues.insert(aValue); } aLength = P[0].Distance(P[1]); Value aValue(aLength,aNodeId[0],aNodeId[1]); theValues.insert(aValue); } } } //================================================================================ /* Class : MultiConnection Description : Functor for calculating number of faces conneted to the edge */ //================================================================================ double MultiConnection::GetValue( const TSequenceOfXYZ& P ) { return 0; } double MultiConnection::GetValue( long theId ) { return getNbMultiConnection( myMesh, theId ); } double MultiConnection::GetBadRate( double Value, int /*nbNodes*/ ) const { // meaningless as it is not quality control functor return Value; } SMDSAbs_ElementType MultiConnection::GetType() const { return SMDSAbs_Edge; } //================================================================================ /* Class : MultiConnection2D Description : Functor for calculating number of faces conneted to the edge */ //================================================================================ double MultiConnection2D::GetValue( const TSequenceOfXYZ& P ) { return 0; } double MultiConnection2D::GetValue( long theElementId ) { int aResult = 0; const SMDS_MeshElement* aFaceElem = myMesh->FindElement(theElementId); SMDSAbs_ElementType aType = aFaceElem->GetType(); switch (aType) { case SMDSAbs_Face: { int i = 0, len = aFaceElem->NbNodes(); SMDS_ElemIteratorPtr anIter = aFaceElem->nodesIterator(); if (!anIter) break; const SMDS_MeshNode *aNode, *aNode0; TColStd_MapOfInteger aMap, aMapPrev; for (i = 0; i <= len; i++) { aMapPrev = aMap; aMap.Clear(); int aNb = 0; if (anIter->more()) { aNode = (SMDS_MeshNode*)anIter->next(); } else { if (i == len) aNode = aNode0; else break; } if (!aNode) break; if (i == 0) aNode0 = aNode; SMDS_ElemIteratorPtr anElemIter = aNode->GetInverseElementIterator(); while (anElemIter->more()) { const SMDS_MeshElement* anElem = anElemIter->next(); if (anElem != 0 && anElem->GetType() == SMDSAbs_Face) { int anId = anElem->GetID(); aMap.Add(anId); if (aMapPrev.Contains(anId)) { aNb++; } } } aResult = Max(aResult, aNb); } } break; default: aResult = 0; } return aResult; } double MultiConnection2D::GetBadRate( double Value, int /*nbNodes*/ ) const { // meaningless as it is not quality control functor return Value; } SMDSAbs_ElementType MultiConnection2D::GetType() const { return SMDSAbs_Face; } MultiConnection2D::Value::Value(long thePntId1, long thePntId2) { myPntId[0] = thePntId1; myPntId[1] = thePntId2; if(thePntId1 > thePntId2){ myPntId[1] = thePntId1; myPntId[0] = thePntId2; } } bool MultiConnection2D::Value::operator<(const MultiConnection2D::Value& x) const { if(myPntId[0] < x.myPntId[0]) return true; if(myPntId[0] == x.myPntId[0]) if(myPntId[1] < x.myPntId[1]) return true; return false; } void MultiConnection2D::GetValues(MValues& theValues) { if ( !myMesh ) return; SMDS_FaceIteratorPtr anIter = myMesh->facesIterator(); for(; anIter->more(); ){ const SMDS_MeshFace* anElem = anIter->next(); SMDS_ElemIteratorPtr aNodesIter; if ( anElem->IsQuadratic() ) aNodesIter = dynamic_cast<const SMDS_VtkFace*> (anElem)->interlacedNodesElemIterator(); else aNodesIter = anElem->nodesIterator(); long aNodeId[3]; //int aNbConnects=0; const SMDS_MeshNode* aNode0; const SMDS_MeshNode* aNode1; const SMDS_MeshNode* aNode2; if(aNodesIter->more()){ aNode0 = (SMDS_MeshNode*) aNodesIter->next(); aNode1 = aNode0; const SMDS_MeshNode* aNodes = (SMDS_MeshNode*) aNode1; aNodeId[0] = aNodeId[1] = aNodes->GetID(); } for(; aNodesIter->more(); ) { aNode2 = (SMDS_MeshNode*) aNodesIter->next(); long anId = aNode2->GetID(); aNodeId[2] = anId; Value aValue(aNodeId[1],aNodeId[2]); MValues::iterator aItr = theValues.find(aValue); if (aItr != theValues.end()){ aItr->second += 1; //aNbConnects = nb; } else { theValues[aValue] = 1; //aNbConnects = 1; } //cout << "NodeIds: "<<aNodeId[1]<<","<<aNodeId[2]<<" nbconn="<<aNbConnects<<endl; aNodeId[1] = aNodeId[2]; aNode1 = aNode2; } Value aValue(aNodeId[0],aNodeId[2]); MValues::iterator aItr = theValues.find(aValue); if (aItr != theValues.end()) { aItr->second += 1; //aNbConnects = nb; } else { theValues[aValue] = 1; //aNbConnects = 1; } //cout << "NodeIds: "<<aNodeId[0]<<","<<aNodeId[2]<<" nbconn="<<aNbConnects<<endl; } } //================================================================================ /* Class : BallDiameter Description : Functor returning diameter of a ball element */ //================================================================================ double BallDiameter::GetValue( long theId ) { double diameter = 0; if ( const SMDS_BallElement* ball = dynamic_cast<const SMDS_BallElement*>( myMesh->FindElement( theId ))) { diameter = ball->GetDiameter(); } return diameter; } double BallDiameter::GetBadRate( double Value, int /*nbNodes*/ ) const { // meaningless as it is not a quality control functor return Value; } SMDSAbs_ElementType BallDiameter::GetType() const { return SMDSAbs_Ball; } /* PREDICATES */ //================================================================================ /* Class : BadOrientedVolume Description : Predicate bad oriented volumes */ //================================================================================ BadOrientedVolume::BadOrientedVolume() { myMesh = 0; } void BadOrientedVolume::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } bool BadOrientedVolume::IsSatisfy( long theId ) { if ( myMesh == 0 ) return false; SMDS_VolumeTool vTool( myMesh->FindElement( theId )); return !vTool.IsForward(); } SMDSAbs_ElementType BadOrientedVolume::GetType() const { return SMDSAbs_Volume; } /* Class : BareBorderVolume */ bool BareBorderVolume::IsSatisfy(long theElementId ) { SMDS_VolumeTool myTool; if ( myTool.Set( myMesh->FindElement(theElementId))) { for ( int iF = 0; iF < myTool.NbFaces(); ++iF ) if ( myTool.IsFreeFace( iF )) { const SMDS_MeshNode** n = myTool.GetFaceNodes(iF); vector< const SMDS_MeshNode*> nodes( n, n+myTool.NbFaceNodes(iF)); if ( !myMesh->FindElement( nodes, SMDSAbs_Face, /*Nomedium=*/false)) return true; } } return false; } //================================================================================ /* Class : BareBorderFace */ //================================================================================ bool BareBorderFace::IsSatisfy(long theElementId ) { bool ok = false; if ( const SMDS_MeshElement* face = myMesh->FindElement(theElementId)) { if ( face->GetType() == SMDSAbs_Face ) { int nbN = face->NbCornerNodes(); for ( int i = 0; i < nbN && !ok; ++i ) { // check if a link is shared by another face const SMDS_MeshNode* n1 = face->GetNode( i ); const SMDS_MeshNode* n2 = face->GetNode( (i+1)%nbN ); SMDS_ElemIteratorPtr fIt = n1->GetInverseElementIterator( SMDSAbs_Face ); bool isShared = false; while ( !isShared && fIt->more() ) { const SMDS_MeshElement* f = fIt->next(); isShared = ( f != face && f->GetNodeIndex(n2) != -1 ); } if ( !isShared ) { const int iQuad = face->IsQuadratic(); myLinkNodes.resize( 2 + iQuad); myLinkNodes[0] = n1; myLinkNodes[1] = n2; if ( iQuad ) myLinkNodes[2] = face->GetNode( i+nbN ); ok = !myMesh->FindElement( myLinkNodes, SMDSAbs_Edge, /*noMedium=*/false); } } } } return ok; } //================================================================================ /* Class : OverConstrainedVolume */ //================================================================================ bool OverConstrainedVolume::IsSatisfy(long theElementId ) { // An element is over-constrained if it has N-1 free borders where // N is the number of edges/faces for a 2D/3D element. SMDS_VolumeTool myTool; if ( myTool.Set( myMesh->FindElement(theElementId))) { int nbSharedFaces = 0; for ( int iF = 0; iF < myTool.NbFaces(); ++iF ) if ( !myTool.IsFreeFace( iF ) && ++nbSharedFaces > 1 ) break; return ( nbSharedFaces == 1 ); } return false; } //================================================================================ /* Class : OverConstrainedFace */ //================================================================================ bool OverConstrainedFace::IsSatisfy(long theElementId ) { // An element is over-constrained if it has N-1 free borders where // N is the number of edges/faces for a 2D/3D element. if ( const SMDS_MeshElement* face = myMesh->FindElement(theElementId)) if ( face->GetType() == SMDSAbs_Face ) { int nbSharedBorders = 0; int nbN = face->NbCornerNodes(); for ( int i = 0; i < nbN; ++i ) { // check if a link is shared by another face const SMDS_MeshNode* n1 = face->GetNode( i ); const SMDS_MeshNode* n2 = face->GetNode( (i+1)%nbN ); SMDS_ElemIteratorPtr fIt = n1->GetInverseElementIterator( SMDSAbs_Face ); bool isShared = false; while ( !isShared && fIt->more() ) { const SMDS_MeshElement* f = fIt->next(); isShared = ( f != face && f->GetNodeIndex(n2) != -1 ); } if ( isShared && ++nbSharedBorders > 1 ) break; } return ( nbSharedBorders == 1 ); } return false; } //================================================================================ /* Class : CoincidentNodes Description : Predicate of Coincident nodes */ //================================================================================ CoincidentNodes::CoincidentNodes() { myToler = 1e-5; } bool CoincidentNodes::IsSatisfy( long theElementId ) { return myCoincidentIDs.Contains( theElementId ); } SMDSAbs_ElementType CoincidentNodes::GetType() const { return SMDSAbs_Node; } void CoincidentNodes::SetMesh( const SMDS_Mesh* theMesh ) { myMeshModifTracer.SetMesh( theMesh ); if ( myMeshModifTracer.IsMeshModified() ) { TIDSortedNodeSet nodesToCheck; SMDS_NodeIteratorPtr nIt = theMesh->nodesIterator(/*idInceasingOrder=*/true); while ( nIt->more() ) nodesToCheck.insert( nodesToCheck.end(), nIt->next() ); list< list< const SMDS_MeshNode*> > nodeGroups; SMESH_OctreeNode::FindCoincidentNodes ( nodesToCheck, &nodeGroups, myToler ); myCoincidentIDs.Clear(); list< list< const SMDS_MeshNode*> >::iterator groupIt = nodeGroups.begin(); for ( ; groupIt != nodeGroups.end(); ++groupIt ) { list< const SMDS_MeshNode*>& coincNodes = *groupIt; list< const SMDS_MeshNode*>::iterator n = coincNodes.begin(); for ( ; n != coincNodes.end(); ++n ) myCoincidentIDs.Add( (*n)->GetID() ); } } } //================================================================================ /* Class : CoincidentElements Description : Predicate of Coincident Elements Note : This class is suitable only for visualization of Coincident Elements */ //================================================================================ CoincidentElements::CoincidentElements() { myMesh = 0; } void CoincidentElements::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } bool CoincidentElements::IsSatisfy( long theElementId ) { if ( !myMesh ) return false; if ( const SMDS_MeshElement* e = myMesh->FindElement( theElementId )) { if ( e->GetType() != GetType() ) return false; set< const SMDS_MeshNode* > elemNodes( e->begin_nodes(), e->end_nodes() ); const int nbNodes = e->NbNodes(); SMDS_ElemIteratorPtr invIt = (*elemNodes.begin())->GetInverseElementIterator( GetType() ); while ( invIt->more() ) { const SMDS_MeshElement* e2 = invIt->next(); if ( e2 == e || e2->NbNodes() != nbNodes ) continue; bool sameNodes = true; for ( size_t i = 0; i < elemNodes.size() && sameNodes; ++i ) sameNodes = ( elemNodes.count( e2->GetNode( i ))); if ( sameNodes ) return true; } } return false; } SMDSAbs_ElementType CoincidentElements1D::GetType() const { return SMDSAbs_Edge; } SMDSAbs_ElementType CoincidentElements2D::GetType() const { return SMDSAbs_Face; } SMDSAbs_ElementType CoincidentElements3D::GetType() const { return SMDSAbs_Volume; } //================================================================================ /* Class : FreeBorders Description : Predicate for free borders */ //================================================================================ FreeBorders::FreeBorders() { myMesh = 0; } void FreeBorders::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } bool FreeBorders::IsSatisfy( long theId ) { return getNbMultiConnection( myMesh, theId ) == 1; } SMDSAbs_ElementType FreeBorders::GetType() const { return SMDSAbs_Edge; } //================================================================================ /* Class : FreeEdges Description : Predicate for free Edges */ //================================================================================ FreeEdges::FreeEdges() { myMesh = 0; } void FreeEdges::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } bool FreeEdges::IsFreeEdge( const SMDS_MeshNode** theNodes, const int theFaceId ) { TColStd_MapOfInteger aMap; for ( int i = 0; i < 2; i++ ) { SMDS_ElemIteratorPtr anElemIter = theNodes[ i ]->GetInverseElementIterator(SMDSAbs_Face); while( anElemIter->more() ) { if ( const SMDS_MeshElement* anElem = anElemIter->next()) { const int anId = anElem->GetID(); if ( anId != theFaceId && !aMap.Add( anId )) return false; } } } return true; } bool FreeEdges::IsSatisfy( long theId ) { if ( myMesh == 0 ) return false; const SMDS_MeshElement* aFace = myMesh->FindElement( theId ); if ( aFace == 0 || aFace->GetType() != SMDSAbs_Face || aFace->NbNodes() < 3 ) return false; SMDS_NodeIteratorPtr anIter = aFace->interlacedNodesIterator(); if ( !anIter ) return false; int i = 0, nbNodes = aFace->NbNodes(); std::vector <const SMDS_MeshNode*> aNodes( nbNodes+1 ); while( anIter->more() ) if ( ! ( aNodes[ i++ ] = anIter->next() )) return false; aNodes[ nbNodes ] = aNodes[ 0 ]; for ( i = 0; i < nbNodes; i++ ) if ( IsFreeEdge( &aNodes[ i ], theId ) ) return true; return false; } SMDSAbs_ElementType FreeEdges::GetType() const { return SMDSAbs_Face; } FreeEdges::Border::Border(long theElemId, long thePntId1, long thePntId2): myElemId(theElemId) { myPntId[0] = thePntId1; myPntId[1] = thePntId2; if(thePntId1 > thePntId2){ myPntId[1] = thePntId1; myPntId[0] = thePntId2; } } bool FreeEdges::Border::operator<(const FreeEdges::Border& x) const{ if(myPntId[0] < x.myPntId[0]) return true; if(myPntId[0] == x.myPntId[0]) if(myPntId[1] < x.myPntId[1]) return true; return false; } inline void UpdateBorders(const FreeEdges::Border& theBorder, FreeEdges::TBorders& theRegistry, FreeEdges::TBorders& theContainer) { if(theRegistry.find(theBorder) == theRegistry.end()){ theRegistry.insert(theBorder); theContainer.insert(theBorder); }else{ theContainer.erase(theBorder); } } void FreeEdges::GetBoreders(TBorders& theBorders) { TBorders aRegistry; SMDS_FaceIteratorPtr anIter = myMesh->facesIterator(); for(; anIter->more(); ){ const SMDS_MeshFace* anElem = anIter->next(); long anElemId = anElem->GetID(); SMDS_ElemIteratorPtr aNodesIter; if ( anElem->IsQuadratic() ) aNodesIter = static_cast<const SMDS_VtkFace*>(anElem)-> interlacedNodesElemIterator(); else aNodesIter = anElem->nodesIterator(); long aNodeId[2]; const SMDS_MeshElement* aNode; if(aNodesIter->more()){ aNode = aNodesIter->next(); aNodeId[0] = aNodeId[1] = aNode->GetID(); } for(; aNodesIter->more(); ){ aNode = aNodesIter->next(); long anId = aNode->GetID(); Border aBorder(anElemId,aNodeId[1],anId); aNodeId[1] = anId; UpdateBorders(aBorder,aRegistry,theBorders); } Border aBorder(anElemId,aNodeId[0],aNodeId[1]); UpdateBorders(aBorder,aRegistry,theBorders); } } //================================================================================ /* Class : FreeNodes Description : Predicate for free nodes */ //================================================================================ FreeNodes::FreeNodes() { myMesh = 0; } void FreeNodes::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } bool FreeNodes::IsSatisfy( long theNodeId ) { const SMDS_MeshNode* aNode = myMesh->FindNode( theNodeId ); if (!aNode) return false; return (aNode->NbInverseElements() < 1); } SMDSAbs_ElementType FreeNodes::GetType() const { return SMDSAbs_Node; } //================================================================================ /* Class : FreeFaces Description : Predicate for free faces */ //================================================================================ FreeFaces::FreeFaces() { myMesh = 0; } void FreeFaces::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } bool FreeFaces::IsSatisfy( long theId ) { if (!myMesh) return false; // check that faces nodes refers to less than two common volumes const SMDS_MeshElement* aFace = myMesh->FindElement( theId ); if ( !aFace || aFace->GetType() != SMDSAbs_Face ) return false; int nbNode = aFace->NbNodes(); // collect volumes to check that number of volumes with count equal nbNode not less than 2 typedef map< SMDS_MeshElement*, int > TMapOfVolume; // map of volume counters typedef map< SMDS_MeshElement*, int >::iterator TItrMapOfVolume; // iterator TMapOfVolume mapOfVol; SMDS_ElemIteratorPtr nodeItr = aFace->nodesIterator(); while ( nodeItr->more() ) { const SMDS_MeshNode* aNode = static_cast<const SMDS_MeshNode*>(nodeItr->next()); if ( !aNode ) continue; SMDS_ElemIteratorPtr volItr = aNode->GetInverseElementIterator(SMDSAbs_Volume); while ( volItr->more() ) { SMDS_MeshElement* aVol = (SMDS_MeshElement*)volItr->next(); TItrMapOfVolume itr = mapOfVol.insert(make_pair(aVol, 0)).first; (*itr).second++; } } int nbVol = 0; TItrMapOfVolume volItr = mapOfVol.begin(); TItrMapOfVolume volEnd = mapOfVol.end(); for ( ; volItr != volEnd; ++volItr ) if ( (*volItr).second >= nbNode ) nbVol++; // face is not free if number of volumes constructed on thier nodes more than one return (nbVol < 2); } SMDSAbs_ElementType FreeFaces::GetType() const { return SMDSAbs_Face; } //================================================================================ /* Class : LinearOrQuadratic Description : Predicate to verify whether a mesh element is linear */ //================================================================================ LinearOrQuadratic::LinearOrQuadratic() { myMesh = 0; } void LinearOrQuadratic::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } bool LinearOrQuadratic::IsSatisfy( long theId ) { if (!myMesh) return false; const SMDS_MeshElement* anElem = myMesh->FindElement( theId ); if ( !anElem || (myType != SMDSAbs_All && anElem->GetType() != myType) ) return false; return (!anElem->IsQuadratic()); } void LinearOrQuadratic::SetType( SMDSAbs_ElementType theType ) { myType = theType; } SMDSAbs_ElementType LinearOrQuadratic::GetType() const { return myType; } //================================================================================ /* Class : GroupColor Description : Functor for check color of group to whic mesh element belongs to */ //================================================================================ GroupColor::GroupColor() { } bool GroupColor::IsSatisfy( long theId ) { return myIDs.count( theId ); } void GroupColor::SetType( SMDSAbs_ElementType theType ) { myType = theType; } SMDSAbs_ElementType GroupColor::GetType() const { return myType; } static bool isEqual( const Quantity_Color& theColor1, const Quantity_Color& theColor2 ) { // tolerance to compare colors const double tol = 5*1e-3; return ( fabs( theColor1.Red() - theColor2.Red() ) < tol && fabs( theColor1.Green() - theColor2.Green() ) < tol && fabs( theColor1.Blue() - theColor2.Blue() ) < tol ); } void GroupColor::SetMesh( const SMDS_Mesh* theMesh ) { myIDs.clear(); const SMESHDS_Mesh* aMesh = dynamic_cast<const SMESHDS_Mesh*>(theMesh); if ( !aMesh ) return; int nbGrp = aMesh->GetNbGroups(); if ( !nbGrp ) return; // iterates on groups and find necessary elements ids const std::set<SMESHDS_GroupBase*>& aGroups = aMesh->GetGroups(); set<SMESHDS_GroupBase*>::const_iterator GrIt = aGroups.begin(); for (; GrIt != aGroups.end(); GrIt++) { SMESHDS_GroupBase* aGrp = (*GrIt); if ( !aGrp ) continue; // check type and color of group if ( !isEqual( myColor, aGrp->GetColor() )) continue; // IPAL52867 (prevent infinite recursion via GroupOnFilter) if ( SMESHDS_GroupOnFilter * gof = dynamic_cast< SMESHDS_GroupOnFilter* >( aGrp )) if ( gof->GetPredicate().get() == this ) continue; SMDSAbs_ElementType aGrpElType = (SMDSAbs_ElementType)aGrp->GetType(); if ( myType == aGrpElType || (myType == SMDSAbs_All && aGrpElType != SMDSAbs_Node) ) { // add elements IDS into control int aSize = aGrp->Extent(); for (int i = 0; i < aSize; i++) myIDs.insert( aGrp->GetID(i+1) ); } } } void GroupColor::SetColorStr( const TCollection_AsciiString& theStr ) { Kernel_Utils::Localizer loc; TCollection_AsciiString aStr = theStr; aStr.RemoveAll( ' ' ); aStr.RemoveAll( '\t' ); for ( int aPos = aStr.Search( ";;" ); aPos != -1; aPos = aStr.Search( ";;" ) ) aStr.Remove( aPos, 2 ); Standard_Real clr[3]; clr[0] = clr[1] = clr[2] = 0.; for ( int i = 0; i < 3; i++ ) { TCollection_AsciiString tmpStr = aStr.Token( ";", i+1 ); if ( !tmpStr.IsEmpty() && tmpStr.IsRealValue() ) clr[i] = tmpStr.RealValue(); } myColor = Quantity_Color( clr[0], clr[1], clr[2], Quantity_TOC_RGB ); } //======================================================================= // name : GetRangeStr // Purpose : Get range as a string. // Example: "1,2,3,50-60,63,67,70-" //======================================================================= void GroupColor::GetColorStr( TCollection_AsciiString& theResStr ) const { theResStr.Clear(); theResStr += TCollection_AsciiString( myColor.Red() ); theResStr += TCollection_AsciiString( ";" ) + TCollection_AsciiString( myColor.Green() ); theResStr += TCollection_AsciiString( ";" ) + TCollection_AsciiString( myColor.Blue() ); } //================================================================================ /* Class : ElemGeomType Description : Predicate to check element geometry type */ //================================================================================ ElemGeomType::ElemGeomType() { myMesh = 0; myType = SMDSAbs_All; myGeomType = SMDSGeom_TRIANGLE; } void ElemGeomType::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } bool ElemGeomType::IsSatisfy( long theId ) { if (!myMesh) return false; const SMDS_MeshElement* anElem = myMesh->FindElement( theId ); if ( !anElem ) return false; const SMDSAbs_ElementType anElemType = anElem->GetType(); if ( myType != SMDSAbs_All && anElemType != myType ) return false; bool isOk = ( anElem->GetGeomType() == myGeomType ); return isOk; } void ElemGeomType::SetType( SMDSAbs_ElementType theType ) { myType = theType; } SMDSAbs_ElementType ElemGeomType::GetType() const { return myType; } void ElemGeomType::SetGeomType( SMDSAbs_GeometryType theType ) { myGeomType = theType; } SMDSAbs_GeometryType ElemGeomType::GetGeomType() const { return myGeomType; } //================================================================================ /* Class : ElemEntityType Description : Predicate to check element entity type */ //================================================================================ ElemEntityType::ElemEntityType(): myMesh( 0 ), myType( SMDSAbs_All ), myEntityType( SMDSEntity_0D ) { } void ElemEntityType::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } bool ElemEntityType::IsSatisfy( long theId ) { if ( !myMesh ) return false; if ( myType == SMDSAbs_Node ) return myMesh->FindNode( theId ); const SMDS_MeshElement* anElem = myMesh->FindElement( theId ); return ( anElem && myEntityType == anElem->GetEntityType() ); } void ElemEntityType::SetType( SMDSAbs_ElementType theType ) { myType = theType; } SMDSAbs_ElementType ElemEntityType::GetType() const { return myType; } void ElemEntityType::SetElemEntityType( SMDSAbs_EntityType theEntityType ) { myEntityType = theEntityType; } SMDSAbs_EntityType ElemEntityType::GetElemEntityType() const { return myEntityType; } //================================================================================ /*! * \brief Class ConnectedElements */ //================================================================================ ConnectedElements::ConnectedElements(): myNodeID(0), myType( SMDSAbs_All ), myOkIDsReady( false ) {} SMDSAbs_ElementType ConnectedElements::GetType() const { return myType; } int ConnectedElements::GetNode() const { return myXYZ.empty() ? myNodeID : 0; } // myNodeID can be found by myXYZ std::vector<double> ConnectedElements::GetPoint() const { return myXYZ; } void ConnectedElements::clearOkIDs() { myOkIDsReady = false; myOkIDs.clear(); } void ConnectedElements::SetType( SMDSAbs_ElementType theType ) { if ( myType != theType || myMeshModifTracer.IsMeshModified() ) clearOkIDs(); myType = theType; } void ConnectedElements::SetMesh( const SMDS_Mesh* theMesh ) { myMeshModifTracer.SetMesh( theMesh ); if ( myMeshModifTracer.IsMeshModified() ) { clearOkIDs(); if ( !myXYZ.empty() ) SetPoint( myXYZ[0], myXYZ[1], myXYZ[2] ); // find a node near myXYZ it in a new mesh } } void ConnectedElements::SetNode( int nodeID ) { myNodeID = nodeID; myXYZ.clear(); bool isSameDomain = false; if ( myOkIDsReady && myMeshModifTracer.GetMesh() && !myMeshModifTracer.IsMeshModified() ) if ( const SMDS_MeshNode* n = myMeshModifTracer.GetMesh()->FindNode( myNodeID )) { SMDS_ElemIteratorPtr eIt = n->GetInverseElementIterator( myType ); while ( !isSameDomain && eIt->more() ) isSameDomain = IsSatisfy( eIt->next()->GetID() ); } if ( !isSameDomain ) clearOkIDs(); } void ConnectedElements::SetPoint( double x, double y, double z ) { myXYZ.resize(3); myXYZ[0] = x; myXYZ[1] = y; myXYZ[2] = z; myNodeID = 0; bool isSameDomain = false; // find myNodeID by myXYZ if possible if ( myMeshModifTracer.GetMesh() ) { auto_ptr<SMESH_ElementSearcher> searcher ( SMESH_MeshAlgos::GetElementSearcher( (SMDS_Mesh&) *myMeshModifTracer.GetMesh() )); vector< const SMDS_MeshElement* > foundElems; searcher->FindElementsByPoint( gp_Pnt(x,y,z), SMDSAbs_All, foundElems ); if ( !foundElems.empty() ) { myNodeID = foundElems[0]->GetNode(0)->GetID(); if ( myOkIDsReady && !myMeshModifTracer.IsMeshModified() ) isSameDomain = IsSatisfy( foundElems[0]->GetID() ); } } if ( !isSameDomain ) clearOkIDs(); } bool ConnectedElements::IsSatisfy( long theElementId ) { // Here we do NOT check if the mesh has changed, we do it in Set...() only!!! if ( !myOkIDsReady ) { if ( !myMeshModifTracer.GetMesh() ) return false; const SMDS_MeshNode* node0 = myMeshModifTracer.GetMesh()->FindNode( myNodeID ); if ( !node0 ) return false; list< const SMDS_MeshNode* > nodeQueue( 1, node0 ); std::set< int > checkedNodeIDs; // algo: // foreach node in nodeQueue: // foreach element sharing a node: // add ID of an element of myType to myOkIDs; // push all element nodes absent from checkedNodeIDs to nodeQueue; while ( !nodeQueue.empty() ) { const SMDS_MeshNode* node = nodeQueue.front(); nodeQueue.pop_front(); // loop on elements sharing the node SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(); while ( eIt->more() ) { // keep elements of myType const SMDS_MeshElement* element = eIt->next(); if ( element->GetType() == myType ) myOkIDs.insert( myOkIDs.end(), element->GetID() ); // enqueue nodes of the element SMDS_ElemIteratorPtr nIt = element->nodesIterator(); while ( nIt->more() ) { const SMDS_MeshNode* n = static_cast< const SMDS_MeshNode* >( nIt->next() ); if ( checkedNodeIDs.insert( n->GetID() ).second ) nodeQueue.push_back( n ); } } } if ( myType == SMDSAbs_Node ) std::swap( myOkIDs, checkedNodeIDs ); size_t totalNbElems = myMeshModifTracer.GetMesh()->GetMeshInfo().NbElements( myType ); if ( myOkIDs.size() == totalNbElems ) myOkIDs.clear(); myOkIDsReady = true; } return myOkIDs.empty() ? true : myOkIDs.count( theElementId ); } //================================================================================ /*! * \brief Class CoplanarFaces */ //================================================================================ CoplanarFaces::CoplanarFaces() : myFaceID(0), myToler(0) { } void CoplanarFaces::SetMesh( const SMDS_Mesh* theMesh ) { myMeshModifTracer.SetMesh( theMesh ); if ( myMeshModifTracer.IsMeshModified() ) { // Build a set of coplanar face ids myCoplanarIDs.clear(); if ( !myMeshModifTracer.GetMesh() || !myFaceID || !myToler ) return; const SMDS_MeshElement* face = myMeshModifTracer.GetMesh()->FindElement( myFaceID ); if ( !face || face->GetType() != SMDSAbs_Face ) return; bool normOK; gp_Vec myNorm = getNormale( static_cast<const SMDS_MeshFace*>(face), &normOK ); if (!normOK) return; const double radianTol = myToler * M_PI / 180.; std::set< SMESH_TLink > checkedLinks; std::list< pair< const SMDS_MeshElement*, gp_Vec > > faceQueue; faceQueue.push_back( make_pair( face, myNorm )); while ( !faceQueue.empty() ) { face = faceQueue.front().first; myNorm = faceQueue.front().second; faceQueue.pop_front(); for ( int i = 0, nbN = face->NbCornerNodes(); i < nbN; ++i ) { const SMDS_MeshNode* n1 = face->GetNode( i ); const SMDS_MeshNode* n2 = face->GetNode(( i+1 )%nbN); if ( !checkedLinks.insert( SMESH_TLink( n1, n2 )).second ) continue; SMDS_ElemIteratorPtr fIt = n1->GetInverseElementIterator(SMDSAbs_Face); while ( fIt->more() ) { const SMDS_MeshElement* f = fIt->next(); if ( f->GetNodeIndex( n2 ) > -1 ) { gp_Vec norm = getNormale( static_cast<const SMDS_MeshFace*>(f), &normOK ); if (!normOK || myNorm.Angle( norm ) <= radianTol) { myCoplanarIDs.insert( f->GetID() ); faceQueue.push_back( make_pair( f, norm )); } } } } } } } bool CoplanarFaces::IsSatisfy( long theElementId ) { return myCoplanarIDs.count( theElementId ); } /* *Class : RangeOfIds *Description : Predicate for Range of Ids. * Range may be specified with two ways. * 1. Using AddToRange method * 2. With SetRangeStr method. Parameter of this method is a string * like as "1,2,3,50-60,63,67,70-" */ //======================================================================= // name : RangeOfIds // Purpose : Constructor //======================================================================= RangeOfIds::RangeOfIds() { myMesh = 0; myType = SMDSAbs_All; } //======================================================================= // name : SetMesh // Purpose : Set mesh //======================================================================= void RangeOfIds::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; } //======================================================================= // name : AddToRange // Purpose : Add ID to the range //======================================================================= bool RangeOfIds::AddToRange( long theEntityId ) { myIds.Add( theEntityId ); return true; } //======================================================================= // name : GetRangeStr // Purpose : Get range as a string. // Example: "1,2,3,50-60,63,67,70-" //======================================================================= void RangeOfIds::GetRangeStr( TCollection_AsciiString& theResStr ) { theResStr.Clear(); TColStd_SequenceOfInteger anIntSeq; TColStd_SequenceOfAsciiString aStrSeq; TColStd_MapIteratorOfMapOfInteger anIter( myIds ); for ( ; anIter.More(); anIter.Next() ) { int anId = anIter.Key(); TCollection_AsciiString aStr( anId ); anIntSeq.Append( anId ); aStrSeq.Append( aStr ); } for ( int i = 1, n = myMin.Length(); i <= n; i++ ) { int aMinId = myMin( i ); int aMaxId = myMax( i ); TCollection_AsciiString aStr; if ( aMinId != IntegerFirst() ) aStr += aMinId; aStr += "-"; if ( aMaxId != IntegerLast() ) aStr += aMaxId; // find position of the string in result sequence and insert string in it if ( anIntSeq.Length() == 0 ) { anIntSeq.Append( aMinId ); aStrSeq.Append( aStr ); } else { if ( aMinId < anIntSeq.First() ) { anIntSeq.Prepend( aMinId ); aStrSeq.Prepend( aStr ); } else if ( aMinId > anIntSeq.Last() ) { anIntSeq.Append( aMinId ); aStrSeq.Append( aStr ); } else for ( int j = 1, k = anIntSeq.Length(); j <= k; j++ ) if ( aMinId < anIntSeq( j ) ) { anIntSeq.InsertBefore( j, aMinId ); aStrSeq.InsertBefore( j, aStr ); break; } } } if ( aStrSeq.Length() == 0 ) return; theResStr = aStrSeq( 1 ); for ( int j = 2, k = aStrSeq.Length(); j <= k; j++ ) { theResStr += ","; theResStr += aStrSeq( j ); } } //======================================================================= // name : SetRangeStr // Purpose : Define range with string // Example of entry string: "1,2,3,50-60,63,67,70-" //======================================================================= bool RangeOfIds::SetRangeStr( const TCollection_AsciiString& theStr ) { myMin.Clear(); myMax.Clear(); myIds.Clear(); TCollection_AsciiString aStr = theStr; //aStr.RemoveAll( ' ' ); //aStr.RemoveAll( '\t' ); for ( int i = 1; i <= aStr.Length(); ++i ) if ( isspace( aStr.Value( i ))) aStr.SetValue( i, ','); for ( int aPos = aStr.Search( ",," ); aPos != -1; aPos = aStr.Search( ",," ) ) aStr.Remove( aPos, 1 ); TCollection_AsciiString tmpStr = aStr.Token( ",", 1 ); int i = 1; while ( tmpStr != "" ) { tmpStr = aStr.Token( ",", i++ ); int aPos = tmpStr.Search( '-' ); if ( aPos == -1 ) { if ( tmpStr.IsIntegerValue() ) myIds.Add( tmpStr.IntegerValue() ); else return false; } else { TCollection_AsciiString aMaxStr = tmpStr.Split( aPos ); TCollection_AsciiString aMinStr = tmpStr; while ( aMinStr.Search( "-" ) != -1 ) aMinStr.RemoveAll( '-' ); while ( aMaxStr.Search( "-" ) != -1 ) aMaxStr.RemoveAll( '-' ); if ( (!aMinStr.IsEmpty() && !aMinStr.IsIntegerValue()) || (!aMaxStr.IsEmpty() && !aMaxStr.IsIntegerValue()) ) return false; myMin.Append( aMinStr.IsEmpty() ? IntegerFirst() : aMinStr.IntegerValue() ); myMax.Append( aMaxStr.IsEmpty() ? IntegerLast() : aMaxStr.IntegerValue() ); } } return true; } //======================================================================= // name : GetType // Purpose : Get type of supported entities //======================================================================= SMDSAbs_ElementType RangeOfIds::GetType() const { return myType; } //======================================================================= // name : SetType // Purpose : Set type of supported entities //======================================================================= void RangeOfIds::SetType( SMDSAbs_ElementType theType ) { myType = theType; } //======================================================================= // name : IsSatisfy // Purpose : Verify whether entity satisfies to this rpedicate //======================================================================= bool RangeOfIds::IsSatisfy( long theId ) { if ( !myMesh ) return false; if ( myType == SMDSAbs_Node ) { if ( myMesh->FindNode( theId ) == 0 ) return false; } else { const SMDS_MeshElement* anElem = myMesh->FindElement( theId ); if ( anElem == 0 || (myType != anElem->GetType() && myType != SMDSAbs_All )) return false; } if ( myIds.Contains( theId ) ) return true; for ( int i = 1, n = myMin.Length(); i <= n; i++ ) if ( theId >= myMin( i ) && theId <= myMax( i ) ) return true; return false; } /* Class : Comparator Description : Base class for comparators */ Comparator::Comparator(): myMargin(0) {} Comparator::~Comparator() {} void Comparator::SetMesh( const SMDS_Mesh* theMesh ) { if ( myFunctor ) myFunctor->SetMesh( theMesh ); } void Comparator::SetMargin( double theValue ) { myMargin = theValue; } void Comparator::SetNumFunctor( NumericalFunctorPtr theFunct ) { myFunctor = theFunct; } SMDSAbs_ElementType Comparator::GetType() const { return myFunctor ? myFunctor->GetType() : SMDSAbs_All; } double Comparator::GetMargin() { return myMargin; } /* Class : LessThan Description : Comparator "<" */ bool LessThan::IsSatisfy( long theId ) { return myFunctor && myFunctor->GetValue( theId ) < myMargin; } /* Class : MoreThan Description : Comparator ">" */ bool MoreThan::IsSatisfy( long theId ) { return myFunctor && myFunctor->GetValue( theId ) > myMargin; } /* Class : EqualTo Description : Comparator "=" */ EqualTo::EqualTo(): myToler(Precision::Confusion()) {} bool EqualTo::IsSatisfy( long theId ) { return myFunctor && fabs( myFunctor->GetValue( theId ) - myMargin ) < myToler; } void EqualTo::SetTolerance( double theToler ) { myToler = theToler; } double EqualTo::GetTolerance() { return myToler; } /* Class : LogicalNOT Description : Logical NOT predicate */ LogicalNOT::LogicalNOT() {} LogicalNOT::~LogicalNOT() {} bool LogicalNOT::IsSatisfy( long theId ) { return myPredicate && !myPredicate->IsSatisfy( theId ); } void LogicalNOT::SetMesh( const SMDS_Mesh* theMesh ) { if ( myPredicate ) myPredicate->SetMesh( theMesh ); } void LogicalNOT::SetPredicate( PredicatePtr thePred ) { myPredicate = thePred; } SMDSAbs_ElementType LogicalNOT::GetType() const { return myPredicate ? myPredicate->GetType() : SMDSAbs_All; } /* Class : LogicalBinary Description : Base class for binary logical predicate */ LogicalBinary::LogicalBinary() {} LogicalBinary::~LogicalBinary() {} void LogicalBinary::SetMesh( const SMDS_Mesh* theMesh ) { if ( myPredicate1 ) myPredicate1->SetMesh( theMesh ); if ( myPredicate2 ) myPredicate2->SetMesh( theMesh ); } void LogicalBinary::SetPredicate1( PredicatePtr thePredicate ) { myPredicate1 = thePredicate; } void LogicalBinary::SetPredicate2( PredicatePtr thePredicate ) { myPredicate2 = thePredicate; } SMDSAbs_ElementType LogicalBinary::GetType() const { if ( !myPredicate1 || !myPredicate2 ) return SMDSAbs_All; SMDSAbs_ElementType aType1 = myPredicate1->GetType(); SMDSAbs_ElementType aType2 = myPredicate2->GetType(); return aType1 == aType2 ? aType1 : SMDSAbs_All; } /* Class : LogicalAND Description : Logical AND */ bool LogicalAND::IsSatisfy( long theId ) { return myPredicate1 && myPredicate2 && myPredicate1->IsSatisfy( theId ) && myPredicate2->IsSatisfy( theId ); } /* Class : LogicalOR Description : Logical OR */ bool LogicalOR::IsSatisfy( long theId ) { return myPredicate1 && myPredicate2 && (myPredicate1->IsSatisfy( theId ) || myPredicate2->IsSatisfy( theId )); } /* FILTER */ // #ifdef WITH_TBB // #include <tbb/parallel_for.h> // #include <tbb/enumerable_thread_specific.h> // namespace Parallel // { // typedef tbb::enumerable_thread_specific< TIdSequence > TIdSeq; // struct Predicate // { // const SMDS_Mesh* myMesh; // PredicatePtr myPredicate; // TIdSeq & myOKIds; // Predicate( const SMDS_Mesh* m, PredicatePtr p, TIdSeq & ids ): // myMesh(m), myPredicate(p->Duplicate()), myOKIds(ids) {} // void operator() ( const tbb::blocked_range<size_t>& r ) const // { // for ( size_t i = r.begin(); i != r.end(); ++i ) // if ( myPredicate->IsSatisfy( i )) // myOKIds.local().push_back(); // } // } // } // #endif Filter::Filter() {} Filter::~Filter() {} void Filter::SetPredicate( PredicatePtr thePredicate ) { myPredicate = thePredicate; } void Filter::GetElementsId( const SMDS_Mesh* theMesh, PredicatePtr thePredicate, TIdSequence& theSequence ) { theSequence.clear(); if ( !theMesh || !thePredicate ) return; thePredicate->SetMesh( theMesh ); SMDS_ElemIteratorPtr elemIt = theMesh->elementsIterator( thePredicate->GetType() ); if ( elemIt ) { while ( elemIt->more() ) { const SMDS_MeshElement* anElem = elemIt->next(); long anId = anElem->GetID(); if ( thePredicate->IsSatisfy( anId ) ) theSequence.push_back( anId ); } } } void Filter::GetElementsId( const SMDS_Mesh* theMesh, Filter::TIdSequence& theSequence ) { GetElementsId(theMesh,myPredicate,theSequence); } /* ManifoldPart */ typedef std::set<SMDS_MeshFace*> TMapOfFacePtr; /* Internal class Link */ ManifoldPart::Link::Link( SMDS_MeshNode* theNode1, SMDS_MeshNode* theNode2 ) { myNode1 = theNode1; myNode2 = theNode2; } ManifoldPart::Link::~Link() { myNode1 = 0; myNode2 = 0; } bool ManifoldPart::Link::IsEqual( const ManifoldPart::Link& theLink ) const { if ( myNode1 == theLink.myNode1 && myNode2 == theLink.myNode2 ) return true; else if ( myNode1 == theLink.myNode2 && myNode2 == theLink.myNode1 ) return true; else return false; } bool ManifoldPart::Link::operator<( const ManifoldPart::Link& x ) const { if(myNode1 < x.myNode1) return true; if(myNode1 == x.myNode1) if(myNode2 < x.myNode2) return true; return false; } bool ManifoldPart::IsEqual( const ManifoldPart::Link& theLink1, const ManifoldPart::Link& theLink2 ) { return theLink1.IsEqual( theLink2 ); } ManifoldPart::ManifoldPart() { myMesh = 0; myAngToler = Precision::Angular(); myIsOnlyManifold = true; } ManifoldPart::~ManifoldPart() { myMesh = 0; } void ManifoldPart::SetMesh( const SMDS_Mesh* theMesh ) { myMesh = theMesh; process(); } SMDSAbs_ElementType ManifoldPart::GetType() const { return SMDSAbs_Face; } bool ManifoldPart::IsSatisfy( long theElementId ) { return myMapIds.Contains( theElementId ); } void ManifoldPart::SetAngleTolerance( const double theAngToler ) { myAngToler = theAngToler; } double ManifoldPart::GetAngleTolerance() const { return myAngToler; } void ManifoldPart::SetIsOnlyManifold( const bool theIsOnly ) { myIsOnlyManifold = theIsOnly; } void ManifoldPart::SetStartElem( const long theStartId ) { myStartElemId = theStartId; } bool ManifoldPart::process() { myMapIds.Clear(); myMapBadGeomIds.Clear(); myAllFacePtr.clear(); myAllFacePtrIntDMap.clear(); if ( !myMesh ) return false; // collect all faces into own map SMDS_FaceIteratorPtr anFaceItr = myMesh->facesIterator(); for (; anFaceItr->more(); ) { SMDS_MeshFace* aFacePtr = (SMDS_MeshFace*)anFaceItr->next(); myAllFacePtr.push_back( aFacePtr ); myAllFacePtrIntDMap[aFacePtr] = myAllFacePtr.size()-1; } SMDS_MeshFace* aStartFace = (SMDS_MeshFace*)myMesh->FindElement( myStartElemId ); if ( !aStartFace ) return false; // the map of non manifold links and bad geometry TMapOfLink aMapOfNonManifold; TColStd_MapOfInteger aMapOfTreated; // begin cycle on faces from start index and run on vector till the end // and from begin to start index to cover whole vector const int aStartIndx = myAllFacePtrIntDMap[aStartFace]; bool isStartTreat = false; for ( int fi = aStartIndx; !isStartTreat || fi != aStartIndx ; fi++ ) { if ( fi == aStartIndx ) isStartTreat = true; // as result next time when fi will be equal to aStartIndx SMDS_MeshFace* aFacePtr = myAllFacePtr[ fi ]; if ( aMapOfTreated.Contains( aFacePtr->GetID() ) ) continue; aMapOfTreated.Add( aFacePtr->GetID() ); TColStd_MapOfInteger aResFaces; if ( !findConnected( myAllFacePtrIntDMap, aFacePtr, aMapOfNonManifold, aResFaces ) ) continue; TColStd_MapIteratorOfMapOfInteger anItr( aResFaces ); for ( ; anItr.More(); anItr.Next() ) { int aFaceId = anItr.Key(); aMapOfTreated.Add( aFaceId ); myMapIds.Add( aFaceId ); } if ( fi == ( myAllFacePtr.size() - 1 ) ) fi = 0; } // end run on vector of faces return !myMapIds.IsEmpty(); } static void getLinks( const SMDS_MeshFace* theFace, ManifoldPart::TVectorOfLink& theLinks ) { int aNbNode = theFace->NbNodes(); SMDS_ElemIteratorPtr aNodeItr = theFace->nodesIterator(); int i = 1; SMDS_MeshNode* aNode = 0; for ( ; aNodeItr->more() && i <= aNbNode; ) { SMDS_MeshNode* aN1 = (SMDS_MeshNode*)aNodeItr->next(); if ( i == 1 ) aNode = aN1; i++; SMDS_MeshNode* aN2 = ( i >= aNbNode ) ? aNode : (SMDS_MeshNode*)aNodeItr->next(); i++; ManifoldPart::Link aLink( aN1, aN2 ); theLinks.push_back( aLink ); } } bool ManifoldPart::findConnected ( const ManifoldPart::TDataMapFacePtrInt& theAllFacePtrInt, SMDS_MeshFace* theStartFace, ManifoldPart::TMapOfLink& theNonManifold, TColStd_MapOfInteger& theResFaces ) { theResFaces.Clear(); if ( !theAllFacePtrInt.size() ) return false; if ( getNormale( theStartFace ).SquareModulus() <= gp::Resolution() ) { myMapBadGeomIds.Add( theStartFace->GetID() ); return false; } ManifoldPart::TMapOfLink aMapOfBoundary, aMapToSkip; ManifoldPart::TVectorOfLink aSeqOfBoundary; theResFaces.Add( theStartFace->GetID() ); ManifoldPart::TDataMapOfLinkFacePtr aDMapLinkFace; expandBoundary( aMapOfBoundary, aSeqOfBoundary, aDMapLinkFace, theNonManifold, theStartFace ); bool isDone = false; while ( !isDone && aMapOfBoundary.size() != 0 ) { bool isToReset = false; ManifoldPart::TVectorOfLink::iterator pLink = aSeqOfBoundary.begin(); for ( ; !isToReset && pLink != aSeqOfBoundary.end(); ++pLink ) { ManifoldPart::Link aLink = *pLink; if ( aMapToSkip.find( aLink ) != aMapToSkip.end() ) continue; // each link could be treated only once aMapToSkip.insert( aLink ); ManifoldPart::TVectorOfFacePtr aFaces; // find next if ( myIsOnlyManifold && (theNonManifold.find( aLink ) != theNonManifold.end()) ) continue; else { getFacesByLink( aLink, aFaces ); // filter the element to keep only indicated elements ManifoldPart::TVectorOfFacePtr aFiltered; ManifoldPart::TVectorOfFacePtr::iterator pFace = aFaces.begin(); for ( ; pFace != aFaces.end(); ++pFace ) { SMDS_MeshFace* aFace = *pFace; if ( myAllFacePtrIntDMap.find( aFace ) != myAllFacePtrIntDMap.end() ) aFiltered.push_back( aFace ); } aFaces = aFiltered; if ( aFaces.size() < 2 ) // no neihgbour faces continue; else if ( myIsOnlyManifold && aFaces.size() > 2 ) // non manifold case { theNonManifold.insert( aLink ); continue; } } // compare normal with normals of neighbor element SMDS_MeshFace* aPrevFace = aDMapLinkFace[ aLink ]; ManifoldPart::TVectorOfFacePtr::iterator pFace = aFaces.begin(); for ( ; pFace != aFaces.end(); ++pFace ) { SMDS_MeshFace* aNextFace = *pFace; if ( aPrevFace == aNextFace ) continue; int anNextFaceID = aNextFace->GetID(); if ( myIsOnlyManifold && theResFaces.Contains( anNextFaceID ) ) // should not be with non manifold restriction. probably bad topology continue; // check if face was treated and skipped if ( myMapBadGeomIds.Contains( anNextFaceID ) || !isInPlane( aPrevFace, aNextFace ) ) continue; // add new element to connected and extend the boundaries. theResFaces.Add( anNextFaceID ); expandBoundary( aMapOfBoundary, aSeqOfBoundary, aDMapLinkFace, theNonManifold, aNextFace ); isToReset = true; } } isDone = !isToReset; } return !theResFaces.IsEmpty(); } bool ManifoldPart::isInPlane( const SMDS_MeshFace* theFace1, const SMDS_MeshFace* theFace2 ) { gp_Dir aNorm1 = gp_Dir( getNormale( theFace1 ) ); gp_XYZ aNorm2XYZ = getNormale( theFace2 ); if ( aNorm2XYZ.SquareModulus() <= gp::Resolution() ) { myMapBadGeomIds.Add( theFace2->GetID() ); return false; } if ( aNorm1.IsParallel( gp_Dir( aNorm2XYZ ), myAngToler ) ) return true; return false; } void ManifoldPart::expandBoundary ( ManifoldPart::TMapOfLink& theMapOfBoundary, ManifoldPart::TVectorOfLink& theSeqOfBoundary, ManifoldPart::TDataMapOfLinkFacePtr& theDMapLinkFacePtr, ManifoldPart::TMapOfLink& theNonManifold, SMDS_MeshFace* theNextFace ) const { ManifoldPart::TVectorOfLink aLinks; getLinks( theNextFace, aLinks ); int aNbLink = (int)aLinks.size(); for ( int i = 0; i < aNbLink; i++ ) { ManifoldPart::Link aLink = aLinks[ i ]; if ( myIsOnlyManifold && (theNonManifold.find( aLink ) != theNonManifold.end()) ) continue; if ( theMapOfBoundary.find( aLink ) != theMapOfBoundary.end() ) { if ( myIsOnlyManifold ) { // remove from boundary theMapOfBoundary.erase( aLink ); ManifoldPart::TVectorOfLink::iterator pLink = theSeqOfBoundary.begin(); for ( ; pLink != theSeqOfBoundary.end(); ++pLink ) { ManifoldPart::Link aBoundLink = *pLink; if ( aBoundLink.IsEqual( aLink ) ) { theSeqOfBoundary.erase( pLink ); break; } } } } else { theMapOfBoundary.insert( aLink ); theSeqOfBoundary.push_back( aLink ); theDMapLinkFacePtr[ aLink ] = theNextFace; } } } void ManifoldPart::getFacesByLink( const ManifoldPart::Link& theLink, ManifoldPart::TVectorOfFacePtr& theFaces ) const { std::set<SMDS_MeshCell *> aSetOfFaces; // take all faces that shared first node SMDS_ElemIteratorPtr anItr = theLink.myNode1->facesIterator(); for ( ; anItr->more(); ) { SMDS_MeshFace* aFace = (SMDS_MeshFace*)anItr->next(); if ( !aFace ) continue; aSetOfFaces.insert( aFace ); } // take all faces that shared second node anItr = theLink.myNode2->facesIterator(); // find the common part of two sets for ( ; anItr->more(); ) { SMDS_MeshFace* aFace = (SMDS_MeshFace*)anItr->next(); if ( aSetOfFaces.count( aFace ) ) theFaces.push_back( aFace ); } } /* Class : BelongToMeshGroup Description : Verify whether a mesh element is included into a mesh group */ BelongToMeshGroup::BelongToMeshGroup(): myGroup( 0 ) { } void BelongToMeshGroup::SetGroup( SMESHDS_GroupBase* g ) { myGroup = g; } void BelongToMeshGroup::SetStoreName( const std::string& sn ) { myStoreName = sn; } void BelongToMeshGroup::SetMesh( const SMDS_Mesh* theMesh ) { if ( myGroup && myGroup->GetMesh() != theMesh ) { myGroup = 0; } if ( !myGroup && !myStoreName.empty() ) { if ( const SMESHDS_Mesh* aMesh = dynamic_cast<const SMESHDS_Mesh*>(theMesh)) { const std::set<SMESHDS_GroupBase*>& grps = aMesh->GetGroups(); std::set<SMESHDS_GroupBase*>::const_iterator g = grps.begin(); for ( ; g != grps.end() && !myGroup; ++g ) if ( *g && myStoreName == (*g)->GetStoreName() ) myGroup = *g; } } if ( myGroup ) { myGroup->IsEmpty(); // make GroupOnFilter update its predicate } } bool BelongToMeshGroup::IsSatisfy( long theElementId ) { return myGroup ? myGroup->Contains( theElementId ) : false; } SMDSAbs_ElementType BelongToMeshGroup::GetType() const { return myGroup ? myGroup->GetType() : SMDSAbs_All; } /* ElementsOnSurface */ ElementsOnSurface::ElementsOnSurface() { myIds.Clear(); myType = SMDSAbs_All; mySurf.Nullify(); myToler = Precision::Confusion(); myUseBoundaries = false; } ElementsOnSurface::~ElementsOnSurface() { } void ElementsOnSurface::SetMesh( const SMDS_Mesh* theMesh ) { myMeshModifTracer.SetMesh( theMesh ); if ( myMeshModifTracer.IsMeshModified()) process(); } bool ElementsOnSurface::IsSatisfy( long theElementId ) { return myIds.Contains( theElementId ); } SMDSAbs_ElementType ElementsOnSurface::GetType() const { return myType; } void ElementsOnSurface::SetTolerance( const double theToler ) { if ( myToler != theToler ) myIds.Clear(); myToler = theToler; } double ElementsOnSurface::GetTolerance() const { return myToler; } void ElementsOnSurface::SetUseBoundaries( bool theUse ) { if ( myUseBoundaries != theUse ) { myUseBoundaries = theUse; SetSurface( mySurf, myType ); } } void ElementsOnSurface::SetSurface( const TopoDS_Shape& theShape, const SMDSAbs_ElementType theType ) { myIds.Clear(); myType = theType; mySurf.Nullify(); if ( theShape.IsNull() || theShape.ShapeType() != TopAbs_FACE ) return; mySurf = TopoDS::Face( theShape ); BRepAdaptor_Surface SA( mySurf, myUseBoundaries ); Standard_Real u1 = SA.FirstUParameter(), u2 = SA.LastUParameter(), v1 = SA.FirstVParameter(), v2 = SA.LastVParameter(); Handle(Geom_Surface) surf = BRep_Tool::Surface( mySurf ); myProjector.Init( surf, u1,u2, v1,v2 ); process(); } void ElementsOnSurface::process() { myIds.Clear(); if ( mySurf.IsNull() ) return; if ( !myMeshModifTracer.GetMesh() ) return; myIds.ReSize( myMeshModifTracer.GetMesh()->GetMeshInfo().NbElements( myType )); SMDS_ElemIteratorPtr anIter = myMeshModifTracer.GetMesh()->elementsIterator( myType ); for(; anIter->more(); ) process( anIter->next() ); } void ElementsOnSurface::process( const SMDS_MeshElement* theElemPtr ) { SMDS_ElemIteratorPtr aNodeItr = theElemPtr->nodesIterator(); bool isSatisfy = true; for ( ; aNodeItr->more(); ) { SMDS_MeshNode* aNode = (SMDS_MeshNode*)aNodeItr->next(); if ( !isOnSurface( aNode ) ) { isSatisfy = false; break; } } if ( isSatisfy ) myIds.Add( theElemPtr->GetID() ); } bool ElementsOnSurface::isOnSurface( const SMDS_MeshNode* theNode ) { if ( mySurf.IsNull() ) return false; gp_Pnt aPnt( theNode->X(), theNode->Y(), theNode->Z() ); // double aToler2 = myToler * myToler; // if ( mySurf->IsKind(STANDARD_TYPE(Geom_Plane))) // { // gp_Pln aPln = Handle(Geom_Plane)::DownCast(mySurf)->Pln(); // if ( aPln.SquareDistance( aPnt ) > aToler2 ) // return false; // } // else if ( mySurf->IsKind(STANDARD_TYPE(Geom_CylindricalSurface))) // { // gp_Cylinder aCyl = Handle(Geom_CylindricalSurface)::DownCast(mySurf)->Cylinder(); // double aRad = aCyl.Radius(); // gp_Ax3 anAxis = aCyl.Position(); // gp_XYZ aLoc = aCyl.Location().XYZ(); // double aXDist = anAxis.XDirection().XYZ() * ( aPnt.XYZ() - aLoc ); // double aYDist = anAxis.YDirection().XYZ() * ( aPnt.XYZ() - aLoc ); // if ( fabs(aXDist*aXDist + aYDist*aYDist - aRad*aRad) > aToler2 ) // return false; // } // else // return false; myProjector.Perform( aPnt ); bool isOn = ( myProjector.IsDone() && myProjector.LowerDistance() <= myToler ); return isOn; } /* ElementsOnShape */ ElementsOnShape::ElementsOnShape() : //myMesh(0), myType(SMDSAbs_All), myToler(Precision::Confusion()), myAllNodesFlag(false) { } ElementsOnShape::~ElementsOnShape() { clearClassifiers(); } SMDSAbs_ElementType ElementsOnShape::GetType() const { return myType; } void ElementsOnShape::SetTolerance (const double theToler) { if (myToler != theToler) { myToler = theToler; SetShape(myShape, myType); } } double ElementsOnShape::GetTolerance() const { return myToler; } void ElementsOnShape::SetAllNodes (bool theAllNodes) { myAllNodesFlag = theAllNodes; } void ElementsOnShape::SetMesh (const SMDS_Mesh* theMesh) { myMeshModifTracer.SetMesh( theMesh ); if ( myMeshModifTracer.IsMeshModified()) { size_t nbNodes = theMesh ? theMesh->NbNodes() : 0; if ( myNodeIsChecked.size() == nbNodes ) { std::fill( myNodeIsChecked.begin(), myNodeIsChecked.end(), false ); } else { SMESHUtils::FreeVector( myNodeIsChecked ); SMESHUtils::FreeVector( myNodeIsOut ); myNodeIsChecked.resize( nbNodes, false ); myNodeIsOut.resize( nbNodes ); } } } bool ElementsOnShape::getNodeIsOut( const SMDS_MeshNode* n, bool& isOut ) { if ( n->GetID() >= (int) myNodeIsChecked.size() || !myNodeIsChecked[ n->GetID() ]) return false; isOut = myNodeIsOut[ n->GetID() ]; return true; } void ElementsOnShape::setNodeIsOut( const SMDS_MeshNode* n, bool isOut ) { if ( n->GetID() < (int) myNodeIsChecked.size() ) { myNodeIsChecked[ n->GetID() ] = true; myNodeIsOut [ n->GetID() ] = isOut; } } void ElementsOnShape::SetShape (const TopoDS_Shape& theShape, const SMDSAbs_ElementType theType) { myType = theType; myShape = theShape; if ( myShape.IsNull() ) return; TopTools_IndexedMapOfShape shapesMap; TopAbs_ShapeEnum shapeTypes[4] = { TopAbs_SOLID, TopAbs_FACE, TopAbs_EDGE, TopAbs_VERTEX }; TopExp_Explorer sub; for ( int i = 0; i < 4; ++i ) { if ( shapesMap.IsEmpty() ) for ( sub.Init( myShape, shapeTypes[i] ); sub.More(); sub.Next() ) shapesMap.Add( sub.Current() ); if ( i > 0 ) for ( sub.Init( myShape, shapeTypes[i], shapeTypes[i-1] ); sub.More(); sub.Next() ) shapesMap.Add( sub.Current() ); } clearClassifiers(); myClassifiers.resize( shapesMap.Extent() ); for ( int i = 0; i < shapesMap.Extent(); ++i ) myClassifiers[ i ] = new TClassifier( shapesMap( i+1 ), myToler ); if ( theType == SMDSAbs_Node ) { SMESHUtils::FreeVector( myNodeIsChecked ); SMESHUtils::FreeVector( myNodeIsOut ); } else { std::fill( myNodeIsChecked.begin(), myNodeIsChecked.end(), false ); } } void ElementsOnShape::clearClassifiers() { for ( size_t i = 0; i < myClassifiers.size(); ++i ) delete myClassifiers[ i ]; myClassifiers.clear(); } bool ElementsOnShape::IsSatisfy (long elemId) { const SMDS_Mesh* mesh = myMeshModifTracer.GetMesh(); const SMDS_MeshElement* elem = ( myType == SMDSAbs_Node ? mesh->FindNode( elemId ) : mesh->FindElement( elemId )); if ( !elem || myClassifiers.empty() ) return false; bool isSatisfy = myAllNodesFlag, isNodeOut; gp_XYZ centerXYZ (0, 0, 0); SMDS_ElemIteratorPtr aNodeItr = elem->nodesIterator(); while (aNodeItr->more() && (isSatisfy == myAllNodesFlag)) { SMESH_TNodeXYZ aPnt( aNodeItr->next() ); centerXYZ += aPnt; isNodeOut = true; if ( !getNodeIsOut( aPnt._node, isNodeOut )) { for ( size_t i = 0; i < myClassifiers.size() && isNodeOut; ++i ) isNodeOut = myClassifiers[i]->IsOut( aPnt ); setNodeIsOut( aPnt._node, isNodeOut ); } isSatisfy = !isNodeOut; } // Check the center point for volumes MantisBug 0020168 if (isSatisfy && myAllNodesFlag && myClassifiers[0]->ShapeType() == TopAbs_SOLID) { centerXYZ /= elem->NbNodes(); isSatisfy = false; for ( size_t i = 0; i < myClassifiers.size() && !isSatisfy; ++i ) isSatisfy = ! myClassifiers[i]->IsOut( centerXYZ ); } return isSatisfy; } TopAbs_ShapeEnum ElementsOnShape::TClassifier::ShapeType() const { return myShape.ShapeType(); } bool ElementsOnShape::TClassifier::IsOut(const gp_Pnt& p) { return (this->*myIsOutFun)( p ); } void ElementsOnShape::TClassifier::Init (const TopoDS_Shape& theShape, double theTol) { myShape = theShape; myTol = theTol; switch ( myShape.ShapeType() ) { case TopAbs_SOLID: { if ( isBox( theShape )) { myIsOutFun = & ElementsOnShape::TClassifier::isOutOfBox; } else { mySolidClfr.Load(theShape); myIsOutFun = & ElementsOnShape::TClassifier::isOutOfSolid; } break; } case TopAbs_FACE: { Standard_Real u1,u2,v1,v2; Handle(Geom_Surface) surf = BRep_Tool::Surface( TopoDS::Face( theShape )); surf->Bounds( u1,u2,v1,v2 ); myProjFace.Init(surf, u1,u2, v1,v2, myTol ); myIsOutFun = & ElementsOnShape::TClassifier::isOutOfFace; break; } case TopAbs_EDGE: { Standard_Real u1, u2; Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge(theShape), u1, u2); myProjEdge.Init(curve, u1, u2); myIsOutFun = & ElementsOnShape::TClassifier::isOutOfEdge; break; } case TopAbs_VERTEX:{ myVertexXYZ = BRep_Tool::Pnt( TopoDS::Vertex( theShape ) ); myIsOutFun = & ElementsOnShape::TClassifier::isOutOfVertex; break; } default: throw SALOME_Exception("Programmer error in usage of ElementsOnShape::TClassifier"); } } bool ElementsOnShape::TClassifier::isOutOfSolid (const gp_Pnt& p) { mySolidClfr.Perform( p, myTol ); return ( mySolidClfr.State() != TopAbs_IN && mySolidClfr.State() != TopAbs_ON ); } bool ElementsOnShape::TClassifier::isOutOfBox (const gp_Pnt& p) { return myBox.IsOut( p.XYZ() ); } bool ElementsOnShape::TClassifier::isOutOfFace (const gp_Pnt& p) { myProjFace.Perform( p ); if ( myProjFace.IsDone() && myProjFace.LowerDistance() <= myTol ) { // check relatively to the face Quantity_Parameter u, v; myProjFace.LowerDistanceParameters(u, v); gp_Pnt2d aProjPnt (u, v); BRepClass_FaceClassifier aClsf ( TopoDS::Face( myShape ), aProjPnt, myTol ); if ( aClsf.State() == TopAbs_IN || aClsf.State() == TopAbs_ON ) return false; } return true; } bool ElementsOnShape::TClassifier::isOutOfEdge (const gp_Pnt& p) { myProjEdge.Perform( p ); return ! ( myProjEdge.NbPoints() > 0 && myProjEdge.LowerDistance() <= myTol ); } bool ElementsOnShape::TClassifier::isOutOfVertex(const gp_Pnt& p) { return ( myVertexXYZ.Distance( p ) > myTol ); } bool ElementsOnShape::TClassifier::isBox (const TopoDS_Shape& theShape) { TopTools_IndexedMapOfShape vMap; TopExp::MapShapes( theShape, TopAbs_VERTEX, vMap ); if ( vMap.Extent() != 8 ) return false; myBox.Clear(); for ( int i = 1; i <= 8; ++i ) myBox.Add( BRep_Tool::Pnt( TopoDS::Vertex( vMap( i ))).XYZ() ); gp_XYZ pMin = myBox.CornerMin(), pMax = myBox.CornerMax(); for ( int i = 1; i <= 8; ++i ) { gp_Pnt p = BRep_Tool::Pnt( TopoDS::Vertex( vMap( i ))); for ( int iC = 1; iC <= 3; ++ iC ) { double d1 = Abs( pMin.Coord( iC ) - p.Coord( iC )); double d2 = Abs( pMax.Coord( iC ) - p.Coord( iC )); if ( Min( d1, d2 ) > myTol ) return false; } } myBox.Enlarge( myTol ); return true; } /* Class : BelongToGeom Description : Predicate for verifying whether entity belongs to specified geometrical support */ BelongToGeom::BelongToGeom() : myMeshDS(NULL), myType(SMDSAbs_All), myIsSubshape(false), myTolerance(Precision::Confusion()) {} void BelongToGeom::SetMesh( const SMDS_Mesh* theMesh ) { myMeshDS = dynamic_cast<const SMESHDS_Mesh*>(theMesh); init(); } void BelongToGeom::SetGeom( const TopoDS_Shape& theShape ) { myShape = theShape; init(); } static bool IsSubShape (const TopTools_IndexedMapOfShape& theMap, const TopoDS_Shape& theShape) { if (theMap.Contains(theShape)) return true; if (theShape.ShapeType() == TopAbs_COMPOUND || theShape.ShapeType() == TopAbs_COMPSOLID) { TopoDS_Iterator anIt (theShape, Standard_True, Standard_True); for (; anIt.More(); anIt.Next()) { if (!IsSubShape(theMap, anIt.Value())) { return false; } } return true; } return false; } void BelongToGeom::init() { if (!myMeshDS || myShape.IsNull()) return; // is sub-shape of main shape? TopoDS_Shape aMainShape = myMeshDS->ShapeToMesh(); if (aMainShape.IsNull()) { myIsSubshape = false; } else { TopTools_IndexedMapOfShape aMap; TopExp::MapShapes(aMainShape, aMap); myIsSubshape = IsSubShape(aMap, myShape); } //if (!myIsSubshape) // to be always ready to check an element not bound to geometry { myElementsOnShapePtr.reset(new ElementsOnShape()); myElementsOnShapePtr->SetTolerance(myTolerance); myElementsOnShapePtr->SetAllNodes(true); // "belong", while false means "lays on" myElementsOnShapePtr->SetMesh(myMeshDS); myElementsOnShapePtr->SetShape(myShape, myType); } } static bool IsContains( const SMESHDS_Mesh* theMeshDS, const TopoDS_Shape& theShape, const SMDS_MeshElement* theElem, TopAbs_ShapeEnum theFindShapeEnum, TopAbs_ShapeEnum theAvoidShapeEnum = TopAbs_SHAPE ) { TopExp_Explorer anExp( theShape,theFindShapeEnum,theAvoidShapeEnum ); while( anExp.More() ) { const TopoDS_Shape& aShape = anExp.Current(); if( SMESHDS_SubMesh* aSubMesh = theMeshDS->MeshElements( aShape ) ){ if( aSubMesh->Contains( theElem ) ) return true; } anExp.Next(); } return false; } bool BelongToGeom::IsSatisfy (long theId) { if (myMeshDS == 0 || myShape.IsNull()) return false; if (!myIsSubshape) { return myElementsOnShapePtr->IsSatisfy(theId); } // Case of submesh if (myType == SMDSAbs_Node) { if( const SMDS_MeshNode* aNode = myMeshDS->FindNode( theId ) ) { if ( aNode->getshapeId() < 1 ) return myElementsOnShapePtr->IsSatisfy(theId); const SMDS_PositionPtr& aPosition = aNode->GetPosition(); SMDS_TypeOfPosition aTypeOfPosition = aPosition->GetTypeOfPosition(); switch( aTypeOfPosition ) { case SMDS_TOP_VERTEX : return ( IsContains( myMeshDS,myShape,aNode,TopAbs_VERTEX )); case SMDS_TOP_EDGE : return ( IsContains( myMeshDS,myShape,aNode,TopAbs_EDGE )); case SMDS_TOP_FACE : return ( IsContains( myMeshDS,myShape,aNode,TopAbs_FACE )); case SMDS_TOP_3DSPACE: return ( IsContains( myMeshDS,myShape,aNode,TopAbs_SOLID ) || IsContains( myMeshDS,myShape,aNode,TopAbs_SHELL )); } } } else { if ( const SMDS_MeshElement* anElem = myMeshDS->FindElement( theId )) { if ( anElem->getshapeId() < 1 ) return myElementsOnShapePtr->IsSatisfy(theId); if( myType == SMDSAbs_All ) { return ( IsContains( myMeshDS,myShape,anElem,TopAbs_EDGE ) || IsContains( myMeshDS,myShape,anElem,TopAbs_FACE ) || IsContains( myMeshDS,myShape,anElem,TopAbs_SOLID )|| IsContains( myMeshDS,myShape,anElem,TopAbs_SHELL )); } else if( myType == anElem->GetType() ) { switch( myType ) { case SMDSAbs_Edge : return ( IsContains( myMeshDS,myShape,anElem,TopAbs_EDGE )); case SMDSAbs_Face : return ( IsContains( myMeshDS,myShape,anElem,TopAbs_FACE )); case SMDSAbs_Volume: return ( IsContains( myMeshDS,myShape,anElem,TopAbs_SOLID )|| IsContains( myMeshDS,myShape,anElem,TopAbs_SHELL )); } } } } return false; } void BelongToGeom::SetType (SMDSAbs_ElementType theType) { myType = theType; init(); } SMDSAbs_ElementType BelongToGeom::GetType() const { return myType; } TopoDS_Shape BelongToGeom::GetShape() { return myShape; } const SMESHDS_Mesh* BelongToGeom::GetMeshDS() const { return myMeshDS; } void BelongToGeom::SetTolerance (double theTolerance) { myTolerance = theTolerance; if (!myIsSubshape) init(); } double BelongToGeom::GetTolerance() { return myTolerance; } /* Class : LyingOnGeom Description : Predicate for verifying whether entiy lying or partially lying on specified geometrical support */ LyingOnGeom::LyingOnGeom() : myMeshDS(NULL), myType(SMDSAbs_All), myIsSubshape(false), myTolerance(Precision::Confusion()) {} void LyingOnGeom::SetMesh( const SMDS_Mesh* theMesh ) { myMeshDS = dynamic_cast<const SMESHDS_Mesh*>(theMesh); init(); } void LyingOnGeom::SetGeom( const TopoDS_Shape& theShape ) { myShape = theShape; init(); } void LyingOnGeom::init() { if (!myMeshDS || myShape.IsNull()) return; // is sub-shape of main shape? TopoDS_Shape aMainShape = myMeshDS->ShapeToMesh(); if (aMainShape.IsNull()) { myIsSubshape = false; } else { myIsSubshape = myMeshDS->IsGroupOfSubShapes( myShape ); } if (myIsSubshape) { TopTools_IndexedMapOfShape shapes; TopExp::MapShapes( myShape, shapes ); mySubShapesIDs.Clear(); for ( int i = 1; i <= shapes.Extent(); ++i ) { int subID = myMeshDS->ShapeToIndex( shapes( i )); if ( subID > 0 ) mySubShapesIDs.Add( subID ); } } else { myElementsOnShapePtr.reset(new ElementsOnShape()); myElementsOnShapePtr->SetTolerance(myTolerance); myElementsOnShapePtr->SetAllNodes(false); // lays on, while true means "belong" myElementsOnShapePtr->SetMesh(myMeshDS); myElementsOnShapePtr->SetShape(myShape, myType); } } bool LyingOnGeom::IsSatisfy( long theId ) { if ( myMeshDS == 0 || myShape.IsNull() ) return false; if (!myIsSubshape) { return myElementsOnShapePtr->IsSatisfy(theId); } // Case of sub-mesh const SMDS_MeshElement* elem = ( myType == SMDSAbs_Node ) ? myMeshDS->FindNode( theId ) : myMeshDS->FindElement( theId ); if ( mySubShapesIDs.Contains( elem->getshapeId() )) return true; if ( elem->GetType() != SMDSAbs_Node ) { SMDS_ElemIteratorPtr nodeItr = elem->nodesIterator(); while ( nodeItr->more() ) { const SMDS_MeshElement* aNode = nodeItr->next(); if ( mySubShapesIDs.Contains( aNode->getshapeId() )) return true; } } return false; } void LyingOnGeom::SetType( SMDSAbs_ElementType theType ) { myType = theType; init(); } SMDSAbs_ElementType LyingOnGeom::GetType() const { return myType; } TopoDS_Shape LyingOnGeom::GetShape() { return myShape; } const SMESHDS_Mesh* LyingOnGeom::GetMeshDS() const { return myMeshDS; } void LyingOnGeom::SetTolerance (double theTolerance) { myTolerance = theTolerance; if (!myIsSubshape) init(); } double LyingOnGeom::GetTolerance() { return myTolerance; } bool LyingOnGeom::Contains( const SMESHDS_Mesh* theMeshDS, const TopoDS_Shape& theShape, const SMDS_MeshElement* theElem, TopAbs_ShapeEnum theFindShapeEnum, TopAbs_ShapeEnum theAvoidShapeEnum ) { // if (IsContains(theMeshDS, theShape, theElem, theFindShapeEnum, theAvoidShapeEnum)) // return true; // TopTools_MapOfShape aSubShapes; // TopExp_Explorer exp( theShape, theFindShapeEnum, theAvoidShapeEnum ); // for ( ; exp.More(); exp.Next() ) // { // const TopoDS_Shape& aShape = exp.Current(); // if ( !aSubShapes.Add( aShape )) continue; // if ( SMESHDS_SubMesh* aSubMesh = theMeshDS->MeshElements( aShape )) // { // if ( aSubMesh->Contains( theElem )) // return true; // SMDS_ElemIteratorPtr nodeItr = theElem->nodesIterator(); // while ( nodeItr->more() ) // { // const SMDS_MeshElement* aNode = nodeItr->next(); // if ( aSubMesh->Contains( aNode )) // return true; // } // } // } return false; } TSequenceOfXYZ::TSequenceOfXYZ(): myElem(0) {} TSequenceOfXYZ::TSequenceOfXYZ(size_type n) : myArray(n), myElem(0) {} TSequenceOfXYZ::TSequenceOfXYZ(size_type n, const gp_XYZ& t) : myArray(n,t), myElem(0) {} TSequenceOfXYZ::TSequenceOfXYZ(const TSequenceOfXYZ& theSequenceOfXYZ) : myArray(theSequenceOfXYZ.myArray), myElem(theSequenceOfXYZ.myElem) {} template <class InputIterator> TSequenceOfXYZ::TSequenceOfXYZ(InputIterator theBegin, InputIterator theEnd): myArray(theBegin,theEnd), myElem(0) {} TSequenceOfXYZ::~TSequenceOfXYZ() {} TSequenceOfXYZ& TSequenceOfXYZ::operator=(const TSequenceOfXYZ& theSequenceOfXYZ) { myArray = theSequenceOfXYZ.myArray; myElem = theSequenceOfXYZ.myElem; return *this; } gp_XYZ& TSequenceOfXYZ::operator()(size_type n) { return myArray[n-1]; } const gp_XYZ& TSequenceOfXYZ::operator()(size_type n) const { return myArray[n-1]; } void TSequenceOfXYZ::clear() { myArray.clear(); } void TSequenceOfXYZ::reserve(size_type n) { myArray.reserve(n); } void TSequenceOfXYZ::push_back(const gp_XYZ& v) { myArray.push_back(v); } TSequenceOfXYZ::size_type TSequenceOfXYZ::size() const { return myArray.size(); } SMDSAbs_EntityType TSequenceOfXYZ::getElementEntity() const { return myElem ? myElem->GetEntityType() : SMDSEntity_Last; } TMeshModifTracer::TMeshModifTracer(): myMeshModifTime(0), myMesh(0) { } void TMeshModifTracer::SetMesh( const SMDS_Mesh* theMesh ) { if ( theMesh != myMesh ) myMeshModifTime = 0; myMesh = theMesh; } bool TMeshModifTracer::IsMeshModified() { bool modified = false; if ( myMesh ) { modified = ( myMeshModifTime != myMesh->GetMTime() ); myMeshModifTime = myMesh->GetMTime(); } return modified; }
timthelion/FreeCAD
src/3rdParty/salomesmesh/src/Controls/SMESH_Controls.cpp
C++
lgpl-2.1
138,589
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "ASTPath.h" #include <AST.h> #include <TranslationUnit.h> #ifdef DEBUG_AST_PATH # include <QDebug> # include <typeinfo> #endif // DEBUG_AST_PATH using namespace CPlusPlus; QList<AST *> ASTPath::operator()(int line, int column) { _nodes.clear(); _line = line; _column = column; if (_doc) { if (TranslationUnit *unit = _doc->translationUnit()) accept(unit->ast()); } return _nodes; } #ifdef DEBUG_AST_PATH void ASTPath::dump(const QList<AST *> nodes) { qDebug() << "ASTPath dump," << nodes.size() << "nodes:"; for (int i = 0; i < nodes.size(); ++i) qDebug() << qPrintable(QString(i + 1, QLatin1Char('-'))) << typeid(*nodes.at(i)).name(); } #endif // DEBUG_AST_PATH bool ASTPath::preVisit(AST *ast) { unsigned firstToken = ast->firstToken(); unsigned lastToken = ast->lastToken(); if (firstToken > 0) { if (lastToken <= firstToken) return false; unsigned startLine, startColumn; getTokenStartPosition(firstToken, &startLine, &startColumn); if (_line > startLine || (_line == startLine && _column >= startColumn)) { unsigned endLine, endColumn; getTokenEndPosition(lastToken - 1, &endLine, &endColumn); if (_line < endLine || (_line == endLine && _column <= endColumn)) { _nodes.append(ast); return true; } } } return false; }
ostash/qt-creator-i18n-uk
src/libs/cplusplus/ASTPath.cpp
C++
lgpl-2.1
2,743
//Version-IE: < 9 if ( 'function' !== typeof Array.prototype.reduce ) { Array.prototype.reduce = function( callback /*, initialValue*/ ) { 'use strict'; if ( null === this || 'undefined' === typeof this ) { throw new TypeError( 'Array.prototype.reduce called on null or undefined' ); } if ( 'function' !== typeof callback ) { throw new TypeError( callback + ' is not a function' ); } var t = Object( this ), len = t.length >>> 0, k = 0, value; if ( arguments.length >= 2 ) { value = arguments[1]; } else { while ( k < len && ! k in t ) k++; if ( k >= len ) throw new TypeError('Reduce of empty array with no initial value'); value = t[ k++ ]; } for ( ; k < len ; k++ ) { if ( k in t ) { value = callback( value, t[k], k, t ); } } return value; }; } //Version-IE: < 9 if ( 'function' !== typeof Array.prototype.reduceRight ) { Array.prototype.reduceRight = function( callback /*, initialValue*/ ) { 'use strict'; if ( null === this || 'undefined' === typeof this ) { throw new TypeError( 'Array.prototype.reduce called on null or undefined' ); } if ( 'function' !== typeof callback ) { throw new TypeError( callback + ' is not a function' ); } var t = Object( this ), len = t.length >>> 0, k = len - 1, value; if ( arguments.length >= 2 ) { value = arguments[1]; } else { while ( k >= 0 && ! k in t ) k--; if ( k < 0 ) throw new TypeError('Reduce of empty array with no initial value'); value = t[ k-- ]; } for ( ; k >= 0 ; k-- ) { if ( k in t ) { value = callback( value, t[k], k, t ); } } return value; }; } //Version-IE: < 9 if (!Array.prototype.filter) { Array.prototype.filter = function(fun /*, thisArg */) { "use strict"; if (this === void 0 || this === null) throw new TypeError(); var t = Object(this); var len = t.length >>> 0; if (typeof fun !== "function") throw new TypeError(); var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // NOTE: Technically this should Object.defineProperty at // the next index, as push can be affected by // properties on Object.prototype and Array.prototype. // But that method's new, and collisions should be // rare, so use the more-compatible alternative. if (fun.call(<span style="line-height: normal;">thisArg</span><span style="line-height: normal;">, val, i, t))</span> res.push(val); } } return res; }; } //Version-IE: < 9 if (!Array.prototype.every) { Array.prototype.every = function (callbackfn, thisArg) { "use strict"; var T, k; if (this == null) { throw new TypeError("this is null or not defined"); } // 1. Let O be the result of calling ToObject passing the this // value as the argument. var O = Object(this); // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // 4. If IsCallable(callbackfn) is false, throw a TypeError exception. if (typeof callbackfn !== "function") { throw new TypeError(); } // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. if (arguments.length > 1) { T = thisArg; } // 6. Let k be 0. k = 0; // 7. Repeat, while k < len while (k < len) { var kValue; // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the HasProperty internal // method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then if (k in O) { // i. Let kValue be the result of calling the Get internal method of O with argument Pk. kValue = O[k]; // ii. Let testResult be the result of calling the Call internal method // of callbackfn with T as the this value and argument list // containing kValue, k, and O. var testResult = callbackfn.call(T, kValue, k, O); // iii. If ToBoolean(testResult) is false, return false. if (!testResult) { return false; } } k++; } return true; }; } //Version-IE: < 9 if (!Array.prototype.some) { Array.prototype.some = function(fun /*, thisArg */) { 'use strict'; if (this === void 0 || this === null) throw new TypeError(); var t = Object(this); var len = t.length >>> 0; if (typeof fun !== 'function') throw new TypeError(); var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t && fun.call(thisArg, t[i], i, t)) return true; } return false; }; } // Production steps of ECMA-262, Edition 5, 15.4.4.19 // Reference: http://es5.github.com/#x15.4.4.19 //Version-IE: < 9 if (!Array.prototype.map) { Array.prototype.map = function (callback, thisArg) { var T, A, k; if (this == null) { throw new TypeError(" this is null or not defined"); } // 1. Let O be the result of calling ToObject passing the |this| value as the argument. var O = Object(this); // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // 4. If IsCallable(callback) is false, throw a TypeError exception. // See: http://es5.github.com/#x9.11 if (typeof callback !== "function") { throw new TypeError(callback + " is not a function"); } // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. if (arguments.length > 1) { T = thisArg; } // 6. Let A be a new array created as if by the expression new Array( len) where Array is // the standard built-in constructor with that name and len is the value of len. A = new Array(len); // 7. Let k be 0 k = 0; // 8. Repeat, while k < len while (k < len) { var kValue, mappedValue; // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then if (k in O) { // i. Let kValue be the result of calling the Get internal method of O with argument Pk. kValue = O[k]; // ii. Let mappedValue be the result of calling the Call internal method of callback // with T as the this value and argument list containing kValue, k, and O. mappedValue = callback.call(T, kValue, k, O); // iii. Call the DefineOwnProperty internal method of A with arguments // Pk, Property Descriptor {Value: mappedValue, Writable: true, Enumerable: true, Configurable: true}, // and false. // In browsers that support Object.defineProperty, use the following: // Object.defineProperty( A, k, { value: mappedValue, writable: true, enumerable: true, configurable: true }); // For best browser support, use the following: A[k] = mappedValue; } // d. Increase k by 1. k++; } // 9. return A return A; }; } // Production steps of ECMA-262, Edition 5, 15.4.4.18 // Reference: http://es5.github.com/#x15.4.4.18 //Version-IE: < 9 if (!Array.prototype.forEach) { Array.prototype.forEach = function (callback, thisArg) { var T, k; if (this == null) { throw new TypeError(" this is null or not defined"); } // 1. Let O be the result of calling ToObject passing the |this| value as the argument. var O = Object(this); // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // 4. If IsCallable(callback) is false, throw a TypeError exception. // See: http://es5.github.com/#x9.11 if (typeof callback !== "function") { throw new TypeError(callback + " is not a function"); } // 5. If thisArg was supplied, let T be thisArg; else let T be undefined. if (arguments.length > 1) { T = thisArg; } // 6. Let k be 0 k = 0; // 7. Repeat, while k < len while (k < len) { var kValue; // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then if (k in O) { // i. Let kValue be the result of calling the Get internal method of O with argument Pk. kValue = O[k]; // ii. Call the Call internal method of callback with T as the this value and // argument list containing kValue, k, and O. callback.call(T, kValue, k, O); } // d. Increase k by 1. k++; } // 8. return undefined }; }
OCamlPro-Henry/js_of_ocaml
runtime/polyfill/array.js
JavaScript
lgpl-2.1
9,421
<!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>ECShop_mobile</title> </head> <body> <p align='left'> 用户中心<br/> --------------<br/> <a href='user.php?act=order_list'>我的订单</a><br/> --------------<br/> 商城推荐产品<br/> {foreach from=$best_goods item=best_data} <a href='goods.php?id={$best_data.id}'>{$best_data.name}</a>[{$best_data.shop_price}]<br/> {/foreach} --------------<br/> <a href='index.php'>返回首页</a> {$footer} </p> </body> </html>
tiger-young/ecallaShop
mobile/templates/user.html
HTML
lgpl-2.1
679
/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2011 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <gadget/gadgetConfig.h> #include <jccl/Config/ConfigElement.h> #include <gadget/Devices/Sim/SimDigital.h> namespace gadget { /** Default Constructor */ SimDigital::SimDigital() { vprDEBUG(vprDBG_ALL, vprDBG_VERB_LVL)<<"*** SimDigital::SimDigital()\n"<< vprDEBUG_FLUSH; } /** Destructor */ SimDigital::~SimDigital() { //vprDEBUG(vprDBG_ALL, vprDBG_VERB_LVL)<<"*** SimDigital::~SimDigital()\n"<< vprDEBUG_FLUSH; } std::string SimDigital::getElementType() { return "simulated_digital_device"; } bool SimDigital::config(jccl::ConfigElementPtr element) { //vprDEBUG(vprDBG_ALL, vprDBG_VERB_LVL)<<"*** SimDigital::config()\n"<< vprDEBUG_FLUSH; if (! (Input::config(element) && Digital::config(element) && SimInput::config(element)) ) { return false; } std::vector<jccl::ConfigElementPtr> key_list; int key_count = element->getNum("key_pair"); for ( int i = 0; i < key_count; ++i ) { key_list.push_back(element->getProperty<jccl::ConfigElementPtr>("key_pair", i)); } mSimKeys = readKeyList(key_list); return true; } /** * Updates the state of the digital data vector. * * @note Digital is on when key is held down. * When key is release, digital goes to off state. */ void SimDigital::updateData() { //vprDEBUG(vprDBG_ALL, vprDBG_VERB_LVL)<<"*** SimDigital::updateData()\n"<< vprDEBUG_FLUSH; std::vector<DigitalData> digital_data_sample(mSimKeys.size()); // The digital data that makes up the sample // -- Update digital data --- // for (unsigned int i = 0; i < mSimKeys.size(); ++i) { // Set the time for the digital data to the KeyboardMouse timestamp digital_data_sample[i].setTime(mKeyboardMouse->getTimeStamp()); // ON if keys pressed, OFF otherwise. digital_data_sample[i] = checkKeyPair(mSimKeys[i]) ? DigitalState::ON : DigitalState::OFF; } // Add a sample addDigitalSample(digital_data_sample); swapDigitalBuffers(); } } // End of gadget namespace
vrjuggler/vrjuggler
modules/gadgeteer/gadget/Devices/Sim/SimDigital.cpp
C++
lgpl-2.1
3,184
// Copyright (c)2008-2011, Preferred Infrastructure Inc. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // // * Neither the name of Preferred Infrastructure nor the names of other // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /** Range minimum query (rmq) in O(log N) time and O(N) precomputed information. */ /* Implementation is based on Johannes Fischer, Volker Heun. "Theoretical and Practical Improvements on the RMQ-Problem, with Applications to LCA and LCE", Proceedings of the 17th Annual Symposium on Combinatorial Pattern Matching (CPM'06), Lecture Notes in Computer Science 4009, 36-48, Springer-Verlag, 2006. and Johannes Fischer, Volker Heun. "A New Succinct Representation of RMQ-Information and Improvements in the Enhanced Suffix Array", Proceedings of the International Symposium on Combinatorics, Algorithms, Probabilistic and Experimental Methodologies (ESCAPE'07), Lecture Notes in Computer Science 4614, 459-470, Springer-Verlag, 2007. but modified for simplicity. There are two differences in Fischer'07 and this implementation: * Blocks / superblocks are replaced by Catalan number representation. * Use precomputed Catalan number table for all blocks. * Use O(16/7 N) bits Drawback of this method is query time of order O(log(8)N). It takes about 10 recursion to calculate RMQ if N = 1e9. FIXME: compare speed with another implementation. especially when RMQ is changed to Bender & Farach's (O(NlogN),O(1)) */ /* Large block_size may cause overflow. FYI: C = 4^s / (sqrt(pi) * s^(3/2)) s | C ---+----- 8 | 1635 10 | 19K 16 | 38M 20 | 6.9G */ #include <vector> #include <iterator> #include <climits> // new in C99, but // nowadays almost all compilers should have it #include <stdint.h> namespace jubatus { namespace util { namespace data { namespace suffix_array { namespace { enum { block_bits = 3, block_size = 1 << block_bits, block_size_sq = block_size * (block_size+1) / 2, block_access_depth = 3 }; // enough to fit in int16 typedef int16_t block_type; /** Ballot number table. Generated from balgen.hs, with s = 8 */ const int ballot_table[block_size+1][block_size+1] = { #include "ballot_num8.dat" }; /** Minimum position table for cartesian types */ const unsigned char cartesian_table[][block_size_sq] = { #include "cartesian_table8.dat" }; /** RMQ(i,j) -> cartesian_table[foo][access_table[i][j]] conversion */ const int access_table[block_size][block_size] = { { 0, 1, 2, 3, 4, 5, 6, 7, }, { -1, 8, 9, 10, 11, 12, 13, 14, }, { -1, -1, 15, 16, 17, 18, 19, 20, }, { -1, -1, -1, 21, 22, 23, 24, 25, }, { -1, -1, -1, -1, 26, 27, 28, 29, }, { -1, -1, -1, -1, -1, 30, 31, 32, }, { -1, -1, -1, -1, -1, -1, 33, 34, }, { -1, -1, -1, -1, -1, -1, -1, 35, }, }; const int msb_table[256] = { 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, }; const int all_block = access_table[0][block_size - 1]; int get_msb(unsigned int b){ if(b >= (1 << 24)) return 24 + msb_table[b >> 24]; if(b >= (1 << 16)) return 16 + msb_table[b >> 16]; if(b >= (1 << 8)) return 8 + msb_table[b >> 8]; return msb_table[b]; } /** Calculate cartesian tree's "type". See J. Fischer and V. Heun, "New succinct ... " @param b Beginning of iterator that points to the sequence of number @return cartesian tree type */ const int infty = INT_MAX; const int neg_infty = INT_MIN; template<typename IT> int cartesian_type(IT b){ const size_t s = block_size; // FIXME: remove this "R" reconstruction for speeding up std::vector<int> R(s+1); R[0] = neg_infty; int q = s; int N = 0; for(size_t i = 0; i < s; ++i){ while(R[q + i - s] > *(b+i)){ N += ballot_table[s-(i+1)][q]; --q; } R[q+i+1-s] = *(b+i); } return N; } /** This routine is used if s != distance(b,e). */ template<typename IT> int cartesian_type(IT b, IT e){ const size_t real_s = std::distance(b, e); const size_t s = block_size; std::vector<int> R(s+1); R[0] = neg_infty; int q = s; int N = 0; for(size_t i = 0; i < real_s; ++i){ while(R[q + i - s] > *(b+i)){ N += ballot_table[s-(i+1)][q]; --q; } R[q+i+1-s] = *(b+i); } return N; } } /** Range-minimum-query data structure */ template<typename CONT> class rmq{ typedef typename CONT::value_type T; public: /** RMQ constructor. takes container v and precompute data structure @param v target container */ rmq(const CONT &v): orig(v), types(block_access_depth), log_rmq_table(){ construct_type(v.begin(), v.end(), 0); } /* TODO: load/save from file */ /** RMQ query in the range [l,r]. (right inclusive) @param l leftmost range @param r rightmost range (inclusive) @return position of minimum element */ int query(int l, int r){ int buf[(block_access_depth << 1) + 1]; for(size_t i = 0; i < (block_access_depth << 1) + 1; ++i) buf[i] = -1; return query_iter(l, r, 0, buf); } /** RMQ query in the range [l,r). (right exclusive) @param l leftmost range @param r rightmost range (exclusive) @return position of minimum element */ int query_exclusive(int l, int r){ return query(l, r-1); } private: const CONT &orig; std::vector<std::vector<block_type> > types; std::vector<std::vector<int> > log_rmq_table; template<typename IT> void construct_type(IT b, IT e, int level){ if(level >= block_access_depth) { construct_log_table(b, e); return; } size_t s = std::distance(b, e); size_t blks = (s + block_size - 1) >> block_bits; size_t blks_p = s >> block_bits; std::vector<block_type> &tys = types[level]; std::vector<T> rm(blks); tys.resize(blks); // cartesian type calculation { IT it(b); for(size_t i = 0; i < blks_p; ++i){ int ty = cartesian_type(it); tys[i] = ty; rm[i] = *(it + cartesian_table[ty][all_block]); it += block_size; } if(blks != blks_p){ int ty = cartesian_type(it, e); tys[blks_p] = ty; rm[blks_p] = *(it + cartesian_table[ty][all_block]); } } // FIXME: is this tail-recursive? construct_type(rm.begin(), rm.end(), level + 1); } template<typename IT> void construct_log_table(IT b, IT e){ // four-russian-trick size_t s = std::distance(b, e); log_rmq_table.clear(); { // first pass: fill k = 1 case log_rmq_table.push_back(std::vector<int>(s-1)); std::vector<int> &log_cur_table = log_rmq_table.back(); int lmin_ = -1; IT it(b); for(size_t i = 0; i < s-1; ++i, ++it){ if(*it < *(it+1)){ log_cur_table[i] = (lmin_ >= 0 ? lmin_: query_super_cartesian_block(i)); lmin_ = -1; }else{ int rmin = query_super_cartesian_block(i+1); log_cur_table[i] = rmin; lmin_ = rmin; } } } for(size_t k = 2; (1U<<k) < s; ++k){ int prev_size = 1 << (k-1); int cur_size = 1 << k; log_rmq_table.push_back(std::vector<int>(s-cur_size+1)); std::vector<int> &prev = log_rmq_table[k-2]; std::vector<int> &cur = log_rmq_table.back(); for(size_t i = 0; i < s - cur_size + 1; ++i){ // try not to call query_super_cartesian_block again int lm_ = prev[i]; int lm = lm_ >> (block_bits * block_access_depth); int rm_ = prev[i + prev_size]; int rm = rm_ >> (block_bits * block_access_depth); cur[i] = (*(b+lm) < *(b+rm) ? lm_ : rm_); } } } int query_in_cartesian_block(int level, int blockpos){ int ty = types[level][blockpos]; return cartesian_table[ty][all_block]; } int query_cartesian_block(int level, int super_blockpos){ int pos = super_blockpos; for(int l = level; l >= 0; --l){ pos = (pos << block_bits) + query_in_cartesian_block(l, pos); } return pos; } int query_super_cartesian_block(int super_blockpos){ return query_cartesian_block(block_access_depth - 1, super_blockpos); } int query_iter(int l, int r, int level, int* buf){ if(level >= block_access_depth) return query_iter_super_block(l, r, buf); int lb = l >> block_bits; int lh = l & (block_size - 1); int rb = r >> block_bits; int rh = r & (block_size - 1); std::vector<block_type> &tys = types[level]; if(lb >= rb){ // in-block query if(l <= r){ buf[block_access_depth] = query_cartesian_block(level - 1, // level = 0 -> ok (lb << block_bits) + cartesian_table[tys[lb]][access_table[lh][rh]]); } return best_in_buf(buf); }else{ // out-of-block query if(lh != 0){ buf[level] = query_cartesian_block(level-1, (lb << block_bits) + cartesian_table[tys[lb]][access_table[lh][block_size-1]]); lb++; } if(rh != block_size - 1){ buf[(block_access_depth << 1) - level] = query_cartesian_block(level-1, (rb << block_bits) + cartesian_table[tys[rb]][access_table[0][rh]]); rb--; } return query_iter(lb, rb, level + 1, buf); } } int query_iter_super_block(int l, int r, int *buf){ r++; int s = r - l; if(s <= 0) return best_in_buf(buf); if(s == 1) { buf[block_access_depth] = query_cartesian_block(block_access_depth - 1, l); return best_in_buf(buf); } int b = get_msb(s); int bl = 1 << (b-1); int leftix = log_rmq_table[b-2][l]; int rightix = log_rmq_table[b-2][r-bl]; buf[block_access_depth] = (orig[leftix] < orig[rightix] ? leftix : rightix); return best_in_buf(buf); } int best_in_buf(int *buf){ int cur_min_ix = -1; T cur_min = T(); for(int i = 0; i < (block_access_depth << 1) + 1; ++i){ int m = buf[i]; if(m == -1) continue; T mval = orig[m]; if(cur_min_ix == -1 || mval < cur_min){ cur_min_ix = m; cur_min = mval; } } return cur_min_ix; } }; } // suffix_array } // data } // util } // jubatus
gwtnb/jubatus_core
jubatus/util/data/suffix_array/rmq.h
C
lgpl-2.1
13,357
input: clean ./copy_script gmsh -2 -bin src/MMS_A.geo gmsh -2 -bin src/MMS_B.geo gmsh -2 -bin src/MMS_C.geo run: ../../bin/fluidity MMS_A.flml ../../bin/fluidity MMS_B.flml ../../bin/fluidity MMS_C.flml clean: rm -f *.vtu *.stat *.s *_A* *_B* *_C* *_D* src/*A.* src/*B.* src/*C.* src/*D.* *.log matrix* *~ *.pyc fluidity.* nohup.out *.node *.ele *.edge
rjferrier/fluidity
tests/swe_mms_p2p1_quadratic_drag/Makefile
Makefile
lgpl-2.1
363
/* * Copyright (C) 2015 Freie Universität Berlin * * This file is subject to the terms and conditions of the GNU Lesser * General Public License v2.1. See the file LICENSE in the top level * directory for more details. */ /** * @ingroup cpu_stm32f4 * @{ * * @file * @brief CPU specific definitions for internal peripheral handling * * @author Hauke Petersen <hauke.peterse@fu-berlin.de> */ #ifndef PERIPH_CPU_H #define PERIPH_CPU_H #include "cpu.h" #ifdef __cplusplus extern "C" { #endif /** * @brief Overwrite the default gpio_t type definition * @{ */ #define HAVE_GPIO_T typedef uint32_t gpio_t; /** @} */ /** * @brief Definition of a fitting UNDEF value */ #define GPIO_UNDEF (0xffffffff) /** * @brief Define a CPU specific GPIO pin generator macro */ #define GPIO_PIN(x, y) ((GPIOA_BASE + (x << 10)) | y) /** * @brief declare needed generic SPI functions * @{ */ #define PERIPH_SPI_NEEDS_TRANSFER_BYTES #define PERIPH_SPI_NEEDS_TRANSFER_REG #define PERIPH_SPI_NEEDS_TRANSFER_REGS /** @} */ /** * @brief Available ports on the STM32F4 family */ enum { PORT_A = 0, /**< port A */ PORT_B = 1, /**< port B */ PORT_C = 2, /**< port C */ PORT_D = 3, /**< port D */ PORT_E = 4, /**< port E */ PORT_F = 5, /**< port F */ PORT_G = 6, /**< port G */ PORT_H = 7, /**< port H */ PORT_I = 8 /**< port I */ }; /** * @brief Available MUX values for configuring a pin's alternate function */ typedef enum { GPIO_AF0 = 0, /**< use alternate function 0 */ GPIO_AF1, /**< use alternate function 1 */ GPIO_AF2, /**< use alternate function 2 */ GPIO_AF3, /**< use alternate function 3 */ GPIO_AF4, /**< use alternate function 4 */ GPIO_AF5, /**< use alternate function 5 */ GPIO_AF6, /**< use alternate function 6 */ GPIO_AF7, /**< use alternate function 7 */ GPIO_AF8, /**< use alternate function 8 */ GPIO_AF9, /**< use alternate function 9 */ GPIO_AF10, /**< use alternate function 10 */ GPIO_AF11, /**< use alternate function 11 */ GPIO_AF12, /**< use alternate function 12 */ GPIO_AF13, /**< use alternate function 13 */ GPIO_AF14 /**< use alternate function 14 */ } gpio_af_t; /** * @brief Structure for UART configuration data * @{ */ typedef struct { USART_TypeDef *dev; /**< UART device base register address */ uint32_t rcc_mask; /**< bit in clock enable register */ gpio_t rx_pin; /**< RX pin */ gpio_t tx_pin; /**< TX pin */ gpio_af_t af; /**< alternate pin function to use */ uint8_t irqn; /**< IRQ channel */ uint8_t dma_stream; /**< DMA stream used for TX */ uint8_t dma_chan; /**< DMA channel used for TX */ } uart_conf_t; /** @} */ /** * @brief Configure the alternate function for the given pin * * @note This is meant for internal use in STM32F4 peripheral drivers only * * @param[in] pin pin to configure * @param[in] af alternate function to use */ void gpio_init_af(gpio_t pin, gpio_af_t af); /** * @brief Power on the DMA device the given stream belongs to * * @param[in] stream logical DMA stream */ static inline void dma_poweron(int stream) { if (stream < 8) { RCC->AHB1ENR |= RCC_AHB1ENR_DMA1EN; } else { RCC->AHB1ENR |= RCC_AHB1ENR_DMA2EN; } } /** * @brief Get DMA base register * * For simplifying DMA stream handling, we map the DMA channels transparently to * one integer number, such that DMA1 stream0 equals 0, DMA2 stream0 equals 8, * DMA2 stream 7 equals 15 and so on. * * @param[in] stream logical DMA stream */ static inline DMA_TypeDef *dma_base(int stream) { return (stream < 8) ? DMA1 : DMA2; } /** * @brief Get the DMA stream base address * * @param[in] stream logical DMA stream * * @return base address for the selected DMA stream */ static inline DMA_Stream_TypeDef *dma_stream(int stream) { uint32_t base = (uint32_t)dma_base(stream); return (DMA_Stream_TypeDef *)(base + (0x10 + (0x18 * (stream & 0x7)))); } /** * @brief Select high or low DMA interrupt register based on stream number * * @param[in] stream logical DMA stream * * @return 0 for streams 0-3, 1 for streams 3-7 */ static inline int dma_hl(int stream) { return ((stream & 0x4) >> 2); } /** * @brief Get the interrupt flag clear bit position in the DMA LIFCR register * * @param[in] stream logical DMA stream */ static inline uint32_t dma_ifc(int stream) { switch (stream & 0x3) { case 0: return (1 << 5); case 1: return (1 << 11); case 2: return (1 << 21); case 3: return (1 << 27); default: return 0; } } static inline void dma_isr_enable(int stream) { if (stream < 7) { NVIC_EnableIRQ((IRQn_Type)((int)DMA1_Stream0_IRQn + stream)); } else if (stream == 8) { NVIC_EnableIRQ(DMA1_Stream7_IRQn); } else if (stream < 14) { NVIC_EnableIRQ((IRQn_Type)((int)DMA2_Stream0_IRQn + stream)); } else if (stream < 17) { NVIC_EnableIRQ((IRQn_Type)((int)DMA2_Stream5_IRQn + stream)); } } #ifdef __cplusplus } #endif #endif /* PERIPH_CPU_H */ /** @} */
mziegert/RIOT
cpu/stm32f4/include/periph_cpu.h
C
lgpl-2.1
5,630
/*====================================================================* - Copyright (C) 2001 Leptonica. 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 ANY - 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. *====================================================================*/ /*! * \file ptafunc1.c * <pre> * * Simple rearrangements * PTA *ptaSubsample() * l_int32 ptaJoin() * l_int32 ptaaJoin() * PTA *ptaReverse() * PTA *ptaTranspose() * PTA *ptaCyclicPerm() * PTA *ptaSelectRange() * * Geometric * BOX *ptaGetBoundingRegion() * l_int32 *ptaGetRange() * PTA *ptaGetInsideBox() * PTA *pixFindCornerPixels() * l_int32 ptaContainsPt() * l_int32 ptaTestIntersection() * PTA *ptaTransform() * l_int32 ptaPtInsidePolygon() * l_float32 l_angleBetweenVectors() * * Min/max and filtering * l_int32 ptaGetMinMax() * PTA *ptaSelectByValue() * PTA *ptaCropToMask() * * Least Squares Fit * l_int32 ptaGetLinearLSF() * l_int32 ptaGetQuadraticLSF() * l_int32 ptaGetCubicLSF() * l_int32 ptaGetQuarticLSF() * l_int32 ptaNoisyLinearLSF() * l_int32 ptaNoisyQuadraticLSF() * l_int32 applyLinearFit() * l_int32 applyQuadraticFit() * l_int32 applyCubicFit() * l_int32 applyQuarticFit() * * Interconversions with Pix * l_int32 pixPlotAlongPta() * PTA *ptaGetPixelsFromPix() * PIX *pixGenerateFromPta() * PTA *ptaGetBoundaryPixels() * PTAA *ptaaGetBoundaryPixels() * PTAA *ptaaIndexLabeledPixels() * PTA *ptaGetNeighborPixLocs() * * Interconversion with Numa * PTA *numaConvertToPta1() * PTA *numaConvertToPta2() * l_int32 ptaConvertToNuma() * * Display Pta and Ptaa * PIX *pixDisplayPta() * PIX *pixDisplayPtaaPattern() * PIX *pixDisplayPtaPattern() * PTA *ptaReplicatePattern() * PIX *pixDisplayPtaa() * </pre> */ #include <math.h> #include "allheaders.h" #ifndef M_PI #define M_PI 3.14159265358979323846 #endif /* M_PI */ /*---------------------------------------------------------------------* * Simple rearrangements * *---------------------------------------------------------------------*/ /*! * \brief ptaSubsample() * * \param[in] ptas * \param[in] subfactor subsample factor, >= 1 * \return ptad evenly sampled pt values from ptas, or NULL on error */ PTA * ptaSubsample(PTA *ptas, l_int32 subfactor) { l_int32 n, i; l_float32 x, y; PTA *ptad; PROCNAME("pixSubsample"); if (!ptas) return (PTA *)ERROR_PTR("ptas not defined", procName, NULL); if (subfactor < 1) return (PTA *)ERROR_PTR("subfactor < 1", procName, NULL); ptad = ptaCreate(0); n = ptaGetCount(ptas); for (i = 0; i < n; i++) { if (i % subfactor != 0) continue; ptaGetPt(ptas, i, &x, &y); ptaAddPt(ptad, x, y); } return ptad; } /*! * \brief ptaJoin() * * \param[in] ptad dest pta; add to this one * \param[in] ptas source pta; add from this one * \param[in] istart starting index in ptas * \param[in] iend ending index in ptas; use -1 to cat all * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) istart < 0 is taken to mean 'read from the start' (istart = 0) * (2) iend < 0 means 'read to the end' * (3) if ptas == NULL, this is a no-op * </pre> */ l_int32 ptaJoin(PTA *ptad, PTA *ptas, l_int32 istart, l_int32 iend) { l_int32 n, i, x, y; PROCNAME("ptaJoin"); if (!ptad) return ERROR_INT("ptad not defined", procName, 1); if (!ptas) return 0; if (istart < 0) istart = 0; n = ptaGetCount(ptas); if (iend < 0 || iend >= n) iend = n - 1; if (istart > iend) return ERROR_INT("istart > iend; no pts", procName, 1); for (i = istart; i <= iend; i++) { ptaGetIPt(ptas, i, &x, &y); ptaAddPt(ptad, x, y); } return 0; } /*! * \brief ptaaJoin() * * \param[in] ptaad dest ptaa; add to this one * \param[in] ptaas source ptaa; add from this one * \param[in] istart starting index in ptaas * \param[in] iend ending index in ptaas; use -1 to cat all * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) istart < 0 is taken to mean 'read from the start' (istart = 0) * (2) iend < 0 means 'read to the end' * (3) if ptas == NULL, this is a no-op * </pre> */ l_int32 ptaaJoin(PTAA *ptaad, PTAA *ptaas, l_int32 istart, l_int32 iend) { l_int32 n, i; PTA *pta; PROCNAME("ptaaJoin"); if (!ptaad) return ERROR_INT("ptaad not defined", procName, 1); if (!ptaas) return 0; if (istart < 0) istart = 0; n = ptaaGetCount(ptaas); if (iend < 0 || iend >= n) iend = n - 1; if (istart > iend) return ERROR_INT("istart > iend; no pts", procName, 1); for (i = istart; i <= iend; i++) { pta = ptaaGetPta(ptaas, i, L_CLONE); ptaaAddPta(ptaad, pta, L_INSERT); } return 0; } /*! * \brief ptaReverse() * * \param[in] ptas * \param[in] type 0 for float values; 1 for integer values * \return ptad reversed pta, or NULL on error */ PTA * ptaReverse(PTA *ptas, l_int32 type) { l_int32 n, i, ix, iy; l_float32 x, y; PTA *ptad; PROCNAME("ptaReverse"); if (!ptas) return (PTA *)ERROR_PTR("ptas not defined", procName, NULL); n = ptaGetCount(ptas); if ((ptad = ptaCreate(n)) == NULL) return (PTA *)ERROR_PTR("ptad not made", procName, NULL); for (i = n - 1; i >= 0; i--) { if (type == 0) { ptaGetPt(ptas, i, &x, &y); ptaAddPt(ptad, x, y); } else { /* type == 1 */ ptaGetIPt(ptas, i, &ix, &iy); ptaAddPt(ptad, ix, iy); } } return ptad; } /*! * \brief ptaTranspose() * * \param[in] ptas * \return ptad with x and y values swapped, or NULL on error */ PTA * ptaTranspose(PTA *ptas) { l_int32 n, i; l_float32 x, y; PTA *ptad; PROCNAME("ptaTranspose"); if (!ptas) return (PTA *)ERROR_PTR("ptas not defined", procName, NULL); n = ptaGetCount(ptas); if ((ptad = ptaCreate(n)) == NULL) return (PTA *)ERROR_PTR("ptad not made", procName, NULL); for (i = 0; i < n; i++) { ptaGetPt(ptas, i, &x, &y); ptaAddPt(ptad, y, x); } return ptad; } /*! * \brief ptaCyclicPerm() * * \param[in] ptas * \param[in] xs, ys start point; must be in ptas * \return ptad cyclic permutation, starting and ending at (xs, ys, * or NULL on error * * <pre> * Notes: * (1) Check to insure that (a) ptas is a closed path where * the first and last points are identical, and (b) the * resulting pta also starts and ends on the same point * (which in this case is (xs, ys). * </pre> */ PTA * ptaCyclicPerm(PTA *ptas, l_int32 xs, l_int32 ys) { l_int32 n, i, x, y, j, index, state; l_int32 x1, y1, x2, y2; PTA *ptad; PROCNAME("ptaCyclicPerm"); if (!ptas) return (PTA *)ERROR_PTR("ptas not defined", procName, NULL); n = ptaGetCount(ptas); /* Verify input data */ ptaGetIPt(ptas, 0, &x1, &y1); ptaGetIPt(ptas, n - 1, &x2, &y2); if (x1 != x2 || y1 != y2) return (PTA *)ERROR_PTR("start and end pts not same", procName, NULL); state = L_NOT_FOUND; for (i = 0; i < n; i++) { ptaGetIPt(ptas, i, &x, &y); if (x == xs && y == ys) { state = L_FOUND; break; } } if (state == L_NOT_FOUND) return (PTA *)ERROR_PTR("start pt not in ptas", procName, NULL); if ((ptad = ptaCreate(n)) == NULL) return (PTA *)ERROR_PTR("ptad not made", procName, NULL); for (j = 0; j < n - 1; j++) { if (i + j < n - 1) index = i + j; else index = (i + j + 1) % n; ptaGetIPt(ptas, index, &x, &y); ptaAddPt(ptad, x, y); } ptaAddPt(ptad, xs, ys); return ptad; } /*! * \brief ptaSelectRange() * * \param[in] ptas * \param[in] first use 0 to select from the beginning * \param[in] last use 0 to select to the end * \return ptad, or NULL on error */ PTA * ptaSelectRange(PTA *ptas, l_int32 first, l_int32 last) { l_int32 n, npt, i; l_float32 x, y; PTA *ptad; PROCNAME("ptaSelectRange"); if (!ptas) return (PTA *)ERROR_PTR("ptas not defined", procName, NULL); if ((n = ptaGetCount(ptas)) == 0) { L_WARNING("ptas is empty\n", procName); return ptaCopy(ptas); } first = L_MAX(0, first); if (last <= 0) last = n - 1; if (first >= n) return (PTA *)ERROR_PTR("invalid first", procName, NULL); if (first > last) return (PTA *)ERROR_PTR("first > last", procName, NULL); npt = last - first + 1; ptad = ptaCreate(npt); for (i = first; i <= last; i++) { ptaGetPt(ptas, i, &x, &y); ptaAddPt(ptad, x, y); } return ptad; } /*---------------------------------------------------------------------* * Geometric * *---------------------------------------------------------------------*/ /*! * \brief ptaGetBoundingRegion() * * \param[in] pta * \return box, or NULL on error * * <pre> * Notes: * (1) This is used when the pta represents a set of points in * a two-dimensional image. It returns the box of minimum * size containing the pts in the pta. * </pre> */ BOX * ptaGetBoundingRegion(PTA *pta) { l_int32 n, i, x, y, minx, maxx, miny, maxy; PROCNAME("ptaGetBoundingRegion"); if (!pta) return (BOX *)ERROR_PTR("pta not defined", procName, NULL); minx = 10000000; miny = 10000000; maxx = -10000000; maxy = -10000000; n = ptaGetCount(pta); for (i = 0; i < n; i++) { ptaGetIPt(pta, i, &x, &y); if (x < minx) minx = x; if (x > maxx) maxx = x; if (y < miny) miny = y; if (y > maxy) maxy = y; } return boxCreate(minx, miny, maxx - minx + 1, maxy - miny + 1); } /*! * \brief ptaGetRange() * * \param[in] pta * \param[out] pminx [optional] min value of x * \param[out] pmaxx [optional] max value of x * \param[out] pminy [optional] min value of y * \param[out] pmaxy [optional] max value of y * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) We can use pts to represent pairs of floating values, that * are not necessarily tied to a two-dimension region. For * example, the pts can represent a general function y(x). * </pre> */ l_int32 ptaGetRange(PTA *pta, l_float32 *pminx, l_float32 *pmaxx, l_float32 *pminy, l_float32 *pmaxy) { l_int32 n, i; l_float32 x, y, minx, maxx, miny, maxy; PROCNAME("ptaGetRange"); if (!pminx && !pmaxx && !pminy && !pmaxy) return ERROR_INT("no output requested", procName, 1); if (pminx) *pminx = 0; if (pmaxx) *pmaxx = 0; if (pminy) *pminy = 0; if (pmaxy) *pmaxy = 0; if (!pta) return ERROR_INT("pta not defined", procName, 1); if ((n = ptaGetCount(pta)) == 0) return ERROR_INT("no points in pta", procName, 1); ptaGetPt(pta, 0, &x, &y); minx = x; maxx = x; miny = y; maxy = y; for (i = 1; i < n; i++) { ptaGetPt(pta, i, &x, &y); if (x < minx) minx = x; if (x > maxx) maxx = x; if (y < miny) miny = y; if (y > maxy) maxy = y; } if (pminx) *pminx = minx; if (pmaxx) *pmaxx = maxx; if (pminy) *pminy = miny; if (pmaxy) *pmaxy = maxy; return 0; } /*! * \brief ptaGetInsideBox() * * \param[in] ptas input pts * \param[in] box * \return ptad of pts in ptas that are inside the box, or NULL on error */ PTA * ptaGetInsideBox(PTA *ptas, BOX *box) { PTA *ptad; l_int32 n, i, contains; l_float32 x, y; PROCNAME("ptaGetInsideBox"); if (!ptas) return (PTA *)ERROR_PTR("ptas not defined", procName, NULL); if (!box) return (PTA *)ERROR_PTR("box not defined", procName, NULL); n = ptaGetCount(ptas); ptad = ptaCreate(0); for (i = 0; i < n; i++) { ptaGetPt(ptas, i, &x, &y); boxContainsPt(box, x, y, &contains); if (contains) ptaAddPt(ptad, x, y); } return ptad; } /*! * \brief pixFindCornerPixels() * * \param[in] pixs 1 bpp * \return pta, or NULL on error * * <pre> * Notes: * (1) Finds the 4 corner-most pixels, as defined by a search * inward from each corner, using a 45 degree line. * </pre> */ PTA * pixFindCornerPixels(PIX *pixs) { l_int32 i, j, x, y, w, h, wpl, mindim, found; l_uint32 *data, *line; PTA *pta; PROCNAME("pixFindCornerPixels"); if (!pixs) return (PTA *)ERROR_PTR("pixs not defined", procName, NULL); if (pixGetDepth(pixs) != 1) return (PTA *)ERROR_PTR("pixs not 1 bpp", procName, NULL); w = pixGetWidth(pixs); h = pixGetHeight(pixs); mindim = L_MIN(w, h); data = pixGetData(pixs); wpl = pixGetWpl(pixs); if ((pta = ptaCreate(4)) == NULL) return (PTA *)ERROR_PTR("pta not made", procName, NULL); for (found = FALSE, i = 0; i < mindim; i++) { for (j = 0; j <= i; j++) { y = i - j; line = data + y * wpl; if (GET_DATA_BIT(line, j)) { ptaAddPt(pta, j, y); found = TRUE; break; } } if (found == TRUE) break; } for (found = FALSE, i = 0; i < mindim; i++) { for (j = 0; j <= i; j++) { y = i - j; line = data + y * wpl; x = w - 1 - j; if (GET_DATA_BIT(line, x)) { ptaAddPt(pta, x, y); found = TRUE; break; } } if (found == TRUE) break; } for (found = FALSE, i = 0; i < mindim; i++) { for (j = 0; j <= i; j++) { y = h - 1 - i + j; line = data + y * wpl; if (GET_DATA_BIT(line, j)) { ptaAddPt(pta, j, y); found = TRUE; break; } } if (found == TRUE) break; } for (found = FALSE, i = 0; i < mindim; i++) { for (j = 0; j <= i; j++) { y = h - 1 - i + j; line = data + y * wpl; x = w - 1 - j; if (GET_DATA_BIT(line, x)) { ptaAddPt(pta, x, y); found = TRUE; break; } } if (found == TRUE) break; } return pta; } /*! * \brief ptaContainsPt() * * \param[in] pta * \param[in] x, y point * \return 1 if contained, 0 otherwise or on error */ l_int32 ptaContainsPt(PTA *pta, l_int32 x, l_int32 y) { l_int32 i, n, ix, iy; PROCNAME("ptaContainsPt"); if (!pta) return ERROR_INT("pta not defined", procName, 0); n = ptaGetCount(pta); for (i = 0; i < n; i++) { ptaGetIPt(pta, i, &ix, &iy); if (x == ix && y == iy) return 1; } return 0; } /*! * \brief ptaTestIntersection() * * \param[in] pta1, pta2 * \return bval which is 1 if they have any elements in common; * 0 otherwise or on error. */ l_int32 ptaTestIntersection(PTA *pta1, PTA *pta2) { l_int32 i, j, n1, n2, x1, y1, x2, y2; PROCNAME("ptaTestIntersection"); if (!pta1) return ERROR_INT("pta1 not defined", procName, 0); if (!pta2) return ERROR_INT("pta2 not defined", procName, 0); n1 = ptaGetCount(pta1); n2 = ptaGetCount(pta2); for (i = 0; i < n1; i++) { ptaGetIPt(pta1, i, &x1, &y1); for (j = 0; j < n2; j++) { ptaGetIPt(pta2, i, &x2, &y2); if (x1 == x2 && y1 == y2) return 1; } } return 0; } /*! * \brief ptaTransform() * * \param[in] ptas * \param[in] shiftx, shifty * \param[in] scalex, scaley * \return pta, or NULL on error * * <pre> * Notes: * (1) Shift first, then scale. * </pre> */ PTA * ptaTransform(PTA *ptas, l_int32 shiftx, l_int32 shifty, l_float32 scalex, l_float32 scaley) { l_int32 n, i, x, y; PTA *ptad; PROCNAME("ptaTransform"); if (!ptas) return (PTA *)ERROR_PTR("ptas not defined", procName, NULL); n = ptaGetCount(ptas); ptad = ptaCreate(n); for (i = 0; i < n; i++) { ptaGetIPt(ptas, i, &x, &y); x = (l_int32)(scalex * (x + shiftx) + 0.5); y = (l_int32)(scaley * (y + shifty) + 0.5); ptaAddPt(ptad, x, y); } return ptad; } /*! * \brief ptaPtInsidePolygon() * * \param[in] pta vertices of a polygon * \param[in] x, y point to be tested * \param[out] pinside 1 if inside; 0 if outside or on boundary * \return 1 if OK, 0 on error * * The abs value of the sum of the angles subtended from a point by * the sides of a polygon, when taken in order traversing the polygon, * is 0 if the point is outside the polygon and 2*pi if inside. * The sign will be positive if traversed cw and negative if ccw. */ l_int32 ptaPtInsidePolygon(PTA *pta, l_float32 x, l_float32 y, l_int32 *pinside) { l_int32 i, n; l_float32 sum, x1, y1, x2, y2, xp1, yp1, xp2, yp2; PROCNAME("ptaPtInsidePolygon"); if (!pinside) return ERROR_INT("&inside not defined", procName, 1); *pinside = 0; if (!pta) return ERROR_INT("pta not defined", procName, 1); /* Think of (x1,y1) as the end point of a vector that starts * from the origin (0,0), and ditto for (x2,y2). */ n = ptaGetCount(pta); sum = 0.0; for (i = 0; i < n; i++) { ptaGetPt(pta, i, &xp1, &yp1); ptaGetPt(pta, (i + 1) % n, &xp2, &yp2); x1 = xp1 - x; y1 = yp1 - y; x2 = xp2 - x; y2 = yp2 - y; sum += l_angleBetweenVectors(x1, y1, x2, y2); } if (L_ABS(sum) > M_PI) *pinside = 1; return 0; } /*! * \brief l_angleBetweenVectors() * * \param[in] x1, y1 end point of first vector * \param[in] x2, y2 end point of second vector * \return angle radians, or 0.0 on error * * <pre> * Notes: * (1) This gives the angle between two vectors, going between * vector1 (x1,y1) and vector2 (x2,y2). The angle is swept * out from 1 --> 2. If this is clockwise, the angle is * positive, but the result is folded into the interval [-pi, pi]. * </pre> */ l_float32 l_angleBetweenVectors(l_float32 x1, l_float32 y1, l_float32 x2, l_float32 y2) { l_float64 ang; ang = atan2(y2, x2) - atan2(y1, x1); if (ang > M_PI) ang -= 2.0 * M_PI; if (ang < -M_PI) ang += 2.0 * M_PI; return ang; } /*---------------------------------------------------------------------* * Min/max and filtering * *---------------------------------------------------------------------*/ /*! * \brief ptaGetMinMax() * * \param[in] pta * \param[out] pxmin [optional] min of x * \param[out] pymin [optional] min of y * \param[out] pxmax [optional] max of x * \param[out] pymax [optional] max of y * \return 0 if OK, 1 on error. If pta is empty, requested * values are returned as -1.0. */ l_int32 ptaGetMinMax(PTA *pta, l_float32 *pxmin, l_float32 *pymin, l_float32 *pxmax, l_float32 *pymax) { l_int32 i, n; l_float32 x, y, xmin, ymin, xmax, ymax; PROCNAME("ptaGetMinMax"); if (pxmin) *pxmin = -1.0; if (pymin) *pymin = -1.0; if (pxmax) *pxmax = -1.0; if (pymax) *pymax = -1.0; if (!pta) return ERROR_INT("pta not defined", procName, 1); if (!pxmin && !pxmax && !pymin && !pymax) return ERROR_INT("no output requested", procName, 1); if ((n = ptaGetCount(pta)) == 0) { L_WARNING("pta is empty\n", procName); return 0; } xmin = ymin = 1.0e20; xmax = ymax = -1.0e20; for (i = 0; i < n; i++) { ptaGetPt(pta, i, &x, &y); if (x < xmin) xmin = x; if (y < ymin) ymin = y; if (x > xmax) xmax = x; if (y > ymax) ymax = y; } if (pxmin) *pxmin = xmin; if (pymin) *pymin = ymin; if (pxmax) *pxmax = xmax; if (pymax) *pymax = ymax; return 0; } /*! * \brief ptaSelectByValue() * * \param[in] ptas * \param[in] xth, yth threshold values * \param[in] type L_SELECT_XVAL, L_SELECT_YVAL, * L_SELECT_IF_EITHER, L_SELECT_IF_BOTH * \param[in] relation L_SELECT_IF_LT, L_SELECT_IF_GT, * L_SELECT_IF_LTE, L_SELECT_IF_GTE * \return ptad filtered set, or NULL on error */ PTA * ptaSelectByValue(PTA *ptas, l_float32 xth, l_float32 yth, l_int32 type, l_int32 relation) { l_int32 i, n; l_float32 x, y; PTA *ptad; PROCNAME("ptaSelectByValue"); if (!ptas) return (PTA *)ERROR_PTR("ptas not defined", procName, NULL); if (ptaGetCount(ptas) == 0) { L_WARNING("ptas is empty\n", procName); return ptaCopy(ptas); } if (type != L_SELECT_XVAL && type != L_SELECT_YVAL && type != L_SELECT_IF_EITHER && type != L_SELECT_IF_BOTH) return (PTA *)ERROR_PTR("invalid type", procName, NULL); if (relation != L_SELECT_IF_LT && relation != L_SELECT_IF_GT && relation != L_SELECT_IF_LTE && relation != L_SELECT_IF_GTE) return (PTA *)ERROR_PTR("invalid relation", procName, NULL); n = ptaGetCount(ptas); ptad = ptaCreate(n); for (i = 0; i < n; i++) { ptaGetPt(ptas, i, &x, &y); if (type == L_SELECT_XVAL) { if ((relation == L_SELECT_IF_LT && x < xth) || (relation == L_SELECT_IF_GT && x > xth) || (relation == L_SELECT_IF_LTE && x <= xth) || (relation == L_SELECT_IF_GTE && x >= xth)) ptaAddPt(ptad, x, y); } else if (type == L_SELECT_YVAL) { if ((relation == L_SELECT_IF_LT && y < yth) || (relation == L_SELECT_IF_GT && y > yth) || (relation == L_SELECT_IF_LTE && y <= yth) || (relation == L_SELECT_IF_GTE && y >= yth)) ptaAddPt(ptad, x, y); } else if (type == L_SELECT_IF_EITHER) { if (((relation == L_SELECT_IF_LT) && (x < xth || y < yth)) || ((relation == L_SELECT_IF_GT) && (x > xth || y > yth)) || ((relation == L_SELECT_IF_LTE) && (x <= xth || y <= yth)) || ((relation == L_SELECT_IF_GTE) && (x >= xth || y >= yth))) ptaAddPt(ptad, x, y); } else { /* L_SELECT_IF_BOTH */ if (((relation == L_SELECT_IF_LT) && (x < xth && y < yth)) || ((relation == L_SELECT_IF_GT) && (x > xth && y > yth)) || ((relation == L_SELECT_IF_LTE) && (x <= xth && y <= yth)) || ((relation == L_SELECT_IF_GTE) && (x >= xth && y >= yth))) ptaAddPt(ptad, x, y); } } return ptad; } /*! * \brief ptaCropToMask() * * \param[in] ptas input pta * \param[in] pixm 1 bpp mask * \return ptad with only pts under the mask fg, or NULL on error */ PTA * ptaCropToMask(PTA *ptas, PIX *pixm) { l_int32 i, n, x, y; l_uint32 val; PTA *ptad; PROCNAME("ptaCropToMask"); if (!ptas) return (PTA *)ERROR_PTR("ptas not defined", procName, NULL); if (!pixm || pixGetDepth(pixm) != 1) return (PTA *)ERROR_PTR("pixm undefined or not 1 bpp", procName, NULL); if (ptaGetCount(ptas) == 0) { L_INFO("ptas is empty\n", procName); return ptaCopy(ptas); } n = ptaGetCount(ptas); ptad = ptaCreate(n); for (i = 0; i < n; i++) { ptaGetIPt(ptas, i, &x, &y); pixGetPixel(pixm, x, y, &val); if (val == 1) ptaAddPt(ptad, x, y); } return ptad; } /*---------------------------------------------------------------------* * Least Squares Fit * *---------------------------------------------------------------------*/ /*! * \brief ptaGetLinearLSF() * * \param[in] pta * \param[out] pa [optional] slope a of least square fit: y = ax + b * \param[out] pb [optional] intercept b of least square fit * \param[out] pnafit [optional] numa of least square fit * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) Either or both &a and &b must be input. They determine the * type of line that is fit. * (2) If both &a and &b are defined, this returns a and b that minimize: * * sum (yi - axi -b)^2 * i * * The method is simple: differentiate this expression w/rt a and b, * and solve the resulting two equations for a and b in terms of * various sums over the input data (xi, yi). * (3) We also allow two special cases, where either a = 0 or b = 0: * (a) If &a is given and &b = null, find the linear LSF that * goes through the origin (b = 0). * (b) If &b is given and &a = null, find the linear LSF with * zero slope (a = 0). * (4) If &nafit is defined, this returns an array of fitted values, * corresponding to the two implicit Numa arrays (nax and nay) in pta. * Thus, just as you can plot the data in pta as nay vs. nax, * you can plot the linear least square fit as nafit vs. nax. * Get the nax array using ptaGetArrays(pta, &nax, NULL); * </pre> */ l_int32 ptaGetLinearLSF(PTA *pta, l_float32 *pa, l_float32 *pb, NUMA **pnafit) { l_int32 n, i; l_float32 a, b, factor, sx, sy, sxx, sxy, val; l_float32 *xa, *ya; PROCNAME("ptaGetLinearLSF"); if (pa) *pa = 0.0; if (pb) *pb = 0.0; if (pnafit) *pnafit = NULL; if (!pa && !pb && !pnafit) return ERROR_INT("no output requested", procName, 1); if (!pta) return ERROR_INT("pta not defined", procName, 1); if ((n = ptaGetCount(pta)) < 2) return ERROR_INT("less than 2 pts found", procName, 1); xa = pta->x; /* not a copy */ ya = pta->y; /* not a copy */ sx = sy = sxx = sxy = 0.; if (pa && pb) { /* general line */ for (i = 0; i < n; i++) { sx += xa[i]; sy += ya[i]; sxx += xa[i] * xa[i]; sxy += xa[i] * ya[i]; } factor = n * sxx - sx * sx; if (factor == 0.0) return ERROR_INT("no solution found", procName, 1); factor = 1. / factor; a = factor * ((l_float32)n * sxy - sx * sy); b = factor * (sxx * sy - sx * sxy); } else if (pa) { /* b = 0; line through origin */ for (i = 0; i < n; i++) { sxx += xa[i] * xa[i]; sxy += xa[i] * ya[i]; } if (sxx == 0.0) return ERROR_INT("no solution found", procName, 1); a = sxy / sxx; b = 0.0; } else { /* a = 0; horizontal line */ for (i = 0; i < n; i++) sy += ya[i]; a = 0.0; b = sy / (l_float32)n; } if (pnafit) { *pnafit = numaCreate(n); for (i = 0; i < n; i++) { val = a * xa[i] + b; numaAddNumber(*pnafit, val); } } if (pa) *pa = a; if (pb) *pb = b; return 0; } /*! * \brief ptaGetQuadraticLSF() * * \param[in] pta * \param[out] pa [optional] coeff a of LSF: y = ax^2 + bx + c * \param[out] pb [optional] coeff b of LSF: y = ax^2 + bx + c * \param[out] pc [optional] coeff c of LSF: y = ax^2 + bx + c * \param[out] pnafit [optional] numa of least square fit * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) This does a quadratic least square fit to the set of points * in %pta. That is, it finds coefficients a, b and c that minimize: * * sum (yi - a*xi*xi -b*xi -c)^2 * i * * The method is simple: differentiate this expression w/rt * a, b and c, and solve the resulting three equations for these * coefficients in terms of various sums over the input data (xi, yi). * The three equations are in the form: * f[0][0]a + f[0][1]b + f[0][2]c = g[0] * f[1][0]a + f[1][1]b + f[1][2]c = g[1] * f[2][0]a + f[2][1]b + f[2][2]c = g[2] * (2) If &nafit is defined, this returns an array of fitted values, * corresponding to the two implicit Numa arrays (nax and nay) in pta. * Thus, just as you can plot the data in pta as nay vs. nax, * you can plot the linear least square fit as nafit vs. nax. * Get the nax array using ptaGetArrays(pta, &nax, NULL); * </pre> */ l_int32 ptaGetQuadraticLSF(PTA *pta, l_float32 *pa, l_float32 *pb, l_float32 *pc, NUMA **pnafit) { l_int32 n, i, ret; l_float32 x, y, sx, sy, sx2, sx3, sx4, sxy, sx2y; l_float32 *xa, *ya; l_float32 *f[3]; l_float32 g[3]; PROCNAME("ptaGetQuadraticLSF"); if (pa) *pa = 0.0; if (pb) *pb = 0.0; if (pc) *pc = 0.0; if (pnafit) *pnafit = NULL; if (!pa && !pb && !pc && !pnafit) return ERROR_INT("no output requested", procName, 1); if (!pta) return ERROR_INT("pta not defined", procName, 1); if ((n = ptaGetCount(pta)) < 3) return ERROR_INT("less than 3 pts found", procName, 1); xa = pta->x; /* not a copy */ ya = pta->y; /* not a copy */ sx = sy = sx2 = sx3 = sx4 = sxy = sx2y = 0.; for (i = 0; i < n; i++) { x = xa[i]; y = ya[i]; sx += x; sy += y; sx2 += x * x; sx3 += x * x * x; sx4 += x * x * x * x; sxy += x * y; sx2y += x * x * y; } for (i = 0; i < 3; i++) f[i] = (l_float32 *)LEPT_CALLOC(3, sizeof(l_float32)); f[0][0] = sx4; f[0][1] = sx3; f[0][2] = sx2; f[1][0] = sx3; f[1][1] = sx2; f[1][2] = sx; f[2][0] = sx2; f[2][1] = sx; f[2][2] = n; g[0] = sx2y; g[1] = sxy; g[2] = sy; /* Solve for the unknowns, also putting f-inverse into f */ ret = gaussjordan(f, g, 3); for (i = 0; i < 3; i++) LEPT_FREE(f[i]); if (ret) return ERROR_INT("quadratic solution failed", procName, 1); if (pa) *pa = g[0]; if (pb) *pb = g[1]; if (pc) *pc = g[2]; if (pnafit) { *pnafit = numaCreate(n); for (i = 0; i < n; i++) { x = xa[i]; y = g[0] * x * x + g[1] * x + g[2]; numaAddNumber(*pnafit, y); } } return 0; } /*! * \brief ptaGetCubicLSF() * * \param[in] pta * \param[out] pa [optional] coeff a of LSF: y = ax^3 + bx^2 + cx + d * \param[out] pb [optional] coeff b of LSF * \param[out] pc [optional] coeff c of LSF * \param[out] pd [optional] coeff d of LSF * \param[out] pnafit [optional] numa of least square fit * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) This does a cubic least square fit to the set of points * in %pta. That is, it finds coefficients a, b, c and d * that minimize: * * sum (yi - a*xi*xi*xi -b*xi*xi -c*xi - d)^2 * i * * Differentiate this expression w/rt a, b, c and d, and solve * the resulting four equations for these coefficients in * terms of various sums over the input data (xi, yi). * The four equations are in the form: * f[0][0]a + f[0][1]b + f[0][2]c + f[0][3] = g[0] * f[1][0]a + f[1][1]b + f[1][2]c + f[1][3] = g[1] * f[2][0]a + f[2][1]b + f[2][2]c + f[2][3] = g[2] * f[3][0]a + f[3][1]b + f[3][2]c + f[3][3] = g[3] * (2) If &nafit is defined, this returns an array of fitted values, * corresponding to the two implicit Numa arrays (nax and nay) in pta. * Thus, just as you can plot the data in pta as nay vs. nax, * you can plot the linear least square fit as nafit vs. nax. * Get the nax array using ptaGetArrays(pta, &nax, NULL); * </pre> */ l_int32 ptaGetCubicLSF(PTA *pta, l_float32 *pa, l_float32 *pb, l_float32 *pc, l_float32 *pd, NUMA **pnafit) { l_int32 n, i, ret; l_float32 x, y, sx, sy, sx2, sx3, sx4, sx5, sx6, sxy, sx2y, sx3y; l_float32 *xa, *ya; l_float32 *f[4]; l_float32 g[4]; PROCNAME("ptaGetCubicLSF"); if (pa) *pa = 0.0; if (pb) *pb = 0.0; if (pc) *pc = 0.0; if (pd) *pd = 0.0; if (pnafit) *pnafit = NULL; if (!pa && !pb && !pc && !pd && !pnafit) return ERROR_INT("no output requested", procName, 1); if (!pta) return ERROR_INT("pta not defined", procName, 1); if ((n = ptaGetCount(pta)) < 4) return ERROR_INT("less than 4 pts found", procName, 1); xa = pta->x; /* not a copy */ ya = pta->y; /* not a copy */ sx = sy = sx2 = sx3 = sx4 = sx5 = sx6 = sxy = sx2y = sx3y = 0.; for (i = 0; i < n; i++) { x = xa[i]; y = ya[i]; sx += x; sy += y; sx2 += x * x; sx3 += x * x * x; sx4 += x * x * x * x; sx5 += x * x * x * x * x; sx6 += x * x * x * x * x * x; sxy += x * y; sx2y += x * x * y; sx3y += x * x * x * y; } for (i = 0; i < 4; i++) f[i] = (l_float32 *)LEPT_CALLOC(4, sizeof(l_float32)); f[0][0] = sx6; f[0][1] = sx5; f[0][2] = sx4; f[0][3] = sx3; f[1][0] = sx5; f[1][1] = sx4; f[1][2] = sx3; f[1][3] = sx2; f[2][0] = sx4; f[2][1] = sx3; f[2][2] = sx2; f[2][3] = sx; f[3][0] = sx3; f[3][1] = sx2; f[3][2] = sx; f[3][3] = n; g[0] = sx3y; g[1] = sx2y; g[2] = sxy; g[3] = sy; /* Solve for the unknowns, also putting f-inverse into f */ ret = gaussjordan(f, g, 4); for (i = 0; i < 4; i++) LEPT_FREE(f[i]); if (ret) return ERROR_INT("cubic solution failed", procName, 1); if (pa) *pa = g[0]; if (pb) *pb = g[1]; if (pc) *pc = g[2]; if (pd) *pd = g[3]; if (pnafit) { *pnafit = numaCreate(n); for (i = 0; i < n; i++) { x = xa[i]; y = g[0] * x * x * x + g[1] * x * x + g[2] * x + g[3]; numaAddNumber(*pnafit, y); } } return 0; } /*! * \brief ptaGetQuarticLSF() * * \param[in] pta * \param[out] pa [optional] coeff a of LSF: * y = ax^4 + bx^3 + cx^2 + dx + e * \param[out] pb [optional] coeff b of LSF * \param[out] pc [optional] coeff c of LSF * \param[out] pd [optional] coeff d of LSF * \param[out] pe [optional] coeff e of LSF * \param[out] pnafit [optional] numa of least square fit * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) This does a quartic least square fit to the set of points * in %pta. That is, it finds coefficients a, b, c, d and 3 * that minimize: * * sum (yi - a*xi*xi*xi*xi -b*xi*xi*xi -c*xi*xi - d*xi - e)^2 * i * * Differentiate this expression w/rt a, b, c, d and e, and solve * the resulting five equations for these coefficients in * terms of various sums over the input data (xi, yi). * The five equations are in the form: * f[0][0]a + f[0][1]b + f[0][2]c + f[0][3] + f[0][4] = g[0] * f[1][0]a + f[1][1]b + f[1][2]c + f[1][3] + f[1][4] = g[1] * f[2][0]a + f[2][1]b + f[2][2]c + f[2][3] + f[2][4] = g[2] * f[3][0]a + f[3][1]b + f[3][2]c + f[3][3] + f[3][4] = g[3] * f[4][0]a + f[4][1]b + f[4][2]c + f[4][3] + f[4][4] = g[4] * (2) If &nafit is defined, this returns an array of fitted values, * corresponding to the two implicit Numa arrays (nax and nay) in pta. * Thus, just as you can plot the data in pta as nay vs. nax, * you can plot the linear least square fit as nafit vs. nax. * Get the nax array using ptaGetArrays(pta, &nax, NULL); * </pre> */ l_int32 ptaGetQuarticLSF(PTA *pta, l_float32 *pa, l_float32 *pb, l_float32 *pc, l_float32 *pd, l_float32 *pe, NUMA **pnafit) { l_int32 n, i, ret; l_float32 x, y, sx, sy, sx2, sx3, sx4, sx5, sx6, sx7, sx8; l_float32 sxy, sx2y, sx3y, sx4y; l_float32 *xa, *ya; l_float32 *f[5]; l_float32 g[5]; PROCNAME("ptaGetQuarticLSF"); if (pa) *pa = 0.0; if (pb) *pb = 0.0; if (pc) *pc = 0.0; if (pd) *pd = 0.0; if (pe) *pe = 0.0; if (pnafit) *pnafit = NULL; if (!pa && !pb && !pc && !pd && !pe && !pnafit) return ERROR_INT("no output requested", procName, 1); if (!pta) return ERROR_INT("pta not defined", procName, 1); if ((n = ptaGetCount(pta)) < 5) return ERROR_INT("less than 5 pts found", procName, 1); xa = pta->x; /* not a copy */ ya = pta->y; /* not a copy */ sx = sy = sx2 = sx3 = sx4 = sx5 = sx6 = sx7 = sx8 = 0; sxy = sx2y = sx3y = sx4y = 0.; for (i = 0; i < n; i++) { x = xa[i]; y = ya[i]; sx += x; sy += y; sx2 += x * x; sx3 += x * x * x; sx4 += x * x * x * x; sx5 += x * x * x * x * x; sx6 += x * x * x * x * x * x; sx7 += x * x * x * x * x * x * x; sx8 += x * x * x * x * x * x * x * x; sxy += x * y; sx2y += x * x * y; sx3y += x * x * x * y; sx4y += x * x * x * x * y; } for (i = 0; i < 5; i++) f[i] = (l_float32 *)LEPT_CALLOC(5, sizeof(l_float32)); f[0][0] = sx8; f[0][1] = sx7; f[0][2] = sx6; f[0][3] = sx5; f[0][4] = sx4; f[1][0] = sx7; f[1][1] = sx6; f[1][2] = sx5; f[1][3] = sx4; f[1][4] = sx3; f[2][0] = sx6; f[2][1] = sx5; f[2][2] = sx4; f[2][3] = sx3; f[2][4] = sx2; f[3][0] = sx5; f[3][1] = sx4; f[3][2] = sx3; f[3][3] = sx2; f[3][4] = sx; f[4][0] = sx4; f[4][1] = sx3; f[4][2] = sx2; f[4][3] = sx; f[4][4] = n; g[0] = sx4y; g[1] = sx3y; g[2] = sx2y; g[3] = sxy; g[4] = sy; /* Solve for the unknowns, also putting f-inverse into f */ ret = gaussjordan(f, g, 5); for (i = 0; i < 5; i++) LEPT_FREE(f[i]); if (ret) return ERROR_INT("quartic solution failed", procName, 1); if (pa) *pa = g[0]; if (pb) *pb = g[1]; if (pc) *pc = g[2]; if (pd) *pd = g[3]; if (pe) *pe = g[4]; if (pnafit) { *pnafit = numaCreate(n); for (i = 0; i < n; i++) { x = xa[i]; y = g[0] * x * x * x * x + g[1] * x * x * x + g[2] * x * x + g[3] * x + g[4]; numaAddNumber(*pnafit, y); } } return 0; } /*! * \brief ptaNoisyLinearLSF() * * \param[in] pta * \param[in] factor reject outliers with error greater than this * number of medians; typically ~ 3 * \param[out] pptad [optional] with outliers removed * \param[out] pa [optional] slope a of least square fit: y = ax + b * \param[out] pb [optional] intercept b of least square fit * \param[out] pmederr [optional] median error * \param[out] pnafit [optional] numa of least square fit to ptad * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) This does a linear least square fit to the set of points * in %pta. It then evaluates the errors and removes points * whose error is >= factor * median_error. It then re-runs * the linear LSF on the resulting points. * (2) Either or both &a and &b must be input. They determine the * type of line that is fit. * (3) The median error can give an indication of how good the fit * is likely to be. * </pre> */ l_int32 ptaNoisyLinearLSF(PTA *pta, l_float32 factor, PTA **pptad, l_float32 *pa, l_float32 *pb, l_float32 *pmederr, NUMA **pnafit) { l_int32 n, i, ret; l_float32 x, y, yf, val, mederr; NUMA *nafit, *naerror; PTA *ptad; PROCNAME("ptaNoisyLinearLSF"); if (pptad) *pptad = NULL; if (pa) *pa = 0.0; if (pb) *pb = 0.0; if (pmederr) *pmederr = 0.0; if (pnafit) *pnafit = NULL; if (!pptad && !pa && !pb && !pnafit) return ERROR_INT("no output requested", procName, 1); if (!pta) return ERROR_INT("pta not defined", procName, 1); if (factor <= 0.0) return ERROR_INT("factor must be > 0.0", procName, 1); if ((n = ptaGetCount(pta)) < 3) return ERROR_INT("less than 2 pts found", procName, 1); if (ptaGetLinearLSF(pta, pa, pb, &nafit) != 0) return ERROR_INT("error in linear LSF", procName, 1); /* Get the median error */ naerror = numaCreate(n); for (i = 0; i < n; i++) { ptaGetPt(pta, i, &x, &y); numaGetFValue(nafit, i, &yf); numaAddNumber(naerror, L_ABS(y - yf)); } numaGetMedian(naerror, &mederr); if (pmederr) *pmederr = mederr; numaDestroy(&nafit); /* Remove outliers */ ptad = ptaCreate(n); for (i = 0; i < n; i++) { ptaGetPt(pta, i, &x, &y); numaGetFValue(naerror, i, &val); if (val <= factor * mederr) /* <= in case mederr = 0 */ ptaAddPt(ptad, x, y); } numaDestroy(&naerror); /* Do LSF again */ ret = ptaGetLinearLSF(ptad, pa, pb, pnafit); if (pptad) *pptad = ptad; else ptaDestroy(&ptad); return ret; } /*! * \brief ptaNoisyQuadraticLSF() * * \param[in] pta * \param[in] factor reject outliers with error greater than this * number of medians; typically ~ 3 * \param[out] pptad [optional] with outliers removed * \param[out] pa [optional] coeff a of LSF: y = ax^2 + bx + c * \param[out] pb [optional] coeff b of LSF: y = ax^2 + bx + c * \param[out] pc [optional] coeff c of LSF: y = ax^2 + bx + c * \param[out] pmederr [optional] median error * \param[out] pnafit [optional] numa of least square fit to ptad * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) This does a quadratic least square fit to the set of points * in %pta. It then evaluates the errors and removes points * whose error is >= factor * median_error. It then re-runs * a quadratic LSF on the resulting points. * </pre> */ l_int32 ptaNoisyQuadraticLSF(PTA *pta, l_float32 factor, PTA **pptad, l_float32 *pa, l_float32 *pb, l_float32 *pc, l_float32 *pmederr, NUMA **pnafit) { l_int32 n, i, ret; l_float32 x, y, yf, val, mederr; NUMA *nafit, *naerror; PTA *ptad; PROCNAME("ptaNoisyQuadraticLSF"); if (pptad) *pptad = NULL; if (pa) *pa = 0.0; if (pb) *pb = 0.0; if (pc) *pc = 0.0; if (pmederr) *pmederr = 0.0; if (pnafit) *pnafit = NULL; if (!pptad && !pa && !pb && !pc && !pnafit) return ERROR_INT("no output requested", procName, 1); if (factor <= 0.0) return ERROR_INT("factor must be > 0.0", procName, 1); if (!pta) return ERROR_INT("pta not defined", procName, 1); if ((n = ptaGetCount(pta)) < 3) return ERROR_INT("less than 3 pts found", procName, 1); if (ptaGetQuadraticLSF(pta, NULL, NULL, NULL, &nafit) != 0) return ERROR_INT("error in quadratic LSF", procName, 1); /* Get the median error */ naerror = numaCreate(n); for (i = 0; i < n; i++) { ptaGetPt(pta, i, &x, &y); numaGetFValue(nafit, i, &yf); numaAddNumber(naerror, L_ABS(y - yf)); } numaGetMedian(naerror, &mederr); if (pmederr) *pmederr = mederr; numaDestroy(&nafit); /* Remove outliers */ ptad = ptaCreate(n); for (i = 0; i < n; i++) { ptaGetPt(pta, i, &x, &y); numaGetFValue(naerror, i, &val); if (val <= factor * mederr) /* <= in case mederr = 0 */ ptaAddPt(ptad, x, y); } numaDestroy(&naerror); n = ptaGetCount(ptad); if ((n = ptaGetCount(ptad)) < 3) { ptaDestroy(&ptad); return ERROR_INT("less than 3 pts found", procName, 1); } /* Do LSF again */ ret = ptaGetQuadraticLSF(ptad, pa, pb, pc, pnafit); if (pptad) *pptad = ptad; else ptaDestroy(&ptad); return ret; } /*! * \brief applyLinearFit() * * \param[in] a, b linear fit coefficients * \param[in] x * \param[out] py y = a * x + b * \return 0 if OK, 1 on error */ l_int32 applyLinearFit(l_float32 a, l_float32 b, l_float32 x, l_float32 *py) { PROCNAME("applyLinearFit"); if (!py) return ERROR_INT("&y not defined", procName, 1); *py = a * x + b; return 0; } /*! * \brief applyQuadraticFit() * * \param[in] a, b, c quadratic fit coefficients * \param[in] x * \param[out] py y = a * x^2 + b * x + c * \return 0 if OK, 1 on error */ l_int32 applyQuadraticFit(l_float32 a, l_float32 b, l_float32 c, l_float32 x, l_float32 *py) { PROCNAME("applyQuadraticFit"); if (!py) return ERROR_INT("&y not defined", procName, 1); *py = a * x * x + b * x + c; return 0; } /*! * \brief applyCubicFit() * * \param[in] a, b, c, d cubic fit coefficients * \param[in] x * \param[out] py y = a * x^3 + b * x^2 + c * x + d * \return 0 if OK, 1 on error */ l_int32 applyCubicFit(l_float32 a, l_float32 b, l_float32 c, l_float32 d, l_float32 x, l_float32 *py) { PROCNAME("applyCubicFit"); if (!py) return ERROR_INT("&y not defined", procName, 1); *py = a * x * x * x + b * x * x + c * x + d; return 0; } /*! * \brief applyQuarticFit() * * \param[in] a, b, c, d, e quartic fit coefficients * \param[in] x * \param[out] py y = a * x^4 + b * x^3 + c * x^2 + d * x + e * \return 0 if OK, 1 on error */ l_int32 applyQuarticFit(l_float32 a, l_float32 b, l_float32 c, l_float32 d, l_float32 e, l_float32 x, l_float32 *py) { l_float32 x2; PROCNAME("applyQuarticFit"); if (!py) return ERROR_INT("&y not defined", procName, 1); x2 = x * x; *py = a * x2 * x2 + b * x2 * x + c * x2 + d * x + e; return 0; } /*---------------------------------------------------------------------* * Interconversions with Pix * *---------------------------------------------------------------------*/ /*! * \brief pixPlotAlongPta() * * \param[in] pixs any depth * \param[in] pta set of points on which to plot * \param[in] outformat GPLOT_PNG, GPLOT_PS, GPLOT_EPS, GPLOT_LATEX * \param[in] title [optional] for plot; can be null * \return 0 if OK, 1 on error * * <pre> * Notes: * (1) This is a debugging function. * (2) Removes existing colormaps and clips the pta to the input %pixs. * (3) If the image is RGB, three separate plots are generated. * </pre> */ l_int32 pixPlotAlongPta(PIX *pixs, PTA *pta, l_int32 outformat, const char *title) { char buffer[128]; char *rtitle, *gtitle, *btitle; static l_int32 count = 0; /* require separate temp files for each call */ l_int32 i, x, y, d, w, h, npts, rval, gval, bval; l_uint32 val; NUMA *na, *nar, *nag, *nab; PIX *pixt; PROCNAME("pixPlotAlongPta"); lept_mkdir("lept/plot"); if (!pixs) return ERROR_INT("pixs not defined", procName, 1); if (!pta) return ERROR_INT("pta not defined", procName, 1); if (outformat != GPLOT_PNG && outformat != GPLOT_PS && outformat != GPLOT_EPS && outformat != GPLOT_LATEX) { L_WARNING("outformat invalid; using GPLOT_PNG\n", procName); outformat = GPLOT_PNG; } pixt = pixRemoveColormap(pixs, REMOVE_CMAP_BASED_ON_SRC); d = pixGetDepth(pixt); w = pixGetWidth(pixt); h = pixGetHeight(pixt); npts = ptaGetCount(pta); if (d == 32) { nar = numaCreate(npts); nag = numaCreate(npts); nab = numaCreate(npts); for (i = 0; i < npts; i++) { ptaGetIPt(pta, i, &x, &y); if (x < 0 || x >= w) continue; if (y < 0 || y >= h) continue; pixGetPixel(pixt, x, y, &val); rval = GET_DATA_BYTE(&val, COLOR_RED); gval = GET_DATA_BYTE(&val, COLOR_GREEN); bval = GET_DATA_BYTE(&val, COLOR_BLUE); numaAddNumber(nar, rval); numaAddNumber(nag, gval); numaAddNumber(nab, bval); } snprintf(buffer, sizeof(buffer), "/tmp/lept/plot/%03d", count++); rtitle = stringJoin("Red: ", title); gplotSimple1(nar, outformat, buffer, rtitle); snprintf(buffer, sizeof(buffer), "/tmp/lept/plot/%03d", count++); gtitle = stringJoin("Green: ", title); gplotSimple1(nag, outformat, buffer, gtitle); snprintf(buffer, sizeof(buffer), "/tmp/lept/plot/%03d", count++); btitle = stringJoin("Blue: ", title); gplotSimple1(nab, outformat, buffer, btitle); numaDestroy(&nar); numaDestroy(&nag); numaDestroy(&nab); LEPT_FREE(rtitle); LEPT_FREE(gtitle); LEPT_FREE(btitle); } else { na = numaCreate(npts); for (i = 0; i < npts; i++) { ptaGetIPt(pta, i, &x, &y); if (x < 0 || x >= w) continue; if (y < 0 || y >= h) continue; pixGetPixel(pixt, x, y, &val); numaAddNumber(na, (l_float32)val); } snprintf(buffer, sizeof(buffer), "/tmp/lept/plot/%03d", count++); gplotSimple1(na, outformat, buffer, title); numaDestroy(&na); } pixDestroy(&pixt); return 0; } /*! * \brief ptaGetPixelsFromPix() * * \param[in] pixs 1 bpp * \param[in] box [optional] can be null * \return pta, or NULL on error * * <pre> * Notes: * (1) Generates a pta of fg pixels in the pix, within the box. * If box == NULL, it uses the entire pix. * </pre> */ PTA * ptaGetPixelsFromPix(PIX *pixs, BOX *box) { l_int32 i, j, w, h, wpl, xstart, xend, ystart, yend, bw, bh; l_uint32 *data, *line; PTA *pta; PROCNAME("ptaGetPixelsFromPix"); if (!pixs || (pixGetDepth(pixs) != 1)) return (PTA *)ERROR_PTR("pixs undefined or not 1 bpp", procName, NULL); pixGetDimensions(pixs, &w, &h, NULL); data = pixGetData(pixs); wpl = pixGetWpl(pixs); xstart = ystart = 0; xend = w - 1; yend = h - 1; if (box) { boxGetGeometry(box, &xstart, &ystart, &bw, &bh); xend = xstart + bw - 1; yend = ystart + bh - 1; } if ((pta = ptaCreate(0)) == NULL) return (PTA *)ERROR_PTR("pta not made", procName, NULL); for (i = ystart; i <= yend; i++) { line = data + i * wpl; for (j = xstart; j <= xend; j++) { if (GET_DATA_BIT(line, j)) ptaAddPt(pta, j, i); } } return pta; } /*! * \brief pixGenerateFromPta() * * \param[in] pta * \param[in] w, h of pix * \return pix 1 bpp, or NULL on error * * <pre> * Notes: * (1) Points are rounded to nearest ints. * (2) Any points outside (w,h) are silently discarded. * (3) Output 1 bpp pix has values 1 for each point in the pta. * </pre> */ PIX * pixGenerateFromPta(PTA *pta, l_int32 w, l_int32 h) { l_int32 n, i, x, y; PIX *pix; PROCNAME("pixGenerateFromPta"); if (!pta) return (PIX *)ERROR_PTR("pta not defined", procName, NULL); if ((pix = pixCreate(w, h, 1)) == NULL) return (PIX *)ERROR_PTR("pix not made", procName, NULL); n = ptaGetCount(pta); for (i = 0; i < n; i++) { ptaGetIPt(pta, i, &x, &y); if (x < 0 || x >= w || y < 0 || y >= h) continue; pixSetPixel(pix, x, y, 1); } return pix; } /*! * \brief ptaGetBoundaryPixels() * * \param[in] pixs 1 bpp * \param[in] type L_BOUNDARY_FG, L_BOUNDARY_BG * \return pta, or NULL on error * * <pre> * Notes: * (1) This generates a pta of either fg or bg boundary pixels. * (2) See also pixGeneratePtaBoundary() for rendering of * fg boundary pixels. * </pre> */ PTA * ptaGetBoundaryPixels(PIX *pixs, l_int32 type) { PIX *pixt; PTA *pta; PROCNAME("ptaGetBoundaryPixels"); if (!pixs || (pixGetDepth(pixs) != 1)) return (PTA *)ERROR_PTR("pixs undefined or not 1 bpp", procName, NULL); if (type != L_BOUNDARY_FG && type != L_BOUNDARY_BG) return (PTA *)ERROR_PTR("invalid type", procName, NULL); if (type == L_BOUNDARY_FG) pixt = pixMorphSequence(pixs, "e3.3", 0); else pixt = pixMorphSequence(pixs, "d3.3", 0); pixXor(pixt, pixt, pixs); pta = ptaGetPixelsFromPix(pixt, NULL); pixDestroy(&pixt); return pta; } /*! * \brief ptaaGetBoundaryPixels() * * \param[in] pixs 1 bpp * \param[in] type L_BOUNDARY_FG, L_BOUNDARY_BG * \param[in] connectivity 4 or 8 * \param[out] pboxa [optional] bounding boxes of the c.c. * \param[out] ppixa [optional] pixa of the c.c. * \return ptaa, or NULL on error * * <pre> * Notes: * (1) This generates a ptaa of either fg or bg boundary pixels, * where each pta has the boundary pixels for a connected * component. * (2) We can't simply find all the boundary pixels and then select * those within the bounding box of each component, because * bounding boxes can overlap. It is necessary to extract and * dilate or erode each component separately. Note also that * special handling is required for bg pixels when the * component touches the pix boundary. * </pre> */ PTAA * ptaaGetBoundaryPixels(PIX *pixs, l_int32 type, l_int32 connectivity, BOXA **pboxa, PIXA **ppixa) { l_int32 i, n, w, h, x, y, bw, bh, left, right, top, bot; BOXA *boxa; PIX *pixt1, *pixt2; PIXA *pixa; PTA *pta1, *pta2; PTAA *ptaa; PROCNAME("ptaaGetBoundaryPixels"); if (pboxa) *pboxa = NULL; if (ppixa) *ppixa = NULL; if (!pixs || (pixGetDepth(pixs) != 1)) return (PTAA *)ERROR_PTR("pixs undefined or not 1 bpp", procName, NULL); if (type != L_BOUNDARY_FG && type != L_BOUNDARY_BG) return (PTAA *)ERROR_PTR("invalid type", procName, NULL); if (connectivity != 4 && connectivity != 8) return (PTAA *)ERROR_PTR("connectivity not 4 or 8", procName, NULL); pixGetDimensions(pixs, &w, &h, NULL); boxa = pixConnComp(pixs, &pixa, connectivity); n = boxaGetCount(boxa); ptaa = ptaaCreate(0); for (i = 0; i < n; i++) { pixt1 = pixaGetPix(pixa, i, L_CLONE); boxaGetBoxGeometry(boxa, i, &x, &y, &bw, &bh); left = right = top = bot = 0; if (type == L_BOUNDARY_BG) { if (x > 0) left = 1; if (y > 0) top = 1; if (x + bw < w) right = 1; if (y + bh < h) bot = 1; pixt2 = pixAddBorderGeneral(pixt1, left, right, top, bot, 0); } else { pixt2 = pixClone(pixt1); } pta1 = ptaGetBoundaryPixels(pixt2, type); pta2 = ptaTransform(pta1, x - left, y - top, 1.0, 1.0); ptaaAddPta(ptaa, pta2, L_INSERT); ptaDestroy(&pta1); pixDestroy(&pixt1); pixDestroy(&pixt2); } if (pboxa) *pboxa = boxa; else boxaDestroy(&boxa); if (ppixa) *ppixa = pixa; else pixaDestroy(&pixa); return ptaa; } /*! * \brief ptaaIndexLabeledPixels() * * \param[in] pixs 32 bpp, of indices of c.c. * \param[out] pncc [optional] number of connected components * \return ptaa, or NULL on error * * <pre> * Notes: * (1) The pixel values in %pixs are the index of the connected component * to which the pixel belongs; %pixs is typically generated from * a 1 bpp pix by pixConnCompTransform(). Background pixels in * the generating 1 bpp pix are represented in %pixs by 0. * We do not check that the pixel values are correctly labelled. * (2) Each pta in the returned ptaa gives the pixel locations * correspnding to a connected component, with the label of each * given by the index of the pta into the ptaa. * (3) Initialize with the first pta in ptaa being empty and * representing the background value (index 0) in the pix. * </pre> */ PTAA * ptaaIndexLabeledPixels(PIX *pixs, l_int32 *pncc) { l_int32 wpl, index, i, j, w, h; l_uint32 maxval; l_uint32 *data, *line; PTA *pta; PTAA *ptaa; PROCNAME("ptaaIndexLabeledPixels"); if (pncc) *pncc = 0; if (!pixs || (pixGetDepth(pixs) != 32)) return (PTAA *)ERROR_PTR("pixs undef or not 32 bpp", procName, NULL); /* The number of c.c. is the maximum pixel value. Use this to * initialize ptaa with sufficient pta arrays */ pixGetMaxValueInRect(pixs, NULL, &maxval, NULL, NULL); if (pncc) *pncc = maxval; pta = ptaCreate(1); ptaa = ptaaCreate(maxval + 1); ptaaInitFull(ptaa, pta); ptaDestroy(&pta); /* Sweep over %pixs, saving the pixel coordinates of each pixel * with nonzero value in the appropriate pta, indexed by that value. */ pixGetDimensions(pixs, &w, &h, NULL); data = pixGetData(pixs); wpl = pixGetWpl(pixs); for (i = 0; i < h; i++) { line = data + wpl * i; for (j = 0; j < w; j++) { index = line[j]; if (index > 0) ptaaAddPt(ptaa, index, j, i); } } return ptaa; } /*! * \brief ptaGetNeighborPixLocs() * * \param[in] pixs any depth * \param[in] x, y pixel from which we search for nearest neighbors * conn (4 or 8 connectivity * \return pta, or NULL on error * * <pre> * Notes: * (1) Generates a pta of all valid neighbor pixel locations, * or NULL on error. * </pre> */ PTA * ptaGetNeighborPixLocs(PIX *pixs, l_int32 x, l_int32 y, l_int32 conn) { l_int32 w, h; PTA *pta; PROCNAME("ptaGetNeighborPixLocs"); if (!pixs) return (PTA *)ERROR_PTR("pixs not defined", procName, NULL); pixGetDimensions(pixs, &w, &h, NULL); if (x < 0 || x >= w || y < 0 || y >= h) return (PTA *)ERROR_PTR("(x,y) not in pixs", procName, NULL); if (conn != 4 && conn != 8) return (PTA *)ERROR_PTR("conn not 4 or 8", procName, NULL); pta = ptaCreate(conn); if (x > 0) ptaAddPt(pta, x - 1, y); if (x < w - 1) ptaAddPt(pta, x + 1, y); if (y > 0) ptaAddPt(pta, x, y - 1); if (y < h - 1) ptaAddPt(pta, x, y + 1); if (conn == 8) { if (x > 0) { if (y > 0) ptaAddPt(pta, x - 1, y - 1); if (y < h - 1) ptaAddPt(pta, x - 1, y + 1); } if (x < w - 1) { if (y > 0) ptaAddPt(pta, x + 1, y - 1); if (y < h - 1) ptaAddPt(pta, x + 1, y + 1); } } return pta; } /*---------------------------------------------------------------------* * Interconversion with Numa * *---------------------------------------------------------------------*/ /*! * \brief numaConvertToPta1() * * \param[in] na numa with implicit y(x) * \return pta if OK; null on error */ PTA * numaConvertToPta1(NUMA *na) { l_int32 i, n; l_float32 startx, delx, val; PTA *pta; PROCNAME("numaConvertToPta1"); if (!na) return (PTA *)ERROR_PTR("na not defined", procName, NULL); n = numaGetCount(na); pta = ptaCreate(n); numaGetParameters(na, &startx, &delx); for (i = 0; i < n; i++) { numaGetFValue(na, i, &val); ptaAddPt(pta, startx + i * delx, val); } return pta; } /*! * \brief numaConvertToPta2() * * \param[in] nax * \param[in] nay * \return pta if OK; null on error */ PTA * numaConvertToPta2(NUMA *nax, NUMA *nay) { l_int32 i, n, nx, ny; l_float32 valx, valy; PTA *pta; PROCNAME("numaConvertToPta2"); if (!nax || !nay) return (PTA *)ERROR_PTR("nax and nay not both defined", procName, NULL); nx = numaGetCount(nax); ny = numaGetCount(nay); n = L_MIN(nx, ny); if (nx != ny) L_WARNING("nx = %d does not equal ny = %d\n", procName, nx, ny); pta = ptaCreate(n); for (i = 0; i < n; i++) { numaGetFValue(nax, i, &valx); numaGetFValue(nay, i, &valy); ptaAddPt(pta, valx, valy); } return pta; } /*! * \brief ptaConvertToNuma() * * \param[in] pta * \param[out] pnax addr of nax * \param[out] pnay addr of nay * \return 0 if OK, 1 on error */ l_int32 ptaConvertToNuma(PTA *pta, NUMA **pnax, NUMA **pnay) { l_int32 i, n; l_float32 valx, valy; PROCNAME("ptaConvertToNuma"); if (pnax) *pnax = NULL; if (pnay) *pnay = NULL; if (!pnax || !pnay) return ERROR_INT("&nax and &nay not both defined", procName, 1); if (!pta) return ERROR_INT("pta not defined", procName, 1); n = ptaGetCount(pta); *pnax = numaCreate(n); *pnay = numaCreate(n); for (i = 0; i < n; i++) { ptaGetPt(pta, i, &valx, &valy); numaAddNumber(*pnax, valx); numaAddNumber(*pnay, valy); } return 0; } /*---------------------------------------------------------------------* * Display Pta and Ptaa * *---------------------------------------------------------------------*/ /*! * \brief pixDisplayPta() * * \param[in] pixd can be same as pixs or NULL; 32 bpp if in-place * \param[in] pixs 1, 2, 4, 8, 16 or 32 bpp * \param[in] pta of path to be plotted * \return pixd 32 bpp RGB version of pixs, with path in green. * * <pre> * Notes: * (1) To write on an existing pixs, pixs must be 32 bpp and * call with pixd == pixs: * pixDisplayPta(pixs, pixs, pta); * To write to a new pix, use pixd == NULL and call: * pixd = pixDisplayPta(NULL, pixs, pta); * (2) On error, returns pixd to avoid losing pixs if called as * pixs = pixDisplayPta(pixs, pixs, pta); * </pre> */ PIX * pixDisplayPta(PIX *pixd, PIX *pixs, PTA *pta) { l_int32 i, n, w, h, x, y; l_uint32 rpixel, gpixel, bpixel; PROCNAME("pixDisplayPta"); if (!pixs) return (PIX *)ERROR_PTR("pixs not defined", procName, pixd); if (!pta) return (PIX *)ERROR_PTR("pta not defined", procName, pixd); if (pixd && (pixd != pixs || pixGetDepth(pixd) != 32)) return (PIX *)ERROR_PTR("invalid pixd", procName, pixd); if (!pixd) pixd = pixConvertTo32(pixs); pixGetDimensions(pixd, &w, &h, NULL); composeRGBPixel(255, 0, 0, &rpixel); /* start point */ composeRGBPixel(0, 255, 0, &gpixel); composeRGBPixel(0, 0, 255, &bpixel); /* end point */ n = ptaGetCount(pta); for (i = 0; i < n; i++) { ptaGetIPt(pta, i, &x, &y); if (x < 0 || x >= w || y < 0 || y >= h) continue; if (i == 0) pixSetPixel(pixd, x, y, rpixel); else if (i < n - 1) pixSetPixel(pixd, x, y, gpixel); else pixSetPixel(pixd, x, y, bpixel); } return pixd; } /*! * \brief pixDisplayPtaaPattern() * * \param[in] pixd 32 bpp * \param[in] pixs 1, 2, 4, 8, 16 or 32 bpp; 32 bpp if in place * \param[in] ptaa giving locations at which the pattern is displayed * \param[in] pixp 1 bpp pattern to be placed such that its reference * point co-locates with each point in pta * \param[in] cx, cy reference point in pattern * \return pixd 32 bpp RGB version of pixs. * * <pre> * Notes: * (1) To write on an existing pixs, pixs must be 32 bpp and * call with pixd == pixs: * pixDisplayPtaPattern(pixs, pixs, pta, ...); * To write to a new pix, use pixd == NULL and call: * pixd = pixDisplayPtaPattern(NULL, pixs, pta, ...); * (2) Puts a random color on each pattern associated with a pta. * (3) On error, returns pixd to avoid losing pixs if called as * pixs = pixDisplayPtaPattern(pixs, pixs, pta, ...); * (4) A typical pattern to be used is a circle, generated with * generatePtaFilledCircle() * </pre> */ PIX * pixDisplayPtaaPattern(PIX *pixd, PIX *pixs, PTAA *ptaa, PIX *pixp, l_int32 cx, l_int32 cy) { l_int32 i, n; l_uint32 color; PIXCMAP *cmap; PTA *pta; PROCNAME("pixDisplayPtaaPattern"); if (!pixs) return (PIX *)ERROR_PTR("pixs not defined", procName, pixd); if (!ptaa) return (PIX *)ERROR_PTR("ptaa not defined", procName, pixd); if (pixd && (pixd != pixs || pixGetDepth(pixd) != 32)) return (PIX *)ERROR_PTR("invalid pixd", procName, pixd); if (!pixp) return (PIX *)ERROR_PTR("pixp not defined", procName, pixd); if (!pixd) pixd = pixConvertTo32(pixs); /* Use 256 random colors */ cmap = pixcmapCreateRandom(8, 0, 0); n = ptaaGetCount(ptaa); for (i = 0; i < n; i++) { pixcmapGetColor32(cmap, i % 256, &color); pta = ptaaGetPta(ptaa, i, L_CLONE); pixDisplayPtaPattern(pixd, pixd, pta, pixp, cx, cy, color); ptaDestroy(&pta); } pixcmapDestroy(&cmap); return pixd; } /*! * \brief pixDisplayPtaPattern() * * \param[in] pixd can be same as pixs or NULL; 32 bpp if in-place * \param[in] pixs 1, 2, 4, 8, 16 or 32 bpp * \param[in] pta giving locations at which the pattern is displayed * \param[in] pixp 1 bpp pattern to be placed such that its reference * point co-locates with each point in pta * \param[in] cx, cy reference point in pattern * \param[in] color in 0xrrggbb00 format * \return pixd 32 bpp RGB version of pixs. * * <pre> * Notes: * (1) To write on an existing pixs, pixs must be 32 bpp and * call with pixd == pixs: * pixDisplayPtaPattern(pixs, pixs, pta, ...); * To write to a new pix, use pixd == NULL and call: * pixd = pixDisplayPtaPattern(NULL, pixs, pta, ...); * (2) On error, returns pixd to avoid losing pixs if called as * pixs = pixDisplayPtaPattern(pixs, pixs, pta, ...); * (3) A typical pattern to be used is a circle, generated with * generatePtaFilledCircle() * </pre> */ PIX * pixDisplayPtaPattern(PIX *pixd, PIX *pixs, PTA *pta, PIX *pixp, l_int32 cx, l_int32 cy, l_uint32 color) { l_int32 i, n, w, h, x, y; PTA *ptat; PROCNAME("pixDisplayPtaPattern"); if (!pixs) return (PIX *)ERROR_PTR("pixs not defined", procName, pixd); if (!pta) return (PIX *)ERROR_PTR("pta not defined", procName, pixd); if (pixd && (pixd != pixs || pixGetDepth(pixd) != 32)) return (PIX *)ERROR_PTR("invalid pixd", procName, pixd); if (!pixp) return (PIX *)ERROR_PTR("pixp not defined", procName, pixd); if (!pixd) pixd = pixConvertTo32(pixs); pixGetDimensions(pixs, &w, &h, NULL); ptat = ptaReplicatePattern(pta, pixp, NULL, cx, cy, w, h); n = ptaGetCount(ptat); for (i = 0; i < n; i++) { ptaGetIPt(ptat, i, &x, &y); if (x < 0 || x >= w || y < 0 || y >= h) continue; pixSetPixel(pixd, x, y, color); } ptaDestroy(&ptat); return pixd; } /*! * \brief ptaReplicatePattern() * * \param[in] ptas "sparse" input pta * \param[in] pixp [optional] 1 bpp pattern, to be replicated in output pta * \param[in] ptap [optional] set of pts, to be replicated in output pta * \param[in] cx, cy reference point in pattern * \param[in] w, h clipping sizes for output pta * \return ptad with all points of replicated pattern, or NULL on error * * <pre> * Notes: * (1) You can use either the image %pixp or the set of pts %ptap. * (2) The pattern is placed with its reference point at each point * in ptas, and all the fg pixels are colleced into ptad. * For %pixp, this is equivalent to blitting pixp at each point * in ptas, and then converting the resulting pix to a pta. * </pre> */ PTA * ptaReplicatePattern(PTA *ptas, PIX *pixp, PTA *ptap, l_int32 cx, l_int32 cy, l_int32 w, l_int32 h) { l_int32 i, j, n, np, x, y, xp, yp, xf, yf; PTA *ptat, *ptad; PROCNAME("ptaReplicatePattern"); if (!ptas) return (PTA *)ERROR_PTR("ptas not defined", procName, NULL); if (!pixp && !ptap) return (PTA *)ERROR_PTR("no pattern is defined", procName, NULL); if (pixp && ptap) L_WARNING("pixp and ptap defined; using ptap\n", procName); n = ptaGetCount(ptas); ptad = ptaCreate(n); if (ptap) ptat = ptaClone(ptap); else ptat = ptaGetPixelsFromPix(pixp, NULL); np = ptaGetCount(ptat); for (i = 0; i < n; i++) { ptaGetIPt(ptas, i, &x, &y); for (j = 0; j < np; j++) { ptaGetIPt(ptat, j, &xp, &yp); xf = x - cx + xp; yf = y - cy + yp; if (xf >= 0 && xf < w && yf >= 0 && yf < h) ptaAddPt(ptad, xf, yf); } } ptaDestroy(&ptat); return ptad; } /*! * \brief pixDisplayPtaa() * * \param[in] pixs 1, 2, 4, 8, 16 or 32 bpp * \param[in] ptaa array of paths to be plotted * \return pixd 32 bpp RGB version of pixs, with paths plotted * in different colors, or NULL on error */ PIX * pixDisplayPtaa(PIX *pixs, PTAA *ptaa) { l_int32 i, j, w, h, npta, npt, x, y, rv, gv, bv; l_uint32 *pixela; NUMA *na1, *na2, *na3; PIX *pixd; PTA *pta; PROCNAME("pixDisplayPtaa"); if (!pixs) return (PIX *)ERROR_PTR("pixs not defined", procName, NULL); if (!ptaa) return (PIX *)ERROR_PTR("ptaa not defined", procName, NULL); npta = ptaaGetCount(ptaa); if (npta == 0) return (PIX *)ERROR_PTR("no pta", procName, NULL); if ((pixd = pixConvertTo32(pixs)) == NULL) return (PIX *)ERROR_PTR("pixd not made", procName, NULL); pixGetDimensions(pixd, &w, &h, NULL); /* Make a colormap for the paths */ if ((pixela = (l_uint32 *)LEPT_CALLOC(npta, sizeof(l_uint32))) == NULL) { pixDestroy(&pixd); return (PIX *)ERROR_PTR("calloc fail for pixela", procName, NULL); } na1 = numaPseudorandomSequence(256, 14657); na2 = numaPseudorandomSequence(256, 34631); na3 = numaPseudorandomSequence(256, 54617); for (i = 0; i < npta; i++) { numaGetIValue(na1, i % 256, &rv); numaGetIValue(na2, i % 256, &gv); numaGetIValue(na3, i % 256, &bv); composeRGBPixel(rv, gv, bv, &pixela[i]); } numaDestroy(&na1); numaDestroy(&na2); numaDestroy(&na3); for (i = 0; i < npta; i++) { pta = ptaaGetPta(ptaa, i, L_CLONE); npt = ptaGetCount(pta); for (j = 0; j < npt; j++) { ptaGetIPt(pta, j, &x, &y); if (x < 0 || x >= w || y < 0 || y >= h) continue; pixSetPixel(pixd, x, y, pixela[i]); } ptaDestroy(&pta); } LEPT_FREE(pixela); return pixd; }
DocCreator/DocCreator
thirdparty/leptonica/src/ptafunc1.c
C
lgpl-3.0
75,693
// #include <ia32/arch/board-ia32_pc-config.h>
tectronics/phantomuserland
include/ia32/arch/board-ia32_default-config.h
C
lgpl-3.0
50
/* * Copyright 2014-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.store.serializers; import org.onosproject.net.ConnectPoint; import org.onosproject.net.LinkKey; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.Serializer; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; /** * Kryo Serializer for {@link LinkKey}. */ public class LinkKeySerializer extends Serializer<LinkKey> { /** * Creates {@link LinkKey} serializer instance. */ public LinkKeySerializer() { // non-null, immutable super(false, true); } @Override public void write(Kryo kryo, Output output, LinkKey object) { kryo.writeClassAndObject(output, object.src()); kryo.writeClassAndObject(output, object.dst()); } @Override public LinkKey read(Kryo kryo, Input input, Class<LinkKey> type) { ConnectPoint src = (ConnectPoint) kryo.readClassAndObject(input); ConnectPoint dst = (ConnectPoint) kryo.readClassAndObject(input); return LinkKey.linkKey(src, dst); } }
opennetworkinglab/onos
core/store/serializers/src/main/java/org/onosproject/store/serializers/LinkKeySerializer.java
Java
apache-2.0
1,671
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * If x is -Infinity and y>0 and y is an odd integer, Math.pow(x,y) is -Infinity * * @path ch15/15.8/15.8.2/15.8.2.13/S15.8.2.13_A13.js * @description Checking if Math.pow(x,y) equals to -Infinity, where x is -Infinity and y>0 */ // CHECK#1 x = -Infinity; y = new Array(); y[0] = 1; y[1] = 111; y[2] = 111111; ynum = 3; for (i = 0; i < ynum; i++) { if (Math.pow(x,y[i]) !== -Infinity) { $ERROR("#1: Math.pow(" + x + ", " + y[i] + ") !== -Infinity"); } }
popravich/typescript
tests/Fidelity/test262/suite/ch15/15.8/15.8.2/15.8.2.13/S15.8.2.13_A13.js
JavaScript
apache-2.0
604
var fs = require('fs') var path = require('path') var resolve = path.resolve var osenv = require('osenv') var mkdirp = require('mkdirp') var rimraf = require('rimraf') var test = require('tap').test var npm = require('../../lib/npm') var common = require('../common-tap') var chain = require('slide').chain var mockPath = resolve(__dirname, 'install-shrinkwrapped') var parentPath = resolve(mockPath, 'parent') var parentNodeModulesPath = path.join(parentPath, 'node_modules') var outdatedNodeModulesPath = resolve(mockPath, 'node-modules-backup') var childPath = resolve(mockPath, 'child.git') var gitDaemon var gitDaemonPID var git var parentPackageJSON = JSON.stringify({ name: 'parent', version: '0.1.0' }) var childPackageJSON = JSON.stringify({ name: 'child', version: '0.1.0' }) test('setup', function (t) { cleanup() setup(function (err, result) { t.ifError(err, 'git started up successfully') if (!err) { gitDaemon = result[result.length - 2] gitDaemonPID = result[result.length - 1] } t.end() }) }) test('shrinkwrapped git dependency got updated', function (t) { t.comment('test for https://github.com/npm/npm/issues/12718') // Prepare the child package git repo with two commits prepareChildAndGetRefs(function (refs) { chain([ // Install & shrinkwrap child package's first commit [npm.commands.install, ['git://localhost:1234/child.git#' + refs[0]]], // Backup node_modules with the first commit [fs.rename, parentNodeModulesPath, outdatedNodeModulesPath], // Install & shrinkwrap child package's second commit [npm.commands.install, ['git://localhost:1234/child.git#' + refs[1]]], // Restore node_modules with the first commit [rimraf, parentNodeModulesPath], [fs.rename, outdatedNodeModulesPath, parentNodeModulesPath], // Update node_modules [npm.commands.install, []] ], function () { var childPackageJSON = require(path.join(parentNodeModulesPath, 'child', 'package.json')) t.equal( childPackageJSON._resolved, 'git://localhost:1234/child.git#' + refs[1], "Child package wasn't updated" ) t.end() }) }) }) test('clean', function (t) { gitDaemon.on('close', function () { cleanup() t.end() }) process.kill(gitDaemonPID) }) function setup (cb) { // Setup parent package mkdirp.sync(parentPath) fs.writeFileSync(resolve(parentPath, 'package.json'), parentPackageJSON) process.chdir(parentPath) // Setup child mkdirp.sync(childPath) fs.writeFileSync(resolve(childPath, 'package.json'), childPackageJSON) // Setup npm and then git npm.load({ registry: common.registry, loglevel: 'silent', save: true // Always install packages with --save }, function () { // It's important to initialize git after npm because it uses config initializeGit(cb) }) } function cleanup () { process.chdir(osenv.tmpdir()) rimraf.sync(mockPath) rimraf.sync(common['npm_config_cache']) } function prepareChildAndGetRefs (cb) { var opts = { cwd: childPath, env: { PATH: process.env.PATH } } chain([ [fs.writeFile, path.join(childPath, 'README.md'), ''], git.chainableExec(['add', 'README.md'], opts), git.chainableExec(['commit', '-m', 'Add README'], opts), git.chainableExec(['log', '--pretty=format:"%H"', '-2'], opts) ], function () { var gitLogStdout = arguments[arguments.length - 1] var refs = gitLogStdout[gitLogStdout.length - 1].split('\n').map(function (ref) { return ref.match(/^"(.+)"$/)[1] }).reverse() // Reverse refs order: last, first -> first, last cb(refs) }) } function initializeGit (cb) { git = require('../../lib/utils/git') common.makeGitRepo({ path: childPath, commands: [startGitDaemon] }, cb) } function startGitDaemon (cb) { var daemon = git.spawn( [ 'daemon', '--verbose', '--listen=localhost', '--export-all', '--base-path=' + mockPath, // Path to the dir that contains child.git '--reuseaddr', '--port=1234' ], { cwd: parentPath, env: process.env, stdio: ['pipe', 'pipe', 'pipe'] } ) daemon.stderr.on('data', function findChild (c) { var cpid = c.toString().match(/^\[(\d+)\]/) if (cpid[1]) { this.removeListener('data', findChild) cb(null, [daemon, cpid[1]]) } }) }
mrtequino/JSW
nodejs/pos-server/node_modules/npm/test/tap/install-shrinkwrapped-git.js
JavaScript
apache-2.0
4,407
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.test.rest.yaml.section; import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.xcontent.DeprecationHandler; import org.elasticsearch.common.xcontent.LoggingDeprecationHandler; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.yaml.YamlXContent; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TreeSet; /** * Holds a REST test suite loaded from a specific yaml file. * Supports a setup section and multiple test sections. */ public class ClientYamlTestSuite { public static ClientYamlTestSuite parse(String api, Path file) throws IOException { if (!Files.isRegularFile(file)) { throw new IllegalArgumentException(file.toAbsolutePath() + " is not a file"); } String filename = file.getFileName().toString(); //remove the file extension int i = filename.lastIndexOf('.'); if (i > 0) { filename = filename.substring(0, i); } //our yaml parser seems to be too tolerant. Each yaml suite must end with \n, otherwise clients tests might break. try (FileChannel channel = FileChannel.open(file, StandardOpenOption.READ)) { ByteBuffer bb = ByteBuffer.wrap(new byte[1]); if (channel.size() == 0) { throw new IllegalArgumentException("test suite file " + file.toString() + " is empty"); } channel.read(bb, channel.size() - 1); if (bb.get(0) != 10) { throw new IOException("test suite [" + api + "/" + filename + "] doesn't end with line feed (\\n)"); } } try (XContentParser parser = YamlXContent.yamlXContent.createParser(ExecutableSection.XCONTENT_REGISTRY, LoggingDeprecationHandler.INSTANCE, Files.newInputStream(file))) { return parse(api, filename, parser); } catch(Exception e) { throw new IOException("Error parsing " + api + "/" + filename, e); } } public static ClientYamlTestSuite parse(String api, String suiteName, XContentParser parser) throws IOException { parser.nextToken(); assert parser.currentToken() == XContentParser.Token.START_OBJECT : "expected token to be START_OBJECT but was " + parser.currentToken(); ClientYamlTestSuite restTestSuite = new ClientYamlTestSuite(api, suiteName); restTestSuite.setSetupSection(SetupSection.parseIfNext(parser)); restTestSuite.setTeardownSection(TeardownSection.parseIfNext(parser)); while(true) { //the "---" section separator is not understood by the yaml parser. null is returned, same as when the parser is closed //we need to somehow distinguish between a null in the middle of a test ("---") // and a null at the end of the file (at least two consecutive null tokens) if(parser.currentToken() == null) { if (parser.nextToken() == null) { break; } } ClientYamlTestSection testSection = ClientYamlTestSection.parse(parser); if (!restTestSuite.addTestSection(testSection)) { throw new ParsingException(testSection.getLocation(), "duplicate test section [" + testSection.getName() + "]"); } } return restTestSuite; } private final String api; private final String name; private SetupSection setupSection; private TeardownSection teardownSection; private Set<ClientYamlTestSection> testSections = new TreeSet<>(); public ClientYamlTestSuite(String api, String name) { this.api = api; this.name = name; } public String getApi() { return api; } public String getName() { return name; } public String getPath() { return api + "/" + name; } public SetupSection getSetupSection() { return setupSection; } public void setSetupSection(SetupSection setupSection) { this.setupSection = setupSection; } public TeardownSection getTeardownSection() { return teardownSection; } public void setTeardownSection(TeardownSection teardownSection) { this.teardownSection = teardownSection; } /** * Adds a {@link org.elasticsearch.test.rest.yaml.section.ClientYamlTestSection} to the REST suite * @return true if the test section was not already present, false otherwise */ public boolean addTestSection(ClientYamlTestSection testSection) { return this.testSections.add(testSection); } public List<ClientYamlTestSection> getTestSections() { return new ArrayList<>(testSections); } }
qwerty4030/elasticsearch
test/framework/src/main/java/org/elasticsearch/test/rest/yaml/section/ClientYamlTestSuite.java
Java
apache-2.0
5,796
#region License /* * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion using System; using System.Messaging; using System.Transactions; using Common.Logging; using Spring.Transaction; namespace Spring.Messaging.Listener { /// <summary> /// A MessageListenerContainer that uses distributed (DTC) based transactions. Exceptions are /// handled by instances of <see cref="IDistributedTransactionExceptionHandler"/>. /// </summary> /// <remarks> /// <para> /// Starts a DTC based transaction before receiving the message. The transaction is /// automaticaly promoted to 2PC to avoid the default behaivor of transactional promotion. /// Database and messaging operations will commit or rollback together. /// </para> /// <para> /// If you only want local message based transactions use the /// <see cref="TransactionalMessageListenerContainer"/>. With some simple programming /// you may also achieve 'exactly once' processing using the /// <see cref="TransactionalMessageListenerContainer"/>. /// </para> /// <para> /// Poison messages can be detected and sent to another queue using Spring's /// <see cref="SendToQueueDistributedTransactionExceptionHandler"/>. /// </para> /// </remarks> public class DistributedTxMessageListenerContainer : AbstractTransactionalMessageListenerContainer { #region Logging Definition private static readonly ILog LOG = LogManager.GetLogger(typeof (DistributedTxMessageListenerContainer)); #endregion private IDistributedTransactionExceptionHandler distributedTransactionExceptionHandler; /// <summary> /// Gets or sets the distributed transaction exception handler. /// </summary> /// <value>The distributed transaction exception handler.</value> public IDistributedTransactionExceptionHandler DistributedTransactionExceptionHandler { get { return distributedTransactionExceptionHandler; } set { distributedTransactionExceptionHandler = value; } } /// <summary> /// Set the transaction name to be the spring object name. /// Call base class Initialize() functionality. /// </summary> public override void Initialize() { // Use object name as default transaction name. if (TransactionDefinition.Name == null) { TransactionDefinition.Name = ObjectName; } // Proceed with superclass initialization. base.Initialize(); } /// <summary> /// Does the receive and execute using TxPlatformTransactionManager. Starts a distributed /// transaction before calling Receive. /// </summary> /// <param name="mq">The message queue.</param> /// <param name="status">The transactional status.</param> /// <returns> /// true if should continue peeking, false otherwise. /// </returns> protected override bool DoReceiveAndExecuteUsingPlatformTransactionManager(MessageQueue mq, ITransactionStatus status) { #region Logging if (LOG.IsDebugEnabled) { LOG.Debug("Executing DoReceiveAndExecuteUsingTxScopeTransactionManager"); } #endregion Logging //We are sure to be talking to a second resource manager, so avoid going through //the promotable transaction and force a distributed transaction right from the start. TransactionInterop.GetTransmitterPropagationToken(System.Transactions.Transaction.Current); Message message; try { message = mq.Receive(TimeSpan.Zero, MessageQueueTransactionType.Automatic); } catch (MessageQueueException ex) { if (ex.MessageQueueErrorCode == MessageQueueErrorCode.IOTimeout) { //expected to occur occasionally #region Logging if (LOG.IsTraceEnabled) { LOG.Trace( "MessageQueueErrorCode.IOTimeout: No message available to receive. May have been processed by another thread."); } #endregion status.SetRollbackOnly(); return false; // no more peeking unless this is the last listener thread } else { // A real issue in receiving the message lock (messageQueueMonitor) { mq.Close(); MessageQueue.ClearConnectionCache(); } throw; // will cause rollback in surrounding platform transaction manager and log exception } } if (message == null) { #region Logging if (LOG.IsTraceEnabled) { LOG.Trace("Message recieved is null from Queue = [" + mq.Path + "]"); } #endregion status.SetRollbackOnly(); return false; // no more peeking unless this is the last listener thread } try { #region Logging if (LOG.IsDebugEnabled) { LOG.Debug("Received message [" + message.Id + "] on queue [" + mq.Path + "]"); } #endregion MessageReceived(message); if (DistributedTransactionExceptionHandler != null) { if (DistributedTransactionExceptionHandler.IsPoisonMessage(message)) { DistributedTransactionExceptionHandler.HandlePoisonMessage(message); return true; // will remove from queue and continue receive loop. } } DoExecuteListener(message); } catch (Exception ex) { HandleDistributedTransactionListenerException(ex, message); throw; // will rollback and keep message on the queue. } finally { message.Dispose(); } return true; } /// <summary> /// Handles the distributed transaction listener exception by calling the /// <see cref="IDistributedTransactionExceptionHandler"/> if not null. /// </summary> /// <param name="exception">The exception.</param> /// <param name="message">The message.</param> protected virtual void HandleDistributedTransactionListenerException(Exception exception, Message message) { IDistributedTransactionExceptionHandler exceptionHandler = DistributedTransactionExceptionHandler; if (exceptionHandler != null) { exceptionHandler.OnException(exception, message); } } } }
yonglehou/spring-net
src/Spring/Spring.Messaging/Messaging/Listener/DistributedTxMessageListenerContainer.cs
C#
apache-2.0
8,103
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using FluentAssertions.Collections; using FluentAssertions.Common; using FluentAssertions.Equivalency; using FluentAssertions.Numeric; using FluentAssertions.Primitives; using FluentAssertions.Types; namespace FluentAssertions { /// <summary> /// Contains extension methods for custom assertions in unit tests. /// </summary> [DebuggerNonUserCode] internal static class InternalAssertionExtensions { /// <summary> /// Invokes the specified action on an subject so that you can chain it with any of the ShouldThrow or ShouldNotThrow /// overloads. /// </summary> public static Action Invoking<T>(this T subject, Action<T> action) { return () => action(subject); } /// <summary> /// Forces enumerating a collection. Should be used to assert that a method that uses the /// <c>yield</c> keyword throws a particular exception. /// </summary> public static Action Enumerating(this Func<IEnumerable> enumerable) { return () => ForceEnumeration(enumerable); } /// <summary> /// Forces enumerating a collection. Should be used to assert that a method that uses the /// <c>yield</c> keyword throws a particular exception. /// </summary> public static Action Enumerating<T>(this Func<IEnumerable<T>> enumerable) { return () => ForceEnumeration(() => (IEnumerable)enumerable()); } private static void ForceEnumeration(Func<IEnumerable> enumerable) { foreach (object item in enumerable()) { // Do nothing } } /// <summary> /// Returns an <see cref="ObjectAssertions"/> object that can be used to assert the /// current <see cref="object"/>. /// </summary> public static ObjectAssertions Should(this object actualValue) { return new ObjectAssertions(actualValue); } /// <summary> /// Returns an <see cref="BooleanAssertions"/> object that can be used to assert the /// current <see cref="bool"/>. /// </summary> public static BooleanAssertions Should(this bool actualValue) { return new BooleanAssertions(actualValue); } /// <summary> /// Returns an <see cref="NullableBooleanAssertions"/> object that can be used to assert the /// current nullable <see cref="bool"/>. /// </summary> public static NullableBooleanAssertions Should(this bool? actualValue) { return new NullableBooleanAssertions(actualValue); } /// <summary> /// Returns an <see cref="GuidAssertions"/> object that can be used to assert the /// current <see cref="Guid"/>. /// </summary> public static GuidAssertions Should(this Guid actualValue) { return new GuidAssertions(actualValue); } /// <summary> /// Returns an <see cref="NullableGuidAssertions"/> object that can be used to assert the /// current nullable <see cref="Guid"/>. /// </summary> public static NullableGuidAssertions Should(this Guid? actualValue) { return new NullableGuidAssertions(actualValue); } /// <summary> /// Returns an <see cref="NonGenericCollectionAssertions"/> object that can be used to assert the /// current <see cref="IEnumerable"/>. /// </summary> public static NonGenericCollectionAssertions Should(this IEnumerable actualValue) { return new NonGenericCollectionAssertions(actualValue); } /// <summary> /// Returns an <see cref="GenericCollectionAssertions{T}"/> object that can be used to assert the /// current <see cref="IEnumerable{T}"/>. /// </summary> public static GenericCollectionAssertions<T> Should<T>(this IEnumerable<T> actualValue) { return new GenericCollectionAssertions<T>(actualValue); } /// <summary> /// Returns an <see cref="StringCollectionAssertions"/> object that can be used to assert the /// current <see cref="IEnumerable{T}"/>. /// </summary> public static StringCollectionAssertions Should(this IEnumerable<string> @this) { return new StringCollectionAssertions(@this); } /// <summary> /// Returns an <see cref="GenericDictionaryAssertions{TKey, TValue}"/> object that can be used to assert the /// current <see cref="IDictionary{TKey, TValue}"/>. /// </summary> public static GenericDictionaryAssertions<TKey, TValue> Should<TKey, TValue>(this IDictionary<TKey, TValue> actualValue) { return new GenericDictionaryAssertions<TKey, TValue>(actualValue); } /// <summary> /// Returns an <see cref="DateTimeOffsetAssertions"/> object that can be used to assert the /// current <see cref="DateTime"/>. /// </summary> public static DateTimeOffsetAssertions Should(this DateTime actualValue) { return new DateTimeOffsetAssertions(actualValue); } /// <summary> /// Returns an <see cref="NullableDateTimeOffsetAssertions"/> object that can be used to assert the /// current nullable <see cref="DateTime"/>. /// </summary> public static NullableDateTimeOffsetAssertions Should(this DateTime? actualValue) { return new NullableDateTimeOffsetAssertions(actualValue); } /// <summary> /// Returns an <see cref="ComparableTypeAssertions{T}"/> object that can be used to assert the /// current <see cref="IComparable{T}"/>. /// </summary> public static ComparableTypeAssertions<T> Should<T>(this IComparable<T> comparableValue) { return new ComparableTypeAssertions<T>(comparableValue); } /// <summary> /// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the /// current <see cref="int"/>. /// </summary> public static NumericAssertions<int> Should(this int actualValue) { return new NumericAssertions<int>(actualValue); } /// <summary> /// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the /// current nullable <see cref="int"/>. /// </summary> public static NullableNumericAssertions<int> Should(this int? actualValue) { return new NullableNumericAssertions<int>(actualValue); } /// <summary> /// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the /// current <see cref="decimal"/>. /// </summary> public static NumericAssertions<decimal> Should(this decimal actualValue) { return new NumericAssertions<decimal>(actualValue); } /// <summary> /// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the /// current nullable <see cref="decimal"/>. /// </summary> public static NullableNumericAssertions<decimal> Should(this decimal? actualValue) { return new NullableNumericAssertions<decimal>(actualValue); } /// <summary> /// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the /// current <see cref="byte"/>. /// </summary> public static NumericAssertions<byte> Should(this byte actualValue) { return new NumericAssertions<byte>(actualValue); } /// <summary> /// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the /// current nullable <see cref="byte"/>. /// </summary> public static NullableNumericAssertions<byte> Should(this byte? actualValue) { return new NullableNumericAssertions<byte>(actualValue); } /// <summary> /// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the /// current <see cref="short"/>. /// </summary> public static NumericAssertions<short> Should(this short actualValue) { return new NumericAssertions<short>(actualValue); } /// <summary> /// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the /// current nullable <see cref="short"/>. /// </summary> public static NullableNumericAssertions<short> Should(this short? actualValue) { return new NullableNumericAssertions<short>(actualValue); } /// <summary> /// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the /// current <see cref="long"/>. /// </summary> public static NumericAssertions<long> Should(this long actualValue) { return new NumericAssertions<long>(actualValue); } /// <summary> /// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the /// current nullable <see cref="long"/>. /// </summary> public static NullableNumericAssertions<long> Should(this long? actualValue) { return new NullableNumericAssertions<long>(actualValue); } /// <summary> /// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the /// current <see cref="float"/>. /// </summary> public static NumericAssertions<float> Should(this float actualValue) { return new NumericAssertions<float>(actualValue); } /// <summary> /// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the /// current nullable <see cref="float"/>. /// </summary> public static NullableNumericAssertions<float> Should(this float? actualValue) { return new NullableNumericAssertions<float>(actualValue); } /// <summary> /// Returns an <see cref="NumericAssertions{T}"/> object that can be used to assert the /// current <see cref="double"/>. /// </summary> public static NumericAssertions<double> Should(this double actualValue) { return new NumericAssertions<double>(actualValue); } /// <summary> /// Returns an <see cref="NullableNumericAssertions{T}"/> object that can be used to assert the /// current nullable <see cref="double"/>. /// </summary> public static NullableNumericAssertions<double> Should(this double? actualValue) { return new NullableNumericAssertions<double>(actualValue); } /// <summary> /// Returns an <see cref="StringAssertions"/> object that can be used to assert the /// current <see cref="string"/>. /// </summary> public static StringAssertions Should(this string actualValue) { return new StringAssertions(actualValue); } /// <summary> /// Returns an <see cref="SimpleTimeSpanAssertions"/> object that can be used to assert the /// current <see cref="TimeSpan"/>. /// </summary> public static SimpleTimeSpanAssertions Should(this TimeSpan actualValue) { return new SimpleTimeSpanAssertions(actualValue); } /// <summary> /// Returns an <see cref="NullableSimpleTimeSpanAssertions"/> object that can be used to assert the /// current nullable <see cref="TimeSpan"/>. /// </summary> public static NullableSimpleTimeSpanAssertions Should(this TimeSpan? actualValue) { return new NullableSimpleTimeSpanAssertions(actualValue); } /// <summary> /// Returns a <see cref="TypeAssertions"/> object that can be used to assert the /// current <see cref="System.Type"/>. /// </summary> public static TypeAssertions Should(this Type subject) { return new TypeAssertions(subject); } /// <summary> /// Returns a <see cref="TypeAssertions"/> object that can be used to assert the /// current <see cref="System.Type"/>. /// </summary> public static TypeSelectorAssertions Should(this TypeSelector typeSelector) { return new TypeSelectorAssertions(typeSelector.ToArray()); } /// <summary> /// Returns a <see cref="MethodInfoAssertions"/> object that can be used to assert the current <see cref="MethodInfo"/>. /// </summary> /// <seealso cref="TypeAssertions"/> public static MethodInfoAssertions Should(this MethodInfo methodInfo) { return new MethodInfoAssertions(methodInfo); } /// <summary> /// Returns a <see cref="MethodInfoSelectorAssertions"/> object that can be used to assert the methods returned by the /// current <see cref="MethodInfoSelector"/>. /// </summary> /// <seealso cref="TypeAssertions"/> public static MethodInfoSelectorAssertions Should(this MethodInfoSelector methodSelector) { return new MethodInfoSelectorAssertions(methodSelector.ToArray()); } /// <summary> /// Returns a <see cref="PropertyInfoAssertions"/> object that can be used to assert the /// current <see cref="PropertyInfoSelector"/>. /// </summary> /// <seealso cref="TypeAssertions"/> public static PropertyInfoAssertions Should(this PropertyInfo propertyInfo) { return new PropertyInfoAssertions(propertyInfo); } /// <summary> /// Returns a <see cref="PropertyInfoAssertions"/> object that can be used to assert the properties returned by the /// current <see cref="PropertyInfoSelector"/>. /// </summary> /// <seealso cref="TypeAssertions"/> public static PropertyInfoSelectorAssertions Should(this PropertyInfoSelector propertyInfoSelector) { return new PropertyInfoSelectorAssertions(propertyInfoSelector.ToArray()); } /// <summary> /// Asserts that an object is equivalent to another object. /// </summary> /// <remarks> /// Objects are equivalent when both object graphs have equally named properties with the same value, /// irrespective of the type of those objects. Two properties are also equal if one type can be converted to another and the result is equal. /// The type of a collection property is ignored as long as the collection implements <see cref="IEnumerable"/> and all /// items in the collection are structurally equal. /// Notice that actual behavior is determined by the <see cref="EquivalencyAssertionOptions.Default"/> instance of the /// <see cref="EquivalencyAssertionOptions"/> class. /// </remarks> /// <param name="because"> /// An optional formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the /// assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="becauseArgs"> /// Zero or more objects to format using the placeholders in <see cref="because" />. /// </param> public static void ShouldBeEquivalentTo<T>(this T subject, object expectation, string because = "", params object[] becauseArgs) { ShouldBeEquivalentTo(subject, expectation, config => config, because, becauseArgs); } /// <summary> /// Asserts that an object is equivalent to another object. /// </summary> /// <remarks> /// Objects are equivalent when both object graphs have equally named properties with the same value, /// irrespective of the type of those objects. Two properties are also equal if one type can be converted to another and the result is equal. /// The type of a collection property is ignored as long as the collection implements <see cref="IEnumerable"/> and all /// items in the collection are structurally equal. /// </remarks> /// <param name="config"> /// A reference to the <see cref="EquivalencyAssertionOptions.Default"/> configuration object that can be used /// to influence the way the object graphs are compared. You can also provide an alternative instance of the /// <see cref="EquivalencyAssertionOptions"/> class. /// </param> /// <param name="because"> /// An optional formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the /// assertion is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically. /// </param> /// <param name="becauseArgs"> /// Zero or more objects to format using the placeholders in <see cref="because" />. /// </param> public static void ShouldBeEquivalentTo<T>(this T subject, object expectation, Func<EquivalencyAssertionOptions<T>, EquivalencyAssertionOptions<T>> config, string because = "", params object[] becauseArgs) { IEquivalencyAssertionOptions options = config(AssertionOptions.CloneDefaults<T>()); var context = new EquivalencyValidationContext { Subject = subject, Expectation = expectation, CompileTimeType = typeof(T), Because = because, BecauseArgs = becauseArgs, Tracer = options.TraceWriter }; new EquivalencyValidator(options).AssertEquality(context); } public static void ShouldAllBeEquivalentTo<T>(this IEnumerable<T> subject, IEnumerable expectation, string because = "", params object[] becauseArgs) { ShouldAllBeEquivalentTo(subject, expectation, config => config, because, becauseArgs); } public static void ShouldAllBeEquivalentTo<T>(this IEnumerable<T> subject, IEnumerable expectation, Func<EquivalencyAssertionOptions<T>, EquivalencyAssertionOptions<T>> config, string because = "", params object[] becauseArgs) { IEquivalencyAssertionOptions options = config(AssertionOptions.CloneDefaults<T>()); var context = new EquivalencyValidationContext { Subject = subject, Expectation = expectation, CompileTimeType = typeof(T), Because = because, BecauseArgs = becauseArgs, Tracer = options.TraceWriter }; new EquivalencyValidator(options).AssertEquality(context); } /// <summary> /// Safely casts the specified object to the type specified through <typeparamref name="TTo"/>. /// </summary> /// <remarks> /// Has been introduced to allow casting objects without breaking the fluent API. /// </remarks> /// <typeparam name="TTo"></typeparam> public static TTo As<TTo>(this object subject) { return subject is TTo ? (TTo)subject : default(TTo); } } }
SaroTasciyan/FluentAssertions
Src/Core/InternalAssertionExtensions.cs
C#
apache-2.0
19,975
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.accumulo.shell.commands; import java.util.Map.Entry; import org.apache.accumulo.core.data.constraints.Constraint; import org.apache.accumulo.shell.Shell; import org.apache.accumulo.shell.Shell.Command; import org.apache.accumulo.shell.ShellCommandException; import org.apache.accumulo.shell.ShellCommandException.ErrorCode; import org.apache.accumulo.shell.ShellOptions; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionGroup; import org.apache.commons.cli.Options; public class ConstraintCommand extends Command { protected Option namespaceOpt; @Override public int execute(final String fullCommand, final CommandLine cl, final Shell shellState) throws Exception { final String tableName; final String namespace; if (cl.hasOption(namespaceOpt.getOpt())) { namespace = cl.getOptionValue(namespaceOpt.getOpt()); } else { namespace = null; } if (cl.hasOption(OptUtil.tableOpt().getOpt()) || !shellState.getTableName().isEmpty()) { tableName = OptUtil.getTableOpt(cl, shellState); } else { tableName = null; } int i; switch (OptUtil.getAldOpt(cl)) { case ADD: for (String constraint : cl.getArgs()) { if (namespace != null) { if (!shellState.getAccumuloClient().namespaceOperations().testClassLoad(namespace, constraint, Constraint.class.getName())) { throw new ShellCommandException(ErrorCode.INITIALIZATION_FAILURE, "Servers are unable to load " + constraint + " as type " + Constraint.class.getName()); } i = shellState.getAccumuloClient().namespaceOperations().addConstraint(namespace, constraint); shellState.getWriter().println("Added constraint " + constraint + " to namespace " + namespace + " with number " + i); } else if (tableName != null && !tableName.isEmpty()) { if (!shellState.getAccumuloClient().tableOperations().testClassLoad(tableName, constraint, Constraint.class.getName())) { throw new ShellCommandException(ErrorCode.INITIALIZATION_FAILURE, "Servers are unable to load " + constraint + " as type " + Constraint.class.getName()); } i = shellState.getAccumuloClient().tableOperations().addConstraint(tableName, constraint); shellState.getWriter().println( "Added constraint " + constraint + " to table " + tableName + " with number " + i); } else { throw new IllegalArgumentException("Please specify either a table or a namespace"); } } break; case DELETE: for (String constraint : cl.getArgs()) { i = Integer.parseInt(constraint); if (namespace != null) { shellState.getAccumuloClient().namespaceOperations().removeConstraint(namespace, i); shellState.getWriter() .println("Removed constraint " + i + " from namespace " + namespace); } else if (tableName != null) { shellState.getAccumuloClient().tableOperations().removeConstraint(tableName, i); shellState.getWriter().println("Removed constraint " + i + " from table " + tableName); } else { throw new IllegalArgumentException("Please specify either a table or a namespace"); } } break; case LIST: if (namespace != null) { for (Entry<String,Integer> property : shellState.getAccumuloClient().namespaceOperations() .listConstraints(namespace).entrySet()) { shellState.getWriter().println(property.toString()); } } else if (tableName != null) { for (Entry<String,Integer> property : shellState.getAccumuloClient().tableOperations() .listConstraints(tableName).entrySet()) { shellState.getWriter().println(property.toString()); } } else { throw new IllegalArgumentException("Please specify either a table or a namespace"); } } return 0; } @Override public String description() { return "adds, deletes, or lists constraints for a table"; } @Override public int numArgs() { return Shell.NO_FIXED_ARG_LENGTH_CHECK; } @Override public String usage() { return getName() + " <constraint>{ <constraint>}"; } @Override public Options getOptions() { final Options o = new Options(); o.addOptionGroup(OptUtil.addListDeleteGroup("constraint")); OptionGroup grp = new OptionGroup(); grp.addOption(OptUtil.tableOpt("table to add, delete, or list constraints for")); namespaceOpt = new Option(ShellOptions.namespaceOption, "namespace", true, "name of a namespace to operate on"); namespaceOpt.setArgName("namespace"); grp.addOption(namespaceOpt); o.addOptionGroup(grp); return o; } }
milleruntime/accumulo
shell/src/main/java/org/apache/accumulo/shell/commands/ConstraintCommand.java
Java
apache-2.0
5,893