Exemplo n.º 1
0
    def _do_partial_comparison(self, left_side_table, right_side_table):
        '''
        Loops on the fields,
        For each field (record) compare just the traits (columns) I need to.
        I need to do it that way to have a detailed report as to what is not matching
        Columns in records come in this order: Field,Type,Nul,Key,Default,Extra
        '''
        if len(left_side_table) != len(right_side_table):
            self.has_errors = True
            self.dynamic_error_str += "number of fields do not match between both tables\n"

        for field_name in left_side_table.keys():
            L.info("checking field {}".format(field_name))
            try:
                for compare_type in self.params:
                    if left_side_table[field_name][Same.comapre[
                            compare_type]] != right_side_table[field_name][
                                Same.comapre[compare_type]]:
                        self.has_errors = True
                        self.dynamic_error_str += "field [{}] is not same for comparison param [{}]".format(
                            field_name, compare_type) + "\n"

            except IndexError:
                self.has_errors = True
                self.dynamic_error_str += "Field [{}] does not exists in right side table".format(
                    field_name) + "\n"

            except KeyError:
                self.has_errors = True
                self.dynamic_error_str += "Field [{}] does not exists in table [{}.{}]".format(
                    field_name, self.right_side_db,
                    self.right_side_table) + "\n"
Exemplo n.º 2
0
def start(processID, parallelMode, useGUI):
    """ main entry point into the application """
    Config.processID = processID
    Config.parallelMode = parallelMode
    Config.sumoUseGUI = useGUI

    # Check if sumo is installed and available
    SUMODependency.checkDeps()
    info('# SUMO-Dependency check OK!', Fore.GREEN)

    # Load the sumo map we are using into Python
    Network.loadNetwork()
    info(Fore.GREEN + "# Map loading OK! " + Fore.RESET)
    info(Fore.CYAN + "# Nodes: " + str(Network.nodesCount()) + " / Edges: " +
         str(Network.edgesCount()) + Fore.RESET)

    # Start sumo in the background
    SUMOConnector.start()
    info("\n# SUMO-Application started OK!", Fore.GREEN)

    # Start the simulation
    Simulation.start()
    # Simulation ended, so we shutdown
    info(Fore.RED + '# Shutdown' + Fore.RESET)

    traci.close()
    sys.stdout.flush()
    return None
Exemplo n.º 3
0
    def _do_full_comparison(self, left_side_table, right_side_table):
        '''
        I check number of fields match (I removed ignored fields in previous steps)
        I check structure is exact same
        '''

        if len(left_side_table) != len(right_side_table):
            self.has_errors = True
            self.dynamic_error_str = "number of fields does not match between both tables"
            return

        for field_name in left_side_table.keys():
            L.info("checking field {}".format(field_name))
            try:
                if left_side_table[field_name] != right_side_table[
                        field_name]:  #full array comparison
                    self.has_errors = True
                    self.dynamic_error_str = "schema for field {} is not same".format(
                        field_name)
                    return

            except IndexError:
                self.has_errors = True
                self.dynamic_error_str = "Field {} does not exists in right side table".format(
                    field_name)
                return
Exemplo n.º 4
0
 def start(cls):
     """ start the simulation """
     info("# Start adding initial cars to the simulation", Fore.MAGENTA)
     # apply the configuration from the json file
     cls.applyFileConfig()
     CarRegistry.applyCarCounter()
     cls.loop()
Exemplo n.º 5
0
def sms():
	_from = request.values.get('from',None) #from means the person from whom the text is coming from.
	text = request.values.get('text',None) #this gets the text in the message sent by user

	split_text = text.split('*')

	name   = split_text[0].capitalize()
	age    = split_text[1]
	gender = split_text[2].lower()


	count = Contacts.query.filter_by(phoneNumber = _from).count()

	if not count > 0:
		#no idea what api key is, what it does. Also, the use of the username is a mystery.
		#username is your Africa'sTalking username and api key is obtained from website
		gateway = AfricasTalkingGateway(os.environ.get('username'), os.environ.get('apikey')) 
		gateway.sendMessage (_from, "Thank you for registering for this service. To get inspiration messages, call 20880. Calls charged at 10 bob per minute. Have a blessed day.")

		#here the details are added to db table contacts
		contacts = Contacts (name=name, age = age, phoneNumber = _from)
		db.session.add(contacts)
		db.session.commit()
		logging.info("user added{}".format(contacts))

	else:
		logging.info("User already registered.")

	resp = make_response ("OK", 200)
	return resp
Exemplo n.º 6
0
 def  action(self):
     '''
     @return should_i_stop boolean
             the result of the previous action. If it is true
             execution should stop, but I will alert the user this arg was activated, he/she might have done a mistake
             return True will break the command string from fully executing.
             This type of command is a blocking command i.e. nothing happens later if
             this flag was supplied
     '''
     if self.do_test:
         if self.validate_input():
             if self.handle_x_files != None and int(self.handle_x_files) >0:
                 limit_of_files_processed = int(self.handle_x_files)
                 limit_info = self.handle_x_files
             else: #if I do not provide the --all flag, I still run JUST the tests on all the files.
                 limit_of_files_processed = 0 #Inverse loop, 0 means all
                 limit_info = 'all'
                 
             L.info('RUNNING TEST upgrade on {}:{}@{}'.format(upgrade_config['test_user'],upgrade_config['test_password'],upgrade_config['test_host']))
             L.info("WILL TEST upgrade with {} files".format(limit_info))
             files_where_processed = app.upgrade.actions.test(limit_of_files_processed)
             if not files_where_processed:
                 return True
 
     return False
Exemplo n.º 7
0
    def action(self):
        '''
        @return should_i_stop boolean
                the result of the previous action. If it is true
                execution should stop, but I will alert the user this arg was activated, he/she might have done a mistake
                return True will break the command string from fully executing.
                This type of command is a blocking command i.e. nothing happens later if
                this flag was supplied
        '''
        if self.do_test:
            if self.validate_input():
                if self.handle_x_files != None and int(
                        self.handle_x_files) > 0:
                    limit_of_files_processed = int(self.handle_x_files)
                    limit_info = self.handle_x_files
                else:  #if I do not provide the --all flag, I still run JUST the tests on all the files.
                    limit_of_files_processed = 0  #Inverse loop, 0 means all
                    limit_info = 'all'

                L.info('RUNNING TEST upgrade on {}:{}@{}'.format(
                    upgrade_config['test_user'],
                    upgrade_config['test_password'],
                    upgrade_config['test_host']))
                L.info("WILL TEST upgrade with {} files".format(limit_info))
                files_where_processed = app.upgrade.actions.test(
                    limit_of_files_processed)
                if not files_where_processed:
                    return True

        return False
Exemplo n.º 8
0
async def register_chat(message: types.Message):
    chat_id = message.from_user.id
    admins = await message.chat.get_administrators()
    for admin in admins:
        if chat_id == admin.user.id:
            await message.reply(_("🏡 Добро пожаловать Домой!\n"
                                  "🏛 Перейдите пожалуйста в ЛС и укажите Ваше расположение\n"))
            exists = add_chat(message.chat.id)

            if exists:
                text = _("🏛 Ваше расположение уже было зарегистрировано. "
                         "Создайте новое расположение Вашего 🏡чата/канала\n"
                         "Для этого выберите язык чата из списка")
            else:
                text = _("🏛 Поздравляем! Ваш 🏡чат/канал ⚡️связан с ☀️Атлантидой. "
                         "Создайте расположение Вашего 🏡чата/канала\n"
                         "Для этого выберите язык чата из списка")

            language_keyboard = ListOfButtons(
                text=["English", "Русский", "Українська"],
                callback=[language_callback.new(code="en"),
                          language_callback.new(code="ru"),
                          language_callback.new(code="uk")]
            ).inline_keyboard

            await bot.send_message(chat_id, text,
                                   reply_markup=language_keyboard)
            await dp.current_state(chat=chat_id, user=chat_id).set_state(Registration.Language)
            await dp.current_state(chat=chat_id, user=chat_id).update_data(chat_id=message.chat.id)
            break
    else:
        await message.answer(_("🏛 Приносим извинения за временные неудобства. \n"
                               "В данный момент принимаются только администраторы чатов/каналов"))
        logging.info("User is not an admin")
Exemplo n.º 9
0
    def process(self,db,file_content,filename):
        '''
            Read the file and extract from the CREATE stmt the type and name
        '''
        command = ""
        db_object_search = re.search("CREATE\W*(\w*)\W*(\w*)\W*(\w*)\W*(\w*)",file_content,re.I)
        try:
            db_obj_type = db_object_search.group(1)
            db_obj_name = db_object_search.group(2)
            if(db_obj_type == "ALGORITHM"):
                db_obj_type = db_object_search.group(3)
                db_obj_name = db_object_search.group(4)

            command = "DROP {type} {name} ".format(type=db_obj_type,name=db_obj_name)
            L.info(command)
                
        except IndexError:
            L.fatal("Error parsing file contents [{}]".format(file_content))
            raise Exception("Error parsing file contents")
            
        
        try:
            self.cursor.execute(command)

        except MyExcp as err:
            if (
                    err.errno == MyErrCode.ER_SP_DOES_NOT_EXIST or
                    err.errno == MyErrCode.ER_TRG_DOES_NOT_EXIST
                ):
                pass
Exemplo n.º 10
0
    def __init__(self, args):
        '''
        Stores a dictionary of what to clean
        '''
        # Process arguments
        self.args = args
        
        # Loads the database names rcom is tracking. This will be used in case of --all, this will also be used in case a specific db 
        # is targeted to make sure i is a tracked DB.
        sp_dbs       = meta.tracked_dbs(meta.STORED_PROCEDURES,self.args.assets_path)
        trigger_dbs  = meta.tracked_dbs(meta.TRIGGERS,self.args.assets_path)
        function_dbs = meta.tracked_dbs(meta.FUNCTIONS,self.args.assets_path)
        views_dbs    = meta.tracked_dbs(meta.VIEWS,self.args.assets_path)
        
        # decide which DBs I am going to clean. --all means EVERYTHING,
        #  -s,-w,-t,-f means every thing for each of those types
        #  -s db name, -f db name -w db name -tdb name means JUST THAT db name 
        #      for the specified object type, u can have several object types
        if self.args.handle_all:
            self.what_to_handle = {'s':sp_dbs,'w':views_dbs, 't':trigger_dbs, 'f':function_dbs}

        else:
            self.what_to_handle = {'s': sp_dbs       if self.args.stored_proc == 'All' else ([self.args.stored_proc] if self.args.stored_proc in sp_dbs       else []),
                                   'w': views_dbs    if self.args.views       == 'All' else ([self.args.views]       if self.args.views       in views_dbs    else []), 
                                   't': trigger_dbs  if self.args.triggers    == 'All' else ([self.args.triggers]    if self.args.triggers    in trigger_dbs  else []), 
                                   'f': function_dbs if self.args.functions   == 'All' else ([self.args.functions]   if self.args.functions   in function_dbs else [])}
        L.info("cleaning the following:")
        L.info(self.what_to_handle)
       
        # More config values for later
        self.dry_run = self.args.dry_run
        self.ignore_dbs = [('information_schema',),('performance_schema',),('sys',)]
        self.ignore_dbs_str = "'information_schema','performance_schema','sys'"
        self.connect()
Exemplo n.º 11
0
    def process(self, db, file_content, filename):
        '''
            Read the file and extract from the CREATE stmt the type and name
        '''
        command = ""
        db_object_search = re.search("CREATE\W*(\w*)\W*(\w*)\W*(\w*)\W*(\w*)",
                                     file_content, re.I)
        try:
            db_obj_type = db_object_search.group(1)
            db_obj_name = db_object_search.group(2)
            if (db_obj_type == "ALGORITHM"):
                db_obj_type = db_object_search.group(3)
                db_obj_name = db_object_search.group(4)

            command = "DROP {type} {name} ".format(type=db_obj_type,
                                                   name=db_obj_name)
            L.info(command)

        except IndexError:
            L.fatal("Error parsing file contents [{}]".format(file_content))
            raise Exception("Error parsing file contents")

        try:
            self.cursor.execute(command)

        except MyExcp as err:
            if (err.errno == MyErrCode.ER_SP_DOES_NOT_EXIST
                    or err.errno == MyErrCode.ER_TRG_DOES_NOT_EXIST):
                pass
Exemplo n.º 12
0
    def refresh(self):
        response = requests.post(constants.OAUTH_TOKEN,
                                 headers={
                                     'Authorization':
                                     'basic {}'.format(self.fortnite_token)
                                 },
                                 data={
                                     'grant_type':
                                     'refresh_token',
                                     'refresh_token':
                                     '{}'.format(self.refresh_token),
                                     'includePerms':
                                     True
                                 }).json()
        access_token = response.get('access_token')
        self.session.headers.update(
            {'Authorization': 'bearer {}'.format(access_token)})
        self.refresh_token = response.get('refresh_token')
        self.expires_at = utils.convert_iso_time(response.get('expires_at'))

        logging.info(
            "Токен доступа для использования Fortnite API перегенерирован.")
        logging.debug(
            "Access Token: {0}; Refresh Token: {1}; Expires At: {2}.".format(
                access_token, self.refresh_token, self.expires_at))
Exemplo n.º 13
0
    def action(self):
        '''
        @return should_i_stop boolean
                the result of the previous action. If it is true
                execution should stop, but I will alert the user this arg was activated, he/she might have done a mistake
                return True will break the command string from fully executing.
                This type of command is a blocking command i.e. nothing happens later if
                this flag was supplied
        '''
        if self.validate_input():
            if self.handle_x_files != None and int(self.handle_x_files) > 0:
                limit_of_files_processed = -1 * int(self.handle_x_files)
                limit_info = self.handle_x_files
            else:  #if I do not provide the --all flag, I still run JUST the tests on all the files.
                limit_of_files_processed = 0  #Invers loop, 0 means all, negative numbers I use to represent how many files more to run
                limit_info = 'all'

            L.info('RUNNING UPGRADE ON ACTUAL SERVER')
            L.info("WILL UPGRADE with {} files".format(limit_info))
            files_where_processed = app.upgrade.actions.upgrade(
                limit_of_files_processed)
            if not files_where_processed:
                return True

        return False
Exemplo n.º 14
0
 def __init__(self, db):
     '''
     Constructor
     '''
     self.current_db = db
     self.tables_list = {}
     self.right_side_db = ''
     L.info("Initiating TableList for db [{}]".format(db))
def get_companies_guid_by_keyword(keyword, **kwargs):
    logging.info(
        f'Получение guid компаний с сервера по ключевому слову -> {keyword}')
    companies_guid = parser.get_companies_guid_by_keyword(keyword, **kwargs)
    logging.info(
        f'Найдено {len(companies_guid)} компаний по ключевому слову -> {keyword}'
    )
    return companies_guid
Exemplo n.º 16
0
 def __init__(self,db):
     '''
     Constructor
     '''
     self.current_db       = db
     self.tables_list      = {}
     self.right_side_db = ''
     L.info("Initiating TableList for db [{}]".format(db))
Exemplo n.º 17
0
        def check_token():
            Timer(20.0, check_token).start()
            now = datetime.utcnow()
            if self.expires_at < (now - timedelta(seconds=60)):
                logging.info(
                    "Время действия токена доступа для Fortnite API истекло, генерируется новый."
                )

                self.refresh()
def close_db():
    # Close connection to database
    global conn
    conn.close()

    # Stop the tunnel
    global tunnel
    tunnel.stop()
    logging.info("Closed connections successfully.")
Exemplo n.º 19
0
def get_connection():
    global _connection
    if not _connection:
        user     = config.mysql['username']
        password = config.mysql['password']
        host     = config.mysql['host']
        L.info("Trying to connect to {}:{}@{}".format(config.mysql['username'],config.mysql['password'],config.mysql['host']))
        _connection = My.connect(user=user, password=password,host=host,buffered=True)
        
    return _connection
Exemplo n.º 20
0
    def __init__(self, args):
        '''
        Stores a dictionary of what to clean
        '''
        # Process arguments
        self.args = args

        # Loads the database names rcom is tracking. This will be used in case of --all, this will also be used in case a specific db
        # is targeted to make sure i is a tracked DB.
        sp_dbs = meta.tracked_dbs(meta.STORED_PROCEDURES,
                                  self.args.assets_path)
        trigger_dbs = meta.tracked_dbs(meta.TRIGGERS, self.args.assets_path)
        function_dbs = meta.tracked_dbs(meta.FUNCTIONS, self.args.assets_path)
        views_dbs = meta.tracked_dbs(meta.VIEWS, self.args.assets_path)

        # decide which DBs I am going to clean. --all means EVERYTHING,
        #  -s,-w,-t,-f means every thing for each of those types
        #  -s db name, -f db name -w db name -tdb name means JUST THAT db name
        #      for the specified object type, u can have several object types
        if self.args.handle_all:
            self.what_to_handle = {
                's': sp_dbs,
                'w': views_dbs,
                't': trigger_dbs,
                'f': function_dbs
            }

        else:
            self.what_to_handle = {
                's':
                sp_dbs if self.args.stored_proc == 'All' else
                ([self.args.stored_proc]
                 if self.args.stored_proc in sp_dbs else []),
                'w':
                views_dbs if self.args.views == 'All' else
                ([self.args.views] if self.args.views in views_dbs else []),
                't':
                trigger_dbs if self.args.triggers == 'All' else
                ([self.args.triggers]
                 if self.args.triggers in trigger_dbs else []),
                'f':
                function_dbs if self.args.functions == 'All' else
                ([self.args.functions]
                 if self.args.functions in function_dbs else [])
            }
        L.info("cleaning the following:")
        L.info(self.what_to_handle)

        # More config values for later
        self.dry_run = self.args.dry_run
        self.ignore_dbs = [('information_schema', ), ('performance_schema', ),
                           ('sys', )]
        self.ignore_dbs_str = "'information_schema','performance_schema','sys'"
        self.connect()
Exemplo n.º 21
0
 def action(self):
     '''
     @return should_i_stop boolean
             the result of the previous action. If it is true
             execution should stop, but I will alert the user this arg was activated, he/she might have done a mistake
             return True will break the command string from fully executing.
             This type of command is a blocking command i.e. nothing happens later if
             this flag was supplied
     '''
     L.info("Validating system files and db entries")
     app.upgrade.actions.validate_system()
     return False
Exemplo n.º 22
0
 def action(self):
     '''
     @return should_i_stop boolean
             the result of the previous action. If it is true
             execution should stop, but I will alert the user this arg was activated, he/she might have done a mistake
             return True will break the command string from fully executing.
             This type of command is a blocking command i.e. nothing happens later if
             this flag was supplied
     '''
     L.info("Validating system files and db entries")
     app.upgrade.actions.validate_system()
     return False
Exemplo n.º 23
0
    def iterate(self):
        '''
        Main iteration processor bala bala
        '''
        print(self.folders)
        print('------------------')
        for sub_folder in self.folders:
            # If this is actually just a sql file, do it directly. Otherwise do loop next
            if self.file_postfix in sub_folder:
                db = meta.extract_db_name(sub_folder)
                # TOBEDELETED once verified not used self._current_file = sub_folder
                self._current_path = sub_folder  # NOT SURE IT IS USED!
                L.info(
                    "handler is [{}] doing root [{}] file [{}] in database [{}]\n"
                    .format(self.__class__.__name__, sub_folder, sub_folder,
                            db))
                f = open(sub_folder, 'r')
                file_content = f.read()
                f.close()
                self.changeDB(db, file_content)
                self.process(db, file_content, sub_folder)

                continue

            else:
                # Loop on files and run sql
                for root, dirnames, filenames in os.walk(sub_folder):
                    # This is where I apply the filter of the ignored file list.
                    if any(ignored_partial_string in root
                           for ignored_partial_string in
                           config.ignore_files_dirs_with):
                        continue

                    for filename in fnmatch.filter(filenames,
                                                   '*' + self.file_postfix):
                        # print(filenames)
                        # print(dirnames)
                        # print("----------------------------------")
                        # print(root)
                        db = meta.extract_db_name(root)
                        # print(db+"\n")
                        # print(config.ignore_files_dirs_with)
                        self._current_path = root
                        L.info(
                            "handler is [{}] doing root [{}] file [{}] in database [{}]\n"
                            .format(self.__class__.__name__, root, filename,
                                    db))
                        f = open(root + '/' + filename, 'r')
                        file_content = f.read()
                        f.close()
                        self.changeDB(db, file_content)
                        self.process(db, file_content, filename)
Exemplo n.º 24
0
def messages(company_guid):
    regex_filter = request.args.get('regex_filter') or r'банкрот'

    messages_info = []
    messages = ds.get_company_messages(company_guid, **request.args)
    for message in messages:
        if re.search(regex_filter, message.get('text').lower() or ' '):
            messages_info.append(message)

    logging.info(
        f'Найдено {len(messages_info)} релевантных сообщений компании ({company_guid}) (текст-фильтр: "{regex_filter}")'
    )

    return {'count': len(messages_info), 'messages': messages_info}
Exemplo n.º 25
0
def load_data():
    db = create_database()
    logging.info('-------------------')
    logging.info('Created Database..')
    logging.info('Loading Trucks data to Database')
    db.insert_multiple(TRUCKS)
    logging.info('Loading is done')
Exemplo n.º 26
0
 def action(self):
     '''
     @return should_i_stop boolean
             the result of the previous action. If it is true
             execution should stop, but I will alert the user this arg was activated, he/she might have done a mistake
             return True will break the command string from fully executing.
             This type of command is a blocking command i.e. nothing happens later if
             this flag was supplied
     '''
     if self.file_name_to_mark_complete != None:
         L.info("Marking {} as COMPLETE in upgrade tracking table {}.rcom_sql_upgrades".format(self.file_name_to_mark_complete,upgrade_config['upgrade_tracking_database']))
         app.upgrade.actions.mark_complete(self.file_name_to_mark_complete)
         return True
     return False
Exemplo n.º 27
0
def voice_callback():
    isActive     = request.values.get('isActive', None)
    sessionId    = request.values.get('sessionId', None)
    callerNumber = request.values.get('callerNumber', None)

    if isActive == '1':

        callerNumber = request.values.get('callerNumber', None)
        logging.info("caller is {}".format(callerNumber))

        response = '<Response>'
        response += '<Say maxDuration="60" playBeep="false"> Hi, '
        response += 'Welcome to the Moringa school dating challenge.'

        member = Member.query.get(callerNumber)

        if member.gender.lower() == 'female':
            # find a man
            count = Member.query.filter_by(gender = 'male').count() 
            man   = random.choice(Member.query.filter_by(gender = 'male', status='Active').all())
            logging.info("{} calling -- {}".format(member.name, man))

            if count > 0:
                response += "I'll connect you in a second </Say>"
                response += '<Dial phoneNumbers="{}" ringBackTone="{}"/>'.format(man.phoneNumber, os.environ.get('sauti'))
            else:
                response += "No love for you today, for now. </Say>"
        else:
            # find a woman
            count = Member.query.filter_by(gender='female').count()
            woman = random.choice(Member.query.filter_by(gender='female', status='Active').all())
            logging.info("{} caller - {}".format(member.name, woman))

            if count > 0:
                response += "I'll connect you in a second</Say>"
                response += '<Dial phoneNumbers="{}" ringBackTone="{}"/>'.format(woman.phoneNumber, os.environ.get('sauti'))
            else:
                response += "No love for you today, for now. </Say>"

        response += '</Response>'

        voice = Voice(sessionId=sessionId, url='')
        db.session.add(voice)
        db.session.commit()

    else:
        voice = Voice.query.filter_by(sessionId = sessionId).first()
        voice.callCost = request.values.get('amount', None)

        db.session.add(voice)
        db.session.commit()
        logging.info(request.values)
        
        response = ""


    resp = make_response(response, 200)
    resp.headers['Content-Type'] = "application/xml"
    return resp
Exemplo n.º 28
0
    async def connection():
        try:
            psql_connection = await asyncpg.connect(host=config.databaseHost,
                                                    database=config.databaseName,
                                                    user=config.databaseUsername,
                                                    port=config.databasePort)

            logging.info("Соединение с Базой Данных PostgreSQL может быть установлено успешно.")
            logging.debug("Returned response: " + str(psql_connection))

            await psql_connection.close()
            return "OK"
        except Exception as e:
            logging.error("Произошла ошибка при попытке подключения к Базе Данных PostgreSQL.", exc_info=True)
            return e
Exemplo n.º 29
0
    async def connection():
        try:
            response = await Redis.execute("ping")

            logging.info(
                "The connection to Redis Server can be established successfully."
            )
            logging.debug("Returned response: " + str(response))
            return "OK"
        except Exception as e:
            logging.error(
                "Exception has been occurred while trying to establish connection with "
                "Redis.",
                exc_info=True)
            return e
Exemplo n.º 30
0
    def action(self):
        '''
        Runs the schma checker on the test server

        @return should_i_stop boolean
                the result of the previous action. If it is true
                execution should stop, but I will alert the user this arg was activated, he/she might have done a mistake
                return True will break the command string from fully executing.
                This type of command is a blocking command i.e. nothing happens later if
                this flag was supplied
        '''
        if self.do_on_test_server and self.do_schema_test:
            L.info("Running schema checker on test server {}@{}".format(upgrade_config['test_user'],upgrade_config['test_host']))
            app.upgrade.actions.test_with_schema()
        return False
Exemplo n.º 31
0
    def _internal_test_rule(self):
        '''
        Remember! the results of describe [table_name] are:
        Field,Type,Nul,Key,Default,Extra
        '''
        cursor = self._get_cursor()
        cursor.execute(self.sql)
        fields = [all_fields[0] for all_fields in cursor]

        for check_field in self.params:
            L.info("checking field [{}] exists in".format(check_field))
            L.debug(str(fields))
            if check_field not in fields:
                self.has_errors = True
                self.dynamic_error_str += " [" + check_field + "]"
        return self
Exemplo n.º 32
0
def _move_file_if_completed(file_name):
    '''
    used in archive, moves the file if is completed
    '''
    cnx = app.db.get_connection()
    cursor = cnx.cursor()
    sql = "SELECT COUNT(*) FROM {}.rcom_sql_upgrades WHERE file_name=%s AND execution_status = 'completed' ".format(
        upgrade_config['upgrade_tracking_database'])
    cursor.execute(sql, (file_name, ))
    res = cursor.fetchall()
    if res[0][0] == 1:
        L.info("About to ARCHIVE [{}]".format(file_name))
        subprocess.check_call([
            'mv', config.assets_folder + "/upgrades/current/" + file_name,
            config.assets_folder + "/upgrades/archive/."
        ])
Exemplo n.º 33
0
    def action(self):
        '''
        Runs the schma checker on the test server

        @return should_i_stop boolean
                the result of the previous action. If it is true
                execution should stop, but I will alert the user this arg was activated, he/she might have done a mistake
                return True will break the command string from fully executing.
                This type of command is a blocking command i.e. nothing happens later if
                this flag was supplied
        '''
        if self.do_on_test_server and self.do_schema_test:
            L.info("Running schema checker on test server {}@{}".format(
                upgrade_config['test_user'], upgrade_config['test_host']))
            app.upgrade.actions.test_with_schema()
        return False
Exemplo n.º 34
0
async def post_async(client):
    item_store_channel = (await redis_hgetall("fortnite:store:channel"))
    item_store_file, item_store_hash = await parse_item_store()

    item_store_caption = "🛒 Магазин предметов в Фортнайте был обновлен. #магазин"
    item_store_caption_edited = f"{item_store_caption}\n\n__Магазин предметов после оригинальной публикации " \
                                "сообщения был обновлен в {} по московскому времени.__"

    if not item_store_channel or item_store_channel[
            'hash'] != item_store_hash or config.DEVELOPER_MODE:
        logging.info(
            "Магазин предметов в Фортнайте был обновлен. Публикуется его изображение в канал, "
            "указанный в конфигурационном файле.")

        try:
            assert item_store_channel['chat_id']
            assert item_store_channel['message_id']
            assert item_store_channel['time']

            if int(time()) - int(item_store_channel['time']) < 3600:
                logging.info(
                    "Последний пост с магазином предметов был опубликован в канал меньше, "
                    "чем час назад, поэтому сообщение было отредактировано обновленным магазином."
                )

                message = client.edit_message_media(
                    int(item_store_channel['chat_id']),
                    int(item_store_channel['message_id']),
                    media=InputMediaPhoto(
                        item_store_file,
                        caption=item_store_caption_edited.format(
                            convert_to_moscow(
                                datetime.utcnow()).strftime("%H:%M:%S"))))
            else:
                raise AssertionError
        except (AssertionError, TypeError, KeyError):
            message = client.send_photo(config.CHANNEL_ID,
                                        item_store_file,
                                        caption=item_store_caption)

        await Redis.execute("HSET", "fortnite:store:channel", "hash",
                            item_store_hash, "chat_id", message['chat']['id'],
                            "message_id", message['message_id'], "time",
                            int(time()))
        await Redis.execute("EXPIRE", "fortnite:store:channel", 86400)
        """
Exemplo n.º 35
0
 def action(self):
     '''
     @return should_i_stop boolean
             the result of the previous action. If it is true
             execution should stop, but I will alert the user this arg was activated, he/she might have done a mistake
             return True will break the command string from fully executing.
             This type of command is a blocking command i.e. nothing happens later if
             this flag was supplied
     '''
     if self.file_name_to_mark_complete != None:
         L.info(
             "Marking {} as COMPLETE in upgrade tracking table {}.rcom_sql_upgrades"
             .format(self.file_name_to_mark_complete,
                     upgrade_config['upgrade_tracking_database']))
         app.upgrade.actions.mark_complete(self.file_name_to_mark_complete)
         return True
     return False
Exemplo n.º 36
0
def register_url():
    logging.info('Processing shorten request')
    url = request.json.get('url')
    current_user = User.get_by_email(get_jwt_identity())
    if not current_user:
        abort(HTTPStatus.BAD_REQUEST, INVALID_ACCOUNT)

    # create short url
    new_short_url = Url(user=current_user,
                        long_url=url,
                        short_id=Url.create_id())
    new_short_url.save()

    response = create_response({'short_url': new_short_url.get_short_url()},
                               SHORT_URL_CREATED, HTTPStatus.CREATED)

    return response
Exemplo n.º 37
0
    def _internal_test_rule(self):
        '''
        Remember! the results of describe [table_name] are:
        Field,Type,Nul,Key,Default,Extra
        '''
        sql = self.sql.split(';')
        cursor = self._get_cursor()
        cursor.execute(sql[0])
        left_side_table = {
            all_fields[0]: all_fields
            for all_fields in cursor if all_fields[0] not in self.ignore_params
        }
        del cursor
        cursor = self._get_cursor()
        try:
            cursor.execute(sql[1])
        except MyExcp as err:
            if err.errno == MyErrCode.ER_NO_SUCH_TABLE:
                print(
                    "The following query failed for missing table:\n {}\n\n folder [{}] file [{}]\nFIx Schema file before running again!"
                    .format(sql[1], self.left_side_db, self.right_side_db))
                exit(1)
            else:
                raise err

        right_side_table = {
            all_fields[0]: all_fields
            for all_fields in cursor if all_fields[0] not in self.ignore_params
        }
        del cursor

        # print(left_side_table)
        # print(right_side_table)
        # exit()

        if (self.params[0] in ['*', 'All', 'all']
                or sorted(['type', 'defaults', 'incr', 'keys']) == sorted(
                    self.params)):  # Do a full comparison
            L.info('doing full comparison')
            self._do_full_comparison(left_side_table, right_side_table)
        else:
            L.info('doing ' + str(self.params))
            self._do_partial_comparison(left_side_table, right_side_table)

        return self
Exemplo n.º 38
0
def perform_adaptation(tick):

    info("*******************************", Fore.CYAN)
    info("Starting adaptation at tick " + str(tick), Fore.CYAN)
    info("*******************************", Fore.CYAN)

    strategy = get_adaptation_stategy(tick)
    info("Invoking strategy: " + str(strategy.__class__.__name__), Fore.CYAN)

    monitor_data = strategy.monitor()
    if monitor_data:
        analysis_data = strategy.analyze(monitor_data)
        if analysis_data:
            plan_data = strategy.plan(analysis_data)
            if plan_data:
                strategy.execute(plan_data)

    info("*******************************", Fore.CYAN)
Exemplo n.º 39
0
def run_commands(commands):
    '''
    actually running the commands

        @var should_i_stop is boolean, the result of the previous action. If it is true
         execution should stop, but I will alert the user this arg was activated, he/she might have done a mistake
        return True will break the command string from fully executing.
        This type of command is a blocking command i.e. nothing happens later if
        this flag was supplied

    '''
    should_i_stop = False
    while commands:
        if should_i_stop:
            L.info("Either no files to work with where found, OR You have used a solo command like --unblock, --mark_complete or --archive.\nNo further actions will take place.\nBye Bye!")
            return
        command = commands.pop()
        should_i_stop = command.action()
Exemplo n.º 40
0
def processProblem():
    logging.info("The request is: {} and {}".format(request.form['question'], request.form['answer']))
    logging.info("Time elapsed: {}".format(request.form['time']))
    logging.info("Problem type is: {}".format(request.form['ptype']))
    if 'user' in session:
        logging.info("The user is: {}".format(session['user']))
        user = User.query.filter_by(nickname=session['user']).first()
        post = Problem(question=request.form['question'], answer=request.form['answer'], problem_type=request.form['ptype'], time_to_complete=request.form['time'], author=user)
        db.session.add(post)
        db.session.commit()
    return "Correct!"
Exemplo n.º 41
0
def calculate_stat(ptype, query_type):
    user = User.query.filter_by(nickname=session['user']).first()
    logging.info("we got this far with {}".format(user))
    problems = Problem.query.filter_by(author=user).all()
    logging.info("now we got the problems {}".format(problems))

    prob_map = {
        'Addition': [int(n.time_to_complete) for n in problems if n.problem_type == 'Addition'],
        'Subtraction': [int(n.time_to_complete) for n in problems if n.problem_type == 'Subtraction'],
        'Multiplication': [int(n.time_to_complete) for n in problems if n.problem_type == 'Multiplication'],
        'Division': [int(n.time_to_complete) for n in problems if n.problem_type == 'Division'],
        'Hexadecimal': [int(n.time_to_complete) for n in problems if n.problem_type == 'Hexadecimal']
    }

    def statify(x): return {'Average': sum(x)/len(x), 'Quickest': min(x)}

    stats = {prob_type: statify(prob_map[prob_type]) for prob_type in prob_map}

    return stats[ptype][query_type]
Exemplo n.º 42
0
    def iterate(self):
        '''
        Main iteration processor bala bala
        '''
        print(self.folders)
        print('------------------')
        for sub_folder in self.folders:
            # If this is actually just a sql file, do it directly. Otherwise do loop next
            if self.file_postfix in sub_folder:
                db = meta.extract_db_name(sub_folder)
                # TOBEDELETED once verified not used self._current_file = sub_folder
                self._current_path = sub_folder # NOT SURE IT IS USED!
                L.info("handler is [{}] doing root [{}] file [{}] in database [{}]\n".format(self.__class__.__name__,sub_folder,sub_folder,db))
                f = open(sub_folder,'r')
                file_content = f.read()
                f.close()
                self.changeDB(db,file_content)
                self.process(db,file_content,sub_folder)

                continue

            else:
                # Loop on files and run sql
                for root, dirnames, filenames in os.walk(sub_folder):
                    # This is where I apply the filter of the ignored file list.
                    if any(ignored_partial_string in root for ignored_partial_string in config.ignore_files_dirs_with):
                        continue

                    for filename in fnmatch.filter(filenames, '*'+self.file_postfix):
                        # print(filenames)
                        # print(dirnames)
                        # print("----------------------------------")
                        # print(root)
                        db = meta.extract_db_name(root)
                        # print(db+"\n")
                        # print(config.ignore_files_dirs_with)
                        self._current_path = root
                        L.info("handler is [{}] doing root [{}] file [{}] in database [{}]\n".format(self.__class__.__name__,root,filename,db))
                        f = open(root + '/' + filename,'r')
                        file_content = f.read()
                        f.close()
                        self.changeDB(db,file_content)
                        self.process(db,file_content,filename)
Exemplo n.º 43
0
 def process(self,db,file_content,filename):
     '''
         Loops on each folder, Each PROCESS call handles one rule file (*.rchk | .schk),
         Calls the following actions: 
         - Parses each rule and run the checks.
         - Each file found, a new table list object is instantiated for that file to be
           processed.
         - Run the tests in the TableList object
         @param db is the current database name, the left side db name: string 
     '''
     L.info("\n\nOpening db [{}] file [{}].\n".format(db,filename))
     
     # INITIALIZE THE LIST OF TABLES OBJECT, load tbls, set the DB name with which current DB is checked.
     DBTableList = (TableList(db)).loadTables()
     RuleParser  = (ChkFileParser(all_tables_names=DBTableList.getTablesNames(),
                                  left_side_db=db,
                                  right_side_db=self.getRightSideDB(filename,db),
                                  file_content=file_content)).parseRules()
     DBTableList.bindRulesToTables(RuleParser.getRuleList())
     self.store_table_lists.append(DBTableList)
Exemplo n.º 44
0
def do_login():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        username, password, email = request.form['username'], request.form['password'], request.form['email']
        does_user_exist = User.query.filter_by(nickname=username).first()
        if not does_user_exist:
            new_user = User(nickname=username, password=password, email=email)
            db.session.add(new_user)
            db.session.commit()
            session['user'] = username
            return render_template('main_page.html', welcome='Welcome, {}'.format(session['user']))
        else:
            user_pw = User.query.filter_by(nickname=username).first().password
            if user_pw == password:
                session['user'] = username
                logging.info("setting session user")
                logging.info("user is {}".format(session['user']))
                return redirect(url_for('math_teasers.main_page'))
            else:
                return render_template('login.html', message="Invalid password, please try again")
Exemplo n.º 45
0
def run_tests(table_name,table_rules):
    if len(table_rules) == 0:
        return EmptyErrorContainer()
    
    # initiating an error report container
    MyErrorContainer = ErrorContainer(right_side_table_name=table_name)
    L.info("Checking rules for table [{table_name}]".format(table_name=table_name))
    for rule in table_rules:
        table_name = rule.test_rule(table_name) # Do notice, a rule might change the table name, like prefix[baba_] will add baba_ to the right side
                                                # table name for the rest of the rules.
                                                # same with postfix[_gaga] which would add _gaga to the end of the right side table name.
                                                # Both rules can appear in any combination (both, or just one, in any order, in the BEGINNING)
        
        if rule.hasErrors() == True:
            MyErrorContainer.append(error_msg=rule.get_error_msg())
            
        if rule.dontContinue() == True:
            #step away from the rest of the tests
            break
    
    return MyErrorContainer
Exemplo n.º 46
0
def sms():
    _from = request.values.get('from', None)
    text  = request.values.get('text', None)

    split_text = text.split('*')

    name        = split_text[0].capitalize()
    gender      = split_text[1].lower()
    age         = split_text[2]
    preference  = split_text[3].lower()

    count = Member.query.filter_by(phoneNumber = _from).count()

    if not count > 0:
        gateway = AfricasTalkingGateway(os.environ.get('username'), os.environ.get('apikey'))
        gateway.sendMessage(_from, "You have been registered for the Moringa dating session")

        if gender.lower() == 'male':
            member = Member(name=name, age=age, preference=preference, status='active', phoneNumber=_from, gender='Male')
            db.session.add(member)
            db.session.commit()
            logging.info("user added {}".format(member))

        elif gender.lower() == 'female':
            member = Member(name=name, age=age, preference=preference, status='active', phoneNumber=_from, gender='Female')
            db.session.add(member)
            db.session.commit()
            logging.info("user added {}".format(member))

    else:
        logging.info("member already exists")


    resp = make_response("OK", 200 )
    return resp
Exemplo n.º 47
0
    def  action(self):
        '''
        @return should_i_stop boolean
                the result of the previous action. If it is true
                execution should stop, but I will alert the user this arg was activated, he/she might have done a mistake
                return True will break the command string from fully executing.
                This type of command is a blocking command i.e. nothing happens later if
                this flag was supplied
        '''
        if self.validate_input():
            if self.handle_x_files != None and int(self.handle_x_files) >0:
                limit_of_files_processed = -1 * int(self.handle_x_files)
                limit_info = self.handle_x_files
            else: #if I do not provide the --all flag, I still run JUST the tests on all the files.
                limit_of_files_processed = 0 #Invers loop, 0 means all, negative numbers I use to represent how many files more to run
                limit_info = 'all'

            L.info('RUNNING UPGRADE ON ACTUAL SERVER')
            L.info("WILL UPGRADE with {} files".format(limit_info))
            files_where_processed = app.upgrade.actions.upgrade(limit_of_files_processed)
            if not files_where_processed:
                return True

        return False
Exemplo n.º 48
0
    def cleanMain(self):
        '''
        Just call each specific cleaner -> very procedural and simple
        '''
        if(len(self.what_to_handle['s']) > 0):
            L.info("Start dropping Stored Procedures")
            self._cleanSP()
            
        if(len(self.what_to_handle['f']) > 0):
            L.info("Start dropping Functions")
            self._cleanFunctions()

        if(len(self.what_to_handle['t']) > 0):
            L.info("Start dropping Triggers")
            self._cleanTriggers()

        if(len(self.what_to_handle['w']) > 0):
            L.info("Start dropping Views")
            self._cleanViews()
Exemplo n.º 49
0
def get_stats():
    if request.method == 'GET':
        logging.info("Doing a GET")
        if 'user' not in session:
            return redirect(url_for('do_login'))
        else:
            return render_template('stats.html')
    elif request.method == 'POST':
        if 'user' not in session:
            logging.info("No user!")
            return redirect(url_for('do_login'))
        logging.info("Getting stats for {}".format(session['user']))
        try:
            user = User.query.filter_by(nickname=session['user']).first()
            logging.info("we got this far with {}".format(user))
            problems = Problem.query.filter_by(author=user).all()
            logging.info("now we got the problems {}".format(problems))
            session['num_of_problems'] = len(problems)
            additions = [n for n in problems if n.problem_type == 'Addition']
            times = [int(n.time_to_complete) for n in additions]
            average = sum(times)/len(times)
            logging.info("Your average was {} milliseconds".format(average))
            return "Your {} for {} was {}".format("average time", "Addition", average)
        except Exception as e:
            logging.error("There is a problem finding the stats: {}".format(e))
        return "We have a problem"