本文整理汇总了Python中pyaid.string.StringUtils.StringUtils类的典型用法代码示例。如果您正苦于以下问题:Python StringUtils类的具体用法?Python StringUtils怎么用?Python StringUtils使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了StringUtils类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: set
def set(self, key, value, defaultValue =None):
if not key:
return False
if value is None or value == defaultValue:
self.remove(key)
return True
if not StringUtils.isStringType(key) and len(key) == 1:
key = key[0]
if StringUtils.isStringType(key):
addKey = self._formatKey(key)
source = self._data
else:
addKey = self._formatKey(key[-1])
source = self._data
temp = self._data
for k in key[:-1]:
temp = self._getFrom(temp, k)
if temp == self.null:
temp = dict()
source[self._formatKey(k)] = temp
source = temp
source[addKey] = value
return True
示例2: formatAsString
def formatAsString(cls, src, indentLevel =0):
indents = ' '*indentLevel
if isinstance(src, (list, tuple)):
out = [StringUtils.toUnicode('%s%s' % (indents, src[0]))]
indents += ' '
lines = []
maxIndex = 0
for item in src[1:]:
item = StringUtils.toUnicode(item)
index = item.find(':')
index = index if index != -1 and index < 12 else 0
maxIndex = max(index, maxIndex)
lines.append([index, item])
for item in lines:
if item[0] > 0:
out.append(indents + (' '*max(0, maxIndex - item[0])) + item[1])
else:
out.append(indents + item[1])
return StringUtils.toUnicode('\n'.join(out))
else:
return StringUtils.toUnicode(indents + src)
示例3: addKeysFromLists
def addKeysFromLists(self, **kwargs):
self._clearCache()
x = ArgsUtils.get('times', None, kwargs)
if not x:
return
y = ArgsUtils.get('values', None, kwargs)
if not y:
return
tans = ArgsUtils.get('tangents', None, kwargs)
inTans = ArgsUtils.get('inTangents', tans, kwargs)
outTans = ArgsUtils.get('outTangents', tans, kwargs)
if not inTans:
inTans = 'lin'
if not outTans:
outTans = 'lin'
for i in range(0,len(x)):
self._keys.append(DataChannelKey(
time=x[i],
value=y[i],
inTangent=inTans if StringUtils.isStringType(inTans) else inTans[i],
outTangent=outTans if StringUtils.isStringType(outTans) else outTans[i] ))
示例4: insertColumn
def insertColumn(self, sheetname, columnname, columnnumber):
"""Inserts a new empty column into the current doc.
@param sheetname: The name of the sheet to be added to.
@type sheetname: string
@param columnname: The name of the new column to be added
@type columnname: string
@param columnnumber: Where to insert the new column (= how many come before it?)
@type columnnumber: int
"""
sheets = self._doc.spreadsheet.getElementsByType(Table)
for sheet in sheets:
if sheet.getAttribute('name') == sheetname:
rownum = 0
rows = sheet.getElementsByType(TableRow)
for row in rows:
colNum = 0
cells = row.getElementsByType(TableCell)
for cell in cells:
if colNum == columnnumber:
newCell = TableCell()
if rownum == 0:
p = P()
p.addText(StringUtils.toUnicode(columnname))
newCell.addElement(p)
else:
p = P()
p.addText(StringUtils.toUnicode(''))
newCell.addElement(p)
row.insertBefore(newCell, cell)
colNum += 1
rownum += 1
示例5: _handleResponseReady
def _handleResponseReady(self, request, response):
"""Event handler for the response object being ready for use."""
if self._cacheControlPublic:
response.cache_control = "public"
# -------------------------------------------------------------------------------------------
# Cache Expiration: Set the caching values according to the _expires property
rep = self._explicitResponse
if rep is None or (isinstance(rep, ViewResponse) and rep.allowCaching):
response.cache_control.max_age = self.expires if not self.expires is None else 0
else:
response.cache_control.max_age = 0
# -------------------------------------------------------------------------------------------
# Cache Validators
if self._etag is not None:
response.etag = StringUtils.toUnicode(self._etag)
if self._lastModified is not None:
response.last_modified = self._lastModified
# If required encode the response headers as strings to prevent unicode errors. This is
# necessary for certain WSGI server applications, e.g. flup.
if self.ziggurat.strEncodeEnviron:
for n, v in DictUtils.iter(response.headers):
if StringUtils.isStringType(v):
response.headers[n] = StringUtils.toStr2(v)
# Clean up per-thread sessions.
ConcreteModelsMeta.cleanupSessions()
示例6: getPrefix
def getPrefix(self, *args, **kwargs):
if self._locationPrefix:
item = self.getStackData()[-1]
loc = ' -> %s #%s]' % (item['file'], StringUtils.toUnicode(item['line']))
else:
loc = ']'
if self._app and self._app.pyramidApp:
wsgi = self._app.environ
initials = self._INITIALS_RX.sub('', ArgsUtils.get('REMOTE_USER', '', wsgi))
if initials:
initials += ' | '
domainName = ArgsUtils.get('SERVER_NAME', '', wsgi)
uriPath = ArgsUtils.get(
'REQUEST_URI',
ArgsUtils.get('HTTP_REQUEST_URI', '', wsgi), wsgi)
info = ' <' + initials + domainName + uriPath + '>'
else:
info = ''
threadID = ThreadUtils.getCurrentID()
return StringUtils.toUnicode(
TimeUtils.toFormat('[%a %H:%M <%S.%f>') + '<' + threadID + '>' + info + loc)
示例7: __init__
def __init__(self, capType, addExp=None, addReplace="", removeExp=None, removeReplace=""):
"""Creates a new instance of ClassTemplate."""
self._addPattern = re.compile(addExp) if StringUtils.isStringType(addExp) else addExp
self._removePattern = re.compile(removeExp) if StringUtils.isStringType(removeExp) else removeExp
self._addReplace = addReplace
self._removeReplace = removeReplace
self._capType = capType
示例8: _createSetupFile
def _createSetupFile(self, binPath):
path = FileUtils.createPath(binPath, 'setup.py', isFile=True)
scriptPath = inspect.getabsfile(self.applicationClass)
try:
sourcePath = PyGlassEnvironment.getPyGlassResourcePath(
'..', 'setupSource.txt', isFile=True)
f = open(sourcePath, 'r+')
source = f.read()
f.close()
except Exception as err:
print(err)
return None
try:
f = open(path, 'w+')
f.write(source.replace(
'##SCRIPT_PATH##', StringUtils.escapeBackSlashes(scriptPath)
).replace(
'##RESOURCES##', StringUtils.escapeBackSlashes(JSON.asString(self.resources))
).replace(
'##INCLUDES##', StringUtils.escapeBackSlashes(JSON.asString(self.siteLibraries))
).replace(
'##ICON_PATH##', StringUtils.escapeBackSlashes(self._createIcon(binPath))
).replace(
'##APP_NAME##', self.appDisplayName
).replace(
'##SAFE_APP_NAME##', self.appDisplayName.replace(' ', '_') ))
f.close()
except Exception as err:
print(err)
return None
return path
示例9: prettyPrint
def prettyPrint(target, indentLevel =1):
indent = '\n' + (indentLevel*' ')
s = '\n'
if isinstance(target, list):
index = 0
for t in target:
try:
v = StringUtils.toUnicode(t)
except Exception:
v = '<UNPRINTABLE>'
s += '%s[%s]: %s' % (indent, index, v)
return s
if isinstance(target, dict):
for n,v in target.items():
try:
v = StringUtils.toUnicode(v)
except Exception:
v = '<UNPRINTABLE>'
s += '%s%s: %s' % (indent, n, v)
return s
items = dir(target)
for n in items:
v = getattr(target, n)
try:
v = StringUtils.toUnicode(v)
except Exception:
v = '<UNPRINTABLE>'
s += '%s%s: %s' % (indent, n, v)
return s
示例10: createErrorMessage
def createErrorMessage(cls, message, error):
try:
errorType = StringUtils.toUnicode(sys.exc_info()[0])
except Exception:
try:
errorType = str(sys.exc_info()[0])
except Exception:
errorType = '[[UNABLE TO PARSE]]'
try:
errorValue = StringUtils.toUnicode(sys.exc_info()[1])
except Exception:
try:
errorValue = str(sys.exc_info()[1])
except Exception:
errorValue = '[[UNABLE TO PARSE]]'
try:
error = StringUtils.toUnicode(error)
except Exception as err:
try:
error = str(err)
except Exception:
error = '[[UNABLE TO PARSE]]'
try:
es = '%s\n TYPE: %s\n VALUE: %s\nERROR: %s\n' % (
cls.formatAsString(message), errorType, errorValue, error)
except Exception:
try:
es = '%s\n [[ERROR ATTRIBUTE PARSING FAILURE]]' % cls.formatAsString(message)
except Exception:
es = 'FAILED TO PARSE EXCEPTION'
return es
示例11: _handleAddApp
def _handleAddApp(self):
defaultPath = self.appConfig.get('LAST_APP_PATH', OsUtils.getDocumentsPath())
path = PyGlassBasicDialogManager.browseForDirectory(
parent=self,
caption=StringUtils.dedent("""
Specify the root path to a PyGlass application, in which a resource folder
resides"""),
defaultPath=defaultPath)
if not path:
return
label = PyGlassBasicDialogManager.openTextQuery(
parent=self,
header='Enter Application Name',
message='Specify the name of this application for display within Alembic Migrator',
defaultText=os.path.basename(path.rstrip(os.sep)) )
apps = self.appConfig.get('APPLICATIONS', dict())
appData = {
'label':label,
'path':path,
'databases':dict(),
'id':TimeUtils.getUidTimecode('App', StringUtils.slugify(label))}
apps[appData['id']] = appData
self.appConfig.set('APPLICATIONS', apps)
self.refresh()
resultItem = self.appsListWidget.findItems(appData['id'], QtCore.Qt.MatchExactly)
if resultItem:
resultItem[0].setSelected(True)
示例12: cleanFilename
def cleanFilename(cls, filename):
if not filename:
return StringUtils.getRandomString(12)
out = StringUtils.slugify(filename)
if not out:
return StringUtils.getRandomString(12)
return out
示例13: _listPath
def _listPath(cls, rootPath, recursive, **kwargs):
listDirs = ArgsUtils.get('listDirs', False, kwargs)
skipSVN = ArgsUtils.get('skipSVN', True, kwargs)
skips = ArgsUtils.get('skips', None, kwargs)
allowExtensions = ArgsUtils.getAsList('allowExtensions', kwargs)
skipExtensions = ArgsUtils.getAsList('skipExtensions', kwargs)
out = []
for item in os.listdir(rootPath):
if (skipSVN and item == '.svn') or (skips and item in skips):
continue
absItem = os.path.join(rootPath, item)
if os.path.isdir(absItem):
path = (absItem + os.sep)
if listDirs:
out.append(path)
absItem = None
if recursive:
out += cls._listPath(path, recursive, **kwargs)
elif os.path.isfile(absItem):
if skipExtensions and StringUtils.ends(item, skipExtensions):
continue
if allowExtensions and not StringUtils.ends(item, allowExtensions):
continue
if absItem:
out.append(absItem)
return out
示例14: __init__
def __init__(self):
"""Creates a new instance of UniqueObject."""
self._INSTANCE_INDEX += 1
self._instanceUid = TimeUtils.getUidTimecode(
prefix=self.__class__.__name__,
suffix=StringUtils.toUnicode(
self._INSTANCE_INDEX) + '-' + StringUtils.getRandomString(8) )
示例15: asWebRgbOpacity
def asWebRgbOpacity(self, opacity =None):
c = self.asRgb(output=tuple)
return 'rgba(%s, %s, %s, %s)' % (
StringUtils.toUnicode(c[0]),
StringUtils.toUnicode(c[1]),
StringUtils.toUnicode(c[2]),
StringUtils.toUnicode(100.0*(self._opacity if opacity is None else opacity)) + '%' )