本文整理汇总了Python中configuration.Configuration类的典型用法代码示例。如果您正苦于以下问题:Python Configuration类的具体用法?Python Configuration怎么用?Python Configuration使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Configuration类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
def run(par):
scenario, cfg_dict, sc_dict = par
cfg = Configuration(log_to_file=True, **cfg_dict)
sc = import_object('scenarios', scenario)(cfg.rnd, cfg.seed, **sc_dict)
cfg.scenario = sc
cli.run(cfg)
示例2: read_trj
def read_trj(trj_file):
"""
return: Simulation
parameters:
trj_file: string | name of trj file
"""
simulation = Simulation()
with open(trj_file, 'r') as trj:
while True:
line = trj.readline()
if not line:
break
lattice = Lattice()
lattice.set_a(np.array(line.split(), dtype=float))
lattice.set_b(np.array(trj.readline().split(), dtype=float))
lattice.set_c(np.array(trj.readline().split(), dtype=float))
configuration = Configuration(lattice=lattice)
atom_types = trj.readline().split()
atom_counts = np.array(trj.readline().split(), dtype=int)
natom = np.sum(atom_counts)
for i in xrange(natom):
atom_record = trj.readline().split()
atom_name = atom_record[0]
atom_position = np.array(atom_record[1:], dtype=float)
configuration.insert_atom(Atom(atom_name, atom_position))
simulation.insert_configuration(configuration)
return simulation
示例3: acceptor_udp_server
def acceptor_udp_server():
ID = Configuration.getMyID()
#UDP_PORT = Configuration.ACCEPTOR_PORT
UDP_PORT = Configuration.PORTS["prepare"]
print threading.currentThread().getName(), ' Acceptor UDP Server Starting. I am Node#', ID, "at port", UDP_PORT
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind(('', UDP_PORT))
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
peerID = Configuration.getID( addr[0] )
#try
json_object = transferInput(data)
if json_object['msgname'] == "commit":
onCommit(json_object['entryID'], json_object['msglist'], peerID)
printdata("Acceptor Recv Commit", ID, peerID, ID, data)
elif json_object['msgname'] == "accept":
onAccept(json_object['entryID'], json_object['msglist'], peerID)
printdata("Acceptor Recv Accept", ID, peerID, ID, data)
elif json_object['msgname'] == "prepare":
onPrepare(json_object['entryID'], json_object['msglist'], peerID)
printdata("Acceptor Recv Prepare", ID, peerID, ID, data)
#except:
# print "Can't parse data:", data, sys.exc_info()[0]
print threading.currentThread().getName(), ' Acceptor UDP Server Exiting. I am Node#', ID
return
示例4: _generateArtifactList
def _generateArtifactList(options):
# load configuration
logging.info("Loading configuration...")
config = Configuration()
config.load(options)
# build list
logging.info("Building artifact list...")
listBuilder = ArtifactListBuilder(config)
artifactList = listBuilder.buildList()
logging.debug("Generated list contents:")
for gat in artifactList:
priorityList = artifactList[gat]
for priority in priorityList:
versionList = priorityList[priority]
for version in versionList:
logging.debug(" %s:%s", gat, version)
#filter list
logging.info("Filtering artifact list...")
listFilter = Filter(config)
artifactList = listFilter.filter(artifactList)
logging.debug("Filtered list contents:")
for gat in artifactList:
priorityList = artifactList[gat]
for priority in priorityList:
versionList = priorityList[priority]
for version in versionList:
logging.debug(" %s:%s", gat, version)
logging.info("Artifact list generation done")
return artifactList
示例5: TCPSend
def TCPSend(dest, content):
TCP_IP = Configuration.getIP(dest)
MYIP = Configuration.getPublicIP()
if TCP_IP == MYIP:
print "TCPSend() terminates. (Error: sending to itself)" #Ignore itself
return
TCP_PORT = Configuration.TCPPORT
ID = Configuration.getMyID()
print threading.currentThread().getName(), 'TCP Client Starting. I am Node#', ID
BUFFER_SIZE = 1024
MESSAGE = "Hello, World! from Node#%d" % ID
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
flag = True
while flag:
try:
s.connect((TCP_IP, TCP_PORT))
s.send(content)
printdata("TCP Send", ID, ID, Configuration.getID(TCP_IP), content)
data = s.recv(BUFFER_SIZE)
s.close()
flag = False
except:
printdata("TCP Client Reconnect", ID, ID, Configuration.getID(TCP_IP), "@[email protected]")
time.sleep(1) #Reconnect delay
time.sleep(5)
print threading.currentThread().getName(), 'TCP Client Exiting Successfully. I am Node #', ID
return
示例6: url_handler
def url_handler(ref):
uri = None
prefix = None
conf = Configuration()
datasetBase = conf.get_value("datasetBase")
webBase = conf.get_value("webBase")
webResourcePrefix = conf.get_value("webResourcePrefix")
if (len(webResourcePrefix) == 0):
splitted = ref.split("/")
prefix = splitted[0]
if (prefix in get_supported_prefixes()):
uri = "%s%s" % (datasetBase, ref[len(prefix)+1:])
return uri, prefix
else:
prefix = None
uri = datasetBase + ref
return uri, prefix
else:
if (ref.startswith(webResourcePrefix)):
prefix = None
uri = datasetBase + ref
return uri, prefix
else:
splitted = ref.split("/")
prefix = splitted[0]
if (prefix in get_supported_prefixes()):
uri = datasetBase + ref.replace(prefix+"/", conf.get_value("webResourcePrefix"))
return uri, prefix
else:
raise ValueError("Unsupportet type '%s'" % splitted[0])
示例7: Kobol
class Kobol(object):
def __init__(self, directory = None):
self.home = os.path.normpath(directory or os.getcwd()) + os.sep
self.config = Configuration()
self.config['home'] = self.home
self.site = Site()
self.site.config(self.config)
def scaffold(self, **kwargs):
if os.path.isfile(self.home + '/.kobol'):
return False
elif kwargs.get('dry') != True:
skel = os.path.dirname(os.path.abspath(__file__)) + '/skel/'
os.system("cp -R %s* %s.kobol %s" % (skel, skel, self.home))
return True
def load_config_files(self, files):
self.config.load(files)
self.site.config(self.config)
def main(self):
self.scaffold()
示例8: closeEvent
def closeEvent(self, event):
if not self.trayIcon.isVisible() and Configuration.icon:
self.trayIcon.show()
self.hide()
event.ignore()
else:
termine = True
# On vérifie que tous les téléchargements soient finis
for download in self.downloads.instance.downloads:
if download.state == 3:
termine = False
# Si il y a un download en cours on affiche la fenêtre
if not termine and not Configuration.close_window:
# Un petit messageBox avec bouton clickable :)
msgBox = QMessageBox(QMessageBox.Question, u"Voulez-vous vraiment quitter?", u"Un ou plusieurs téléchargements sont en cours, et pyRex ne gère pas encore la reprise des téléchargements. Si vous quittez maintenant, toute progression sera perdue!")
checkBox = QCheckBox(u"Ne plus afficher ce message", msgBox)
checkBox.blockSignals(True)
msgBox.addButton(checkBox, QMessageBox.ActionRole)
msgBox.addButton("Annuler", QMessageBox.NoRole)
yesButton = msgBox.addButton("Valider", QMessageBox.YesRole)
msgBox.exec_()
if msgBox.clickedButton() == yesButton:
# On save l'état du bouton à cliquer
if checkBox.checkState() == Qt.Checked:
Configuration.close_window = True
Configuration.write_config()
event.accept()
else:
event.ignore()
else:
event.accept()
示例9: test_filter_excluded_GAVs
def test_filter_excluded_GAVs(self):
config = Configuration()
alf = Filter(config)
config.excludedGAVs = ["com.google.guava:guava:1.1.0"]
al = copy.deepcopy(self.artifactList)
self.assertTrue('1.1.0' in al['com.google.guava:guava:pom']['1'])
alf._filterExcludedGAVs(al)
self.assertFalse('1.1.0' in al['com.google.guava:guava:pom']['1'])
config.excludedGAVs = ["com.google.guava:guava:1.0*"]
al = copy.deepcopy(self.artifactList)
self.assertTrue('1.0.0' in al['com.google.guava:guava:pom']['1'])
self.assertTrue('1.0.1' in al['com.google.guava:guava:pom']['1'])
self.assertTrue('1.0.2' in al['com.google.guava:guava:pom']['2'])
self.assertTrue('1.0.0' in al['com.google.guava:guava:pom']['3'])
alf._filterExcludedGAVs(al)
self.assertFalse('1.0.0' in al['com.google.guava:guava:pom']['1'])
self.assertFalse('1.0.1' in al['com.google.guava:guava:pom']['1'])
self.assertFalse('2' in al['com.google.guava:guava:pom'])
self.assertFalse('1.0.0' in al['com.google.guava:guava:pom']['3'])
config.excludedGAVs = ["com.google.guava:*"]
al = copy.deepcopy(self.artifactList)
self.assertTrue('com.google.guava:guava:pom' in al)
alf._filterExcludedGAVs(al)
self.assertFalse('com.google.guava:guava:pom' in al)
示例10: show_form
def show_form(self):
'''
Displays this form, blocking until the user closes it. When it is closed,
this method will return a Configuration object containing the settings
that this dialog was displaying when it was closed (these settings were
also just saved on the filesystem, so they are also the settings that
this dialog will display the next time it is opened.)
If the user clicks 'Cancel' then this method will simply return null.
'''
log.debug("opened the settings dialog.")
defaults = Configuration()
defaults.load_defaults()
self.__set_configuration(defaults)
self.__switch_to_best_tab()
dialogAnswer = self.ShowDialog() # blocks
if dialogAnswer == DialogResult.OK:
config = self.__get_configuration()
config.save_defaults()
log.debug("closed the settings dialog.")
else:
config = None
log.debug("cancelled the settings dialog.")
return config
示例11: clear
def clear():
"""
Clear the screen,
only if the configuration says it's OK.
"""
if Configuration.getClear() and Configuration.getInteractive():
sys.stdout.write(Configuration.clearcode)
示例12: test_filter_excludedTypes
def test_filter_excludedTypes(self):
config = Configuration()
alf = Filter(config)
config.excludedTypes = ["zip", "war"]
al = copy.deepcopy(self.artifactList)
al["foo:bar"] = {
"1": {
"1.0.0": ArtifactSpec("http://repo1.maven.org/maven2/",
[ArtifactType("zip", True, set([''])), ArtifactType("pom", False, set(['']))])
}
}
alf._filterExcludedTypes(al)
self.assertFalse('foo:bar' in al)
al["foo:bar"] = {
"1": {
"1.0.0": ArtifactSpec("http://repo1.maven.org/maven2/",
[ArtifactType("zip", True, set([''])), ArtifactType("pom", False, set(['']))])
}
}
config.gatcvWhitelist = ["*:zip:scm-sources:*"]
alf._filterExcludedTypes(al)
self.assertFalse('foo:bar' in al)
al["foo:bar"] = {
"1": {
"1.0.0": ArtifactSpec("http://repo1.maven.org/maven2/",
[ArtifactType("zip", True, set(['scm-sources'])),
ArtifactType("pom", False, set(['']))])
}
}
alf._filterExcludedTypes(al)
self.assertTrue('foo:bar' in al)
示例13: TCPClient
def TCPClient():
MYIP = Configuration.getPublicIP()
ID = Configuration.getMyID()
print threading.currentThread().getName(), 'TCP Client Starting. I am Node#', ID
while True:
user_input = raw_input("format: send <Dest Node ID> <Message>")
cmd = user_input.split(" ")
for ip in Configuration.IPTABLE:
if ip == MYIP: continue #Ignore itself
TCP_IP = ip
TCP_PORT = Configuration.TCPPORT
BUFFER_SIZE = 1024
MESSAGE = "Hello, World! from Node#%d" % ID
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
flag = True
while flag:
try:
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE)
printdata("TCP Send", ID, ID, Configuration.getID(TCP_IP), MESSAGE)
data = s.recv(BUFFER_SIZE)
s.close()
flag = False
except:
printdata("TCP Client Reconnect", ID, ID, Configuration.getID(TCP_IP), "@[email protected]")
time.sleep(1) #Reconnect delay
time.sleep(5)
print threading.currentThread().getName(), 'TCP Client Exiting. I am Node #', ID
return
示例14: runMain
def runMain():
# First, we import our devices from our configuration file. These will be split into two different groups, those
# controlled by Philips Hue and those controlled by Insteon.
configuration = Configuration()
config = configuration.loadConfig()
hueDevices = {}
insteonDevices = {}
for device in config['devices']['hue']:
hueDevices[device] = config['devices']['hue'][device]
for device in config['devices']['insteon']:
insteonDevices[device] = config['devices']['insteon'][device]
insteon = Insteon()
hue = Hue()
roomba = Roomba()
# Now we set up the voice recognition using Pocketsphinx from CMU Sphinx.
pocketSphinxListener = PocketSphinxListener()
# We want to run forever, or until the user presses control-c, whichever comes first.
while True:
try:
command = pocketSphinxListener.getCommand().lower()
command = command.replace('the', '')
if command.startswith('turn'):
onOrOff = command.split()[1]
deviceName = ''.join(command.split()[2:])
if deviceName in hueDevices:
deviceId = hueDevices[deviceName]['deviceID']
hue.turn(deviceId=deviceId, onOrOff=onOrOff)
if deviceName in insteonDevices:
deviceId = insteonDevices[deviceName]['deviceID']
insteon.turn(deviceId=deviceId, onOrOff=onOrOff)
if deviceName == 'roomba':
roomba.turn(onOrOff)
elif command.startswith('roomba'):
action = ' '.join(command.split()[1:])
if action == 'clean':
roomba.clean()
if action == 'go home':
roomba.goHome()
# This will allow us to be good cooperators and sleep for a second.
# This will give the other greenlets which we have created for talking
# to the Hue and Insteon hubs a chance to run.
gevent.sleep(1)
except (KeyboardInterrupt, SystemExit):
print 'People sometimes make mistakes, Goodbye.'
sys.exit()
except Exception as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback,
limit=2,
file=sys.stdout)
sys.exit()
示例15: do_destroy
def do_destroy(args):
"""Destroy a droplet based on configuration"""
config = Configuration()
if not config.read_config(args.config_file):
return False
destroy(config)
return True