Пример #1
0
    def override_gtk_theme(self):
        css_provider = Gtk.CssProvider()

        bg = Gdk.color_parse(ConfigManager.get_conf('color-background'))
        bg_hex =  '#%02X%02X%02X' % (int((bg.red/65536.0)*256), int((bg.green/65536.0)*256), int((bg.blue/65536.0)*256))

        css_provider.load_from_data('''
            #notebook GtkPaned 
            {
                -GtkPaned-handle-size: %i;
            }
            GtkVScrollbar
            {
                -GtkRange-slider-width: 5;
            }
            GtkVScrollbar.trough {
                background-image: none;
                background-color: %s;
                border-width: 0;
                border-radius: 0;

            }
            GtkVScrollbar.slider, GtkVScrollbar.slider:prelight, GtkVScrollbar.button {
                background-image: none;
                border-width: 0;
                background-color: alpha(#FFF, 0.4);
                border-radius: 10px;
                box-shadow: none;
            }
            ''' % (ConfigManager.get_conf('seperator-size'), bg_hex))

        style_context = Gtk.StyleContext()
        style_context.add_provider_for_screen(self.screen, css_provider, Gtk.STYLE_PROVIDER_PRIORITY_USER)
Пример #2
0
    def __init__(self, progname=[ConfigManager.get_conf('shell')], run_dir=None, term_id=0):
        super(Gtk.HBox, self).__init__()
        ConfigManager.add_callback(self.update_ui)

        self.progname = ' '.join(progname)
        self.id = VteObjectContainer.handle_id(term_id)
        self.parent = 0
        self.vte = Vte.Terminal()
        self.pack_start(self.vte, True, True, 0)

        self.vscroll = Gtk.VScrollbar(self.vte.get_vadjustment())
        self.pack_start(self.vscroll, False, False, 0)

        self.fork_process(progname, run_dir)

        for regex_string in regex_strings:
            regex_obj = GLib.Regex.new(regex_string, 0, 0)
            tag = self.vte.match_add_gregex(regex_obj, 0)
            self.vte.match_set_cursor_type(tag, Gdk.CursorType.HAND2)

        self.vte.connect('scroll-event', self.scroll_event)
        self.vte.connect('child-exited', self.on_child_exited)
        self.vte.connect('button-release-event', self.on_button_release)
        self.vte.connect('increase-font-size', self.change_font_size, 0.1)
        self.vte.connect('decrease-font-size', self.change_font_size, -0.1)

        self.update_ui()
Пример #3
0
    def __init__(self):
        super(Gtk.HBox, self).__init__()
        ConfigManager.add_callback(self.update_ui)

        self.vte = Vte.Terminal()
        self.pack_start(self.vte, True, True, 0)

        if ConfigManager.get_conf('show-scrollbar'):
            self.vscroll = Gtk.VScrollbar()
            self.vscroll.set_adjustment(self.vte.get_vadjustment())
            self.pack_end(self.vscroll, False, True, 0)

        dir_conf = ConfigManager.get_conf('dir')
        if dir_conf == '$home$':
            run_dir = os.environ['HOME']
        elif dir_conf == '$pwd$':
            run_dir = os.getcwd()
        else:
            run_dir = dir_conf

        self.vte.fork_command_full(
            Vte.PtyFlags.DEFAULT,
            run_dir,
            ConfigManager.get_conf('shell').split(),
            [],
            GLib.SpawnFlags.DO_NOT_REAP_CHILD,
            None,
            None)

        self.vte.connect('button-release-event', self.on_button_release)
        self.update_ui()
Пример #4
0
    def close_node(self, widget):
        parent = self.get_parent()
        if type(parent) == VteObjectContainer:
            return

        container = parent
        while type(container) != VteObjectContainer:
            container = container.get_parent()

        if parent.get_child1() == self:
            sibling = parent.get_child2()
        else:
            sibling = parent.get_child1()

        ConfigManager.remove_callback(self.update_ui)
        parent.remove(sibling)
        top_level = parent.get_parent()
        if type(top_level) == VteObjectContainer:
            top_level.remove(parent)
            top_level.pack_start(sibling, True, True, 0)
        else:
            if top_level.get_child1() == parent:
                top_level.remove(parent)
                top_level.pack1(sibling, True, True)
            else:
                top_level.remove(parent)
                top_level.pack2(sibling, True, True)

        sibling.vte.grab_focus()
        container.active_terminal = sibling
Пример #5
0
    def __init__(self):
        super(Gtk.HBox, self).__init__()
        ConfigManager.add_callback(self.update_ui)

        self.vte = Vte.Terminal()
        self.pack_start(self.vte, True, True, 0)

        if ConfigManager.get_conf('show-scrollbar'):
            self.vscroll = Gtk.VScrollbar()
            self.vscroll.set_adjustment(self.vte.get_vadjustment())
            self.pack_end(self.vscroll, False, True, 0)

        dir_conf = ConfigManager.get_conf('dir')
        if dir_conf == '$home$':
            run_dir = os.environ['HOME']
        elif dir_conf == '$pwd$':
            run_dir = os.getcwd()
        else:
            run_dir = dir_conf

        self.vte.fork_command_full(Vte.PtyFlags.DEFAULT, run_dir,
                                   ConfigManager.get_conf('shell').split(), [],
                                   GLib.SpawnFlags.DO_NOT_REAP_CHILD, None,
                                   None)

        self.vte.connect('button-release-event', self.on_button_release)
        self.update_ui()
Пример #6
0
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()  # 退出子进程
Пример #7
0
    def update_resizer(self, widget, event):
        self.resizer.set_position(self.get_allocation().height)

        if not self.is_fullscreen:
            new_percent = int((self.get_allocation().height * 1.0) / self.screen.get_height() * 100.0)
            ConfigManager.set_conf('height', str(new_percent))
            ConfigManager.save_config()
Пример #8
0
    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()
Пример #9
0
def test_realize_path():
    assert "/baz" == ConfigManager.realize_path("/foo/../bar/../baz")
    os.path.abspath = Mock(return_value="/baz")
    assert "/baz" == ConfigManager.realize_path("../baz")

    os.path.expanduser = Mock(return_value="/home/foobar")
    assert "/home/foobar" == ConfigManager.realize_path("~foobar/")
Пример #10
0
    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
Пример #11
0
    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()
Пример #12
0
    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
Пример #13
0
def cannot_bind(app):
    ConfigManager.set_conf('hide-on-start', False)
    ConfigManager.set_conf('losefocus-hiding', False)
    msgtext = _("Another application using '%s'. Please open preferences and change the shortcut key.") % ConfigManager.get_conf('global-key')
    msgbox = Gtk.MessageDialog(app, Gtk.DialogFlags.DESTROY_WITH_PARENT, Gtk.MessageType.WARNING, Gtk.ButtonsType.OK, msgtext)
    msgbox.run()
    msgbox.destroy()
Пример #14
0
    def close_node(self, widget):
        parent = self.get_parent()
        if type(parent) == VteObjectContainer:
            return

        container = parent
        while type(container) != VteObjectContainer:
            container = container.get_parent()

        if parent.get_child1() == self:
            sibling = parent.get_child2()
        else:
            sibling = parent.get_child1()

        ConfigManager.remove_callback(self.update_ui)
        parent.remove(sibling)
        top_level = parent.get_parent()
        if type(top_level) == VteObjectContainer:
            top_level.remove(parent)
            top_level.pack_start(sibling, True, True, 0)
        else:
            if top_level.get_child1() == parent:
                top_level.remove(parent)
                top_level.pack1(sibling, True, True)
            else:
                top_level.remove(parent)
                top_level.pack2(sibling, True, True)

        sibling.vte.grab_focus()
        container.active_terminal = sibling
Пример #15
0
    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
Пример #16
0
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)
Пример #17
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()
Пример #18
0
 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)
Пример #19
0
    def update_resizer(self, widget, event):
        self.resizer.set_position(self.get_allocation().height)

        if not self.is_fullscreen:
            new_percent = int((self.get_allocation().height * 1.0) /
                              self.screen.get_height() * 100.0)
            ConfigManager.set_conf('height', str(new_percent))
            ConfigManager.save_config()
Пример #20
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()
Пример #21
0
class WarpZoneListener(BaseListener):

	default_config = {
			'warpzones': [
				{
					'area': {
						'min': [0, 0, 0],
						'max': [1, 1, 1],
						'world': 'world'
					},
					'to': {
						'location': [2, 2, 2],
						'world': 'world'
					}
				}
			]
		}

	def __init__(self, plugin):
		self.plugin = plugin

	def onEnable(self):
		self.config_manager = ConfigManager(path.join(self.plugin.getDataFolder().getAbsolutePath(), 'warpzones.yml'), default=self.default_config)
		self.config_manager.load_config()

		self.register_event(self.onPlayerMoveEvent, PlayerMoveEvent)

	def onDisable(self):
		self.config_manager.save_config()

	def onPlayerMoveEvent(self, event):

		if event.getFrom().getBlock() == event.getTo().getBlock():
			return

		to = event.getTo()
		to_arr = [to.getBlockX(), to.getBlockY(), to.getBlockZ()]

		for warp in self.config_manager.config['warpzones']:
			if warp['area']['world'] == event.getPlayer().getLocation().getWorld().getName():
				if self.is_in_range(to_arr, warp['area']['min'], warp['area']['max']): #Should probably do a rtree or something
					to_loc = warp['to']['location']
					event.getPlayer().teleport(Location(self.plugin.getServer().getWorld(warp['to']['world']), to_loc[0], to_loc[1], to_loc[2]))

	def is_in_range(self, loc, mini, maxi):
		return self.arr_gt(loc, mini) and self.arr_lt(loc, maxi)

	def arr_gt(self, arr1, arr2):
		for index in range(0, len(arr1)):
			if not arr1[index] >= arr2[index]:
				return False
		return True

	def arr_lt(self, arr1, arr2):
		for index in range(0, len(arr1)):
			if not arr1[index] <= (arr2[index]):
				return False
		return True
Пример #22
0
def cannot_bind(app):
    ConfigManager.set_conf('hide-on-start', False)
    ConfigManager.set_conf('losefocus-hiding', False)
    msgtext = _(
        "Another application using '%s'. Please open preferences and change the shortcut key."
    ) % ConfigManager.get_conf('global-key')
    msgbox = Gtk.MessageDialog(app, Gtk.DialogFlags.DESTROY_WITH_PARENT,
                               Gtk.MessageType.WARNING, Gtk.ButtonsType.OK,
                               msgtext)
    msgbox.run()
    msgbox.destroy()
Пример #23
0
def register_nick_and_username():
    servconn().send_message(string.join([
        "NICK",
        ConfigManager.get("nick")], " "
    ))

    servconn().send_message(string.join([
        "USER",
        ConfigManager.get("nick"),
        socket.gethostname(),
        ConfigManager.get("server"),
        ConfigManager.get("nick")], " "
    ))
Пример #24
0
    def on_window_losefocus(self, window, event):
        if self.slide_effect_running:
            return
        if ConfigManager.disable_losefocus_temporary:
            return
        if not ConfigManager.get_conf('losefocus-hiding'):
            return

        if self.get_property('visible'):
            self.losefocus_time = GdkX11.x11_get_server_time(self.get_window())
            if ConfigManager.get_conf('use-animation'):
                self.slide_up()
            self.unrealize()
            self.hide()
Пример #25
0
    def on_window_losefocus(self, window, event):
        if self.slide_effect_running:
            return
        if ConfigManager.disable_losefocus_temporary:
            return
        if not ConfigManager.get_conf('losefocus-hiding'):
            return

        if self.get_property('visible'):
            self.losefocus_time = GdkX11.x11_get_server_time(self.get_window())
            if ConfigManager.get_conf('use-animation'):
                self.slide_up()
            self.unrealize()
            self.hide()
Пример #26
0
    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
Пример #27
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()
Пример #28
0
    def redis_connect_properties(self):
        config_obj = ConfigManager.get_instance()
        self.config = config_obj.dataMap

        self.redis_block = self.config.get(REDIS_CONFIG, {})
        self.redis_connect = get_redis_instance_from_redis_address(
            self.redis_block)
Пример #29
0
 def __init__ (self):
   pygame.init()
   pygame.key.set_repeat(10,10)
   res = ConfigManager.get("resolution")
   self.screen = pygame.display.set_mode(res, pygame.DOUBLEBUF)
   self.ball = Ball()
   self.space = Space(res)
Пример #30
0
    def onEnable(self):
        self.config_manager = ConfigManager(
            path.join(self.plugin.getDataFolder().getAbsolutePath(), "warpzones.yml"), default=self.default_config
        )
        self.config_manager.load_config()

        self.register_event(self.onPlayerMoveEvent, PlayerMoveEvent)
Пример #31
0
    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)
Пример #32
0
	def onEnable(self):
		self.config_manager = ConfigManager(path.join(self.plugin.getDataFolder().getAbsolutePath(), 'signs.yml'), default=self.default_config)
		self.config_manager.load_config()

		self.register_event(self.onPlayerInteract, PlayerInteractEvent)

		register_command(self.reload_command, 'reload-sign-config', permission="omneity.actionsigns.reload")
Пример #33
0
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()
Пример #34
0
    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)
Пример #35
0
    def start_client(self):
        self.log.info('start client')

        self.transport.pauseProducing()
        conf = ConfigManager().default
        proxy_host_port = conf.get('local', 'proxy_host_port')
        point = clientFromString(self.factory.reactor,
                                 f"tcp:{proxy_host_port}")

        d = connectProtocol(point, ProxyClient(self))

        def error(failure):
            raise errors.HostUnreachable()

        d.addErrback(error)

        return d
Пример #36
0
 def __init__(self, bare=False, progname=[ConfigManager.get_conf('shell')]):
     super(VteObjectContainer, self).__init__()
     if not bare:
         self.vte_list = []
         self.active_terminal = VteObject(progname, None, 0)
         self.vte_list.append(self.active_terminal)
         self.pack_start(self.active_terminal , True, True, 0)
         self.show_all()
Пример #37
0
	def onEnable(self):
		self.config_manager = ConfigManager(path.join(self.plugin.getDataFolder().getAbsolutePath(), 'nether.yml'), default=self.default_config)
		self.config_manager.load_config()

		self.register_event(self.onPlayerPortalEvent, PlayerPortalEvent)
		self.register_event(self.onPortalCreateEvent, PortalCreateEvent)

		self.travelagent = OtOTravelAgent(self.plugin.getServer())
Пример #38
0
    def update_ui(self):
        #self.vte.set_background_saturation(ConfigManager.get_conf('transparency') / 100.0)

        #self.vte.set_opacity(int((100 - ConfigManager.get_conf(('transparency'))) / 100.0 * 65535))

        self.vte.set_colors(
            Gdk.color_parse(ConfigManager.get_conf('color-text')),
            Gdk.color_parse(ConfigManager.get_conf('color-background')),
            [])

        #self.vte.set_background_image_file(
         #   ConfigManager.get_conf('background-image'))

        if not ConfigManager.get_conf('use-default-font'):
            self.vte.set_font_from_string(ConfigManager.get_conf('font-name'))

        self.show_all()
Пример #39
0
    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)
Пример #40
0
    def __init__(self, host='wx.qq.com'):
        super(WeChat, self).__init__(host)

        self.db = None
        self.save_data_folder = ''  # 保存图片,语音,小视频的文件夹
        self.last_login = 0  # 上次退出的时间
        self.time_out = 5  # 同步时间间隔(单位:秒)
        self.msg_handler = None
        self.start_time = time.time()
        self.bot = None

        cm = ConfigManager()
        self.save_data_folders = cm.get_wechat_media_dir()
        self.cookie_file = cm.get_cookie()
        self.pickle_file = cm.get_pickle_files()
        self.log_mode = cm.get('setting', 'log_mode') == 'True'
        self.exit_code = 0
Пример #41
0
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))
Пример #42
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)
Пример #43
0
    def __init__(self, msg_db):

        self.smartqq = None
        self.msg_db = msg_db

        cm = ConfigManager()
        self.data_file = cm.getpath('datafile')
        if not os.path.exists(self.data_file):
            os.makedirs(self.data_file)

        self.msg_col = '''
                    MsgOrder integer primary key,
                    Time text,
                    FromNick text,
                    ToNick text,
                    content text
                '''
        self.user_type = ['normal', 'group', 'discuss']
Пример #44
0
	def onEnable(self):
		self.config_manager = ConfigManager(path.join(self.plugin.getDataFolder().getAbsolutePath(), 'spawn.yml'), default=self.default_config)
		self.config_manager.load_config()

		self.register_event(self.onPlayerJoinEvent, PlayerJoinEvent)
		self.register_event(self.onPlayerPortalEvent, PlayerPortalEvent)
		self.register_event(self.onPlayerRespawnEvent, PlayerRespawnEvent)

		register_command(self.spawnCommand, "spawn", permission="omneity.spawn.tp")
Пример #45
0
 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
Пример #46
0
    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()
Пример #47
0
 def __init__(self):
     globalhotkeys.init()
     self.hotkey = globalhotkeys.GlobalHotkey()
     self.bind_success = self.hotkey.bind(ConfigManager.get_conf('global-key'), lambda w: self.show_hide(), None)
     self.apps = []
     self.old_apps = []
     self.screenid = 0
     self.on_doing = False
     self.is_running = False
Пример #48
0
 def slide_down(self, i=1):
     step = ConfigManager.get_conf('step-count')
     self.slide_effect_running = True
     if not self.is_fullscreen:
         win_rect = self.monitor
     else:
         win_rect = self.get_screen_rectangle()
     if self.get_window() != None:
         self.get_window().enable_synchronized_configure()
     if i < step + 1:
         self.resize(win_rect.width, int(((win_rect.height/step) * i)))
         self.queue_resize()
         self.resizer.set_property('position', int(((win_rect.height/step) * i)))
         self.resizer.queue_resize()
         self.update_events()
         GObject.timeout_add(ConfigManager.get_conf('step-time'), self.slide_down, i+1)
     if self.get_window() != None:
         self.get_window().configure_finished()
     self.slide_effect_running = False
Пример #49
0
def main():
    GObject.threads_init()
    app = TerminalWin()

    keybinding = GlobalKeyBinding()
    app.keybinding = keybinding
    ConfigManager.ref_keybinding = keybinding
    ConfigManager.ref_show_hide = app.show_hide
    keybinding.connect('activate', lambda w: app.show_hide())
    if not keybinding.grab():
        ConfigManager.set_conf('losefocus-hiding', 'False')
        ConfigManager.set_conf('hide-on-start', 'False')
        app.update_ui()
        msgtext = "Another application using '%s'. Please open preferences and change the shortcut key." % ConfigManager.get_conf('global-key')
        msgbox = Gtk.MessageDialog(app, Gtk.DialogFlags.DESTROY_WITH_PARENT, Gtk.MessageType.WARNING, Gtk.ButtonsType.OK, msgtext)
        msgbox.run()
        msgbox.destroy()
    else:
        keybinding.start()
    Gtk.main()
Пример #50
0
 def slide_up(self, i=0):
     self.slide_effect_running = True
     step = ConfigManager.get_conf('step-count')
     if not self.is_fullscreen:
         win_rect = self.monitor
     else:
         win_rect = self.get_allocation()
     if self.get_window() != None:
         self.get_window().enable_synchronized_configure()
     if i < step+1:
         self.resize(win_rect.width, win_rect.height - int(((win_rect.height/step) * i)))
         self.queue_resize()
         self.update_events()
         GObject.timeout_add(ConfigManager.get_conf('step-time'), self.slide_up, i+1)
     else:
         self.hide()
         self.unrealize()
     if self.get_window() != None:
         self.get_window().configure_finished()
     self.slide_effect_running = False
Пример #51
0
    def __init__(self):
        super(TerminalWin, self).__init__()

        self.keybinding = None
        self.builder = Gtk.Builder()
        self.builder.add_from_file(ConfigManager.data_dir + 'ui/main.ui')

        ConfigManager.add_callback(self.update_ui)
        ConfigManager.show_hide_callback = self.show_hide

        self.screen = self.get_screen()
        self.losefocus_time = 0
        self.init_transparency()
        self.init_ui()
        self.add_page()
        self.update_ui()
        

        if ConfigManager.get_conf('hide-on-start'):
            self.hide()
Пример #52
0
    def __init__(self, name, monitor):
        super(TerminalWin, self).__init__()

        self.builder = Gtk.Builder()
        self.builder.set_translation_domain('terra')
        self.builder.add_from_file(ConfigManager.data_dir + 'ui/main.ui')
        self.name = name
        self.screen_id = int(name.split('-')[1])
        ConfigManager.add_callback(self.update_ui)
        
        self.screen = self.get_screen()
        self.monitor = monitor

        self.init_transparency()
        self.init_ui()
        self.update_ui()

        if not ConfigManager.get_conf('hide-on-start'):
            self.show_all()
        self.paned_childs = []
Пример #53
0
class TC_LOI_FUNC(unittest.TestCase):
    @classmethod
    def setUpClass(self):
        self.dev = Device(TEST_DEVICE)
        self.mGS = GSMonitor(self.dev)
        self.mCfg = ConfigManager(self.dev)

    @classmethod
    def tearDownClass(self):
        self.mCfg.close()
        self.mGS.close()
        self.dev.close()

    def test_loi_generating(self):
        self.assertEqual(self.dev.isFSRunning(), True, "Fusion Sensor is not running.")
        self.mCfg.setLoiMode()
        time.sleep(8*60)
        self.assertTrue(self.dev.isNewDataOnDevice("loi") or self.mGS.isNewLoiUploaded(),
                    "Failed to find new loi data"
                )
        print("Loi generating is approved")
Пример #54
0
class TC_ZC_FUNC(unittest.TestCase):
    @classmethod
    def setUpClass(self):
        self.dev = Device(TEST_DEVICE)
        self.mGS = GSMonitor(self.dev)
        self.mCfg = ConfigManager(self.dev)

    @classmethod
    def tearDownClass(self):
        self.mCfg.close()
        self.mGS.close()
        self.dev.close()

    def test_zc_generating(self):
        self.assertEqual(self.dev.isFSRunning(), True, "Fusion Sensor is not running.")
        self.mCfg.setZoneCountMode()
        time.sleep(5*60)
        self.assertTrue(self.dev.isNewDataOnDevice("zone-count") or self.mGS.isNewZoneCountUploaded(),
                    "Failed to find new zone-count data"
                )
        print("ZoneCount generating is approved")
Пример #55
0
class XpListener(BaseListener):

	default_config = {
			'xp_buff': 5
		}

	def __init__(self, plugin):
		self.plugin = plugin

	def onEnable(self):
		self.config_manager = ConfigManager(path.join(self.plugin.getDataFolder().getAbsolutePath(), 'xp.yml'), default=self.default_config)
		self.config_manager.load_config()

		self.register_event(self.onPlayerExpChangeEvent, PlayerExpChangeEvent)

	def onDisable(self):
		self.config_manager.save_config()

	def onPlayerExpChangeEvent(self, event):

		event.setAmount(event.getAmount()*self.config_manager.config['xp_buff'])