def __le__(self, other): if (isinstance(other, Time)): return (self.__time <= other.time()) if (isinstance(other, str)): return (self <= Time(other)) raise Exceptions.WrongTimeFormat(str(other))
def __VerifyFileInTar(self, expectedName): tarInfo = self.backupFile.next() if tarInfo is None or os.path.basename(tarInfo.name) != expectedName: raise Exceptions.MissingFileInArchive(name=expectedName) return tarInfo
def set_paymentType(self, paymentType): if paymentType is None or len(paymentType) <= 0: raise Exceptions.InvalidParameterValue( 'Invalid value for paymentType') self.paymentType = paymentType
def get_matrix(request): avail_matrices = { 'default': { 'A': { 'A': 1, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 0, 'I': 0, 'K': 0, 'L': 0, 'M': 0, 'N': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'V': 0, 'W': 0, 'Y': 0 }, 'C': { 'A': 0, 'C': 1, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 0, 'I': 0, 'K': 0, 'L': 0, 'M': 0, 'N': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'V': 0, 'W': 0, 'Y': 0 }, 'D': { 'A': 0, 'C': 0, 'D': 1, 'E': 0, 'F': 0, 'G': 0, 'H': 0, 'I': 0, 'K': 0, 'L': 0, 'M': 0, 'N': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'V': 0, 'W': 0, 'Y': 0 }, 'E': { 'A': 0, 'C': 0, 'D': 0, 'E': 1, 'F': 0, 'G': 0, 'H': 0, 'I': 0, 'K': 0, 'L': 0, 'M': 0, 'N': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'V': 0, 'W': 0, 'Y': 0 }, 'F': { 'A': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 1, 'G': 0, 'H': 0, 'I': 0, 'K': 0, 'L': 0, 'M': 0, 'N': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'V': 0, 'W': 0, 'Y': 0 }, 'G': { 'A': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 1, 'H': 0, 'I': 0, 'K': 0, 'L': 0, 'M': 0, 'N': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'V': 0, 'W': 0, 'Y': 0 }, 'H': { 'A': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 1, 'I': 0, 'K': 0, 'L': 0, 'M': 0, 'N': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'V': 0, 'W': 0, 'Y': 0 }, 'I': { 'A': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 0, 'I': 1, 'K': 0, 'L': 0, 'M': 0, 'N': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'V': 0, 'W': 0, 'Y': 0 }, 'K': { 'A': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 0, 'I': 0, 'K': 1, 'L': 0, 'M': 0, 'N': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'V': 0, 'W': 0, 'Y': 0 }, 'L': { 'A': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 0, 'I': 0, 'K': 0, 'L': 1, 'M': 0, 'N': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'V': 0, 'W': 0, 'Y': 0 }, 'M': { 'A': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 0, 'I': 0, 'K': 0, 'L': 0, 'M': 1, 'N': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'V': 0, 'W': 0, 'Y': 0 }, 'N': { 'A': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 0, 'I': 0, 'K': 0, 'L': 0, 'M': 0, 'N': 1, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'V': 0, 'W': 0, 'Y': 0 }, 'P': { 'A': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 0, 'I': 0, 'K': 0, 'L': 0, 'M': 0, 'N': 0, 'P': 1, 'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'V': 0, 'W': 0, 'Y': 0 }, 'Q': { 'A': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 0, 'I': 0, 'K': 0, 'L': 0, 'M': 0, 'N': 0, 'P': 0, 'Q': 1, 'R': 0, 'S': 0, 'T': 0, 'V': 0, 'W': 0, 'Y': 0 }, 'R': { 'A': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 0, 'I': 0, 'K': 0, 'L': 0, 'M': 0, 'N': 0, 'P': 0, 'Q': 0, 'R': 1, 'S': 0, 'T': 0, 'V': 0, 'W': 0, 'Y': 0 }, 'S': { 'A': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 0, 'I': 0, 'K': 0, 'L': 0, 'M': 0, 'N': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 1, 'T': 0, 'V': 0, 'W': 0, 'Y': 0 }, 'T': { 'A': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 0, 'I': 0, 'K': 0, 'L': 0, 'M': 0, 'N': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 1, 'V': 0, 'W': 0, 'Y': 0 }, 'V': { 'A': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 0, 'I': 0, 'K': 0, 'L': 0, 'M': 0, 'N': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'V': 1, 'W': 0, 'Y': 0 }, 'W': { 'A': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 0, 'I': 0, 'K': 0, 'L': 0, 'M': 0, 'N': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'V': 0, 'W': 1, 'Y': 0 }, 'Y': { 'A': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 0, 'I': 0, 'K': 0, 'L': 0, 'M': 0, 'N': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'V': 0, 'W': 0, 'Y': 1 }, }, 'BLOSUM62': {} } # TODO if request in avail_matrices.keys(): return avail_matrices[request] else: raise Exceptions.MissingMatrixType("Matrix type " + request + "does not exist")
if options.replaceExisting: sid = options.asSid or databaseFromEnv.sid existingDatabase = manager.DatabaseBySid(sid, ignoreIfMissing=True) if existingDatabase is not None: existingDatabase.Remove() mapping = None database = backupSet.database if options.asSid: newDatabase = Database.Database(manager, options.asSid, databaseFromEnv.oracleHome, backupSet.database.startMode, options.sysPassword) mapping = Utils.Mapping(newDatabase, backupSet.database, options.prompts) newDatabase.info = database.info.Clone(newDatabase.sid, mapping) database = newDatabase database.Initialize(dirs=database.GetDirectories()) backupSet.Restore(database, mapping) else: sid = options.asSid or backupSet.database.sid existingDatabase = manager.DatabaseBySid(sid, ignoreIfMissing=True) if existingDatabase is not None: if not options.replaceExisting: raise Exceptions.DatabaseAlreadyExists(sid=sid) del existingDatabase if options.asSid and options.prompts: origValue = Utils.NormalizePath(backupSet.database.oracleHome) backupSet.database.oracleHome = \ cx_ReadLine.ReadLine("Map %s to" % origValue, origValue) manager.ExecuteForDatabase(backupSet.database)
def ReadDiscreteInputs(self, startingAddress, quantity): """ Read Discrete Inputs from Master device (Function code 2) startingAddress: First discrete input to be read quantity: Numer of discrete Inputs to be read returns: Boolean Array [0..quantity-1] which contains the discrete Inputs """ self.__transactionIdentifier += 1 if (self.ser is not None): if (self.ser.closed): raise Exception.SerialPortNotOpenedException( "serial port not opened") if (startingAddress > 65535 | quantity > 2000): raise ValueError( "Starting address must be 0 - 65535; quantity must be 0 - 2000" ) functionCode = 2 length = 6 transactionIdentifierLSB = self.__transactionIdentifier & 0xFF transactionIdentifierMSB = ( (self.__transactionIdentifier & 0xFF00) >> 8) lengthLSB = length & 0xFF lengthMSB = (length & 0xFF00) >> 8 startingAddressLSB = startingAddress & 0xFF startingAddressMSB = (startingAddress & 0xFF00) >> 8 quatityLSB = quantity & 0xFF quatityMSB = (quantity & 0xFF00) >> 8 if (self.ser is not None): data = bytearray([ self._unitIdentifier, functionCode, startingAddressMSB, startingAddressLSB, quatityMSB, quatityLSB, 0, 0 ]) CRC = self.__calculateCRC(data, len(data) - 2, 0) CrcLSB = CRC & 0xFF CrcMSB = (CRC & 0xFF00) >> 8 data[6] = CrcLSB data[7] = CrcMSB self.ser.write(data) if (quantity % 8 != 0): bytesToRead = 6 + int(quantity / 8) else: bytesToRead = 5 + int(quantity / 8) data = self.ser.read(bytesToRead) if ((data[1] == 0x82) & (data[2] == 0x01)): raise Exceptions.FunctionCodeNotSupportedException( "Function code not supported by master") if ((data[1] == 0x82) & (data[2] == 0x02)): raise Exceptions.StartingAddressInvalidException( "Starting address invalid or starting address + quantity invalid" ) if ((data[1] == 0x82) & (data[2] == 0x03)): raise Exceptions.QuantityInvalidException("quantity invalid") if ((data[1] == 0x82) & (data[2] == 0x04)): raise Exceptions.ModbusException("error reading") myList = list() for i in range(0, quantity): myList.append(bool((data[int(i / 8) + 3] >> int(i % 8)) & 0x1)) return myList else: protocolIdentifierLSB = 0x00 protocolIdentifierMSB = 0x00 lengthLSB = 0x06 lengthMSB = 0x00 data = bytearray([ transactionIdentifierMSB, transactionIdentifierLSB, protocolIdentifierMSB, protocolIdentifierLSB, lengthMSB, lengthLSB, self._unitIdentifier, functionCode, startingAddressMSB, startingAddressLSB, quatityMSB, quatityLSB ]) self.tcpClientSocket.send(data) if (quantity % 8 != 0): bytesToRead = 10 + int(quantity / 8) else: bytesToRead = 9 + int(quantity / 8) data = self.tcpClientSocket.recv(bytesToRead) if ((data[1 + 6] == 0x82) & (data[2 + 6] == 0x01)): raise Exceptions.FunctionCodeNotSupportedException( "Function code not supported by master") if ((data[1 + 6] == 0x82) & (data[2 + 6] == 0x02)): raise Exceptions.StartingAddressInvalidException( "Starting address invalid or starting address + quantity invalid" ) if ((data[1 + 6] == 0x82) & (data[2 + 6] == 0x03)): raise Exceptions.QuantityInvalidException("quantity invalid") if ((data[1 + 6] == 0x82) & (data[2 + 6] == 0x04)): raise Exceptions.ModbusException("error reading") myList = list() for i in range(0, quantity): myList.append( bool((data[int(i / 8) + 3 + 6] >> int(i % 8)) & 0x1)) return myList
def new_show_error(message, detail=None, fatal=False): raise Exceptions.TestException(message)
def get(self, key, whitelist=None, strict_whitelist=True): raise Exceptions.NotImplemented("MatrixManager: get")
def get_2(self, key, snps_1, snps_2): raise Exceptions.NotImplemented("MatrixManager: get_2")
def _check_strict(whitelist, snps, key): extra = {x for x in whitelist if not x in snps} if len(extra): msg = "SNPs in whitelist not in matrix for %s:%s" % (key, extra) raise Exceptions.InvalidArguments(msg)
def _check_value(value, key, id1, id2): try: float(value) except: msg = "Invalid value:{} for ({},{},{})".format(value, key, id1, id2) raise Exceptions.InvalidInputFormat(msg)
parser.AddOption(cx_OracleUtils.SchemaOption()) parser.AddOption(Options.NO_COMMENTS) parser.AddOption(Options.NO_GRANTS) parser.AddOption(Options.USE_DBA_VIEWS) cx_LoggingOptions.AddOptions(parser) parser.AddArgument("fromDir", required = 1, help = "the directory containing the source objects") parser.AddArgument("toDir", required = 1, help = "the directory containing the target objects or the objects " "which the source objects will be transformed into using the " "generated script") options = parser.Parse() cx_LoggingOptions.ProcessOptions(options) options.fromDir = os.path.normpath(options.fromDir) if not os.path.exists(options.fromDir): raise Exceptions.SourceDirectoryNotFound() options.toDir = os.path.normpath(options.toDir) if not os.path.exists(options.toDir): raise Exceptions.TargetDirectoryNotFound() # set up describe environment connection = cx_OracleUtils.Connect(options.schema) environment = cx_OracleObject.Environment(connection, options) describer = cx_OracleObject.Describer(environment, options) wantGrants = describer.wantGrants # define some constants CONSTRAINT_TYPES = ["PRIMARY KEY", "UNIQUE CONSTRAINT", "FOREIGN KEY", "CHECK CONSTRAINT"] SOURCE_TYPES = ["FUNCTION", "PACKAGE", "PACKAGE BODY", "PROCEDURE", "TYPE", "TYPE BODY", "VIEW"]
def read_gauout(filename): # check extension end_out = (filename.lower()).endswith(".out") end_log = (filename.lower()).endswith(".log") if (not end_out) and (not end_log): raise Exc.FileType(Exception) key = 'GINC' fin = '@' str_end = 'Normal termination' str_atoms = 'NAtoms' str_geom1a = 'Z-Matrix orientation' str_geom1b = 'Input orientation' str_geom2 = 'Standard orientation' str_nosym = 'Nosym' str_zmat = 'Final structure in terms of initial Z-matrix' start_archives = [] end_archives = [] str_endfiles = [] latom = [] idx_last_zmat = -1 list_zmat_backup = [] # More then one archive file for instance Link1 filex = open(filename, 'r') nlin = 0 for linea in filex: nlin += 1 if str_end in linea: str_endfiles.append(nlin) if key in linea: start_archives.append(nlin) if fin in linea: end_archives.append(nlin) if str_atoms in linea: latom = linea.split() filex.close() # It does not consider an archive file right after the main archive file # For some reason gaussian sometimes print one archive after the other str_tmp = str_endfiles[:] num_tmp = len(str_tmp) if num_tmp > 1: for i in range(num_tmp - 1, 0, -1): if abs(str_tmp[i - 1] - str_tmp[i]) < 300: del str_endfiles[i] del start_archives[i] del end_archives[i] # # number_archives = len(start_archives) if number_archives == 0: return -1 str_beginfiles = str_endfiles[:] str_beginfiles.insert(0, 0) str_beginfiles.pop() natoms = int(latom[1]) if number_archives == 1 and start_archives[0] == 0: return str_geom1s = [] str_geom2s = [] str_nosyms = [] str_zmats = [] for i in range(number_archives): str_geom1s.append(0) str_geom2s.append(0) str_nosyms.append(0) str_zmats.append(0) start_archive = start_archives[i] end_archive = end_archives[i] pos_beginfile = str_beginfiles[i] pos_endfile = str_endfiles[i] filex = open(filename, 'r') nlin = 0 for linea in filex: nlin += 1 if nlin >= pos_beginfile and nlin <= pos_endfile: if str_nosym.lower() in linea.lower(): str_nosyms[i] = nlin if str_geom1a in linea or str_geom1b in linea: str_geom1s[i] = nlin if str_geom2 in linea: str_geom2s[i] = nlin if str_zmat in linea: str_zmats[i] = nlin filex.close() # position of the geometries pos_nosym = str_nosyms[i] pos_geom1 = str_geom1s[i] pos_geom2 = str_geom2s[i] pos_zmat1 = str_zmats[i] num_imag,charge,mult,commands,list_level,list_energy,atomic_number,ccgeom,list_zmat,\ hess_data,hess_full,grad=\ archive(filename,natoms,start_archive,end_archive,\ pos_beginfile,pos_endfile,pos_nosym,pos_geom1,pos_geom2,pos_zmat1) # Saves the last available z-matrix if str_zmats[i] != 0: idx_last_zmat = i list_zmat_backup = list_zmat[:] # atomic mass atomic_mass = atonums2masses(atomic_number) ccgeom = flatten_llist(ccgeom) energy = list_energy[-1] level = list_level[-1] # from Angstrom to Bohr ccgeom = [xx / ANGSTROM for xx in ccgeom] return ccgeom, atomic_number, charge, mult, energy, grad, hess_data, atomic_mass, level
def execute(self,arguments,global_variables:dict): local_variables = {'arguments':arguments,} arguments_native = arguments#arguments.this['value'] if len(self.input_arguments) >=\ len(arguments_native): for argument in enumerate(arguments_native): local_variables[self.input_arguments[argument[0]]] = argument[1] for i in range(len(arguments_native),\ len(self.input_arguments)): try: local_variables[self.input_arguments[i]] = self.default_values[self.input_arguments[i]] except: local_variables[self.input_arguments[i]] = Types.undefined else: for input_argument in enumerate(self.input_arguments): local_variables[input_argument[1]] = arguments_native[input_argument[0]] return_value = Types.undefined for operation in self.operations: if operation[0] == 'var': result = self.calc_operation(operation[2],\ global_variables,\ local_variables) local_variables[operation[1]] = result elif operation[0] == 'var_change': index = self.calc_operation(operation[1],\ global_variables,\ local_variables) result = self.calc_operation(operation[2],\ global_variables,\ local_variables) if isinstance(index,tuple): data = self.get_variable(index[0], global_variables, local_variables) for layer in index[1:-1]: new_index = index_check(layer) try: data = data[new_index] except: raise Exceptions.ReferenceError(new_index) new_index = index_check(index[-1]) try: data[new_index] = result except: raise Exceptions.ReferenceError(new_index) else: self.change_variable(index, result, global_variables, local_variables) elif operation[0] == 'let': result = self.calc_operation(operation[2],\ global_variables,\ local_variables) local_variables[operation[1]] = result elif operation[0] == 'function': local_variables[operation[1]] = Function(operation[2],operation[3],nested=True) elif operation[0] == 'if'\ or operation[0] == 'loop'\ or operation[0] == 'try': global_copy = global_variables.copy() global_copy.update(local_variables) result = operation[1].execute(global_copy) if isinstance(result,tuple): for key in result[1].keys(): try: self.change_variable(key, result[1][key], global_variables, local_variables) except: local_variables[key] = result[1][key] if self.nested: return result[0],global_variables else: return result[0] else: for key in result.keys(): try: self.change_variable(key, result[key], global_variables, local_variables) except: local_variables[key] = result[key] elif operation[0] == 'return': result = self.calc_operation(operation[1],\ global_variables,\ local_variables) if self.nested: return result,global_variables else: return result if self.nested: return None,global_variables else: return None
def WriteSingleRegister(self, startingAddress, value): """ Write single Register to Master device (Function code 6) startingAddress: Register to be written value: Register Value to be written """ self.__transactionIdentifier += 1 if (self.ser is not None): if (self.ser.closed): raise Exception.SerialPortNotOpenedException( "serial port not opened") functionCode = 6 length = 6 transactionIdentifierLSB = self.__transactionIdentifier & 0xFF transactionIdentifierMSB = ( (self.__transactionIdentifier & 0xFF00) >> 8) lengthLSB = length & 0xFF lengthMSB = (length & 0xFF00) >> 8 startingAddressLSB = startingAddress & 0xFF startingAddressMSB = (startingAddress & 0xFF00) >> 8 valueLSB = value & 0xFF valueMSB = (value & 0xFF00) >> 8 if (self.ser is not None): data = bytearray([ self._unitIdentifier, functionCode, startingAddressMSB, startingAddressLSB, valueMSB, valueLSB, 0, 0 ]) CRC = self.__calculateCRC(data, len(data) - 2, 0) CrcLSB = CRC & 0xFF CrcMSB = (CRC & 0xFF00) >> 8 data[6] = CrcLSB data[7] = CrcMSB self.ser.write(data) bytesToRead = 8 data = self.ser.read(bytesToRead) if ((data[1] == 0x86) & (data[2] == 0x01)): raise Exceptions.FunctionCodeNotSupportedException( "Function code not supported by master") if ((data[1] == 0x86) & (data[2] == 0x02)): raise Exceptions.StartingAddressInvalidException( "Starting address invalid or starting address + quantity invalid" ) if ((data[1] == 0x86) & (data[2] == 0x03)): raise Exceptions.QuantityInvalidException("quantity invalid") if ((data[1] == 0x86) & (data[2] == 0x04)): raise Exceptions.ModbusException("error reading") if data[1] == self._unitIdentifier: return True else: return False else: protocolIdentifierLSB = 0x00 protocolIdentifierMSB = 0x00 lengthLSB = 0x06 lengthMSB = 0x00 data = bytearray([ transactionIdentifierMSB, transactionIdentifierLSB, protocolIdentifierMSB, protocolIdentifierLSB, lengthMSB, lengthLSB, self._unitIdentifier, functionCode, startingAddressMSB, startingAddressLSB, valueMSB, valueLSB ]) self.tcpClientSocket.send(data) bytesToRead = 12 data = self.tcpClientSocket.recv(bytesToRead) if ((data[1 + 6] == 0x86) & (data[2 + 6] == 0x01)): raise Exceptions.FunctionCodeNotSupportedException( "Function code not supported by master") if ((data[1 + 6] == 0x86) & (data[2 + 6] == 0x02)): raise Exceptions.StartingAddressInvalidException( "Starting address invalid or starting address + quantity invalid" ) if ((data[1 + 6] == 0x86) & (data[2 + 6] == 0x03)): raise Exceptions.QuantityInvalidException("quantity invalid") if ((data[1 + 6] == 0x86) & (data[2 + 6] == 0x04)): raise Exceptions.ModbusException("error reading") return True
def model_labels(self): raise Exceptions.NotImplemented("MatrixManager: model_labels")
def WriteMultipleRegisters(self, startingAddress, values): """ Write multiple registers to Master device (Function code 16) startingAddress: First register to be written values: Register Values [0..quantity-1] to be written """ self.__transactionIdentifier += 1 if (self.ser is not None): if (self.ser.closed): raise Exception.SerialPortNotOpenedException( "serial port not opened") functionCode = 16 length = 6 transactionIdentifierLSB = self.__transactionIdentifier & 0xFF transactionIdentifierMSB = ( (self.__transactionIdentifier & 0xFF00) >> 8) lengthLSB = length & 0xFF lengthMSB = (length & 0xFF00) >> 8 startingAddressLSB = startingAddress & 0xFF startingAddressMSB = (startingAddress & 0xFF00) >> 8 quantityLSB = len(values) & 0xFF quantityMSB = (len(values) & 0xFF00) >> 8 valueToWrite = list() for i in range(0, len(values)): valueToWrite.append(values[i]) if (self.ser is not None): data = bytearray([ self._unitIdentifier, functionCode, startingAddressMSB, startingAddressLSB, quantityMSB, quantityLSB ]) data.append(len(valueToWrite) * 2) #Bytecount for i in range(0, len(valueToWrite)): data.append((valueToWrite[i] & 0xFF00) >> 8) data.append(valueToWrite[i] & 0xFF) CRC = self.__calculateCRC(data, len(data), 0) CrcLSB = CRC & 0xFF CrcMSB = (CRC & 0xFF00) >> 8 data.append(CrcLSB) data.append(CrcMSB) self.ser.write(data) bytesToRead = 8 data = self.ser.read(bytesToRead) if ((data[1] == 0x90) & (data[2] == 0x01)): raise Exceptions.FunctionCodeNotSupportedException( "Function code not supported by master") if ((data[1] == 0x90) & (data[2] == 0x02)): raise Exceptions.StartingAddressInvalidException( "Starting address invalid or starting address + quantity invalid" ) if ((data[1] == 0x90) & (data[2] == 0x03)): raise Exceptions.QuantityInvalidException("quantity invalid") if ((data[1] == 0x90) & (data[2] == 0x04)): raise Exceptions.ModbusException("error reading") if data[1] == self._unitIdentifier: return True else: return False else: protocolIdentifierLSB = 0x00 protocolIdentifierMSB = 0x00 lengthLSB = 0x06 lengthMSB = 0x00 data = bytearray([ transactionIdentifierMSB, transactionIdentifierLSB, protocolIdentifierMSB, protocolIdentifierLSB, lengthMSB, lengthLSB, self._unitIdentifier, functionCode, startingAddressMSB, startingAddressLSB, quantityMSB, quantityLSB ]) data.append(len(valueToWrite) * 2) #Bytecount for i in range(0, len(valueToWrite)): data.append((valueToWrite[i] & 0xFF00) >> 8) data.append(valueToWrite[i] & 0xFF) self.tcpClientSocket.send(data) bytesToRead = 12 data = self.tcpClientSocket.recv(bytesToRead) if ((data[1] == 0x90) & (data[2] == 0x01)): raise Exceptions.FunctionCodeNotSupportedException( "Function code not supported by master") if ((data[1] == 0x90) & (data[2] == 0x02)): raise Exceptions.StartingAddressInvalidException( "Starting address invalid or starting address + quantity invalid" ) if ((data[1] == 0x90) & (data[2] == 0x03)): raise Exceptions.QuantityInvalidException("quantity invalid") if ((data[1] == 0x90) & (data[2] == 0x04)): raise Exceptions.ModbusException("error reading") return True
def n_ids(self, gene): raise Exceptions.NotImplemented("MatrixManager: n_ids")
def getSerialByte(self, timeout=None): serialByte = self.uart.readByte(timeout) if len(serialByte) != 1: raise Exceptions.SnifferTimeout("Packet read timed out.") return ord(serialByte)
def Train(self): if TRAIN_KEY not in self._dict: raise Exceptions.ManifestInvalidException("Invalid train") return self._dict[TRAIN_KEY]
def pop(self): if (len(self.__stack) == 0): raise Exceptions.EmptyStack() obj = self.__stack[-1] del self.__stack[-1] return obj
Log.Warn(e.Pipe) package.CheckState() if not package.IsInstalled(): Log.Error("Package: %s, errored during install." % package.GetName()) raise Exceptions.InstallException("Failed to install", package.GetName()) Log.kLogFile.Write("Package: %s installed.\n" % package.GetName()) Log.Result("Package: %s installed." % package.GetName()) return package.GetInstallPath() else: # Cannot be installed, raise error Log.Error( "Package %s cannot be installed by snoing, please install manually." % packageName) Log.Detail(package.GetHelpText()) raise Exceptions.InstallException("Cannot install", packageName) def InstallDependencies(self, packageName): """ Install the dependencies for named package.""" if not packageName in self._Packages.keys(): Log.Error("Package %s not found" % packageName) raise Exceptions.InstallException("Package not found", packageName) self._InstallDependencies(self._Packages[packageName]) return def _InstallDependencies(self, package): """ Install the dependencies (if required).""" dependencyDict = {} # Return dictionary of dependencies for dependency in package.GetDependencies(): if isinstance(dependency, types.ListType): # Multiple optional dependencies
blockSize = 8192 # Convenient block size while True: buffer = remoteFile.read( blockSize ) if not buffer: # Nothing left to download break downloaded += len( buffer ) localFile.write( buffer ) remoteFile.close() localFile.close() except (KeyboardInterrupt, SystemExit): localFile.close() remoteFile.close() os.remove( tempFile ) raise if downloaded < downloadSize: # Something has gone wrong raise Exceptions.PackageException( "Download error", "$i" % downloadSize ) os.rename( tempFile, os.path.join( kCachePath, fileName ) ) return "Downloaded %i bytes\n" % downloadSize def ExecuteSimpleCommand( command, args, env, cwd, verbose = False ): """ Blocking execute command. Returns True on success""" global kCachePath, kInstallPath, kVerbose shellCommand = [ command ] + args useEnv = os.environ.copy() # Default to current environment if env is not None: for key in env: useEnv[key] = env[key] process = subprocess.Popen( args = shellCommand, env = useEnv, cwd = cwd, stdout = subprocess.PIPE, stderr = subprocess.PIPE ) output = "" error = "" if kVerbose or verbose:
def CheckPackage(self, packageName): """ Check if a package is installed, minimal logging. Returns True or False.""" if not packageName in self._Packages.keys(): Log.Error("Package %s not found" % packageName) raise Exceptions.InstallException("Package not found", packageName) return self._Packages[packageName].IsInstalled()
def __VerifyFileExists(self, fileName): if not os.path.exists(fileName): raise Exceptions.MissingFile(name=fileName)
bindType = cx_Oracle.LONG_BINARY else: mode = "r" bindType = cx_Oracle.LONG_STRING data = open(options.fileName, mode).read() if options.statementInFile: options.statement = open(options.statement).read().strip() options.isColumn = " " not in options.statement if not options.isColumn: statement = options.statement options.values["data"] = data cursor.setinputsizes(data=bindType) else: parts = options.statement.upper().split(".") if len(parts) < 2 or len(parts) > 3: raise Exceptions.InvalidColumnName() if len(parts) == 2: owner = connection.username.upper() table, column = parts else: owner, table, column = parts clauses = ["%s = :%s" % (n, n) for n in options.values] updateStatement = "update %s.%s set %s = :%s where %s" % \ (owner, table, column, column, " and ".join(clauses)) options.values[column] = data names = list(options.values.keys()) values = [":%s" % n for n in names] statement = "insert into %s.%s (%s) values (%s)" % \ (owner, table, ",".join(names), ",".join(values)) initialBinds = {column: bindType} cursor.setinputsizes(**initialBinds)
def set_receiverPhone(self, receiverPhone): ''' one of receiverEmail or receiverPhone must be set''' if receiverPhone is None or len(receiverPhone) <= 0: raise Exceptions.InvalidParameterValue( 'Invalid value for receiverPhone') self.receiverPhone = receiverPhone
def ReadHoldingRegisters(self, startingAddress, quantity): """ Read Holding Registers from Master device (Function code 3) startingAddress: First holding register to be read quantity: Number of holding registers to be read returns: Int Array [0..quantity-1] which contains the holding registers """ self.__transactionIdentifier += 1 if (self.ser is not None): if (self.ser.closed): raise Exception.SerialPortNotOpenedException( "serial port not opened") if (startingAddress > 65535 | quantity > 125): raise ValueError( "Starting address must be 0 - 65535; quantity must be 0 - 125") functionCode = 3 length = 6 transactionIdentifierLSB = self.__transactionIdentifier & 0xFF transactionIdentifierMSB = ( (self.__transactionIdentifier & 0xFF00) >> 8) lengthLSB = length & 0xFF lengthMSB = (length & 0xFF00) >> 8 startingAddressLSB = startingAddress & 0xFF startingAddressMSB = (startingAddress & 0xFF00) >> 8 quatityLSB = quantity & 0xFF quatityMSB = (quantity & 0xFF00) >> 8 if (self.ser is not None): data = bytearray([ self._unitIdentifier, functionCode, startingAddressMSB, startingAddressLSB, quatityMSB, quatityLSB, 0, 0 ]) CRC = self.__calculateCRC(data, len(data) - 2, 0) CrcLSB = CRC & 0xFF CrcMSB = (CRC & 0xFF00) >> 8 data[6] = CrcLSB data[7] = CrcMSB self.ser.write(data) bytesToRead = 5 + int(quantity * 2) data = self.ser.read(bytesToRead) if ((data[1] == 0x83) & (data[2] == 0x01)): raise Exceptions.FunctionCodeNotSupportedException( "Function code not supported by master") if ((data[1] == 0x83) & (data[2] == 0x02)): raise Exceptions.StartingAddressInvalidException( "Starting address invalid or starting address + quantity invalid" ) if ((data[1] == 0x83) & (data[2] == 0x03)): raise Exceptions.QuantityInvalidException("quantity invalid") if ((data[1] == 0x83) & (data[2] == 0x04)): raise Exceptions.ModbusException("error reading") myList = list() for i in range(0, quantity): myList.append((data[i * 2 + 3] << 8) + data[i * 2 + 4]) return myList else: protocolIdentifierLSB = 0x00 protocolIdentifierMSB = 0x00 lengthLSB = 0x06 lengthMSB = 0x00 data = bytearray([ transactionIdentifierMSB, transactionIdentifierLSB, protocolIdentifierMSB, protocolIdentifierLSB, lengthMSB, lengthLSB, self._unitIdentifier, functionCode, startingAddressMSB, startingAddressLSB, quatityMSB, quatityLSB ]) self.tcpClientSocket.send(data) bytesToRead = 9 + int(quantity * 2) data = self.tcpClientSocket.recv(bytesToRead) if ((data[1 + 6] == 0x83) & (data[2 + 6] == 0x01)): raise Exceptions.FunctionCodeNotSupportedException( "Function code not supported by master") if ((data[1 + 6] == 0x83) & (data[2 + 6] == 0x02)): raise Exceptions.StartingAddressInvalidException( "Starting address invalid or starting address + quantity invalid" ) if ((data[1 + 6] == 0x83) & (data[2 + 6] == 0x03)): raise Exceptions.QuantityInvalidException("quantity invalid") if ((data[1 + 6] == 0x83) & (data[2 + 6] == 0x04)): raise Exceptions.ModbusException("error reading") myList = list() for i in range(0, quantity): myList.append((data[i * 2 + 3 + 6] << 8) + data[i * 2 + 4 + 6]) return myList
def set_amount(self, amount): if amount is None or amount <= 0: raise Exceptions.InvalidParameterValue('Invalid value for amount') self.amount = amount
def fromint(self, i): assert (isinstance(i, int)) try: self.__time = datetime.datetime.fromtimestamp(i) except: raise Exceptions.WrongTimeFormat(str(i))