Ejemplo n.º 1
0
 def add_entry(self, entry_id, entry_name, index):
     # container = BoxLayout(
     #     # id=F"{entry_id}c",
     #     orientation='horizontal',
     #     size_hint=(1, None),
     #     height=config.get('entries_height'),
     # )
     entry_note = Button(
         id=F"{entry_id}e",
         text=str(lang.get('open_entry_note')),
         size_hint=(0.2, None),
         height=config.get_option_value('entries_height'),
         font_size=config.get_option_value('entries_font_size'),
         on_release=self.open_notes_screen,
     )
     entry = Button(
         id=str(entry_id),
         text=str(entry_name),
         size_hint=(1, None),
         height=config.get_option_value('entries_height'),
         font_size=config.get_option_value('entries_font_size'),
         on_release=self.complete_entry,
     )
     # container.add_widget(entry_note)
     # container.add_widget(entry)
     # self.ids.entries_panel_id.add_widget(container, index)
     self.ids.entries_panel_id.add_widget(entry_note, index)
     self.ids.entries_panel_id.add_widget(entry, index)
Ejemplo n.º 2
0
 def __init__(self, cfg):
     settings = ConfigParser(cfg)
     super(Application, self).__init__(
         template_path=os.path.join(os.path.dirname(__file__), 'templates'),
         static_path=os.path.join(os.path.dirname(__file__), 'static'),
         autoreload=settings.get('DEBUG'),
         cookie_secret=settings.get('SECRET_KEY'),
         compiled_template_cache=not settings.get('DEBUG'),
         gzip=True,
         **settings
     )
     self.configure_routes()
Ejemplo n.º 3
0
def run_migrations():
    current_db_version = int(config.get_option_value('db_version'))
    available_db_version = int(config.get_option_value('available_db_version'))
    if available_db_version > current_db_version:  # need to run migrations
        sqlite_connection = sqlite3.connect(db_path)
        for key, value in migrations_list.items():
            if key > current_db_version:
                cursor = sqlite_connection.cursor()
                cursor.execute(value)
                cursor.close()
                current_db_version = key
        sqlite_connection.commit()
        sqlite_connection.close()
        config.set_option_value('db_version', current_db_version)
Ejemplo n.º 4
0
 def __init__(self, **kwargs):
     super(HistoryScreen, self).__init__(**kwargs)
     # self.current_list_id = EntriesScreen.current_list_id
     # self.current_list_name = EntriesScreen.current_list_name
     self.entries_list = []
     self.entries_list_to_delete = []
     self.sorting_type = config.get_option_value('history_sorting')
Ejemplo n.º 5
0
def run(config_fname):
    with open(config_fname, 'r', encoding='utf8') as f:
        config_params = yaml.load(f, Loader=yaml.Loader)
        config_params['config_file_name'] = config_fname

    config = ConfigParser.from_args(config_params)
    main(config)
Ejemplo n.º 6
0
 def open_list(self, btn_obj):
     EntriesScreen.current_list_id = btn_obj.id
     EntriesScreen.current_list_name = db.get_list_name(btn_obj.id)
     self.manager.transition = CardTransition(
         direction='left',
         duration=float(
             config.get_option_value('screen_transition_duration')))
     self.manager.current = "entries_screen"
Ejemplo n.º 7
0
 def build(self):
     # TODO refactor backgroung - handle list type for config.get()
     backgroung_dict = {
         'Orange': [0.8, 0.4, 0.0, 1],
         "White": [1.0, 1.0, 1.0, 1],
         "Black": [0, 0, 0, 1],
     }
     Window.clearcolor = backgroung_dict[config.get_option_value(
         'background_colour')]
     Window.softinput_mode = 'below_target'  # TextInput keyboard position https://android.developreference.com/article/19684878/Android+on-screen+keyboard+hiding+Python+Kivy+TextInputs
     # TODO move ALL paths to system settings
     self.icon = 'images/icon.png'
     self.title = F"{config.get_option_value('app_title')}  {config.get_option_value('app_version')}"
     config.load_config()
     db.create_db()
     lang.reload_lang()
     return ScreenManagement()
Ejemplo n.º 8
0
def read_entries_by_name_part(list_id: int, name_part: str) -> list:
    count = int(config.get_option_value('max_suggestions_count'))
    sqlite_connection = sqlite3.connect(db_path)
    cursor = sqlite_connection.cursor()
    query = '''SELECT name FROM `Entries` WHERE list_id = ? and name like ? and is_completed = 1 ORDER BY frequency DESC LIMIT ?;'''
    cursor.execute(query, (list_id, name_part + '%', count))
    records = cursor.fetchall()
    cursor.close()
    sqlite_connection.close()
    return records
Ejemplo n.º 9
0
 def add_entry(self, entry_id, entry_name, index):
     entry = Button(
         id=str(entry_id),
         text=str(entry_name),
         size_hint=(1, None),
         height="70dp",
         font_size=config.get_option_value('entries_font_size'),
         on_release=self.tag_entry_to_delete,
     )
     self.ids.history_panel_id.add_widget(entry, index)
Ejemplo n.º 10
0
    def __init__(self, config_file='config.ini'):
        self.all_config = ConfigParser(config_file)
        self.response_seq = self.all_config.get("RESPONSE_SEQ")
        self.encode_type = self.all_config.get("ENCODE_TYPE")
        # print "@"*88,"all_config=", self.all_config
        ip = self.all_config.get('IP')
        port = self.all_config.get('PORT')
        address = (ip, port)
        websocket.enableTrace(True)
        self.client = websocket.WebSocketApp(url='ws://%s:%s' % address,
                                             on_message=self.on_message,
                                             on_open=self.on_open,
                                             on_close=self.on_close,
                                             on_error=self.on_error)

        self.fmt = 'iii'
        self.version = 0
        self.head_len = struct.calcsize(self.fmt)
        print "encode_type=", self.encode_type
        self.aes_encoder = AesEncoder(encode_type=self.encode_type)
Ejemplo n.º 11
0
 def add_list(self, list_id, list_name, index):
     list_btn = Button(
         id=str(list_id),
         font_size=config.get_option_value('lists_font_size'),
         size_hint=(1, None),
         height="70dp",
     )
     if self.edit_mode:
         list_btn.bind(on_release=self.open_edit_popup)
         list_btn.text = F"{list_name}{lang.get('tap_to_edit')}"
     else:
         list_btn.bind(on_release=self.open_list)
         list_btn.text = F"{list_name} ({str(db.read_entries_count(list_id))})"
     self.ids.lists_panel_id.add_widget(list_btn, index)
Ejemplo n.º 12
0
class SettingsScreen(Screen):
    # TODO fix bug with font_size not apply on save(same as lang)
    # TODO move all kv strings to lang

    def __init__(self, **kwargs):
        super(SettingsScreen, self).__init__(**kwargs)

    current_settings = DictProperty({
        'background_colour':
        config.get_option_value('background_colour'),
        'lang':
        config.get_option_value('lang'),
        'entries_font_size':
        config.get_option_value('entries_font_size'),
        'lists_font_size':
        config.get_option_value('lists_font_size'),
        'max_suggestions_count':
        config.get_option_value('max_suggestions_count'),
        'font_size':
        config.get_option_value('font_size'),
        'padding':
        config.get_option_value('padding'),
        'spacing':
        config.get_option_value('spacing'),
        'scrollview_size':
        config.get_option_value('scrollview_size'),
    })

    def get_current_settings(self):
        for key in self.current_settings:
            self.current_settings[key] = config.get_option_value(key)

    @staticmethod
    def reset_db():
        db.recreate_database()

    def apply_settings(self):
        for key in self.current_settings:
            config.set_option_value(key, self.current_settings[key])
        # TODO lang reload doesnt work
        MainApp.build(self)
Ejemplo n.º 13
0
def reload_lang():
    lang_dict.clear()
    try:
        # this var is not useless. If no lang key in main.ini - this row trigger exception
        system_language = config.get_option_value('lang')
    except:
        system_default_lang = locale.getdefaultlocale()[0][:2]
        if system_default_lang in ('EN', 'en'):
            config.set_option_value('lang', 'en')
        elif system_default_lang in ('RU', 'ru'):
            config.set_option_value('lang', 'ru')
        else:
            config.set_option_value('lang', 'en')
    finally:
        system_language = config.get_option_value('lang')

    with codecs.open("lang/{}.ini".format(system_language), encoding='utf-8') as myfile:
        for line in myfile:
            name, var = line.partition("=")[::2]
            lang_dict[name.strip()] = str(var).rstrip('\n')
Ejemplo n.º 14
0
def main():
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

    config = ConfigParser.parse_config()

    loader = LoaderHandler(config)

    embedding_path = config['model']['embedding']
    embedding = torch.FloatTensor(np.load(embedding_path))
    vocab_size = len(embedding)

    hidden_size = config['model']['hidden_size']
    batch_size = config['loader']['batchSize']
    encoder = EncoderRNN(vocab_size, 100, hidden_size, batch_size,
                         embedding).to(device)
    decoder = DecoderRNN(vocab_size, 100, hidden_size, batch_size,
                         embedding).to(device)

    trainIters(loader, encoder, decoder, 30, device, learning_rate=0.01)
Ejemplo n.º 15
0
def run_tag_creator(args: argparse.Namespace):
    print(">>> Reading config file...")
    if args.conf is None:
        args.conf = ConfigParser.parse()
    print(">>> Config file read : {}".format(args.conf))

    print(">>> Configuring repository...")
    if args.repo is None:
        args.repo = Repo(args.conf["repo"]["path"])
    print(">>> Repository configured : {}".format(args.repo))

    if args.environment is None:
        args.environment = args.conf["default"]["environment"]
    elif args.environment not in args.conf["environment"]:
        print(">>> Environment couldn't be found on config : {}".format(args.environment))
        exit(-1)
    print(">>> Environment configured : {}".format(args.environment))

    if args.branch is None:
        args.branch = args.conf["environment"][args.environment]["branch"]

    if args.commit:
        print(">>> Checking out to {}...".format(args.commit))
        if args.repo.checkout(commit=args.commit):
            print(">>> Check out completed!")
        else:
            exit(-1)
    else:
        print(">>> Checking out to {}...".format(args.branch))
        if args.repo.checkout(branch=args.branch):
            print(">>> Check out completed!")
        else:
            exit(-1)

    if args.fetch:
        print(">>> Fetching...")
        if args.repo.fetch():
            print(">>> Fetch completed!")
        else:
            exit(-1)
    else:
        print(">>> Fetch not set, skipping fetch!")

    if args.pull:
        print(">>> Pulling...")
        if args.repo.pull(branch=args.branch):
            print(">>> Pull completed!")
        else:
            exit(-1)
    else:
        print(">>> Pull not set, skipping pull!")

    if args.tag:
        new_tag = args.tag
    else:
        tag_config = args.conf["environment"][args.environment]["tag"]
        print(">>> Environment configuration read for tag limits : {}".format(tag_config))
        prefix, *_ = tag_config.values()
        max_values = {k: v for k, v in tag_config.items() if k.startswith("max")}
        base_ver = Version(**max_values)
        tags = []
        print(">>> Reading existing tags for environment...")
        for tag in args.repo.tags():
            if tag.startswith(prefix):
                try:
                    tags.append(base_ver.parse(tag))
                except VersionError as err:
                    print(">>> Tag exceeds configured environment tag limits({}) : {}".format(base_ver.maximum(), tag))
                    print(err)
        new_tag = max(tags).next()
    print(">>> New tag : {}".format(new_tag))
    if args.repo.create_tag(tag_name=str(new_tag), commit=args.commit):
        print(">>> Tag created : {}".format(str(new_tag)))
    else:
        print(">>> Tag couldn't be created!")
        exit(-1)

    if args.push:
        print(">>> Pushing...")
        if args.repo.push(branch=args.branch):
            print(">>> Push completed!")
        else:
            exit(-1)
    else:
        print(">>> Push not set, skipping push!")
Ejemplo n.º 16
0
class BaseTestClient(object):
    def __init__(self, config_file='config.ini'):
        self.all_config = ConfigParser(config_file)
        self.response_seq = self.all_config.get("RESPONSE_SEQ")
        self.encode_type = self.all_config.get("ENCODE_TYPE")
        # print "@"*88,"all_config=", self.all_config
        ip = self.all_config.get('IP')
        port = self.all_config.get('PORT')
        address = (ip, port)
        websocket.enableTrace(True)
        self.client = websocket.WebSocketApp(url='ws://%s:%s' % address,
                                             on_message=self.on_message,
                                             on_open=self.on_open,
                                             on_close=self.on_close,
                                             on_error=self.on_error)

        self.fmt = 'iii'
        self.version = 0
        self.head_len = struct.calcsize(self.fmt)
        print "encode_type=", self.encode_type
        self.aes_encoder = AesEncoder(encode_type=self.encode_type)

    def pack(self, data, command_id):
        """
        打包消息, 用於傳輸
        :param data:  傳輸數據
        :param command_id:  消息ID
        :return:
        """
        data = json.dumps(data)
        data = self.aes_encoder.encode(data)
        data = "%s" % data
        length = data.__len__() + self.head_len
        # head = struct.pack("", length, command_id, self.version)
        head = struct.pack(self.fmt, length, command_id, self.version)
        return str(head + data)

    def unpack(self, data):
        # print "!"*20,"data=",[data]
        if len(data) < self.head_len:
            return None

        head = data[0:self.head_len]
        list_head = struct.unpack(self.fmt, head)
        # print "-"*30,'return head is',list_head
        result = data[self.head_len:]
        if self.encode_type == 1:
            result = self.aes_encoder.decode_aes(result)
        if not result:
            result = {}
            # return None
        return {'result': True, 'command': list_head[1], 'data': result}

    def send(self, data):
        self.client.send(data, opcode=websocket.ABNF.OPCODE_BINARY)

    def on_message(self, ws, message):
        print "on_message:"

    def on_error(self, ws, error):
        print '====== ERROR ======'
        print error
        print '====== ERROR ======'

    def on_close(self, ws):
        print '### closed ###'

    def on_open(self, ws):
        print '### opened ###'
        raise NotImplementedError

    def run(self):
        # print "ccccccccccccccccccccccccccccclient:", self.client
        self.client.run_forever()
Ejemplo n.º 17
0
 def __init__(self, name, config_file):
     self.__name__ = name
     self.config = ConfigParser(config_file)
     self.supports_visual = False
Ejemplo n.º 18
0
 def change_screen(self, screen_name, direction):
     self.transition = CardTransition(
         direction=direction,
         duration=float(
             config.get_option_value('screen_transition_duration')))
     self.current = screen_name
Ejemplo n.º 19
0
 def apply_settings(self):
     for key in self.current_settings:
         config.set_option_value(key, self.current_settings[key])
     # TODO lang reload doesnt work
     MainApp.build(self)
Ejemplo n.º 20
0
 def get_current_settings(self):
     for key in self.current_settings:
         self.current_settings[key] = config.get_option_value(key)
Ejemplo n.º 21
0
import os.path
import sqlite3

import utils.ConfigParser as config

db_path = config.get_option_value('db_path')

migrations_list = {
    1: '''ALTER TABLE `Entries` ADD COLUMN note TEXT;''',
}


def create_db():
    if not os.path.exists(db_path):
        recreate_database()


# TODO add feature to backup db and load from backup
# TODO default lists and entries - make it lang related
def recreate_database():
    sqlite_connection = sqlite3.connect(db_path)
    sqlite_drop_lists = "DROP TABLE IF EXISTS Lists"
    sqlite_drop_entries = "DROP TABLE IF EXISTS Entries"
    sqlite_create_lists = '''
    CREATE TABLE Lists (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT UNIQUE NOT NULL,
    order_id INTEGER,
    created_date datetime DEFAULT (datetime('now','localtime'))); 
    '''
    sqlite_create_entries = '''
Ejemplo n.º 22
0
 def __call__(self, parser, namespace, value, option_string=None):
     if option_string in self.option_strings:
         setattr(namespace, self.dest, ConfigParser.parse(value))