def configInit(self): config = ConfigManager("config/default.ini") self.title = config.config_get("project", "title") self.version = config.config_get("project", "version") self.shortcut_new_file_compare = config.config_get( "shortcut", "new_file_compare") self.shortcut_new_dir_compare = config.config_get( "shortcut", "new_dir_compare") self.shortcut_choose_left = config.config_get("shortcut", "choose_left") self.shortcut_choose_right = config.config_get("shortcut", "choose_right") self.shortcut_settings = config.config_get("shortcut", "settings") self.shortcut_exit = config.config_get("shortcut", "exit") self.shortcut_compare = config.config_get("shortcut", "compare") self.shortcut_copy_to_left = config.config_get("shortcut", "copy_to_left") self.shortcut_copy_to_right = config.config_get( "shortcut", "copy_to_right") self.shortcut_next_diff = config.config_get("shortcut", "next_diff") self.shortcut_pre_diff = config.config_get("shortcut", "pre_diff") self.shortcut_help = config.config_get("shortcut", "help")
def __init__(self, root): self.window = Toplevel(root) self.window.wm_title("Paste types") self.window.grab_set() self.config = ConfigManager("config.xml") self.mod_frame = Frame(self.window) self.mod_frame.grid(row=2, pady=3, sticky="w") Label(self.mod_frame, text="Enter Mod name:").grid(row=0, column=0, padx=3, pady=3) self.modSelector = ttk.Combobox(self.mod_frame, values=self.config.get_mods()) self.modSelector.set(self.config.get_mods()[0]) self.modSelector.grid(row=0, column=1) self.ini_manger = INIManager("app.ini") self.database = DAO(self.ini_manger.read_ini("Database", "Database_Name")) self.duplicate = IntVar() self.duplicate.set(0) Checkbutton(self.mod_frame, text="Use Values of Duplicate Items", variable=self.duplicate) \ .grid(row=0, column=2, padx=10) self.text_area = Text(self.window) self.text_area.grid(row=1, padx=3, pady=3) self.buttons = Frame(self.window) self.buttons.grid(row=3, sticky="w") Button(self.buttons, text="OK", height=1, width=10, command=self.__add_items) \ .grid(padx=10, pady=10) self.window.wait_window()
def send_mail(to_addr, type_name, name): try: host = Constant.send_mail_host port = Constant.send_mail_ssl_port sender = Constant.send_mail_addr pwd = Constant.send_mail_apikey receiver = to_addr msg = MIMEMultipart() text = '发送记录为:%s %s' % (name, type_name) msg.attach(MIMEText(text, 'plain', 'utf-8')) msg['subject'] = 'deepintell测试记录发送' # 设置标题 msg['from'] = sender # 设置发送人 msg['to'] = receiver # 设置接收人 cm = ConfigManager() file_dir = cm.getpath('datafile') file_name = type_name + 'z' + trans_unicode_into_int( trans_coding(name)) + '.csv' att1 = MIMEText( open(file_dir + file_name, 'rb').read(), 'base64', 'utf-8') att1["Content-Type"] = 'application/octet-stream' att1["Content-Disposition"] = 'attachment; filename="%s"' % file_name msg.attach(att1) s = smtplib.SMTP_SSL(host, port) # 使用SSL端口 s.login(sender, pwd) # 登陆邮箱 s.sendmail(sender, receiver, msg.as_string()) # 发送邮件 s.quit() # 关闭链接 print '邮件发送成功\n' except: error(traceback.format_exc()) print '邮件发送失败\n' finally: exit() # 退出子进程
def main(): api = Auth.getAPI() conf = CM.ConfigManager() query_term = "#MakeAmericaGreatAgain" tweets = tweepy.Cursor(api.search, q=query_term, result_type="recent", since="2016-10-13", until="2016-10-14", show_user=True).items(200) query_dir = conf.newQueryPath(query_term) # TODO Turn saving on tweetsAsJSON = FM.saveTweetQuery(tweets, query_dir) # TP.printTweets(tweets) HTList = HTA.getAssociatedHashtags(tweetsAsJSON, "MakeAmericaGreatAgain") # TP.printList(HTList) WordOccurrences = TP.countWordOccurrences(tweetsAsJSON, HTList) # print HTA.getMostUsed(HTList, 3) # print HTCount # Plotter.plotTupleCount(HTA.getMostUsed(HTList, 3)) Plotter.plotTupleCount(WordOccurrences)
def str2qr_terminal(data, is_send): """ @brief convert string to qrcode matrix and outprint @param data The string """ cm = ConfigManager() file_dir = cm.getpath('qrcode_path') with open(file_dir, 'wb') as f: f.write(data) if is_send: p = multiprocessing.Process(target=send_login_mail, args=(file_dir, )) p.start() scanner = zbar.ImageScanner() scanner.parse_config('enable') pil = Image.open(file_dir).convert('L') width, height = pil.size raw = pil.tobytes() image = zbar.Image(width, height, 'Y800', raw) scanner.scan(image) text = '' for symbol in image: text += symbol.data del image echo('二维码表示地址:%s\n' % text) qr = qrcode.QRCode() qr.border = 1 qr.add_data(text) mat = qr.get_matrix() print_qr(mat)
def recover_login_data(self): cm = ConfigManager() # 恢复鉴权参数 self.clientid = int(cm.get('login_data', 'clientid')) self.urlPtwebqq = cm.get('login_data', 'url_ptwebqq') self.ptwebqq = cm.get('login_data', 'ptwebqq') self.vfwebqq = cm.get('login_data', 'vfwebqq') self.uin = int(cm.get('login_data', 'uin')) self.psessionid = cm.get('login_data', 'psessionid') self.hash = cm.get('login_data', 'hash') self.bkn = int(cm.get('login_data', 'bkn')) self.user['qq'] = cm.get('login_data', 'user_qq') self.user['nick'] = cm.get('login_data', 'user_nick') # 恢复cookies file_dir = cm.getpath('cookie') with open(file_dir, 'rb') as f: cookies = requests.utils.cookiejar_from_dict(pickle.load(f)) self.session = requests.session() self.session.cookies = cookies self.session.headers.update({ 'User-Agent': ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9;' ' rv:27.0) Gecko/20100101 Firefox/27.0'), 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }) return True
def __init__(self, config_path="../config/server.ini", server_id=None): self.id = server_id if server_id else str(random.randint(0, 9999)).zfill(4) self.time_started = 0 # Init socket self.sel = selectors.DefaultSelector() self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) messaging.set_keepalive(self.server_socket) self.server_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) self.host = socket.gethostname() self.ip = messaging.get_ip_address() # Init configs self.config = ConfigManager() self.config_path = config_path # Init threads self.autoconnect_thread = threading.Thread(target=self._client_processor, daemon=True, name='Client processor') self.client_processor_thread_running = threading.Event() # Can be used for manual thread killing self.broadcast_thread = threading.Thread(target=self._ip_broadcast, daemon=True, name='IP broadcast sender') self.broadcast_thread_running = threading.Event() # TODO replace by interrupt self.broadcast_thread_interrupt = threading.Event() self.listener_thread = threading.Thread(target=self._broadcast_listen, daemon=True, name='IP broadcast listener') self.listener_thread_running = threading.Event()
def __init__(self, config_path=os.path.join(current_dir, os.pardir, "config", "client.ini")): """ Initializtion ```python client = Client(config_path) ``` Args: config_path (string, optional): Path to the file with configuration. There also should be config specification file at `<config_path>\config\configspec_client.ini`. Defaults to `<current_dir>\os.pardir\config\client.ini`. """ self.selector = selectors.DefaultSelector() self.client_socket = None self.server_connection = messaging.ConnectionManager() self.connected = False self.client_id = None # Init configs self.config = ConfigManager() self.config_path = config_path global active_client active_client = self
def test_read_hypervisor(self): with open(self.hypervisor_file, "w") as f: f.write(HYPERVISOR_JSON) with open(self.config_file, "w") as f: f.write(""" [test] type=fake is_hypervisor=true file=%s """ % self.hypervisor_file) manager = ConfigManager(self.logger, self.config_dir) self.assertEquals(len(manager.configs), 1) virt = Virt.fromConfig(self.logger, manager.configs[0]) self.assertEquals(type(virt), FakeVirt) mapping = virt.getHostGuestMapping() self.assertTrue("hypervisors" in mapping) hypervisors = mapping["hypervisors"] self.assertEquals(len(hypervisors), 1) hypervisor = hypervisors[0] self.assertEquals(type(hypervisor), Hypervisor) self.assertEquals(hypervisor.hypervisorId, "60527517-6284-7593-6AAB-75BF2A6375EF") self.assertEquals(len(hypervisor.guestIds), 1) guest = hypervisor.guestIds[0] self.assertEquals(guest.uuid, "07ED8178-95D5-4244-BC7D-582A54A48FF8") self.assertEquals(guest.state, 1)
def snapshot(self): """ @brief Save basic infos for next login. @return Bool: whether operation succeed. """ try: conf = { 'uuid': self.uuid, 'redirect_uri': self.redirect_uri, 'uin': self.uin, 'sid': self.sid, 'skey': self.skey, 'pass_ticket': self.pass_ticket, 'synckey': self.synckey, 'device_id': self.device_id, 'last_login': time.time(), } cm = ConfigManager() Log.debug('save wechat config') cm.set_wechat_config(conf) # save cookie Log.debug('save cookie') if self.cookie: self.cookie.save(ignore_discard=True) # save contacts Log.debug('save contacts') self.save_contacts() except Exception, e: Log.error(traceback.format_exc()) return False
def batch_insert(session, org_category, mm_result): es_config = ConfigManager().get_setting(key='elasticsearch') addresses = es_config['address'] if not isinstance(addresses, list): addresses = [addresses] es = Elasticsearch(addresses, port=es_config['port']) batch_insert = es.msearch(body=mm_result)['responses'] if batch_insert: try: for org_cat, batch_result in zip(org_category, batch_insert): if len(batch_result['hits']['hits']) == 0: message = 'No Category Mapping: %s' % ' '.join( str(item) for item in org_cat) logging.getLogger(__name__).error(message) else: item_cat = ItemCat(org_cat) intg_id = batch_result['hits']['hits'][0]['_source'][ 'intg_id'] cat_map = CatMap(INTG_ID=intg_id, UPDATE_TIME=datetime.datetime.now( timezone('Asia/Seoul'))) item_cat.cat_map.append(cat_map) session.add(item_cat) session.commit() except IntegrityError as e: logger.error('Insertion Error %s' % e) session.rollback() session.close()
def recover(self): """ @brief Recover from snapshot data. @return Bool: whether operation succeed. """ cm = ConfigManager() [ self.uuid, self.redirect_uri, self.uin, self.sid, self.skey, self.pass_ticket, self.synckey, device_id, self.last_login ] = cm.get_wechat_config() if device_id: self.device_id = device_id self.base_request = { 'Uin': int(self.uin), 'Sid': self.sid, 'Skey': self.skey, 'DeviceID': self.device_id, } # set cookie Log.debug('set cookie') self.cookie = set_cookie(self.cookie_file) return True
def testInvalidConfig(self): with open(os.path.join(self.config_dir, "test.conf"), "w") as f: f.write(""" Malformed configuration file """) manager = ConfigManager(self.config_dir) self.assertEqual(len(manager.configs), 0)
def wrapper(*args, **kwargs): config = ConfigManager() meta = (args[0]).meta meta.add_log_entry( LogEntry.create_log(datetime.today(), config.default_author, func.__name__)) func(*args, **kwargs)
def LoadConfiguration(): global configManager # Bit of a hack I dont kow what to do about? from config import ConfigManager configName = rc = win32ui.GetProfileVal("Editor", "Keyboard Config", "default") configManager = ConfigManager(configName) if configManager.last_error: bTryDefault = 0 msg = "Error loading configuration '%s'\n\n%s" % (configName, configManager.last_error) if configName != "default": msg = msg + "\n\nThe default configuration will be loaded." bTryDefault = 1 win32ui.MessageBox(msg) if bTryDefault: configManager = ConfigManager("default") if configManager.last_error: win32ui.MessageBox("Error loading configuration 'default'\n\n%s" % (configManager.last_error))
def sendAuthentication(self): conf = ConfigManager().default token = conf.get('local', 'token', fallback='').encode() request = b''.join( [struct.pack('!BB', constants.SOCKS5_VER, len(token)), token]) log.debug('sendAuthentication {data!r}', data=request) self.write(request) self.set_state(self.STATE_SentAuthentication)
def testNoOptionsConfig(self): with open(os.path.join(self.config_dir, "test.conf"), "w") as f: f.write(""" [test] type=esx """) manager = ConfigManager(self.config_dir) self.assertEqual(len(manager.configs), 0)
def __init__(self, db): self.db = db self.wechat = None # recieve `WeChat` class instance # for call some wechat apis # read config cm = ConfigManager() [self.upload_dir, self.data_dir, self.log_dir] = cm.setup_database()
def test_logger(self): author = ConfigManager().default_author dataset = structures.StructuredDataSet.create_dataset(self._test_path, "test_logger", author) # create a branch dataset["x"]["xx"] dataset.write()
def __init__(self, irc_logger): self.conf = ConfigManager() self.db_path = self.conf.data_path + "data.sqlite" self.users_table = "users" self.karma_table = "karma" self.create_karma_table() self.create_users_table() # TODO (sentenza) Logger.getLogger or Twisted.logger self.irc_logger = irc_logger
def __init__(self): self.cm = ConfigManager() self.channel = self.cm.channel self.protocol = IRCBot # The factory needs the protocol class to make a new connection self.nickname = self.cm.bot_nick if not os.path.exists(self.cm.data_path): os.makedirs(self.cm.data_path) self.data_folder = self.cm.data_path self.log_filename = self.data_folder + self.nickname + ".log"
def es_connect(): """Open up a ElasticSearch connector :return: ElasticSearch connector instance """ es_config = ConfigManager().get_setting(key='elasticsearch') addresses = es_config['address'] if not isinstance(addresses, list): addresses = [addresses] return Elasticsearch(addresses, port=es_config['port'])
def __init__(self, reactor): self.reactor = reactor self.num_protocols = 0 conf = ConfigManager().default self.shadow = ShadowProtocol( key=conf.get('local', 'key'), data_salt=conf.get('local', 'data_salt'), pro_salt=conf.get('local', 'pro_salt'), data_cipher=conf.get('local', 'data_cipher'), pro_cipher=conf.get('local', 'pro_cipher'), )
def drop_config(self, path, row): if not ConfigManager.config_exists(path): return False config = ConfigManager() config.load_only_config(path) config_dict = config.full_dict(include_defaults=False) config_dict.pop("PRIVATE", None) self.data_contents[row].client.send_message("config", kwargs={ "config": config_dict, "mode": "rewrite" }) return False
def testUnreadableConfig(self): filename = os.path.join(self.config_dir, "test.conf") with open(filename, "w") as f: f.write(""" [test] type=esx server=1.2.3.4 username=admin password=password owner=root env=staging """) os.chmod(filename, 0) manager = ConfigManager(self.config_dir) self.assertEqual(len(manager.configs), 0)
def _command_config_write(*args, **kwargs): mode = kwargs.get("mode", "modify") # exceptions would be risen in case of incorrect config if mode == "rewrite": active_client.config.load_from_dict( kwargs["config"], configspec=active_client.config_path) # with validation elif mode == "modify": new_config = ConfigManager() new_config.load_from_dict(kwargs["config"]) active_client.config.merge(new_config, validate=True) active_client.config.write() logger.info("Config successfully updated from command") active_client.load_config()
def __init__(self, config_path="config/client.ini"): self.selector = selectors.DefaultSelector() self.client_socket = None self.server_connection = messaging.ConnectionManager() self.connected = False self.client_id = None # Init configs self.config = ConfigManager() self.config_path = config_path global active_client active_client = self
def readConfigFile(self): """ Utility function to read the configuration file, and parse it into the dictionary structure used by the application. """ self.app_config = ConfigManager(self.config_file, self.run_date) self.app_config.app_version = __version__ config_obj = ConfigParser() try: config_obj.read_file(open(self.config_file, encoding='utf-8')) # self.configData['configReader'] = config_obj except Exception as e: print( f'ERROR: Configuration file "{self.config_file}" could not be read: {e}' ) sys.exit(1)
def send_login_mail(img_dir): try: host = Constant.send_mail_host port = Constant.send_mail_ssl_port sender = Constant.send_mail_addr pwd = Constant.send_mail_apikey receiver = Constant.send_login_addr cm = ConfigManager() if img_dir: msg = MIMEMultipart('alternative') msg['subject'] = 'deepintell测试记录发送' # 设置标题 msg['from'] = sender # 设置发送人 msg['to'] = receiver # 设置接收人 mail_msg = '重新登录帐号:%s(%s)\n' % \ (cm.get('login_data', 'user_nick'), cm.get('login_data', 'user_qq')) mail_msg += '二维码见附件\n' msg.attach(MIMEText(mail_msg, 'plain', 'utf-8')) # 添加图片 with open(img_dir, 'rb') as f: att1 = MIMEText(f.read(), 'base64', 'utf-8') att1["Content-Type"] = 'application/octet-stream' att1[ "Content-Disposition"] = 'attachment; filename="%s"' % img_dir.split( '/')[-1] msg.attach(att1) else: msg = MIMEMultipart() text = '已经停止为帐号:%s(%s)进行重新登录,程序即将退出,请重新打开程序登录。' % \ (cm.get('login_data', 'user_nick'), cm.get('login_data', 'user_qq')) msg.attach(MIMEText(text, 'plain', 'utf-8')) msg['subject'] = 'deepintell测试记录发送' # 设置标题 msg['from'] = sender # 设置发送人 msg['to'] = receiver # 设置接收人 s = smtplib.SMTP_SSL(host, port) # 使用SSL端口 s.login(sender, pwd) # 登陆邮箱 s.sendmail(sender, receiver, msg.as_string()) # 发送邮件 s.quit() # 关闭链接 print '邮件发送成功\n' except: error(traceback.format_exc()) print '邮件发送失败\n' finally: exit() # 退出子进程
def testEsxDisableSimplifiedVim(self): with open(os.path.join(self.config_dir, "test1.conf"), "w") as f: f.write(""" [test1] type=esx server=1.2.3.4 username=admin password=password owner=root env=staging simplified_vim=false """) manager = ConfigManager(self.logger, self.config_dir) self.assertEqual(len(manager.configs), 1) config = manager.configs[0] self.assertFalse(config.simplified_vim)