def getValueStrings( val, blnUgly=True ):
#Used by joinWithComma function to join list items for SQL queries.
#Expects to receive 'valid' types, as this was designed specifically for joining object attributes and nonvalid attributes were pulled.
#If the default blnUgly is set to false, then the nonvalid types are ignored and the output will be pretty, but the SQL Insert statement will
#probably be wrong.
tplStrings = (types.StringType, types.StringTypes )
tplNums = ( types.FloatType, types.IntType, types.LongType, types.BooleanType )
if isinstance( val, tplNums ):
return '#num#'+ str( val ) + '#num#'
elif isinstance( val, tplStrings ):
strDblQuote = '"'
return strDblQuote + val + strDblQuote
else:
if blnUgly == True:
return "Error: nonconvertable value passed - value type: %s" % type(val )
else:
return None
python类FloatType()的实例源码
def assertEquals( exp, got ):
"""assertEquals(exp, got)
Two objects test as "equal" if:
* they are the same object as tested by the 'is' operator.
* either object is a float or complex number and the absolute
value of the difference between the two is less than 1e-8.
* applying the equals operator ('==') returns True.
"""
from types import FloatType, ComplexType
if exp is got:
r = True
elif ( type( exp ) in ( FloatType, ComplexType ) or
type( got ) in ( FloatType, ComplexType ) ):
r = abs( exp - got ) < 1e-8
else:
r = ( exp == got )
if not r:
print >>sys.stderr, "Error: expected <%s> but got <%s>" % ( repr( exp ), repr( got ) )
traceback.print_stack()
def assertEquals( exp, got, msg = None ):
"""assertEquals( exp, got[, message] )
Two objects test as "equal" if:
* they are the same object as tested by the 'is' operator.
* either object is a float or complex number and the absolute
value of the difference between the two is less than 1e-8.
* applying the equals operator ('==') returns True.
"""
if exp is got:
r = True
elif ( type( exp ) in ( FloatType, ComplexType ) or
type( got ) in ( FloatType, ComplexType ) ):
r = abs( exp - got ) < 1e-8
else:
r = ( exp == got )
if not r:
print >>sys.stderr, "Error: expected <%s> but got <%s>%s" % ( repr( exp ), repr( got ), colon( msg ) )
traceback.print_stack()
def __imul__(self, other):
"""Producto punto con otro"""
if isinstance(other, Vector3):
self.x *= other.get_x()
self.y *= other.get_y()
self.z *= other.get_z()
return self
else:
if isinstance(other, types.ListType) or isinstance(other, types.TupleType):
self.x *= other[0]
self.y *= other[1]
self.z *= other[2]
return self
elif isinstance(other, types.IntType) or isinstance(other, types.FloatType):
self.x *= other
self.y *= other
self.z *= other
return self
else:
self.throwError(2, "__imul__")
return self
def __idiv__(self, other):
"""Division con otro vector por valor"""
if isinstance(other, Vector3):
self.x /= other.get_x()
self.y /= other.get_y()
self.z /= other.get_z()
return self
else:
if isinstance(other, types.ListType) or isinstance(other, types.TupleType):
self.x /= other[0]
self.y /= other[1]
self.z /= other[2]
return self
elif isinstance(other, types.IntType) or isinstance(other, types.FloatType):
self.x /= other
self.y /= other
self.z /= other
return self
else:
self.throwError(2, "__idiv__")
return self
def __imul__(self, other):
"""Producto punto con otro"""
if isinstance(other, Vector3):
self.x *= other.get_x()
self.y *= other.get_y()
self.z *= other.get_z()
return self
else:
if isinstance(other, types.ListType) or isinstance(other, types.TupleType):
self.x *= other[0]
self.y *= other[1]
self.z *= other[2]
return self
elif isinstance(other, types.IntType) or isinstance(other, types.FloatType):
self.x *= other
self.y *= other
self.z *= other
return self
else:
self.throwError(2, "__imul__")
return self
def __idiv__(self, other):
"""Division con otro vector por valor"""
if isinstance(other, Vector3):
self.x /= other.get_x()
self.y /= other.get_y()
self.z /= other.get_z()
return self
else:
if isinstance(other, types.ListType) or isinstance(other, types.TupleType):
self.x /= other[0]
self.y /= other[1]
self.z /= other[2]
return self
elif isinstance(other, types.IntType) or isinstance(other, types.FloatType):
self.x /= other
self.y /= other
self.z /= other
return self
else:
self.throwError(2, "__idiv__")
return self
def isOlderThan(self, arg):
if not self.timestamp:
return True
if isinstance(arg, types.IntType) or isinstance(arg, types.LongType) or isinstance(arg, types.FloatType):
return self.timestamp < arg
if isinstance(arg, TimeStampFile):
if arg.timestamp is None:
return False
else:
return arg.timestamp > self.timestamp
elif isinstance(arg, types.ListType):
files = arg
else:
files = [arg]
for f in files:
if os.path.getmtime(f) > self.timestamp:
return True
return False
def isNewerThan(self, arg):
if not self.timestamp:
return False
if isinstance(arg, types.IntType) or isinstance(arg, types.LongType) or isinstance(arg, types.FloatType):
return self.timestamp > arg
if isinstance(arg, TimeStampFile):
if arg.timestamp is None:
return False
else:
return arg.timestamp < self.timestamp
elif isinstance(arg, types.ListType):
files = arg
else:
files = [arg]
for f in files:
if os.path.getmtime(f) < self.timestamp:
return True
return False
def _parsePaneOptions(self, name, args):
# Parse <args> for options.
for arg, value in args.items():
if type(value) == types.FloatType:
relvalue = value
value = self._absSize(relvalue)
else:
relvalue = None
if arg == 'size':
self._size[name], self._relsize[name] = value, relvalue
elif arg == 'min':
self._min[name], self._relmin[name] = value, relvalue
elif arg == 'max':
self._max[name], self._relmax[name] = value, relvalue
else:
raise ValueError, 'keyword must be "size", "min", or "max"'
def __init__(self, user, passwd, host=constants.CDefMySQLDBHost, port=constants.CDefMySQLDBPort,
db=constants.CDefMySQLDBName, identify=None, resetDB=False, resetIdentify=True,
frequency=constants.CDefMySQLStatsGenFreq, commit_freq=constants.CDefMySQLStatsCommitFreq):
""" The creator of the DBSQLite Class """
super(DBMySQLAdapter, self).__init__(frequency, identify)
self.mysqldbmod = None
self.connection = None
self.resetDB = resetDB
self.resetIdentify = resetIdentify
self.db = db
self.host = host
self.port = port
self.user = user
self.passwd = passwd
self.typeDict = {types.FloatType: "DOUBLE(14,6)"}
self.cursorPool = None
self.commitFreq = commit_freq
def __init__(self, user, passwd, host=constants.CDefMySQLDBHost, port=constants.CDefMySQLDBPort,
db=constants.CDefMySQLDBName, identify=None, resetDB=False, resetIdentify=True,
frequency=constants.CDefMySQLStatsGenFreq, commit_freq=constants.CDefMySQLStatsCommitFreq):
""" The creator of the DBSQLite Class """
super(DBMySQLAdapter, self).__init__(frequency, identify)
self.mysqldbmod = None
self.connection = None
self.resetDB = resetDB
self.resetIdentify = resetIdentify
self.db = db
self.host = host
self.port = port
self.user = user
self.passwd = passwd
self.typeDict = {types.FloatType: "DOUBLE(14,6)"}
self.cursorPool = None
self.commitFreq = commit_freq
def __pow__(self, other):
"""Raise each element of sparse vector to a power.
If power is another sparse vector, compute elementwise power.
In this latter case, by convention, 0^0 = 0.
"""
if not isSparseVector(self):
raise TypeError("Argument must be a SparseVector")
if isSparseVector(other):
rv = SparseVector(max(self.n, other.n), {})
for k in self.values.keys():
rv[k] = self[k]**other[k]
return rv
if not isinstance(other, types.IntType) and \
not isinstance(other, types.LongType) and \
not isinstance(other, types.FloatType):
raise TypeError("Power must be numeric or a sparse vector")
rv = SparseVector(self.n, {})
for k in self.values.keys():
rv[k] = math.pow(self[k], other)
return rv
def _escape_json(json):
"""Escapes all string fields of JSON data.
Operates recursively."""
t = type(json)
if t == types.StringType or t == types.UnicodeType:
return cgi.escape(json)
elif t == types.IntType:
return json
elif t == types.FloatType:
return json
elif t == types.DictType:
result = {}
for f in json.keys():
result[f] = _escape_json(json[f])
return result
elif t == types.ListType:
result = []
for f in json:
result.append(_escape_json(f))
return result
else:
raise RuntimeError, "Unsupported type: %s" % str(t)
def convert(cf):
rc = []
for i in cf.keys():
if cf[i]['type'] == types.StringType:
rc.append([i, cf[i]['val'], None])
elif cf[i]['type'] == types.FloatType:
rc.append([i, `cf[i]['val']`, None])
elif cf[i]['type'] == types.IntType:
rc.append([i, `cf[i]['val']`, None])
elif cf[i]['type'] == 'toggle':
rc.append([i, write_yes(cf[i]['val']), 'toggle'])
elif cf[i]['type'] == types.ListType:
rc.append([i, `cf[i]['val']`, None])
else:
error("don't know how to handle " + `cf[i]['type']`)
return rc
def find_sqltype(val):
"""
Find sqlite data type which matches the type of `val`.
Parameters
----------
val : any python type
Returns
-------
sqltype : str
String with sql type which can be used to set up a sqlile table
"""
mapping = {\
types.NoneType: 'NULL',
types.IntType: 'INTEGER',
types.LongType: 'INTEGER',
types.FloatType: 'REAL', # 'FLOAT' also works
types.StringTypes: 'TEXT', # StringType + UnicodeType
types.BufferType: 'BLOB'}
for typ in mapping.keys():
if isinstance(val, typ):
return mapping[typ]
raise StandardError("type '%s' unknown, cannot find mapping "
"to sqlite3 type" %str(type(val)))
def is_scalar_element(self, x):
"""Is x a scalar
By default a scalar is an element in the complex number field.
A class that wants to perform linear algebra on things other than
numbers may override this function.
"""
return isinstance(x, types.IntType) or \
isinstance(x, types.FloatType) or \
isinstance(x, types.ComplexType)
def makeObjInsertStrings( obj, tplObjects = None, blnUseParens=True, blnGetAllAttrib=True ):
# Returns a 3 val tuple, the first two of which are strings which can be dropped into a MySQL Insert statement for (1) column names and (2) values
if not tplObjects:
return None, None, None
if isinstance( obj, tplObjects ): #find out what got passed - valid objects must be included in tuple tplObjects
strDblQuote = '"'
lstCols = list()
lstVals = list()
lstExcludedAttrib = list()
dctObj = vars( obj )
lstObjVarNames = dctObj.keys()
if blnGetAllAttrib:
tplValidTypes = ( types.BooleanType, types.FloatType, types.IntType, types.LongType, types.StringType, types.StringTypes, types.NoneType )
for varName in lstObjVarNames:
val = dctObj[ varName ]
if isinstance( val, tplValidTypes ):
lstCols.append( varName )
if val or val == 0:
lstVals.append( dctObj[ varName ] )
else:
lstVals.append('')
else:
lstExcludedAttrib.append( varName )
if blnUseParens:
strCols = joinListItems( lstCols )
strVals = joinListItems( lstVals )
else:
strCols = joinListItems( lstCols, blnUseParens=False )
strCols = joinListItems( lstVals, blnUseParens=False )
strCols = strCols.replace('"', '')
return strCols, strVals, lstExcludedAttrib
else:
print 'No object passed.'
return None, None, None
def to_sec(v):
"""
Convert millisecond, microsecond or nanosecond to second.
ms_to_ts, us_to_ts, ns_to_ts are then deprecated.
"""
v = float(str(v))
if (type(v) != types.FloatType
or v < 0):
raise ValueError('invalid time to convert to second: {v}'.format(v=v))
l = len(str(int(v)))
if l == 10:
return int(v)
elif l == 13:
return int(v / 1000)
elif l == 16:
return int(v / (1000**2))
elif l == 19:
return int(v / (1000**3))
else:
raise ValueError(
'invalid time length, not 10, 13, 16 or 19: {v}'.format(v=v))
def ponderate(self, a=1):
"""Pondera el vector por un numero"""
if isinstance(a, types.FloatType) or isinstance(a, types.IntType):
self.x *= a
self.y *= a
self.z *= a
else:
self.throwError(2, "ponderate")
return self
def __mul__(self, other):
"""Producto punto o producto por valor"""
if isinstance(other, Vector3):
return Vector3(self.x * other.get_x(), self.y * other.get_y(), self.z * other.get_z())
else:
if isinstance(other, types.ListType) or isinstance(other, types.TupleType):
return Vector3(self.x * other[0], self.y * other[1], self.z * other[2])
elif isinstance(other, types.IntType) or isinstance(other, types.FloatType):
return Vector3(self.x * other, self.y * other, self.z * other)
else:
self.throwError(2, "__mul__")
return self
def __div__(self, other):
"""Dividir por un ector o por un valor"""
if isinstance(other, Vector3):
return Vector3(self.x / other.get_x(), self.y / other.get_y(), self.z / other.get_z())
else:
if isinstance(other, types.IntType) or isinstance(other, types.FloatType):
return Vector3(self.x / other, self.y / other, self.z / other)
else:
self.throwError(2, "__div__")
return self
def __mul__(self, other):
"""Producto punto o producto por valor"""
if isinstance(other, Vector3):
return Vector3(self.x * other.get_x(), self.y * other.get_y(), self.z * other.get_z())
else:
if isinstance(other, types.ListType) or isinstance(other, types.TupleType):
return Vector3(self.x * other[0], self.y * other[1], self.z * other[2])
elif isinstance(other, types.IntType) or isinstance(other, types.FloatType):
return Vector3(self.x * other, self.y * other, self.z * other)
else:
self.throwError(2, "__mul__")
return self
def __div__(self, other):
"""Dividir por un ector o por un valor"""
if isinstance(other, Vector3):
return Vector3(self.x / other.get_x(), self.y / other.get_y(), self.z / other.get_z())
else:
if isinstance(other, types.IntType) or isinstance(other, types.FloatType):
return Vector3(self.x / other, self.y / other, self.z / other)
else:
self.throwError(2, "__div__")
return self
def show_font_details(font):
print('{0:-^80}:'.format(' Font Details: '))
for name in dir(font):
if name.startswith('_'):
continue
value = getattr(font, name)
if name == 'sfnt_names':
for locale, _name, _value in value:
print('{0:>32}: {1} = {2}'.format(locale, _name, _value))
if type(value) in (types.IntType, types.FloatType,) + types.StringTypes:
print('{0:>32}: {1}'.format(name, value))
def AddRow( self, *cells ) :
height = None
if isinstance( cells[ 0 ], (IntType, FloatType, LongType) ):
height = int( cells[ 0 ] )
cells = cells[ 1 : ]
# make sure all of the spans add up to the number of columns
# otherwise the table will get corrupted
if self.ColumnCount != sum( [ cell.Span for cell in cells ] ) :
raise Exception( 'ColumnCount != the total of this row\'s cell.Spans.' )
self.Rows.append( ( height, cells ) )
def AddRow( self, *cells ) :
height = None
if isinstance( cells[ 0 ], (IntType, FloatType, LongType) ):
height = int( cells[ 0 ] )
cells = cells[ 1 : ]
# make sure all of the spans add up to the number of columns
# otherwise the table will get corrupted
if self.ColumnCount != sum( [ cell.Span for cell in cells ] ) :
raise Exception( 'ColumnCount != the total of this row\'s cell.Spans.' )
self.Rows.append( ( height, cells ) )
def AddRow( self, *cells ) :
height = None
if isinstance( cells[ 0 ], (IntType, FloatType, LongType) ):
height = int( cells[ 0 ] )
cells = cells[ 1 : ]
# make sure all of the spans add up to the number of columns
# otherwise the table will get corrupted
if self.ColumnCount != sum( [ cell.Span for cell in cells ] ) :
raise Exception( 'ColumnCount != the total of this row\'s cell.Spans.' )
self.Rows.append( ( height, cells ) )
def mysql_escape(f):
@wraps(f)
def decorated_function(*args, **kwargs):
newargs = []
#???????????
for arg in args:
#????????
if type(arg) is types.StringType or type(arg) is types.UnicodeType:
newargs.append(MySQLdb.escape_string(arg))
#??
elif isinstance(arg, dict):
newargs.append(MySQLdb.escape_dict(arg, {
types.StringType: _str_escape,
types.UnicodeType: _str_escape,
types.IntType: _no_escape,
types.FloatType: _no_escape
}))
#???????
else:
newargs.append(arg)
newargs = tuple(newargs)
func = f(*newargs, **kwargs)
return func
return decorated_function
def AddRow( self, *cells ) :
height = None
if isinstance( cells[ 0 ], (IntType, FloatType, LongType) ):
height = int( cells[ 0 ] )
cells = cells[ 1 : ]
# make sure all of the spans add up to the number of columns
# otherwise the table will get corrupted
if self.ColumnCount != sum( [ cell.Span for cell in cells ] ) :
raise Exception( 'ColumnCount != the total of this row\'s cell.Spans.' )
self.Rows.append( ( height, cells ) )