class DecryptionMarkConfig(object): def __init__(self, logger, encryption_environment): self.logger = logger self.encryption_environment = encryption_environment self.command = None self.volume_type = None self.decryption_mark_config = ConfigUtil(self.encryption_environment.azure_decrypt_request_queue_path, 'decryption_request_queue', self.logger) def get_current_command(self): return self.decryption_mark_config.get_config(CommonVariables.EncryptionEncryptionOperationKey) def config_file_exists(self): return self.decryption_mark_config.config_file_exists() def commit(self): key_value_pairs = [] command = ConfigKeyValuePair(CommonVariables.EncryptionEncryptionOperationKey, self.command) key_value_pairs.append(command) volume_type = ConfigKeyValuePair(CommonVariables.EncryptionVolumeTypeKey, self.volume_type) key_value_pairs.append(volume_type) self.decryption_mark_config.save_configs(key_value_pairs) def clear_config(self): try: if(os.path.exists(self.encryption_environment.azure_decrypt_request_queue_path)): os.remove(self.encryption_environment.azure_decrypt_request_queue_path) return True except OSError as e: self.logger.log("Failed to clear_queue with error: {0}, stack trace: {1}".format(e, traceback.format_exc())) return False
async def on_server_join(server): # add the server ID servers = ConfigUtil.add_server(str(server.id), ConfigUtil.get_servers()) # Send welcome embed await client.send_message( ServerUtil.get_general(server), embed=build_welcome_embed(base=EmbedUtil.prep( title="Server Welcome!", description=":::::::::::::::::")))
def __init__(self, logger, encryption_environment): self.logger = logger self.encryption_environment = encryption_environment self.command = None self.volume_type = None self.decryption_mark_config = ConfigUtil( self.encryption_environment.azure_decrypt_request_queue_path, 'decryption_request_queue', self.logger)
def read_col_info(): DbMgr.allColName = ConfigUtil.read_sections(Config.PATH_COL_INFO) col_num = len(DbMgr.allColName) DbMgr.allColDetail = [] for i in range(col_num): cur_section = DbMgr.allColName[i] cur_options = ConfigUtil.read_options(Config.PATH_COL_INFO, cur_section) DbMgr.allColDetail.append(cur_options)
class EncryptionMarkConfig(object): def __init__(self, logger, encryption_environment): self.logger = logger self.encryption_environment = encryption_environment self.command = None self.volume_type = None self.diskFormatQuery = None self.encryption_mark_config = ConfigUtil( self.encryption_environment.azure_crypt_request_queue_path, 'encryption_request_queue', self.logger) def get_current_command(self): return self.encryption_mark_config.get_config( CommonVariables.EncryptionEncryptionOperationKey) def get_encryption_disk_format_query(self): return self.encryption_mark_config.get_config( CommonVariables.EncryptionDiskFormatQueryKey) def config_file_exists(self): """ we should compare the timestamp of the file with the current system time if not match (in 30 minutes, then should skip the file) """ return self.encryption_mark_config.config_file_exists() def commit(self): key_value_pairs = [] command = ConfigKeyValuePair( CommonVariables.EncryptionEncryptionOperationKey, self.command) key_value_pairs.append(command) volume_type = ConfigKeyValuePair( CommonVariables.EncryptionVolumeTypeKey, self.volume_type) key_value_pairs.append(volume_type) disk_format_query = ConfigKeyValuePair( CommonVariables.EncryptionDiskFormatQueryKey, self.diskFormatQuery) key_value_pairs.append(disk_format_query) self.encryption_mark_config.save_configs(key_value_pairs) def clear_config(self): try: if (os.path.exists( self.encryption_environment.azure_crypt_request_queue_path) ): os.remove( self.encryption_environment.azure_crypt_request_queue_path) return True except OSError as e: self.logger.log( "Failed to clear_queue with error: {0}, stack trace: {1}". format(e, traceback.format_exc())) return False
def getCookie(siteName, cookieFileName): #从配置文件中获取登录微博的URL和用户名、密码。 userJson = confUtil.getJsonStr("user.json") weibo_com = userJson.get(siteName) login_url = weibo_com.get("login_url") username = weibo_com.get("username") password = weibo_com.get("password") username_xpath = weibo_com.get("username_xpath") password_xpath = weibo_com.get("password_xpath") submit_xpath = weibo_com.get("submit_xpath") driver = webdriver.PhantomJS(service_args=conf.service_args, desired_capabilities=conf.dcap) driver.get(login_url) #添加等待,等待元素都完成加载。 driver.implicitly_wait(10) #输入用户名和密码 driver.find_element_by_xpath(username_xpath).send_keys(username) driver.find_element_by_xpath(password_xpath).send_keys(password) #提交 driver.find_element_by_xpath(submit_xpath).click() #保存Cookie对象。 cookiePkl = getCookieFile(cookieFileName) pickle.dump(driver.get_cookies(), open(cookiePkl, "wb")) driver.start_client() driver.close() driver.quit() #返回cookie的存放文件路径。 return cookiePkl
def LoadColors(self): global configdict if configdict == None: configdict = ConfigUtil.LoadConfigDictFromFile(colorpath) lang = re.compile(r'^[0-9A-Z]+$') style = re.compile(r'^[0-9A-Z_]+$') for k, v in configdict.items(): if lang.match(k): k = self.syntax.Prefix + k if not hasattr(stc, k): #print "Warning: Can't find %s" % k continue k = getattr(stc, k) self.StyleSetSpec(k, v) elif style.match(k): k = getattr(stc, k) self.StyleSetSpec(k, v) else: pass if configdict.has_key('caretforeground'): self.SetCaretForeground(configdict['caretforeground']) if configdict.has_key('selbackground'): self.SetSelBackground(1, configdict['selbackground']) if configdict.has_key('selforeground'): self.SetSelForeground(1, configdict['selforeground'])
def __init__(self,logger,encryption_environment): self.logger = logger self.encryption_environment = encryption_environment self.command = None self.volume_type = None self.diskFormatQuery = None self.encryption_mark_config = ConfigUtil(self.encryption_environment.azure_crypt_request_queue_path,'encryption_request_queue',self.logger)
def create_table_to_db(): # 建立数据库连接,剔除已入库的部分 db = DbMgr.connect() cursor = db.cursor() c_len = len(DB.TABLE_ALL) for i in range(c_len): try: cur_table = DB.TABLE_ALL[i] # drop table sql_drop_table = DB.SQL_DROP_TABLE_FORMAT % cur_table print(sql_drop_table) cursor.execute(sql_drop_table) db.commit() # create table cur_all_col_with_table = ConfigUtil.read_sections( os.path.join(Config.PATH_DB, cur_table)) print(cur_all_col_with_table) cur_sql_create_table = DbMgr._create_table_sql( cur_table, cur_all_col_with_table) print(cur_sql_create_table) cursor.execute(cur_sql_create_table) db.commit() except Exception as err: print(err) continue cursor.close() db.close()
def getCookie(siteName,cookieFileName): #从配置文件中获取登录微博的URL和用户名、密码。 userJson = confUtil.getJsonStr("user.json") weibo_com = userJson.get(siteName) login_url = weibo_com.get("login_url") username = weibo_com.get("username") password = weibo_com.get("password") username_xpath=weibo_com.get("username_xpath") password_xpath=weibo_com.get("password_xpath") submit_xpath=weibo_com.get("submit_xpath") driver = webdriver.PhantomJS(service_args=conf.service_args,desired_capabilities=conf.dcap) driver.get(login_url) #添加等待,等待元素都完成加载。 driver.implicitly_wait(10) #输入用户名和密码 driver.find_element_by_xpath(username_xpath).send_keys(username) driver.find_element_by_xpath(password_xpath).send_keys(password) #提交 driver.find_element_by_xpath(submit_xpath).click() #保存Cookie对象。 cookiePkl=getCookieFile(cookieFileName) pickle.dump(driver.get_cookies(),open(cookiePkl,"wb")) driver.start_client() driver.close() driver.quit() #返回cookie的存放文件路径。 return cookiePkl
class DecryptionMarkConfig(object): def __init__(self, logger, encryption_environment): self.logger = logger self.encryption_environment = encryption_environment self.command = None self.volume_type = None self.decryption_mark_config = ConfigUtil( self.encryption_environment.azure_decrypt_request_queue_path, 'decryption_request_queue', self.logger) def get_current_command(self): return self.decryption_mark_config.get_config( CommonVariables.EncryptionEncryptionOperationKey) def config_file_exists(self): return self.decryption_mark_config.config_file_exists() def commit(self): key_value_pairs = [] command = ConfigKeyValuePair( CommonVariables.EncryptionEncryptionOperationKey, self.command) key_value_pairs.append(command) volume_type = ConfigKeyValuePair( CommonVariables.EncryptionVolumeTypeKey, self.volume_type) key_value_pairs.append(volume_type) self.decryption_mark_config.save_configs(key_value_pairs) def clear_config(self): try: if (os.path.exists(self.encryption_environment. azure_decrypt_request_queue_path)): os.remove(self.encryption_environment. azure_decrypt_request_queue_path) return True except OSError as e: self.logger.log( "Failed to clear_queue with error: {0}, stack trace: {1}". format(e, traceback.format_exc())) return False
class EncryptionMarkConfig(object): def __init__(self, logger, encryption_environment): self.logger = logger self.encryption_environment = encryption_environment self.command = None self.volume_type = None self.diskFormatQuery = None self.encryption_mark_config = ConfigUtil(self.encryption_environment.azure_crypt_request_queue_path, 'encryption_request_queue', self.logger) def get_current_command(self): return self.encryption_mark_config.get_config(CommonVariables.EncryptionEncryptionOperationKey) def get_encryption_disk_format_query(self): return self.encryption_mark_config.get_config(CommonVariables.EncryptionDiskFormatQueryKey) def config_file_exists(self): """ we should compare the timestamp of the file with the current system time if not match (in 30 minutes, then should skip the file) """ return self.encryption_mark_config.config_file_exists() def commit(self): key_value_pairs = [] command = ConfigKeyValuePair(CommonVariables.EncryptionEncryptionOperationKey,self.command) key_value_pairs.append(command) volume_type = ConfigKeyValuePair(CommonVariables.EncryptionVolumeTypeKey,self.volume_type) key_value_pairs.append(volume_type) disk_format_query = ConfigKeyValuePair(CommonVariables.EncryptionDiskFormatQueryKey,self.diskFormatQuery) key_value_pairs.append(disk_format_query) self.encryption_mark_config.save_configs(key_value_pairs) def clear_config(self): try: if(os.path.exists(self.encryption_environment.azure_crypt_request_queue_path)): os.remove(self.encryption_environment.azure_crypt_request_queue_path) return True except OSError as e: self.logger.log("Failed to clear_queue with error: {0}, stack trace: {1}".format(e, traceback.format_exc())) return False
def getDateFromInterface(): #载入url urls = ConfigUtil.config2map('config/config_url.ini','URL') headers = {'content-type': 'application/json'} # headers = {} data={} for url_key in urls.keys(): resquest_data = json.dumps({"messageid": str(uuid.uuid1())}) response = requests.post(url = urls[url_key], data = resquest_data, headers=headers, timeout=10) data[url_key] = json.loads(response.text) return data
def __init__(self): ''' this to create the instance of mqttclientconnector and connect to the host we want''' Thread.__init__(self) self.mqttClient = mqttClientConnector.MqttClientConnector( "52.207.33.252", 1883, on_connect, on_message, on_publish, on_subscribe) self.mqttClient.connect() self.config = ConfigUtil.ConfigUtil('') self.config.loadConfig() self.pollCycleSecs = int( self.config.getProperty(ConfigConst.CONSTRAINED_DEVICE, ConfigConst.POLL_CYCLES_KEY))
def __init__(self, ipAddr="0.0.0.0", port=5683, multicast=False): self.config = ConfigUtil.ConfigUtil( ConfigConst.DEFAULT_CONFIG_FILE_NAME) self.config.loadConfig() print('Configuration data...\n' + str(self.config)) CoAP.__init__(self, (ipAddr, port), multicast) if port >= 1024: self.port = port else: self.port = 5683 self.ipAddr = ipAddr self.useMulticast = multicast self.initResources()
def import_daily_basic_data_from_tu_share(query_date): pro = TuShare.pro_api() cur_table = DB.TABLE_DAILY_BASIC cur_all_col_with_table = ConfigUtil.read_sections( os.path.join(Config.PATH_DB, cur_table)) cur_type_arrays = [] for cur_col in cur_all_col_with_table: cur_type_arrays.append(DbMgr.get_col_type(cur_col)) data = pro.daily_basic(trade_date=query_date) print(data) DbMgr._insert_to_db(data, cur_table, cur_all_col_with_table, cur_type_arrays) print('Import ' + cur_table + '(' + query_date + ') :' + ' Finished!')
def __init__(self, enableEmulator, lowVal, highVal, curTemp, isPrevTempSet): super(SensorAdaptor, self).__init__() self.enableEmulator = enableEmulator self.curTemp = curTemp self.lowVal = lowVal self.highVal = highVal self.isPrevTempSet = isPrevTempSet self.sh = sense_hat.SenseHat() self.config = ConfigUtil.ConfigUtil('') self.config.loadConfig()
def import_data_from_tu_share(): pro = TuShare.pro_api() for cur_table in DB.TABLE_ALL: cur_all_col_with_table = ConfigUtil.read_sections( os.path.join(Config.PATH_DB, cur_table)) data = TuShare.query(pro, cur_table, cur_all_col_with_table) print(data) cur_type_arrays = [] for cur_col in cur_all_col_with_table: cur_type_arrays.append(DbMgr.get_col_type(cur_col)) # 建立数据库连接,剔除已入库的部分 DbMgr._insert_to_db(data, cur_table, cur_all_col_with_table, cur_type_arrays) print('Import ' + cur_table + ' Finished!')
def __init__(self): ''' Constructor read the config file to load the broker address, port and protocol ''' self.config = ConfigUtil.ConfigUtil( ConfigConst.DEFAULT_CONFIG_FILE_NAME) self.config.loadConfig() self.host = self.config.getProperty(ConfigConst.COAP_DEVICE_SECTION, ConfigConst.HOST_KEY) self.port = self.config.getProperty(ConfigConst.COAP_DEVICE_SECTION, ConfigConst.PORT_KEY)
def sendMail(configFile, section, subject=0, context=0): config_mail = ConfigUtil.config2map(configFile, section) # 第三方 SMTP 服务 mail_host = config_mail["mail.host"] #设置服务器 mail_user = config_mail["mail.user"] #用户名 mail_pass = config_mail["mail.pass"] #口令 sender = config_mail["mail.sender"] receivers = config_mail["mail.receivers"].split( ";") # 接收邮件,可设置为你的QQ邮箱或者其他邮箱 if subject == 0: subject = config_mail["mail.subject"] + " —— " + time.strftime( "%Y-%m-%d %H:%M:%S", time.localtime()) else: subject = subject + " —— " + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) if context == 0: context = config_mail["mail.context"] + " —— " + time.strftime( "%Y-%m-%d %H:%M:%S", time.localtime()) else: context = context + " —— " + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) #创建一个带附件的实例 message = MIMEMultipart('mixed') message['From'] = "系统邮件<%s>" % sender message['To'] = ";".join(receivers) message['Subject'] = subject #邮件正文内容 message.attach(MIMEText(context, 'plain', 'utf-8')) try: smtpObj = smtplib.SMTP() smtpObj.connect(mail_host, 25) # 25 为 SMTP 端口号 smtpObj.login(mail_user, mail_pass) smtpObj.sendmail(sender, receivers, message.as_string()) logging.info("邮件发送成功") except smtplib.SMTPException: logging.info("Error: 无法发送邮件")
def __init__(self): self.config = ConfigUtil.ConfigUtil( ConfigConst.DEFAULT_CONFIG_FILE_NAME) self.config.loadConfig() self.host = self.config.getProperty(ConfigConst.COAP_CLOUD_SECTION, ConfigConst.CLOUD_COAP_HOST) self.port = int( self.config.getProperty( ConfigConst.COAP_CLOUD_SECTION.CLOUD_COAP_PORT)) print('\tHost: ' + self.host) print('\tPort: ' + self.port) if not self.host or self.host.isspace(): print("Using default host: " + self.host) if self.port < 1024 or self.port > 65535: print("using default port: " + self.port) #adding all parts and protocol used is coap self.serverAddr = (self.host, self.port) self.url = "coap://" + self.host + ":" + str(self.port)
f.write(cookie) return cookie try: # Initiating logging logs_dir = CommonUtil.get_file_dir_location('logs') log_config_path = CommonUtil.get_file_location('config', 'logging.conf') if not os.path.exists(logs_dir): os.makedirs(logs_dir) os.environ['ViPR_COMMAND_LOG_DIR'] = logs_dir logging.config.fileConfig(log_config_path, disable_existing_loggers=False) logger = logging.getLogger(__name__) logger.info("## Starting ViPRCommand ##") ConfigUtil.load_config() # Get username, password from arguments or prompt user if sys.argv and len(sys.argv) > 1: if sys.argv[1] == "help" or len(sys.argv) != 5: print("python ViPRCommand -u name -p password") sys.exit() user = sys.argv[2] pswd = sys.argv[4] print("Connecting to ViPR: %s" % ConfigUtil.VIPR_HOST) else: print("Connecting to ViPR: %s" % ConfigUtil.VIPR_HOST) user = input("login as: ") pswd = getpass.getpass() # Login user
def getDateFromInterface(): #载入url urls = ConfigUtil.config2map('config/config_url.ini','URL') headers = {'content-type': 'application/json'} # headers = {} data={} for url_key in urls.keys(): resquest_data = json.dumps({"messageid": str(uuid.uuid1())}) response = requests.post(url = urls[url_key], data = resquest_data, headers=headers, timeout=10) data[url_key] = json.loads(response.text) return data if __name__ == '__main__': config_mysql = ConfigUtil.config2map('config/config_mysql.ini','mysql-local') host = str(config_mysql["host"]) user = str(config_mysql["user"]) passwd = str(config_mysql["passwd"]) port = int(config_mysql["port"]) dbName = str(config_mysql["dbname"]) tableName = str(config_mysql["tablename"]) charset = str(config_mysql["charset"]) try: db = pymysql.connect(host=host, port=port, user=user,
""" import discord import EmbedUtil import area4 from discord.utils import get import FileUtil import ConfigUtil import ServerUtil Bot_Prefix = "+" client = discord.Client() log_file = FileUtil.FileHandler( FileUtil.AbstractFile( "/home/jumbocakeyumyum/cakebot/rocks.rdil.cakebot.log")) servers = ConfigUtil.get_servers() @client.event async def on_ready(): print("Changing playing status...") await client.change_presence(game=discord.Game(name="BETA! Run +help")) print(area4.divider(1)) print("Ready to roll, I'll see you on Discord: @" + client.user.__str__()) print(area4.divider(1)) # Called on message event @client.event async def on_message(message): # Check if this message was authored by the bot:
def clean(start, end): dir = os.getcwd() + '/resources/danmu/all/' for file in os.listdir(dir): # 避免非xml文件的干扰 if file.split('.')[1] == 'xml': name_id = int(file.split('-')[1].split('.')[0]) if start <= name_id <= end: os.remove(dir + file) print(file + " deleted") print('cleaned xml finished.') if __name__ == '__main__': xml_path = os.getcwd() + '/resources/danmu/all/' nowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') # 现在 p = ConfigUtil.get_config('start') max_p = ConfigUtil.get_config('max') ConfigUtil.set_config('from', max_p + 1) print('{0} av id {1}-{2}'.format(nowTime, p, max_p)) # 追加 out_file = open(os.getcwd() + '/resources/config/out.txt', 'a') try: while p < max_p: try: out = parse(xml_path, 'all-{0}.xml'.format(p), p) if out is not None: out_file.write(out + '\n') except Exception as e: print('{0} not parsed error {1}'.format(p, e)) p = p + 1
match = re.search(r'cid=(\d+)', page.text) if match: cid = match.group(1) else: return 0 xml_path = "http://comment.bilibili.tv/{0}.xml".format(cid) try: save_xml(xml_path, av) except UnicodeDecodeError as e: raise e if __name__ == '__main__': nowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') # 现在 p = ConfigUtil.get_config('from') print('{0} from av id {1}'.format(nowTime, p)) try: while p < 99999999: try: save_danmu(str(p)) except UnicodeDecodeError as e: print('{0} not saved for decoding error {1}'.format(p, e)) except Exception as e: print('{0} not saved for unknown error {1}'.format(p, e)) finally: p = p + 1 except SystemExit as ex: print('-----------------------exit raised-----------------------') print('code ' + ex.code) print(str(ex))
with open(os.path.join(ConfigUtil.COOKIE_DIR_ABS_PATH, Constants.COOKIE_FILE_NAME), 'w+') as f: f.write(cookie) return cookie try: # Initiating logging logs_dir = CommonUtil.get_file_dir_location('logs') log_config_path = CommonUtil.get_file_location('config', 'logging.conf') if not os.path.exists(logs_dir): os.makedirs(logs_dir) os.environ['ViPR_COMMAND_LOG_DIR'] = logs_dir logging.config.fileConfig(log_config_path, disable_existing_loggers=False) logger = logging.getLogger(__name__) logger.info("## Starting ViPRCommand ##") ConfigUtil.load_config() # Get username, password from arguments or prompt user if sys.argv and len(sys.argv) > 1: if sys.argv[1] == "help" or len(sys.argv) != 5: print("python ViPRCommand -u name -p password") sys.exit() user = sys.argv[2] pswd = sys.argv[4] print("Connecting to ViPR: %s" % ConfigUtil.VIPR_HOST) else: print("Connecting to ViPR: %s" % ConfigUtil.VIPR_HOST) try: input = raw_input except NameError: pass user = input("login as: ") pswd = getpass.getpass()
async def on_message(message): # Check if this message was authored by the bot: if message.author == client.user: return # Check if message starts with the prefix: if not message.content.startswith(Bot_Prefix): # log it log_file.get_file().wrap().write("[Message Log] Sent by " + str(message.author) + " on server " + message.server.name + ": " + message.content) # cancel now return # Split the input theinput = message.content[len(Bot_Prefix):] args = theinput.split() # the command, e.x. "help" cmd = args[0].lower() # if the user doesn't put in a command with the prefix, cancel: if cmd is None: return # if the user doesn't put in a command with the prefix, cancel: if cmd == "" or cmd == " ": # fix npe return # the args (array) e.x. ["hello", "world"] args = args[1:] # make all args lowercase: for i in range(len(args)): args[i] = args[i].lower() # COMMANDS if cmd == "help": await client.send_message( message.channel, embed=EmbedUtil.build_help_menu( EmbedUtil.prep( title="Cakebot Help", description="Make sure to add a + before each command!"))) elif cmd == "ping": await client.send_message(message.channel, "🏓") elif cmd == "invite": await client.send_message( message.channel, embed=EmbedUtil.prep( "Invite CakeBot", "[Click here to invite me!](https://discordapp.com/oauth2/authorize?client_id=580573141898887199&scope=bot&permissions=8)" )) elif cmd == "beta": print(servers[str(message.server.id)]["beta_features"]) # toggle beta command state = servers[str(message.server.id)]["beta_features"] if False: # has perms to toggle # switch it to the state it isn't (toggle it) ConfigUtil.toggle_state(str(message.server.id), "beta_features", not state) else: # doesnt have perms await client.send_message( message.channel, "**Sorry, but you do not have the manage server permission, have somebody with it use this command instead!**" )