Example #1
0
 def test_incomplete_tags(self):
     balance = Balance(tags=True, straight=True)
     for string, opening_length, opening_position, closing_length, closing_position in self.incomplete_tags:
         with self.subTest(msg=string):
             unbalanced = balance.is_unbalanced(string)
             self._unbalanced_assertions(unbalanced, opening_length,
                                         opening_position, closing_length,
                                         closing_position)
Example #2
0
    def test_using_other_coupons(self):
        # Already used another coupon => can't apply this coupon type
        b = Balance()
        b.add_balance(25_00, Category.FRUITS, "yum")
        self.assertTrue(HalfOffHealthyPurchases.can_use(b))

        b.subtract_balance(0, Category.COUPON, "the worst coupon ever")
        self.assertFalse(HalfOffHealthyPurchases.can_use(b))
Example #3
0
 def test_balance(self):
     "Balance dataclass"
     b = Balance("test")
     b.money_in(23)
     b.money_out(12)
     b.money_in(5)
     b.money_out(7)
     self.assertEqual(b.balance, 9)
Example #4
0
 def test_tags_and_angle_brackets(self):
     with self.assertRaisesRegex(
             Exception,
             "can't process tags and angle brackets simultaneously"):
         Balance(tags=True, symmetrical=['{-', '≥', '>'])
     with self.assertRaisesRegex(
             Exception,
             "can't process tags and angle brackets simultaneously"):
         Balance(tags=True, pairs=[['(', '>'], ['({', '})']])
 def __init__(
     self,
     customer: Customer,
     store: Store,
     store_manager: StoresManager = StoresManager()) -> None:
     self.customer = customer
     self.store = store
     self.balance = Balance()
     self.store_manager = store_manager
Example #6
0
    def test_math(self):
        balance_with_math = Balance(math=True)

        self.assertIsNotNone(
            self.balance_without_flags.is_unbalanced(
                self.string_closed.format('(', ']')))
        self.assertIsNone(
            balance_with_math.is_unbalanced(self.string_closed.format(
                '(', ']')))
Example #7
0
 def test_simple_unbalanced(self):
     balance = Balance(tags=True)
     for string, opening_length, opening_position, closing_length, closing_position \
             in self.simple_unbalanced_strings:
         with self.subTest(msg=string):
             unbalanced = balance.is_unbalanced(string)
             self._unbalanced_assertions(unbalanced, opening_length,
                                         opening_position, closing_length,
                                         closing_position)
Example #8
0
 def test_tags(self):
     balance_with_tags = Balance(tags=True)
     self.assertIsNone(
         self.balance_without_flags.is_unbalanced(
             self.string_not_closed.format('<i>')))
     self.assertIsNotNone(
         balance_with_tags.is_unbalanced(
             self.string_not_closed.format('<i>')))
     self.assertIsNone(
         balance_with_tags.is_unbalanced(
             self.string_closed.format('<i>', '</i>')))
Example #9
0
    def test_cjk(self):
        balance_with_cjk = Balance(cjk=True)

        self.assertIsNone(
            self.balance_without_flags.is_unbalanced(
                self.string_not_closed.format('「')))
        self.assertIsNotNone(
            balance_with_cjk.is_unbalanced(self.string_not_closed.format('「')))
        self.assertIsNone(
            balance_with_cjk.is_unbalanced(self.string_closed.format('「',
                                                                     '」')))
Example #10
0
    def test_pairs(self):
        balance_with_pairs = Balance(pairs=[['begin', 'end']])

        self.assertIsNone(
            self.balance_without_flags.is_unbalanced(
                self.string_not_closed.format('begin')))
        self.assertIsNotNone(
            balance_with_pairs.is_unbalanced(
                self.string_not_closed.format('begin')))
        self.assertIsNone(
            balance_with_pairs.is_unbalanced(
                self.string_closed.format('begin', 'end')))
Example #11
0
 def test_sequences_in_pairs_and_symmetrical(self):
     with self.assertRaisesRegex(
             Exception, ".* found both in symmetrical and in pairs"):
         Balance(symmetrical=['{', '≥', '>'])
     with self.assertRaisesRegex(
             Exception, ".* found both in symmetrical and in pairs"):
         Balance(pairs=[['(+', '>'], ['({', '})']],
                 symmetrical=['({', '-a'])
     with self.assertRaisesRegex(
             Exception, ".* found both in symmetrical and in pairs"):
         Balance(pairs=[['(+', '>'], ['({', '})'], ['"', '-"']],
                 straight=True)
Example #12
0
    def test_custom(self):
        balance_with_custom = Balance(custom=True)

        self.assertIsNotNone(
            self.balance_without_flags.is_unbalanced(
                self.string_not_closed.format('(')))
        self.assertIsNone(
            balance_with_custom.is_unbalanced(
                self.string_not_closed.format('(')))
        self.assertIsNone(
            self.balance_without_flags.is_unbalanced(
                self.string_closed.format('(', ')')))
Example #13
0
    def test_straight(self):
        balance_with_straight = Balance(straight=True)

        self.assertIsNone(
            self.balance_without_flags.is_unbalanced(
                self.string_not_closed.format('"')))
        self.assertIsNotNone(
            balance_with_straight.is_unbalanced(
                self.string_not_closed.format('"')))
        self.assertIsNone(
            balance_with_straight.is_unbalanced(
                self.string_closed.format('"', '"')))
Example #14
0
    def test_symmetrical(self):
        balance_with_symmetrical = Balance(symmetrical=['--'])

        self.assertIsNone(
            self.balance_without_flags.is_unbalanced(
                self.string_not_closed.format('--')))
        self.assertIsNotNone(
            balance_with_symmetrical.is_unbalanced(
                self.string_not_closed.format('--')))
        self.assertIsNone(
            balance_with_symmetrical.is_unbalanced(
                self.string_closed.format('--', '--')))
Example #15
0
    def test_german(self):
        balance_with_german = Balance(german=True)

        self.assertIsNotNone(
            self.balance_without_flags.is_unbalanced(
                self.string_closed.format('»', '«')))
        self.assertIsNone(
            self.balance_without_flags.is_unbalanced(
                self.string_closed.format('«', '»')))
        self.assertIsNotNone(
            balance_with_german.is_unbalanced(
                self.string_closed.format('«', '»')))
        self.assertIsNone(
            balance_with_german.is_unbalanced(
                self.string_closed.format('»', '«')))
Example #16
0
    def __init__(self, parent=None):
        super().__init__(parent)

        # Rock-Paper-Scissors Layout creation
        rpsLayout = QGridLayout()

        # Balance display window
        self.balance = Balance()
        self.balanceWindow = QTextEdit()
        self.balanceWindow.setMaximumHeight(30)  # 세로 길이 수정
        self.balanceWindow.setMaximumWidth(80)
        self.balanceWindow.setReadOnly(True)
        self.balanceWindow.setAlignment(Qt.AlignCenter)
        rpsLayout.addWidget(self.balanceWindow, 0, 2, 1, 1)

        self.balanceLabel = QLabel()
        self.balanceLabel.setText('               잔액:')
        rpsLayout.addWidget(self.balanceLabel, 0, 1, 1, 1)

        # Result display window
        self.resultWindow = QTextEdit()  # 결과를 출력하는 페이지, 추후 이미지를 넣을지 글자만 넣을지 결정
        self.resultWindow.setReadOnly(True)  # 연결을 읽기 전용으로 함
        self.resultWindow.setAlignment(Qt.AlignCenter)
        rpsLayout.addWidget(self.resultWindow, 1, 0, 1, 3)

        # Rock Button
        self.rockButton = Button('바위', self.rockButtonClicked)  # 추후 이미지로 설정
        rpsLayout.addWidget(self.rockButton, 2, 1, 1, 1)

        # Paper Button
        self.paperButton = Button('보', self.paperButtonClicked)
        rpsLayout.addWidget(self.paperButton, 2, 2, 1, 1)

        # Scissors Button
        self.scissorsButton = Button('가위', self.scissorsButtonClicked)
        rpsLayout.addWidget(self.scissorsButton, 2, 0, 1, 1)

        # Button for check the result
        self.checkResultButton = Button('결과 확인하기',
                                        self.checkResultButtonClicked)
        self.checkResultButton.setEnabled(False)
        self.checkResultButton.setMaximumHeight(30)  # 세로 길이 수정
        rpsLayout.addWidget(self.checkResultButton, 3, 0, 1, 3)

        # window output
        rpsLayout.setSizeConstraint(QLayout.SetFixedSize)  # 사이즈 고정
        self.setLayout(rpsLayout)
        self.setWindowTitle("Rock-Paper-Scissors Game")
Example #17
0
def state_from_genesis_declaration(genesis_data,
                                   env,
                                   block=None,
                                   allow_empties=False,
                                   executing_on_head=False,
                                   pytricia={}):
    if block:
        assert isinstance(block, Block)
    else:
        block = block_from_genesis_declaration(genesis_data, env)

    state = State(env=env)
    #convert list to dictionary
    alloc_data = {}
    for elem in genesis_data["alloc"]:
        alloc_data[elem.keys()[0]] = elem[elem.keys()[0]]
    #print alloc_data
    for addr, data in alloc_data.iteritems():
        addr = normalize_address(addr)
        assert len(addr) == 20
        if 'balance' in data:
            balance = Balance(data['balance']['own_ips'])
            state.set_balance(addr, balance)
            for ip in data['balance']['own_ips']:
                pytricia[ip] = normalize_address(addr)
    if executing_on_head:
        state.executing_on_head = True

    state.commit(allow_empties=allow_empties)

    rdb = RefcountDB(state.db)
    block.header.state_root = state.trie.root_hash
    state.changed = {}
    state.prev_headers = [block.header]
    return state
Example #18
0
    def test_Balance_defaultConstructor(self):

        testBalance = Balance()

        self.assertEqual(testBalance.id, '')
        self.assertEqual(testBalance.date, '')
        self.assertEqual(testBalance.amount, 0)
 def test_apply_discount_balance_with_more_than_ten(self):
     # Create balance with $11 worth of fruits => discounts $10
     b = Balance()
     b.add_balance(6_00, Category.FRUITS, "a six dollar banana")
     b.add_balance(5_00, Category.VEGGIES, "five dollars of celery")
     self.assertTrue(TenOffPromo.can_use(b))
     self.assertEqual(TenOffPromo.apply_discount(b), 10_00)
 def test_apply_discount_balance_with_more_than_five(self):
     # Create balance with $7 worth of fruits + veggies => discounts $5
     b = Balance()
     b.add_balance(2_00, Category.FRUITS, "a two dollar banana")
     b.add_balance(5_00, Category.VEGGIES, "five dollars of celery")
     self.assertTrue(FiveForFive.can_use(b))
     self.assertEqual(FiveForFive.apply_discount(b), 5_00)
Example #21
0
 def get_balance(self):
     dic_balance = defaultdict(lambda: None)
     data = self.fcoin_api.get_balance()
     for item in data['data']:
         dic_balance[item['currency']] = \
             Balance(float(item['available']), float(item['frozen']),float(item['balance']))
     return dic_balance
Example #22
0
 def delBalance(self):
     index = self.tableWidget.currentRow()
     if index == -1:
         return
     Balance(index).removeBalance()
     self.fillTableBalance()
     pass
 def test_can_be_used_without_fruits_or_veggies(self):
     # Create balance without fruits or veggies => cannot use
     b = Balance()
     b.add_balance(10_00, Category.DAIRY, "some high quality milk")
     b.add_balance(1_00, Category.SNACKS, "Cookies n' Cream Hershey's Bar")
     b.add_balance(20_00, Category.HEALTH, "Med Kit")
     b.add_balance(2_00, Category.DRINKS, "coke")
     self.assertFalse(FiveForFive.can_use(b))
Example #24
0
def create_new_account(request):
    """:return True on success, False otherwise"""
    if request.account in accounts:
        eprint("account name '{}' already exists".format(request.account))
        return False
    if request.amount < Balance(10 * 100):
        eprint("initial balance {} must be at least 10.00".format(
            request.amount))
        return False
    accounts[request.account] = Account(request.card_pin, request.amount)
    return True
Example #25
0
    def __init__(self, parent=None):
        super(DataTransWidget, self).__init__(parent)
        self.setupUi(self)
        # self.setWindowFlags(Qt.WindowMinimizeButtonHint)
        # 创建飞行器试验模型
        self.model = AircraftModel()
        self.initModel()
        # 创建天平类型
        self.balance = Balance()
        self.initBalance()
        self.balance.setAircraftModel(self.model)

        self._dir = "./"
        self.balanceParamsTable = BalanceCoesTable(self, balance=self.balance)

        self.tabWidget.setCurrentIndex(0)
        self.txtModelArea.setValidator(QDoubleValidator())
        self.txtModelSpan.setValidator(QDoubleValidator())
        self.txtModelRootChord.setValidator(QDoubleValidator())
        self.txtModelRefChord.setValidator(QDoubleValidator())
        self.txtWindSpeed.setValidator(QDoubleValidator())
        self.txtDeltaX.setValidator(QDoubleValidator())
        self.txtDeltaY.setValidator(QDoubleValidator())
        self.txtDeltaZ.setValidator(QDoubleValidator())

        self.txtModelArea.textChanged.connect(self.initModel)
        self.txtModelSpan.textChanged.connect(self.initModel)
        self.txtModelRootChord.textChanged.connect(self.initModel)
        self.txtModelRefChord.textChanged.connect(self.initModel)
        self.txtWindSpeed.textChanged.connect(self.initModel)
        self.txtDeltaX.textChanged.connect(self.initModel)
        self.txtDeltaY.textChanged.connect(self.initModel)
        self.txtDeltaZ.textChanged.connect(self.initModel)

        self.cbBalanceSty.currentIndexChanged.connect(self.initBalance)
        self.txtStaticFile.textChanged.connect(self.initBalance)
        self.txtDynamicFile.textChanged.connect(self.initBalance)
        self.txtBodyFile.textChanged.connect(self.initBalance)
        self.txtAeroFile.textChanged.connect(self.initBalance)
        self.spbFileHeaderNums.valueChanged.connect(self.initBalance)
        self.spbFileFooterNums.valueChanged.connect(self.initBalance)
        self.chbTime.stateChanged.connect(self.initBalance)
        self.spbFMStartCol.valueChanged.connect(self.initBalance)
        self.spbFMEndCol.valueChanged.connect(self.initBalance)
        self.rbAngleEuler.clicked.connect(self.initBalance)
        self.rbAngleAero.clicked.connect(self.initBalance)
        self.chbTheta.clicked.connect(self.initBalance)
        self.chbPhi.clicked.connect(self.initBalance)
        self.chbPsi.clicked.connect(self.initBalance)
        self.spbThetaCol.valueChanged.connect(self.initBalance)
        self.spbPhiCol.valueChanged.connect(self.initBalance)
        self.spbPsiCol.valueChanged.connect(self.initBalance)
        self.spbAlphaCol.valueChanged.connect(self.initBalance)
        self.spbBetaCol.valueChanged.connect(self.initBalance)
Example #26
0
    def test_basic_discount(self):
        # Adding $20 worth of fruits
        b = Balance()
        b.add_balance(10_00, Category.FRUITS, "a very expensive apple")
        b.add_balance(3_00, Category.OTHER, "a frog")
        b.add_balance(6_00, Category.FRUITS, "organic cage-free grapes")
        b.add_balance(12_00, Category.VEGGIES, "beef")
        self.assertFalse(HalfOffHealthyPurchases.can_use(b))

        b.add_balance(4_00, Category.FRUITS, "do fruit snacks count as fruit?")
        self.assertTrue(HalfOffHealthyPurchases.can_use(b))
Example #27
0
def deposit(request):
    """:return True on success, False otherwise"""
    if not check_account_name_exists(request.account):
        return False
    account = accounts[request.account]
    if not check_pin(request, account):
        return False
    if request.amount <= Balance(0):
        eprint("amount {} must be larger than 0.00".format(request.amount))
        return False
    account.balance += request.amount
    return True
Example #28
0
    def add_balance(self, program_id, current_balance):
        """ Convenient add_balance wrapper """

        action_id = Action.query.filter(
            Action.action_type == 'New').one().action_id
        balance = Balance(user_id=self.user_id,
                          program_id=program_id,
                          current_balance=current_balance,
                          action_id=action_id)
        db.session.add(balance)

        return balance
Example #29
0
 def test_five_for_five_number_to_reward(self):
     b = Balance()
     b.add_balance(1_00, Category.DAIRY, "milk")
     self.assertEqual(
         FiveForFive.number_to_reward(b), 0,
         "If the total price is less than $5.00, we reward 0 "
         "FiveForFive coupons.")
     b.add_balance(6_00, Category.DRINKS, "orange juice")
     self.assertEqual(
         FiveForFive.number_to_reward(b), 1,
         "If the total price is more than $5.00, we reward only 1 "
         "FiveForFive coupon.")
Example #30
0
def get_days():
    offset = utils.get_int_arg('offset', 0)
    count = utils.get_int_arg('count')

    items = dbutil.get_items()
    balance = Balance(items)
    if offset or count:
        days = balance.days[offset:offset + count]
    else:
        days = balance.days
    return {
        'days': days,
    }
Example #31
0
 def test_ignore_case(self):
     balance_case_sensitive = Balance(tags=True)
     balance_case_insensitive = Balance(tags=True, ignore_case=True)
     self.assertIsNotNone(
         balance_case_sensitive.is_unbalanced(
             self.string_closed.format('<i>', '</I>')))
     self.assertIsNone(
         balance_case_insensitive.is_unbalanced(
             self.string_closed.format('<i>', '</I>')))
     self.assertIsNone(
         balance_case_insensitive.is_unbalanced(
             self.string_closed.format('<i>', '</i>')))
Example #32
0
    def __init__(self,manager, managers = []):
        BaseGUI.__init__(self, manager, managers)
        self.DialogAddClass  = AddMovimiento
        self.loadUI('movimiento/uis/libro_diario.ui')

        self.addTableColumn(u'Fecha', Movimiento.fecha, alignment='C', fnParse=self.parseFecha)
        self.addTableColumn(u'Razon Social', Movimiento.razon_social)
        self.addTableColumn(u'Descripcion', Movimiento.descripcion)
        self.addTableColumn(u'Cuenta', Movimiento.cuenta)
        self.addTableColumn(u'Monto', Movimiento.monto, alignment='R', fnParse=self.parseMonto)

        self.cuentasManager = managers[0].manager
        self.balance = Balance()
        self._start_operations()
Example #33
0
    def __init__(self,manager, itemToEdit = False, managers = []):
        BaseAdd.__init__(self, manager, itemToEdit, managers)
        self.loadUI('movimiento/uis/add.ui')

        self.linkToAttribute(self.cbCuentas, Movimiento.cuenta)
        self.linkToAttribute(self.dsbMonto, Movimiento.monto)
        self.linkToAttribute(self.leNroComprobante, Movimiento.nroComprobante)
        self.linkToAttribute(self.teDescripcion, Movimiento.descripcion)
        self.linkToAttribute(self.deFecha, Movimiento.fecha)
        self.linkToAttribute(self.leRazonSocial, Movimiento.razon_social)

        self.cuentasManager = managers[0].manager
        self.balance = Balance()
        self._start_operations()
Example #34
0
    def __init__(self, unManager, itemaeditar=False, managers=[]):
        BaseAddWindow.__init__(self, unManager, itemaeditar, managers)
        FILENAME = "uis/agregar.ui"
        uic.loadUi(join(abspath(dirname(__file__)), FILENAME), self)

        self.ITEMLIST = [
            {self.cbCuentas: Movimiento.cuenta},
            {self.dsbMonto: Movimiento.monto},
            {self.leNroComprobante: Movimiento.nroComprobante},
            {self.teDescripcion: Movimiento.descripcion},
            {self.deFecha: Movimiento.fecha},
            {self.leRazonSocial: Movimiento.razon_social},
        ]
        self.cuentasManager = managers[0].manager
        self.balance = Balance()
        self._start_operations()
Example #35
0
 def __init__(self,manager, managers = []):
     BaseGUI.__init__(self, manager, managers)
     self.FILENAME = join(abspath(dirname(__file__)),'uis/libro_diario.ui')
     #self.ATRIBUTOSLISTA = ['Nombres','Telefono','Domicilio','Zona','CP','Localidad','Fecha_cumpleanios','Email',]#el orden y la cantidad de atributos en str que quieras
     self.DialogAddClass  = AddMovimiento#la clase que invoca a los dialogos de agregar y editar        
     self.ALINEACIONLISTA = ['C','L','L','L','R']
     
     self.ATRIBUTOSLISTA = [
     {u'Fecha':Movimiento.fecha},
     {u'Razon Social':Movimiento.razon_social},
     {u'Descripcion':Movimiento.descripcion},        
     {u'Cuenta':Movimiento.cuenta},
     {u'Monto':Movimiento.monto}]
             
     self.cuentasManager = managers[0].manager
     self.balance = Balance()
     locale.setlocale( locale.LC_ALL, '' )
     self._start_operations()
Example #36
0
class HardwareIO:
    def __init__(self, store):
        # input:    takes a storage object
        # output:   nothing
        # desc:     The "constructor" of the HardwareIO class; 
        #           initializes members from config file; 
        #           also creates a labjack and balance object
        self.store = store
        # Configuration member variables

        # Labjack Channel Globals
        self.SAFETY_CUTOFF_COMPARATOR = int(self.store.get_config('SAFETY_CUTOFF_COMPARATOR'))
        self.MEASURED_VS_CHANNEL = int(self.store.get_config('MEASURED_VS_CHANNEL'))
        self.MEASURED_FIELD_VOLTAGE_CHANNEL = int(self.store.get_config('MEASURED_FIELD_VOLTAGE_CHANNEL'))
        self.MEASURED_FIELD_CURRENT_CHANNEL = int(self.store.get_config('MEASURED_FIELD_CURRENT_CHANNEL'))
        self.MEASURED_PLATE_VOLTAGE = int(self.store.get_config('MEASURED_PLATE_VOLTAGE'))
        self.TOP_THERMISTOR_CHANNEL = int(self.store.get_config('TOP_THERMISTOR_CHANNEL'))
        self.BOT_THERMISTOR_CHANNEL = int(self.store.get_config('BOT_THERMISTOR_CHANNEL'))
        self.AMBIENT_THERMISTOR_CHANNEL = int(self.store.get_config('AMBIENT_THERMISTOR_CHANNEL'))
        self.INFRARED_SDA_CHANNEL = int(self.store.get_config('INFRARED_SDA_CHANNEL'))
        self.INFRARED_SCL_CHANNEL = int(self.store.get_config('INFRARED_SCL_CHANNEL'))
        self.HUMIDITY_SCL_CHANNEL = int(self.store.get_config('HUMIDITY_SCL_CHANNEL'))
        self.HUMIDITY_SDA_CHANNEL = int(self.store.get_config('HUMIDITY_SDA_CHANNEL'))
        self.HIGH_VOLTAGE_SET_CHANNEL = int(self.store.get_config('HIGH_VOLTAGE_SET_CHANNEL'))
        self.CURRENT_CUTOFF_SET_CHANNEL = int(self.store.get_config('CURRENT_CUTOFF_SET_CHANNEL'))

        # Resistor value for thermistors
        self.surfaceResistorTop = int(self.store.get_config('surfaceResistorTop'))
        self.surfaceResistorBot = int(self.store.get_config('surfaceResistorBot'))
        self.ambientResistor = int(self.store.get_config('ambientResistor'))

        # Resistor values for measuring plate voltage
        self.plateResistor1 = int(self.store.get_config('plateResistor1'))
        self.plateResistor2 = int(self.store.get_config('plateResistor2'))

        # Magic constants for the ambient thermistor's equation (model #44006)
        self.ambientA = float(self.store.get_config('ambientA'))
        self.ambientB = float(self.store.get_config('ambientB'))
        self.ambientC = float(self.store.get_config('ambientC'))

        # Magic constants for the surface mount thermistor's equation (model #44004)
        self.surfaceA = float(self.store.get_config('surfaceA'))
        self.surfaceB = float(self.store.get_config('surfaceB'))
        self.surfaceC = float(self.store.get_config('surfaceC'))

        # Other random constants because science
        self.kelvinOffset = float(self.store.get_config('kelvinOffset'))

        try:
            self.labjack = u3.U3()
        except LabJackException as e:
            self.store.log_event('debug',"A LabJack error occurred in __init__(): %s" %str(e))
        except Exception as e:
            self.store.log_event('debug','An unhandled error occurred in __init__(): %s' %str(e))
        else:
            self.set_labjack_config()
            self.labjack.getCalibrationData()
            self.select_current_cutoff(int(self.store.get_config('currentCutoff')))
        try:
            self.balance = Balance()
        except BalanceException as e:
            self.store.log_event('debug',"A Balance error occurred in __init__(): %s" %str(e))

    def gather_data(self, store):
        # input:    storage object so that most recent values from config file are used, not stale data
        # output:   returns an array with a timestamp and temperature/humidity/mass readings, follows CSV order convention
        # desc:     the main workhorse in hardwareIO; 
        #           gets data from the labjack and balance, converts, and returns
        # notes:    1.  Heavily dependent on global variables defined above, implementation may change at a later time
        #           2.  Please note that no labjack object is createcd in this function, it relies on one being created
        #               in init or in check_sensors()
        # TODO: replace self.store with store

        validSensors = self.check_sensors(store)

        timeStamp = strftime('%Y-%m-%d %H:%M:%S')
        dataArray = [timeStamp, 'invalid', 'invalid', 'invalid', 'invalid', 'invalid', 'invalid', 'invalid', 'invalid', 'invalid', 'invalid']

        try:
            vsVoltage = self.get_voltage(self.MEASURED_VS_CHANNEL)

            #--------------------Surface Thermistor Top -----------------------
            if (int(store.get_config('Top Temperature')) and validSensors[0]):
                # get those voltages!
                topThermistorVoltage = self.get_voltage(self.TOP_THERMISTOR_CHANNEL)

                # voltage divide the crap out of the top thermistor
                # resistance = resistor * thermVoltage/(Vs - ThermVoltage)
                topThermistorResistance = self.surfaceResistorTop*topThermistorVoltage/(vsVoltage-topThermistorVoltage)
                
                # apply Omega's magic formula
                lnSurfaceTop = math.log(topThermistorResistance)
                surfaceThermistorTemperatureTop = 1/(self.surfaceA + self.surfaceB*lnSurfaceTop + self.surfaceC*lnSurfaceTop*lnSurfaceTop*lnSurfaceTop) - self.kelvinOffset
                
                # throw this value onto the back of the dataArray train:
                dataArray[1] = surfaceThermistorTemperatureTop
            else:
                dataArray[1] = 'invalid'

            #--------------------Surface Thermistor Bottom -----------------------
            if (int(store.get_config('Bottom Temperature')) and validSensors[1]):
                # get those voltages!
                botThermistorVoltage = self.get_voltage(self.BOT_THERMISTOR_CHANNEL)
                
                # voltage divide the crap out of the ambient thermistor
                botThermistorResistance = self.surfaceResistorBot*botThermistorVoltage/(vsVoltage-botThermistorVoltage)
                
                # apply Omega's magic formula
                lnSurfaceBot = math.log(botThermistorResistance)
                surfaceThermistorTemperatureBot = 1/(self.surfaceA + self.surfaceB*lnSurfaceBot + self.surfaceC*lnSurfaceBot*lnSurfaceBot*lnSurfaceBot) - self.kelvinOffset
                
                # append to dataArray for returning:
                dataArray[2] = surfaceThermistorTemperatureBot
            else:
                dataArray[2] = 'invalid'

            #-----------------Infrared I2C Sensor-----------------------
            if (int(store.get_config('Surface Temperature')) and validSensors[2]):
                # Infrared sensor send and receive I2C object data
                infraredData = self.labjack.i2c(0x0, [0x7], NoStopWhenRestarting = True, SDAPinNum = self.INFRARED_SDA_CHANNEL, SCLPinNum = self.INFRARED_SCL_CHANNEL, NumI2CBytesToReceive = 3)
                I2CInfraredBytes = infraredData['I2CBytes']
                # Convert I2C Data into temp
                infraredTemperature = (I2CInfraredBytes[0] + 16*16*I2CInfraredBytes[1])*0.02 - self.kelvinOffset

                # append to dataArray for returning
                dataArray[3] = infraredTemperature
            else:
                dataArray[3] = 'invalid'

            #-----------------Ambient Thermistor-----------------
            if (int(store.get_config('Ambient Temperature')) and validSensors[3]):
                # get those voltages!
                ambientVoltage = self.get_voltage(self.AMBIENT_THERMISTOR_CHANNEL)
                
                # voltage divide the crap out of the ambient thermistor
                ambientThermistorResistance = self.ambientResistor*ambientVoltage/(vsVoltage-ambientVoltage)
                
                # apply Omega's magic formula
                lnAmbient = math.log(ambientThermistorResistance)
                ambientThermistorTemperature = 1/(self.ambientA + self.ambientB*lnAmbient + self.ambientC*lnAmbient*lnAmbient*lnAmbient) - self.kelvinOffset
                
                # append to dataArray for returning:
                dataArray[4] = ambientThermistorTemperature
            else:
                dataArray[4] = 'invalid'

            #-----------------Ambient Humidity I2C-----------------
            if (int(store.get_config('Humidity')) and validSensors[4]):
                # because gather_data() is called right after check_sensors(), it's possible that some "stale" data may still be found in the 
                # buffer of the humidity chip. If this is so, a value greater than 100 will be read, and if a % is > 100, that's probably not good
                staleData = True
                while(staleData == True):
                    #send & receive I2C humidity and temp data
                    humidity_data = self.labjack.i2c(0x28, [], NoStopWhenRestarting = True, SDAPinNum = self.HUMIDITY_SDA_CHANNEL, SCLPinNum = self.HUMIDITY_SCL_CHANNEL, NumI2CBytesToReceive = 4)
                    I2CBytes = humidity_data['I2CBytes']
                    #Convert I2C data into temp and humidity
                    relative_humidity = 100.0*(I2CBytes[0]*256 + I2CBytes[1])/pow(2,14)
                    if (relative_humidity < 100):
                        staleData = False
                dataArray[5] = relative_humidity
            else:
                dataArray[5] = 'invalid'

            #-----------------Voltage of HFG-----------------
            if (int(store.get_config('Voltage')) and validSensors[6]):
                hfgVoltage = self.get_voltage(self.MEASURED_FIELD_VOLTAGE_CHANNEL) * 6000
                dataArray[7] = hfgVoltage
            else:
                dataArray[7] = 'invalid'
            #-----------------Current of HFG-----------------
            if (int(store.get_config('Current')) and validSensors[7]):
                hfgVoltage = self.get_voltage(self.MEASURED_FIELD_CURRENT_CHANNEL)
                hfgCurrent = hfgVoltage * 80.0 # in uA
                dataArray[8] = hfgCurrent
            else:
                dataArray[8] = 'invalid'
            #-----------------Heating Plate Voltage-----------------
            if (int(store.get_config('Plate Voltage')) and validSensors[8]):
                dividerVoltage = self.get_voltage(self.MEASURED_PLATE_VOLTAGE)
                # Vsource = (R1 + R2)/R1 * Vin
                plateVoltage = (self.plateResistor1 + self.plateResistor2)/self.plateResistor1 * dividerVoltage
                dataArray[9] = plateVoltage
            else:
                dataArray[9] = 'invalid'
            #------------------Heat Transfer (Heat Flux)---------------
            if (int(store.get_config('Heat Transfer'))):
                heatFlux = self.calculate_heat_flux(
                    plateVoltage = dataArray[9], 
                    topTemp = dataArray[1], 
                    botTemp = dataArray[2], 
                    surfaceTemp = dataArray[3], 
                    ambientTemp = dataArray[4])
                dataArray[10] = heatFlux
            else:
                dataArray[10] = 'invalid'

        except AttributeError:{}
            
        except LabJackException as e:
            store.log_event('debug',"A LabJack error occurred in gather_data(): %s" %str(e))

        except Exception as e:
            store.log_event('debug',"An unhandled LabJack error occurred in gather_data(): %s" %str(e))

        try:
            #-----------------------Mass Balance--------------------------
            if (int(store.get_config('Mass')) and validSensors[5]):
                mass = self.balance.get_mass()
                dataArray[6] = mass
            else:
                dataArray[6] = 'invalid'
        except BalanceException as e:
            store.log_event('debug','A Balance error occurred in gather_data(): %s' %str(e))
        except Exception as e:
            store.log_event('debug','An unhandled error occurred in gather_data(): %s' %str(e))
        return dataArray

    def check_sensors(self, store):
        # input:    storage object
        # output:   a boolean array that indicates which sensors are functional, follows the conventional sensor order
        # desc:     checks the state of all sensors before "officially" retrieving data in gather_data()
        # notes:    technically this function encompases the functionality of gather_data(), 
        #           but this is done for ease of use when programming

        # Temperature values for validating sensor readings
        maxTemperature = float(store.get_config('maxTemperature'))
        minTemperature = float(store.get_config('minTemperature'))
        
        sensorStateArray = [0,0,0,0,0,0,0,0,0]


        #------------------------------------Labjack Data-------------------------------------
        try:
            self.labjack = u3.U3()
        except LabJackException as e:
            store.log_event('debug','A LabJack error occurred in check_sensors(): %s' %str(e))
        except Exception as e:
            store.log_event('debug',"An unhandled error occurred in check_sensors(): %s" %str(e))
        else:
            self.set_labjack_config()
            self.labjack.getCalibrationData()
            self.select_current_cutoff(int(self.store.get_config('currentCutoff')))
            try:
                try:
                    vsVoltage = self.get_voltage(self.MEASURED_VS_CHANNEL)

                    if (vsVoltage > 5.1 or vsVoltage < 4.9):
                        store.log_event('debug','Measured Vs is returning a voltage of %fV, which is outside the expected range of 4.9V to 5.1V.' % (vsVoltage))
                except ValueError:
                    store.log_event('debug','An error occurred when reading Vs, are some cables swapped?')
                except Exception as e:
                    store.log_event('debug','An unhandled error occurred when reading Vs: %s' %str(e))
                #----------------------Surface Thermistor Top----------------------
                try:
                    # check top thermistor connection by seeing if voltage reading is reasonable
                    thermVoltage = self.get_voltage(self.TOP_THERMISTOR_CHANNEL)

                    # apply Omega's magic formula
                    lnSurfaceTop = math.log(self.surfaceResistorTop*thermVoltage/(vsVoltage-thermVoltage))
                    thermTemperature = 1/(self.surfaceA + self.surfaceB*lnSurfaceTop + self.surfaceC*lnSurfaceTop*lnSurfaceTop*lnSurfaceTop) - self.kelvinOffset

                    if (thermTemperature <= maxTemperature and thermTemperature >=  minTemperature):
                        sensorStateArray[0] = 1
                    else:
                        sensorStateArray[0] = 0
                        store.log_event('debug','Top Thermistor is returning a temperature of %f, which is outside the expected range of %f to %f.' % (thermTemperature, minTemperature, maxTemperature))
                except ValueError:
                    sensorStateArray[0] = 0
                    store.log_event('debug','An error occurred for Top Thermistor, are some cables swapped?')
                except Exception as e:
                    sensorStateArray[0] = 0
                    store.log_event('debug','An unhandled error occurred for Top Thermistor: %s' %str(e))
                
                #----------------------Surface Thermistor Bottom----------------------
                try:
                    # check bot thermistor connection by seeing if voltage reading is reasonable
                    thermVoltage = self.get_voltage(self.BOT_THERMISTOR_CHANNEL)

                    # apply Omega's magic formula
                    lnSurfaceBot = math.log(self.surfaceResistorBot*thermVoltage/(vsVoltage-thermVoltage))
                    thermTemperature = 1/(self.surfaceA + self.surfaceB*lnSurfaceBot + self.surfaceC*lnSurfaceBot*lnSurfaceBot*lnSurfaceBot) - self.kelvinOffset
                    if (thermTemperature <= maxTemperature and thermTemperature >=  minTemperature):
                        sensorStateArray[1] = 1
                    else:
                        sensorStateArray[1] = 0
                        store.log_event('debug','Bot Thermistor is returning a temperature of %f, which is outside the expected range of %f to %f.' % (thermTemperature, minTemperature, maxTemperature))
                except ValueError:
                    sensorStateArray[1] = 0
                    store.log_event('debug','An error occurred for Bot Thermistor, are some cables swapped?')
                except Exception as e:
                    sensorStateArray[1] = 0
                    store.log_event('debug','An unhandled error occurred for Bot Thermistor: %s' %str(e))

                #----------------------Surface Infrared I2C----------------------
                try:
                    # Infrared sensor send and receive I2C object data
                    infraredData = self.labjack.i2c(0x0, [0x7], NoStopWhenRestarting = True, SDAPinNum = self.INFRARED_SDA_CHANNEL, 
                                                      SCLPinNum = self.INFRARED_SCL_CHANNEL, NumI2CBytesToReceive = 3)
                    I2CInfraredBytes = infraredData['I2CBytes']
                    #print I2CInfraredBytes
                    # Convert I2C Data into temp
                    infraredTemperature = (I2CInfraredBytes[0] + 16*16*I2CInfraredBytes[1])*0.02 - self.kelvinOffset
                    if(I2CInfraredBytes[0] == 255):
                        sensorStateArray[2] = 0
                        store.log_event('debug','Surface Infrared Sensor is unplugged, please plug it back in!.')
                    elif(infraredTemperature <= maxTemperature and infraredTemperature >= minTemperature):
                        sensorStateArray[2] = 1
                    else:
                        sensorStateArray[2] = 0
                        store.log_event('debug','Surface Infrared Sensor is returning a temperature of %f, which is outside the expected range of %f to %f.' % (thermTemperature, minTemperature, maxTemperature))
                except Exception as e:
                    sensorStateArray[2] = 0
                    store.log_event('debug','An unhandled error occurred for Infrared Sensor: %s' %str(e))


                #----------------------Ambient Thermistor----------------------
                try:
                    # check ambient thermistor connection by seeing if voltage reading is reasonable
                    thermVoltage = self.get_voltage(self.AMBIENT_THERMISTOR_CHANNEL)
                    
                    # apply Omega's magic formula
                    lnAmbient = math.log(self.ambientResistor*thermVoltage/(vsVoltage-thermVoltage))
                    thermTemperature = 1/(self.ambientA + self.ambientB*lnAmbient + self.ambientC*lnAmbient*lnAmbient*lnAmbient) - self.kelvinOffset
                    if (thermTemperature <= maxTemperature and thermTemperature >=  minTemperature):
                        sensorStateArray[3] = 1
                    else:
                        sensorStateArray[3] = 0
                        store.log_event('debug','Ambient Thermistor is returning a temperature of %f, which is outside the expected range of %f to %f.' % (thermTemperature, minTemperature, maxTemperature))

                except ValueError:
                    sensorStateArray[3] = 0
                    store.log_event('debug','An error occurred for Ambient Thermistor, are some cables swapped?')
                except Exception as e:
                    sensorStateArray[3] = 0
                    store.log_event('debug','An unhandled error occurred for Ambient Thermistor: %s' %str(e))

                #----------------------Ambient Humidity I2C----------------------
                try:
                    #send & receive I2C humidity and temp data
                    humidity_data = self.labjack.i2c(0x28, [], NoStopWhenRestarting = True, SDAPinNum = self.HUMIDITY_SDA_CHANNEL, SCLPinNum = self.HUMIDITY_SCL_CHANNEL, NumI2CBytesToReceive = 4)
                    I2CBytes = humidity_data['I2CBytes']
                    #Convert I2C data into temp and humidity
                    ambient_temp = -40 + 165.0*(I2CBytes[2]*64 + I2CBytes[3]/16)/pow(2,14)
                    relative_humidity = 100.0*(I2CBytes[0]*256 + I2CBytes[1])/pow(2,14)

                    if(relative_humidity > 100):
                        relative_humidity = relative_humidity - 100
                    if(relative_humidity <= 70 and relative_humidity >= 5):
                        sensorStateArray[4] = 1
                    else:
                        sensorStateArray[4] = 0
                        store.log_event('debug','Ambient Humidity Sensor is returning a value of %f%, which is outside the expected range of 5 to 70%.' % (relative_humidity))
                
                except Exception as e:
                    sensorStateArray[4] = 0
                    store.log_event('debug','An unhandled error occurred for Ambient Humidity Sensor: %s' %str(e))

                #----------------------Voltage of HFG----------------------
                try:
                    # check voltage measuring connection by seeing if voltage reading is reasonable
                    hfgVoltage = self.get_voltage(self.MEASURED_FIELD_VOLTAGE_CHANNEL)

                    if (hfgVoltage <= 5 and hfgVoltage >= 0):
                        sensorStateArray[6] = 1
                    else:
                        sensorStateArray[6] = 0
                        store.log_event('debug','An invalid value of %fV was returned when measuring the field voltage, which is outside the possible range of 0 to 30 kV.' % (hfgVoltage * 6000))
                except Exception as e:
                    sensorStateArray[6] = 0
                    store.log_event('debug','An unhandled error occurred when measuring the field voltage: %s' %str(e))

                #----------------------Current of HFG----------------------
                try:
                    # check current measuring connection by seeing if voltage reading is reasonable
                    hfgVoltage = self.get_voltage(self.MEASURED_FIELD_CURRENT_CHANNEL)
                    hfgCurrent = hfgVoltage * 80.0 # in uA
                    if (hfgCurrent <= 400 and hfgCurrent >= 0):
                        sensorStateArray[7] = 1
                    else:
                        sensorStateArray[7] = 0
                        store.log_event('debug','An invalid value of %fuA was returned when measuring the field current, which is outside the possible range of 0 to 400 uA.' % hfgCurrent)
                except Exception as e:
                    sensorStateArray[7] = 0
                    store.log_event('debug','An unhandled error occurred when measuring the field current: %s' %str(e))

                #----------------------Heating Plate Voltage----------------------
                try:
                    # check heating plate voltage connection by seeing if voltage reading is reasonable
                    dividerVoltage = self.get_voltage(self.MEASURED_PLATE_VOLTAGE)

                    # Vsource = (R1 + R2)/R1 * Vin
                    plateVoltage = (self.plateResistor1 + self.plateResistor2)/self.plateResistor1 * dividerVoltage
                    if (plateVoltage <= 20 and plateVoltage >= 0):
                        sensorStateArray[8] = 1
                    else:
                        sensorStateArray[8] = 0
                        store.log_event('debug','An invalid value of %fV was returned when measuring the plate voltage, which is outside the possible range of 0 to 20 V.' % plateVoltage)
                except Exception as e:
                    sensorStateArray[8] = 0
                    store.log_event('debug','An unhandled error occurred when measuring the plate voltage: %s' %str(e))

            except LabJackException as e:
                store.log_event('debug',"A LabJack error occurred in check_sensors(): %s" %str(e))
            except Exception as e:
                store.log_event('debug','An unhandled error occurred in check_sensors(): %s' %str(e))
        #------------------------------Balance Data---------------------------------  
        try:
            self.balance = Balance()
        except BalanceException as e:
            sensorStateArray[5] = 0
            store.log_event('debug','A Balance error occurred in check_sensors(): %s' %str(e))
        else:
            try:
                #----------------------Mass Balance----------------------
                mass = self.balance.get_mass()
                sensorStateArray[5] = 1
            except AttributeError as e: # The mass isn't connected
                sensorStateArray[5] = 0
                store.log_event('debug','A Balance error occurred in check_sensors(), is it plugged in? %s' %str(e))
            except IndexError as e: # The mass isn't turned on
                sensorStateArray[5] = 0
                store.log_event('debug','A Balance error occurred in check_sensors(), is it powered on or is it being overloaded? %s' %str(e))
            except Exception as e:
                store.log_event('debug','An unhandled Balance error occurred in check_sensors(): %s' %str(e))
        return sensorStateArray

    def get_voltage(self, positiveChannel, negativeChannel = 31, settle = True):
        # input:    positiveChannel, negativeChannel, settle
        # output:   returns a voltage value
        # desc:     polls the labjack for the voltage of a positive channel relative to the negative channel
        # notes:
        if self.labjack:
            return self.labjack.binaryToCalibratedAnalogVoltage(bits = self.labjack.getFeedback(u3.AIN(positiveChannel, negativeChannel, settle))[0], isLowVoltage = positiveChannel/4)
        else:
            self.store.log_event('debug','Attempted to get voltage info when a labjack wasn\'t plugged in, this should never happen')

    def set_labjack_config(self):
        # input:    no arguments passed
        # output:   nothing returned
        # desc:     configures labjack pins; defaults to analog in, sets any I2C channels to digital in
        # notes:    If you (a dev) are adding sensors, YOU NEED TO CONFIGURE THE PINS HERE!
        #           this should be called upon creation of a labjack object
        #           Designed to look at channels selected in the config file and set FIOAnalog and EIOAnalog appropriately
        try:
            # set all channels to analog in, then set the handful of digital ins to zero
            analogSelect = int(math.pow(2, 16) - 1)
            # infrared
            analogSelect = int(analogSelect - math.pow(2, self.INFRARED_SCL_CHANNEL) - math.pow(2, self.INFRARED_SDA_CHANNEL))
            # humidity
            analogSelect = int(analogSelect - math.pow(2, self.HUMIDITY_SCL_CHANNEL) - math.pow(2, self.HUMIDITY_SDA_CHANNEL))
            FIO = 0x00FF & analogSelect
            EIO = analogSelect / 256
            self.labjack.configIO(
                FIOAnalog = FIO, 
                EIOAnalog = EIO)
            return 0

        except AttributeError:
            self.store.log_event('debug','An error occurred in set_labjack_config(), is the labjack plugged in?')
        except LabJackException as e:
            self.store.log_event('debug',"A LabJack error occurred in set_labjack_config(): %s" %str(e))
        except Exception as e:
            self.store.log_event('debug','An unhandled error occurred in set_labjack_config(): %s' %str(e))

    def calculate_heat_flux(self, plateVoltage, topTemp, botTemp, surfaceTemp, ambientTemp):
        # input:    plateVoltage, topTemp, botTemp, surfaceTemp, ambientTemp
        # output:   if successful, returns heat flux
        # desc:     calculates the heat flux, made purely for your readability
        # notes:               
        try:
            plateArea = float(self.store.get_config('plateArea'))
            plateResistance = float(self.store.get_config('plateResistance'))
            polyConduct = float(self.store.get_config('polyConduct'))
            plateEmiss = float(self.store.get_config('plateEmiss'))
            stephBoltzConst = float(self.store.get_config('stephBoltzConst'))
            heatFlux = (math.pow(plateVoltage, 2)/(plateArea * plateResistance) - polyConduct/plateEmiss * (topTemp - botTemp) - stephBoltzConst * (math.pow(surfaceTemp + self.kelvinOffset, 4) - math.pow(ambientTemp + self.kelvinOffset, 4)))/(surfaceTemp - ambientTemp)
        except Exception as e:
            self.store.log_event('debug','An error occurred in calculate_heat_flux(%f, %f, %f, %f, %f): %s' %(plateVoltage, topTemp, botTemp, surfaceTemp, ambientTemp, str(e)))
        else:
            return heatFlux

    def set_hfg_voltage_feedback(self, desiredVoltage = 0, localMode = False, errorVoltage = 0, maxCalls = 20): 
        # input:    receives a user-determined voltage (will convert from 0-5V or 0-30kV)
        # output:   nothing, but sets the field voltage accordingly over chosen DAC (probs DAC0)
        # desc:     given a voltage range of either (0-5V) or (0-30kV), sets the HV field;
        #           also measures the HV supply's "output" voltage, finds error, and does a feedback loop
        # notes:    1. it seems to be accurate enough for now, within roughly .005 volts 
        #           2. DON'T overload the maxCalls parameter when using, it's done this way for recursion
        try:

            # for future devs, you may find that the threading we've done is stupid. you may want to add
            # additional checks for thread count and kill old voltage threads if needed - idk though
            #print threading.activeCount()
            #threading.currentThread()._Thread__delete()
            #print threading.activeCount()
            #print threading.currentThread().getName()

            if(localMode == False and threading.active_count() == 2):
                if(maxCalls > 0):
                    # convert from 0-30kV to 0-5V if necessary
                    if (desiredVoltage < 0 or desiredVoltage > 30000):
                        self.store.log_event('debug','The desired voltage was %s, which falls outside the feasible range of 0V to 30000V' %desiredVoltage)
                        return
                    # assume the user will never want a field voltage of less than 100 (100/30000 * 5 = .016667)
                    if (desiredVoltage < .017):
                        desiredVoltage = .017

                    if (desiredVoltage > 5):
                        desiredVoltage = desiredVoltage / 6000.0
                    bits = self.labjack.voltageToDACBits(volts = desiredVoltage + errorVoltage * 0.85, dacNumber = self.HIGH_VOLTAGE_SET_CHANNEL, is16Bits = True)
                    self.labjack.getFeedback(u3.DAC16(Dac = self.HIGH_VOLTAGE_SET_CHANNEL, Value = bits))
                    if(maxCalls == 20):
                        time.sleep(2)
                    else:
                        time.sleep(.2) ## give the voltage a bit to settle
                    measuredVoltage = self.get_voltage(self.MEASURED_FIELD_VOLTAGE_CHANNEL)      
                    errorVoltage = desiredVoltage - measuredVoltage
                    #print ("[Measured:%f | Error:%f]" %(measuredVoltage, errorVoltage))
                    if (errorVoltage > .005 or errorVoltage < -.005): # should provide accuracy within %0.1 of the desired voltage
                        self.set_hfg_voltage_feedback(desiredVoltage, False, errorVoltage, maxCalls - 1)
                    else:
                        return 0
                elif(maxCalls == 0 and errorVoltage > .1):
                    # voltage wasn't able to settle, either a result of the generator being in manual (local) mode or the safety cutoff being tripped
                    comparatorVoltage = self.get_voltage(self.SAFETY_CUTOFF_COMPARATOR)
                    if(comparatorVoltage < 1):
                        raise HardwareIOException('[ERROR2] Unable to remotely control the voltage, safety cutoff was activated.')
                    else:
                        raise HardwareIOException('[ERROR1] Unable to remotely control the voltage, is the supply on, is it in remote mode, and is the DAC pin correct?')
                        
                else:
                    # voltage wasn't able to settle in 20 calls
                    return 1 
        except AttributeError as e:
            self.store.log_event('debug','A LabJack error occurred in set_hfg_voltage_feedback(%f, %f): %s' %(desiredVoltage, errorVoltage, str(e)))
            return 1
        except KeyError as e:
            self.store.log_event('debug','A Labjack error occurred in set_hfg_voltage_feedback(%f, %f): %s' %(desiredVoltage, errorVoltage, str(e)))
            return 1
        except LabJackException as e:
            self.store.log_event('debug','A LabJack error occurred in set_hfg_voltage_feedback(%f, %f): %s' %(desiredVoltage, errorVoltage, str(e)))


    def set_hfg_voltage_lookup(self, desiredVoltage, localMode = False):
        # input:    receives a user-determined voltage
        # output:   nothing, but sets the field voltage accordingly over chosen DAC (probs DAC0)
        # desc:     As of 4/6/2016, this function is not in use and has been included as a backup to the feedback function
        #           Acts like a lookup table for voltages - definitely not ideal
               
        try:
            #convert voltage given in volts to kV
            desiredVoltage = int(desiredVoltage / 1000)
            voltageTable = [0/6.0, 1/6.0, 2/6.0, 3/6.0, 4/6.0, 5/6.0, 6/6.0, 7/6.0, 8/6.0, 9/6.0, 
                            10/6.0, 11/6.0, 12/6.0, 13/6.0, 14/6.0, 15/6.0, 16/6.0, 17/6.0, 18/6.0, 19/6.0,
                            20/6.0, 21/6.0, 22/6.0, 23/6.0, 24/6.0, 25/6.0, 26/6.0, 27/6.0, 28/6.0, 29/6.0, 30/6.0]

            bits = self.labjack.voltageToDACBits(
                            volts = voltageTable[desiredVoltage], 
                            dacNumber = self.HIGH_VOLTAGE_SET_CHANNEL, 
                            is16Bits = True)
            self.labjack.getFeedback(u3.DAC16(Dac = self.HIGH_VOLTAGE_SET_CHANNEL, Value = bits))
            return 0
        except Exception as e:
            self.store.log_event('debug','An unhandled error occurred in set_hfg_voltage_lookup(%f): %s' %(desiredVoltage, str(e)))
            return 1

    def select_current_cutoff(self, currentuA = 200):
        # input:    receives a current cutoff (in uA)
        # output:   nothing, but sets the voltage (0-5V) that's proportional to the possible current of the HV supply
        # desc:     This sets a voltage that represents the current going through the supply;
        #           this voltage is run through a comparator/sr-latch circuit; 
        #           if this current threshold is hit, the supply is disabled via hardware
        # notes:     
                
        try:
            selectVoltage = (currentuA/400.0) * 5
            bits = self.labjack.voltageToDACBits(
                volts = selectVoltage, 
                dacNumber = self.CURRENT_CUTOFF_SET_CHANNEL, 
                is16Bits = True)
            self.labjack.getFeedback(u3.DAC16(Dac = self.CURRENT_CUTOFF_SET_CHANNEL, Value = bits))
            return 0
        except Exception as e:
            self.store.log_event('debug','An unhandled error occurred in select_current_cutoff(%f): %s' %(currentuA, str(e)))
            return 1
Example #37
0
    def __init__(self, store):
        # input:    takes a storage object
        # output:   nothing
        # desc:     The "constructor" of the HardwareIO class; 
        #           initializes members from config file; 
        #           also creates a labjack and balance object
        self.store = store
        # Configuration member variables

        # Labjack Channel Globals
        self.SAFETY_CUTOFF_COMPARATOR = int(self.store.get_config('SAFETY_CUTOFF_COMPARATOR'))
        self.MEASURED_VS_CHANNEL = int(self.store.get_config('MEASURED_VS_CHANNEL'))
        self.MEASURED_FIELD_VOLTAGE_CHANNEL = int(self.store.get_config('MEASURED_FIELD_VOLTAGE_CHANNEL'))
        self.MEASURED_FIELD_CURRENT_CHANNEL = int(self.store.get_config('MEASURED_FIELD_CURRENT_CHANNEL'))
        self.MEASURED_PLATE_VOLTAGE = int(self.store.get_config('MEASURED_PLATE_VOLTAGE'))
        self.TOP_THERMISTOR_CHANNEL = int(self.store.get_config('TOP_THERMISTOR_CHANNEL'))
        self.BOT_THERMISTOR_CHANNEL = int(self.store.get_config('BOT_THERMISTOR_CHANNEL'))
        self.AMBIENT_THERMISTOR_CHANNEL = int(self.store.get_config('AMBIENT_THERMISTOR_CHANNEL'))
        self.INFRARED_SDA_CHANNEL = int(self.store.get_config('INFRARED_SDA_CHANNEL'))
        self.INFRARED_SCL_CHANNEL = int(self.store.get_config('INFRARED_SCL_CHANNEL'))
        self.HUMIDITY_SCL_CHANNEL = int(self.store.get_config('HUMIDITY_SCL_CHANNEL'))
        self.HUMIDITY_SDA_CHANNEL = int(self.store.get_config('HUMIDITY_SDA_CHANNEL'))
        self.HIGH_VOLTAGE_SET_CHANNEL = int(self.store.get_config('HIGH_VOLTAGE_SET_CHANNEL'))
        self.CURRENT_CUTOFF_SET_CHANNEL = int(self.store.get_config('CURRENT_CUTOFF_SET_CHANNEL'))

        # Resistor value for thermistors
        self.surfaceResistorTop = int(self.store.get_config('surfaceResistorTop'))
        self.surfaceResistorBot = int(self.store.get_config('surfaceResistorBot'))
        self.ambientResistor = int(self.store.get_config('ambientResistor'))

        # Resistor values for measuring plate voltage
        self.plateResistor1 = int(self.store.get_config('plateResistor1'))
        self.plateResistor2 = int(self.store.get_config('plateResistor2'))

        # Magic constants for the ambient thermistor's equation (model #44006)
        self.ambientA = float(self.store.get_config('ambientA'))
        self.ambientB = float(self.store.get_config('ambientB'))
        self.ambientC = float(self.store.get_config('ambientC'))

        # Magic constants for the surface mount thermistor's equation (model #44004)
        self.surfaceA = float(self.store.get_config('surfaceA'))
        self.surfaceB = float(self.store.get_config('surfaceB'))
        self.surfaceC = float(self.store.get_config('surfaceC'))

        # Other random constants because science
        self.kelvinOffset = float(self.store.get_config('kelvinOffset'))

        try:
            self.labjack = u3.U3()
        except LabJackException as e:
            self.store.log_event('debug',"A LabJack error occurred in __init__(): %s" %str(e))
        except Exception as e:
            self.store.log_event('debug','An unhandled error occurred in __init__(): %s' %str(e))
        else:
            self.set_labjack_config()
            self.labjack.getCalibrationData()
            self.select_current_cutoff(int(self.store.get_config('currentCutoff')))
        try:
            self.balance = Balance()
        except BalanceException as e:
            self.store.log_event('debug',"A Balance error occurred in __init__(): %s" %str(e))
Example #38
0
	def testSingleArray2n(self):
		balance = Balance([3])
		self.assertEquals([0], balance.point2n())
Example #39
0
    def check_sensors(self, store):
        # input:    storage object
        # output:   a boolean array that indicates which sensors are functional, follows the conventional sensor order
        # desc:     checks the state of all sensors before "officially" retrieving data in gather_data()
        # notes:    technically this function encompases the functionality of gather_data(), 
        #           but this is done for ease of use when programming

        # Temperature values for validating sensor readings
        maxTemperature = float(store.get_config('maxTemperature'))
        minTemperature = float(store.get_config('minTemperature'))
        
        sensorStateArray = [0,0,0,0,0,0,0,0,0]


        #------------------------------------Labjack Data-------------------------------------
        try:
            self.labjack = u3.U3()
        except LabJackException as e:
            store.log_event('debug','A LabJack error occurred in check_sensors(): %s' %str(e))
        except Exception as e:
            store.log_event('debug',"An unhandled error occurred in check_sensors(): %s" %str(e))
        else:
            self.set_labjack_config()
            self.labjack.getCalibrationData()
            self.select_current_cutoff(int(self.store.get_config('currentCutoff')))
            try:
                try:
                    vsVoltage = self.get_voltage(self.MEASURED_VS_CHANNEL)

                    if (vsVoltage > 5.1 or vsVoltage < 4.9):
                        store.log_event('debug','Measured Vs is returning a voltage of %fV, which is outside the expected range of 4.9V to 5.1V.' % (vsVoltage))
                except ValueError:
                    store.log_event('debug','An error occurred when reading Vs, are some cables swapped?')
                except Exception as e:
                    store.log_event('debug','An unhandled error occurred when reading Vs: %s' %str(e))
                #----------------------Surface Thermistor Top----------------------
                try:
                    # check top thermistor connection by seeing if voltage reading is reasonable
                    thermVoltage = self.get_voltage(self.TOP_THERMISTOR_CHANNEL)

                    # apply Omega's magic formula
                    lnSurfaceTop = math.log(self.surfaceResistorTop*thermVoltage/(vsVoltage-thermVoltage))
                    thermTemperature = 1/(self.surfaceA + self.surfaceB*lnSurfaceTop + self.surfaceC*lnSurfaceTop*lnSurfaceTop*lnSurfaceTop) - self.kelvinOffset

                    if (thermTemperature <= maxTemperature and thermTemperature >=  minTemperature):
                        sensorStateArray[0] = 1
                    else:
                        sensorStateArray[0] = 0
                        store.log_event('debug','Top Thermistor is returning a temperature of %f, which is outside the expected range of %f to %f.' % (thermTemperature, minTemperature, maxTemperature))
                except ValueError:
                    sensorStateArray[0] = 0
                    store.log_event('debug','An error occurred for Top Thermistor, are some cables swapped?')
                except Exception as e:
                    sensorStateArray[0] = 0
                    store.log_event('debug','An unhandled error occurred for Top Thermistor: %s' %str(e))
                
                #----------------------Surface Thermistor Bottom----------------------
                try:
                    # check bot thermistor connection by seeing if voltage reading is reasonable
                    thermVoltage = self.get_voltage(self.BOT_THERMISTOR_CHANNEL)

                    # apply Omega's magic formula
                    lnSurfaceBot = math.log(self.surfaceResistorBot*thermVoltage/(vsVoltage-thermVoltage))
                    thermTemperature = 1/(self.surfaceA + self.surfaceB*lnSurfaceBot + self.surfaceC*lnSurfaceBot*lnSurfaceBot*lnSurfaceBot) - self.kelvinOffset
                    if (thermTemperature <= maxTemperature and thermTemperature >=  minTemperature):
                        sensorStateArray[1] = 1
                    else:
                        sensorStateArray[1] = 0
                        store.log_event('debug','Bot Thermistor is returning a temperature of %f, which is outside the expected range of %f to %f.' % (thermTemperature, minTemperature, maxTemperature))
                except ValueError:
                    sensorStateArray[1] = 0
                    store.log_event('debug','An error occurred for Bot Thermistor, are some cables swapped?')
                except Exception as e:
                    sensorStateArray[1] = 0
                    store.log_event('debug','An unhandled error occurred for Bot Thermistor: %s' %str(e))

                #----------------------Surface Infrared I2C----------------------
                try:
                    # Infrared sensor send and receive I2C object data
                    infraredData = self.labjack.i2c(0x0, [0x7], NoStopWhenRestarting = True, SDAPinNum = self.INFRARED_SDA_CHANNEL, 
                                                      SCLPinNum = self.INFRARED_SCL_CHANNEL, NumI2CBytesToReceive = 3)
                    I2CInfraredBytes = infraredData['I2CBytes']
                    #print I2CInfraredBytes
                    # Convert I2C Data into temp
                    infraredTemperature = (I2CInfraredBytes[0] + 16*16*I2CInfraredBytes[1])*0.02 - self.kelvinOffset
                    if(I2CInfraredBytes[0] == 255):
                        sensorStateArray[2] = 0
                        store.log_event('debug','Surface Infrared Sensor is unplugged, please plug it back in!.')
                    elif(infraredTemperature <= maxTemperature and infraredTemperature >= minTemperature):
                        sensorStateArray[2] = 1
                    else:
                        sensorStateArray[2] = 0
                        store.log_event('debug','Surface Infrared Sensor is returning a temperature of %f, which is outside the expected range of %f to %f.' % (thermTemperature, minTemperature, maxTemperature))
                except Exception as e:
                    sensorStateArray[2] = 0
                    store.log_event('debug','An unhandled error occurred for Infrared Sensor: %s' %str(e))


                #----------------------Ambient Thermistor----------------------
                try:
                    # check ambient thermistor connection by seeing if voltage reading is reasonable
                    thermVoltage = self.get_voltage(self.AMBIENT_THERMISTOR_CHANNEL)
                    
                    # apply Omega's magic formula
                    lnAmbient = math.log(self.ambientResistor*thermVoltage/(vsVoltage-thermVoltage))
                    thermTemperature = 1/(self.ambientA + self.ambientB*lnAmbient + self.ambientC*lnAmbient*lnAmbient*lnAmbient) - self.kelvinOffset
                    if (thermTemperature <= maxTemperature and thermTemperature >=  minTemperature):
                        sensorStateArray[3] = 1
                    else:
                        sensorStateArray[3] = 0
                        store.log_event('debug','Ambient Thermistor is returning a temperature of %f, which is outside the expected range of %f to %f.' % (thermTemperature, minTemperature, maxTemperature))

                except ValueError:
                    sensorStateArray[3] = 0
                    store.log_event('debug','An error occurred for Ambient Thermistor, are some cables swapped?')
                except Exception as e:
                    sensorStateArray[3] = 0
                    store.log_event('debug','An unhandled error occurred for Ambient Thermistor: %s' %str(e))

                #----------------------Ambient Humidity I2C----------------------
                try:
                    #send & receive I2C humidity and temp data
                    humidity_data = self.labjack.i2c(0x28, [], NoStopWhenRestarting = True, SDAPinNum = self.HUMIDITY_SDA_CHANNEL, SCLPinNum = self.HUMIDITY_SCL_CHANNEL, NumI2CBytesToReceive = 4)
                    I2CBytes = humidity_data['I2CBytes']
                    #Convert I2C data into temp and humidity
                    ambient_temp = -40 + 165.0*(I2CBytes[2]*64 + I2CBytes[3]/16)/pow(2,14)
                    relative_humidity = 100.0*(I2CBytes[0]*256 + I2CBytes[1])/pow(2,14)

                    if(relative_humidity > 100):
                        relative_humidity = relative_humidity - 100
                    if(relative_humidity <= 70 and relative_humidity >= 5):
                        sensorStateArray[4] = 1
                    else:
                        sensorStateArray[4] = 0
                        store.log_event('debug','Ambient Humidity Sensor is returning a value of %f%, which is outside the expected range of 5 to 70%.' % (relative_humidity))
                
                except Exception as e:
                    sensorStateArray[4] = 0
                    store.log_event('debug','An unhandled error occurred for Ambient Humidity Sensor: %s' %str(e))

                #----------------------Voltage of HFG----------------------
                try:
                    # check voltage measuring connection by seeing if voltage reading is reasonable
                    hfgVoltage = self.get_voltage(self.MEASURED_FIELD_VOLTAGE_CHANNEL)

                    if (hfgVoltage <= 5 and hfgVoltage >= 0):
                        sensorStateArray[6] = 1
                    else:
                        sensorStateArray[6] = 0
                        store.log_event('debug','An invalid value of %fV was returned when measuring the field voltage, which is outside the possible range of 0 to 30 kV.' % (hfgVoltage * 6000))
                except Exception as e:
                    sensorStateArray[6] = 0
                    store.log_event('debug','An unhandled error occurred when measuring the field voltage: %s' %str(e))

                #----------------------Current of HFG----------------------
                try:
                    # check current measuring connection by seeing if voltage reading is reasonable
                    hfgVoltage = self.get_voltage(self.MEASURED_FIELD_CURRENT_CHANNEL)
                    hfgCurrent = hfgVoltage * 80.0 # in uA
                    if (hfgCurrent <= 400 and hfgCurrent >= 0):
                        sensorStateArray[7] = 1
                    else:
                        sensorStateArray[7] = 0
                        store.log_event('debug','An invalid value of %fuA was returned when measuring the field current, which is outside the possible range of 0 to 400 uA.' % hfgCurrent)
                except Exception as e:
                    sensorStateArray[7] = 0
                    store.log_event('debug','An unhandled error occurred when measuring the field current: %s' %str(e))

                #----------------------Heating Plate Voltage----------------------
                try:
                    # check heating plate voltage connection by seeing if voltage reading is reasonable
                    dividerVoltage = self.get_voltage(self.MEASURED_PLATE_VOLTAGE)

                    # Vsource = (R1 + R2)/R1 * Vin
                    plateVoltage = (self.plateResistor1 + self.plateResistor2)/self.plateResistor1 * dividerVoltage
                    if (plateVoltage <= 20 and plateVoltage >= 0):
                        sensorStateArray[8] = 1
                    else:
                        sensorStateArray[8] = 0
                        store.log_event('debug','An invalid value of %fV was returned when measuring the plate voltage, which is outside the possible range of 0 to 20 V.' % plateVoltage)
                except Exception as e:
                    sensorStateArray[8] = 0
                    store.log_event('debug','An unhandled error occurred when measuring the plate voltage: %s' %str(e))

            except LabJackException as e:
                store.log_event('debug',"A LabJack error occurred in check_sensors(): %s" %str(e))
            except Exception as e:
                store.log_event('debug','An unhandled error occurred in check_sensors(): %s' %str(e))
        #------------------------------Balance Data---------------------------------  
        try:
            self.balance = Balance()
        except BalanceException as e:
            sensorStateArray[5] = 0
            store.log_event('debug','A Balance error occurred in check_sensors(): %s' %str(e))
        else:
            try:
                #----------------------Mass Balance----------------------
                mass = self.balance.get_mass()
                sensorStateArray[5] = 1
            except AttributeError as e: # The mass isn't connected
                sensorStateArray[5] = 0
                store.log_event('debug','A Balance error occurred in check_sensors(), is it plugged in? %s' %str(e))
            except IndexError as e: # The mass isn't turned on
                sensorStateArray[5] = 0
                store.log_event('debug','A Balance error occurred in check_sensors(), is it powered on or is it being overloaded? %s' %str(e))
            except Exception as e:
                store.log_event('debug','An unhandled Balance error occurred in check_sensors(): %s' %str(e))
        return sensorStateArray
Example #40
0
def main():
    try:
        lastWeights = []

        balance = Balance()
        board = wiiboard.Wiiboard()

        pygame.init()

        #address = board.discover()
        address = "78:A2:A0:22:28:E8"

        disconnect_devices()

        log("Connecting to wiiboard address {}".format(address))
        board.connect(address) #The wii board must be in sync mode at this time
        log("Board connected")

        time.sleep(0.1)
        board.setLight(True)


        while True:

            if int(time.time() % 60) == 0:
                blink(board, times=1)
                time.sleep(1)

            time.sleep(0.05)
            events = pygame.event.get()
            #if len(events) > 10:
            #    print("Too many elements on queue {}".format(len(events)))

            for event in events:
                if event.type == wiiboard.WIIBOARD_MASS:
                    weight = event.mass.totalWeight
                    if (weight > 40):
                        #print "Total weight: {}. Top left: {} ".format(weight, event.mass.topLeft)


                        weight = round2(weight) # Weight becomes a string
                        lastWeights = add_list(lastWeights,weight)

                        if len(lastWeights) == MAX_STABLE_WEIGHTS and all_same(lastWeights):

                            if weight > 60:
                                user = "******"
                            else:
                                user = "******"

                            log("Saving weight {weight} for user {user}".format(**locals()))
                            balance.save(weight, user)

                            lastWeights = []

                            blink(board)
                            board.setLight(False)

                            for x in range(0,25): # Sleeps for 2.5 seconds while emptying queue
                                pygame.event.clear()
                                time.sleep(0.1)

                            board.setLight(True)
                    elif lastWeights:
                        log("Removing cached weights {}".format(lastWeights))
                        lastWeights = []

                #else:
                #    print ("Got different event type {}".format(event.type))
    except KeyboardInterrupt as e:
        log("Interrupt, exiting...")

        if board:
            log("Disconnecting board")
            board.disconnect()

    except BluetoothError as e:
        log("Got bluetooth error {}".format(e), level = "ERROR")

        if board:
            log("Disconnecting board")
            board.disconnect()
            main() #Retrying
    except Exception as e:
        log("Got unexpected error {}".format(e), level = "ERROR")
        if board:
            log("Disconnecting board")
            board.disconnect()
            main() #Retrying
Example #41
0
from balance import Balance



myaccount = Balance()
#asset
myaccount.add_asset(type1='bank',name='lukelu',number='0021179-0664447',balance=67619.00)
myaccount.add_asset(type1='bank',name='lukelu',number='0021179-0664448',balance=67619.00)
myaccount.del_asset(type1='bank',name='lukelu',number='0021179-0664448',balance=67619.00)
myaccount.show_assets()
#liability
myaccount.add_liability(type1='bank',name='lukelu',number='0021179-0664447',balance=67619.00)
myaccount.add_liability(type1='bank',name='lukelu',number='0021179-0664448',balance=67619.00)
myaccount.del_liability(type1='bank',name='lukelu',number='0021179-0664448',balance=67619.00)
myaccount.show_liabilities()

myaccount.show_balance()
Example #42
0
class TestBalanceMethods(unittest.TestCase):
    """ Test the methods of balance class """

    @classmethod
    def setUp(self):
        """ setting up data fixture """
        self.balance = Balance()

    def test_add(self):
        """ test add method in Balance """
        self.balance.add(10)
        self.assertEqual(self.balance.get_balance(), 10)

    def test_positive_integer(self):
        """ test positive integer values """
        self.balance.add(100)
        self.assertEqual(self.balance.get_balance(), 100)

    def test_float_values(self):
        """ test floating point values """
        self.balance.add(110.50)
        self.assertEqual(self.balance.get_balance(), 110)

    def test_string_integer(self):
        """ test string integer values """
        self.balance.add('100')
        self.assertEqual(self.balance.get_balance(), 100)

    def test_string(self):
        """ test string values """
        self.assertRaises(ValueError, self.balance.add, 'a')

    def test_substract(self):
        """ test subtract method """
        self.balance.subtract(1)
        self.assertEqual(self.balance.get_balance(), -1)
Example #43
0
	def testArrayOf2(self):
		balance = Balance([3,5])
		self.assertEquals([-1], balance.point())
Example #44
0
class LibroDiarioGUI(BaseGUI):

    def __init__(self,manager, managers = []):
        BaseGUI.__init__(self, manager, managers)
        self.DialogAddClass  = AddMovimiento
        self.loadUI('movimiento/uis/libro_diario.ui')

        self.addTableColumn(u'Fecha', Movimiento.fecha, alignment='C', fnParse=self.parseFecha)
        self.addTableColumn(u'Razon Social', Movimiento.razon_social)
        self.addTableColumn(u'Descripcion', Movimiento.descripcion)
        self.addTableColumn(u'Cuenta', Movimiento.cuenta)
        self.addTableColumn(u'Monto', Movimiento.monto, alignment='R', fnParse=self.parseMonto)

        self.cuentasManager = managers[0].manager
        self.balance = Balance()
        self._start_operations()

#===============================================================================
# LOGICA GUI Y EXTRAS
#===============================================================================

    def parseFecha(self, row, value):
        return value.strftime("%d/%m/%Y")

    def parseMonto(self, row, value):
        return "$ %8.2f" % float(value)

    def _start_operations(self):
        u'''
        operaciones necesarias para levantar las ventanas
        '''
        self.setWindowTitle(self.pluralTitle)
        self.makeTable()
        self.loadTable()
        self.loadShortcuts()
        self.fullScreen = False

        centerOnScreen(self)
        self.deFechaMostradaDesde.setDate( datetime.today() )
        self.deFechaMostradaHasta.setDate( datetime.today() )
        self.cbTipoMovimiento.setCurrentIndex(1)
        self.cbTipoMovimiento.setCurrentIndex(0)
        self.cbCuentas.setCurrentIndex(0)

        self.actualizarLabelBalance()
        self.setWindowTitle("Libro Diario")

    def reloadList(self):
        desde = self.deFechaMostradaDesde.date().toPyDate()
        hasta = self.deFechaMostradaHasta.date().toPyDate()
        filtro = self.obtenerTipoMovimientoSeleccionado()
        cuenta = self.obtenerCuentaSeleccionada()
        movimientos = self.manager.obtenerMovimientosDesdeHasta(desde, hasta, filtro, cuenta)
        self.loadTable(movimientos)
        self.actualizarLabelBalance()

    def loadTable(self,listadeobj = None):
        if listadeobj == None:
            listadeobj = self.manager.getall()
        listadefilas = [self._getAttributesValues(obj) for obj in listadeobj]
        self.tableItems.addItems(listadefilas)

    def obtenerTipoMovimientoSeleccionado(self):
        return unicode(self.cbTipoMovimiento.itemText(self.cbTipoMovimiento.currentIndex()).toUtf8(), 'utf-8')

    def obtenerCuentaSeleccionada(self):
        return unicode(self.cbCuentas.itemText(self.cbCuentas.currentIndex()).toUtf8(), 'utf-8')

    def cargarComboCuentas(self):
        filtro = self.obtenerTipoMovimientoSeleccionado()
        items = None
        if filtro == u'TODOS':
            items = self.cuentasManager.getall()
        elif filtro == u'INGRESOS':
            items = self.cuentasManager.cuentasDeIngreso()
        elif filtro == u'EGRESOS':
            items = self.cuentasManager.cuentasDeEgreso()

        self.cbCuentas.clear()
        self.cbCuentas.addItem("TODOS")
        nombres_cuentas = [cuenta.nombre for cuenta in items]
        nombres_cuentas.sort()
        [self.cbCuentas.addItem( nombre_cuenta ) for nombre_cuenta in nombres_cuentas ]

    def establecerMontoBalance(self, monto):
        style = '''QLabel {
        color: black;
        background-color: #BFBFBF;
        font: bold 18px;
        font-family: Ubuntu, Helvetica, sans-serif;
        border: 1px solid #BFBFBF;
        border-top-left-radius: 0px;border-top-right-radius: 0px;border-bottom-right-radius: 6px;border-bottom-left-radius: 6px;
        }'''
        self.lbBalance.setText( "$ %8.2f" % float(monto))
        if monto == 0 :
            self.lbBalance.setText("$ 00,00")
            self.lbBalance.setStyleSheet(style)
        elif monto > 0 :
            self.lbBalance.setStyleSheet( style.replace("color: black;","color: green;"))
        elif monto < 0 :
            self.lbBalance.setStyleSheet( style.replace("color: black;","color: red;"))

    def actualizarLabelBalance(self):
        self.establecerMontoBalance( self.balance.valor() )

#===============================================================================
# MOTODOS DE LAS SEÑALES
#===============================================================================

    @QtCore.pyqtSlot(int)
    def on_cbTipoMovimiento_currentIndexChanged(self , index):
        self.cargarComboCuentas()

    @QtCore.pyqtSlot(int)
    def on_cbCuentas_currentIndexChanged(self , index):
        self.reloadList()

    def on_deFechaMostradaDesde_dateChanged(self , date):
        if self.isVisible() :
            if date > self.deFechaMostradaHasta.date() :
                QtGui.QMessageBox.information(self, "Libro diario","La fecha <Desde> no puede ser mayor a <Hasta>.")
                self.deFechaMostradaDesde.setDate( datetime.today() )
            else:
                self.reloadList()

    def on_deFechaMostradaHasta_dateChanged(self , date):
        if self.isVisible() :
            if date < self.deFechaMostradaDesde.date() :
                QtGui.QMessageBox.information(self, "Libro diario","La fecha <Hasta> no puede ser mayor a <Desde>.")
                self.deFechaMostradaHasta.setDate( datetime.today() )
            else:
                self.reloadList()

    def on_twItems_itemSelectionChanged(self):
        pass
Example #45
0
 def setUp(self):
     """ setting up data fixture """
     self.balance = Balance()
Example #46
0
 def __init__(self, name):
     self.name = str(name)
     self.balance = Balance()
Example #47
0
	def testShouldReturnBalancePoint(self):
		balance = Balance([-7, 1, 5, 2, -4, 3, 0])
		self.assertEquals([3,6], balance.point())
Example #48
0
class LibroDiarioGUI(BaseGUI):
    
    def __init__(self,manager, managers = []):
        BaseGUI.__init__(self, manager, managers)
        self.FILENAME = join(abspath(dirname(__file__)),'uis/libro_diario.ui')
        #self.ATRIBUTOSLISTA = ['Nombres','Telefono','Domicilio','Zona','CP','Localidad','Fecha_cumpleanios','Email',]#el orden y la cantidad de atributos en str que quieras
        self.DialogAddClass  = AddMovimiento#la clase que invoca a los dialogos de agregar y editar        
        self.ALINEACIONLISTA = ['C','L','L','L','R']
        
        self.ATRIBUTOSLISTA = [
        {u'Fecha':Movimiento.fecha},
        {u'Razon Social':Movimiento.razon_social},
        {u'Descripcion':Movimiento.descripcion},        
        {u'Cuenta':Movimiento.cuenta},
        {u'Monto':Movimiento.monto}]
                
        self.cuentasManager = managers[0].manager
        self.balance = Balance()
        locale.setlocale( locale.LC_ALL, '' )
        self._start_operations()
        
#===============================================================================
# LOGICA GUI Y EXTRAS 
#===============================================================================

    def _obtenerValoresAtributos(self,obj):
        resultado = []
        atributos_objeto = self.manager.getClassAttributesValues(obj)
        if not self.ATRIBUTOSLISTA :            
            return atributos_objeto
        else:
            atributos_clase = self.manager.getClassAttributes()
            atributos_ordenados = self.ATRIBUTOSLISTA_CLASSNAMES
            for atributo in atributos_ordenados:
                resultado.append( atributos_objeto[ atributos_clase.index( atributo ) ] )
            # formatea la fecha, de date -> str
            resultado[0] = resultado[0].strftime("%d/%m/%Y") 
            # formatear el monto
            monto = locale.currency(float(resultado[4]), grouping = True)
            resultado[4] = unicode( monto )
            return resultado
        
    def _start_operations(self):
        u'''
        operaciones necesarias para levantar las ventanas
        '''
        uic.loadUi(self.FILENAME, self)
        self.setWindowTitle(self.TITULO)
        self._makeTable()
        
        self.cargarTabla()
        self._loadAppShortcuts()
        self.fullScreen = False
        
        self._centerOnScreen()       
        #self.setWindowState(QtCore.Qt.WindowMaximized)
        self.deFechaMostradaDesde.setDate( datetime.today() )
        self.deFechaMostradaHasta.setDate( datetime.today() )
        self.cbTipoMovimiento.setCurrentIndex(1)
        self.cbTipoMovimiento.setCurrentIndex(0)
        self.cbCuentas.setCurrentIndex(0)
        
        self.actualizarLabelBalance()
        self.setWindowTitle("Libro Diario")

    def recargarLista(self):
        desde = self.deFechaMostradaDesde.date().toPyDate() 
        hasta = self.deFechaMostradaHasta.date().toPyDate()
        filtro = self.obtenerTipoMovimientoSeleccionado()
        cuenta = self.obtenerCuentaSeleccionada()
        movimientos = self.manager.obtenerMovimientosDesdeHasta(desde, hasta, filtro, cuenta)     
        self.cargarTabla(movimientos)
        self.actualizarLabelBalance()
        
    def cargarTabla(self,listadeobj = None):        
        if listadeobj == None:
            listadeobj = self.manager.getall()
        listadefilas = [self._obtenerValoresAtributos(obj) for obj in listadeobj]
        self.MyTabla.addItems(listadefilas)        
        
    def obtenerTipoMovimientoSeleccionado(self):
        return unicode(self.cbTipoMovimiento.itemText(self.cbTipoMovimiento.currentIndex()).toUtf8(), 'utf-8')
    
    def obtenerCuentaSeleccionada(self):
        return unicode(self.cbCuentas.itemText(self.cbCuentas.currentIndex()).toUtf8(), 'utf-8')
    
    def cargarComboCuentas(self):        
        filtro = self.obtenerTipoMovimientoSeleccionado()
        items = None        
        if filtro == u'TODOS':
            items = self.cuentasManager.getall()
        elif filtro == u'INGRESOS':
            items = self.cuentasManager.cuentasDeIngreso()
        elif filtro == u'EGRESOS':
            items = self.cuentasManager.cuentasDeEgreso()
        
        self.cbCuentas.clear()
        self.cbCuentas.addItem("TODOS")
        nombres_cuentas = [cuenta.nombre for cuenta in items]
        nombres_cuentas.sort()
        [self.cbCuentas.addItem( nombre_cuenta ) for nombre_cuenta in nombres_cuentas ]
        
    def establecerMontoBalance(self, monto):
        style = '''QLabel {
        color: black;
        background-color: #BFBFBF;
        font: bold 18px;
        font-family: Ubuntu, Helvetica, sans-serif;
        border: 1px solid #BFBFBF;
        border-top-left-radius: 0px;border-top-right-radius: 0px;border-bottom-right-radius: 6px;border-bottom-left-radius: 6px;
        }'''
        self.lbBalance.setText( str(locale.currency( float(monto), grouping = True)) )        
        if monto == 0 :            
            self.lbBalance.setText("$ 00,00")
            self.lbBalance.setStyleSheet(style)
        elif monto > 0 :
            self.lbBalance.setStyleSheet( style.replace("color: black;","color: green;"))
        elif monto < 0 :
            self.lbBalance.setStyleSheet( style.replace("color: black;","color: red;"))

    def actualizarLabelBalance(self):
        self.establecerMontoBalance( self.balance.valor() )
        
#===============================================================================
# MOTODOS DE LAS SEÑALES
#===============================================================================

    @QtCore.pyqtSlot(int)
    def on_cbTipoMovimiento_currentIndexChanged(self , index):
        self.cargarComboCuentas()
    
    @QtCore.pyqtSlot(int)
    def on_cbCuentas_currentIndexChanged(self , index):
        self.recargarLista()
        
    def on_deFechaMostradaDesde_dateChanged(self , date):
        if self.isVisible() :
            if date > self.deFechaMostradaHasta.date() : 
                QtGui.QMessageBox.information(self, "Libro diario","La fecha <Desde> no puede ser mayor a <Hasta>.")
                self.deFechaMostradaDesde.setDate( datetime.today() )
            else:
                self.recargarLista()
            
    def on_deFechaMostradaHasta_dateChanged(self , date):
        if self.isVisible() :
            if date < self.deFechaMostradaDesde.date() : 
                QtGui.QMessageBox.information(self, "Libro diario","La fecha <Hasta> no puede ser mayor a <Desde>.")
                self.deFechaMostradaHasta.setDate( datetime.today() )
            else:
                self.recargarLista()
Example #49
0
class AddMovimiento(BaseAddWindow):
    def __init__(self, unManager, itemaeditar=False, managers=[]):
        BaseAddWindow.__init__(self, unManager, itemaeditar, managers)
        FILENAME = "uis/agregar.ui"
        uic.loadUi(join(abspath(dirname(__file__)), FILENAME), self)

        self.ITEMLIST = [
            {self.cbCuentas: Movimiento.cuenta},
            {self.dsbMonto: Movimiento.monto},
            {self.leNroComprobante: Movimiento.nroComprobante},
            {self.teDescripcion: Movimiento.descripcion},
            {self.deFecha: Movimiento.fecha},
            {self.leRazonSocial: Movimiento.razon_social},
        ]
        self.cuentasManager = managers[0].manager
        self.balance = Balance()
        self._start_operations()

    # REIMPLEMENTED
    def _start_operations(self):
        self._centerOnScreen()
        self.agregarValidadores()
        self.btGuardar.setDefault(True)
        if self.EDITITEM:
            self.btGuardar.setText("Editar")
            self.setWindowTitle(u"Editar Ingreso")
            self._cargarDatosinWidgets()
        else:
            self.setWindowTitle(u"Agregar Ingreso")
        self.lbTitulo.setText(self.windowTitle())

        self.deFecha.setDate(datetime.today())

    @QtCore.pyqtSlot()
    def on_btAgregarCategoria_clicked(self):
        self.managers[0].on_btAgregar_clicked()
        try:
            self.cargarComboCuentas()
        except AttributeError:
            pass

    @QtCore.pyqtSlot()
    def on_rbIngreso_clicked(self):
        self.cbCuentas.clear()
        items = self.managers[0].manager.cuentasDeIngreso()
        nombres_cuentas = [cuenta.nombre for cuenta in items]
        nombres_cuentas.sort()
        [self.cbCuentas.addItem(nombre_cuenta) for nombre_cuenta in nombres_cuentas]

    @QtCore.pyqtSlot()
    def on_rbEgreso_clicked(self):
        self.cbCuentas.clear()
        items = self.managers[0].manager.cuentasDeEgreso()
        nombres_cuentas = [cuenta.nombre for cuenta in items]
        nombres_cuentas.sort()
        [self.cbCuentas.addItem(nombre_cuenta) for nombre_cuenta in nombres_cuentas]

    @QtCore.pyqtSlot()
    def on_btGuardar_clicked(self):
        BaseAddWindow.on_btGuardar_clicked(self)
        self.leRazonSocial.clear()
        self.dsbMonto.setValue(0)
        self.teDescripcion.clear()
        self.leNroComprobante.clear()

    # REIMPLEMENTED
    def guardar(self, listadedatos):
        # obtenemos el objeto cuenta
        unaCuenta = self.cuentasManager.get(listadedatos[0])[0]
        listadedatos[0] = unaCuenta
        listadedatos[1] = unicode(str(listadedatos[1]), "utf-8")
        listadedatos.append(unaCuenta.tipo)
        self.balance.actualizar(float(listadedatos[1]), unaCuenta.tipo)
        return BaseAddWindow.guardar(self, listadedatos)

    def editar(self, listadedatos):
        BaseAddWindow.editar(self, listadedatos)
Example #50
0
class AddMovimiento(BaseAdd):

    def __init__(self,manager, itemToEdit = False, managers = []):
        BaseAdd.__init__(self, manager, itemToEdit, managers)
        self.loadUI('movimiento/uis/add.ui')

        self.linkToAttribute(self.cbCuentas, Movimiento.cuenta)
        self.linkToAttribute(self.dsbMonto, Movimiento.monto)
        self.linkToAttribute(self.leNroComprobante, Movimiento.nroComprobante)
        self.linkToAttribute(self.teDescripcion, Movimiento.descripcion)
        self.linkToAttribute(self.deFecha, Movimiento.fecha)
        self.linkToAttribute(self.leRazonSocial, Movimiento.razon_social)

        self.cuentasManager = managers[0].manager
        self.balance = Balance()
        self._start_operations()

    # REIMPLEMENTED
    def _start_operations(self):
        centerOnScreen(self)
        self.setValidators()
        self.btSave.setDefault(True)
        if self.itemToEdit:
            self.btSave.setText('Editar')
            self.setWindowTitle(u'Editar Ingreso')
            self._loadDataInWidgets()
        else:
            self.setWindowTitle(u"Agregar Ingreso")
        #self.lbTitle.setText(self.windowTitle())

        self.deFecha.setDate( datetime.today() )

    @QtCore.pyqtSlot()
    def on_btAgregarCategoria_clicked(self):
        self.managers[0].on_btAgregar_clicked()
        try:
            self.cargarComboCuentas()
        except AttributeError :
            pass

    @QtCore.pyqtSlot()
    def on_rbIngreso_clicked(self):
        self.cbCuentas.clear()
        items = self.managers[0].manager.cuentasDeIngreso()
        nombres_cuentas = [cuenta.nombre for cuenta in items]
        nombres_cuentas.sort()
        [self.cbCuentas.addItem( nombre_cuenta ) for nombre_cuenta in nombres_cuentas ]

    @QtCore.pyqtSlot()
    def on_rbEgreso_clicked(self):
        self.cbCuentas.clear()
        items = self.managers[0].manager.cuentasDeEgreso()
        nombres_cuentas = [cuenta.nombre for cuenta in items]
        nombres_cuentas.sort()
        [self.cbCuentas.addItem( nombre_cuenta ) for nombre_cuenta in nombres_cuentas ]

    @QtCore.pyqtSlot()
    def on_btSave_clicked(self):
        BaseAdd.on_btSave_clicked(self)
        self.leRazonSocial.clear()
        self.dsbMonto.setValue(0)
        self.teDescripcion.clear()
        self.leNroComprobante.clear()

    # REIMPLEMENTED
    def save(self, listadedatos):
        # obtenemos el objeto cuenta
        unaCuenta = listadedatos[0]
        listadedatos[1] = unicode(str(listadedatos[1]),'utf-8')
        listadedatos.append( unaCuenta.tipo )
        self.balance.actualizar(float(listadedatos[1]), unaCuenta.tipo)
        return BaseAdd.save(self, listadedatos)

    def edit(self, listadedatos):
        BaseAdd.edit(self, listadedatos)
Example #51
0
class DataTransWidget(QDialog, Ui_dataTransWidget):
    AppName = u'气动数据转换'
    _BalanceSty__ = [u"14杆天平", u"16杆天平", u"18杆天平", u"盒式天平(内)", u"盒式天平(外)"]

    def __init__(self, parent=None):
        super(DataTransWidget, self).__init__(parent)
        self.setupUi(self)
        # self.setWindowFlags(Qt.WindowMinimizeButtonHint)
        # 创建飞行器试验模型
        self.model = AircraftModel()
        self.initModel()
        # 创建天平类型
        self.balance = Balance()
        self.initBalance()
        self.balance.setAircraftModel(self.model)

        self._dir = "./"
        self.balanceParamsTable = BalanceCoesTable(self, balance=self.balance)

        self.tabWidget.setCurrentIndex(0)
        self.txtModelArea.setValidator(QDoubleValidator())
        self.txtModelSpan.setValidator(QDoubleValidator())
        self.txtModelRootChord.setValidator(QDoubleValidator())
        self.txtModelRefChord.setValidator(QDoubleValidator())
        self.txtWindSpeed.setValidator(QDoubleValidator())
        self.txtDeltaX.setValidator(QDoubleValidator())
        self.txtDeltaY.setValidator(QDoubleValidator())
        self.txtDeltaZ.setValidator(QDoubleValidator())

        self.txtModelArea.textChanged.connect(self.initModel)
        self.txtModelSpan.textChanged.connect(self.initModel)
        self.txtModelRootChord.textChanged.connect(self.initModel)
        self.txtModelRefChord.textChanged.connect(self.initModel)
        self.txtWindSpeed.textChanged.connect(self.initModel)
        self.txtDeltaX.textChanged.connect(self.initModel)
        self.txtDeltaY.textChanged.connect(self.initModel)
        self.txtDeltaZ.textChanged.connect(self.initModel)

        self.cbBalanceSty.currentIndexChanged.connect(self.initBalance)
        self.txtStaticFile.textChanged.connect(self.initBalance)
        self.txtDynamicFile.textChanged.connect(self.initBalance)
        self.txtBodyFile.textChanged.connect(self.initBalance)
        self.txtAeroFile.textChanged.connect(self.initBalance)
        self.spbFileHeaderNums.valueChanged.connect(self.initBalance)
        self.spbFileFooterNums.valueChanged.connect(self.initBalance)
        self.chbTime.stateChanged.connect(self.initBalance)
        self.spbFMStartCol.valueChanged.connect(self.initBalance)
        self.spbFMEndCol.valueChanged.connect(self.initBalance)
        self.rbAngleEuler.clicked.connect(self.initBalance)
        self.rbAngleAero.clicked.connect(self.initBalance)
        self.chbTheta.clicked.connect(self.initBalance)
        self.chbPhi.clicked.connect(self.initBalance)
        self.chbPsi.clicked.connect(self.initBalance)
        self.spbThetaCol.valueChanged.connect(self.initBalance)
        self.spbPhiCol.valueChanged.connect(self.initBalance)
        self.spbPsiCol.valueChanged.connect(self.initBalance)
        self.spbAlphaCol.valueChanged.connect(self.initBalance)
        self.spbBetaCol.valueChanged.connect(self.initBalance)

    def initModel(self):
        self.model.setArea(float(self.txtModelArea.text()))    # 初始化模型面积
        self.model.setSpan(float(self.txtModelSpan.text()))    # 初始化模型展长
        self.model.setRootChord(float(self.txtModelRootChord.text()))   # 初始化模型根弦长
        self.model.setRefChord(float(self.txtModelRefChord.text()))     # 初始化模型参考弦长
        self.model.setWindSpeed(float(self.txtWindSpeed.text()))             # 初始化试验风速
        self.model.dx = float(self.txtDeltaX.text())                    # 初始化deltaX
        self.model.dy = float(self.txtDeltaY.text())
        self.model.dz = float(self.txtDeltaZ.text())

    def initBalance(self):
        self.balance.setBalanceSty(self.cbBalanceSty.currentIndex())  # 初始化天平类型
        self.balance.setStaFile(unicode(self.txtStaticFile.text()))
        self.balance.setDynFile(unicode(self.txtDynamicFile.text()))
        self.balance.setBodyFile(unicode(self.txtBodyFile.text()))
        self.balance.setAeroFile(unicode(self.txtAeroFile.text()))
        self.balance.setHeaderRows(self.spbFileHeaderNums.value())
        self.balance.setFooterRows(self.spbFileFooterNums.value())
        self.balance.setTime(self.chbTime.isChecked())
        self.balance.setFMStartCol(self.spbFMStartCol.value() - 1)
        self.spbFMEndCol.setValue(self.spbFMStartCol.value() + 5)
        self.balance.setFMEndCol(self.spbFMEndCol.value() - 1)
        # 更新角度列
        self.balance.setAngleType('body') if self.rbAngleEuler.isChecked() else self.balance.setAngleType('aero')
        self.balance.setThetaCol(self.spbThetaCol.value() - 1) if self.rbAngleEuler.isChecked() and self.chbTheta.isChecked() else self.balance.setThetaCol(None)
        self.balance.setPhiCol(self.spbPhiCol.value() - 1) if self.rbAngleEuler.isChecked() and self.chbPhi.isChecked() else self.balance.setPhiCol(None)
        self.balance.setPsiCol(self.spbPsiCol.value() - 1) if self.rbAngleEuler.isChecked() and self.chbPsi.isChecked() else self.balance.setPsiCol(None)
        self.balance.setAlphaCol(self.spbAlphaCol.value() - 1) if self.rbAngleAero.isChecked() and self.chbAlpha.isChecked() else self.balance.setAlphaCol(None)
        self.balance.setBetaCol(self.spbBetaCol.value() - 1) if self.rbAngleAero.isChecked() and self.chbBeta.isChecked() else self.balance.setBetaCol(None)

    def updateBatchFiles(self):
        self.listWidgetBatchFiles.clear()
        rawjReg = self.txtBatchStaFileReg.text()
        rawdReg = self.txtBatchDynFileReg.text()
        if (not rawjReg) or (not rawdReg):
            QMessageBox.warning(self, u"{0} -- warning".format(DataTransWidget.AppName), u"请输入动/静文件校验符")
            return
        jReg = unicode(rawjReg).strip().lower()
        dReg = unicode(rawdReg).strip().lower()
        dirNums = self.listWidgetBatchDirs.count()
        if self.chbBatchStaticFile.isChecked():
            staticFile = unicode(self.txtBatchStaticFile.text())
            if not staticFile:
                QMessageBox.warning(self, u"{0} -- warning".format(DataTransWidget.AppName), u"请输入静态文件")
                return
            for i in range(dirNums):
                rawDir = unicode(self.listWidgetBatchDirs.item(i).text())
                fileList = os.listdir(rawDir)
                for f in fileList:
                    if f.lower().endswith(dReg):
                        filePath = os.path.join(rawDir, f)
                        self.listWidgetBatchFiles.addItem(staticFile)
                        self.listWidgetBatchFiles.addItem(filePath)
        else:
            for i in range(dirNums):
                rawDir = unicode(self.listWidgetBatchDirs.item(i).text())
                fileList = os.listdir(rawDir)
                for df in fileList:
                    if df.lower().endswith(dReg):
                        jfLower = df.lower().replace(dReg, jReg)
                        fileLowerList = [item.lower() for item in fileList]
                        if jfLower in fileLowerList:
                            index = fileLowerList.index(jfLower)
                            jf = fileList[index]
                            jfilePath = os.path.join(rawDir, jf)
                            dfilePath = os.path.join(rawDir, df)
                            self.listWidgetBatchFiles.addItem(jfilePath)
                            self.listWidgetBatchFiles.addItem(dfilePath)

    @pyqtSignature("int")
    def on_cbBalanceSty_currentIndexChanged(self, index):
        self.balance.setBalanceSty(index)
        self.balance.setBalanceCoes(None)
        self.balanceParamsTable.tableWidget.clear()

    @pyqtSignature("")
    def on_pbtnBalanceParamsSetting_clicked(self):
        if self.cbBalanceSty.currentIndex() == -1:
            QMessageBox.warning(self, u"{0}提示".format(DataTransWidget.AppName), u"未选择天平类型")
            return

        index = self.cbBalanceSty.currentIndex()
        self.balanceParamsTable.label.setText(DataTransWidget._BalanceSty__[index])
        self.balanceParamsTable.labelIndex.setText(str(index + 1))
        coes = self.balance.getBalanceCoes()
        if coes is not None:
            self.balanceParamsTable.setBalanceCoes(coes)
        else:
            if index == 0:
                self.balanceParamsTable.tableWidget.setRowCount(6)
                self.balanceParamsTable.tableWidget.setColumnCount(6)
            if index == 1:
                self.balanceParamsTable.tableWidget.setRowCount(6)
                self.balanceParamsTable.tableWidget.setColumnCount(6)
            if index == 2:
                self.balanceParamsTable.tableWidget.setRowCount(6)
                self.balanceParamsTable.tableWidget.setColumnCount(27)
            if index == 3 or index == 4:
                self.balanceParamsTable.label.setText(DataTransWidget._BalanceSty__[3] + '/' + DataTransWidget._BalanceSty__[4])
                self.balanceParamsTable.tableWidget.setRowCount(6)
                self.balanceParamsTable.tableWidget.setColumnCount(8)
        self.balanceParamsTable.exec_()

    @pyqtSignature("")
    def on_pbtnModelDataInput_clicked(self):
        mdFn = QFileDialog.getOpenFileName(self, u"打开模型文件...", directory=self._dir,
                                           filter=u"所有文件(*.*);;数据文件(*.dat);;文本文件(*.txt)",
                                           selectedFilter=u"文本文件(*.txt)")

        if not mdFn.isEmpty():
            self._dir = mdFn
            try:
                with codecs.open(mdFn, "r", "utf8") as f:
                    rawData = f.readlines()[2:-2]
                    params1 = [s.split('\t')[1].encode('ascii') for s in rawData[:5]]
                    params2 = [s.split('\t')[1].encode('ascii') for s in rawData[6:]]
                    self.txtModelArea.setText(params1[0])
                    self.txtModelSpan.setText(params1[1])
                    self.txtModelRootChord.setText(params1[2])
                    self.txtModelRefChord.setText(params1[3])
                    self.txtWindSpeed.setText(params1[4])
                    self.txtDeltaX.setText(params2[0])
                    self.txtDeltaY.setText(params2[1])
                    self.txtDeltaZ.setText(params2[2])
                return True
            except Exception, msg:
                QMessageBox.about(self, u"{0}提示".format(DataTransWidget.AppName), u"模型文件打开失败\n{0}".format(msg))

            return
Example #52
0
class Account(object):
    """ account related information and operations are contained here """

    def __init__(self, name):
        self.name = str(name)
        self.balance = Balance()

    def withdrawal(self, money):
        """ withdrawal from account if self.balance._total >= money
        Args:
            money (int) : money is dollars
        """
	money = int(money)
        if not self.balance.get_balance() > money:
            raise ValueError("I am sorry! Your balance is less than {}".format(money))

        if self.balance.get_balance() >= money:
            self.balance.subtract(money)

    def deposit(self, money):
        """ deposit to your account
        Args:
            money (int) : money in dollars
        """
	money = int(money)
        self.balance.add(money)

    def get_balance(self):
        """ get balance amount
        Returns:
            self.balance._total (int) : balance left
        """
        return self.balance.get_balance()

    def transfer(self, recipient_name, account_type, money):
        """ transfer money to recipient_name
        Args:
            recipient_name (Customer): it should be the object of type Customer
            account_type (str): the type of account
            money (int): money in dollars to be transferred
        """

	account_type = str(account_type) 
	money = int(money)
        if not self.balance.get_balance() > money:
            raise ValueError("I am sorry! Amount cannot be transferred. Your balance is less than {}".format(money))

        if self.balance.get_balance() >= money:
            self.balance.subtract(money)

        recipient_account = recipient_name.accounts[account_type]
        recipient_balance = recipient_account.balance
        recipient_balance.add(money)