def setup(): log.debug("Starting " + application.name + " %s" % (application.version, )) config.setup() fixes.setup() log.debug("Using %s %s" % (platform.system(), platform.architecture()[0])) log.debug("Application path is %s" % (paths.app_path(), )) log.debug("config path is %s" % (paths.config_path(), )) sound.setup() output.setup() languageHandler.setLanguage(config.app["app-settings"]["language"]) keys.setup() from controller import mainController from sessionmanager import sessionManager app = widgetUtils.mainLoopObject() if system == "Windows": if config.app["app-settings"]["donation_dialog_displayed"] == False: donation() updater.do_update() sm = sessionManager.sessionManagerController() sm.fill_list() if len(sm.sessions) == 0: sm.show() else: sm.do_ok() if hasattr(sm.view, "destroy"): sm.view.destroy() del sm r = mainController.Controller() r.view.show() r.do_work() r.check_invisible_at_startup() if system == "Windows": call_threaded(r.start) elif system == "Linux": GLib.idle_add(r.start) app.run()
def cmd_reload(main_window, argv): """ /reload Reload the configuration. """ # FIXME config.setup() print_notification("Config reloaded.")
def setUp(self): utils.logger.info("TESTCASE =====> %s <===== START" % CASENAME) config.setup(CASENAME) config.prepareSrc(CASENAME, SRCPKG) config.buildBin(CASENAME, cmdToBuild='make linux-AMD64', subdir='src/current', cmdToInstall='manual', pkg2build=SRCPKG) utils.manualInstall('src/current', config.binDir())
def run(self): global task_socket task_socket.connect((HOST, PORT)) # connect to the server config.setup() voice.setup() # initial handshake response = send_task_socket('handshake', '', True) # WAITING FOR VOICE INPUT message = get_voice() success, pro, struct = input_control.Process(message) while message.lower().strip() != 'unicorn': if (success): response = send_task_socket('message', { 'pro': pro, 'struct': struct }, True) handle_response(response) # WAITING FOR VOICE INPUT message = get_voice() success, pro, struct = input_control.Process(message)
def new_account(self, ev): twitter_object = twitter.twitter.twitter() dlg = wx.MessageDialog( self, _(u"The request for the required Twitter authorization to continue will be opened on your browser. You only need to do it once. Would you like to autorhise a new account now?" ), _(u"Authorisation"), wx.YES_NO) if dlg.ShowModal() == wx.ID_NO: return else: location = (str(time.time())[:12]) manager.manager.add_session(location) config.MAINFILE = "%s/session.conf" % (location, ) config.setup() try: twitter_object.authorise() except: wx.MessageDialog( None, _(u"Your access token is invalid or the authorisation has failed. Please try again." ), _(u"Invalid user token"), wx.ICON_ERROR).ShowModal() return total = self.list.get_count() name = _(u"Authorised account %d") % (total + 1) self.list.insert_item(False, name) if self.list.get_count() == 1: self.list.select_item(0) self.sessions.append(location)
def setUp(self): utils.logger.info("TESTCASE =====> %s <===== START" % CASENAME) config.setup(CASENAME) config.prepareSrc(CASENAME, SRCPKG) config.buildBin(CASENAME, cmdToBuild="./configure --prefix=%s && make all"% config.binDir(), cmdToInstall="make install") # FIXME: sub-dirs can not be searched in clr os.system("mv %s/bin/* %s" % (config.binDir(), config.binDir()))
def main(): start_time = config.time.time() config.setup() print_tables_of_user_input() HealthAPIDataManager.get_data() store_data_in_DB() end_time = config.time.time() print(f'Seconds taken: {end_time - start_time}')
def initialize(): app.logger.debug('Initializing app configuration') try: import config config.setup(app_config) app.logger.debug(config) except: traceback.print_exc()
def test_bad_filename(random_string_fx): """ Intentionally insert a bad filename to ensure FileNotFoundError is thrown, when passed to config.setup. """ filename = random_string_fx with pytest.raises(FileNotFoundError): config.setup(filename)
def main(): # Run the setup to create folders etc setup() dl = DataLoader(f'../../data/clean/{LOCATION.value}.csv') # dl.histogram() # Method experimentation is done inside each model module: baseline(dl)
def setup(): import globals as G import world.World globals.world = world.World.World() import rendering.model.BlockState import Language config.setup() import world.gen.mode.DebugOverWorldGenerator
def setUp(self): utils.logger.info("TESTCASE =====> %s <===== START" % CASENAME) utils.requiredPkgs('zypper', REQUIREDPKGS) config.setup(CASENAME) config.prepareSrc(CASENAME, None) config.buildBin(CASENAME, cmdToBuild="./configure --prefix=%s && make all" % config.binDir(), cmdToInstall="make install") # FIXME system bug - dont's search subdir underneath $PATH os.system("cp -v %s/%s %s" % (config.binDir(), "bin/*", config.binDir())) # prepare and start netserver self.process = self.prepareNetServer()
def test_user_directory(self, mock_user_config_dir): """ Make sure when using the default setup (system variable user directory), the config file is found in the correct place :param mock_user_config_dir: :return: """ mock_user_config_dir.side_effect = [test_config_file_dir] config.setup() self.assertTrue( os.path.exists(os.path.join(test_config_file_dir, "config.conf")))
def ok(self, ev): if self.list.get_count() == 0: wx.MessageDialog(None, _(u"You need to configure an account."), _(u"Account Error"), wx.ICON_ERROR).ShowModal() return current_session = self.sessions[self.list.get_selected()] manager.manager.set_current_session(current_session) config.MAINFILE = "%s/session.conf" % (manager.manager.get_current_session()) config.setup() lang=config.main['general']['language'] languageHandler.setLanguage(lang) sound.setup() output.setup() self.EndModal(wx.ID_OK)
def update_system(currentVerison): dir_path = os.path.dirname(os.path.realpath(__file__)) pullGit = ''.join(['git -C', dir_path, 'pull']) os.system(pullGit) config.setup() newVersion = config.CONFIG['version'] # Ensure that version is up to speed if (newVersion != currentVerison): reboot() else: return "Already updated to the latest version"
def main2(): try: c.setup('roadmap.md') resp = requests.get(c.get_milestone_url(v._CONFIG_), auth=c.get_basic_auth_credentials(v._CONFIG_)) if resp.status_code == 200: fmt.h1('Technology Roadmap') milestones = simplejson.loads(resp.content) for milestone in milestones: write_milestone(milestone) print 'Done.' else: print 'Unexpected reponse' print 'Status: %s' % resp.status_code finally: c.teardown()
def test_write_config_option(self, mock_user_config_dir): """ Test writing to config file, make sure writen values are written correctly :param mock_user_config_dir: :return: """ mock_user_config_dir.side_effect = [test_config_file_dir] config.setup() self.assertEqual(config.read_config_option('client_id'), '') config.write_config_option('client_id', "new_id") self.assertEqual(config.read_config_option('client_id'), "new_id")
def ok(self, ev): if self.list.get_count() == 0: wx.MessageDialog(None, _(u"You need to configure an account."), _(u"Account Error"), wx.ICON_ERROR).ShowModal() return current_session = self.sessions[self.list.get_selected()] manager.manager.set_current_session(current_session) config.MAINFILE = "%s/session.conf" % ( manager.manager.get_current_session()) config.setup() lang = config.main['general']['language'] languageHandler.setLanguage(lang) sound.setup() output.setup() self.EndModal(wx.ID_OK)
def main(args): config = setup(args.config, args.params) logger.info(config) logger.info("Watching serial %s", args.dev) with Serial(args.dev, config.baud_rate, timeout=config.timeout) as dev: while True: hello_message = protocol.init(dev) logger.info("Received hello: %s", hello_message) try: while True: magic, payload = protocol.readline(dev) if magic == b"M": logger.info("Recv message %s", payload) elif magic == b"C": cmd = int(payload.decode().strip()) logger.info("Recv command %s", cmd) config.commands[cmd].run(log=True) else: raise ValueError( f"main: unexpected magic {magic}, mesg {payload}") except KeyboardInterrupt: break except Exception as e: logger.warning(f"Unhandled exception: {e}. Restarting.") continue
def main(): window = setup(title=MILES_TO_KM, image=IMAGE_TITLE_BAR, width=WINDOW_WIDTH, is_center=True) window.config(padx=5, pady=40) miles_to_km = tkinter.Label(text="Convert Miles to Km", font=("Arial", 15, "bold")) # expand=bool, it shows label in the center[center center] of window or make it just top center # side one of ==> [top, bottom, left, or right] # padding ==> padx, pady # miles_to_km.pack( # expand=0, side=TOP, padx=MAIN_TITLE_XPAD, pady=MAIN_TITLE_YPAD # ) # show and center component(label) with custom features tkinter.Label(text="test").grid(row=0, column=0) btn = tkinter.Button(text="click Me") # btn.config(padx=50) btn.grid(row=0, column=2) btn2 = tkinter.Button(text="Attach") btn2.grid(row=1, column=1, padx=50) # padding between components btn2.config(padx=30, pady=200) # padding in the item itself between item text # tkinter.Button(text="ok").grid(row=1, column=2) tkinter.Entry().grid(row=2, column=3) # tkinter.Label().grid(row=2, column=3) # tkinter.Entry().grid(row=2, column=4) # add components to the window and keep me working # keep window opens and listening to the user actions window.mainloop() # keep window open while working
def main(use_cache): try: c.setup('roadmap.md') if use_cache: with open('milestones.pickle') as f: milestones = pickle.load(f) else: issues = fetch_issues() milestones = add_milestones_with_no_issues(into_milestones(issues)) milestones = sorted(milestones.iteritems(), cmp_due_dates) with open('milestones.pickle', 'w') as f: pickle.dump(milestones, f) fmt.h1('Technology Roadmap') write_milestones(milestones) print 'Done.' finally: c.teardown()
def setup(): log.debug("Starting " + application.name + " %s" % (application.version,)) config.setup() log.debug("Using %s %s" % (platform.system(), platform.architecture()[0])) log.debug("Application path is %s" % (paths.app_path(),)) log.debug("config path is %s" % (paths.config_path(),)) sound.setup() output.setup() languageHandler.setLanguage(config.app["app-settings"]["language"]) message(message=_(u"Loading files and configuration, please wait...")) fixes.setup() keys.setup() from controller import mainController from sessionmanager import sessionManager app = widgetUtils.mainLoopObject() gplwarning() if system == "Windows": if config.app["app-settings"]["donation_dialog_displayed"] == False: donation() if config.app["app-settings"]["check_updates"] == True: updater.do_update() else: message(message=_(u"Set to ignore updates at startup. To change this preference, go to global config")) sm = sessionManager.sessionManagerController() sm.fill_list() if len(sm.sessions) == 0: sm.show() else: sm.do_ok() if hasattr(sm.view, "destroy"): sm.view.destroy() del sm r = mainController.Controller() r.view.show() r.do_work() r.check_invisible_at_startup() if system == "Windows": call_threaded(r.start) elif system == "Linux": GLib.idle_add(r.start) message( message=_(u"Welcome to %s. Main application's window will appears shortly. Happy tweeting!") % application.name ) app.run()
def main(milestone): try: c.setup("issues.md") resp = requests.get(c.get_issues_url(v._CONFIG_), auth=c.get_basic_auth_credentials(v._CONFIG_), params={'milestone': milestone}) if resp.status_code == 200: fmt.h1("Issues") issues = simplejson.loads(resp.content) for issue in issues: write_issue(issue) print "Done." else: print "Unexpected reponse" print "Status: %s" % resp.status_code finally: c.teardown()
def run_monitor(): try: cfg = setup(sys.argv) except Exception, e: print "Startup failure: %s" % e import traceback traceback.print_exc() return
def main(): """Main loop for the bot.""" setup() updater = Updater(TELEGRAM_API_TOKEN) dp = updater.dispatcher dp.add_handler(CommandHandler("start", start)) dp.add_handler(CommandHandler("shutdown", shutdown)) # radio dp.add_handler(CommandHandler("radio", Radio.telegram_command, pass_args=True, pass_job_queue=True)) dp.add_handler(CallbackQueryHandler( Radio.telegram_change_station, pass_job_queue=True)) # on noncommand i.e message - echo the message on Telegram dp.add_handler(MessageHandler(None, receive)) # log all errors dp.add_error_handler(error) # Start the Bot updater.start_polling() # Start the players gif_player = Video() gif_player.setDaemon(True) gif_player.start() radio = Radio() radio.setDaemon(True) radio.start() # Run the bot until the you presses Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT. This should be used most of the time, since # start_polling() is non-blocking and will stop the bot gracefully. updater.idle() gif_player.stop() radio.stop()
def setup(): log.debug("Starting Socializer %s" % (application.version,)) config.setup() log.debug("Using %s %s" % (platform.system(), platform.architecture()[0])) log.debug("Application path is %s" % (paths.app_path(),)) log.debug("config path is %s" % (paths.config_path(),)) output.setup() languageHandler.setLanguage(config.app["app-settings"]["language"]) log.debug("Language set to %s" % (languageHandler.getLanguage())) keys.setup() from controller import mainController from sessionmanager import sessionManager app = widgetUtils.mainLoopObject() log.debug("Created Application mainloop object") sm = sessionManager.sessionManagerController() del sm r = mainController.Controller() call_threaded(r.login) app.run()
def main(): """Main Function of VRManager.""" config.setup() service_threads = [] #Create the Cleanup Thread cleaner = Cleanup() service_threads.append(cleaner) for thread in service_threads: thread.start() #for thread in service_threads: #thread.stop() for thread in service_threads: thread.join() return 0
def main(argv): """ :param argv: parser :return: None """ parser = argparse.ArgumentParser() parser.add_argument( "--instance", default="ft06", type=str, help="Nom de l'instance", ) parser.add_argument( "--temps", default=10, type=int, help="Temps de recherche", ) args = parser.parse_args() setup() recherche_exact(args.instance, args.temps)
def main(args): filename = os.getcwd() + '/.patchesrc' if os.access(filename, os.R_OK): raise Exception('Configuration file %s already exists' % filename) ini = RawConfigParser() if args.url: ini.add_section('fetch') ini.set('fetch', 'url', args.url[0]) with open(filename, 'w') as fp: ini.write(fp) if args.url: config.setup(filename) return fetch.fetch() return 0
def test_parameter(self): """ Tests that reading from the global variables (parameter passing) works Also ensures that it can read from the file correctly with read_config_option :return: """ example_path = os.path.join(path_to_module, "example_config.conf") global_settings.config_file = example_path config.setup() self.assertEqual(config.config.user_config_file, example_path) # Verify all the options were set correctly self.assertEqual(config.read_config_option('client_id'), 'uploader') self.assertEqual(config.read_config_option('client_secret'), 'secret') self.assertEqual(config.read_config_option('username'), 'admin') self.assertEqual(config.read_config_option('password'), 'password1') self.assertEqual(config.read_config_option('base_url'), 'http://localhost:8080/irida-latest/api/') self.assertEqual(config.read_config_option('parser'), 'miseq')
def new_account(self, ev): twitter_object = twitter.twitter.twitter() dlg = wx.MessageDialog(self, _(u"The request for the required Twitter authorization to continue will be opened on your browser. You only need to do it once. Would you like to autorhise a new account now?"), _(u"Authorisation"), wx.YES_NO) if dlg.ShowModal() == wx.ID_NO: return else: location = (str(time.time())[:12]) manager.manager.add_session(location) config.MAINFILE = "%s/session.conf" % (location,) config.setup() try: twitter_object.authorise() except: wx.MessageDialog(None, _(u"Your access token is invalid or the authorisation has failed. Please try again."), _(u"Invalid user token"), wx.ICON_ERROR).ShowModal() return total = self.list.get_count() name = _(u"Authorised account %d") % (total+1) self.list.insert_item(False, name) if self.list.get_count() == 1: self.list.select_item(0) self.sessions.append(location)
def main(): """ Return value Run the main logic of the app """ args, config = cfg.setup() folder = (args.folder or './modules/aks') function = (args.function or 'reference') for file in fs.findFiles(folder): json = hcl.convertTfFileToJson(file) controller(function, json)
def check(filepath, assumptions, gccopt='', excludedata='', instrument=False): """ Perform basic check on analyzed executable and set configuration values :param filepath: path to executable :param assumptions: list of assumption codes :param gccopt: additional options for the compiler :param excludedata: path to file of address exclusions :param instrument: True if instrumentation enabled :return: True if everything ok """ if not assumptions: assumptions = [] if not os.path.isfile(filepath): sys.stderr.write("Cannot find input binary\n") return False if len(excludedata) != 0 and not os.path.isfile(excludedata): sys.stderr.write("File with exclusions not found\n") return False for f in glob.glob('*'): os.remove(f) if os.path.dirname(filepath) != os.getcwd(): shutil.copy(filepath, '.') os.system('file ' + filepath + ' > elf.info') config.setup(filepath, gccopt, excludedata, instrument) if config.is_lib: sys.stderr.write("Uroboros doesn't support shared libraries\n") return False # if assumption three is utilized, then input binary should be unstripped. if ('3' in assumptions or instrument) and not config.is_unstrip: print colored('Warning:', 'yellow'), 'binary is stripped, function boundaries evaluation may not be precise' return True
def initialize_db(participants, event_name): with Database(DB) as db: if not config.check_event_exists(db, event_name): participants = config.setup(participants, db) event_name = db.add_event(event_name) print('\nPsst... Your event name is: {}'.format(event_name)) db.add_participants(event_name, *participants) shuffled = raffle.shuffle_names(*participants) mapped = raffle.map_names(*shuffled) for secret in mapped: db.add_secret(event_name, *secret) else: print('\nData for event {} already exists.\n'.format(event_name))
import theano from matplotlib import pyplot from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams from config import setup, setup_main from dataset import deserialize_from_file, divide_dataset, build_fuel, GuessOrder from game.asker import Asker from game.responder import Responder from models.variational import Helmholtz from utils.generic_utils import * theano.config.optimizer = 'fast_compile' Asker = Asker # GridAsker # PyramidAsker # GridAsker logger = logging.getLogger(__name__) lm_config = setup() main_config = setup_main( ) # setup_grid6() # setup_pyramid() # setup_grid() # setup_main() # logging.basicConfig(level= main_config['level'], format="%(asctime)s: %(name)s: %(levelname)s: %(message)s") np.random.seed(main_config['seed']) n_rng = np.random.RandomState(main_config['seed']) rng = RandomStreams(n_rng.randint(2**30), use_cuda=True) """ Main Loop. """ print 'start.' # load the dataset and build a fuel-dataset. idx2word, word2idx = deserialize_from_file(lm_config['vocabulary_set'])
def setUp(self): utils.logger.info("TESTCASE =====> %s <===== START" % CASENAME) utils.requiredPkgs(package=REQUIREDPKGS) config.setup(CASENAME) config.prepareSrc(CASENAME, SRCPKG) config.buildBin(CASENAME, pkg2build = SRCPKG)
def run(self): log.info("Starting Cleanup Thread...") ResourcePool = cloud_management.ResourcePool() OpenstackCluster = openstackcluster.OpenStackCluster(name='', username='', password='', tenant_id='', auth_url='') while not self.quit: start_loop_time = time.time() """Try to execute command 'condor_status -l' and transform the output into machine objects.""" try: condor_status_machinelist = ResourcePool.resource_query_local( self.NoneGroup) except Exception as e: log.error( "Some error occured when trying to excute function ResourcePool.resource_query_local()." ) """Try to find vms running on openstack and transform the output into VM objects.""" vms = () vms_new = () try: vms = OpenstackCluster.get_vms_local() except Exception as e: print e log.error( "Some error occured when trying to excute function OpenstackCluster.get_vms_local()." ) #sys.exit(1) continue """Try to modify VM object's job attribute with results from command 'condor_status -l'.""" try: vms_new = ResourcePool.update_vmslist_from_machinelist( vms, condor_status_machinelist) OpenstackCluster.vms = vms_new except Exception as e: log.error( "Some error occured when trying to excute function ResourcePool.update_vmslist_from machinelist" ) print e num_vm_busy = OpenstackCluster.num_vms_by_group_activity( vms=vms_new, group=GROUP_DICT[self.NoneGroup], activity=ACTIVE_SET) print "num_vm_busy" print num_vm_busy num_vm_idle = OpenstackCluster.num_vms_by_group_activity( vms=vms_new, group=GROUP_DICT[self.NoneGroup], activity=INACTIVE_SET) print "num_vm_idle" print num_vm_idle num_vm_all = num_vm_busy + num_vm_idle num_vm_to_launch = 0 num_vm_to_destroy = num_vm_idle print "Cleanup %d instance of %s!" % (num_vm_to_destroy, self.NoneGroup) if (num_vm_to_destroy > 0): try: OpenstackCluster.vm_destroy_by_Group_JobActivity( count=num_vm_to_destroy, group=GROUP_DICT[self.NoneGroup], activity=INACTIVE_SET, vms=vms_new) except Exception as e: log.error( "Unable to destroy %d instances by method OpenstackCluster.vm_destroy_by_Group_JobActivity for group %s." % (num_vm_to_destroy, self.NoneGroup)) print e config.setup() if config.exit == 'false': print 'exit' self.quit = True self.sleep_tics = config.cleanup_interval if (not self.quit) and self.sleep_tics > 0: print self.sleep_tics time.sleep(self.sleep_tics)
#!/usr/bin/env python """ Plot distribution of levels """ import csv import config import matplotlib.pyplot as plt config.setup() # load data data = [] with open(config.data_path + '/levels.csv', 'rb') as csvfile: spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in spamreader: data.append(int(row[0])) # make data into histrogram total = len(data) xs = range(max(data) + 1) ys = map(lambda x: float(len(filter(lambda i: i == x, data)))/total, xs) width = 0.7 fig, ax = plt.subplots() rects = ax.bar([i+(1.-width)/2. for i in xs], ys, width, color=config.colors()[0]) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False)
def application(environ, start_response): gr = GitRest(environ, start_response) config.setup() gr.set_repos(config.Settings.repos) return gr.serve()
maintainer_email="*****@*****.**", url="https://github.com/lsbardel/ccy", license="BSD", long_description=config.read(os.path.join(b, 'README.rst')), packages=find_packages(include=['ccy', 'ccy.*']), install_requires=config.requirements(os.path.join(b, 'requirements.txt')), zip_safe=False, test_suite="tests.suite", classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Plugins', 'Intended Audience :: Developers', 'Intended Audience :: Financial and Insurance Industry', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Office/Business :: Financial', 'Topic :: Utilities' ] ) if __name__ == '__main__': setup(**config.setup(meta, 'ccy'))
def setUp(self): utils.logger.info("TESTCASE =====> %s <===== START" % CASENAME) config.setup(CASENAME)
def hook_setup(cmd): config.setup() sys.exit(0)
#!/usr/bin/python # # -*- coding: utf-8 -*- # vim: set ts=4 sw=4 et sts=4 ai: """Default handler for admin pages.""" import os import config config.setup(os.environ.get('HTTP_HOST', None)) # AppEngine imports from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app # OpenID middleware import aeoid.middleware # Import the actual handlers import event_edit import event_publish import offers application = webapp.WSGIApplication( [('/event/add', event_edit.EditEvent), ('/event/(.*)/edit', event_edit.EditEvent), ('/event/(.*)/publish', event_publish.PublishEvent), ('/event/(.*)/email', event_publish.SendEmailAboutEvent), ('/offer/add', offers.EditOffer), ('/offer/(.*)/edit', offers.EditOffer), ],
# Project : rhc_smoke # Loc : /lib # Author : cshi # Date : 4.Jan.2015 import config def print_log_info(): print "|- result: result/rhc_smoke_test.result" print "----------------------------" def print_config_info(smokeconfig): print "------ RHC SMOKE TEST ------" print "|- account : %s" % (smokeconfig.get('default_rhlogin')) print "|- password : %s" % (smokeconfig.get('default_rhpasswd')) print "|- env : %s" % (smokeconfig.get('libra_server')) def setup(smokeconfig): print_config_info(smokeconfig) print_log_info() # DEBUG if __name__ == "__main__": cfg = config.setup() setup(cfg)
def setUp(self): utils.logger.info("TESTCASE =====> %s <===== START" % CASENAME) config.setup(CASENAME) config.prepareSrc(CASENAME, SRCPKG) config.buildBin(CASENAME, cmdToBuild="./configure.sh && make all")
def hook_setup(cmd): if '-h' in cmd: return config.setup() sys.exit(0)
def setUp(self): utils.requiredPkgs('zypper', REQUIREDPKGS) config.setup(CASENAME) utils.logger.info("TESTCASE =====> %s <===== START" % CASENAME)
def main(start=True, argv=None): try: import twisted except ImportError: print "Orbited requires Twisted, which is not installed. See http://twistedmatrix.com/trac/ for installation instructions." sys.exit(1) ################# # This corrects a bug in Twisted 8.2.0 for certain Python 2.6 builds on Windows # Twisted ticket: http://twistedmatrix.com/trac/ticket/3868 # -mario try: from twisted.python import lockfile except ImportError: from orbited import __path__ as orbited_path sys.path.append(os.path.join(orbited_path[0],"hotfixes","win32api")) from twisted.python import lockfile lockfile.kill = None ################# from optparse import OptionParser parser = OptionParser() parser.add_option( "-c", "--config", dest="config", default=None, help="path to configuration file" ) parser.add_option( "-v", "--version", dest="version", action="store_true", default=False, help="print Orbited version" ) parser.add_option( "-p", "--profile", dest="profile", action="store_true", default=False, help="run Orbited with a profiler" ) parser.add_option( "-q", "--quickstart", dest="quickstart", action="store_true", default=False, help="run Orbited on port 8000 and MorbidQ on port 61613" ) if argv == None: argv = sys.argv[1:] (options, args) = parser.parse_args(argv) if args: print 'the "orbited" command does not accept positional arguments. type "orbited -h" for options.' sys.exit(1) if options.version: print "Orbited version: %s" % (version,) sys.exit(0) if options.quickstart: config.map['[listen]'].append('http://:8000') config.map['[listen]'].append('stomp://:61613') config.map['[access]'][('localhost',61613)] = ['*'] print "Quickstarting Orbited" else: # load configuration from configuration # file and from command line arguments. config.setup(options=options) logging.setup(config.map) # we can now safely get loggers. global logger; logger = logging.get_logger('orbited.start') ############ # This crude garbage corrects a bug in twisted # Orbited ticket: http://orbited.org/ticket/111 # Twisted ticket: http://twistedmatrix.com/trac/ticket/2447 # XXX : do we still need this? # -mcarter 9/24/09 # import twisted.web.http # twisted.web.http.HTTPChannel.setTimeout = lambda self, arg: None # twisted.web.http.HTTPChannel.resetTimeout = lambda self: None ############ # NB: we need to install the reactor before using twisted. reactor_name = config.map['[global]'].get('reactor') if reactor_name: install = _import('twisted.internet.%sreactor.install' % reactor_name) install() logger.info('using %s reactor' % reactor_name) from twisted.internet import reactor from twisted.web import resource from twisted.web import server from twisted.web import static # import orbited.system if 'INDEX' in config.map['[static]']: root = static.File(config.map['[static]']['INDEX']) else: root = resource.Resource() static_files = static.File(os.path.join(os.path.dirname(__file__), 'static')) root.putChild('static', static_files) # Note: hard coding timeout to 120. site = server.Site(root, timeout=120) from proxy import ProxyFactory from csp_twisted import CometPort reactor.listenWith(CometPort, factory=ProxyFactory(), resource=root, childName='csp') _setup_static(root, config.map) start_listening(site, config.map, logger) # switch uid and gid to configured user and group. if os.name == 'posix' and os.getuid() == 0: user = config.map['[global]'].get('user') group = config.map['[global]'].get('group') if user: import pwd import grp try: pw = pwd.getpwnam(user) uid = pw.pw_uid if group: gr = grp.getgrnam(group) gid = gr.gr_gid else: gid = pw.pw_gid gr = grp.getgrgid(gid) group = gr.gr_name except Exception, e: logger.error('Aborting; Unknown user or group: %s' % e) sys.exit(1) logger.info('switching to user %s (uid=%d) and group %s (gid=%d)' % (user, uid, group, gid)) os.setgid(gid) os.setuid(uid) else: logger.error('Aborting; You must define a user (and optionally a group) in the configuration file.') sys.exit(1)
exit(0) if len(sys.argv) > 2: speed = float(sys.argv[2]) if len(sys.argv) > 3: trim = float(sys.argv[3]) fn = sys.argv[1] print "Loading motion from",fn traj = Trajectory() traj.load(fn) if len(traj.milestones[0]) != 14: print "Error loading arms trajectory, size is not 14" #simple motion setup config.setup(parse_sys=False) motion.robot.startup() try: if trim == 0: print "Moving to start, 20%% speed..." else: print "Moving to config at time %f, 20%% speed..."%(trim,) motion.robot.arms_mq.setRamp(traj.eval(trim),speed=0.2) while motion.robot.arms_mq.moving(): time.sleep(0.1) print "Starting motion..." """ #this is direct interpolation in Python at 50 Hz t0 = time.time() while time.time()-t0 < traj.times[-1]/speed:
def setUp(self): utils.logger.info("TESTCASE =====> %s <===== START" % CASENAME) config.setup(CASENAME) config.prepareSrc(CASENAME, SRCPKG)
maintainer_email="*****@*****.**", url="https://github.com/lsbardel/ccy", license="BSD", long_description=config.read(os.path.join(b, 'README.rst')), packages=find_packages(include=['ccy', 'ccy.*']), install_requires=config.requirements(os.path.join(b, 'requirements.txt')), zip_safe=False, test_suite="tests.suite", classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Plugins', 'Intended Audience :: Developers', 'Intended Audience :: Financial and Insurance Industry', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Office/Business :: Financial', 'Topic :: Utilities' ] ) if __name__ == '__main__': setup(**config.setup(meta, 'ccy'))
#!/usr/bin/python # # -*- coding: utf-8 -*- # vim: set ts=4 sw=4 et sts=4 ai: """Module for creating and editing Event objects.""" import config config.setup() # AppEngine Imports from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app # Third Party imports import aeoid.middleware class AdminEvents(webapp.RequestHandler): """Handler for creating and editing Event objects.""" def get(self, key=None): self.redirect('/events') application = webapp.WSGIApplication( [('/events/admin', AdminEvents)], debug=True) application = aeoid.middleware.AeoidMiddleware(application)
from config import setup class MainWindow(pyglet.window.Window): def __init__(self, config, width=1280, height=720): super(MainWindow, self).__init__(width, height) self.layout = config.get_layout(self) root = config.get_root(self) self.layout.set_root(root) self.controller = self.layout.get_controller() def on_draw(self): print "draw" self.clear() self.layout.draw() def on_text_motion(self, motion): print "here" self.controller.process_motion(motion) self.flip() def on_key_press(self, symbol, modifiers): print symbol self.controller.process_key_press(symbol, modifiers) self.flip() if __name__ == "__main__": cfg = setup(sys.argv) window = MainWindow(cfg) pyglet.app.run()