Пример #1
0
    def __init__(self, path_info, mode='circular'):

        self.path_info = path_info
        self.coordinates = self.path_info['coords']
        # dll of nodes, where node is a wrapper object 'Coord' for named tuple Coordinates
        self.nodes = [Coord(item, self.coordinates[idx - 1] if idx >= 1 else None,
                            self.coordinates[idx + 1] if idx < len(self.coordinates) - 1 else None) for idx, item in
                      enumerate(self.coordinates)]
        self.elevation = grouper(self.coordinates, 2)
        self.distance = grouper(self.path_info['distance'], 2)
        self.lat_distance = grouper(self.path_info['latDistance'], 2)
        self.lon_distance = grouper(self.path_info['lonDistance'], 2)
        self.idx = -1
        self.mode = mode
Пример #2
0
async def lang_list_callback_handler(
    query: types.CallbackQuery,
    callback_data: typing.Dict[str, str],
    user: UserRepository,
    _: dict,
):
    btn_list = []
    inline_keyboard_markup = types.InlineKeyboardMarkup(row_width=2)

    for lang in Lang:
        lang_id = lang.value
        if (lang_id is None):
            continue

        btn_list.append(
            types.InlineKeyboardButton(
                language_map[lang.name],
                callback_data=lang_cb.new(
                    id=lang_id,
                ),
            ),
        )

    for i in grouper(2, btn_list):
        inline_keyboard_markup.row(*i)

    await query.message.edit_text(_['choose_lang'], reply_markup=inline_keyboard_markup)
    await query.answer()
Пример #3
0
async def currency_callback_handler(
    query: types.CallbackQuery,
    callback_data: typing.Dict[str, str],
    user: UserRepository,
    _: dict,
):
    currency_list = await user.get_available_currency()

    user_currency = await user.get_user_currency(query.from_user.id)

    inline_keyboard_markup = types.InlineKeyboardMarkup(row_width=2)

    buttons = []

    for curr in currency_list:
        enabled = "❌"
        if (curr.id == user_currency.currency_id):
            enabled = "✅"

        buttons.append(
            types.InlineKeyboardButton(
                f"{enabled} {curr.currency_code}",
                callback_data=currency_cb.new(
                    id=curr.id, action=curr.id != user_currency.currency_id),
            ), )

    for b_row in grouper(2, buttons):
        inline_keyboard_markup.row(*b_row)

    await query.message.edit_text(_['curr_list'],
                                  reply_markup=inline_keyboard_markup)
    await query.answer()
Пример #4
0
    async def handle(self, message: types.Message, user: UserRepository,
                     _: dict):
        """
        Conversation's entry point
        """

        await user.create(message.from_user.id, int(DEFAULT_LANG.value))

        keyboard_markup = types.ReplyKeyboardMarkup(row_width=2,
                                                    resize_keyboard=True)

        btns_text = (_['cabinet'], _['faq'])
        keyboard_markup.row(*(types.KeyboardButton(text)
                              for text in btns_text))
        btns_text = [_['setting']]  #, _['feedback_button']
        keyboard_markup.row(*(types.KeyboardButton(text)
                              for text in btns_text))

        await message.answer(_['hello'], reply_markup=keyboard_markup)

        btn_list = []
        inline_keyboard_markup = types.InlineKeyboardMarkup(row_width=2)

        for lang in Lang:
            lang_id = lang.value
            if (lang_id is None):
                continue

            btn_list.append(
                types.InlineKeyboardButton(
                    language_map[lang.name],
                    callback_data=lang_cb.new(id=lang_id, ),
                ), )

        for i in grouper(2, btn_list):
            inline_keyboard_markup.row(*i)

        await message.answer(_['choose_lang'],
                             reply_markup=inline_keyboard_markup)

        await user.add_notification_setting(message.from_user.id, True)
        await user.add_notification_payouts_setting(message.from_user.id, True)

        await user.add_user_coin(message.from_user.id, Coin.Bitcoin.value,
                                 True)
        await user.add_user_coin(message.from_user.id, Coin.BitcoinHash.value,
                                 False)
        await user.add_user_coin(message.from_user.id, Coin.BitcoinSV.value,
                                 False)
        await user.add_user_coin(message.from_user.id, Coin.Ethereum.value,
                                 False)
        await user.add_user_coin(message.from_user.id,
                                 Coin.EthereumClassic.value, False)
        await user.add_user_coin(message.from_user.id, Coin.Litecoin.value,
                                 False)
        await user.add_user_coin(message.from_user.id, Coin.Dash.value, False)

        await user.add_user_currency(message.from_user.id, DEFAULT_CURRENCY)
Пример #5
0
async def finance_callback_handler(
    query: types.CallbackQuery,
    callback_data: typing.Dict[str, str],
    user: UserRepository,
    _: LangHolder,
):
    account_id = callback_data["id"]
    page = int(callback_data["page"])

    keyboard_markup = types.InlineKeyboardMarkup(row_width=2)

    account = next(
        (acc for acc in await user.get_accounts(query.from_user.id)
         if str(acc.account_id) == account_id),
        None,
    )

    if (account is None):
        return await reply_to_account_not_found(query.message, _)

    btn_list = []

    for coin in await user.get_account_coins(query.from_user.id, account_id):
        if coin.is_active:
            btn_list.append(
                types.InlineKeyboardButton(
                    f"{Coin(coin.coin_id).name}",
                    callback_data=finance_cb.new(
                        id=account_id,
                        type=coin.coin_id,
                        action="payouts",
                        page=page,
                    ),
                ), )

    for i in grouper(2, btn_list):
        keyboard_markup.add(*i)

    keyboard_markup.add(
        types.InlineKeyboardButton(
            _['back_to_account_button'],
            callback_data=menu_cb.new(id=account.account_id,
                                      type="account",
                                      action='open'),
        ), )

    await query.message.edit_text(
        _["finance_choose_coin"],
        reply_markup=keyboard_markup,
    )
    await query.answer()
async def change_coin_enabled_setting_coins_for_account(
    query: types.CallbackQuery,
    callback_data: typing.Dict[str, str],
    user: UserRepository,
    _: dict,
):
    coin_id = callback_data["id"]

    is_active = callback_data['action'] == 'on'

    await user.change_coin_enabled(query.from_user.id, coin_id, is_active)
    await user.change_account_coin_enabled(query.from_user.id, coin_id,
                                           is_active)

    keyboard_markup = types.InlineKeyboardMarkup(row_width=2)

    btn_list = []

    for coin in await user.get_coins(query.from_user.id, ):
        if coin.is_enabled:
            btn_list.append(
                types.InlineKeyboardButton(
                    f"{Coin(coin.coin_id).name} ✅",
                    callback_data=coin_account_cb.new(id=coin.coin_id,
                                                      action="off"),
                ), )
        else:
            btn_list.append(
                types.InlineKeyboardButton(
                    f"{Coin(coin.coin_id).name} ❌",
                    callback_data=coin_account_cb.new(id=coin.coin_id,
                                                      action="on"),
                ), )

    for i in grouper(2, btn_list):
        keyboard_markup.add(*i)
    '''
    keyboard_markup.add(
        types.InlineKeyboardButton(
            _['back_to_account_button'],
            callback_data=menu_cb.new(id=account.account_id, type="account", action='open'),
        ),
    )
    '''

    await query.message.edit_text(
        _["coin_list_descr"],
        reply_markup=keyboard_markup,
    )
    await query.answer(_['coin_enabled'] if is_active else _['coin_disabled'])
Пример #7
0
async def change_coins_for_account_callback_handler(
    query: types.CallbackQuery,
    callback_data: typing.Dict[str, str],
    user: UserRepository,
    _: dict,
):
    keyboard_markup = types.InlineKeyboardMarkup(row_width=2)

    btn_list = []

    for coin in await user.get_coins(query.from_user.id, ):
        if coin.is_enabled:
            btn_list.append(
                types.InlineKeyboardButton(
                    f"{Coin(coin.coin_id).name} ✅",
                    callback_data=coin_account_cb.new(id=coin.coin_id,
                                                      action="off"),
                ), )
        else:
            btn_list.append(
                types.InlineKeyboardButton(
                    f"{Coin(coin.coin_id).name} ❌",
                    callback_data=coin_account_cb.new(id=coin.coin_id,
                                                      action="on"),
                ), )

    for i in grouper(2, btn_list):
        keyboard_markup.add(*i)
    '''keyboard_markup.add(
        types.InlineKeyboardButton(
            _["back_to_account_list_button"],
            callback_data=menu_cb.new(
                id="_", type="menu", action="main_menu"
            ),
        ),
    )'''

    await query.message.edit_text(
        _["coin_list_descr"],
        reply_markup=keyboard_markup,
    )
    await query.answer()
Пример #8
0
def get_key_center_estimates(
        score: music21.stream.Score,
        measures_window_size: int = 64) -> music21.stream.Part:

    analyzer = music21.analysis.discrete.BellmanBudge()

    wa = music21.analysis.windowed.WindowedAnalysis(score, analyzer)

    solutions, color = wa.analyze(measures_window_size, 'overlap')

    part_key_centers = music21.stream.Part()

    solutions = [
        music21.note.Note(music21.pitch.Pitch(midi=tuple_pitch[0].midi))
        for tuple_pitch in solutions
    ]

    solutions_beats = _assign_key_centers(solutions, measures_window_size)

    solutions_measures = utils.grouper(4, solutions_beats)

    solutions_measures_21 = []

    for solution_measure in solutions_measures:

        measure = music21.stream.Measure()

        for i_solution, name_solution in enumerate(list(solution_measure)):
            note_beat = music21.note.Note(
                pitch=music21.pitch.Pitch(name=name_solution, octave=4))
            note_beat.duration = music21.duration.Duration(quarterLength=1)
            measure.insert(i_solution, note_beat)

        solutions_measures_21.append(measure)

    for measure in solutions_measures_21:
        part_key_centers.append(measure)

    return part_key_centers
 def push_stops_to_ckan(stops_list, is_cp, resource_id):
     """ Pushes OST's GTFS Stops to CKAN Datastore in chunks of five """
     geolocators = []
     geolocator_index = 0
     geolocators.append(GoogleV3())
     geolocators.append(Nominatim())
     # Needed variables for the places' description
     agency_name = CP_NAME if is_cp else CARRIS_NAME
     transport = TRAIN if is_cp else BUS
     agency_url = CP_URL if is_cp else CARRIS_URL
     print '\n- Started importing stops from {}'.format(agency_name)
     api = get_ckan_api(
         ckan_host=CKAN_HOST,
         ckan_type='datastore',
         ckan_action='create',  # 'upsert',
     )
     geolocator = geolocators[geolocator_index]
     for stop_group in grouper(stops_list, 5):
         stop_places = []
         belem_tuple = (u'Santa Maria de Belém', u'São Francisco Xavier')
         for stop in stop_group:
             location = None
             is_able_to_continue = False
             if stop:
                 place = {}
                 coords = (
                     stop['point']['coordinates'][1],
                     stop['point']['coordinates'][0],
                 )
                 coords_str = ','.join((str(coords[1]), str(coords[0])))
                 api_url = get_ost_api(
                     api=OST_API_MAIN_URL,
                     model_name='whereat',
                     api_key=OST_API_KEY,
                     params={'coords': coords_str},
                 )
                 # Get the parish/neighbourhood from OST
                 whereat = requests.get(api_url)
                 if whereat.status_code == 200:
                     whereat = json.loads(whereat.content)
                 else:
                     whereat = {}
                 parish = whereat.get('parish', {})
                 municipality = whereat.get('municipality', {})
                 # Get the Address from coordinates with GoogleMaps API
                 while is_able_to_continue is False:
                     try:
                         location = geolocator.reverse(
                             coords,
                             exactly_one=True,
                             timeout=60,
                         )
                         is_able_to_continue = True
                     except GeocoderTimedOut as e:
                         print '>>>>>>>>>>>>>>> GeocoderTimedOut\n', e
                         location = None
                         print 'Moving on...\n\n'
                     except GeocoderQuotaExceeded as e:
                         print '>>>>>>>>>>>>>>> GeocoderQuotaExceeded\n', e
                         geolocator_index += 1
                         if geolocator_index < len(geolocators):
                             geolocator = geolocators[geolocator_index]
                             debug = 'Trying a new geocoder: {}...\n\n'
                             print debug.format(type(geolocator).__name__)
                         else:
                             geolocator_index = 0
                             geolocator = geolocators[geolocator_index]
                             break
                     except GeocoderServiceError as e:
                         print '\n\n>>>>>>>> Geocoder Service Error:', e
                         time.sleep(30)
                 place_name = capwords(stop['stop_name'])
                 body = PLACE_BODY.format(
                     agency_name, transport, place_name.encode('utf-8'),
                 )
                 # Create a JSON list to be written to file
                 place['field_poi_id'] = stop['id']
                 place['field_title'] = place_name
                 place['field_category_places'] = TRANSPORTATION_CATEGORY
                 place['field_body'] = body
                 place['field_photographs'] = ""
                 place['field_website'] = agency_url
                 place['field_email'] = ""
                 place['field_phone'] = ""
                 place['field_location_latitude'] = coords[0]
                 place['field_location_longitude'] = coords[1]
                 if parish:
                     neighbourhood = parish.get('name', '')
                     if neighbourhood in belem_tuple:
                         neighbourhood = 'Belém'
                     place['field_neighbourhood'] = neighbourhood
                 else:
                     place['field_neighbourhood'] = ''
                 if location:
                     address = location.address
                     address = address.replace('&', 'E').replace(';', ' ')
                     place['field_location_address_first_line'] = address
                 else:
                     input_str = '\"No Location for {}. Please enter it: \"'
                     subprocess.call(['say', input_str])
                     input_str = input_str.format(coords)
                     address = raw_input(input_str)
                     print 'You entered', address
                     address = address.replace('&', 'E').replace(';', ' ')
                     place['field_location_address_first_line'] = address
                 place['field_location_address_second_line'] = ''
                 if municipality:
                     municipality_name = municipality.get('name', '')
                     place['field_location_city'] = municipality_name
                 else:
                     place['field_location_city'] = ''
                 place['field_location_country'] = 'Portugal'
                 place['resource_id'] = resource_id
                 stop_places.append(place)
         records = {
             'resource_id': resource_id,
             'primary_key': ['field_poi_id'],
             'indexes': ['field_poi_id'],
             'records': stop_places,
             'force': True,
         }
         # print records
         response = requests.post(
             api,
             data=json.dumps(records),
             headers=CKAN_AUTH,
         )
         print "\n", response.content.encode('utf-8', 'replace'), "\n"
         if response.status_code != 200:
             print "\n\n>>>>>>>>>>>> ERROR"
             print records
 def push_stops_to_ckan(stops_list, is_cp, resource_id):
     """ Pushes OST's GTFS Stops to CKAN Datastore in chunks of five """
     geolocators = []
     geolocator_index = 0
     geolocators.append(GoogleV3())
     geolocators.append(Nominatim())
     # Needed variables for the places' description
     agency_name = CP_NAME if is_cp else CARRIS_NAME
     transport = TRAIN if is_cp else BUS
     agency_url = CP_URL if is_cp else CARRIS_URL
     print '\n- Started importing stops from {}'.format(agency_name)
     api = get_ckan_api(
         ckan_host=CKAN_HOST,
         ckan_type='datastore',
         ckan_action='create',  # 'upsert',
     )
     geolocator = geolocators[geolocator_index]
     for stop_group in grouper(stops_list, 5):
         stop_places = []
         belem_tuple = (u'Santa Maria de Belém', u'São Francisco Xavier')
         for stop in stop_group:
             location = None
             is_able_to_continue = False
             if stop:
                 place = {}
                 coords = (
                     stop['point']['coordinates'][1],
                     stop['point']['coordinates'][0],
                 )
                 coords_str = ','.join((str(coords[1]), str(coords[0])))
                 api_url = get_ost_api(
                     api=OST_API_MAIN_URL,
                     model_name='whereat',
                     api_key=OST_API_KEY,
                     params={'coords': coords_str},
                 )
                 # Get the parish/neighbourhood from OST
                 whereat = requests.get(api_url)
                 if whereat.status_code == 200:
                     whereat = json.loads(whereat.content)
                 else:
                     whereat = {}
                 parish = whereat.get('parish', {})
                 municipality = whereat.get('municipality', {})
                 # Get the Address from coordinates with GoogleMaps API
                 while is_able_to_continue is False:
                     try:
                         location = geolocator.reverse(
                             coords,
                             exactly_one=True,
                             timeout=60,
                         )
                         is_able_to_continue = True
                     except GeocoderTimedOut as e:
                         print '>>>>>>>>>>>>>>> GeocoderTimedOut\n', e
                         location = None
                         print 'Moving on...\n\n'
                     except GeocoderQuotaExceeded as e:
                         print '>>>>>>>>>>>>>>> GeocoderQuotaExceeded\n', e
                         geolocator_index += 1
                         if geolocator_index < len(geolocators):
                             geolocator = geolocators[geolocator_index]
                             debug = 'Trying a new geocoder: {}...\n\n'
                             print debug.format(type(geolocator).__name__)
                         else:
                             geolocator_index = 0
                             geolocator = geolocators[geolocator_index]
                             break
                     except GeocoderServiceError as e:
                         print '\n\n>>>>>>>> Geocoder Service Error:', e
                         time.sleep(30)
                 place_name = capwords(stop['stop_name'])
                 body = PLACE_BODY.format(
                     agency_name,
                     transport,
                     place_name.encode('utf-8'),
                 )
                 # Create a JSON list to be written to file
                 place['field_poi_id'] = stop['id']
                 place['field_title'] = place_name
                 place['field_category_places'] = TRANSPORTATION_CATEGORY
                 place['field_body'] = body
                 place['field_photographs'] = ""
                 place['field_website'] = agency_url
                 place['field_email'] = ""
                 place['field_phone'] = ""
                 place['field_location_latitude'] = coords[0]
                 place['field_location_longitude'] = coords[1]
                 if parish:
                     neighbourhood = parish.get('name', '')
                     if neighbourhood in belem_tuple:
                         neighbourhood = 'Belém'
                     place['field_neighbourhood'] = neighbourhood
                 else:
                     place['field_neighbourhood'] = ''
                 if location:
                     address = location.address
                     address = address.replace('&', 'E').replace(';', ' ')
                     place['field_location_address_first_line'] = address
                 else:
                     input_str = '\"No Location for {}. Please enter it: \"'
                     subprocess.call(['say', input_str])
                     input_str = input_str.format(coords)
                     address = raw_input(input_str)
                     print 'You entered', address
                     address = address.replace('&', 'E').replace(';', ' ')
                     place['field_location_address_first_line'] = address
                 place['field_location_address_second_line'] = ''
                 if municipality:
                     municipality_name = municipality.get('name', '')
                     place['field_location_city'] = municipality_name
                 else:
                     place['field_location_city'] = ''
                 place['field_location_country'] = 'Portugal'
                 place['resource_id'] = resource_id
                 stop_places.append(place)
         records = {
             'resource_id': resource_id,
             'primary_key': ['field_poi_id'],
             'indexes': ['field_poi_id'],
             'records': stop_places,
             'force': True,
         }
         # print records
         response = requests.post(
             api,
             data=json.dumps(records),
             headers=CKAN_AUTH,
         )
         print "\n", response.content.encode('utf-8', 'replace'), "\n"
         if response.status_code != 200:
             print "\n\n>>>>>>>>>>>> ERROR"
             print records
Пример #11
0
async def black_list_info_callback_handler(
    query: types.CallbackQuery,
    callback_data: typing.Dict[str, str],
    user: UserRepository,
    _: dict,
    logger: logging.Logger,
    state: FSMContext,
):
    account_id = callback_data["id"]
    coin_id = callback_data['type']
    action = callback_data['action']
    page = int(callback_data['page'])

    if (action != '_'):
        async with state.proxy() as data:
            worker_id = data.get('workers_unique', {}).get(action, None)
            if (worker_id):
                is_blacklisted = await user.toggle_worker_blacklist(
                    query.from_user.id, worker_id)
                await query.answer(_['worker_blacklisted' if is_blacklisted
                                     else 'worker_not_blacklisted'].format(
                                         worker=worker_id, ))
            else:
                logger.warning(
                    f'worker_id was null {data.get("workers_unique")}')
                await query.answer(
                    'If you see this message please contact with support',
                    show_alert=True)

    keyboard_markup = types.InlineKeyboardMarkup(row_width=2)

    blacklisted_workers = [
        w.worker_id
        for w in await user.get_blacklisted_workers(query.from_user.id)
    ]

    workers = None
    async with EmcdClient(account_id, logger) as client:
        workers = await client.get_workers(coin_id)

    if (workers is None):
        await query.answer()
        logger.warning('workers is none')
        return

    buttons = []

    buttons_workers = []

    if (page > 1):
        buttons.append(
            types.InlineKeyboardButton(
                _["prev_button"],
                callback_data=worker_black_cb.new(id=account_id,
                                                  page=page - 1,
                                                  type=coin_id,
                                                  action="_"),
            ), )

    workers_normalized = workers.get_all_workers(0, )

    if (workers_normalized):
        buttons.append(
            types.InlineKeyboardButton(
                f"{page}/{ceil(len(workers_normalized) / PER_PAGE_BLACK_LIST)}",
                callback_data="do_nothing"), )

        async with state.proxy() as data:
            data['workers_unique'] = generate_unique_workers_dict(
                workers_normalized)

        for worker in workers_normalized[(page - 1) *
                                         PER_PAGE_BLACK_LIST:page *
                                         PER_PAGE_BLACK_LIST]:
            buttons_workers.append(
                types.InlineKeyboardButton(
                    worker.worker + (_["blacklist_pointer"] if worker.worker
                                     in blacklisted_workers else ""),
                    callback_data=worker_black_cb.new(
                        id=account_id,
                        page=page,
                        type=coin_id,
                        action=worker.hash_name()),
                ), )

        if (len(workers_normalized) > page * PER_PAGE_BLACK_LIST):
            buttons.append(
                types.InlineKeyboardButton(
                    _["next_button"],
                    callback_data=worker_black_cb.new(id=account_id,
                                                      page=page + 1,
                                                      type=coin_id,
                                                      action="_"),
                ), )

    for w_row in grouper(2, buttons_workers):
        keyboard_markup.row(*w_row)

    keyboard_markup.row(*buttons)

    coins = [
        coin for coin in await user.get_account_coins(
            query.from_user.id, account_id) if coin.is_active
    ]
    if (len(coins) == 1
        ):  #in case if enabled only one coin we treat them as default
        keyboard_markup.row(
            types.InlineKeyboardButton(
                _["cabinet"],
                callback_data=menu_cb.new(
                    id=account_id,
                    type="account",
                    action="open",
                ),
            ), )
    else:
        keyboard_markup.row(
            types.InlineKeyboardButton(
                _["back_to_workers_blacklist"],
                callback_data=worker_black_cb.new(
                    id=account_id,
                    page=page,
                    type=SELECT_COIN_CB,
                    action="_",
                ),
            ), )

    await query.message.edit_text(
        _['worker_blacklist_descr'].format(
            b_count=len(blacklisted_workers),
            pointer=_["blacklist_pointer"],
        ),
        reply_markup=keyboard_markup,
    )
    await query.answer()