本文整理汇总了Python中pyaid.dict.DictUtils.DictUtils类的典型用法代码示例。如果您正苦于以下问题:Python DictUtils类的具体用法?Python DictUtils怎么用?Python DictUtils使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DictUtils类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _writeError
def _writeError(self, data):
""" Writes import error data to the logger, formatting it for human readable display. """
source = {}
if 'data' in data:
for n,v in DictUtils.iter(data['data']):
source[' '.join(n.split('_')).title()] = v
indexPrefix = ''
if 'index' in data:
indexPrefix = ' [INDEX: %s]:' % data.get('index', 'Unknown')
result = [
'IMPORT ERROR%s: %s' % (indexPrefix, data['message']),
'DATA: ' + DictUtils.prettyPrint(source)]
if 'existing' in data:
source = {}
snapshot = data['existing'].snapshot
if snapshot:
snapshot = JSON.fromString(snapshot)
if snapshot:
for n,v in DictUtils.iter(snapshot):
source[' '.join(n.split('_')).title()] = v
result.append('CONFLICT: ' + DictUtils.prettyPrint(source))
if 'error' in data:
self._logger.writeError(result, data['error'])
else:
self._logger.write(result)
示例2: __call__
def __call__(self):
super(ZigguratDataView, self).__call__()
if isinstance(self._response, Response) or StringUtils.isStringType(self._response):
return self._response
DictUtils.cleanBytesToText(self._response, inPlace=True)
return render_to_response('json', self._response, self._request)
示例3: test_closestPointOnLine
def test_closestPointOnLine(self):
""" doc... """
count = 5000
bound = 10000.0
for i in range(count):
start = PositionValue2D(
x=random.uniform(-bound, bound),
y=random.uniform(-bound, bound),
xUnc=0.1,
yUnc=0.1)
end = PositionValue2D(
x=random.uniform(-bound, bound) + start.x,
y=random.uniform(-bound, bound) + start.y,
xUnc=0.1,
yUnc=0.1)
line = LineSegment2D(start, end)
if not line.isValid:
continue
target = line.getParametricPosition(random.uniform(0.0, 1.0))
offset = random.uniform(1.0, bound)
point = line.adjustPointAlongLine(target, offset, inPlace=False)
debug = {
'POINT':point, 'TARGET':target,
'OFFSET':offset, 'DISTANCE':point.distanceTo(target) }
self.assertAlmostEqual(
offset, point.distanceTo(target).raw,
msg='Invalid offset distance:\n'
+ DictUtils.prettyPrint(debug, delimiter='\n'))
point.rotate(Angle(degrees=90.0*random.choice([1.0, -1.0])), target)
self.assertAlmostEqual(
offset, point.distanceTo(target).raw,
msg='Invalid rotated offset distance:\n'
+ DictUtils.prettyPrint(debug, delimiter='\n'))
pointOnLine = line.closestPointOnLine(point)
xUnc = math.sqrt(pointOnLine.xUnc*pointOnLine.xUnc + target.xUnc*target.xUnc)
yUnc = math.sqrt(pointOnLine.yUnc*pointOnLine.yUnc + target.yUnc*target.yUnc)
debug = {
'POINT':point, 'RESULT':pointOnLine,
'INDEX':i, 'TARGET':target,
'START':start, 'END':end,
'X_UNC':xUnc, 'Y_UNC':yUnc }
self.assertAlmostEqual(
pointOnLine.x, target.x, delta=2.0*xUnc,
msg='BAD RESULT [X]:\n' + DictUtils.prettyPrint(debug, delimiter='\n'))
self.assertAlmostEqual(
pointOnLine.y, target.y, delta=2.0*yUnc,
msg='BAD RESULT [Y]:\n' + DictUtils.prettyPrint(debug, delimiter='\n'))
示例4: _postAnalyze
def _postAnalyze(self):
self.logger.write('TRACKWAY COUNT: %s' % self._weightedStats.count)
self._weightedStats.save()
self._unweightedStats.save()
for key, csv in DictUtils.iter(self._quartileStats):
csv.save()
for label, paths in DictUtils.iter(self._densityPlots):
self.mergePdfs(paths, '%s-Densities.pdf' % label.replace(' ', '-'))
示例5: _postAnalyze
def _postAnalyze(self):
"""_postAnalyze doc..."""
ratios = []
for name, curve in DictUtils.iter(self.data):
segments = curve.segments
for i in ListUtils.rangeOn(segments):
segment = segments[i]
segmentLine = segment.line
# If this is an extrapolated segment, use the length from the neighboring segment
# instead of the artificial length of this segment.
if segment == segments[0]:
segmentLine = segments[i + 1].line
elif segment == segments[-1]:
segmentLine = segments[i - 1].line
for pairData in segment.pairs:
projectionLine = pairData["line"]
ratios.append(100.0 * projectionLine.length.raw / segmentLine.length.raw)
h = Histogram(
data=ratios,
binCount=50,
xLabel="Projection/Stride Ratio (%)",
title="Relative Stride to Projection Length Ratios",
)
h.shaveDataToXLimits()
self._paths.append(h.save(path=self.getTempFilePath(extension="pdf")))
self.mergePdfs(self._paths, "Curve-Projection.pdf")
示例6: echo
def echo(self):
print('TARGET:',self.target)
print('GAIT PHASE OFFSET:',self._phaseOffset)
print('DUTY FACTOR:',self._dutyFactor)
print('CHANNELS:')
for n,v in DictUtils.iter(self._channels):
print(v.toString())
示例7: save
def save(self, path =None):
""" Saves the CSV file data to the specified path """
if path is None:
path = self.path
if self.removeIfSavedEmpty and not self.rows:
self.remove()
return
index = 0
names = self.fieldNames
if self.autoIndexFieldName:
names.insert(0, self.autoIndexFieldName)
try:
with open(path, 'wb') as f:
writer = csv.DictWriter(f, fieldnames=names, dialect=csv.excel)
writer.writeheader()
for row in self.rows:
result = dict()
if self.autoIndexFieldName:
index += 1
result[self.autoIndexFieldName] = index
for key, spec in DictUtils.iter(self._fields):
value = row.get(key, spec.get('empty', ''))
name = spec.get('name', key)
if StringUtils.isTextType(value):
value = value.encode('latin-1')
result[name] = value
writer.writerow(result)
return True
except Exception:
return False
示例8: __init__
def __init__(self, **kwargs):
"""Creates a new instance of ConfigReader."""
self._configs = ArgsUtils.get('configs', dict(), kwargs)
self._filenames = ArgsUtils.get('filenames', None, kwargs)
self._configPath = ArgsUtils.get(
'rootConfigPath',
CadenceEnvironment.getConfigPath(),
kwargs
)
if self._filenames:
for n,v in DictUtils.iter(self._filenames):
if not v:
continue
path = os.path.join(self._configPath, v)
if not path.endswith('.cfg'):
path += '.cfg'
parser = ConfigParser.ConfigParser()
if os.path.exists(path):
parser.read(path)
else:
raise Exception(path + ' config file does not exist!')
self._configs[n] = self._configParserToDict(parser)
self._overrides = dict()
self.setOverrides(ArgsUtils.get('overrides', None, kwargs))
示例9: echoModel
def echoModel(self):
""" An example using a Ziggurat database model. Here a new entry of the ZigguratTest_Test
model is created and added to the database and its index in differing radices is
returned in the response.
NOTE: The model class is imported in-line in this example simply to allow use of the
Hello Ziggurat examples without model support for those not in an environment
without the required database support. """
try:
from ziggHello.models.zigguratTest.ZigguratTest_Test import ZigguratTest_Test
model = ZigguratTest_Test.MASTER
out = dict()
for name, value in DictUtils.iter(self._router.ziggurat.environ):
if name.upper() == name:
out[name] = StringUtils.toUnicode(value)
entry = model()
entry.infoData = out
model.session.add(entry)
model.session.flush()
except Exception as err:
self._router.response['error'] = str(err)
self._router.logger.writeError(u'MODEL ERROR', err)
return
self._router.response['index'] = [entry.i, entry.i16, entry.i36, entry.i64]
示例10: _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()
示例11: getColorNameAndValue
def getColorNameAndValue(self):
""" Finds the nearest named color by comparing all named colors """
if self._rawColor == 0:
return {
'name':'Black',
'value':0,
'key':'black',
'residual':0.0 }
maxRange = 560.0
nearestValue = None
nearestName = None
range = 360
myColor = self.asHsl(output=list)
poolColor = self.__class__(0)
for name, value in DictUtils.iter(ColorNames.NAMES):
poolColor.load(value)
color = poolColor.asHsl(output=list)
test = (myColor[0] - color[0])*(myColor[0] - color[0]) \
+ (myColor[1] - color[1])*(myColor[1] - color[1]) \
+ (myColor[2] - color[2])*(myColor[2] - color[2])
if test < range:
nearestValue = value
nearestName = name
range = test
if range < 1:
break
return {
'name':StringUtils.capitalizeWords(nearestName.replace('_', ' ')),
'value':nearestValue,
'key':nearestName,
'residual':100.0*range/maxRange }
示例12: currentChildWidgetID
def currentChildWidgetID(self):
if not self._currentWidget:
return None
for key, widget in DictUtils.iter(self._widgets):
if widget == self._currentWidget:
return key
return None
示例13: getChannel
def getChannel(self, kind):
"""Doc..."""
for n,v in DictUtils.iter(self._channels):
if n == kind:
return v
return None
示例14: compileAllOnPath
def compileAllOnPath(path, rootPath=None, recursive=False, debug=False, trace=False, force=False, compress=False):
CoffeescriptBuilder._results = ""
CoffeescriptBuilder._missing = {}
if recursive:
print("RECURSIVE COMPILE AT: " + path)
def walker(paths, dirName, names):
out = CoffeescriptBuilder._compileAllInDirectory(
os.path.join(paths[0], dirName), paths[1], debug=debug, trace=trace, force=force, compress=compress
)
CoffeescriptBuilder._results += out["res"]
for n, v in DictUtils.iter(out["missing"]):
if n in CoffeescriptBuilder._missing:
continue
CoffeescriptBuilder._missing[n] = v
FileUtils.walkPath(path, walker, [path, rootPath])
print("\n\nCOMPILATION RESULTS:" + CoffeescriptBuilder._results)
if CoffeescriptBuilder._missing:
print("\n\nMISSING IMPORTS:" + "\n\n")
for n, v in DictUtils.iter(CoffeescriptBuilder._missing):
print(v["class"] + " [LINE: #" + str(v["line"]) + " | " + v["package"] + "]")
else:
print("COMPILING DIRECTORY: " + path)
CoffeescriptBuilder._compileAllInDirectory(
path, rootPath, debug=debug, trace=trace, force=force, compress=compress
)
示例15: addChannels
def addChannels(self, channels):
if isinstance(channels, list):
for v in channels:
self.addChannel(v)
elif isinstance(channels, dict):
for n, v in DictUtils.iter(channels):
self.addChannel(v)