本文整理汇总了Python中pyaid.string.StringUtils.StringUtils类的典型用法代码示例。如果您正苦于以下问题:Python StringUtils类的具体用法?Python StringUtils怎么用?Python StringUtils使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了StringUtils类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:sernst,项目名称:PyAid,代码行数:27,代码来源:ConfigsDict.py
示例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)
开发者ID:sernst,项目名称:PyAid,代码行数:25,代码来源:Logger.py
示例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] ))
开发者ID:sernst,项目名称:Cadence,代码行数:27,代码来源:DataChannel.py
示例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
开发者ID:sernst,项目名称:PyAid,代码行数:31,代码来源:ODSSpreadsheet.py
示例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()
开发者ID:sernst,项目名称:Ziggurat,代码行数:31,代码来源:ZigguratBaseView.py
示例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)
开发者ID:sernst,项目名称:Ziggurat,代码行数:25,代码来源:ServerLogger.py
示例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
开发者ID:sernst,项目名称:PyAid,代码行数:7,代码来源:InsertCapPolicy.py
示例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
开发者ID:sernst,项目名称:PyGlass,代码行数:34,代码来源:PyGlassApplicationCompiler.py
示例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
开发者ID:sernst,项目名称:PyAid,代码行数:31,代码来源:Logger.py
示例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
开发者ID:sernst,项目名称:PyAid,代码行数:35,代码来源:Logger.py
示例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)
开发者ID:sernst,项目名称:PyGlassAlembic,代码行数:31,代码来源:AlembicMainWidget.py
示例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
开发者ID:sernst,项目名称:PyAid,代码行数:7,代码来源:FileUtils.py
示例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
开发者ID:hannahp,项目名称:PyAid,代码行数:32,代码来源:FileUtils.py
示例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) )
开发者ID:sernst,项目名称:PyAid,代码行数:7,代码来源:UniqueObject.py
示例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)) + '%' )
开发者ID:sernst,项目名称:PyAid,代码行数:7,代码来源:ColorValue.py
示例16: autoDescription
def autoDescription(self):
if self._autoDescription:
return self._autoDescription
if not self._result:
return u''
source = self._result
p = re.compile('<script.*(?!</script>)', re.DOTALL)
source = p.sub(u'', source)
p = re.compile('<pre.*(?!</pre>)', re.DOTALL)
source = p.sub(u'', source)
p = re.compile('<[/A-Za-z]+[^>]+>')
source = p.sub(u'\n', source)
res = re.compile('[A-Za-z0-9.,?!\'" -:;\(\)&%$#@]{64,}').search(source)
if not res or not res.group():
return u''
r = res.group()
r = r[:2000].replace(u'\n',u' ')
r = MarkupProcessor._WHITESPACE_KILLER_REGEX.sub(u' ', r)
return StringUtils.htmlEscape(StringUtils.getCompleteFragment(r, 255, True))
开发者ID:sernst,项目名称:StaticFlow,代码行数:26,代码来源:MarkupProcessor.py
示例17: createUploadPolicy
def createUploadPolicy(self, key, durationSeconds, maxSizeBytes):
"""Returns a S3 upload policy and signature for this bucket with the specified key. """
return self._conn.build_post_form_args(
bucket_name=StringUtils.toUnicode(self.bucketName),
key=StringUtils.toUnicode(key),
expires_in=durationSeconds,
acl=StringUtils.toUnicode('private'),
max_content_length=maxSizeBytes)
开发者ID:sernst,项目名称:PyAid,代码行数:8,代码来源:S3Bucket.py
示例18: __str__
def __str__(self):
modelInfo = self._getReprString()
return '<%s[%s] cts[%s] upts[%s]%s>' % (
self.__class__.__name__,
StringUtils.toUnicode(self.i),
StringUtils.toUnicode(self.cts.strftime('%m-%d-%y %H:%M:%S') if self.cts else 'None'),
StringUtils.toUnicode(self.upts.strftime('%m-%d-%y %H:%M:%S') if self.upts else 'None'),
(' %s' % modelInfo) if modelInfo else '')
开发者ID:sernst,项目名称:Ziggurat,代码行数:8,代码来源:ZigguratModelsBase.py
示例19: getPrefix
def getPrefix(self, *args, **kwargs):
if self._locationPrefix:
item = self.getStackData()[-1]
loc = ' -> %s #%s]' % (item['file'], StringUtils.toUnicode(item['line']))
else:
loc = ']'
return StringUtils.toUnicode(
self.getTime(self.timezone).strftime('[%a %H:%M <%S.%f>') + loc)
开发者ID:sernst,项目名称:PyAid,代码行数:9,代码来源:Logger.py
示例20: _compileUiFile
def _compileUiFile(self, path, filename):
"""Doc..."""
source = FileUtils.createPath(path, filename, isFile=True)
if self._verbose:
self._log.write('COMPILING: ' + source)
if PyGlassEnvironment.isWindows:
uicCommand = FileUtils.createPath(self._pythonPath, 'Scripts', 'pyside-uic.exe')
else:
uicCommand = 'pyside-uic'
cmd = '%s %s' % (uicCommand, source)
pipe = subprocess.Popen(
cmd,
shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, error = pipe.communicate()
if pipe.returncode or error:
self._log.write('ERROR: Failed to compile %s widget: %s' % (str(source), str(error)))
return False
out = StringUtils.toUnicode(out)
res = WidgetUiCompiler._CLASS_NAME_RE.search(out)
if not res:
self._log.write('ERROR: Failed to find widget class name for ' + str(source))
return False
out = WidgetUiCompiler._CLASS_NAME_RE.sub('PySideUiFileSetup', out, 1)
res = WidgetUiCompiler._SETUP_UI_RE.search(out)
if not res:
self._log.write('ERROR: Failed to find widget setupUi method for ' + str(source))
return False
targetName = res.groupdict().get('parentName')
out = WidgetUiCompiler._SETUP_UI_RE.sub('\g<parentName>', out, 1)
res = WidgetUiCompiler._RETRANSLATE_RE.search(out)
if not res:
self._log.write('ERROR: Failed to find widget retranslateUi method for ' + str(source))
return False
out = WidgetUiCompiler._RETRANSLATE_RE.sub('\g<parentName>', out, 1)
out = StringUtils.toUnicode(out)
out = WidgetUiCompiler._SELF_RE.sub(targetName + '.', out)
dest = FileUtils.createPath(path, filename[:-3] + '.py', isFile=True)
if os.path.exists(dest):
os.remove(dest)
f = open(dest, 'w+')
f.write(out)
f.close()
py_compile.compile(dest)
return True
开发者ID:sernst,项目名称:PyGlass,代码行数:57,代码来源:WidgetUiCompiler.py
注:本文中的pyaid.string.StringUtils.StringUtils类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论