Example #1
0
 def __init__(self):
     self.util = Util()
     self.log = Logger()
     self.block_size = 8
     self.circle_radius = self.block_size * 5
     self.qrcode_img_name_prefix = "qrcode"
     self.qrcode_img_name_surffix = ".png"
Example #2
0
    def __init__(self):
        super().__init__()

        # Load Config
        self.configPath = "config.yml"
        with open(self.configPath, "r") as config:
            self.cfg = yaml.load(config)

        # Inti default variables.
        self.requests = True
        self.auto_shutdown = False
        self.voiceClient = None
        self.info_channel = None
        self.stream_player = None
        self.is_playing = False
        self.playlist = list()
        self.skip_list = list()
        self.role = None
        self.log = Logger("logs/")
        self.conditions = asyncio.Condition()
        self.queue = music.Playlist()
        self.__version__ = '2.8.2'

        # Get the settings from the config.
        self.skips = self.cfg['ReqSkips']
        self.p = self.cfg['Prefix']
        self.volume = self.cfg['Volume']
        self.allowedLinks = self._load_allowed_sites()
        self._load_opus()
        self.__start_bot(self.cfg['Token'], bot=True)
Example #3
0
    def onLOAD(self, verify=False):
        """E.onLOAD(verify=False)

        Load the Environment. Load the configuration and logging
        components. If verify=True, verify the Environment first.
        """

        if verify:
            self.send(Verify(), "verify", self.channel)

        os.chdir(self.path)

        # Create Config Component
        configfile = os.path.join(self.path, "conf", "%s.ini" % self.envname)
        self.config = Config(configfile)
        self.manager += self.config
        self.send(LoadConfig(), "load", "config")

        # Create Logger Component
        logname = self.envname
        logtype = self.config.get("logging", "type", "file")
        loglevel = self.config.get("logging", "level", "INFO")
        logfile = self.config.get("logging", "file", "/dev/null")
        logfile = logfile % {"name": self.envname}
        if not os.path.isabs(logfile):
            logfile = os.path.join(self.path, logfile)
        self.log = Logger(logfile, logname, logtype, loglevel)
        self.manager += self.log

        self.send(Loaded(), "loaded", self.channel)
Example #4
0
def main():
    # Create Model, Criterion and State
    model, criterion, state = create_model(args)
    print("=> Model and criterion are ready")

    # Create Dataloader
    if not args.test_only:
        train_loader = get_train_loader(args)
    val_loader = get_test_loader(args)
    print("=> Dataloaders are ready")

    # Create Logger
    logger = Logger(args, state)
    print("=> Logger is ready")  # Create Trainer
    trainer = Trainer(args, model, criterion, logger)
    print("=> Trainer is ready")

    if args.test_only:
        test_summary = trainer.test(0, val_loader)
        print("- Test:  Acc %6.3f " % (test_summary['acc']))
    else:
        start_epoch = logger.state['epoch'] + 1
        print("=> Start training")
        # test_summary = trainer.test(0, val_loader)

        for epoch in range(start_epoch, args.n_epochs + 1):
            train_summary = trainer.train(epoch, train_loader)
            test_summary = trainer.test(epoch, val_loader)

            logger.record(epoch, train_summary, test_summary, model)

        logger.final_print()
    def __init__(self,
                 db,
                 ip_address,
                 nat_type,
                 testnet=False,
                 relaying=False):
        """
        Initialize the new protocol with the connection handler factory.

        Args:
                ip_address: a `tuple` of the (ip address, port) of ths node.
        """
        self.ip_address = ip_address
        self.testnet = testnet
        self.ws = None
        self.blockchain = None
        self.processors = []
        self.relay_node = None
        self.nat_type = nat_type
        self.vendors = db.vendors.get_vendors()
        self.ban_score = BanScore(self)
        self.factory = self.ConnHandlerFactory(self.processors, nat_type,
                                               self.relay_node, self.ban_score)
        self.log = Logger(system=self)
        self.keep_alive_loop = LoopingCall(self.keep_alive)
        self.keep_alive_loop.start(30, now=False)
        ConnectionMultiplexer.__init__(self,
                                       CryptoConnectionFactory(self.factory),
                                       self.ip_address[0], relaying)
Example #6
0
class Spawn:
    Log = Logger('Spawn')

    def __init__(self, argv, cb, *cb_data):
        self.Log.i('cmd = %s' % str(argv))
        self.cmd = argv
        self.exited = False
        flags = (GLib.SPAWN_SEARCH_PATH | GLib.SPAWN_DO_NOT_REAP_CHILD)
        self.pid, stdin, stdout, stderr = GLib.spawn_async(argv, flags=flags)
        self.cb = cb
        self.cb_data = cb_data

        def cb(pid, status, ref):
            spawn = ref()
            if spawn:
                spawn.watch(pid, status)

        self.tag = GLib.child_watch_add(self.pid, cb, weakref.ref(self))

    def watch(self, pid, status):
        self.Log.i('cmd = %s was exited with %d' % (str(self.cmd), status))
        self.exited = True
        self.cb(pid, status, *self.cb_data)

    def __del__(self):
        if not self.exited:
            self.Log.w('cmd = %s is still alive. try to terminate' %
                       (str(self.cmd)))
            try:
                os.kill(self.pid, signal.SIGTERM)
                os.kill(self.pid, signal.SIGKILL)
            except OSError:
                pass
            self.cb(self.pid, 255, *self.cb_data)
        GLib.source_remove(self.tag)
Example #7
0
def getVoucherUrl(driver, waitJobid, ticketPlatform, ticketNum):
    # Load logger
    voucherlogger = Logger(ticketPlatform,
                           waitJobid,
                           botid='1',
                           method='wait_voucher',
                           logger='waitVoucher').getlog()
    voucherlogger.info("wait_vocher jobid=" + waitJobid)
    voucherlogger.info("order ticketplatform=" + ticketPlatform)
    voucherlogger.info("wait_vocher ticketNumber=" + ticketNum)

    singleorderurl = 'http://www.travelmart.com.cn/singleOrder.asp?id='
    try:
        driver.get(singleorderurl + ticketNum)
    except:
        voucherlogger.error("Don't open singleorderurl")
        return False
    try:
        voucherurl = driver.find_element_by_link_text('查看打印凭证').get_attribute(
            'href')
    except:
        voucherlogger.error("[Voucherurl] don't find element")
        return False

    return voucherurl
Example #8
0
 def _init_post(self):
     """
     once below two are initialized, it will be locked by thread and thus cannot be pickled.
     Need to initialize later.
     """
     logName = self.__class__.__name__ + self.logAppendName
     self.log = Logger(logName, level=ENV.MODEL_LOG_LEVEL.value).logger
     self.evlEngine = EvlTimeExpEngine(logAppendName=self.logAppendName)
Example #9
0
    def insert_database_from_dic(self, score, text):
        # conn = Database()
        if not re.findall("\d+", score['course_score']):
            return

        conn = self.conn
        con = conn.cursor()
        # parms = [score['学号'],score['课程序号'],score['课程代码'],score['课程名称'],score['课程类别'],score['学分'],score['总评'],score['最终'],score['绩点']]
        parms = (score[k] for k in score if score[k] is not None)
        try:
            # insert.insert_from_dic(conn,'new_stu_score',score)
            check_sql = "select * from score where username='******' and course_code='%s'" % (
                self.__username, score['course_code'])
            # print(check_sql)
            rs = con.execute(check_sql)
            # if rs>0:
            #     score = con.fetchone()[5]
            #     if score != parms[5]:
            #         sql = "replace into VALUES ('{0}','{1}','{2}','{3}','{4}','{5}')".format(parms)
            #         con.execute(sql)

            if rs <= 0:
                sql = """insert into score (
                semester,username,course_id,course_code,course_evaluation,course_score)
                VALUES ('{0}','{1}','{2}','{3}','{4}','{5}')""".format(*parms)
                con.execute(sql)
                return True
            else:
                course_score = con.fetchone()[5]
                # print(course_score)
                # print(score)
                if course_score != float(score['course_score']):
                    sql = """replace into score (
                semester,username,course_id,course_code,course_evaluation,course_score)
                VALUES ('{0}','{1}','{2}','{3}','{4}','{5}')""".format(*parms)
                    con.execute(sql)
                return False
        except Exception as e:
            traceback.print_exc()
            log = Logger('all.log', level='info')
            log.logger.debug(e)
            Logger('debug.log', level='debug').logger.warning(str(e) + text)
            return False
        finally:
            # conn.commit()
            con.close()
Example #10
0
 def __init__(self):
     self.httpRequest = HttpRequest()
     self.httpParser = HttpParser()
     self.redisConn = RedisConnect()
     self.logger = Logger()
     self.user_file = open("/opt_c/dianping/file/user_urls_4.txt", "a")
     #self.mysqlConn = MysqlClient("127.0.0.1","root","homelink",'dianping',3306)
     self.mysqlConn = MysqlPool()
Example #11
0
    def __init__(self):
        self.smtp.debuglevel = 1
        self.smtp.connect(host="smtp.qq.com")
        self.sender = '*****@*****.**'
        self.smtp.login(self.sender, "oiwtvumjgjndjcbb")
        self.logger = Logger()

        self.logger.info(f'正在登录 {self.sender} ...', if_print=True)
Example #12
0
 def __init__(self, processors, active_connections, *args, **kwargs):
     super(OpenBazaarProtocol.ConnHandler,
           self).__init__(*args, **kwargs)
     self.log = Logger(system=self)
     self.processors = processors
     self.active_connections = active_connections
     self.connection = None
     self.node = None
Example #13
0
 def __init__(self, stop_times, vehicle_2_stops_times, trips,
              logger_verbosity):
     self._logger = Logger(logger_verbosity)
     self._stop_times = stop_times
     self._vehicle_2_stops_times = vehicle_2_stops_times
     self._vehicles = list(vehicle_2_stops_times.keys())
     self._trips = trips
     self._all_trip_ids = list(map(lambda t: t.id, self._trips))
Example #14
0
 def __init__(self):
     self.httpRequest = HttpRequest()
     self.httpParser = HttpParser()
     self.redisConn = RedisConnect()
     self.start_url = "http://www.dianping.com/shopall/2/0"
     self.logger = Logger()
     #	self.mysqlConn = MysqlClient("127.0.0.1","root","homelink",'dianping',3306)
     self.mysqlConn = MysqlPool()
     self.store_file = open("/opt_c/dianping/file/store_urls.txt", "a")
 def __init__(self,
              node_id: int,
              working_group: set,
              initializer_id: int = -1):
     super().__init__(node_id, working_group, initializer_id)
     # wait
     self.__log = Logger('ParaServer'.format(node_id), log_to_file=True)
     self.__done: [bool] = False
     self.__transfer: [ITransfer] = None
Example #16
0
class Player:
    Log = Logger('player')

    def __init__(self, filename):
        cmd = 'play', filename
        self.proc = Spawn(cmd, self.watch)

    def watch(self, pid, status):
        self.Log.i('player is exited with %s' % status)
Example #17
0
 def __init__(self):
     """
     initializes the command catalog
     """
     self._catalog = {}
     self._features = {}
     self._log = Logger("CMD")
     Command.LOG = self._log
     self.import_commands()
Example #18
0
def dns_discovery(testnet=False):
    log = Logger(system="Discovery")
    addrs = []
    for seed in TESTNET3_SEEDS if testnet else MAINNET_SEEDS:
        answers = dns.resolver.query(seed)
        for addr in answers:
            addrs.append((str(addr), 18333 if testnet else 8333))
    log.info("DNS discovery returned %s peers" % len(addrs))
    return addrs
Example #19
0
    def __init__(self, handler: TargetHandler):
        """
        :param handler: An instance of the TargetHandler class, used to
            manage the position estimates.
        """
        self.north_start = None
        self.east_start = None
        self.down_start = None
        self.loc = None
        self.attitude = None
        self.poll_delay = 0
        self.currentTime = self.previousTime = self.start_time = 0
        self.positioning = PositionAggregator(handler)
        self.simplePosition = None
        self.missLimit = 1000
        # Connect to the Vehicle
        print(f'Connecting to vehicle on: {ARDUPILOT_CONNECTION}')
        self.vehicle = connect(ARDUPILOT_CONNECTION, wait_ready=True)
        while not self.vehicle.is_armable:
            print("Initializing ...")
            time.sleep(1)

        self.Z_control = Controller(kp=0.5,
                                    ki=0.2,
                                    kd=0.4,
                                    target=0,
                                    lower_limit=-.15,
                                    upper_limit=1,
                                    update_rate=0.01,
                                    scalar=0)
        self.X_control = Controller(kp=0.105,
                                    ki=0.005,
                                    kd=0.055,
                                    target=0.0,
                                    lower_limit=-1,
                                    upper_limit=1,
                                    update_rate=0.01,
                                    scalar=0)
        self.Y_control = Controller(kp=0.105,
                                    ki=0.005,
                                    kd=0.055,
                                    target=0.0,
                                    lower_limit=-1,
                                    upper_limit=1,
                                    update_rate=0.01,
                                    scalar=0)
        self.landed = False
        self.waiting = True

        # logging
        self.logging = Logger("Drone_Control_Log.csv", [
            "Time", "Mode", "Roll", "Pitch", "Z Relative distance",
            "Y Relative Distance", "X Relative Distance", "Z Velocity Input",
            "Y Velocity Input", "X Velocity Input", "Z Absolute Variance",
            "Y Absolute Variance", "X Absolute Variance"
        ])
Example #20
0
 def __init__(self, caller, confpath, **kwargs):
     self.logger = Logger(str(self.__class__))
     self._filename = '/etc/argo-egi-connectors/customer.conf' if not confpath else confpath
     if not kwargs:
         self._jobattrs = self._defjobattrs[os.path.basename(caller)]
     else:
         if 'jobattrs' in kwargs.keys():
             self._jobattrs = kwargs['jobattrs']
         if 'custattrs' in kwargs.keys():
             self._custattrs = kwargs['custattrs']
Example #21
0
 def __init__(self, configDict, problemSpecs):
     self.configDict = configDict
     self.problemSpecs = problemSpecs
     self.evalsLeft = self.configDict["numEvals"]
     self.solutionGen = SolutionGenerator(self.problemSpecs)
     self.solutionTracker = SolutionTracker()
     self.logger = Logger(self.configDict)
     self.problemSpecs["maxSheetLength"] = self.solutionGen.problemSpecs[
         "maxSheetLength"]
     self.population = self._initializePopulation()
Example #22
0
 def __init__(self):
     self._logger = Logger(__file__)
     #profile = FirefoxProfile()
     #profile.set_preference('dom.ipc.plugins.enabled.libflashplayer.so', 'false')
     #self._browser = webdriver.Firefox(profile)
     self._browser = webdriver.Firefox()
     self.baidu = Baidu(self._browser)
     self.map = BaiduMap()
     self.ak = "sh0wDYRg1LnB5OYTefZcuHu3zwuoFeOy"
     self.table = Tables();
Example #23
0
 def __init__(self):
     self.headers = {
         'User-Agent':
         'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.4620.400 QQBrowser/9.7.13014.400'
     }
     self.redis = StrictRedis(host='localhost',
                              port=6379,
                              db=0,
                              password='******')
     self.logyc = Logger('yc.log')
    def __init__(self, tx, testnet=False):
        """
        Create a new transaction

        Args:
            tx: a `CMutableTransaction` object
        """
        SelectParams("testnet" if testnet else "mainnet")
        self.tx = tx
        self.log = Logger(system=self)
Example #25
0
 def __init__(self, home='/home/ec2-user/CpGPython/', **params):
     tf.logging.set_verbosity(tf.logging.WARN)
     self.home = home
     log_dir = home + 'logs/'
     self.logger = Logger.Logger(log_dir, False).get_logger()
     self.tensorboard_log = home + 'tensor_logs/' + datetime.utcnow(
     ).strftime("%Y%m%d%H%M%S")
     self.params = params
     self.scoring = self.params[
         'scoring'] if 'scoring' in params else 'precision'
Example #26
0
    def __init__(self, argv):
        logger = Logger().logger
        self.appConfig = AppConfig(logger)
        self.logger = logger
        self.quitting = False
        self.handling_events = False
        self.accounts = {}

        self.logger.debug("Creating the Endpoint")
        self.endpoint = Endpoint(self)
Example #27
0
 def __init__(self, sourceNode, storage, ksize):
     self.ksize = ksize
     self.router = RoutingTable(self, ksize, sourceNode)
     self.storage = storage
     self.sourceNode = sourceNode
     self.multiplexer = None
     self.log = Logger(system=self)
     self.handled_commands = [
         PING, STUN, STORE, DELETE, FIND_NODE, FIND_VALUE, HOLE_PUNCH
     ]
     RPCProtocol.__init__(self, sourceNode.getProto(), self.router)
    def __init__(self, db):
        self.db = db
        self.server = 'localhost:25'
        self.sender = 'OpenBazaar'
        self.recipient = ''
        self.username = None
        self.password = None

        self.log = Logger(system=self)

        self.get_smtp_settings()
Example #29
0
 def __init__(self, node_proto, router, signing_key, database):
     self.router = router
     RPCProtocol.__init__(self, node_proto, router)
     self.log = Logger(system=self)
     self.multiplexer = None
     self.db = database
     self.signing_key = signing_key
     self.listeners = []
     self.handled_commands = [GET_CONTRACT, GET_IMAGE, GET_PROFILE, GET_LISTINGS, GET_USER_METADATA,
                              GET_CONTRACT_METADATA, FOLLOW, UNFOLLOW, GET_FOLLOWERS, GET_FOLLOWING,
                              NOTIFY, MESSAGE, ORDER, ORDER_CONFIRMATION, COMPLETE_ORDER]
Example #30
0
    def __init__(self):
        if not common.file_exist(common.CONST_DIR_LOG):
            common.create_directory(common.CONST_DIR_LOG)

        if not common.file_exist(common.CONST_DIR_CONF):
            common.create_directory(common.CONST_DIR_CONF)

        if not common.file_exist(common.CONST_DIR_DATABASE):
            common.create_directory(common.CONST_DIR_DATABASE)

        self.log = Logger(trader_log_filename, level='debug')