desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Instance initialiation. Arguments: dbf: A `Dbf.Dbf` instance this record belonogs to. index: An integer record index or None. If this value is None, record will be appended to the DBF. deleted: Boolean flag indicating whether this record is a deleted record. data: A sequence or None. This is a data of the fields. If this argument is None, default values will be used.'
def __init__(self, dbf, index=None, deleted=False, data=None):
self.dbf = dbf self.index = index self.deleted = deleted if (data is None): self.fieldData = [_fd.defaultValue for _fd in dbf.header.fields] else: self.fieldData = list(data)
'Return raw record contents read from the stream. Arguments: dbf: A `Dbf.Dbf` instance containing the record. index: Index of the record in the records\' container. This argument can\'t be None in this call. Return value is a string containing record data in DBF format.'
def rawFromStream(cls, dbf, index):
dbf.stream.seek((dbf.header.headerLength + (index * dbf.header.recordLength))) return dbf.stream.read(dbf.header.recordLength)
'Return a record read from the stream. Arguments: dbf: A `Dbf.Dbf` instance new record should belong to. index: Index of the record in the records\' container. This argument can\'t be None in this call. Return value is an instance of the current class.'
def fromStream(cls, dbf, index):
return cls.fromString(dbf, cls.rawFromStream(dbf, index), index)
'Return record read from the string object. Arguments: dbf: A `Dbf.Dbf` instance new record should belong to. string: A string new record should be created from. index: Index of the record in the container. If this argument is None, record will be appended. Return value is an instance of the current class.'
def fromString(cls, dbf, string, index=None):
return cls(dbf, index, (string[0] == '*'), [_fd.decodeFromRecord(string) for _fd in dbf.header.fields])
'Write data to the dbf stream. Note: This isn\'t a public method, it\'s better to use \'store\' instead publically. Be design ``_write`` method should be called only from the `Dbf` instance.'
def _write(self):
self._validateIndex(False) self.dbf.stream.seek(self.position) self.dbf.stream.write(bytes(self.toString(), sys.getfilesystemencoding())) if (self.index == len(self.dbf)): self.dbf.stream.write('\x1a')
'Valid ``self.index`` value. If ``allowUndefined`` argument is True functions does nothing in case of ``self.index`` pointing to None object.'
def _validateIndex(self, allowUndefined=True, checkRange=False):
if (self.index is None): if (not allowUndefined): raise ValueError('Index is undefined') elif (self.index < 0): raise ValueError(("Index can't be negative (%s)" % self.index)) elif (checkRange and (self.index <= self.dbf.header.recordCount)): raise ValueError(('There are only %d records in the DBF' % self.dbf.header.recordCount))
'Store current record in the DBF. If ``self.index`` is None, this record will be appended to the records of the DBF this records belongs to; or replaced otherwise.'
def store(self):
self._validateIndex() if (self.index is None): self.index = len(self.dbf) self.dbf.append(self) else: self.dbf[self.index] = self
'Mark method as deleted.'
def delete(self):
self.deleted = True
'Return string packed record values.'
def toString(self):
return ''.join(([' *'[self.deleted]] + [_def.encodeValue(_dat) for (_def, _dat) in zip(self.dbf.header.fields, self.fieldData)]))
'Return a flat list of fields. Note: Change of the list\'s values won\'t change real values stored in this object.'
def asList(self):
return self.fieldData[:]
'Return a dictionary of fields. Note: Change of the dicts\'s values won\'t change real values stored in this object.'
def asDict(self):
return dict([_i for _i in zip(self.dbf.fieldNames, self.fieldData)])
'Return value by field name or field index.'
def __getitem__(self, key):
if isinstance(key, int): return self.fieldData[key] return self.fieldData[self.dbf.indexOfFieldName(key)]
'Set field value by integer index of the field or string name.'
def __setitem__(self, key, value):
if isinstance(key, int): return self.fieldData[key] self.fieldData[self.dbf.indexOfFieldName(key)] = value
'Append the actual tags to content.'
def render(self, tag, single, between, kwargs):
out = (u'<%s' % tag) for (key, value) in kwargs.iteritems(): if (value is not None): key = key.strip('_') if (key in ['http_equiv', 'accept_charset']): key.replace('_', '-') out = (u'%s %s="%s"' % (out, key, escape(value))) else: out = (u'%s %s' % (out, key)) if (between is not None): out = (u'%s>%s</%s>' % (out, between, tag)) elif single: out = (u'%s />' % out) else: out = (u'%s>' % out) if (self.parent is not None): self.parent.content.append(out) else: return out
'Append a closing tag unless element has only opening tag.'
def close(self):
if (self.tag in self.parent.twotags): self.parent.content.append(('</%s>' % self.tag)) elif (self.tag in self.parent.onetags): raise ClosingError(self.tag) elif ((self.parent.mode == 'strict_html') and (self.tag in self.parent.deptags)): raise DeprecationError(self.tag)
'Append an opening tag.'
def open(self, **kwargs):
if ((self.tag in self.parent.twotags) or (self.tag in self.parent.onetags)): self.render(self.tag, False, None, kwargs) elif ((self.mode == 'strict_html') and (self.tag in self.parent.deptags)): raise DeprecationError(self.tag)
'Stuff that effects the whole document. mode -- \'strict_html\' for HTML 4.01 (default) \'html\' alias for \'strict_html\' \'loose_html\' to allow some deprecated elements \'xml\' to allow arbitrary elements case -- \'lower\' element names will be printed in lower case (default) \'upper\' they will be printed in upper case onetags -- list or tuple of valid elements with opening tags only twotags -- list or tuple of valid elements with both opening and closing tags these two keyword arguments may be used to select the set of valid elements in \'xml\' mode invalid elements will raise appropriate exceptions separator -- string to place between added elements, defaults to newline class_ -- a class that will be added to every element if defined'
def __init__(self, mode='strict_html', case='lower', onetags=None, twotags=None, separator='\n', class_=None):
valid_onetags = ['AREA', 'BASE', 'BR', 'COL', 'FRAME', 'HR', 'IMG', 'INPUT', 'LINK', 'META', 'PARAM'] valid_twotags = ['A', 'ABBR', 'ACRONYM', 'ADDRESS', 'B', 'BDO', 'BIG', 'BLOCKQUOTE', 'BODY', 'BUTTON', 'CAPTION', 'CITE', 'CODE', 'COLGROUP', 'DD', 'DEL', 'DFN', 'DIV', 'DL', 'DT', 'EM', 'FIELDSET', 'FORM', 'FRAMESET', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'HEAD', 'HTML', 'I', 'IFRAME', 'INS', 'KBD', 'LABEL', 'LEGEND', 'LI', 'MAP', 'NOFRAMES', 'NOSCRIPT', 'OBJECT', 'OL', 'OPTGROUP', 'OPTION', 'P', 'PRE', 'Q', 'SAMP', 'SCRIPT', 'SELECT', 'SMALL', 'SPAN', 'STRONG', 'STYLE', 'SUB', 'SUP', 'TABLE', 'TBODY', 'TD', 'TEXTAREA', 'TFOOT', 'TH', 'THEAD', 'TITLE', 'TR', 'TT', 'UL', 'VAR'] deprecated_onetags = ['BASEFONT', 'ISINDEX'] deprecated_twotags = ['APPLET', 'CENTER', 'DIR', 'FONT', 'MENU', 'S', 'STRIKE', 'U'] self.header = [] self.content = [] self.footer = [] self.case = case self.separator = separator self._full = False self.class_ = class_ if ((mode == 'strict_html') or (mode == 'html')): self.onetags = valid_onetags self.onetags += map(string.lower, self.onetags) self.twotags = valid_twotags self.twotags += map(string.lower, self.twotags) self.deptags = (deprecated_onetags + deprecated_twotags) self.deptags += map(string.lower, self.deptags) self.mode = 'strict_html' elif (mode == 'loose_html'): self.onetags = (valid_onetags + deprecated_onetags) self.onetags += map(string.lower, self.onetags) self.twotags = (valid_twotags + deprecated_twotags) self.twotags += map(string.lower, self.twotags) self.mode = mode elif (mode == 'xml'): if (onetags and twotags): self.onetags = onetags self.twotags = twotags elif ((onetags and (not twotags)) or (twotags and (not onetags))): raise CustomizationError() else: self.onetags = russell() self.twotags = russell() self.mode = mode else: raise ModeError(mode)
'Return the document as a string. escape -- False print normally True replace < and > by &lt; and &gt; the default escape sequences in most browsers'
def __call__(self, escape=False):
if escape: return _escape(self.__str__()) else: return self.__str__()
'This is an alias to addcontent.'
def add(self, text):
self.addcontent(text)
'Add some text to the bottom of the document'
def addfooter(self, text):
self.footer.append(text)
'Add some text to the top of the document'
def addheader(self, text):
self.header.append(text)
'Add some text to the main part of the document'
def addcontent(self, text):
self.content.append(text)
'This method is used for complete documents with appropriate doctype, encoding, title, etc information. For an HTML/XML snippet omit this method. lang -- language, usually a two character string, will appear as <html lang=\'en\'> in html mode (ignored in xml mode) css -- Cascading Style Sheet filename as a string or a list of strings for multiple css files (ignored in xml mode) metainfo -- a dictionary in the form { \'name\':\'content\' } to be inserted into meta element(s) as <meta name=\'name\' content=\'content\'> (ignored in xml mode) bodyattrs --a dictionary in the form { \'key\':\'value\', ... } which will be added as attributes of the <body> element as <body key=\'value\' ... > (ignored in xml mode) script -- dictionary containing src:type pairs, <script type=\'text/type\' src=src></script> title -- the title of the document as a string to be inserted into a title element as <title>my title</title> (ignored in xml mode) header -- some text to be inserted right after the <body> element (ignored in xml mode) footer -- some text to be inserted right before the </body> element (ignored in xml mode) charset -- a string defining the character set, will be inserted into a <meta http-equiv=\'Content-Type\' content=\'text/html; charset=myset\'> element (ignored in xml mode) encoding -- a string defining the encoding, will be put into to first line of the document as <?xml version=\'1.0\' encoding=\'myencoding\' ?> in xml mode (ignored in html mode) doctype -- the document type string, defaults to <!DOCTYPE HTML PUBLIC \'-//W3C//DTD HTML 4.01 Transitional//EN\'> in html mode (ignored in xml mode)'
def init(self, lang='en', css=None, metainfo=None, title=None, header=None, footer=None, charset=None, encoding=None, doctype=None, bodyattrs=None, script=None):
self._full = True if ((self.mode == 'strict_html') or (self.mode == 'loose_html')): if (doctype is None): doctype = "<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'>" self.header.append(doctype) self.html(lang=lang) self.head() if (charset is not None): self.meta(http_equiv='Content-Type', content=('text/html; charset=%s' % charset)) if (metainfo is not None): self.metainfo(metainfo) if (css is not None): self.css(css) if (title is not None): self.title(title) if (script is not None): self.scripts(script) self.head.close() if (bodyattrs is not None): self.body(**bodyattrs) else: self.body() if (header is not None): self.content.append(header) if (footer is not None): self.footer.append(footer) elif (self.mode == 'xml'): if (doctype is None): if (encoding is not None): doctype = ("<?xml version='1.0' encoding='%s' ?>" % encoding) else: doctype = "<?xml version='1.0' ?>" self.header.append(doctype)
'This convenience function is only useful for html. It adds css stylesheet(s) to the document via the <link> element.'
def css(self, filelist):
if isinstance(filelist, basestring): self.link(href=filelist, rel='stylesheet', type='text/css', media='all') else: for file in filelist: self.link(href=file, rel='stylesheet', type='text/css', media='all')
'This convenience function is only useful for html. It adds meta information via the <meta> element, the argument is a dictionary of the form { \'name\':\'content\' }.'
def metainfo(self, mydict):
if isinstance(mydict, dict): for (name, content) in mydict.iteritems(): self.meta(name=name, content=content) else: raise TypeError('Metainfo should be called with a dictionary argument of name:content pairs.')
'Only useful in html, mydict is dictionary of src:type pairs will be rendered as <script type=\'text/type\' src=src></script>'
def scripts(self, mydict):
if isinstance(mydict, dict): for (src, type) in mydict.iteritems(): self.script('', src=src, type=('text/%s' % type)) else: raise TypeError('Script should be given a dictionary of src:type pairs.')
'Return `DbfFieldDef` instance from the current definition.'
def getDbfField(self):
return self.cls(self.name, self.len, self.dec)
'Create a `DbfFieldDef` instance and append it to the dbf header. Arguments: dbfh: `DbfHeader` instance.'
def appendToHeader(self, dbfh):
_dbff = self.getDbfField() dbfh.addField(_dbff)
'Add field definition. Arguments: name: field name (str object). field name must not contain ASCII NULs and it\'s length shouldn\'t exceed 10 characters. typ: type of the field. this must be a single character from the "CNLMDT" set meaning character, numeric, logical, memo, date and date/time respectively. len: length of the field. this argument is used only for the character and numeric fields. all other fields have fixed length. FIXME: use None as a default for this argument? dec: decimal precision. used only for the numric fields.'
def add_field(self, name, typ, len, dec=0):
self.fields.append(self.FieldDefinitionClass(name, typ, len, dec))
'Create empty .DBF file using current structure.'
def write(self, filename):
_dbfh = DbfHeader() _dbfh.setCurrentDate() for _fldDef in self.fields: _fldDef.appendToHeader(_dbfh) _dbfStream = file(filename, 'wb') _dbfh.write(_dbfStream) _dbfStream.close()
'Initialize instance.'
def __init__(self, name, length=None, decimalCount=None, start=None, stop=None, ignoreErrors=False):
assert (self.typeCode is not None), 'Type code must be overriden' assert (self.defaultValue is not None), 'Default value must be overriden' if (len(name) > 10): raise ValueError(('Field name "%s" is too long' % name)) name = str(name).upper() if (self.__class__.length is None): if (length is None): raise ValueError(("[%s] Length isn't specified" % name)) length = int(length) if (length <= 0): raise ValueError(('[%s] Length must be a positive integer' % name)) else: length = self.length if (decimalCount is None): decimalCount = 0 self.name = name self.length = length self.decimalCount = decimalCount self.ignoreErrors = ignoreErrors self.start = start self.end = stop
'Decode dbf field definition from the string data. Arguments: string: a string, dbf definition is decoded from. length of the string must be 32 bytes. start: position in the database file. ignoreErrors: initial error processing mode for the new field (boolean)'
def fromString(cls, string, start, ignoreErrors=False):
assert (len(string) == 32) _length = ord(string[16]) return cls(utils.unzfill(string)[:11], _length, ord(string[17]), start, (start + _length), ignoreErrors=ignoreErrors)
'Return encoded field definition. Return: Return value is a string object containing encoded definition of this field.'
def toString(self):
if (sys.version_info < (2, 4)): _name = (self.name[:11] + ('\x00' * (11 - len(self.name)))) else: _name = self.name.ljust(11, '\x00') return (((((_name + self.typeCode) + (chr(0) * 4)) + chr(self.length)) + chr(self.decimalCount)) + (chr(0) * 14))
'Return field information. Return: Return value is a (name, type, length, decimals) tuple.'
def fieldInfo(self):
return (self.name, self.typeCode, self.length, self.decimalCount)
'Return a "raw" field value from the record string.'
def rawFromRecord(self, record):
return record[self.start:self.end]
'Return decoded field value from the record string.'
def decodeFromRecord(self, record):
try: return self.decodeValue(self.rawFromRecord(record)) except: if self.ignoreErrors: return utils.INVALID_VALUE else: raise
'Return decoded value from string value. This method shouldn\'t be used publicly. It\'s called from the `decodeFromRecord` method. This is an abstract method and it must be overridden in child classes.'
def decodeValue(self, value):
raise NotImplementedError
'Return str object containing encoded field value. This is an abstract method and it must be overriden in child classes.'
def encodeValue(self, value):
raise NotImplementedError
'Return string object. Return value is a ``value`` argument with stripped right spaces.'
def decodeValue(self, value):
return value.rstrip(' ')
'Return raw data string encoded from a ``value``.'
def encodeValue(self, value):
return str(value)[:self.length].ljust(self.length)
'Return a number decoded from ``value``. If decimals is zero, value will be decoded as an integer; or as a float otherwise. Return: Return value is a int (long) or float instance.'
def decodeValue(self, value):
value = value.strip(' \x00') if ('.' in value): return float(value) elif value: return int(value) else: return 0
'Return string containing encoded ``value``.'
def encodeValue(self, value):
_rv = ('%*.*f' % (self.length, self.decimalCount, value)) if (len(_rv) > self.length): _ppos = _rv.find('.') if (0 <= _ppos <= self.length): _rv = _rv[:self.length] else: raise ValueError(('[%s] Numeric overflow: %s (field width: %i)' % (self.name, _rv, self.length))) return _rv
'Return an integer number decoded from ``value``.'
def decodeValue(self, value):
return struct.unpack('<i', value)[0]
'Return string containing encoded ``value``.'
def encodeValue(self, value):
return struct.pack('<i', int(value))
'Return float number decoded from ``value``.'
def decodeValue(self, value):
return (struct.unpack('<q', value)[0] / 10000.0)
'Return string containing encoded ``value``.'
def encodeValue(self, value):
return struct.pack('<q', round((value * 10000)))
'Return True, False or -1 decoded from ``value``.'
def decodeValue(self, value):
if (value == '?'): return (-1) if (value in 'NnFf '): return False if (value in 'YyTt'): return True raise ValueError(('[%s] Invalid logical value %r' % (self.name, value)))
'Return a character from the "TF?" set. Return: Return value is "T" if ``value`` is True "?" if value is -1 or False otherwise.'
def encodeValue(self, value):
if (value is True): return 'T' if (value == (-1)): return '?' return 'F'
'Return int .dbt block number decoded from the string object.'
def decodeValue(self, value):
raise NotImplementedError
'Return raw data string encoded from a ``value``. Note: this is an internal method.'
def encodeValue(self, value):
raise NotImplementedError
'Return a ``datetime.date`` instance decoded from ``value``.'
def decodeValue(self, value):
if value.strip(): return utils.getDate(value) else: return None
'Return a string-encoded value. ``value`` argument should be a value suitable for the `utils.getDate` call. Return: Return value is a string in format "yyyymmdd".'
def encodeValue(self, value):
if value: return utils.getDate(value).strftime('%Y%m%d') else: return (' ' * self.length)
'Return a `datetime.datetime` instance.'
def decodeValue(self, value):
assert (len(value) == self.length) (_jdn, _msecs) = struct.unpack('<2I', value) if (_jdn >= 1): _rv = datetime.datetime.fromordinal((_jdn - self.JDN_GDN_DIFF)) _rv += datetime.timedelta(0, (_msecs / 1000.0)) else: _rv = None return _rv
'Return a string-encoded ``value``.'
def encodeValue(self, value):
if value: value = utils.getDateTime(value) _rv = struct.pack('<2I', (value.toordinal() + self.JDN_GDN_DIFF), ((((value.hour * 3600) + (value.minute * 60)) + value.second) * 1000)) else: _rv = ('\x00' * self.length) assert (len(_rv) == self.length) return _rv
'Initialize instance. Arguments: fields: a list of field definitions; recordLength: size of the records; headerLength: size of the header; recordCount: number of records stored in DBF; signature: version number (aka signature). using 0x03 as a default meaning "File without DBT". for more information about this field visit ``http://www.clicketyclick.dk/databases/xbase/format/dbf.html#DBF_NOTE_1_TARGET`` lastUpdate: date of the DBF\'s update. this could be a string (\'yymmdd\' or \'yyyymmdd\'), timestamp (int or float), datetime/date value, a sequence (assuming (yyyy, mm, dd, ...)) or an object having callable ``ticks`` field. ignoreErrors: error processing mode for DBF fields (boolean)'
def __init__(self, fields=None, headerLength=0, recordLength=0, recordCount=0, signature=3, lastUpdate=None, ignoreErrors=False):
self.signature = signature if (fields is None): self.fields = [] else: self.fields = list(fields) self.lastUpdate = utils.getDate(lastUpdate) self.recordLength = recordLength self.headerLength = headerLength self.recordCount = recordCount self.ignoreErrors = ignoreErrors self.changed = bool(self.fields)
'Return header instance from the string object.'
def fromString(cls, string):
return cls.fromStream(cStringIO.StringIO(str(string)))
'Return header object from the stream.'
def fromStream(cls, stream):
stream.seek(0) _data = stream.read(32) (_cnt, _hdrLen, _recLen) = struct.unpack('<I2H', _data[4:12]) _year = ord(_data[1]) if (_year < 80): _year += 2000 else: _year += 1900 _obj = cls(None, _hdrLen, _recLen, _cnt, ord(_data[0]), (_year, ord(_data[2]), ord(_data[3]))) _pos = 1 _data = stream.read(1) while (_data[0] not in ['\r', '\n']): _data += stream.read(31) _fld = fields.lookupFor(_data[11]).fromString(_data, _pos) _obj._addField(_fld) _pos = _fld.end _data = stream.read(1) return _obj
'Update `ignoreErrors` flag on self and all fields'
def ignoreErrors(self, value):
self._ignore_errors = value = bool(value) for _field in self.fields: _field.ignoreErrors = value
'Internal variant of the `addField` method. This method doesn\'t set `self.changed` field to True. Return value is a length of the appended records. Note: this method doesn\'t modify ``recordLength`` and ``headerLength`` fields. Use `addField` instead of this method if you don\'t exactly know what you\'re doing.'
def _addField(self, *defs):
_defs = [] _recordLength = 0 for _def in defs: if isinstance(_def, fields.DbfFieldDef): _obj = _def else: (_name, _type, _len, _dec) = (tuple(_def) + ((None,) * 4))[:4] _cls = fields.lookupFor(_type) _obj = _cls(_name, _len, _dec, ignoreErrors=self._ignore_errors) _recordLength += _obj.length _defs.append(_obj) self.fields += _defs return _recordLength
'Add field definition to the header. Examples: dbfh.addField( ("name", "C", 20), dbf.DbfCharacterFieldDef("surname", 20), dbf.DbfDateFieldDef("birthdate"), ("member", "L"), dbfh.addField(("price", "N", 5, 2)) dbfh.addField(dbf.DbfNumericFieldDef("origprice", 5, 2))'
def addField(self, *defs):
_oldLen = self.recordLength self.recordLength += self._addField(*defs) if (not _oldLen): self.recordLength += 1 self.headerLength = ((32 + (32 * len(self.fields))) + 1) self.changed = True
'Encode and write header to the stream.'
def write(self, stream):
stream.seek(0) stream.write(self.toString()) stream.write(''.join([_fld.toString() for _fld in self.fields])) stream.write(chr(13)) self.changed = False
'Returned 32 chars length string with encoded header.'
def toString(self):
return (struct.pack('<4BI2H', self.signature, (self.year - 1900), self.month, self.day, self.recordCount, self.headerLength, self.recordLength) + ('\x00' * 20))
'Update ``self.lastUpdate`` field with current date value.'
def setCurrentDate(self):
self.lastUpdate = datetime.date.today()
'Return a field definition by numeric index or name string'
def __getitem__(self, item):
if isinstance(item, basestring): _name = item.upper() for _field in self.fields: if (_field.name == _name): return _field else: raise KeyError(item) else: return self.fields[item]
'Initialize instance. Arguments: f: Filename or file-like object. new: True if new data table must be created. Assume data table exists if this argument is False. readOnly: if ``f`` argument is a string file will be opend in read-only mode; in other cases this argument is ignored. This argument is ignored even if ``new`` argument is True. headerObj: `header.DbfHeader` instance or None. If this argument is None, new empty header will be used with the all fields set by default. ignoreErrors: if set, failing field value conversion will return ``INVALID_VALUE`` instead of raising conversion error.'
def __init__(self, f, readOnly=False, new=False, ignoreErrors=False):
if isinstance(f, basestring): self.name = f if new: self.stream = file(f, 'w+b') else: self.stream = file(f, ('r+b', 'rb')[bool(readOnly)]) else: self.name = getattr(f, 'name', '') self.stream = f if new: self.header = self.HeaderClass() else: self.header = self.HeaderClass.fromStream(self.stream) self.ignoreErrors = ignoreErrors self._new = bool(new) self._changed = False
'Update `ignoreErrors` flag on the header object and self'
def ignoreErrors(self, value):
self.header.ignoreErrors = self._ignore_errors = bool(value)
'Return fixed index. This method fails if index isn\'t a numeric object (long or int). Or index isn\'t in a valid range (less or equal to the number of records in the db). If ``index`` is a negative number, it will be treated as a negative indexes for list objects. Return: Return value is numeric object maning valid index.'
def _fixIndex(self, index):
if (not isinstance(index, (int, long))): raise TypeError('Index must be a numeric object') if (index < 0): index += (len(self) + 1) if (index >= len(self)): raise IndexError('Record index out of range') return index
'Flush data to the associated stream.'
def flush(self):
if self.changed: self.header.setCurrentDate() self.header.write(self.stream) self.stream.flush() self._changed = False
'Index of field named ``name``.'
def indexOfFieldName(self, name):
return self.header.fields.index(name)
'Return new record, which belong to this table.'
def newRecord(self):
return self.RecordClass(self)
'Append ``record`` to the database.'
def append(self, record):
record.index = self.header.recordCount record._write() self.header.recordCount += 1 self._changed = True self._new = False
'Add field definitions. For more information see `header.DbfHeader.addField`.'
def addField(self, *defs):
if self._new: self.header.addField(*defs) else: raise TypeError("At least one record was added, structure can't be changed")
'Return number of records.'
def __len__(self):
return self.recordCount
'Return `DbfRecord` instance.'
def __getitem__(self, index):
return self.RecordClass.fromStream(self, self._fixIndex(index))
'Write `DbfRecord` instance to the stream.'
def __setitem__(self, index, record):
record.index = self._fixIndex(index) record._write() self._changed = True self._new = False
'Instance initialiation. Arguments: dbf: A `Dbf.Dbf` instance this record belonogs to. index: An integer record index or None. If this value is None, record will be appended to the DBF. deleted: Boolean flag indicating whether this record is a deleted record. data: A sequence or None. This is a data of the fields. If this argument is None, default values will be used.'
def __init__(self, dbf, index=None, deleted=False, data=None):
self.dbf = dbf self.index = index self.deleted = deleted if (data is None): self.fieldData = [_fd.defaultValue for _fd in dbf.header.fields] else: self.fieldData = list(data)
'Return raw record contents read from the stream. Arguments: dbf: A `Dbf.Dbf` instance containing the record. index: Index of the record in the records\' container. This argument can\'t be None in this call. Return value is a string containing record data in DBF format.'
def rawFromStream(cls, dbf, index):
dbf.stream.seek((dbf.header.headerLength + (index * dbf.header.recordLength))) return dbf.stream.read(dbf.header.recordLength)
'Return a record read from the stream. Arguments: dbf: A `Dbf.Dbf` instance new record should belong to. index: Index of the record in the records\' container. This argument can\'t be None in this call. Return value is an instance of the current class.'
def fromStream(cls, dbf, index):
return cls.fromString(dbf, cls.rawFromStream(dbf, index), index)
'Return record read from the string object. Arguments: dbf: A `Dbf.Dbf` instance new record should belong to. string: A string new record should be created from. index: Index of the record in the container. If this argument is None, record will be appended. Return value is an instance of the current class.'
def fromString(cls, dbf, string, index=None):
return cls(dbf, index, (string[0] == '*'), [_fd.decodeFromRecord(string) for _fd in dbf.header.fields])
'Write data to the dbf stream. Note: This isn\'t a public method, it\'s better to use \'store\' instead publically. Be design ``_write`` method should be called only from the `Dbf` instance.'
def _write(self):
self._validateIndex(False) self.dbf.stream.seek(self.position) self.dbf.stream.write(self.toString()) if (self.index == len(self.dbf)): self.dbf.stream.write('\x1a')
'Valid ``self.index`` value. If ``allowUndefined`` argument is True functions does nothing in case of ``self.index`` pointing to None object.'
def _validateIndex(self, allowUndefined=True, checkRange=False):
if (self.index is None): if (not allowUndefined): raise ValueError('Index is undefined') elif (self.index < 0): raise ValueError(("Index can't be negative (%s)" % self.index)) elif (checkRange and (self.index <= self.dbf.header.recordCount)): raise ValueError(('There are only %d records in the DBF' % self.dbf.header.recordCount))
'Store current record in the DBF. If ``self.index`` is None, this record will be appended to the records of the DBF this records belongs to; or replaced otherwise.'
def store(self):
self._validateIndex() if (self.index is None): self.index = len(self.dbf) self.dbf.append(self) else: self.dbf[self.index] = self
'Mark method as deleted.'
def delete(self):
self.deleted = True
'Return string packed record values.'
def toString(self):
return ''.join(([' *'[self.deleted]] + [_def.encodeValue(_dat) for (_def, _dat) in izip(self.dbf.header.fields, self.fieldData)]))
'Return a flat list of fields. Note: Change of the list\'s values won\'t change real values stored in this object.'
def asList(self):
return self.fieldData[:]
'Return a dictionary of fields. Note: Change of the dicts\'s values won\'t change real values stored in this object.'
def asDict(self):
return dict([_i for _i in izip(self.dbf.fieldNames, self.fieldData)])
'Return value by field name or field index.'
def __getitem__(self, key):
if isinstance(key, (long, int)): return self.fieldData[key] return self.fieldData[self.dbf.indexOfFieldName(key)]
'Set field value by integer index of the field or string name.'
def __setitem__(self, key, value):
if isinstance(key, (int, long)): return self.fieldData[key] self.fieldData[self.dbf.indexOfFieldName(key)] = value
'Init Result Event.'
def __init__(self, data):
wx.PyEvent.__init__(self) self.SetEventType(EVT_DEBUG_ID) self.data = data
'Initializes port by resetting device and gettings supported PIDs.'
def __init__(self, portnum, _notify_window, SERTIMEOUT, RECONNATTEMPTS):
baud = 9600 databits = 8 par = serial.PARITY_NONE sb = 1 to = SERTIMEOUT self.ELMver = 'Unknown' self.State = 1 self._notify_window = _notify_window wx.PostEvent(self._notify_window, DebugEvent([1, 'Opening interface (serial port)'])) try: self.port = serial.Serial(portnum, baud, parity=par, stopbits=sb, bytesize=databits, timeout=to) except serial.SerialException as e: print e self.State = 0 return None wx.PostEvent(self._notify_window, DebugEvent([1, (('Interface successfully ' + self.port.portstr) + ' opened')])) wx.PostEvent(self._notify_window, DebugEvent([1, 'Connecting to ECU...'])) try: self.send_command('atz') except serial.SerialException: self.State = 0 return None self.ELMver = self.get_result() wx.PostEvent(self._notify_window, DebugEvent([2, ('atz response:' + self.ELMver)])) self.send_command('ate0') wx.PostEvent(self._notify_window, DebugEvent([2, ('ate0 response:' + self.get_result())])) self.send_command('0100') ready = self.get_result() wx.PostEvent(self._notify_window, DebugEvent([2, ('0100 response:' + ready)])) return None
'Resets device and closes all associated filehandles'
def close(self):
if ((self.port != None) and (self.State == 1)): self.send_command('atz') self.port.close() self.port = None self.ELMver = 'Unknown'
'Internal use only: not a public interface'
def send_command(self, cmd):
if self.port: self.port.flushOutput() self.port.flushInput() for c in cmd: self.port.write(c) self.port.write('\r\n') wx.PostEvent(self._notify_window, DebugEvent([3, ('Send command:' + cmd)]))
'Internal use only: not a public interface'
def interpret_result(self, code):
if (len(code) < 7): print ('boguscode?' + code) code = string.split(code, '\r') code = code[0] code = string.split(code) code = string.join(code, '') if (code[:6] == 'NODATA'): return 'NODATA' code = code[4:] return code
'Internal use only: not a public interface'
def get_result(self):
time.sleep(0.1) if self.port: buffer = '' while 1: c = self.port.read(1) if ((c == '\r') and (len(buffer) > 0)): break elif ((buffer != '') or (c != '>')): buffer = (buffer + c) wx.PostEvent(self._notify_window, DebugEvent([3, ('Get result:' + buffer)])) return buffer else: wx.PostEvent(self._notify_window, DebugEvent([3, ('NO self.port!' + buffer)])) return None
'Internal use only: not a public interface'
def get_sensor_value(self, sensor):
cmd = sensor.cmd self.send_command(cmd) data = self.get_result() if data: data = self.interpret_result(data) if (data != 'NODATA'): data = sensor.value(data) else: return 'NORESPONSE' return data
'Returns 3-tuple of given sensors. 3-tuple consists of (Sensor Name (string), Sensor Value (string), Sensor Unit (string) )'
def sensor(self, sensor_index):
sensor = obd_sensors.SENSORS[sensor_index] r = self.get_sensor_value(sensor) return (sensor.name, r, sensor.unit)
'Internal use only: not a public interface'
def sensor_names(self):
names = [] for s in obd_sensors.SENSORS: names.append(s.name) return names
'Returns a list of all pending DTC codes. Each element consists of a 2-tuple: (DTC code (string), Code description (string) )'
def get_dtc(self):
dtcLetters = ['P', 'C', 'B', 'U'] r = self.sensor(1)[1] dtcNumber = r[0] mil = r[1] DTCCodes = [] print ((('Number of stored DTC:' + str(dtcNumber)) + ' MIL: ') + str(mil)) for i in range(0, ((dtcNumber + 2) / 3)): self.send_command(GET_DTC_COMMAND) res = self.get_result() print ('DTC result:' + res) for i in range(0, 3): val1 = hex_to_int(res[(3 + (i * 6)):(5 + (i * 6))]) val2 = hex_to_int(res[(6 + (i * 6)):(8 + (i * 6))]) val = ((val1 << 8) + val2) if (val == 0): break DTCStr = ((((dtcLetters[((val & 49152) > 14)] + str(((val & 12288) >> 12))) + str(((val & 3840) >> 8))) + str(((val & 240) >> 4))) + str((val & 15))) DTCCodes.append(['Active', DTCStr]) self.send_command(GET_FREEZE_DTC_COMMAND) res = self.get_result() if (res[:7] == 'NO DATA'): return DTCCodes print ('DTC freeze result:' + res) for i in range(0, 3): val1 = hex_to_int(res[(3 + (i * 6)):(5 + (i * 6))]) val2 = hex_to_int(res[(6 + (i * 6)):(8 + (i * 6))]) val = ((val1 << 8) + val2) if (val == 0): break DTCStr = ((((dtcLetters[((val & 49152) > 14)] + str(((val & 12288) >> 12))) + str(((val & 3840) >> 8))) + str(((val & 240) >> 4))) + str((val & 15))) DTCCodes.append(['Passive', DTCStr]) return DTCCodes
'Clears all DTCs and freeze frame data'
def clear_dtc(self):
self.send_command(CLEAR_DTC_COMMAND) r = self.get_result() return r
'Download packages, packges must be list in format of [url, path, package name]'
def download(self, packages):
for package in packages: url = package[0] filename = package[1] pkg_name = package[2] try: directory = os.path.dirname(filename) if (not os.path.exists(directory)): os.makedirs(directory) Log.info(self, 'Downloading {0:20}'.format(pkg_name), end=' ') urllib.request.urlretrieve(url, filename) Log.info(self, '{0}'.format((((('[' + Log.ENDC) + 'Done') + Log.OKBLUE) + ']'))) except urllib.error.URLError as e: Log.debug(self, '[{err}]'.format(err=str(e.reason))) Log.error(self, 'Unable to download file, {0}'.format(filename)) return False except urllib.error.HTTPError as e: Log.error(self, 'Package download failed. {0}'.format(pkg_name)) Log.debug(self, '[{err}]'.format(err=str(e.reason))) return False except urllib.error.ContentTooShortError as e: Log.debug(self, '{0}{1}'.format(e.errno, e.strerror)) Log.error(self, 'Package download failed. The amount of the downloaded data is less than the expected amount \\{0} '.format(pkg_name)) return False