repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
lask/esp-iot-solution
components/i2c_devices/sensor/apds9960/apds9960.c
<filename>components/i2c_devices/sensor/apds9960/apds9960.c // Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <stdio.h> #include "driver/i2c.h" #include "iot_apds9960.h" #define APDS9960_TIMEOUT_MS_DEFAULT (1000) typedef struct { i2c_bus_handle_t bus; uint16_t dev_addr; uint32_t timeout; apds9960_control_t _control_t; /*< config control register>*/ apds9960_enable_t _enable_t; /*< config enable register>*/ apds9960_config1_t _config1_t; /*< config config1 register>*/ apds9960_config2_t _config2_t; /*< config config2 register>*/ apds9960_config3_t _config3_t; /*< config config3 register>*/ apds9960_gconf1_t _gconf1_t; /*< config gconfig1 register>*/ apds9960_gconf2_t _gconf2_t; /*< config gconfig2 register>*/ apds9960_gconf3_t _gconf3_t; /*< config gconfig3 register>*/ apds9960_gconf4_t _gconf4_t; /*< config gconfig4 register>*/ apds9960_status_t _status_t; /*< config status register>*/ apds9960_gstatus_t _gstatus_t; /*< config gstatus register>*/ apds9960_propulse_t _ppulse_t; /*< config pro pulse register>*/ apds9960_gespulse_t _gpulse_t; /*< config ges pulse register>*/ apds9960_pers_t _pers_t; /*< config pers register>*/ uint8_t gest_cnt; /*< counter of gesture >*/ uint8_t up_cnt; /*< counter of up gesture >*/ uint8_t down_cnt; /*< counter of down gesture >*/ uint8_t left_cnt; /*< counter of left gesture >*/ uint8_t right_cnt; /*< counter of right gesture >*/ } apds9960_dev_t; static float __powf(const float x, const float y) { return (float) (pow((double) x, (double) y)); } uint8_t iot_apds9960_get_enable(apds9960_handle_t sensor) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; return (sens->_enable_t.gen << 6) | (sens->_enable_t.pien << 5) | (sens->_enable_t.aien << 4) | (sens->_enable_t.wen << 3) | (sens->_enable_t.pen << 2) | (sens->_enable_t.aen << 1) | sens->_enable_t.pon; } uint8_t iot_apds9960_get_pers(apds9960_handle_t sensor) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; return (sens->_pers_t.ppers << 4) | sens->_pers_t.apers; } uint8_t iot_apds9960_get_ppulse(apds9960_handle_t sensor) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; return (sens->_ppulse_t.pplen << 6) | sens->_ppulse_t.ppulse; } uint8_t iot_apds9960_get_gpulse(apds9960_handle_t sensor) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; return (sens->_gpulse_t.gplen << 6) | sens->_gpulse_t.gpulse; } uint8_t iot_apds9960_get_control(apds9960_handle_t sensor) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; return (sens->_control_t.leddrive << 6) | (sens->_control_t.pgain << 2) | sens->_control_t.again; } uint8_t iot_apds9960_get_config1(apds9960_handle_t sensor) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; return sens->_config1_t.wlong << 1; } uint8_t iot_apds9960_get_config2(apds9960_handle_t sensor) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; return (sens->_config2_t.psien << 7) | (sens->_config2_t.cpsien << 6) | (sens->_config2_t.led_boost << 4) | 1; } uint8_t iot_apds9960_get_config3(apds9960_handle_t sensor) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; return (sens->_config3_t.pcmp << 5) | (sens->_config3_t.sai << 4) | (sens->_config3_t.pmask_u << 3) | (sens->_config3_t.pmask_d << 2) | (sens->_config3_t.pmask_l << 1) | sens->_config3_t.pmask_r; } void iot_apds9960_set_status(apds9960_handle_t sensor, uint8_t data) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; sens->_status_t.avalid = data & 0x01; sens->_status_t.pvalid = (data >> 1) & 0x01; sens->_status_t.gint = (data >> 2) & 0x01; sens->_status_t.aint = (data >> 4) & 0x01; sens->_status_t.pint = (data >> 5) & 0x01; sens->_status_t.pgsat = (data >> 6) & 0x01; sens->_status_t.cpsat = (data >> 7) & 0x01; } void iot_apds9960_set_gstatus(apds9960_handle_t sensor, uint8_t data) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; sens->_gstatus_t.gfov = (data >> 1) & 0x01; sens->_gstatus_t.gvalid = data & 0x01; } uint8_t iot_apds9960_get_gconf1(apds9960_handle_t sensor) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; return (sens->_gconf1_t.gfifoth << 7) | (sens->_gconf1_t.gexmsk << 5) | sens->_gconf1_t.gexpers; } uint8_t iot_apds9960_get_gconf2(apds9960_handle_t sensor) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; return (sens->_gconf2_t.ggain << 5) | (sens->_gconf2_t.gldrive << 3) | sens->_gconf2_t.gwtime; } uint8_t iot_apds9960_get_gconf3(apds9960_handle_t sensor) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; return sens->_gconf3_t.gdims; } uint8_t iot_apds9960_get_gconf4(apds9960_handle_t sensor) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; return (sens->_gconf4_t.gien << 1) | sens->_gconf4_t.gmode; } void iot_apds9960_set_gconf4(apds9960_handle_t sensor, uint8_t data) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; sens->_gconf4_t.gien = (data >> 1) & 0x01; sens->_gconf4_t.gmode = data & 0x01; } void iot_apds9960_reset_counts(apds9960_handle_t sensor) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; sens->gest_cnt = 0; sens->up_cnt = 0; sens->down_cnt = 0; sens->left_cnt = 0; sens->right_cnt = 0; } esp_err_t iot_apds9960_write_byte(apds9960_handle_t sensor, uint8_t reg_addr, uint8_t data) { return iot_apds9960_write(sensor, reg_addr, &data, 1); } esp_err_t iot_apds9960_write(apds9960_handle_t sensor, uint8_t addr, uint8_t *buf, uint8_t len) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; esp_err_t ret; i2c_cmd_handle_t cmd = i2c_cmd_link_create(); i2c_master_start(cmd); i2c_master_write_byte(cmd, (sens->dev_addr << 1) | WRITE_BIT, ACK_CHECK_EN); i2c_master_write_byte(cmd, addr, ACK_CHECK_EN); i2c_master_write(cmd, buf, len, ACK_CHECK_EN); ret = iot_i2c_bus_cmd_begin(sens->bus, cmd, sens->timeout / portTICK_RATE_MS); i2c_cmd_link_delete(cmd); return ret; } esp_err_t iot_apds9960_set_timeout(apds9960_handle_t sensor, uint32_t tout_ms) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; sens->timeout = tout_ms; return ESP_OK; } esp_err_t iot_apds9960_read_byte(apds9960_handle_t sensor, uint8_t reg, uint8_t *data) { return iot_apds9960_read(sensor, reg, data, 1); } esp_err_t iot_apds9960_read(apds9960_handle_t sensor, uint8_t reg_addr, uint8_t *buf, uint8_t len) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; esp_err_t ret; i2c_cmd_handle_t cmd = i2c_cmd_link_create(); i2c_master_start(cmd); i2c_master_write_byte(cmd, (sens->dev_addr << 1) | WRITE_BIT, ACK_CHECK_EN); i2c_master_write_byte(cmd, reg_addr, ACK_CHECK_EN); i2c_master_stop(cmd); ret = iot_i2c_bus_cmd_begin(sens->bus, cmd, sens->timeout / portTICK_RATE_MS); i2c_cmd_link_delete(cmd); if (ret == ESP_FAIL) { return ret; } cmd = i2c_cmd_link_create(); i2c_master_start(cmd); i2c_master_write_byte(cmd, (sens->dev_addr << 1) | READ_BIT, ACK_CHECK_EN); if (len > 1) { i2c_master_read(cmd, buf, len - 1, ACK_VAL); i2c_master_read_byte(cmd, buf + len - 1, NACK_VAL); } else { i2c_master_read_byte(cmd, buf, NACK_VAL); } i2c_master_stop(cmd); ret = iot_i2c_bus_cmd_begin(sens->bus, cmd, sens->timeout / portTICK_RATE_MS); i2c_cmd_link_delete(cmd); return ret; } esp_err_t iot_apds9960_get_deviceid(apds9960_handle_t sensor, uint8_t* deviceid) { esp_err_t ret; uint8_t tmp; ret = iot_apds9960_read_byte(sensor, APDS9960_WHO_AM_I_REG, &tmp); *deviceid = tmp; return ret; } esp_err_t iot_apds9960_set_mode(apds9960_handle_t sensor, apds9960_mode_t mode) { uint8_t tmp; if (iot_apds9960_read_byte(sensor, APDS9960_MODE_ENABLE, &tmp) == ESP_FAIL) { return ESP_FAIL; } tmp |= mode; return iot_apds9960_write_byte(sensor, APDS9960_MODE_ENABLE, tmp); } apds9960_mode_t iot_apds9960_get_mode(apds9960_handle_t sensor) { uint8_t value; /* Read current ENABLE register */ if (iot_apds9960_read_byte(sensor, APDS9960_MODE_ENABLE, &value) == ESP_FAIL) { return ESP_FAIL; } return (apds9960_mode_t) value; } esp_err_t iot_apds9960_enable_gesture_engine(apds9960_handle_t sensor, bool en) { esp_err_t ret; apds9960_dev_t* sens = (apds9960_dev_t*) sensor; if (!en) { sens->_gconf4_t.gmode = 0; if (iot_apds9960_write_byte(sensor, APDS9960_GCONF4, (sens->_gconf4_t.gien << 1) | sens->_gconf4_t.gmode) == ESP_FAIL) { return ESP_FAIL; } } sens->_enable_t.gen = en; ret = iot_apds9960_write_byte(sensor, APDS9960_MODE_ENABLE, (sens->_enable_t.gen << 6) | (sens->_enable_t.pien << 5) | (sens->_enable_t.aien << 4) | (sens->_enable_t.wen << 3) | (sens->_enable_t.pen << 2) | (sens->_enable_t.aen << 1) | sens->_enable_t.pon); iot_apds9960_reset_counts(sensor); return ret; } esp_err_t iot_apds9960_set_led_drive_boost(apds9960_handle_t sensor, apds9960_leddrive_t drive, apds9960_ledboost_t boost) { // set BOOST apds9960_dev_t* sens = (apds9960_dev_t*) sensor; sens->_config2_t.led_boost = boost; if (iot_apds9960_write_byte(sensor, APDS9960_CONFIG2, (sens->_config2_t.psien << 7) | (sens->_config2_t.cpsien << 6) | (sens->_config2_t.led_boost << 4) | 1) == ESP_FAIL) { return ESP_FAIL; } sens->_control_t.leddrive = drive; return iot_apds9960_write_byte(sensor, APDS9960_CONTROL, ((sens->_control_t.leddrive << 6) | (sens->_control_t.pgain << 2) | sens->_control_t.again)); } esp_err_t iot_apds9960_set_wait_time(apds9960_handle_t sensor, uint8_t time) { return iot_apds9960_write_byte(sensor, APDS9960_WTIME, time); } esp_err_t iot_apds9960_set_adc_integration_time(apds9960_handle_t sensor, uint16_t iTimeMS) { float temp; // convert ms into 2.78ms increments temp = iTimeMS; temp /= 2.78; temp = 256 - temp; if (temp > 255) { temp = 255; } else if (temp < 0) { temp = 0; } /* Update the timing register */ return iot_apds9960_write_byte(sensor, APDS9960_ATIME, (uint8_t) temp); } float iot_apds9960_get_adc_integration_time(apds9960_handle_t sensor) { float temp; uint8_t val; if (iot_apds9960_read_byte(sensor, APDS9960_ATIME, &val) == ESP_FAIL) { return ESP_FAIL; } temp = val; // convert to units of 2.78 ms temp = 256 - temp; temp *= 2.78; return temp; } esp_err_t iot_apds9960_set_ambient_light_gain(apds9960_handle_t sensor, apds9960_again_t again) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; sens->_control_t.again = again; /* Update the timing register */ return iot_apds9960_write_byte(sensor, APDS9960_CONTROL, ((sens->_control_t.leddrive << 6) | (sens->_control_t.pgain << 2) | sens->_control_t.again)); } apds9960_again_t iot_apds9960_get_ambient_light_gain(apds9960_handle_t sensor) { uint8_t val; if (iot_apds9960_read_byte(sensor, APDS9960_CONTROL, &val) == ESP_FAIL) { return ESP_FAIL; } return (apds9960_again_t) (val & 0x03); } esp_err_t iot_apds9960_enable_gesture_interrupt(apds9960_handle_t sensor, bool en) { esp_err_t ret; apds9960_dev_t* sens = (apds9960_dev_t*) sensor; sens->_enable_t.gen = en; ret = iot_apds9960_write_byte(sensor, APDS9960_MODE_ENABLE, ((sens->_enable_t.gen << 6) | (sens->_enable_t.pien << 5) | (sens->_enable_t.aien << 4) | (sens->_enable_t.wen << 3) | (sens->_enable_t.pen << 2) | (sens->_enable_t.aen << 1) | sens->_enable_t.pon)); iot_apds9960_clear_interrupt(sensor); return ret; } esp_err_t iot_apds9960_enable_proximity_engine(apds9960_handle_t sensor, bool en) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; sens->_enable_t.pen = en; return iot_apds9960_write_byte(sensor, APDS9960_MODE_ENABLE, ((sens->_enable_t.gen << 6) | (sens->_enable_t.pien << 5) | (sens->_enable_t.aien << 4) | (sens->_enable_t.wen << 3) | (sens->_enable_t.pen << 2) | (sens->_enable_t.aen << 1) | sens->_enable_t.pon)); } esp_err_t iot_apds9960_set_proximity_gain(apds9960_handle_t sensor, apds9960_pgain_t pgain) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; sens->_control_t.pgain = pgain; /* Update the timing register */ return iot_apds9960_write_byte(sensor, APDS9960_CONTROL, (sens->_control_t.leddrive << 6) | (sens->_control_t.pgain << 2) | sens->_control_t.again); } apds9960_pgain_t iot_apds9960_get_proximity_gain(apds9960_handle_t sensor) { uint8_t val; if (iot_apds9960_read_byte(sensor, APDS9960_CONTROL, &val) == ESP_FAIL) { return ESP_FAIL; } return (apds9960_pgain_t) (val & 0x0C); } esp_err_t iot_apds9960_set_proximity_pulse(apds9960_handle_t sensor, apds9960_ppulse_len_t pLen, uint8_t pulses) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; if (pulses < 1) { pulses = 1; } else if (pulses > 64) { pulses = 64; } pulses--; sens->_ppulse_t.pplen = pLen; sens->_ppulse_t.ppulse = pulses; return iot_apds9960_write_byte(sensor, APDS9960_PPULSE, (sens->_ppulse_t.pplen << 6) | sens->_ppulse_t.ppulse); } esp_err_t iot_apds9960_enable_color_engine(apds9960_handle_t sensor, bool en) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; sens->_enable_t.aen = en; return iot_apds9960_write_byte(sensor, APDS9960_MODE_ENABLE, ((sens->_enable_t.gen << 6) | (sens->_enable_t.pien << 5) | (sens->_enable_t.aien << 4) | (sens->_enable_t.wen << 3) | (sens->_enable_t.pen << 2) | (sens->_enable_t.aen << 1) | sens->_enable_t.pon)); } bool iot_apds9960_color_data_ready(apds9960_handle_t sensor) { uint8_t data; apds9960_dev_t* sens = (apds9960_dev_t*) sensor; iot_apds9960_read_byte(sensor, APDS9960_STATUS, &data); iot_apds9960_set_status(sensor, data); return sens->_status_t.avalid; } esp_err_t iot_apds9960_get_color_data(apds9960_handle_t sensor, uint16_t *r, uint16_t *g, uint16_t *b, uint16_t *c) { uint8_t data[2] = { 0 }; iot_apds9960_read(sensor, APDS9960_CDATAL, data, 2); *c = (data[0] << 8) | data[1]; iot_apds9960_read(sensor, APDS9960_RDATAL, data, 2); *r = (data[0] << 8) | data[1]; iot_apds9960_read(sensor, APDS9960_GDATAL, data, 2); *g = (data[0] << 8) | data[1]; iot_apds9960_read(sensor, APDS9960_BDATAL, data, 2); *b = (data[0] << 8) | data[1]; return ESP_OK; } uint16_t iot_apds9960_calculate_color_temperature(apds9960_handle_t sensor, uint16_t r, uint16_t g, uint16_t b) { float rgb_xcorrelation, rgb_ycorrelation, rgb_zcorrelation; /* RGB to XYZ correlation */ float chromaticity_xc, chromaticity_yc; /* Chromaticity co-ordinates */ float formula; /* McCamy's formula */ float cct; /* 1. Map RGB values to their XYZ counterparts. */ /* Based on 6500K fluorescent, 3000K fluorescent */ /* and 60W incandescent values for a wide range. */ /* Note: Y = Illuminance or lux */ rgb_xcorrelation = (-0.14282F * r) + (1.54924F * g) + (-0.95641F * b); rgb_ycorrelation = (-0.32466F * r) + (1.57837F * g) + (-0.73191F * b); rgb_zcorrelation = (-0.68202F * r) + (0.77073F * g) + (0.56332F * b); /* 2. Calculate the chromaticity co-ordinates */ chromaticity_xc = (rgb_xcorrelation) / (rgb_xcorrelation); chromaticity_yc = (rgb_ycorrelation) / (rgb_xcorrelation + rgb_ycorrelation + rgb_zcorrelation); /* 3. Use McCamy's formula to determine the CCT */ formula = (chromaticity_xc - 0.3320F) / (0.1858F - chromaticity_yc); /* Calculate the final CCT */ cct = (449.0F * __powf(formula, 3)) + (3525.0F * __powf(formula, 2)) + (6823.3F * formula) + 5520.33F; /* Return the results in degrees Kelvin */ return (uint16_t) cct; } uint16_t iot_apds9960_calculate_lux(apds9960_handle_t sensor, uint16_t r, uint16_t g, uint16_t b) { float illuminance; /* This only uses RGB ... how can we integrate clear or calculate lux */ /* based exclusively on clear since this might be more reliable? */ illuminance = (-0.32466F * r) + (1.57837F * g) + (-0.73191F * b); return (uint16_t) illuminance; } esp_err_t iot_apds9960_enable_color_interrupt(apds9960_handle_t sensor, bool en) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; sens->_enable_t.aien = en; return iot_apds9960_write_byte(sensor, APDS9960_MODE_ENABLE, ((sens->_enable_t.gen << 6) | (sens->_enable_t.pien << 5) | (sens->_enable_t.aien << 4) | (sens->_enable_t.wen << 3) | (sens->_enable_t.pen << 2) | (sens->_enable_t.aen << 1) | sens->_enable_t.pon)); } esp_err_t iot_apds9960_set_int_limits(apds9960_handle_t sensor, uint16_t low, uint16_t high) { iot_apds9960_write_byte(sensor, APDS9960_AILTL, low & 0xFF); iot_apds9960_write_byte(sensor, APDS9960_AILTH, low >> 8); iot_apds9960_write_byte(sensor, APDS9960_AIHTL, high & 0xFF); return iot_apds9960_write_byte(sensor, APDS9960_AIHTH, high >> 8); } esp_err_t iot_apds9960_enable_proximity_interrupt(apds9960_handle_t sensor, bool en) { esp_err_t ret; apds9960_dev_t* sens = (apds9960_dev_t*) sensor; sens->_enable_t.pien = en; ret = iot_apds9960_write_byte(sensor, APDS9960_MODE_ENABLE, ((sens->_enable_t.gen << 6) | (sens->_enable_t.pien << 5) | (sens->_enable_t.aien << 4) | (sens->_enable_t.wen << 3) | (sens->_enable_t.pen << 2) | (sens->_enable_t.aen << 1) | sens->_enable_t.pon)); iot_apds9960_clear_interrupt(sensor); return ret; } uint8_t iot_apds9960_read_proximity(apds9960_handle_t sensor) { uint8_t data; if (iot_apds9960_read_byte(sensor, APDS9960_PDATA, &data)) { return ESP_FAIL; } return data; } esp_err_t iot_apds9960_set_proximity_interrupt_threshold(apds9960_handle_t sensor, uint8_t low, uint8_t high, uint8_t persistance) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; iot_apds9960_write_byte(sensor, APDS9960_PILT, low); iot_apds9960_write_byte(sensor, APDS9960_PIHT, high); if (persistance > 7) { persistance = 7; } sens->_pers_t.ppers = persistance; return iot_apds9960_write_byte(sensor, APDS9960_PERS, (sens->_pers_t.ppers << 4) | sens->_pers_t.apers); } bool iot_apds9960_get_proximity_interrupt(apds9960_handle_t sensor) { uint8_t data; apds9960_dev_t* sens = (apds9960_dev_t*) sensor; iot_apds9960_read_byte(sensor, APDS9960_STATUS, &data); iot_apds9960_set_status(sensor, data); return sens->_status_t.pint; } esp_err_t iot_apds9960_clear_interrupt(apds9960_handle_t sensor) { esp_err_t ret = 0; apds9960_dev_t* sens = (apds9960_dev_t*) sensor; i2c_cmd_handle_t cmd = i2c_cmd_link_create(); i2c_master_start(cmd); i2c_master_write_byte(cmd, (sens->dev_addr << 1) | WRITE_BIT, ACK_CHECK_EN); i2c_master_write_byte(cmd, APDS9960_AICLEAR, ACK_CHECK_EN); ret = iot_i2c_bus_cmd_begin(sens->bus, cmd, sens->timeout / portTICK_RATE_MS); i2c_cmd_link_delete(cmd); return ret; } esp_err_t iot_apds9960_enable(apds9960_handle_t sensor, bool en) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; sens->_enable_t.pon = en; return iot_apds9960_write_byte(sensor, APDS9960_MODE_ENABLE, ((sens->_enable_t.gen << 6) | (sens->_enable_t.pien << 5) | (sens->_enable_t.aien << 4) | (sens->_enable_t.wen << 3) | (sens->_enable_t.pen << 2) | (sens->_enable_t.aen << 1) | sens->_enable_t.pon)); } esp_err_t iot_apds9960_set_gesture_dimensions(apds9960_handle_t sensor, uint8_t dims) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; sens->_gconf3_t.gdims = dims; return iot_apds9960_write_byte(sensor, APDS9960_GCONF3, sens->_gconf3_t.gdims); } esp_err_t iot_apds9960_set_light_intlow_threshold(apds9960_handle_t sensor, uint16_t threshold) { uint8_t val_low; uint8_t val_high; /* Break 16-bit threshold into 2 8-bit values */ val_low = threshold & 0x00FF; val_high = (threshold & 0xFF00) >> 8; /* Write low byte */ if (iot_apds9960_write_byte(sensor, APDS9960_AILTL, val_low) == ESP_FAIL) { return ESP_FAIL; } /* Write high byte */ return iot_apds9960_write_byte(sensor, APDS9960_AILTH, val_high); } esp_err_t iot_apds9960_set_light_inthigh_threshold(apds9960_handle_t sensor, uint16_t threshold) { uint8_t val_low; uint8_t val_high; /* Break 16-bit threshold into 2 8-bit values */ val_low = threshold & 0x00FF; val_high = (threshold & 0xFF00) >> 8; /* Write low byte */ if (iot_apds9960_write_byte(sensor, APDS9960_AIHTL, val_low) == ESP_FAIL) { return ESP_FAIL; } /* Write high byte */ return iot_apds9960_write_byte(sensor, APDS9960_AIHTH, val_high); } esp_err_t iot_apds9960_set_gesture_fifo_threshold(apds9960_handle_t sensor, uint8_t thresh) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; sens->_gconf1_t.gfifoth = thresh; return iot_apds9960_write_byte(sensor, APDS9960_GCONF1, ((sens->_gconf1_t.gfifoth << 7) | (sens->_gconf1_t.gexmsk << 5) | sens->_gconf1_t.gexpers)); } esp_err_t iot_apds9960_set_gesture_waittime(apds9960_handle_t sensor, apds9960_gwtime_t time) { uint8_t val; /* Read value from GCONF2 register */ if (iot_apds9960_read_byte(sensor, APDS9960_GCONF2, &val) == ESP_FAIL) { return ESP_FAIL; } /* Set bits in register to given value */ time &= 0x07; val &= 0xf8; val |= time; /* Write register value back into GCONF2 register */ return iot_apds9960_write_byte(sensor, APDS9960_GCONF2, val); } esp_err_t iot_apds9960_set_gesture_gain(apds9960_handle_t sensor, apds9960_ggain_t gain) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; sens->_gconf2_t.ggain = gain; return iot_apds9960_write_byte(sensor, APDS9960_GCONF2, ((sens->_gconf2_t.ggain << 5) | (sens->_gconf2_t.gldrive << 3) | sens->_gconf2_t.gwtime)); } esp_err_t iot_apds9960_set_gesture_proximity_threshold(apds9960_handle_t sensor, uint8_t entthresh, uint8_t exitthresh) { esp_err_t ret; if (iot_apds9960_write_byte(sensor, APDS9960_GPENTH, entthresh)) { return ESP_FAIL; } ret = iot_apds9960_write_byte(sensor, APDS9960_GEXTH, exitthresh); return ret; } esp_err_t iot_apds9960_set_gesture_offset(apds9960_handle_t sensor, uint8_t offset_up, uint8_t offset_down, uint8_t offset_left, uint8_t offset_right) { iot_apds9960_write_byte(sensor, APDS9960_GOFFSET_U, offset_up); iot_apds9960_write_byte(sensor, APDS9960_GOFFSET_D, offset_down); iot_apds9960_write_byte(sensor, APDS9960_GOFFSET_L, offset_left); iot_apds9960_write_byte(sensor, APDS9960_GOFFSET_R, offset_right); return ESP_OK; } uint8_t iot_apds9960_read_gesture(apds9960_handle_t sensor) { uint8_t toRead, bytesRead; uint8_t buf[256]; unsigned long t = 0; uint8_t gestureReceived; apds9960_dev_t* sens = (apds9960_dev_t*) sensor; while (1) { int up_down_diff = 0; int left_right_diff = 0; gestureReceived = 0; if (!iot_apds9960_gesture_valid(sensor)) { return 0; } vTaskDelay(30 / portTICK_RATE_MS); iot_apds9960_read_byte(sensor, APDS9960_GFLVL, &toRead); iot_apds9960_read(sensor, APDS9960_GFIFO_U, buf, toRead); bytesRead = toRead; for (int i = 0; i < (bytesRead >> 2); i++) { if (abs((int) buf[0] - (int) buf[1]) > 13) { up_down_diff += (int) buf[0] - (int) buf[1]; } } for (int i = 0; i < (bytesRead >> 2); i++) { if (abs((int) buf[2] - (int) buf[3]) > 13) { left_right_diff += (int) buf[2] - (int) buf[3]; } } if (up_down_diff != 0) { if (up_down_diff < 0) { if (sens->down_cnt > 0) { gestureReceived = APDS9960_UP; } else { sens->up_cnt++; } } else if (up_down_diff > 0) { if (sens->up_cnt > 0) { gestureReceived = APDS9960_DOWN; } else { sens->down_cnt++; } } } if (left_right_diff != 0) { if (left_right_diff < 0) { if (sens->right_cnt > 0) { gestureReceived = APDS9960_LEFT; } else { sens->left_cnt++; } } else if (left_right_diff > 0) { if (sens->left_cnt > 0) { gestureReceived = APDS9960_RIGHT; } else { sens->right_cnt++; } } } if (up_down_diff != 0 || left_right_diff != 0) { t = xTaskGetTickCount(); } if (gestureReceived || xTaskGetTickCount() - t > (30000)) { iot_apds9960_reset_counts(sensor); return gestureReceived; } } } bool iot_apds9960_gesture_valid(apds9960_handle_t sensor) { uint8_t data; apds9960_dev_t* sens = (apds9960_dev_t*) sensor; iot_apds9960_read_byte(sensor, APDS9960_GSTATUS, &data); sens->_gstatus_t.gfov = (data >> 1) & 0x01; sens->_gstatus_t.gvalid = data & 0x01; return sens->_gstatus_t.gvalid; } esp_err_t iot_apds9960_set_gesture_pulse(apds9960_handle_t sensor, apds9960_gpulselen_t gpulseLen, uint8_t pulses) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; sens->_gpulse_t.gplen = gpulseLen; sens->_gpulse_t.gpulse = pulses; //10 pulses return iot_apds9960_write_byte(sensor, APDS9960_GPULSE, (sens->_gpulse_t.gplen << 6) | sens->_gpulse_t.gpulse); } esp_err_t iot_apds9960_set_gesture_enter_thresh(apds9960_handle_t sensor, uint8_t threshold) { esp_err_t ret; ret = iot_apds9960_write_byte(sensor, APDS9960_GPENTH, threshold); return ret; } esp_err_t iot_apds9960_set_gesture_exit_thresh(apds9960_handle_t sensor, uint8_t threshold) { esp_err_t ret; ret = iot_apds9960_write_byte(sensor, APDS9960_GEXTH, threshold); return ret; } apds9960_handle_t iot_apds9960_create(i2c_bus_handle_t bus, uint16_t dev_addr) { apds9960_dev_t* sensor = (apds9960_dev_t*) calloc(1, sizeof(apds9960_dev_t)); sensor->bus = bus; sensor->dev_addr = dev_addr; sensor->timeout = APDS9960_TIMEOUT_MS_DEFAULT; return (apds9960_handle_t) sensor; } esp_err_t iot_apds9960_delete(apds9960_handle_t sensor, bool del_bus) { apds9960_dev_t* sens = (apds9960_dev_t*) sensor; if (del_bus) { iot_i2c_bus_delete(sens->bus); sens->bus = NULL; } free(sens); return ESP_OK; } esp_err_t iot_apds9960_gesture_init(apds9960_handle_t sensor) { /* Set default values for ambient light and proximity registers */ iot_apds9960_set_adc_integration_time(sensor, 10); iot_apds9960_set_ambient_light_gain(sensor, APDS9960_AGAIN_4X); iot_apds9960_enable_gesture_engine(sensor, false); iot_apds9960_enable_proximity_engine(sensor, false); iot_apds9960_enable_color_engine(sensor, false); iot_apds9960_enable_color_interrupt(sensor, false); iot_apds9960_enable_proximity_interrupt(sensor, false); iot_apds9960_clear_interrupt(sensor); iot_apds9960_enable(sensor, false); iot_apds9960_enable(sensor, true); iot_apds9960_set_gesture_dimensions(sensor, APDS9960_DIMENSIONS_ALL); iot_apds9960_set_gesture_fifo_threshold(sensor, APDS9960_GFIFO_4); iot_apds9960_set_gesture_gain(sensor, APDS9960_GGAIN_4X); iot_apds9960_set_gesture_proximity_threshold(sensor, 10, 10); iot_apds9960_reset_counts(sensor); iot_apds9960_set_led_drive_boost(sensor, APDS9960_LEDDRIVE_100MA, APDS9960_LEDBOOST_100PCNT); iot_apds9960_set_gesture_waittime(sensor, APDS9960_GWTIME_2_8MS); iot_apds9960_set_gesture_pulse(sensor, APDS9960_GPULSELEN_8US, 8); iot_apds9960_enable_proximity_engine(sensor, true); return iot_apds9960_enable_gesture_engine(sensor, true); }
fduminy/intellij-community
java/java-tests/testSrc/com/intellij/java/editor/JavaEditorTextAttributesTest.java
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.editor; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.editor.colors.ex.DefaultColorSchemesManager; import com.intellij.openapi.editor.colors.impl.EditorColorsSchemeImpl; import com.intellij.openapi.editor.markup.EffectType; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.options.colors.AttributesDescriptor; import com.intellij.openapi.options.colors.pages.JavaColorSettingsPage; import com.intellij.openapi.util.Pair; import com.intellij.testFramework.LightPlatformTestCase; import com.intellij.ui.ColorUtil; import com.intellij.util.ObjectUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Ensures that Java attributes are not affected by changes in EditorColorScheme or these changes are planned and intentional. */ public class JavaEditorTextAttributesTest extends LightPlatformTestCase { private static List<AttributesDescriptor> getDescriptors() { JavaColorSettingsPage page = new JavaColorSettingsPage(); List<AttributesDescriptor> result = Arrays.asList(page.getAttributeDescriptors()); Collections.sort(result, (o1, o2) -> o1.getKey().getExternalName().compareToIgnoreCase(o2.getKey().getExternalName())); return result; } private static void appendAttributes(@NotNull String name, @NotNull StringBuilder builder, @NotNull TextAttributes attributes, @NotNull Color defaultForeground) { builder.append(name).append(" {"); appendHexColor(builder, "color", ObjectUtils.notNull(attributes.getForegroundColor(), defaultForeground)); appendHexColor(builder, "background-color", attributes.getBackgroundColor()); appendFontType(builder, attributes); appendEffects(builder, attributes); builder.append("}"); } private static void appendEffects(@NotNull StringBuilder builder, @NotNull TextAttributes attributes) { if (attributes.getEffectColor() != null) { Pair<String,String> textStyle = effectTypeToTextStyle(attributes.getEffectType()); builder.append("text-decoration: ").append(textStyle.first); builder.append(" #").append(ColorUtil.toHex(attributes.getEffectColor())); if (!textStyle.second.isEmpty()) { builder.append(textStyle.second); } builder.append("; "); } } private static Pair<String,String> effectTypeToTextStyle(@NotNull EffectType effectType) { switch (effectType) { case LINE_UNDERSCORE: return Pair.create("underline", ""); case BOLD_LINE_UNDERSCORE: return Pair.create("underline", "bold"); case STRIKEOUT: return Pair.create("line-through", ""); case BOXED: return Pair.create("boxed", ""); case WAVE_UNDERSCORE: return Pair.create("underline", "wavy"); case BOLD_DOTTED_LINE: return Pair.create("underline", "dotted"); case SEARCH_MATCH: break; case ROUNDED_BOX: break; } return Pair.create("??", ""); } private static void appendFontType(@NotNull StringBuilder builder, @NotNull TextAttributes attributes) { builder.append(" font-style: "); int fontType = attributes.getFontType(); builder.append((fontType & Font.ITALIC) != 0 ? "italic" : "normal").append("; "); if ((fontType & Font.BOLD) != 0) { builder.append(" font-weight: bold").append("; "); } } private static void appendHexColor(@NotNull StringBuilder builder, @NotNull String title, @Nullable Color color) { if (color != null) { builder.append(" ").append(title).append(": #").append(ColorUtil.toHex(color)).append("; "); } } private static String dumpDefaultColorScheme(@NotNull String name) { StringBuilder dumpBuilder = new StringBuilder(); EditorColorsScheme baseScheme = DefaultColorSchemesManager.getInstance().getScheme(name); EditorColorsScheme scheme = new EditorColorsSchemeImpl(baseScheme); Color defaultForeground = scheme.getDefaultForeground(); for (AttributesDescriptor descriptor : getDescriptors()) { TextAttributes attributes = scheme.getAttributes(descriptor.getKey()); appendAttributes(descriptor.getKey().getExternalName(), dumpBuilder, attributes, defaultForeground); dumpBuilder.append("\n"); } return dumpBuilder.toString(); } public void testDefaultColorScheme() { assertEquals( "ABSTRACT_CLASS_NAME_ATTRIBUTES { color: #000000; font-style: normal; }\n" + "ABSTRACT_METHOD_ATTRIBUTES { color: #000000; font-style: normal; }\n" + "ANNOTATION_ATTRIBUTE_NAME_ATTRIBUTES { color: #000000; font-style: normal; }\n" + "ANNOTATION_NAME_ATTRIBUTES { color: #808000; font-style: normal; }\n" + "ANONYMOUS_CLASS_NAME_ATTRIBUTES { color: #000000; font-style: normal; }\n" + "CLASS_NAME_ATTRIBUTES { color: #000000; font-style: normal; }\n" + "CONSTRUCTOR_CALL_ATTRIBUTES { color: #000000; font-style: normal; }\n" + "CONSTRUCTOR_DECLARATION_ATTRIBUTES { color: #000000; font-style: normal; }\n" + "DOC_COMMENT_TAG_VALUE { color: #3d3d3d; font-style: italic; font-weight: bold; }\n" + "ENUM_NAME_ATTRIBUTES { color: #000000; font-style: normal; }\n" + "IMPLICIT_ANONYMOUS_CLASS_PARAMETER_ATTRIBUTES { color: #660e7a; font-style: normal; }\n" + "INHERITED_METHOD_ATTRIBUTES { color: #000000; font-style: normal; }\n" + "INSTANCE_FIELD_ATTRIBUTES { color: #660e7a; font-style: normal; font-weight: bold; }\n" + "INSTANCE_FINAL_FIELD_ATTRIBUTES { color: #660e7a; font-style: normal; font-weight: bold; }\n" + "INTERFACE_NAME_ATTRIBUTES { color: #000000; font-style: normal; }\n" + "JAVA_BLOCK_COMMENT { color: #808080; font-style: italic; }\n" + "JAVA_BRACES { color: #000000; font-style: normal; }\n" + "JAVA_BRACKETS { color: #000000; font-style: normal; }\n" + "JAVA_COMMA { color: #000000; font-style: normal; }\n" + "JAVA_DOC_COMMENT { color: #808080; font-style: italic; }\n" + "JAVA_DOC_MARKUP { color: #000000; background-color: #e2ffe2; font-style: normal; }\n" + "JAVA_DOC_TAG { color: #000000; font-style: normal; font-weight: bold; text-decoration: underline #808080; }\n" + "JAVA_DOT { color: #000000; font-style: normal; }\n" + "JAVA_INVALID_STRING_ESCAPE { color: #008000; background-color: #ffcccc; font-style: normal; }\n" + "JAVA_KEYWORD { color: #000080; font-style: normal; font-weight: bold; }\n" + "JAVA_LINE_COMMENT { color: #808080; font-style: italic; }\n" + "JAVA_NUMBER { color: #0000ff; font-style: normal; }\n" + "JAVA_OPERATION_SIGN { color: #000000; font-style: normal; }\n" + "JAVA_PARENTH { color: #000000; font-style: normal; }\n" + "JAVA_SEMICOLON { color: #000000; font-style: normal; }\n" + "JAVA_STRING { color: #008000; font-style: normal; font-weight: bold; }\n" + "JAVA_VALID_STRING_ESCAPE { color: #000080; font-style: normal; font-weight: bold; }\n" + "LAMBDA_PARAMETER_ATTRIBUTES { color: #000000; font-style: normal; }\n" + "LOCAL_VARIABLE_ATTRIBUTES { color: #000000; font-style: normal; }\n" + "METHOD_CALL_ATTRIBUTES { color: #000000; font-style: normal; }\n" + "METHOD_DECLARATION_ATTRIBUTES { color: #000000; font-style: normal; }\n" + "PARAMETER_ATTRIBUTES { color: #000000; font-style: normal; }\n" + "REASSIGNED_LOCAL_VARIABLE_ATTRIBUTES { color: #000000; font-style: normal; text-decoration: underline #909090; }\n" + "REASSIGNED_PARAMETER_ATTRIBUTES { color: #000000; font-style: normal; text-decoration: underline #909090; }\n" + "STATIC_FIELD_ATTRIBUTES { color: #660e7a; font-style: italic; }\n" + "STATIC_FIELD_IMPORTED_ATTRIBUTES { color: #660e7a; font-style: italic; }\n" + "STATIC_FINAL_FIELD_ATTRIBUTES { color: #660e7a; font-style: italic; font-weight: bold; }\n" + "STATIC_FINAL_FIELD_IMPORTED_ATTRIBUTES { color: #660e7a; font-style: italic; font-weight: bold; }\n" + "STATIC_METHOD_ATTRIBUTES { color: #000000; font-style: italic; }\n" + "STATIC_METHOD_IMPORTED_ATTRIBUTES { color: #000000; font-style: italic; }\n" + "TYPE_PARAMETER_NAME_ATTRIBUTES { color: #20999d; font-style: normal; }\n", dumpDefaultColorScheme(EditorColorsScheme.DEFAULT_SCHEME_NAME)); } public void testDarculaColorScheme() { assertEquals( "ABSTRACT_CLASS_NAME_ATTRIBUTES { color: #a9b7c6; font-style: normal; }\n" + "ABSTRACT_METHOD_ATTRIBUTES { color: #a9b7c6; font-style: normal; }\n" + "ANNOTATION_ATTRIBUTE_NAME_ATTRIBUTES { color: #d0d0ff; font-style: normal; }\n" + "ANNOTATION_NAME_ATTRIBUTES { color: #bbb529; font-style: normal; }\n" + "ANONYMOUS_CLASS_NAME_ATTRIBUTES { color: #a9b7c6; font-style: normal; }\n" + "CLASS_NAME_ATTRIBUTES { color: #a9b7c6; font-style: normal; }\n" + "CONSTRUCTOR_CALL_ATTRIBUTES { color: #a9b7c6; font-style: normal; }\n" + "CONSTRUCTOR_DECLARATION_ATTRIBUTES { color: #ffc66d; font-style: normal; }\n" + "DOC_COMMENT_TAG_VALUE { color: #8a653b; font-style: normal; }\n" + "ENUM_NAME_ATTRIBUTES { color: #a9b7c6; font-style: normal; }\n" + "IMPLICIT_ANONYMOUS_CLASS_PARAMETER_ATTRIBUTES { color: #b389c5; font-style: normal; text-decoration: underline #b389c5; }\n" + "INHERITED_METHOD_ATTRIBUTES { color: #a9b7c6; font-style: normal; }\n" + "INSTANCE_FIELD_ATTRIBUTES { color: #9876aa; font-style: normal; }\n" + "INSTANCE_FINAL_FIELD_ATTRIBUTES { color: #9876aa; font-style: normal; }\n" + "INTERFACE_NAME_ATTRIBUTES { color: #a9b7c6; font-style: normal; }\n" + "JAVA_BLOCK_COMMENT { color: #808080; font-style: normal; }\n" + "JAVA_BRACES { color: #a9b7c6; font-style: normal; }\n" + "JAVA_BRACKETS { color: #a9b7c6; font-style: normal; }\n" + "JAVA_COMMA { color: #cc7832; font-style: normal; }\n" + "JAVA_DOC_COMMENT { color: #629755; font-style: italic; }\n" + "JAVA_DOC_MARKUP { color: #77b767; font-style: normal; }\n" + "JAVA_DOC_TAG { color: #629755; font-style: italic; font-weight: bold; text-decoration: underline #629755; }\n" + "JAVA_DOT { color: #a9b7c6; font-style: normal; }\n" + "JAVA_INVALID_STRING_ESCAPE { color: #6a8759; font-style: normal; text-decoration: underline #ff0000wavy; }\n" + "JAVA_KEYWORD { color: #cc7832; font-style: normal; }\n" + "JAVA_LINE_COMMENT { color: #808080; font-style: normal; }\n" + "JAVA_NUMBER { color: #6897bb; font-style: normal; }\n" + "JAVA_OPERATION_SIGN { color: #a9b7c6; font-style: normal; }\n" + "JAVA_PARENTH { color: #a9b7c6; font-style: normal; }\n" + "JAVA_SEMICOLON { color: #cc7832; font-style: normal; }\n" + "JAVA_STRING { color: #6a8759; font-style: normal; }\n" + "JAVA_VALID_STRING_ESCAPE { color: #cc7832; font-style: normal; }\n" + "LAMBDA_PARAMETER_ATTRIBUTES { color: #a9b7c6; font-style: normal; }\n" + "LOCAL_VARIABLE_ATTRIBUTES { color: #a9b7c6; font-style: normal; }\n" + "METHOD_CALL_ATTRIBUTES { color: #a9b7c6; font-style: normal; }\n" + "METHOD_DECLARATION_ATTRIBUTES { color: #ffc66d; font-style: normal; }\n" + "PARAMETER_ATTRIBUTES { color: #a9b7c6; font-style: normal; }\n" + "REASSIGNED_LOCAL_VARIABLE_ATTRIBUTES { color: #a9b7c6; font-style: normal; text-decoration: underline #707d95; }\n" + "REASSIGNED_PARAMETER_ATTRIBUTES { color: #a9b7c6; font-style: normal; text-decoration: underline #707d95; }\n" + "STATIC_FIELD_ATTRIBUTES { color: #9876aa; font-style: italic; }\n" + "STATIC_FIELD_IMPORTED_ATTRIBUTES { color: #9876aa; font-style: italic; }\n" + "STATIC_FINAL_FIELD_ATTRIBUTES { color: #9876aa; font-style: italic; }\n" + "STATIC_FINAL_FIELD_IMPORTED_ATTRIBUTES { color: #9876aa; font-style: italic; }\n" + "STATIC_METHOD_ATTRIBUTES { color: #a9b7c6; font-style: italic; }\n" + "STATIC_METHOD_IMPORTED_ATTRIBUTES { color: #a9b7c6; font-style: italic; }\n" + "TYPE_PARAMETER_NAME_ATTRIBUTES { color: #507874; font-style: normal; }\n", dumpDefaultColorScheme("Darcula") ); } }
jelly/zarafa-webapp
client/zarafa/common/rules/dialogs/RulesWordsEditPanel.js
<reponame>jelly/zarafa-webapp Ext.namespace('Zarafa.common.rules.dialogs'); /** * @class Zarafa.common.rules.dialogs.RulesWordsEditPanel * @extends Ext.form.FormPanel * @xtype zarafa.ruleswordseditpanel * * Panel to edit the {@link Zarafa.common.rules.data.ConditionFlags#SUBJECT_WORDS} condition * for a {@link Zarafa.common.rules.data.RulesRecord Rule}. */ Zarafa.common.rules.dialogs.RulesWordsEditPanel = Ext.extend(Ext.form.FormPanel, { /** * @cfg {Ext.data.Store} store The store which contains the words on which * is being filtered. */ store : undefined, /** * @constructor * @param config Configuration structure */ constructor : function(config) { config = config || {}; Ext.applyIf(config, { // Override from Ext.Component xtype : 'zarafa.ruleswordseditpanel', layout : { type : 'vbox', align : 'stretch' }, padding : 5, items : [{ xtype : 'zarafa.compositefield', items : [{ xtype : 'button', ref : '../editWordBtn', text : _('Edit'), width : 70, disabled : true, handler : this.onWordEdit, scope : this },{ xtype : 'spacer', width : 5 },{ xtype : 'button', ref : '../deleteWordBtn', text : _('Delete'), width : 70, disabled : true, handler : this.onWordDelete, scope : this }] },{ xtype : 'spacer', height : 5 },{ xtype : 'zarafa.compositefield', items : [{ xtype : 'textfield', ref : '../wordField', hideLabel : true, flex : 1, listeners : { 'specialkey' : this.onInputSpecialKey, 'scope' : this } },{ xtype : 'button', autoWidth : true, iconCls : 'zarafa-rules-add', handler : this.onWordAdd, scope : this }] },{ xtype : 'spacer', height : 5 },{ xtype : 'grid', ref : 'gridPanel', flex : 1, border : true, enableHdMenu : false, enableColumnMove : false, store : config.store, viewConfig : { headersDisabled : true, forceFit: true, autoExpandColumn: true, markDirty : false, scrollOffset: 0 }, colModel : new Ext.grid.ColumnModel({ columns: [{ dataIndex: 'words', sortable: false, renderer : Ext.util.Format.htmlEncode }] }), sm : new Ext.grid.RowSelectionModel({ singleSelect : true, listeners : { 'selectionchange' : this.onSelectionChange, 'scope' : this } }) }] }); Zarafa.common.rules.dialogs.RulesWordsEditPanel.superclass.constructor.call(this, config); }, /** * Event handler which is fired when the user pressed the {@link Ext.EventObject#ENTER ENTER} key. * This will call {@link #onWordAdd}. * @param {Ext.form.Field} field The field which fired the event * @param {Ext.EventObject} e The event object * @private */ onInputSpecialKey : function(field, e) { if (e.getKey() == e.ENTER) { this.onWordAdd(); } }, /** * Event handler which is fired when the 'Add' button has been clicked. This * will read the content of the input field, and add it to the {@link #store}. * After that the wordField is cleared, and the focus is reapplied to the * input field. * @return {Boolean} False when user tries to add another word. * @private */ onWordAdd : function() { var value = this.wordField.getValue().trim(); if (!Ext.isEmpty(value)) { this.store.add(new Ext.data.Record({ words : value })); this.wordField.reset(); } this.wordField.focus(); }, /** * Event handler which is fired when the 'Edit' button has been clicked. This * will obtain the currently selected record, remove it from the {@link #store} * and place the contents into the input field for further editing. * @private */ onWordEdit : function() { var record = this.gridPanel.getSelectionModel().getSelected(); if (record) { this.store.remove(record); this.wordField.setValue(record.get('words')); this.wordField.focus(); } }, /** * Event handler which is fired when the 'Delete' button has been clicked. This * will remove the selected record from the {@link #store}. * @private */ onWordDelete : function() { var record = this.gridPanel.getSelectionModel().getSelected(); if (record) { this.store.remove(record); } }, /** * Event handler which is fired when the {@link Ext.grid.RowSelectionModel} fires the * {@link Ext.grid.RowSelectionModel#selectionchange 'selectionchange'} event. This will * update the "Edit" and "Delete" buttons. * @param {Ext.grid.RowSelectionModel} selModel The selection model which fired the event * @private */ onSelectionChange : function(selModel) { var hasSelection = selModel.hasSelection(); this.editWordBtn.setDisabled(!hasSelection); this.deleteWordBtn.setDisabled(!hasSelection); } }); Ext.reg('zarafa.ruleswordseditpanel', Zarafa.common.rules.dialogs.RulesWordsEditPanel);
weijizhu1000/mall_jzb
src/clients/admin/component/system/user.list.js
import React from 'react' import moment from 'moment' import {Pagination} from 'antd' import {getAllUser, delUser} from "../../../../actions/api/user"; class UserItem extends React.Component { constructor(...args) { super(...args) } handlerDelete(evt) { this.props.removeUserItem(this.props.item._id); } render() { return ( <tr> <td className='itemTd'>{this.props.item.username}</td> <td className='itemTd'>{this.props.item.rolename}</td> <td className='itemTd'>{moment(this.props.item.createtime).format('YYYY-MM-DD HH:mm')}</td> <td className='itemTd'> <a className="itemBtn" onClick={this.handlerDelete.bind(this)}>删除</a> </td> </tr> ) } } class UserList extends React.Component { constructor(...args) { super(...args) } render() { var result = [] if (this.props.users.length > 0) { this.props.users.forEach(item => { result.push(<UserItem key={item.id} item={item} removeUserItem={this.props.removeUserItem}/>) }) } return ( <tbody>{result}</tbody> ) } } export default class User extends React.Component { constructor(props) { super(props) this.state = { totalcount: 0, pagesize: 10, users: [], } } componentWillMount() { this.queryUser(1) } queryUser(page) { getAllUser({ props: this.props, body: { page: page, pagesize: this.state.pagesize }, success: (result) => { console.log(result) this.setState({ totalcount: result.total, users: result.data }) }, error: (message) => { console.error(message) } }) } removeUserItem(key) { console.log(key) delUser({ props: this.props, body: {'_id': key}, success: (result) => { if (result.status == 100) { this.removeLocalUser(key) } }, error: (message) => { alert('删除失败,' + message) } }) } removeLocalUser(key) { for (var index = 0; index < this.state.users.length; index++) { if (this.state.users[index]._id == key) { this.state.users.splice(index, 1) break } } this.setState({ users: this.state.users }) } handlePageChange = (page, pageSize) => { console.log(page) console.log(pageSize) this.queryUser(page) } render() { return ( <div style={{width:'70%', marginRight:'auto', marginLeft:'auto'}}> <div style={{minHeight:380}}> <table className="table table-bordered table-hover index_table"> <thead> <tr> <th>账号</th> <th>角色</th> <th>创建时间</th> <th>操作</th> </tr> </thead> <UserList users={this.state.users} removeUserItem={this.removeUserItem.bind(this)}/> </table> </div> <label className="index_data_empty" style={{'display': (this.state.totalcount == 0) ? 'block' : 'none'}}>暂无数据</label> <div className="personlist_page"> <Pagination style={{'display': (this.state.totalcount == 0) ? 'none' : 'block'}} defaultCurrent={1} total={this.state.totalcount} onChange={this.handlePageChange}/> </div> </div> ) } }
lybdtt123/7Buy
AndroidBase/src/main/java/self/androidbase/utils/ScannerUtils.java
<reponame>lybdtt123/7Buy package self.androidbase.utils; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.media.MediaScannerConnection; import android.net.Uri; import android.os.Environment; import android.util.Log; import android.widget.Toast; import java.io.File; import java.io.FileOutputStream; /** * @author: HouSheng * @类 说 明: 图片扫描工具类 */ public class ScannerUtils { // 扫描的三种方式 public static enum ScannerType { RECEIVER, MEDIA } // 首先保存图片 public static void saveImageToGallery(Context context, Bitmap bitmap, ScannerType type) { File appDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "Doctor"); if (!appDir.exists()) { // 目录不存在 则创建 appDir.mkdirs(); } String fileName = System.currentTimeMillis() + ".jpg"; File file = new File(appDir, fileName); try { FileOutputStream fos = new FileOutputStream(file); bitmap.compress(CompressFormat.JPEG, 100, fos); // 保存bitmap至本地 fos.flush(); fos.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (type == ScannerType.RECEIVER) { ScannerByReceiver(context, file.getAbsolutePath()); } else if (type == ScannerType.MEDIA) { ScannerByMedia(context, file.getAbsolutePath()); } if (!bitmap.isRecycled()) { // bitmap.recycle(); 当存储大图片时,为避免出现OOM ,及时回收Bitmap System.gc(); // 通知系统回收 } // Toast.makeText(context, "图片保存为" + file.getAbsolutePath(), Toast.LENGTH_SHORT).show(); Toast.makeText(context, "保存成功!", Toast.LENGTH_SHORT).show(); } } /** * Receiver扫描更新图库图片 **/ private static void ScannerByReceiver(Context context, String path) { context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path))); Log.v("TAG", "receiver scanner completed"); } /** * MediaScanner 扫描更新图片图片 **/ private static void ScannerByMedia(Context context, String path) { MediaScannerConnection.scanFile(context, new String[]{path}, null, null); Log.v("TAG", "media scanner completed"); } }
JoanAzpeitia/lp_sg
install/app_store/tk-nuke/v0.9.4/python/tk_nuke/__init__.py
<gh_stars>1-10 # Copyright (c) 2015 Shotgun Software Inc. # # CONFIDENTIAL AND PROPRIETARY # # This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit # Source Code License included in this distribution package. See LICENSE. # By accessing, using, copying or modifying this work you indicate your # agreement to the Shotgun Pipeline Toolkit Source Code License. All rights # not expressly granted therein are reserved by Shotgun Software Inc. """ Callbacks to manage the engine when a new file is loaded in tank. Please note that this module is imported during Nuke's setup phase to handle automatic context switching. At this point, QT is not necessarily fully initialized. Therefore, any modules that require QT to be imported should be placed in the tk_nuke_qt module instead in order to avoid import errors at startup and context switch. """ import os import textwrap import nuke import tank import sys import traceback from .menu_generation import ( NukeMenuGenerator, HieroMenuGenerator, NukeStudioMenuGenerator, ) from .context import ClassicStudioContextSwitcher, PluginStudioContextSwitcher # noqa def __show_tank_disabled_message(details): """ Message when user clicks the tank is disabled menu """ msg = ("Shotgun integration is currently disabled because the file you " "have opened is not recognized. Shotgun cannot " "determine which Context the currently open file belongs to. " "In order to enable the Shotgun functionality, try opening another " "file. <br><br><i>Details:</i> %s" % details) nuke.message(msg) def __create_tank_disabled_menu(details): """ Creates a std "disabled" shotgun menu """ if nuke.env.get("gui"): nuke_menu = nuke.menu("Nuke") sg_menu = nuke_menu.addMenu("Shotgun") sg_menu.clearMenu() cmd = lambda d=details: __show_tank_disabled_message(d) sg_menu.addCommand("Toolkit is disabled.", cmd) else: nuke.error("The Shotgun Pipeline Toolkit is disabled: %s" % details) def __create_tank_error_menu(): """ Creates a std "error" tank menu and grabs the current context. Make sure that this is called from inside an except clause. """ (exc_type, exc_value, exc_traceback) = sys.exc_info() message = "" message += "Message: Shotgun encountered a problem starting the Engine.\n" message += "Please contact <EMAIL>\n\n" message += "Exception: %s - %s\n" % (exc_type, exc_value) message += "Traceback (most recent call last):\n" message += "\n".join( traceback.format_tb(exc_traceback)) if nuke.env.get("gui"): nuke_menu = nuke.menu("Nuke") sg_menu = nuke_menu.addMenu("Shotgun") sg_menu.clearMenu() cmd = lambda m=message: nuke.message(m) sg_menu.addCommand("[Shotgun Error - Click for details]", cmd) else: nuke.error("The Shotgun Pipeline Toolkit caught an error: %s" % message) def __engine_refresh(tk, new_context): """ Checks the the tank engine should be """ engine_name = os.environ.get("TANK_NUKE_ENGINE_INIT_NAME") curr_engine = tank.platform.current_engine() if curr_engine: # an old engine is running. if new_context == curr_engine.context: # no need to restart the engine! return else: # shut down the engine curr_engine.destroy() # try to create new engine try: tank.platform.start_engine(engine_name, tk, new_context) except tank.TankEngineInitError, e: # context was not sufficient! - disable tank! __create_tank_disabled_menu(e) def __tank_on_save_callback(): """ Callback that fires every time a file is saved. Carefully manage exceptions here so that a bug in Tank never interrupts the normal workflows in Nuke. """ # get the new file name file_name = nuke.root().name() try: # this file could be in another project altogether, so create a new Tank # API instance. try: tk = tank.tank_from_path(file_name) except tank.TankError, e: __create_tank_disabled_menu(e) return # try to get current ctx and inherit its values if possible curr_ctx = None if tank.platform.current_engine(): curr_ctx = tank.platform.current_engine().context # and now extract a new context based on the file new_ctx = tk.context_from_path(file_name, curr_ctx) # now restart the engine with the new context __engine_refresh(tk, new_ctx) except Exception, e: __create_tank_error_menu() def tank_startup_node_callback(): """ Callback that fires every time a node gets created. Carefully manage exceptions here so that a bug in Tank never interrupts the normal workflows in Nuke. """ try: if nuke.root().name() == "Root": # file->new # base it on the context we 'inherited' from the prev session # get the context from the previous session - this is helpful if user does file->new project_root = os.environ.get("TANK_NUKE_ENGINE_INIT_PROJECT_ROOT") tk = tank.Tank(project_root) ctx_str = os.environ.get("TANK_NUKE_ENGINE_INIT_CONTEXT") if ctx_str: try: new_ctx = tank.context.deserialize(ctx_str) except: new_ctx = tk.context_empty() else: new_ctx = tk.context_empty() else: # file->open file_name = nuke.root().name() try: tk = tank.tank_from_path(file_name) except tank.TankError, e: __create_tank_disabled_menu(e) return # try to get current ctx and inherit its values if possible curr_ctx = None if tank.platform.current_engine(): curr_ctx = tank.platform.current_engine().context new_ctx = tk.context_from_path(file_name, curr_ctx) # now restart the engine with the new context __engine_refresh(tk, new_ctx) except Exception, e: __create_tank_error_menu() g_tank_callbacks_registered = False def tank_ensure_callbacks_registered(): """ Make sure that we have callbacks tracking context state changes. """ import sgtk engine = sgtk.platform.current_engine() # Register only if we're missing an engine (to allow going from disabled to something else) # or if the engine specifically requests for it. if not engine or engine.get_setting("automatic_context_switch"): global g_tank_callbacks_registered if not g_tank_callbacks_registered: nuke.addOnScriptLoad(tank_startup_node_callback) nuke.addOnScriptSave(__tank_on_save_callback) g_tank_callbacks_registered = True
svenskan/pronunciation
vendor/swftools/lib/log.c
/* log.c Logging facilities for displaying information on screen, as well as (optional) storing it to a file and transmitting it over the network. Part of the swftools package. Copyright (c) 2001 <NAME> <<EMAIL>> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <stdlib.h> #include <string.h> #include <stdarg.h> #ifdef WIN32 //#include "stdafx.h" #include <malloc.h> #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #else #include <stdio.h> #include <unistd.h> #endif #include "log.h" int maxloglevel = 1; static int screenloglevel = 1; static int fileloglevel = -1; static FILE *logFile = 0; int getScreenLogLevel() { return screenloglevel; } int getLogLevel() { return maxloglevel; } void setConsoleLogging(int level) { if(level>maxloglevel) maxloglevel=level; screenloglevel = level; } void setFileLogging(char*filename, int level, char append) { if(level>maxloglevel) maxloglevel=level; if(logFile) { fclose(logFile);logFile=0; } if(filename && level>=0) { logFile = fopen(filename, append?"ab+":"wb"); fileloglevel = level; } else { logFile = 0; fileloglevel = 0; } } /* deprecated */ void initLog(char* filename, int filelevel, char* s00, char* s01, int s02, int screenlevel) { setFileLogging(filename, filelevel, 0); setConsoleLogging(screenlevel); } void exitLog() { // close file if(logFile != NULL) { fclose(logFile); logFile = 0; fileloglevel = -1; screenloglevel = 1; maxloglevel = 1; } } static char * logimportance[]= {"Fatal","Error","Warning","Notice","Verbose","Debug","Trace"}; static int loglevels=7; static char * logimportance2[]= {" ","FATAL ","ERROR ","WARNING","NOTICE ","VERBOSE","DEBUG ", "TRACE "}; static inline void log_str(const char* logString) { char timebuffer[32]; char* logBuffer; char dbuffer[9]; char tbuffer[9]; int level; char*lt; char*gt; int l; logBuffer = (char*)malloc (strlen(logString) + 24 + 15); #ifndef __NT__ { /*time_t t = time(0); tm*t2 = localtime(t); strftime(dbuffer, 8, "%m %d", t2); strftime(tbuffer, 8, "%m %d", t2); dbuffer[0]=0; //FIXME tbuffer[0]=0;*/ time_t t = time(0); char* a = ctime(&t); int l = strlen(a); while(a[l-1] == 13 || a[l-1] == 10) l--; a[l]=0; sprintf(timebuffer, "%s", a); } #else _strdate( dbuffer ); _strtime( tbuffer ); sprintf(timebuffer, "%s - %s",dbuffer,tbuffer); #endif // search for <level> field level = -1; lt=strchr(logString, '<'); gt=strchr(logString, '>'); if(lt && gt && lt<gt) { int t; for(t=0;t<loglevels;t++) { #ifndef __NT__ if(!strncasecmp(lt+1,logimportance[t],strlen(logimportance[t]))) #else if(!strnicmp(lt+1,logimportance[t],strlen(logimportance[t]))) #endif { logString = gt+1; while(logString[0]==' ') logString ++; level = t; break; } } } // sprintf(logBuffer, "%s: %s %s", timebuffer, logimportance2[level + 1],logString); sprintf(logBuffer, "%s %s", logimportance2[level + 1],logString); // we always do exactly one newline. l=strlen(logBuffer)-1; while((logBuffer[l]==13 || logBuffer[l]==10) && l>=0) { logBuffer[l]=0; l--; } if (level <= screenloglevel) { printf("%s\n", logBuffer); fflush(stdout); } if (level <= fileloglevel) { if (logFile != NULL) { fprintf(logFile, "%s\r\n", logBuffer); fflush(logFile); } } free (logBuffer); } void msg_str(const char* buf) { if(buf[0]=='<') { char*z = "fewnvdt"; char*x = strchr(z,buf[1]); if(x && (x-z)>maxloglevel) return; } log_str(buf); } char char2loglevel[32] = /* a b c d e f g h i j k l m n o */ {-1,-1,-1,-1, /*debug*/5, /*error*/1, /*fatal*/0, -1, -1, -1,-1,-1,-1,-1,/*notice*/3,-1, /* p q r s t u v w x y z */ -1,-1,-1, -1, /*trace*/6, -1,/*verbose*/4,/*warning*/2, -1,-1,-1, -1,-1,-1,-1,-1}; int msg_internal(const char* format, ...) { char buf[1024]; va_list arglist; va_start(arglist, format); /* speed up hack */ if(format[0]=='<') { char*z = "fewnvdt"; char*x = strchr(z,format[1]); if(x && (x-z)>maxloglevel) return 0; } vsnprintf(buf, sizeof(buf)-1, format, arglist); va_end(arglist); strcat(buf, "\n"); log_str(buf); return 0; }
RockyLOMO/rxlib
src/main/java/org/rx/io/Serializer.java
package org.rx.io; import org.rx.bean.RxConfig; public interface Serializer { Serializer DEFAULT = new JdkAndJsonSerializer(); default <T> IOStream<?, ?> serialize(T obj) { return serialize(obj, RxConfig.MAX_HEAP_BUF_SIZE, null); } default <T> HybridStream serialize(T obj, int maxMemorySize, String tempFilePath) { HybridStream stream = new HybridStream(maxMemorySize, tempFilePath); serialize(obj, stream); return stream; } <T> void serialize(T obj, IOStream<?, ?> stream); default <T> T deserialize(IOStream<?, ?> stream) { return deserialize(stream, false); } <T> T deserialize(IOStream<?, ?> stream, boolean leveOpen); }
mixcore/mix.spa.portal
src/app/app-portal/pages/theme/components/theme-export-posts/script.js
<reponame>mixcore/mix.spa.portal app.component("themeExportPosts", { templateUrl: "/mix-app/views/app-portal/pages/theme/components/theme-export-posts/view.html", controller: [ "$rootScope", "$scope", "ngAppSettings", function ($rootScope, $scope) { var ctrl = this; ctrl.updatePostExport = function (value, isSelected) { // Filter actived post var idx = (ctrl.selectedExport.posts = angular.copy( $rootScope.filterArray(ctrl.exportData.posts, ["isActived"], [true]) )); }; ctrl.isSelected = function (value) { return ctrl.selectedValues.indexOf(value) >= 0; }; ctrl.selectAll = function (arr) { ctrl.selectedList.data = []; angular.forEach(arr, function (e) { e.isActived = ctrl.selectedList.isSelectAll; e.isExportData = ctrl.selectedList.isExportData; }); ctrl.updatePostExport(); }; }, ], bindings: { exportData: "=", selectedExport: "=", }, });
zhoushiqiang222/base-service
react/src/app/iam/containers/market/SideBar/ApplyForRelease/Store/Step2/marketAppDataSet.js
<filename>react/src/app/iam/containers/market/SideBar/ApplyForRelease/Store/Step2/marketAppDataSet.js import { axios } from '@choerodon/boot'; import React from 'react'; import { Icon, Tooltip, DataSet } from 'choerodon-ui/pro'; import { message } from 'choerodon-ui'; export default function (projectId, organizationId, categoryTypeOption) { const validateName = async (value, name, record) => { if (value === record.getPristineValue(name) || !value) return; if (value.length > 30) { return '文本内容限制 30 字符,请重新输入'; } if (!/^[\u4e00-\u9fa5a-zA-Z0-9_\-.\s]+$/.test(value)) { return '应用名称只能由汉字、字母、数字、"_" 、"."、"-"、空格、组成'; } if (/^\s|\s$/.test(value)) { return '不能以空格开头或结束'; } try { const res = await axios.get(`iam/choerodon/v1/projects/${projectId}/publish_applications/check_name`, { params: { name: value, }, }); if (res.failed) { return res.message; } if (!res) { return '应用名称重复'; } } catch (err) { return err; } return true; }; const validateCategoryName = async (value, name, record) => { if (value === record.getPristineValue(name) || !value) return; // "^[A-Za-z0-9\\u4e00-\\u9fa5\\s]{1,30}$" // \u4e00-\u9fa5a-zA-Z0-9\s if (!/^[\u4e00-\u9fa5a-zA-Z0-9\s]+$/.test(value)) { return '只能由汉字、字母(大小写)、数字、空格构成'; } if (value.length > 30) { return '文本内容限制 30 字符,请重新输入'; } if (/^\s|\s$/.test(value)) { return '不能以空格开头或结束'; } try { const res = await axios.get(`iam/choerodon/v1/projects/${projectId}/publish_applications/app_categories/check`, { params: { category_name: value, }, }); if (res.failed) { return res.message; } if (!res) { return '应用类型重复'; } } catch (err) { return err; } return true; }; const validateContributor = (value) => { if (value.length > 30) { return '文本内容限制 30 字符,请重新输入'; } if (/^\s|\s$/.test(value)) { return '不能以空格开头或结束'; } return true; }; const validateImg = async (value) => { if (!value) { return '请上传应用图标'; } return true; }; const validateDescription = (value) => { if (value.length > 250) { return '文本内容限制 250 字符,请重新输入'; } return true; }; const emailValidator = (value) => { if (!/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)) { return '邮箱不符合规范'; } return true; }; const remarkValidator = (value) => { if (value && value.length > 250) { return '文本内容限制 250 字符,请重新输入'; } return true; }; const dynamicCategoryName = ({ record }) => ({ required: record.get('categoryType') === 'custom', validator: record.get('categoryType') === 'custom' ? validateCategoryName : null, }); return { autoQuery: false, autoCreate: true, dataKey: null, paging: false, fields: [ { name: 'imageUrl', type: 'string', label: '应用图标', validator: validateImg }, { name: 'name', type: 'string', label: '应用名称', required: true, validator: validateName }, { name: 'contributor', type: 'string', label: '贡献者', required: true, validator: validateContributor }, { name: 'categoryOption', type: 'object', label: '应用类型', textField: 'name', valueField: 'type', options: categoryTypeOption, required: true, ignore: 'always', defaultValue: categoryTypeOption.get(0) }, { name: 'categoryType', type: 'string', bind: 'categoryOption.type', ignore: 'always' }, { name: 'categoryName', type: 'string', label: '类型名称', dynamicProps: dynamicCategoryName, ignore: 'always' }, { name: 'description', type: 'string', label: '应用描述', required: true, validator: validateDescription }, { name: 'free', type: 'boolean', label: '是否免费', required: true, defaultValue: true }, { name: 'publishType', type: 'string', label: ( <span style={{ pointerEvents: 'auto' }} className="labelHelp"> 发布类型 <Tooltip title={( <div> <p style={{ marginBottom: 0 }}>源代码:该应用下的服务会开放源码,可用于二次开发。</p> <p style={{ marginBottom: 0 }}>部署包:该应用无源码库,只可进行部署</p> </div> )} > <Icon type="help" style={{ marginLeft: '0.1rem' }} /> </Tooltip> </span> ), multiple: true, defaultValue: 'mkt_deploy_only', required: true }, { name: 'notificationEmail', type: 'string', label: '通知邮箱', validator: emailValidator, required: true }, { name: 'remark', type: 'string', label: '备注', validator: remarkValidator }, ], events: { update: ({ name, value, oldValue, record }) => { if (name === 'categoryOption' && oldValue && oldValue.type === 'custom') { record.set('categoryName', null); } }, }, }; }
NordicWayInterchange/interchange
onboard-server/src/main/java/no/vegvesen/ixn/serviceprovider/TypeTransformer.java
<reponame>NordicWayInterchange/interchange<filename>onboard-server/src/main/java/no/vegvesen/ixn/serviceprovider/TypeTransformer.java package no.vegvesen.ixn.serviceprovider; import no.vegvesen.ixn.federation.api.v1_0.CapabilityApi; import no.vegvesen.ixn.federation.model.*; import no.vegvesen.ixn.federation.transformer.CapabilityToCapabilityApiTransformer; import no.vegvesen.ixn.serviceprovider.model.*; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.*; public class TypeTransformer { public static AddCapabilitiesResponse addCapabilitiesResponse(String serviceProviderName, Set<Capability> capabilities) { return new AddCapabilitiesResponse( serviceProviderName, capabilitySetToLocalActorCapability(serviceProviderName,capabilities) ); } private static Set<LocalActorCapability> capabilitySetToLocalActorCapability(String serviceProviderName, Set<Capability> capabilities) { Set<LocalActorCapability> result = new HashSet<>(); for (Capability capability : capabilities) { result.add(capabilityToLocalCapability(serviceProviderName,capability)); } return result; } private static LocalActorCapability capabilityToLocalCapability(String serviceProviderName, Capability capability) { String id = capability.getId().toString(); return new LocalActorCapability( id, createCapabilitiesPath(serviceProviderName, id), capability.toApi()); } public ListSubscriptionsResponse transformLocalSubscriptionsToListSubscriptionResponse(String name, Set<LocalSubscription> subscriptions) { return new ListSubscriptionsResponse(name,transformLocalSubscriptionsToLocalActorSubscription(name,subscriptions)); } private Set<LocalActorSubscription> transformLocalSubscriptionsToLocalActorSubscription(String name, Set<LocalSubscription> subscriptions) { Set<LocalActorSubscription> result = new HashSet<>(); for (LocalSubscription subscription : subscriptions) { String sub_id = subscription.getSub_id() == null ? null : subscription.getSub_id().toString(); result.add(new LocalActorSubscription( sub_id, createSubscriptionPath(name,sub_id), subscription.getSelector(), transformLocalDateTimeToEpochMili(subscription.getLastUpdated()), transformLocalSubscriptionStaturToLocalActorSubscriptionStatusApi(subscription.getStatus()))); } return result; } public LocalSubscription transformSelectorApiToLocalSubscription(String serviceProviderName, SelectorApi selectorApi) { return new LocalSubscription(LocalSubscriptionStatus.REQUESTED, selectorApi.getSelector(), serviceProviderName); } public AddSubscriptionsResponse transformLocalSubscriptionsToSubscriptionPostResponseApi(String serviceProviderName, Set<LocalSubscription> localSubscriptions) { return new AddSubscriptionsResponse(serviceProviderName, tranformLocalSubscriptionsToSubscriptionsPostResponseSubscriptionApi( serviceProviderName, localSubscriptions) ); } private Set<LocalActorSubscription> tranformLocalSubscriptionsToSubscriptionsPostResponseSubscriptionApi(String serviceProviderName, Set<LocalSubscription> localSubscriptions) { Set<LocalActorSubscription> result = new HashSet<>(); for (LocalSubscription subscription : localSubscriptions) { String subscriptionId = subscription.getSub_id().toString(); result.add(new LocalActorSubscription( subscriptionId, createSubscriptionPath(serviceProviderName, subscriptionId), subscription.getSelector(), transformLocalDateTimeToEpochMili(subscription.getLastUpdated()), transformLocalSubscriptionStaturToLocalActorSubscriptionStatusApi(subscription.getStatus()) ) ); } return result; } private String createSubscriptionPath(String serviceProviderName, String subscriptionId) { return String.format("/%s/subscriptions/%s", serviceProviderName, subscriptionId); } private static String createCapabilitiesPath(String serviceProviderName, String capabilityId) { return String.format("/%s/capabilities/%s", serviceProviderName, capabilityId); } private long transformLocalDateTimeToEpochMili(LocalDateTime lastUpdated) { return lastUpdated == null ? 0 : ZonedDateTime.of(lastUpdated, ZoneId.systemDefault()).toInstant().toEpochMilli(); } public GetSubscriptionResponse transformLocalSubscriptionToGetSubscriptionResponse(String serviceProviderName, LocalSubscription localSubscription) { return new GetSubscriptionResponse( localSubscription.getSub_id().toString(), createSubscriptionPath(serviceProviderName,localSubscription.getSub_id().toString()), localSubscription.getSelector(), transformLocalDateTimeToEpochMili(localSubscription.getLastUpdated()), transformLocalSubscriptionStaturToLocalActorSubscriptionStatusApi(localSubscription.getStatus()), transformLocalBrokersToEndpoints(localSubscription.getLocalBrokers()) ); } private Set<Endpoint> transformLocalBrokersToEndpoints(Set<LocalBroker> localBrokers) { Set<Endpoint> result = new HashSet<>(); for (LocalBroker broker : localBrokers) { result.add(new Endpoint(broker.getMessageBrokerUrl(), broker.getQueueName(), broker.getMaxBandwidth(), broker.getMaxMessageRate())); } return result; } private LocalActorSubscriptionStatusApi transformLocalSubscriptionStaturToLocalActorSubscriptionStatusApi(LocalSubscriptionStatus status) { switch (status) { case REQUESTED: return LocalActorSubscriptionStatusApi.REQUESTED; case CREATED: return LocalActorSubscriptionStatusApi.CREATED; case TEAR_DOWN: return LocalActorSubscriptionStatusApi.NOT_VALID; default: return LocalActorSubscriptionStatusApi.ILLEGAL; } } public Set<Capability> capabilitiesRequestToCapabilities(CapabilityToCapabilityApiTransformer capabilityApiTransformer, AddCapabilitiesRequest capabilitiesRequest) { Set<Capability> capabilities = new HashSet<>(); for (CapabilityApi capabilityApi : capabilitiesRequest.getCapabilities()) { Capability capability = capabilityApiTransformer.capabilityApiToCapability(capabilityApi); capabilities.add(capability); } return capabilities; } public ListCapabilitiesResponse listCapabilitiesResponse(String serviceProviderName, Set<Capability> capabilities) { return new ListCapabilitiesResponse( serviceProviderName, capabilitySetToLocalActorCapability(serviceProviderName,capabilities) ); } public GetCapabilityResponse getCapabilityResponse(String serviceProviderName, Capability capability) { String capabilityId = capability.getId().toString(); return new GetCapabilityResponse( capabilityId, createCapabilitiesPath(serviceProviderName,capabilityId), capability.toApi() ); } }
capeanalytics/aws-sdk-cpp
aws-cpp-sdk-cloudtrail/include/aws/cloudtrail/model/PublicKey.h
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/cloudtrail/CloudTrail_EXPORTS.h> #include <aws/core/utils/Array.h> #include <aws/core/utils/DateTime.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace CloudTrail { namespace Model { /** * <p>Contains information about a returned public key.</p><p><h3>See Also:</h3> * <a * href="http://docs.aws.amazon.com/goto/WebAPI/cloudtrail-2013-11-01/PublicKey">AWS * API Reference</a></p> */ class AWS_CLOUDTRAIL_API PublicKey { public: PublicKey(); PublicKey(const Aws::Utils::Json::JsonValue& jsonValue); PublicKey& operator=(const Aws::Utils::Json::JsonValue& jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The DER encoded public key value in PKCS#1 format.</p> */ inline const Aws::Utils::ByteBuffer& GetValue() const{ return m_value; } /** * <p>The DER encoded public key value in PKCS#1 format.</p> */ inline void SetValue(const Aws::Utils::ByteBuffer& value) { m_valueHasBeenSet = true; m_value = value; } /** * <p>The DER encoded public key value in PKCS#1 format.</p> */ inline void SetValue(Aws::Utils::ByteBuffer&& value) { m_valueHasBeenSet = true; m_value = std::move(value); } /** * <p>The DER encoded public key value in PKCS#1 format.</p> */ inline PublicKey& WithValue(const Aws::Utils::ByteBuffer& value) { SetValue(value); return *this;} /** * <p>The DER encoded public key value in PKCS#1 format.</p> */ inline PublicKey& WithValue(Aws::Utils::ByteBuffer&& value) { SetValue(std::move(value)); return *this;} /** * <p>The starting time of validity of the public key.</p> */ inline const Aws::Utils::DateTime& GetValidityStartTime() const{ return m_validityStartTime; } /** * <p>The starting time of validity of the public key.</p> */ inline void SetValidityStartTime(const Aws::Utils::DateTime& value) { m_validityStartTimeHasBeenSet = true; m_validityStartTime = value; } /** * <p>The starting time of validity of the public key.</p> */ inline void SetValidityStartTime(Aws::Utils::DateTime&& value) { m_validityStartTimeHasBeenSet = true; m_validityStartTime = std::move(value); } /** * <p>The starting time of validity of the public key.</p> */ inline PublicKey& WithValidityStartTime(const Aws::Utils::DateTime& value) { SetValidityStartTime(value); return *this;} /** * <p>The starting time of validity of the public key.</p> */ inline PublicKey& WithValidityStartTime(Aws::Utils::DateTime&& value) { SetValidityStartTime(std::move(value)); return *this;} /** * <p>The ending time of validity of the public key.</p> */ inline const Aws::Utils::DateTime& GetValidityEndTime() const{ return m_validityEndTime; } /** * <p>The ending time of validity of the public key.</p> */ inline void SetValidityEndTime(const Aws::Utils::DateTime& value) { m_validityEndTimeHasBeenSet = true; m_validityEndTime = value; } /** * <p>The ending time of validity of the public key.</p> */ inline void SetValidityEndTime(Aws::Utils::DateTime&& value) { m_validityEndTimeHasBeenSet = true; m_validityEndTime = std::move(value); } /** * <p>The ending time of validity of the public key.</p> */ inline PublicKey& WithValidityEndTime(const Aws::Utils::DateTime& value) { SetValidityEndTime(value); return *this;} /** * <p>The ending time of validity of the public key.</p> */ inline PublicKey& WithValidityEndTime(Aws::Utils::DateTime&& value) { SetValidityEndTime(std::move(value)); return *this;} /** * <p>The fingerprint of the public key.</p> */ inline const Aws::String& GetFingerprint() const{ return m_fingerprint; } /** * <p>The fingerprint of the public key.</p> */ inline void SetFingerprint(const Aws::String& value) { m_fingerprintHasBeenSet = true; m_fingerprint = value; } /** * <p>The fingerprint of the public key.</p> */ inline void SetFingerprint(Aws::String&& value) { m_fingerprintHasBeenSet = true; m_fingerprint = std::move(value); } /** * <p>The fingerprint of the public key.</p> */ inline void SetFingerprint(const char* value) { m_fingerprintHasBeenSet = true; m_fingerprint.assign(value); } /** * <p>The fingerprint of the public key.</p> */ inline PublicKey& WithFingerprint(const Aws::String& value) { SetFingerprint(value); return *this;} /** * <p>The fingerprint of the public key.</p> */ inline PublicKey& WithFingerprint(Aws::String&& value) { SetFingerprint(std::move(value)); return *this;} /** * <p>The fingerprint of the public key.</p> */ inline PublicKey& WithFingerprint(const char* value) { SetFingerprint(value); return *this;} private: Aws::Utils::ByteBuffer m_value; bool m_valueHasBeenSet; Aws::Utils::DateTime m_validityStartTime; bool m_validityStartTimeHasBeenSet; Aws::Utils::DateTime m_validityEndTime; bool m_validityEndTimeHasBeenSet; Aws::String m_fingerprint; bool m_fingerprintHasBeenSet; }; } // namespace Model } // namespace CloudTrail } // namespace Aws
dacheng-mall/platform-client
src/pages/products/list.js
import React, { PureComponent } from 'react'; import { connect } from 'dva'; import { Switch, Button, Divider, Modal } from 'antd'; import { jump } from '../../utils'; import { TableX } from '../../utils/ui'; import styles from './list.less'; const source = window.config.source; class List extends PureComponent { columns = [ { key: 'title', title: '名称', dataIndex: 'title', render: (t, r) => { return ( <div className={styles.title}> <img src={`${source}${r.mainImageUrl}`} title={t} alt="" className={styles.mainImage} /> <div className={styles.text}> <div className={styles.name}>{t}</div> </div> </div> ); }, }, { key: 'category', title: '分类', dataIndex: 'category.name', align: 'center', }, { key: 'price', title: '单价(元)', dataIndex: 'price', align: 'center', render: (t) => <div className={styles.price}>{t ? t.toFixed(2) : '未知'}</div>, }, { key: 'status', title: '状态', dataIndex: 'status', render: (t, r) => { return ( <Switch size="small" checked={t === 1} onChange={this.changeStatus.bind(null, r.id)} /> ); }, align: 'center', }, { key: 'operator', title: '操作', dataIndex: 'id', render: (t) => { return ( <div> <Button onClick={this.edit.bind(null, t)} size="small" shape="circle" type="ghost" icon="edit" /> <Divider type="vertical" /> <Button onClick={this.remove.bind(null, t)} size="small" shape="circle" type="danger" icon="delete" /> </div> ); }, align: 'right', }, ]; edit = (id) => { if (id) { jump(`/products/detail/${id}`); } else { jump(`/products/detail`); } }; changeStatus = (id, status) => { this.props.dispatch({ type: 'products/setStatus', id, status, }); }; remove = (id, e) => { e.preventDefault(); Modal.confirm({ title: '是否删除商品?', onOk: () => { this.props.dispatch({ type: 'products/remove', id, }); }, }); }; render() { const showAddBtn = ((type, institutionId) => { if(type === 'self' && !institutionId) { return true; } if(type === 'third' && institutionId) { return true; } return false; })(this.props.institutionId, this.props.user.institutionId) return ( <div className={styles.wrap}> {showAddBtn ? <Button type="primary" onClick={this.edit.bind(null, false)} icon="plus"> 添加商品 </Button> : null} <TableX columns={this.columns} dataSource={this.props.data || []} pagination={this.props.pagination} fetchType="products/fetch" dispatch={this.props.dispatch} /> {/* <Table rowKey="id" size="small" columns={this.columns} dataSource={this.props.data} locale={{ emptyText: '暂无数据' }} pagination={{ pageSize: this.props.pagination.pageSize, total: this.props.pagination.total, current: this.props.pagination.page, onChange: (page, pageSize) => { this.props.dispatch({ type: 'products/fetch', payload: {page, pageSize} }) } }} /> */} </div> ); } } function mapStateToProps({ products, app }) { return {...products, user: app.user}; } export default connect(mapStateToProps)(List);
manoelmenezes/gswgg
src/test/java/chapter04/MultimapExamplesTest.java
package chapter04; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.HashMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.hamcrest.core.Is; import org.junit.Assert; import org.junit.Test; import java.util.List; import java.util.Set; public class MultimapExamplesTest { @Test public void testArrayListMultiMap() { ArrayListMultimap<String, String> multimap = ArrayListMultimap.create(); multimap.put("Foo", "1"); multimap.put("Foo", "2"); multimap.put("Foo", "3"); List<String> expected = Lists.newArrayList("1", "2", "3"); Assert.assertThat(multimap.get("Foo"), Is.is(expected)); } @Test public void testArrayListMultiMapSameKeyValue() { ArrayListMultimap<String, String> multimap = ArrayListMultimap.create(); multimap.put("Bar", "1"); multimap.put("Bar", "2"); multimap.put("Bar", "3"); multimap.put("Bar", "3"); multimap.put("Bar", "3"); List<String> expected = Lists.newArrayList("1", "2", "3", "3", "3"); Assert.assertThat(multimap.get("Bar"), Is.is(expected)); } @Test public void testHashMultimap() { HashMultimap<String, String> multimap = HashMultimap.create(); multimap.put("Bar", "1"); multimap.put("Bar", "2"); multimap.put("Bar", "3"); multimap.put("Bar", "3"); multimap.put("Bar", "3"); Set<String> expected = Sets.newHashSet("1", "2", "3"); Assert.assertThat(multimap.size(), Is.is(3)); Assert.assertThat(multimap.get("Bar"), Is.is(expected)); } }
maslenitsa93/RocketJoe
apps/resource-hub/init_service.hpp
#pragma once #include <components/configuration/configuration.hpp> #include <components/log/log.hpp> #include <goblin-engineer/components/root_manager.hpp> #include <zmq.hpp> void init_service(goblin_engineer::components::root_manager&, components::configuration&, components::log_t&,zmq::context_t&);
6un9-h0-Dan/cobaul
deps/gnucobol-2.2/cobc/codegen.c
/* Copyright (C) 2003-2012, 2014-2017 Free Software Foundation, Inc. Written by <NAME>, <NAME>, <NAME>, <NAME>, <NAME> This file is part of GnuCOBOL. The GnuCOBOL compiler 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. GnuCOBOL 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 GnuCOBOL. If not, see <http://www.gnu.org/licenses/>. */ #include "config.h" #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <stdarg.h> #include <string.h> #include <ctype.h> #include <time.h> #include <limits.h> #include "tarstamp.h" #include "cobc.h" #include "tree.h" #ifdef HAVE_ATTRIBUTE_ALIGNED #define COB_ALIGN " __attribute__((aligned))" #else #define COB_ALIGN "" #endif #define COB_MAX_SUBSCRIPTS 16 #define COB_MALLOC_ALIGN 15 #define COB_INSIDE_SIZE 64 #define INITIALIZE_NONE 0 #define INITIALIZE_ONE 1 #define INITIALIZE_DEFAULT 2 #define INITIALIZE_COMPOUND 3 #define CB_NEED_HIGH (1U << 0) #define CB_NEED_LOW (1U << 1) #define CB_NEED_QUOTE (1U << 2) #define CB_NEED_SPACE (1U << 3) #define CB_NEED_ZERO (1U << 4) struct sort_list { struct sort_list *next; }; struct system_table { const char *syst_name; const char *syst_call; const unsigned int syst_max_params; }; struct label_list { struct label_list *next; int id; int call_num; }; struct string_list { struct string_list *next; char *text; int id; }; struct pic_list { struct pic_list *next; const cob_pic_symbol *str; int length; int id; }; struct attr_list { struct attr_list *next; int pic_id; int id; int type; cob_u32_t digits; int scale; cob_u32_t flags; }; struct literal_list { struct literal_list *next; struct cb_literal *literal; cb_tree x; int id; int make_decimal; }; struct field_list { struct field_list *next; struct cb_field *f; cb_tree x; const char *curr_prog; }; struct call_list { struct call_list *next; const char *call_name; }; #define COB_RETURN_INT 0 #define COB_RETURN_ADDRESS_OF 1 #define COB_RETURN_NULL 2 struct static_call_list { struct static_call_list *next; const char *call_name; int convention; int return_type; }; struct base_list { struct base_list *next; struct cb_field *f; const char *curr_prog; }; /* Local variables */ static struct pic_list *pic_cache = NULL; static struct attr_list *attr_cache = NULL; static struct literal_list *literal_cache = NULL; static struct field_list *field_cache = NULL; static struct field_list *local_field_cache = NULL; static struct call_list *call_cache = NULL; static struct call_list *func_call_cache = NULL; static struct static_call_list *static_call_cache = NULL; static struct base_list *base_cache = NULL; static struct base_list *globext_cache = NULL; static struct base_list *local_base_cache = NULL; static struct string_list *string_cache = NULL; static char *string_buffer = NULL; static struct label_list *label_cache = NULL; static FILE *output_target = NULL; static FILE *cb_local_file = NULL; static const char *excp_current_program_id = NULL; static const char *excp_current_section = NULL; static const char *excp_current_paragraph = NULL; static struct cb_program *current_prog = NULL; static struct cb_label *last_section = NULL; static unsigned char *litbuff = NULL; static int litsize = 0; static unsigned int needs_exit_prog = 0; static unsigned int needs_unifunc = 0; static unsigned int need_save_exception = 0; static unsigned int gen_nested_tab = 0; static unsigned int gen_alt_ebcdic = 0; static unsigned int gen_ebcdic_ascii = 0; static unsigned int gen_full_ebcdic = 0; static unsigned int gen_native = 0; static unsigned int gen_custom = 0; static unsigned int gen_figurative = 0; static unsigned int gen_dynamic = 0; static int param_id = 0; static int stack_id = 0; static int string_id = 1; static int num_cob_fields = 0; static int non_nested_count = 0; static int loop_counter = 0; static int progid = 0; static int last_line = 0; static cob_u32_t field_iteration = 0; static int screenptr = 0; static int local_mem = 0; static int working_mem = 0; static int local_working_mem = 0; static int output_indent_level = 0; static int last_segment = 0; static int gen_if_level = 0; static unsigned int nolitcast = 0; static unsigned int inside_check = 0; static unsigned int inside_stack[COB_INSIDE_SIZE]; static unsigned int i_counters[COB_MAX_SUBSCRIPTS]; #undef COB_SYSTEM_GEN #define COB_SYSTEM_GEN(cob_name, pmin, pmax, c_name) { cob_name, #c_name, pmax }, static const struct system_table system_tab[] = { #include "libcob/system.def" { NULL, NULL, 0 } }; #undef COB_SYSTEM_GEN /* Declarations */ static void output (const char *, ...) COB_A_FORMAT12; static void output_line (const char *, ...) COB_A_FORMAT12; static void output_storage (const char *, ...) COB_A_FORMAT12; static void output_local (const char *, ...) COB_A_FORMAT12; static void output_stmt (cb_tree); static void output_integer (cb_tree); static void output_index (cb_tree); static void output_func_1 (const char *, cb_tree); static void output_param (cb_tree, int); static void output_funcall (cb_tree); /* Local functions */ static struct cb_field * cb_code_field (cb_tree x) { if (likely(CB_REFERENCE_P (x))) { if (unlikely(!CB_REFERENCE (x)->value)) { return CB_FIELD (cb_ref (x)); } return CB_FIELD (CB_REFERENCE (x)->value); } return CB_FIELD (x); } static int lookup_string (const char *p) { struct string_list *stp; for (stp = string_cache; stp; stp = stp->next) { if (strcmp (p, stp->text) == 0) { return stp->id; } } stp = cobc_parse_malloc (sizeof (struct string_list)); stp->text = cobc_parse_strdup (p); stp->id = string_id; stp->next = string_cache; string_cache = stp; return string_id++; } static void lookup_call (const char *p) { struct call_list *clp; for (clp = call_cache; clp; clp = clp->next) { if (strcmp (p, clp->call_name) == 0) { return; } } clp = cobc_parse_malloc (sizeof (struct call_list)); clp->call_name = p; clp->next = call_cache; call_cache = clp; } static void lookup_func_call (const char *p) { struct call_list *clp; for (clp = func_call_cache; clp; clp = clp->next) { if (strcmp (p, clp->call_name) == 0) { return; } } clp = cobc_parse_malloc (sizeof (struct call_list)); clp->call_name = p; clp->next = func_call_cache; func_call_cache = clp; } static void lookup_static_call (const char *p, int convention, int return_type) { struct static_call_list *sclp; for (sclp = static_call_cache; sclp; sclp = sclp->next) { if (strcmp (p, sclp->call_name) == 0) { return; } } sclp = cobc_parse_malloc (sizeof (struct static_call_list)); sclp->call_name = p; sclp->convention = convention; sclp->return_type = return_type; sclp->next = static_call_cache; static_call_cache = sclp; } #define LIST_REVERSE_FUNC(list_struct) \ static struct list_struct * \ list_struct##_reverse (struct list_struct *p) \ { \ struct list_struct *next; \ struct list_struct *last; \ \ last = NULL; \ for (; p; p = next) { \ next = p->next; \ p->next = last; \ last = p; \ } \ return last; \ } LIST_REVERSE_FUNC (call_list) LIST_REVERSE_FUNC (static_call_list) LIST_REVERSE_FUNC (pic_list) LIST_REVERSE_FUNC (attr_list) LIST_REVERSE_FUNC (string_list) LIST_REVERSE_FUNC (literal_list) static int field_cache_cmp (const void *mp1, const void *mp2) { const struct field_list *fl1; const struct field_list *fl2; int ret; fl1 = (const struct field_list *)mp1; fl2 = (const struct field_list *)mp2; ret = strcasecmp (fl1->curr_prog, fl2->curr_prog); if (ret) { return ret; } return fl1->f->id - fl2->f->id; } static int base_cache_cmp (const void *mp1, const void *mp2) { const struct base_list *fl1; const struct base_list *fl2; fl1 = (const struct base_list *)mp1; fl2 = (const struct base_list *)mp2; return fl1->f->id - fl2->f->id; } /* Sort a structure linked list in place */ /* Assumed that pointer "next" is first item in structure */ static void * list_cache_sort (void *inlist, int (*cmpfunc)(const void *mp1, const void *mp2)) { struct sort_list *p; struct sort_list *q; struct sort_list *e; struct sort_list *tail; struct sort_list *list; size_t insize; size_t nmerges; size_t psize; size_t qsize; size_t i; if (!inlist) { return NULL; } list = (struct sort_list *)inlist; insize = 1; for (;;) { p = list; list = NULL; tail = NULL; nmerges = 0; while (p) { nmerges++; q = p; psize = 0; for (i = 0; i < insize; i++) { psize++; q = q->next; if (!q) { break; } } qsize = insize; while (psize > 0 || (qsize > 0 && q)) { if (psize == 0) { e = q; q = q->next; if (qsize) { qsize--; } } else if (qsize == 0 || !q) { e = p; p = p->next; if (psize) { psize--; } } else if ((*cmpfunc) (p, q) <= 0) { e = p; p = p->next; if (psize) { psize--; } } else { e = q; q = q->next; if (qsize) { qsize--; } } if (tail) { tail->next = e; } else { list = e; } tail = e; } p = q; } tail->next = NULL; if (nmerges <= 1) { return (void *)list; } insize *= 2; } } /* Output routines */ static void output (const char *fmt, ...) { va_list ap; if (output_target) { va_start (ap, fmt); vfprintf (output_target, fmt, ap); va_end (ap); } } static void output_newline (void) { if (output_target) { fputs ("\n", output_target); } } static void output_prefix (void) { int i; if (output_target) { for (i = 0; i < output_indent_level; i++) { fputc (' ', output_target); } } } static void output_line (const char *fmt, ...) { va_list ap; if (output_target) { output_prefix (); va_start (ap, fmt); vfprintf (output_target, fmt, ap); va_end (ap); fputc ('\n', output_target); } } static void output_indent (const char *str) { const char *p; int level; level = 2; for (p = str; *p == ' '; p++) { level++; } if (*p == '}' && strcmp (str, "})") != 0) { output_indent_level -= level; } output_line ("%s", str); if (*p == '{' && strcmp (str, ")}") != 0) { output_indent_level += level; } } static void output_string (const unsigned char *s, const int size, const cob_u32_t llit) { int i; int c; if (!s) { output ("NULL"); return; } output ("\""); for (i = 0; i < size; i++) { c = s[i]; if (!isprint (c)) { output ("\\%03o", c); } else if (c == '\"') { output ("\\%c", c); } else if ((c == '\\' || c == '?') && !llit) { output ("\\%c", c); } else { output ("%c", c); } } output ("\""); } static void output_storage (const char *fmt, ...) { va_list ap; if (cb_storage_file) { va_start (ap, fmt); vfprintf (cb_storage_file, fmt, ap); va_end (ap); } } static void output_local (const char *fmt, ...) { va_list ap; if (cb_local_file) { va_start (ap, fmt); vfprintf (cb_local_file, fmt, ap); va_end (ap); } } /* Field */ static struct cb_field * real_field_founder (const struct cb_field *f) { const struct cb_field *ff; ff = f; while (ff->parent) { ff = ff->parent; } if (ff->redefines) { return ff->redefines; } return (struct cb_field *)ff; } static struct cb_field * chk_field_variable_size (struct cb_field *f) { struct cb_field *p; struct cb_field *fc; if (f->flag_vsize_done) { return f->vsize; } for (fc = f->children; fc; fc = fc->sister) { if (fc->depending) { /* FIXME: does only cater for one ODO, not for the extension nested ones */ f->vsize = fc; f->flag_vsize_done = 1; return fc; } else if ((p = chk_field_variable_size (fc)) != NULL) { f->vsize = p; f->flag_vsize_done = 1; return p; } } f->vsize = NULL; f->flag_vsize_done = 1; return NULL; } /* Check if previous field on current or higher level has variable size */ static unsigned int chk_field_variable_address (struct cb_field *fld) { struct cb_field *p; struct cb_field *f; if (fld->flag_vaddr_done) { return fld->vaddr; } f = fld; for (p = f->parent; p; f = f->parent, p = f->parent) { for (p = p->children; p != f; p = p->sister) { if (p->depending || chk_field_variable_size (p)) { fld->vaddr = 1; fld->flag_vaddr_done = 1; return 1; } } } fld->vaddr = 0; fld->flag_vaddr_done = 1; return 0; } static void output_base (struct cb_field *f, const cob_u32_t no_output) { struct cb_field *f01; struct cb_field *p; struct cb_field *v; struct base_list *bl; if (unlikely(f->flag_item_78)) { /* LCOV_EXCL_START */ cobc_err_msg (_("unexpected CONSTANT item")); COBC_ABORT (); /* LCOV_EXCL_STOP */ } f01 = real_field_founder (f); /* Base storage */ if (!f01->flag_base) { if (f01->special_index == 2U) { bl = cobc_parse_malloc (sizeof (struct base_list)); bl->f = f01; bl->curr_prog = excp_current_program_id; bl->next = local_base_cache; local_base_cache = bl; } else if (!f01->flag_external && !f01->flag_local_storage) { if (!f01->flag_local || f01->flag_is_global) { bl = cobc_parse_malloc (sizeof (struct base_list)); bl->f = f01; bl->curr_prog = excp_current_program_id; if (f01->flag_is_global || current_prog->flag_file_global) { bl->next = base_cache; base_cache = bl; } else { bl->next = local_base_cache; local_base_cache = bl; } } else { if (current_prog->flag_global_use) { output_local ("unsigned char\t\t*%s%d = NULL;", CB_PREFIX_BASE, f01->id); output_local ("\t/* %s */\n", f01->name); output_local ("static unsigned char\t*save_%s%d;\n", CB_PREFIX_BASE, f01->id); } else { output_local ("unsigned char\t*%s%d = NULL;", CB_PREFIX_BASE, f01->id); output_local ("\t/* %s */\n", f01->name); } } } f01->flag_base = 1; } if (no_output) { return; } if (f01->special_index) { output ("(cob_u8_t *)&%s%d", CB_PREFIX_BASE, f01->id); return; } else if (f01->flag_local_storage) { if (f01->mem_offset) { output ("cob_local_ptr + %d", f01->mem_offset); } else { output ("cob_local_ptr"); } } else { output ("%s%d", CB_PREFIX_BASE, f01->id); } if (chk_field_variable_address (f)) { for (p = f->parent; p; f = f->parent, p = f->parent) { for (p = p->children; p != f; p = p->sister) { v = chk_field_variable_size (p); if (v) { output (" + %d + ", v->offset - p->offset); if (v->size != 1) { output ("%d * ", v->size); } output_integer (v->depending); } else if (p->depending && cb_flag_odoslide) { output (" + "); if (p->size != 1) { output ("%d * ", p->size); } output_integer (p->depending); } else { output (" + %d", p->size * p->occurs_max); } } } } else if (f->offset > 0) { output (" + %d", f->offset); } } static void output_data (cb_tree x) { struct cb_literal *l; struct cb_reference *r; struct cb_field *f; struct cb_field *o_slide; struct cb_field *o; cb_tree lsub; switch (CB_TREE_TAG (x)) { case CB_TAG_LITERAL: l = CB_LITERAL (x); if (CB_TREE_CLASS (x) == CB_CLASS_NUMERIC) { output ("(cob_u8_ptr)\"%s%s\"", (l->sign < 0) ? "-" : (l->sign > 0) ? "+" : "", (char *)l->data); } else { output ("(cob_u8_ptr)"); output_string (l->data, (int) l->size, l->llit); } break; case CB_TAG_FIELD: output_base (CB_FIELD(x), 0); break; case CB_TAG_REFERENCE: r = CB_REFERENCE (x); f = CB_FIELD (r->value); /* Base address */ output_base (f, 0); /* Subscripts */ if (r->subs) { lsub = r->subs; o_slide = NULL; for (; f && lsub; f = f->parent) { /* add current field size for OCCURS */ if (f->flag_occurs) { /* recalculate size for nested ODO ... */ if (unlikely(o_slide)) { for (o = o_slide; o; o = o->children) { if (o->depending) { output (" + (%d * ", o->size); output_integer (o->depending); output (")"); } } output (" * "); } else { /* ... use field size otherwise */ output (" + "); if (f->size != 1) { output ("%d * ", f->size); } } if (cb_flag_odoslide && f->depending) { o_slide = f; } output_index (CB_VALUE (lsub)); lsub = CB_CHAIN (lsub); } } } /* Offset */ if (r->offset) { output (" + "); output_index (r->offset); } break; case CB_TAG_CAST: output ("&"); output_param (x, 0); break; case CB_TAG_INTRINSIC: output ("cob_procedure_params[%u]->data", field_iteration); break; case CB_TAG_CONST: if (x == cb_null) { output ("NULL"); return; } /* Fall through */ default: /* LCOV_EXCL_START */ cobc_err_msg (_("unexpected tree tag: %d"), (int)CB_TREE_TAG (x)); COBC_ABORT (); /* LCOV_EXCL_STOP */ } } static void output_size (const cb_tree x) { struct cb_literal *l; struct cb_reference *r; struct cb_field *f; struct cb_field *p; struct cb_field *q; switch (CB_TREE_TAG (x)) { case CB_TAG_CONST: output ("1"); break; case CB_TAG_LITERAL: l = CB_LITERAL (x); output ("%d", (int)(l->size + ((l->sign != 0) ? 1 : 0))); break; case CB_TAG_REFERENCE: r = CB_REFERENCE (x); f = CB_FIELD (r->value); if (f->flag_no_field) { output ("0"); break; } if (r->length) { output_integer (r->length); } else if (r->offset && f->flag_any_length) { output ("%s%d.size - ", CB_PREFIX_FIELD, f->id); output_index (r->offset); } else { p = chk_field_variable_size (f); q = f; again: if (!cb_flag_odoslide && p && p->flag_odo_relative) { q = p; output ("%d", p->size * p->occurs_max); } else if (p && (!r->flag_receiving || !cb_field_subordinate (cb_code_field (p->depending), q))) { if (p->offset - q->offset > 0) { output ("%d + ", p->offset - q->offset); } if (p->size != 1) { #if 0 /* draft from Simon - works only if the ODOs are directly nested and have no "sister" elements, the content would only be correct if -fodoslide is active as we need a temporary field otherwise see FR #99 */ /* size for nested ODO */ if (p->odo_level > 1) { output_integer (p->depending); output (" * "); p = q; goto again; } #endif output ("%d * ", p->size); } output_integer (p->depending); q = p; } else { output ("%d", q->size); } for (; q != f; q = q->parent) { if (q->sister && !q->sister->redefines) { q = q->sister; p = q->depending ? q : chk_field_variable_size (q); output (" + "); goto again; } } if (r->offset) { output (" - "); output_index (r->offset); } } break; case CB_TAG_FIELD: output ("(int)%s%d.size", CB_PREFIX_FIELD, CB_FIELD (x)->id); break; default: /* LCOV_EXCL_START */ cobc_err_msg (_("unexpected tree tag: %d"), (int)CB_TREE_TAG (x)); COBC_ABORT (); /* LCOV_EXCL_STOP */ } } /* Picture strings */ static int lookup_pic (const cob_pic_symbol *pic, const int length) { struct pic_list *l; int i; int different_pic_str; /* Search picture string cache */ for (l = pic_cache; l; l = l->next) { if (length != l->length) { continue; } different_pic_str = 0; for (i = 0; i < l->length; ++i) { if (pic[i].symbol != l->str[i].symbol || pic[i].times_repeated != l->str[i].times_repeated) { different_pic_str = 1; break; } } if (different_pic_str) { continue; } return l->id; } /* Cache new picture string */ l = cobc_parse_malloc (sizeof (struct pic_list)); l->id = cb_pic_id; l->length = length; l->str = pic; l->next = pic_cache; pic_cache = l; return cb_pic_id++; } static void output_pic_cache (void) { struct pic_list *pic; int pos; if (!pic_cache) { return; } output_storage ("\n/* Picture strings */\n\n"); pic_cache = pic_list_reverse (pic_cache); for (pic = pic_cache; pic; pic = pic->next) { output_storage ("static const cob_pic_symbol %s%d[] = {\n", CB_PREFIX_PIC, pic->id); for (pos = 0; pos < pic->length && pic->str[pos].symbol != '\0'; ++pos) { output_storage ("\t{'%c', %u}", pic->str[pos].symbol, pic->str[pos].times_repeated); output_storage (",\n"); } output_storage ("\t{'\\0', 1}"); output_storage ("\n};\n"); } output_storage ("\n"); } /* Attributes */ static int lookup_attr (const int type, const cob_u32_t digits, const int scale, const cob_u32_t flags, cob_pic_symbol *pic, const int lenstr) { const int pic_id = pic ? lookup_pic (pic, lenstr) : -1; struct attr_list *l; /* Search attribute cache */ for (l = attr_cache; l; l = l->next) { if (type == l->type && digits == l->digits && scale == l->scale && flags == l->flags && pic_id == l->pic_id) { return l->id; } } /* Cache new attribute */ l = cobc_parse_malloc (sizeof (struct attr_list)); l->id = cb_attr_id; l->type = type; l->digits = digits; l->scale = scale; l->flags = flags; l->pic_id = pic_id; l->next = attr_cache; attr_cache = l; return cb_attr_id++; } static void output_attr (const cb_tree x) { struct cb_literal *l; struct cb_reference *r; struct cb_field *f; int id; int type; cob_u32_t flags; id = 0; switch (CB_TREE_TAG (x)) { case CB_TAG_LITERAL: l = CB_LITERAL (x); if (CB_TREE_CLASS (x) == CB_CLASS_NUMERIC) { flags = COB_FLAG_CONSTANT; if (l->sign != 0) { flags = COB_FLAG_HAVE_SIGN | COB_FLAG_SIGN_SEPARATE | COB_FLAG_SIGN_LEADING; } id = lookup_attr (COB_TYPE_NUMERIC_DISPLAY, l->size, l->scale, flags, NULL, 0); } else { if (l->all) { id = lookup_attr (COB_TYPE_ALPHANUMERIC_ALL, 0, 0, COB_FLAG_CONSTANT, NULL, 0); } else { id = lookup_attr (COB_TYPE_ALPHANUMERIC, 0, 0, COB_FLAG_CONSTANT, NULL, 0); } } break; case CB_TAG_REFERENCE: r = CB_REFERENCE (x); f = CB_FIELD (r->value); flags = 0; if (r->offset) { id = lookup_attr (COB_TYPE_ALPHANUMERIC, 0, 0, 0, NULL, 0); } else { type = cb_tree_type (x, f); switch (type) { case COB_TYPE_GROUP: case COB_TYPE_ALPHANUMERIC: if (f->flag_justified) { id = lookup_attr (type, 0, 0, COB_FLAG_JUSTIFIED, NULL, 0); } else { id = lookup_attr (type, 0, 0, 0, NULL, 0); } break; default: if (f->pic->have_sign) { flags |= COB_FLAG_HAVE_SIGN; if (f->flag_sign_separate) { flags |= COB_FLAG_SIGN_SEPARATE; } if (f->flag_sign_leading) { flags |= COB_FLAG_SIGN_LEADING; } } if (f->flag_blank_zero) { flags |= COB_FLAG_BLANK_ZERO; } if (f->flag_justified) { flags |= COB_FLAG_JUSTIFIED; } if (f->flag_binary_swap) { flags |= COB_FLAG_BINARY_SWAP; } if (f->flag_real_binary) { flags |= COB_FLAG_REAL_BINARY; } if (f->flag_is_pointer) { flags |= COB_FLAG_IS_POINTER; } if (cb_binary_truncate && f->usage == CB_USAGE_BINARY && !f->flag_real_binary) { flags |= COB_FLAG_BINARY_TRUNC; } switch (f->usage) { case CB_USAGE_COMP_6: flags |= COB_FLAG_NO_SIGN_NIBBLE; break; case CB_USAGE_DOUBLE: case CB_USAGE_FLOAT: case CB_USAGE_LONG_DOUBLE: #if 0 /* RXWRXW - Floating ind */ case CB_USAGE_FP_BIN32: case CB_USAGE_FP_BIN64: case CB_USAGE_FP_BIN128: case CB_USAGE_FP_DEC64: case CB_USAGE_FP_DEC128: #endif flags |= COB_FLAG_IS_FP; break; default: break; } id = lookup_attr (type, f->pic->digits, f->pic->scale, flags, f->pic->str, f->pic->lenstr); break; } } break; case CB_TAG_ALPHABET_NAME: id = lookup_attr (COB_TYPE_ALPHANUMERIC, 0, 0, 0, NULL, 0); break; default: /* LCOV_EXCL_START */ cobc_err_msg (_("unexpected tree tag: %d"), (int)CB_TREE_TAG (x)); COBC_ABORT (); /* LCOV_EXCL_STOP */ } output ("&%s%d", CB_PREFIX_ATTR, id); } static void output_attributes (void) { struct attr_list *attr; if (!(attr_cache || gen_figurative)) { return; } output_storage ("\n/* Attributes */\n\n"); attr_cache = attr_list_reverse (attr_cache); for (attr = attr_cache; attr; attr = attr->next) { output_storage ("static const cob_field_attr %s%d =\t", CB_PREFIX_ATTR, attr->id); output_storage ("{0x%02x, %3u, %3d, 0x%04x, ", attr->type, attr->digits, attr->scale, attr->flags); if (attr->pic_id != -1) { output_storage ("%s%d", CB_PREFIX_PIC, attr->pic_id); } else { output_storage ("NULL"); } output_storage ("};\n"); } if (gen_figurative) { output_storage ("\nstatic const cob_field_attr cob_all_attr = "); output_storage ("{0x%02x, 0, 0, 0, NULL};\n", COB_TYPE_ALPHANUMERIC_ALL); } output_storage ("\n"); } /* GLOBAL EXTERNAL pointers */ static void output_globext_cache (void) { struct base_list *blp; if (!globext_cache) { return; } output_storage ("\n/* GLOBAL EXTERNAL pointers */\n"); globext_cache = list_cache_sort (globext_cache, &base_cache_cmp); for (blp = globext_cache; blp; blp = blp->next) { output_storage ("static unsigned char\t\t*%s%d = NULL;", CB_PREFIX_BASE, blp->f->id); output_storage ("\t/* %s */\n", blp->f->name); } } /* Headers */ static void output_standard_includes (void) { #if !defined (_GNU_SOURCE) && defined (_XOPEN_SOURCE_EXTENDED) output ("#ifndef\t_XOPEN_SOURCE_EXTENDED\n"); output ("#define\t_XOPEN_SOURCE_EXTENDED 1\n"); output ("#endif\n"); #endif output ("#include <stdio.h>\n"); output ("#include <stdlib.h>\n"); output ("#include <stddef.h>\n"); output ("#include <string.h>\n"); output ("#include <math.h>\n"); #ifdef WORDS_BIGENDIAN output ("#define WORDS_BIGENDIAN 1\n"); #endif #ifdef COB_KEYWORD_INLINE output ("#define COB_KEYWORD_INLINE %s\n", CB_XSTRINGIFY(COB_KEYWORD_INLINE)); #endif if (cb_flag_winmain) { output ("#include <windows.h>\n"); } output ("#include <libcob.h>\n\n"); } /* GnuCOBOL defines */ static void output_gnucobol_defines (const char *formatted_date, struct tm *local_time) { int i; output ("#define COB_SOURCE_FILE\t\t\"%s\"\n", cb_source_file); output ("#define COB_PACKAGE_VERSION\t\t\"%s\"\n", PACKAGE_VERSION); output ("#define COB_PATCH_LEVEL\t\t%d\n", PATCH_LEVEL); output ("#define COB_MODULE_FORMATTED_DATE\t\"%s\"\n", formatted_date); if (local_time) { i = ((local_time->tm_year + 1900) * 10000) + ((local_time->tm_mon + 1) * 100) + local_time->tm_mday; output ("#define COB_MODULE_DATE\t\t%d\n", i); i = (local_time->tm_hour * 10000) + (local_time->tm_min * 100) + local_time->tm_sec; output ("#define COB_MODULE_TIME\t\t%d\n", i); } else { output ("#define COB_MODULE_DATE\t\t0\n"); output ("#define COB_MODULE_TIME\t\t0\n"); } } /* CALL cache */ static void output_call_cache (void) { struct call_list *call; struct static_call_list *static_call; const char *convention_modifier; if (needs_unifunc || call_cache || func_call_cache) { output_local ("\n/* Call pointers */\n"); } if (needs_unifunc) { output_local ("cob_call_union\t\tcob_unifunc;\n"); } call_cache = call_list_reverse (call_cache); for (call = call_cache; call; call = call->next) { output_local ("static cob_call_union\tcall_%s;\n", call->call_name); } func_call_cache = call_list_reverse (func_call_cache); for (call = func_call_cache; call; call = call->next) { output_local ("static cob_call_union\tfunc_%s;\n", call->call_name); } if (static_call_cache) { static_call_cache = static_call_list_reverse (static_call_cache); output_local ("/* Define external subroutines being called statically */\n"); for (static_call = static_call_cache; static_call; static_call = static_call->next) { if (static_call->convention & CB_CONV_STDCALL) { convention_modifier = "__stdcall "; } else { convention_modifier = ""; } output_local ("#ifndef %s\n", static_call->call_name); if (static_call->return_type == COB_RETURN_NULL) { output_local ("extern void %s%s ();\n", convention_modifier, static_call->call_name); } else if (static_call->return_type == COB_RETURN_ADDRESS_OF) { output_local ("extern void * %s%s ();\n", convention_modifier, static_call->call_name); } else { output_local ("extern int %s%s ();\n", convention_modifier, static_call->call_name); } output_local ("#endif\n"); } } needs_unifunc = 0; } /* Nested CALL table */ static void output_nested_call_table (struct cb_program *prog) { struct nested_list *nlp; if (!(prog->nested_prog_list && gen_nested_tab)) { return; } /* Generate contained program list */ output_local ("\n/* Nested call table */\n"); output_local ("static struct cob_call_struct\tcob_nest_tab[] = {\n"); for (nlp = prog->nested_prog_list; nlp; nlp = nlp->next) { if (nlp->nested_prog == prog) { output_local ("\t{ \"%s\", { (void *(*)())%s_%d__ }, { NULL } },\n", nlp->nested_prog->orig_program_id, nlp->nested_prog->program_id, nlp->nested_prog->toplev_count); } else { output_local ("\t{ \"%s\", { (void *(*)())%s_%d__ }, { (void *(*)())%s_%d_ } },\n", nlp->nested_prog->orig_program_id, nlp->nested_prog->program_id, nlp->nested_prog->toplev_count, nlp->nested_prog->program_id, nlp->nested_prog->toplev_count); } } output_local ("\t{ NULL, { NULL }, { NULL } }\n"); output_local ("};\n"); } /* Local indexes */ static void output_local_indexes (void) { int i; int found = 0; for (i = 0; i < COB_MAX_SUBSCRIPTS; i++) { if (i_counters[i]) { if (!found) { found = 1; output_local ("\n/* Subscripts */\n"); } output_local ("int\t\ti%d;\n", i); } } } /* PERFORM TIMES counters */ static void output_perform_times_counters (void) { int i; if (loop_counter) { output_local ("\n/* Loop counters */\n"); for (i = 0; i < loop_counter; i++) { output_local ("cob_s64_t\tn%d = 0;\n", i); } output_local ("\n"); } } /* Local implicit fields */ static void output_local_implicit_fields (void) { int i; if (num_cob_fields) { output_local ("\n/* Local cob_field items */\n"); for (i = 0; i < num_cob_fields; i++) { output_local ("cob_field\t\tf%d;\n", i); } output_local ("\n"); } } /* DEBUGGING fields */ static void output_debugging_fields (struct cb_program *prog) { if (prog->flag_debugging) { output_local ("\n/* DEBUG runtime switch */\n"); output_local ("static int\tcob_debugging_mode = 0;\n"); } if (need_save_exception) { output_local ("\n/* DEBUG exception code save */\n"); output_local ("int\t\tsave_exception_code = 0;\n"); } } /* LOCAL-STORAGE pointer */ static void output_local_storage_pointer (struct cb_program *prog) { if (prog->local_storage && local_mem) { output_local ("\n/* LOCAL storage pointer */\n"); output_local ("unsigned char\t\t*cob_local_ptr = NULL;\n"); if (current_prog->flag_global_use) { output_local ("static unsigned char\t*cob_local_save = NULL;\n"); } } } /* CALL parameter stack */ static void output_call_parameter_stack_pointers (struct cb_program *prog) { output_local ("\n/* Call parameters */\n"); if (cb_flag_stack_on_heap || prog->flag_recursive) { output_local ("cob_field\t\t**cob_procedure_params;\n"); } else { output_local ("cob_field\t\t*cob_procedure_params[%u];\n", prog->max_call_param ? prog->max_call_param : 1); } } /* Frame stack */ static void output_frame_stack (struct cb_program *prog) { output_local ("\n/* Perform frame stack */\n"); if (cb_perform_osvs && current_prog->prog_type == CB_PROGRAM_TYPE) { output_local ("struct cob_frame\t*temp_index;\n"); } if (cb_flag_stack_check) { output_local ("struct cob_frame\t*frame_overflow;\n"); } output_local ("struct cob_frame\t*frame_ptr;\n"); if (cb_flag_stack_on_heap || prog->flag_recursive) { output_local ("struct cob_frame\t*frame_stack;\n\n"); } else { output_local ("struct cob_frame\tframe_stack[%d];\n\n", cb_stack_size); } } /* Dynamic field FUNCTION-ID pointers */ static void output_dynamic_field_function_id_pointers (void) { cob_u32_t i; if (gen_dynamic) { output_local ("\n/* Dynamic field FUNCTION-ID pointers */\n"); for (i = 0; i < gen_dynamic; i++) { output_local ("cob_field\t*cob_dyn_%u = NULL;\n", i); } } } /* Based data */ static void output_local_base_cache (void) { struct base_list *blp; if (!local_base_cache) { return; } output_local ("\n/* Data storage */\n"); local_base_cache = list_cache_sort (local_base_cache, &base_cache_cmp); for (blp = local_base_cache; blp; blp = blp->next) { if (blp->f->special_index == 2U) { output_local ("int %s%d;", CB_PREFIX_BASE, blp->f->id); } else if (blp->f->special_index) { output_local ("static int %s%d;", CB_PREFIX_BASE, blp->f->id); } else { output_local ("static cob_u8_t %s%d[%d]%s;", CB_PREFIX_BASE, blp->f->id, blp->f->memory_size, COB_ALIGN); } output_local ("\t/* %s */\n", blp->f->name); } output_local ("\n/* End of data storage */\n\n"); } static void output_nonlocal_base_cache (void) { struct base_list *blp; const char *prev_prog = NULL; if (!base_cache) { return; } output_storage ("\n/* Data storage */\n"); base_cache = list_cache_sort (base_cache, &base_cache_cmp); for (blp = base_cache; blp; blp = blp->next) { if (blp->curr_prog != prev_prog) { prev_prog = blp->curr_prog; output_storage ("\n/* PROGRAM-ID : %s */\n", prev_prog); } if (blp->f->special_index) { output_storage ("static int %s%d;", CB_PREFIX_BASE, blp->f->id); } else { output_storage ("static cob_u8_t %s%d[%d]%s;", CB_PREFIX_BASE, blp->f->id, blp->f->memory_size, COB_ALIGN); } output_storage ("\t/* %s */\n", blp->f->name); } output_storage ("\n/* End of data storage */\n\n"); } /* Fields */ static void output_field (cb_tree x) { output ("{"); output_size (x); output (", "); output_data (x); output (", "); output_attr (x); output ("}"); } static void output_local_field_cache (void) { struct field_list *field; if (!local_field_cache) { return; } /* Switch to local storage file */ output_target = current_prog->local_include->local_fp; output_local ("\n/* Fields */\n"); local_field_cache = list_cache_sort (local_field_cache, &field_cache_cmp); for (field = local_field_cache; field; field = field->next) { output ("static cob_field %s%d\t= ", CB_PREFIX_FIELD, field->f->id); if (!field->f->flag_local) { output_field (field->x); } else { output ("{"); output_size (field->x); output (", NULL, "); output_attr (field->x); output ("}"); } if (field->f->flag_filler) { output (";\t/* Implicit FILLER */\n"); } else { output (";\t/* %s */\n", field->f->name); } } output_local ("\n/* End of fields */\n\n"); /* Switch to main storage file */ output_target = cb_storage_file; } static void output_nonlocal_field_cache (void) { struct field_list *field; const char *prev_prog = NULL; if (!field_cache) { return; } output_storage ("\n/* Fields */\n"); field_cache = list_cache_sort (field_cache, &field_cache_cmp); for (field = field_cache; field; field = field->next) { if (field->curr_prog != prev_prog) { prev_prog = field->curr_prog; output_storage ("\n/* PROGRAM-ID : %s */\n", prev_prog); } output ("static cob_field %s%d\t= ", CB_PREFIX_FIELD, field->f->id); if (!field->f->flag_local) { output_field (field->x); } else { output ("{"); output_size (field->x); output (", NULL, "); output_attr (field->x); output ("}"); } if (field->f->flag_filler) { output (";\t/* Implicit FILLER */\n"); } else { output (";\t/* %s */\n", field->f->name); } } output_storage ("\n/* End of fields */\n\n"); } /* Literals, figurative constants and user-defined constants */ static void output_low_value (void) { if (gen_figurative & CB_NEED_LOW) { output ("static cob_field cob_all_low\t= "); output ("{1, "); output ("(cob_u8_ptr)\"\\0\", "); output ("&cob_all_attr};\n"); } } static void output_high_value (void) { if (gen_figurative & CB_NEED_HIGH) { output ("static cob_field cob_all_high\t= "); output ("{1, "); output ("(cob_u8_ptr)\"\\xff\", "); output ("&cob_all_attr};\n"); } } static void output_quote (void) { if (gen_figurative & CB_NEED_QUOTE) { output ("static cob_field cob_all_quote\t= "); output ("{1, "); if (cb_flag_apostrophe) { output ("(cob_u8_ptr)\"'\", "); } else { output ("(cob_u8_ptr)\"\\\"\", "); } output ("&cob_all_attr};\n"); } } static void output_space (void) { if (gen_figurative & CB_NEED_SPACE) { output ("static cob_field cob_all_space\t= "); output ("{1, "); output ("(cob_u8_ptr)\" \", "); output ("&cob_all_attr};\n"); } } static void output_zero (void) { if (gen_figurative & CB_NEED_ZERO) { output ("static cob_field cob_all_zero\t= "); output ("{1, "); output ("(cob_u8_ptr)\"0\", "); output ("&cob_all_attr};\n"); } } static void output_literals_figuratives_and_constants (void) { struct literal_list *lit; if (!(literal_cache || gen_figurative)) { return; } output_storage ("\n/* Constants */\n"); literal_cache = literal_list_reverse (literal_cache); for (lit = literal_cache; lit; lit = lit->next) { #if 0 /* RXWRXW - Const */ output ("static const cob_fld_union %s%d\t= ", CB_PREFIX_CONST, lit->id); output ("{"); output_size (lit->x); output (", "); lp = CB_LITERAL (lit->x); if (CB_TREE_CLASS (lit->x) == CB_CLASS_NUMERIC) { output ("\"%s%s\"", (char *)lp->data, (lp->sign < 0) ? "-" : (lp->sign > 0) ? "+" : ""); } else { output_string (lp->data, (int) lp->size, lp->llit); } output (", "); output_attr (lit->x); output ("}"); #else output ("static const cob_field %s%d\t= ", CB_PREFIX_CONST, lit->id); output_field (lit->x); #endif output (";\n"); } if (gen_figurative) { output ("\n"); output_low_value (); output_high_value (); output_quote (); output_space (); output_zero (); } output ("\n"); } /* Collating tables */ static void output_alt_ebcdic_table (void) { if (!gen_alt_ebcdic) { return; } output_storage ("\n/* ASCII to EBCDIC translate table (restricted) */\n"); output ("static const unsigned char\tcob_a2e[256] = {\n"); /* Restricted table */ output ("\t0x00, 0x01, 0x02, 0x03, 0x1D, 0x19, 0x1A, 0x1B,\n"); output ("\t0x0F, 0x04, 0x16, 0x06, 0x07, 0x08, 0x09, 0x0A,\n"); output ("\t0x0B, 0x0C, 0x0D, 0x0E, 0x1E, 0x1F, 0x1C, 0x17,\n"); output ("\t0x10, 0x11, 0x20, 0x18, 0x12, 0x13, 0x14, 0x15,\n"); output ("\t0x21, 0x27, 0x3A, 0x36, 0x28, 0x30, 0x26, 0x38,\n"); output ("\t0x24, 0x2A, 0x29, 0x25, 0x2F, 0x2C, 0x22, 0x2D,\n"); output ("\t0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A,\n"); output ("\t0x7B, 0x7C, 0x35, 0x2B, 0x23, 0x39, 0x32, 0x33,\n"); output ("\t0x37, 0x57, 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D,\n"); output ("\t0x5E, 0x5F, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66,\n"); output ("\t0x67, 0x68, 0x69, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F,\n"); output ("\t0x70, 0x71, 0x72, 0x7D, 0x6A, 0x7E, 0x7F, 0x31,\n"); output ("\t0x34, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41,\n"); output ("\t0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,\n"); output ("\t0x4A, 0x4B, 0x4C, 0x4E, 0x4F, 0x50, 0x51, 0x52,\n"); output ("\t0x53, 0x54, 0x55, 0x56, 0x2E, 0x60, 0x4D, 0x05,\n"); output ("\t0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,\n"); output ("\t0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F,\n"); output ("\t0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,\n"); output ("\t0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F,\n"); output ("\t0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7,\n"); output ("\t0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF,\n"); output ("\t0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7,\n"); output ("\t0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBF,\n"); output ("\t0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7,\n"); output ("\t0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF,\n"); output ("\t0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7,\n"); output ("\t0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF,\n"); output ("\t0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7,\n"); output ("\t0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF,\n"); output ("\t0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7,\n"); output ("\t0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF\n"); output ("};\n"); output_storage ("\n"); } static void output_full_ebcdic_table (void) { int i; if (!gen_full_ebcdic) { return; } output_storage ("\n/* ASCII to EBCDIC table */\n"); output ("static const unsigned char\tcob_ascii_ebcdic[256] = {\n"); output ("\t0x00, 0x01, 0x02, 0x03, 0x37, 0x2D, 0x2E, 0x2F,\n"); output ("\t0x16, 0x05, 0x25, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,\n"); output ("\t0x10, 0x11, 0x12, 0x13, 0x3C, 0x3D, 0x32, 0x26,\n"); output ("\t0x18, 0x19, 0x3F, 0x27, 0x1C, 0x1D, 0x1E, 0x1F,\n"); output ("\t0x40, 0x5A, 0x7F, 0x7B, 0x5B, 0x6C, 0x50, 0x7D,\n"); output ("\t0x4D, 0x5D, 0x5C, 0x4E, 0x6B, 0x60, 0x4B, 0x61,\n"); output ("\t0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7,\n"); output ("\t0xF8, 0xF9, 0x7A, 0x5E, 0x4C, 0x7E, 0x6E, 0x6F,\n"); output ("\t0x7C, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7,\n"); output ("\t0xC8, 0xC9, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6,\n"); output ("\t0xD7, 0xD8, 0xD9, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6,\n"); output ("\t0xE7, 0xE8, 0xE9, 0xAD, 0xE0, 0xBD, 0x5F, 0x6D,\n"); output ("\t0x79, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,\n"); output ("\t0x88, 0x89, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96,\n"); output ("\t0x97, 0x98, 0x99, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6,\n"); output ("\t0xA7, 0xA8, 0xA9, 0xC0, 0x6A, 0xD0, 0xA1, 0x07,\n"); output ("\t0x68, 0xDC, 0x51, 0x42, 0x43, 0x44, 0x47, 0x48,\n"); output ("\t0x52, 0x53, 0x54, 0x57, 0x56, 0x58, 0x63, 0x67,\n"); output ("\t0x71, 0x9C, 0x9E, 0xCB, 0xCC, 0xCD, 0xDB, 0xDD,\n"); output ("\t0xDF, 0xEC, 0xFC, 0xB0, 0xB1, 0xB2, 0x3E, 0xB4,\n"); output ("\t0x45, 0x55, 0xCE, 0xDE, 0x49, 0x69, 0x9A, 0x9B,\n"); output ("\t0xAB, 0x9F, 0xBA, 0xB8, 0xB7, 0xAA, 0x8A, 0x8B,\n"); output ("\t0xB6, 0xB5, 0x62, 0x4F, 0x64, 0x65, 0x66, 0x20,\n"); output ("\t0x21, 0x22, 0x70, 0x23, 0x72, 0x73, 0x74, 0xBE,\n"); output ("\t0x76, 0x77, 0x78, 0x80, 0x24, 0x15, 0x8C, 0x8D,\n"); output ("\t0x8E, 0x41, 0x06, 0x17, 0x28, 0x29, 0x9D, 0x2A,\n"); output ("\t0x2B, 0x2C, 0x09, 0x0A, 0xAC, 0x4A, 0xAE, 0xAF,\n"); output ("\t0x1B, 0x30, 0x31, 0xFA, 0x1A, 0x33, 0x34, 0x35,\n"); output ("\t0x36, 0x59, 0x08, 0x38, 0xBC, 0x39, 0xA0, 0xBF,\n"); output ("\t0xCA, 0x3A, 0xFE, 0x3B, 0x04, 0xCF, 0xDA, 0x14,\n"); output ("\t0xE1, 0x8F, 0x46, 0x75, 0xFD, 0xEB, 0xEE, 0xED,\n"); output ("\t0x90, 0xEF, 0xB3, 0xFB, 0xB9, 0xEA, 0xBB, 0xFF\n"); output ("};\n"); if (gen_full_ebcdic > 1) { i = lookup_attr (COB_TYPE_ALPHANUMERIC, 0, 0, 0, NULL, 0); output ("static cob_field f_ascii_ebcdic = { 256, (cob_u8_ptr)cob_ascii_ebcdic, &%s%d };\n", CB_PREFIX_ATTR, i); } output_storage ("\n"); } static void output_ebcdic_to_ascii_table (void) { int i; if (!gen_ebcdic_ascii) { return; } output_storage ("\n/* EBCDIC to ASCII table */\n"); output ("static const unsigned char\tcob_ebcdic_ascii[256] = {\n"); output ("\t0x00, 0x01, 0x02, 0x03, 0xEC, 0x09, 0xCA, 0x7F,\n"); output ("\t0xE2, 0xD2, 0xD3, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,\n"); output ("\t0x10, 0x11, 0x12, 0x13, 0xEF, 0xC5, 0x08, 0xCB,\n"); output ("\t0x18, 0x19, 0xDC, 0xD8, 0x1C, 0x1D, 0x1E, 0x1F,\n"); output ("\t0xB7, 0xB8, 0xB9, 0xBB, 0xC4, 0x0A, 0x17, 0x1B,\n"); output ("\t0xCC, 0xCD, 0xCF, 0xD0, 0xD1, 0x05, 0x06, 0x07,\n"); output ("\t0xD9, 0xDA, 0x16, 0xDD, 0xDE, 0xDF, 0xE0, 0x04,\n"); output ("\t0xE3, 0xE5, 0xE9, 0xEB, 0x14, 0x15, 0x9E, 0x1A,\n"); output ("\t0x20, 0xC9, 0x83, 0x84, 0x85, 0xA0, 0xF2, 0x86,\n"); output ("\t0x87, 0xA4, 0xD5, 0x2E, 0x3C, 0x28, 0x2B, 0xB3,\n"); output ("\t0x26, 0x82, 0x88, 0x89, 0x8A, 0xA1, 0x8C, 0x8B,\n"); output ("\t0x8D, 0xE1, 0x21, 0x24, 0x2A, 0x29, 0x3B, 0x5E,\n"); output ("\t0x2D, 0x2F, 0xB2, 0x8E, 0xB4, 0xB5, 0xB6, 0x8F,\n"); output ("\t0x80, 0xA5, 0x7C, 0x2C, 0x25, 0x5F, 0x3E, 0x3F,\n"); output ("\t0xBA, 0x90, 0xBC, 0xBD, 0xBE, 0xF3, 0xC0, 0xC1,\n"); output ("\t0xC2, 0x60, 0x3A, 0x23, 0x40, 0x27, 0x3D, 0x22,\n"); output ("\t0xC3, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,\n"); output ("\t0x68, 0x69, 0xAE, 0xAF, 0xC6, 0xC7, 0xC8, 0xF1,\n"); output ("\t0xF8, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70,\n"); output ("\t0x71, 0x72, 0xA6, 0xA7, 0x91, 0xCE, 0x92, 0xA9,\n"); output ("\t0xE6, 0x7E, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,\n"); output ("\t0x79, 0x7A, 0xAD, 0xA8, 0xD4, 0x5B, 0xD6, 0xD7,\n"); output ("\t0x9B, 0x9C, 0x9D, 0xFA, 0x9F, 0xB1, 0xB0, 0xAC,\n"); output ("\t0xAB, 0xFC, 0xAA, 0xFE, 0xE4, 0x5D, 0xBF, 0xE7,\n"); output ("\t0x7B, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,\n"); output ("\t0x48, 0x49, 0xE8, 0x93, 0x94, 0x95, 0xA2, 0xED,\n"); output ("\t0x7D, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50,\n"); output ("\t0x51, 0x52, 0xEE, 0x96, 0x81, 0x97, 0xA3, 0x98,\n"); output ("\t0x5C, 0xF0, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,\n"); output ("\t0x59, 0x5A, 0xFD, 0xF5, 0x99, 0xF7, 0xF6, 0xF9,\n"); output ("\t0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,\n"); output ("\t0x38, 0x39, 0xDB, 0xFB, 0x9A, 0xF4, 0xEA, 0xFF\n"); output ("};\n"); if (gen_ebcdic_ascii > 1) { i = lookup_attr (COB_TYPE_ALPHANUMERIC, 0, 0, 0, NULL, 0); output ("static cob_field f_ebcdic_ascii = { 256, (cob_u8_ptr)cob_ebcdic_ascii, &%s%d };\n", CB_PREFIX_ATTR, i); } output_storage ("\n"); } static void output_native_table (void) { int i; if (!gen_native) { return; } output_storage ("\n/* NATIVE table */\n"); output ("static const unsigned char\tcob_native[256] = {\n"); output ("\t0, 1, 2, 3, 4, 5, 6, 7,\n"); output ("\t8, 9, 10, 11, 12, 13, 14, 15,\n"); output ("\t16, 17, 18, 19, 20, 21, 22, 23,\n"); output ("\t24, 25, 26, 27, 28, 29, 30, 31,\n"); output ("\t32, 33, 34, 35, 36, 37, 38, 39,\n"); output ("\t40, 41, 42, 43, 44, 45, 46, 47,\n"); output ("\t48, 49, 50, 51, 52, 53, 54, 55,\n"); output ("\t56, 57, 58, 59, 60, 61, 62, 63,\n"); output ("\t64, 65, 66, 67, 68, 69, 70, 71,\n"); output ("\t72, 73, 74, 75, 76, 77, 78, 79,\n"); output ("\t80, 81, 82, 83, 84, 85, 86, 87,\n"); output ("\t88, 89, 90, 91, 92, 93, 94, 95,\n"); output ("\t96, 97, 98, 99, 100, 101, 102, 103,\n"); output ("\t104, 105, 106, 107, 108, 109, 110, 111,\n"); output ("\t112, 113, 114, 115, 116, 117, 118, 119,\n"); output ("\t120, 121, 122, 123, 124, 125, 126, 127,\n"); output ("\t128, 129, 130, 131, 132, 133, 134, 135,\n"); output ("\t136, 137, 138, 139, 140, 141, 142, 143,\n"); output ("\t144, 145, 146, 147, 148, 149, 150, 151,\n"); output ("\t152, 153, 154, 155, 156, 157, 158, 159,\n"); output ("\t160, 161, 162, 163, 164, 165, 166, 167,\n"); output ("\t168, 169, 170, 171, 172, 173, 174, 175,\n"); output ("\t176, 177, 178, 179, 180, 181, 182, 183,\n"); output ("\t184, 185, 186, 187, 188, 189, 190, 191,\n"); output ("\t192, 193, 194, 195, 196, 197, 198, 199,\n"); output ("\t200, 201, 202, 203, 204, 205, 206, 207,\n"); output ("\t208, 209, 210, 211, 212, 213, 214, 215,\n"); output ("\t216, 217, 218, 219, 220, 221, 222, 223,\n"); output ("\t224, 225, 226, 227, 228, 229, 230, 231,\n"); output ("\t232, 233, 234, 235, 236, 237, 238, 239,\n"); output ("\t240, 241, 242, 243, 244, 245, 246, 247,\n"); output ("\t248, 249, 250, 251, 252, 253, 254, 255\n"); output ("};\n"); if (gen_native > 1) { i = lookup_attr (COB_TYPE_ALPHANUMERIC, 0, 0, 0, NULL, 0); output ("static cob_field f_native = { 256, (cob_u8_ptr)cob_native, &%s%d };\n", CB_PREFIX_ATTR, i); } output_storage ("\n"); } static void output_collating_tables (void) { output_alt_ebcdic_table (); output_full_ebcdic_table (); output_ebcdic_to_ascii_table (); output_native_table (); } /* Strings */ static void output_string_cache (void) { struct string_list *stp; if (!string_cache) { return; } output_storage ("\n/* Strings */\n"); string_cache = string_list_reverse (string_cache); for (stp = string_cache; stp; stp = stp->next) { output ("static const char %s%d[]\t= \"%s\";\n", CB_PREFIX_STRING, stp->id, stp->text); } output_storage ("\n"); } static char * user_func_upper (const char *func) { unsigned char *s; char *rets; rets = cb_encode_program_id (func); for (s = (unsigned char *)rets; *s; s++) { if (islower ((int)*s)) { *s = (cob_u8_t)toupper ((int)*s); } } return rets; } /* Literal */ int cb_lookup_literal (cb_tree x, int make_decimal) { struct cb_literal *literal; struct literal_list *l; FILE *savetarget; literal = CB_LITERAL (x); /* Search literal cache */ for (l = literal_cache; l; l = l->next) { if (CB_TREE_CLASS (literal) == CB_TREE_CLASS (l->literal) && literal->size == l->literal->size && literal->all == l->literal->all && literal->sign == l->literal->sign && literal->scale == l->literal->scale && memcmp (literal->data, l->literal->data, (size_t)literal->size) == 0) { if(make_decimal) l->make_decimal = 1; return l->id; } } /* Output new literal */ savetarget = output_target; output_target = NULL; output_field (x); output_target = savetarget; /* Cache it */ l = cobc_parse_malloc (sizeof (struct literal_list)); l->id = cb_literal_id; l->literal = literal; l->make_decimal = make_decimal; l->x = x; l->next = literal_cache; literal_cache = l; return cb_literal_id++; } /* Integer */ static void output_integer (cb_tree x) { struct cb_binary_op *p; struct cb_cast *cp; struct cb_field *f; switch (CB_TREE_TAG (x)) { case CB_TAG_CONST: if (x == cb_zero) { output ("0"); } else if (x == cb_null) { output ("(cob_u8_ptr)NULL"); } else { output ("%s", CB_CONST (x)->val); } break; case CB_TAG_INTEGER: if (CB_INTEGER (x)->hexval) { output ("0x%X", CB_INTEGER (x)->val); } else { output ("%d", CB_INTEGER (x)->val); } break; case CB_TAG_LITERAL: output ("%d", cb_get_int (x)); break; case CB_TAG_BINARY_OP: p = CB_BINARY_OP (x); if (p->flag) { if (!cb_fits_int (p->x) || !cb_fits_int (p->y)) { output ("cob_get_int ("); output_param (x, -1); output (")"); break; } } if (p->op == '^') { output ("(int) pow ("); output_integer (p->x); output (", "); output_integer (p->y); output (")"); } else { output ("("); output_integer (p->x); output (" %c ", p->op); output_integer (p->y); output (")"); } break; case CB_TAG_CAST: cp = CB_CAST (x); switch (cp->cast_type) { case CB_CAST_ADDRESS: output ("("); output_data (cp->val); output (")"); break; case CB_CAST_PROGRAM_POINTER: output ("cob_call_field ("); output_param (x, -1); if (current_prog->nested_prog_list) { gen_nested_tab = 1; output (", cob_nest_tab, 0, %d)", cb_fold_call); } else { output (", NULL, 0, %d)", cb_fold_call); } break; default: /* LCOV_EXCL_START */ cobc_err_msg (_("unexpected cast type: %d"), (int)cp->cast_type); COBC_ABORT (); /* LCOV_EXCL_STOP */ } break; case CB_TAG_REFERENCE: f = cb_code_field (x); switch (f->usage) { case CB_USAGE_INDEX: if (f->special_index) { output_base (f, 1U); output ("%s%d", CB_PREFIX_BASE, f->id); return; } /* Fall through */ case CB_USAGE_HNDL: case CB_USAGE_HNDL_WINDOW: case CB_USAGE_HNDL_SUBWINDOW: case CB_USAGE_HNDL_FONT: case CB_USAGE_HNDL_THREAD: case CB_USAGE_HNDL_MENU: case CB_USAGE_HNDL_VARIANT: case CB_USAGE_HNDL_LM: case CB_USAGE_LENGTH: output ("(*(int *) ("); output_data (x); output ("))"); return; case CB_USAGE_POINTER: case CB_USAGE_PROGRAM_POINTER: #ifdef COB_NON_ALIGNED output ("(cob_get_pointer ("); output_data (x); output ("))"); #else output ("(*(unsigned char **) ("); output_data (x); output ("))"); #endif return; case CB_USAGE_DISPLAY: if (f->pic && f->pic->scale >= 0 && f->size - f->pic->scale > 0 && f->size - f->pic->scale <= 9 && f->pic->have_sign == 0 && !cb_ebcdic_sign) { optimize_defs[COB_GET_NUMDISP] = 1; output ("cob_get_numdisp ("); output_data (x); output (", %d)", f->size - f->pic->scale); return; } break; case CB_USAGE_PACKED: if (f->pic->scale == 0 && f->pic->digits < 10) { optimize_defs[COB_GET_PACKED_INT] = 1; output_func_1 ("cob_get_packed_int", x); return; } break; case CB_USAGE_BINARY: case CB_USAGE_COMP_5: case CB_USAGE_COMP_X: if (f->size == 1) { output ("(*("); if (!f->pic->have_sign) { output ("cob_u8_ptr) ("); } else { output ("cob_s8_ptr) ("); } output_data (x); output ("))"); return; } #ifdef COB_NON_ALIGNED if (f->storage != CB_STORAGE_LINKAGE && f->indexes == 0 && ( #ifdef COB_SHORT_BORK (f->size == 2 && (f->offset % 4 == 0)) || #else (f->size == 2 && (f->offset % 2 == 0)) || #endif (f->size == 4 && (f->offset % 4 == 0)) || (f->size == 8 && (f->offset % 8 == 0)))) { #else if (f->size == 2 || f->size == 4 || f->size == 8) { #endif if (f->flag_binary_swap) { output ("(("); switch (f->size) { case 2: if (!f->pic->have_sign) { output ("unsigned short)COB_BSWAP_16("); } else { output ("short)COB_BSWAP_16("); } break; case 4: if (!f->pic->have_sign) { output ("unsigned int)COB_BSWAP_32("); } else { output ("int)COB_BSWAP_32("); } break; case 8: if (!f->pic->have_sign) { output ("cob_u64_t)COB_BSWAP_64("); } else { output ("cob_s64_t)COB_BSWAP_64("); } break; default: break; } output ("*("); switch (f->size) { case 2: output ("short *)("); break; case 4: output ("int *)("); break; case 8: output ("cob_s64_t *)("); break; default: break; } output_data (x); output (")))"); return; } else { output ("(*("); switch (f->size) { case 2: if (!f->pic->have_sign) { output ("unsigned short *)("); } else { output ("short *)("); } break; case 4: if (!f->pic->have_sign) { output ("unsigned int *)("); } else { output ("int *)("); } break; case 8: if (!f->pic->have_sign) { output ("cob_u64_ptr)("); } else { output ("cob_s64_ptr)("); } break; default: break; } output_data (x); output ("))"); return; } } if (f->pic->have_sign == 0) { output ("(unsigned int)"); } break; default: break; } output_func_1 ("cob_get_int", x); break; case CB_TAG_INTRINSIC: output ("cob_get_int ("); output_param (x, -1); output (")"); break; default: /* LCOV_EXCL_START */ cobc_err_msg (_("unexpected tree tag: %d"), (int)CB_TREE_TAG (x)); COBC_ABORT (); /* LCOV_EXCL_STOP */ } } #if 0 } #endif static void output_long_integer (cb_tree x) { struct cb_binary_op *p; struct cb_cast *cp; struct cb_field *f; switch (CB_TREE_TAG (x)) { case CB_TAG_CONST: if (x == cb_zero) { output ("0"); } else if (x == cb_null) { output ("(cob_u8_ptr)NULL"); } else { output ("%s", CB_CONST (x)->val); } break; case CB_TAG_INTEGER: if (CB_INTEGER (x)->hexval) { output ("0x%X", CB_INTEGER (x)->val); } else { output ("%d", CB_INTEGER (x)->val); } break; case CB_TAG_LITERAL: output (CB_FMT_LLD_F, cb_get_long_long (x)); break; case CB_TAG_BINARY_OP: p = CB_BINARY_OP (x); if (p->flag) { if (!cb_fits_long_long (p->x) || !cb_fits_long_long (p->y)) { output ("cob_get_llint ("); output_param (x, -1); output (")"); break; } } if (p->op == '^') { output ("(cob_s64_t) pow ("); output_long_integer (p->x); output (", "); output_long_integer (p->y); output (")"); } else { output ("("); output_long_integer (p->x); output (" %c ", p->op); output_long_integer (p->y); output (")"); } break; case CB_TAG_CAST: cp = CB_CAST (x); switch (cp->cast_type) { case CB_CAST_ADDRESS: output ("("); output_data (cp->val); output (")"); break; case CB_CAST_PROGRAM_POINTER: output ("cob_call_field ("); output_param (x, -1); if (current_prog->nested_prog_list) { gen_nested_tab = 1; output (", cob_nest_tab, 0, %d)", cb_fold_call); } else { output (", NULL, 0, %d)", cb_fold_call); } break; default: /* LCOV_EXCL_START */ cobc_err_msg (_("unexpected cast type: %d"), (int)cp->cast_type); COBC_ABORT (); /* LCOV_EXCL_STOP */ } break; case CB_TAG_REFERENCE: f = cb_code_field (x); switch (f->usage) { case CB_USAGE_INDEX: if (f->special_index) { output_base (f, 1U); output ("(cob_s64_t)%s%d", CB_PREFIX_BASE, f->id); return; } /* Fall through */ case CB_USAGE_HNDL: case CB_USAGE_HNDL_WINDOW: case CB_USAGE_HNDL_SUBWINDOW: case CB_USAGE_HNDL_FONT: case CB_USAGE_HNDL_THREAD: case CB_USAGE_HNDL_MENU: case CB_USAGE_HNDL_VARIANT: case CB_USAGE_HNDL_LM: case CB_USAGE_LENGTH: output ("(cob_s64_t)(*(int *) ("); output_data (x); output ("))"); return; case CB_USAGE_POINTER: case CB_USAGE_PROGRAM_POINTER: #ifdef COB_NON_ALIGNED output ("(cob_get_pointer ("); output_data (x); output ("))"); #else output ("(*(unsigned char **) ("); output_data (x); output ("))"); #endif return; case CB_USAGE_BINARY: case CB_USAGE_COMP_5: case CB_USAGE_COMP_X: if (f->size == 1) { output ("(*("); if (!f->pic->have_sign) { output ("cob_u8_ptr) ("); } else { output ("cob_s8_ptr) ("); } output_data (x); output ("))"); return; } #ifdef COB_NON_ALIGNED if (f->storage != CB_STORAGE_LINKAGE && f->indexes == 0 && ( #ifdef COB_SHORT_BORK (f->size == 2 && (f->offset % 4 == 0)) || #else (f->size == 2 && (f->offset % 2 == 0)) || #endif (f->size == 4 && (f->offset % 4 == 0)) || (f->size == 8 && (f->offset % 8 == 0)))) { #else if (f->size == 2 || f->size == 4 || f->size == 8) { #endif if (f->flag_binary_swap) { output ("(("); switch (f->size) { case 2: if (!f->pic->have_sign) { output ("unsigned short)COB_BSWAP_16("); } else { output ("short)COB_BSWAP_16("); } break; case 4: if (!f->pic->have_sign) { output ("unsigned int)COB_BSWAP_32("); } else { output ("int)COB_BSWAP_32("); } break; case 8: if (!f->pic->have_sign) { output ("cob_u64_t)COB_BSWAP_64("); } else { output ("cob_s64_t)COB_BSWAP_64("); } break; default: break; } output ("*("); switch (f->size) { case 2: output ("short *)("); break; case 4: output ("int *)("); break; case 8: output ("cob_s64_t *)("); break; default: break; } output_data (x); output (")))"); return; } else { output ("(*("); switch (f->size) { case 2: if (!f->pic->have_sign) { output ("unsigned short *)("); } else { output ("short *)("); } break; case 4: if (!f->pic->have_sign) { output ("unsigned int *)("); } else { output ("int *)("); } break; case 8: if (!f->pic->have_sign) { output ("cob_u64_ptr)("); } else { output ("cob_s64_ptr)("); } break; default: break; } output_data (x); output ("))"); return; } } #if 0 /* RXWRXW - unsigned */ if (f->pic->have_sign == 0) { output ("(unsigned int)"); } #endif break; default: break; } output_func_1 ("cob_get_llint", x); break; case CB_TAG_INTRINSIC: output ("cob_get_llint ("); output_param (x, -1); output (")"); break; default: /* LCOV_EXCL_START */ cobc_err_msg (_("unexpected tree tag: %d"), (int)CB_TREE_TAG (x)); COBC_ABORT (); /* LCOV_EXCL_STOP */ } } static void output_index (cb_tree x) { struct cb_field *f; switch (CB_TREE_TAG (x)) { case CB_TAG_INTEGER: output ("%d", CB_INTEGER (x)->val - 1); break; case CB_TAG_LITERAL: output ("%d", cb_get_int (x) - 1); break; default: output ("("); if(CB_TREE_TAG (x) == CB_TAG_REFERENCE) { f = cb_code_field (x); if(f->pic && f->pic->have_sign == 0) { /* Avoid ((unsigned int)(0 - 1)) */ f->pic->have_sign = 1; /* Handle subscript as signed */ output_integer (x); f->pic->have_sign = 0; /* Restore to unsigned */ } else { output_integer (x); } } else { output_integer (x); } output (" - 1)"); break; } } /* Parameter */ static void output_param (cb_tree x, int id) { struct cb_reference *r; struct cb_field *f; struct cb_field *ff; struct cb_cast *cp; struct cb_binary_op *bp; struct field_list *fl; FILE *savetarget; struct cb_intrinsic *ip; struct cb_alphabet_name *abp; struct cb_alphabet_name *rbp; cb_tree l; char *func; int n; int sav_stack_id; char fname[12]; param_id = id; if (x == NULL) { output ("NULL"); return; } switch (CB_TREE_TAG (x)) { case CB_TAG_CONST: if (x == cb_quote) { gen_figurative |= CB_NEED_QUOTE; } else if (x == cb_norm_low) { gen_figurative |= CB_NEED_LOW; } else if (x == cb_norm_high) { gen_figurative |= CB_NEED_HIGH; } else if (x == cb_space) { gen_figurative |= CB_NEED_SPACE; } else if (x == cb_zero) { gen_figurative |= CB_NEED_ZERO; } output ("%s", CB_CONST (x)->val); break; case CB_TAG_INTEGER: output_integer (x); break; case CB_TAG_STRING: output_string (CB_STRING (x)->data, (int) CB_STRING (x)->size, 0); break; case CB_TAG_LOCALE_NAME: output_param (CB_LOCALE_NAME(x)->list, id); break; case CB_TAG_ALPHABET_NAME: abp = CB_ALPHABET_NAME (x); switch (abp->alphabet_type) { case CB_ALPHABET_ASCII: #ifdef COB_EBCDIC_MACHINE gen_ebcdic_ascii = 1; output ("cob_ebcdic_ascii"); break; #endif /* Fall through for ASCII */ case CB_ALPHABET_NATIVE: if (current_prog->collating_sequence) { gen_native = 1; output ("cob_native"); } else { output ("NULL"); } break; case CB_ALPHABET_EBCDIC: #ifdef COB_EBCDIC_MACHINE if (current_prog->collating_sequence) { gen_native = 1; output ("cob_native"); } else { output ("NULL"); } #else if (cb_flag_alt_ebcdic) { gen_alt_ebcdic = 1; output ("cob_a2e"); } else { gen_full_ebcdic = 1; output ("cob_ascii_ebcdic"); } #endif break; case CB_ALPHABET_CUSTOM: gen_custom = 1; output ("%s%s", CB_PREFIX_SEQUENCE, abp->cname); break; default: break; } break; case CB_TAG_CAST: cp = CB_CAST (x); switch (cp->cast_type) { case CB_CAST_INTEGER: output_integer (cp->val); break; case CB_CAST_LONG_INT: output_long_integer (cp->val); break; case CB_CAST_ADDRESS: output_data (cp->val); break; case CB_CAST_ADDR_OF_ADDR: output ("&"); output_data (cp->val); break; case CB_CAST_LENGTH: output_size (cp->val); break; case CB_CAST_PROGRAM_POINTER: output_param (cp->val, id); break; default: break; } break; case CB_TAG_DECIMAL: output ("d%d", CB_DECIMAL (x)->id); break; case CB_TAG_DECIMAL_LITERAL: output ("%s%d", CB_PREFIX_DEC_CONST, CB_DECIMAL_LITERAL (x)->id); break; case CB_TAG_FILE: output ("%s%s", CB_PREFIX_FILE, CB_FILE (x)->cname); break; case CB_TAG_LITERAL: if (nolitcast) { output ("&%s%d", CB_PREFIX_CONST, cb_lookup_literal (x, 0)); } else { output ("(cob_field *)&%s%d", CB_PREFIX_CONST, cb_lookup_literal (x, 0)); } break; case CB_TAG_FIELD: /* TODO: remove me */ output_param (cb_build_field_reference (CB_FIELD (x), NULL), id); break; case CB_TAG_REFERENCE: r = CB_REFERENCE (x); if (CB_LOCALE_NAME_P (r->value)) { output_param (CB_LOCALE_NAME(r->value)->list, id); break; } if (r->check) { inside_stack[inside_check++] = 0; /* LCOV_EXCL_START */ if (inside_check >= COB_INSIDE_SIZE) { cobc_err_msg (_("internal statement stack depth exceeded: %d"), COB_INSIDE_SIZE); COBC_ABORT (); } /* LCOV_EXCL_STOP */ output ("\n"); output_prefix (); output ("("); n = output_indent_level; output_indent_level = 0; for (l = r->check; l; l = CB_CHAIN (l)) { sav_stack_id = stack_id; output_stmt (CB_VALUE (l)); stack_id = sav_stack_id; if (l == r->check) { output_indent_level = n; } } } if (CB_FILE_P (r->value)) { output ("%s%s", CB_PREFIX_FILE, CB_FILE (r->value)->cname); if (r->check) { if (inside_check) { --inside_check; } output (" )"); } break; } if (CB_ALPHABET_NAME_P (r->value)) { rbp = CB_ALPHABET_NAME (r->value); switch (rbp->alphabet_type) { case CB_ALPHABET_ASCII: #ifdef COB_EBCDIC_MACHINE gen_ebcdic_ascii = 2; output ("&f_ebcdic_ascii"); break; #endif /* Fall through for ASCII */ case CB_ALPHABET_NATIVE: gen_native = 2; output ("&f_native"); break; case CB_ALPHABET_EBCDIC: #ifdef COB_EBCDIC_MACHINE gen_native = 2; output ("&f_native"); #else gen_full_ebcdic = 2; output ("&f_ascii_ebcdic"); #endif break; case CB_ALPHABET_CUSTOM: gen_custom = 1; output ("&%s%s", CB_PREFIX_FIELD, rbp->cname); break; default: break; } if (r->check) { if (inside_check) { --inside_check; } output (" )"); } break; } if (!CB_FIELD_P (r->value)) { /* LCOV_EXCL_START */ cobc_err_msg (_("call to '%s' with invalid parameter '%s'"), "output_param", "x"); cobc_err_msg (_("%s is not a field"), r->word->name); cobc_err_msg (_("Please report this!")); COBC_ABORT (); /* LCOV_EXCL_STOP */ } f = CB_FIELD (r->value); ff = real_field_founder (f); if (ff->flag_external) { f->flag_external = 1; f->flag_local = 1; } else if (ff->flag_item_based) { f->flag_local = 1; } if (!r->subs && !r->offset && f->count > 0 && !chk_field_variable_size (f) && !chk_field_variable_address (f)) { if (!f->flag_field) { savetarget = output_target; output_target = NULL; output_field (x); fl = cobc_parse_malloc (sizeof (struct field_list)); fl->x = x; fl->f = f; fl->curr_prog = excp_current_program_id; if (f->special_index != 2U && (f->flag_is_global || current_prog->flag_file_global)) { fl->next = field_cache; field_cache = fl; } else { fl->next = local_field_cache; local_field_cache = fl; } f->flag_field = 1; output_target = savetarget; } if (f->flag_local) { #if 0 /* RXWRXW - Any data pointer */ if (f->flag_any_length && f->flag_anylen_done) { output ("&%s%d", CB_PREFIX_FIELD, f->id); } else { #endif output ("COB_SET_DATA (%s%d, ", CB_PREFIX_FIELD, f->id); output_data (x); output (")"); #if 0 /* RXWRXW - Any data pointer */ f->flag_anylen_done = 1; } #endif } else { if (screenptr && f->storage == CB_STORAGE_SCREEN) { output ("&s_%d", f->id); } else { output ("&%s%d", CB_PREFIX_FIELD, f->id); } } } else { if (stack_id >= num_cob_fields) { num_cob_fields = stack_id + 1; } sprintf (fname, "f%d", stack_id++); if (inside_check != 0) { if (inside_stack[inside_check - 1] != 0) { inside_stack[inside_check - 1] = 0; output (",\n"); output_prefix (); } } output ("COB_SET_FLD(%s, ", fname); output_size (x); output (", "); output_data (x); output (", "); output_attr (x); output (")"); } if (r->check) { if (inside_check) { --inside_check; } output (" )"); } break; case CB_TAG_BINARY_OP: bp = CB_BINARY_OP (x); output ("cob_intr_binop ("); output_param (bp->x, id); output (", "); output ("%d", bp->op); output (", "); output_param (bp->y, id); output (")"); break; case CB_TAG_INTRINSIC: ip = CB_INTRINSIC (x); if (ip->isuser) { func = user_func_upper (CB_PROTOTYPE (cb_ref (ip->name))->ext_name); lookup_func_call (func); #if 0 /* RXWRXW Func */ output ("cob_user_function (func_%s, &cob_dyn_%u, ", func, gen_dynamic); #else output ("func_%s.funcfld (&cob_dyn_%u", func, gen_dynamic); #endif gen_dynamic++; if (ip->intr_field || ip->args) { output (", "); } #if 0 /* RXWRXW Func */ if (ip->intr_tab->refmod) { if (ip->offset) { output_integer (ip->offset); output (", "); } else { output ("0, "); } if (ip->length) { output_integer (ip->length); } else { output ("0"); } if (ip->intr_field || ip->args) { output (", "); } } #endif } else { output ("%s (", ip->intr_tab->intr_routine); if (ip->intr_tab->refmod) { if (ip->offset) { output_integer (ip->offset); output (", "); } else { output ("0, "); } if (ip->length) { output_integer (ip->length); } else { output ("0"); } if (ip->intr_field || ip->args) { output (", "); } } } if (ip->intr_field) { if (ip->intr_field == cb_int0) { output ("NULL"); } else if (ip->intr_field == cb_int1) { output ("%u", cb_list_length (ip->args)); } else { output_param (ip->intr_field, id); } if (ip->args) { output (", "); } } for (l = ip->args; l; l = CB_CHAIN (l)) { output_param (CB_VALUE (l), id); id++; param_id++; if (CB_CHAIN (l)) { output (", "); } } output (")"); break; case CB_TAG_FUNCALL: output_funcall (x); break; default: /* LCOV_EXCL_START */ cobc_err_msg (_("unexpected tree tag: %d"), (int)CB_TREE_TAG (x)); COBC_ABORT (); /* LCOV_EXCL_STOP */ } } /* Function call */ static void output_funcall (cb_tree x) { struct cb_funcall *p; cb_tree l; int i; p = CB_FUNCALL (x); if (p->name[0] == '$') { switch (p->name[1]) { case 'E': /* Set of one character */ output ("*("); output_data (p->argv[0]); output (") = "); output_param (p->argv[1], 1); break; case 'F': /* Move of one character */ output ("*("); output_data (p->argv[0]); output (") = *("); output_data (p->argv[1]); output (")"); break; case 'G': /* Test of one character */ output ("(int)(*("); output_data (p->argv[0]); if (p->argv[1] == cb_space) { output (") - ' ')"); } else if (p->argv[1] == cb_zero) { output (") - '0')"); } else if (p->argv[1] == cb_low) { output ("))"); } else if (p->argv[1] == cb_high) { output (") - 255)"); } else if (CB_LITERAL_P (p->argv[1])) { output (") - %d)", *(CB_LITERAL (p->argv[1])->data)); } else { output (") - *("); output_data (p->argv[1]); output ("))"); } break; default: /* LCOV_EXCL_START */ cobc_err_msg (_("unexpected function: %s"), p->name); COBC_ABORT (); /* LCOV_EXCL_STOP */ } return; } screenptr = p->screenptr; output ("%s (", p->name); for (i = 0; i < p->argc; i++) { if (p->varcnt && i + 1 == p->argc) { output ("%d, ", p->varcnt); for (l = p->argv[i]; l; l = CB_CHAIN (l)) { if (CB_VALUE (l) && CB_LITERAL_P (CB_VALUE (l))) { nolitcast = p->nolitcast; } output_param (CB_VALUE (l), i); nolitcast = 0; i++; if (CB_CHAIN (l)) { output (", "); } } } else { if (p->argv[i] && CB_LITERAL_P (p->argv[i])) { nolitcast = p->nolitcast; } output_param (p->argv[i], i); nolitcast = 0; if (i + 1 < p->argc) { output (", "); } } } output (")"); nolitcast = 0; screenptr = 0; } static void output_func_1 (const char *name, cb_tree x) { output ("%s (", name); output_param (x, param_id); output (")"); } /* Condition */ static void output_cond (cb_tree x, const int save_flag) { struct cb_binary_op *p; switch (CB_TREE_TAG (x)) { case CB_TAG_CONST: if (x == cb_true) { output ("1"); } else if (x == cb_false) { output ("0"); } else { /* LCOV_EXCL_START */ cobc_err_msg ("invalid constant"); COBC_ABORT (); /* LCOV_EXCL_STOP */ } break; case CB_TAG_BINARY_OP: p = CB_BINARY_OP (x); switch (p->op) { case '!': output ("!"); output_cond (p->x, save_flag); break; case '&': case '|': output ("("); output_cond (p->x, save_flag); output (p->op == '&' ? " && " : " || "); output_newline (); output_prefix (); output (" "); output_cond (p->y, save_flag); output (")"); break; case '=': case '<': case '[': case '>': case ']': case '~': output ("((int)"); output_cond (p->x, save_flag); switch (p->op) { case '=': output (" == 0"); break; case '<': output (" < 0"); break; case '[': output (" <= 0"); break; case '>': output (" > 0"); break; case ']': output (" >= 0"); break; case '~': output (" != 0"); break; default: /* FIXME - Check */ break; } output (")"); break; default: output_integer (x); break; } break; case CB_TAG_FUNCALL: if (save_flag) { output ("(ret = "); } output_funcall (x); if (save_flag) { output (")"); } break; case CB_TAG_LIST: if (save_flag) { output ("(ret = "); } inside_stack[inside_check++] = 0; if (inside_check >= COB_INSIDE_SIZE) { /* LCOV_EXCL_START */ cobc_err_msg (_("internal statement stack depth exceeded: %d"), COB_INSIDE_SIZE); COBC_ABORT (); /* LCOV_EXCL_STOP */ } output ("(\n"); for (; x; x = CB_CHAIN (x)) { output_stmt (CB_VALUE (x)); } if (inside_check) { --inside_check; } output (")"); if (save_flag) { output (")"); } break; default: /* LCOV_EXCL_START */ cobc_err_msg (_("unexpected tree tag: %d"), (int)CB_TREE_TAG (x)); COBC_ABORT (); /* LCOV_EXCL_STOP */ } } /* MOVE */ static void output_move (cb_tree src, cb_tree dst) { cb_tree x; /* Suppress warnings */ suppress_warn = 1; x = cb_build_move (src, dst); if (x != cb_error_node) { output_stmt (x); } suppress_warn = 0; } /* INITIALIZE */ static int deduce_initialize_type (struct cb_initialize *p, struct cb_field *f, const int topfield) { cb_tree l; int type; if (f->flag_item_78) { /* LCOV_EXCL_START */ cobc_err_msg (_("unexpected CONSTANT item")); COBC_ABORT (); /* LCOV_EXCL_STOP */ } if (f->flag_external && !p->flag_init_statement) { return INITIALIZE_NONE; } if (f->redefines && (!topfield || !p->flag_init_statement)) { return INITIALIZE_NONE; } if (f->flag_filler && p->flag_no_filler_init && !f->children) { return INITIALIZE_NONE; } if (p->val && f->values) { return INITIALIZE_ONE; } if (p->var && CB_REFERENCE_P (p->var) && CB_REFERENCE (p->var)->offset) { /* Reference modified item */ return INITIALIZE_ONE; } if (f->children) { type = deduce_initialize_type (p, f->children, 0); if (type == INITIALIZE_ONE) { return INITIALIZE_COMPOUND; } for (f = f->children->sister; f; f = f->sister) { if (type != deduce_initialize_type (p, f, 0)) { return INITIALIZE_COMPOUND; } } return type; } else { for (l = p->rep; l; l = CB_CHAIN (l)) { if ((int)CB_PURPOSE_INT (l) == (int)CB_TREE_CATEGORY (f)) { return INITIALIZE_ONE; } } } if (p->flag_default) { if (cb_default_byte >= 0 && !p->flag_init_statement) { return INITIALIZE_DEFAULT; } switch (f->usage) { case CB_USAGE_FLOAT: case CB_USAGE_DOUBLE: case CB_USAGE_LONG_DOUBLE: case CB_USAGE_FP_BIN32: case CB_USAGE_FP_BIN64: case CB_USAGE_FP_BIN128: case CB_USAGE_FP_DEC64: case CB_USAGE_FP_DEC128: return INITIALIZE_ONE; default: break; } switch (CB_TREE_CATEGORY (f)) { case CB_CATEGORY_NUMERIC_EDITED: case CB_CATEGORY_ALPHANUMERIC_EDITED: case CB_CATEGORY_NATIONAL_EDITED: return INITIALIZE_ONE; default: if (cb_tree_type (CB_TREE (f), f) == COB_TYPE_NUMERIC_PACKED) { return INITIALIZE_ONE; } else { return INITIALIZE_DEFAULT; } } } return INITIALIZE_NONE; } static int initialize_uniform_char (const struct cb_field *f, const struct cb_initialize *p) { int c; if (f->children) { c = initialize_uniform_char (f->children, p); for (f = f->children->sister; f; f = f->sister) { if (!f->redefines) { if (c != initialize_uniform_char (f, p)) { return -1; } } } return c; } else { if (cb_default_byte >= 0 && !p->flag_init_statement) { return cb_default_byte; } switch (cb_tree_type (CB_TREE (f), f)) { case COB_TYPE_NUMERIC_BINARY: return 0; case COB_TYPE_NUMERIC_DISPLAY: return '0'; case COB_TYPE_ALPHANUMERIC: return ' '; default: return -1; } } } static void output_figurative (cb_tree x, const struct cb_field *f, const int value, const int init_occurs) { output_prefix (); /* Check for non-standard 01 OCCURS */ if (init_occurs) { output ("memset ("); output_data (x); output (", %d, %d);\n", value, f->occurs_max); } else if (f->size == 1) { output ("*(cob_u8_ptr)("); output_data (x); output (") = %d;\n", value); } else { output ("memset ("); output_data (x); if (CB_REFERENCE_P(x) && CB_REFERENCE(x)->length) { output (", %d, ", value); output_size (x); output (");\n"); } else { output (", %d, %d);\n", value, f->size); } } } static void output_initialize_literal (cb_tree x, struct cb_field *f, struct cb_literal *l, const int init_occurs) { int i; int n; int size; int lsize; /* Check for non-standard 01 OCCURS */ if (init_occurs) { size = f->occurs_max; lsize = (int)l->size; /* Check truncated literal */ if (lsize > f->size) { lsize = f->size; } } else { size = f->size; lsize = (int)l->size; } if (lsize == 1) { output_prefix (); output ("memset ("); output_data (x); if (CB_REFERENCE_P(x) && CB_REFERENCE(x)->length) { output (", %d, ", l->data[0]); output_size (x); output (");\n"); } else { output (", %d, %d);\n", l->data[0], size); } return; } if (lsize >= size) { output_prefix (); output ("memcpy ("); output_data (x); output (", "); output_string (l->data, size, l->llit); output (", %d);\n", size); return; } i = size / lsize; i_counters[0] = 1; output_line ("for (i0 = 0; i0 < %d; i0++)", i); output_indent ("{"); output_prefix (); output ("memcpy ("); output_data (x); output (" + (i0 * %d), ", lsize); output_string (l->data, lsize, l->llit); output (", %d);\n", lsize); output_indent ("}"); n = size % lsize; if (n) { output_prefix (); output ("memcpy ("); output_data (x); output (" + (i0 * %d), ", lsize); output_string (l->data, n, l->llit); output (", %d);\n", n); } } static void output_initialize_fp_bindec (cb_tree x, struct cb_field *f) { output_prefix (); output ("memset ("); output_data (x); output (", 0, %d);\n", (int)f->size); } static void output_initialize_fp (cb_tree x, struct cb_field *f) { output_prefix (); if (f->usage == CB_USAGE_FLOAT) { output ("{float temp = 0.0;"); } else { output ("{double temp = 0.0;"); } output (" memcpy ("); output_data (x); output (", (void *)&temp, sizeof(temp));}\n"); } static void output_initialize_uniform (cb_tree x, const int c, const int size) { output_prefix (); if (size == 1) { output ("*(cob_u8_ptr)("); output_data (x); output (") = %d;\n", c); } else { output ("memset ("); output_data (x); if (CB_REFERENCE_P(x) && CB_REFERENCE(x)->length) { output (", %d, ", c); output_size (x); output (");\n"); } else { output (", %d, %d);\n", c, size); } } } static void output_initialize_chaining (struct cb_field *f, struct cb_initialize *p) { /* only handle CHAINING for program initialization*/ if (p->flag_init_statement) { return; } /* Note: CHAINING must be an extra initialization step as parameters not passed must have standard initialization */ if (f->flag_chained) { output_prefix (); output ("cob_chain_setup ("); output_data (p->var); output (", %d, %d);\n", f->param_num, f->size); } } static void output_initialize_one (struct cb_initialize *p, cb_tree x) { struct cb_field *f; cb_tree value; cb_tree lrp; struct cb_literal *l; size_t lsize; cob_u32_t inci; int i; int n; int size; int offset; int init_occurs; unsigned char buffchar; f = cb_code_field (x); /* Initialize by value */ if (p->val && f->values) { value = CB_VALUE (f->values); /* Check for non-standard OCCURS */ if ((f->level == 1 || f->level == 77) && f->flag_occurs && !p->flag_init_statement) { init_occurs = 1; } else { init_occurs = 0; } if (value == cb_space) { output_figurative (x, f, ' ', init_occurs); return; } else if (value == cb_low) { output_figurative (x, f, 0, init_occurs); return; } else if (value == cb_high) { output_figurative (x, f, 255, init_occurs); return; } else if (value == cb_quote) { if (cb_flag_apostrophe) { output_figurative (x, f, '\'', init_occurs); } else { output_figurative (x, f, '"', init_occurs); } return; } else if (value == cb_zero && f->usage == CB_USAGE_DISPLAY) { if (!f->flag_sign_separate && !f->flag_blank_zero) { output_figurative (x, f, '0', init_occurs); } else { output_move (cb_zero, x); } return; } else if (value == cb_null && f->usage == CB_USAGE_DISPLAY) { output_figurative (x, f, 0, init_occurs); return; } else if (CB_LITERAL_P (value) && CB_LITERAL (value)->all) { /* ALL literal */ output_initialize_literal (x, f, CB_LITERAL (value), init_occurs); return; } else if (CB_CONST_P (value) || CB_TREE_CLASS (value) == CB_CLASS_NUMERIC) { /* Figurative literal, numeric literal */ /* Check for non-standard 01 OCCURS */ if (init_occurs) { i_counters[0] = 1; output_line ("for (i0 = 1; i0 <= %d; i0++)", f->occurs_max); output_indent ("{"); CB_REFERENCE (x)->subs = CB_BUILD_CHAIN (cb_i[0], CB_REFERENCE (x)->subs); output_move (value, x); CB_REFERENCE (x)->subs = CB_CHAIN (CB_REFERENCE (x)->subs); output_indent ("}"); } else { output_move (value, x); } return; } /* Alphanumeric literal */ /* We do not use output_move here because we do not want to have the value be edited. */ l = CB_LITERAL (value); /* Check for non-standard 01 OCCURS */ if (init_occurs) { output_initialize_literal (x, f, l, 1); return; } size = f->size; if (size == 1) { output_prefix (); output ("*(cob_u8_ptr)("); output_data (x); output (") = %u;\n", l->data[0]); return; } buffchar = l->data[0]; for (lsize = 0; lsize < l->size; lsize++) { if (l->data[lsize] != buffchar) { break; } } if (lsize == l->size) { output_prefix (); output ("memset ("); output_data (x); output (", %u, %d);\n", (unsigned int)buffchar, (int)lsize); if ((int)l->size < (int)size) { output_prefix (); output ("memset ("); output_data (x); output (" + %d, ' ', %d);\n", (int)lsize, (int)(size - lsize)); } return; } if (size > litsize) { litsize = size + 128; if (litbuff) { litbuff = cobc_main_realloc (litbuff, (size_t)litsize); } else { litbuff = cobc_main_malloc ((size_t)litsize); } } if ((int)l->size >= (int)size) { memcpy (litbuff, l->data, (size_t)size); } else { memcpy (litbuff, l->data, (size_t)l->size); memset (litbuff + l->size, ' ', (size_t)(size - l->size)); } buffchar = *(litbuff + size - 1); n = 0; for (i = size - 1; i >= 0; i--, n++) { if (*(litbuff + i) != buffchar) { break; } } if (i < 0) { output_prefix (); output ("memset ("); output_data (x); output (", %u, %d);\n", (unsigned int)buffchar, size); return; } if (n > 2) { offset = size - n; size -= n; } else { offset = 0; } inci = 0; for (; size > 509; size -= 509, inci += 509) { output_prefix (); output ("memcpy ("); output_data (x); if (!inci) { output (", "); } else { output (" + %u, ", inci); } output_string (litbuff + inci, 509, l->llit); output (", 509);\n"); } output_prefix (); output ("memcpy ("); output_data (x); if (!inci) { output (", "); } else { output (" + %u, ", inci); } output_string (litbuff + inci, size, l->llit); output (", %d);\n", size); if (offset) { output_prefix (); output ("memset ("); output_data (x); output (" + %d, %u, %d);\n", offset, (unsigned int)buffchar, n); } return; } /* Initialize replacing */ if (!f->children) { for (lrp = p->rep; lrp; lrp = CB_CHAIN (lrp)) { if ((int)CB_PURPOSE_INT (lrp) == (int)CB_TREE_CATEGORY (x)) { output_move (CB_VALUE (lrp), x); return; } } } /* Initialize by default */ if (p->flag_default) { switch (f->usage) { case CB_USAGE_FLOAT: case CB_USAGE_DOUBLE: case CB_USAGE_LONG_DOUBLE: output_initialize_fp (x, f); return; case CB_USAGE_FP_BIN32: case CB_USAGE_FP_BIN64: case CB_USAGE_FP_BIN128: case CB_USAGE_FP_DEC64: case CB_USAGE_FP_DEC128: output_initialize_fp_bindec (x, f); return; default: break; } switch (CB_TREE_CATEGORY (x)) { case CB_CATEGORY_NUMERIC: case CB_CATEGORY_NUMERIC_EDITED: output_move (cb_zero, x); break; case CB_CATEGORY_ALPHANUMERIC: case CB_CATEGORY_ALPHANUMERIC_EDITED: case CB_CATEGORY_NATIONAL: case CB_CATEGORY_NATIONAL_EDITED: output_move (cb_space, x); break; default: /* LCOV_EXCL_START */ cobc_err_msg (_("unexpected tree category: %d"), (int)CB_TREE_CATEGORY (x)); COBC_ABORT (); /* LCOV_EXCL_STOP */ } } } static void output_initialize_compound (struct cb_initialize *p, cb_tree x) { struct cb_field *ff; struct cb_field *f; struct cb_field *last_field; cb_tree c; size_t size; int type; int last_char; int i; ff = cb_code_field (x); for (f = ff->children; f; f = f->sister) { type = deduce_initialize_type (p, f, 0); c = cb_build_field_reference (f, x); switch (type) { case INITIALIZE_NONE: break; case INITIALIZE_DEFAULT: last_field = f; last_char = initialize_uniform_char (f, p); if (last_char != -1) { if (f->flag_occurs) { CB_REFERENCE (c)->subs = CB_BUILD_CHAIN (cb_int1, CB_REFERENCE (c)->subs); } for (; f->sister; f = f->sister) { if (!f->sister->redefines) { if (deduce_initialize_type (p, f->sister, 0) != INITIALIZE_DEFAULT || initialize_uniform_char (f->sister, p) != last_char) { break; } } } if (f->sister) { size = f->sister->offset - last_field->offset; } else { size = ff->offset + ff->size - last_field->offset; } output_initialize_uniform (c, last_char, (int) size); break; } /* Fall through */ default: if (f->flag_occurs) { /* Begin occurs loop */ i = f->indexes; i_counters[i] = 1; output_line ("for (i%d = 1; i%d <= %d; i%d++)", i, i, f->occurs_max, i); output_indent ("{"); CB_REFERENCE (c)->subs = CB_BUILD_CHAIN (cb_i[i], CB_REFERENCE (c)->subs); } if (type == INITIALIZE_ONE) { output_initialize_one (p, c); } else { output_initialize_compound (p, c); } if (f->flag_occurs) { /* Close loop */ CB_REFERENCE (c)->subs = CB_CHAIN (CB_REFERENCE (c)->subs); output_indent ("}"); } } } } static void output_initialize (struct cb_initialize *p) { struct cb_field *f; cb_tree x; int c; int type; f = cb_code_field (p->var); type = deduce_initialize_type (p, f, 1); /* Check for non-standard OCCURS */ if ((f->level == 1 || f->level == 77) && f->flag_occurs && !p->flag_init_statement) { switch (type) { case INITIALIZE_NONE: return; case INITIALIZE_ONE: output_initialize_one (p, p->var); output_initialize_chaining (f, p); return; case INITIALIZE_DEFAULT: c = initialize_uniform_char (f, p); if (c != -1) { output_initialize_uniform (p->var, c, f->occurs_max); output_initialize_chaining (f, p); return; } /* Fall through */ case INITIALIZE_COMPOUND: i_counters[0] = 1; output_line ("for (i0 = 1; i0 <= %d; i0++)", f->occurs_max); output_indent ("{"); x = cb_build_field_reference (f, NULL); CB_REFERENCE (x)->subs = CB_BUILD_CHAIN (cb_i[0], CB_REFERENCE (x)->subs); output_initialize_compound (p, x); CB_REFERENCE (x)->subs = CB_CHAIN (CB_REFERENCE (x)->subs); output_indent ("}"); output_initialize_chaining (f, p); return; default: break; } } switch (type) { case INITIALIZE_NONE: return; case INITIALIZE_ONE: output_initialize_one (p, p->var); output_initialize_chaining (f, p); return; case INITIALIZE_DEFAULT: c = initialize_uniform_char (f, p); if (c != -1) { output_initialize_uniform (p->var, c, f->size); output_initialize_chaining (f, p); return; } /* Fall through */ case INITIALIZE_COMPOUND: output_initialize_compound (p, p->var); output_initialize_chaining (f, p); return; default: break; } } /* SEARCH */ static void output_occurs (struct cb_field *p) { if (p->depending) { output_integer (p->depending); } else { output ("%d", p->occurs_max); } } static void output_search_whens (cb_tree table, struct cb_field *p, cb_tree stmt, cb_tree var, cb_tree whens) { cb_tree l; cb_tree idx = NULL; COB_UNUSED(table); /* to be handled later */ if (!p->index_list) { /* LCOV_EXCL_START */ cobc_err_msg (_("call to '%s' with invalid parameter '%s'"), "output_search", "table"); COBC_ABORT (); /* LCOV_EXCL_STOP */ } /* Determine the index to use */ if (var) { for (l = p->index_list; l; l = CB_CHAIN (l)) { if (cb_ref (CB_VALUE (l)) == cb_ref (var)) { idx = var; } } } if (!idx) { idx = CB_VALUE (p->index_list); } /* Start loop */ output_line ("for (;;) {"); output_indent_level += 2; /* End test */ output_prefix (); output ("if ("); output_integer (idx); output (" > "); output_occurs (p); output (")\n"); output_indent ("{"); output_line ("/* Table end */"); if (stmt) { output_stmt (stmt); } else { output_line ("break;"); } output_indent ("}"); /* WHEN test */ output_stmt (whens); /* Iteration */ output_newline (); output_prefix (); output_integer (idx); output ("++;\n"); if (var && var != idx) { output_move (idx, var); } output_line ("/* Iterate */"); /* End loop */ output_indent_level -= 2; output_line ("}"); } static void output_search_all (cb_tree table, struct cb_field *p, cb_tree stmt, cb_tree cond, cb_tree when) { cb_tree idx; COB_UNUSED(table); /* to be handled later */ idx = CB_VALUE (p->index_list); /* Header */ output_indent ("{"); output_line ("int ret;"); output_line ("int head = 0;"); output_prefix (); output ("int tail = "); output_occurs (p); output (" + 1;\n"); /* Check for at least one entry */ output_prefix (); output ("if ("); output_occurs (p); output (" == 0) head = tail;\n"); /* Start loop */ output_line ("for (;;)"); output_indent ("{"); /* End test */ output_line ("if (head >= tail - 1)"); output_indent ("{"); output_line ("/* Table end */"); if (stmt) { output_stmt (stmt); } else { output_line ("break;"); } output_indent ("}"); /* Next index */ output_prefix (); output_integer (idx); output (" = (head + tail) / 2;\n"); output_newline (); /* WHEN test */ output_line ("/* WHEN */"); output_prefix (); output ("if ("); output_cond (cond, 1); output (")\n"); output_indent ("{"); output_stmt (when); output_indent ("}"); output_line ("if (ret < 0)"); output_prefix (); output (" head = "); output_integer (idx); output (";\n"); output_line ("else"); output_prefix (); output (" tail = "); output_integer (idx); output (";\n"); output_indent ("}"); output_indent ("}"); } static void output_search (struct cb_search *p) { struct cb_field *fp = cb_code_field (p->table); /* TODO: Add run-time checks for the table, including ODO */ if (p->flag_all) { output_search_all (p->table, fp, p->end_stmt, CB_IF (p->whens)->test, CB_IF (p->whens)->stmt1); } else { output_search_whens (p->table, fp, p->end_stmt, p->var, p->whens); } } /* CALL */ #if 0 /* BWT, working through CALL BY VALUE */ static void debug_call_by_value(cb_tree x, cb_tree l) { struct cb_field *f; printf("CB_TREE_TAG(x) = %d\n", CB_TREE_TAG(x)); printf("CB_TREE_CLASS(x) = %d\n", CB_TREE_CLASS(x)); printf("CB_TREE_TAG(l) = %d\n", CB_TREE_TAG(l)); printf("CB_TREE_CLASS(l) = %d\n", CB_TREE_CLASS(l)); f = cb_code_field (x); printf("cb_code_field(x)->usage = %d\n", f->usage); return; } #endif /** * cast function pointer call frame to avoid default argument promotion */ static void output_call_protocast (cb_tree x, cb_tree l) { struct cb_field *f; const char *s; cob_s64_t val; cob_u64_t uval; int sizes; int sign; switch (CB_TREE_TAG (x)) { case CB_TAG_CAST: output ("int"); return; case CB_TAG_INTRINSIC: if (CB_INTRINSIC(x)->intr_tab->category == CB_CATEGORY_NUMERIC) { output ("int"); } else { output ("void *"); } return; case CB_TAG_LITERAL: if (CB_TREE_CLASS (x) != CB_CLASS_NUMERIC) { output ("int"); return; } if (CB_SIZES_INT_UNSIGNED(l)) { uval = cb_get_u_long_long (x); switch (CB_SIZES_INT (l)) { case CB_SIZE_AUTO: if (uval > UINT_MAX) { output ("cob_u64_t"); return; } /* Fall through to case 4 */ case CB_SIZE_4: output ("cob_u32_t"); return; case CB_SIZE_1: output ("cob_u8_t"); return; case CB_SIZE_2: output ("cob_u16_t"); return; case CB_SIZE_8: output ("cob_u64_t"); return; default: /* LCOV_EXCL_START */ cobc_err_msg (_("unexpected size: %d"), CB_SIZES_INT (l)); COBC_ABORT (); /* LCOV_EXCL_STOP */ } } val = cb_get_long_long (x); switch (CB_SIZES_INT (l)) { case CB_SIZE_AUTO: if (val > INT_MAX) { output ("cob_s64_t"); return; } /* Fall through to case 4 */ case CB_SIZE_4: output ("cob_s32_t"); return; case CB_SIZE_1: output ("cob_s8_t"); return; case CB_SIZE_2: output ("cob_s16_t"); return; case CB_SIZE_8: output ("cob_s64_t"); return; default: /* LCOV_EXCL_START */ cobc_err_msg (_("unexpected size: %d"), CB_SIZES_INT (l)); COBC_ABORT (); /* LCOV_EXCL_STOP */ } return; default: f = cb_code_field (x); switch (f->usage) { case CB_USAGE_BINARY: case CB_USAGE_COMP_5: case CB_USAGE_COMP_X: case CB_USAGE_PACKED: case CB_USAGE_DISPLAY: case CB_USAGE_COMP_6: sizes = CB_SIZES_INT (l); sign = 0; if (sizes == CB_SIZE_AUTO) { if (f->pic->have_sign) { sign = 1; } if (f->usage == CB_USAGE_PACKED || f->usage == CB_USAGE_DISPLAY || f->usage == CB_USAGE_COMP_6) { sizes = f->pic->digits - f->pic->scale; } else { sizes = f->size; } switch (sizes) { case 0: sizes = CB_SIZE_4; break; case 1: sizes = CB_SIZE_1; break; case 2: sizes = CB_SIZE_2; break; case 3: sizes = CB_SIZE_4; break; case 4: sizes = CB_SIZE_4; break; case 5: sizes = CB_SIZE_8; break; case 6: sizes = CB_SIZE_8; break; case 7: sizes = CB_SIZE_8; break; default: sizes = CB_SIZE_8; break; } } else { if (!CB_SIZES_INT_UNSIGNED(l)) { sign = 1; } } switch (sizes) { case CB_SIZE_1: if (sign) { s = "cob_c8_t"; } else { s = "cob_u8_t"; } break; case CB_SIZE_2: if (sign) { s = "cob_s16_t"; } else { s = "cob_u16_t"; } break; case CB_SIZE_4: if (sign) { s = "cob_s32_t"; } else { s = "cob_u32_t"; } break; case CB_SIZE_8: if (sign) { s = "cob_s64_t"; } else { s = "cob_u64_t"; } break; default: if (sign) { s = "cob_s32_t"; } else { s = "cob_u32_t"; } break; } output ("%s", s); return; case CB_USAGE_INDEX: output ("cob_s32_t"); return; case CB_USAGE_LENGTH: output ("cob_u32_t"); return; case CB_USAGE_POINTER: case CB_USAGE_PROGRAM_POINTER: output ("void *"); return; case CB_USAGE_FLOAT: output ("float"); return; case CB_USAGE_DOUBLE: output ("double"); return; case CB_USAGE_LONG_DOUBLE: output ("long double"); return; case CB_USAGE_FP_BIN32: output ("cob_u32_t"); return; case CB_USAGE_FP_BIN64: case CB_USAGE_FP_DEC64: output ("cob_u64_t"); return; case CB_USAGE_FP_BIN128: case CB_USAGE_FP_DEC128: output ("cob_fp_128"); return; default: output ("void *"); return; } } } /** * dereference BY VALUE arguments, sync with call_output_protocast */ static void output_call_by_value_args (cb_tree x, cb_tree l) { struct cb_field *f; const char *s; cob_s64_t val; cob_u64_t uval; int sizes; int sign; switch (CB_TREE_TAG (x)) { case CB_TAG_CAST: output_integer (x); return; case CB_TAG_INTRINSIC: if (CB_INTRINSIC(x)->intr_tab->category == CB_CATEGORY_NUMERIC) { output ("cob_get_int ("); output_param (x, -1); output (")"); } else { output_data (x); } return; case CB_TAG_LITERAL: if (CB_TREE_CLASS (x) != CB_CLASS_NUMERIC) { output ("%d", CB_LITERAL (x)->data[0]); return; } if (CB_SIZES_INT_UNSIGNED(l)) { uval = cb_get_u_long_long (x); switch (CB_SIZES_INT (l)) { case CB_SIZE_AUTO: if (uval > UINT_MAX) { output ("(cob_u64_t)"); output (CB_FMT_LLU_F, uval); return; } /* Fall through to case 4 */ case CB_SIZE_4: output ("(cob_u32_t)"); output (CB_FMT_LLU_F, uval); return; case CB_SIZE_1: output ("(cob_u8_t)"); output (CB_FMT_LLU_F, uval); return; case CB_SIZE_2: output ("(cob_u16_t)"); output (CB_FMT_LLU_F, uval); return; case CB_SIZE_8: output ("(cob_u64_t)"); output (CB_FMT_LLU_F, uval); return; default: /* LCOV_EXCL_START */ cobc_err_msg (_("unexpected size: %d"), CB_SIZES_INT (l)); COBC_ABORT (); /* LCOV_EXCL_STOP */ } } val = cb_get_long_long (x); switch (CB_SIZES_INT (l)) { case CB_SIZE_AUTO: if (val > INT_MAX) { output ("(cob_s64_t)"); output (CB_FMT_LLD_F, val); return; } /* Fall through to case 4 */ case CB_SIZE_4: output ("(cob_s32_t)"); output (CB_FMT_LLD_F, val); return; case CB_SIZE_1: output ("(cob_s8_t)"); output (CB_FMT_LLD_F, val); return; case CB_SIZE_2: output ("(cob_s16_t)"); output (CB_FMT_LLD_F, val); return; case CB_SIZE_8: output ("(cob_s64_t)"); output (CB_FMT_LLD_F, val); return; default: /* LCOV_EXCL_START */ cobc_err_msg (_("unexpected size: %d"), CB_SIZES_INT (l)); COBC_ABORT (); /* LCOV_EXCL_STOP */ } return; default: f = cb_code_field (x); switch (f->usage) { case CB_USAGE_BINARY: case CB_USAGE_COMP_5: case CB_USAGE_COMP_X: case CB_USAGE_PACKED: case CB_USAGE_DISPLAY: case CB_USAGE_COMP_6: sizes = CB_SIZES_INT (l); sign = 0; if (sizes == CB_SIZE_AUTO) { if (f->pic->have_sign) { sign = 1; } if (f->usage == CB_USAGE_PACKED || f->usage == CB_USAGE_DISPLAY || f->usage == CB_USAGE_COMP_6) { sizes = f->pic->digits - f->pic->scale; } else { sizes = f->size; } switch (sizes) { case 0: sizes = CB_SIZE_4; break; case 1: sizes = CB_SIZE_1; break; case 2: sizes = CB_SIZE_2; break; case 3: sizes = CB_SIZE_4; break; case 4: sizes = CB_SIZE_4; break; case 5: sizes = CB_SIZE_8; break; case 6: sizes = CB_SIZE_8; break; case 7: sizes = CB_SIZE_8; break; default: sizes = CB_SIZE_8; break; } } else { if (!CB_SIZES_INT_UNSIGNED(l)) { sign = 1; } } switch (sizes) { case CB_SIZE_1: if (sign) { s = "cob_c8_t"; } else { s = "cob_u8_t"; } break; case CB_SIZE_2: if (sign) { s = "cob_s16_t"; } else { s = "cob_u16_t"; } break; case CB_SIZE_4: if (sign) { s = "cob_s32_t"; } else { s = "cob_u32_t"; } break; case CB_SIZE_8: if (sign) { s = "cob_s64_t"; } else { s = "cob_u64_t"; } break; default: if (sign) { s = "cob_s32_t"; } else { s = "cob_u32_t"; } break; } output ("(%s)(", s); output_integer (x); output (")"); return; case CB_USAGE_INDEX: case CB_USAGE_HNDL: case CB_USAGE_HNDL_WINDOW: case CB_USAGE_HNDL_SUBWINDOW: case CB_USAGE_HNDL_FONT: case CB_USAGE_HNDL_THREAD: case CB_USAGE_HNDL_MENU: case CB_USAGE_HNDL_VARIANT: case CB_USAGE_HNDL_LM: case CB_USAGE_LENGTH: case CB_USAGE_POINTER: case CB_USAGE_PROGRAM_POINTER: output_integer (x); return; case CB_USAGE_FLOAT: output ("*(float *)("); output_data (x); output (")"); return; case CB_USAGE_DOUBLE: output ("*(double *)("); output_data (x); output (")"); return; case CB_USAGE_LONG_DOUBLE: output ("*(long double *)("); output_data (x); output (")"); return; case CB_USAGE_FP_BIN32: output ("*(cob_u32_t *)("); output_data (x); output (")"); return; case CB_USAGE_FP_BIN64: case CB_USAGE_FP_DEC64: output ("*(cob_u64_t *)("); output_data (x); output (")"); return; case CB_USAGE_FP_BIN128: case CB_USAGE_FP_DEC128: output ("*(cob_fp_128 *)("); output_data (x); output (")"); return; default: output ("*("); output_data (x); output (")"); return; } } } static void output_bin_field (const cb_tree x, const cob_u32_t id) { int i; cob_u32_t size; cob_u32_t aflags; cob_u32_t digits; if (!CB_NUMERIC_LITERAL_P (x)) { return; } aflags = COB_FLAG_REAL_BINARY; if (cb_fits_int (x)) { size = 4; digits = 9; aflags = COB_FLAG_HAVE_SIGN; /* Drop: COB_FLAG_REAL_BINARY */ } else { size = 8; digits = 18; if (CB_LITERAL (x)->sign < 0) { aflags |= COB_FLAG_HAVE_SIGN; } } aflags |= COB_FLAG_CONSTANT; i = lookup_attr (COB_TYPE_NUMERIC_BINARY, digits, 0, aflags, NULL, 0); output_line ("cob_field\tcontent_fb_%u = { %u, content_%u.data, &%s%d };", id, size, id, CB_PREFIX_ATTR, i); } static COB_INLINE COB_A_INLINE int is_literal_or_prototype_ref (cb_tree x) { return CB_LITERAL_P (x) || (CB_REFERENCE_P (x) && CB_PROTOTYPE_P (cb_ref (x))); } static char * get_program_id_str (cb_tree id_item) { if (CB_LITERAL_P (id_item)) { return (char *)(CB_LITERAL (id_item)->data); } else { /* prototype */ return (char *)CB_PROTOTYPE (cb_ref (id_item))->ext_name; } } static struct nested_list * find_nested_prog_with_id (const char *encoded_id) { struct nested_list *nlp; for (nlp = current_prog->nested_prog_list; nlp; nlp = nlp->next) { if (!strcmp (encoded_id, nlp->nested_prog->program_id)) { break; } } return nlp; } static void output_call (struct cb_call *p) { cb_tree x; cb_tree l; const char *name_str; struct nested_list *nlp; const struct system_table *psyst = NULL; const char *convention; struct cb_text_list *ctl; const char *s; cob_u32_t n; size_t ret_ptr = 0; size_t gen_exit_program = 0; size_t dynamic_link = 1; size_t need_brace; const int name_is_literal_or_prototype = is_literal_or_prototype_ref (p->name); int except_id; #if 0 /* RXWRXW - Clear params */ cob_u32_t parmnum; #endif except_id = 0; if (p->call_returning && p->call_returning != cb_null && CB_TREE_CLASS(p->call_returning) == CB_CLASS_POINTER) { ret_ptr = 1; } #ifdef _WIN32 if (p->convention & CB_CONV_STDCALL) { convention = "_std"; } else { convention = ""; } #else convention = ""; #endif /* System routine entry points */ if (p->is_system) { psyst = &system_tab[p->is_system - 1]; dynamic_link = 0; } if (dynamic_link && name_is_literal_or_prototype) { if (cb_flag_static_call || (p->convention & CB_CONV_STATIC_LINK)) { dynamic_link = 0; } if (CB_LITERAL_P (p->name)) { name_str = (const char *) CB_LITERAL (p->name)->data; } else { /* prototype */ name_str = CB_PROTOTYPE (cb_ref (p->name))->ext_name; } for (ctl = cb_static_call_list; ctl; ctl = ctl->next) { if (!strcmp (name_str, ctl->text)) { dynamic_link = 0; break; } } for (ctl = cb_early_exit_list; ctl; ctl = ctl->next) { if (!strcmp (name_str, ctl->text)) { gen_exit_program = 1; break; } } } need_brace = 0; #ifdef COB_NON_ALIGNED if (dynamic_link && ret_ptr) { if (!need_brace) { need_brace = 1; output_indent ("{"); } output_line ("void *temptr;"); } #endif if (CB_REFERENCE_P (p->name) && CB_FIELD_P (CB_REFERENCE (p->name)->value) && CB_FIELD (CB_REFERENCE (p->name)->value)->usage == CB_USAGE_PROGRAM_POINTER) { dynamic_link = 0; } /* Set up arguments */ for (l = p->args, n = 1; l; l = CB_CHAIN (l), n++) { x = CB_VALUE (l); switch (CB_PURPOSE_INT (l)) { case CB_CALL_BY_REFERENCE: if (CB_NUMERIC_LITERAL_P (x) || CB_BINARY_OP_P (x)) { if (!need_brace) { need_brace = 1; output_indent ("{"); } output_line ("cob_content\tcontent_%u;", n); output_bin_field (x, n); } else if (CB_CAST_P (x)) { if (!need_brace) { need_brace = 1; output_indent ("{"); } output_line ("void *ptr_%u;", n); } break; case CB_CALL_BY_CONTENT: if (CB_CAST_P (x)) { if (!need_brace) { need_brace = 1; output_indent ("{"); } output_line ("void *ptr_%u;", n); } else if (CB_TREE_TAG (x) != CB_TAG_INTRINSIC && x != cb_null && !(CB_CAST_P (x))) { if (!need_brace) { need_brace = 1; output_indent ("{"); } output_line ("union {"); output_prefix (); output ("\tunsigned char data["); if (CB_NUMERIC_LITERAL_P (x) || CB_BINARY_OP_P (x) || CB_CAST_P(x)) { output ("8"); } else { if (CB_REF_OR_FIELD_P (x)) { output ("%u", (cob_u32_t)cb_code_field (x)->size); } else { output_size (x); } } output ("];\n"); output_line ("\tcob_s64_t datall;"); output_line ("\tcob_u64_t dataull;"); output_line ("\tint dataint;"); output_line ("} content_%u;", n); output_line ("cob_field content_%s%u;", CB_PREFIX_FIELD, n); output_line ("cob_field_attr content_%s%u;", CB_PREFIX_ATTR, n); output_bin_field (x, n); } break; default: break; } } if (need_brace) { output_newline (); } for (l = p->args, n = 1; l; l = CB_CHAIN (l), n++) { x = CB_VALUE (l); switch (CB_PURPOSE_INT (l)) { case CB_CALL_BY_REFERENCE: if (CB_NUMERIC_LITERAL_P (x)) { output_prefix (); if (cb_fits_int (x)) { output ("content_%u.dataint = ", n); output ("%d", cb_get_int (x)); } else { if (CB_LITERAL (x)->sign >= 0) { output ("content_%u.dataull = ", n); output (CB_FMT_LLU_F, cb_get_u_long_long (x)); } else { output ("content_%u.datall = ", n); output (CB_FMT_LLD_F, cb_get_long_long (x)); } } output (";\n"); } else if (CB_BINARY_OP_P (x)) { output_prefix (); output ("content_%u.dataint = ", n); output_integer (x); output (";\n"); } else if (CB_CAST_P (x)) { output_prefix (); output ("ptr_%u = ", n); output_integer (x); output (";\n"); } break; case CB_CALL_BY_CONTENT: if (CB_CAST_P (x)) { output_prefix (); output ("ptr_%u = ", n); output_integer (x); output (";\n"); } else if (CB_TREE_TAG (x) != CB_TAG_INTRINSIC) { if (CB_NUMERIC_LITERAL_P (x)) { output_prefix (); if (cb_fits_int (x)) { output ("content_%u.dataint = ", n); output ("%d", cb_get_int (x)); } else if (CB_LITERAL (x)->sign >= 0) { output ("content_%u.dataull = ", n); output (CB_FMT_LLU_F, cb_get_u_long_long (x)); } else { output ("content_%u.datall = ", n); output (CB_FMT_LLD_F, cb_get_long_long (x)); } output (";\n"); } else if (CB_REF_OR_FIELD_P (x) && CB_TREE_CATEGORY (x) == CB_CATEGORY_NUMERIC && cb_code_field (x)->usage == CB_USAGE_LENGTH) { output_prefix (); output ("content_%u.dataint = ", n); output_integer (x); output (";\n"); } else if (x != cb_null && !(CB_CAST_P (x))) { /* * Create copy of cob_field&attr pointing to local copy of data * and setting flag COB_FLAG_CONSTANT */ output_prefix (); output ("cob_field_constant ("); output_param (x, -1); output (", &content_%s%u ", CB_PREFIX_FIELD, n); output (", &content_%s%u ", CB_PREFIX_ATTR, n); output (", &content_%u);\n", n); } } break; default: break; } } /* Set up parameter types */ n = 0; for (l = p->args; l; l = CB_CHAIN (l), n++) { x = CB_VALUE (l); field_iteration = n; output_prefix (); output ("cob_procedure_params[%u] = ", n); switch (CB_TREE_TAG (x)) { case CB_TAG_LITERAL: if (CB_NUMERIC_LITERAL_P (x) && CB_PURPOSE_INT (l) != CB_CALL_BY_VALUE) { output ("&content_fb_%u", n + 1); break; } /* Fall through */ case CB_TAG_FIELD: if (CB_PURPOSE_INT (l) == CB_CALL_BY_CONTENT) { output ("&content_%s%u", CB_PREFIX_FIELD, n + 1); break; } output_param (x, -1); break; case CB_TAG_INTRINSIC: output_param (x, -1); break; case CB_TAG_REFERENCE: switch (CB_TREE_TAG (CB_REFERENCE(x)->value)) { case CB_TAG_LITERAL: case CB_TAG_FIELD: case CB_TAG_INTRINSIC: if (CB_PURPOSE_INT (l) == CB_CALL_BY_CONTENT) { output ("&content_%s%u", CB_PREFIX_FIELD, n + 1); break; } output_param (x, -1); break; default: output ("NULL"); break; } break; default: output ("NULL"); break; } output (";\n"); } #if 0 /* RXWRXW - Clear params */ /* Clear extra parameters */ if (n > MAX_CALL_FIELD_PARAMS - 4) { parmnum = MAX_CALL_FIELD_PARAMS - n; } else { parmnum = 4; } parmnum *= sizeof(cob_field *); output_line ("memset (&(cob_procedure_params[%u]), 0, %u);", n, parmnum); #endif /* Set number of parameters */ output_prefix (); output ("cob_glob_ptr->cob_call_params = %u;\n", n); output_prefix (); if (p->stmt1) { output ("cob_glob_ptr->cob_stmt_exception = 1;\n"); } else { output ("cob_glob_ptr->cob_stmt_exception = 0;\n"); } /* Function name */ output_prefix (); /* Special for program pointers */ if (CB_REFERENCE_P (p->name) && CB_FIELD_P (CB_REFERENCE (p->name)->value) && CB_FIELD (CB_REFERENCE (p->name)->value)->usage == CB_USAGE_PROGRAM_POINTER) { needs_unifunc = 1; output ("cob_unifunc.funcvoid = "); output_integer (p->name); output (";\n"); output_prefix (); if (p->call_returning == cb_null) { output ("cob_unifunc.funcnull"); } else if (ret_ptr) { #ifdef COB_NON_ALIGNED output ("temptr"); #else output_integer (p->call_returning); #endif output (" = cob_unifunc.funcptr"); } else { if (p->convention & CB_CONV_NO_RET_UPD || !current_prog->cb_return_code) { output ("(void)cob_unifunc.funcint"); } else { output_integer (current_prog->cb_return_code); output (" = cob_unifunc.funcint"); } } } else if (!dynamic_link) { /* Static link */ if (p->call_returning != cb_null) { if (ret_ptr) { #ifdef COB_NON_ALIGNED output ("temptr"); #else output_integer (p->call_returning); #endif output (" = (void *)"); } else if (!(p->convention & CB_CONV_NO_RET_UPD) && current_prog->cb_return_code) { output_integer (current_prog->cb_return_code); output (" = "); } else { output ("(void)"); } } if (psyst) { output ("%s", (char *)psyst->syst_call); } else { s = get_program_id_str (p->name); name_str = cb_encode_program_id (s); /* Check contained programs */ nlp = find_nested_prog_with_id (name_str); if (nlp) { output ("%s_%d__", name_str, nlp->nested_prog->toplev_count); } else { output ("%s", name_str); if (cb_flag_c_decl_for_static_call) { if (p->call_returning == cb_null) { lookup_static_call (name_str, p->convention, COB_RETURN_NULL); } else if (ret_ptr == 1) { lookup_static_call (name_str, p->convention, COB_RETURN_ADDRESS_OF); } else { lookup_static_call (name_str, p->convention, COB_RETURN_INT); } } } } } else { /* Dynamic link */ if (name_is_literal_or_prototype) { s = get_program_id_str (p->name); name_str = cb_encode_program_id (s); lookup_call (name_str); output ("if (unlikely(call_%s.funcvoid == NULL || cob_glob_ptr->cob_physical_cancel)) {\n", name_str); output_prefix (); nlp = find_nested_prog_with_id (name_str); if (nlp) { output (" call_%s.funcint = %s_%d__;\n", name_str, name_str, nlp->nested_prog->toplev_count); } else { output (" call_%s.funcvoid = ", name_str); output ("cob_resolve_cobol ("); output_string ((const unsigned char *)s, (int)strlen (s), 0); output (", %d, %d);\n", cb_fold_call, !p->stmt1); } output_prefix (); output ("}\n"); } else { name_str = NULL; needs_unifunc = 1; output ("cob_unifunc.funcvoid = cob_call_field ("); output_param (p->name, -1); if (current_prog->nested_prog_list) { gen_nested_tab = 1; output (", cob_nest_tab, %d, %d);\n", !p->stmt1, cb_fold_call); } else { output (", NULL, %d, %d);\n", !p->stmt1, cb_fold_call); } } if (p->stmt1) { if (name_str) { output_line ("if (unlikely(call_%s.funcvoid == NULL))", name_str); } else { output_line ("if (unlikely(cob_unifunc.funcvoid == NULL))"); } output_line ("{"); output_indent_level += 2; except_id = cb_id++; output_line ("%s%d:", CB_PREFIX_LABEL, except_id); output_stmt (p->stmt1); output_indent_level -= 2; output_line ("}"); output_line ("else"); output_indent ("{"); } output_prefix (); /* call frame cast prototype */ if (ret_ptr) { #ifdef COB_NON_ALIGNED output ("temptr"); #else output_integer (p->call_returning); #endif output (" = ((void *(*)"); } else { if (p->call_returning != cb_null) { if (p->convention & CB_CONV_NO_RET_UPD || !current_prog->cb_return_code) { output ("((int (*)"); } else { output_integer (current_prog->cb_return_code); output (" = ((int (*)"); } } else { output ("((void (*)"); } } if (p->args) { output ("("); } else { output ("(void)"); } for (l = p->args, n = 1; l; l = CB_CHAIN (l), n++) { x = CB_VALUE (l); field_iteration = n - 1U; switch (CB_PURPOSE_INT (l)) { case CB_CALL_BY_REFERENCE: case CB_CALL_BY_CONTENT: output ("void *"); break; case CB_CALL_BY_VALUE: output_call_protocast (x, l); break; default: break; } if (CB_CHAIN (l)) { output (", "); } } if (p->args) { output (")"); } output(")"); if (p->call_returning == cb_null) { if (name_str) { output ("call_%s.funcnull%s", name_str, convention); } else { output ("cob_unifunc.funcnull%s", convention); } } else if (ret_ptr) { if (name_str) { output ("call_%s.funcptr%s", name_str, convention); } else { output ("cob_unifunc.funcptr%s", convention); } } else { if (name_str) { output ("call_%s.funcint%s", name_str, convention); } else { output ("cob_unifunc.funcint%s", convention); } } output (")"); } /* Arguments */ output (" ("); for (l = p->args, n = 1; l; l = CB_CHAIN (l), n++) { x = CB_VALUE (l); field_iteration = n - 1U; switch (CB_PURPOSE_INT (l)) { case CB_CALL_BY_REFERENCE: if (CB_NUMERIC_LITERAL_P (x) || CB_BINARY_OP_P (x)) { output ("content_%u.data", n); } else if (CB_REFERENCE_P (x) && CB_FILE_P (cb_ref (x))) { output_param (cb_ref (x), -1); } else if (CB_CAST_P (x)) { output ("&ptr_%u", n); } else { output_data (x); } break; case CB_CALL_BY_CONTENT: if (CB_TREE_TAG (x) != CB_TAG_INTRINSIC && x != cb_null) { if (CB_CAST_P (x)) { output ("&ptr_%u", n); } else { output ("content_%u.data", n); } } else { output_data (x); } break; case CB_CALL_BY_VALUE: output_call_by_value_args (x, l); break; default: break; } /* early exit if call parameters don't match, this is actually needed for all static calls, but only possible with an external program repository, so just do so for system calls */ if (psyst && psyst->syst_max_params == n) { break; } if (CB_CHAIN (l)) { output (", "); } } output (");\n"); if (except_id > 0) { output_line ("if (unlikely(cob_glob_ptr->cob_exception_code != 0))"); output_line ("\tgoto %s%d;", CB_PREFIX_LABEL, except_id); } if (p->call_returning && (!(p->convention & CB_CONV_NO_RET_UPD)) && current_prog->cb_return_code) { if (p->call_returning == cb_null) { output_prefix (); output_integer (current_prog->cb_return_code); output (" = 0;\n"); } else if (!ret_ptr) { output_move (current_prog->cb_return_code, p->call_returning); #ifdef COB_NON_ALIGNED } else { output_prefix (); output ("memcpy ("); output_data (p->call_returning); output (", &temptr, %u);\n", (cob_u32_t)sizeof (void *)); #endif } } if (gen_exit_program) { needs_exit_prog = 1; output_line ("if (unlikely(module->flag_exit_program)) {"); output_line ("\tmodule->flag_exit_program = 0;"); output_line ("\tgoto exit_program;"); output_line ("}"); } if (p->stmt2) { output_stmt (p->stmt2); } if (dynamic_link && p->stmt1) { output_indent ("}"); } if (need_brace) { output_indent ("}"); } } /* SET ATTRIBUTE */ static void output_set_attribute (const struct cb_field *f, cob_flags_t val_on, cob_flags_t val_off) { /* Extension */ /* Prevent specifying HIGHLIGHT and LOWLIGHT simultaneously. */ if (val_on & COB_SCREEN_HIGHLIGHT) { val_off |= COB_SCREEN_LOWLIGHT; } else if (val_on & COB_SCREEN_LOWLIGHT) { val_off |= COB_SCREEN_HIGHLIGHT; } if (val_on) { output_line ("s_%d.attr |= 0x" CB_FMT_LLX ";", f->id, val_on); } if (val_off) { output_line ("s_%d.attr &= ~0x" CB_FMT_LLX ";", f->id, val_off); } } /* CANCEL */ static void output_cancel (struct cb_cancel *p) { struct nested_list *nlp; char *name_str; char *s; unsigned int i; if (is_literal_or_prototype_ref (p->target)) { s = get_program_id_str (p->target); name_str = cb_encode_program_id (s); nlp = find_nested_prog_with_id (name_str); if (nlp) { output_prefix (); output ("(void)%s_%d_ (-1", name_str, nlp->nested_prog->toplev_count); for (i = 0; i < nlp->nested_prog->num_proc_params; ++i) { output (", NULL"); } output (");\n"); } else { output ("cob_cancel ("); output_string ((const unsigned char *)s, (int)strlen (s), 0); output (");\n"); } return; } output_prefix (); output ("cob_cancel_field ("); output_param (p->target, -1); if (current_prog->nested_prog_list) { gen_nested_tab = 1; output (", cob_nest_tab"); } else { output (", NULL"); } output (");\n"); } /* PERFORM */ static void output_perform_call (struct cb_label *lb, struct cb_label *le) { struct cb_para_label *p; struct label_list *l; if (lb == current_prog->all_procedure || lb->flag_is_debug_sect) { output_line ("/* DEBUGGING Callback PERFORM %s */", (const char *)lb->name); } else if (lb == le) { output_line ("/* PERFORM %s */", (const char *)lb->name); } else { output_line ("/* PERFORM %s THRU %s */", (const char *)lb->name, (const char *)le->name); } /* Save current independent segment pointers */ if (current_prog->flag_segments && last_section && last_section->section_id != lb->section_id) { p = last_section->para_label; for (; p; p = p->next) { if (p->para->segment > 49 && p->para->flag_alter) { output_line ("save_label_%s%d = label_%s%d;", CB_PREFIX_LABEL, p->para->id, CB_PREFIX_LABEL, p->para->id); } } } /* Zap target independent labels */ if (current_prog->flag_segments && last_segment != lb->segment) { if (lb->flag_section) { p = lb->para_label; } else if (lb->section) { p = lb->section->para_label; } else { p = NULL; } for (; p; p = p->next) { if (p->para->segment > 49 && p->para->flag_alter) { output_line ("label_%s%d = 0;", CB_PREFIX_LABEL, p->para->id); } } } /* Update debugging name */ if (current_prog->flag_gen_debug && lb->flag_real_label && (current_prog->all_procedure || lb->flag_debugging_mode)) { output_stmt (cb_build_debug (cb_debug_name, (const char *)lb->name, NULL)); } output_line ("frame_ptr++;"); if (cb_flag_stack_check) { output_line ("if (unlikely(frame_ptr == frame_overflow))"); output_line (" cob_fatal_error (COB_FERROR_STACK);"); } output_line ("frame_ptr->perform_through = %d;", le->id); if (!cb_flag_computed_goto) { l = cobc_parse_malloc (sizeof (struct label_list)); l->next = label_cache; l->id = cb_id; if (label_cache == NULL) { l->call_num = 0; } else { l->call_num = label_cache->call_num + 1; } label_cache = l; output_line ("frame_ptr->return_address_num = %d;", l->call_num); output_line ("goto %s%d;", CB_PREFIX_LABEL, lb->id); output_line ("%s%d:", CB_PREFIX_LABEL, cb_id); } else { output_line ("frame_ptr->return_address_ptr = &&%s%d;", CB_PREFIX_LABEL, cb_id); output_line ("goto %s%d;", CB_PREFIX_LABEL, lb->id); output_line ("%s%d:", CB_PREFIX_LABEL, cb_id); } output_line ("frame_ptr--;"); cb_id++; if (current_prog->flag_segments && last_section && last_section->section_id != lb->section_id) { /* Restore current independent segment pointers */ p = last_section->para_label; for (; p; p = p->next) { if (p->para->segment > 49 && p->para->flag_alter) { output_line ("label_%s%d = save_label_%s%d;", CB_PREFIX_LABEL, p->para->id, CB_PREFIX_LABEL, p->para->id); } } /* Zap target independent labels */ if (lb->flag_section) { p = lb->para_label; } else if (lb->section) { p = lb->section->para_label; } else { p = NULL; } for (; p; p = p->next) { if (p->para->segment > 49 && p->para->flag_alter) { output_line ("label_%s%d = 0;", CB_PREFIX_LABEL, p->para->id); } } } } static void output_perform_exit (struct cb_label *l) { if (l->flag_global) { output_newline (); output_line ("/* Implicit GLOBAL DECLARATIVE return */"); output_line ("if (entry == %d) {", l->id); output_line (" cob_module_leave (module);"); if (cb_flag_stack_on_heap || current_prog->flag_recursive) { output_line (" cob_free (frame_stack);"); output_line (" cob_free (cob_procedure_params);"); output_line (" cob_module_free (&module);"); } output_line (" return 0;"); output_line ("}"); } output_newline (); if (l->flag_declarative_exit) { output_line ("/* Implicit DECLARATIVE return */"); } else if (l->flag_default_handler) { output_line ("/* Implicit Default Error Handler return */"); } else { output_line ("/* Implicit PERFORM return */"); } if (cb_perform_osvs && current_prog->prog_type == CB_PROGRAM_TYPE) { output_line ("for (temp_index = frame_ptr; temp_index->perform_through; temp_index--) {"); output_line (" if (temp_index->perform_through == %d) {", l->id); output_line (" frame_ptr = temp_index;"); if (!cb_flag_computed_goto) { output_line (" goto P_switch;"); } else { output_line (" goto *frame_ptr->return_address_ptr;"); } output_line (" }"); output_line ("}"); } else { output_line ("if (frame_ptr->perform_through == %d)", l->id); if (!cb_flag_computed_goto) { output_line (" goto P_switch;"); } else { output_line (" goto *frame_ptr->return_address_ptr;"); } } if (l->flag_fatal_check) { output_newline (); output_line ("/* Fatal error if reached */"); output_line ("cob_fatal_error (COB_FERROR_GLOBAL);"); } } static void output_funcall_debug (cb_tree x) { struct cb_funcall *p; cb_tree l; cb_tree z; int i; p = CB_FUNCALL (x); if (p->name[0] == '$') { z = p->argv[0]; if (CB_REF_OR_FIELD_P (z) && cb_code_field (z)->flag_field_debug) { /* DEBUG */ output_stmt (cb_build_debug (cb_debug_name, (const char *)cb_code_field (z)->name, NULL)); output_stmt (cb_build_debug (cb_debug_contents, NULL, z)); output_perform_call (cb_code_field (z)->debug_section, cb_code_field (z)->debug_section); } z = p->argv[1]; if (CB_REF_OR_FIELD_P (z) && cb_code_field (z)->flag_field_debug) { /* DEBUG */ output_stmt (cb_build_debug (cb_debug_name, (const char *)cb_code_field (z)->name, NULL)); output_stmt (cb_build_debug (cb_debug_contents, NULL, z)); output_perform_call (cb_code_field (z)->debug_section, cb_code_field (z)->debug_section); } return; } for (i = 0; i < p->argc; i++) { if (p->varcnt && i + 1 == p->argc) { for (l = p->argv[i]; l; l = CB_CHAIN (l)) { output_param (CB_VALUE (l), i); z = CB_VALUE (l); if (CB_REF_OR_FIELD_P (z) && cb_code_field (z)->flag_field_debug) { /* DEBUG */ output_stmt (cb_build_debug (cb_debug_name, (const char *)cb_code_field (z)->name, NULL)); output_stmt (cb_build_debug (cb_debug_contents, NULL, z)); output_perform_call (cb_code_field (z)->debug_section, cb_code_field (z)->debug_section); } i++; } } else { z = p->argv[i]; if (CB_REF_OR_FIELD_P (z) && cb_code_field (z)->flag_field_debug) { /* DEBUG */ output_stmt (cb_build_debug (cb_debug_name, (const char *)cb_code_field (z)->name, NULL)); output_stmt (cb_build_debug (cb_debug_contents, NULL, z)); output_perform_call (cb_code_field (z)->debug_section, cb_code_field (z)->debug_section); } } } } static void output_cond_debug (cb_tree x) { struct cb_binary_op *p; switch (CB_TREE_TAG (x)) { case CB_TAG_FUNCALL: output_funcall_debug (x); break; case CB_TAG_LIST: break; case CB_TAG_BINARY_OP: p = CB_BINARY_OP (x); switch (p->op) { case '!': output_cond_debug (p->x); break; case '&': case '|': output_cond_debug (p->x); output_cond_debug (p->y); break; case '=': case '<': case '[': case '>': case ']': case '~': output_cond_debug (p->x); break; default: if (CB_REF_OR_FIELD_P (x) && cb_code_field (x)->flag_field_debug) { output_stmt (cb_build_debug (cb_debug_name, (const char *)cb_code_field (x)->name, NULL)); output_stmt (cb_build_debug (cb_debug_contents, NULL, x)); output_perform_call (cb_code_field (x)->debug_section, cb_code_field (x)->debug_section); } break; } break; default: break; } } static void output_perform_once (struct cb_perform *p) { if (p->body && CB_PAIR_P (p->body)) { output_perform_call (CB_LABEL (cb_ref (CB_PAIR_X (p->body))), CB_LABEL (cb_ref (CB_PAIR_Y (p->body)))); } else { output_stmt (p->body); } if (p->cycle_label) { output_stmt (cb_ref (p->cycle_label)); } } static void output_perform_until (struct cb_perform *p, cb_tree l) { struct cb_perform_varying *v; struct cb_field *f; cb_tree next; if (l == NULL) { /* Perform body at the end */ output_perform_once (p); return; } v = CB_PERFORM_VARYING (CB_VALUE (l)); next = CB_CHAIN (l); output_line ("for (;;)"); output_indent ("{"); if (next && CB_PERFORM_VARYING (CB_VALUE (next))->name) { output_move (CB_PERFORM_VARYING (CB_VALUE (next))->from, CB_PERFORM_VARYING (CB_VALUE (next))->name); /* DEBUG */ if (current_prog->flag_gen_debug) { f = CB_FIELD (cb_ref (CB_PERFORM_VARYING (CB_VALUE (next))->name)); if (f->flag_field_debug) { output_stmt (cb_build_debug (cb_debug_name, (const char *)f->name, NULL)); output_stmt (cb_build_debug (cb_debug_contents, NULL, CB_PERFORM_VARYING (CB_VALUE (next))->name)); output_perform_call (f->debug_section, f->debug_section); } } } if (p->test == CB_AFTER) { output_perform_until (p, next); } /* DEBUG */ if (current_prog->flag_gen_debug) { output_cond_debug (v->until); } output_prefix (); output ("if ("); output_cond (v->until, 0); output (")\n"); output_line (" break;"); if (p->test == CB_BEFORE) { output_perform_until (p, next); } if (v->step) { output_stmt (v->step); } output_indent ("}"); } static void output_perform (struct cb_perform *p) { struct cb_perform_varying *v; struct cb_field *f; switch (p->perform_type) { case CB_PERFORM_EXIT: if (CB_LABEL (p->data)->flag_return) { output_perform_exit (CB_LABEL (p->data)); } break; case CB_PERFORM_ONCE: output_perform_once (p); break; case CB_PERFORM_TIMES: output_prefix (); output ("for (n%d = ", loop_counter); output_param (cb_build_cast_llint (p->data), 0); output ("; n%d > 0; n%d--)\n", loop_counter, loop_counter); loop_counter++; output_indent ("{"); output_perform_once (p); output_indent ("}"); break; case CB_PERFORM_UNTIL: v = CB_PERFORM_VARYING (CB_VALUE (p->varying)); if (v->name) { output_move (v->from, v->name); /* DEBUG */ if (current_prog->flag_gen_debug) { f = CB_FIELD (cb_ref (v->name)); if (f->flag_field_debug) { output_stmt (cb_build_debug (cb_debug_name, (const char *)f->name, NULL)); output_stmt (cb_build_debug (cb_debug_contents, NULL, v->name)); output_perform_call (f->debug_section, f->debug_section); } } } output_perform_until (p, p->varying); break; case CB_PERFORM_FOREVER: output_prefix (); output ("for (;;)\n"); output_indent ("{"); output_perform_once (p); output_indent ("}"); break; default: break; } if (p->exit_label) { output_stmt (cb_ref (p->exit_label)); } } static void output_file_error (struct cb_file *pfile) { struct cb_file *fl; cb_tree l; if (current_prog->flag_gen_debug) { output_stmt (cb_build_debug (cb_debug_contents, "USE PROCEDURE", NULL)); } for (l = current_prog->local_file_list; l; l = CB_CHAIN (l)) { fl = CB_FILE(CB_VALUE (l)); if (!strcmp (pfile->name, fl->name)) { output_perform_call (fl->handler, fl->handler); return; } } for (l = current_prog->global_file_list; l; l = CB_CHAIN (l)) { fl = CB_FILE(CB_VALUE (l)); if (!strcmp (pfile->name, fl->name)) { if (fl->handler_prog == current_prog) { output_perform_call (fl->handler, fl->handler); } else { if (fl->handler_prog->nested_level) { output_line ("%s_%d_ (%d);", fl->handler_prog->program_id, fl->handler_prog->toplev_count, fl->handler->id); } else { output_line ("%s_ (%d);", fl->handler_prog->program_id, fl->handler->id); } } return; } } output_perform_call (pfile->handler, pfile->handler); } /* GO TO */ static void output_goto_1 (cb_tree x) { struct cb_label *lb; struct cb_para_label *p; lb = CB_LABEL (cb_ref (x)); if (current_prog->flag_segments && last_segment != lb->segment) { /* Zap independent labels */ if (lb->flag_section) { p = lb->para_label; } else if (lb->section) { p = lb->section->para_label; } else { p = NULL; } for (; p; p = p->next) { if (p->para->segment > 49 && p->para->flag_alter) { output_line ("label_%s%d = 0;", CB_PREFIX_LABEL, p->para->id); } } } /* Check for debugging on procedure */ if (current_prog->flag_gen_debug && lb->flag_real_label && (current_prog->all_procedure || lb->flag_debugging_mode)) { output_stmt (cb_build_debug (cb_debug_name, (const char *)lb->name, NULL)); output_move (cb_space, cb_debug_contents); } output_line ("goto %s%d;", CB_PREFIX_LABEL, lb->id); } static void output_goto (struct cb_goto *p) { cb_tree l; struct cb_field *f; int i; i = 1; if (p->depending) { /* Check for debugging on the DEPENDING item */ if (current_prog->flag_gen_debug) { f = CB_FIELD (cb_ref (p->depending)); if (f->flag_all_debug) { output_stmt (cb_build_debug (cb_debug_name, (const char *)f->name, NULL)); output_stmt (cb_build_debug (cb_debug_contents, NULL, p->depending)); output_perform_call (f->debug_section, f->debug_section); } } output_prefix (); output ("switch ("); output_param (cb_build_cast_int (p->depending), 0); output (")\n"); output_indent ("{"); for (l = p->target; l; l = CB_CHAIN (l)) { output_indent_level -= 2; output_line ("case %d:", i++); output_indent_level += 2; output_goto_1 (CB_VALUE (l)); } output_indent ("}"); } else if (p->target == NULL) { /* EXIT PROGRAM/FUNCTION */ needs_exit_prog = 1; if (cb_flag_implicit_init || current_prog->nested_level || current_prog->prog_type == CB_FUNCTION_TYPE) { output_line ("goto exit_program;"); } else { /* Ignore if not a callee */ output_line ("if (module->next)"); output_line (" goto exit_program;"); } } else if (p->target == cb_int1) { needs_exit_prog = 1; output_line ("goto exit_program;"); } else { output_goto_1 (p->target); } } /* ALTER */ static void output_alter (struct cb_alter *p) { struct cb_label *l1; struct cb_label *l2; l1 = CB_LABEL (CB_REFERENCE(p->source)->value); l2 = CB_LABEL (CB_REFERENCE(p->target)->value); output_line ("label_%s%d = %d;", CB_PREFIX_LABEL, l1->id, l2->id); /* Check for debugging on procedure name */ if (current_prog->flag_gen_debug && l1->flag_real_label && (current_prog->all_procedure || l1->flag_debugging_mode)) { output_stmt (cb_build_debug (cb_debug_name, (const char *)l1->name, NULL)); output_stmt (cb_build_debug (cb_debug_contents, (const char *)l2->name, NULL)); if (current_prog->all_procedure) { output_perform_call (current_prog->all_procedure, current_prog->all_procedure); } else if (l1->flag_debugging_mode) { output_perform_call (l1->debug_section, l1->debug_section); } } } /* Output statement */ static int get_ec_code_for_handler (const enum cb_handler_type handler_type) { switch (handler_type) { case AT_END_HANDLER: return CB_EXCEPTION_CODE (COB_EC_I_O_AT_END); case EOP_HANDLER: return CB_EXCEPTION_CODE (COB_EC_I_O_EOP); case INVALID_KEY_HANDLER: return CB_EXCEPTION_CODE (COB_EC_I_O_INVALID_KEY); default: /* LCOV_EXCL_START */ cobc_err_msg (_("unexpected handler type: %d"), (int) handler_type); COBC_ABORT (); /* LCOV_EXCL_STOP */ } } static void output_ferror_stmt (struct cb_statement *stmt) { output_line ("if (unlikely(cob_glob_ptr->cob_exception_code != 0))"); output_indent ("{"); if (stmt->ex_handler) { output_line ("if (cob_glob_ptr->cob_exception_code == 0x%04x)", get_ec_code_for_handler (stmt->handler_type)); output_indent ("{"); output_stmt (stmt->ex_handler); output_indent ("}"); output_line ("else"); output_indent ("{"); } output_file_error (CB_FILE (stmt->file)); output_indent ("}"); if (stmt->ex_handler) { output_indent ("}"); } if (stmt->not_ex_handler || stmt->handler3) { output_line ("else"); output_indent ("{"); if (stmt->handler3) { output_stmt (stmt->handler3); } if (stmt->not_ex_handler) { output_stmt (stmt->not_ex_handler); } output_indent ("}"); } } static void output_section_info (struct cb_label *lp) { if (CB_TREE (lp) == cb_standard_error_handler) { return; } if (lp->flag_dummy_exit) { return; } if (lp->flag_section) { if (!lp->flag_dummy_section) { sprintf (string_buffer, "Section: %s", lp->orig_name); } else { sprintf (string_buffer, "Section: (None)"); } } else if (lp->flag_entry) { sprintf (string_buffer, "Entry: %s", lp->orig_name); } else { if (!lp->flag_dummy_paragraph) { sprintf (string_buffer, "Paragraph: %s", lp->orig_name); } else { sprintf (string_buffer, "Paragraph: (None)"); } } if (CB_TREE (lp)->source_file) { output_line ("cob_trace_section (%s%d, %s%d, %d);", CB_PREFIX_STRING, lookup_string (string_buffer), CB_PREFIX_STRING, lookup_string (CB_TREE (lp)->source_file), CB_TREE (lp)->source_line); } else { output_line ("cob_trace_section (%s%d, NULL, %d);", CB_PREFIX_STRING, lookup_string (string_buffer), CB_TREE (lp)->source_line); } } static void output_trace_info (cb_tree x, const char *name) { output_prefix (); output ("cob_set_location (%s%d, %d, ", CB_PREFIX_STRING, lookup_string (x->source_file), x->source_line); if (excp_current_section) { output ("%s%d, ", CB_PREFIX_STRING, lookup_string (excp_current_section)); } else { output ("NULL, "); } if (excp_current_paragraph) { output ("%s%d, ", CB_PREFIX_STRING, lookup_string (excp_current_paragraph)); } else { output ("NULL, "); } if (name) { output ("%s%d);\n", CB_PREFIX_STRING, lookup_string (name)); } else { output ("NULL);\n"); } } static void output_label_info (cb_tree x, struct cb_label *lp) { if (lp->flag_dummy_section || lp->flag_dummy_paragraph) { return; } output_newline (); if (lp->flag_dummy_exit) { output_line ("/* Implicit EXIT label */"); return; } else if (lp->flag_next_sentence) { output_line ("/* Implicit NEXT SENTENCE label */"); return; } output_prefix (); if (x->source_file) { output ("/* Line: %-10d: ", x->source_line); } else { output ("/* "); } if (lp->flag_section) { output ("Section %-24s", (const char *)lp->name); excp_current_section = (const char *)lp->name; excp_current_paragraph = NULL; } else { if (lp->flag_entry) { output ("Entry %-24s", lp->orig_name); excp_current_section = NULL; excp_current_paragraph = NULL; } else { output ("Paragraph %-24s", (const char *)lp->name); excp_current_paragraph = (const char *)lp->name; } } if (x->source_file) { output (": %s */\n", x->source_file); } else { output ("*/\n"); } } static void output_alter_check (struct cb_label *lp) { struct cb_alter_id *aid; output_local ("static int\tlabel_%s%d = 0;\n", CB_PREFIX_LABEL, lp->id); if (current_prog->flag_segments) { output_local ("static int\tsave_label_%s%d = 0;\n", CB_PREFIX_LABEL, lp->id); } output_newline (); output_line ("/* ALTER processing */"); output_line ("switch (label_%s%d)", CB_PREFIX_LABEL, lp->id); output_indent ("{"); for (aid = lp->alter_gotos; aid; aid = aid->next) { output_line ("case %d:", aid->goto_id); output_line ("goto %s%d;", CB_PREFIX_LABEL, aid->goto_id); } output_indent ("}"); output_newline (); } static void output_level_2_ex_condition (const int level_2_ec) { output_line ("if (unlikely ((cob_glob_ptr->cob_exception_code & 0xff00) == 0x%04x))", CB_EXCEPTION_CODE (level_2_ec)); } static void output_display_accept_ex_condition (const enum cb_handler_type handler_type) { int imp_ec; output_line ("if (unlikely ((cob_glob_ptr->cob_exception_code & 0xff00) == 0x%04x", CB_EXCEPTION_CODE (COB_EC_SCREEN)); if (handler_type == DISPLAY_HANDLER) { imp_ec = COB_EC_IMP_DISPLAY; } else { /* ACCEPT_HANDLER */ imp_ec = COB_EC_IMP_ACCEPT; } output_line (" || cob_glob_ptr->cob_exception_code == 0x%04x))", CB_EXCEPTION_CODE (imp_ec)); } static void output_ec_condition_for_handler (const enum cb_handler_type handler_type) { switch (handler_type) { case DISPLAY_HANDLER: output_display_accept_ex_condition (DISPLAY_HANDLER); break; case ACCEPT_HANDLER: output_display_accept_ex_condition (ACCEPT_HANDLER); break; case SIZE_ERROR_HANDLER: output_level_2_ex_condition (COB_EC_SIZE); break; case OVERFLOW_HANDLER: output_level_2_ex_condition (COB_EC_OVERFLOW); break; default: /* LCOV_EXCL_START */ cobc_err_msg (_("unexpected handler type: %d"), (int) handler_type); COBC_ABORT (); /* LCOV_EXCL_STOP */ } } static void output_handler (struct cb_statement *stmt) { if (stmt->file) { output_ferror_stmt (stmt); return; } if (stmt->ex_handler) { output_ec_condition_for_handler (stmt->handler_type); output_indent ("{"); output_stmt (stmt->ex_handler); output_indent ("}"); if (stmt->not_ex_handler) { output_line ("else"); } } if (stmt->not_ex_handler) { if (stmt->ex_handler == NULL) { output_line ("if (!cob_glob_ptr->cob_exception_code)"); } output_indent ("{"); output_stmt (stmt->not_ex_handler); output_indent ("}"); } } static void output_stmt (cb_tree x) { struct cb_binary_op *bop; cb_tree w; struct cb_statement *p; struct cb_label *lp; struct cb_assign *ap; struct cb_if *ip; struct cb_para_label *pal; struct cb_set_attr *sap; #ifdef COB_NON_ALIGNED struct cb_cast *cp; #endif size_t size; int code, skip_else; stack_id = 0; if (x == NULL) { output_line (";"); return; } if (unlikely(x == cb_error_node)) { /* LCOV_EXCL_START */ cobc_err_msg (_("unexpected error_node parameter")); COBC_ABORT (); /* LCOV_EXCL_STOP */ } if (inside_check != 0) { if (inside_stack[inside_check - 1] != 0) { inside_stack[inside_check - 1] = 0; output (",\n"); } } switch (CB_TREE_TAG (x)) { case CB_TAG_STATEMENT: p = CB_STATEMENT (x); /* Output source location as a comment */ if (p->name) { output_newline (); output_line ("/* Line: %-10d: %-19.19s: %s */", x->source_line, p->name, x->source_file); } if (x->source_file) { if (cb_flag_source_location) { /* Output source location as code */ output_trace_info (x, p->name); } if (current_prog->flag_gen_debug && !p->flag_in_debug) { output_prefix (); output ("memcpy ("); output_data (cb_debug_line); output (", \"%6d\", 6);\n", x->source_line); } last_line = x->source_line; } if (!p->file && (p->ex_handler || p->not_ex_handler)) { output_line ("cob_glob_ptr->cob_exception_code = 0;"); } if (p->null_check) { output_stmt (p->null_check); } if (p->body) { output_stmt (p->body); } /* Output field debugging statements */ if (current_prog->flag_gen_debug && p->debug_check) { output_stmt (p->debug_check); } /* Special debugging callback for START / DELETE */ /* Must be done immediately after I/O and before */ /* status check */ if (current_prog->flag_gen_debug && p->file && p->flag_callback) { output_line ("save_exception_code = cob_glob_ptr->cob_exception_code;"); output_stmt (cb_build_debug (cb_debug_name, CB_FILE(p->file)->name, NULL)); output_move (cb_space, cb_debug_contents); output_perform_call (CB_FILE(p->file)->debug_section, CB_FILE(p->file)->debug_section); output_line ("cob_glob_ptr->cob_exception_code = save_exception_code;"); need_save_exception = 1; } if (p->ex_handler || p->not_ex_handler || (p->file && CB_EXCEPTION_ENABLE (COB_EC_I_O))) { output_handler (p); } break; case CB_TAG_LABEL: lp = CB_LABEL (x); if (lp->flag_skip_label) { break; } output_label_info (x, lp); if (lp->flag_section) { for (pal = lp->para_label; pal; pal = pal->next) { if (pal->para->segment > 49 && pal->para->flag_alter) { output_line ("label_%s%d = 0;", CB_PREFIX_LABEL, pal->para->id); } } last_segment = lp->segment; last_section = lp; } if (lp->flag_begin) { output_line ("%s%d:;", CB_PREFIX_LABEL, lp->id); } /* Check for runtime debug flag */ if (current_prog->flag_debugging && lp->flag_is_debug_sect) { output_line ("if (!cob_debugging_mode)"); output_line ("\tgoto %s%d;", CB_PREFIX_LABEL, CB_LABEL (lp->exit_label)->id); } if (cb_flag_trace) { output_section_info (lp); } /* Check procedure debugging */ if (current_prog->flag_gen_debug && lp->flag_real_label) { output_stmt (cb_build_debug (cb_debug_name, (const char *)lp->name, NULL)); if (current_prog->all_procedure) { output_perform_call (current_prog->all_procedure, current_prog->all_procedure); } else if (lp->flag_debugging_mode) { output_perform_call (lp->debug_section, lp->debug_section); } } /* Check ALTER processing */ if (lp->flag_alter) { output_alter_check (lp); } break; case CB_TAG_FUNCALL: output_prefix (); output_funcall (x); if (inside_check == 0) { output (";\n"); } else { inside_stack[inside_check - 1] = 1; } break; case CB_TAG_ASSIGN: ap = CB_ASSIGN (x); #ifdef COB_NON_ALIGNED /* Nonaligned */ if (CB_TREE_CLASS (ap->var) == CB_CLASS_POINTER || CB_TREE_CLASS (ap->val) == CB_CLASS_POINTER) { /* Pointer assignment */ output_indent ("{"); output_line ("void *temp_ptr;"); /* temp_ptr = source address; */ output_prefix (); if (ap->val == cb_null || ap->val == cb_zero) { /* MOVE NULL ... */ output ("temp_ptr = 0;\n"); } else if (CB_TREE_TAG (ap->val) == CB_TAG_CAST) { /* MOVE ADDRESS OF val ... */ cp = CB_CAST (ap->val); output ("temp_ptr = "); switch (cp->cast_type) { case CB_CAST_ADDRESS: output_data (cp->val); break; case CB_CAST_PROGRAM_POINTER: output ("cob_call_field ("); output_param (ap->val, -1); if (current_prog->nested_prog_list) { gen_nested_tab = 1; output (", cob_nest_tab, 0, %d)", cb_fold_call); } else { output (", NULL, 0, %d)", cb_fold_call); } break; default: /* LCOV_EXCL_START */ cobc_err_msg (_("unexpected cast type: %d"), cp->cast_type); COBC_ABORT (); /* LCOV_EXCL_STOP */ } output (";\n"); } else { /* MOVE val ... */ output ("memcpy(&temp_ptr, "); output_data (ap->val); output (", sizeof(temp_ptr));\n"); } /* Destination address = temp_ptr; */ output_prefix (); if (CB_TREE_TAG (ap->var) == CB_TAG_CAST) { /* SET ADDRESS OF var ... */ cp = CB_CAST (ap->var); if (cp->cast_type != CB_CAST_ADDRESS) { /* LCOV_EXCL_START */ cobc_err_msg (_("unexpected tree type: %d"), cp->cast_type); COBC_ABORT (); /* LCOV_EXCL_STOP */ } output_data (cp->val); output (" = temp_ptr;\n"); } else { /* MOVE ... TO var */ output ("memcpy("); output_data (ap->var); output (", &temp_ptr, sizeof(temp_ptr));\n"); } output_indent ("}"); } else { /* Numeric assignment */ output_prefix (); output_integer (ap->var); output (" = "); output_integer (ap->val); if (inside_check == 0) { output (";\n"); } else { inside_stack[inside_check - 1] = 1; } } #else /* Nonaligned */ output_prefix (); output_integer (ap->var); output (" = "); output_integer (ap->val); if (inside_check == 0) { output (";\n"); } else { inside_stack[inside_check - 1] = 1; } #endif /* Nonaligned */ break; case CB_TAG_INITIALIZE: output_initialize (CB_INITIALIZE (x)); break; case CB_TAG_SEARCH: output_search (CB_SEARCH (x)); break; case CB_TAG_CALL: output_call (CB_CALL (x)); break; case CB_TAG_GOTO: output_goto (CB_GOTO (x)); break; case CB_TAG_CANCEL: output_cancel (CB_CANCEL (x)); break; case CB_TAG_SET_ATTR: sap = CB_SET_ATTR (x); output_set_attribute (sap->fld, sap->val_on, sap->val_off); break; case CB_TAG_ALTER: output_alter (CB_ALTER (x)); break; case CB_TAG_IF: ip = CB_IF (x); if (ip->stmt1 == NULL && ip->stmt2 == NULL) { if (!ip->is_if) { output_line ("/* WHEN has code omitted */"); } else { output_line ("/* IF has code omitted */"); } break; } if (!ip->is_if) { output_newline (); if (ip->test == cb_true) { output_line ("/* WHEN is always TRUE */"); } else if (ip->test == cb_false) { output_line ("/* WHEN is always FALSE */"); } else if (ip->test && CB_TREE_TAG (ip->test) == CB_TAG_BINARY_OP) { bop = CB_BINARY_OP (ip->test); w = NULL; if (bop->op == '!') { w = bop->x; } else if (bop->y) { w = bop->y; } else if (bop->x) { w = bop->x; } if (w == cb_true) { output_line ("/* WHEN is always %s */", bop->op == '!'?"FALSE":"TRUE"); } else if (w == cb_false) { output_line ("/* WHEN is always %s */", bop->op != '!'?"FALSE":"TRUE"); } else if (w && w->source_line) { output_prefix (); output ("/* Line: %-10d: %-19s",w->source_line, "WHEN"); if (w->source_file) { output (": %s ", w->source_file); } output ("*/\n"); if (cb_flag_source_location && last_line != w->source_line) { /* Output source location as code */ output_trace_info (w, "WHEN"); } } else { output_line ("/* WHEN */"); } } else if (ip->test->source_line) { output_line ("/* Line: %-10d: WHEN */",ip->test->source_line); if (cb_flag_source_location && last_line != ip->test->source_line) { /* Output source location as code */ output_trace_info (ip->test, "WHEN"); } } else { output_line ("/* WHEN */"); } output_newline (); } gen_if_level++; code = 0; output_prefix (); if (ip->test == cb_false && ip->stmt1 == NULL) { output_line (" /* FALSE condition and code omitted */"); skip_else = 1; } else { skip_else = 0; output ("if ("); output_cond (ip->test, 0); output (")\n"); output_line ("{"); output_indent_level += 2; if (ip->stmt1) { output_stmt (ip->stmt1); } else { output_line ("; /* Nothing */"); } if (gen_if_level > cb_if_cutoff) { if (ip->stmt2) { code = cb_id++; output_line ("goto l_%d;", code); } } output_indent_level -= 2; output_line ("}"); } if (ip->stmt2) { if (gen_if_level <= cb_if_cutoff) { if (!skip_else) output_line ("else"); output_line ("{"); output_indent_level += 2; } if (ip->is_if) { output_line ("/* ELSE */"); } else { output_line ("/* WHEN */"); } output_stmt (ip->stmt2); if (gen_if_level <= cb_if_cutoff) { output_indent_level -= 2; output_line ("}"); } else { output_line ("l_%d:;", code); } } gen_if_level--; break; case CB_TAG_PERFORM: output_perform (CB_PERFORM (x)); break; case CB_TAG_CONTINUE: output_prefix (); output (";\n"); break; case CB_TAG_LIST: if (cb_flag_extra_brace) { output_indent ("{"); } for (; x; x = CB_CHAIN (x)) { output_stmt (CB_VALUE (x)); } if (cb_flag_extra_brace) { output_indent ("}"); } break; case CB_TAG_REFERENCE: output_stmt (CB_REFERENCE(x)->value); break; case CB_TAG_DIRECT: if (CB_DIRECT (x)->flag_is_direct) { if (CB_DIRECT (x)->flag_new_line) { output_newline (); } output_line ("%s", (const char *)(CB_DIRECT (x)->line)); } else { output_newline (); output_line ("/* %s */", (const char *)(CB_DIRECT (x)->line)); } break; case CB_TAG_DEBUG: if (!current_prog->flag_gen_debug) { break; } output_prefix (); size = cb_code_field (CB_DEBUG(x)->target)->size; if (CB_DEBUG(x)->value) { if (size <= CB_DEBUG(x)->size) { output ("memcpy ("); output_data (CB_DEBUG(x)->target); output (", %s%d, %d);\n", CB_PREFIX_STRING, lookup_string (CB_DEBUG(x)->value), (int)size); } else { output ("memcpy ("); output_data (CB_DEBUG(x)->target); output (", %s%d, %d);\n", CB_PREFIX_STRING, lookup_string (CB_DEBUG(x)->value), (int)CB_DEBUG(x)->size); output_prefix (); output ("memset ("); output_data (CB_DEBUG(x)->target); code = (int)(size - CB_DEBUG(x)->size); output (" + %d, ' ', %d);\n", (int)CB_DEBUG(x)->size, code); } } else { if (size <= CB_DEBUG(x)->size) { output ("memcpy ("); output_data (CB_DEBUG(x)->target); output (", "); output_data (CB_DEBUG(x)->fld); output (", %d);\n", (int)size); } else { output ("memcpy ("); output_data (CB_DEBUG(x)->target); output (", "); output_data (CB_DEBUG(x)->fld); output (", %d);\n", (int)CB_DEBUG(x)->size); output_prefix (); output ("memset ("); output_data (CB_DEBUG(x)->target); code = (int)(size - CB_DEBUG(x)->size); output (" + %d, ' ', %d);\n", (int)CB_DEBUG(x)->size, code); } } break; case CB_TAG_DEBUG_CALL: output_perform_call (CB_DEBUG_CALL(x)->target, CB_DEBUG_CALL(x)->target); break; default: /* LCOV_EXCL_START */ cobc_err_msg (_("unexpected tree tag: %d"), (int)CB_TREE_TAG (x)); COBC_ABORT (); /* LCOV_EXCL_STOP */ } } /* File definition */ static int output_file_allocation (struct cb_file *f) { if (f->flag_global) { #if 0 /* RXWRXW - Global status */ if (f->file_status) { /* Force status into main storage file */ CB_FIELD_PTR (f->file_status)->flag_is_global = 1; } #endif output_storage ("\n/* Global file %s */\n", f->name); } else { output_local ("\n/* File %s */\n", f->name); } /* Output RELATIVE/RECORD KEY's */ if (f->organization == COB_ORG_RELATIVE || f->organization == COB_ORG_INDEXED) { if (f->flag_global) { output_storage ("static cob_file_key\t*%s%s = NULL;\n", CB_PREFIX_KEYS, f->cname); } else { output_local ("static cob_file_key\t*%s%s = NULL;\n", CB_PREFIX_KEYS, f->cname); } } if (f->flag_global) { output_storage ("static cob_file\t\t*%s%s = NULL;\n", CB_PREFIX_FILE, f->cname); output_storage ("static unsigned char\t%s%s_status[4];\n", CB_PREFIX_FILE, f->cname); } else { output_local ("static cob_file\t\t*%s%s = NULL;\n", CB_PREFIX_FILE, f->cname); output_local ("static unsigned char\t%s%s_status[4];\n", CB_PREFIX_FILE, f->cname); } if (f->code_set) { gen_native = 1; switch (f->code_set->alphabet_type) { case CB_ALPHABET_ASCII: gen_ebcdic_ascii = 1; break; case CB_ALPHABET_EBCDIC: gen_full_ebcdic = 1; break; case CB_ALPHABET_CUSTOM: gen_custom = 1; break; default: break; } } if (f->linage) { return 1; } return 0; } static void output_file_initialization (struct cb_file *f) { struct cb_alt_key *l; int nkeys; int features; char key_ptr[64]; output_line ("/* File initialization for %s */", f->name); if (f->organization == COB_ORG_RELATIVE || f->organization == COB_ORG_INDEXED) { nkeys = 1; for (l = f->alt_key_list; l; l = l->next) { nkeys++; } sprintf (key_ptr,"&%s%s",CB_PREFIX_KEYS, f->cname); } else { nkeys = 0; strcpy(key_ptr,"NULL"); } if (f->flag_external) { output_line ("cob_file_external_addr (\"%s\", &%s%s, %s, %d, %d);", f->cname, CB_PREFIX_FILE, f->cname, key_ptr, nkeys, f->linage?1:0); output_line ("if (cob_glob_ptr->cob_initial_external)"); output_indent ("{"); } else { output_line ("cob_file_malloc (&%s%s, %s, %d, %d);", CB_PREFIX_FILE, f->cname, key_ptr, nkeys, f->linage?1:0); } nkeys = 1; /* Output RELATIVE/RECORD KEY's */ if (f->organization == COB_ORG_RELATIVE || f->organization == COB_ORG_INDEXED) { nkeys = 1; output_prefix (); output ("%s%s->field = ", CB_PREFIX_KEYS, f->cname); output_param (f->key, -1); output (";\n"); output_prefix (); output ("%s%s->flag = 0;\n", CB_PREFIX_KEYS, f->cname); output_prefix (); if (f->key) { output ("%s%s->offset = %d;\n", CB_PREFIX_KEYS, f->cname, cb_code_field (f->key)->offset); } else { output ("%s%s->offset = 0;\n", CB_PREFIX_KEYS, f->cname); } for (l = f->alt_key_list; l; l = l->next) { output_prefix (); output ("(%s%s + %d)->field = ", CB_PREFIX_KEYS, f->cname, nkeys); output_param (l->key, -1); output (";\n"); output_prefix (); output ("(%s%s + %d)->flag = %d;\n", CB_PREFIX_KEYS, f->cname, nkeys, l->duplicates); output_prefix (); output ("(%s%s + %d)->offset = %d;\n", CB_PREFIX_KEYS, f->cname, nkeys, cb_code_field (l->key)->offset); nkeys++; } } output_line ("%s%s->select_name = (const char *)\"%s\";", CB_PREFIX_FILE, f->cname, f->name); if (f->flag_external && !f->file_status) { output_line ("%s%s->file_status = cob_external_addr (\"%s%s_status\", 4);", CB_PREFIX_FILE, f->cname, CB_PREFIX_FILE, f->cname); } else { output_line ("%s%s->file_status = %s%s_status;", CB_PREFIX_FILE, f->cname, CB_PREFIX_FILE, f->cname); output_line ("memset (%s%s_status, '0', 2);", CB_PREFIX_FILE, f->cname); } output_prefix (); output ("%s%s->assign = ", CB_PREFIX_FILE, f->cname); output_param (f->assign, -1); output (";\n"); output_prefix (); output ("%s%s->record = ", CB_PREFIX_FILE, f->cname); output_param (CB_TREE (f->record), -1); output (";\n"); output_prefix (); output ("%s%s->variable_record = ", CB_PREFIX_FILE, f->cname); if (f->record_depending) { output_param (f->record_depending, -1); } else { output ("NULL"); } output (";\n"); output_line ("%s%s->record_min = %d;", CB_PREFIX_FILE, f->cname, f->record_min); output_line ("%s%s->record_max = %d;", CB_PREFIX_FILE, f->cname, f->record_max); if (f->organization == COB_ORG_RELATIVE || f->organization == COB_ORG_INDEXED) { output_line ("%s%s->nkeys = %d;", CB_PREFIX_FILE, f->cname, nkeys); output_line ("%s%s->keys = %s%s;", CB_PREFIX_FILE, f->cname, CB_PREFIX_KEYS, f->cname); } else { output_line ("%s%s->nkeys = 0;", CB_PREFIX_FILE, f->cname); output_line ("%s%s->keys = NULL;", CB_PREFIX_FILE, f->cname); } output_line ("%s%s->file = NULL;", CB_PREFIX_FILE, f->cname); if (f->linage) { output_line ("lingptr = %s%s->linorkeyptr;", CB_PREFIX_FILE, f->cname); output_prefix (); output ("lingptr->linage = "); output_param (f->linage, -1); output (";\n"); output_prefix (); output ("lingptr->linage_ctr = "); output_param (f->linage_ctr, -1); output (";\n"); if (f->latfoot) { output_prefix (); output ("lingptr->latfoot = "); output_param (f->latfoot, -1); output (";\n"); } else { output_line ("lingptr->latfoot = NULL;"); } if (f->lattop) { output_prefix (); output ("lingptr->lattop = "); output_param (f->lattop, -1); output (";\n"); } else { output_line ("lingptr->lattop = NULL;"); } if (f->latbot) { output_prefix (); output ("lingptr->latbot = "); output_param (f->latbot, -1); output (";\n"); } else { output_line ("lingptr->latbot = NULL;"); } output_line ("lingptr->lin_lines = 0;"); output_line ("lingptr->lin_foot = 0;"); output_line ("lingptr->lin_top = 0;"); output_line ("lingptr->lin_bot = 0;"); } output_line ("%s%s->fd = -1;", CB_PREFIX_FILE, f->cname); output_line ("%s%s->organization = %d;", CB_PREFIX_FILE, f->cname, f->organization); output_line ("%s%s->access_mode = %d;", CB_PREFIX_FILE, f->cname, f->access_mode); output_line ("%s%s->lock_mode = " CB_FMT_LLD ";", CB_PREFIX_FILE, f->cname, f->lock_mode); output_line ("%s%s->open_mode = 0;", CB_PREFIX_FILE, f->cname); output_line ("%s%s->flag_optional = %d;", CB_PREFIX_FILE, f->cname, f->optional); features = 0; if (f->file_status) { features |= COB_SELECT_FILE_STATUS; } if (f->linage) { features |= COB_SELECT_LINAGE; } if (f->flag_ext_assign) { features |= COB_SELECT_EXTERNAL; } if (f->special) { /* Special assignment */ features |= f->special; } output_line ("%s%s->flag_select_features = %d;", CB_PREFIX_FILE, f->cname, features); if (f->flag_external) { output_indent ("}"); } output_newline (); } /* Screen definition */ static void output_screen_definition (struct cb_field *p) { int type; if (p->sister) { output_screen_definition (p->sister); } if (p->children) { output_screen_definition (p->children); } type = (p->children ? COB_SCREEN_TYPE_GROUP : p->values ? COB_SCREEN_TYPE_VALUE : (p->size > 0) ? COB_SCREEN_TYPE_FIELD : COB_SCREEN_TYPE_ATTRIBUTE); if (type == COB_SCREEN_TYPE_FIELD || type == COB_SCREEN_TYPE_VALUE) { p->count++; } output_local ("static cob_screen\ts_%d;\n", p->id); } static void output_screen_init (struct cb_field *p, struct cb_field *previous) { int type; type = (p->children ? COB_SCREEN_TYPE_GROUP : p->values ? COB_SCREEN_TYPE_VALUE : (p->size > 0) ? COB_SCREEN_TYPE_FIELD : COB_SCREEN_TYPE_ATTRIBUTE); output_prefix (); output ("cob_set_screen (&s_%d, ", p->id); if (p->sister && p->sister->level != 1) { output ("&s_%d, ", p->sister->id); } else { output ("NULL, "); } if (previous && previous->level != 1) { output ("&s_%d, ", previous->id); } else { output ("NULL, "); } output_newline (); output_prefix (); output ("\t\t "); if (type == COB_SCREEN_TYPE_GROUP) { output ("&s_%d, ", p->children->id); } else { output ("NULL, "); } if (p->parent) { output ("&s_%d, ", p->parent->id); } else { output ("NULL, "); } if (type == COB_SCREEN_TYPE_FIELD) { output_param (cb_build_field_reference (p, NULL), -1); output (", "); } else { output ("NULL, "); } output_newline (); output_prefix (); output ("\t\t "); if (type == COB_SCREEN_TYPE_VALUE) { /* Need a field reference here */ output_param (cb_build_field_reference (p, NULL), -1); output (", "); } else { output ("NULL, "); } if (p->screen_line) { output_param (p->screen_line, 0); output (", "); } else { output ("NULL, "); } if (p->screen_column) { output_param (p->screen_column, 0); output (", "); } else { output ("NULL, "); } output_newline (); output_prefix (); output ("\t\t "); if (p->screen_foreg) { output_param (p->screen_foreg, 0); output (", "); } else { output ("NULL, "); } if (p->screen_backg) { output_param (p->screen_backg, 0); output (", "); } else { output ("NULL, "); } if (p->screen_prompt) { output_param (p->screen_prompt, 0); output (", "); } else { output ("NULL, "); } output_newline (); output_prefix (); output ("\t\t "); output ("%d, %d, 0x" CB_FMT_LLX ");\n", type, p->occurs_min, p->screen_flag); if (p->children) { output_screen_init (p->children, NULL); } if (p->sister) { output_screen_init (p->sister, p); } } /* Alphabet-name */ static int literal_value (cb_tree x) { if (x == cb_space) { return ' '; } else if (x == cb_zero) { return '0'; } else if (x == cb_quote) { return cb_flag_apostrophe ? '\'' : '"'; } else if (x == cb_norm_low) { return 0; } else if (x == cb_norm_high) { return 255; } else if (x == cb_null) { return 0; } else if (CB_TREE_CLASS (x) == CB_CLASS_NUMERIC) { return cb_get_int (x) - 1; } else { return CB_LITERAL (x)->data[0]; } } static void output_alphabet_name_definition (struct cb_alphabet_name *p) { int i; if (p->alphabet_type != CB_ALPHABET_CUSTOM) { return; } /* Output the table */ output_local ("static const unsigned char %s%s[256] = {\n", CB_PREFIX_SEQUENCE, p->cname); for (i = 0; i < 256; i++) { if (i == 255) { output_local (" %d", p->values[i]); } else { output_local (" %d,", p->values[i]); } if (i % 16 == 15) { output_local ("\n"); } } output_local ("};\n"); i = lookup_attr (COB_TYPE_ALPHANUMERIC, 0, 0, 0, NULL, 0); output_local ("static cob_field %s%s = { 256, (cob_u8_ptr)%s%s, &%s%d };\n", CB_PREFIX_FIELD, p->cname, CB_PREFIX_SEQUENCE, p->cname, CB_PREFIX_ATTR, i); output_local ("\n"); } /* Class definition */ static void output_class_name_definition (struct cb_class_name *p) { cb_tree l; cb_tree x; unsigned char *data; size_t i; size_t size; int n; int lower; int upper; int vals[256]; output_line ("static int"); output_line ("%s (cob_field *f)", p->cname); output_indent ("{"); output_line ("size_t\ti;\n"); output_line ("for (i = 0; i < f->size; i++)"); output_indent ("{"); output_line ("switch (f->data[i]) {"); memset (vals, 0, sizeof(vals)); for (l = p->list; l; l = CB_CHAIN (l)) { x = CB_VALUE (l); if (CB_PAIR_P (x)) { lower = literal_value (CB_PAIR_X (x)); upper = literal_value (CB_PAIR_Y (x)); for (n = lower; n <= upper; ++n) { vals[n] = 1; } } else { if (CB_NUMERIC_LITERAL_P (x)) { vals[literal_value (x)] = 1; } else if (x == cb_space) { vals[' '] = 1; } else if (x == cb_zero) { vals['0'] = 1; } else if (x == cb_quote) { if (cb_flag_apostrophe) { vals['\''] = 1; } else { vals['"'] = 1; } } else if (x == cb_null) { vals[0] = 1; } else if (x == cb_low) { vals[0] = 1; } else if (x == cb_high) { vals[255] = 1; } else { size = CB_LITERAL (x)->size; data = CB_LITERAL (x)->data; for (i = 0; i < size; i++) { vals[data[i]] = 1; } } } } for (i = 0; i < 256; ++i) { if (vals[i]) { output_line ("case %d:", (int)i); } } output_line (" break;"); output_line ("default:"); output_line (" return 0;"); output_line ("}"); output_indent ("}"); output_line ("return 1;"); output_indent ("}"); output_newline (); } static void output_class_names (struct cb_program *prog) { cb_tree l; if (!prog->nested_level && prog->class_name_list) { output ("/* Class names */\n"); for (l = prog->class_name_list; l; l = CB_CHAIN (l)) { output_class_name_definition (CB_CLASS_NAME (CB_VALUE (l))); } } } static void output_initial_values (struct cb_field *f) { struct cb_field *p; cb_tree x; for (p = f; p; p = p->sister) { x = cb_build_field_reference (p, NULL); if (p->flag_item_based) { continue; } /* For special registers */ if (p->flag_no_init && !p->count) { continue; } output_stmt (cb_build_initialize (x, cb_true, NULL, 1, 0, 0)); } } #if 0 /* BWT coerce linkage values to picture */ /** * Ensure linkage items match picture */ static void output_coerce_linkage (struct cb_field *f) { struct cb_field *p; cb_tree x; for (p = f; p; p = p->sister) { x = cb_build_field_reference (p, NULL); if (p->flag_item_based) { continue; } /* For special registers */ if (p->flag_no_init && !p->count) { continue; } output_stmt (cb_build_move (x, x)); } } #endif static void output_error_handler (struct cb_program *prog) { struct handler_struct *hstr; size_t seen; unsigned int parameter_count, pcounter, hcounter; output_newline (); seen = 0; for (hcounter = COB_OPEN_INPUT; hcounter <= COB_OPEN_EXTEND; hcounter++) { if (prog->global_handler[hcounter].handler_label) { seen = 1; break; } } output_stmt (cb_standard_error_handler); output_newline (); if (seen) { output_line ("switch (cob_glob_ptr->cob_error_file->last_open_mode)"); output_indent ("{"); for (hcounter = COB_OPEN_INPUT; hcounter <= COB_OPEN_EXTEND; hcounter++) { hstr = &prog->global_handler[hcounter]; if (hstr->handler_label) { output_line ("case %u:", hcounter); output_indent ("{"); if (prog == hstr->handler_prog) { output_perform_call (hstr->handler_label, hstr->handler_label); } else { output_prefix (); if (hstr->handler_prog->nested_level) { output ("%s_%d_ (%d", hstr->handler_prog->program_id, hstr->handler_prog->toplev_count, hstr->handler_label->id); } else { output ("%s_ (%d", hstr->handler_prog->program_id, hstr->handler_label->id); } parameter_count = cb_list_length (hstr->handler_prog->parameter_list); for (pcounter = 0; pcounter < parameter_count; pcounter++) { output (", NULL"); } output (");\n"); } output_line ("break;"); output_indent ("}"); } } output_line ("default:"); output_indent ("{"); } output_line ("if (!(cob_glob_ptr->cob_error_file->flag_select_features & COB_SELECT_FILE_STATUS)) {"); output_line ("\tcob_fatal_error (COB_FERROR_FILE);"); output_line ("}"); if (seen) { output_line ("break;"); output_indent ("}"); output_indent ("}"); } output_perform_exit (CB_LABEL (cb_standard_error_handler)); output_newline (); output_line ("/* Fatal error if reached */"); output_line ("cob_fatal_error (COB_FERROR_CODEGEN);"); output_newline (); } static void output_module_init (struct cb_program *prog) { #if 0 /* Module comments */ output ("/* Next pointer, Parameter list pointer, Module name, */\n"); output ("/* Module formatted date, Module source, */\n"); output ("/* Module entry, Module cancel, */\n"); output ("/* Collating, CRT status, CURSOR, */\n"); output ("/* Module reference count, Module path, Module active, */\n"); output ("/* Module date, Module time, */\n"); output ("/* Module type, Number of USING parameters, Return type */\n"); output ("/* Current parameter count */\n"); output ("/* Display sign, Decimal point, Currency symbol, */\n"); output ("/* Numeric separator, File name mapping, Binary truncate, */\n"); output ("/* Alternate numeric display, Host sign, No physical cancel */\n"); output ("/* Flag main program, Fold call, Exit after CALL */\n\n"); #endif /* Do not initialize next pointer, parameter list pointer + count */ output_line ("/* Initialize module structure */"); output_line ("module->module_name = \"%s\";", prog->orig_program_id); output_line ("module->module_formatted_date = COB_MODULE_FORMATTED_DATE;"); output_line ("module->module_source = COB_SOURCE_FILE;"); if (!prog->nested_level) { output_line ("module->module_entry.funcptr = (void *(*)())%s;", prog->program_id); if (prog->prog_type == CB_FUNCTION_TYPE) { output_line ("module->module_cancel.funcptr = NULL;"); } else { output_line ("module->module_cancel.funcptr = (void *(*)())%s_;", prog->program_id); } } else { output_line ("module->module_entry.funcvoid = NULL;"); output_line ("module->module_cancel.funcvoid = NULL;"); } if (prog->collating_sequence) { output_prefix (); output ("module->collating_sequence = "); output_param (cb_ref (prog->collating_sequence), -1); output (";\n"); } else { output_line ("module->collating_sequence = NULL;"); } if (prog->crt_status && cb_code_field (prog->crt_status)->count) { output_prefix (); output ("module->crt_status = "); output_param (cb_ref (prog->crt_status), -1); output (";\n"); } else { output_line ("module->crt_status = NULL;"); } if (prog->cursor_pos) { output_prefix (); output ("module->cursor_pos = "); output_param (cb_ref (prog->cursor_pos), -1); output (";\n"); } else { output_line ("module->cursor_pos = NULL;"); } if (!cobc_flag_main && non_nested_count > 1) { output_line ("module->module_ref_count = &cob_reference_count;"); } else { output_line ("module->module_ref_count = NULL;"); } output_line ("module->module_path = &cob_module_path;"); output_line ("module->module_active = 0;"); output_line ("module->module_date = COB_MODULE_DATE;"); output_line ("module->module_time = COB_MODULE_TIME;"); output_line ("module->module_type = %u;", prog->prog_type); output_line ("module->module_param_cnt = %u;", prog->num_proc_params); output_line ("module->module_returning = 0;"); output_line ("module->ebcdic_sign = %d;", cb_ebcdic_sign); output_line ("module->decimal_point = '%c';", prog->decimal_point); output_line ("module->currency_symbol = '%c';", prog->currency_symbol); output_line ("module->numeric_separator = '%c';", prog->numeric_separator); output_line ("module->flag_filename_mapping = %d;", cb_filename_mapping); output_line ("module->flag_binary_truncate = %d;", cb_binary_truncate); output_line ("module->flag_pretty_display = %d;", cb_pretty_display); output_line ("module->flag_host_sign = %d;", cb_host_sign); output_line ("module->flag_no_phys_canc = %d;", no_physical_cancel); output_line ("module->flag_main = %d;", cobc_flag_main); output_line ("module->flag_fold_call = %d;", cb_fold_call); output_line ("module->flag_exit_program = 0;"); output_newline (); } static void output_internal_function (struct cb_program *prog, cb_tree parameter_list) { cb_tree l; cb_tree l2; struct cb_field *f; struct cb_program *next_prog; struct cb_file *fl; char *p; struct label_list *pl; struct cb_alter_id *cpl; struct call_list *clp; struct base_list *bl; struct literal_list *m; FILE *savetarget; const char *s; char key_ptr[64]; unsigned int i; cob_u32_t inc; int parmnum; int seen; int anyseen; /* Program function */ #if 0 /* RXWRXW USERFUNC */ if (prog->prog_type == CB_FUNCTION_TYPE) { output ("static cob_field *\n%s_ (const int entry, cob_field **cob_parms", prog->program_id); #else if (prog->prog_type == CB_FUNCTION_TYPE) { output ("static cob_field *\n%s_ (const int entry", prog->program_id); #endif } else if (!prog->nested_level) { output ("static int\n%s_ (const int entry", prog->program_id); } else { output ("static int\n%s_%d_ (const int entry", prog->program_id, prog->toplev_count); } parmnum = 0; #if 0 /* RXWRXW USERFUNC */ if (!prog->flag_chained && prog->prog_type != CB_FUNCTION_TYPE) { #else if (!prog->flag_chained) { #endif for (l = parameter_list; l; l = CB_CHAIN (l)) { if (l == parameter_list) { output (", "); } if (parmnum && !(parmnum % 2)) { output ("\n\t"); } output ("cob_u8_t *%s%d", CB_PREFIX_BASE, cb_code_field (CB_VALUE (l))->id); if (CB_CHAIN (l)) { output (", "); } parmnum++; } } output (")\n"); output_indent ("{"); /* Program local variables */ output_line ("/* Program local variables */"); output_line ("#include \"%s\"", prog->local_include->local_name); output_newline (); /* Alphabet-names */ if (prog->alphabet_name_list) { for (l = prog->alphabet_name_list; l; l = CB_CHAIN (l)) { output_alphabet_name_definition (CB_ALPHABET_NAME (CB_VALUE (l))); } } #if 0 /* cob_call_name_hash and cob_call_from_c are rw-branch only features for now - TODO: activate on merge of r1547 */ output_line ("/* Entry point name_hash values */"); output_line ("static const unsigned int %sname_hash [] = {",CB_PREFIX_STRING); if (cb_list_length (prog->entry_list) > 1) { for (i = 0, l = prog->entry_list; l; l = CB_CHAIN (l)) { name_hash = ; output_line ("\t0x%X,\t/* %d: %s */", cob_get_name_hash (CB_LABEL (CB_PURPOSE (l))->name), i, CB_LABEL (CB_PURPOSE (l))->name); i++; } } else { name_hash = ; output_line ("\t0x%X,\t/* %s */", cob_get_name_hash (prog->orig_program_id), prog->orig_program_id); } output_line ("0};"); #endif /* Module initialization indicator */ output_local ("/* Module initialization indicator */\n"); output_local ("static unsigned int\tinitialized = 0;\n\n"); if (prog->flag_recursive) { output_local ("/* Module structure pointer for recursive */\n"); output_local ("cob_module\t\t*module = NULL;\n\n"); } else { output_local ("/* Module structure pointer */\n"); output_local ("static cob_module\t*module = NULL;\n\n"); } output_local ("/* Global variable pointer */\n"); output_local ("cob_global\t\t*cob_glob_ptr;\n\n"); /* Decimal structures */ if (prog->decimal_index_max) { output_local ("/* Decimal structures */\n"); for (i = 0; i < prog->decimal_index_max; i++) { output_local ("\tcob_decimal\t*d%d = NULL;\n", i); } output_local ("\n"); } /* External items */ seen = 0; for (f = prog->working_storage; f; f = f->sister) { if (f->flag_external) { if (f->flag_is_global) { bl = cobc_parse_malloc (sizeof (struct base_list)); bl->f = f; bl->curr_prog = excp_current_program_id; bl->next = globext_cache; globext_cache = bl; continue; } if (!seen) { seen = 1; output_local ("/* EXTERNAL items */\n"); } output_local ("static unsigned char\t*%s%d = NULL;", CB_PREFIX_BASE, f->id); output_local (" /* %s */\n", f->name); } } if (seen) { output_local ("\n"); } for (l = prog->file_list; l; l = CB_CHAIN (l)) { f = CB_FILE (CB_VALUE (l))->record; if (f->flag_external) { if (f->flag_is_global) { bl = cobc_parse_malloc (sizeof (struct base_list)); bl->f = f; bl->curr_prog = excp_current_program_id; bl->next = globext_cache; globext_cache = bl; continue; } output_local ("static unsigned char\t*%s%d = NULL;", CB_PREFIX_BASE, f->id); output_local (" /* %s */\n", f->name); } } /* Allocate files */ if (prog->file_list) { i = 0; for (l = prog->file_list; l; l = CB_CHAIN (l)) { i += output_file_allocation (CB_FILE (CB_VALUE (l))); } if (i) { output_local ("\n/* LINAGE pointer */\n"); output_local ("static cob_linage\t\t*lingptr;\n"); } } /* BASED working-storage */ i = 0; for (f = prog->working_storage; f; f = f->sister) { if (f->redefines) { continue; } if (f->flag_item_based) { if (!i) { i = 1; output_local("\n/* BASED WORKING-STORAGE SECTION */\n"); } output_local ("static unsigned char\t*%s%d = NULL; /* %s */\n", CB_PREFIX_BASE, f->id, f->name); } } if (i) { output_local ("\n"); } /* BASED local-storage */ i = 0; for (f = prog->local_storage; f; f = f->sister) { if (f->redefines) { continue; } if (f->flag_item_based) { if (!i) { i = 1; output_local("\n/* BASED LOCAL-STORAGE */\n"); } output_local ("static unsigned char\t*%s%d = NULL; /* %s */\n", CB_PREFIX_BASE, f->id, f->name); } } if (i) { output_local ("\n"); } #if 0 /* RXWRXW USERFUNC */ if (prog->prog_type == CB_FUNCTION_TYPE) { /* USING parameters for user FUNCTION */ seen = 0; for (l = parameter_list; l; l = CB_CHAIN (l)) { f = cb_code_field (CB_VALUE (l)); if (!seen) { seen = 1; output_local ("\n/* USING parameters */\n"); } output_local ("unsigned char\t*%s%d = NULL; /* %s */\n", CB_PREFIX_BASE, f->id, f->name); } if (seen) { output_local ("\n"); } } #endif /* Dangling linkage section items */ seen = 0; for (f = prog->linkage_storage; f; f = f->sister) { if (f->redefines) { continue; } for (l = parameter_list; l; l = CB_CHAIN (l)) { if (f == cb_code_field (CB_VALUE (l))) { break; } } if (l == NULL) { if (!seen) { seen = 1; output_local ("\n/* LINKAGE SECTION (Items not referenced by USING clause) */\n"); } if (!f->flag_is_returning) { output_local ("static "); } output_local ("unsigned char\t*%s%d = NULL; /* %s */\n", CB_PREFIX_BASE, f->id, f->name); } } if (seen) { output_local ("\n"); } /* Screens */ if (prog->screen_storage) { optimize_defs[COB_SET_SCREEN] = 1; output_local ("\n/* Screens */\n\n"); output_screen_definition (prog->screen_storage); output_local ("\n"); } /* ANY LENGTH items */ anyseen = 0; for (l = parameter_list; l; l = CB_CHAIN (l)) { f = cb_code_field (CB_VALUE (l)); if (f->flag_any_length) { anyseen = 1; #if 0 /* RXWRXW - Any */ output_local ("/* ANY LENGTH variable */\n"); output_local ("cob_field\t\t*cob_anylen;\n\n"); #endif break; } } /* Save variables for global callback */ if (prog->flag_global_use && parameter_list) { output_local ("/* Parameter save */\n"); for (l = parameter_list; l; l = CB_CHAIN (l)) { f = cb_code_field (CB_VALUE (l)); output_local ("static unsigned char\t*save_%s%d;\n", CB_PREFIX_BASE, f->id); } output_local ("\n"); } /* Runtime DEBUGGING MODE variable */ if (prog->flag_debugging) { output_line ("char\t\t*s;"); output_newline (); } /* Start of function proper */ output_line ("/* Start of function code */"); output_newline (); /* CANCEL callback */ if (prog->prog_type == CB_PROGRAM_TYPE) { output_line ("/* CANCEL callback */"); output_line ("if (unlikely(entry < 0)) {"); output_line ("\tif (entry == -20)"); output_line ("\t\tgoto P_clear_decimal;"); output_line ("\tgoto P_cancel;"); output_line ("}"); output_newline (); } output_line ("/* Check initialized, check module allocated, */"); output_line ("/* set global pointer, */"); output_line ("/* push module stack, save call parameter count */"); #if 0 /* cob_call_name_hash and cob_call_from_c are rw-branch only features for now - TODO: activate on merge of r1547 */ output_line ("if (cob_module_global_enter (&module, &cob_glob_ptr, %d, entry, %sname_hash))", cb_flag_implicit_init, CB_PREFIX_STRING); #else output_line ("if (cob_module_global_enter (&module, &cob_glob_ptr, %d, entry, 0))", cb_flag_implicit_init); #endif if (prog->prog_type == CB_FUNCTION_TYPE) { output_line ("\treturn NULL;"); } else { output_line ("\treturn -1;"); } output_newline (); if (prog->flag_chained) { output_line ("/* Check program with CHAINING being main program */"); output_line ("if (cob_glob_ptr->cob_current_module->next) {"); output_line ("\tcob_fatal_error (COB_FERROR_CHAINING);"); output_line ("}"); output_newline (); } /* Recursive module initialization */ if (prog->flag_recursive) { output_module_init (prog); } /* Module Parameters */ output_line ("/* Set address of module parameter list */"); if (cb_flag_stack_on_heap || prog->flag_recursive) { if (prog->max_call_param) { i = prog->max_call_param; } else { i = 1; } output_line ("cob_procedure_params = cob_malloc (%dU * sizeof(void *));", i); } output_line ("module->cob_procedure_params = cob_procedure_params;"); output_newline (); #if 0 /* RXWRXW USERFUNC */ if (prog->prog_type == CB_FUNCTION_TYPE) { parmnum = 0; for (l = parameter_list; l; l = CB_CHAIN (l), parmnum++) { f = cb_code_field (CB_VALUE (l)); output_line ("if (cob_parms[%d])", parmnum); output_line (" %s%d = cob_parms[%d]->data;", CB_PREFIX_BASE, f->id, parmnum); output_line ("else"); output_line (" %s%d = NULL;", CB_PREFIX_BASE, f->id); } output_newline (); } #endif output_line ("/* Set frame stack pointer */"); if (cb_flag_stack_on_heap || prog->flag_recursive) { if (prog->flag_recursive && cb_stack_size == 255) { i = 63; } else { i = cb_stack_size; } output_line ("frame_stack = cob_malloc (%dU * sizeof(struct cob_frame));", i); output_line ("frame_ptr = frame_stack;"); if (cb_flag_stack_check) { output_line ("frame_overflow = frame_ptr + %d - 1;", i); } } else { output_line ("frame_ptr = frame_stack;"); output_line ("frame_ptr->perform_through = 0;"); if (cb_flag_stack_check) { output_line ("frame_overflow = frame_ptr + %d - 1;", cb_stack_size); } } output_newline (); /* Set up LOCAL-STORAGE size */ if (prog->local_storage) { for (f = prog->local_storage; f; f = f->sister) { if (f->flag_item_based || f->flag_local_alloced) { continue; } if (f->redefines) { continue; } if (f->flag_item_78) { /* LCOV_EXCL_START */ cobc_err_msg (_("unexpected CONSTANT item")); COBC_ABORT (); /* LCOV_EXCL_STOP */ } f->flag_local_storage = 1; f->flag_local_alloced = 1; f->mem_offset = local_mem; /* Round up to COB_MALLOC_ALIGN + 1 bytes */ /* Caters for current types */ local_mem += ((f->memory_size + COB_MALLOC_ALIGN) & ~COB_MALLOC_ALIGN); } } /* Initialization */ /* Allocate and initialize LOCAL storage */ if (prog->local_storage) { if (local_mem) { output_line ("/* Allocate LOCAL storage */"); output_line ("cob_local_ptr = cob_malloc (%dU);", local_mem); if (prog->flag_global_use) { output_line ("cob_local_save = cob_local_ptr;"); } } output_newline (); output_line ("/* Initialize LOCAL storage */"); output_initial_values (prog->local_storage); output_newline (); } output_line ("/* Initialize rest of program */"); output_line ("if (unlikely(initialized == 0)) {"); output_line ("\tgoto P_initialize;"); output_line ("}"); output_line ("P_ret_initialize:"); output_newline (); if (prog->decimal_index_max) { output_line ("/* Allocate decimal numbers */"); output_prefix (); if (prog->flag_recursive) { output ("cob_decimal_push (%u", prog->decimal_index_max); } else { output ("cob_decimal_alloc (%u", prog->decimal_index_max); } for (i = 0; i < prog->decimal_index_max; i++) { output (", &d%u", i); } output (");\n"); output_newline (); } /* Global entry dispatch */ if (prog->global_list) { output_line ("/* Global entry dispatch */"); output_newline (); for (l = prog->global_list; l; l = CB_CHAIN (l)) { output_line ("if (unlikely(entry == %d)) {", CB_LABEL (CB_VALUE (l))->id); if (local_mem) { output_line ("\tcob_local_ptr = cob_local_save;"); } for (l2 = parameter_list; l2; l2 = CB_CHAIN (l2)) { f = cb_code_field (CB_VALUE (l2)); output_line ("\t%s%d = save_%s%d;", CB_PREFIX_BASE, f->id, CB_PREFIX_BASE, f->id); } output_line ("\tgoto %s%d;", CB_PREFIX_LABEL, CB_LABEL (CB_VALUE (l))->id); output_line ("}"); } output_newline (); } if (!prog->flag_recursive) { output_line ("/* Increment module active */"); output_line ("module->module_active++;"); output_newline (); } if (!cobc_flag_main && non_nested_count > 1) { output_line ("/* Increment module reference count */"); output_line ("cob_reference_count++;"); output_newline (); } /* Initialize W/S and files unconditionally when INITIAL program */ if (prog->flag_initial) { if (prog->working_storage) { output_line ("/* Initialize INITIAL program WORKING-STORAGE */"); output_initial_values (prog->working_storage); output_newline (); } if (prog->file_list) { for (l = prog->file_list; l; l = CB_CHAIN (l)) { output_file_initialization (CB_FILE (CB_VALUE (l))); } } } /* Call parameters */ if (prog->cb_call_params && cb_code_field (prog->cb_call_params)->count) { output_line ("/* Set NUMBER-OF-CALL-PARAMETERS (independent from LINKAGE) */"); output_prefix (); output_integer (prog->cb_call_params); output (" = cob_glob_ptr->cob_call_params;\n"); output_newline (); } #if 0 /* RXWRXW - Params (in each module or in cob_module_enter) */ output_line ("/* Save number of call params */"); output_line ("module->module_num_params = cob_glob_ptr->cob_call_params;"); output_newline (); #endif if (!cb_sticky_linkage && !prog->flag_chained #if 0 /* RXWRXW USERFUNC */ && prog->prog_type != CB_FUNCTION_TYPE #endif && prog->num_proc_params) { output_line ("/* Set not passed parameter pointers to NULL */"); output_line ("switch (cob_call_params) {"); i = 0; for (l = parameter_list; l; l = CB_CHAIN (l)) { output_line ("case %d:", i++); output_line ("\t%s%d = NULL;", CB_PREFIX_BASE, cb_code_field (CB_VALUE (l))->id); } output_line ("default:\n\tbreak;"); output_line ("}"); output_newline (); } /* Set up ANY length items */ i = 0; if (anyseen) { output_line ("/* Initialize ANY LENGTH parameters */"); for (l = parameter_list; l; l = CB_CHAIN (l), i++) { f = cb_code_field (CB_VALUE (l)); if (f->flag_any_length) { /* Force field cache */ savetarget = output_target; output_target = NULL; output_param (CB_VALUE (l), i); output_target = savetarget; output_line ("if (cob_call_params > %d && %s%d%s)", i, "module->next->cob_procedure_params[", i, "]"); if (f->flag_any_numeric) { /* Copy complete structure */ output_line (" %s%d = *(%s%d%s);", CB_PREFIX_FIELD, f->id, "module->next->cob_procedure_params[", i, "]"); } else { /* Copy size */ output_line (" %s%d.size = %s%d%s;", CB_PREFIX_FIELD, f->id, "module->next->cob_procedure_params[", i, "]->size"); } output_prefix (); output ("%s%d.data = ", CB_PREFIX_FIELD, f->id); output_data (CB_VALUE (l)); output (";\n"); #if 0 /* RXWRXW - Num check */ if (CB_EXCEPTION_ENABLE (COB_EC_DATA_INCOMPATIBLE) && f->flag_any_numeric && (f->usage == CB_USAGE_DISPLAY || f->usage == CB_USAGE_PACKED || f->usage == CB_USAGE_COMP_6)) { output_line ("cob_check_numeric (&%s%d, %s%d);", CB_PREFIX_FIELD f->id, CB_PREFIX_STRING, lookup_string (f->name)); } #endif } } output_newline (); #if 0 /* cob_call_name_hash and cob_call_from_c are rw-branch only features for now - TODO: activate on merge of r1547 */ name_hash = cob_get_name_hash (prog->orig_program_id); output_line ("if (cob_glob_ptr->cob_call_name_hash != 0x%X) {", name_hash); output_line (" cob_glob_ptr->cob_call_from_c = 1;"); output_line ("} else {"); output_line (" cob_glob_ptr->cob_call_from_c = 0;"); for (i = 0, l = parameter_list; l; l = CB_CHAIN (l), i++) { pickup_param (l, i, 0); } output_line ("}"); #endif } if (prog->prog_type == CB_FUNCTION_TYPE && CB_FIELD_PTR(prog->returning)->storage == CB_STORAGE_LINKAGE) { output_line ("/* Storage for returning item */"); output_prefix (); output_data (prog->returning); output (" = cob_malloc ("); output_size (prog->returning); output ("U);\n\n"); } if (prog->flag_global_use && parameter_list) { output_line ("/* Parameter save */"); for (l = parameter_list; l; l = CB_CHAIN (l)) { f = cb_code_field (CB_VALUE (l)); output_line ("save_%s%d = %s%d;", CB_PREFIX_BASE, f->id, CB_PREFIX_BASE, f->id); } output_newline (); } /* Classification */ if (prog->classification) { if (prog->classification == cb_int1) { output_line ("cob_set_locale (NULL, COB_LC_CLASS);"); } else { output_prefix (); output ("cob_set_locale ("); output_param (prog->classification, -1); output (", COB_LC_CTYPE);"); } output_newline (); } /* Entry dispatch */ output_line ("/* Entry dispatch */"); if (cb_list_length (prog->entry_list) > 1) { output_newline (); output_line ("switch (entry)"); output_line (" {"); for (i = 0, l = prog->entry_list; l; l = CB_CHAIN (l)) { output_line (" case %d:", i++); output_line (" goto %s%d;", CB_PREFIX_LABEL, CB_LABEL (CB_PURPOSE (l))->id); } output_line (" }"); output_line ("/* This should never be reached */"); output_line ("cob_fatal_error (COB_FERROR_MODULE);"); output_newline (); } else { l = prog->entry_list; output_line ("goto %s%d;", CB_PREFIX_LABEL, CB_LABEL (CB_PURPOSE (l))->id); output_newline (); } /* PROCEDURE DIVISION */ output_line ("/* PROCEDURE DIVISION */"); for (l = prog->exec_list; l; l = CB_CHAIN (l)) { output_stmt (CB_VALUE (l)); } output_newline (); /* End of program */ output_line ("/* Program exit */"); output_newline (); if (needs_exit_prog) { output_line ("exit_program:"); output_newline (); } if (!prog->flag_recursive) { output_line ("/* Decrement module active count */"); output_line ("if (module->module_active) {"); output_line ("\tmodule->module_active--;"); output_line ("}"); output_newline (); } if (!cobc_flag_main && non_nested_count > 1) { output_line ("/* Decrement module reference count */"); output_line ("if (cob_reference_count) {"); output_line ("\tcob_reference_count--;"); output_line ("}"); output_newline (); } if (gen_dynamic) { output_line ("/* Deallocate dynamic FUNCTION-ID fields */"); for (inc = 0; inc < gen_dynamic; inc++) { output_line ("if (cob_dyn_%u) {", inc); output_line (" if (cob_dyn_%u->data) {", inc); output_line (" cob_free (cob_dyn_%u->data);", inc); output_line (" }"); output_line (" cob_free (cob_dyn_%u);", inc); output_line (" cob_dyn_%u = NULL;", inc); output_line ("}"); } output_newline (); } if (prog->local_storage) { output_line ("/* Deallocate LOCAL storage */"); if (local_mem) { output_line ("if (cob_local_ptr) {"); output_line ("\tfree (cob_local_ptr);"); output_line ("\tcob_local_ptr = NULL;"); if (current_prog->flag_global_use) { output_line ("\tcob_local_save = NULL;"); } output_line ("}"); } for (f = prog->local_storage; f; f = f->sister) { if (f->flag_item_based) { output_line ("if (%s%d) {", CB_PREFIX_BASE, f->id); output_line ("\tcob_free_alloc (&%s%d, NULL);", CB_PREFIX_BASE, f->id); output_line ("\t%s%d = NULL;", CB_PREFIX_BASE, f->id); output_line ("}"); } } output_newline (); } if (prog->decimal_index_max && prog->flag_recursive) { output_line ("/* Free decimal structures */"); output_prefix (); output ("cob_decimal_pop (%u", prog->decimal_index_max); for (i = 0; i < prog->decimal_index_max; i++) { output (", d%u", i); } output (");\n"); output_newline (); } if (cb_flag_stack_on_heap || prog->flag_recursive) { output_line ("/* Free frame stack / call parameters */"); output_line ("cob_free (frame_stack);"); output_line ("cob_free (cob_procedure_params);"); output_newline (); } if (cb_flag_trace) { output_line ("/* Trace program exit */"); sprintf (string_buffer, "Exit: %s", excp_current_program_id); output_line ("cob_trace_section (%s%d, NULL, 0);", CB_PREFIX_STRING, lookup_string (string_buffer)); output_newline (); } output_line ("/* Pop module stack */"); output_line ("cob_module_leave (module);"); output_newline (); if (prog->flag_recursive) { output_line ("/* Free for recursive module */"); output_line ("cob_module_free (&module);"); output_newline (); } /* Implicit CANCEL for INITIAL program */ if (prog->flag_initial) { output_line ("/* CANCEL for INITIAL program */"); output_prefix (); if (!prog->nested_level) { output ("%s_ (-1", prog->program_id); } else { output ("%s_%d_ (-1", prog->program_id, prog->toplev_count); } if (!prog->flag_chained) { for (l = parameter_list; l; l = CB_CHAIN (l)) { output (", NULL"); } } output (");\n"); output_newline (); } output_line ("/* Program return */"); if (prog->returning && prog->cb_return_code) { output_move (prog->returning, prog->cb_return_code); } output_prefix (); output ("return "); if (prog->prog_type == CB_FUNCTION_TYPE) { output_param (prog->returning, -1); } else if (prog->cb_return_code) { output_integer (prog->cb_return_code); } else { output ("0"); } output (";\n"); /* Error handlers */ if (prog->file_list || prog->flag_gen_error) { output_error_handler (prog); } /* Frame stack jump table for compiler without computed goto */ if (!cb_flag_computed_goto) { output_newline (); output_line ("/* Frame stack jump table */"); output_line ("P_switch:"); if (label_cache) { output_line (" switch (frame_ptr->return_address_num) {"); for (pl = label_cache; pl; pl = pl->next) { output_line (" case %d:", pl->call_num); output_line (" goto %s%d;", CB_PREFIX_LABEL, pl->id); } output_line (" }"); } output_line (" cob_fatal_error (COB_FERROR_CODEGEN);"); output_newline (); } /* Program initialization */ #if 0 /* RXWRXW WS */ if (prog->working_storage) { for (f = prog->working_storage; f; f = f->sister) { if (f->flag_item_based || f->flag_local_alloced) { continue; } if (f->redefines || f->flag_external) { continue; } #if 0 /* RXWRXW - Check global */ if (f->flag_is_global) { continue; } #endif if (f->flag_no_init && !f->count) { continue; } if (f->flag_item_78) { /* LCOV_EXCL_START */ cobc_err_msg (_("unexpected CONSTANT item")); COBC_ABORT (); /* LCOV_EXCL_STOP */ } if (f->flag_is_global) { f->mem_offset = working_mem; working_mem += ((f->memory_size + COB_MALLOC_ALIGN) & ~COB_MALLOC_ALIGN); } else { f->mem_offset = local_working_mem; local_working_mem += ((f->memory_size + COB_MALLOC_ALIGN) & ~COB_MALLOC_ALIGN); } } } #endif output_newline (); output_line ("/* Program initialization */"); output_line ("P_initialize:"); output_newline (); /* Check matching version */ if (!prog->nested_level) { output_line ("cob_check_version (COB_SOURCE_FILE, COB_PACKAGE_VERSION, COB_PATCH_LEVEL);"); output_newline (); } /* Resolve user functions */ for (clp = func_call_cache; clp; clp = clp->next) { output_line ("func_%s.funcvoid = cob_resolve_func (\"%s\");", clp->call_name, clp->call_name); } if (cobc_flag_main && !prog->nested_level) { output_line ("cob_module_path = cob_glob_ptr->cob_main_argv0;"); output_newline (); } /* Module initialization */ if (!prog->flag_recursive) { output_module_init (prog); } /* Check runtime DEBUGGING MODE variable */ if (prog->flag_debugging) { output_line ("if ((s = getenv (\"COB_SET_DEBUG\")) && (*s == 'Y' || *s == 'y' || *s == '1'))"); output_line ("\tcob_debugging_mode = 1;"); output_newline (); } /* Setup up CANCEL callback */ if (!prog->nested_level && prog->prog_type == CB_PROGRAM_TYPE) { output_line ("/* Initialize cancel callback */"); #if 0 /* RXWRXW CA */ if (!cb_flag_implicit_init) { output_line ("if (module->next)"); } #endif output_line ("cob_set_cancel (module);"); output_newline (); } /* Initialize EXTERNAL files */ for (l = prog->file_list; l; l = CB_CHAIN (l)) { f = CB_FILE (CB_VALUE (l))->record; if (f->flag_external) { strcpy (string_buffer, f->name); for (p = string_buffer; *p; p++) { if (*p == '-' || *p == ' ') { *p = '_'; } } output_line ("%s%d = cob_external_addr (\"%s\", %d);", CB_PREFIX_BASE, f->id, string_buffer, CB_FILE (CB_VALUE (l))->record_max); } } /* Initialize WORKING-STORAGE EXTERNAL items */ for (f = prog->working_storage; f; f = f->sister) { if (f->redefines) { continue; } if (!f->flag_external) { continue; } output_prefix (); output_base (f, 0); output (" = cob_external_addr (\"%s\", %d);\n", f->ename, f->size); } /* Initialize WORKING-STORAGE/files if not INITIAL program */ if (!prog->flag_initial) { if (prog->working_storage) { output_line ("/* Initialize WORKING-STORAGE */"); output_initial_values (prog->working_storage); output_newline (); } if (prog->file_list) { for (l = prog->file_list; l; l = CB_CHAIN (l)) { output_file_initialization (CB_FILE (CB_VALUE (l))); } } i = 1; for (m = literal_cache; m; m = m->next) { if (CB_TREE_CLASS (m->x) == CB_CLASS_NUMERIC && m->make_decimal) { if (i) { i = 0; output_line ("/* Set Decimal Constant values */"); } output_line ("%s%d = &%s%d;", CB_PREFIX_DEC_CONST,m->id, CB_PREFIX_DEC_FIELD,m->id); output_line ("cob_decimal_init(%s%d);",CB_PREFIX_DEC_CONST,m->id); output_line ("cob_decimal_set_field (%s%d, (cob_field *)&%s%d);", CB_PREFIX_DEC_CONST,m->id, CB_PREFIX_CONST,m->id); output_newline (); } } } #if 0 /* BWT coerce linkage to picture */ /* Manage linkage section */ if (prog->linkage_storage) { output_line ("/* Initialize LINKAGE */"); output_coerce_linkage (prog->linkage_storage); output_newline (); } #endif if (prog->screen_storage) { output_line ("/* Initialize SCREEN items */"); /* Initialize items with VALUE */ output_initial_values (prog->screen_storage); output_screen_init (prog->screen_storage, NULL); output_newline (); } output_line ("initialized = 1;"); output_line ("goto P_ret_initialize;"); /* Set up CANCEL callback code */ if (prog->prog_type != CB_PROGRAM_TYPE) { goto prog_cancel_end; } output_newline (); output_line ("/* CANCEL callback handling */"); output_line ("P_cancel:"); output_newline (); output_line ("if (!initialized) {"); output_line ("\treturn 0;"); output_line ("}"); output_line ("if (module->module_active) {"); output_line ("\tcob_fatal_error (COB_FERROR_CANCEL);"); output_line ("}"); output_newline (); if (prog->flag_main) { goto cancel_end; } next_prog = prog->next_program; /* Check for implicit cancel of contained programs */ for (; next_prog; next_prog = next_prog->next_program) { if (next_prog->nested_level == prog->nested_level + 1) { output_prefix (); output ("(void)%s_%d_ (-1", next_prog->program_id, next_prog->toplev_count); for (i = 0; i < next_prog->num_proc_params; ++i) { output (", NULL"); } output (");\n"); } } /* Close files on cancel */ for (l = prog->file_list; l; l = CB_CHAIN (l)) { fl = CB_FILE (CB_VALUE (l)); if (fl->organization != COB_ORG_SORT) { output_line ("cob_close (%s%s, NULL, COB_CLOSE_NORMAL, 1);", CB_PREFIX_FILE, fl->cname); if (!fl->flag_external) { if (fl->organization == COB_ORG_RELATIVE || fl->organization == COB_ORG_INDEXED) { sprintf (key_ptr,"&%s%s",CB_PREFIX_KEYS, fl->cname); } else { strcpy(key_ptr,"NULL"); } output_line ("cob_file_free (&%s%s,%s);",CB_PREFIX_FILE, fl->cname,key_ptr); } } else { output_line ("cob_cache_free (%s%s);", CB_PREFIX_FILE, fl->cname); output_line ("%s%s = NULL;", CB_PREFIX_FILE, fl->cname); } } /* Clear alter indicators */ for (cpl = prog->alter_gotos; cpl; cpl = cpl->next) { output_line ("label_%s%d = 0;", CB_PREFIX_LABEL, cpl->goto_id); if (prog->flag_segments) { output_line ("save_label_%s%d = 0;", CB_PREFIX_LABEL, cpl->goto_id); } } /* Release based storage */ for (f = prog->working_storage; f; f = f->sister) { if (f->flag_item_based) { output_line ("if (%s%d) {", CB_PREFIX_BASE, f->id); output_line ("\tcob_free_alloc (&%s%d, NULL);", CB_PREFIX_BASE, f->id); output_line ("}"); } } /* Reset DEBUGGING mode */ if (prog->flag_debugging) { output_line ("cob_debugging_mode = 0;"); } /* Clear CALL pointers */ for (clp = call_cache; clp; clp = clp->next) { output_line ("call_%s.funcvoid = NULL;", clp->call_name); } for (clp = func_call_cache; clp; clp = clp->next) { output_line ("func_%s.funcvoid = NULL;", clp->call_name); } /* Clear sticky-linkage pointers */ if (cb_sticky_linkage) { for (l = prog->parameter_list; l; l = CB_CHAIN (l)) { output_line ("cob_parm_%d = NULL;", cb_code_field (CB_VALUE (l))->id); } } /* Clear RETURN-CODE */ if (!prog->nested_level && prog->cb_return_code) { output_prefix (); output_integer (current_prog->cb_return_code); output (" = 0;\n"); } output_line ("cob_module_free (&module);"); output_newline (); cancel_end: output_line ("initialized = 0;"); output_newline (); output_line ("P_clear_decimal:"); i = 1; for (m = literal_cache; m; m = m->next) { if (CB_TREE_CLASS (m->x) == CB_CLASS_NUMERIC && m->make_decimal) { if (i) { i = 0; output_line ("/* Clear Decimal Constant values */"); } output_line ("cob_decimal_clear(%s%d);",CB_PREFIX_DEC_CONST,m->id); output_line ("%s%d = NULL;",CB_PREFIX_DEC_CONST,m->id); } } output_newline (); output_line ("return 0;"); output_newline (); /* End of CANCEL callback code */ prog_cancel_end: output_indent ("}"); output_newline (); if (prog->prog_type == CB_FUNCTION_TYPE) { s = "FUNCTION-ID"; } else { s = "PROGRAM-ID"; } output_line ("/* End %s '%s' */", s, prog->orig_program_id); output_newline (); } /* Output the entry function for a COBOL function. */ static void output_function_entry_function (struct cb_program *prog, const int gencode, const char *entry_name, cb_tree using_list) { cob_u32_t parmnum = 0; cob_u32_t n; cb_tree l; if (gencode) { output ("cob_field *\n"); } else { output ("cob_field\t\t*"); } output ("%s (", entry_name); if (!gencode) { output ("cob_field **, const int"); } else { output ("cob_field **cob_fret, const int cob_pam"); } parmnum = 0; if (using_list) { output (", "); n = 0; for (l = using_list; l; l = CB_CHAIN (l), ++n, ++parmnum) { if (!gencode) { output ("cob_field *"); } else { output ("cob_field *f%u", n); } if (CB_CHAIN (l)) { output (", "); } } } if (gencode) { output (")\n"); } else { /* Finish prototype and return */ output (");\n"); return; } output_indent ("{"); output_line ("struct cob_func_loc\t*floc;"); output_newline (); output_line ("/* Save environment */"); output_prefix (); output ("floc = cob_save_func (cob_fret, cob_pam, %u", parmnum); for (n = 0; n < parmnum; ++n) { output (", f%u", n); } output (");\n"); output_line ("cob_call_params = cob_get_global_ptr ()->cob_call_params;"); output_prefix (); output ("floc->ret_fld = %s_ (0", prog->program_id); if (parmnum != 0) { output (", "); for (n = 0; n < parmnum; ++n) { output ("floc->data[%u]", n); if (n != parmnum - 1) { output (", "); } } } output (");\n"); output_line ("**cob_fret = *floc->ret_fld;"); output_line ("/* Restore environment */"); output_line ("cob_restore_func (floc);"); output_line ("return *cob_fret;"); output_indent ("}"); output_newline (); } /* Returns NULL if it could not deduce the parameter type. */ static const char * try_get_by_value_parameter_type (const enum cb_usage usage, cb_tree param_list_elt) { const int is_unsigned = CB_SIZES (param_list_elt) == CB_SIZE_UNSIGNED; if (usage == CB_USAGE_FLOAT) { return "float"; } else if (usage == CB_USAGE_DOUBLE) { return "double"; } else if (usage == CB_USAGE_LONG_DOUBLE) { return "long double"; } else if (usage == CB_USAGE_FP_BIN32) { return "cob_u32_t"; } else if (usage == CB_USAGE_FP_BIN64 || usage == CB_USAGE_FP_DEC64) { return "cob_u64_t"; } else if (usage == CB_USAGE_FP_BIN128 || usage == CB_USAGE_FP_DEC128) { return "cob_fp_128"; } else if (CB_TREE_CLASS (CB_VALUE (param_list_elt)) == CB_CLASS_NUMERIC) { /* To-do: Split this duplicated code into another function */ switch (CB_SIZES_INT (param_list_elt)) { case CB_SIZE_1: if (is_unsigned) { return "cob_u8_t"; } else { return "cob_c8_t"; } case CB_SIZE_2: if (is_unsigned) { return "cob_u16_t"; } else { return "cob_s16_t"; } case CB_SIZE_4: if (is_unsigned) { return "cob_u32_t"; } else { return "cob_s32_t"; } case CB_SIZE_8: if (is_unsigned) { return "cob_u64_t"; } else { return "cob_s64_t"; } default: break; } } return NULL; } static void output_program_entry_function_parameters (cb_tree using_list, const int gencode, const char ** const s_type) { cob_u32_t n = 0; cb_tree l; struct cb_field *f; const char *type; for (l = using_list; l; l = CB_CHAIN (l), ++n) { f = cb_code_field (CB_VALUE (l)); switch (CB_PURPOSE_INT (l)) { case CB_CALL_BY_VALUE: type = try_get_by_value_parameter_type (f->usage, l); if (type) { if (gencode) { output ("%s %s%d", type, CB_PREFIX_BASE, f->id); } else { output ("%s", type); } if (cb_sticky_linkage) { s_type[n] = ""; } else { s_type[n] = "(cob_u8_ptr)&"; } break; } /* Fall through */ case CB_CALL_BY_REFERENCE: case CB_CALL_BY_CONTENT: if (gencode) { output ("cob_u8_t *%s%d", CB_PREFIX_BASE, f->id); } else { output ("cob_u8_t *"); } s_type[n] = ""; break; default: break; } if (CB_CHAIN (l)) { output (", "); } } } static void output_entry_function (struct cb_program *prog, cb_tree entry, cb_tree parameter_list, const int gencode) { const char *entry_name; cb_tree using_list; cb_tree l; cb_tree l1; cb_tree l2; struct cb_field *f; struct cb_field *f1; struct cb_field *f2; const char *s; const char *s2; const char *s_prefix; const char *s_type[MAX_CALL_FIELD_PARAMS]; cob_u32_t parmnum; cob_u32_t n; int sticky_ids[MAX_CALL_FIELD_PARAMS] = { 0 }; int sticky_nonp[MAX_CALL_FIELD_PARAMS] = { 0 }; int entry_convention = 0; entry_name = CB_LABEL (CB_PURPOSE (entry))->name; using_list = CB_VALUE (CB_VALUE (entry)); if (gencode) { output ("/* ENTRY '%s' */\n\n", entry_name); } #if (defined(_WIN32) || defined(__CYGWIN__)) && !defined(__clang__) if (!gencode && !prog->nested_level) { output ("__declspec(dllexport) "); } #endif if (unlikely (prog->prog_type == CB_FUNCTION_TYPE)) { output_function_entry_function (prog, gencode, entry_name, using_list); return; } /* entry convention */ l = CB_PURPOSE (CB_VALUE (entry)); if (!l || !(CB_INTEGER_P (l) || CB_NUMERIC_LITERAL_P (l))) { /* not translated as it is an unlikely internal abort, remove the check later */ /* LCOV_EXCL_START */ cobc_err_msg ("Missing/wrong internal entry convention!"); cobc_err_msg (_("Please report this!")); COBC_ABORT (); /* LCOV_EXCL_STOP */ } else if (CB_INTEGER_P (l)) { entry_convention = CB_INTEGER (l)->val; } else if (CB_NUMERIC_LITERAL_P (l)) { entry_convention = cb_get_int (l); } /* Output return type. */ if ((prog->nested_level && !prog->flag_void) || (prog->flag_main && !prog->flag_recursive && !strcmp(prog->program_id, entry_name))) { output ("static "); } if (prog->flag_void) { output ("void"); } else { output ("int"); } if (entry_convention & CB_CONV_STDCALL) { output (" __stdcall"); } if (gencode) { output ("\n"); } else { output ("\t\t"); } /* Output function name */ if (prog->nested_level) { output ("%s_%d__ (", entry_name, prog->toplev_count); } else { output ("%s (", entry_name); } /* Output parameter list */ if (prog->flag_chained) { using_list = NULL; parameter_list = NULL; } if (!gencode && !using_list) { output ("void);\n"); return; } output_program_entry_function_parameters (using_list, gencode, s_type); if (gencode) { output (")\n"); } else { /* Finish prototype and return */ output (");\n"); return; } output_indent ("{"); /* By value pointer fields */ for (l2 = using_list; l2; l2 = CB_CHAIN (l2)) { f2 = cb_code_field (CB_VALUE (l2)); if (CB_PURPOSE_INT (l2) == CB_CALL_BY_VALUE && (f2->usage == CB_USAGE_POINTER || f2->usage == CB_USAGE_PROGRAM_POINTER)) { output_line ("unsigned char\t\t*ptr_%d;", f2->id); } } /* For calling into a module, cob_call_params may not be known */ if (using_list) { parmnum = 0; for (l = using_list; l; l = CB_CHAIN (l)) { parmnum++; } if (entry_convention & CB_CONV_COBOL) { output_line("/* Get current number of call parameters,"); output_line(" if the parameter count is unknown, set it to all */"); if (cb_flag_implicit_init) { output_line ("if (cob_is_initialized () && cob_get_global_ptr ()->cob_current_module) {"); } else { output_line ("if (cob_get_global_ptr ()->cob_current_module) {"); } output_line ("\tcob_call_params = cob_get_global_ptr ()->cob_call_params;"); output_line ("} else {"); output_line ("\tcob_call_params = %d;", parmnum); output_line ("};"); } else { output_line ("/* Set current number of call parameters to max */"); output_line (" cob_call_params = %d;", parmnum); } output_newline(); } /* We have to cater for sticky-linkage here at the entry point site. Doing it in the internal function is too late as we then do not have the information as to possible ENTRY clauses. */ /* Sticky linkage parameters */ if (cb_sticky_linkage && using_list) { for (l = using_list, parmnum = 0; l; l = CB_CHAIN (l), parmnum++) { f = cb_code_field (CB_VALUE (l)); sticky_ids[parmnum] = f->id; if (CB_PURPOSE_INT (l) == CB_CALL_BY_VALUE) { s = try_get_by_value_parameter_type (f->usage, l); if (f->usage == CB_USAGE_FP_BIN128 || f->usage == CB_USAGE_FP_DEC128) { s2 = "{{0, 0}}"; } else { s2 = "0"; } if (s) { output_line ("static %s\tcob_parm_l_%d = %s;", s, f->id, s2); sticky_nonp[parmnum] = 1; } } } } /* Sticky linkage set up */ if (cb_sticky_linkage && using_list) { output_line ("/* Set the parameter list */"); parmnum = 0; output_line ("switch (cob_call_params) {"); for (l = using_list; l; l = CB_CHAIN (l), parmnum++) { output_prefix (); output ("case %u:\n", parmnum); for (n = 0; n < parmnum; ++n) { if (sticky_nonp[n]) { output_line ("\tcob_parm_l_%d = %s%d;", sticky_ids[n], CB_PREFIX_BASE, sticky_ids[n]); output_line ("\tcob_parm_%d = (cob_u8_ptr)&cob_parm_l_%d;", sticky_ids[n], sticky_ids[n]); } else { output_line ("\tcob_parm_%d = %s%d;", sticky_ids[n], CB_PREFIX_BASE, sticky_ids[n]); } } output_line ("\tbreak;"); } output_prefix (); output ("default:\n"); for (n = 0; n < parmnum; ++n) { if (sticky_nonp[n]) { output_line ("\tcob_parm_l_%d = %s%d;", sticky_ids[n], CB_PREFIX_BASE, sticky_ids[n]); output_line ("\tcob_parm_%d = (cob_u8_ptr)&cob_parm_l_%d;", sticky_ids[n], sticky_ids[n]); } else { output_line ("\tcob_parm_%d = %s%d;", sticky_ids[n], CB_PREFIX_BASE, sticky_ids[n]); } } output_line ("\tbreak;"); output ("}\n"); } if (cb_sticky_linkage) { s_prefix = "cob_parm_"; } else { s_prefix = CB_PREFIX_BASE; } for (l2 = using_list; l2; l2 = CB_CHAIN (l2)) { f2 = cb_code_field (CB_VALUE (l2)); if (CB_PURPOSE_INT (l2) == CB_CALL_BY_VALUE && (f2->usage == CB_USAGE_POINTER || f2->usage == CB_USAGE_PROGRAM_POINTER)) { output_line ("ptr_%d = %s%d;", f2->id, s_prefix, f2->id); } } output_prefix (); if (prog->flag_void) { output ("(void)"); } else { output ("return "); } if (!prog->nested_level) { output ("%s_ (%d", prog->program_id, progid++); } else { output ("%s_%d_ (%d", prog->program_id, prog->toplev_count, progid++); } if (using_list || parameter_list) { /* Output parameter list for final function call. */ for (l1 = parameter_list; l1; l1 = CB_CHAIN (l1)) { f1 = cb_code_field (CB_VALUE (l1)); n = 0; for (l2 = using_list; l2; l2 = CB_CHAIN (l2), ++n) { f2 = cb_code_field (CB_VALUE (l2)); if (strcasecmp (f1->name, f2->name) == 0) { switch (CB_PURPOSE_INT (l2)) { case CB_CALL_BY_VALUE: if (f2->usage == CB_USAGE_POINTER || f2->usage == CB_USAGE_PROGRAM_POINTER) { output (", (cob_u8_ptr)&ptr_%d", f2->id); break; } /* Fall through */ case CB_CALL_BY_REFERENCE: case CB_CALL_BY_CONTENT: output (", %s%s%d", s_type[n], s_prefix, f2->id); break; default: break; } break; } } if (l2 == NULL) { if (cb_sticky_linkage) { output (", %s%d", s_prefix, f1->id); } else { output (", NULL"); } } } } output (");\n"); output_indent ("}"); output_newline (); } static void output_function_prototypes (struct cb_program *prog) { struct cb_program *cp; cb_tree entry; cb_tree entry_param; cb_tree prog_param; cb_tree l; output ("/* Function prototypes */\n\n"); for (cp = prog; cp; cp = cp->next_program) { /* Collect all items used as parameters in the procedure division header and ENTRY statements in the parameter list. */ for (entry = cp->entry_list; entry; entry = CB_CHAIN (entry)) { for (entry_param = CB_VALUE (CB_VALUE (entry)); entry_param; entry_param = CB_CHAIN (entry_param)) { for (prog_param = cp->parameter_list; prog_param; prog_param = CB_CHAIN (prog_param)) { if (strcasecmp (cb_code_field (CB_VALUE (entry_param))->name, cb_code_field (CB_VALUE (prog_param))->name) == 0) { break; } } if (prog_param == NULL) { cp->parameter_list = cb_list_add (cp->parameter_list, CB_VALUE (entry_param)); } } } if (cp->flag_main) { /* Output prototype for main program wrapper. */ if (!cp->flag_recursive) { output ("static int\t\t%s ();\n", cp->program_id); } else { output ("int\t\t\t%s ();\n", cp->program_id); } #if (defined(_WIN32) || defined(__CYGWIN__)) && !defined(__clang__) for (l = cp->entry_list; l; l = CB_CHAIN (l)) { const char * entry_name = CB_LABEL (CB_PURPOSE (l))->name; if(0 == strcmp (entry_name, cp->program_id)) { continue; } output_entry_function (cp, l, cp->parameter_list, 0); } #endif } else { /* Output implementation of other program wrapper. */ for (l = cp->entry_list; l; l = CB_CHAIN (l)) { output_entry_function (cp, l, cp->parameter_list, 0); } } /* Output prototype for the actual function */ if (cp->prog_type == CB_FUNCTION_TYPE) { non_nested_count++; output ("static cob_field\t*%s_ (const int", cp->program_id); } else if (!cp->nested_level) { non_nested_count++; output ("static int\t\t%s_ (const int", cp->program_id); } else { output ("static int\t\t%s_%d_ (const int", cp->program_id, cp->toplev_count); } /* Output prototype parameters */ if (!cp->flag_chained) { for (l = cp->parameter_list; l; l = CB_CHAIN (l)) { output (", cob_u8_t *"); if (cb_sticky_linkage) { output_storage ("static cob_u8_t\t\t\t*cob_parm_%d = NULL;\n", cb_code_field (CB_VALUE (l))->id); } } } output (");\n"); } output ("\n"); } static void output_main_function (struct cb_program *prog) { output_line ("/* Main function */"); if (!cb_flag_winmain) { output_line ("int"); output_line ("main (int argc, char **argv)"); output_indent ("{"); output_line ("cob_init (argc, argv);"); } else { output_line ("int WINAPI"); output_line ("WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nCmdShow)"); output_indent ("{"); output_line ("cob_init (__argc, __argv);"); } output_line ("cob_stop_run (%s ());", prog->program_id); output_indent ("}\n"); } static void output_header (FILE *fp, const char *locbuff, const struct cb_program *cp) { int i; if (fp) { fprintf (fp, "/* Generated by cobc %s.%d */\n", PACKAGE_VERSION, PATCH_LEVEL); fprintf (fp, "/* Generated from %s */\n", cb_source_file); fprintf (fp, "/* Generated at %s */\n", locbuff); fprintf (fp, "/* GnuCOBOL build date %s */\n", cb_cobc_build_stamp); fprintf (fp, "/* GnuCOBOL package date %s */\n", COB_TAR_DATE); fprintf (fp, "/* Compile command "); for (i = 0; i < cb_saveargc; i++) { fprintf (fp, "%s ", cb_saveargv[i]); } fprintf (fp, "*/\n\n"); if (cp) { fprintf (fp, "/* Program local variables for '%s' */\n\n", cp->orig_program_id); } } } void codegen (struct cb_program *prog, const int subsequent_call) { cb_tree l; struct literal_list *m; struct cb_program *cp; struct tm *loctime; int i; enum cb_optim optidx; time_t sectime; /* Clear local program stuff */ current_prog = prog; param_id = 0; stack_id = 0; num_cob_fields = 0; progid = 0; loop_counter = 0; output_indent_level = 0; last_line = 0; needs_exit_prog = 0; gen_custom = 0; gen_nested_tab = 0; gen_dynamic = 0; gen_if_level = 0; local_mem = 0; local_working_mem = 0; need_save_exception = 0; last_segment = 0; last_section = NULL; call_cache = NULL; func_call_cache = NULL; static_call_cache = NULL; label_cache = NULL; local_base_cache = NULL; local_field_cache = NULL; inside_check = 0; for (i = 0; i < COB_INSIDE_SIZE; ++i) { inside_stack[i] = 0; } excp_current_program_id = prog->orig_program_id; excp_current_section = NULL; excp_current_paragraph = NULL; memset ((void *)i_counters, 0, sizeof (i_counters)); output_target = yyout; cb_local_file = current_prog->local_include->local_fp; if (!subsequent_call) { /* First iteration */ gen_alt_ebcdic = 0; gen_ebcdic_ascii = 0; gen_full_ebcdic = 0; gen_native = 0; gen_figurative = 0; non_nested_count = 0; working_mem = 0; pic_cache = NULL; base_cache = NULL; globext_cache = NULL; field_cache = NULL; if (!string_buffer) { string_buffer = cobc_main_malloc ((size_t)COB_MINI_BUFF); } sectime = time (NULL); loctime = localtime (&sectime); if (loctime) { /* Leap seconds ? */ if (loctime->tm_sec >= 60) { loctime->tm_sec = 59; } strftime (string_buffer, (size_t)COB_MINI_MAX, "%b %d %Y %H:%M:%S", loctime); output_header (output_target, string_buffer, NULL); output_header (cb_storage_file, string_buffer, NULL); for (cp = prog; cp; cp = cp->next_program) { output_header (cp->local_include->local_fp, string_buffer, cp); } } output_standard_includes (); /* string_buffer has formatted date from above */ output_gnucobol_defines (string_buffer, loctime); output_newline (); output ("/* Global variables */\n"); output ("#include \"%s\"\n\n", cb_storage_file_name); output_function_prototypes (prog); } output_class_names (prog); /* Main function */ if (prog->flag_main) { output_main_function (prog); } /* Functions */ if (!subsequent_call) { output ("/* Functions */\n\n"); } if (prog->prog_type == CB_FUNCTION_TYPE) { output ("/* FUNCTION-ID '%s' */\n\n", prog->orig_program_id); } else { output ("/* PROGRAM-ID '%s' */\n\n", prog->orig_program_id); } for (l = prog->entry_list; l; l = CB_CHAIN (l)) { output_entry_function (prog, l, prog->parameter_list, 1); } output_internal_function (prog, prog->parameter_list); if (!prog->next_program) { output ("/* End functions */\n\n"); } if (gen_native || gen_full_ebcdic || gen_ebcdic_ascii || prog->alphabet_name_list) { (void)lookup_attr (COB_TYPE_ALPHANUMERIC, 0, 0, 0, NULL, 0); } output_target = cb_storage_file; /* Program local stuff */ output_call_cache (); output_nested_call_table (prog); output_local_indexes (); output_perform_times_counters (); output_local_implicit_fields (); output_debugging_fields (prog); output_local_storage_pointer (prog); output_call_parameter_stack_pointers (prog); output_frame_stack (prog); output_dynamic_field_function_id_pointers (); output_local_base_cache (); output_local_field_cache (); /* Skip to next program contained in the source */ if (prog->next_program) { codegen (prog->next_program, 1); return; } /* Finalize the main include file */ if (!cobc_flag_main && non_nested_count > 1) { output_storage ("\n/* Module reference count */\n"); output_storage ("static unsigned int\t\tcob_reference_count = 0;\n"); } output_storage ("\n/* Module path */\n"); output_storage ("static const char\t\t*cob_module_path = NULL;\n"); output_storage ("\n/* Number of call parameters */\n"); output_storage ("static int\t\tcob_call_params = 0;\n"); output_globext_cache (); output_nonlocal_base_cache (); output_pic_cache (); output_attributes (); output_nonlocal_field_cache (); output_literals_figuratives_and_constants (); output_collating_tables (); output_string_cache (); /* Optimizer output */ for (optidx = COB_OPTIM_MIN; optidx < COB_OPTIM_MAX; ++optidx) { if (optimize_defs[optidx]) { cob_gen_optim (optidx); output_storage ("\n"); } } if (literal_cache) { output_storage ("\t/* Decimal constants */\n"); for (m = literal_cache; m; m = m->next) { if (CB_TREE_CLASS (m->x) == CB_CLASS_NUMERIC && m->make_decimal) { output_storage ("static\tcob_decimal\t%s%d;\n", CB_PREFIX_DEC_FIELD,m->id); output_storage ("static\tcob_decimal\t*%s%d = NULL;\n", CB_PREFIX_DEC_CONST,m->id); } } } /* Clean up by clearing these */ attr_cache = NULL; literal_cache = NULL; string_cache = NULL; string_id = 1; }
rec/leds
bibliopixel/control/extractor.py
import collections class Extractor: """ Extractor is a class that extracts and normalizes values from incoming message dictionaries into ordered dictionaries based on the `type` key of each message. """ def __init__(self, omit=None, normalizers=None, keys_by_type=None, accept=None, reject=None, auto_omit=True): """ Arguments omit -- A list of keys that will not be extracted. normalizers -- Some keys also need to be "normalized" - scaled and offset so they are between 0 and 1, or -1 and 1. The `normalizers` table maps key names to a function that normalizes the value of that key. keys_by_type -- `keys_by_type` is a dictionary from the `type` in an incoming message to a list of message keys to be extracted accept -- maps keys to a value or a list of values that are accepted for that key. A message has to match *all* entries in `accept` to be accepted. reject -- map key to a value or a list of values that are not accepted for that key. A message is rejected if it matches *any* entry in the reject map. auto_omit -- if True, omit all keys in `accept` that only have one possible value. auto_omit=True, the default, is probably more useful: if you request data for channel=1, type=note_on then you probably don't want to see channel=1, type=note_on with each message. """ def to_set(x): if x is None: return set() if isinstance(x, (list, tuple)): return set(x) return set([x]) def make_match(m): return m and {k: to_set(v) for k, v in m.items()} self.accept, self.reject = make_match(accept), make_match(reject) self.omit = to_set(omit) if auto_omit and self.accept: self.omit.update(k for k, v in self.accept.items() if len(v) == 1) self.normalizers = normalizers or {} if keys_by_type is None: self.keys_by_type = None else: self.keys_by_type = {} for k, v in keys_by_type.items(): if isinstance(v, str): v = [v] self.keys_by_type[k] = tuple(i for i in v if i not in self.omit) def extract(self, msg): """Yield an ordered dictionary if msg['type'] is in keys_by_type.""" def normal(key): v = msg.get(key) if v is None: return v normalizer = self.normalizers.get(key, lambda x: x) return normalizer(v) def odict(keys): return collections.OrderedDict((k, normal(k)) for k in keys) def match(m): return (msg.get(k) in v for k, v in m.items()) if m else () accept = all(match(self.accept)) reject = any(match(self.reject)) if reject or not accept: keys = () elif self.keys_by_type is None: keys = [k for k in msg.keys() if k not in self.omit] else: keys = self.keys_by_type.get(msg.get('type')) return odict(keys)
yangyu456/pc-chat
src/js/wfc/messages/notification/dismissGroupNotification.js
import wfc from '../../client/wfc' import MessageContentType from '../messageContentType'; import GroupNotificationContent from './groupNotification'; export default class DismissGroupNotification extends GroupNotificationContent { operator = ''; constructor(operator) { super(MessageContentType.DismissGroup_Notification); this.operator = operator; } formatNotification() { if (this.fromSelf) { return '您解散了群组'; } else { return wfc.getGroupMemberDisplayName(this.groupId, this.operator) + '解散了群组'; } } encode() { let payload = super.encode(); let obj = { g: this.groupId, o: this.operator, }; payload.binaryContent = wfc.utf8_to_b64(JSON.stringify(obj)); return payload; } decode(payload) { super.decode(payload); let json = wfc.b64_to_utf8(payload.binaryContent) let obj = JSON.parse(json); this.groupId = obj.g; this.operator = obj.o; } }
thisisgopalmandal/opencv
modules/video/misc/java/test/KalmanFilterTest.java
<reponame>thisisgopalmandal/opencv package org.opencv.test.video; import org.opencv.test.OpenCVTestCase; import org.opencv.video.KalmanFilter; public class KalmanFilterTest extends OpenCVTestCase { public void testCorrect() { fail("Not yet implemented"); } public void testKalmanFilter() { KalmanFilter kf = new KalmanFilter(); assertNotNull(kf); } public void testKalmanFilterIntInt() { fail("Not yet implemented"); } public void testKalmanFilterIntIntInt() { fail("Not yet implemented"); } public void testKalmanFilterIntIntIntInt() { fail("Not yet implemented"); } public void testPredict() { fail("Not yet implemented"); } public void testPredictMat() { fail("Not yet implemented"); } }
perfectrecall/aws-sdk-cpp
aws-cpp-sdk-sagemaker/source/model/UserSettings.cpp
<gh_stars>1-10 /** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/sagemaker/model/UserSettings.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace SageMaker { namespace Model { UserSettings::UserSettings() : m_executionRoleHasBeenSet(false), m_securityGroupsHasBeenSet(false), m_sharingSettingsHasBeenSet(false), m_jupyterServerAppSettingsHasBeenSet(false), m_kernelGatewayAppSettingsHasBeenSet(false), m_tensorBoardAppSettingsHasBeenSet(false), m_rStudioServerProAppSettingsHasBeenSet(false), m_rSessionAppSettingsHasBeenSet(false) { } UserSettings::UserSettings(JsonView jsonValue) : m_executionRoleHasBeenSet(false), m_securityGroupsHasBeenSet(false), m_sharingSettingsHasBeenSet(false), m_jupyterServerAppSettingsHasBeenSet(false), m_kernelGatewayAppSettingsHasBeenSet(false), m_tensorBoardAppSettingsHasBeenSet(false), m_rStudioServerProAppSettingsHasBeenSet(false), m_rSessionAppSettingsHasBeenSet(false) { *this = jsonValue; } UserSettings& UserSettings::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("ExecutionRole")) { m_executionRole = jsonValue.GetString("ExecutionRole"); m_executionRoleHasBeenSet = true; } if(jsonValue.ValueExists("SecurityGroups")) { Array<JsonView> securityGroupsJsonList = jsonValue.GetArray("SecurityGroups"); for(unsigned securityGroupsIndex = 0; securityGroupsIndex < securityGroupsJsonList.GetLength(); ++securityGroupsIndex) { m_securityGroups.push_back(securityGroupsJsonList[securityGroupsIndex].AsString()); } m_securityGroupsHasBeenSet = true; } if(jsonValue.ValueExists("SharingSettings")) { m_sharingSettings = jsonValue.GetObject("SharingSettings"); m_sharingSettingsHasBeenSet = true; } if(jsonValue.ValueExists("JupyterServerAppSettings")) { m_jupyterServerAppSettings = jsonValue.GetObject("JupyterServerAppSettings"); m_jupyterServerAppSettingsHasBeenSet = true; } if(jsonValue.ValueExists("KernelGatewayAppSettings")) { m_kernelGatewayAppSettings = jsonValue.GetObject("KernelGatewayAppSettings"); m_kernelGatewayAppSettingsHasBeenSet = true; } if(jsonValue.ValueExists("TensorBoardAppSettings")) { m_tensorBoardAppSettings = jsonValue.GetObject("TensorBoardAppSettings"); m_tensorBoardAppSettingsHasBeenSet = true; } if(jsonValue.ValueExists("RStudioServerProAppSettings")) { m_rStudioServerProAppSettings = jsonValue.GetObject("RStudioServerProAppSettings"); m_rStudioServerProAppSettingsHasBeenSet = true; } if(jsonValue.ValueExists("RSessionAppSettings")) { m_rSessionAppSettings = jsonValue.GetObject("RSessionAppSettings"); m_rSessionAppSettingsHasBeenSet = true; } return *this; } JsonValue UserSettings::Jsonize() const { JsonValue payload; if(m_executionRoleHasBeenSet) { payload.WithString("ExecutionRole", m_executionRole); } if(m_securityGroupsHasBeenSet) { Array<JsonValue> securityGroupsJsonList(m_securityGroups.size()); for(unsigned securityGroupsIndex = 0; securityGroupsIndex < securityGroupsJsonList.GetLength(); ++securityGroupsIndex) { securityGroupsJsonList[securityGroupsIndex].AsString(m_securityGroups[securityGroupsIndex]); } payload.WithArray("SecurityGroups", std::move(securityGroupsJsonList)); } if(m_sharingSettingsHasBeenSet) { payload.WithObject("SharingSettings", m_sharingSettings.Jsonize()); } if(m_jupyterServerAppSettingsHasBeenSet) { payload.WithObject("JupyterServerAppSettings", m_jupyterServerAppSettings.Jsonize()); } if(m_kernelGatewayAppSettingsHasBeenSet) { payload.WithObject("KernelGatewayAppSettings", m_kernelGatewayAppSettings.Jsonize()); } if(m_tensorBoardAppSettingsHasBeenSet) { payload.WithObject("TensorBoardAppSettings", m_tensorBoardAppSettings.Jsonize()); } if(m_rStudioServerProAppSettingsHasBeenSet) { payload.WithObject("RStudioServerProAppSettings", m_rStudioServerProAppSettings.Jsonize()); } if(m_rSessionAppSettingsHasBeenSet) { payload.WithObject("RSessionAppSettings", m_rSessionAppSettings.Jsonize()); } return payload; } } // namespace Model } // namespace SageMaker } // namespace Aws
visit-dav/vis
src/visit_vtk/full/vtkVertexFilter.h
<gh_stars>100-1000 // Copyright (c) Lawrence Livermore National Security, LLC and other VisIt // Project developers. See the top-level LICENSE file for dates and other // details. No copyright assignment is required to contribute to VisIt. // .NAME vtkVertexFilter -- Make a vertex at each point incident to a cell // or at each cell. // // .SECTION Description // You can specify if you would like cell vertices or point vertices. // #ifndef __vtkVertexFilter_h #define __vtkVertexFilter_h #include <visit_vtk_exports.h> #include "vtkPolyDataAlgorithm.h" // *************************************************************************** // Class: vtkVertexFilter // // Modifications: // <NAME>, Thu Jan 10 12:15:52 PST 2013 // Modified to inherit from vtkPolyDataAlgorithm. // // *************************************************************************** class VISIT_VTK_API vtkVertexFilter : public vtkPolyDataAlgorithm { public: vtkTypeMacro(vtkVertexFilter, vtkPolyDataAlgorithm); void PrintSelf(ostream& os, vtkIndent indent) override; vtkSetMacro(VertexAtPoints,bool); vtkGetMacro(VertexAtPoints,bool); vtkBooleanMacro(VertexAtPoints,bool); static vtkVertexFilter *New(); protected: vtkVertexFilter(); ~vtkVertexFilter() {}; virtual int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *) override; virtual int FillInputPortInformation(int port, vtkInformation *info) override; bool VertexAtPoints; private: vtkVertexFilter(const vtkVertexFilter&); void operator=(const vtkVertexFilter&); }; #endif
glsdown/dash-bootstrap-components
docs/components_page/components/input/radio_check_standalone.py
import dash_bootstrap_components as dbc from dash import Input, Output, html standalone_radio_check = html.Div( [ html.Div( [ dbc.Checkbox( id="standalone-checkbox", label="This is a checkbox", value=False, ), dbc.Switch( id="standalone-switch", label="This is a toggle switch", value=False, ), dbc.RadioButton( id="standalone-radio", label="This is a radio button", value=False, ), ] ), html.P(id="standalone-radio-check-output"), ] ) @app.callback( Output("standalone-radio-check-output", "children"), [ Input("standalone-checkbox", "value"), Input("standalone-switch", "value"), Input("standalone-radio", "value"), ], ) def on_form_change(checkbox_checked, switch_checked, radio_checked): return f"Selections: Checkbox: {checkbox_checked}, Toggle Switch: {switch_checked}, Radio Button: {radio_checked}"
jodavis42/ZilchShaders
Libraries/ZilchShaders/ZilchShaderIRCore.cpp
<gh_stars>1-10 /////////////////////////////////////////////////////////////////////////////// /// /// Authors: <NAME> /// Copyright 2018, DigiPen Institute of Technology /// /////////////////////////////////////////////////////////////////////////////// #include "Precompiled.hpp" #include "ZilchShaderIRCore.hpp" #include "ShaderIRLibraryTranslation.hpp" namespace Zero { //-------------------------------------------------------------------ZilchShaderIRCore ZilchShaderIRCore* ZilchShaderIRCore::mInstance = nullptr; void ZilchShaderIRCore::InitializeInstance() { ReturnIf(mInstance != nullptr, , "Can't initialize a static library more than once"); mInstance = new ZilchShaderIRCore(); } void ZilchShaderIRCore::Destroy() { delete mInstance; mInstance = nullptr; } ZilchShaderIRCore& ZilchShaderIRCore::GetInstance() { ErrorIf(mInstance == nullptr, "Attempted to get an uninitialized singleton static library"); return *mInstance; } ZilchShaderIRCore::ZilchShaderIRCore() { mGlsl450ExtensionsLibrary = nullptr; Zilch::Core& core = Zilch::Core::GetInstance(); mZilchTypes.mVoidType = core.VoidType; mZilchTypes.mRealVectorTypes.PushBack(core.RealType); mZilchTypes.mRealVectorTypes.PushBack(core.Real2Type); mZilchTypes.mRealVectorTypes.PushBack(core.Real3Type); mZilchTypes.mRealVectorTypes.PushBack(core.Real4Type); // Make all of the matrix types for(size_t y = 2; y <= 4; ++y) { for(size_t x = 2; x <= 4; ++x) { Zilch::BoundType* basisType = mZilchTypes.mRealVectorTypes[x - 1]; String matrixName = BuildString("Real", ToString(y), "x", ToString(x)); Zilch::BoundType* zilchMatrixType = core.GetLibrary()->BoundTypes.FindValue(matrixName, nullptr); mZilchTypes.mRealMatrixTypes.PushBack(zilchMatrixType); } } mZilchTypes.mIntegerVectorTypes.PushBack(core.IntegerType); mZilchTypes.mIntegerVectorTypes.PushBack(core.Integer2Type); mZilchTypes.mIntegerVectorTypes.PushBack(core.Integer3Type); mZilchTypes.mIntegerVectorTypes.PushBack(core.Integer4Type); mZilchTypes.mBooleanVectorTypes.PushBack(core.BooleanType); mZilchTypes.mBooleanVectorTypes.PushBack(core.Boolean2Type); mZilchTypes.mBooleanVectorTypes.PushBack(core.Boolean3Type); mZilchTypes.mBooleanVectorTypes.PushBack(core.Boolean4Type); mZilchTypes.mQuaternionType = core.QuaternionType; } void ZilchShaderIRCore::Parse(ZilchSpirVFrontEnd* translator) { ZilchShaderIRLibrary* shaderLibrary = new ZilchShaderIRLibrary(); shaderLibrary->mZilchLibrary = Zilch::Core::GetInstance().GetLibrary(); mLibraryRef = shaderLibrary; translator->mLibrary = shaderLibrary; Zilch::Core& core = Zilch::Core::GetInstance(); Zilch::BoundType* mathType = core.MathType; translator->MakeStructType(shaderLibrary, core.MathType->Name, core.MathType, spv::StorageClass::StorageClassGeneric); Zilch::BoundType* zilchIntType = core.IntegerType; String intTypeName = zilchIntType->ToString(); ShaderTypeGroups& types = mShaderTypes; MakeMathTypes(translator, shaderLibrary, types); // Add all static/instance functions for primitive types RegisterPrimitiveFunctions(translator, shaderLibrary, types, types.mRealVectorTypes[0]); RegisterPrimitiveFunctions(translator, shaderLibrary, types, types.mIntegerVectorTypes[0]); RegisterPrimitiveFunctions(translator, shaderLibrary, types, types.mBooleanVectorTypes[0]); // Add all static/instance functions for vector types RegisterVectorFunctions(translator, shaderLibrary, types, types.mRealVectorTypes); RegisterVectorFunctions(translator, shaderLibrary, types, types.mIntegerVectorTypes); RegisterVectorFunctions(translator, shaderLibrary, types, types.mBooleanVectorTypes); // Add all static/instance functions for matrix types (only float matrices exist) RegisterMatrixFunctions(translator, shaderLibrary, types, types.mRealMatrixTypes); // Also the quaternion type RegisterQuaternionFunctions(translator, shaderLibrary, types, types.mQuaternionType); // Add a bunch of math ops (a lot on the math class) RegisterArithmeticOps(translator, shaderLibrary, mZilchTypes); RegisterConversionOps(translator, shaderLibrary, mZilchTypes); RegisterLogicalOps(translator, shaderLibrary, mZilchTypes); RegisterBitOps(translator, shaderLibrary, mZilchTypes); RegisterColorsOps(translator, shaderLibrary, mZilchTypes); // Add special extension functions such as Matrix.Determinant and Sin mGlsl450ExtensionsLibrary = new SpirVExtensionLibrary(); shaderLibrary->mExtensionLibraries.PushBack(mGlsl450ExtensionsLibrary); RegisterGlsl450Extensions(shaderLibrary, mGlsl450ExtensionsLibrary, mZilchTypes); shaderLibrary->mTranslated = true; } ZilchShaderIRLibraryRef ZilchShaderIRCore::GetLibrary() { return mLibraryRef; } void ZilchShaderIRCore::MakeMathTypes(ZilchSpirVFrontEnd* translator, ZilchShaderIRLibrary* shaderLibrary, ShaderTypeGroups& types) { Zilch::Core& core = Zilch::Core::GetInstance(); types.mVoidType = translator->MakeCoreType(shaderLibrary, ShaderIRTypeBaseType::Void, 0, nullptr, core.VoidType, false); ZilchShaderIRType* floatType = translator->MakeCoreType(shaderLibrary, ShaderIRTypeBaseType::Float, 1, nullptr, core.RealType); ZilchShaderIRType* float2Type = translator->MakeCoreType(shaderLibrary, ShaderIRTypeBaseType::Vector, 2, floatType, core.Real2Type); ZilchShaderIRType* float3Type = translator->MakeCoreType(shaderLibrary, ShaderIRTypeBaseType::Vector, 3, floatType, core.Real3Type); ZilchShaderIRType* float4Type = translator->MakeCoreType(shaderLibrary, ShaderIRTypeBaseType::Vector, 4, floatType, core.Real4Type); types.mRealVectorTypes.PushBack(floatType); types.mRealVectorTypes.PushBack(float2Type); types.mRealVectorTypes.PushBack(float3Type); types.mRealVectorTypes.PushBack(float4Type); // Make all of the matrix types for(u32 y = 2; y <= 4; ++y) { for(u32 x = 2; x <= 4; ++x) { ZilchShaderIRType* basisType = types.mRealVectorTypes[x - 1]; String matrixName = BuildString("Real", ToString(y), "x", ToString(x)); Zilch::BoundType* zilchMatrixType = core.GetLibrary()->BoundTypes.FindValue(matrixName, nullptr); ZilchShaderIRType* shaderMatrixType = translator->MakeCoreType(shaderLibrary, ShaderIRTypeBaseType::Matrix, y, basisType, zilchMatrixType); types.mRealMatrixTypes.PushBack(shaderMatrixType); } } ZilchShaderIRType* intType = translator->MakeCoreType(shaderLibrary, ShaderIRTypeBaseType::Int, 1, nullptr, core.IntegerType); ZilchShaderIRType* int2Type = translator->MakeCoreType(shaderLibrary, ShaderIRTypeBaseType::Vector, 2, intType, core.Integer2Type); ZilchShaderIRType* int3Type = translator->MakeCoreType(shaderLibrary, ShaderIRTypeBaseType::Vector, 3, intType, core.Integer3Type); ZilchShaderIRType* int4Type = translator->MakeCoreType(shaderLibrary, ShaderIRTypeBaseType::Vector, 4, intType, core.Integer4Type); types.mIntegerVectorTypes.PushBack(intType); types.mIntegerVectorTypes.PushBack(int2Type); types.mIntegerVectorTypes.PushBack(int3Type); types.mIntegerVectorTypes.PushBack(int4Type); ZilchShaderIRType* boolType = translator->MakeCoreType(shaderLibrary, ShaderIRTypeBaseType::Bool, 1, nullptr, core.BooleanType); ZilchShaderIRType* bool2Type = translator->MakeCoreType(shaderLibrary, ShaderIRTypeBaseType::Vector, 2, boolType, core.Boolean2Type); ZilchShaderIRType* bool3Type = translator->MakeCoreType(shaderLibrary, ShaderIRTypeBaseType::Vector, 3, boolType, core.Boolean3Type); ZilchShaderIRType* bool4Type = translator->MakeCoreType(shaderLibrary, ShaderIRTypeBaseType::Vector, 4, boolType, core.Boolean4Type); types.mBooleanVectorTypes.PushBack(boolType); types.mBooleanVectorTypes.PushBack(bool2Type); types.mBooleanVectorTypes.PushBack(bool3Type); types.mBooleanVectorTypes.PushBack(bool4Type); // Make quaternion a struct type. Ideally quaternion would just be a vec4 type, but it's illegal to declare // multiple vec4 types. This causes a lot of complications in translating core functionality. Zilch::BoundType* zilchQuaternion = core.QuaternionType; String quaternionTypeName = zilchQuaternion->ToString(); ZilchShaderIRType* quaternionType = translator->MakeStructType(shaderLibrary, quaternionTypeName, core.QuaternionType, spv::StorageClassFunction); quaternionType->mDebugResultName = quaternionType->mName = quaternionTypeName; quaternionType->AddMember(float4Type, "Data"); types.mQuaternionType = quaternionType; } void ZilchShaderIRCore::RegisterPrimitiveFunctions(ZilchSpirVFrontEnd* translator, ZilchShaderIRLibrary* shaderLibrary, ShaderTypeGroups& types, ZilchShaderIRType* shaderType) { Zilch::BoundType* intType = types.mIntegerVectorTypes[0]->mZilchType; Zilch::BoundType* zilchType = shaderType->mZilchType; String zilchTypeName = zilchType->ToString(); String intTypeName = intType->ToString(); TypeResolvers& primitiveTypeResolvers = shaderLibrary->mTypeResolvers[zilchType]; primitiveTypeResolvers.mDefaultConstructorResolver = &TranslatePrimitiveDefaultConstructor; primitiveTypeResolvers.mBackupConstructorResolver = &TranslateBackupPrimitiveConstructor; primitiveTypeResolvers.RegisterBackupFieldResolver(&ScalarBackupFieldResolver); primitiveTypeResolvers.RegisterFunctionResolver(GetStaticProperty(zilchType, "Count")->Get, ResolveVectorTypeCount); primitiveTypeResolvers.RegisterFunctionResolver(GetInstanceProperty(zilchType, "Count")->Get, ResolveVectorTypeCount); primitiveTypeResolvers.RegisterFunctionResolver(GetMemberOverloadedFunction(zilchType, Zilch::OperatorGet, intTypeName), ResolvePrimitiveGet); primitiveTypeResolvers.RegisterFunctionResolver(GetMemberOverloadedFunction(zilchType, Zilch::OperatorSet, intTypeName, zilchTypeName), ResolvePrimitiveSet); } void ZilchShaderIRCore::RegisterVectorFunctions(ZilchSpirVFrontEnd* translator, ZilchShaderIRLibrary* shaderLibrary, ShaderTypeGroups& types, Array<ZilchShaderIRType*>& vectorTypes) { Zilch::BoundType* intType = types.mIntegerVectorTypes[0]->mZilchType; String intTypeName = intType->ToString(); for(size_t i = 1; i < vectorTypes.Size(); ++i) { ZilchShaderIRType* shaderType = vectorTypes[i]; Zilch::BoundType* zilchType = shaderType->mZilchType; String zilchTypeName = zilchType->ToString(); ZilchShaderIRType* componentType = GetComponentType(shaderType); Zilch::BoundType* zilchComponentType = componentType->mZilchType; String zilchComponentTypeName = zilchComponentType->ToString(); TypeResolvers& primitiveTypeResolvers = shaderLibrary->mTypeResolvers[zilchType]; primitiveTypeResolvers.mDefaultConstructorResolver = &TranslateCompositeDefaultConstructor; primitiveTypeResolvers.RegisterBackupFieldResolver(&VectorBackupFieldResolver); primitiveTypeResolvers.RegisterConstructorResolver(zilchType->GetDefaultConstructor(), TranslateCompositeDefaultConstructor); primitiveTypeResolvers.RegisterConstructorResolver(GetConstructor(zilchType, zilchComponentTypeName), TranslateCompositeSplatConstructor); Zilch::Function* copyConstructor = GetConstructor(zilchType, zilchTypeName); if(copyConstructor != nullptr) primitiveTypeResolvers.RegisterConstructorResolver(copyConstructor, ResolveVectorCopyConstructor); primitiveTypeResolvers.RegisterFunctionResolver(GetStaticProperty(zilchType, "Count")->Get, ResolveVectorTypeCount); primitiveTypeResolvers.RegisterFunctionResolver(GetInstanceProperty(zilchType, "Count")->Get, ResolveVectorTypeCount); primitiveTypeResolvers.RegisterFunctionResolver(GetMemberOverloadedFunction(zilchType, Zilch::OperatorGet, intTypeName), ResolveVectorGet); primitiveTypeResolvers.RegisterFunctionResolver(GetMemberOverloadedFunction(zilchType, Zilch::OperatorSet, intTypeName, zilchComponentTypeName), ResolveVectorSet); primitiveTypeResolvers.RegisterBackupSetterResolver(VectorBackupPropertySetter); primitiveTypeResolvers.mBackupConstructorResolver = &TranslateBackupCompositeConstructor; } } void ZilchShaderIRCore::RegisterMatrixFunctions(ZilchSpirVFrontEnd* translator, ZilchShaderIRLibrary* shaderLibrary, ShaderTypeGroups& types, Array<ZilchShaderIRType*>& matrixTypes) { Zilch::BoundType* intType = types.mIntegerVectorTypes[0]->mZilchType; String intTypeName = intType->ToString(); for(size_t i = 0; i < matrixTypes.Size(); ++i) { ZilchShaderIRType* shaderType = matrixTypes[i]; Zilch::BoundType* zilchType = shaderType->mZilchType; // Get the component (vector row) type ZilchShaderIRType* componentType = GetComponentType(shaderType); Zilch::BoundType* zilchComponentType = componentType->mZilchType; String zilchComponentTypeName = zilchComponentType->ToString(); // Get the scalar type of the matrix ZilchShaderIRType* scalarType = GetComponentType(componentType); Zilch::BoundType* zilchScalarType = scalarType->mZilchType; TypeResolvers& matrixTypeResolver = shaderLibrary->mTypeResolvers[zilchType]; // Constructors matrixTypeResolver.mDefaultConstructorResolver = &TranslateMatrixDefaultConstructor; matrixTypeResolver.RegisterConstructorResolver(zilchType->GetDefaultConstructor(), TranslateMatrixDefaultConstructor); matrixTypeResolver.RegisterConstructorResolver(GetConstructor(zilchType, zilchScalarType->ToString()), TranslateCompositeSplatConstructor); // Constructor for each scalar entry in the matrix Array<String> constructorParams; for(size_t i = 0; i < shaderType->mComponents * componentType->mComponents; ++i) constructorParams.PushBack(zilchScalarType->ToString()); matrixTypeResolver.RegisterConstructorResolver(GetConstructor(zilchType, constructorParams), TranslateMatrixFullConstructor); // Fields (M00, etc...) matrixTypeResolver.RegisterBackupFieldResolver(&MatrixBackupFieldResolver); matrixTypeResolver.RegisterFunctionResolver(GetMemberOverloadedFunction(zilchType, Zilch::OperatorGet, intTypeName), ResolveMatrixGet); matrixTypeResolver.RegisterFunctionResolver(GetMemberOverloadedFunction(zilchType, Zilch::OperatorSet, intTypeName, zilchComponentTypeName), ResolveMatrixSet); } } void ZilchShaderIRCore::RegisterQuaternionFunctions(ZilchSpirVFrontEnd* translator, ZilchShaderIRLibrary* shaderLibrary, ShaderTypeGroups& types, ZilchShaderIRType* quaternionType) { Zilch::BoundType* intType = types.mIntegerVectorTypes[0]->mZilchType; String intTypeName = intType->ToString(); Zilch::BoundType* zilchType = quaternionType->mZilchType; String zilchTypeName = zilchType->ToString(); // While quaternion's component type is technically vec4, all operations behave as if it's real ZilchShaderIRType* componentType = types.mRealVectorTypes[0]; Zilch::BoundType* zilchComponentType = componentType->mZilchType; String zilchComponentTypeName = zilchComponentType->ToString(); TypeResolvers& primitiveTypeResolvers = shaderLibrary->mTypeResolvers[zilchType]; primitiveTypeResolvers.mDefaultConstructorResolver = &TranslateQuaternionDefaultConstructor; primitiveTypeResolvers.RegisterBackupFieldResolver(&QuaternionBackupFieldResolver); primitiveTypeResolvers.RegisterConstructorResolver(zilchType->GetDefaultConstructor(), TranslateQuaternionDefaultConstructor); primitiveTypeResolvers.RegisterConstructorResolver(GetConstructor(zilchType, zilchComponentTypeName), TranslateQuaternionSplatConstructor); primitiveTypeResolvers.RegisterFunctionResolver(GetStaticProperty(zilchType, "Count")->Get, ResolveQuaternionTypeCount); primitiveTypeResolvers.RegisterFunctionResolver(GetInstanceProperty(zilchType, "Count")->Get, ResolveQuaternionTypeCount); primitiveTypeResolvers.RegisterFunctionResolver(GetMemberOverloadedFunction(zilchType, Zilch::OperatorGet, intTypeName), ResolveQuaternionGet); primitiveTypeResolvers.RegisterFunctionResolver(GetMemberOverloadedFunction(zilchType, Zilch::OperatorSet, intTypeName, zilchComponentTypeName), ResolveQuaternionSet); primitiveTypeResolvers.RegisterBackupSetterResolver(QuaternionBackupPropertySetter); primitiveTypeResolvers.mBackupConstructorResolver = &TranslateBackupQuaternionConstructor; } }//namespace Zero
wrldwzrd89/older-java-games
MazeRunner2/src/com/puttysoftware/mazerunner2/maze/objects/IPort.java
<gh_stars>0 /* MazeRunnerII: A Maze-Solving Game Copyright (C) 2008 <NAME> Any questions should be directed to the author via email at: <EMAIL> */ package com.puttysoftware.mazerunner2.maze.objects; import com.puttysoftware.mazerunner2.maze.abc.AbstractPort; import com.puttysoftware.mazerunner2.resourcemanagers.ObjectImageConstants; public class IPort extends AbstractPort { // Constructors public IPort() { super(new IPlug(), 'I'); } @Override public int getBaseID() { return ObjectImageConstants.OBJECT_IMAGE_I_PORT; } }
yashgolwala/Software_Measurement_Team_M
ProjectSourceCode/Apache Commons Math v3.5/src/main/java/org/apache/commons/math3/ode/ParameterizedWrapper.java
version https://git-lfs.github.com/spec/v1 oid sha256:2e99aa97ad170213b271b2d27e0cbdc564d275ca13a563251bd7fd2ffea29826 size 3029
IvanSolenkov/JS-Advanced
03. Lab Arrays/06. Smallest Two Numbers.js
<filename>03. Lab Arrays/06. Smallest Two Numbers.js function solve(arr) { let result = arr.sort((a,b) => a - b).slice(0, 2); console.log(result); } solve([30, 15, 50, 5]);
binary-star-near/near-wallet
packages/frontend/src/components/Swap/views/SwapPage.js
import React, { useCallback, useState } from 'react'; import { Translate } from 'react-localize-redux'; import { useDispatch } from 'react-redux'; import { useFetchByorSellUSN } from '../../../hooks/fetchByorSellUSN'; import { showCustomAlert } from '../../../redux/actions/status'; import { actions as ledgerActions } from '../../../redux/slices/ledger'; import { fetchMultiplier } from '../../../redux/slices/multiplier'; import { formatTokenAmount } from '../../../utils/amounts'; import { formatNearAmount } from '../../common/balance/helpers'; import FormButton from '../../common/FormButton'; import SwapIconTwoArrows from '../../svg/SwapIconTwoArrows'; import AvailableToSwap from '../AvailableToSwap'; import { commission } from '../helpers'; import Loader from '../Loader'; import SwapInfoContainer from '../SwapInfoContainer'; import SwapTokenContainer from '../SwapTokenContainer'; const { checkAndHideLedgerModal } = ledgerActions; const balanceForError = (from) => { return from?.onChainFTMetadata?.symbol === 'NEAR' ? +formatNearAmount(from?.balance) : +formatTokenAmount(from?.balance, from?.onChainFTMetadata?.decimals, 5); }; const SwapPage = ({ from, to, inputValueFrom, setInputValueFrom, multiplier, accountId, onSwap, setActiveView }) => { const [isSwapped, setIsSwapped] = useState(false); const [slippageValue, setSlippageValue] = useState(1); const [usnAmount, setUSNAmount] = useState(''); const { commissionFee, isLoadingCommission } = commission({ accountId, amount: inputValueFrom, delay: 500, exchangeRate: + multiplier, token: from, isSwapped, }); const { fetchByOrSell, isLoading, setIsLoading } = useFetchByorSellUSN(); const dispatch = useDispatch(); const balance = balanceForError(from); const error = balance < +inputValueFrom || !inputValueFrom; const slippageError = slippageValue < 1 || slippageValue > 50; const onHandleSwapTokens = useCallback(async (accountId, multiplier, slippageValue, inputValueFrom, symbol, usnAmount) => { try { setIsLoading(true); await fetchByOrSell(accountId, multiplier, slippageValue, +inputValueFrom, symbol, usnAmount); setActiveView('success'); } catch (e) { dispatch(showCustomAlert({ errorMessage: e.message, success: false, messageCodeHeader: 'error', })); } finally { setIsLoading(false); dispatch(checkAndHideLedgerModal()); } }, []); return ( <> <Loader onRefreshMultiplier={() => dispatch(fetchMultiplier())}/> <h1> <Translate id="button.swap"/> </h1> <SwapTokenContainer text="swap.from" fromToToken={from} value={inputValueFrom} setInputValueFrom={setInputValueFrom} /> <AvailableToSwap onClick={(balance) => { setInputValueFrom(balance); from?.onChainFTMetadata?.symbol === 'USN' && setUSNAmount(from?.balance); }} balance={from?.balance} symbol={from?.onChainFTMetadata?.symbol} decimals={from?.onChainFTMetadata?.decimals} /> <div className="iconSwap" onClick={() => { onSwap(); setIsSwapped((prev) => !prev); }} > <SwapIconTwoArrows width="23" height="23" color="#72727A" /> </div> <SwapTokenContainer text="swap.to" fromToToken={to} multiplier={multiplier} value={inputValueFrom} /> <SwapInfoContainer slippageError={slippageError} slippageValue={slippageValue} setSlippageValue={setSlippageValue} token={from?.onChainFTMetadata?.symbol} exchangeRate={+multiplier / 10000} amount={inputValueFrom} tradingFee={commissionFee?.result} isLoading={isLoadingCommission} percent={commissionFee?.percent} /> <div className="buttons-bottom-buttons"> <FormButton type="submit" disabled={error || slippageError || isLoading} data-test-id="sendMoneyPageSubmitAmountButton" onClick={() => onHandleSwapTokens(accountId, multiplier, slippageValue, +inputValueFrom, from?.onChainFTMetadata?.symbol, usnAmount)} sending={isLoading} > <Translate id="button.swap"/> </FormButton> <FormButton type="button" className="link" color="gray" linkTo="/" > <Translate id="button.cancel"/> </FormButton> </div> </> ); }; export default SwapPage;
GulajavaMinistudio/CSUDM20202
src/eventsp2/appjs_event2.js
<reponame>GulajavaMinistudio/CSUDM20202 // MULTIPLE LISTENER DI EVENT const colorArray = [ 'red', 'orange', 'yellow', 'green', 'blue', 'purple', 'indigo', 'violet', ]; // EVENTLISTENER akan menampilkan parameter yang bernama event atau e function cetakWarnaKotak(eventclick) { console.log('Tipe event ', eventclick.type); const elementTarget = eventclick.target; const jenisWarna = elementTarget.style.backgroundColor; console.log('Jenis Warna Click ', jenisWarna); const h1ElementJudul = document.querySelector('h1'); h1ElementJudul.style.color = jenisWarna; console.dir(window.getComputedStyle(h1ElementJudul).textAlign); console.log(h1ElementJudul.getAttribute('style')); } // container kotak const containerKotak = document.querySelector('#boxes'); const panjangArray = colorArray.length; for (let i = 0; i < panjangArray; i += 1) { const jenisWarna = colorArray[i]; const kotakElement = document.createElement('div'); kotakElement.style.backgroundColor = jenisWarna; kotakElement.classList.add('box'); containerKotak.appendChild(kotakElement); // berikan listener kotakElement.addEventListener('click', cetakWarnaKotak); } // KEYPRESS KEYUP KEYDOWN // Event listener ketika keyboard telah ditekan, keyboard dipencet, dan ketika keyboard dipencet // KEYPRESS EVENT OBJECT const inputKeyPress = document.querySelector('div #inputkey'); inputKeyPress.addEventListener('keypress', event => { console.log(event); console.log('Key Ditekan', event.key, event.keyCode); }); // KEYDOWN EVENT LISTENER const inputKeydown = document.querySelector('#input_keydown'); inputKeydown.addEventListener('keydown', event => { console.log('KEYDOWN EVENT ', event); }); // KEYUP EVENT LISTENER const inputKeyup = document.querySelector('#input_keyup'); inputKeyup.addEventListener('keyup', event => { console.log('KEYUP EVENT ', event); }); // KEYPRESS CONTOH // Contoh Kasus penggunaan Key Press const inputTambahMakanan = document.querySelector('div #input_makanan'); const listDaftarMakanan = document.querySelector('div #daftar_item'); const tambahMakanan = event => { const elementTarget = event.target; const stringNamaMakanan = elementTarget.value; if (stringNamaMakanan && stringNamaMakanan.length > 1) { const liItem = document.createElement('li'); liItem.innerText = stringNamaMakanan; listDaftarMakanan.appendChild(liItem); // Kosongkan nilai input elementTarget.value = ''; } }; // Ambil aksi Enter dan jalankan ambil nilai value dari input const initListenerInput = () => { inputTambahMakanan.addEventListener('keypress', event => { const keyCodeEvent = event.keyCode; const stringKeyCode = event.key; if (keyCodeEvent === 13 || stringKeyCode === 'Enter') { // tambah ke dalam daftar // jika pake arrow function, tidak bisa pake this. // console.log(this.value); tambahMakanan(event); } }); }; initListenerInput();
JackChan1999/boohee_v5.6
src/main/java/com/boohee/widgets/WaterMakerTextFactory.java
package com.boohee.widgets; import android.content.Context; import android.text.TextUtils; import android.view.View; import android.widget.TextView; import com.boohee.one.R; import java.util.Map; public class WaterMakerTextFactory { public static final String BOTTOM_TEXT = "BOTTOM_TEXT"; public static final String UP_LEFT_TEXT = "UP_LEFT_TEXT"; public static final String UP_MIDDLE_TEXT = "UP_MIDDLE_TEXT"; public static final String UP_RIGHT_TEXT = "UP_RIGHT_TEXT"; private static WaterMakerTextFactory instance = new WaterMakerTextFactory(); private WaterMakerTextFactory() { } public static WaterMakerTextFactory newInstance() { return instance; } public View createEatView(Context mContext, Map<String, String> datas) { View eatView = View.inflate(mContext, R.layout.p3, null); initView(eatView, datas); return eatView; } public View createSportView(Context mContext, Map<String, String> datas) { View sportView = View.inflate(mContext, R.layout.p6, null); initView(sportView, datas); return sportView; } public View createFigureView(Context mContext, Map<String, String> datas) { View figureView = View.inflate(mContext, R.layout.p4, null); initView(figureView, datas); return figureView; } public View createSleepView(Context mContext, Map<String, String> datas) { View sleepView = View.inflate(mContext, R.layout.p5, null); initView(sleepView, datas); return sleepView; } public void initView(View v, Map<String, String> mParams) { v.setClickable(true); String leftText = (String) mParams.get(UP_LEFT_TEXT); String midText = (String) mParams.get(UP_MIDDLE_TEXT); String rightText = (String) mParams.get(UP_RIGHT_TEXT); String botText = (String) mParams.get(BOTTOM_TEXT); if (!TextUtils.isEmpty(leftText)) { TextView mUpLeftText = (TextView) v.findViewById(R.id.upLeftText); mUpLeftText.setText(leftText); mUpLeftText.setVisibility(0); } if (!TextUtils.isEmpty(midText)) { TextView mUpMiddleText = (TextView) v.findViewById(R.id.upMiddleText); mUpMiddleText.setText(midText); mUpMiddleText.setVisibility(0); } if (!TextUtils.isEmpty(rightText)) { TextView mUpRightText = (TextView) v.findViewById(R.id.upRightText); mUpRightText.setText(rightText); mUpRightText.setVisibility(0); } if (!TextUtils.isEmpty(botText)) { TextView mBottomText = (TextView) v.findViewById(R.id.bottomText); mBottomText.setText(botText); mBottomText.setVisibility(0); } } }
dashevo/tendermint
internal/store/store.go
<filename>internal/store/store.go package store import ( "bytes" "fmt" "strconv" "github.com/gogo/protobuf/proto" "github.com/google/orderedcode" dbm "github.com/tendermint/tm-db" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" "github.com/tendermint/tendermint/types" ) /* BlockStore is a simple low level store for blocks. There are three types of information stored: - BlockMeta: Meta information about each block - Block part: Parts of each block, aggregated w/ PartSet - Commit: The commit part of each block, for gossiping precommit votes Currently the precommit signatures are duplicated in the Block parts as well as the Commit. In the future this may change, perhaps by moving the Commit data outside the Block. (TODO) The store can be assumed to contain all contiguous blocks between base and height (inclusive). // NOTE: BlockStore methods will panic if they encounter errors // deserializing loaded data, indicating probable corruption on disk. */ type BlockStore struct { db dbm.DB } // NewBlockStore returns a new BlockStore with the given DB, // initialized to the last height that was committed to the DB. func NewBlockStore(db dbm.DB) *BlockStore { return &BlockStore{db} } // Base returns the first known contiguous block height, or 0 for empty block stores. func (bs *BlockStore) Base() int64 { iter, err := bs.db.Iterator( blockMetaKey(1), blockMetaKey(1<<63-1), ) if err != nil { panic(err) } defer iter.Close() if iter.Valid() { height, err := decodeBlockMetaKey(iter.Key()) if err == nil { return height } } if err := iter.Error(); err != nil { panic(err) } return 0 } // Height returns the last known contiguous block height, or 0 for empty block stores. func (bs *BlockStore) Height() int64 { iter, err := bs.db.ReverseIterator( blockMetaKey(1), blockMetaKey(1<<63-1), ) if err != nil { panic(err) } defer iter.Close() if iter.Valid() { height, err := decodeBlockMetaKey(iter.Key()) if err == nil { return height } } if err := iter.Error(); err != nil { panic(err) } return 0 } func (bs *BlockStore) CoreChainLockedHeight() uint32 { block := bs.LoadBlock(bs.Height()) if block != nil { return block.CoreChainLockedHeight } return 0 } // Size returns the number of blocks in the block store. func (bs *BlockStore) Size() int64 { height := bs.Height() if height == 0 { return 0 } return height + 1 - bs.Base() } // LoadBase atomically loads the base block meta, or returns nil if no base is found. func (bs *BlockStore) LoadBaseMeta() *types.BlockMeta { iter, err := bs.db.Iterator( blockMetaKey(1), blockMetaKey(1<<63-1), ) if err != nil { return nil } defer iter.Close() if iter.Valid() { var pbbm = new(tmproto.BlockMeta) err = proto.Unmarshal(iter.Value(), pbbm) if err != nil { panic(fmt.Errorf("unmarshal to tmproto.BlockMeta: %w", err)) } blockMeta, err := types.BlockMetaFromProto(pbbm) if err != nil { panic(fmt.Errorf("error from proto blockMeta: %w", err)) } return blockMeta } return nil } // LoadBlock returns the block with the given height. // If no block is found for that height, it returns nil. func (bs *BlockStore) LoadBlock(height int64) *types.Block { var blockMeta = bs.LoadBlockMeta(height) if blockMeta == nil { return nil } pbb := new(tmproto.Block) buf := []byte{} for i := 0; i < int(blockMeta.BlockID.PartSetHeader.Total); i++ { part := bs.LoadBlockPart(height, i) // If the part is missing (e.g. since it has been deleted after we // loaded the block meta) we consider the whole block to be missing. if part == nil { return nil } buf = append(buf, part.Bytes...) } err := proto.Unmarshal(buf, pbb) if err != nil { // NOTE: The existence of meta should imply the existence of the // block. So, make sure meta is only saved after blocks are saved. panic(fmt.Errorf("error reading block: %w", err)) } block, err := types.BlockFromProto(pbb) if err != nil { panic(fmt.Errorf("error from proto block: %w", err)) } return block } // LoadBlockByHash returns the block with the given hash. // If no block is found for that hash, it returns nil. // Panics if it fails to parse height associated with the given hash. func (bs *BlockStore) LoadBlockByHash(hash []byte) *types.Block { bz, err := bs.db.Get(blockHashKey(hash)) if err != nil { panic(err) } if len(bz) == 0 { return nil } s := string(bz) height, err := strconv.ParseInt(s, 10, 64) if err != nil { panic(fmt.Sprintf("failed to extract height from %s: %v", s, err)) } return bs.LoadBlock(height) } // LoadBlockMetaByHash returns the blockmeta who's header corresponds to the given // hash. If none is found, returns nil. func (bs *BlockStore) LoadBlockMetaByHash(hash []byte) *types.BlockMeta { bz, err := bs.db.Get(blockHashKey(hash)) if err != nil { panic(err) } if len(bz) == 0 { return nil } s := string(bz) height, err := strconv.ParseInt(s, 10, 64) if err != nil { panic(fmt.Sprintf("failed to extract height from %s: %v", s, err)) } return bs.LoadBlockMeta(height) } // LoadBlockPart returns the Part at the given index // from the block at the given height. // If no part is found for the given height and index, it returns nil. func (bs *BlockStore) LoadBlockPart(height int64, index int) *types.Part { var pbpart = new(tmproto.Part) bz, err := bs.db.Get(blockPartKey(height, index)) if err != nil { panic(err) } if len(bz) == 0 { return nil } err = proto.Unmarshal(bz, pbpart) if err != nil { panic(fmt.Errorf("unmarshal to tmproto.Part failed: %w", err)) } part, err := types.PartFromProto(pbpart) if err != nil { panic(fmt.Errorf("error reading block part: %w", err)) } return part } // LoadBlockMeta returns the BlockMeta for the given height. // If no block is found for the given height, it returns nil. func (bs *BlockStore) LoadBlockMeta(height int64) *types.BlockMeta { var pbbm = new(tmproto.BlockMeta) bz, err := bs.db.Get(blockMetaKey(height)) if err != nil { panic(err) } if len(bz) == 0 { return nil } err = proto.Unmarshal(bz, pbbm) if err != nil { panic(fmt.Errorf("unmarshal to tmproto.BlockMeta: %w", err)) } blockMeta, err := types.BlockMetaFromProto(pbbm) if err != nil { panic(fmt.Errorf("error from proto blockMeta: %w", err)) } return blockMeta } // LoadBlockCommit returns the Commit for the given height. // This commit consists of the +2/3 and other Precommit-votes for block at `height`, // and it comes from the block.LastCommit for `height+1`. // If no commit is found for the given height, it returns nil. func (bs *BlockStore) LoadBlockCommit(height int64) *types.Commit { var pbc = new(tmproto.Commit) bz, err := bs.db.Get(blockCommitKey(height)) if err != nil { panic(err) } if len(bz) == 0 { return nil } err = proto.Unmarshal(bz, pbc) if err != nil { panic(fmt.Errorf("error reading block commit: %w", err)) } commit, err := types.CommitFromProto(pbc) if err != nil { panic(fmt.Errorf("error reading block commit: %w", err)) } return commit } // LoadSeenCommit returns the last locally seen Commit before being // cannonicalized. This is useful when we've seen a commit, but there // has not yet been a new block at `height + 1` that includes this // commit in its block.LastCommit. func (bs *BlockStore) LoadSeenCommit() *types.Commit { var pbc = new(tmproto.Commit) bz, err := bs.db.Get(seenCommitKey()) if err != nil { panic(err) } if len(bz) == 0 { return nil } err = proto.Unmarshal(bz, pbc) if err != nil { panic(fmt.Errorf("error reading block seen commit: %w", err)) } commit, err := types.CommitFromProto(pbc) if err != nil { panic(fmt.Errorf("error from proto commit: %w", err)) } return commit } // PruneBlocks removes block up to (but not including) a height. It returns the number of blocks pruned. func (bs *BlockStore) PruneBlocks(height int64) (uint64, error) { if height <= 0 { return 0, fmt.Errorf("height must be greater than 0") } if height > bs.Height() { return 0, fmt.Errorf("height must be equal to or less than the latest height %d", bs.Height()) } // when removing the block meta, use the hash to remove the hash key at the same time removeBlockHash := func(key, value []byte, batch dbm.Batch) error { // unmarshal block meta var pbbm = new(tmproto.BlockMeta) err := proto.Unmarshal(value, pbbm) if err != nil { return fmt.Errorf("unmarshal to tmproto.BlockMeta: %w", err) } blockMeta, err := types.BlockMetaFromProto(pbbm) if err != nil { return fmt.Errorf("error from proto blockMeta: %w", err) } // delete the hash key corresponding to the block meta's hash if err := batch.Delete(blockHashKey(blockMeta.BlockID.Hash)); err != nil { return fmt.Errorf("failed to delete hash key: %X: %w", blockHashKey(blockMeta.BlockID.Hash), err) } return nil } // remove block meta first as this is used to indicate whether the block exists. // For this reason, we also use ony block meta as a measure of the amount of blocks pruned pruned, err := bs.pruneRange(blockMetaKey(0), blockMetaKey(height), removeBlockHash) if err != nil { return pruned, err } if _, err := bs.pruneRange(blockPartKey(0, 0), blockPartKey(height, 0), nil); err != nil { return pruned, err } if _, err := bs.pruneRange(blockCommitKey(0), blockCommitKey(height), nil); err != nil { return pruned, err } return pruned, nil } // pruneRange is a generic function for deleting a range of values based on the lowest // height up to but excluding retainHeight. For each key/value pair, an optional hook can be // executed before the deletion itself is made. pruneRange will use batch delete to delete // keys in batches of at most 1000 keys. func (bs *BlockStore) pruneRange( start []byte, end []byte, preDeletionHook func(key, value []byte, batch dbm.Batch) error, ) (uint64, error) { var ( err error pruned uint64 totalPruned uint64 ) batch := bs.db.NewBatch() defer batch.Close() pruned, start, err = bs.batchDelete(batch, start, end, preDeletionHook) if err != nil { return totalPruned, err } // loop until we have finished iterating over all the keys by writing, opening a new batch // and incrementing through the next range of keys. for !bytes.Equal(start, end) { if err := batch.Write(); err != nil { return totalPruned, err } totalPruned += pruned if err := batch.Close(); err != nil { return totalPruned, err } batch = bs.db.NewBatch() pruned, start, err = bs.batchDelete(batch, start, end, preDeletionHook) if err != nil { return totalPruned, err } } // once we looped over all keys we do a final flush to disk if err := batch.WriteSync(); err != nil { return totalPruned, err } totalPruned += pruned return totalPruned, nil } // batchDelete runs an iterator over a set of keys, first preforming a pre deletion hook before adding it to the batch. // The function ends when either 1000 keys have been added to the batch or the iterator has reached the end. func (bs *BlockStore) batchDelete( batch dbm.Batch, start, end []byte, preDeletionHook func(key, value []byte, batch dbm.Batch) error, ) (uint64, []byte, error) { var pruned uint64 iter, err := bs.db.Iterator(start, end) if err != nil { return pruned, start, err } defer iter.Close() for ; iter.Valid(); iter.Next() { key := iter.Key() if preDeletionHook != nil { if err := preDeletionHook(key, iter.Value(), batch); err != nil { return 0, start, fmt.Errorf("pruning error at key %X: %w", iter.Key(), err) } } if err := batch.Delete(key); err != nil { return 0, start, fmt.Errorf("pruning error at key %X: %w", iter.Key(), err) } pruned++ if pruned == 1000 { return pruned, iter.Key(), iter.Error() } } return pruned, end, iter.Error() } // SaveBlock persists the given block, blockParts, and seenCommit to the underlying db. // blockParts: Must be parts of the block // seenCommit: The +2/3 precommits that were seen which committed at height. // If all the nodes restart after committing a block, // we need this to reload the precommits to catch-up nodes to the // most recent height. Otherwise they'd stall at H-1. func (bs *BlockStore) SaveBlock(block *types.Block, blockParts *types.PartSet, seenCommit *types.Commit) { if block == nil { panic("BlockStore can only save a non-nil block") } batch := bs.db.NewBatch() height := block.Height hash := block.Hash() if g, w := height, bs.Height()+1; bs.Base() > 0 && g != w { panic(fmt.Sprintf("BlockStore can only save contiguous blocks. Wanted %v, got %v", w, g)) } if !blockParts.IsComplete() { panic("BlockStore can only save complete block part sets") } // Save block parts. This must be done before the block meta, since callers // typically load the block meta first as an indication that the block exists // and then go on to load block parts - we must make sure the block is // complete as soon as the block meta is written. for i := 0; i < int(blockParts.Total()); i++ { part := blockParts.GetPart(i) bs.saveBlockPart(height, i, part, batch) } blockMeta := types.NewBlockMeta(block, blockParts) pbm := blockMeta.ToProto() if pbm == nil { panic("nil blockmeta") } metaBytes := mustEncode(pbm) if err := batch.Set(blockMetaKey(height), metaBytes); err != nil { panic(err) } if err := batch.Set(blockHashKey(hash), []byte(fmt.Sprintf("%d", height))); err != nil { panic(err) } pbc := block.LastCommit.ToProto() blockCommitBytes := mustEncode(pbc) if err := batch.Set(blockCommitKey(height-1), blockCommitBytes); err != nil { panic(err) } // Save seen commit (seen +2/3 precommits for block) pbsc := seenCommit.ToProto() seenCommitBytes := mustEncode(pbsc) if err := batch.Set(seenCommitKey(), seenCommitBytes); err != nil { panic(err) } if err := batch.WriteSync(); err != nil { panic(err) } if err := batch.Close(); err != nil { panic(err) } } func (bs *BlockStore) saveBlockPart(height int64, index int, part *types.Part, batch dbm.Batch) { pbp, err := part.ToProto() if err != nil { panic(fmt.Errorf("unable to make part into proto: %w", err)) } partBytes := mustEncode(pbp) if err := batch.Set(blockPartKey(height, index), partBytes); err != nil { panic(err) } } // SaveSeenCommit saves a seen commit, used by e.g. the state sync reactor when bootstrapping node. func (bs *BlockStore) SaveSeenCommit(height int64, seenCommit *types.Commit) error { pbc := seenCommit.ToProto() seenCommitBytes, err := proto.Marshal(pbc) if err != nil { return fmt.Errorf("unable to marshal commit: %w", err) } return bs.db.Set(seenCommitKey(), seenCommitBytes) } func (bs *BlockStore) SaveSignedHeader(sh *types.SignedHeader, blockID types.BlockID) error { // first check that the block store doesn't already have the block bz, err := bs.db.Get(blockMetaKey(sh.Height)) if err != nil { return err } if bz != nil { return fmt.Errorf("block at height %d already saved", sh.Height) } // FIXME: saving signed headers although necessary for proving evidence, // doesn't have complete parity with block meta's thus block size and num // txs are filled with negative numbers. We should aim to find a solution to // this. blockMeta := &types.BlockMeta{ BlockID: blockID, BlockSize: -1, Header: *sh.Header, NumTxs: -1, } batch := bs.db.NewBatch() pbm := blockMeta.ToProto() metaBytes := mustEncode(pbm) if err := batch.Set(blockMetaKey(sh.Height), metaBytes); err != nil { return fmt.Errorf("unable to save block meta: %w", err) } pbc := sh.Commit.ToProto() blockCommitBytes := mustEncode(pbc) if err := batch.Set(blockCommitKey(sh.Height), blockCommitBytes); err != nil { return fmt.Errorf("unable to save commit: %w", err) } if err := batch.WriteSync(); err != nil { return err } return batch.Close() } func (bs *BlockStore) Close() error { return bs.db.Close() } //---------------------------------- KEY ENCODING ----------------------------------------- // key prefixes const ( // prefixes are unique across all tm db's prefixBlockMeta = int64(0) prefixBlockPart = int64(1) prefixBlockCommit = int64(2) prefixSeenCommit = int64(3) prefixBlockHash = int64(4) ) func blockMetaKey(height int64) []byte { key, err := orderedcode.Append(nil, prefixBlockMeta, height) if err != nil { panic(err) } return key } func decodeBlockMetaKey(key []byte) (height int64, err error) { var prefix int64 remaining, err := orderedcode.Parse(string(key), &prefix, &height) if err != nil { return } if len(remaining) != 0 { return -1, fmt.Errorf("expected complete key but got remainder: %s", remaining) } if prefix != prefixBlockMeta { return -1, fmt.Errorf("incorrect prefix. Expected %v, got %v", prefixBlockMeta, prefix) } return } func blockPartKey(height int64, partIndex int) []byte { key, err := orderedcode.Append(nil, prefixBlockPart, height, int64(partIndex)) if err != nil { panic(err) } return key } func blockCommitKey(height int64) []byte { key, err := orderedcode.Append(nil, prefixBlockCommit, height) if err != nil { panic(err) } return key } func seenCommitKey() []byte { key, err := orderedcode.Append(nil, prefixSeenCommit) if err != nil { panic(err) } return key } func blockHashKey(hash []byte) []byte { key, err := orderedcode.Append(nil, prefixBlockHash, string(hash)) if err != nil { panic(err) } return key } //----------------------------------------------------------------------------- // mustEncode proto encodes a proto.message and panics if fails func mustEncode(pb proto.Message) []byte { bz, err := proto.Marshal(pb) if err != nil { panic(fmt.Errorf("unable to marshal: %w", err)) } return bz }
shockazoid/HydroLanguage
src/assembly/nodes/TryNode.hpp
<reponame>shockazoid/HydroLanguage<filename>src/assembly/nodes/TryNode.hpp // // __ __ __ // / / / /__ __ ____/ /_____ ____ // / /_/ // / / // __ // ___// __ \ // / __ // /_/ // /_/ // / / /_/ / // /_/ /_/ \__, / \__,_//_/ \____/ // /____/ // // The Hydro Programming Language // // © 2020 Shockazoid, Inc. All Rights Reserved. // #ifndef __h3o_TryNode__ #define __h3o_TryNode__ #include "FuncNode.hpp" #include "CatchNode.hpp" #include "Label.hpp" namespace hydro { class TryNode : public BlockNode { private: FuncNode *_owner; Label *_from; Label *_to; Label *_jump; std::vector<CatchNode *> _catches; public: TryNode(FuncNode *owner, Label *start, Label *end, Label *jump); virtual ~TryNode(); virtual void build(Chunk *chunk) override; void append(CatchNode *ctch); const std::vector<CatchNode *> catches() const { return _catches; } }; } // namespace hydro #endif /* __h3o_TryNode__ */
zdzaz/e-c-its
OpenC2X/common/asn1/WheelBaseVehicle.h
<reponame>zdzaz/e-c-its /* * Generated by asn1c-0.9.24 (http://lionet.info/asn1c) * From ASN.1 module "ITS-Container" * found in "its_facilities_pdu_all.asn" * `asn1c -fnative-types -gen-PER` */ #ifndef _WheelBaseVehicle_H_ #define _WheelBaseVehicle_H_ #include <asn_application.h> /* Including external dependencies */ #include <NativeInteger.h> #ifdef __cplusplus extern "C" { #endif /* Dependencies */ typedef enum WheelBaseVehicle { WheelBaseVehicle_tenCentimeters = 1, WheelBaseVehicle_unavailable = 127 } e_WheelBaseVehicle; /* WheelBaseVehicle */ typedef long WheelBaseVehicle_t; /* Implementation */ extern asn_TYPE_descriptor_t asn_DEF_WheelBaseVehicle; asn_struct_free_f WheelBaseVehicle_free; asn_struct_print_f WheelBaseVehicle_print; asn_constr_check_f WheelBaseVehicle_constraint; ber_type_decoder_f WheelBaseVehicle_decode_ber; der_type_encoder_f WheelBaseVehicle_encode_der; xer_type_decoder_f WheelBaseVehicle_decode_xer; xer_type_encoder_f WheelBaseVehicle_encode_xer; per_type_decoder_f WheelBaseVehicle_decode_uper; per_type_encoder_f WheelBaseVehicle_encode_uper; #ifdef __cplusplus } #endif #endif /* _WheelBaseVehicle_H_ */ #include <asn_internal.h>
rom1119/pacgame-fx
src/main/java/com/pacgame/provider/stage/PrimaryStage.java
package com.pacgame.provider.stage; import com.pacgame.provider.Stage; public class PrimaryStage extends Stage { public PrimaryStage() { super(); } void setProxyObject(javafx.stage.Stage stage) { this.getProxy().setProxyObject(stage); } }
xlvchao/spartacus
spartacus-common/spartacus-common-core/src/main/java/com/xlc/spartacus/common/core/exception/BaseException.java
<filename>spartacus-common/spartacus-common-core/src/main/java/com/xlc/spartacus/common/core/exception/BaseException.java package com.xlc.spartacus.common.core.exception; /** * 基础异常 * * @author xlc, since 2021 */ public class BaseException extends RuntimeException { private static final long serialVersionUID = 1L; public BaseException(String message) { super(message); } public BaseException(Throwable cause) { super(cause); } public BaseException(String message, Throwable cause) { super(message, cause); } public BaseException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
zhengyi5541/driver
eladmin-system/src/main/java/me/zhengjie/modules/zhengyi/user/domain/ZyDriveUser.java
<gh_stars>0 /* * Copyright 2019-2020 <NAME> * * 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 me.zhengjie.modules.zhengyi.user.domain; import lombok.Data; import cn.hutool.core.bean.BeanUtil; import io.swagger.annotations.ApiModelProperty; import cn.hutool.core.bean.copier.CopyOptions; import javax.persistence.*; import javax.validation.constraints.*; import javax.persistence.Entity; import javax.persistence.Table; import org.hibernate.annotations.*; import java.sql.Timestamp; import java.io.Serializable; /** * @website https://el-admin.vip * @description / * @author 政一 * @date 2020-06-25 **/ @Entity @Data @Table(name="zy_drive_user") public class ZyDriveUser implements Serializable { @Id @Column(name = "id") @ApiModelProperty(value = "id") private String id; @Column(name = "name") @ApiModelProperty(value = "姓名") private String name; @Column(name = "img") @ApiModelProperty(value = "照片") private String img; @Column(name = "age") @ApiModelProperty(value = "年龄") private Integer age; @Column(name = "driving_years") @ApiModelProperty(value = "驾龄") private Integer drivingYears; @Column(name = "phone") @ApiModelProperty(value = "电话") private String phone; @Column(name = "driving_type") @ApiModelProperty(value = "驾驶证类型") private Integer drivingType; @Column(name = "working_state") @ApiModelProperty(value = "在职状态") private Integer workingState; @Column(name = "status") @ApiModelProperty(value = "禁用状态") private Long status; @Column(name = "del") @ApiModelProperty(value = "删除状态") private Integer del; @Column(name = "audit") @ApiModelProperty(value = "审核状态") private Integer audit; @Column(name = "driver_positive") @ApiModelProperty(value = "驾驶证正面") private String driverPositive; @Column(name = "driver_reverse") @ApiModelProperty(value = "驾驶证反面") private String driverReverse; @Column(name = "create_time") @CreationTimestamp @ApiModelProperty(value = "创建时间") private Timestamp createTime; public void copy(ZyDriveUser source){ BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true)); } }
algol60/constellation
CoreUtilities/test/unit/src/au/gov/asd/tac/constellation/utilities/genericjsonio/JsonIODialogNGTest.java
/* * Copyright 2010-2021 Australian Signals Directorate * * 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 au.gov.asd.tac.constellation.utilities.genericjsonio; import java.util.List; import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import javafx.collections.FXCollections; import javafx.scene.control.Button; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.control.TextField; import javafx.stage.Modality; import javafx.stage.Stage; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.testfx.api.FxRobot; import org.testfx.api.FxToolkit; import static org.testfx.util.NodeQueryUtils.hasText; import org.testfx.util.WaitForAsyncUtils; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * * @author formalhaunt */ public class JsonIODialogNGTest { private final FxRobot robot = new FxRobot(); public JsonIODialogNGTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @BeforeMethod public void setUpMethod() throws Exception { FxToolkit.registerPrimaryStage(); } @AfterMethod public void tearDownMethod() throws Exception { FxToolkit.cleanupStages(); } @Test public void getSelection_ok_pressed() throws InterruptedException, ExecutionException { final List<String> names = List.of("myPreferenceFile", "theirPreferenceFile"); final Future<Optional<String>> future = WaitForAsyncUtils.asyncFx( () -> JsonIODialog.getSelection(names, Optional.of(""), Optional.of(""))); final Stage dialog = getDialog(robot); WaitForAsyncUtils.asyncFx(() -> dialog.requestFocus()).get(); robot.clickOn(robot.from(dialog.getScene().getRoot()) .lookup(".list-cell") .lookup(hasText("myPreferenceFile")) .queryAs(ListCell.class)); robot.clickOn(robot.from(dialog.getScene().getRoot()) .lookup(".button") .lookup(hasText("OK")) .queryAs(Button.class)); final Optional<String> result = WaitForAsyncUtils.waitFor(future); assertTrue(result.isPresent()); assertEquals(result.get(), "myPreferenceFile"); } @Test public void getSelection_cancel_pressed() throws InterruptedException, ExecutionException { final List<String> names = List.of("myPreferenceFile", "theirPreferenceFile"); final Future<Optional<String>> future = WaitForAsyncUtils.asyncFx( () -> JsonIODialog.getSelection(names, Optional.of(""), Optional.of(""))); final Stage dialog = getDialog(robot); WaitForAsyncUtils.asyncFx(() -> dialog.requestFocus()).get(); robot.clickOn(robot.from(dialog.getScene().getRoot()) .lookup(".list-cell") .lookup(hasText("myPreferenceFile")) .queryAs(ListCell.class)); robot.clickOn(robot.from(dialog.getScene().getRoot()) .lookup(".button") .lookup(hasText("Cancel")) .queryAs(Button.class)); final Optional<String> result = WaitForAsyncUtils.waitFor(future); assertFalse(result.isPresent()); } @Test public void getSelection_remove_pressed() throws InterruptedException, ExecutionException { final List<String> names = List.of("myPreferenceFile", "theirPreferenceFile"); final Future<Optional<String>> future = WaitForAsyncUtils.asyncFx(() -> { // The JsonIO Mock happens here because the static mocking needs to be on // the same thread as the execution try (MockedStatic<JsonIO> jsonIOMockedStatic = Mockito.mockStatic(JsonIO.class)) { final Optional<String> result = JsonIODialog.getSelection( names, Optional.of("loadDir"), Optional.of("filePrefix")); // Verify the call to delete jsonIOMockedStatic.verify(() -> JsonIO .deleteJsonPreference("theirPreferenceFile", Optional.of("loadDir"), Optional.of("filePrefix"))); return result; } }); final Stage dialog = getDialog(robot); // IMPORTANT. Request focus. Until this is done the JavaFX scene in the // dialog does not appear to initialize and the following robot lookup // code will fail WaitForAsyncUtils.asyncFx(() -> dialog.requestFocus()).get(); // Select a row and delete it robot.clickOn(robot.from(dialog.getScene().getRoot()) .lookup(".list-cell") .lookup(hasText("theirPreferenceFile")) .queryAs(ListCell.class)); robot.clickOn(robot.from(dialog.getScene().getRoot()) .lookup(".button") .lookup(hasText("Remove")) .queryAs(Button.class)); // Pull out the list view and verify its current list state. There should // only be one item now. final ListView listView = robot.from(dialog.getScene().getRoot()) .lookup(".list-view") .queryAs(ListView.class); assertEquals(listView.getItems(), FXCollections.observableArrayList("myPreferenceFile")); // Cancel the dialog so it closes robot.clickOn(robot.from(dialog.getScene().getRoot()) .lookup(".button") .lookup(hasText("Cancel")) .queryAs(Button.class)); final Optional<String> result = WaitForAsyncUtils.waitFor(future); assertFalse(result.isPresent()); } @Test public void getPreferenceFileName_ok_pressed() { final Future<Optional<String>> future = WaitForAsyncUtils.asyncFx( () -> JsonIODialog.getPreferenceFileName()); final Stage dialog = getDialog(robot); final String input = "myPreferenceFile"; robot.clickOn( robot.from(dialog.getScene().getRoot()) .lookup(".text-field") .queryAs(TextField.class) ).write(input); robot.clickOn( robot.from(dialog.getScene().getRoot()) .lookup(".button") .lookup(hasText("OK")) .queryAs(Button.class) ); final Optional<String> result = WaitForAsyncUtils.waitFor(future); assertEquals(input, result.get()); } @Test public void getPreferenceFileName_cancel_pressed() { final Future<Optional<String>> future = WaitForAsyncUtils.asyncFx( () -> JsonIODialog.getPreferenceFileName()); final Stage dialog = getDialog(robot); robot.clickOn( robot.from(dialog.getScene().getRoot()) .lookup(".text-field") .queryAs(TextField.class) ).write("myPreferenceFile"); robot.clickOn( robot.from(dialog.getScene().getRoot()) .lookup(".button") .lookup(hasText("Cancel")) .queryAs(Button.class) ); final Optional<String> result = WaitForAsyncUtils.waitFor(future); assertFalse(result.isPresent()); } /** * Get a dialog that has been displayed to the user. This will iterate through * all open windows and identify one that is modal. The assumption is that there * will only ever be one dialog open. * <p/> * If a dialog is not found then it will wait for the JavaFX thread queue to empty * and try again. * * @param robot the FX robot for these tests * @return the found dialog */ private Stage getDialog(final FxRobot robot) { Stage dialog = null; while(dialog == null) { dialog = robot.robotContext().getWindowFinder().listWindows().stream() .filter(window -> window instanceof javafx.stage.Stage) .map(window -> (javafx.stage.Stage) window) .filter(stage -> stage.getModality() == Modality.APPLICATION_MODAL) .findFirst() .orElse(null); if (dialog == null) { WaitForAsyncUtils.waitForFxEvents(); } } return dialog; } }
lesaint/experimenting-annotation-processing
experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_1626.java
<gh_stars>1-10 package fr.javatronic.blog.massive.annotation1.sub1; import fr.javatronic.blog.processor.Annotation_001; @Annotation_001 public class Class_1626 { }
todorkrastev/softuni-software-engineering
JavaScript/M02_JavaScriptFundamentals/L05_ArraysAdvanced/Exercises/P02_DistinctArray.js
<reponame>todorkrastev/softuni-software-engineering function foo(arr) { return arr.reduce((a, v) => { if (!a.includes(v)) a.push(v) return a }, []).join(' '); }
eshuo/bfly
p2p-app/src/main/java/info/bfly/app/protocol/model/response/ApiUser.java
package info.bfly.app.protocol.model.response; import info.bfly.archer.user.model.User; import javax.validation.constraints.NotNull; import static org.apache.commons.lang3.Validate.notNull; /** * Created by XXSun on 2016/12/13. */ public class ApiUser { @NotNull private String emailAddress; private Integer age; private String id; public ApiUser() { } public ApiUser(User user) { this.emailAddress = user.getEmail(); this.id = user.getId(); } public String getEmailAddress() { return emailAddress; } public void setEmailAddress(final String emailAddress) { notNull(emailAddress, "Mandatory argument 'emailAddress missing.'"); this.emailAddress = emailAddress; } public String getId() { return id; } public void setId(final String id) { notNull(id, "Mandatory argument 'id missing.'"); this.id = id; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
MagnusTiberius/terra.simulacra
socketd/MasterSocket.cpp
<reponame>MagnusTiberius/terra.simulacra #include "stdafx.h" #include "MasterSocket.h" MasterSocket::MasterSocket(void) :SocketServer(DEFAULT_DOMAIN, (int)DEFAULT_PORT) { } MasterSocket::~MasterSocket(void) { } void MasterSocket::Start(void) { do { printf("Listening...\n"); SOCKET clientSocket = Accept(); SocketdThread* socketdThread = SocketdThread::Create(clientSocket); auto w = socketdThread->Wait(100); delete socketdThread; } while (true); }
Sahil1515/coding
002_YouTube/GeeksForGeeks/Queues/prog0006_Reversing_a_queue.cpp
//Initial Template for C++ #include<bits/stdc++.h> using namespace std; queue<long long int> rev(queue<long long int> q); int main() { long long int test; cin>>test; while(test--) { queue<long long int> q; long long int n, var; cin>>n; while(n--) { cin>>var; q.push(var); } queue<long long int> a=rev(q); while(!a.empty()) { cout<<a.front()<<" "; a.pop(); } cout<<endl; } }// } Driver Code Ends //function Template for C++ void reverse(queue<long long int> &q) { if(!q.empty()) { int temp=q.front(); q.pop(); reverse(q); q.push(temp); } } queue<long long int> rev(queue<long long int> q) { // add code here. reverse(q); return q; } // Execution Time:0.2 // 1 Mark // Input: // 4 // 4 3 2 1 // Output: // 1 2 3 4
bbodenmiller/onebusaway-android
onebusaway-android/src/main/java/com/joulespersecond/oba/elements/ObaReferencesElement.java
/* * Copyright (C) 2010 <NAME> (<EMAIL>) * * 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.joulespersecond.oba.elements; import java.util.ArrayList; import java.util.List; public final class ObaReferencesElement implements ObaReferences { public static final ObaReferencesElement EMPTY_OBJECT = new ObaReferencesElement(); private final ObaStopElement[] stops; private final ObaRouteElement[] routes; private final ObaTripElement[] trips; private final ObaAgencyElement[] agencies; private final ObaSituationElement[] situations; public ObaReferencesElement() { stops = ObaStopElement.EMPTY_ARRAY; routes = ObaRouteElement.EMPTY_ARRAY; trips = ObaTripElement.EMPTY_ARRAY; agencies = ObaAgencyElement.EMPTY_ARRAY; situations = ObaSituationElement.EMPTY_ARRAY; } @Override public ObaStop getStop(String id) { return findById(stops, id); } @Override public List<ObaStop> getStops(String[] ids) { return findList(ObaStop.class, stops, ids); } @Override public ObaRoute getRoute(String id) { return findById(routes, id); } @Override public List<ObaRoute> getRoutes(String[] ids) { return findList(ObaRoute.class, routes, ids); } @Override public ObaTrip getTrip(String id) { return findById(trips, id); } @Override public List<ObaTrip> getTrips(String[] ids) { return findList(ObaTrip.class, trips, ids); } @Override public ObaAgency getAgency(String id) { return findById(agencies, id); } @Override public List<ObaAgency> getAgencies(String[] ids) { return findList(ObaAgency.class, agencies, ids); } @Override public ObaSituation getSituation(String id) { return findById(situations, id); } @Override public List<ObaSituation> getSituations(String[] ids) { return findList(ObaSituation.class, situations, ids); } // // TODO: This will be much easier when we convert to HashMap storage. // private static <T extends ObaElement> T findById(T[] objects, String id) { final int len = objects.length; for (int i = 0; i < len; ++i) { final T obj = objects[i]; if (obj.getId().equals(id)) { return obj; } } return null; } private static <E extends ObaElement, T extends E> List<E> findList( Class<E> cls, T[] objects, String[] ids) { ArrayList<E> result = new ArrayList<E>(); final int len = ids.length; for (int i = 0; i < len; ++i) { final String id = ids[i]; final T obj = findById(objects, id); if (obj != null) { result.add(obj); } } return result; } }
kvtemadden/music-to-my-eyes
client/src/components/SpotifyComp/SpotifyDashboard.js
<filename>client/src/components/SpotifyComp/SpotifyDashboard.js import { useState, useEffect } from 'react' import { Container, Form } from 'react-bootstrap' import useAuth from "./spotifyUserAuth" import SpotifyWebApi from 'spotify-web-api-node' import TrackSearchResult from './TrackSearchResult' const spotifyApi = new SpotifyWebApi({ clientId: process.env.REACT_APP_CLIENT_ID, }) export default function SpotifyDashboard({ code }) { const accessToken = useAuth(code); const [songSearch, setSongSearch] = useState(""); const [searchResults, setSearchResults] = useState([]); useEffect(() => { if (!accessToken) return spotifyApi.setAccessToken(accessToken) }, [accessToken]) useEffect(() => { if (!songSearch) return setSearchResults([]) if (!accessToken) return let cancel = false spotifyApi.searchTracks(songSearch).then(res => { if (cancel) return setSearchResults( res.body.tracks.items.map(track => { const smallestAlbumImage = track.album.images.reduce( (smallest, image) => { if (image.height < smallest.height) return image return smallest }, track.album.images[0] ) return { artist: track.artists[0].name, title: track.name, uri: track.uri, albumUrl: smallestAlbumImage.url, } }) ) }); return () => (cancel = true) }, [songSearch, accessToken]) return ( <Container> <h3 className="my-2">Please select 3 of your favourite songs from the search results</h3> <Form.Control className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline my-2" type="search" placeholder="Search Songs or Artists" value={songSearch} onChange={e => setSongSearch(e.target.value)} /> <div className="flex-grow-1 my-2" style={{ overflowY: "auto" }}> {searchResults.map(track => ( <TrackSearchResult track={track} key={track.uri} /> ))} </div> </Container> ) }
ahmadertarizqi/layar-movie-app
src/views/home/HomeContainer.js
import React, { useEffect, useState } from 'react'; import API from 'services/movies'; import { Link } from 'react-router-dom'; import { BoxGenre, BoxGenreItem } from 'components/BoxGenre'; import TrendingMovieList from './TrendingMovieList'; import TrendingPeopleList from './TrendingPeopleList'; import Loading from 'components/Loading'; export default function Browse() { const [genresMovie, setGenresMovie] = useState([]); const [trendingMovie, setTrendingMovie] = useState([]); const [trendingPeople, setTrendingPeople] = useState([]); const [timeCategory, setTimeCategory] = useState('day'); const [isLoading, setIsLoading] = useState(false); useEffect(() => { const getGenre = async () => { const results = await API.getGenreMovie(); setGenresMovie(results); }; const getTrendingPeople = async () => { const response = await API.getTrending('person'); setTrendingPeople(response.results); }; getGenre(); getTrendingPeople(); }, []); const getTrendingMovie = async (time) => { setIsLoading(true); const response = await API.getTrending('movie', time); setTrendingMovie(response.results); setIsLoading(false); }; useEffect(() => { getTrendingMovie(timeCategory); }, [timeCategory]); if(genresMovie.length < 1 || trendingMovie.length < 1 || trendingPeople.length < 1) { return ( <div className="loading-wrapper-centered"> <Loading width={50} height={50} /> <h4 className="has-text-white">Loading...</h4> </div> ) } return ( <div> <BoxGenre data={genresMovie}> {genresMovie.map(genre => ( <BoxGenreItem key={genre.id}> <Link to={`/genres/${genre.id}-${genre.name.toLowerCase().replace(' ','-')}`} className="box-genre-item-value"> {genre.name} </Link> </BoxGenreItem> ))} </BoxGenre> <div className="mb-5"></div> <div className="columns"> <div className="column is-8"> <TrendingMovieList movies={trendingMovie} timeCategory={timeCategory} onSelectChange={setTimeCategory} isLoading={isLoading} /> </div> <div className="column is-4"> <TrendingPeopleList peoples={trendingPeople} /> </div> </div> </div> ) };
WillyLu326/Angular2-MEAN
node_modules/tsickle/test_files/variables/variables.js
<filename>node_modules/tsickle/test_files/variables/variables.js goog.module('test_files.variables.variables');var module = module || {id: 'test_files/variables/variables.js'};var /** @type {string} */ v1; var /** @type {string} */ v2, /** @type {number} */ v3;
luc-tuyishime/authors-haven-backend
src/middlewares/checkArticlePermissions.js
<reponame>luc-tuyishime/authors-haven-backend<gh_stars>10-100 import status from '../config/status'; const checkArticlePermissions = role => (req, res, next) => ((role[req.user.role] === 'self' && req.user.id === req.article.userId) || role[req.user.role] === 'all' ? next() : res.status(status.UNAUTHORIZED).json({ errors: { permission: "you don't have the required permission to perform this action" } })); export default checkArticlePermissions;
jlynch2121/dpla-frontend
pages/pro/index.js
import React from "react"; import MainLayout from "components/MainLayout"; import HomePro from "components/HomePageComponents/HomePro"; import { NEWS_PRO_ENDPOINT, PAGES_ENDPOINT } from "constants/content-pages"; import { API_SETTINGS_ENDPOINT } from "constants/site"; const Home = ({ url, news, content }) => <MainLayout hidePageHeader={false} hideSearchBar={true} route={url}> <div id="main" role="main"> <HomePro url={url} news={news} content={content} /> </div> </MainLayout>; Home.getInitialProps = async ({ req }) => { // fetch home info // 1. fetch the settings from WP const settingsRes = await fetch(API_SETTINGS_ENDPOINT); const settingsJson = await settingsRes.json(); // 2. get the corresponding value const endpoint = `${PAGES_ENDPOINT}/${settingsJson.acf .pro_homepage_endpoint}`; // 3. fetch it const homeRes = await fetch(endpoint); const homeJson = await homeRes.json(); // fetch news posts const newsRes = await fetch(NEWS_PRO_ENDPOINT); const newsItems = await newsRes.json(); return { news: newsItems, content: homeJson }; }; export default Home;
Imranr2/tp
src/main/java/ay2122s1_cs2103t_w16_2/btbb/model/shared/Quantity.java
package ay2122s1_cs2103t_w16_2.btbb.model.shared; import static ay2122s1_cs2103t_w16_2.btbb.commons.util.AppUtil.checkArgument; import static java.util.Objects.requireNonNull; /** * Represents the quantity of an Ingredient in btbb. * Guarantees: details are present and not null, field values are validated, immutable. */ public class Quantity implements Comparable<Quantity> { public static final int DEFAULT_MIN_QUANTITY = 0; public static final int DEFAULT_MAX_QUANTITY = 40000; public static final String DEFAULT_MIN_QUANTITY_STRING = String.valueOf(DEFAULT_MIN_QUANTITY); public static final String DEFAULT_MAX_QUANTITY_STRING = String.valueOf(DEFAULT_MAX_QUANTITY); public static final String MESSAGE_CONSTRAINTS = "Quantity should only contain numbers, it should be positive " + "and the largest acceptable quantity is 40000."; public static final String MESSAGE_INTERNAL_CONSTRAINTS = "Quantity should only contain numbers, " + "it should be non-negative and the largest acceptable quantity is 40000."; private final int quantity; /** * Constructs a {@code Quantity}. * * @param quantity A valid quantity number. */ public Quantity(String quantity) { requireNonNull(quantity); checkArgument(isValidInternalQuantity(quantity), MESSAGE_INTERNAL_CONSTRAINTS); this.quantity = Integer.parseInt(quantity); } /** * Returns true if a given string is a valid quantity. * * @param test String input to check. * @return boolean of whether quantity is valid. */ public static boolean isValidQuantity(String test) { try { int quantity = Integer.parseInt(test); return quantity > DEFAULT_MIN_QUANTITY && quantity <= DEFAULT_MAX_QUANTITY; } catch (NumberFormatException numberFormatException) { return false; } } /** * Returns true if a given string is a valid internal quantity. * For internal use there is a wider definition of a valid quantity. * * @param test String input to check. * @return boolean of whether quantity is valid. */ public static boolean isValidInternalQuantity(String test) { try { int quantity = Integer.parseInt(test); return quantity >= DEFAULT_MIN_QUANTITY && quantity <= DEFAULT_MAX_QUANTITY; } catch (NumberFormatException numberFormatException) { return false; } } /** * Gets the integer value stored in {@Quantity}. * * @return Quantity value. */ public int getQuantityAsInt() { return this.quantity; } /** * Returns a new {@code Quantity} object with its quantity increased by amount * multiplier. * * @param amount The amount to increase. * @param multiplier The multiplier. * @return A new {@code Quantity} object. */ public Quantity addQuantityBy(Quantity amount, Quantity multiplier) { return new Quantity(Integer.toString( Math.min(quantity + amount.quantity * multiplier.quantity, DEFAULT_MAX_QUANTITY))); } /** * Returns a new {@code Quantity} object with its quantity reduced by amount * multiplier. * * @param amount The amount to decrease. * @param multiplier The multiplier. * @return A new {@code Quantity} object. */ public Quantity minusQuantityBy(Quantity amount, Quantity multiplier) { return new Quantity(Integer.toString( Math.max(quantity - amount.quantity * multiplier.quantity, DEFAULT_MIN_QUANTITY))); } /** * Converts Quantity object into its String representation. * * @return String representation of quantity. */ @Override public String toString() { return Integer.toString(quantity); } /** * Returns true if object and this quantity are the same. * * @param other object to compare this quantity to. * @return boolean of whether quantity and other object match. */ @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof Quantity // instanceof handles nulls && quantity == ((Quantity) other).quantity); // state check } /** * Implements hashcode for quantity objects. * * @return hashcode of quantity. */ @Override public int hashCode() { return quantity; } @Override public int compareTo(Quantity otherQuantity) { return this.quantity - otherQuantity.quantity; } }
m5o/passenger
test/cxx/StaticStringTest.cpp
#include <TestSupport.h> #include <StaticString.h> using namespace Passenger; using namespace std; namespace tut { struct StaticStringTest: public TestBase { }; DEFINE_TEST_GROUP(StaticStringTest); TEST_METHOD(1) { // Test == operator. ensure(StaticString("") == ""); ensure(StaticString("foo") == "foo"); ensure(!(StaticString("foo") == "bar")); ensure(!(StaticString("barr") == "bar")); ensure(!(StaticString("bar") == "barr")); ensure(StaticString("") == StaticString("")); ensure(StaticString("foo") == StaticString("foo")); ensure(!(StaticString("foo") == StaticString("bar"))); ensure(!(StaticString("barr") == StaticString("bar"))); ensure(!(StaticString("bar") == StaticString("barr"))); ensure(StaticString("") == string("")); ensure(StaticString("foo") == string("foo")); ensure(!(StaticString("foo") == string("bar"))); ensure(!(StaticString("barr") == string("bar"))); ensure(!(StaticString("bar") == string("barr"))); } TEST_METHOD(2) { // Test != operator ensure(!(StaticString("") != "")); ensure(!(StaticString("foo") != "foo")); ensure(StaticString("foo") != "bar"); ensure(StaticString("barr") != "bar"); ensure(StaticString("bar") != "barr"); ensure(!(StaticString("") != StaticString(""))); ensure(!(StaticString("foo") != StaticString("foo"))); ensure(StaticString("foo") != StaticString("bar")); ensure(StaticString("barr") != StaticString("bar")); ensure(StaticString("bar") != StaticString("barr")); ensure(!(StaticString("") != string(""))); ensure(!(StaticString("foo") != string("foo"))); ensure(StaticString("foo") != string("bar")); ensure(StaticString("barr") != string("bar")); ensure(StaticString("bar") != string("barr")); } TEST_METHOD(3) { // Test < operator. ensure_equals("Assertion 1", StaticString("") < "", string("") < string("") ); ensure_equals("Assertion 2", StaticString("abc") < "abc", string("abc") < string("abc") ); ensure_equals("Assertion 3", StaticString("foo") < "bar", string("foo") < string("bar") ); ensure_equals("Assertion 4", StaticString("foo") < "bar!", string("foo") < string("bar!") ); ensure_equals("Assertion 5", StaticString("bar!") < "foo", string("bar!") < string("foo") ); ensure_equals("Assertion 6", StaticString("hello") < "hello world", string("hello") < string("hello world") ); ensure_equals("Assertion 7", StaticString("hello world") < "hello", string("hello world") < string("hello") ); } TEST_METHOD(4) { // Test find(char) ensure_equals("Assertion 1", StaticString("").find('c'), string::npos ); ensure_equals("Assertion 2", StaticString("hello world").find('c'), string::npos ); ensure_equals("Assertion 3", StaticString("hello world").find('h'), (string::size_type) 0 ); ensure_equals("Assertion 4", StaticString("hello world").find('o'), (string::size_type) 4 ); ensure_equals("Assertion 5", StaticString("hello world").find('h', 1), string::npos ); ensure_equals("Assertion 6", StaticString("hello world").find('o', 1), (string::size_type) 4 ); ensure_equals("Assertion 7", StaticString("hello world").find('o', 5), (string::size_type) 7 ); ensure_equals("Assertion 8", StaticString("hello world").find('h', 12), string::npos ); ensure_equals("Assertion 9", StaticString("hello world").find('h', 20), string::npos ); } TEST_METHOD(5) { // Test find(str) ensure_equals("Assertion 1", StaticString("").find(""), (string::size_type) 0 ); ensure_equals("Assertion 2", StaticString("").find("c"), string::npos ); ensure_equals("Assertion 3", StaticString("hello world").find("c"), string::npos ); ensure_equals("Assertion 4", StaticString("hello world").find("h"), (string::size_type) 0 ); ensure_equals("Assertion 5", StaticString("hello world").find("o"), (string::size_type) 4 ); ensure_equals("Assertion 6", StaticString("hello world").find("ello"), (string::size_type) 1 ); ensure_equals("Assertion 7", StaticString("hello world").find("world"), (string::size_type) 6 ); ensure_equals("Assertion 8", StaticString("hello world").find("worldd"), string::npos ); ensure_equals("Assertion 9", StaticString("hello world").find(""), (string::size_type) 0 ); ensure_equals("Assertion 10", StaticString("hello world").find("h", 1), string::npos ); ensure_equals("Assertion 11", StaticString("hello hello").find("ll", 1), (string::size_type) 2 ); ensure_equals("Assertion 12", StaticString("hello hello").find("ll", 3), (string::size_type) 8 ); ensure_equals("Assertion 13", StaticString("hello world").find("he", 12), string::npos ); ensure_equals("Assertion 14", StaticString("hello world").find("he", 20), string::npos ); } TEST_METHOD(6) { // Test substr() ensure_equals("Assertion 1", StaticString("hello world").substr(), "hello world"); ensure_equals("Assertion 2", StaticString("hello world").substr(1), "ello world"); ensure_equals("Assertion 3", StaticString("hello world").substr(4), "o world"); ensure_equals("Assertion 4", StaticString("hello world").substr(11), ""); try { StaticString("hello world").substr(12); fail("out_of_range expected"); } catch (out_of_range &) { // Success. } ensure_equals("Assertion 5", StaticString("hello world").substr(2, 3), "llo"); ensure_equals("Assertion 6", StaticString("hello world").substr(6, 10), "world"); } TEST_METHOD(7) { // Test find_first_of() ensure_equals("Assertion 1", StaticString("hello world").find_first_of("h"), 0u); ensure_equals("Assertion 2", StaticString("hello world").find_first_of("e"), 1u); ensure_equals("Assertion 3", StaticString("hello world").find_first_of("o"), 4u); ensure_equals("Assertion 4", StaticString("hello world").find_first_of("o", 4), 4u); ensure_equals("Assertion 5", StaticString("hello world").find_first_of("o", 5), 7u); ensure_equals("Assertion 6", StaticString("hello world").find_first_of("wo"), 4u); ensure_equals("Assertion 7", StaticString("hello world").find_first_of("ow", 5), 6u); ensure_equals("Assertion 8", StaticString("hello world").find_first_of("x"), string::npos); ensure_equals("Assertion 9", StaticString("hello world").find_first_of("xyz"), string::npos); ensure_equals("Assertion 10", StaticString("").find_first_of("a"), string::npos); ensure_equals("Assertion 11", StaticString("").find_first_of("a", 5), string::npos); } }
Dandush03/FinalCapstone.FrontEnd
src/javascript/swipedEvent.js
<reponame>Dandush03/FinalCapstone.FrontEnd export default class Swipe { constructor(element) { this.xDown = null; this.yDown = null; this.element = typeof (element) === 'string' ? document.querySelector(element) : element; this.element.addEventListener('touchstart', (evt) => { this.xDown = evt.touches[0].clientX; this.yDown = evt.touches[0].clientY; }, false); } onLeft(callback) { this.onLeft = callback; return this; } onRight(callback) { this.onRight = callback; return this; } handleTouchMove(evt) { if (!this.xDown || !this.yDown) { return; } const xUp = evt.touches[0].clientX; const yUp = evt.touches[0].clientY; this.xDiff = this.xDown - xUp; this.yDiff = this.yDown - yUp; if (Math.abs(this.xDiff) > Math.abs(this.yDiff)) { if (this.xDiff > 0) { this.onLeft(); } else { this.onRight(); } } this.xDown = null; this.yDown = null; } run() { this.element.addEventListener('touchmove', (evt) => { this.handleTouchMove(evt); }, false); } }
solanolabs/cfoundry
lib/cfoundry/v2/app_instance.rb
<reponame>solanolabs/cfoundry module CFoundry::V2 class AppInstance attr_reader :id def self.for_app(name, guid, client) client.base.instances(guid).collect do |i, m| AppInstance.new(name, guid, i.to_s, client, m) end end def initialize(app_name, app_guid, id, client, manifest = {}) @app_name = app_name @app_guid = app_guid @id = id @client = client @manifest = manifest end def inspect "#<App::Instance '#{@app_name}' \##@id>" end def state @manifest[:state] end alias_method :status, :state def since if since = @manifest[:since] Time.at(@manifest[:since]) end end def debugger return unless @manifest[:debug_ip] and @manifest[:debug_port] {:ip => @manifest[:debug_ip], :port => @manifest[:debug_port] } end def console return unless @manifest[:console_ip] and @manifest[:console_port] {:ip => @manifest[:console_ip], :port => @manifest[:console_port] } end def healthy? case state when "STARTING", "RUNNING" true when "DOWN", "FLAPPING" false end end def files(*path) @client.base.files(@app_guid, @id, *path).split("\n").collect do |entry| path + [entry.split(/\s+/, 2)[0]] end end def file(*path) @client.base.files(@app_guid, @id, *path) end def stream_file(*path, &blk) @client.base.stream_file(@app_guid, @id, *path, &blk) end end end
redchew-fork/BlueshiftEngine
Source/Runtime/Private/Math/Line.cpp
// Copyright(c) 2017 POLYGONTEK // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http ://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "Precompiled.h" #include "Math/Math.h" BE_NAMESPACE_BEGIN Line::Line(const LineSegment &lineSegment) { pos = lineSegment.a; dir = lineSegment.Dir(); } Line::Line(const Ray &ray) { pos = ray.origin; dir = ray.dir; } Line Line::Translate(const Vec3 &translation) const { return Line(pos + translation, dir); } Line &Line::TranslateSelf(const Vec3 &translation) { pos += translation; return *this; } void Line::Transform(const Mat3 &transform) { pos = transform * pos; dir = transform * dir; } void Line::Transform(const Mat3x4 &transform) { pos = transform.Transform(pos); dir = transform.TransformNormal(dir); } void Line::Transform(const Mat4 &transform) { pos = transform * pos; dir = transform.TransformNormal(dir); } void Line::Transform(const Quat &transform) { pos = transform * pos; dir = transform * dir; } Vec3 Line::ClosestPoint(const Vec3 &point) const { float d = dir.Dot(point - pos); return GetPoint(d); } float Line::Distance(const Vec3 &point) const { Vec3 closestPoint = ClosestPoint(point); return closestPoint.Distance(point); } float Line::DistanceSqr(const Vec3 &point) const { Vec3 closestPoint = ClosestPoint(point); return closestPoint.DistanceSqr(point); } LineSegment Line::ToLineSegment(float d) const { return LineSegment(pos, GetPoint(d)); } LineSegment Line::ToLineSegment(float dStart, float dEnd) const { return LineSegment(GetPoint(dStart), GetPoint(dEnd)); } Ray Line::ToRay() const { return Ray(pos, dir); } Line Line::FromString(const char *str) { Line line; sscanf(str, "%f %f %f %f %f %f", &line.pos.x, &line.pos.y, &line.pos.z, &line.dir.x, &line.dir.y, &line.dir.z); return line; } BE_NAMESPACE_END
kazikikaziki/Kamilo
Kamilo/KEdgeFile.cpp
#include "KEdgeFile.h" #include "KChunkedFile.h" #include "KZlib.h" #include "KInternal.h" namespace Kamilo { #define EDGE2_STRING_ENCODING "JPN" // Edge2 は日本語環境で使う事を前提とする static int _Min(int a, int b) { return (a < b) ? a : b; } static KImage _MakeImage(int width, int height, int bitdepth) { if (bitdepth == 32) { return KImage::createFromPixels(width, height, KColorFormat_RGBA32, NULL); } if (bitdepth == 24) { return KImage::createFromPixels(width, height, KColorFormat_RGB24, NULL); } if (bitdepth == 8) { return KImage::createFromPixels(width, height, KColorFormat_INDEX8, NULL); } K__ASSERT(0); return KImage(); } #pragma region KEdgePalette KEdgePalette::KEdgePalette() { m_data_b = 0; m_data_c = 0; m_data_d = 0; m_data_e = 0; m_bgr_colors.resize(256 * 3); m_data_f.resize(256); m_data_g.resize(256); m_data_h.resize(256*6); m_data_i.resize(256); m_data_j.resize(0); m_data_k = 0; m_data_l = 0; m_data_m = 0; } KEdgePalette::KEdgePalette(const KEdgePalette *copy) { *this = *copy; } #pragma endregion // KEdgePalette #pragma region KEdgeLayer KEdgeLayer::KEdgeLayer() { m_delay = 10; m_label_u8.clear(); m_label_color_rgbx[0] = 255; m_label_color_rgbx[1] = 255; m_label_color_rgbx[2] = 255; m_label_color_rgbx[3] = 0; m_is_grouped = false; m_is_visibled = true; m_data_a = 4; m_data_b = 1; m_data_c = 0; m_data_d = 0; m_data_e.clear(); m_data_f = 1; m_data_g = 2; m_data_h = 1; } /// レイヤーをコピーする /// @param source コピー元レイヤー /// @param sharePixels ピクセルバッファの参照を共有する KEdgeLayer::KEdgeLayer(const KEdgeLayer *source, bool sharePixels) { m_delay = source->m_delay; m_label_u8 = source->m_label_u8; memcpy(m_label_color_rgbx, source->m_label_color_rgbx, 4); m_is_grouped = source->m_is_grouped; m_is_visibled = source->m_is_visibled; m_data_a = source->m_data_a; m_data_b = source->m_data_b; m_data_c = source->m_data_c; m_data_d = source->m_data_d; m_data_e.assign(source->m_data_e.begin(), source->m_data_e.end()); m_data_f = source->m_data_f; m_data_g = source->m_data_g; m_data_h = source->m_data_h; if (sharePixels) { // 参照コピー m_image_rgb24 = source->m_image_rgb24; } else { // 実体コピー m_image_rgb24 = source->m_image_rgb24.clone(); } } KEdgeLayer::~KEdgeLayer() { } #pragma endregion // KEdgeLayer #pragma region KEdgePage KEdgePage::KEdgePage() { m_width = 256; m_height = 256; m_delay = 10; m_is_grouped = false; m_label_u8.clear(); m_layers.clear(); m_label_color_rgbx[0] = 255; m_label_color_rgbx[1] = 255; m_label_color_rgbx[2] = 255; m_label_color_rgbx[3] = 0; m_data_a = 0; m_data_b = 1; m_data_c = 0; m_data_d = (uint32_t)(-1); m_data_e = (uint32_t)(-1); m_data_f = 0; m_data_g = 0; m_data_h = 0; m_data_i = 1; m_data_j = 2; m_data_k = 1; m_ani_xparam.dest = 0; m_ani_xparam.is_relative = 0; m_ani_yparam.dest = 0; m_ani_yparam.is_relative = 0; } KEdgePage::KEdgePage(const KEdgePage *source, bool copy_layers) { m_delay = source->m_delay; m_label_u8 = source->m_label_u8; m_is_grouped = source->m_is_grouped; memcpy(m_label_color_rgbx, source->m_label_color_rgbx, 4); m_width = source->m_width; m_height = source->m_height; m_data_a = source->m_data_a; m_data_b = source->m_data_b; m_data_c = source->m_data_c; m_data_d = source->m_data_d; m_data_e = source->m_data_e; m_data_f = source->m_data_f; m_data_g = source->m_data_g; m_data_h = source->m_data_h; m_data_i = source->m_data_i; m_data_j = source->m_data_j; m_data_k = source->m_data_k; m_ani_xparam = source->m_ani_xparam; m_ani_yparam = source->m_ani_yparam; if (copy_layers) { int numlayers = source->getLayerCount(); for (int i=0; i<numlayers; i++) { const KEdgeLayer *src_layer = source->getLayer(i); addCopyLayer(src_layer, true); } } } KEdgePage::~KEdgePage() { for (auto it=m_layers.begin(); it!=m_layers.end(); it++) { KEdgeLayer *layer = *it; delete layer; } } KEdgeLayer * KEdgePage::addLayer() { KEdgeLayer *layer = new KEdgeLayer(); m_layers.push_back(layer); return layer; } KEdgeLayer * KEdgePage::addCopyLayer(const KEdgeLayer *source, bool share_pixels) { KEdgeLayer *layer = new KEdgeLayer(source, share_pixels); m_layers.push_back(layer); return layer; } KEdgeLayer * KEdgePage::addLayerAt(int index) { KEdgeLayer *layer = new KEdgeLayer(); if (index < 0) { m_layers.insert(m_layers.begin(), layer); } else if (index < (int)m_layers.size()) { m_layers.insert(m_layers.begin() + index, layer); } else { m_layers.push_back(layer); } return layer; } void KEdgePage::delLayer(int index) { if (index < 0) return; if (index >= (int)m_layers.size()) return; delete m_layers[index]; m_layers.erase(m_layers.begin() + index); } KEdgeLayer * KEdgePage::getLayer(int index) { if (index < 0) return NULL; if (index >= (int)m_layers.size()) return NULL; return m_layers[index]; } const KEdgeLayer * KEdgePage::getLayer(int index) const { if (index < 0) return NULL; if (index >= (int)m_layers.size()) return NULL; return m_layers[index]; } int KEdgePage::getLayerCount() const { return (int)m_layers.size(); } #pragma endregion // KEdgePage #pragma region KEdgeDocument KEdgeDocument::KEdgeDocument() { clear(); } KEdgeDocument::KEdgeDocument(const KEdgeDocument *source, bool copy_pages) { bool copy_palettes = true; K__ASSERT(source); m_compression_flag = source->m_compression_flag; m_bit_depth = source->m_bit_depth; { m_fg_palette.color_index = source->m_fg_palette.color_index; m_fg_palette.data_a = source->m_fg_palette.data_a; m_fg_palette.data_c = source->m_fg_palette.data_c; memcpy(m_fg_palette.bgr_colors, source->m_fg_palette.bgr_colors, 3); memcpy(m_fg_palette.data_b, source->m_fg_palette.data_b, 6); m_bg_palette.color_index = source->m_bg_palette.color_index; m_bg_palette.data_a = source->m_bg_palette.data_a; m_bg_palette.data_c = source->m_bg_palette.data_c; memcpy(m_bg_palette.bgr_colors, source->m_bg_palette.bgr_colors, 3); memcpy(m_bg_palette.data_b, source->m_bg_palette.data_b, 6); } m_data_d = source->m_data_d; m_data_d2 = source->m_data_d2; m_data_d3.assign(source->m_data_d3.begin(), source->m_data_d3.end()); m_data_e.assign(source->m_data_e.begin(), source->m_data_e.end()); m_data_a = source->m_data_a; m_data_b = source->m_data_b; m_data_c = source->m_data_c; m_data_f = source->m_data_f; m_data_g = source->m_data_g; m_data_h = source->m_data_h; m_data_i = source->m_data_i; m_data_j = source->m_data_j; m_data_k = source->m_data_k; if (copy_pages) { int numpages = source->getPageCount(); for (int i=0; i<numpages; i++) { const KEdgePage *src = source->getPage(i); addCopyPage(src); } } if (copy_palettes) { K__ASSERT(m_palettes.empty()); for (size_t i=0; i<source->m_palettes.size(); i++) { KEdgePalette *p = source->m_palettes[i]; m_palettes.push_back(new KEdgePalette(p)); } } } KEdgeDocument::~KEdgeDocument() { clear(); } void KEdgeDocument::clear() { for (auto it=m_palettes.begin(); it!=m_palettes.end(); ++it) { delete (*it); } for (auto it=m_pages.begin(); it!=m_pages.end(); ++it) { delete (*it); } m_pages.clear(); m_palettes.clear(); m_compression_flag = 256; m_bit_depth = 24; m_fg_palette.color_index = 0; m_bg_palette.color_index = 0; memset(&m_fg_palette, 0, sizeof(m_fg_palette)); memset(&m_bg_palette, 0, sizeof(m_bg_palette)); m_fg_palette.data_a = 255; m_fg_palette.data_c = 0; m_bg_palette.data_a = 255; m_bg_palette.data_c = 0; m_data_a = 0; m_data_b = 0; m_data_c = 0; m_data_d = 1; m_data_d2 = 1; m_data_d3.clear(); m_data_e.clear(); m_data_f = 0; m_data_g = 0; m_data_h = 0; m_data_i = 256; m_data_j = 1; m_data_k = 0; } bool KEdgeDocument::loadFromStream(KInputStream &file) { if (!file.isOpen()) return false; KEdgeRawReader reader; if (reader.read(this, file) != 0) { clear(); return false; } return true; } bool KEdgeDocument::loadFromFileName(const std::string &filename) { bool success = false; KInputStream file; if (file.openFileName(filename)) { success = loadFromStream(file); } return success; } void KEdgeDocument::saveToStream(KOutputStream &file) { KEdgeRawWriter writer; writer.write(this, file); } void KEdgeDocument::saveToFileName(const std::string &filename) { KOutputStream file; if (file.openFileName(filename)) { saveToStream(file); } } // Make document for Edge2 Application ( http://takabosoft.com/edge2 ) // All pages need to have least 1 layer. void KEdgeDocument::autoComplete() { if (m_bit_depth == 0) { m_bit_depth = 0; } // Edge needs least one palette if (m_palettes.empty()) { m_palettes.push_back(new KEdgePalette()); } // Edge needs least one page if (m_pages.empty()) { m_pages.push_back(new KEdgePage()); } for (size_t p=0; p<m_pages.size(); p++) { KEdgePage *page = m_pages[p]; if (page->m_width==0 || page->m_height==0) { int DEFAULT_SIZE = 8; page->m_width = (uint16_t)DEFAULT_SIZE; page->m_height = (uint16_t)DEFAULT_SIZE; } // Page needs least one layer if (page->m_layers.empty()) { KEdgeLayer *layer = new KEdgeLayer(); page->m_layers.push_back(layer); } // Make empty image if not exists for (size_t l=0; l<page->m_layers.size(); l++) { KEdgeLayer *layer = page->m_layers[l]; if (layer->m_image_rgb24.empty()) { layer->m_image_rgb24 = _MakeImage(page->m_width, page->m_height, m_bit_depth); } } } } KEdgePage * KEdgeDocument::addPage() { KEdgePage *page = new KEdgePage(); m_pages.push_back(page); return page; } KEdgePage * KEdgeDocument::addCopyPage(const KEdgePage *source) { KEdgePage *page = new KEdgePage(source, true); m_pages.push_back(page); return page; } KEdgePage * KEdgeDocument::addPageAt(int index) { KEdgePage *page = new KEdgePage(); if (index < 0) { m_pages.insert(m_pages.begin(), page); } else if (index < (int)m_pages.size()) { m_pages.insert(m_pages.begin() + index, page); } else { m_pages.push_back(page); } return page; } void KEdgeDocument::delPage(int index) { if (index < 0) return; if (index >= (int)m_pages.size()) return; delete m_pages[index]; m_pages.erase(m_pages.begin() + index); } int KEdgeDocument::getPageCount() const { return (int)m_pages.size(); } KEdgePage * KEdgeDocument::getPage(int index) { if (index < 0) return NULL; if (index >= (int)m_pages.size()) return NULL; return m_pages[index]; } const KEdgePage * KEdgeDocument::getPage(int index) const { if (index < 0) return NULL; if (index >= (int)m_pages.size()) return NULL; return m_pages[index]; } uint8_t * KEdgeDocument::getPalettePointer(int index) { if (0 <= index && index < (int)m_palettes.size()) { return (uint8_t *)&m_palettes[index]->m_bgr_colors[0]; } return NULL; } int KEdgeDocument::getPaletteCount() const { return (int)m_palettes.size(); } KEdgePalette * KEdgeDocument::getPalette(int index) { return m_palettes[index]; } const KEdgePalette * KEdgeDocument::getPalette(int index) const { return m_palettes[index]; } std::string KEdgeDocument::expotyXml() const { std::string xml_u8; char tmp[1024] = {0}; int numPages = getPageCount(); sprintf_s(tmp, sizeof(tmp), "<Edge pages='%d'>\n", numPages); xml_u8 += tmp; for (int p=0; p<numPages; p++) { const KEdgePage *page = getPage(p); int numLayers = page->getLayerCount(); sprintf_s(tmp, sizeof(tmp), " <Page label='%s' labelColor='#%02x%02x%02x' delay='%d' w='%d' h='%d' layers='%d'>\n", page->m_label_u8.c_str(), page->m_label_color_rgbx[0], page->m_label_color_rgbx[1], page->m_label_color_rgbx[2], page->m_delay, page->m_width, page->m_height, numLayers); xml_u8 += tmp; for (int l=0; l<numLayers; l++) { const KEdgeLayer *layer = page->getLayer(l); sprintf_s(tmp, sizeof(tmp), " <Layer label='%s' labelColor='#%02x%02x%02x' delay='%d'/>\n", layer->m_label_u8.c_str(), layer->m_label_color_rgbx[0], layer->m_label_color_rgbx[1], layer->m_label_color_rgbx[2], layer->m_delay); xml_u8 += tmp; } xml_u8 += " </Page>\n"; } int numPal = getPaletteCount(); sprintf_s(tmp, sizeof(tmp), " <Palettes count='%d'>\n", numPal); xml_u8 += tmp; for (int i=0; i<numPal; i++) { const KEdgePalette *pal = getPalette(i); sprintf_s(tmp, sizeof(tmp), " <Pal label='%s'/>\n", pal->m_name_u8.c_str()); xml_u8 += tmp; } xml_u8 += " </Palettes>\n"; xml_u8 += "</Edge>\n"; return xml_u8; } /// パレットを画像化したものを作成する /// 横幅は 16 ドット、高さは 16 * パレット数になる /// EDGE 背景色に該当するピクセルのみアルファ値が 0 になるが、それ以外のピクセルのアルファは必ず 255 になる KImage KEdgeDocument::exportPaletteImage() const { if (m_palettes.empty()) return KImage(); KImage pal = KImage::createFromSize(K_PALETTE_IMAGE_SIZE, K_PALETTE_IMAGE_SIZE * m_palettes.size()); uint8_t *dest = pal.lockData(); for (size_t p=0; p<m_palettes.size(); p++) { const auto &bgr = m_palettes[p]->m_bgr_colors; for (int i=0; i<256; i++) { uint8_t b = bgr[i*3+0]; uint8_t g = bgr[i*3+1]; uint8_t r = bgr[i*3+2]; uint8_t a = (m_bg_palette.color_index == i) ? 0 : 255; dest[(256 * p + i) * 4 + 0] = r; dest[(256 * p + i) * 4 + 1] = g; dest[(256 * p + i) * 4 + 2] = b; dest[(256 * p + i) * 4 + 3] = a; } } pal.unlockData(); return pal; } /// Edge レイヤーの画像を、パレット番号が取得可能な形式で書き出す。 /// RGBそれぞれにパレット番号を、A には常に255をセットするため、パレット変換しないで表示した場合は奇妙なグレースケール画像に見える /// 書き出し時のフォーマットは RGBA32 ビットになる /// 元画像がパレットでない場合は NULL を返す KImage KEdgeDocument::exportSurfaceRaw(int pageindex, int layerindex, int transparent_index) const { KImage output; const KEdgePage *page = getPage(pageindex); if (page) { const KEdgeLayer *layer = page->getLayer(layerindex); if (layer && m_bit_depth == 8) { int w = page->m_width; int h = page->m_height; const uint8_t *p_src = layer->m_image_rgb24.getData(); output = KImage::createFromSize(w, h); uint8_t *p_dst = output.lockData(); for (int y=0; y<h; y++) { for (int x=0; x<w; x++) { uint8_t i = p_src[y * w + x]; p_dst[(y * w + x) * 4 + 0] = i; // パレットインデックスをそのままRGB値として書き込む p_dst[(y * w + x) * 4 + 1] = i; p_dst[(y * w + x) * 4 + 2] = i; p_dst[(y * w + x) * 4 + 3] = (transparent_index == i) ? 0 : 255; } } output.unlockData(); } } return output; } static KImage kk_ImageFromRGB24(int w, int h, const uint8_t *pixels, const uint8_t *transparent_color_BGR) { if (w <= 0 || h <= 0 || pixels == NULL) { K__ERROR("invalid argument"); return KImage(); } KEdgeBin buf(w * h * 4, '\0'); uint8_t *buf_p = (uint8_t*)&buf[0]; const uint8_t *t = transparent_color_BGR; const int srcPitch = w * 3; const int dstPitch = w * 4; for (int y=0; y<h; y++) { for (int x=0; x<w; x++) { const uint8_t r = pixels[srcPitch*y + x*3 + 2]; // r const uint8_t g = pixels[srcPitch*y + x*3 + 1]; // g const uint8_t b = pixels[srcPitch*y + x*3 + 0]; // b const uint8_t a = (t && b==t[0] && g==t[1] && r==t[2]) ? 0 : 255; buf_p[dstPitch*y + x*4 + 0] = r; buf_p[dstPitch*y + x*4 + 1] = g; buf_p[dstPitch*y + x*4 + 2] = b; buf_p[dstPitch*y + x*4 + 3] = a; } } return KImage::createFromPixels(w, h, KColorFormat_RGBA32, buf_p); } static KImage kk_ImageFromIndexed(int w, int h, const uint8_t *indexed_format_pixels, const uint8_t *palette_colors_BGR, int transparent_color_index) { if (w <= 0 || h <= 0) { K__ERROR("invalid argument"); return KImage(); } K__ASSERT(indexed_format_pixels); K__ASSERT(palette_colors_BGR); const int dstPitch = w * 4; KEdgeBin buf(w * h * 4, '\0'); uint8_t *buf_p = (uint8_t*)&buf[0]; for (int y=0; y<h; y++) { for (int x=0; x<w; x++) { const uint8_t idx = indexed_format_pixels[w * y + x]; if (idx == transparent_color_index) { buf_p[dstPitch*y + x*4 + 0] = 0; // r buf_p[dstPitch*y + x*4 + 1] = 0; // g buf_p[dstPitch*y + x*4 + 2] = 0; // b buf_p[dstPitch*y + x*4 + 3] = 0; // a } else { buf_p[dstPitch*y + x*4 + 0] = palette_colors_BGR[idx * 3 + 2]; // r buf_p[dstPitch*y + x*4 + 1] = palette_colors_BGR[idx * 3 + 1]; // g buf_p[dstPitch*y + x*4 + 2] = palette_colors_BGR[idx * 3 + 0]; // b buf_p[dstPitch*y + x*4 + 3] = 255; // a } } } return KImage::createFromPixels(w, h, KColorFormat_RGBA32, buf_p); } /// Edge レイヤーの画像を KImage に書き出す /// 書き出し時のフォーマットは常に RGBA32 ビットになる(Edgeの背景色を透過色にする) /// 失敗した場合は NULL を返す KImage KEdgeDocument::exportSurface(int pageindex, int layerindex, int paletteindex) const { KImage output; const KEdgePage *page = getPage(pageindex); if (page) { const KEdgeLayer *layer = page->getLayer(layerindex); if (layer) { // Make surface const uint8_t *p_src = layer->m_image_rgb24.getData(); int w = page->m_width; int h = page->m_height; if (m_bit_depth == 24) { output = kk_ImageFromRGB24(w, h, p_src, m_bg_palette.bgr_colors); } else if (m_bit_depth == 8) { const uint8_t *colors = (uint8_t *)&m_palettes[paletteindex]->m_bgr_colors[0]; output = kk_ImageFromIndexed(w, h, p_src, colors, m_bg_palette.color_index); } } } return output; } /// 4枚の元画像とチャンネルを指定し、抽出した4つのチャンネル画像を合成して一枚の画像にする。 /// @arg src_surface_r 画像の src_channel_r チャンネル画像を、Rチャンネルとして使う。 /// @arg src_surface_g 画像の src_channel_g チャンネル画像を、Gチャンネルとして使う。 /// @arg src_surface_b 画像の src_channel_b チャンネル画像を、Bチャンネルとして使う。 /// @arg src_surface_a 画像の src_channel_a チャンネル画像を、Aチャンネルとして使う。 /// /// @param src_r Rチャンネルとして使う元画像 /// @param src_g Gチャンネルとして使う元画像 /// @param src_b Bチャンネルとして使う元画像 /// @param src_a Aチャンネルとして使う元画像 /// @param off_r src_r から色を取り出す時の各ピクセル先頭からのオフセットバイト数。1ピクセルが4バイトで構成されているとき、0 から 3 までの値を指定できる /// @param off_g (略) /// @param off_b (略) /// @param off_a (略) static KImage kk_ImageFromChannels(const KImage *src_r, const KImage *src_g, const KImage *src_b, const KImage *src_a, int off_r, int off_g, int off_b, int off_a) { K__ASSERT(src_r); K__ASSERT(src_g); K__ASSERT(src_b); K__ASSERT(src_a); if(off_r < 0 || 4 <= off_r) { K__ERROR("Invalid offset bytes for R channel"); return KImage(); } if(off_g < 0 || 4 <= off_g) { K__ERROR("Invalid offset bytes for G channel"); return KImage(); } if(off_b < 0 || 4 <= off_b) { K__ERROR("Invalid offset bytes for B channel"); return KImage(); } if(off_a < 0 || 4 <= off_a) { K__ERROR("Invalid offset bytes for A channel"); return KImage(); } // すべてのサーフェスでサイズが一致することを確認 const int w = src_r->getWidth(); const int h = src_r->getHeight(); if (w <= 0 || h <= 0) { K__ERROR("Invalid image size"); return KImage(); } const bool size_r_ok = (src_r->getWidth()==w && src_r->getHeight()==h); const bool size_g_ok = (src_g->getWidth()==w && src_g->getHeight()==h); const bool size_b_ok = (src_b->getWidth()==w && src_b->getHeight()==h); const bool size_a_ok = (src_a->getWidth()==w && src_a->getHeight()==h); if (!size_r_ok || !size_g_ok || !size_b_ok || !size_a_ok) { K__ERROR("Source images have different sizes"); return KImage(); } // 準備 KImage out = KImage::createFromPixels(w, h, KColorFormat_RGBA32, NULL); // RGBAそれぞれのチャンネルを合成する const uint8_t *src_p_r = src_r->getData(); const uint8_t *src_p_g = src_g->getData(); const uint8_t *src_p_b = src_b->getData(); const uint8_t *src_p_a = src_a->getData(); uint8_t *dstP = out.lockData(); K__ASSERT(dstP); for (int y=0; y<h; y++) { for (int x=0; x<w; x++) { const int i = (w * y + x) * 4; dstP[i + 0] = src_p_r[i + off_r]; dstP[i + 1] = src_p_g[i + off_g]; dstP[i + 2] = src_p_b[i + off_b]; dstP[i + 3] = src_p_a[i + off_a]; } } out.unlockData(); return out; } /// Edge レイヤーの画像をアルファチャンネルつきで KImage に書き出す /// 書き出し時のフォーマットは常に RGBA32 ビットで、アルファ値の入力にはアルファマスクレイヤーを指定する /// マスクレイヤーはアルファ値をグレースケールで記録したもので、変換元のレイヤーと同じページ内にある /// マスクレイヤーのインデックスに -1 が指定されている場合は、Edgeの背景色を透過させる /// 失敗した場合は NULL を返す KImage KEdgeDocument::exportSurfaceWithAlpha(int pageindex, int layerindex, int maskindex, int paletteindex) const { if (maskindex < 0) { // アルファマスクが省略されている return exportSurface(pageindex, layerindex, paletteindex); } else { KImage rgb = exportSurface(pageindex, layerindex, paletteindex); KImage mask = exportSurface(pageindex, maskindex, 0); KImage output = kk_ImageFromChannels(&rgb, &rgb, &rgb, &mask, 0, 1, 2, 0); return output; } } /// 指定された色に最も近いカラーインデックスを返す /// 検索できない場合は defaultindex を返す int KEdgeDocument::findColorIndex(int paletteindex, uint8_t r, uint8_t g, uint8_t b, int defaultindex) const { if (paletteindex < 0 || (int)m_palettes.size() <= paletteindex) return defaultindex; int result = defaultindex; int min_diff = 255; const KEdgePalette *pal = m_palettes[paletteindex]; for (int i=0; i<256; i++) { int pal_b = (int)pal->m_bgr_colors[i*3 + 0]; int pal_g = (int)pal->m_bgr_colors[i*3 + 1]; int pal_r = (int)pal->m_bgr_colors[i*3 + 2]; int diff = abs(pal_r - r) + abs(pal_g - g) + abs(pal_b - b); if (diff < min_diff) { min_diff = diff; result = i; } } return result; } /// KImage で指定された画像を Edge レイヤーに書き出す /// 書き込み先の Edge レイヤーにパレットが設定されている場合は、適当に減色してパレットに対応させる /// 書き込みに成功すれば true を返す bool KEdgeDocument::writeImageToLayer(int pageindex, int layerindex, int paletteindex, const KImage *image) { if (image == NULL) { K__ERROR("E_INVALID_ARGUMENT"); return false; } if (image->getBytesPerPixel() != 3) { K__ERROR("E_EDGE_INVALID_BYTES_PER_PIXEL: %d", image->getBytesPerPixel()); return false; } KEdgePage *page = getPage(pageindex); if (page == NULL) { K__ERROR("E_EDGE_INVALID_PAGE_INDEX: PAGE=%d/%d", pageindex, getPageCount()); return false; } KEdgeLayer *layer = page->getLayer(layerindex); if (layer == NULL) { K__ERROR("E_EDGE_INVALID_LAYER_INDEX: PAGE=%d, LAYER=%d/%d", pageindex, layerindex, page->getLayerCount()); return false; } // コピー範囲を決定 const int w = _Min((int)page->m_width, image->getWidth()); const int h = _Min((int)page->m_height, image->getHeight()); if (m_bit_depth == 24) { // RGB24ビットカラー // コピー先のバッファ uint8_t *dst_p = layer->m_image_rgb24.lockData(); // RGB値を直接コピーする。アルファチャンネルは無視する const uint8_t *src_p = image->getData(); int src_data_size = image->getDataSize(); const int dst_pitch = page->m_width * 3; const int src_pitch = image->getPitch(); memset(dst_p, 0, src_data_size); // アラインメントによる余白も含めてクリア for (int y=0; y<h; y++) { for (int x=0; x<w; x++) { const uint8_t r = src_p[src_pitch*y + x*3 + 0]; const uint8_t g = src_p[src_pitch*y + x*3 + 1]; const uint8_t b = src_p[src_pitch*y + x*3 + 2]; // EdgeにはBGRの順番で保存する dst_p[dst_pitch*y + x*3 + 0] = b; dst_p[dst_pitch*y + x*3 + 1] = g; dst_p[dst_pitch*y + x*3 + 2] = r; } } layer->m_image_rgb24.unlockData(); return true; } if (m_bit_depth == 8) { // インデックスカラー // コピー先のバッファ uint8_t *dst_p = layer->m_image_rgb24.lockData(); // パレットを考慮してコピーする const uint8_t *src_p = image->getData(); int src_data_size = image->getDataSize(); const int dst_pitch = page->m_width; const int src_pitch = image->getPitch(); memset(dst_p, 0, src_data_size); // アラインメントによる余白も含めてクリア for (int y=0; y<h; y++) { for (int x=0; x<w; x++) { const uint8_t r = src_p[src_pitch*y + 3*x + 0]; const uint8_t g = src_p[src_pitch*y + 3*x + 1]; const uint8_t b = src_p[src_pitch*y + 3*x + 2]; dst_p[dst_pitch*y + x] = (uint8_t)findColorIndex(paletteindex, r, g, b, 0); } } layer->m_image_rgb24.unlockData(); return true; } K__ERROR("E_EDGE_INVALID_BIT_DEPTH: DEPTH=%d, PAGE=%d, LAYER=%d", m_bit_depth, pageindex, layerindex); return false; } #pragma endregion // KEdgeDocument #pragma region KEdgePalFile KEdgePalFile::KEdgePalFile() { memset(m_bgr, 0, sizeof(m_bgr)); memset(m_data, 0, sizeof(m_data)); } KImage KEdgePalFile::exportImage(bool index0_for_transparent) const { KImage img = KImage::createFromSize(16, 16); uint8_t *dst = img.lockData(); for (int i=0; i<256; i++) { dst[i*4 + 0] = m_bgr[i*3+2]; // r dst[i*4 + 1] = m_bgr[i*3+1]; // g dst[i*4 + 2] = m_bgr[i*3+0]; // b dst[i*4 + 3] = 255; // a } if (index0_for_transparent) { dst[0*4 + 3] = 0; // a } img.unlockData(); return img; } #pragma endregion // KEdgePalFile #pragma region KEdgePalReader bool KEdgePalReader::loadFromFileName(const std::string &filename) { bool ok = false; KInputStream file; if (file.openFileName(filename)) { ok = loadFromStream(file); } return ok; } bool KEdgePalReader::loadFromMemory(const void *data, size_t size) { bool ok = false; KInputStream file; if (file.openMemory(data, size)) { ok = loadFromStream(file); } return ok; } bool KEdgePalReader::loadFromStream(KInputStream &file) { if (!file.isOpen()) { return false; } // 識別子 { char sign[12]; file.read(sign, sizeof(sign)); if (strcmp(sign, "EDGE2 PAL") != 0) { return false; // sign not matched } } // 展開後のデータサイズ uint32_t uzsize = file.readUint32(); K__ASSERT(uzsize > 0); // 圧縮データ int zsize = file.size() - file.tell(); KEdgeBin zbin = file.readBin(zsize); K__ASSERT(zsize > 0); K__ASSERT(! zbin.empty()); // 展開 KEdgeBin bin = KZlib::uncompress_zlib(zbin.data(), zsize, uzsize); K__ASSERT(! bin.empty()); K__ASSERT(bin.size() == uzsize); KChunkedFileReader::init(bin.data(), bin.size()); uint16_t a; readChunk(0x03e8, 2, &a); // パレットをすべて読みだす while (!eof()) { KEdgePalFile pal; std::string name_mb; readChunk(0x03e9, &name_mb); pal.m_name_u8 = K::strAnsiToUtf8(name_mb, EDGE2_STRING_ENCODING); readChunk(0x03ea, 256*3, pal.m_bgr); readChunk(0x03eb, 256, pal.m_data); m_items.push_back(pal); } return true; } std::string KEdgePalReader::exportXml() { // UTF8 char tmp[1024] = {0}; std::string xml_u8 = "<PalFile>\n"; for (size_t i=0; i<m_items.size(); i++) { sprintf_s(tmp, sizeof(tmp), " <Pal label='%s'/><!-- %d -->\n", m_items[i].m_name_u8.c_str(), i); xml_u8 += tmp; } xml_u8 += "</PalFile>\n"; return xml_u8; } #pragma endregion // KEdgePalReader #pragma region KEdgeRawReader KEdgeRawReader::KEdgeRawReader() { } // Edge2 バイナリファイルからデータを読み取る int KEdgeRawReader::read(KEdgeDocument *e, KInputStream &file) { if (e == NULL) return 0; if (!file.isOpen()) return 0; uint16_t zflag; KEdgeBin uzbin = unzip(file, &zflag); if (uzbin.empty()) return -1; // EDGE を得る readFromUncompressedBuffer(e, uzbin.data(), uzbin.size()); e->m_compression_flag = zflag; return 0; } KEdgeBin KEdgeRawReader::unzip(KInputStream &file, uint16_t *zflag) { K__VERIFY(zflag); // 識別子 { char sign[6]; file.read(sign, sizeof(sign)); if (strcmp(sign, "EDGE2") != 0) { return KEdgeBin(); // signature doest not matched } } // 圧縮フラグ file.read(zflag, 2); // 展開後のデータサイズ uint32_t uzsize; file.read(&uzsize, 4); K__ASSERT(uzsize > 0); // 圧縮データ int zsize = file.size() - file.tell(); KEdgeBin zbin = file.readBin(zsize); K__ASSERT(zsize > 0); K__ASSERT(! zbin.empty()); // 展開 KEdgeBin uzbin = KZlib::uncompress_zlib(zbin, uzsize); K__ASSERT(! uzbin.empty()); K__ASSERT(uzbin.size() == uzsize); return uzbin; } void KEdgeRawReader::scanLayer(KEdgeDocument *e, KEdgePage *page, KEdgeLayer *layer) { std::string label_mb; readChunk(0x03e8, &label_mb); layer->m_label_u8 = K::strAnsiToUtf8(label_mb, EDGE2_STRING_ENCODING); readChunk(0x03e9, 4, &layer->m_data_a); readChunk(0x03ea, 1, &layer->m_is_grouped); readChunk(0x03eb, 1, &layer->m_data_b); readChunk(0x03ec, 1, &layer->m_data_c); readChunk(0x03ed, 1, &layer->m_is_visibled); { layer->m_image_rgb24 = _MakeImage(page->m_width, page->m_height, e->m_bit_depth); uint8_t *p = layer->m_image_rgb24.lockData(); K__ASSERT(p); uint32_t len = page->m_width * page->m_height * e->m_bit_depth / 8; readChunk(0x03ee, len, p); // 8bit palette or 24bit BGR layer->m_image_rgb24.unlockData(); } readChunk(0x03ef, 1, &layer->m_data_d); readChunk(0x03f0, 0, &layer->m_data_e); // 子チャンクを含む readChunk(0x03f1, 4, layer->m_label_color_rgbx); { uint32_t raw_delay = 0; readChunk(0x07d0, 4, &raw_delay); layer->m_delay = raw_delay / 100; } readChunk(0x07d1, 1, &layer->m_data_f); readChunk(0x07d2, 1, &layer->m_data_g); readChunk(0x07d3, 1, &layer->m_data_h); } void KEdgeRawReader::scanPage(KEdgeDocument *e, KEdgePage *page) { uint16_t numlayers; std::string label_mb; readChunk(0x03e8, &label_mb); page->m_label_u8 = K::strAnsiToUtf8(label_mb, EDGE2_STRING_ENCODING); readChunk(0x03e9, 4, &page->m_data_a); readChunk(0x03ea, 1, &page->m_is_grouped); readChunk(0x03eb, 1, &page->m_data_b); readChunk(0x03ec, 1, &page->m_data_c); readChunk(0x03ed, 2, &page->m_width); readChunk(0x03ee, 2, &page->m_height); readChunk(0x03ef, 4, &page->m_data_d); readChunk(0x03f0, 4, &page->m_data_e); readChunk(0x03f1, 4, page->m_label_color_rgbx); readChunk(0x07d0, 1, &page->m_data_f); readChunk(0x07d1, 4, &page->m_data_g); readChunk(0x07d2, 2, &numlayers); // レイヤ for (uint16_t i=0; i<numlayers; i++) { openChunk(0x07d3); KEdgeLayer *layer = new KEdgeLayer(); scanLayer(e, page, layer); page->m_layers.push_back(layer); closeChunk(); } readChunk(0x07d4, 4, &page->m_data_h); { uint32_t raw_delay = 0; readChunk(0x0bb8, 4, &raw_delay); page->m_delay = raw_delay / 100; } readChunk(0x0bb9, 1, &page->m_data_i); readChunk(0x0bba, 1, &page->m_data_j); readChunk(0x0bbb, 5, &page->m_ani_xparam); readChunk(0x0bbc, 5, &page->m_ani_yparam); readChunk(0x0bbd, 1, &page->m_data_k); } void KEdgeRawReader::scanEdge(KEdgeDocument *e) { e->m_pages.clear(); e->m_palettes.clear(); uint16_t numpages; readChunk(0x03e8, 1, &e->m_bit_depth); readChunk(0x03e9, 1, &e->m_data_a); readChunk(0x03ea, 1, &e->m_data_b); readChunk(0x03eb, 1, &e->m_data_c); openChunk(0x03ed); { readChunk(0x3e8, 1, &e->m_data_d); readChunk(0x3e9, 1, &e->m_data_d2); } closeChunk(); // Optional chunk if (checkChunkId(0x03ee)) { readChunk(0x03ee, 0, &e->m_data_d3); } if (checkChunkId(0x03ef)) { readChunk(0x03ef, 0, &e->m_data_d4); } readChunk(0x0fa1, 0, &e->m_data_e); readChunk(0x07d0, 2, &numpages); readChunk(0x07d1, 4, &e->m_data_f); readChunk(0x07d2, 1, &e->m_data_g); // Pages for (uint16_t i=0; i<numpages; ++i) { openChunk(0x07d3); KEdgePage *page = new KEdgePage(); scanPage(e, page); e->m_pages.push_back(page); closeChunk(); } uint16_t numpals; readChunk(0x07d4, 4, &e->m_data_h); readChunk(0x0bb8, 2, &numpals); readChunk(0x0bb9, 2, &e->m_data_i); readChunk(0x0bba, 4, &e->m_data_j); // パレット(3 * 256バイト * 任意の個数) for (uint16_t i=0; i<numpals; ++i) { openChunk(0x0bbb); KEdgePalette *pal = new KEdgePalette(); std::string name_mb; readChunk(0x03e8, 0, &name_mb); pal->m_name_u8 = K::strAnsiToUtf8(name_mb, EDGE2_STRING_ENCODING); readChunk(0x03e9, 4, &pal->m_data_b); readChunk(0x03ea, 1, &pal->m_data_c); readChunk(0x03eb, 1, &pal->m_data_d); readChunk(0x03ec, 1, &pal->m_data_e); readChunk(0x03ed, 256*3, &pal->m_bgr_colors); readChunk(0x03ef, 256, &pal->m_data_f); readChunk(0x03f0, 256, &pal->m_data_g); readChunk(0x03f1, 256*6, &pal->m_data_h); readChunk(0x03f2, 256, &pal->m_data_i); readChunk(0x03f3, 0, &pal->m_data_j); // 子チャンクを含む readChunk(0x07d0, 4, &pal->m_data_k); // Delay? readChunk(0x07d1, 1, &pal->m_data_l); readChunk(0x07d2, 1, &pal->m_data_m); e->m_palettes.push_back(pal); closeChunk(); } readChunk(0x0bbc, 4, &e->m_data_k); // 前景色 openChunk(0x0bbf); { readChunk(0x03e8, 1, &e->m_fg_palette.color_index); readChunk(0x03e9, 3, e->m_fg_palette.bgr_colors); readChunk(0x03ea, 1, &e->m_fg_palette.data_a); readChunk(0x03eb, 6, e->m_fg_palette.data_b); readChunk(0x03ec, 1, &e->m_fg_palette.data_c); } closeChunk(); // 背景色 openChunk(0x0bc0); { readChunk(0x03e8, 1, &e->m_bg_palette.color_index); readChunk(0x03e9, 3, e->m_bg_palette.bgr_colors); readChunk(0x03ea, 1, &e->m_bg_palette.data_a); readChunk(0x03eb, 6, e->m_bg_palette.data_b); readChunk(0x03ec, 1, &e->m_bg_palette.data_c); } closeChunk(); } // 非圧縮の Edge2 バイナリデータからデータを読み取る // @param buf バイナリ列(ZLibで展開後のデータであること) // @param len バイナリ列のバイト数 void KEdgeRawReader::readFromUncompressedBuffer(KEdgeDocument *e, const void *buf, size_t len) { init(buf, len); scanEdge(e); } #pragma endregion // KEdgeRawReader #pragma region KEdgeRawWriter KEdgeRawWriter::KEdgeRawWriter() { clear(); } void KEdgeRawWriter::write(KEdgeDocument *e, KOutputStream &file) { // 無圧縮 Edge バイナリを作成する writeUncompressedEdge(e); // データを圧縮し、Edge2 ツールで扱える形式にしたものを得る writeCompressedEdge(file); } void KEdgeRawWriter::writeLayer(KEdgePage *page, int layerindex, int bitdepth) { K__ASSERT(page); KEdgeLayer *layer = page->getLayer(layerindex); K__ASSERT(layer); std::string label_mb = K::strUtf8ToAnsi(layer->m_label_u8, EDGE2_STRING_ENCODING); writeChunkN(0x03e8, label_mb.c_str()); writeChunk4(0x03e9, layer->m_data_a); writeChunk1(0x03ea, layer->m_is_grouped); writeChunk1(0x03eb, layer->m_data_b); writeChunk1(0x03ec, layer->m_data_c); writeChunk1(0x03ed, layer->m_is_visibled?1:0); { // write RGB pixels uint32_t pixels_size = page->m_width * page->m_height * bitdepth/8; uint8_t * pixels_ptr = layer->m_image_rgb24.lockData(); if (pixels_ptr) { K__ASSERT(pixels_size == (uint32_t)layer->m_image_rgb24.getDataSize()); writeChunkN(0x03ee, pixels_size, pixels_ptr); layer->m_image_rgb24.unlockData(); } else { // 画像が Empty 状態になっている writeChunkN(0x03ee, pixels_size, NULL); } } writeChunk1(0x03ef, layer->m_data_d); writeChunkN(0x03f0, layer->m_data_e); writeChunkN(0x03f1, 4, layer->m_label_color_rgbx); writeChunk4(0x07d0, layer->m_delay * 100); // delay must be written x100 writeChunk1(0x07d1, layer->m_data_f); writeChunk1(0x07d2, layer->m_data_g); writeChunk1(0x07d3, layer->m_data_h); } void KEdgeRawWriter::writePage(KEdgeDocument *e, int pageindex) { K__ASSERT(e); KEdgePage *page = e->getPage(pageindex); K__ASSERT(page); K__ASSERT(page->m_width > 0); K__ASSERT(page->m_height > 0); std::string label_mb = K::strUtf8ToAnsi(page->m_label_u8, EDGE2_STRING_ENCODING); writeChunkN(0x03e8, label_mb.c_str()); writeChunk4(0x03e9, page->m_data_a); writeChunk1(0x03ea, page->m_is_grouped); writeChunk1(0x03eb, page->m_data_b); writeChunk1(0x03ec, page->m_data_c); writeChunk2(0x03ed, page->m_width); writeChunk2(0x03ee, page->m_height); writeChunk4(0x03ef, page->m_data_d); writeChunk4(0x03f0, page->m_data_e); writeChunkN(0x03f1, 4, page->m_label_color_rgbx); writeChunk1(0x07d0, page->m_data_f); writeChunk4(0x07d1, page->m_data_g); uint16_t numLayers = (uint16_t)page->getLayerCount(); writeChunk2(0x07d2, numLayers); // Layers K__ASSERT(numLayers > 0); for (uint16_t i=0; i<numLayers; i++) { openChunk(0x07d3); writeLayer(page, i, e->m_bit_depth); closeChunk(); } writeChunk4(0x07d4, page->m_data_h); writeChunk4(0x0bb8, page->m_delay * 100); // delay must be written x100 writeChunk1(0x0bb9, page->m_data_i); writeChunk1(0x0bba, page->m_data_j); writeChunkN(0x0bbb, 5, &page->m_ani_xparam); writeChunkN(0x0bbc, 5, &page->m_ani_yparam); writeChunk1(0x0bbd, page->m_data_k); } void KEdgeRawWriter::writeEdge(KEdgeDocument *e) { K__ASSERT(e); K__ASSERT(e->m_bit_depth==8 || e->m_bit_depth==24); writeChunk1(0x03e8, e->m_bit_depth); writeChunk1(0x03e9, e->m_data_a); writeChunk1(0x03ea, e->m_data_b); writeChunk1(0x03eb, e->m_data_c); openChunk(0x03ed); { writeChunk1(0x03e8, e->m_data_d); writeChunk1(0x03e9, e->m_data_d2); } closeChunk(); if (e->m_data_d3.size() > 0) { writeChunkN(0x03ee, e->m_data_d3); } else { // データサイズゼロとして書くのではなく // チャンク自体を書き込まない } writeChunkN(0x0fa1, e->m_data_e); uint16_t numPages = (uint16_t)e->getPageCount(); writeChunk2(0x07d0, numPages); writeChunk4(0x07d1, e->m_data_f); writeChunk1(0x07d2, e->m_data_g); // Pages K__ASSERT(numPages > 0); for (uint16_t i=0; i<numPages; i++) { openChunk(0x07d3); writePage(e, i); closeChunk(); } writeChunk4(0x07d4, e->m_data_h); uint16_t numPalettes = (uint16_t)e->getPaletteCount(); writeChunk2(0x0bb8, numPalettes); writeChunk2(0x0bb9, e->m_data_i); writeChunk4(0x0bba, e->m_data_j); // Palettes K__ASSERT(numPalettes > 0); for (uint16_t i=0; i<numPalettes; i++) { openChunk(0x0bbb); const KEdgePalette *pal = e->m_palettes[i]; std::string name_mb = K::strUtf8ToAnsi(pal->m_name_u8, EDGE2_STRING_ENCODING); writeChunkN(0x03e8, name_mb.c_str()); writeChunk4(0x03e9, pal->m_data_b); writeChunk1(0x03ea, pal->m_data_c); writeChunk1(0x03eb, pal->m_data_d); writeChunk1(0x03ec, pal->m_data_e); writeChunkN(0x03ed, pal->m_bgr_colors); writeChunkN(0x03ef, pal->m_data_f); writeChunkN(0x03f0, pal->m_data_g); writeChunkN(0x03f1, pal->m_data_h); writeChunkN(0x03f2, pal->m_data_i); writeChunkN(0x03f3, pal->m_data_j); writeChunk4(0x07d0, pal->m_data_k); writeChunk1(0x07d1, pal->m_data_l); writeChunk1(0x07d2, pal->m_data_m); closeChunk(); } writeChunk4(0x0bbc, e->m_data_k); // 前景色 openChunk(0x0bbf); { writeChunk1(0x03e8, e->m_fg_palette.color_index); writeChunkN(0x03e9, 3, e->m_fg_palette.bgr_colors); writeChunk1(0x03ea, e->m_fg_palette.data_a); writeChunkN(0x03eb, 6, e->m_fg_palette.data_b); writeChunk1(0x03ec, e->m_fg_palette.data_c); } closeChunk(); // 背景色 openChunk(0x0bc0); { writeChunk1(0x03e8, e->m_bg_palette.color_index); writeChunkN(0x03e9, 3, e->m_bg_palette.bgr_colors); writeChunk1(0x03ea, e->m_bg_palette.data_a); writeChunkN(0x03eb, 6, e->m_bg_palette.data_b); writeChunk1(0x03ec, e->m_bg_palette.data_c); } closeChunk(); } void KEdgeRawWriter::writeCompressedEdge(KOutputStream &file) const { if (!file.isOpen()) { K__ERROR(""); return; } // 圧縮前のサイズ uint32_t uncompsize = size(); KEdgeBin zbuf = KZlib::compress_zlib(data(), size(), 1); // ヘッダーを出力 uint16_t compflag = 256; file.write("EDGE2\0", 6); file.write((char *)&compflag, 2); file.write((char *)&uncompsize, 4); // 圧縮データを出力 file.write(zbuf.data(), zbuf.size()); } void KEdgeRawWriter::writeUncompressedEdge(KEdgeDocument *e) { if (e == NULL) { K__ERROR(""); return; } // 初期化 clear(); // 無圧縮 Edge データを作成 writeEdge(e); } #pragma endregion // KEdgeRawWriter #pragma region KEdgeWriter KEdgeWriter::KEdgeWriter() { m_doc = new KEdgeDocument(); m_doc->m_palettes.push_back(new KEdgePalette()); m_doc->m_bit_depth = 24; } KEdgeWriter::~KEdgeWriter() { delete (m_doc); } void KEdgeWriter::clear() { delete(m_doc); // m_doc = new KEdgeDocument(); m_doc->m_palettes.push_back(new KEdgePalette()); m_doc->m_bit_depth = 24; } void KEdgeWriter::addPage(const KImage *img, int delay) { if (img==NULL || img->empty()) return; int img_w = img->getWidth(); int img_h = img->getHeight(); { KEdgePage *page = m_doc->addPage(); page->m_width = (uint16_t)img_w; page->m_height = (uint16_t)img_h; page->m_delay = delay; { KEdgeLayer *layer = page->addLayer(); if (img->getBytesPerPixel() == 4) { // 32ビット画像から24ビット画像へ KImage image_rgb24 = KImage::createFromPixels(img_w, img_h, KColorFormat_RGB24, NULL); int src_p = img->getPitch(); const uint8_t *sbuf = img->getData(); int dst_p = image_rgb24.getPitch(); uint8_t *dbuf = image_rgb24.lockData(); for (int y=0; y<img_h; y++) { for (int x=0; x<img_w; x++) { uint8_t r = sbuf[src_p * y + 4 * x + 0]; uint8_t g = sbuf[src_p * y + 4 * x + 1]; uint8_t b = sbuf[src_p * y + 4 * x + 2]; // uint8_t a = sbuf[src_p * y + 4 * x + 3]; // edge へは BGR 順で保存することに注意 dbuf[dst_p * y + 3 * x + 0] = b; dbuf[dst_p * y + 3 * x + 1] = g; dbuf[dst_p * y + 3 * x + 2] = r; } } layer->m_image_rgb24 = image_rgb24; } } } } void KEdgeWriter::saveToStream(KOutputStream &file) { K__ASSERT(m_doc); m_doc->saveToStream(file); } #pragma endregion // KEdgeWriter } // namespace
DhirajWishal/Flint
Code/Graphics/Source/Tools/ImageLoader.cpp
// Copyright 2021 <NAME> // SPDX-License-Identifier: Apache-2.0 #include "Graphics/Tools/ImageLoader.hpp" #include "GraphicsCore/Device.hpp" #define STB_IMAGE_IMPLEMENTATION #include "Graphics/ThirdParty/stb_image.h" namespace Flint { ImageLoader::ImageLoader(const std::filesystem::path& assetFile) { int32 texWidth = 0, texHeight = 0, texChannels = 0; if (stbi_is_hdr(assetFile.string().c_str())) { pPixelData = reinterpret_cast<unsigned char*>(stbi_loadf(assetFile.string().c_str(), &texWidth, &texHeight, &texChannels, STBI_rgb_alpha)); mPixelFormat = PixelFormat::R32G32B32A32_SFLOAT; } else { pPixelData = stbi_load(assetFile.string().c_str(), &texWidth, &texHeight, &texChannels, STBI_rgb_alpha); mPixelFormat = PixelFormat::R8G8B8A8_SRGB; } mExtent = FBox3D(texWidth, texHeight, 1); } ImageLoader::ImageLoader(const std::vector<std::filesystem::path>& assetFiles) { int32 texWidth = 0, texHeight = 0, texChannels = 0; uint64 offset = 0; for (uint64 i = 0; i < assetFiles.size(); i++) { auto pixels = stbi_load(assetFiles[i].string().c_str(), &texWidth, &texHeight, &texChannels, STBI_rgb_alpha); uint64 imageSize = static_cast<uint64>(texWidth) * static_cast<uint64>(texHeight) * 4; if (!imageSize) throw std::runtime_error("Couldn't load the requested image at location: " + assetFiles[i].string()); if (!pPixelData) pPixelData = new unsigned char[imageSize * assetFiles.size()]; std::copy(pixels, pixels + imageSize, pPixelData + offset); offset += imageSize; } mExtent = FBox3D(texWidth, texHeight, 1); mPixelFormat = PixelFormat::R8G8B8A8_SRGB; } ImageLoader::ImageLoader(ImageLoader&& other) : pPixelData(other.pPixelData), mExtent(other.mExtent), mPixelFormat(other.mPixelFormat) { other.pPixelData = nullptr; } ImageLoader::~ImageLoader() { if (pPixelData) stbi_image_free(pPixelData); } std::shared_ptr<Image> ImageLoader::CreateImage(const std::shared_ptr<Device>& pDevice, const ImageType type, const ImageUsage usage, const uint32 layers, const uint32 mipLevels, const MultiSampleCount sampleCount) const { if (mipLevels != 0) return pDevice->CreateImage(type, usage, mExtent, mPixelFormat, layers, mipLevels, pPixelData, sampleCount); else return pDevice->CreateImage(type, usage, mExtent, mPixelFormat, layers, Image::GetBestMipLevels(mExtent), pPixelData, sampleCount); } MaterialProperties::TextureData ImageLoader::GetAsTextureData(const MaterialProperties::TextureType type) { auto data = MaterialProperties::TextureData(pPixelData, mExtent, mPixelFormat, type); pPixelData = nullptr; return data; } ImageLoader& ImageLoader::operator=(ImageLoader&& other) { pPixelData = other.pPixelData; mExtent = other.mExtent; mPixelFormat = other.mPixelFormat; other.pPixelData = nullptr; return *this; } }
showurl/Open-IM-SDK-Core
ws_wrapper/ws_local_server/ws_user.go
package ws_local_server import ( "open_im_sdk/open_im_sdk" ) func (wsRouter *WsFuncRouter) GetUsersInfo(userIDList string, operationID string) { userWorker := open_im_sdk.GetUserWorker(wsRouter.uId) if !wsRouter.checkResourceLoadingAndKeysIn(userWorker, userIDList, operationID, runFuncName(), nil) { return } userWorker.Full().GetUsersInfo(&BaseSuccessFailed{runFuncName(), operationID, wsRouter.uId}, userIDList, operationID) } func (wsRouter *WsFuncRouter) SetSelfInfo(userInfo string, operationID string) { userWorker := open_im_sdk.GetUserWorker(wsRouter.uId) if !wsRouter.checkResourceLoadingAndKeysIn(userWorker, userInfo, operationID, runFuncName(), nil) { return } userWorker.User().SetSelfInfo(&BaseSuccessFailed{runFuncName(), operationID, wsRouter.uId}, userInfo, operationID) } func (wsRouter *WsFuncRouter) GetSelfUserInfo(input string, operationID string) { userWorker := open_im_sdk.GetUserWorker(wsRouter.uId) if !wsRouter.checkResourceLoadingAndKeysIn(userWorker, input, operationID, runFuncName(), nil) { return } userWorker.User().GetSelfUserInfo(&BaseSuccessFailed{runFuncName(), operationID, wsRouter.uId}, operationID) } type UserCallback struct { uid string } func (u *UserCallback) OnSelfInfoUpdated(userInfo string) { SendOneUserMessage(EventData{cleanUpfuncName(runFuncName()), 0, "", userInfo, "0"}, u.uid) } func (wsRouter *WsFuncRouter) SetUserListener() { var u UserCallback u.uid = wsRouter.uId userWorker := open_im_sdk.GetUserWorker(wsRouter.uId) userWorker.SetUserListener(&u) }
JetmirAv/flagpack-core
flags/AG.js
import l from '../svg/l/AG.svg' import m from '../svg/m/AG.svg' import s from '../svg/s/AG.svg' export default {l,m,s}
zp19890228/nacos
naming/src/main/java/com/alibaba/nacos/naming/remote/rpc/handler/ServiceListRequestHandler.java
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * 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.alibaba.nacos.naming.remote.rpc.handler; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.remote.request.ServiceListRequest; import com.alibaba.nacos.api.naming.remote.response.ServiceListResponse; import com.alibaba.nacos.api.remote.request.RequestMeta; import com.alibaba.nacos.auth.annotation.Secured; import com.alibaba.nacos.core.remote.RequestHandler; import com.alibaba.nacos.naming.core.v2.ServiceManager; import com.alibaba.nacos.naming.core.v2.pojo.Service; import com.alibaba.nacos.naming.utils.ServiceUtil; import com.alibaba.nacos.plugin.auth.constant.ActionTypes; import org.springframework.stereotype.Component; import java.util.Collection; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Objects; /** * Service list request handler. * * @author xiweng.yy */ @Component public class ServiceListRequestHandler extends RequestHandler<ServiceListRequest, ServiceListResponse> { @Override @Secured(action = ActionTypes.READ) public ServiceListResponse handle(ServiceListRequest request, RequestMeta meta) throws NacosException { Collection<Service> serviceSet = ServiceManager.getInstance().getSingletons(request.getNamespace()); ServiceListResponse result = ServiceListResponse.buildSuccessResponse(0, new LinkedList<>()); if (!serviceSet.isEmpty()) { Collection<String> serviceNameSet = selectServiceWithGroupName(serviceSet, request.getGroupName()); // TODO select service by selector List<String> serviceNameList = ServiceUtil .pageServiceName(request.getPageNo(), request.getPageSize(), serviceNameSet); result.setCount(serviceNameSet.size()); result.setServiceNames(serviceNameList); } return result; } private Collection<String> selectServiceWithGroupName(Collection<Service> serviceSet, String groupName) { Collection<String> result = new HashSet<>(serviceSet.size()); for (Service each : serviceSet) { if (Objects.equals(groupName, each.getGroup())) { result.add(each.getGroupedServiceName()); } } return result; } }
colinw7/CGameBoy
src/CZ80Assemble.h
<reponame>colinw7/CGameBoy #include <CZ80.h> #include <CZ80Op.h> #include <CStrUtil.h> #include <COStreamFile.h> #include <CFileParse.h> #ifdef CL_PARSER #include <CCeilP.h> #endif
10cy18/meite_shop_parent
meite_shop_service_impl/meite_shop_service_member/src/main/java/com/cy/member/service/impl/MemberLoginServiceImpl.java
<reponame>10cy18/meite_shop_parent package com.cy.member.service.impl; import com.alibaba.fastjson.JSONObject; import com.cy.base.BaseApiService; import com.cy.base.BaseResponse; import com.cy.constants.Constants; import com.cy.core.token.GenerateToken; import com.cy.core.utils.MD5Util; import com.cy.member.input.dto.UserLoginInpDTO; import com.cy.member.mapper.UserMapper; import com.cy.member.mapper.UserTokenMapper; import com.cy.member.mapper.entity.UserDO; import com.cy.member.mapper.entity.UserTokenDo; import com.cy.member.service.MemberLoginService; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.TransactionStatus; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class MemberLoginServiceImpl extends BaseApiService<JSONObject> implements MemberLoginService { @Autowired private UserMapper userMapper; @Autowired private UserTokenMapper userTokenMapper; @Autowired private GenerateToken generateToken; @Autowired private com.cy.core.transaction.RedisDataSoureceTransaction redisDataSoureceTransaction; @Override public BaseResponse<JSONObject> login(@RequestBody UserLoginInpDTO userLoginInpDTO) { // 1.验证参数 String mobile = userLoginInpDTO.getMobile(); if (StringUtils.isEmpty(mobile)) { return setResultError("手机号码不能为空!"); } String password = userLoginInpDTO.getPassword(); if (StringUtils.isEmpty(password)) { return setResultError("密码不能为空!"); } String loginType = userLoginInpDTO.getLoginType(); if (StringUtils.isEmpty(loginType)) { return setResultError("登陆类型不能为空!"); } //限制登录类型的范围 if (!(loginType.equals(Constants.MEMBER_LOGIN_TYPE_ANDROID) || loginType.equals(Constants.MEMBER_LOGIN_TYPE_IOS) || loginType.equals(Constants.MEMBER_LOGIN_TYPE_PC))) { return setResultError("登陆类型出现错误!"); } // 设备信息 String deviceInfor = userLoginInpDTO.getDeviceInfor(); if (StringUtils.isEmpty(deviceInfor)) { return setResultError("设备信息不能为空!"); } // 密码加密 String newPassWord = <PASSWORD>.<PASSWORD>(password); // 2.用户名称与密码登陆 UserDO userDo = userMapper.login(mobile, newPassWord); if (userDo == null) { return setResultError("用户名称与密码错误!"); } // 用户登陆Token Session 区别 // 用户每一个端登陆成功之后,会对应生成一个token令牌(临时且唯一)存放在redis中作为rediskey value userid TransactionStatus transactionStatus = null; try { // 3.查询之前是否有过登陆 获取userid Integer userId = userDo.getUserId(); // 5.根据userId+loginType 查询当前登陆类型账号之前是否有登陆过,如果登陆过 清除之前redistoken UserTokenDo userTokenDo = userTokenMapper.selectByUserIdAndLoginType(userId, loginType); transactionStatus = redisDataSoureceTransaction.begin(); if (userTokenDo != null) { // 4.清除之前的token String token = userTokenDo.getToken(); //开启redis事务 删除的时候方法会返回false Boolean removeToken = generateToken.removeToken(token); // 把该token的状态改为1 int updateTokenAvailability = userTokenMapper.updateTokenAvailability(token); if (!toDaoResult(updateTokenAvailability)) { return setResultError("系统错误!"); } } // 6.存入在数据库中 UserTokenDo userToken = new UserTokenDo(); userToken.setUserId(userId); userToken.setLoginType(userLoginInpDTO.getLoginType()); // 5. 生成新的token String keyPrefix = Constants.MEMBER_TOKEN_KEYPREFIX + loginType; String newToken = generateToken.createToken(keyPrefix, userId + "", Constants.MEMBRE_LOGIN_TOKEN_TIME); userToken.setToken(newToken); userToken.setDeviceInfor(deviceInfor); int insertUserToken = userTokenMapper.insertUserToken(userToken); if(!toDaoResult(insertUserToken)){ redisDataSoureceTransaction.rollback(transactionStatus); return setResultError("系统错误!"); } JSONObject tokenData = new JSONObject(); tokenData.put("token", newToken); redisDataSoureceTransaction.commit(transactionStatus); return setResultSuccess(tokenData); }catch (Exception e){ try{ redisDataSoureceTransaction.rollback(transactionStatus); }catch (Exception e2){ } return setResultError("系统错误!"); } } }
marcopollivier/java-tccinfnet-processboss
src/main/java/br/com/processboss/core/service/IExecutorService.java
package br.com.processboss.core.service; import java.util.List; import br.com.processboss.core.exception.ProcessExecutionException; import br.com.processboss.core.model.ProcessExecutionDetail; import br.com.processboss.core.model.ProcessInTask; import br.com.processboss.core.scheduling.executor.TaskExecutationManager; public interface IExecutorService { ProcessInTask prepareToExecution(ProcessInTask process); void executeProcess(ProcessInTask processInTask, String processExecutionKey, TaskExecutationManager manager) throws ProcessExecutionException; ProcessExecutionDetail saveOrUpdate(ProcessExecutionDetail processExecutionDetail); ProcessInTask loadHistory(ProcessInTask process); List<ProcessInTask> loadHistory(List<ProcessInTask> processes); ProcessInTask loadDependencies(ProcessInTask process); }
georgekach/iomonitor
public/modules/useradministration/config/useradministration.client.routes.js
<reponame>georgekach/iomonitor<gh_stars>0 'use strict'; //Setting up route angular.module('useradministration').config(['$stateProvider', function($stateProvider) { // Useradministration state routing $stateProvider. state('useradministration', { url: '/useradministration', templateUrl: 'modules/useradministration/views/useradministration.client.view.html' }); } ]);
lriki/Lumino
src/Transcoder/Parser/ParserIntermediates.cpp
 #include "ParserIntermediates.hpp" //============================================================================== // PIDocument ln::String PIDocument::formatComment(const ln::String& comment) { ln::String output = comment.trim(); // 先頭の : を取り除く (主に @param 用) if (output.indexOf(U":") == 0) { output = output.substr(1); output = output.trim(); } // 各行先頭の * を取り除く。Cスタイルコメントで行頭に * を各パターンの対策 output = output.remove(U"\r"); auto lines = output.split(U"\n"); output.clear(); for (auto& line : lines) { line = line.trim(); if (line.indexOf(U"*") == 0) { line = line.substr(1); } if (!line.isEmpty()) { output += line.trim(); } } return output; } bool PIDocument::equalsLocalSigneture(const PIDocument* lhs, const PIDocument* rhs) { if (lhs->copydocLocalSignature.size() != rhs->copydocLocalSignature.size()) return false; for (int i = 0; i < lhs->copydocLocalSignature.size(); i++) { if (lhs->copydocLocalSignature[i] != rhs->copydocLocalSignature[i]) { return false; } } return true; } //============================================================================== // PIDatabase ln::List<ln::String> PIDatabase::parseLocalSigneture(const ln::String& signeture, const ln::String& methodName) { ln::String actual; if (!methodName.isEmpty()) { actual = signeture.substr(signeture.indexOf(methodName)); } else { actual = signeture; } ln::List<ln::String> output; ln::MatchResult result; if (ln::Regex::search(actual, _T(R"((\w+)(.*))"), &result)) { output.add(result.groupValue(1)); auto params = ln::String(result.groupValue(2)).remove(U"(").remove(U")").remove(U" ").remove(U"\t").split(U",", ln::StringSplitOptions::RemoveEmptyEntries); for (auto& p : params) { output.add(p); } } return output; } PIDocument* PIDatabase::findRelativeDocument(const ln::List<ln::String>& localSignature) { // 関数名で絞る ln::Array<Ref<PIDocument>> docs = relativeDocuments.filter([&](auto& x) { return x->copydocLocalSignature[0] == localSignature[0]; }); if (docs.size() == 1) { // この時点で 1 つだけだったらそれを採用 return docs[0]; } // 引数の数で絞る docs = docs.filter([&](auto& x) { return x->copydocLocalSignature.size() == localSignature.size(); }); if (docs.size() == 1) { // この時点で 1 つだけだったらそれを採用 return docs[0]; } // 各引数を、copydoc 側に書かれた引数型の先頭部分一致で比較し、マッチしたものを採用 for (auto& doc : docs) { int i = 0; for (; i < localSignature.size(); i++) { if (doc->copydocLocalSignature[i].indexOf(localSignature[i]) != 0) { break; } } if (i == localSignature.size()) { return doc; } } return nullptr; } void PIDatabase::clear() { types.clear(); relativeDocuments.clear(); } void PIDatabase::save(const ln::Path& filePath) { auto json = ln::JsonSerializer::serialize(*this); ln::FileSystem::writeAllText(filePath, json); } void PIDatabase::load(const ln::Path& filePath) { auto json = ln::FileSystem::readAllText(filePath); ln::JsonSerializer::deserialize(json, *this); } void PIDatabase::mergeFrom(const PIDatabase* src) { for (auto& t : src->types) { if (!types.containsIf([&](auto& x) { return x->rawFullName == t->rawFullName; })) { t->moduleName = src->moduleName; types.add(t); } } for (auto& d : src->relativeDocuments) { if (!relativeDocuments.containsIf([&](auto& x) { return PIDocument::equalsLocalSigneture(x, d); })) { relativeDocuments.push(d); } } }
majunbao/xue
electron/demo04/renderer/Layer.js
// 图层类 class Layer { constructor() { this._layers = [] } append() { } }
davidkpiano/azure-sdk-for-node
lib/services/batch/lib/models/taskInformation.js
<filename>lib/services/batch/lib/models/taskInformation.js /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * @summary Information about a task running on a compute node. * */ class TaskInformation { /** * Create a TaskInformation. * @member {string} [taskUrl] The URL of the task. * @member {string} [jobId] The ID of the job to which the task belongs. * @member {string} [taskId] The ID of the task. * @member {number} [subtaskId] The ID of the subtask if the task is a * multi-instance task. * @member {string} taskState The current state of the task. Possible values * include: 'active', 'preparing', 'running', 'completed' * @member {object} [executionInfo] Information about the execution of the * task. * @member {date} [executionInfo.startTime] 'Running' corresponds to the * running state, so if the task specifies resource files or application * packages, then the start time reflects the time at which the task started * downloading or deploying these. If the task has been restarted or retried, * this is the most recent time at which the task started running. This * property is present only for tasks that are in the running or completed * state. * @member {date} [executionInfo.endTime] This property is set only if the * task is in the Completed state. * @member {number} [executionInfo.exitCode] This property is set only if the * task is in the completed state. In general, the exit code for a process * reflects the specific convention implemented by the application developer * for that process. If you use the exit code value to make decisions in your * code, be sure that you know the exit code convention used by the * application process. However, if the Batch service terminates the task * (due to timeout, or user termination via the API) you may see an operating * system-defined exit code. * @member {object} [executionInfo.containerInfo] This property is set only * if the task runs in a container context. * @member {string} [executionInfo.containerInfo.containerId] * @member {string} [executionInfo.containerInfo.state] This is the state of * the container according to the Docker service. It is equivalent to the * status field returned by "docker inspect". * @member {string} [executionInfo.containerInfo.error] This is the detailed * error string from the Docker service, if available. It is equivalent to * the error field returned by "docker inspect". * @member {object} [executionInfo.failureInfo] This property is set only if * the task is in the completed state and encountered a failure. * @member {string} [executionInfo.failureInfo.category] Possible values * include: 'userError', 'serverError' * @member {string} [executionInfo.failureInfo.code] * @member {string} [executionInfo.failureInfo.message] * @member {array} [executionInfo.failureInfo.details] * @member {number} [executionInfo.retryCount] Task application failures * (non-zero exit code) are retried, pre-processing errors (the task could * not be run) and file upload errors are not retried. The Batch service will * retry the task up to the limit specified by the constraints. * @member {date} [executionInfo.lastRetryTime] This element is present only * if the task was retried (i.e. retryCount is nonzero). If present, this is * typically the same as startTime, but may be different if the task has been * restarted for reasons other than retry; for example, if the compute node * was rebooted during a retry, then the startTime is updated but the * lastRetryTime is not. * @member {number} [executionInfo.requeueCount] When the user removes nodes * from a pool (by resizing/shrinking the pool) or when the job is being * disabled, the user can specify that running tasks on the nodes be requeued * for execution. This count tracks how many times the task has been requeued * for these reasons. * @member {date} [executionInfo.lastRequeueTime] This property is set only * if the requeueCount is nonzero. * @member {string} [executionInfo.result] If the value is 'failed', then the * details of the failure can be found in the failureInfo property. Possible * values include: 'success', 'failure' */ constructor() { } /** * Defines the metadata of TaskInformation * * @returns {object} metadata of TaskInformation * */ mapper() { return { required: false, serializedName: 'TaskInformation', type: { name: 'Composite', className: 'TaskInformation', modelProperties: { taskUrl: { required: false, serializedName: 'taskUrl', type: { name: 'String' } }, jobId: { required: false, serializedName: 'jobId', type: { name: 'String' } }, taskId: { required: false, serializedName: 'taskId', type: { name: 'String' } }, subtaskId: { required: false, serializedName: 'subtaskId', type: { name: 'Number' } }, taskState: { required: true, serializedName: 'taskState', type: { name: 'Enum', allowedValues: [ 'active', 'preparing', 'running', 'completed' ] } }, executionInfo: { required: false, serializedName: 'executionInfo', type: { name: 'Composite', className: 'TaskExecutionInformation' } } } } }; } } module.exports = TaskInformation;
caninojories/erp_moe3
front-end/resources/js/routes/admin/quotationList/dataservice.js
(function() { 'use strict'; angular .module('app.quotationList') .factory('quotationListDataService', quotationListDataService); quotationListDataService.$inject = ['quotationServiceApi']; /*@ngInject*/ function quotationListDataService(quotationServiceApi) { var service = { httpGET: httpGET, httpPUT: httpPUT, httpDELETE: httpDELETE }; return service; function httpGET(api, param) { return quotationServiceApi.one(api) .get(param) .then(httpGETCallBack) .catch(function(message) { }); function httpGETCallBack(response, status, header, config) { return response; } } function httpPUT(api, param) { return quotationServiceApi.one(api) .put(param) .then(httpPUTCallBack) .catch(function(message) { }); function httpPUTCallBack(response, status, header, config) { return response; } } function httpDELETE(api, param) { return quotationServiceApi.one(api) .remove(param) .then(httpDELETECallBack) .catch(function(message) { }); function httpDELETECallBack(response, status, header, config) { return response; } } } }());
yxqzjj/renren-fast_wcs
src/main/java/io/renren/wcs/client/dto/MsgChangeStationModeAckDTO.java
<filename>src/main/java/io/renren/wcs/client/dto/MsgChangeStationModeAckDTO.java package io.renren.wcs.client.dto; import io.renren.wcs.client.Factory.FactoryConstant; import io.renren.wcs.client.Factory.FactoryProducer; import io.renren.wcs.service.MsgReceiveService; import java.util.Objects; /** * Console→WCS 站台模式切换应答 * * @Author: CalmLake * @Date: 2018/11/17 12:55 * @Version: V1.0.0 **/ public class MsgChangeStationModeAckDTO extends MsgDTO { /** * 站台号 */ private String station; /** * 模式 01-入库,02-出库 */ private String mode; public MsgChangeStationModeAckDTO getMsgDTO(String msg) { MsgReceiveService msgReceiveService = Objects.requireNonNull(FactoryProducer.getFactory(FactoryConstant.RECEIVE)).getMsgReceiveService(msg); return (MsgChangeStationModeAckDTO) msgReceiveService.getMsgDTO(msg); } public String getStation() { return station; } public void setStation(String station) { this.station = station; } public String getMode() { return mode; } public void setMode(String mode) { this.mode = mode; } @Override public String toString() { return String.format("站台号:%s,模式:%s", station, mode); } @Override public String getNumString() { return getMessageNumber() + getCommandType() + getReSend() + getSendTime() + station + mode + getBcc(); } }
RockerHX/FishChat
WeChat-Headers/MMOOMCrashReport.h
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "NSObject.h" #import "MonoServiceLogicExt.h" @class NSString; @interface MMOOMCrashReport : NSObject <MonoServiceLogicExt> { } + (void)reportFoomScene; + (void)reportIDKEYByType:(unsigned long long)arg1; + (void)checkAndReport; + (_Bool)isOSReboot; + (unsigned int)getSystemLaunchTimeStamp; + (_Bool)isOSChange; + (_Bool)isAppChange; + (void)enterForeground; + (void)willSuspend; + (void)enterBackground; + (void)registerExtension; + (void)setScene:(id)arg1; + (void)setFlag:(id)arg1; + (void)initialize; - (void)onMonoServiceDidEnd; - (void)onMonoServiceWalkieTalkieWillStart; - (void)onMonoServiceMultitalkWillStart; - (void)onMonoServiceVoipWillStart; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
agancsos/hak5
USB-Rubber-Ducky/Firmware/Source/Composite_Duck/src/asf/common/services/storage/ctrl_access/ctrl_access.h
/***************************************************************************** * * \file * * \brief Abstraction layer for memory interfaces. * * This module contains the interfaces: * - MEM <-> USB; * - MEM <-> RAM; * - MEM <-> MEM. * * This module may be configured and expanded to support the following features: * - write-protected globals; * - password-protected data; * - specific features; * - etc. * * Copyright (c) 2009-2012 Atmel Corporation. All rights reserved. * * \asf_license_start * * \page License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name of Atmel may not be used to endorse or promote products derived * from this software without specific prior written permission. * * 4. This software may only be redistributed and used in connection with an * Atmel microcontroller product. * * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. * * \asf_license_stop * ******************************************************************************/ #ifndef _CTRL_ACCESS_H_ #define _CTRL_ACCESS_H_ /** * \defgroup group_common_services_storage_ctrl_access Memory Control Access * * Common abstraction layer for memory interfaces. It provides interfaces between: * Memory and USB, Memory and RAM, Memory and Memory. Common API for XMEGA and UC3. * * \{ */ #include "compiler.h" #include "conf_access.h" #define SECTOR_SIZE 512 //! Status returned by CTRL_ACCESS interfaces. typedef enum { CTRL_GOOD = PASS, //!< Success, memory ready. CTRL_FAIL = FAIL, //!< An error occurred. CTRL_NO_PRESENT = FAIL + 1, //!< Memory unplugged. CTRL_BUSY = FAIL + 2 //!< Memory not initialized or changed. } Ctrl_status; // FYI: Each Logical Unit Number (LUN) corresponds to a memory. // Check LUN defines. #ifndef LUN_0 #error LUN_0 must be defined as ENABLE or DISABLE in conf_access.h #endif #ifndef LUN_1 #error LUN_1 must be defined as ENABLE or DISABLE in conf_access.h #endif #ifndef LUN_2 #error LUN_2 must be defined as ENABLE or DISABLE in conf_access.h #endif #ifndef LUN_3 #error LUN_3 must be defined as ENABLE or DISABLE in conf_access.h #endif #ifndef LUN_4 #error LUN_4 must be defined as ENABLE or DISABLE in conf_access.h #endif #ifndef LUN_5 #error LUN_5 must be defined as ENABLE or DISABLE in conf_access.h #endif #ifndef LUN_6 #error LUN_6 must be defined as ENABLE or DISABLE in conf_access.h #endif #ifndef LUN_7 #error LUN_7 must be defined as ENABLE or DISABLE in conf_access.h #endif #ifndef LUN_USB #error LUN_USB must be defined as ENABLE or DISABLE in conf_access.h #endif /*! \name LUN IDs */ //! @{ #define LUN_ID_0 (0) //!< First static LUN. #define LUN_ID_1 (LUN_ID_0 + LUN_0) #define LUN_ID_2 (LUN_ID_1 + LUN_1) #define LUN_ID_3 (LUN_ID_2 + LUN_2) #define LUN_ID_4 (LUN_ID_3 + LUN_3) #define LUN_ID_5 (LUN_ID_4 + LUN_4) #define LUN_ID_6 (LUN_ID_5 + LUN_5) #define LUN_ID_7 (LUN_ID_6 + LUN_6) #define MAX_LUN (LUN_ID_7 + LUN_7) //!< Number of static LUNs. #define LUN_ID_USB (MAX_LUN) //!< First dynamic LUN (USB host mass storage). //! @} // Include LUN header files. #if LUN_0 == ENABLE #include LUN_0_INCLUDE #endif #if LUN_1 == ENABLE #include LUN_1_INCLUDE #endif #if LUN_2 == ENABLE #include LUN_2_INCLUDE #endif #if LUN_3 == ENABLE #include LUN_3_INCLUDE #endif #if LUN_4 == ENABLE #include LUN_4_INCLUDE #endif #if LUN_5 == ENABLE #include LUN_5_INCLUDE #endif #if LUN_6 == ENABLE #include LUN_6_INCLUDE #endif #if LUN_7 == ENABLE #include LUN_7_INCLUDE #endif #if LUN_USB == ENABLE #include LUN_USB_INCLUDE #endif // Check the configuration of write protection in conf_access.h. #ifndef GLOBAL_WR_PROTECT #error GLOBAL_WR_PROTECT must be defined as true or false in conf_access.h #endif #if GLOBAL_WR_PROTECT == true //! Write protect. extern bool g_wr_protect; #endif /*! \name Control Interface */ //! @{ #ifdef FREERTOS_USED /*! \brief Initializes the LUN access locker. * * \return \c true if the locker was successfully initialized, else \c false. */ extern bool ctrl_access_init(void); #endif // FREERTOS_USED /*! \brief Returns the number of LUNs. * * \return Number of LUNs in the system. */ extern U8 get_nb_lun(void); /*! \brief Returns the current LUN. * * \return Current LUN. * * \todo Implement. */ extern U8 get_cur_lun(void); /*! \brief Tests the memory state and initializes the memory if required. * * The TEST UNIT READY SCSI primary command allows an application client to poll * a LUN until it is ready without having to allocate memory for returned data. * * This command may be used to check the media status of LUNs with removable * media. * * \param lun Logical Unit Number. * * \return Status. */ extern Ctrl_status mem_test_unit_ready(U8 lun); /*! \brief Returns the address of the last valid sector (512 bytes) in the * memory. * * \param lun Logical Unit Number. * \param u32_nb_sector Pointer to the address of the last valid sector. * * \return Status. */ extern Ctrl_status mem_read_capacity(U8 lun, U32 *u32_nb_sector); /*! \brief Returns the size of the physical sector. * * \param lun Logical Unit Number. * * \return Sector size (unit: 512 bytes). */ extern U8 mem_sector_size(U8 lun); /*! \brief Returns the write-protection state of the memory. * * \param lun Logical Unit Number. * * \return \c true if the memory is write-protected, else \c false. * * \note Only used by removable memories with hardware-specific write * protection. */ extern bool mem_wr_protect(U8 lun); /*! \brief Tells whether the memory is removable. * * \param lun Logical Unit Number. * * \return \c true if the memory is removable, else \c false. */ extern bool mem_removal(U8 lun); /*! \brief Returns a pointer to the LUN name. * * \param lun Logical Unit Number. * * \return Pointer to the LUN name string. */ extern const char *mem_name(U8 lun); //! @} #if ACCESS_USB == true /*! \name MEM <-> USB Interface */ //! @{ /*! \brief Transfers data from the memory to USB. * * \param lun Logical Unit Number. * \param addr Address of first memory sector to read. * \param nb_sector Number of sectors to transfer. * * \return Status. */ extern Ctrl_status memory_2_usb(U8 lun, U32 addr, U16 nb_sector); /*! \brief Transfers data from USB to the memory. * * \param lun Logical Unit Number. * \param addr Address of first memory sector to write. * \param nb_sector Number of sectors to transfer. * * \return Status. */ extern Ctrl_status usb_2_memory(U8 lun, U32 addr, U16 nb_sector); //! @} #endif // ACCESS_USB == true #if ACCESS_MEM_TO_RAM == true /*! \name MEM <-> RAM Interface */ //! @{ /*! \brief Copies 1 data sector from the memory to RAM. * * \param lun Logical Unit Number. * \param addr Address of first memory sector to read. * \param ram Pointer to RAM buffer to write. * * \return Status. */ extern Ctrl_status memory_2_ram(U8 lun, U32 addr, void *ram); /*! \brief Copies 1 data sector from RAM to the memory. * * \param lun Logical Unit Number. * \param addr Address of first memory sector to write. * \param ram Pointer to RAM buffer to read. * * \return Status. */ extern Ctrl_status ram_2_memory(U8 lun, U32 addr, const void *ram); //! @} #endif // ACCESS_MEM_TO_RAM == true #if ACCESS_STREAM == true /*! \name Streaming MEM <-> MEM Interface */ //! @{ //! Erroneous streaming data transfer ID. #define ID_STREAM_ERR 0xFF #if ACCESS_MEM_TO_MEM == true /*! \brief Copies data from one memory to another. * * \param src_lun Source Logical Unit Number. * \param src_addr Source address of first memory sector to read. * \param dest_lun Destination Logical Unit Number. * \param dest_addr Destination address of first memory sector to write. * \param nb_sector Number of sectors to copy. * * \return Status. */ extern Ctrl_status stream_mem_to_mem(U8 src_lun, U32 src_addr, U8 dest_lun, U32 dest_addr, U16 nb_sector); #endif // ACCESS_MEM_TO_MEM == true /*! \brief Returns the state of a streaming data transfer. * * \param id Transfer ID. * * \return Status. * * \todo Implement. */ extern Ctrl_status stream_state(U8 id); /*! \brief Stops a streaming data transfer. * * \param id Transfer ID. * * \return Number of remaining sectors. * * \todo Implement. */ extern U16 stream_stop(U8 id); //! @} #endif // ACCESS_STREAM == true /** * \} */ #endif // _CTRL_ACCESS_H_
Mu-L/flinkStreamSQL
core/src/test/java/com/dtstack/flink/sql/side/AbstractSideTableInfoTest.java
package com.dtstack.flink.sql.side; import org.junit.Test; public class AbstractSideTableInfoTest { @Test public void getRowTypeInfo(){ AbstractSideTableInfo sideTableInfo = new AbstractSideTableInfo() { @Override public boolean check() { return false; } }; Class[] fieldClasses = new Class[1]; fieldClasses[0] = String.class; sideTableInfo.setFieldClasses(fieldClasses); String[] fields = new String[1]; fields[0] = "a"; sideTableInfo.setFields(fields); sideTableInfo.getRowTypeInfo(); } }
atianxia/cas-study
support/cas-server-support-actions/src/test/java/org/apereo/cas/web/flow/InitialFlowSetupActionCookieTests.java
<reponame>atianxia/cas-study package org.apereo.cas.web.flow; import com.google.common.collect.Lists; import org.apereo.cas.authentication.principal.Service; import org.apereo.cas.authentication.principal.WebApplicationServiceFactory; import org.apereo.cas.config.CasCoreAuthenticationConfiguration; import org.apereo.cas.config.CasCoreConfiguration; import org.apereo.cas.config.CasCoreServicesConfiguration; import org.apereo.cas.config.CasCoreTicketsConfiguration; import org.apereo.cas.config.CasCoreWebConfiguration; import org.apereo.cas.config.CasPersonDirectoryAttributeRepositoryConfiguration; import org.apereo.cas.configuration.CasConfigurationProperties; import org.apereo.cas.logout.config.CasCoreLogoutConfiguration; import org.apereo.cas.services.ServicesManager; import org.apereo.cas.services.TestUtils; import org.apereo.cas.web.config.CasCookieConfiguration; import org.apereo.cas.web.flow.config.CasCoreWebflowConfiguration; import org.apereo.cas.web.support.ArgumentExtractor; import org.apereo.cas.web.support.CookieRetrievingCookieGenerator; import org.apereo.cas.web.support.DefaultArgumentExtractor; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockServletContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.webflow.context.servlet.ServletExternalContext; import org.springframework.webflow.test.MockRequestContext; import static org.junit.Assert.*; import static org.mockito.Mockito.*; /** * This is {@link InitialFlowSetupActionCookieTests}. * * @author <NAME> * @since 5.0.0 */ @RunWith(SpringRunner.class) @SpringBootTest( classes = { CasCoreWebflowConfiguration.class, CasCoreWebConfiguration.class, CasCoreConfiguration.class, CasCoreTicketsConfiguration.class, CasCoreLogoutConfiguration.class, CasCoreAuthenticationConfiguration.class, CasPersonDirectoryAttributeRepositoryConfiguration.class, CasCookieConfiguration.class, RefreshAutoConfiguration.class, CasCoreServicesConfiguration.class}) @ContextConfiguration(locations = "classpath:/core-context.xml") @TestPropertySource(properties = "spring.aop.proxy-target-class=true") public class InitialFlowSetupActionCookieTests { private static final String CONST_CONTEXT_PATH = "/test"; private static final String CONST_CONTEXT_PATH_2 = "/test1"; @Autowired private CasConfigurationProperties casProperties; private InitialFlowSetupAction action = new InitialFlowSetupAction(); private CookieRetrievingCookieGenerator warnCookieGenerator; private CookieRetrievingCookieGenerator tgtCookieGenerator; private ServicesManager servicesManager; @Before public void setUp() throws Exception { this.warnCookieGenerator = new CookieRetrievingCookieGenerator(); this.warnCookieGenerator.setCookiePath(""); this.tgtCookieGenerator = new CookieRetrievingCookieGenerator(); this.tgtCookieGenerator.setCookiePath(""); this.action.setTicketGrantingTicketCookieGenerator(this.tgtCookieGenerator); this.action.setWarnCookieGenerator(this.warnCookieGenerator); final ArgumentExtractor[] argExtractors = new ArgumentExtractor[]{new DefaultArgumentExtractor( new WebApplicationServiceFactory() )}; this.action.setArgumentExtractors(Lists.newArrayList(argExtractors)); this.action.setCasProperties(casProperties); this.servicesManager = mock(ServicesManager.class); when(this.servicesManager.findServiceBy(any(Service.class))).thenReturn( TestUtils.getRegisteredService("test")); this.action.setServicesManager(this.servicesManager); this.action.afterPropertiesSet(); } @Test public void verifySettingContextPath() throws Exception { final MockHttpServletRequest request = new MockHttpServletRequest(); request.setContextPath(CONST_CONTEXT_PATH); final MockRequestContext context = new MockRequestContext(); context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, new MockHttpServletResponse())); this.action.doExecute(context); assertEquals(CONST_CONTEXT_PATH + '/', this.warnCookieGenerator.getCookiePath()); assertEquals(CONST_CONTEXT_PATH + '/', this.tgtCookieGenerator.getCookiePath()); } @Test public void verifyResettingContexPath() throws Exception { final MockHttpServletRequest request = new MockHttpServletRequest(); request.setContextPath(CONST_CONTEXT_PATH); final MockRequestContext context = new MockRequestContext(); context.setExternalContext(new ServletExternalContext(new MockServletContext(), request, new MockHttpServletResponse())); this.action.doExecute(context); assertEquals(CONST_CONTEXT_PATH + '/', this.warnCookieGenerator.getCookiePath()); assertEquals(CONST_CONTEXT_PATH + '/', this.tgtCookieGenerator.getCookiePath()); request.setContextPath(CONST_CONTEXT_PATH_2); this.action.doExecute(context); assertNotSame(CONST_CONTEXT_PATH_2 + '/', this.warnCookieGenerator.getCookiePath()); assertNotSame(CONST_CONTEXT_PATH_2 + '/', this.tgtCookieGenerator.getCookiePath()); assertEquals(CONST_CONTEXT_PATH + '/', this.warnCookieGenerator.getCookiePath()); assertEquals(CONST_CONTEXT_PATH + '/', this.tgtCookieGenerator.getCookiePath()); } }
AngelAlvie/homeworld
platform/go/deps.bzl
<filename>platform/go/deps.bzl load("@com_google_protobuf//:protobuf_deps.bzl", "protobuf_deps") load("@bazel_gazelle//:deps.bzl", "gazelle_dependencies") load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies") def go_dependencies(): go_rules_dependencies() # TODO: stop using binaries built by upstream; use our own go_register_toolchains( go_version = "1.12.10", ) protobuf_deps() gazelle_dependencies()
TermuxArch/dom-distiller
java/org/chromium/distiller/webdocument/filters/images/AreaScorer.java
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.distiller.webdocument.filters.images; import com.google.gwt.dom.client.Element; /** * ImageScorer that uses image area (length*width) as its heuristic. */ public class AreaScorer extends BaseImageScorer { public final int maxScore; public final int minArea; public final int maxArea; /** * Initialize this ImageScorer with appropriate info. * @param maximumScore The maximum score that should be given to any image. * @param minimumArea The smallest area in px an image can consume and still be scored. * @param maximumArea The largest area in px an image can consume and still be scored. */ public AreaScorer(int maximumScore, int minimumArea, int maximumArea) { maxScore = maximumScore; minArea = minimumArea; maxArea = maximumArea; } @Override protected int computeScore(Element e) { int area = e.getOffsetWidth() * e.getOffsetHeight(); if (area < minArea) return 0; int score = (int) ((float) (area - minArea) / (maxArea - minArea) * maxScore); return Math.min(score, maxScore); } @Override public int getMaxScore() { return maxScore; } }
yearm/aliyun-log-go-sdk
errors.go
package sls import ( "encoding/json" ) // BadResponseError : special sls error, not valid json format type BadResponseError struct { RespBody string RespHeader map[string][]string HTTPCode int } func (e BadResponseError) String() string { b, err := json.MarshalIndent(e, "", " ") if err != nil { return "" } return string(b) } func (e BadResponseError) Error() string { return e.String() } // NewBadResponseError ... func NewBadResponseError(body string, header map[string][]string, httpCode int) *BadResponseError { return &BadResponseError{ RespBody: body, RespHeader: header, HTTPCode: httpCode, } } // mockErrorRetry : for mock the error retry logic type mockErrorRetry struct { Err Error RetryCnt int // RetryCnt-- after each retry. When RetryCnt > 0, return Err, else return nil, if set it BigUint, it equivalents to always failing. } func (e mockErrorRetry) Error() string { return e.Err.String() }
alrs/acyl
vendor/github.com/hashicorp/vault/ui/app/controllers/vault/cluster/replication/mode/secondaries/index.js
import ReplicationController from '../../../replication'; export default ReplicationController.extend();
excel-academy/excel-academy-website
site-config.js
<gh_stars>0 module.exports = { siteTitle: 'Excel Academy', siteTitleShort: 'ExcelAcademy', siteDescription: 'Start a career in the growing healthcare industry.', siteUrl: 'https://www.excelacademyct.com/', themeColor: '#4bb2b6', backgroundColor: '#fff', // Prefixes all links. For cases when deployed to example.github.io/gatsby-advanced-starter/. pathPrefix: null, logo: 'src/images/icon.png', company: { type: 'School', name: 'Excel Academy', legalName: 'Excel Academy, LLC', email: '<EMAIL>', address: { country: 'United States', region: 'Stamford, CT', postalCode: '06901', streetAddress: '482 Summer St', }, sameAs: [ 'https://www.facebook.com/excelacademyct', ], telephone: [ '203-691-7989', ], }, };
viktarshumik/ptusa_main
PAC/common/sys/console.h
/// @file console.h /// @brief Работа с консолью вне зависимости от аппаратной реализации. Также /// некоторые безопасные функции работы со строками. /// /// @author <NAME>. /// /// @par Описание директив препроцессора: /// /// @par Текущая версия: /// @$Rev: 220 $.\n /// @$Author: id $.\n /// @$Date:: 2011-02-15 16:58:56#$. #ifndef CONSOLE_H #define CONSOLE_H #if !defined WIN_OS && !defined LINUX_OS #error You must define OS! #endif #include <string.h> #include <stdio.h> #include "s_types.h" //----------------------------------------------------------------------------- /// @brief Печать в консоль. #ifdef WIN_OS #include "w_console.h" #endif // WIN_OS #ifdef LINUX_OS #include "l_console.h" #endif // LINUX_OS //----------------------------------------------------------------------------- /// @brief Проверка нажатия клавиши. /// /// @return 0 - нет нажатий клавиш. /// @return 1 - нажата клавиша. int kb_hit(); //----------------------------------------------------------------------------- /// @brief Считывание нажатого символа с консоли. /// /// @return - символ нажатой клавиши. int get_char(); //----------------------------------------------------------------------------- /// @brief Вывод числа в консоль в двоичном виде. /// /// @param c - выводимое число. void print_binary( unsigned int c ); //----------------------------------------------------------------------------- #endif // CONSOLE_H
da0shi/replviz
src/javarepl/console/ConsoleLoggerPrintStream.java
<reponame>da0shi/replviz package javarepl.console; import com.googlecode.totallylazy.Predicate; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.Locale; import static com.googlecode.totallylazy.Predicates.not; import static javarepl.console.ConsoleLog.consoleLog; public class ConsoleLoggerPrintStream extends PrintStream { private final ConsoleLog.Type type; private final Predicate<String> ignore; private final ConsoleLogger logger; public ConsoleLoggerPrintStream(ConsoleLog.Type type, Predicate<String> ignore, ConsoleLogger logger) { super(new OutputStream() { public void write(int b) throws IOException { } }); this.type = type; this.ignore = ignore; this.logger = logger; } @Override public void write(byte[] buf, int off, int len) { logMessage(new String(buf, off, len)); } @Override public void print(boolean b) { logMessage(String.valueOf(b)); } @Override public void print(char c) { logMessage(String.valueOf(c)); } @Override public void print(int i) { logMessage(String.valueOf(i)); } @Override public void print(long l) { logMessage(String.valueOf(l)); } @Override public void print(float f) { logMessage(String.valueOf(f)); } @Override public void print(double d) { logMessage(String.valueOf(d)); } @Override public void print(char[] s) { logMessage(String.valueOf(s)); } @Override public void print(String s) { logMessage(s); } @Override public void print(Object obj) { logMessage(String.valueOf(obj)); } @Override public void println() { logMessage(""); } @Override public void println(boolean x) { logMessage(String.valueOf(x)); } @Override public void println(char x) { logMessage(String.valueOf(x)); } @Override public void println(int x) { logMessage(String.valueOf(x)); } @Override public void println(long x) { logMessage(String.valueOf(x)); } @Override public void println(float x) { logMessage(String.valueOf(x)); } @Override public void println(double x) { logMessage(String.valueOf(x)); } @Override public void println(char[] x) { logMessage(String.valueOf(x)); } @Override public void println(String x) { logMessage(String.valueOf(x)); } @Override public void println(Object x) { logMessage(String.valueOf(x)); } @Override public PrintStream printf(String format, Object... args) { logMessage(String.format(format, args)); return this; } @Override public PrintStream printf(Locale l, String format, Object... args) { logMessage(String.format(l, format, args)); return this; } @Override public PrintStream format(String format, Object... args) { logMessage(String.format(format, args)); return this; } @Override public PrintStream format(Locale l, String format, Object... args) { logMessage(String.format(l, format, args)); return this; } @Override public PrintStream append(CharSequence csq) { logMessage(String.valueOf(csq)); return this; } @Override public PrintStream append(CharSequence csq, int start, int end) { logMessage(String.valueOf(csq).substring(start, end)); return this; } @Override public PrintStream append(char c) { logMessage(String.valueOf(c)); return this; } private void logMessage(String message) { if (not(ignore).matches(message)) logger.log(consoleLog(type, message)); } }
Domiii/code-dbgs
dbux-babel-plugin/src/parse/ObjectExpression.js
<reponame>Domiii/code-dbgs<filename>dbux-babel-plugin/src/parse/ObjectExpression.js import TraceType from '@dbux/common/src/types/constants/TraceType'; import EmptyArray from '@dbux/common/src/util/EmptyArray'; import { buildObjectExpression } from '../instrumentation/builders/objects'; import BaseNode from './BaseNode'; /** * Convert: `{ a, b: 3, ...spread1, [c]() {}, [d]: f(), ...spread2 }` * To: `toe([['a', a], ['b', 3], spread1, ['c', function () {}], [d, f()], spread2], tids)` */ export default class ObjectExpression extends BaseNode { static children = ['properties']; // /** // * Whether this OE is ES5. // * Cannot have `SpreadElement`, `ObjectMethod`, `computed` or `shorthand` properties. // * If `true`, can be instrument without reshaping. // */ // isES5() { // const [properties] = this.getChildPaths(); // return !properties.some( // el => el.isSpreadElement() || el.isObjectMethod() || el.node.computed || el.node.shorthand // ); // } /** * Takes a an array of arguments to indicate which are `SpreadElement` and which not. * * NOTE: This is used by `ObjectExpression`. */ makeArgsCfg(propertyPaths) { return propertyPaths?.map((propPath) => ({ key: propPath.node.key, isSpread: propPath.isSpreadElement(), kind: propPath.node.kind })) || EmptyArray; } // enter() { // console.error('OE disabled', this.path.getData('disabled'), this.path._traverseFlags); // } exit() { // if (!this.isES5()) { // this.warn(`Cannot properly instrument non-es5 ObjectExpression syntax yet: ${this}`); // return; // } const { path } = this; const [propertyPaths] = this.getChildPaths(); const traceData = { path, node: this, staticTraceData: { type: TraceType.ExpressionResult, dataNode: { isNew: true }, data: { argConfigs: this.makeArgsCfg(propertyPaths) } }, meta: { build: buildObjectExpression } }; const inputs = propertyPaths; this.Traces.addTraceWithInputs(traceData, inputs); } }
noriHanda/study_matching
account/migrations/0003_auto_20190905_1212.py
# Generated by Django 2.2.4 on 2019-09-05 03:12 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('account', '0002_auto_20190905_0205'), ] operations = [ migrations.AddField( model_name='user', name='department', field=models.TextField(blank=True, max_length=50, verbose_name='department'), ), migrations.AddField( model_name='user', name='faculty', field=models.TextField(blank=True, max_length=50, verbose_name='faculty'), ), migrations.AddField( model_name='user', name='hobby', field=models.TextField(blank=True, max_length=200, verbose_name='hobby'), ), migrations.AddField( model_name='user', name='school_year', field=models.PositiveIntegerField(blank=True, null=True, verbose_name='school year'), ), migrations.AddField( model_name='user', name='want_to_know', field=models.TextField(blank=True, max_length=400, verbose_name='what want to know'), ), migrations.AddField( model_name='user', name='want_to_teach', field=models.TextField(blank=True, max_length=400, verbose_name='what want to teach'), ), ]
doolse/Equella
Source/Plugins/Core/com.equella.core/src/com/tle/web/viewitem/viewer/GoogleDocViewerConfigDialog.java
<gh_stars>0 /* * Copyright 2017 Apereo * * 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.tle.web.viewitem.viewer; import com.tle.web.sections.SectionResult; import com.tle.web.sections.SectionTree; import com.tle.web.sections.SectionUtils; import com.tle.web.sections.equella.annotation.PlugKey; import com.tle.web.sections.equella.viewers.AbstractNewWindowConfigDialog; import com.tle.web.sections.events.RenderContext; import com.tle.web.sections.events.RenderEventContext; import com.tle.web.sections.generic.AbstractPrototypeSection; import com.tle.web.sections.render.HtmlRenderer; import com.tle.web.sections.render.Label; import com.tle.web.sections.render.LabelRenderer; import com.tle.web.sections.render.TextLabel; import com.tle.web.sections.result.util.KeyLabel; import com.tle.web.sections.standard.dialog.model.DialogControl; import com.tle.web.sections.standard.model.HtmlLinkState; import com.tle.web.sections.standard.model.SimpleBookmark; import com.tle.web.sections.standard.renderers.LinkRenderer; /** @author larry */ @SuppressWarnings("nls") public class GoogleDocViewerConfigDialog extends AbstractNewWindowConfigDialog { /** * Keys to the locale-specific strings in i18n.properties. The URLs are are also stored as * locale-specific properties. */ @PlugKey("googledoc.tos.url.label") private static Label LABEL_TOS_LINK; @PlugKey("googledoc.tos.text") private static String KEY_TOS_TEXT; @PlugKey("googledocviewer") private static Label LABEL_TITLE; @Override public String getHeight() { return "auto"; } @Override public void registered(String id, SectionTree tree) { super.registered(id, tree); TermsOfServiceText renderedLink = new TermsOfServiceText(LABEL_TOS_LINK, KEY_TOS_TEXT); tree.registerInnerSection(renderedLink, id); controls.add(new DialogControl(new TextLabel(""), renderedLink)); } @Override protected Label getTitleLabel(RenderContext context) { return LABEL_TITLE; } } @SuppressWarnings("nls") class TermsOfServiceText extends AbstractPrototypeSection<Object> implements HtmlRenderer { /** Link to the text of the Google Docs Terms of Service, presumed to be unchanging. */ private static final String GOOGLEDOC_TOS_URL = "http://docs.google.com/viewer/TOS?"; private final Label tosLinkLabel; private final String tosTextKey; public TermsOfServiceText(Label tosLinkLabel, String tosTextKey) { this.tosLinkLabel = tosLinkLabel; this.tosTextKey = tosTextKey; } @Override public SectionResult renderHtml(RenderEventContext context) { SimpleBookmark bookmark = new SimpleBookmark(GOOGLEDOC_TOS_URL); HtmlLinkState htmlLinkState = new HtmlLinkState(tosLinkLabel, bookmark); htmlLinkState.setTarget("_blank"); LinkRenderer linkRenderer = new LinkRenderer(htmlLinkState); LabelRenderer labelRenderer = new LabelRenderer( new KeyLabel(tosTextKey, SectionUtils.renderToString(context, linkRenderer))); return labelRenderer; } }
fr1tz/alux3d
Engine/source/sfx/sfxTypes.cpp
// Copyright information can be found in the file named COPYING // located in the root directory of this distribution. #include "sfx/sfxTypes.h" #include "sfx/sfxDescription.h" #include "sfx/sfxTrack.h" #include "sfx/sfxEnvironment.h" #include "sfx/sfxState.h" #include "sfx/sfxAmbience.h" #include "sfx/sfxSource.h" #include "core/stringTable.h" #include "core/stream/bitStream.h" #include "platform/typetraits.h" //RDTODO: find a more optimal way to transmit names rather than using full // strings; don't know how to facilitate NetStrings for this as we don't // have access to the connection template< class T > inline void sWrite( BitStream* stream, T* ptr ) { if( stream->writeFlag( ptr != NULL ) ) { if( stream->writeFlag( ptr->isClientOnly() ) ) stream->writeString( ptr->getName() ); else stream->writeRangedU32( ptr->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast ); } } template< class T > inline void sRead( BitStream* stream, T** ptr ) { if( !stream->readFlag() ) *ptr = NULL; else { if( stream->readFlag() ) { StringTableEntry name = stream->readSTString(); AssertFatal( !( U32( name ) & 0x1 ), "sRead - misaligned pointer" ); // StringTableEntry pointers are always word-aligned. *( ( StringTableEntry* ) ptr ) = name; } else *reinterpret_cast< U32* >( ptr ) = ( stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast ) << 1 ) | 0x1; } } template< class T > inline bool sResolve( T** ptr, String& errorString ) { if( !*ptr ) return true; else if( *reinterpret_cast< U32* >( ptr ) & 0x1 ) { U32 id = *reinterpret_cast< U32* >( ptr ) >> 1; T* p; if( !Sim::findObject( id, p ) ) { errorString = String::ToString( "sfxResolve - Could not resolve networked %s datalock with id '%i'", T::getStaticClassRep()->getClassName(), id ); *ptr = NULL; return false; } *ptr = p; } else { StringTableEntry name = *( ( StringTableEntry* ) ptr ); T* p; if( !Sim::findObject( name, p ) ) { errorString = String::ToString( "sfxResolve - Could not resolve local %s datablock with name '%s'", T::getStaticClassRep()->getClassName(), name ); *ptr = NULL; return false; } *ptr = p; } return true; } //============================================================================= // TypeSFXSourceName. //============================================================================= ConsoleType( SFXSource, TypeSFXSourceName, SFXSource* ) ConsoleGetType( TypeSFXSourceName ) { SFXSource** obj = ( SFXSource** ) dptr; if( !*obj ) return ""; else return Con::getReturnBuffer( ( *obj )->getName() ); } ConsoleSetType( TypeSFXSourceName ) { if( argc == 1 ) { SFXSource** obj = ( SFXSource**) dptr; Sim::findObject( argv[ 0 ], *obj ); } else Con::printf("(TypeSFXSourceName) Cannot set multiple args to a single SFXSource."); } //============================================================================= // TypeSFXParameterName. //============================================================================= ConsoleType( string, TypeSFXParameterName, StringTableEntry ) ConsoleGetType( TypeSFXParameterName ) { return *( ( const char** ) dptr ); } ConsoleSetType( TypeSFXParameterName ) { if( argc == 1 ) *( ( const char** ) dptr ) = StringTable->insert( argv[ 0 ] ); else Con::errorf( "(TypeSFXParameterName) Cannot set multiple args to a single SFXParameter." ); } //============================================================================= // TypeSFXDescriptionName. //============================================================================= ConsoleType( SFXDescription, TypeSFXDescriptionName, SFXDescription* ) ConsoleSetType( TypeSFXDescriptionName ) { if( argc == 1 ) { SFXDescription* description; Sim::findObject( argv[ 0 ], description ); *( ( SFXDescription** ) dptr ) = description; } else Con::errorf( "(TypeSFXDescriptionName) Cannot set multiple args to a single SFXDescription."); } ConsoleGetType( TypeSFXDescriptionName ) { SFXDescription* description = *( ( SFXDescription** ) dptr ); if( !description || !description->getName() ) return ""; else return description->getName(); } //============================================================================= // TypeSFXTrackName. //============================================================================= ConsoleType( SFXTrack, TypeSFXTrackName, SFXTrack* ) ConsoleSetType( TypeSFXTrackName ) { if( argc == 1 ) { SFXTrack* track; Sim::findObject( argv[ 0 ], track ); *( ( SFXTrack** ) dptr ) = track; } else Con::errorf( "(TypeSFXTrackName) Cannot set multiple args to a single SFXTrack."); } ConsoleGetType( TypeSFXTrackName ) { SFXTrack* track = *( ( SFXTrack** ) dptr ); if( !track || !track->getName() ) return ""; else return track->getName(); } //============================================================================= // TypeSFXEnvironmentName. //============================================================================= ConsoleType( SFXEnvironment, TypeSFXEnvironmentName, SFXEnvironment* ) ConsoleSetType( TypeSFXEnvironmentName ) { if( argc == 1 ) { SFXEnvironment* environment; Sim::findObject( argv[ 0 ], environment ); *( ( SFXEnvironment** ) dptr ) = environment; } else Con::errorf( "(TypeSFXEnvironmentName) Cannot set multiple args to a single SFXEnvironment."); } ConsoleGetType( TypeSFXEnvironmentName ) { SFXEnvironment* environment = *( ( SFXEnvironment** ) dptr ); if( !environment || !environment->getName() ) return ""; else return environment->getName(); } //============================================================================= // TypeSFXStateName. //============================================================================= ConsoleType( SFXState, TypeSFXStateName, SFXState* ) ConsoleSetType( TypeSFXStateName ) { if( argc == 1 ) { SFXState* state; Sim::findObject( argv[ 0 ], state ); *( ( SFXState** ) dptr ) = state; } else Con::errorf( "(TypeSFXStateName) Cannot set multiple args to a single SFXState."); } ConsoleGetType( TypeSFXStateName ) { SFXState* state = *( ( SFXState** ) dptr ); if( !state || !state->getName() ) return ""; else return state->getName(); } //============================================================================= // TypeSFXAmbienceName. //============================================================================= ConsoleType( SFXAmbience, TypeSFXAmbienceName, SFXAmbience* ) ConsoleSetType( TypeSFXAmbienceName ) { if( argc == 1 ) { SFXAmbience* ambience; Sim::findObject( argv[ 0 ], ambience ); *( ( SFXAmbience** ) dptr ) = ambience; } else Con::errorf( "(TypeSFXAmbienceName) Cannot set multiple args to a single SFXAmbience."); } ConsoleGetType( TypeSFXAmbienceName ) { SFXAmbience* ambience = *( ( SFXAmbience** ) dptr ); if( !ambience || !ambience->getName() ) return ""; else return ambience->getName(); } //============================================================================= // I/O. //============================================================================= //----------------------------------------------------------------------------- void sfxWrite( BitStream* stream, SFXSource* source ) { if( stream->writeFlag( source != NULL ) ) stream->writeString( source->getName() ); } //----------------------------------------------------------------------------- void sfxWrite( BitStream* stream, SFXDescription* description ) { sWrite( stream, description ); } //----------------------------------------------------------------------------- void sfxWrite( BitStream* stream, SFXTrack* track ) { sWrite( stream, track ); } //----------------------------------------------------------------------------- void sfxWrite( BitStream* stream, SFXEnvironment* environment ) { sWrite( stream, environment ); } //----------------------------------------------------------------------------- void sfxWrite( BitStream* stream, SFXState* state ) { sWrite( stream, state ); } //----------------------------------------------------------------------------- void sfxWrite( BitStream* stream, SFXAmbience* ambience ) { sWrite( stream, ambience ); } //----------------------------------------------------------------------------- void sfxRead( BitStream* stream, SFXDescription** description ) { sRead( stream, description ); } //----------------------------------------------------------------------------- void sfxRead( BitStream* stream, SFXTrack** track ) { sRead( stream, track ); } //----------------------------------------------------------------------------- void sfxRead( BitStream* stream, SFXEnvironment** environment ) { sRead( stream, environment ); } //----------------------------------------------------------------------------- void sfxRead( BitStream* stream, SFXState** state ) { sRead( stream, state ); } //----------------------------------------------------------------------------- void sfxRead( BitStream* stream, SFXAmbience** ambience ) { sRead( stream, ambience ); } //----------------------------------------------------------------------------- bool sfxResolve( SFXDescription** description, String& errorString ) { return sResolve( description, errorString ); } //----------------------------------------------------------------------------- bool sfxResolve( SFXTrack** track, String& errorString ) { return sResolve( track, errorString ); } //----------------------------------------------------------------------------- bool sfxResolve( SFXEnvironment** environment, String& errorString ) { return sResolve( environment, errorString ); } //----------------------------------------------------------------------------- bool sfxResolve( SFXState** state, String& errorString ) { return sResolve( state, errorString ); } //----------------------------------------------------------------------------- bool sfxResolve( SFXAmbience** ambience, String& errorString ) { return sResolve( ambience, errorString ); } //----------------------------------------------------------------------------- bool sfxReadAndResolve( BitStream* stream, SFXSource** source, String& errorString ) { if( !stream->readFlag() ) { *source = NULL; return true; } const char* name = stream->readSTString(); SFXSource* object; if( !Sim::findObject( name, object ) ) { errorString = String::ToString( "sfxReadAndResolve - no SFXSource '%s'", name ); return false; } *source = object; return true; }
maurizioabba/rose
projects/simulator/syscall_tests/syscall_sa.122.03.c
#include <errno.h> #include <sys/utsname.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <err.h> char *TCID = "syscall.122"; int TST_TOTAL = 1; int main(int ac, char **av) { struct utsname *buf; if ((buf = (struct utsname *)malloc((size_t) sizeof(struct utsname))) == NULL) err(1,"malloc failed"); int result = uname(buf); if( result != 0 ) err(1,"uname failed"); free(buf); buf = NULL; return 0; }
larynx95/DART.IMT.C
2311_search.c
<filename>2311_search.c // https://codecast.france-ioi.org/v6/player?stepperControls=_undo,_redo,_expr,_out,_over&base=https%3A%2F%2Ffioi-recordings.s3.amazonaws.com%2Fdartmouth%2F1518608621712 #include <stdio.h> int main(void) { //! showArray(list, cursors=[i]) int list[] = {6, -2, 5, 12, 7, 3, 8, 18, -10, 1}; int n = 10; int item, i, found; printf("Which number are you looking for? "); scanf("%d", &item); found = 0; i = 0; while (!found && i < n) { if (item == list[i]) { found = 1; } else { i++; } } if (!found) { printf("%d is not a member of this list. \n", item); } else { printf("I found %d at index %d in the list. \n", item, i); } return 0; }
eschnett/kotekan
lib/stages/ReadGain.cpp
#include "ReadGain.hpp" #include "Config.hpp" // for Config #include "StageFactory.hpp" // for REGISTER_KOTEKAN_STAGE, StageMakerTemplate #include "Telescope.hpp" // for Telescope, FREQ_ID_NOT_SET #include "buffer.h" // for mark_frame_full, register_producer, wait_for_empty_frame #include "configUpdater.hpp" // for configUpdater #include "kotekanLogging.hpp" // for WARN, INFO, DEBUG #include "restServer.hpp" // for HTTP_RESPONSE, connectionInstance, restServer #include "visUtil.hpp" // for current_time #include <algorithm> // for copy, copy_backward, equal, max #include <atomic> // for atomic_bool #include <chrono> // for seconds #include <cstdint> // for int32_t #include <deque> // for deque #include <exception> // for exception #include <functional> // for _Bind_helper<>::type, bind, _Placeholder, _1, function #include <memory> // for allocator_traits<>::value_type #include <regex> // for match_results<>::_Base_type #include <stdexcept> // for runtime_error #include <stdio.h> // for fclose, fopen, fread, snprintf, FILE #include <sys/types.h> // for uint using kotekan::bufferContainer; using kotekan::Config; using kotekan::configUpdater; using kotekan::Stage; using kotekan::connectionInstance; using kotekan::HTTP_RESPONSE; using kotekan::restServer; REGISTER_KOTEKAN_STAGE(ReadGain); // clang-format off // Request gain file re-parse with e.g. // FRB // curl localhost:12048/frb_gain -X POST -H 'Content-Type: appication/json' -d '{"frb_gain_dir":"the_new_path"}' // Tracking Beamformer // curl localhost:12048/updatable_config/tracking_gain -X POST -H 'Content-Type: application/json' -d // '{"tracking_gain_dir":["path0","path1","path2","path3","path4","path5","path6","path7","path8","path9"]}' // // clang-format on ReadGain::ReadGain(Config& config, const std::string& unique_name, bufferContainer& buffer_container) : Stage(config, unique_name, buffer_container, std::bind(&ReadGain::main_thread, this)), gains_last_update_success_metric(kotekan::prometheus::Metrics::instance().add_gauge( "kotekan_gains_last_update_success", unique_name, {"type"})), gains_last_update_timestamp_metric(kotekan::prometheus::Metrics::instance().add_gauge( "kotekan_gains_last_update_timestamp", unique_name, {"type", "beam_id"})) { // Apply config. _num_elements = config.get<uint32_t>(unique_name, "num_elements"); _num_beams = config.get<int32_t>(unique_name, "num_beams"); scaling = config.get_default<float>(unique_name, "frb_scaling", 1.0); vector<float> dg = {0.0, 0.0}; // re,im default_gains = config.get_default<std::vector<float>>(unique_name, "frb_missing_gains", dg); metadata_buf = get_buffer("in_buf"); register_consumer(metadata_buf, unique_name.c_str()); metadata_buffer_id = 0; metadata_buffer_precondition_id = 0; freq_idx = FREQ_ID_NOT_SET; freq_MHz = -1; // Gain for FRB gain_frb_buf = get_buffer("gain_frb_buf"); gain_frb_buf_id = 0; register_producer(gain_frb_buf, unique_name.c_str()); update_gains_frb = false; // Gain for Tracking Beamformer gain_tracking_buf = get_buffer("gain_tracking_buf"); gain_tracking_buf_id = 0; register_producer(gain_tracking_buf, unique_name.c_str()); update_gains_tracking = false; using namespace std::placeholders; // listen for gain updates FRB std::string gainfrb = config.get_default<std::string>(unique_name, "updatable_config/gain_frb", ""); if (gainfrb.length() > 0) configUpdater::instance().subscribe( gainfrb, std::bind(&ReadGain::update_gains_frb_callback, this, _1)); // Listen for gain updates Tracking Beamformer using namespace std::placeholders; for (int beam_id = 0; beam_id < _num_beams; beam_id++) { configUpdater::instance().subscribe( config.get<std::string>(unique_name, "updatable_config/gain_tracking") + "/" + std::to_string(beam_id), [beam_id, this](nlohmann::json& json_msg) -> bool { return update_gains_tracking_callback(json_msg, beam_id); }); } } bool ReadGain::update_gains_frb_callback(nlohmann::json& json) { if (update_gains_frb) { WARN("[FRB] cannot handle two back-to-back gain updates, rejecting the latter"); return true; } try { _gain_dir_frb = json.at("frb_gain_dir"); } catch (std::exception& e) { WARN("[FRB] Fail to read gain_dir {:s}", e.what()); return false; } { std::lock_guard<std::mutex> lock(mux); update_gains_frb = true; } cond_var.notify_all(); return true; } bool ReadGain::update_gains_tracking_callback(nlohmann::json& json, const uint8_t beam_id) { { std::lock_guard<std::mutex> lock(mux); try { _gain_dir_tracking.push( std::make_pair(beam_id, json.at("gain_dir").get<std::string>())); INFO("[Tracking Beamformer] Updating gains from {:s}", _gain_dir_tracking.back().second); } catch (std::exception const& e) { WARN("[Tracking Beamformer] Fail to read gain_dir {:s}", e.what()); return false; } update_gains_tracking = true; } cond_var.notify_all(); return true; } void ReadGain::read_gain_frb() { float* out_frame_frb = (float*)wait_for_empty_frame(gain_frb_buf, unique_name.c_str(), gain_frb_buf_id); if (out_frame_frb == nullptr) { return; } double start_time = current_time(); FILE* ptr_myfile; char filename[256]; snprintf(filename, sizeof(filename), "%s/quick_gains_%04d_reordered.bin", _gain_dir_frb.c_str(), freq_idx); INFO("FRB Loading gains from {:s}", filename); ptr_myfile = fopen(filename, "rb"); if (ptr_myfile == nullptr) { WARN("GPU Cannot open gain file {:s}", filename); gains_last_update_success_metric.labels({"frb"}).set(0); for (uint i = 0; i < _num_elements; i++) { out_frame_frb[i * 2] = default_gains[0] * scaling; out_frame_frb[i * 2 + 1] = default_gains[1] * scaling; } } else { if (_num_elements != fread(out_frame_frb, sizeof(float) * 2, _num_elements, ptr_myfile)) { WARN("Gain file ({:s}) wasn't long enough! Something went wrong, using default " "gains", filename); gains_last_update_success_metric.labels({"frb"}).set(0); for (uint i = 0; i < _num_elements; i++) { out_frame_frb[i * 2] = default_gains[0] * scaling; out_frame_frb[i * 2 + 1] = default_gains[1] * scaling; } } else { gains_last_update_success_metric.labels({"frb"}).set(1); } fclose(ptr_myfile); for (uint i = 0; i < _num_elements; i++) { out_frame_frb[i * 2] = out_frame_frb[i * 2] * scaling; out_frame_frb[i * 2 + 1] = out_frame_frb[i * 2 + 1] * scaling; } } gains_last_update_timestamp_metric.labels({"frb", ""}).set(start_time); mark_frame_full(gain_frb_buf, unique_name.c_str(), gain_frb_buf_id); DEBUG("Maked gain_frb_buf frame {:d} full", gain_frb_buf_id); INFO("Time required to load FRB gains: {:f}", current_time() - start_time); DEBUG("Gain_frb_buf: {:.2f} {:.2f} {:.2f} ", out_frame_frb[0], out_frame_frb[1], out_frame_frb[2]); gain_frb_buf_id = (gain_frb_buf_id + 1) % gain_frb_buf->num_frames; } void ReadGain::read_gain_tracking() { float* out_frame_tracking = (float*)wait_for_empty_frame(gain_tracking_buf, unique_name.c_str(), gain_tracking_buf_id); if (out_frame_tracking == nullptr) { return; } double start_time = current_time(); FILE* ptr_myfile; char filename[256]; std::pair<uint8_t, std::string> beam; while (_gain_dir_tracking.size() > 0) { { std::lock_guard<std::mutex> lock(mux); beam = _gain_dir_tracking.front(); _gain_dir_tracking.pop(); } uint8_t beam_id = beam.first; snprintf(filename, sizeof(filename), "%s/quick_gains_%04d_reordered.bin", beam.second.c_str(), freq_idx); INFO("Tracking Beamformer Loading gains from {:s}", filename); ptr_myfile = fopen(filename, "rb"); std::string beam_label = "tracking_beam_" + std::to_string(beam_id); gains_last_update_success_metric.labels({beam_label}).set(1); if (ptr_myfile == nullptr) { WARN("GPU Cannot open gain file {:s}", filename); gains_last_update_success_metric.labels({beam_label}).set(0); for (uint i = 0; i < _num_elements; i++) { out_frame_tracking[(beam_id * _num_elements + i) * 2] = default_gains[0]; out_frame_tracking[(beam_id * _num_elements + i) * 2 + 1] = default_gains[1]; } } else { if (_num_elements != fread(&out_frame_tracking[beam_id * _num_elements * 2], sizeof(float) * 2, _num_elements, ptr_myfile)) { WARN("Gain file ({:s}) wasn't long enough! Something went wrong, using default " "gains", filename); gains_last_update_success_metric.labels({beam_label}).set(0); for (uint i = 0; i < _num_elements; i++) { out_frame_tracking[(beam_id * _num_elements + i) * 2] = default_gains[0]; out_frame_tracking[(beam_id * _num_elements + i) * 2 + 1] = default_gains[1]; } } fclose(ptr_myfile); } gains_last_update_timestamp_metric.labels({"tracking", beam_label}).set(start_time); } // end beam mark_frame_full(gain_tracking_buf, unique_name.c_str(), gain_tracking_buf_id); DEBUG("Maked gain_tracking_buf frame {:d} full", gain_tracking_buf_id); INFO("Time required to load tracking beamformer gains: {:f}", current_time() - start_time); DEBUG("Gain_tracking_buf: {:.2f} {:.2f} {:.2f} ", out_frame_tracking[0], out_frame_tracking[1], out_frame_tracking[2]); gain_tracking_buf_id = (gain_tracking_buf_id + 1) % gain_tracking_buf->num_frames; } void ReadGain::main_thread() { uint8_t* frame = wait_for_full_frame(metadata_buf, unique_name.c_str(), metadata_buffer_precondition_id); if (frame == nullptr) return; auto& tel = Telescope::instance(); freq_idx = tel.to_freq_id(metadata_buf, metadata_buffer_id); freq_MHz = tel.to_freq(freq_idx); metadata_buffer_precondition_id = (metadata_buffer_precondition_id + 1) % metadata_buf->num_frames; mark_frame_empty(metadata_buf, unique_name.c_str(), metadata_buffer_id); metadata_buffer_id = (metadata_buffer_id + 1) % metadata_buf->num_frames; unregister_consumer(metadata_buf, unique_name.c_str()); while (!stop_thread) { { std::unique_lock<std::mutex> lock(mux); while (!update_gains_frb && !update_gains_tracking && !stop_thread) { cond_var.wait_for(lock, std::chrono::seconds(5)); } } if (stop_thread) break; if (update_gains_frb) { read_gain_frb(); update_gains_frb = false; } if (update_gains_tracking) { read_gain_tracking(); update_gains_tracking = false; } } }
willemt/yabtorrent
deps/meanqueue/meanqueue.h
<gh_stars>10-100 #ifndef MEANQUEUE_H #define MEANQUEUE_H typedef struct { int *vals; int size; int idxCur; int valSum; float mean; } meanqueue_t; /** * Create of queue of size 0 */ void *meanqueue_new( const int size ); void meanqueue_free( meanqueue_t * qu ); /** * Add an int to the queue. * If the queue can't hold all the ints, the oldest int is removed */ void meanqueue_offer( meanqueue_t * qu, const int val ); /** * @return mean of ints within queue */ float meanqueue_get_value( meanqueue_t * qu ); #endif /* MEANQUEUE_H */
nathanfaucett/ll-lang
src/Lexer.hpp
#ifndef __LL_LEXER_HPP__ #define __LL_LEXER_HPP__ namespace ll { class Token { public: String* value; uintsize row; uintsize column; Token(String* value, uintsize row, uintsize column); }; class Lexer { private: std::istream* _stream; uintsize _index; uintsize _row; uintsize _column; uintsize _token_index; std::vector<Token*> _tokens; int32 _read(void); int32 _peek(void); int32 _peek(uintsize index); bool _is_syntax(int32 ch); bool _is_alpha_numeric(int32 ch); Token* _create_token(String* string, bool peek); Token* _create_token(int32 ch, bool peek); Token* _read_char(int32 ch, bool peek); Token* _read_string(int32 ch, bool peek); Token* _read_number(int32 ch, bool peek); Token* _read_identifier(int32 ch, bool peek); Token* _next(bool peek); public: Lexer(std::istream* stream); Token* peek(intsize index); Token* peek(void); Token* next(void); }; } #endif
smo921/sis-api
test/v1.1-api/test-api-upsert.js
describe('@API @V1.1API - Upsert', function() { "use strict"; var should = require('should'); var BPromise = require('bluebird'); var SIS = require("../../util/constants"); var TestUtil = require('../fixtures/util'); var ApiServer = new TestUtil.TestServer(); it("Should setup fixtures", function(done) { ApiServer.start(function(e) { if (e) { return done(e); } ApiServer.becomeSuperUser(done); }); }); after(function(done) { ApiServer.stop(done); }); describe("Upsert schemas", function() { var schema = { name : "test_upsert_1", id_field : "name", _sis : { owner : ["sistest"] }, definition : { name : { type : "String", required : true, unique : true }, short_name : { type : "String", required : true, unique : true }, other : "String" } }; before(function(done) { ApiServer.del("/api/v1.1/schemas/test_upsert_1").end(done); }); it("Should insert the schema", function(done) { ApiServer.put("/api/v1.1/schemas/test_upsert_1") .query({ upsert : true }).send(schema) .expect(201, done); }); it("Should update the schema", function(done) { schema.id_field = 'short_name'; ApiServer.put("/api/v1.1/schemas/test_upsert_1") .query({ upsert : true }).send(schema) .expect(200, function(err, res) { if (err) { return done(err); } res.body.id_field.should.eql('short_name'); done(); }); }); it("Should not insert with mismatched IDs", function(done) { ApiServer.put("/api/v1.1/schemas/test_upsert_bad") .query({ upsert : true }).send(schema) .expect(400, done); }); }); describe("Upsert entities", function() { var schema = { name : "test_upsert_2", _sis : { owner : ["sistest"] }, definition : { name : { type : "String" }, short_name : { type : "String" }, other : "String" } }; before(function(done) { ApiServer.del("/api/v1.1/schemas/test_upsert_2") .end(function(err, res) { ApiServer.post("/api/v1.1/schemas").send(schema) .expect(201, done); }); }); it("Should fail to upsert with no id field", function(done) { var entity = { name : "foobar", short_name : "foobar_short", other : "foobar" }; ApiServer.put("/api/v1.1/entities/test_upsert_2/foobar") .query({ upsert : true }).send(entity).expect(400, done); }); it("Should upsert with an id field", function(done) { schema.id_field = 'name'; schema.definition.name.unique = true; schema.definition.name.required = true; var entity = { name : "foobar", short_name : "foobar_short", other : "foobar" }; ApiServer.put("/api/v1.1/schemas/test_upsert_2").send(schema) .expect(200, function(err, res) { should.not.exist(err); ApiServer.put("/api/v1.1/entities/test_upsert_2/foobar") .query({ upsert : true }).send(entity).expect(201, done); }); }); it("Should not upsert with mismatched ids", function(done) { var entity = { name : "foobar", short_name : "foobar_short", other : "foobar" }; ApiServer.put("/api/v1.1/entities/test_upsert_2/bar") .query({ upsert : true }).send(entity).expect(400, done); }); it("Should upsert if the id has dots", function(done) { var entity = { name : "foo.bar.baz", short_name: "foo.bar.short", other : "baz" }; ApiServer.put("/api/v1.1/entities/test_upsert_2/foo.bar.baz") .query({ upsert : true }).send(entity).expect(201, done); }); }); });
pointphoton/AndroidMVPTemplate
app/src/main/java/com/photon/templatemvp/data/mapper/GalleryModelCarCollectionMapper.java
<filename>app/src/main/java/com/photon/templatemvp/data/mapper/GalleryModelCarCollectionMapper.java package com.photon.templatemvp.data.mapper; import com.photon.templatemvp.data.model.gallery.Person; import com.photon.templatemvp.data.model.gallery.Properties; import com.photon.templatemvp.di.PerActivity; import com.photon.templatemvp.data.model.gallery.GalleryModel; import com.photon.templatemvp.data.model.gallery.Car; import com.photon.templatemvp.util.DebugLog; import com.photon.templatemvp.util.Utils; import java.lang.annotation.Target; import java.util.Collection; import java.util.Collections; import java.util.List; import javax.inject.Inject; /** * Created by pointphoton on 21/05/2017. */ @PerActivity public class GalleryModelCarCollectionMapper { @Inject public GalleryModelCarCollectionMapper() {} /** * Transform a {@link GalleryModel} into a collection of {@link Car}. * * @param galleryModel Object to be transformed. * @return {@link Collection<Car>}. * @throws IllegalArgumentException if {@code model} is null * @throws NullPointerException if {@code the member(s) of the model} is null * @throws Exception */ public Collection<Car> transform(final GalleryModel galleryModel) throws Exception{ if (galleryModel == null) { DebugLog.write(); throw new IllegalArgumentException("Cannot transform a null " + GalleryModel.class.getSimpleName()); } DebugLog.write(); Properties properties = Utils.checkNotNull(galleryModel.getProperties(), Properties.class.getSimpleName()); Person person = Utils.checkNotNull(properties.getPerson()); List<Car> cars = Utils.checkNotNull(person.getCars()); return cars; } }
jackhumbert/RED4ext.SDK
include/RED4ext/Scripting/Natives/Generated/physics/PhysicsJointLinearLimit.hpp
<reponame>jackhumbert/RED4ext.SDK<filename>include/RED4ext/Scripting/Natives/Generated/physics/PhysicsJointLinearLimit.hpp<gh_stars>10-100 #pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/Scripting/Natives/Generated/physics/PhysicsJointLimitBase.hpp> #include <RED4ext/Scripting/Natives/Generated/physics/PhysicsJointMotion.hpp> namespace RED4ext { namespace physics { struct PhysicsJointLinearLimit : physics::PhysicsJointLimitBase { static constexpr const char* NAME = "physicsPhysicsJointLinearLimit"; static constexpr const char* ALIAS = NAME; float value; // 20 physics::PhysicsJointMotion x; // 24 physics::PhysicsJointMotion y; // 25 physics::PhysicsJointMotion z; // 26 uint8_t unk27[0x28 - 0x27]; // 27 }; RED4EXT_ASSERT_SIZE(PhysicsJointLinearLimit, 0x28); } // namespace physics } // namespace RED4ext
amcp/janusgraph
janusgraph-cassandra/src/main/java/org/janusgraph/diskstorage/cassandra/thrift/thriftpool/CTConnection.java
<reponame>amcp/janusgraph // Copyright 2017 JanusGraph Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.janusgraph.diskstorage.cassandra.thrift.thriftpool; import org.apache.cassandra.thrift.Cassandra; import org.apache.cassandra.thrift.Cassandra.Client; import org.apache.thrift.transport.TTransport; import java.io.Closeable; /** * Wraps a {@code Cassandra.Client} instance, its underlying {@code TTransport} * instance, and the {@link org.janusgraph.diskstorage.cassandra.thrift.thriftpool.CTConnectionFactory.Config} instance used to setup * the connection. * * @see CTConnectionFactory * @see CTConnectionPool * @author <NAME> &lt;<EMAIL>&gt; */ public class CTConnection implements Closeable { private final TTransport transport; private final Cassandra.Client client; private final CTConnectionFactory.Config cfg; public CTConnection(TTransport transport, Client client, CTConnectionFactory.Config cfg) { this.transport = transport; this.client = client; this.cfg = cfg; } public TTransport getTransport() { return transport; } public Cassandra.Client getClient() { return client; } public CTConnectionFactory.Config getConfig() { return cfg; } public boolean isOpen() { return transport.isOpen(); } @Override public void close() { if (transport != null && transport.isOpen()) transport.close(); } @Override public String toString() { return "CTConnection [transport=" + transport + ", client=" + client + ", cfg=" + cfg + "]"; } }
evgenii-m/AudioPlayer
src/main/java/ru/push/caudioplayer/core/facades/dto/ImageSize.java
<gh_stars>0 package ru.push.caudioplayer.core.facades.dto; import java.util.Arrays; public enum ImageSize { SMALL("small"), MEDIUM("medium"), LARGE("large"), EXTRALARGE("extralarge"), UNKNOWN("") ; private String value; ImageSize(String value) { this.value = value; } public String getValue() { return value; } public static ImageSize fromValue(String value) { return (value != null) ? Arrays.stream(values()) .filter(v -> v.getValue().equals(value)) .findFirst().orElse(UNKNOWN) : null; } }
naeramarth7/joynr
java/messaging/messaging-common/src/main/java/io/joynr/messaging/util/MulticastWildcardRegexFactory.java
<reponame>naeramarth7/joynr<gh_stars>0 /* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package io.joynr.messaging.util; import java.util.regex.Pattern; import io.joynr.exceptions.JoynrIllegalStateException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MulticastWildcardRegexFactory { private static final Logger logger = LoggerFactory.getLogger(MulticastWildcardRegexFactory.class); public Pattern createIdPattern(String multicastId) { verifyMulticastIdValid(multicastId); String patternString = multicastId.replaceAll("^\\+(/)?", "[^\\/]+$1"); patternString = patternString.replaceAll("/\\+/", "/[^\\/]+/"); patternString = patternString.replaceAll("(.*)/[\\+]$", "$1/[^\\/]+\\$"); patternString = patternString.replaceAll("(.*)/[\\*]$", "$1(/.*)?\\$"); patternString = patternString.replaceAll("^\\*$", ".+"); logger.trace("Creating multicast ID regex pattern: {}", patternString); return Pattern.compile(patternString); } private void verifyMulticastIdValid(String multicastId) { boolean invalid = multicastId.matches(".*.[^/]\\+.*") || multicastId.matches(".*\\+[^/]+.*") || (!"*".equals(multicastId) && multicastId.contains("*") && !multicastId.matches(".*/\\*$")); if (invalid) { throw new JoynrIllegalStateException("Multicast IDs may only contain '+' as a placeholder for a partition, and '*' as only character or right at the end after a '/'. You passed in: " + multicastId); } } }
yfpeng/pengyifan-commons
src/test/java/com/pengyifan/util/regex/RegExTest.java
<filename>src/test/java/com/pengyifan/util/regex/RegExTest.java package com.pengyifan.util.regex; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.*; public class RegExTest { @Test public void test() throws IOException { String patternStr = "a"; String str = "axa"; RegExpPattern pattern = RegExpPattern.compile(patternStr); RegExpMatcher matcher = pattern.matcher(str); assertTrue(matcher.find()); assertPattern(0, patternStr, matcher); assertTrue(matcher.find()); assertPattern(2, patternStr, matcher); assertFalse(matcher.find()); } private void assertPattern(int nPos, String strPattern, RegExpMatcher matcher) { assertEquals(nPos, matcher.start()); assertEquals(strPattern, matcher.group()); } @Test public void test2() throws IOException { String patternStr = "ab"; String str = "abxxbab"; RegExpPattern pattern = RegExpPattern.compile(patternStr); RegExpMatcher matcher = pattern.matcher(str); assertTrue(matcher.find()); assertPattern(0, patternStr, matcher); assertTrue(matcher.find()); assertPattern(5, patternStr, matcher); assertFalse(matcher.find()); } @Test public void test3() throws IOException { String patternStr = "abc"; String str = "xxabcxx"; RegExpPattern pattern = RegExpPattern.compile(patternStr); RegExpMatcher matcher = pattern.matcher(str); assertTrue(matcher.find()); assertPattern(2, patternStr, matcher); assertFalse(matcher.find()); } @Test public void test4() throws IOException { String patternStr = "(a|c)"; String str = "xxabcxx"; RegExpPattern pattern = RegExpPattern.compile(patternStr); RegExpMatcher matcher = pattern.matcher(str); assertTrue(matcher.find()); assertPattern(2, "a", matcher); assertTrue(matcher.find()); assertPattern(4, "c", matcher); assertFalse(matcher.find()); } @Test public void test5() throws IOException { String patternStr = "(a|c)b"; String str = "xxabxcbxx"; RegExpPattern pattern = RegExpPattern.compile(patternStr); // patterns.writeDfaGraph(Paths.get("dfa.gv")); RegExpMatcher matcher = pattern.matcher(str); assertTrue(matcher.find()); assertPattern(2, "ab", matcher); assertTrue(matcher.find()); assertPattern(5, "cb", matcher); assertFalse(matcher.find()); } }
laffer1/justjournal
src/main/java/com/justjournal/ctl/api/JournalController.java
/* * Copyright (c) 2003-2021 <NAME> * 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 AUTHOR 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 AUTHOR 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 com.justjournal.ctl.api; import com.justjournal.Login; import com.justjournal.core.Constants; import com.justjournal.ctl.error.ErrorHandler; import com.justjournal.model.Journal; import com.justjournal.model.Style; import com.justjournal.model.api.JournalTo; import com.justjournal.repository.JournalRepository; import com.justjournal.repository.UserRepository; import com.justjournal.services.StyleService; import java.util.Calendar; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; /** * Manage individual journals * * @author <NAME> */ @Slf4j @RestController @RequestMapping("/api/journal") public class JournalController { private final JournalRepository journalRepository; private final UserRepository userRepository; private final StyleService styleService; @Autowired public JournalController( final JournalRepository journalRepository, final UserRepository userRepository, final StyleService styleService) { this.journalRepository = journalRepository; this.userRepository = userRepository; this.styleService = styleService; } @GetMapping(value = "user/{username}", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public ResponseEntity<List<Journal>> listByUser( @PathVariable(Constants.PARAM_USERNAME) final String username) { try { return ResponseEntity.ok(journalRepository.findByUsername(username)); } catch (final Exception e) { log.error(e.getMessage(), e); } return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } @GetMapping(value = "{slug}", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public ResponseEntity<Journal> get(@PathVariable("slug") final String slug) { try { return ResponseEntity.ok(journalRepository.findOneBySlug(slug)); } catch (final Exception e) { log.error(e.getMessage(), e); } return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } @PostMapping( value = "", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Map<String, String> post( @RequestBody final JournalTo journal, final HttpSession session, final HttpServletResponse response) { return put(journal.getSlug(), journal, session, response); } @PutMapping( value = "{slug}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Map<String, String> put( @PathVariable("slug") final String slug, @RequestBody JournalTo journalTo, final HttpSession session, final HttpServletResponse response) { if (!Login.isAuthenticated(session)) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return ErrorHandler.modelError(Constants.ERR_INVALID_LOGIN); } try { Journal j = journalRepository.findOneBySlug(slug); if (j == null) { Journal journal = new Journal(); journal.setId(journalTo.getId()); journal.setAllowSpider(journalTo.isAllowSpider()); journal.setSlug(journalTo.getSlug()); journal.setName(journalTo.getName()); journal.setStyleId(journalTo.getStyleId()); final Style s = styleService.get(journal.getStyleId()); journal.setStyle(s); journal.setOwnerViewOnly(journalTo.isOwnerViewOnly()); journal.setPingServices(journalTo.isPingServices()); journal.setUser(userRepository.findById(Login.currentLoginId(session)).orElse(null)); journal.setSince(Calendar.getInstance().getTime()); journal.setModified(Calendar.getInstance().getTime()); journal = journalRepository.saveAndFlush(journal); response.setStatus(HttpServletResponse.SC_CREATED); return java.util.Collections.singletonMap("slug", journal.getSlug()); } if (j.getUser().getId() != Login.currentLoginId(session)) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return ErrorHandler.modelError("You do not have permission to update this journal."); } j.setAllowSpider(journalTo.isAllowSpider()); j.setName(journalTo.getName()); j.setOwnerViewOnly(journalTo.isOwnerViewOnly()); j.setPingServices(journalTo.isPingServices()); if (journalTo.getStyleId() > 0) { final Style s = styleService.get(journalTo.getStyleId()); j.setStyle(s); } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return ErrorHandler.modelError("Missing style id."); } j.setModified(Calendar.getInstance().getTime()); j = journalRepository.saveAndFlush(j); return java.util.Collections.singletonMap("slug", j.getSlug()); } catch (final Exception e) { log.error(e.getMessage(), e); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return ErrorHandler.modelError("Error adding journal."); } } @DeleteMapping(value = "{slug}", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Map<String, String> delete( @PathVariable("slug") final String slug, final HttpSession session, final HttpServletResponse response) { if (!Login.isAuthenticated(session)) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return ErrorHandler.modelError(Constants.ERR_INVALID_LOGIN); } if (slug == null || slug.isEmpty()) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return ErrorHandler.modelError("Error deleting your journal. Slug is missing."); } final Journal journal = journalRepository.findOneBySlug(slug); if (journal == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return ErrorHandler.modelError("Error deleting your journal. Slug not found."); } if (journal.getUser().getId() != Login.currentLoginId(session)) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return ErrorHandler.modelError("You do not have permission to delete this journal."); } journalRepository.delete(journal); journalRepository.flush(); return java.util.Collections.singletonMap("slug", journal.getSlug()); } }
zipated/src
third_party/blink/renderer/platform/text/quoted_printable.cc
<reponame>zipated/src /* * Copyright (C) 2011 Google 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 Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "third_party/blink/renderer/platform/text/quoted_printable.h" #include "third_party/blink/renderer/platform/wtf/ascii_ctype.h" namespace blink { static size_t LengthOfLineEndingAtIndex(const char* input, size_t input_length, size_t index) { SECURITY_DCHECK(index < input_length); if (input[index] == '\n') return 1; // Single LF. if (input[index] == '\r') { if ((index + 1) == input_length || input[index + 1] != '\n') return 1; // Single CR (Classic Mac OS). return 2; // CR-LF. } return 0; } void QuotedPrintableEncode(const char* input, size_t input_length, QuotedPrintableEncodeDelegate* delegate, Vector<char>& out) { out.clear(); out.ReserveCapacity(input_length); delegate->DidStartLine(out); size_t current_line_length = 0; for (size_t i = 0; i < input_length; ++i) { bool is_last_character = (i == input_length - 1); char current_character = input[i]; bool requires_encoding = false; // All non-printable ASCII characters and = require encoding. if ((current_character < ' ' || current_character > '~' || current_character == '=') && current_character != '\t') requires_encoding = true; // Decide if space and tab characters need to be encoded. if (!requires_encoding && (current_character == '\t' || current_character == ' ')) { bool end_of_line = is_last_character || LengthOfLineEndingAtIndex(input, input_length, i + 1); requires_encoding = delegate->ShouldEncodeWhiteSpaceCharacters(end_of_line); } // End of line should be converted to CR-LF sequences. if (!is_last_character) { size_t length_of_line_ending = LengthOfLineEndingAtIndex(input, input_length, i); if (length_of_line_ending) { out.Append("\r\n", 2); current_line_length = 0; i += (length_of_line_ending - 1); // -1 because we'll ++ in the for() above. continue; } } size_t length_of_encoded_character = 1; if (requires_encoding) length_of_encoded_character += 2; if (!is_last_character) length_of_encoded_character += 1; // + 1 for the = (soft line break). // Insert a soft line break if necessary. if (current_line_length + length_of_encoded_character > delegate->GetMaxLineLengthForEncodedContent()) { delegate->DidFinishLine(false /*last_line*/, out); current_line_length = 0; delegate->DidStartLine(out); } // Finally, insert the actual character(s). if (requires_encoding) { out.push_back('='); out.push_back(UpperNibbleToASCIIHexDigit(current_character)); out.push_back(LowerNibbleToASCIIHexDigit(current_character)); current_line_length += 3; } else { out.push_back(current_character); current_line_length++; } } delegate->DidFinishLine(true /*last_line*/, out); } void QuotedPrintableDecode(const Vector<char>& in, Vector<char>& out) { QuotedPrintableDecode(in.data(), in.size(), out); } void QuotedPrintableDecode(const char* data, size_t data_length, Vector<char>& out) { out.clear(); if (!data_length) return; for (size_t i = 0; i < data_length; ++i) { char current_character = data[i]; if (current_character != '=') { out.push_back(current_character); continue; } // We are dealing with a '=xx' sequence. if (data_length - i < 3) { // Unfinished = sequence, append as is. out.push_back(current_character); continue; } char upper_character = data[++i]; char lower_character = data[++i]; if (upper_character == '\r' && lower_character == '\n') continue; if (!IsASCIIHexDigit(upper_character) || !IsASCIIHexDigit(lower_character)) { // Invalid sequence, = followed by non hex digits, just insert the // characters as is. out.push_back('='); out.push_back(upper_character); out.push_back(lower_character); continue; } out.push_back( static_cast<char>(ToASCIIHexValue(upper_character, lower_character))); } } } // namespace blink
build-test-conflicts/dynjs
src/main/java/org/dynjs/compiler/bytecode/AbstractBytecodeCompiler.java
package org.dynjs.compiler.bytecode; import java.io.PrintWriter; import me.qmx.jitescript.JDKVersion; import me.qmx.jitescript.JiteClass; import org.dynjs.Config; import org.dynjs.codegen.CodeGeneratingVisitor; import org.dynjs.codegen.CodeGeneratingVisitorFactory; import org.dynjs.runtime.BlockManager; import org.dynjs.runtime.DynamicClassLoader; import me.qmx.jitescript.internal.org.objectweb.asm.ClassReader; import me.qmx.jitescript.internal.org.objectweb.asm.util.CheckClassAdapter; public abstract class AbstractBytecodeCompiler { private Config config; private CodeGeneratingVisitorFactory factory; public AbstractBytecodeCompiler(Config config, CodeGeneratingVisitorFactory factory) { this.config = config; this.factory = factory; } public AbstractBytecodeCompiler(AbstractBytecodeCompiler parent) { this.config = parent.config; this.factory = parent.factory; } public Config getConfig() { return this.config; } public CodeGeneratingVisitorFactory getFactory() { return this.factory; } public CodeGeneratingVisitor createVisitor(BlockManager blockManager) { return this.factory.create(blockManager); } @SuppressWarnings("unchecked") protected <T> T defineClass(DynamicClassLoader classLoader, JiteClass jiteClass) { byte[] bytecode = jiteClass.toBytes(JDKVersion.V1_7); if (config.isDebug()) { ClassReader reader = new ClassReader(bytecode); CheckClassAdapter.verify(reader, true, new PrintWriter(System.out)); } return (T) classLoader.define(jiteClass.getClassName().replace('/', '.'), bytecode); } }
gaoht/house
java/classes2/com/ziroom/credit/main/CreditScoreAnalysisActivity.java
<gh_stars>1-10 package com.ziroom.credit.main; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.View; import android.widget.ImageView; import com.ziroom.credit.R.drawable; import com.ziroom.credit.R.id; import com.ziroom.credit.R.layout; import com.ziroom.credit.a.d; import com.ziroom.credit.base.CreditBaseActivity; import com.ziroom.credit.base.b; public class CreditScoreAnalysisActivity extends CreditBaseActivity { View d; private boolean e = true; private ViewPager f; private ImageView g; private ImageView h; private ImageView i; protected b b() { return null; } protected int c() { return R.layout.credit_activity_ziroom_scoreanalysis; } protected void d() { this.g = ((ImageView)findViewById(R.id.credit_analysis_ivone)); this.h = ((ImageView)findViewById(R.id.credit_analysis_ivtwo)); this.i = ((ImageView)findViewById(R.id.credit_analysis_ivthree)); this.f = ((ViewPager)findViewById(R.id.credit_analysis_vp)); this.d = findViewById(R.id.credit_bottom_line); this.d.setVisibility(8); this.g.setImageResource(R.drawable.credit_bg_credit_score_analysis_indicator_selected); this.h.setImageResource(R.drawable.credit_bg_credit_score_analysis_indicator_nomal); this.i.setImageResource(R.drawable.credit_bg_credit_score_analysis_indicator_nomal); this.f.setCurrentItem(0); this.f.setOffscreenPageLimit(3); setTitleText("自如分解读"); this.f.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { public void onPageScrollStateChanged(int paramAnonymousInt) {} public void onPageScrolled(int paramAnonymousInt1, float paramAnonymousFloat, int paramAnonymousInt2) {} public void onPageSelected(int paramAnonymousInt) { switch (paramAnonymousInt) { default: return; case 0: CreditScoreAnalysisActivity.a(CreditScoreAnalysisActivity.this).setImageResource(R.drawable.credit_bg_credit_score_analysis_indicator_selected); CreditScoreAnalysisActivity.b(CreditScoreAnalysisActivity.this).setImageResource(R.drawable.credit_bg_credit_score_analysis_indicator_nomal); CreditScoreAnalysisActivity.c(CreditScoreAnalysisActivity.this).setImageResource(R.drawable.credit_bg_credit_score_analysis_indicator_nomal); return; case 1: CreditScoreAnalysisActivity.a(CreditScoreAnalysisActivity.this).setImageResource(R.drawable.credit_bg_credit_score_analysis_indicator_nomal); CreditScoreAnalysisActivity.b(CreditScoreAnalysisActivity.this).setImageResource(R.drawable.credit_bg_credit_score_analysis_indicator_selected); CreditScoreAnalysisActivity.c(CreditScoreAnalysisActivity.this).setImageResource(R.drawable.credit_bg_credit_score_analysis_indicator_nomal); return; } CreditScoreAnalysisActivity.a(CreditScoreAnalysisActivity.this).setImageResource(R.drawable.credit_bg_credit_score_analysis_indicator_nomal); CreditScoreAnalysisActivity.b(CreditScoreAnalysisActivity.this).setImageResource(R.drawable.credit_bg_credit_score_analysis_indicator_nomal); CreditScoreAnalysisActivity.c(CreditScoreAnalysisActivity.this).setImageResource(R.drawable.credit_bg_credit_score_analysis_indicator_selected); } }); } protected void initData() { d locald = new d(getSupportFragmentManager()); this.f.setAdapter(locald); } } /* Location: /Users/gaoht/Downloads/zirom/classes2-dex2jar.jar!/com/ziroom/credit/main/CreditScoreAnalysisActivity.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
companionstudio/islay-shop
db/migrate/20130703024018_alter_skus_for_pricing_restructure.rb
class AlterSkusForPricingRestructure < ActiveRecord::Migration def up # Backup existing SKUs execute(%{ CREATE TABLE legacy_skus (LIKE skus INCLUDING INDEXES); INSERT INTO legacy_skus SELECT * FROM skus }) remove_column(:skus, :price) remove_column(:skus, :batch_size) remove_column(:skus, :batch_price) end def down add_column(:skus, :price, :float, :null => true, :precision => 7, :scale => 2) add_column(:skus, :batch_size, :integer, :null => true, :limit => 5) add_column(:skus, :batch_price, :float, :null => true, :precision => 7, :scale => 2) # Restore from backed up table execute(%{ UPDATE skus SET price = ls.price, batch_size = ls.batch_size, batch_price = ls.batch_price FROM legacy_skus AS ls WHERE ls.id = skus.id }) change_column_null(:skus, :price, false) # Removed the backup drop_table(:legacy_skus) end end
amolabs/amoabci
amo/tx/withdraw.go
package tx import ( "encoding/json" abci "github.com/tendermint/tendermint/abci/types" "github.com/amolabs/amoabci/amo/code" "github.com/amolabs/amoabci/amo/store" "github.com/amolabs/amoabci/amo/types" ) type WithdrawParam struct { Amount types.Currency `json:"amount"` } func parseWithdrawParam(raw []byte) (WithdrawParam, error) { var param WithdrawParam err := json.Unmarshal(raw, &param) if err != nil { return param, err } return param, nil } type TxWithdraw struct { TxBase Param WithdrawParam `json:"-"` } func (t *TxWithdraw) Check() (uint32, string) { // TODO: check format //txParam, err := parseWithdrawParam(t.Payload) _, err := parseWithdrawParam(t.getPayload()) if err != nil { return code.TxCodeBadParam, err.Error() } return code.TxCodeOK, "ok" } func (t *TxWithdraw) Execute(store *store.Store) (uint32, string, []abci.Event) { txParam, err := parseWithdrawParam(t.getPayload()) if err != nil { return code.TxCodeBadParam, err.Error(), nil } if !txParam.Amount.GreaterThan(zero) { return code.TxCodeInvalidAmount, "invalid amount", nil } stake := store.GetStake(t.GetSender(), false) if stake == nil { return code.TxCodeNoStake, "no stake", nil } // this is just for rich error reporting if stake.Amount.Sub(&txParam.Amount).Sign() == -1 { return code.TxCodeNotEnoughBalance, "not enough stake", nil } // total stake for this account is enough for withdrawal, but not unlocked // stake. unlocked := store.GetUnlockedStake(t.GetSender(), false) if unlocked == nil || unlocked.Amount.Sub(&txParam.Amount).Sign() == -1 { return code.TxCodeStakeLocked, "stake locked", nil } if err := store.SetUnlockedStake(t.GetSender(), unlocked); err != nil { switch err { case code.GetError(code.TxCodeBadParam): return code.TxCodeBadParam, err.Error(), nil case code.GetError(code.TxCodePermissionDenied): return code.TxCodePermissionDenied, err.Error(), nil case code.GetError(code.TxCodeDelegateExists): return code.TxCodeDelegateExists, err.Error(), nil case code.GetError(code.TxCodeLastValidator): return code.TxCodeLastValidator, err.Error(), nil default: return code.TxCodeUnknown, err.Error(), nil } } balance := store.GetBalance(t.GetSender(), false) balance.Add(&txParam.Amount) store.SetBalance(t.GetSender(), balance) return code.TxCodeOK, "ok", nil }
hellopanda128/main
src/main/java/seedu/address/ui/VehicleCard.java
package seedu.address.ui; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.layout.HBox; import javafx.scene.layout.Region; import seedu.address.model.vehicle.Vehicle; /** * An UI component that displays information of a {@code Vehicle}. */ public class VehicleCard extends UiPart<Region> { private static final String FXML = "VehicleListCard.fxml"; /** * Note: Certain keywords such as "location" and "resources" are reserved keywords in JavaFX. * As a consequence, UI elements' variable names cannot be set to such keywords * or an exception will be thrown by JavaFX during runtime. */ public final Vehicle vehicle; @FXML private HBox cardPane; @FXML private Label id; @FXML private Label vehicleNumber; @FXML private Label vehicleType; @FXML private Label district; @FXML private Label availability; public VehicleCard(Vehicle vehicle, int displayedIndex) { super(FXML); this.vehicle = vehicle; id.setText(displayedIndex + ". "); vehicleNumber.setText(vehicle.getVehicleNumber().toString()); vehicleType.setText(vehicle.getVehicleType().toString()); district.setText("District: " + String.valueOf(vehicle.getDistrict().getDistrictNum())); availability.setText("Availability: " + vehicle.getAvailability().getAvailabilityTag()); } @Override public boolean equals(Object other) { // short circuit if same object if (other == this) { return true; } // instanceof handles nulls if (!(other instanceof VehicleCard)) { return false; } // state check VehicleCard card = (VehicleCard) other; return id.getText().equals(card.id.getText()) && vehicle.equals(card.vehicle); } }