text
stringlengths
1
2.12k
source
dict
python, embedded, raspberry-pi def show_calcheck_results(measurements, button_text, cal_reset): log_print("show_calcheck_results([%.3f,%.3f], %s)" % ( measurements[0], measurements[1], button_text)) if button_text == 'CHECK LOW RANGE': add_string = 'INSERT HIGH-RANGE\n' \ 'RESISTANCE FIXTURE AND PRESS\n' \ '\'CHECK HIGH RANGE\'' if cal_reset: res_message = 'UPPER-END RESISTANCE: %.3f\n' \ 'LOWER-END RESISTANCE: %.3f\n%s' % \ (round(measurements[0], 3), round(measurements[1], 3), add_string) else: res_message = 'INPUT RESISTANCE: %.3f\n' \ 'OUTPUT RESISTANCE: %.3f\n%s' % \ (round(measurements[0], 3), round(measurements[1], 3), add_string) elif button_text == 'CHECK HIGH RANGE': add_string = 'PRESS \'APPROVE & EXIT\'\n' \ 'OR \'REDO CAL REF\'\n' \ 'IF OUT OF TOLERANCE' if cal_reset: res_message = 'UPPER-END RESISTANCE: %.3f\n' \ 'LOWER-END RESISTANCE: %.3f\n%s' % \ (round(measurements[0], 3), round(measurements[1], 3), add_string) else: res_message = 'INPUT RESISTANCE: %.3f\n' \ 'OUTPUT RESISTANCE: %.3f\n' \ '%s' % \ (round(measurements[0], 3), round(measurements[1], 3), add_string) else: res_message = 'ERROR IN show_calcheck_results\nCONTACT ENGINEERING' log_print("show_calcheck_results() returning") return res_message
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi def show_results(cath_test_result, barcode): log_print("show_results(%s, %s) called" % (cath_test_result, barcode)) if SHOW_LAST_CATH_GUI_MSG: message = 'JOB FINISHED\nUNPLUG CATHETER\nTO PRINT REPORT\n%s: %s' % ( barcode, cath_test_result) else: if REPEATED_CATHETER_DETECTED: message = 'REPEATED CATHETER\nREADY FOR\nNEXT CATHETER\n%s: %s' % ( barcode, cath_test_result) else: message = 'READY FOR\nNEXT CATHETER\n%s: %s' % ( barcode, cath_test_result) log_print("show_results() returning") return message def alrt_rdy_func_enable(): log_print("alrt_rdy_func_enable() called") i2cbus.write_i2c_block_data(I2C_DEV_ADDR, REG_LOTHRESH_ADDR, LOTHRESH_CONFIGURATION_DATA) i2cbus.write_i2c_block_data(I2C_DEV_ADDR, REG_HITHRESH_ADDR, HITHRESH_CONFIGURATION_DATA) log_print("alrt_rdy_func_enable() returning") def configure_adc(config_reg_data): i2cbus.write_i2c_block_data(I2C_DEV_ADDR, REG_CONFIG_ADDR, config_reg_data) def isr_enable(): log_print("isr_enable() called") GPIO.add_event_detect(ADS1115_ALRT_RDY_SIG, GPIO.FALLING) GPIO.add_event_callback(ADS1115_ALRT_RDY_SIG, read_adc) log_print("isr_enable() returning") def isr_disable(): log_print("isr_disable() called") # GPIO.remove_event_detect(ADS1115_ALRT_RDY_SIG) log_print("isr_disable() returning") def adc_decode(adc_codes): msb = adc_codes[0] << 8 lsb = adc_codes[1] adc_code = msb | lsb voltage = adc_code * LSB return voltage
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi def volt2res(voltage): log_print("volt2res(%f) called" % voltage) high_range_correction_factor = \ (initial_m_high_range * voltage) + initial_b_high_range low_range_correction_factor = \ (initial_m_low_range * voltage) + initial_b_low_range dynamic_high_range_correction_factor = \ (dynamic_m_high_range * voltage) + dynamic_b_high_range dynamic_low_range_correction_factor = \ (dynamic_m_low_range * voltage) + dynamic_b_low_range if MEASURE_OUTPUT_RESISTANCE: if CATH_MODEL is MODEL_P16x_SEL: correction_factor = low_range_correction_factor dynamic_correction_factor = dynamic_low_range_correction_factor tfco = TFCO_LOW elif CATH_MODEL is MODEL_P330_SEL: correction_factor = high_range_correction_factor dynamic_correction_factor = dynamic_high_range_correction_factor tfco = TFCO_HIGH elif CATH_MODEL is MODEL_P330B_SEL: correction_factor = high_range_correction_factor dynamic_correction_factor = dynamic_high_range_correction_factor tfco = TFCO_HIGH else: tfco = TFCO_LOW correction_factor = low_range_correction_factor dynamic_correction_factor = dynamic_low_range_correction_factor print("Something went wrong when selecting the correction " "factor during output resistance " "measurement. CATH_MODEL = ", CATH_MODEL) else: if CATH_MODEL is MODEL_P16x_SEL: correction_factor = low_range_correction_factor dynamic_correction_factor = dynamic_low_range_correction_factor tfco = TFCO_LOW elif CATH_MODEL is MODEL_P330_SEL: correction_factor = high_range_correction_factor dynamic_correction_factor = dynamic_high_range_correction_factor tfco = TFCO_HIGH elif CATH_MODEL is MODEL_P330B_SEL:
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi tfco = TFCO_HIGH elif CATH_MODEL is MODEL_P330B_SEL: correction_factor = low_range_correction_factor dynamic_correction_factor = dynamic_low_range_correction_factor tfco = TFCO_LOW else: tfco = TFCO_LOW correction_factor = low_range_correction_factor dynamic_correction_factor = dynamic_low_range_correction_factor print("Something went wrong when selecting the correction factor " "during input resistance measurement. " "CATH_MODEL = ", CATH_MODEL) transfer_func = RGAIN1 * ((10 * ((voltage - V_BIAS) * tfco + V_BIAS)) - 1) r_dut = transfer_func - correction_factor - dynamic_correction_factor log_print("volt2res() returning") return r_dut
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi def configure_measurement(): global MODEL_RES, MODEL_TOL, V_BIAS, RANGE_LIMIT_LOW, RANGE_LIMIT_HIGH log_print("configure_measurement() called") if MEASURE_OUTPUT_RESISTANCE: set_dut_mux_to_output_res() if CATH_MODEL is MODEL_P16x_SEL: set_bias_mux_to_low_range() MODEL_RES = MODEL_P16x_OUTPUT_RES MODEL_TOL = MODEL_P16x_TOL V_BIAS = V_BIAS_LOW RANGE_LIMIT_LOW = LOWRANGE_LIMIT_LOW RANGE_LIMIT_HIGH = LOWRANGE_LIMIT_HIGH elif CATH_MODEL is MODEL_P330_SEL: set_bias_mux_to_hi_range() MODEL_RES = MODEL_P330_OUTPUT_RES MODEL_TOL = MODEL_P330_OUTPUT_TOL V_BIAS = V_BIAS_HIGH RANGE_LIMIT_LOW = HIGHRANGE_LIMIT_LOW RANGE_LIMIT_HIGH = HIGHRANGE_LIMIT_HIGH elif CATH_MODEL is MODEL_P330B_SEL: set_bias_mux_to_hi_range() MODEL_RES = MODEL_P330B_OUTPUT_RES MODEL_TOL = MODEL_P330B_OUTPUT_TOL V_BIAS = V_BIAS_HIGH RANGE_LIMIT_LOW = HIGHRANGE_LIMIT_LOW RANGE_LIMIT_HIGH = HIGHRANGE_LIMIT_HIGH else: log_print("InvalidModelError:model index " "value is invalid (model=%d)" % CATH_MODEL) else: set_dut_mux_to_input_res() if CATH_MODEL is MODEL_P16x_SEL: set_bias_mux_to_low_range() MODEL_RES = MODEL_P16x_INPUT_RES MODEL_TOL = MODEL_P16x_TOL V_BIAS = V_BIAS_LOW RANGE_LIMIT_LOW = LOWRANGE_LIMIT_LOW RANGE_LIMIT_HIGH = LOWRANGE_LIMIT_HIGH elif CATH_MODEL is MODEL_P330_SEL: set_bias_mux_to_hi_range() MODEL_RES = MODEL_P330_INPUT_RES MODEL_TOL = MODEL_P330_INPUT_TOL V_BIAS = V_BIAS_HIGH RANGE_LIMIT_LOW = HIGHRANGE_LIMIT_LOW RANGE_LIMIT_HIGH = HIGHRANGE_LIMIT_HIGH elif CATH_MODEL is MODEL_P330B_SEL:
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi RANGE_LIMIT_HIGH = HIGHRANGE_LIMIT_HIGH elif CATH_MODEL is MODEL_P330B_SEL: set_bias_mux_to_low_range() MODEL_RES = MODEL_P330B_INPUT_RES MODEL_TOL = MODEL_P330B_INPUT_TOL V_BIAS = V_BIAS_LOW RANGE_LIMIT_LOW = LOWRANGE_LIMIT_LOW RANGE_LIMIT_HIGH = LOWRANGE_LIMIT_HIGH else: log_print("InvalidModelError:model index " "value is invalid (model=%d)" % CATH_MODEL) log_print("configure_measurement() returning")
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi def jobsize_capture(jobsize_string): global JOB_SIZE log_print("jobsize_capture(%s) called" % jobsize_string) if len(jobsize_string) > 0: JOB_SIZE = int(jobsize_string) else: log_print("NO VALUE ENTERED.") log_print("jobsize_capture() returning") return False if 0 < JOB_SIZE < MAX_CATHETERS_PER_JOB: log_print("jobsize_capture() returning") return True else: log_print("INVALID JOB SIZE.") log_print("jobsize_capture() returning") return False def validate_job_number_barcode_scan(x): log_print("validate_job_number_barcode_scan(%s) called" % x.strip()) try: if len(x) > 0 and (int(x.strip()) > 999 and int( x.strip()) < 100000000): code_validity = True else: code_validity = False except ValueError: log_print("Invalid Job Number") code_validity = False return code_validity log_print("validate_job_number_barcode_scan() returning") return code_validity def jobnumber_capture(): global JOB_NUMBER log_print("jobnumber_capture() called") for attempts in range(3): JOB_NUMBER, jobnumber_validity = barcode_scanner() if len(JOB_NUMBER) > 1: if validate_job_number_barcode_scan(JOB_NUMBER): log_print("jobnumber_capture() returning") return True else: log_print("jobnumber_capture() returning") return False if not (bool(JOB_NUMBER)): log_print("jobnumber_capture() returning") return False
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi def model_capture(): global CATH_MODEL log_print("model_capture() called") if MODEL_SELECTED == 'P16x': CATH_MODEL = MODEL_P16x_SEL elif MODEL_SELECTED == 'P330': CATH_MODEL = MODEL_P330_SEL elif MODEL_SELECTED == 'P330B': CATH_MODEL = MODEL_P330B_SEL else: log_print("INVALID MODEL SELECTED!") log_print("model_capture() returning") def waiting_for_manual_barcode(): global KEYPAD_CATH_BARCODE, MANUAL_BARCODE_CAPTURED log_print("waiting_for_manual_barcode() called") while not MANUAL_BARCODE_CAPTURED: pass sleep(.1) MANUAL_BARCODE_CAPTURED = False local_barcode = KEYPAD_CATH_BARCODE log_print("waiting_for_manual_barcode() returning") return local_barcode def validate_catheter_barcode_scan(x): log_print("validate_catheter_barcode_scan(%s) called" % x) try: if 5 < len(x) < 10: code_validity = True else: code_validity = False except TypeError: code_validity = False log_print("validate_catheter_barcode_scan() returning") return code_validity
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi def manual_catheter_barcode_entry(): log_print("manual_catheter_barcode_entry() called") keypad_back_btn.update('') gui_frame_msngr_update(3, CATH_KEYPAD_MESSAGE) while True: event, values = window.read() if event in '1234567890': keys_entered = values['input'] # get what's been entered so far keys_entered += event # add the new digit window['input'].update(keys_entered) elif event == 'Submit': keys_entered = values['input'] window['input'].update('') if validate_catheter_barcode_scan(keys_entered): cath_barcode = keys_entered break else: window['keypad_message'].update(CATH_KEYPAD_INVALID_MESSAGE) keys_entered = '' window['input'].update(keys_entered) elif event == 'Clear': # clear keys if clear button keys_entered = '' window['input'].update(keys_entered) log_print("manual_catheter_barcode_entry() returning") return cath_barcode def barcode_scanner(): log_print("barcode_scanner() called") ser.write(SCNR_TRGR_CMD_BYTES) # Write Hex command to trigger barcode read x = ser.read_until( b'\r') # \r is the last character returned by the barcode reader after # a barcode has been read. This character may change if # the scanner model changes. x = x.decode().split("31", 1) # anything to the right of the # first 31 is the barcode. # '31' is the last 2-digit code returned by the reader. # This 2-digit code may have to change (or be removed) # if the scanner model changes. code_validity = validate_catheter_barcode_scan(x[1]) log_print("barcode_scanner() returning") return x[1], code_validity
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi def print_report(local_report_filename): log_print("print_report(%s) called" % local_report_filename) cmd = 'sudo lp ' + local_report_filename system(cmd) log_print("print_report() returning") def sort_data(): log_print("sort_data() called") keys = list(cath_data_dict_unsorted_buffer.keys()) keys.sort() catheter_data_dict_sorted = {key: cath_data_dict_unsorted_buffer[key] for key in keys} log_print("sort_data() returning") return catheter_data_dict_sorted def correction_fctr_calc(xlist, ylist): log_print("correction_factor_calculation() called") delta_x_low_range = xlist[0] - xlist[1] delta_y_low_range = (ylist[0] - CAL_REF_RESISTANCE_LOWRANGE_HIGH) - ( ylist[1] - CAL_REF_RESISTANCE_LOWRANGE_LOW) m_low_range = delta_y_low_range / delta_x_low_range b_low_range = \ (ylist[0] - CAL_REF_RESISTANCE_LOWRANGE_HIGH) - m_low_range * xlist[0] delta_x_high_range = xlist[2] - xlist[3] delta_y_high_range = (ylist[2] - CAL_REF_RESISTANCE_HIRANGE_HIGH) - ( ylist[3] - CAL_REF_RESISTANCE_HIRANGE_LOW) m_high_range = delta_y_high_range / delta_x_high_range b_high_range = \ (ylist[2] - CAL_REF_RESISTANCE_HIRANGE_HIGH) - m_high_range * xlist[2] log_print("correction_factor_calculation() returning") return m_low_range, b_low_range, m_high_range, b_high_range def correction_value(m, b, x): log_print("correction_value() called") corr_val = (m * x) + b log_print("correction_value() returning") return corr_val def calibration(): global CAL_PASSED, V_BIAS, CATH_MODEL, CONVERSION_READY, \ ADC_SAMPLE_LATEST, CAL_REF_RESISTANCE_LOWRANGE_LOW, \ CAL_REF_RESISTANCE_LOWRANGE_HIGH, CAL_REF_RESISTANCE_HIRANGE_LOW, \ CAL_REF_RESISTANCE_HIRANGE_HIGH, \ dynamic_m_low_range, dynamic_b_low_range, dynamic_m_high_range, \ dynamic_b_high_range, CAL_FAIL log_print("calibration() called")
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi # isr_enable() temp_cath_model = CATH_MODEL A = [0, 0] x_list = [] y_list = [] SAMPLES_TO_TAKE = 120 samples_to_remove_cal = int(SAMPLES_TO_TAKE / 2) sample_period = 0.004 CAL_FAIL = False GPIO.output(B_DUT_MUX, GPIO.HIGH) cal_resistances = [CAL_REF_RESISTANCE_LOWRANGE_HIGH, CAL_REF_RESISTANCE_LOWRANGE_LOW, CAL_REF_RESISTANCE_HIRANGE_HIGH, CAL_REF_RESISTANCE_HIRANGE_LOW] v_bias_cal = [] recalculate_dynamic_coefficients = False log_print('\n\n===INITIATING CALIBRATION===\n') for i in range(4): voltage_samples = [] vbias_sample_buffer_cal = [] GPIO.output(A_DUT_MUX, A[1]) GPIO.output(CAL_RES_HI_RANGE_MUX, A[0]) GPIO.output(A_BIAS_MUX, A[0]) for sample in range(SAMPLES_TO_TAKE): configure_adc(SINGLESHOT_VBIAS_CONFIG_REG) while not CONVERSION_READY: sleep(sample_period) CONVERSION_READY = False vbias_sample_buffer_cal.append(adc_decode(ADC_SAMPLE_LATEST)) vbias_sample_buffer_cal = vbias_sample_buffer_cal[ samples_to_remove_cal:] V_BIAS = sum(vbias_sample_buffer_cal) / len(vbias_sample_buffer_cal) log_print("V_BIAS = %f" % V_BIAS) v_bias_cal.append(V_BIAS) CATH_MODEL = A[0] sleep(.35) # to allow the switches to settle log_print('SAMPLING INTERNAL RESISTANCE...') for sample in range(SAMPLES_TO_TAKE): configure_adc(SINGLESHOT_CONFIG_REG) while not CONVERSION_READY: sleep(sample_period) CONVERSION_READY = False voltage_samples.append(adc_decode(ADC_SAMPLE_LATEST)) voltage_samples = voltage_samples[samples_to_remove_cal:] avg_voltage = round(sum(voltage_samples) / len(voltage_samples), 3) x_list.append(avg_voltage)
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi x_list.append(avg_voltage) cal_res_msrmnt = round(volt2res(avg_voltage), 3) y_list.append(cal_res_msrmnt) if (abs(cal_res_msrmnt - cal_resistances[i]) / cal_resistances[i]) > CAL_REF_RESISTANCE_TOL: recalculate_dynamic_coefficients = True log_print('avg_voltage:%.3f\navg_res:%.3f' % ( avg_voltage, cal_res_msrmnt)) for j in range(len(A) - 1, -1, -1): if A[j] == 0: A[j] = 1 break A[j] = 0 if recalculate_dynamic_coefficients: dynamic_m_low_range, dynamic_b_low_range, \ dynamic_m_high_range, dynamic_b_high_range = \ correction_fctr_calc(x_list, y_list) log_print('dynamic_m_low_range, dynamic_b_low_range, ' 'dynamic_m_high_range, dynamic_b_high_range:\n%f %f %f %f' % (dynamic_m_low_range, dynamic_b_low_range, dynamic_m_high_range, dynamic_b_high_range)) log_print("DYNAMIC CORRECTION FACTOR CALCULATED!") # This condition limits how much the system can correct itself # from the initial correction factors before triggering # an engineer to recalibrate the system. if (abs(dynamic_m_low_range)) > 10 or ( abs(dynamic_m_low_range) > 10) or ( abs(dynamic_m_low_range) > 10) or ( abs(dynamic_m_low_range) > 10): CAL_FAIL = True A = [0, 0] for i in range(4): voltage_samples = [] GPIO.output(A_DUT_MUX, A[1]) GPIO.output(CAL_RES_HI_RANGE_MUX, A[0]) GPIO.output(A_BIAS_MUX, A[0]) V_BIAS = v_bias_cal[i] CATH_MODEL = A[0] log_print('SAMPLING INTERNAL RESISTANCES ' 'WITH DYNAMIC CORRECTION FACTOR...') for sample in range(SAMPLES_TO_TAKE): configure_adc(SINGLESHOT_CONFIG_REG)
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi configure_adc(SINGLESHOT_CONFIG_REG) while not CONVERSION_READY: sleep(sample_period) CONVERSION_READY = False voltage_samples.append(adc_decode(ADC_SAMPLE_LATEST)) voltage_samples = voltage_samples[samples_to_remove_cal:] avg_voltage = round(sum(voltage_samples) / len(voltage_samples), 3) error_magnitude_voltage = round( max(voltage_samples) - min(voltage_samples), 3) error_plus_minus_voltage = round(error_magnitude_voltage / 2, 3) cal_res_msrmnt = round(volt2res(avg_voltage), 3) error_magnitude_res = round( volt2res(max(voltage_samples)) - volt2res( min(voltage_samples)), 3) error_plus_minus_res = round(error_magnitude_res / 2, 3) cal_resistance_tolerance = round( cal_resistances[i] * CAL_REF_RESISTANCE_TOL, 3) log_print('avg_voltage:%.3f +/-%.3f\navg_res:%.3f +/-%.3f\n' % ( avg_voltage, error_plus_minus_voltage, cal_res_msrmnt, error_plus_minus_res)) if (abs(cal_res_msrmnt - cal_resistances[i]) / cal_resistances[i])\ < CAL_REF_RESISTANCE_TOL: log_print("Measured calibrated resistance passed\n") else: CAL_FAIL = True log_print("Measured calibrated resistance out of tolerance\n") log_print( 'Expected Ω: %.3fΩ\nCalculated Ω: %fΩ\n' % ( cal_resistances[i], cal_res_msrmnt)) log_print( 'resistance tolerance: %.3f\n' % cal_resistance_tolerance) log_print('resistance error measured: %.3f\n\n' % ( cal_res_msrmnt - cal_resistances[i])) if i == 3 and CAL_FAIL is False: CAL_PASSED = True GPIO.output(A_DUT_MUX, GPIO.LOW)
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi CAL_PASSED = True GPIO.output(A_DUT_MUX, GPIO.LOW) GPIO.output(B_DUT_MUX, GPIO.LOW) CATH_MODEL = temp_cath_model print('===CALIBRATION DONE===') for j in range(len(A) - 1, -1, -1): if A[j] == 0: A[j] = 1 break A[j] = 0 else: GPIO.output(A_DUT_MUX, GPIO.LOW) GPIO.output(B_DUT_MUX, GPIO.LOW) CATH_MODEL = temp_cath_model CAL_PASSED = True log_print('Dynamic coefficients were not recalculated. ' 'Calibration is still stable.')
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi def read_adc(gpionum): global CATH_CONN_EMPTY, RES_SAMPLES_VALS, ACTIVE_SAMPLING, \ CATH_RES_SAMPLES_COLLECTED, TEST_FINISHED, CATH_MODEL, \ ADC_SAMPLE_LATEST, CATH_DETECTED_SAMPLES_COLLECTED, \ CATH_DISCONN_SAMPLES_COLLECTED, end_job, SHOW_LAST_CATH_GUI_MSG, \ CONVERSION_READY, MEASURE_VBIAS, VBIAS_SAMPLES_BUFFER, V_BIAS, \ report_filename ADC_SAMPLE_LATEST = i2cbus.read_i2c_block_data(I2C_DEV_ADDR, REG_CONVERSION_ADDR, 2) CONVERSION_READY = True avg_voltage = adc_decode(ADC_SAMPLE_LATEST)
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi if CATH_CONN_EMPTY and CAL_PASSED and ( not ACTIVE_SAMPLING) and not EXTERNAL_CAL_INPROGRESS: if CATH_DETECTED_SAMPLES_COLLECTED < CATH_DETECTED_SAMPLES_REQUIRED: if avg_voltage < CATH_DETECTED_VOLTAGE: CATH_DETECTED_SAMPLES_COLLECTED += 1 else: CATH_DETECTED_SAMPLES_COLLECTED = 0 else: configure_measurement() MEASURE_VBIAS = True CATH_CONN_EMPTY = False CATH_DETECTED_SAMPLES_COLLECTED = 0 log_print("CATHETER DETECTED. STARTING TEST...") elif MEASURE_VBIAS: if len(VBIAS_SAMPLES_BUFFER) < 100: VBIAS_SAMPLES_BUFFER.append(avg_voltage) configure_adc(SINGLESHOT_VBIAS_CONFIG_REG) # print('collecting vbias samples:',avg_voltage) else: MEASURE_VBIAS = False VBIAS_SAMPLES_BUFFER = VBIAS_SAMPLES_BUFFER[50:] V_BIAS = sum(VBIAS_SAMPLES_BUFFER) / len(VBIAS_SAMPLES_BUFFER) VBIAS_SAMPLES_BUFFER = [] ACTIVE_SAMPLING = True log_print('VBIAS = %f' % V_BIAS) configure_adc(CONTINUOUS_CONFIG_REG) elif ACTIVE_SAMPLING: if CATH_RES_SAMPLES_COLLECTED < SAMPLES_REQUIRED: RES_SAMPLES_VALS.append(avg_voltage) CATH_RES_SAMPLES_COLLECTED += 1 else: log_print("Finished logging test samples") ACTIVE_SAMPLING = False catheter_test() if TEST_FINISHED: if MEASURE_OUTPUT_RESISTANCE: TEST_FINISHED = False MEASURE_VBIAS = True CATH_RES_SAMPLES_COLLECTED = 0 RES_SAMPLES_VALS = [] configure_measurement() log_print("Measuring output resistance now...") else:
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi if CATH_DISCONN_SAMPLES_COLLECTED < CATH_DETECTED_SAMPLES_REQUIRED: if avg_voltage > CATH_DETECTED_VOLTAGE: CATH_DISCONN_SAMPLES_COLLECTED += 1 else: CATH_DISCONN_SAMPLES_COLLECTED = 0 else: log_print("CATHETER DISCONNECTED. WRITING REPORT...") TEST_FINISHED = False CATH_CONN_EMPTY = True CATH_RES_SAMPLES_COLLECTED = 0 CATH_DISCONN_SAMPLES_COLLECTED = 0 RES_SAMPLES_VALS = [] if catheters_processed == JOB_SIZE: report_filename = write_to_report(sort_data()) end_job = True def catheter_test(): global TEST_FINISHED, RES_SAMPLES_VALS, MEASURE_OUTPUT_RESISTANCE, \ catheters_processed, cath_data_dict_unsorted_buffer, avg_res, \ GUI_CURRENT_BARCODE, GUI_CURRENT_CATH_RESULT, SHOW_LAST_CATH_GUI_MSG, \ REPEATED_CATHETER_DETECTED, MANUAL_CATH_BARCODE_CAPTURE, \ test_result_buffer log_print("catheter_test() called") RES_SAMPLES_VALS = RES_SAMPLES_VALS[SAMPLES_TO_REMOVE:] avg_voltage = sum(RES_SAMPLES_VALS) / len(RES_SAMPLES_VALS) unrepeated_cath = False repeated_catheter = True if MEASURE_OUTPUT_RESISTANCE: avg_res[1] = round(volt2res(avg_voltage), 2) avg_res_dut = avg_res[1] if abs(avg_res_dut - MODEL_RES) < MODEL_TOL: test_result_buffer[1] = "PASS" else: test_result_buffer[1] = "FAIL" log_print("Test Result:%s" % test_result_buffer[1]) else: avg_res[0] = round(volt2res(avg_voltage), 2) avg_res_dut = avg_res[0] if abs(avg_res_dut - MODEL_RES) < MODEL_TOL: test_result_buffer[0] = "PASS" else: test_result_buffer[0] = "FAIL" log_print("Test Result:%s" % test_result_buffer[0]) log_print("Average resistance read:%f" % avg_res_dut)
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi if MEASURE_OUTPUT_RESISTANCE: barcode, code_val = barcode_scanner() if test_result_buffer[0] == "FAIL" or test_result_buffer[1] == "FAIL": test_result = "FAIL" else: test_result = "PASS" if bool(barcode) is False: # Trigger main thread to change # GUI to capture catheter SN manually. MANUAL_CATH_BARCODE_CAPTURE = True # This loop simply waits for the # main thread to do the GUI operation. # Reason is, Tkinter does not like working in multiple threads. barcode = waiting_for_manual_barcode() code_val = validate_catheter_barcode_scan(barcode) if barcode.strip() in cath_data_dict_unsorted_buffer: current_catheter_data = cath_data_dict_unsorted_buffer[ barcode.strip()] current_catheter_data[4] = repeated_catheter REPEATED_CATHETER_DETECTED = True log_print("REPEATED CATHETER, UPDATING REPORT FOR %s" % barcode) else:
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi if (avg_res[0] > RANGE_LIMIT_HIGH) or ( avg_res[0] < RANGE_LIMIT_LOW): avg_res[0] = 9999 if (avg_res[1] > RANGE_LIMIT_HIGH) or ( avg_res[1] < RANGE_LIMIT_LOW): avg_res[1] = 9999 cath_data_dict_unsorted_buffer[barcode.strip()] = [test_result, avg_res[0], avg_res[1], code_val, unrepeated_cath] catheters_processed += 1 if catheters_processed < JOB_SIZE: log_print("\n\n---READY FOR NEXT CATHETER---\n\n") elif catheters_processed == JOB_SIZE: log_print("LAST CATHETER OF JOB. UNPLUG TO PRINT REPORT.") SHOW_LAST_CATH_GUI_MSG = True GUI_CURRENT_BARCODE = barcode.strip() GUI_CURRENT_CATH_RESULT = test_result MEASURE_OUTPUT_RESISTANCE = False else: MEASURE_OUTPUT_RESISTANCE = True TEST_FINISHED = True
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi def loop(): global catheters_processed, CATH_MODEL, \ JOB_SIZE, JOB_NUMBER, CAL_PASSED, \ end_job, cath_data_dict_unsorted_buffer, \ MODEL_SELECTED, CURRENT_PROCESS_MESSAGE, \ SHOW_LAST_CATH_GUI_MSG, REPEATED_CATHETER_DETECTED, \ KEYPAD_CATH_BARCODE, MANUAL_BARCODE_CAPTURED, \ MANUAL_CATH_BARCODE_CAPTURE, CATH_RES_SAMPLES_COLLECTED, \ PLAY_SOUND, PROCESS_MESSENGER_FONT, EXTERNAL_CAL_INPROGRESS, \ EXTERNAL_CAL_MEASURED_RES_VALS, EXTERNAL_CAL_USER_ENTERED_RES_VALS, \ dynamic_m_low_range, dynamic_b_low_range, dynamic_m_high_range, \ dynamic_b_high_range, initial_b_low_range, initial_m_low_range, \ initial_b_high_range, initial_m_high_range, \ CAL_REF_RESISTANCE_LOWRANGE_LOW, CAL_REF_RESISTANCE_LOWRANGE_HIGH, \ CAL_REF_RESISTANCE_HIRANGE_LOW, \ CAL_REF_RESISTANCE_HIRANGE_HIGH, CAL_FAIL
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi first_iteration = True jobsize_valid = False jobnumber_valid = False reset_mouse_position() first_job_done = False res_measurements = [] display_cal_check_measurements = False x_list = [[], []] cal_res_fixture_count = 0 admin_logon_attempt = False notify_user_cath_detected = True notify_user_test_result = True cath_data_dict_unsorted_buffer = {} while True: while True: event, values = window.read() f8_btn1_txt = frame8_button1_text.get_text().strip() f8_btn2_txt = frame8_button2_text.get_text().strip() if event in (sg.WINDOW_CLOSED, 'Exit'): break elif event == ADMIN_FUNCS_KEY: log_print("USER PULLED UP ADMIN PASSWORD REQUEST PAGE") gui_frame_msngr_update(3, ENTER_PW_MESSAGE) admin_logon_attempt = True elif event == 'RE-PRINT': log_print('=USER ATTEMPTED TO RE-PRINT=') if first_job_done: reset_mouse_position() print_report(report_filename) else:
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi frame8_button1_text.update('BACK') frame8_button2_text.update('') gui_frame_msngr_update(8, RUN_FIRST_JOB_FIRST) elif event == "TERMINATE SCRIPT": terminate_script() elif event == "REBOOT": reboot_system() elif event == "SHUTDOWN": shutdown_system() elif event == 'CALIBRATE': CAL_FAIL = False log_print("=USER PRESSED 'CALIBRATE'=") reset_mouse_position() GPIO.output(B_DUT_MUX, GPIO.LOW) EXTERNAL_CAL_INPROGRESS = True frame8_button1_text.update('CHECK LOW RANGE') frame8_button2_text.update('BACK') log_print("=INSTRUCTING USER TO MEASURE AND " "INSERT CALIBRATION RESISTANCES=") gui_frame_msngr_update(8, CAL_INSERT_FIXTURE_MESSAGE) elif event == BUTTON_MESSAGE_KEY1 and \ f8_btn1_txt == 'CHECK LOW RANGE' and \ not display_cal_check_measurements: reset_mouse_position() log_print("=USER PRESSED 'CHECK LOW RANGE'=") gui_frame_msngr_update(2, CHECK_CAL_MESSAGE) res_measurements, temp_hold = measure_single_catheter('LOW') window.write_event_value('display_measurements', '') elif event == BUTTON_MESSAGE_KEY1 and \ f8_btn1_txt == 'CHECK HIGH RANGE' and \ not display_cal_check_measurements: log_print("=USER PRESSED 'CHECK HIGH RANGE'=") gui_frame_msngr_update(2, CHECK_CAL_MESSAGE) res_measurements, temp_hold = measure_single_catheter('HIGH') window.write_event_value('display_measurements', '') elif event == BUTTON_MESSAGE_KEY1 and \ f8_btn1_txt == 'APPROVE & EXIT':
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi f8_btn1_txt == 'APPROVE & EXIT': log_print("=USER PRESSED 'APPROVE & EXIT'=") reset_mouse_position() EXTERNAL_CAL_INPROGRESS = False EXTERNAL_CAL_MEASURED_RES_VALS = [[], []] EXTERNAL_CAL_USER_ENTERED_RES_VALS = [0, 0, 0, 0] x_list = [[], []] gui_frame_msngr_update(1) elif event == BUTTON_MESSAGE_KEY2 and \ f8_btn2_txt == 'REDO CAL REF': reset_mouse_position() initial_b_low_range, initial_m_low_range = 0, 0 initial_b_high_range, initial_m_high_range = 0, 0 dynamic_m_low_range, dynamic_b_low_range = 0, 0 dynamic_m_high_range, dynamic_b_high_range = 0, 0 cal_res_count = 0 cal_res_fixture_count = 0 cal_keypad_messager_window.update( CAL_KEYPAD_PROMPT_MESSAGES[cal_res_count]) gui_frame_msngr_update(7) elif event == BUTTON_MESSAGE_KEY1 and \ f8_btn1_txt == 'CAPTURE REF RESISTANCES': gui_frame_msngr_update(2, CAPTURE_CAL_RES_MESSAGE) EXTERNAL_CAL_MEASURED_RES_VALS[cal_res_fixture_count], x_list[ cal_res_fixture_count] = \ measure_single_catheter( 'LOW' if cal_res_fixture_count == 0 else 'HIGH') cal_res_fixture_count += 1 if cal_res_fixture_count > 1: gui_frame_msngr_update(2, RECALCULATE_REF_RES_MESSAGE) ext_cal_measured_vals_f = list( chain.from_iterable(EXTERNAL_CAL_MEASURED_RES_VALS)) x_list_f = list(chain.from_iterable(x_list)) CAL_REF_RESISTANCE_LOWRANGE_HIGH = \ EXTERNAL_CAL_USER_ENTERED_RES_VALS[1] CAL_REF_RESISTANCE_LOWRANGE_LOW = \
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi CAL_REF_RESISTANCE_LOWRANGE_LOW = \ EXTERNAL_CAL_USER_ENTERED_RES_VALS[0] CAL_REF_RESISTANCE_HIRANGE_HIGH = \ EXTERNAL_CAL_USER_ENTERED_RES_VALS[3] CAL_REF_RESISTANCE_HIRANGE_LOW = \ EXTERNAL_CAL_USER_ENTERED_RES_VALS[2] initial_m_low_range, initial_b_low_range, \ initial_m_high_range, initial_b_high_range = \ correction_fctr_calc(x_list_f, ext_cal_measured_vals_f) GPIO.output(B_DUT_MUX, GPIO.HIGH) sleep(.3) low_range_recalculated_interal_resistances, temp_hold = \ measure_single_catheter('LOW') GPIO.output(CAL_RES_HI_RANGE_MUX, GPIO.HIGH) sleep(.3) high_range_recalculated_interal_resistances, temp_hold = \ measure_single_catheter('HIGH') print('%s\n%s\n%s\n%s\n' % ( initial_m_low_range, initial_b_low_range, initial_m_high_range, initial_b_high_range)) print('%s\n%s\n%s\n%s\n' % ( low_range_recalculated_interal_resistances[1], low_range_recalculated_interal_resistances[0], high_range_recalculated_interal_resistances[1], high_range_recalculated_interal_resistances[0] )) with open('initial_correction_factor.txt', 'w') as ff: ff.write('%s\n%s\n%s\n%s\n' % ( initial_m_low_range, initial_b_low_range, initial_m_high_range, initial_b_high_range)) ff.write('%s\n%s\n%s\n%s\n' % ( low_range_recalculated_interal_resistances[1],
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi low_range_recalculated_interal_resistances[1], low_range_recalculated_interal_resistances[0], high_range_recalculated_interal_resistances[1], high_range_recalculated_interal_resistances[0] )) CAL_REF_RESISTANCE_LOWRANGE_HIGH = \ low_range_recalculated_interal_resistances[0] CAL_REF_RESISTANCE_LOWRANGE_LOW = \ low_range_recalculated_interal_resistances[1] CAL_REF_RESISTANCE_HIRANGE_HIGH = \ high_range_recalculated_interal_resistances[0] CAL_REF_RESISTANCE_HIRANGE_LOW = \ high_range_recalculated_interal_resistances[1] GPIO.output(CAL_RES_HI_RANGE_MUX, GPIO.LOW) GPIO.output(B_DUT_MUX, GPIO.LOW) frame8_button1_text.update('CHECK LOW RANGE') frame8_button2_text.update('') res_measurements = [] reset_mouse_position() gui_frame_msngr_update(8, CAL_RE_INSRT_LOW_RANGE_FIXTR_MSG) else: reset_mouse_position() gui_frame_msngr_update(8, CAL_CURRENT_PROCESS_MESSAGES[ cal_res_fixture_count]) elif event == 'display_measurements': log_print("Displaying calibration check values...") reset_mouse_position() if f8_btn1_txt == 'CHECK LOW RANGE': frame8_button1_text.update('CHECK HIGH RANGE') frame8_button2_text.update('') elif f8_btn1_txt == 'CHECK HIGH RANGE': frame8_button1_text.update('APPROVE & EXIT') frame8_button2_text.update('REDO CAL REF') gui_frame_msngr_update(8,
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi gui_frame_msngr_update(8, show_calcheck_results( res_measurements, f8_btn1_txt, cal_res_fixture_count)) display_cal_check_measurements = False elif event == 'cal_Submit': EXTERNAL_CAL_USER_ENTERED_RES_VALS[cal_res_count] = float( values['calinput']) window['calinput'].update('') reset_mouse_position() cal_res_count += 1 if cal_res_count > 3: gui_frame_msngr_update(8, CAL_CURRENT_PROCESS_MESSAGES[ cal_res_fixture_count]) frame8_button1_text.update('CAPTURE REF RESISTANCES') frame8_button2_text.update('') else: cal_keypad_messager_window.update( CAL_KEYPAD_PROMPT_MESSAGES[cal_res_count]) elif event == 'cal_Clear': log_print("=USER PRESSED 'CLEAR' in CAL KEYPAD") reset_mouse_position() cal_keys_entered = '' window['calinput'].update(cal_keys_entered) elif event == 'cal_BACK': initial_m_low_range = float(lines[0].strip()) initial_b_low_range = float(lines[1].strip()) initial_m_high_range = float(lines[2].strip()) initial_b_high_range = float(lines[3].strip()) CAL_REF_RESISTANCE_LOWRANGE_LOW = float(lines[4].strip()) CAL_REF_RESISTANCE_LOWRANGE_HIGH = float(lines[5].strip()) CAL_REF_RESISTANCE_HIRANGE_LOW = float(lines[6].strip()) CAL_REF_RESISTANCE_HIRANGE_HIGH = float(lines[7].strip()) log_print("=USER PRESSED 'BACK' WHEN " "IN THE REDO REF CAL KEYPAD=") reset_mouse_position()
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi "IN THE REDO REF CAL KEYPAD=") reset_mouse_position() gui_frame_msngr_update(1) cal_keys_entered = '' window['calinput'].update(cal_keys_entered) elif 'cal_' in event: event_name = event.split('cal_') reset_mouse_position() cal_keys_entered = values[ 'calinput'] # get what's been entered so far cal_keys_entered += event_name[1] # add the new digit window['calinput'].update(cal_keys_entered) elif (event == BUTTON_MESSAGE_KEY1 and f8_btn1_txt == 'BACK') or ( event == BUTTON_MESSAGE_KEY2 and f8_btn2_txt == 'BACK'): log_print("=USER PRESSED 'BACK' IN CALIBRATE=") admin_logon_attempt = False reset_mouse_position() EXTERNAL_CAL_INPROGRESS = False gui_frame_msngr_update(1) elif event == KEYPAD_BACK_BTN_KEY: if admin_logon_attempt: admin_logon_attempt = False log_print("=USER PRESSED 'BACK' ON " "KEYPAD WHEN PROMPTED FOR ADMIN PW") gui_frame_msngr_update(1) if JOB_SIZE == 0: log_print("=USER PRESSED 'BACK' ON KEYPAD WHEN PROMPTED TO" " ENTER JOB SIZE OR WHEN IN " "THE REDO REF CAL KEYPAD=") gui_frame_msngr_update(1) else: log_print("=USER PRESSED 'BACK' ON KEYPAD WHEN " "PROMPTED FOR JOB NUMBER=") JOB_SIZE = 0 JOB_NUMBER = 0 window['keypad_message'].update(JOBSIZE_KEYPAD_MESSAGE) keys_entered = '' window['input'].update(keys_entered) reset_mouse_position()
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi window['input'].update(keys_entered) reset_mouse_position() elif event == 'P16x' or event == 'P330' or event == 'P330B': log_print("=USER SELECTED %s AS THE MODEL=" % event) # window['keypad_message'].update(JOBSIZE_KEYPAD_MESSAGE) MODEL_SELECTED = event model_capture() gui_frame_msngr_update(3, JOBSIZE_KEYPAD_MESSAGE) elif event in '1234567890': log_print("=USER PRESSED %s ON THE KEYPAD=" % event) reset_mouse_position() keys_entered = values[ 'input'] # get what's been entered so far keys_entered += event # add the new digit window['input'].update(keys_entered) elif event == 'Submit': reset_mouse_position() keys_entered = values['input'] window['input'].update('') if admin_logon_attempt: if keys_entered == ADMIN_PASSWORD: gui_frame_msngr_update(9, get_ip()) else: window['keypad_message'].update(INVALID_PW_MESSAGE) else: if JOB_SIZE == 0: log_print("=USER PRESSED 'SUBMIT' TO RECORD JOB SIZE=") jobsize_valid = jobsize_capture(keys_entered) if jobsize_valid: log_print("=USER WAS PROMPTED TO " "SCAN JOB NUMBER BARCODE=") gui_frame_msngr_update(6, JOBNUMBER_SCAN_MESSAGE) jobnumber_valid = jobnumber_capture() if not jobnumber_valid: log_print("USER WAS PROMPTED TO " "ENTER JOB NUMBER MANUALLY")
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi "ENTER JOB NUMBER MANUALLY") keys_entered = '' window['input'].update('') gui_frame_msngr_update(3, JOBNUM_KEYPAD_MSG) else: window['keypad_message'].update( JOBSIZE_INVALID_MESSAGE) keys_entered = '' JOB_SIZE = 0 if jobsize_valid and jobnumber_valid: log_print( "VALID JOB SIZE AND JOB NUMBERS WERE RECORDED") break elif not jobnumber_valid: log_print( "=USER PRESSED 'SUBMIT' TO RECORD JOB NUMBER=") jobnumber_valid = validate_job_number_barcode_scan( keys_entered) if jobnumber_valid: log_print( "VALID JOB SIZE AND JOB NUMBERS WERE RECORDED") JOB_NUMBER = keys_entered break else: window['keypad_message'].update( JOBNUMBER_INVALID_MESSAGE) keys_entered = '' window['input'].update(keys_entered) elif event == 'Clear': log_print("=USER PRESSED 'CLEAR'") reset_mouse_position() keys_entered = '' window['input'].update(keys_entered)
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi while True: if jobsize_valid and jobnumber_valid and \ not CAL_PASSED and not CAL_FAIL: log_print( "USER WAS NOTIFIED THAT CALIBRATION WAS BEING PERFORMED") gui_frame_msngr_update(2, CAL_PERFORMING_MESSAGE) calibration() elif CAL_FAIL and not CAL_PASSED: log_print("USER WAS NOTIFIED THAT CALIBRATION FAILED") dynamic_m_low_range, dynamic_b_low_range, \ dynamic_m_high_range, dynamic_b_high_range = 0, 0, 0, 0 frame8_button1_text.update('') frame8_button2_text.update('') gui_frame_msngr_update(8, CAL_FAIL_MESSAGE) sleep(10) log_print("Calibration failed. " "An engineer will come troubleshoot the system.") SHOW_LAST_CATH_GUI_MSG = False catheters_processed = 0 cath_data_dict_unsorted_buffer = {} CATH_MODEL = -1 JOB_SIZE = 0 JOB_NUMBER = 0 CATH_RES_SAMPLES_COLLECTED = 0 CAL_PASSED = False first_iteration = True end_job = False reset_mouse_position() gui_frame_msngr_update(1) notify_user_cath_detected = True notify_user_test_result = True break elif CAL_PASSED and first_iteration: # isr_enable() configure_adc(CONTINUOUS_CONFIG_REG) first_iteration = False log_print("USER WAS PROMPTED TO INSERT " "THE FIRST CATHETER OF THE JOB") gui_frame_msngr_update(2, FIRST_CATH_MESSAGE) elif not CATH_CONN_EMPTY and ACTIVE_SAMPLING and \ CATH_DETECTED_SAMPLES_COLLECTED == 0 and \ notify_user_cath_detected:
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi notify_user_cath_detected: notify_user_cath_detected = False notify_user_test_result = True REPEATED_CATHETER_DETECTED = False # flag reset purposes only PLAY_SOUND = True # flag reset purposes only log_print("USER WAS NOTIFIED THAT THE CATHETER WAS DETECTED") gui_frame_msngr_update(2, CATH_DETECTED_MESSAGE) elif MANUAL_CATH_BARCODE_CAPTURE: KEYPAD_CATH_BARCODE = manual_catheter_barcode_entry() keypad_back_btn.update('BACK') MANUAL_BARCODE_CAPTURED = True MANUAL_CATH_BARCODE_CAPTURE = False elif ((TEST_FINISHED and not MEASURE_OUTPUT_RESISTANCE and not SHOW_LAST_CATH_GUI_MSG and not end_job) or (catheters_processed == JOB_SIZE and SHOW_LAST_CATH_GUI_MSG and not end_job)) and notify_user_test_result: notify_user_test_result = False frame_to_see = 4 if GUI_CURRENT_CATH_RESULT == "PASS" else 5 log_print( "USER WAS NOTIFIED THAT %s TEST RESULT IS: %s" % ( GUI_CURRENT_BARCODE, GUI_CURRENT_CATH_RESULT)) gui_frame_msngr_update(frame_to_see, show_results( GUI_CURRENT_CATH_RESULT, GUI_CURRENT_BARCODE)) # resetting flag for next possible catheter notify_user_cath_detected = True if PLAY_SOUND: audio_feedback(GUI_CURRENT_CATH_RESULT) pass elif catheters_processed == JOB_SIZE and end_job: log_print("Job finished. Resetting flags and printing report.") SHOW_LAST_CATH_GUI_MSG = False catheters_processed = 0 cath_data_dict_unsorted_buffer = {} CATH_MODEL = -1 JOB_SIZE = 0
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi CATH_MODEL = -1 JOB_SIZE = 0 JOB_NUMBER = 0 CATH_RES_SAMPLES_COLLECTED = 0 CAL_PASSED = False first_iteration = True end_job = False reset_mouse_position() gui_frame_msngr_update(1) first_job_done = True notify_user_cath_detected = True notify_user_test_result = True print_report(report_filename) break sleep(.05)
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi window.close() alrt_rdy_func_enable() isr_enable() no_blank_screen() loop() Answer: First impressions: way too much code not enough comments if any needs refactoring to achieve better separation of concerns Unfortunately I can't test it, and TBH I don't understand much so I will just focus on style mainly. There are many different things going on in this program, so I think your priority should be to break it up in small pieces to make it more comprehensible and more maintainable. It's difficult to maintain long code, when you have to scroll a lot and don't have a clear overview of code because it spreads along so many lines. The first thing that is obvious is that you missed the logging module. I recommend you start using it from now on because it is more flexible and there is no need to reinvent the wheel. I always use it for my projects and I like to write to console and to file at the same time (at different levels eg DEBUG for file and INFO for console), because it's easier to troubleshoot unattended applications when you have a permanent log file available. But it's already good that you are using some logging in your program because it makes it easier to trace the execution flow. The shebang should be on the first line: #!/usr/bin python3
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi from import * should be avoided, just import what you need. Why: namespace pollution and possibly overriding existing functions, which may cause nasty bugs. sys.path.append is something one should never do. This may be convenient when writing some test code but there are ways in Python to load libraries dynamically if the need arises. When you see this it usually means the application is poorly structured (files, directories) or the virtualenv is not setup right. The PDF class does not seem to be used presently, so remove it from your code along with the unused imports. Declutter your file as much as you can. Anything you don't use is unneeded distraction. If you really need PDF generation capabilities, then move your class code to a separate file, and import it accordingly. Then we have a couple of variables related to sound, which is yet another type of functionality: FAIL_SOUND = 'fail.mp3' PASS_SOUND = 'pass.mp3' PLAY_SOUND = True
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi At this point, it becomes clear that a separate configuration file should be used to contain those settings. Then they can be customized without touching the code itself, at the risk of inadvertently breaking things. In Python there is the classic configparser module but I prefer YAML files personally. Here you can have a look at some options. Then comes the meat. Next function names are set_bias_mux_to_low_range, set_bias_mux_to_hi_range, set_dut_mux_to_input_res, set_dut_mux_to_output_res etc. I have no idea what they do. You might want to comment these functions using docstrings. If I reason purely in terms of functionality and without even understanding your code, it seems to me that the functions related to GPIO deserve to be put in a separate file. Next function: reset_mouse_position. OK, mouse manipulation. I would externalize this part as well. Possibly into a UI class of some sort. Next: no_blank_screen. I suspect there is feature creep here. This is something that I would rather do outside Python. Possibly in a .bashrc file. Or straight into the Xorg configuration. If you're on Linux, that is. You could also create a launcher for your program. But if you're running a graphical environment, it seems sensible to adapt your power management options, or session preferences if you're concerned about screen lock. In short: this is outside the purview of your application. Next: def show_calcheck_results(measurements, button_text, cal_reset): log_print("show_calcheck_results([%.3f,%.3f], %s)" % ( measurements[0], measurements[1], button_text)) if button_text == 'CHECK LOW RANGE': add_string = 'INSERT HIGH-RANGE\n' \ 'RESISTANCE FIXTURE AND PRESS\n' \ '\'CHECK HIGH RANGE\''
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi This does not sound right. If you click on a button, it should call a function with appropriate arguments. Not the other way round. You normally don't write a function that checks which button was clicked by looking at the button caption (which may change). Or it's possible I misunderstand your code because I'm not familiar with pyautogui and you're automating key strokes perhaps. I'd need to look more in depth then. But in GUIs such as GTK, QT etc you work with event handlers that you attach to controls such as buttons. Next: alrt_rdy_func_enable. It was not worth abbreviating the function name. Make it more explicit. You've saved just 3 characters here. Ideally a function name should already give some clue about its purpose. Admittedly I am a noob in this stuff but maybe the function name could be more intuitive? You're handling I2C here by the way. I guess it goes with GPIO stuff then. I could go on and on but there is misuse of global variables. Use function arguments where appropriate instead. When the number of arguments is unknown or variable you can use **kwargs. But global variables are seldom needed or justified really. And of course they are tricky: when you have global variables that can change value in many code paths, this is going to make debugging difficult. It's something you want to avoid. Variable scope should be limited as much as possible. Function scope is usually sufficient, and arguments can be passed from one function to another. Some values are undefined for example RGAIN1 at line 327: transfer_func = RGAIN1 * ((10 * ((voltage - V_BIAS) * tfco + V_BIAS)) - 1)
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi So I would guess it's defined in hw_init, where you've used star import. Then do: from hw_init import RGAIN1 etc. Again, a config file may be more appropriate, if these are not hard values that will seldom change. My IDE (Pycharm) highlights the variables that are undefined or that cannot be resolved and there are quite a few. Declaring them in your imports would be beneficial because you can directly access their definition. This also reduces the risk of typos. Coming next: barcode stuff. Unsurprisingly I might suggest a dedicated file for this. It looks like you're doing serial read/write but I don't see the relevant imports. You're saying the application works but maybe not in all code paths. Let's have a look at one barcode function: def validate_catheter_barcode_scan(x): log_print("validate_catheter_barcode_scan(%s) called" % x) try: if 5 < len(x) < 10: code_validity = True else: code_validity = False except TypeError: code_validity = False log_print("validate_catheter_barcode_scan() returning") return code_validity Since you're merely returning a boolean value it can be shortened to: def validate_catheter_barcode_scan(value): return 5 < len(value) < 10
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi I have omitted logging and exception handling. Instead of TypeError I would probably use ValueError. In function barcode_scanner I would just return the raw results, rather than call validate_catheter_barcode_scan within that same function. Because you may want to handle different types of barcodes and apply different forms of validation. Leave room for flexibility. Coming next: sort_data. The name is too broad to be meaningful. I suppose sort_catheter_data would then be more expressive. correction_value: what are we correcting and why? No idea. Maybe this is important. But since the function appears to be unused anyway, remove it or stash it somewhere. When you've done all that, review the remaining functions: calibration, read_adc, catheter_test and loop since they are the biggest chunks of code. A loop shouldn't be that long. There are lots of variables, not always aptly named so this part is a bit overwhelming. Sadly, many variables are just unneeded. They are there merely to solve control flow problems. In addition to comments, there has to be more line spacing. That would make the code less of a sore to read. Code that is tedious to read and difficult to understand is harder to maintain because it takes more effort. The other thing that strikes me is the nested ifs - the longer the block, the higher there is a risk of wrong indentation, causing bugs. Error logic are prone to happen here. You can "denest" by using the early return pattern instead: illustration (not in Python) but applies to any language. I think that denesting should be a priority, because you are inevitably going to add more code, and the code will become even more difficult to comprehend. It will take a lot of scrolling. And even a large screen won't suffice to show the whole block so we can have a block-level overview. As said already, indentation is critical in Python. It's very easy to break the logic when you have big chunks of if blocks, nested with other ifs or loops.
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
python, embedded, raspberry-pi At least you've made some effort to modularize by defining 4 distinct functions that have to run in order to start your app. But you need to modularize more. Use a __main__ guard as well. This is a good habit to follow. One benefit is that you can import your module (or parts of it) without executing it.
{ "domain": "codereview.stackexchange", "id": 44787, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, embedded, raspberry-pi", "url": null }
c++, networking, c++23, coroutines Title: sendmsg() scatter-gather coroutine awaiter, optimized suspending Question: My attempt at an Awaiter for sending scatter-gather data over an open file descriptor. Tested only on gcc-13.1.1 Micro-optimizing by suspending the coroutine only when actually needed. No perf measurements done. I hope to build on this to create a write_all coroutine. #include <coroutine> #include <ranges> #include <concepts> #include <expected> #include <span> #include <string> #include <cstring> #include <exception> #include <iostream> #include <unistd.h> #include <sys/socket.h>
{ "domain": "codereview.stackexchange", "id": 44788, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, networking, c++23, coroutines", "url": null }
c++, networking, c++23, coroutines template <std::same_as<std::span<char>> ...Args> class WriteAwaiter{ public: WriteAwaiter(int fd, std::span<char>&& arg1, Args&&... args):m_fd(fd){ // Keeping only "pointers" to the data should be enough, as the awaiting coroutine is responsible for keeping the data valid until it is written std::initializer_list<std::span<char>> list{arg1, args...}; const auto zip = std::ranges::views::zip( list, m_data); for (const auto &l : zip ){ struct iovec &iov = std::get<1>(l); auto &data = std::get<0>(l); iov.iov_base = data.data(); iov.iov_len = data.size(); } } bool await_ready(){ return ( m_written = send_int()); } std::coroutine_handle<> await_suspend(std::coroutine_handle<> h){ // HACK to test suspend of awaiter without actually needing the poll() machinery return h; // This simulates a single call, resuming h immediately } std::expected<int, int> await_resume(){ if (!m_written){ send_int(); } // m_ret must be populated. If we were resumed by POLLOUT, EAGAIN is impossible? return m_ret; } private: bool send_int(){ const struct msghdr msg{ .msg_name = nullptr, .msg_namelen = 0, .msg_iov = m_data.data(), .msg_iovlen = m_data.size(), .msg_control = nullptr, .msg_controllen = 0, .msg_flags = 0 }; int r = sendmsg(m_fd, &msg, MSG_NOSIGNAL); if (r < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)){ return false; } if (r < 0){ m_ret = std::unexpected(errno); } else { m_ret = r; } return true; } bool m_written = false; std::expected<int, int> m_ret; std::array<struct iovec, sizeof...(Args) + 1> m_data{}; // +1 because one span is mandatory
{ "domain": "codereview.stackexchange", "id": 44788, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, networking, c++23, coroutines", "url": null }
c++, networking, c++23, coroutines std::array<struct iovec, sizeof...(Args) + 1> m_data{}; // +1 because one span is mandatory int m_fd = -1; };
{ "domain": "codereview.stackexchange", "id": 44788, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, networking, c++23, coroutines", "url": null }
c++, networking, c++23, coroutines template<std::same_as<std::span<char>> ...Args> WriteAwaiter<Args...> send_aw(int fd, std::span<char> &&arg1, Args&& ...args){ return WriteAwaiter(fd, std::move(arg1), std::move(args)...); } Usage: class Coroutine { public: struct promise_type{ Coroutine get_return_object(){ return Coroutine{};} std::suspend_never initial_suspend() noexcept {return {};} std::suspend_never final_suspend() noexcept { return {};} void return_void(){;} void unhandled_exception(){ auto exc = std::current_exception(); std::rethrow_exception(exc); }; }; }; // minimal coroutine object, gets a connected descriptor Coroutine run(fd){ std::string s1("hello"); std::string s2("world"); // Example call, missing logic while(*written != s1.size() + s2.size()){ send_aw() ;} ... auto written = co_await send_aw(fd, std::span(s1.begin(), s1.end()), std::span(s2.begin(), s2.end())); if (!written){ throw std::runtime_error(std::string("Failed to send: ") + std::strerror(written.error())); } int main(){ int sv[2]; int r = socketpair(AF_UNIX, SOCK_STREAM, 0, sv); if (r != 0){ std::cout << "socketpair failure " << std::strerror(errno) << std::endl; exit(1); } auto coro = run(sv[1]); sleep(10) ; // let coroutine do its thing } Ideas welcome on how to allow optional passing of options for msg_control, but that is out of scope for now.
{ "domain": "codereview.stackexchange", "id": 44788, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, networking, c++23, coroutines", "url": null }
c++, networking, c++23, coroutines Answer: Simplify your code Parts of your code are more verbose than necessary, especially when using newer C++ versions. For example, I would write: template<std::same_as<std::span<char>> ...Args> requires (sizeof...(Args) >= 1) class WriteAwaiter { public: WriteAwaiter(int fd, Args&&... args): m_fd(fd) { std::initializer_list list{args...}; for (auto& [data, iov]: std::ranges::views::zip(list, m_data)) { iov = { .iov_base = data.data(), .iov_len = data.size(), }; } } … std::array<iovec, sizeof...(Args)> m_data; }; template<typename ...Args> auto send_aw(int fd, Args&& ...args){ return WriteAwaiter(fd, std::forward<Args>(args)...); } By using the requires clause to check that we have the right number of arguments, I don't need to check it in the constructor, and declaring m_data looks much simpler now, no need for a comment to explain where the + 1 comes from. Using structured bindings we don't need to call std::get<>(), and since C++20 we can use designated initializers as well. For send_aw() you don't have to repeat all the constraints you added to WriteAwaiter. Just forward everything as is (using proper perfect forwarding), WriteAwaiter itself will complain if it was not correct. The drawback is that the error message from incorrect use of send_aw() might not be as nice; one solution would be to move the constraints to send_aw() instead, if you don't expect any caller to construct WriteAwaiters directly themselves. WriteAwaiter's constructor only takes temporaries Because of the way you wrote the constraint that all Args should be std::span<char>, the code does not work if you pass in an l-value: std::string str("Hello, world!\n"); std::span arg(str); write_aw(fd, arg);
{ "domain": "codereview.stackexchange", "id": 44788, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, networking, c++23, coroutines", "url": null }
c++, networking, c++23, coroutines This is because Args will then be deduced to std::span<char>&, not std::span<char>. One fix would be to remove the reference from Args before checking it: template<typename ...Args> requires (std::same_as<std::remove_reference_t<Args>, std::span<char>> && ...) … But even better is to see that it doesn't really matter what the exact type is, as long as you can construct a std::initializer_list<std::span<char>> from the arguments. So as long as it is convertible to a std::span<char> it should be fine: template<std::convertible_to<std::span<char>> ...Args> … This now has the added benefit that you can write: std::string str("Hello, world!\n"); write_aw(fd, str); Since a std::string is implicitly convertible to a std::span<char>. Another solution would be to not make it a template, but rather to take a std::initializer_list<std::span<char>> as a parameter: class WriteAwaiter { public: WriteAwaiter(int fd, std::initializer_list<std::span<char>> args): m_fd(fd) { for (auto& data: args) { m_data.push_back(iovec{ .iov_base = data.data(), .iov_len = data.size(), }); } } … std::vector<iovec> m_data; }; The drawback of that is the need to use braces when calling it, and the fact that its size is not known at compile time. Allow zero args As @Deduplicator mentioned, the code still works fine even if sizeof...(Args) == 0. While it is a corner case with little use, it's better to just allow it; nothing will break, and the behavior of sending zero bytes in this case is very reasonable. Miscellaneous issues Prefer '\n' instead of std::endl. Send error messages to std::cerr instead of std::cout. Prefer standard C++ functions over C or POSIX functions, for example use std::this_thread::sleep_for() instead of the POSIX sleep() function.
{ "domain": "codereview.stackexchange", "id": 44788, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, networking, c++23, coroutines", "url": null }
c#, beginner, console Title: Currency Converter (calling an api in c#) Question: I am in my first week of programming and I created a currency converter. I want to use real time exchange rates through an api when sending the result. This code itself works just fine. But, being new I am always skeptical if it's done the proper way. I found this method working: var client = new WebClient(); var usdToEur = client.DownloadString("http://currencies.apps.grandtrunk.net/getlatest/usd/eur"); var usdToRon = client.DownloadString("http://currencies.apps.grandtrunk.net/getlatest/usd/ron"); var eurToUsd = client.DownloadString("http://currencies.apps.grandtrunk.net/getlatest/eur/usd"); var eurToRon = client.DownloadString("http://currencies.apps.grandtrunk.net/getlatest/eur/ron"); var ronToUsd = client.DownloadString("http://currencies.apps.grandtrunk.net/getlatest/ron/usd"); var ronToEur = client.DownloadString("http://currencies.apps.grandtrunk.net/getlatest/ron/eur"); Complete Method: static double PerformConversion(string firstCurrency, string secondCurrency, double currencyValue) { var client = new WebClient(); var usdToEur = client.DownloadString("http://currencies.apps.grandtrunk.net/getlatest/usd/eur"); var usdToRon = client.DownloadString("http://currencies.apps.grandtrunk.net/getlatest/usd/ron"); var eurToUsd = client.DownloadString("http://currencies.apps.grandtrunk.net/getlatest/eur/usd"); var eurToRon = client.DownloadString("http://currencies.apps.grandtrunk.net/getlatest/eur/ron"); var ronToUsd = client.DownloadString("http://currencies.apps.grandtrunk.net/getlatest/ron/usd"); var ronToEur = client.DownloadString("http://currencies.apps.grandtrunk.net/getlatest/ron/eur");
{ "domain": "codereview.stackexchange", "id": 44789, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, beginner, console", "url": null }
c#, beginner, console if (firstCurrency == "dollar" && secondCurrency == "euro") { return currencyValue * Convert.ToDouble(usdToEur); } if (firstCurrency == "dollar" && secondCurrency == "ron") { return currencyValue * Convert.ToDouble(usdToRon); } if (firstCurrency == "euro" && secondCurrency == "dollar") { return currencyValue * Convert.ToDouble(eurToUsd); } if (firstCurrency == "euro" && secondCurrency == "ron") { return currencyValue * Convert.ToDouble(eurToRon); } if (firstCurrency == "ron" && secondCurrency == "dollar") { return currencyValue * Convert.ToDouble(ronToUsd); } if (firstCurrency == "ron" && secondCurrency == "euro") { return currencyValue * Convert.ToDouble(ronToEur); } return currencyValue; } Answer: Don't use double for currency The double type can't accurately represent base-10 decimal numbers. This is fine for a lot of applications, but it is an issue for currency, where rounding errors can cause money to disappear or be created from thin air. Prefer the decimal type in these applications. Don't make superfluous web requests You get 6 exchange rates from the server each time you call your method, when you only need one. Just request the one exchange rate you need after resolving which currencies you are dealing with. Hard-coded strings You check you function parameters against hard-coded and undocumented strings. This makes it hard to maintain, and leaves the caller guessing how to call your functions. This is made worse as your choice of strings is inconsistent: "euro" is the full name of the currency "ron" is the currency code for the Romanian leu "dollar" is ambiguous, as many currencies are called dollar in some form. In your case, you apparently mean "US dollar"
{ "domain": "codereview.stackexchange", "id": 44789, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, beginner, console", "url": null }
c#, beginner, console An alternative is to provide a class with named constants for designating various currencies. Use of deprecated WebClient The Microsoft C# documentation for WebClient recommends using the System.Net.Http.HttpClient class instead. Synchronous web requests Web requests can potentially take a long time, leaving your program hanging until it gets a response from the server. Consider providing an asynchronous API for making currency conversions. Logic issues You check individually the name of the first and second currency, which means you have a lot of if statements, and this number will grow quadratically with the number of currencies you support. This is a lot of repetition. You will save a lot of effort using string interpolation instead. Excessive instanciations Each time your method is called, a WebClient instance is created and left to be collected by the garbage collector. You can save resources by reusing the same instance over the lifetime of your program. Naming PerformConversion can be simplified to Convert. firstCurrency and secondCurrency can be ambiguous as to which way the conversion is performed. I find fromCurrency and toCurrency to be more explicit. Example code Here is my take on the problem, taking into account the remarks I made: namespace currency { public class Currency { public string Name { get; init; } public string Code { get; init; } public Currency(string name, string code) { Name = name; Code = code; } public static Currency Euro = new Currency("Euro", "eur"); public static Currency USDollar = new Currency("US Dollar", "usd"); public static Currency RomanianLeu = new Currency("Romanian Leu", "ron"); }
{ "domain": "codereview.stackexchange", "id": 44789, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, beginner, console", "url": null }
c#, beginner, console public static class CurrencyConverter { private const string endpoint = @"http://currencies.apps.grandtrunk.net/getlatest/{0}/{1}"; private static HttpClient httpClient = new HttpClient(); public static decimal Convert(decimal amount, Currency from, Currency to) { return amount * GetExchangeRate(from, to); } public static async Task<decimal> ConvertAsync(decimal amount, Currency from, Currency to) { return amount * await GetExchangeRateAsync(from, to); } public static decimal GetExchangeRate(Currency from, Currency to) { string url = string.Format(endpoint, from.Code, to.Code); return decimal.Parse(httpClient.GetStringAsync(url).GetAwaiter().GetResult(), NumberFormatInfo.InvariantInfo); } public static async Task<decimal> GetExchangeRateAsync(Currency from, Currency to) { string url = string.Format(endpoint, from.Code, to.Code); return decimal.Parse(await httpClient.GetStringAsync(url), NumberFormatInfo.InvariantInfo); } } }
{ "domain": "codereview.stackexchange", "id": 44789, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, beginner, console", "url": null }
javascript, game, html, css, rock-paper-scissors Title: Rock, paper, scissors with HTML & CSS & JS Question: I started studying web development a few months ago and to practice my skills I decided to do the game of rock, paper, scissors. Here are some questions for review: Is the use of HTML semantics correct and how could I improve it? How could I improve the CSS and JavaScript code in terms of readability, optimization and best practices? Are the class, functions and variable names correct (I am not a native English speaker and I am learning, so there may be things misspelled)? Is the style of the code correct? Game screenshot: Code: let counter_rounds = 0; let player_wins = 0; let computer_wins = 0; let draws = 0; const ROUNDS_PER_GAME = 3; const choices = ["ROCK", "PAPER", "SCISSORS"]; const score_human = document.querySelector(".score-human"); const score_computer = document.querySelector(".score-computer"); const result_round = document.querySelector(".result-round"); const result_human = document.querySelector(".result-human"); const final_result = document.querySelector(".final-result"); const result_computer = document.querySelector(".result-computer"); const image_container_player = document.querySelector(".player-choose .image-container"); const image_container_computer = document.querySelector(".computer-choose .image-container"); const buttons = document.querySelector(".buttons-container"); const new_game_button = document.querySelector(".new-game-button"); buttons.addEventListener("click", play); new_game_button.addEventListener("click", reset_game); function play(event) { counter_rounds++; let player, computer;
{ "domain": "codereview.stackexchange", "id": 44790, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, game, html, css, rock-paper-scissors", "url": null }
javascript, game, html, css, rock-paper-scissors function play(event) { counter_rounds++; let player, computer; if ( event.target.classList.contains("btn") || event.target.closest(".button-container") && counter_rounds < 3 ) { const button_value = event.target .closest(".button-container") .getAttribute("data-value"); player = choices.indexOf(button_value); computer = Math.floor(Math.random() * 3); check_winner_round(player, computer); } if (counter_rounds === ROUNDS_PER_GAME) { disable_buttons(); check_winner_game(); new_game_button.style.display = "block"; } } function check_winner_round(player, computer) { if (player === computer) { result_round.textContent = "It's a draw."; result_human.textContent = `You chose ${choices[player]}.`; result_computer.textContent = `Computer choose ${choices[computer]}.`; draws++; } else if ((player-computer+3) % 3 === 1) { score_human.textContent = Number(score_human.textContent) + 1; result_round.textContent = "You won."; result_human.textContent = `You chose ${choices[player]}.`; result_computer.textContent = `Computer chose ${choices[computer]}.`; player_wins++; } else { score_computer.textContent = Number(score_computer.textContent) + 1; result_round.textContent = "You lost."; result_human.textContent = `You chose ${choices[player]}.`; result_computer.textContent = `Computer chose ${choices[computer]}.`; computer_wins++; } update_image_containers(player, computer); } function check_winner_game() { if (player_wins === computer_wins) final_result.textContent = "It's a draw."; else if (player_wins > computer_wins) final_result.textContent = "You won the set."; else final_result.textContent = "Computer wins the set."; }
{ "domain": "codereview.stackexchange", "id": 44790, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, game, html, css, rock-paper-scissors", "url": null }
javascript, game, html, css, rock-paper-scissors function update_image_containers(player, computer) { const image_player = `img/${choices[player].toLowerCase()}.png`; const image_computer = `img/${choices[computer].toLowerCase()}.png`; image_container_player.style.backgroundImage = `url(${image_player})`; image_container_computer.style.backgroundImage = `url(${image_computer})`; image_container_player.classList.remove("empty"); image_container_computer.classList.remove("empty"); } function reset_image_containers() { image_container_player.classList.add("empty"); image_container_computer.classList.add("empty"); image_container_player.style.backgroundImage = ""; image_container_computer.style.backgroundImage = ""; } function set_buttons_state(disabled) { const buttonContainer = document.querySelector(".buttons-container"); buttonContainer.classList.toggle("disabled", disabled); } function disable_buttons() { set_buttons_state(true); } function enable_buttons() { set_buttons_state(false); } function reset_game() { score_human.textContent = 0; score_computer.textContent = 0; result_round.textContent = ""; result_human.textContent = ""; result_computer.textContent = ""; final_result.textContent = ""; player_wins = 0; computer_wins = 0; draws = 0; counter_rounds = 0; reset_image_containers(); enable_buttons(); new_game_button.style.display = "none"; } *, *::before, *::after { box-sizing: border-box; padding: 0; margin: 0; } body { background-color: #000; max-height: 100vh; } header { margin-top: 20px; margin-bottom: 20px; } h1 { color: #f3ffff; text-align: center; }
{ "domain": "codereview.stackexchange", "id": 44790, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, game, html, css, rock-paper-scissors", "url": null }
javascript, game, html, css, rock-paper-scissors h1 { color: #f3ffff; text-align: center; } .scoreboard { display: grid; grid-template-columns: repeat(2, 1fr); justify-items: center; align-items: center; background-color: #014689; height: 150px; width: 400px; margin: 0 auto; border: 4px solid #f3ffff; border-radius: 20px; } .player-score, .computer-score { display: flex; flex-direction: column; justify-content: space-around; height: inherit; width: 100px; } .player, .computer { color: #f3ffff; font-weight: bold; font-size: 25px; text-decoration: underline #f3ffff; display: flex; justify-content: center; align-items: center; } .score-computer, .score-human { background-color: #000; border: 4px solid #f3ffff; border-radius: 10px; color: #ea4225; font-family: 'Seven Segment', sans-serif; font-weight: bold; font-size: 55px; display: flex; justify-content: space-around; align-items: center; } .game-board-container { display: flex; justify-content: center; align-items: center; height: 385px; max-width: 100vw; padding-left: 10%; padding-right: 10%; } .game-board { display: flex; justify-content: center; align-items: center; } .player-choose p, .computer-choose p { color: #ffd700; font-weight: bold; font-size: 25px; text-decoration: underline #ffd700; } .circle { background-color: #87ceeb; border: 3px solid #3b83bd; border-radius: 50%; height: 250px; width: 250px; margin-top: 20px; } .image-container { background-repeat: no-repeat; background-size: 80% 80%; background-position: center; height: 100%; width: 100%; } .vs-image { background-repeat: no-repeat; background-size: 100% 100%; background-position: center; height: 200px; width: 200px; }
{ "domain": "codereview.stackexchange", "id": 44790, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, game, html, css, rock-paper-scissors", "url": null }
javascript, game, html, css, rock-paper-scissors .game-play p { font-family: 'Proxima Nova', sans-serif; font-weight: bold; text-align: center; } .win-condition { color: #f5f5dc; font-size: 18px; } .round-results { color: #f3ffff; font-size: 20px; margin-top: 20px; margin-bottom: 50px; } .choose-option { font-family: 'Proxima Nova', sans-serif; font-weight: bold; font-size: 25px; color: red; } .buttons-container { display: flex; justify-content: center; max-width: 100vw; margin-top: 10px; } .button-container { background-color: #014689; width: 150px; height: 70px; padding: 20px; margin-left: 20px; border-radius: 5px; cursor: pointer; } .btn { background: none; border: 0; color: #f3ffff; cursor: pointer; font: inherit; font-weight: bold; line-height: normal; overflow: visible; width: 100%; height: 100%; display: flex; align-items: center; justify-content: space-evenly; padding: 0 10px; } .btn img { width: 50px; height: 50px; background-color: transparent; } .image-container.empty { background: none; } .new-game-button { background-color: #014689; border-radius: 5px; width: 130px; cursor: pointer; display: none; margin: 0 auto; margin-top: 10px; }
{ "domain": "codereview.stackexchange", "id": 44790, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, game, html, css, rock-paper-scissors", "url": null }
javascript, game, html, css, rock-paper-scissors .disabled { opacity: 0.5; pointer-events: none; cursor: not-allowed; } <!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Rock, Paper, Scissors</title> <link rel="stylesheet" href="css/styles.css" /> <link href="https://fonts.cdnfonts.com/css/seven-segment" rel="stylesheet" /> <link href="https://fonts.cdnfonts.com/css/proxima-nova-2" rel="stylesheet" /> </head> <body> <header><h1>Rock, Paper, Scissors</h1></header> <main> <section class="scoreboard"> <div class="player-score"> <p class="player">PLAYER</p> <p class="score-human">0</p> </div> <div class="computer-score"> <p class="computer">COMPUTER</p> <p class="score-computer">0</p> </div> </section> <section class="game-board-container"> <div class="game-board"> <div class="player-choose"> <p class="player">PLAYER</p> <div class="circle"> <div class="image-container empty"></div> </div> </div> <img src="img/vs.png" class="vs-image" /> <div class="computer-choose"> <p class="computer">COMPUTER</p> <div class="circle"> <div class="image-container empty"></div> </div> </div> </div> </section> <section class="game-play"> <p class="win-condition">The best score out of 3 is the winner.</p> <div class="round-results"> <p class="result-human"></p> <p class="result-computer"></p> <p class="result-round"></p> <p class="final-result"></p> <button class="btn new-game-button">New Game</button> </div>
{ "domain": "codereview.stackexchange", "id": 44790, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, game, html, css, rock-paper-scissors", "url": null }
javascript, game, html, css, rock-paper-scissors <button class="btn new-game-button">New Game</button> </div> <p class="choose-option">Choose an option:</p> <div class="buttons-container"> <div class="button-container" data-value="ROCK"> <button class="btn game-button"> <img src="img/rock_emoji.png" alt="rock_button"> Rock </button> </div> <div class="button-container" data-value="PAPER"> <button class="btn game-button"> <img src="img/paper_emoji.png" alt="paper_button" data-value="PAPER"> Paper </button> </div> <div class="button-container" data-value="SCISSORS"> <button class="btn game-button"> <img src="img/scissors_emoji.png" alt="scissors_button" data-value="SCISSORS"> Scissors </button> </div> </div> </section> </main> <script src="js/script.js"></script> </body> </html>
{ "domain": "codereview.stackexchange", "id": 44790, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, game, html, css, rock-paper-scissors", "url": null }
javascript, game, html, css, rock-paper-scissors Github link Answer: 1 HTML Your markup will return 10 flags while validating it. In total, there is 1 red flag (error), 3 yellow flags (warning), and 6 green flags (info). The red flag is for a missing alt attribute for an image in HTML line 38 which will be covered in section 1.2.3. The 3 yellow flags are received for missing headlines or wrong usage of a section tags which will be covered in section 1.2.1. The green flags are received for using a trailing slash in replace elements (tags with no closing tag) which have no use but can have downsides in certain conditions. Since these conditions are not met here, those flags will be no further mentioned or covered. Additionally, to the flags made by w3c validator, I have to red flag the lang attribute which you used in HTML line 2: <html lang="es"> which in this case indicates the website to be written in Spanish while it is written in English. 1.1 Conventions I see some approaches to implementing conventions. While they are acceptable I would not agree with all or highly advise to change them or implement others.
{ "domain": "codereview.stackexchange", "id": 44790, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, game, html, css, rock-paper-scissors", "url": null }
javascript, game, html, css, rock-paper-scissors You use 3 different stylesheets with the usage of the link tag. In the first link, you decided to use a single line, you moved the last 2 into multiple lines highlighting the single attributes. IMHO a single-line link is not less readable but less open to coding errors by missing brackets. In any case, you should decide between both theories and use the same convention on all the links. Your custom CSS comes before the framework/fonts CSS. Custom CSS should always be declared last so that frameworks can not override your custom styles (except specificity weight)! While it is technically correct to use a script tag at the end of the body I would always add them in the head element. To ensure that referenced elements already exist you could either use window.addEventListener('DOMContentLoaded', ... ) or use the defer attribute inside your script tag. While I'm a massive fan of header and main usage, I would recommend indenting the h1 tag into a new line. Block-level elements should always be written in new lines even if they are the only child elements of an element. That improves the readability and recognition of those elements. Add logical gaps (linebreak) between elements to split the block apart. In your case splitting the sections visible apart would improve readability. 1.2 Accessibility & Semantics You tried to use semantic tags wherever possible. However, you paid no extra attention to accessibility beyond that. Sections should always have a headline ranging from h2 to h6 that also works as a label for that section. If no headline is used, then a standard div would be more appropriate. W3C will flag a missing headline. A p stands for paragraph. It is an element to contain flow text and displays that content in a block form. It is not an appropriate use to use it for single words or the display of a score. In fact, displaying the score is a semantic task for the output element while an output element should have a label. An appropriate code use would be:
{ "domain": "codereview.stackexchange", "id": 44790, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, game, html, css, rock-paper-scissors", "url": null }
javascript, game, html, css, rock-paper-scissors <div class="computer-score"> <label class="computer" for="computer-score">COMPUTER</label> <output class="score-computer" id="computer-score">0</output> </div> An Image needs to have an alt attribute so that screen readers know what the content of the image is or what it is about. It also is used as an alternative text in case an image hasn't been loaded. To address the accessibility point of view I cannot see any reasons to present the images to screen readers at all. There is no reason that a blind person will be explained that there is an image that contains a rock as an icon. It should be excluded to screen readers with the usage of aria-hidden="true" so that screen readers will skip it. I can't see any reason to give a div or an image a data attribute. The data-value attribute should be used on the button itself as it is the element that will be clicked. The value of the alt attribute is not appropriate in this context. For example scissors_button is not a description of the image's content or its task. The image in that case just contains a scissor as an item. It is not appropriate to use the alt attribute to describe in which DOM element it has been used. An appropriate value would be: icon of scissors.
{ "domain": "codereview.stackexchange", "id": 44790, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, game, html, css, rock-paper-scissors", "url": null }
javascript, game, html, css, rock-paper-scissors As accessibility was not one of your requirements, I will skip it here. 1.3 Body There is not much to say about the body element and its content. One of your questions was: "Are the class, functions, and variable names correct (I am not a native English speaker and I am learning, so there may be things misspelled)?". All I can answer to that is, that it does not matter much. Names whether they be classes, variables, etc. must be self-explaining. They should not be chosen for efficiency in code or file size but to be readable to other developers while being self-explaining. If you're from Spain and code in Spanish as you know that colleagues of yours are also Spanish, then it would be valid to use Spanish names. It is not a requirement to choose English names. Beyond that, I would highly advise to not limit it to classes but to use ids wherever possible and appropriate. Many of your elements have a unique scope and would be more appropriate with the usage of an id instead of a class. 2 CSS Your CSS is well-ordered but repetitive. It could be optimized and with it reduced by at least 40%. 2.1 Accessibility Red text color on a black background can cause trouble to red-color-blind persons. As it is a definite can and not a will be this will not necessarily be an issue but must be kept in mind. You miss a highlighting of a selected element in case a user decides to control and play with a keyboard only.
{ "domain": "codereview.stackexchange", "id": 44790, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, game, html, css, rock-paper-scissors", "url": null }
javascript, game, html, css, rock-paper-scissors 2.2 Responsivness You didn't pay any attention to RWD (Responsive Web Design) and in general, your web application will only be playable on a larger monitor screen without touch controls. Especially in Web applications, you should make your application responsive. One major issue is the usage of <meta name="viewport" content="width=device-width, initial-scale=1.0" /> in HTML which removes the DPR (Device Pixel Ratio) feature which you did not counter in CSS. This will make the web application unusable on mobile devices in terms of UX (User Experience). As you didn't pay any special attention to RWD and Accessibility, I will skip the review about UX/UI here. 2.3 Structure As said before, your CSS is well structured in order of ordering the elements. You should not use a general reset of all margins and paddings. Many of them have a purpose, especially for UX and UI and removing either cost readability (UX) or causing the extra effort to re-add them manually (efficiency). You should try not to repeat large portions of code. Preferably not repeat code at all. Much of your code could have been cut out if you would select multiple elements with the same styles and adding all properties and values that are equal. Then select the single elements only for element-specific styles. Especially with colors you repeat a hex color quite often. In that case, you should declare a variable for that color within the :root selector. This would make adjustments and maintenance a lot easier as you would need to change the color only in one place (the root). you work a lot with absolute values such as pixels. You should try to use relative units for RWD and UX reasons. 3 JS Your programming style is mostly up-to-date and you use modern techniques for the most part. Especially the usage of string literals and textContent is noted. 3.1 Conventions You make good use of deciding between constants and variables.
{ "domain": "codereview.stackexchange", "id": 44790, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, game, html, css, rock-paper-scissors", "url": null }
javascript, game, html, css, rock-paper-scissors Constants should always be declared on to while global variables should come afterward. Constants should be written in capital letters to immediately spot them in the code and have a visual difference to variables. You started well with ROUND_PER_GAME while unfortunately stopping afterwards. You used: const button_value = event.target .closest(".button-container") .getAttribute("data-value"); This looks strange at first glance. It would be more readable in a single line. However, that approach is strange to start with which will be further addressed in 3.4.1. Parameters should start with a single or double underscores such as __player and __computer to visually differentiate them from variables. You should use logic gaps within the code. Appropriate would be to use a gap to split let and const into different blocks. Especially your addEventListener should be split from the const as well. You should add more comments. While your naming and coding are self-explaining, carefully placed comments can improve readability and understanding of your codes by other developers or teachers. 3.2 Input Validations You use no inputs with exception of button presses. As such there is no reason to address that part in this review. 3.3 Logic For the most part, I can follow your logic but it is flawed. The one flaw I could immediately spot was the following case. The first Round was won by the Computer. The second round was by the Player. The round was a draw The game message is the following: You chose ROCK. Computer chose SCISSORS. You won. It's a draw. You should specially mark the announcing who won the entire set. Such as: " The Set ends with a draw". And you also need to fix to display both choices if the set end in a draw not skipping the last choices. 3.4 Coding Style Overall you have a nice style of coding which is mostly modern and clean. This is especially worth mentioning for beginners.
{ "domain": "codereview.stackexchange", "id": 44790, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, game, html, css, rock-paper-scissors", "url": null }
javascript, game, html, css, rock-paper-scissors As said above, you click a button so you should add the data-value attribute to the button itself. You also do not need getAttribute while using data attributes. The value of that attribute could simply be received by using dataset instead: const BUTTONS = document.querySelectorAll('button'); BUTTONS.forEach(button => button.addEventListener('click', function(event) { let button_dataValue = event.target.dataset.value; console.clear(); console.log(button_dataValue); }) ); <button data-value="Button A">Button A</button> <button data-value="Button B">Button B</button> <button data-value="Button C">Button C</button> <button data-value="Button D">Button D</button> While you already use classList you still keep using the style function to apply inline styles. Use classList all along and apply and remove the background images through CSS as well. Following code block appears to be repetitive: const image_player = `img/${choices[player].toLowerCase()}.png`; const image_computer = `img/${choices[computer].toLowerCase()}.png`; image_container_player.style.backgroundImage = `url(${image_player})`; image_container_computer.style.backgroundImage = `url(${image_computer})`; This indicates to me that both the computer and player use the same 3 images: img/paper.png img/rock.png img/scissors.png The easiest adjustment is to make a function that returns the correct URL string literal. function update_imagecontainers(__player, __computer) { image_container_player.classList.remove('empty'); image_container_computer.classList.remove('empty'); image_container_player.style.background = image_url(__player); image_container_player.style.background = image_url(__computer); } function image_url(__choice) { let url = `img/${__choice.toLowerCase}.png` return url; } console.log(image_url("ROCK")); console.log(image_url("PAPER")); function image_url(__choice) { let url = `img/${__choice.toLowerCase()}.png`; return url; }
{ "domain": "codereview.stackexchange", "id": 44790, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, game, html, css, rock-paper-scissors", "url": null }
javascript, game, html, css, rock-paper-scissors function image_url(__choice) { let url = `img/${__choice.toLowerCase()}.png`; return url; } Beyond that, it is a great test for a loop as the computer and player lines are identical. I see some if/else statements that are kinda slow performing. If you have 2 or more if/else statements then a switch statement would perform faster and more efficiently. In the example, I will just use one of your if/else statements (where you miss curly brackets). function check_winner_game() { if (player_wins === computer_wins) { final_result.textContent = "It's a draw."; } else if (player_wins > computer_wins) { final_result.textContent = "You won the set."; } else { final_result.textContent = "Computer wins the set."; } } That entire block can and should be replaced by a switch statement and combined with a dedicated return function such as above: function check_winner_game() { final_result.textContent = winner_message(); } function winner_message() { switch (true) { case (player_wins === computer_wins): return "It's a draw."; case (player_wins > computer_wins): return = "You won the set"; case (player_wins < computer_wins): return = "Computer wins the set"; } } const FINAL_RESULT = document.querySelector('output'); let player_wins = 2; let computer_wins = 1; function check_winner_game() { FINAL_RESULT.textContent = winner_message(); } function winner_message() { switch (true) { case (player_wins === computer_wins): return "It's a draw."; case (player_wins > computer_wins): return "You won the set"; case (player_wins < computer_wins): return "Computer wins the set"; } } window.addEventListener('DOMContentLoaded', check_winner_game); <output></output>
{ "domain": "codereview.stackexchange", "id": 44790, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, game, html, css, rock-paper-scissors", "url": null }
javascript, game, html, css, rock-paper-scissors window.addEventListener('DOMContentLoaded', check_winner_game); <output></output> 4 Summary You have done a really good job for a beginner. However, you still got stuff to learn. I would recommend you learn about switch statements and the usage of return in JS. Overall to learn and implement conventions and to read into RWD to improve your UI and UX skills.
{ "domain": "codereview.stackexchange", "id": 44790, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, game, html, css, rock-paper-scissors", "url": null }
vba, excel Title: Loop through cells of a range and convert to a hyperlink and change (Text To Display) to an ascending number per each row Question: I have used the below code Loop through cells of a range and convert to a hyperlink and change (Text To Display) to an ascending number per each row. it works, but for the point of ascending number I have to use two loops (r and i). I wish to replace these loops with column index with reference to range rngFinal as this answer by @FaneDuru Link Sub Convert_to_Hyperlink() Dim ws As Worksheet: Set ws = ActiveSheet Dim rngFinal As Range, cel As Range, r As Variant, i As Long Set rngFinal = ws.Range("I2:K4") For Each r In rngFinal.Rows i = 0 For Each cel In r.Cells If cel.Value <> "" Then i = i + 1 ws.Hyperlinks.Add cel, _ Address:=cel.Value, TextToDisplay:="Attach " & i End If Next cel Next r End Sub Answer: Please use the following code. Range column, which is relative to the sheet columns can be made relative to a specific range. There is no need to iterate by rows: Sub Convert_to_Hyperlink() Dim ws As Worksheet: Set ws = ActiveSheet Dim rngFinal As Range, cel As Range Set rngFinal = ws.Range("I2:K4") For Each cel In rngFinal.cells If cel.Value <> "" Then ws.Hyperlinks.Add cel, _ address:=cel.Value, TextToDisplay:="Attach " & cel.column - rngFinal.column + 1 End If Next cel End Sub
{ "domain": "codereview.stackexchange", "id": 44791, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "vba, excel", "url": null }
rust, rock-paper-scissors Title: Yet another simple Rock, Paper and Scissors game Question: I implemented a simple CLI based rock-paper-scissors game in Rust. The player plays against the computer. Each game has three rounds, not counting draws. Cargo.toml [package] name = "rps" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] rand = "0.8.5" lib.rs use rand::{ distributions::{Distribution, Standard}, Rng, }; use std::cmp::Ordering; use std::fmt::{Debug, Display, Formatter}; use std::str::FromStr; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum RPS { Rock, Paper, Scissors, } impl Display for RPS { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!( f, "{}", match self { Self::Rock => '', Self::Paper => '', Self::Scissors => '✀', } ) } } impl PartialOrd<Self> for RPS { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { match (self, other) { (Self::Rock, Self::Paper) => Some(Ordering::Less), (Self::Rock, Self::Scissors) => Some(Ordering::Greater), (Self::Paper, Self::Rock) => Some(Ordering::Greater), (Self::Paper, Self::Scissors) => Some(Ordering::Less), (Self::Scissors, Self::Rock) => Some(Ordering::Less), (Self::Scissors, Self::Paper) => Some(Ordering::Greater), (_, _) => None, } } } impl Ord for RPS { fn cmp(&self, other: &Self) -> Ordering { match self.partial_cmp(other) { Some(order) => order, None => Ordering::Equal, } } } impl Distribution<RPS> for Standard { fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> RPS { match rng.gen_range(0..=2) { 0 => RPS::Rock, 1 => RPS::Paper, _ => RPS::Scissors, } } }
{ "domain": "codereview.stackexchange", "id": 44792, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, rock-paper-scissors", "url": null }
rust, rock-paper-scissors impl FromStr for RPS { type Err = &'static str; fn from_str(s: &str) -> Result<Self, Self::Err> { match s.trim().to_lowercase().as_str() { "r" => Ok(Self::Rock), "p" => Ok(Self::Paper), "s" => Ok(Self::Scissors), _ => Err("invalid string"), } } } main.rs use rand::random; use rps::RPS; use std::cmp::Ordering; use std::io::{stdin, stdout, Write}; use std::str::FromStr; fn main() { let mut rounds: u8 = 0; let mut score: i8 = 0; loop { if rounds >= 3 { break; } let computer: RPS = random(); let user = read_user(); match user.cmp(&computer) { Ordering::Equal => { println!("Draw: {} = {}", user, computer); continue; } Ordering::Less => { println!("You lost: {} < {}", user, computer); score -= 1; } Ordering::Greater => { println!("You won: {} > {}", user, computer); score += 1; } } rounds += 1; } match score.cmp(&0) { Ordering::Equal => println!("The game ended in a draw."), Ordering::Less => println!("The computer won the game."), Ordering::Greater => println!("The player won the game."), } } fn read_user() -> RPS { loop { print!("Your selection (r/p/s): "); stdout().flush().expect("Could not flush STDOUT."); let mut buf = String::new(); if stdin().read_line(&mut buf).is_ok() { match RPS::from_str(&buf) { Ok(rps) => return rps, Err(error) => println!("{}: {}", error, buf), } } } } I'd like to have feedback on the general code style and especially the use of trait implementations in lib.rs.
{ "domain": "codereview.stackexchange", "id": 44792, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, rock-paper-scissors", "url": null }
rust, rock-paper-scissors Answer: PartialOrd and None You're not supposed to return None in partial_cmp() when a and b are equal. You're supposed to return Some(Ordering::Equal). Only weird types that have no total ordering return None, such as NaN and Nan in floats, where it is neither == nor !=. If you do have total ordering, it is better to implement the logic in Ord to make sure you never return None, and then implement PartialOrd in terms of it: Some(self.cmp(other)). PartialOrd<Self> The <Self> is redundant. Self is the default. Stdout and Stdin I wouldn't do this in this program since the I/O is definitely not a performance problem, but if you're doing a lot of I/O know that you can lock stdin and stdout for faster access to them (but this means you cannot access them without the lock), and you can also wrap them with buffering to make them even faster: use std::io::{stdin, stdout, BufRead, BufReader, BufWriter, Write}; fn read_user() -> RPS { let mut stdout = BufWriter::new(stdout().lock()); let mut stdin = BufReader::new(stdin().lock()); loop { write!(stdout, "Your selection (r/p/s): ").unwrap(); stdout.flush().expect("Could not flush STDOUT."); let mut buf = String::new(); if stdin.read_line(&mut buf).is_ok() { match RPS::from_str(&buf) { Ok(rps) => return rps, Err(error) => println!("{}: {}", error, buf), } } } } Using ThreadRng explicitly Again, this doesn't matter in this example because the code is not performance sensitive, but it is faster to store the ThreadRng in a variable instead of calling random() if you do it many times: use rand::Rng; fn main() { let mut rounds: u8 = 0; let mut score: i8 = 0; let mut rng = rand::thread_rng(); loop { if rounds >= 3 { break; } let computer: RPS = rng.gen(); // ... }
{ "domain": "codereview.stackexchange", "id": 44792, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, rock-paper-scissors", "url": null }
rust, rock-paper-scissors let computer: RPS = rng.gen(); // ... } use std::fmt::Debug is redundant. Because Debug is already in the prelude. Not the trait - the derive macro. The compiler doesn't warn about that unfortunately (but see clippy#1124). Don't use Ord or PartialOrd By the contract of PartialOrd (and Ord), it should be transitive (a < b and b < c means a < c). Your implementation does not fulfill that criteria (e.g. Rock < Paper and Paper < Scissors but Rock > Scissors), therefore you cannot implement PartialOrd. Use your own method to compare RPS and checks who win. I recommend also using your own enum for the result (and not Ordering), because for me at least, Ordering::Greater for example does not clearly mean left wins right.
{ "domain": "codereview.stackexchange", "id": 44792, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, rock-paper-scissors", "url": null }
c, console, template Title: Skeleton for a command-line program that takes files in C Question: First. If this question is not allowed, I am sorry. Please, tell me so, and I will try to delete this. If it is, I will delete this paragraph. Personal-ish note/Motivation I was studying assembly because of Tanenbaum and C, and decided to make a "graduation" project from the book: a C compiler for AVR and x86 ISAs, using the C standard with no external source on compilers! For fun, or suffering... and to make my first C "project", not only scripts. So, I wrote a skeleton program that takes files and options ("switches"). So, the file can really grow to any place. It also means it haunts me at night, with so many design decisions, like enum for errors and so many static functions; besides features ideas... I always think something is wrong and there will be pain in growing the project, because it will be unreadable, consequentially buggy. Explanation Like GCC, any input argument that is not an option is a file name. Unlike GCC, it calls options switches, because Windows does it, and I am using Windows. This is all. It is mostly a skeleton for a program that takes files from the user. /* * This file contains the entry function (main) for the SSGCompiler. * The SSGCompiler is a compiler done as a challenge from the author * to the author. More information may be found on the GitHub * repository [REDACTED]. * * This was originally written at 05/06/2023. */ #include <stdio.h> #include <stdbool.h> #include <string.h> #define EXECUTABLE_NAME "ssgcompiler" #define SWITCH_PREFIX '/' enum error { FATAL_ERROR, NOT_FATAL_ERROR }; /* Prints the preamble of an error appended with a message. */ static void print_error_message(enum error err, const char *msg) { fputs(EXECUTABLE_NAME, stdout); if (err == FATAL_ERROR) fputs(". Fatal error: ", stdout); else fputs(". Error: ", stdout); fputs(msg, stdout); }
{ "domain": "codereview.stackexchange", "id": 44793, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, console, template", "url": null }
c, console, template fputs(msg, stdout); } /* Returns whether the switch is a help switch */ static bool switch_is_help(const char *opt) { if ( !strcmp(opt, "/?") || !strcmp(opt, "--help") || !strcmp(opt, "-help") || !strcmp(opt, "--h") || !strcmp(opt, "-h") || !strcmp(opt, "help")) { return true; } return false; } /* Returns whether the argument array has the help switch. */ static bool args_contain_help_switch(const char **argv, const int argLen) { for (int i = 0; i < argLen; i++) { if (switch_is_help(argv[i])) return true; } return false; } int main(const int argc, const char **argv) { if (argc < 2) { print_error_message(FATAL_ERROR, "no input files.\n"); printf("See '" EXECUTABLE_NAME " /?' for help.\n"); return 1; } if (args_contain_help_switch(argv, argc)) { fputs( "Usage: ssgcompiler [switches] file...\n" "Switches:\n" " /? Displays this help message (also --help, " "-help, --h, -h, help)\n", stdout); return 0; } for (size_t i = 1; i < argc; i++) { if (!strlen(argv[i]) || argv[i][0] != SWITCH_PREFIX) continue; print_error_message(NOT_FATAL_ERROR, "Unrecognized switch: "); printf("'%s'.\n", argv[i] + 1); } return 1; }
{ "domain": "codereview.stackexchange", "id": 44793, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, console, template", "url": null }
c, console, template return 1; } Answer: Use getopt_long() to parse the command line Parsing a command line quickly becomes more complex if you want to allow a combination of regular arguments (like filenames), and switches with and without extra arguments. You want your program to parse options the same way as other programs do, as this will less likely confuse your users. On any UNIX-like operating system, the de-facto standard is to use GNU's getopt_long(). On Windows, I would try to find a drop-in replacement library for it. While it does not conform with how Microsoft's programs work, it's not uncommon on Windows to have programs use the UNIX style of command line flags, and it is better if your program behaves the same way on all operating systems. Print warnings and error messages to stderr Standard output is for the regular, expected output of your program. Use stderr when printing warnings and error messages. The benefit is that they stay visible even if the user redirected the standard output of your program to a file or to another program. Note that if the user passed the --help flag, print that help message to stdout; it was after all explicitly requested by the user so it is expected, and then they can easily pipe long help messages through a pager like less. Don't hardcode the name of the program You don't have to hardcode the name of the program; it's actually passed to the program in argv[0]. So you'd typically write something like: int main(const int argc, const char **argv) { … fprintf(stderr, "See '%s --help' for help.\n", argv[0]); … } If the program was called using an explicit path, like ./ssgcompiler ..., then this will also end up in the help message: See './ssgcompiler --help' for help.
{ "domain": "codereview.stackexchange", "id": 44793, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, console, template", "url": null }
c, console, template See './ssgcompiler --help' for help. This way it's even a valid command the user can copy&paste. Make help discoverable In case the user did not provide any arguments, you print an error message and a helpful line that says how to get more help. That's great! However, you should do this consistently. For example, also if an unrecognized switch was passed. Also consider the case where switches were passed but no filenames: argc will be >= 2 in that case, so your check at the beginning of the program is not correct.
{ "domain": "codereview.stackexchange", "id": 44793, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, console, template", "url": null }
rust, matrix Title: Fast BLAS-like matrix multiplication in Rust Question: I have some matrix multiplication code I am writing for a linear algebra library I'm working on. The goal is to emulate BLAS (and achieve BLAS-like performance) without using a BLAS library, as my use-case only needs 2 or 3 BLAS operations and using a BLAS library would be pulling in too many unnecessary dependencies. The code is as follows: // Performs the operation A.T -> B // where A dims = M x N fn transpose(a: &[f64], m: usize, n: usize) -> Vec<f64> { let mut b = vec![0.0; n * m]; for i in 0..n { for j in 0..m { b[(m * i) + j] = a[(n * j) + i] } } b } // Optimized matrix multiplication // Performs AB -> C // where A dims = N x M // and B dims = M x P // and C dims N x P fn sgemm(n: usize, m: usize, p: usize, a: &[f64], b: &[f64]) -> Vec<f64> { let mut c = vec![0.0; n * p]; // Matrix multiply by transpose // to speed up performance let b_transpose = transpose(&b, m, p); for i in 0..n { for j in 0..p { for k in 0..m { c[(p * i) + j] += a[(m * i) + k] * b_transpose[(p * k) + j]; } } } c } fn main() { let a = vec![1.,2.,3.,4.,5.,6.]; // 3 x 2 matrix let b = vec![1.,1.,1.,1.,1.,1.]; // 2 x 3 matrix let c = sgemm(3, 2, 3, &a, &b); println!("{:?}", c); } I am aware that performance can likely be improved, as my level of optimizations is not very high. Please let me know of any suggested improvements to the code.
{ "domain": "codereview.stackexchange", "id": 44794, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, matrix", "url": null }
rust, matrix Answer: sgemm The s in sgemm stands for single-precision. This code works with f64, so it's a dgemm. Performance Unfortunately there won't be anything left of this code when you're done upgrading it. Everything will change. So as far as reviewing goes, that was it. Everything after this point, is a description of what you need to do to engineer the replacement. First decide whether to focus on small matrices, such as in your example, or big ones. They are completely different in nature. For small matrices, the challenge is in writing "bespoke SIMD code" for every particular size that you care about, making every instruction count (there won't be many instructions, so each one is individually more important). Medium to large matrices are a whole different game, which the rest of this answer is about. By the way don't expect to compete with eg Intel MKL, on the other hand you can get 80% of the way there or so no problem. Some people treat this as some sort of mythical problem that mere mortals cannot solve, which may be true if your goal is to get all the way to the end, but getting most of the way there is not so bad. The ingredients Here's a shopping list for efficient matrix multiplication:
{ "domain": "codereview.stackexchange", "id": 44794, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, matrix", "url": null }
rust, matrix Tiling, with repacking (copying a tile into its own memory). The tiling is to make good use of cache, the repacking is to avoid TLB misses. Transposing b helps a bit, but the real solution is tiling, and actually transposing gets in the way of other things that you'll end up wanting to do. An obvious question that comes up with tiling is what dimensions the tiles should have. The best choice varies depending on cache size and such.. A sufficient amount of unrolling (with independent accumulators, otherwise it still doesn't help) to keep the multipliers/FMA units busy. Note that this unrolling cannot be purely of the inner loop. Unrolling the j-loop is necessary to be able to vectorize properly at all, and you will need to unroll it more to reach the amount of independent chains of computation that you need to keep the FMA units busy. SIMD. A somewhat common mistake is trying to apply SIMD to speed up individual dot-products. That has a disadvantage: it requires a horizontal addition (adding up the components of a single SIMD-vector, henceforth just "vector") in the end. Alternatively, you can apply SIMD to compute several different dot-products: you can load a small sub-row from b into a vector (which is why it shouldn't be transposed), broadcast an entry of a into a vector, multiply them together, then add the whole resulting vector into c (even though I describe it like that, in practice you'll want to load some chunks from c into registers first, add to the registers, then store back the results). That way that are no horizontal additions, there is a broadcast which feels a little horizontal but it's much cheaper.
{ "domain": "codereview.stackexchange", "id": 44794, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, matrix", "url": null }
rust, matrix Here's another question where I worked it out a bit more (but in C, so adjust as required), not showing the tiler/repacker that would sit at a higher level to juggle the tiles and make calls to that function. In that answer I didn't go into hard-core optimization, it's just some basic implementation of the principles that you need. Even more detail is available in the classic paper Anatomy of High-Performance Matrix Multiplication
{ "domain": "codereview.stackexchange", "id": 44794, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, matrix", "url": null }
python, beginner, python-3.x, collatz-sequence Title: Automate the boring stuff with python - The Collatz Sequence Question: The Collatz Sequence Write a function named collatz() that has one parameter named number. If number is even, then collatz() should print number // 2 and return this value. If number is odd, then collatz() should print and return 3 * number + 1. Then write a program that lets the user type in an integer and that keeps calling collatz() on that number until the function returns the value 1. import sys def collatz(number): if number % 2 == 0: # check's if number is even. funNumber = number // 2 return funNumber elif number % 2 == 1: # check's if number is odd. funNumber = 3 * number + 1 return funNumber print('Enter a number:') try: inputNumber = int(input()) # check's if input is an integer. except: print('Enter a number!') # if not an integer program quits. sys.exit() whileNumber = collatz(inputNumber) # first function call while whileNumber != 1: # while loop until function returns 1. print(whileNumber) whileNumber = collatz(whileNumber) if whileNumber == 1: # when number is 1 program ends. print(whileNumber) break What do you guys think of my solution? I'm very happy that I did it without cheating - just thinking about the problem and visualising how the code should flow. I did get stuck on the whileNumber = collatz(inputNumber). At first, that line of code was inside the while loop but that just made my entire program freeze. Glad I got it all working.
{ "domain": "codereview.stackexchange", "id": 44795, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, python-3.x, collatz-sequence", "url": null }
python, beginner, python-3.x, collatz-sequence Answer: You should not input() without a prompt argument. You can combine your two modulus operations and the division into one divmod call. Never bare except; in this case you're looking for ValueError. Your input validation is correct but would be friendlier as a loop that does not call exit. whileNumber should be while_number by PEP8. Consider representing the sequence as an iterator function and only printing at the top level (this violates the letter, but not the spirit, of the requirements). Suggested from typing import Iterator def collatz(number: int) -> int: quotient, is_odd = divmod(number, 2) if is_odd: return 3*number + 1 return quotient def collatz_sequence(start: int) -> Iterator[int]: number = start while True: yield number if number == 1: break number = collatz(number) def get_start() -> int: while True: try: return int(input('Enter a number to start the Collatz sequence: ')) except ValueError: pass def main() -> None: start = get_start() for output in collatz_sequence(start): print(output) if __name__ == '__main__': main()
{ "domain": "codereview.stackexchange", "id": 44795, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, python-3.x, collatz-sequence", "url": null }
beginner, python-3.x, number-guessing-game Title: Automate the boring stuff with python - Guess the number Question: import random def guessNumber(guess): if guess == randomNumber: return 'Good job!' elif guess > randomNumber: return'That is to high!' elif guess < randomNumber: return 'That is to low!' guesses = 0 randomNumber = random.randint(1, 20) # print(randomNumber) print('Im thinking of a number between 1 and 20.') answer = '' while answer != 'Good job!': print('Take a guess') answer = guessNumber(int(input())) print(answer) guesses = guesses + 1 if answer == 'Good job!': break print(f'{answer}, You guessed my number in {guesses} guesses!') I have been trying to learn programming for on and off a year. Currently I am on a hot streak of 2 weeks! This is my solution. I did this without cheating or first looking at the answer code. I am very happy with myself that I did this one on my own. Answer: If the user input can't be converted to int, we'll get an exception (and ugly backtrace) here: answer = guessNumber(int(input())) I'd be inclined to create a function for reading integer input, something like this: def input_int(prompt): while True: try: s = input(prompt) return int(s) except ValueError: print(f"Sorry, {s} isn't a valid integer") It's usually a good idea to put your overall functionality in a function called main, and only call that if this is the top level. if __name__ == '__main__': main() This becomes more important when you start writing Python modules, but even at this stage, it helps give the right scope to our variables. I don't like using the global variables. guesses is easily removed, since it's only used in the main() loop. But randomNumber is also used by guessNumber(), so we'll need to pass it in as a parameter: def guessNumber(guess, actual): ⋮
{ "domain": "codereview.stackexchange", "id": 44796, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, python-3.x, number-guessing-game", "url": null }
beginner, python-3.x, number-guessing-game Comparing the user-displayed string seems like a reasonable idea now, but there's actually a problem lurking there. When we add translation to support more languages, that simple test will no longer work. I think the best fix for that is a complete restructure, so that main() sees your hidden number and the user's guess (so it chooses the message to display, and breaks out when guess == actual).
{ "domain": "codereview.stackexchange", "id": 44796, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, python-3.x, number-guessing-game", "url": null }
python, beginner, pandas Title: Flag tukey outliers using python pandas groupby Question: I'm new to python and pandas. I would like to use pandas groupby() to flag values in a df that are outliers. I think I've got it working, but as I'm new to python, wanted to ask if there is a more obvious / pythonic approach. Given input data with two groups, two variables X and Y: n=10000 df= pd.DataFrame({'key': ['a']*n+['b']*n ,"x" : np.hstack(( np.random.normal(10, 1.0, size=n) ,np.random.normal(100, 1.0, size=n) )) ,"y" : np.hstack(( np.random.normal(20, 1.0, size=n) ,np.random.normal(200, 1.0, size=n) )) }) To identify outliers I need to calculate the quartiles and inter-quartile range for each group to calculate the limits. Seemed reasonable to create a function: def get_outlier(x,tukeymultiplier=2): Q1=x.quantile(.25) Q3=x.quantile(.75) IQR=Q3-Q1 lowerlimit = Q1 - tukeymultiplier*IQR upperlimit = Q3 + tukeymultiplier*IQR return (x<lowerlimit) | (x>upperlimit) And then use groupby() and call the function via transform, e.g.: g=df.groupby('key')[['x','y']] df['x_outlierflag']=g.x.transform(get_outlier) df['y_outlierflag']=g.y.transform(get_outlier) df.loc[df.x_outlierflag==True] df.loc[df.y_outlierflag==True] I'm not worried about performance at this point, because the data are small. But not sure if there is a more natural way to do this? For example, it's not clear to me how apply() differs from transform(). Is there an apply() approach that would be better? Is this approach reasonably pythonic / in line with best practices? I would like to stick with pandas. I realize there are SQL approaches etc.
{ "domain": "codereview.stackexchange", "id": 44797, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, pandas", "url": null }
python, beginner, pandas Answer: Consider adding a thousands-separator to 10_000. When generating random sample data for this kind of application, always set a constant seed. There's a lot of formatting here that's non-standard; run a PEP8 linter and/or use PyCharm. The only thing I'll call out specifically is leading commas like ,"y" : np.hstack(( Aside from being non-PEP8-compliant, it's just not legible. Your use of groupby didn't actually work for me (different version of Pandas?), but your [['x', 'y']] just doesn't make sense since you re-index for those column names again later. You can just delete that index operation. Don't transform on a custom function if you can avoid it; it breaks vectorisation. Instead, transform on only quantile which is built into Pandas and should run more quickly; this also means you don't have to write your own inner function. Don't mutate a function argument in-place if you can avoid it. Don't operate on x and y specifically. For this application, just broadcast to all non-key columns. Suggested import numpy as np import pandas as pd from numpy.random import default_rng def flag_outliers(df: pd.DataFrame, tukey_multiplier: float = 2) -> pd.DataFrame: data_cols = df.columns[df.columns != 'key'] groups = df.groupby('key') q1 = groups.transform('quantile', .25) q3 = groups.transform('quantile', .75) iqr = q3 - q1 lower_limit = q1 - tukey_multiplier*iqr upper_limit = q3 + tukey_multiplier*iqr is_outlier = (df[data_cols] < lower_limit) | (df[data_cols] > upper_limit) is_outlier.columns = data_cols + '_outlier_flag' return is_outlier
{ "domain": "codereview.stackexchange", "id": 44797, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, pandas", "url": null }
python, beginner, pandas def test() -> None: n = 10_000 rand = default_rng(seed=0) df = pd.DataFrame({ 'key': ['a']*n + ['b']*n, 'x': np.hstack(( rand.normal(10, 1.0, size=n), rand.normal(100, 1.0, size=n), )), 'y': np.hstack(( rand.normal(20, 1.0, size=n), rand.normal(200, 1.0, size=n), )), }) outliers = flag_outliers(df) # optionally pd.concat() outliers to df print(outliers) if __name__ == '__main__': test()
{ "domain": "codereview.stackexchange", "id": 44797, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, beginner, pandas", "url": null }
java, error-handling, tic-tac-toe, exception Title: Beginner Java Tic-Tac-Toe Question: I had a Tic Tac Toe assignment for class and the program seems to work fine but I feel like the exception/input handling could be done in a much better way. Is this a good way to approach the structure of the app? Is it okay to use try/catch a lot like in here or is it better to try and avoid it? Really newbie question but I'd love your feedback, thanks! public class TicTacToeApp { static Scanner in = new Scanner(System.in); public static void main(String[] args) { char[] gameBoard = new char[9]; Arrays.fill(gameBoard, ' '); char playerOne = ' '; char playerTwo = ' '; System.out.println("Welcome to Tic-Tac-Toe!"); try { playerOne = getPlayerOne(playerOne); playerTwo = getPlayerTwo(playerOne); System.out.println("Player one plays with: " + playerOne); System.out.println("Player two plays with: " + playerTwo); displayBoard(gameBoard); do { System.out.println(playerOne + "'s turn: choose a position from 1-9"); getPosition(gameBoard, playerOne); displayBoard(gameBoard); if (gameOver(gameBoard, playerOne, playerTwo)) break; System.out.println(playerTwo + "'s turn: choose a position from 1-9"); getPosition(gameBoard, playerTwo); displayBoard(gameBoard); } while (!gameOver(gameBoard, playerOne, playerTwo)); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } }
{ "domain": "codereview.stackexchange", "id": 44798, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, error-handling, tic-tac-toe, exception", "url": null }
java, error-handling, tic-tac-toe, exception } /** Displays the board in the console * * @param gameBoard The char[] used for the game */ public static void displayBoard(char[] gameBoard) { System.out.println(gameBoard[0] + " | " + gameBoard[1] + " | " + gameBoard[2]); System.out.println("---------"); System.out.println(gameBoard[3] + " | " + gameBoard[4] + " | " + gameBoard[5]); System.out.println("---------"); System.out.println(gameBoard[6] + " | " + gameBoard[7] + " | " + gameBoard[8]); } /** Gets the mark choice for player one, 'X' or 'O' * * @param playerOne the player to be assigned with a mark * @return the mark that playerOne will play with */ public static char getPlayerOne(char playerOne) { System.out.println("Player one please pick 'X' or 'O' "); while (playerOne != 'X' && playerOne != 'O') { playerOne = in.nextLine().toUpperCase().charAt(0); if (playerOne != 'X' && playerOne != 'O') { System.out.println("Please pick either X or O"); } } return playerOne; } /** Assigns the remaining mark to player two * * @param playerOne the mark player one has chosen * @return the mark that remains for player two */ public static char getPlayerTwo(char playerOne) { if (playerOne == 'X') return 'O'; else return 'X'; }
{ "domain": "codereview.stackexchange", "id": 44798, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, error-handling, tic-tac-toe, exception", "url": null }
java, error-handling, tic-tac-toe, exception /** Checks for victory conditions for either player * * @param gameBoard the char[] used for the game * @param player the player to check for * @return true if the player has won, false otherwise */ public static boolean isVictory(char[] gameBoard, char player) { return ((gameBoard[0] == player) && (gameBoard[1] == player) && (gameBoard[2] == player)) || ((gameBoard[3] == player) && (gameBoard[4] == player) && (gameBoard[5] == player)) || ((gameBoard[6] == player) && (gameBoard[7] == player) && (gameBoard[8] == player)) || ((gameBoard[0] == player) && (gameBoard[3] == player) && (gameBoard[6] == player)) || ((gameBoard[1] == player) && (gameBoard[4] == player) && (gameBoard[7] == player)) || ((gameBoard[2] == player) && (gameBoard[5] == player) && (gameBoard[8] == player)) || ((gameBoard[0] == player) && (gameBoard[4] == player) && (gameBoard[8] == player)) || ((gameBoard[2] == player) && (gameBoard[4] == player) && (gameBoard[6] == player)); } /** Assigns a mark to a position on the board * * @param gameBoard the char[] used for the game * @param player the player whose turn it is to place a mark */ public static void getPosition(char[] gameBoard, char player) { int position = 1; do {
{ "domain": "codereview.stackexchange", "id": 44798, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, error-handling, tic-tac-toe, exception", "url": null }
java, error-handling, tic-tac-toe, exception try { position = Integer.parseInt(in.nextLine()); if (position < 1 || position > 9) { System.out.println("Please enter a number from 1-9"); position = Integer.parseInt(in.nextLine()); } if (gameBoard[position - 1] != ' ') { throw new IllegalArgumentException("Position is occupied. Please choose another position"); } else { gameBoard[position - 1] = player; break; } } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } } while (gameBoard[position - 1] != ' '); } /** Checks if the board is full * * @param gameBoard the char[] used for the game * @return true if the board is full, false otherwise */ public static boolean fullBoard(char[] gameBoard) { for (char c : gameBoard) { if (c == ' ') { return false; } } return true; } /** Checks for end of game conditions (victory or draw) * * @param gameBoard the char[] used for the game * @param playerOne First player * @param playerTwo second player * @return True and a message if the game has ended, False otherwise */ public static boolean gameOver(char[] gameBoard, char playerOne, char playerTwo) { boolean gameOver = false; if (isVictory(gameBoard, playerOne)) { System.out.println(playerOne + "'s win!"); gameOver = true; } else if (isVictory(gameBoard, playerTwo)) { System.out.println(playerTwo + "'s win!"); gameOver = true; } else if (fullBoard(gameBoard)) { System.out.println("Game ended in a draw"); gameOver = true; } return gameOver; } }
{ "domain": "codereview.stackexchange", "id": 44798, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, error-handling, tic-tac-toe, exception", "url": null }
java, error-handling, tic-tac-toe, exception Answer: Overall, the structure of the app is reasonable. Methods are named clearly and do what the name suggests. It misses some of the benefits of object-oriented programming because all the pieces that make up the state of the game (like the game board) are declared in main and must be passed to each other method.* Additionally, methods should generally have the most restrictive viable access modifier; in this case, all the methods except main can be private instead of public. Regarding exceptions, in my experience, there are usually better ways to handle errors in self-contained code like this app. In this case, the try/catch in getPosition makes sense as it catches both the NumberFormatException from Integer.parseInt and the IllegalArgumentException your code throws. However, the try/catch in main is unnecessary since getPosition already catches the exceptions that may be thrown. *Full object-oriented programming generally requires more than 1 class in Java due to the static modifier of the main method.
{ "domain": "codereview.stackexchange", "id": 44798, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, error-handling, tic-tac-toe, exception", "url": null }
beginner, c, collatz-sequence Title: Collatz sequence in C Question: First of all, if you're unfamiliar with the Collatz sequence, it recursively applies the following function to an integer: $$ f(n) = \begin{cases} n/2 & \text{if } n \equiv 0 \pmod{2}, \\ 3n+1 & \text{if } n \equiv 1 \pmod{2}. \end{cases} $$ What I wanted to do was to make a program that would: Quit if 0 was inputted Reprompt the user if something invalid was inputted For positive integers, e.g. 7, output "7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1" For negative integers, e.g. -3, where doing the above would output "-3 -8 -4 -2 -1 -2 -1 -2... [forever repeating]", output something like "-3 -8 -4 (-2 -1)", as "-2 -1" repeats forever. This is what I have, which fits most of the criteria, but could definitely be improved somehow. What do you guys think?: #include <stdio.h> #include <stdbool.h> long long cltz(long long x);
{ "domain": "codereview.stackexchange", "id": 44799, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, collatz-sequence", "url": null }
beginner, c, collatz-sequence int main() { long long n; char input[256]; while (1) { printf("Enter a positive or negative integer (0 to quit): "); if (fgets(input, sizeof(input), stdin) == NULL) break; if (sscanf(input, "%lld", &n) != 1) continue; if (n == 0) break; bool sign = n < 0; long long on = n, slow = n, fast = n; while (sign) { slow = cltz(slow); fast = cltz(cltz(fast)); if (fast == slow) break; } if (on == slow && sign) printf("( "); printf("%lld ", n); while (n != 1) { n = cltz(n); if (n == slow) break; printf("%lld ", n); } long long c_slow = cltz(slow); if (sign && on != slow) { printf("( %lld ", slow); while (c_slow != slow) { printf("%lld ", c_slow); c_slow = cltz(c_slow); } printf(")"); } if (on == slow && sign) printf(")"); printf("\n"); } return 0; } long long cltz(long long x) { return (x & 1) ? ((x << 1) + x + 1) : (x >> 1); } Answer: Let the compile optimize Rather than (x << 1) + x + 1) : (x >> 1), use (x*3 + 1) : (x/2) to match the algorithm and enable your compiler's optimizations. If you can optimize better than the compiler, get a better compiler. Note that x%2 is not the same as x mod 2. Stay with x & 1 or use x % 2llu. Detect overflow cltz() may overflow. Should you want to detect this: #include <limits.h> #include <stdio.h> #include <stdlib.h> // Highest odd value valid for `cltz()` #define CLTX_ODD_HIGH ((LLONG_MAX - 1)/3) long long cltz(long long x) { // return (x & 1) ? ((x << 1) + x + 1) : (x >> 1); if (x & 1) { if (llabs(x) > CLTX_ODD_HIGH) { fprintf(stderr, "Overflow with %lld\n", x); exit(EXIT_FAILURE); } return x*3 + 1; } return x / 2; }
{ "domain": "codereview.stackexchange", "id": 44799, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, collatz-sequence", "url": null }
beginner, c, collatz-sequence Design Consider bool sign = n < 0; ... if (on == slow && sign) printf(")"); printf("\n"); as a helper function. That is, separate user input from doing the task. Easier to perform testing and recover from overflow.
{ "domain": "codereview.stackexchange", "id": 44799, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, collatz-sequence", "url": null }
perl Title: A file renamer in Perl that gets rid of spaces, commas, dots, and dashes Question: I often find myself working with files I get from other users that mostly work on Windows machines (I, myself, am on a macOS) and they tend to name their files in all sorts of (weird & difficult to handle) ways. For example, the files I get may contain any or all of the following: a space a dash a comma one or more dots, not counting the extension dot. So, I might get these files: This is a file example, 2nd edition.pdf Another.File.Name.I.Get.To.Work.With.pdf this-file-is-actually-named-this-way, 7th edition.pdf Having said the above, to make my life easier, I've learned some Perl (heard it's great at string handling) and wrote myself a program that takes a directory as an argument and renames all files within it. By default, I use the _ as the replace_character and .pdf as the file extension, as these are the types of files I mostly work with. Can anyone of you, kind Perl mongers, review the code in terms of readability, ease of maintenance, and usability? I am aware of TIMTOWTDI (There’s more than one way to do it!), but, as I've mentioned, I've just started learning Perl and would like to get a (sort of) canonical answer that focuses on writing clean, maintainable Perl, not a throw-away program. I'm on this Perl: This is perl 5, version 36, subversion 1 (v5.36.1) built for darwin-thread-multi-2level And here's my code: #!/usr/bin/perl use strict; use warnings; use Getopt::Long; use File::Find; use File::Copy; use version; our $VERSION = qv('1.0.0'); =begin comment Function sanitize_file_name sanitizes the file name by removing spaces, commas, dashes and dots except the dot before the file extension. =end comment =cut sub sanitize_file_name { my ($file_name, $replace_char) = @_; # Remove spaces $file_name =~ s/\s+/$replace_char/g; # Remove commas and dashes $file_name =~ s/[,-]+/$replace_char/g;
{ "domain": "codereview.stackexchange", "id": 44800, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "perl", "url": null }
perl # Remove commas and dashes $file_name =~ s/[,-]+/$replace_char/g; # Replace consecutive underscores with a single underscore $file_name =~ s/(?<!\.)_+/$replace_char/g; # Replace dots with underscores, except the one before the file extension $file_name =~ s/(?<=\b)(?<!\.)\.(?![^.]+$)/$replace_char/g; return $file_name; } # Function to get the file name from a path sub get_file_name { my ($file) = @_; my @path = split /\//, $file; return $path[-1]; } # Function to rename the file sub rename_file { my ($old_name, $new_name) = @_; my $old_file_name = get_file_name($old_name); my $new_file_name = get_file_name($new_name); if ($old_file_name ne $new_file_name) { rename $old_name, $new_name; print "File renamed: '$old_file_name' -> '$new_file_name'\n"; } } # Function to process files in a directory sub process_files { my ($file, $extension, $replace_char) = @_; return unless -f $file; return unless $file =~ /\.(?:$extension)$/i; my $new_file_name = sanitize_file_name($file, $replace_char); my $new_full_path = $file; $new_full_path =~ s/([^\/]+)$/$new_file_name/; rename_file($file, $new_full_path); } my $replace_char = '_'; # Default replacement character my $extension = 'pdf'; # Default file extension my $help; # Parse command line options GetOptions( 'replace=s' => \$replace_char, 'ext=s' => \$extension, 'help' => \$help ) or die 'Error in command line arguments\n'; # Display help message if (defined $help) { print "Usage: $0 [options] DIRECTORY\n" or croak $!; print "Options:\n"; print " --replace=CHAR Replace spaces with specified CHAR (default: underscore)\n"; print " --ext=EXTENSION Process files with specified EXTENSION (default: pdf)\n"; print " --help Display this help message\n"; exit; }
{ "domain": "codereview.stackexchange", "id": 44800, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "perl", "url": null }
perl # Check if a directory is provided if (@ARGV != 1) { print "Error: No directory provided\n"; die "Usage: $0 [options] DIRECTORY\n"; } my $directory = $ARGV[0]; # Check if the directory exists if (-d $directory) { find(sub { process_files($File::Find::name, $extension, $replace_char) }, $directory); } else { die "Error: Directory '$directory' not found\n"; } Answer: You have done an excellent job of using good coding style: good layout, good use of subroutines and good leveraging of other's code (modules). It is great that you used strict and warnings. Here are some improvements you can make. Remove the unused File::Copy module. There is no need to call croak in this line: print "Usage: $0 [options] DIRECTORY\n" or croak $!; The print will likely never fail, and even if it did, you want to execute the remaining print lines. Also, croak is not a built-in function; it is from the Carp module, which you did not use. Consider using the Pod::Usage module and POD code instead of the help statements you have. This gives you a Unix-style manpage for free when you use the perldoc command. For example, you can add this POD at the end of your code: =head1 SYNOPSIS renamer [options] DIRECTORY Options: --replace=CHAR Replace spaces with specified CHAR (default: underscore) --ext=EXTENSION Process files with specified EXTENSION (default: pdf) --help Display this help message =head1 DESCRIPTION A file renamer that gets rid of spaces, commas, dots, and dashes. =cut Then you can run this command on your command line to get the manpage (assuming you named the Perl file renamer): perldoc renamer I ran podchecker on your code, and it complained about your =begin POD. I added line breaks to fix the errors: =begin comment Function sanitize_file_name sanitizes the file name by removing spaces, commas, dashes and dots except the dot before the file extension. =end comment =cut
{ "domain": "codereview.stackexchange", "id": 44800, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "perl", "url": null }
perl =end comment =cut When I use Getotp::Long, I prefer to use a single hash variable (like %opt) instead of several scalar variables. I find it cleaner. Indentation is excellent, except for the ext line in the GetOptions call. This is a bit more consistent: GetOptions( 'replace=s' => \$replace_char, 'ext=s' => \$extension, 'help' => \$help ) or die "Error in command line arguments\n"; I also changed the single quotes to double quotes in the die statement because it prints a literal \n instead of the intended newline character. I ran your code through perlcritic to find that one; sometimes it does find bugs in your code. I prefer to explicitly declare all functions that are imported from modules: use Getopt::Long qw(GetOptions); use File::Find qw(find); This makes it clear where the functions are from, and it can limit adding lots of functions into the namespace if a module exports many functions by default. I prefer to have one statement per line: use version; our $VERSION = qv('1.0.0'); Consider the File::Spec module instead of your get_file_name sub.
{ "domain": "codereview.stackexchange", "id": 44800, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "perl", "url": null }
python, machine-learning Title: Movie genre classification using machine learning Question: could you review my below code to train a machine learning model to classify movie genres? I've used the data from Kaggle #!/usr/bin/env python # coding: utf-8 import pandas as pd import numpy as np import ast import joblib from collections import Counter from sklearn.model_selection import train_test_split from sklearn.preprocessing import MultiLabelBinarizer from sklearn.pipeline import Pipeline from sklearn.multioutput import MultiOutputClassifier from sklearn.multiclass import OneVsRestClassifier from sklearn.naive_bayes import MultinomialNB from sklearn.linear_model import LogisticRegression from sklearn.metrics import hamming_loss, accuracy_score, f1_score, classification_report from sklearn.feature_extraction.text import TfidfVectorizer from sentence_transformers import SentenceTransformer import xgboost as xgb
{ "domain": "codereview.stackexchange", "id": 44801, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, machine-learning", "url": null }
python, machine-learning def preprocess_data(): print('Preprocessing data...') df = pd.read_csv('../data/movies_metadata.csv', low_memory=False) df = df[['overview', 'genres']] df.dropna(inplace=True) # Clean up the genres column df['genres'] = df['genres'].apply(ast.literal_eval) \ .apply(lambda x: [i['name'] for i in x]) # Filter out rare genres counter = Counter([genre for sublist in df['genres'] for genre in sublist]) GENRE_FREQ_THRESHOLD = 10 popular_genres = [genre for genre, count in counter.items() if count >= GENRE_FREQ_THRESHOLD] df['genres'] = df['genres'].apply(lambda genres: [genre for genre in genres if genre in popular_genres]) # Drop rows with no popular genre df['genres'] = df['genres'].apply(lambda genres: genres if len(genres) > 0 else np.nan) df.dropna(subset=['genres'], inplace=True) # One hot encoding of genres mlb = MultiLabelBinarizer() df_genres = pd.DataFrame(mlb.fit_transform(df.pop('genres')), columns=mlb.classes_, index=df.index) joblib.dump(mlb, '../models/mlb.joblib') df = df.join(df_genres) df.to_csv('../data/processed_movies_metadata.csv', index=False) def train_model(X_train, y_train, encoder, multilabeler, estimator): if encoder == 'TfIdf': encoder_model = TfidfVectorizer().fit(X_train) elif encoder == 'SentenceTransformer': encoder_model = SentenceTransformer('all-MiniLM-L6-v2') encoder_model.transform = encoder_model.encode X_encoded = encoder_model.transform(X_train) classifier = multilabeler(estimator=estimator) classifier.fit(X_encoded, y_train) return (encoder_model, classifier)
{ "domain": "codereview.stackexchange", "id": 44801, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, machine-learning", "url": null }
python, machine-learning if __name__ == '__main__': preprocess_data() df = pd.read_csv('../data/processed_movies_metadata.csv') X = df['overview'] y = df.drop(['overview'], axis=1) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Reset indices so that SentenceTransformer encode doesn't complain X_train.reset_index(drop=True, inplace=True) y_train.reset_index(drop=True, inplace=True) X_test.reset_index(drop=True, inplace=True) y_test.reset_index(drop=True, inplace=True) print('Training model...') encoder = 'SentenceTransformer' multilabeler = OneVsRestClassifier estimator = LogisticRegression() encoder_model, classifier_model = train_model(X_train, y_train, encoder, multilabeler, estimator) y_pred = classifier_model.predict(encoder_model.transform(X_test)) report = classification_report(y_test, y_pred, output_dict=True) print("F1 Score: %.4f"%(report['micro avg']['f1-score'])) print("Hamming Loss: %.4f"%(hamming_loss(y_test, y_pred))) joblib.dump(encoder_model, '../models/encoder_model.joblib') joblib.dump(classifier_model, '../models/classifier_model.joblib') Answer: Nice variable names throughout, very standard. coding: utf-8 That has been the default encoding for a very long time, so you might remove it. I can't imagine there's anything in your toolchain for which it makes a difference. if __name__ == '__main__': preprocess_data() df = pd.read_csv('../data/processed_movies_metadata.csv')
{ "domain": "codereview.stackexchange", "id": 44801, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, machine-learning", "url": null }