예제 #1
0
파일: bot.py 프로젝트: te0d/discord-misc
    async def on_message(self, message):
        # Check for command
        match = shortcut_regex.match(message.content)
        if (not match):
            return

        logging.debug(
            "Recognized command from {0.author}: {0.content}".format(message))

        # Parse arguments
        try:
            raw_args = parser.convert_arg_line_to_args(match.group("args"))
            args = parser.parse_args(raw_args)
        except ValueError as err:
            await message.channel.send(err)
            return

        # Perform action
        player = self.get_player(message.author)
        if (args.command is None):
            help_msg = "```\n{0}\n```".format(parser.format_help())
            await message.channel.send(help_msg)
        else:
            output = args.action(player, args)
            if (output and output.private):
                await message.author.send(output.message)
            elif (output):
                await message.channel.send(output.message)
예제 #2
0
def main():
    call_args = parser.parse_args()

    if call_args.experiment:
        import pickle
        from experiments import testar_parametros_paralelo_por_arquivo
        print(call_args.tsp_queue)
        r = testar_parametros_paralelo_por_arquivo(
            list(glean_tsp_files(call_args.tsp_queue)))
        binary_file = open(call_args.tsp_queue[0] + '/my_pickled_results.bin',
                           mode='wb')
        pickle.dump(r, binary_file)
        binary_file.close()
        import os
        os.system(
            'play --no-show-progress --null --channels 1 synth %s sine %f' %
            (0.1, 440))

    elif call_args.results:
        from experiments import process_results, process_one_result
        import pickle
        # r = pickle.loads(open(call_args.tsp_queue[0] + '/my_pickled_results.bin', mode='rb').read())
        for tsp_path in glean_tsp_files(call_args.tsp_queue):
            # print(tsp_path)
            r = pickle.loads(open(tsp_path, mode='rb').read())
            process_one_result(r)

    else:
        for tsp_path in glean_tsp_files(call_args.tsp_queue):
            process_from_tsp_path(call_args, tsp_path)
예제 #3
0
def main():
    cli_args = parser.parse_args(sys.argv[1:])
    config_name = cli_args.input
    output_file = cli_args.output

    config = configparser.ConfigParser()
    config.read(config_name)
    args = config['MAIN']
    """
    article_text = args['article']
    article_url = args['url']
    article_title = args['title']
    article_doi = args['doi']
    """

    print('Внимание! Проверьте правильность входных данных:')
    timer = threading.Event()
    timer.clear()
    timer.wait(3)
    for key, value in config['MAIN'].items():
        print(fields_definitions[key])
        timer.wait(0.2)
        print(value)
    if not accept_key():
        print('Завершение работы.')
        return
    print('Запуск поискового бота')
    timer.wait(3)
    results = run(**args)

    print('Поиск завершен. Найдены следующие ссылки:')

    header = 'Название страницы, Оценка точности, URL-адрес \n'
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(header)
        print(header)
        for line in results:
            f.write(line)
            print(line)

    print('Все ссылки сохранены в файле {}'.format(output_file))
    input('Поиск завершен. Нажмите любую клавишу для завершения')
예제 #4
0
def main():

    args = parser.parse_args()
    
    if (args.enc):
        print("encrypt") 
        encryptFile(args.filepath)

    elif (args.dec):
        print("decrypt")
        decryptFile(args.filepath)

    elif (args.sgn):
        print("sighn") 
        addSignature(args.filepath)

    elif (args.chcksign):
        print("check sign")
        if checkSignature(args.filepath, args.sgnpath):
            print('Sign correct')
        else:
            print('Sign incorrect')
예제 #5
0
def main():
    call_args = parser.parse_args()
    for tsp_path in glean_tsp_files(call_args.tsp_queue):
        print_results_from_tsp_path(call_args,tsp_path)
예제 #6
0
def main():
    call_args = parser.parse_args()
    for tsp_path in glean_tsp_files(call_args.tsp_queue):
        print_results_from_tsp_path(call_args, tsp_path)
예제 #7
0
logger = logging.getLogger('mastermind')
logger.propagate = False
logger.setLevel(logging.INFO)

# create console handler with a higher log level
ch = logging.StreamHandler()

# create formatter and add it to the handlers
formatter = logging.Formatter('%(levelname)s - %(message)s')

ch.setFormatter(formatter)

logger.addHandler(ch)

args = parser.parse_args()
game_solver = Mastermind(args.k, args.n, logger=logger, pretty_printer=pretty_name_8_colors)


def init_worker(shared_counter):
    global counter
    counter = shared_counter


# hack to overcome limitation of Pool.map which is unable to execute instance methods
def f(x):
    res = game_solver.batch_solve(x)
    counter.value += 1
    logger.info("{}/{} {}%".format(counter.value, len(game_solver.all_possible_combinations),
                                   100.0 * counter.value / len(game_solver.all_possible_combinations)))
    return res
예제 #8
0
        n = n - 1
    return D(result)


def get_ramanujan_term(k):
    pid = getpid()
    log('...({}) is calculating term for k={}'.format(pid, k))
    k = D(k)
    num = multiply(factorial(4 * k), addition(D(1103), multiply(D(26390), D(k))))
    den = multiply(power(factorial(k), D(4)), power(D(396), multiply(D(4), D(k))))
    term = divide(num, den)
    log('...({}) is done for k={}'.format(pid, k))
    return term

if __name__ == '__main__':
    args = parser.parse_args()

    if args.precision is 1:
        print('default precision 0 will be used')

    # start worker processes
    ts = time()
    log('Started at {}'.format(datetime.now()), True)

    with Pool(processes=args.tasks) as pool:
        factor = divide(multiply(D(2), sqrt(D(2))), D(9801))
        all_terms = pool.map(get_ramanujan_term, range(args.precision))
        the_sum = reduce(lambda x, y: addition(x, y), all_terms)

        with open(args.output_file, 'w') as f:
            f.write('Pi({}) = {}'.format(args.precision, 1 / multiply(factor, the_sum)))
예제 #9
0
                    translations = re.findall(
                        r"""
                        # userContextPersonal.label = Pa ngat moni
                        userContext
                        (Personal|Work|Banking|Shopping|None)
                        \.
                        label
                        \ = \ 
                        (.*?)
                        \n
                        """,
                        browser_properties.read().decode("utf-8"),
                        flags=re.X
                    )

        logging.info(f"Got translations for {lang_name}.")

        await res_q.put((lang_name, lang_code, translations))
        
        file_q.task_done()

if __name__ == "__main__":
    args_dict = vars(parser.parse_args())

    logging.basicConfig(level=args_dict["log"],format="%(message)s")

    # asyncio.run results in RuntimeError: Event loop is closed
    loop = asyncio.get_event_loop()
    loop.set_debug(args_dict["debug"])
    loop.run_until_complete(main(args_dict["workers"]))
예제 #10
0
from MarioGym import MarioGym, MAP_MULTIPLIER, MAP_WIDTH, MAP_HEIGHT
import tensorflow as tf

if "../" not in sys.path:
    sys.path.append("../")

from lib import plotting
from collections import deque, namedtuple
import matplotlib.pyplot as plt
import numpy as np
from constants import *
from argparser import parser
from PER import SumTree, Memory

arguments = parser.parse_args()

env = MarioGym(HEADLESS,
               step_size=STEP_SIZE,
               level_name=LEVEL_NAME,
               partial_observation=PARTIAL_OBSERVATION,
               distance_reward=DISTANCE_REWARD,
               experiment=EXPERIMENT)


class StateProcessor():
    """
    Processes a raw Atari images. Resizes it and converts it to grayscale.
    """
    def __init__(self):
        # Build the Tensorflow graph