def __init__(self, name, config={}): self.name = name self.config = Configure(config) self.__init_local_and_global() self.__init_logger() self.__init_broker_and_processors() self.__init_runtime_tree_storage()
def __init__(self): self.configure = Configure() liveContainers = {} self.cgroups={} self.host = None self.isRunning = False self.lastCurrent = 0 ##manager live contianers and update parameters self.liveContainerManager = None ##default heatbeat interval(s) self.heartbeatInterval = 5 ##remote name server proxy self.remoteNameServer = None ##remote name server host address self.remoteNameServerHost = "" ##remote name server host port self.remoteNameServerPort = 0000 ##remote name server object ID self.remoteNameServerID = "container.master"
def run_sprinkler(flag): # Get configuration data config = Configure() section = 'SPConfig' pin = int(config.read(section, 'pin')) sp_timer = float(config.read(section, 'pihouse/sprinkler/timer')) # Turn pin on print('Starting sprinkler') GPIO.output(pin, GPIO.HIGH) os.environ["sp_status"] = "True" config.set('SPConfig', 'pihouse/sprinkler/schedule/last', str(datetime.datetime.now().strftime('%H:%M, %a %d/%m/%y'))) # If flag changes then turn off, otherwise run for config time timer = time() + sp_timer * 60 while time() < timer: if flag == "False": print('Stopping sprinkler (button)') GPIO.output(pin, GPIO.LOW) os.environ["sp_status"] = "False" break else: sleep(0.1) flag = os.environ.get('sp_ctl') else: print('Stopping sprinkler (timer)') GPIO.output(pin, GPIO.LOW) os.environ["sp_status"] = "False"
def __init__(self): #config database self.configure = Configure() dbpath = (self.configure.getDBPath())[1:-1] print "dbpath ", dbpath self.cx = sq.connect(dbpath) self.cu = self.cx.cursor()
def clear(): config_file = "configures/config.cfg" configure = Configure(config_file) db_path = configure.get_attribute('main', 'db_path') db_name = configure.get_attribute('main', 'db_name') db = Db(db_path, db_name) db.clear_table("Pulses") db.clear_table("Indicators")
def config_prepare(): if path.exists('config.json'): return json.load(open('config.json', 'r', encoding='UTF-8')) else: from configure import Configure Configure().run() return None
def load_models(self, dir: str): conf = Configure() conf.get_conf() board_conf_str = "{0}_{1}".format(conf.conf_dict["board_size"], conf.conf_dict["n_in_a_row"]) model_path = pathlib.Path(dir) / board_conf_str model_path.mkdir(parents=True, exist_ok=True) self.all_model_path = sorted(item for item in model_path.glob('*/') if item.is_dir()) self.all_model_name = [path.name for path in self.all_model_path]
def __init__(self): self.configure = Configure() self.configure.init('PicParser') #get width max_width = self.configure.getint('max_width') max_height = self.configure.getint('max_height') self.__maxsize = (max_width, max_height) print 'get maxsize', self.__maxsize #压缩的尺寸 self.__compressed_size = None
def main(): configure = Configure("config.ini") i_m = InputManager(configure) # モデルの読み込み or 新規作成 bayes = prep_model(i_m.can_load_model(), i_m.load_path) # 学習 or 推論 bayes = train_or_predict(bayes, i_m.targets, i_m.sents, i_m.is_train) # モデルの保存 with open(i_m.save_path, "wb") as f: pickle.dump(bayes, f)
def __init__(self, configure_filename): """ Инициализация класса :param configure_filename - путь к конфигурационному файлу """ self.configure = Configure(configure_filename) self.task_factory = TaskFactory() self.task_factory.register_task_creator(HttpTask) self.task_factory.register_task_creator(HttpsTask) self.logger = LoggerFactory.create_logger(queue=last_record_queue, **self.configure.logger)
def handle_args(): args = get_args() if args.configure: from configure import Configure Configure(False).run() elif args.no_update: DataHandler(config['token']).run(config['delta']) elif args.construct: DataHandler(config['token']).make_video() else: MainHandler(config['token']).run()
def start(): conf = Configure() conf.get_conf() def player_init(player_selected, name): if player_selected == 1: return Human(name=name) elif player_selected == 2: search_times, greedy_value = set_AI_conf(search_times=2000, greedy_value=5.0) return AI_MCTS(name=name, search_times=search_times, greedy_value=greedy_value, is_output_analysis=conf.conf_dict["AI_is_output_analysis"]) elif player_selected == 3: network = select_network() search_times, greedy_value = set_AI_conf(search_times=400, greedy_value=5.0) return AI_MCTS_Net(name=name, policy_value_function=network.predict, board_to_xlabel=network.board_to_xlabel, is_training=False, search_times=search_times, greedy_value=greedy_value, is_output_analysis=conf.conf_dict["AI_is_output_analysis"]) player1_selected, name1 = select_player("Please input first player. Press <Ctrl-C> to end\n" "1: Human\n" "2: AI with pure Monte Carlo tree search\n" "3: AI with Monte Carlo tree search & neural network\n" ": ", allowed_input=[1, 2, 3]) player1 = player_init(player1_selected, name1) player2_selected, name2 = select_player("Please input second player. Press <Ctrl-C> to end\n" "1: Human\n" "2: AI with pure Monte Carlo tree search\n" "3: AI with Monte Carlo tree search & neural network\n" ": ", allowed_input=[1, 2, 3]) player2 = player_init(player2_selected, name2) console_renderer = ConsoleRenderer() print("############### Game Start ###############") winner = Game.start_until_game_over(player1, player2, board_renderer=console_renderer) if winner == BOARD.o: print("Congrats! \"O\" wins.") elif winner == BOARD.x: print("Congrats! \"X\" wins.") else: print("Draw!") print("############### Game Over ###############")
def __init__(self): conf = Configure(sys.argv) conf.username = "******" # 选手自己的用户名 conf.password = "******" # 选手自己的密码 # 单机版推演系统,变量初始化:room_id固定为1 self._sdk = CSFInterface(conf.ip, conf.room_id, conf.camp_id, conf.scenario_id, conf.seat_id) self._init_failed = False self._scenario = None self._camp_id = None self._seat_ids = None self._war_map = None self._logger = Logger("ai_1") self._fetch_scenario_finish = False self._seat_ids = [] self._round = 1 for seat_id in conf.seat_id.split(','): self._seat_ids.append(int(seat_id)) self._camp_id = conf.camp_id self._game_started = False # 创建AI算法对象 self._algorithm = AIAlgorithm(self._sdk, self._scenario, conf.camp_id, conf.scenario_id) self._algorithm.set_logger(self._logger) self._algorithm.set_seat_ids(self._seat_ids) self.df_operator = None self.df_formation = None self.operator_information_original = [] # self.operator_list = [] self._row = 0 self._col = 0 self._update_operator = UpdateOperator(self._scenario) self._cal_map = Hex(self._row, self._col) self._graph = None # 注册回调函数 self._sdk.register(self._call_back) # AI登录 print(conf.username, conf.password) self._login_result = self._sdk.login(conf.username, conf.password) print("_login_result:{}".format(self._login_result)) if self._login_result != 0: self._init_failed = True self._logger.print(self._round, "AI1 登陆失败") return
import os from time import sleep import paho.mqtt.client as mqtt import sprinkler from configure import Configure import RPi.GPIO as GPIO import cron, datetime global config config = Configure() def on_connect(client, userdata, flags, rc): print("Connected with result code " + str(rc)) subscriptions = config.read('MQTTConfig', 'subscriptions') subscriptions = subscriptions.split(',') for topic in subscriptions: client.subscribe(topic) print("Subscribed to " + topic) def on_message(client, userdata, msg): topic = msg.topic payload_decode = str(msg.payload.decode("utf-8")) print(topic + ": " + payload_decode) if topic == 'pihouse/sprinkler/control': if payload_decode == "True":
log_dir = 'log_dir' if not os.path.exists(configures.log_dir) or not hasattr( configures, log_dir): print('log fold not found, creating...') os.mkdir(configures.log_dir) if __name__ == '__main__': parser = argparse.ArgumentParser( description='Entity extractor by binary tagging') parser.add_argument('--config_file', default='system.config', help='Configuration File') args = parser.parse_args() device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') configs = Configure(config_file=args.config_file) fold_check(configs) logger = get_logger(configs.log_dir) configs.show_data_summary(logger) mode = configs.mode.lower() if mode == 'train': logger.info('mode: train') train(configs, device, logger) elif mode == 'interactive_predict': logger.info('mode: predict_one') tokenizer = BertTokenizer.from_pretrained('bert-base-chinese') bert_model = BertModel.from_pretrained('bert-base-chinese').to(device) num_labels = len(configs.class_name) model = Model(hidden_size=768, num_labels=num_labels).to(device) model.load_state_dict( torch.load(os.path.join(configs.checkpoints_dir,
def main(): text = get_configure() if text is not None: c = Configure(text) c.run()
def test_should_create_nucleotide_from_given_jsonfile(self): configure = Configure('test.json') dna = get_a_dna_with_some_structure() nucleotide = Nucleotide(dna.structure) self.assertEquals(configure.nucleotide, nucleotide)
def __init__(self): """Here, all commandline arguments are checked and used.""" # Check if enough commandline args are given if len(sys.argv) is 1: print("python main.py <1, 2, 3> <algorithm> <iterations>") sys.exit() else: # Check if neighbourhood input is correct if sys.argv[1] in ["1", "2", "3"]: self.input = int(sys.argv[1]) neighbourhood = self.input else: print("please insert either a valid neighbourhood number " "as 1st argument") print("select from: 1, 2, 3") sys.exit(2) # If user wants plots if "plot" in sys.argv: plot = "y" else: plot = "n" # Check if correct algorithm is given in third argument if sys.argv[2] in [ "stepdown", "greedy", "hill", "dfs", "random", "bnb" ]: algorithm = sys.argv[2] cluster_option = None if sys.argv[2] in ["stepdown", "dfs", "bnb"]: iterations = 0 # Initialize n iterations, if any elif len(sys.argv) > 3 and sys.argv[3].isnumeric(): iterations = int(sys.argv[3]) else: print("No #iteration given, will be set to 1000") iterations = 1000 # Call cluster algorithm if ("cluster" in sys.argv) and not ("configure" in sys.argv): cluster = Cluster(neighbourhood) min_cost = 999999 index = 0 # Find cheapest positions for battery for i in cluster.options_list: print(f"Checking option {i}...") smart = Smartgrid(neighbourhood, "greedy", 1000, "n", i, "cluster") if smart.cost < min_cost: file = smart.pickle_file min_cost = smart.cost index = i # Call specified algorithm for cheapest option Smartgrid(neighbourhood, algorithm, iterations, "n", index, "cluster") time_var = time.strftime("%d%m%Y") file = os.path.join(*[ cwd, 'results', f"wijk_{self.input}", algorithm, "cluster", f"{algorithm}_lowest_WIJK{self.input}" + f"_{time_var}.dat" ]) # Load pickle so cheapest option can be plotted load_pickle(self, file) sys.exit() # If not cluster, use configure and find cheapest configuration # for this neighbourhood elif ("configure" in sys.argv) and not ("cluster" in sys.argv): # Calculate configurations Configure(neighbourhood) # First test so lowest configuration is saved Weights(neighbourhood, "test", iterations, "configure") # Run algorithm on lowest solution Weights(neighbourhood, algorithm, iterations, "configure") sys.exit() # Else algorithm argument was incorrect else: print("please insert the preferred algorithm as 2nd argument") print("select from: \"stepdown\", \"greedy\", \"hill\", " "\"cluster\", \"configure\", \"random\"") sys.exit(2) # No cluster or configure, so use fixed battery locations Smartgrid(neighbourhood, algorithm, iterations, plot, cluster_option, "fixed")
from queue import Queue from client_kinect import ClientKinectSocket from config_recv_socket import ConfigReceiveSocket from configure import Configure from frame_segment_udp import FrameSegment from kinect_worker import KinectWorker from udp_mesh_socket import UdpMeshSocket if __name__ == "__main__": configure = Configure() image_queue = Queue() detect_queue = Queue() udp_mesh_client = UdpMeshSocket(configure=configure) config_recv_client = ConfigReceiveSocket(configure=configure) clientKinectSocket = ClientKinectSocket(configure=configure) frameSegment = FrameSegment(configure=configure, image_queue=image_queue) clientKinectSocket.start() frameSegment.start() config_recv_client.start() udp_mesh_client.start() kinect_worker = KinectWorker(configure=configure, image_queue=image_queue, detect_queue=detect_queue) kinect_worker.run()
import numpy as np from Game.BoardRenderer import BoardRenderer from Function import coordinates_set from configure import Configure conf = Configure() conf.get_conf() # Fixed Configuration. o = conf.conf_dict["o"] x = conf.conf_dict["x"] empty = conf.conf_dict["empty"] # Changeable Configuration. n_in_a_row = conf.conf_dict["n_in_a_row"] # How many pieces in a row. o_win = n_in_a_row x_win = -n_in_a_row start_player = conf.conf_dict["start_player"] # start player board_size = conf.conf_dict["board_size"] # The size of the board. class Board: def __init__(self): self.board = np.zeros((board_size, board_size)) self.available_actions = coordinates_set(board_size, board_size) self.last_action = None # Last move. self.current_player = start_player # current player def __copy__(self): new_board = Board()
from configure import Configure c = Configure("./config.ini") # c.write('global', 'test', 'a') # print(c.read('global', 'test2', 'def')) c.read_float('glo', 'test6', 4)
coinObj[9].placeItem(gridObj.getMatrix(), 4, 285) coinObj[10].placeItem(gridObj.getMatrix(), 12, 315) coinObj[11].placeItem(gridObj.getMatrix(), 20, 345) coinObj[12].placeItem(gridObj.getMatrix(), 8, 375) coinObj[13].placeItem(gridObj.getMatrix(), 4, 405) coinObj[14].placeItem(gridObj.getMatrix(), 20, 405) coinObj[15].placeItem(gridObj.getMatrix(), 16, 440) speedUps() dragonObj = Dragon() dragonObj.placeItem(gridObj.getMatrix(), 10, 459) T = time.time() configObj = Configure() speedfactor = 1 configObj.setStart(0) gravity = 0.5 remainingTime = 0 def incrementSpeed(): global speedfactor speedfactor = speedfactor + 1 def resetSpeed(): global speedfactor speedfactor = 1
def select_model(dir: str, is_training=False, specified_model_name=""): """ 选择想要使用或训练的网络模型。 Select the network model you want to use or train. :param dir: 网络模型目录。 Network model directory. :param is_training: 是否训练。 Whether to train. :param specified_model_name: 指定想要选择的模型。 Specify the model you want to select. :return: (<bool>, <str>, <str>) 是否是新的网络模型,和网络模型路径,网络模型记录路径。 Whether it is a new network model, and the network model path, and the network model record path. """ conf = Configure() conf.get_conf() board_conf_str = "{0}_{1}".format(conf.conf_dict["board_size"], conf.conf_dict["n_in_a_row"]) model_path = pathlib.Path(dir) model_path = model_path / board_conf_str model_path.mkdir(parents=True, exist_ok=True) all_model_path = sorted(item for item in model_path.glob('*/') if item.is_dir()) all_model_name = [path.name for path in all_model_path] if len(specified_model_name) != 0: model_path = model_path / specified_model_name model_path.mkdir(parents=True, exist_ok=True) model_record_path = model_path / "latest.h5" is_new_model = True if model_record_path.exists(): is_new_model = False return is_new_model, str(model_path) + "/", str(model_record_path) if is_training: print( "请选择想要训练的网络模型。按 <Ctrl-C> 退出。\n" "Please select the network model you want to train. Press <Ctrl-C> to exit." ) print("0: 创建新的网络模型。 Create a new network model.") else: print( "请选择想要使用的网络模型。按 <Ctrl-C> 退出。\n" "Please select the network model you want to use. Press <Ctrl-C> to exit." ) for i, one_model_name in enumerate(all_model_name): print("{0}: {1}".format(i + 1, one_model_name)) model_selected = select(": ", allowed_input=range(0 if is_training else 1, len(all_model_path) + 1)) if model_selected == 0: while True: new_name = input( "请输入新的模型名称。按 <Ctrl-C> 退出。\n" "Please enter a new model name. Press <Ctrl-C> to exit.\n" ": ") if len(new_name) == 0: print("模型名称为空,请重新输入。\n" "Model name is empty, please try again.\n") continue if new_name in all_model_name: print("该模型名称已存在,请重新输入。\n" "The model name already exists, please try again.\n") continue model_path = model_path / new_name model_path.mkdir(parents=True, exist_ok=True) return True, str(model_path) + "/", None else: model_path = all_model_path[model_selected - 1] model_record_path = sorted(item for item in model_path.glob('*.h5')) model_record_name = [path.name[:-3] for path in model_record_path] if is_training: print( "请选择想要训练的模型记录。按 <Ctrl-C> 退出。\n" "Please select the model record you want to train. Press <Ctrl-C> to exit." ) else: print( "请选择想要使用的模型记录。按 <Ctrl-C> 退出。\n" "Please select the model record you want to use. Press <Ctrl-C> to exit." ) for i, one_model_record_name in enumerate(model_record_name): print("{0}: {1}".format(i + 1, one_model_record_name)) model_record_selected = select(": ", allowed_input=range( 1, len(model_record_path) + 1)) return False, str(model_path) + "/", str( model_record_path[model_record_selected - 1])
def __init__(self): self.configure = Configure() dbpath = (self.configure.getDBPath())[1:-1] self.cx = sq.connect(dbpath) self.cu = self.cx.cursor() self.siteID = -1
class Pyro4NameServer: ##default host name for NameServer host = "localhost" ##default host port for NameServer port = 51681 ##default object id for NameServer ID = "pyro4NameServer" ##daemon of NameServer daemon = None ##initialize configure configure = Configure() ##containerTacker, main service implimentation, communicate with slaves ##through heartbeat containerTracker = None def initialize(self): ##initialize configure object if self.configure.initialize() is False: log.error("configure initialize failure") return False ##initialize host name, port and object ID self.host = self.configure.get("nameserverHost") if self.host is None: log.error("host is missing for configure") return False self.port = int(self.configure.get("daemonserverPort")) if self.port is None: log.error("port is missing for configure") return False self.ID = self.configure.get("nameserverID") if self.ID is None: log.error("nameserver ID is missing for configure") return False self.containerTracker = ContainerTracker(self.configure) if self.containerTracker.initialize() is False: log.error("containerTracker initialize failed") return False log.info("name server initialize successfully") return True def start(self): ##start Name Server service try: self.daemon = Pyro4.Daemon(host=self.host,port = self.port) nameServer = Pyro4.locateNS() nameURI = self.daemon.register(self.containerTracker) nameServer.register(self.ID,nameURI) log.info("start pyro4 Name Server") self.daemon.requestLoop() except Exception as error: log.error("error when set up server %s",error) ##start containerTracker main loop self.containerTracker.start() def serviceLoop(self): if self.initialize() is False: log.info("serviceLoop failed due to initialize fail") return self.start() def stop(self): pass
from flask import Flask, render_template, url_for, request import os import sys from subprocess import * # from PIL import Image import datetime import time import json from picture_class import Picture from configure import Configure rover = Configure() # FPV System sys.path.append('hardware_drivers/vision') if rover.config['camera'] == 'raspberry_pi_8mp' or rover.config[ 'camera'] == 'raspberry_pi_5mp': from raspberry_pi_camera import Vision else: print('Error : Rover requires some kind of vision!') exit() # MOTOR System sys.path.append('hardware_drivers/motor') if rover.config['motor'] == 'adafruit_dc_and_stepper_motor_hat': from adafruit_dc_and_stepper_motor_hat import Motor elif rover.config['motor'] == 'raspirobot_board_v3': from raspirobot_board_v3 import Motor else: from immobile_wildlife_cam import Motor
def select_model(dir: str, is_training=False, specified_model_name=""): conf = Configure() conf.get_conf() board_conf_str = "{0}_{1}".format(conf.conf_dict["board_size"], conf.conf_dict["n_in_a_row"]) model_path = pathlib.Path(dir) model_path = model_path / board_conf_str model_path.mkdir(parents=True, exist_ok=True) all_model_path = sorted(item for item in model_path.glob('*/') if item.is_dir()) all_model_name = [path.name for path in all_model_path] if len(specified_model_name) != 0: model_path = model_path / specified_model_name model_path.mkdir(parents=True, exist_ok=True) model_record_path = model_path / "latest.h5" is_new_model = True if model_record_path.exists(): is_new_model = False return is_new_model, str(model_path) + "/", str(model_record_path) if is_training: print( "Please select the network model you want to train. Press <Ctrl-C> to exit." ) print("0: Create a new network model.") else: print( "Please select the network model you want to use. Press <Ctrl-C> to exit." ) for i, one_model_name in enumerate(all_model_name): print("{0}: {1}".format(i + 1, one_model_name)) model_selected = select(": ", allowed_input=range(0 if is_training else 1, len(all_model_path) + 1)) if model_selected == 0: while True: new_name = input( "Please enter a new model name. Press <Ctrl-C> to exit.\n" ": ") if len(new_name) == 0: print("Model name is empty, please try again.\n") continue if new_name in all_model_name: print("The model name already exists, please try again.\n") continue model_path = model_path / new_name model_path.mkdir(parents=True, exist_ok=True) return True, str(model_path) + "/", None else: model_path = all_model_path[model_selected - 1] model_record_path = sorted(item for item in model_path.glob('*.h5')) model_record_name = [path.name[:-3] for path in model_record_path] if is_training: print( "Please select the model record you want to train. Press <Ctrl-C> to exit." ) else: print( "Please select the model record you want to use. Press <Ctrl-C> to exit." ) for i, one_model_record_name in enumerate(model_record_name): print("{0}: {1}".format(i + 1, one_model_record_name)) model_record_selected = select(": ", allowed_input=range( 1, len(model_record_path) + 1)) return False, str(model_path) + "/", str( model_record_path[model_record_selected - 1])
from configure import Configure from dna import DNA import numpy as np from population import Population from population_initializer import PopulationInitializer configure = Configure('data.json') number_of_buckets = configure.data['number_of_buckets'] population_size = configure.data['population_size'] kill_percentage = configure.data['kill_percentage'] mutation_percentage = configure.data['mutation_percentage'] Population.kill_percentage = kill_percentage DNA.mutate_percentage = mutation_percentage nucleotide = configure.nucleotide initializer = PopulationInitializer( nucleotide=nucleotide, number_of_buckets_per_container=number_of_buckets) initial_population = initializer.initialize(population_size) populations = [initial_population] fitness_list = [np.mean(initial_population.fitness)] while True: if len(populations) >= 300 or fitness_list[-1] >= -1: break current_population = populations[-1] next_population = current_population.next_population() next_fitness = np.mean(next_population.fitness) populations.append(next_population) fitness_list.append(next_fitness) for fitness, population in zip(fitness_list, populations): print population.containers[0].dna, fitness
github_repo = 'https://github.com/Brunopvh/coin-qt-gui' __author__ = 'Bruno Chaves' __version__ = '0.1.2' __appname__ = 'coin-qt-gui' __script__ = os.path.realpath(__file__) dir_of_executable = os.path.dirname( __script__) # diretório do arquivo principal dir_of_project = os.path.abspath(os.path.join(dir_of_executable, '..')) # Diretório do projeto sys.path.insert(0, dir_of_executable) from configure import Configure import downloader cfg = Configure(__appname__) class MessageWindow(QWidget): ''' https://doc.qt.io/qtforpython/PySide2/QtWidgets/QMessageBox.html https://stackoverflow.com/questions/40227047/python-pyqt5-how-to-show-an-error-message-with-pyqt5 ''' def __init__(self): super().__init__() self.msgBox = QMessageBox() def msgOK(self, text: str): self.msgBox.setText(text) self.msgBox.exec()