def verificarBaseFull(self, operador):
     hexadecimal = ""
     if operador[0] == self.INDICADOR_HEXADECIMAL:
         try:
             hexadecimal = base(operador.lstrip(
                 self.INDICADOR_HEXADECIMAL).upper(),
                                16,
                                16,
                                string=True)
         except ValueError:
             # print("El operador " + operador + " no esta bien definido")
             return False
     elif operador[0] == self.INDICADOR_OCTAL:
         try:
             hexadecimal = base(operador.lstrip(
                 self.INDICADOR_OCTAL).upper(),
                                8,
                                16,
                                string=True)
         except ValueError:
             # print("El operador " + operador + " no esta bien definido")
             return False
     elif operador[0] == self.INDICADOR_BINARIO:
         try:
             hexadecimal = base(operador.lstrip(
                 self.INDICADOR_BINARIO).upper(),
                                2,
                                16,
                                string=True)
         except ValueError:
             # print("El operador " + operador + " no esta bien definido")
             return False
     else:
         return int(operador)
     return hexadecimal
 def esEtiqueta(self, operador):
     if operador[0] != '$' or operador[0] != '%' or operador[0] != '@':
         try:
             base(operador, 10, string=True)
         except ValueError:
             return True
         else:
             return False
Ejemplo n.º 3
0
 def _vectorIndex(self, i: int, j: int, k: int) -> int:
     return int(''.join(
         map(
             str,
             baseconvert.base(number=str(i) + str(j) + str(k),
                              input_base=self._size,
                              output_base=10))))
Ejemplo n.º 4
0
def convert_num_sys(number, sys_now, sys_will):
    """Функция baseconvert.base не поддерживает отрицательные числа, поэтому нужна эта обертка."""
    ret = number
    neg = ret[0] == '-'
    if neg:
        """Приходится извращаться с удалением символов при работе со строками. И че ж они del не поддерживают?"""
        ret = ret[1:len(ret)]
    ret = baseconvert.base(ret,
                           sys_now,
                           sys_will,
                           string=True,
                           recurring=False)
    if neg:
        """Как удален был знак, так и должен быть восстановлен"""
        ret = '-' + ret
    if ret[-1] == '.':
        ret += '0'
    try:
        """Проверка на то, целое ли число"""
        int(ret)
    except:
        """Если число не целое, то округлить его"""
        if sys_will <= 10:
            ret = str(round(float(ret), 8))
    return ret
Ejemplo n.º 5
0
    def funcion02(self, obj, instruccion):
        if instruccion[4] == self.IDX_1:
            codop = instruccion[1][:2]
            num = int(self.verificarBaseFull(instruccion[3][2][0]))
            rr = self.obtenerCodRegistro(instruccion[3][2][1])
            z = '0'
            if num >= 0:
                s = '0'
            else:
                s = '1'

            offset = Bits(int=num, length=12).bin[4:]
        else:
            codop = instruccion[1][:2]
            a = obj.existeIdentificador(instruccion[3][2][0])
            if a[0]:
                idNum = a[1][1]
                num = int(self.verificarBaseFull(idNum))
            else:
                num = int(self.verificarBaseFull(instruccion[3][2][0]))
            rr = self.obtenerCodRegistro(instruccion[3][2][1])
            z = '1'
            if num >= 0:
                s = '0'
                offset = Bits(uint=num, length=16).bin
            else:
                s = '1'
                offset = Bits(int=num, length=16).bin[4:]

        return codop + base(
            '111' + rr + '0' + z + s + offset, 2, 16, string=True).zfill(
                int(instruccion[2][4]))
 def hex2Dec(self, convertir):
     try:
         decimal = base(convertir.upper(), 16,10, string=True)
     except ValueError:
         print("El valor " + str(convertir) + " no puede ser convertido de hexadecimal a decimal")
         return False
     return decimal
Ejemplo n.º 7
0
def int_to_list(i, shorten_base=False):
    """
    Converts integer to emoji-indexed list (e.g. 1500 => [1, 22, 21])
    Also supports shortened base, if we want to create a reserve sentinel character (See README.md for more on this)
    """
    base = alphabet.length if not shorten_base else alphabet.length - 1
    return list(baseconvert.base(i, 10, base))
Ejemplo n.º 8
0
 def sig(self):
     key_encoded = settings.SECRET_KEY.encode('utf-8')
     pk_encoded = self.pk_encoded.encode('utf-8')
     sig_16 = hmac.new(key=key_encoded, msg=pk_encoded).hexdigest()
     sig_10 = int(sig_16, base=16)
     sig_62 = base(sig_10, 10, 62, string=True)
     return sig_62[:settings.PRIVATE_SHORTENER_SIG_LENGTH]
 def dec2Hex(self, convertir):
     try:
         hexadecimal = base(str(convertir).upper(), 10,16, string=True)
     except ValueError:
         print("El valor " + str(convertir) + " no puede ser convertido de decimal a hexadecimal")
         return False
     return hexadecimal
Ejemplo n.º 10
0
def fromid(id):
    out = basep(id, 36, 16, string=True, pad=6)
    result = tuple(
        map(
            lambda x: "".join(
                map(lambda y: str(y), base(x, 16, 10, string=True))),
            (out[2:4], out[4:6], out[0:2])))
    return ('192.168.' + result[0] + "." + result[1], int(result[2]))
    def funcion06(self, obj, instruccion):
        codop = instruccion[1][:2]

        rr = self.obtenerCodRegistro(instruccion[3][2][1][:-1])
        if not rr:
            return False

        return codop + base('111' + rr + '111', 2, 16, string=True)
Ejemplo n.º 12
0
 def _indexToMove(self, index: int) -> Tuple[int, int, int]:
     result = ''.join(
         map(
             str,
             baseconvert.base(number=index,
                              input_base=10,
                              output_base=self._size))).zfill(3)
     return int(result[0]), int(result[1]), int(result[2])
Ejemplo n.º 13
0
 def action_to_string(self, action):
     """
     Convert an action number to a string representing the action.
     Args:
         action_number: an integer from the action space.
     Returns:
         String representing the action.
     """
     return baseconvert.base(action, 10, 6, string=True)
Ejemplo n.º 14
0
def pascal(n):
    t = 0
    p = 1
    j = int(log(n, 7))
    for i in base(n, 10, 7):
        t += int((i * (i + 1)) / 2) * p * (28**j)
        j -= 1
        p *= (i + 1)
    print(t)
Ejemplo n.º 15
0
def emoji():
    token = request.query.u
    nums = ''.join(map(inv_table.get, token))
    chunks = re.findall('....', nums)  # splits into 4-char chunks
    chunks = [int(baseconvert.base(c, 4, 10, string=True)) for c in chunks]
    url = ''.join(chr(i) for i in chunks)

    response.set_header('Location', url)
    response.status = 302
    return response
Ejemplo n.º 16
0
    def human_to_action(self):
        """
        For multiplayer games, ask the user for a legal action
        and return the corresponding action number.

        Returns:
            An integer from the action space.
        """
        a = input('Your move:')
        x, y = (5 - int(a[0])), (5 - int(a[1]))
        return baseconvert.base(int(str(x) + str(y)), 6, 10, string=True)
Ejemplo n.º 17
0
def new_link():
    to = request.query.u

    chars = [ord(i) for i in to]
    chars = [
        baseconvert.base(i, 10, 4, string=True).rjust(4, '0') for i in chars
    ]
    chars = [''.join(map(table.get, i)) for i in chars]
    token = ''.join(chars)
    url = f'http://lengthened.link/emoji?u={token}'
    return f"<!doctype html><html><head></head><body><a href='{url}'>{url}</a></body></html>"
    def funcion03(self, obj, instruccion):
        codop = instruccion[1][:2]
        a = obj.existeIdentificador(instruccion[3][2][0][1:])
        if a[0]:
            idNum = a[1][1]
            num = self.verificarBaseFull(idNum)
        else:
            num = self.verificarBaseFull(instruccion[3][2][0][1:])

        rr = self.obtenerCodRegistro(instruccion[3][2][1][:-1])
        if not rr:
            return False

        if type(num) == int:
            n = Bits(int=num, length=16).bin[4:]
        else:
            n = Bits(hex=num).bin

        return codop + base('111' + rr + '011', 2, 16, string=True) + base(
            n, 2, 16, string=True).zfill(4)
Ejemplo n.º 19
0
def _encode_as_tile_id(tile_x, tile_y, zoom_level):
    assert tile_x.bit_length() <= zoom_level
    assert tile_y.bit_length() <= zoom_level

    interleaved_bits = _perfect_shuffle(tile_y, tile_x)
    print(interleaved_bits)
    interleaved_bits = (0b1 << (2 * zoom_level)) + interleaved_bits
    print(interleaved_bits)
    quadkey = base(interleaved_bits, 10, 4, string=True)
    print(quadkey)

    return str(int(quadkey, 4))
Ejemplo n.º 20
0
def main():
    """
    Main entry point for running baseconvert as a command.

    Examples:

        $ python -m baseconvert -n 0.5 -i 10 -o 20 -s True
        0.A

        $ echo 3.1415926 | python -m baseconvert -i 10 -o 16 -d 3 -s True
        3.243
    """
    # Parse arguments
    parser = argparse.ArgumentParser(description="Convert rational numbers between bases.")
    parser.add_argument("-n", "--number", default=None,
                        help="The number to convert as a string, else stdin used.")
    parser.add_argument("-i", "--input-base", default=10,
                        help="The input base (default 10).")
    parser.add_argument("-o", "--output-base", default=10,
                        help="The output base (default 10).")
    parser.add_argument("-d", "--max_depth", default=10, type=int,
                        help="The maximum fractional digits (default 10).")
    parser.add_argument("-r", "--recurring", default=True, type=bool,
                        help="Boolean, if True will attempt to find recurring decimals (default True).")
    parser.add_argument("-s", "--string", type=bool,
                        help="Boolean, if True will output number as String, else as tuple (default False).")
    args = parser.parse_args()

    args.input_base = float(args.input_base)
    args.output_base = float(args.output_base)
    if args.input_base == int(args.input_base):
        args.input_base = int(args.input_base)
    if args.output_base == int(args.output_base):
        args.output_base = int(args.output_base)
    if (args.number):
        return base(args.number, args.input_base, args.output_base, string=args.string, max_depth=args.max_depth, recurring=args.recurring)
    elif not sys.stdin.isatty():
        return base(sys.stdin.read().strip(), args.input_base, args.output_base, string=args.string, max_depth=args.max_depth, recurring=args.recurring)
    else:
        raise ValueError("Please input a number!")
Ejemplo n.º 21
0
    def funcion01(self, obj, instruccion):
        codop = instruccion[1][:2]
        num = int(self.verificarBaseFull(instruccion[3][2][0]))

        rr = self.obtenerCodRegistro(instruccion[3][2][1])

        if num >= 0:
            n = '0'
        else:
            n = '1'

        nnnn = Bits(int=num, length=8).bin[4:]

        return codop + base(rr + '0' + n + nnnn, 2, 16, string=True).zfill(
            int(instruccion[2][4]))
Ejemplo n.º 22
0
    def quadgen(self, tileX, tileY):
        binTileX = format(tileX, '#0' + str(self.level + 2) + 'b')[2:]
        # print(binTileX)
        binTileY = format(tileY, '#0' + str(self.level + 2) + 'b')[2:]
        # print(binTileY)
        quadkey = ''
        for i in range(self.level):
            bit = self.level - i - 1
            quadkey = (str(binTileX)[bit]) + quadkey
            quadkey = (str(binTileY)[bit]) + quadkey
        # print(quadkey)
        final = baseconvert.base((int(quadkey, 2)), 10, 4, string=True)
        while (len(final) != self.level):
            final = '0' + final

        return final
    def funcion05(self, obj, instruccion):
        codop = instruccion[1][:2]

        if instruccion[3][2][0] == self.REGISTRO_A:
            aa = '00'
        elif instruccion[3][2][0] == self.REGISTRO_B:
            aa = '01'
        elif instruccion[3][2][0] == self.REGISTRO_D:
            aa = '10'
        else:
            print('Error: El acumulador no existe. {}'.format(instruccion))
            return False

        rr = self.obtenerCodRegistro(instruccion[3][2][1])

        return codop + base('111' + rr + '1' + aa, 2, 16, string=True)
    def funcion04(self, obj, instruccion):
        codop = instruccion[1][:2]

        a = obj.existeIdentificador(instruccion[3][2][0])
        if a[0]:
            idNum = a[1][1]
            num = self.verificarBaseFull(idNum)
        else:
            num = self.verificarBaseFull(instruccion[3][2][0])

        if instruccion[3][2][1].startswith(
                '+') or instruccion[3][2][1].startswith('-'):
            if instruccion[3][2][1][1:] == self.REGISTRO_PC:
                print(
                    'Error: No es valido el registro PC para esta instrucción. {}'
                    .format(instruccion))
                return False
            rr = self.obtenerCodRegistro(instruccion[3][2][1][1:])
            if not rr:
                return False
            p = '0'
        elif instruccion[3][2][1].endswith(
                '+') or instruccion[3][2][1].endswith('-'):
            if instruccion[3][2][1][:-1] == self.REGISTRO_PC:
                print(
                    'Error: No es valido el registro PC para esta instrucción. {}'
                    .format(instruccion))
                return False
            rr = self.obtenerCodRegistro(instruccion[3][2][1][:-1])
            if not rr:
                return False
            p = '1'

        if instruccion[3][2][1].startswith(
                '+') or instruccion[3][2][1].endswith('+'):
            nnnn = Bits(int=int(num) - 1, length=8).bin[4:]
        elif instruccion[3][2][1].startswith(
                '-') or instruccion[3][2][1].endswith('-'):
            nnnn = Bits(int=-int(num), length=8).bin[4:]

        return codop + base(rr + '1' + p + nnnn, 2, 16, string=True)
Ejemplo n.º 25
0
def convert_num_sys(number, sys_now, sys_will):
	"""Функция baseconvert.base не поддерживает отрицательные числа, поэтому нужна эта обертка."""
	ret = number
	neg = ret[0] == '-'
	if neg:
		"""Приходится извращаться с удалением символов при работе со строками. И че ж они del не поддерживают?"""
		ret = ret[1:len(ret)]
	print(number)
	ret = baseconvert.base(ret, sys_now, sys_will, string=True, recurring=False)
	if neg:
		"""Как удален был знак, так и должен быть восстановлен"""
		ret = '-' + ret
	if ret[-1] == '.':
		ret += '0'
	else:
		try:
			tmp = round(float(ret), 5)
			return str(tmp)
		except:
			pass
	return ret
def makeBot():
    gene = []
    for i in range(243):
        # Clear the screen
        system('cls')

        #draw the situation
        currSit = baseconvert.base(str(i), 10, 3, string=True)
        currSit = str(currSit)
        while len(currSit) < 5:
            currSit = "0" + currSit

        if currSit[4] == "2":
            gene.append("4")
            continue

        print(currSit)
        sitPrint(currSit)
        print(
            "Press arrow keys or the 'E' key to program the robot and move to the next scenario."
        )
        gene.append(keyCheck())
    print("".join(gene))
Ejemplo n.º 27
0
def test(i, b):
    return int(base(i, 10, b, string=True))
Ejemplo n.º 28
0
def convertDecimalToBinary(decimal):
    return base(decimal, 10, 2)
Ejemplo n.º 29
0
def convert_base(number, input_base, output_base):
    return baseconvert.base(number, input_base, output_base, string=True)
Ejemplo n.º 30
0
def best_match_base(odds_function,
                    profit_function,
                    criteria,
                    display_function,
                    result_function,
                    site,
                    sport="football",
                    date_max=None,
                    time_max=None,
                    date_min=None,
                    time_min=None,
                    combine=False,
                    nb_matches_combine=2,
                    freebet=False,
                    one_site=False,
                    recalcul=False,
                    combine_opt=False):
    """
    Fonction de base de détermination du meilleur match sur lequel parier en
    fonction de critères donnés
    """
    try:
        if combine:
            all_odds = filter_dict_dates(sportsbetting.ALL_ODDS_COMBINE,
                                         date_max, time_max, date_min,
                                         time_min)
        else:
            all_odds = filter_dict_dates(sportsbetting.ODDS[sport], date_max,
                                         time_max, date_min, time_min)
    except NameError:
        print("""
        Merci de définir les côtes de base, appelez la fonction parse_football,
        parse_nba ou parse_tennis selon vos besoins""")
        return
    best_profit = -float("inf")
    best_rank = 0
    if combine:
        n = (2 + (sport not in ["tennis", "volleyball", "basketball", "nba"
                                ]))**nb_matches_combine
    else:
        n = 2 + (sport not in ["tennis", "volleyball", "basketball", "nba"])
    best_match = None
    best_overall_odds = None
    sites = None
    for match in all_odds:
        if site in all_odds[match]['odds']:
            odds_site = all_odds[match]['odds'][site]
            best_odds = copy.deepcopy(odds_site)
            best_sites = [site for _ in range(n)]
            if not one_site:
                for odds in all_odds[match]['odds'].items():
                    for i in range(n):
                        if odds[1][i] > best_odds[i] and (odds[1][i] >= 1.1
                                                          or odds[0] == "pmu"):
                            best_odds[i] = odds[1][i]
                            best_sites[i] = odds[0]
            for odd_i, site_i in zip(best_odds, best_sites):
                if odd_i < 1.1 and site_i != "pmu":
                    break
            else:
                for i in range(n):
                    try:
                        odds_to_check = odds_function(best_odds, odds_site, i)
                        if criteria(odds_to_check, i):
                            profit = profit_function(odds_to_check, i)
                            if profit > best_profit:
                                best_rank = i
                                best_profit = profit
                                best_match = match
                                best_overall_odds = odds_to_check
                                sites = best_sites[:i] + [
                                    site
                                ] + best_sites[i + 1:]
                    except ZeroDivisionError:  # Si calcul freebet avec cote de 1
                        pass
    if best_match:
        if combine_opt and combine:
            ref_combinaison = list(
                reversed(baseconvert.base(best_rank, 10,
                                          get_nb_issues(sport))))
            n_combi = len(ref_combinaison)
            for _ in range(nb_matches_combine - n_combi):
                ref_combinaison.append(0)
            stakes = result_function(best_overall_odds, best_rank)
            best_combine_reduit(best_match.split(" / "),
                                list(reversed(ref_combinaison)), site,
                                stakes[best_rank], sport)
        else:
            print(best_match)
            pprint(all_odds[best_match], compact=True)
            if recalcul:
                sum_almost_won = find_almost_won_matches(
                    best_match, result_function(best_overall_odds, best_rank),
                    sport)
                display_function = lambda x, y: mises(
                    x, 10000 * 50 / sum_almost_won, True)
                result_function = lambda x, y: mises(
                    x, 10000 * 50 / sum_almost_won, False)
                find_almost_won_matches(
                    best_match, result_function(best_overall_odds, best_rank),
                    sport, True)
            second_rank = display_function(best_overall_odds, best_rank)
            afficher_mises_combine(
                best_match.split(" / "), [sites],
                [result_function(best_overall_odds, best_rank)],
                all_odds[best_match]["odds"], sport,
                best_rank if freebet else None, one_site and freebet,
                best_overall_odds, second_rank)
    else:
        print("No match found")
Ejemplo n.º 31
0
 async def convert(self, ctx, number, basefrom : int, baseto :int ):
     result = base(number, basefrom, baseto, string=True)
     await ctx.send('{0} na base {1} para base {2} dá:\n{3}'
             .format(number, basefrom, baseto, result))