Beispiel #1
0
    def __init__(self) -> None:
        if Mailer.__instance is not None:
            raise Exception("This class is a singleton!")

        Mailer.__instance = self

        self.init_ok: bool = False
        self.msg: EmailMessage = None
        self.smtp_host: str = Config.get('MAILER', 'smtp_host')
        self.smtp_port: str = Config.get('MAILER', 'smtp_port')
        self.smtp_user: str = Config.get('MAILER', 'smtp_user')
        self.smtp_password: str = Config.get('MAILER', 'smtp_password')

        _sender = Config.get('MAILER', 'sender')
        try:
            _receivers = Config.get('MAILER', 'receivers', param_type="json")
        except JSONDecodeError:
            Logger.get(self.__class__.__name__).warn('Problems decoding email receivers from JSON in config!')
            _receivers = None

        if not _sender or not _receivers or not self.smtp_host or not self.smtp_port:
            Logger.get(self.__class__.__name__).warn('Emails not being sent!')
            return

        self.msg = EmailMessage()
        self.msg.set_charset('utf-8')
        self.msg['From'] = _sender
        self.msg['To'] = _receivers

        self.init_ok = True
Beispiel #2
0
 def wrapper(*args, **kwargs):
     global query_counter
     start_time = time.perf_counter()
     with lock:
         query_counter += 1
         query_id = query_counter
     Logger.info(
         f'Query: query_id: <{query_id}> method: <{request.method}>; path=<{request.path}>'
     )
     return func(start_time=start_time, query_id=query_id, *args, **kwargs)
 def __init__(self) -> None:
     self.url = Config.get('URL_FETCHER', 'url')
     try:
         self.headers = Config.get('URL_FETCHER',
                                   'headers',
                                   param_type="json")
     except JSONDecodeError:
         Logger.get(self.__class__.__name__).warn(
             "Problem decoding URL headers from JSON in config!")
         self.headers = None
     self.content: Optional[str] = None
Beispiel #4
0
class AppMonitor(object):

    def __init__(self, config):
        self.name = config['name']
        self.limits = config['limits'].split(",")
        self.setup()

    def setup(self):
        client_id = uuid.uuid3(uuid.NAMESPACE_DNS, self.name)
        self.logger = Logger(str(client_id))

    def monitor(self, process):
        if not process.alive():
            raise NoSuchProcess(self.process_id)

        state = process.get_current_state()

        if state['cpu_percent'] < float(self.limits[0]):
            return

        level = "CAREFUL"

        if state["cpu_percent"] >= float(self.limits[1]):
            level = "WARNING"
        if state["cpu_percent"] >= float(self.limits[2]):
            level = "CRITICAL"

        status = state.copy()
        status.update(self.host_status())

        self.log(level, status)

    def host_status(self):
        # Add more stuff
        return { "system_cpu": psutil.cpu_percent() }

    def log(self, level, process):
        self.logger.log(level, process)

    def run(self, interval):
        process = Process(self.name)

        while True:
            try:
                with Timed(interval) as timed:
                    self.monitor(process)
                time.sleep(timed.interval)
            except psutil.Error as e:
                if isinstance(e, AccessDenied):
                    print "access denied:", e
Beispiel #5
0
def getDateAndTimeByKey(parameters, dt_key, task_id):
    dateValue = None
    timeValue = None

    if parameters.get("".join(["date", dt_key])):
        try:
            dateValue = parse(parameters.get("".join(["date", dt_key]))).date()
        except ValueError:
            Logger.warn(
                f"Bad date format. Continue running task without it. task_id: {task_id} \n"
                f"key=<{''.join(['date', dt_key])}>; value=<{parameters.get(''.join(['date', dt_key]))}>"
            )

    if parameters.get("".join(["time", dt_key])):
        try:
            timeValue = parse(" ".join(
                ["1970-01-01",
                 parameters.get("".join(["time", dt_key]))])).time()
        except ValueError:
            Logger.warn(
                f"Bad time format. Continue running task without it. task_id: {task_id} \n"
                f"key=<{''.join(['time', dt_key])}>; value=<{parameters.get(''.join(['time', dt_key]))}>"
            )

    Logger.debug(dateValue)
    Logger.debug(timeValue)

    return (dateValue, timeValue)
Beispiel #6
0
def change_file(fileid, start_time, query_id):
    if not Files.query.filter_by(fileid=fileid).all():
        code = 404
        Logger.info(
            f"Response: Query failed. query_id: <{query_id}>; err_code: <{code}>; "
            f"time: <{calc_time(start_time)} ms>")
        abort(code)

    if 'file' not in request.files or not request.files['file'].filename:
        code = 400
        Logger.info(
            f"Response: Query failed. query_id: <{query_id}>; err_code: <{code}>; "
            f"time: <{calc_time(start_time)} ms>")
        abort(code)

    # Изменение в бд
    with transaction():
        try:
            Data.query.filter_by(fileid=fileid).delete()
            Files.query.filter_by(fileid=fileid).update(
                {'filename': request.files['file'].filename})
            handleFile(fileid, request.files['file'])
        except HTTPException as ex:
            Logger.info(
                f"Response: Query failed. query_id: <{query_id}>; err_code: <{ex.code}>; "
                f"time: <{calc_time(start_time)} ms>")
            raise

    db.session.commit()

    Logger.info(f"Response: Query successed. query_id: <{query_id}>; "
                f"time: <{calc_time(start_time)} ms>")

    return '', 204
    def fetch(self) -> None:
        # noinspection PyBroadException
        try:
            response = requests.get(self.url, headers=self.headers)
        except Exception as e:
            Logger.get(self.__class__.__name__).error(str(e))
            self.content = None
            return

        if response.status_code >= 300:
            Logger.get(self.__class__.__name__).error('{}: {}'.format(
                response.status_code, response.reason))
            self.content = None
        else:
            self.content = response.content.decode('utf-8')
Beispiel #8
0
def create_app():

    Logger.info('Creating app...')
    app = Flask(__name__)
    Logger.info('App created')
    Logger.info('Configurating config...')
    app.config.from_object(app_config.currentConfig)
    Logger.info('Config configured')

    import app.server.queries.move_handler as move_handler

    app.register_blueprint(move_handler.move_handler)

    Logger.info('Blueprint registered')

    return app
    def start(self):
        """
        Função responsavel por rodar o Load Balance
        """
        ttask = 5
        while self.clock_tick < (len(self.users_per_clock_ticks) + ttask):

            if self.clock_tick < len(
                    self.users_per_clock_ticks) and self.users_per_clock_ticks[
                        self.clock_tick] > 0:
                self.user_manager(self.users_per_clock_ticks[self.clock_tick])

            for server in self.servers:
                server.run_tasks()

            self.balance_servers()

            for server in self.servers:
                if server.users_online() == 0:
                    self.servers.remove(server)

            self.sum_cost()
            self.log_line()
            self.clock_tick += 1

        Logger(f'Total Cost: ${format(self.total_cost, ".2f")}' + '\n' * 2)
def main():
    # application configuration
    config = os.path.join(os.getcwd(), "conf/main.yml")

    window = GameWindow()

    # override the default server settings when yaml file exists
    if os.path.exists(config):
        # open the file and store to the yaml_config variable
        yaml_config = open(config)

        # store the refernce to the config
        config = yaml_load(yaml_config)

        # PYRO:standard.deck@localhost:3000
        game_manager = PyroProxy(
            "PYRO:%s@%s:%d" %
            (config['app']['manager']['object_name'],
             config['app']['server']['host'], config['app']['server']['port']))

        # set the game deck
        window.set_game_manager(game_manager)

        # enable logging
        window.set_logger(Logger("BlackJack Client"))

        # close the file since we do not need it anymore
        yaml_config.close()

    # start application
    window.bootstrap()
Beispiel #11
0
    def send(cls, content: AbstractMailTemplate, subject: str = None) -> None:
        if Mailer.__instance is None:
            Mailer()

        if Mailer.__instance.init_ok:
            smtp = smtplib.SMTP_SSL("{}:{}".format(Mailer.__instance.smtp_host, Mailer.__instance.smtp_port))
            try:
                smtp.login(Mailer.__instance.smtp_user, Mailer.__instance.smtp_password)
            except smtplib.SMTPAuthenticationError as e:
                Logger.get(cls.__name__).warn(str(e))
                return
            Mailer.__instance.msg['Subject'] = subject if subject is not None else Config.get('MAILER', 'Subject')
            Mailer.__instance.msg.set_content(content.get())
            try:
                smtp.send_message(Mailer.__instance.msg)
            except smtplib.SMTPDataError as e:
                Logger.get(cls.__name__).warn(str(e))
            smtp.quit()
 def log_line(self):
     """
     Função que loga a linha no arquivo output.txt
     """
     line = ''
     for server in self.servers:
         line += str(server.users_online()) + ','
     line = line[:-1] + '\n'
     Logger(line)
def read_graphml(graph_file: str, log: Logger = None) -> ig.Graph:
    G = ig.Graph()
    G = G.Read_GraphML(graph_file)
    del (G.vs['id'])
    for attr in G.vs[0].attributes():
        try:
            converter = node_attr_converters[Node(attr)]
            G.vs[attr] = [converter(value) for value in list(G.vs[attr])]
        except Exception:
            if (log is not None):
                log.warning(f'failed to read node attribute {attr}')
    for attr in G.es[0].attributes():
        try:
            converter = edge_attr_converters[Edge(attr)]
            G.es[attr] = [converter(value) for value in list(G.es[attr])]
        except Exception:
            if (log is not None):
                log.warning(f'failed to read edge attribute {attr}')
    return G
Beispiel #14
0
def get_overlapping_paths(log: Logger,
                          param_path: Path,
                          compare_paths: List[Path],
                          buffer_m: int = None) -> List[Path]:
    """Returns [compare_paths] that are within a buffered geometry of [param_path].
    """
    overlapping_paths = [param_path]
    path_geom_buff = param_path.geometry.buffer(buffer_m)
    for compare_path in [
            compare_path for compare_path in compare_paths
            if compare_path.name != param_path.name
    ]:
        bool_within = compare_path.geometry.within(path_geom_buff)
        if (bool_within == True):
            overlapping_paths.append(compare_path)
    if (len(overlapping_paths) > 1):
        log.debug('found ' + str(len(overlapping_paths)) +
                  ' overlapping paths for: ' + param_path.name + ' - ' +
                  str([path.name for path in overlapping_paths]))
    return overlapping_paths
Beispiel #15
0
def file_info(fileid, start_time, query_id):
    if not Files.query.filter_by(fileid=fileid).all():
        code = 404
        Logger.info(
            f"Response: Query failed. query_id: <{query_id}>; err_code: <{code}>; "
            f"time: <{calc_time(start_time)} ms>")
        abort(code)

    try:
        # Соединение таблиц и получение информации
        fileinf = db.session.query(Files, func.count(Data.fileid).label('count_rows'))\
            .join(Files.data)\
            .group_by(Files.fileid)\
            .having(Files.fileid == fileid)\
            .first()
    except HTTPException as ex:
        Logger.info(
            f"Response: Query failed. query_id: <{query_id}>; err_code: <{ex.code}>; "
            f"time: <{calc_time(start_time)} ms>")
        raise

    Logger.info(f"Response: Query successed. query_id: <{query_id}>; "
                f"time: <{calc_time(start_time)} ms>")

    return jsonify(fileid=fileid,
                   filename=fileinf[0].filename,
                   first_download=fileinf[0].first_download,
                   last_download=fileinf[0].last_download,
                   data_count=fileinf.count_rows), 200
Beispiel #16
0
def get_unique_paths_by_geom_overlay(log: Logger,
                                     all_paths: List[Path],
                                     buffer_m: int = None,
                                     cost_attr: str = 'nei_norm') -> List[str]:
    """Filters a list of paths by comparing buffered line geometries of the paths and selecting only the unique paths by given buffer_m (m).

    Args:
        all_paths: Both short and green paths.
        buffer_m: A buffer size in meters with which the path geometries will be buffered when comparing path geometries.
        cost_attr: The name of a cost attribute to minimize when selecting the best of overlapping paths.
    Note:
        Filters out shortest path if an overlapping green path is found to replace it.
    Returns:
        A filtered list of paths having nearly unique line geometry with respect to the given buffer_m.
        None if PathSet contains only one path.
    """
    if (len(all_paths) == 1):
        return None
    paths_already_overlapped = []
    filtered_paths_names = []
    for path in all_paths:
        if (path.name not in filtered_paths_names
                and path.name not in paths_already_overlapped):
            overlay_candidates = get_path_overlay_candidates_by_len(
                path, all_paths, len_diff=25)
            overlapping_paths = get_overlapping_paths(log, path,
                                                      overlay_candidates,
                                                      buffer_m)
            best_overlapping_path = get_least_cost_path(overlapping_paths,
                                                        cost_attr=cost_attr)
            if (best_overlapping_path.name not in filtered_paths_names):
                filtered_paths_names.append(best_overlapping_path.name)
            paths_already_overlapped += [
                path.name for path in overlapping_paths
            ]

    log.debug('filtered ' + str(len(filtered_paths_names)) +
              ' unique paths from ' + str(len(all_paths)) +
              ' unique paths by overlay')
    return filtered_paths_names
Beispiel #17
0
    def parse(self) -> None:
        contents = self.html[self.html.index(Config.get('PARSER', 'start_tag')
                                             ) +
                             len(Config.get('PARSER', 'start_tag')):self.html.
                             index(Config.get('PARSER', 'end_tag'))].strip()

        if Config.get('PARSER', 'empty_pattern') in contents:
            Logger.get(self.__class__.__name__).info("No new contents.")
            self.has_new_content = False
            self.links = {}
            try:
                os.remove("{}/{}".format(Config.get('CRON', 'project_root'),
                                         Config.get('PARSER', 'cache_file')))
            except OSError as e:
                if e.errno != errno.ENOENT:
                    raise
            return

        with open(Config.get('PARSER', 'cache_file'), 'a+') as f:
            f.seek(0)
            if f.read() == contents:
                Logger.get(self.__class__.__name__).info("No new contents.")
                self.has_new_content = False
                self.links = {}
            else:
                Logger.get(
                    self.__class__.__name__).info("New content detected.")
                self.has_new_content = True
                self._extract_links(contents)
                f.seek(0)
                f.truncate()
                f.write(contents)
Beispiel #18
0
def upload_file(start_time, query_id):
    if 'file' not in request.files or not request.files['file'].filename:
        code = 400
        Logger.info(
            f"Response: Query failed. query_id: <{query_id}>; err_code: <{code}>; "
            f"time: <{calc_time(start_time)} ms>")
        abort(code)

    # Добавление в бд
    with transaction():
        try:
            file = Files(filename=request.files['file'].filename)
            with transaction():
                db.session.add(file)
            handleFile(file.fileid, request.files['file'])
        except HTTPException as ex:
            Logger.info(
                f"Response: Query failed. query_id: <{query_id}>; err_code: <{ex.code}>; "
                f"time: <{calc_time(start_time)} ms>")
            raise

    db.session.commit()

    Logger.info(f"Response: Query successed. query_id: <{query_id}>; "
                f"time: <{calc_time(start_time)} ms>")

    return jsonify(fileid=file.fileid), 200
Beispiel #19
0
def delete_file(fileid, start_time, query_id):
    if not Files.query.filter_by(fileid=fileid).all():
        code = 404
        Logger.info(
            f"Response: Query failed. query_id: <{query_id}>; err_code: <{code}>; "
            f"time: <{calc_time(start_time)} ms>")
        abort(code)

    # Удаление из бд
    with transaction():
        try:
            Data.query.filter_by(fileid=fileid).delete()
            Files.query.filter_by(fileid=fileid).delete()
        except HTTPException as ex:
            Logger.info(
                f"Response: Query failed. query_id: <{query_id}>; err_code: <{ex.code}>; "
                f"time: <{calc_time(start_time)} ms>")
            raise

    db.session.commit()

    Logger.info(f"Response: Query successed. query_id: <{query_id}>; "
                f"time: <{calc_time(start_time)} ms>")

    return '', 204
Beispiel #20
0
class Transformer:
    AVAILABLE_STRATEGIES = [
        'remove_undefined_user_orders',
        'keep_undefined_user_orders'
    ]

    def __init__(self, worker_name):
        self.logger = Logger(worker_name)

    def merge_users_and_orders(self, users, orders, strategy='remove_undefined_user_orders'):
        user_orders = []
        users_dict = {}

        try:
            if strategy not in self.AVAILABLE_STRATEGIES:
                raise Exception('Undefined merging strategy')

            for user in users:
                user_id = user['user_id']
                del user['user_id']
                users_dict[user_id] = {f'user_{k}': v for k, v in user.items()}

            for order in orders:
                user_id = order['user_id']
                user_order = order

                if user_id in users_dict.keys():
                    user_data = users_dict[user_id]
                    user_order.update(user_data)
                    user_orders.append(user_order)
                elif strategy == 'keep_undefined_user_orders':
                    user_orders.append(user_order)

            return user_orders
        except Exception as error:
            self.logger.error(error)
            raise error
Beispiel #21
0
class Loader:
    def __init__(self, worker_name):
        self.logger = Logger(worker_name)

    def load(self, user_orders):
        connection = None
        sql_command = getInsert()

        try:
            connection = psycopg2.connect(user=Config.POSTGRES_USER,
                                          password=Config.POSTGRES_PASSWORD,
                                          host=Config.POSTGRES_HOST,
                                          port=Config.POSTGRES_PORT,
                                          database=Config.POSTGRES_DATABASE)
            cursor = connection.cursor()
            cursor.executemany(sql_command, user_orders)
            cursor.close()
            connection.commit()
        except (Exception, psycopg2.DatabaseError) as error:
            self.logger.error('PostgreSQL error')
            raise error
        finally:
            if connection is not None:
                connection.close()
    def __init__(self):
        # create deck object
        self.deck = SerializableDeck()

        # save state
        self.states = {}

        # message logging
        self.logger = Logger("BlackJack State Manager")

        # boolean to determine whether a game is on going or not
        self.room_locked = False

        # boolean if new game is requested
        self.is_new_game_requested = False

        # boolean if deck newly created
        self.is_deck_refreshed = False

        # blackjack goal number
        self.winning_number = 21

        # create the game deck
        self.init_deck()
Beispiel #23
0
class OrdersWorker:
    def __init__(self):
        self.name = 'orders_worker'
        self.extractor = Extractor(self.name)
        self.transformer = Transformer(self.name)
        self.loader = Loader(self.name)
        self.logger = Logger(self.name)

    def process(self):
        self.logger.info('Started')

        orders = self.extractor.extract_orders('orders')
        self.logger.info(f'Extracted orders: {orders.count()}')

        users = self.extractor.extract_users('users')
        data = self.transformer.merge_users_and_orders(users, orders)

        self.loader.load(data)
        self.logger.info(f'Written records: {len(data)}')

        self.logger.info('Finished')
Beispiel #24
0
def uploadToDB(df):

    def insertChunk(inserterStatemant):
        for key in data_keys.keys():
            if key in dicts[0].keys() or key == 'updated':
                try:
                    norm_data_keys[key] = getattr(inserterStatemant.inserted, key)
                except AttributeError:
                    pass
        inserterStatemant = inserterStatemant.on_duplicate_key_update(
            norm_data_keys
        )
        try:
            db.session.execute(inserterStatemant)
        except (InternalError, DataError):
            raise RuntimeError(f"Data is not valid. "
                               f"Problem finded in range "
                               f"({last_boarder}, {min(last_boarder + chunkSize, len(dicts))}). "
                               f"Try to check matching of values with its column names. "
                               f"If you haven't find the problem, try to check the data in specified range.")

    dicts = df.to_dict('records')
    data_schema = DataSchema()
    data_keys = data_schema.dump(Data()).data
    norm_data_keys = {}
    last_boarder = 0
    Logger.debug("Prepare to download")
    for i in range(chunkSize, len(dicts), chunkSize):
        inserterStatemant = insert(Data.__table__).values(
            dicts[i - chunkSize:i]
        )
        insertChunk(inserterStatemant)
        Logger.debug(f"Downloaded chunk. Summary: {i}")
        last_boarder = i
    if last_boarder != len(dicts):
        inserterStatemant = insert(Data.__table__).values(
            dicts[last_boarder:len(dicts)]
        )
        insertChunk(inserterStatemant)
        Logger.debug(f"Downloaded chunk. Summary: {len(dicts)}")
class Manager(object):
    def __init__(self):
        # create deck object
        self.deck = SerializableDeck()

        # save state
        self.states = {}

        # message logging
        self.logger = Logger("BlackJack State Manager")

        # boolean to determine whether a game is on going or not
        self.room_locked = False

        # boolean if new game is requested
        self.is_new_game_requested = False

        # boolean if deck newly created
        self.is_deck_refreshed = False

        # blackjack goal number
        self.winning_number = 21

        # create the game deck
        self.init_deck()

    def get_states(self):
        return self.states

    def init_deck(self):
        # create the deck
        self.deck.create()

        # shuffle the deck
        self.deck.shuffle()

    def new_game(self, identifier):
        if self.is_new_game_requested is False:
            for _, state in self.states.items():
                # make sure player is not ready
                state['is_ready'] = False

            # set back to false to allow deck refresh
            self.is_deck_refreshed = False

            # set to true to prevent executing this block on next call
            self.is_new_game_requested = True

        # increment the number of games played
        self.states[identifier]['games_played'] += 1

        # unlock hand
        self.states[identifier]['hand_locked'] = False

        # empty the cards on hand
        self.states[identifier]['cards_on_hand'] = []

        if self.logger != None:
            self.logger.log('new_game', "Starting a new game.")

    # TODO: throw error when number_of_cards is less than 1
    def draw_cards(self, identifier, number_of_cards=2):
        drawn_cards = []

        # do not invoke pluck when hand is locked
        if self.states[identifier]['hand_locked'] is False:
            drawn_cards = self.deck.pluck(number_of_cards)

        if identifier in self.states and not 'cards_on_hand' in self.states[
                identifier]:
            self.states[identifier]['cards_on_hand'] = []

        if identifier in self.states:
            for card in drawn_cards:
                self.states[identifier]['cards_on_hand'].append(card)

            if self.logger != None:
                self.logger.log(
                    "Drawn card. State of %s modified" % identifier,
                    self.states[identifier])

        if self.logger != None:
            self.logger.log("Drawn card. Remaining cards",
                            self.deck.get_remaining_cards())

        return drawn_cards

    def get_player_cards(self, exclude_uids=None):
        result = {}

        for identifier, state in self.states.items():
            # skip to the next iteration when the identifier needs to be excluded
            if exclude_uids is not None and identifier in exclude_uids:
                continue

            on_hand = []

            if 'cards_on_hand' in state:
                on_hand = state['cards_on_hand']

            result[identifier] = on_hand

        return result

    def get_player_card_total(self, identifier, count_only_first=False):
        card_total = 0
        ace_counter = 0

        if identifier in self.states:
            card_collection = self.states[identifier]['cards_on_hand']

            # extract the first card
            if count_only_first is True and len(card_collection) > 0:
                card_collection = [card_collection[0]]

            for card in card_collection:
                card_obj = TextToCardTransformer(card).transform()
                card_value = card_obj.get_normalized_value()

                # increment the ace counter if we enconter one
                if card_obj.get_face_value() == 'A':
                    ace_counter += 1
                    continue

                card_total += card_value

            if card_total <= 10 and ace_counter == 1:
                # add eleven to the card total when user has 1 ace card if the card total is less than or eq to 10
                card_total += 11
            elif card_total > 10 and ace_counter >= 1:
                # add 1 for each ace the user has when the card total is greater than 10
                card_total += ace_counter
            elif card_total == 0 and ace_counter > 1:
                # if the user's card consists of all aces then add set the initial total to 11
                # and add 1 for each remaining ace card
                card_total += (11 + (ace_counter - 1))
            else:
                pass

        return card_total

    def determine_winners(self):
        is_all_locked = True

        # reset the flag
        self.is_new_game_requested = False

        scores_dict = {}
        for identifier, state in self.states.items():
            if state['hand_locked'] is False:
                is_all_locked = False
                break

            card_total = self.get_player_card_total(identifier, False)

            tmp_score = self.winning_number - card_total

            # store identifiers and scores which is greater than or equal to 0
            if tmp_score >= 0:
                scores_dict[identifier] = tmp_score

        # before we determine the actual winner, all states must be hand_locked!
        if is_all_locked is False:
            return None

        min_val = 0

        if len(scores_dict) > 0:
            min_val = min(scores_dict.values())

        winners = []
        matching_score = 0
        for f_identifier, score in scores_dict.items():
            if score == min_val:
                winners.append(strip_uid(f_identifier))
                matching_score = self.get_player_card_total(
                    f_identifier, False)

        # recreate the deck to prevent error from getting no cards
        if self.deck.get_remaining_cards(
        ) <= 15 and self.is_deck_refreshed is False:
            self.init_deck()

            # set the flag to true to indicate that the deck has been refreshed
            self.is_deck_refreshed = True

            if self.logger != None:
                self.logger.log('new_game',
                                "Creating new  and shuffling the deck.")

        return {'winners': winners, 'score': matching_score}

    def lock_hand(self, identifier, lock=True):
        if identifier in self.states:
            self.states[identifier]['hand_locked'] = lock

    def lock_game(self, lock=True):
        self.room_locked = lock

    def make_ready(self, identifier, ready=True):
        if identifier in self.states:
            self.states[identifier]['is_ready'] = ready

    def is_room_ready(self):
        player_ready_count = self.player_ready_count()

        if player_ready_count > 1:
            return True

        return False

    def player_count(self):
        return len(self.states)

    def player_ready_count(self):
        counter = 0

        for _, state in self.states.items():
            if state['is_ready'] is True:
                counter += 1

        return counter

    def get_player_uids(self):
        identifiter_list = []

        for identifier, _ in self.states.items():
            identifiter_list.append(identifier)

        return identifiter_list

    def disconnect(self, identifier):
        if identifier in self.states:
            del self.states[identifier]

            if self.logger != None:
                self.logger.log("Player left: %s" % identifier, self.states)

            return True

        return False

    def connect(self, name):
        if self.room_locked is True:
            if self.logger != None:
                self.logger.log(
                    "connect",
                    "Player: %s is trying to connect a locked game." % name)
            return False

        key = name + ':uid-' + rand_uid(10)

        self.states[key] = {
            'games_played': 0,
            'total_wins': 0,
            'total_losses': 0,
            'is_ready': False,
            'hand_locked': False
        }

        if self.logger != None:
            self.logger.log("Player Joined: %s" % key, self.states[key])

        return key
Beispiel #26
0
def create_app():

    Logger.info('Creating app...')
    app = Flask(__name__)
    Logger.info('App created')
    Logger.info('Configure app...')
    app.config.from_object(appconfig.getConfig())
    Logger.info('App configured')

    Logger.info('Initialize database...')
    db.init_app(app)
    Logger.info('Database initialized')

    import app.queries.preprocessors_handler as preprocessors_handler
    import app.queries.resources_handler as resources_handler
    import app.queries.models_handler as models_handler
    import app.queries.ml_handler as ml_handler

    app.register_blueprint(preprocessors_handler.preprocessors_handler)
    app.register_blueprint(resources_handler.resources_handler)
    app.register_blueprint(models_handler.models_handler)
    app.register_blueprint(ml_handler.ml_handler)

    return app
Beispiel #27
0
 def setup(self):
     client_id = uuid.uuid3(uuid.NAMESPACE_DNS, self.name)
     self.logger = Logger(str(client_id))
Beispiel #28
0
socket.init_app(app, cors_allowed_origins="*")

mail = Mail(app)
print(f'MAIL USERNAME: {mail.username}\nMAIL PASSWORD: {mail.password}')
'''message = Message()
message.subject = 'TEST FROM OPT'
message.body = 'THIS MESSAGE WAS SENT FROM A LIVING APP'
message.add_recipient('*****@*****.**')

mail.send(message)
'''

fernet = Fernet(
    base64.urlsafe_b64encode(os.getenv('FERNET_SECRET').encode('utf-8')))

logger = Logger(folder=app.config['LOG_FOLDER'], socket=socket)

logger.upd_log('App started', 9)

bu = Backupper()
logger.upd_log('Backupper init', 9)

from app import routes, models

bu.init_app(app,
            tables=[
                models.User, models.Client, models.Result, models.Message,
                models.Userlog, models.Clientlog, models.Testsession,
                models.Testbattery, models.Modaux, models.Module
            ],
            logger=logger)
Beispiel #29
0
def migrate(app):
    engine = create_engine(getConfig().SQLALCHEMY_DATABASE_URI)

    Logger.info('Check database existence...')
    if not database_exists(engine.url):
        Logger.info('Creating database...')
        create_database(engine.url)
        Logger.info('Database created')
    else:
        Logger.info('Database already exists. Not need to create')
    assert database_exists(engine.url)
    Logger.info('Database exists')

    Logger.info('Creating tables...')
    with app.test_request_context():
        db.create_all()
    Logger.info('Tables created')
Beispiel #30
0
 def __init__(self, session):
     self.session = session
     self.logger = Logger.get(__name__)
Beispiel #31
0
def celeryLogSuccessAndEmail(task_id, start_time, email, result):
    message = f"Your request successed! The result is:\n" \
              f"{result}"
    sendEmail(email, message)
    Logger.info(f"Response: Query successed. query_id: <{task_id}>; "
                f"time: <{calc_time(start_time)} ms>")