Example #1
0
    def b_create_new_qrcode_click(self):
        """Creates a new QR-Code for a device"""
        device = self.ui.treeWidget.currentItem().text(0)
        try:
            device_uid = re.match(r"(?:.* mit ID )(?P<ID>\d+)$",
                                  device).group("ID")
        except AttributeError:
            self.status_bar_text("Es konnte leider kein Gerät erkannt werden",
                                 8, "red")
            return

        with CSession() as session:
            device = session.query(
                classes.Device).filter_by(uid=device_uid).first()
            filename = utils.normalize_filename(
                f"{device.uid}_{device.article.name}.svg")
            path = pathlib.Path(config["qr_path"])
            path /= filename
            if not utils.check_if_file_exists(path):
                self.status_bar_text(
                    f"{path} ist kein gültiger Pfad/eine bereits vorhandene Datei",
                    5, "red")
                return
            try:
                generate_qr(device, path)
            except NotImplementedError as e:
                logger.error(str(e))
                self.status_bar_text(
                    f"Um {e[1]} Dateien zu speichern sind weitere Pakete nötig. Das Standartformat ist svg",
                    10, "red")
            else:
                self.status_bar_text(
                    f"Der QR-Code wurde unter {config['qr_path']} gespeichert",
                    8, "green")
Example #2
0
    def b_create_device_click(
        self
    ):  # todo: handle if logged in user is no admin and can't create devices for others
        article = self.cb_article_d.currentText()
        location = self.cb_location_d.currentText()
        user = self.cb_user_d.currentText()
        path = self.t_path_device.text()
        locals_ = {
            key: value
            for (key, value) in locals().items() if key != "self"
        }
        if "" in locals_.values():
            self.not_all_fields_filled_notice()
            return

        path = pathlib.Path(path)
        user_uid = int(user.split(" ")[0])
        with CSession() as session:
            article = session.query(
                classes.Article).filter_by(name=article).first()
            user = session.query(classes.User).filter_by(uid=user_uid).first()
            location = session.query(
                classes.Location).filter_by(name=location).first()
            if self.logged_in_user:
                if user.uid != self.logged_in_user.uid and not self.logged_in_user.is_admin:
                    self.status_bar_text(
                        "Um Geräte für einen anderen Nutzer zu erzeugen ist ein Administrator nötig!",
                        5, "red")
                    return
            else:
                self.status_bar_text(
                    "Um Geräte zu erzeugen müssen Sie eingeloggt sein", 5,
                    "red")
                return
            device = classes.Device()
            session.add(device)
            device.article = article
            resp = classes.Responsibility(device, user, location)
            session.add(resp)
        path = pathlib.Path(self.t_path_device.text())
        if not re.match(r".*\.(?P<filetype>.*$)", str(path), re.IGNORECASE):
            path /= utils.normalize_filename(
                f"{device.uid}_{device.article.name}.svg")
        if not utils.check_if_file_exists(path):
            self.status_bar_text(
                f"{path} ist kein gültiger Pfad/eine bereits vorhandene Datei",
                5, "red")
            return
        try:
            generate_qr(device, path)
        except NotImplementedError as e:
            logger.error(str(e))
            self.status_bar_text(
                f"Um {e[1]} Dateien zu speichern sind weitere Pakete nötig. Das Standartformat ist svg",
                10, "red")
        else:
            self.status_bar_text(
                f"Gerät erfolgreich angelegt. Der QR-Code wurde unter {path} gespeichert",
                10, "green")
Example #3
0
def site(url):
    if check_if_file_exists(txt_src_folder + url + ".md"):
        file = open(txt_src_folder + url + ".md", "r")
        return html_head(url.replace(
            ".md", empty_string)) + "<body>" + top_bar('blog') + md_file2html(
                file) + "</body></html>"
    else:
        return "<h1>404 Not Found</h1>", 404
Example #4
0
def setup():  # returns None
    # create directory if needed
    for dir in const.BASIC_DIR_TREE:
        if utils.check_if_directory_exists(dir) == False:
            utils.create_directory(dir)
    # create files if needed
    if utils.check_if_file_exists(const.CONFIG_FILE) == False:
        # utils.create_file(const.CONFIG_FILE)
        do_file_from_list(const.CONFIG_FILE, const.DEFAULT_CONFIG_FILE)
    if utils.check_if_file_exists(const.KEYS_DOWN_FILE) == False:
        utils.create_file(const.KEYS_DOWN_FILE)
        do_file_from_list(const.KEYS_DOWN_FILE, const.DEFAULT_KEYS_DOWN_FILE)
    if utils.check_if_file_exists(const.KEYS_UP_FILE) == False:
        utils.create_file(const.KEYS_UP_FILE)
        do_file_from_list(const.KEYS_UP_FILE, const.DEFAULT_KEYS_UP_FILE)
    if utils.check_if_file_exists(const.MODS_FILE) == False:
        utils.create_file(const.MODS_FILE)
        do_file_from_list(const.MODS_FILE, const.DEFAULT_MODS_FILE)
def scrape(source_file, dir_name):
    # Check if file that contain image list is exists
    utils.check_if_file_exists(source_file)

    # create directory
    utils.check_if_directory_exists(dir_name)

    # get list of pokemon from pokedex file
    a_file = open(source_file)
    data = a_file.read()
    a_file.close()
    pokemons = re.findall(r'(.*?)\s(.*?)\n', data)

    # container for failed images
    not_retrieved = []

    # loop through list
    for pokemon in pokemons:
        try:
            subprocess.check_output([
                'wget http://img.pokemondb.net/artwork/large/' + pokemon[1] +
                '.jpg -q --show-progress'
            ],
                                    shell=True)
            subprocess.check_output([
                'mv ' + pokemon[1] + '.jpg ' + dir_name + '/' + pokemon[0] +
                '_' + pokemon[1] + '.jpg'
            ],
                                    shell=True)
        except Exception:
            not_retrieved.append(pokemon)

    # print message if there is one or more file that is failed to downloaded
    if len(not_retrieved) > 0:
        message.msg_img_not_retrieved()

    # save the list of failed image
    i = 1
    with open("not_retrieved", "w") as txt_file:
        for line in not_retrieved:
            txt_file.write(line[0] + ' ' +
                           line[1].encode('utf-8').strip().lower() + "\n")
            i += 1
Example #6
0
def get_image(token):

    if not utils.verify_token(token):
        abort(401)

    image_uuid = utils.verify_token(token)

    if not utils.check_if_file_exists(image_uuid):
        abort(404)

    return send_from_directory(app.config['UPLOAD_FOLDER'],
                               '{}.png'.format(image_uuid),
                               as_attachment=False)
Example #7
0
def read_user_data(user_id):
    user_string = user_dir + "/" + str(user_id)
    user_cash = str(starting_currency)
    user_data = {"cash": str(user_cash), "last_daily": str(date.today())}

    utils.check_if_dir_exists(user_dir)
    if utils.check_if_file_exists(user_string):
        with open(user_string) as json_file:
            user_data = json.load(json_file)
    else:
        print("User does not have a profile, creating new storage for user " + str(user_id))
        f = open(user_string, "w")
        f.write("temp")
        f.close()
        with open(user_string, "w") as json_file:
            json.dump(user_data, json_file)

    return user_data
Example #8
0
def write_user_data(user_id, new_value):
    utils.check_if_dir_exists(user_dir)
    user_string = user_dir + "/" + user_id
    utils.check_if_dir_exists(user_dir)
    if utils.check_if_file_exists(user_string):
        with open(user_string, "r+") as json_file:
            final_data = {}
            user_data = json.load(json_file)
            json_file.seek(0)
            json_file.truncate(0)
            if "cash" in new_value:
                final_data["cash"] = new_value["cash"]
            else:
                final_data["cash"] = user_data["cash"]

            if "last_daily" in new_value and new_value["last_daily"] != user_data["last_daily"]:
                final_data["last_daily"] = new_value["last_daily"]
            else:
                final_data["last_daily"] = user_data["last_daily"]
            json.dump(final_data, json_file)
            json_file.close()
Example #9
0
    async def on_raw_reaction_add(self, payload):
        if payload.user_id == self.user.id:
            return

        try:
            channel = client.get_channel(payload.channel_id)
            message = await channel.fetch_message(payload.message_id)

            if self.is_configured is False and self.configure_message_id != 0 and payload.user_id == message.guild.owner_id:
                setup_msg = await message.channel.fetch_message(
                    self.configure_message_id)
                if str(
                        payload.emoji
                ) not in self.command_emojis and not setup.is_setup_finished():
                    setup.set_emoji_symbol(setup.return_first_none_emoji(),
                                           str(payload.emoji))
                    emoji_to_set = setup.return_first_none_emoji()
                    if emoji_to_set is not None:
                        text_content = "React to this message with any emoji aside from " + " ".join(
                            self.command_emojis)
                        text_content = text_content + "to set as visible value: `" + emoji_to_set + "`"
                        await setup_msg.edit(content=text_content)
                        await setup_msg.clear_reactions()

                    setup.create_configuration(message.guild.id)
                    self.is_configured = setup.is_setup_finished()
            if self.is_configured is not False:
                if payload.emoji.name == '♻':
                    await message.clear_reactions()
                    await jelonki.update_user_cash_message(payload=payload,
                                                           message=message)
                if payload.emoji.name == '🥉':
                    await self.clear_msg(message)
                    await linie.spin(message=message,
                                     bet="50",
                                     payload=payload)
                if payload.emoji.name == '🥈':
                    await self.clear_msg(message)
                    await linie.spin(message=message,
                                     bet="100",
                                     payload=payload)
                if payload.emoji.name == '🥇':
                    await self.clear_msg(message)
                    await linie.spin(message=message,
                                     bet="500",
                                     payload=payload)
                if payload.emoji.name == '🔊':
                    if payload.member.voice is not None and utils.check_if_file_exists(
                            "muzyka.mp3"):
                        if payload.member.voice.channel is not None:
                            channel = payload.member.voice.channel
                            self.self_vp = await channel.connect()
                            source = discord.PCMVolumeTransformer(
                                discord.FFmpegPCMAudio("muzyka.mp3"),
                                volume=0.15)
                            self.self_vp.play(source)
                            await messages.add_reactions(message)
                    else:
                        await channel.send(
                            "<!@{}> https://www.wykop.pl/cdn/c3201142/comment_ySeT49KshJdcuuoj9zkwOPvVLaulUvek.jpg"
                            .format(payload.member.id))
                if payload.emoji.name == '🔇':
                    if payload.member.voice is not None:
                        if payload.member.voice.channel is not None or self.self_vp is not None:
                            await self.self_vp.disconnect()
                            await messages.add_reactions(message)
                    else:
                        await channel.send(
                            "<!@{}> https://www.wykop.pl/cdn/c3201142/comment_ySeT49KshJdcuuoj9zkwOPvVLaulUvek.jpg"
                            .format(payload.member.id))

        except discord.HTTPException:
            pass
Example #10
0
    async def on_message(self, message):
        if message.author.id == self.user.id:
            return

        if message.content.startswith('$start'):
            await messages.print_bot_message(self, message)
        #
        # if message.content.startswith('$juz'):
        #     await message.channel.send("Czy mam ustawione emotki? " + str(setup.is_setup_finished()))
        #     await message.channel.send("Czy jestem skonfigurowany? " + str(self.is_configured))
        #     await message.channel.send(" ".join(setup.return_emoji_symbols().values()))

        if message.content.startswith('$sprzataj'):
            if message.author.id == message.guild.owner_id:
                await self.clear_msg(message)

        # if message.content.startswith('$avatar'):
        #     with open('avatar.jpg', 'rb') as f:
        #         image = f.read()
        #
        #     await self.user.edit(avatar=image)

        # if message.content.startswith('$zbigniew'):
        #     for attachment in message.attachments:
        #         await message.channel.send(attachment.url)

        if message.content.startswith('$czy'):
            user_id = '<@{}>'.format(str(message.author.id))
            if message.author.voice is not None and utils.check_if_file_exists(
                    "test.mp3"):
                channel = message.author.voice.channel
                self.self_vp = await channel.connect()
                source = discord.PCMVolumeTransformer(
                    discord.FFmpegPCMAudio("test.mp3"), volume=0.15)
                self.self_vp.play(source)
                await asyncio.sleep(10)
                await self.self_vp.disconnect()
            else:
                await message.channel.send(
                    user_id + " https://www.youtube.com/watch?v=2vbYlqgWZk8")

        # if message.content.startswith('$doladuj'):
        #     await jelonki.add_cash(message)
        #
        # if message.content.startswith('$debug'):
        #     hajs_float = re.search("\d+\.\d+", message.content)
        #
        #     if hajs_float is None:
        #         hajs_int = int(re.search("\d+", message.content).group())
        #         if len(str(hajs_int)) == 1:
        #             hajs_int = hajs_int * 100
        #     else:
        #         hajs_float = float(hajs_float.group())
        #         hajs_int = int(hajs_float * 100)

        # await linie.modify_cash(message.author.id, hajs_int)

        if message.content.startswith('$daily'):
            await jelonki.add_daily_cash(message)

        if message.content.startswith('$hajs'):
            await jelonki.print_user_cash(client=self, message=message)

        if message.content.startswith('$set'):
            config = setup.read_configuration(message.guild.id)
            if config is not None:
                setup.emoji_symbols = config
                self.is_configured = setup.is_setup_finished()
                text_content = "Read existing configuration, set emoji to: " + " ".join(
                    setup.emoji_symbols.values())
                await message.channel.send(text_content)

            # if message.author.id == message.guild.owner_id and self.configure_message_id == 0 and self.is_configured is False:
            if self.configure_message_id == 0 and self.is_configured is False:
                emoji_to_set = setup.return_first_none_emoji()
                text_content = "React to this message with any emoji aside from " + " ".join(
                    self.command_emojis)
                text_content = text_content + "to set as visible value: `" + emoji_to_set + "`"
                setup_msg = await message.channel.send(text_content)
                self.configure_message_id = setup_msg.id
Example #11
0
import numpy as np
import pandas as pd
from psychopy import event, data, visual, core, logging

from utils import (check_if_file_exists, gen_paths, gen_concentration_steps,
                   get_start_val, get_exp_info, load_exp_info, save_exp_info,
                   get_bottle_index, gen_visual_stimuli, find_nearest, plot)

exp_info_loaded = load_exp_info()
exp_info = get_exp_info(exp_info_loaded)

save_exp_info(exp_info)

path = gen_paths(exp_info)

if check_if_file_exists(path['csv_filename']):
    core.quit()

log_file = logging.LogFile(path['log_filename'], level=logging.EXP)
logging.console.setLevel(logging.WARNING)

win = visual.Window(fullscr=False, screen=0, allowGUI=True, color=[0, 0, 0])
vis_stimuli = gen_visual_stimuli(win)

min_trials = 10
previous_concentration = None
previous_detection_successful = False
concentration_steps = np.log10(
    gen_concentration_steps()[exp_info['Substance']])

start_val = np.log10(get_start_val(exp_info['Substance']))
Example #12
0
 def test_check_if_file_exists(self):
     self.assertTrue(utils.check_if_file_exists("abc"))
     with open("abc", "w") as f:
         self.assertFalse(utils.check_if_file_exists("abc"))
     os.remove("abc")