def main():

    # Benchmarking program
    t = Timer(verbose=True)

    # Dataset
    X = [[1], [2], [3], [4], [5], [6], [7]]
    Y = [1, 2, 3, 4, 5, 6, 7]

    # Minimizing using gradient descent method
    print("\n> Using Gradient Descent")
    lr = LinearRegression(X, Y, 0.03)
    t.start()
    lr.setAlpha(0.035706)
    lr.gradientDescent()
    t.finish()
    predicted_Y2 = [lr.predict(x) for x in X]
    print("Error rate: %f" % lr.getErrorRate())

    # Plotting example (2d graph)
    plt.plot(X, Y, 'o')  # Dots are original distribution
    plt.plot(X, predicted_Y2, 'g')  # Green line is Gradient descent
    plt.show()

    return 0
Exemplo n.º 2
0
 def __init__(self, bot):
     self.bot = bot
     self.tris = False
     self.tris_board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
     self.turn = 0
     self.initializer = None
     self.guest = None
     self.running = False
     self.timeout_timer = Timer(60)
     self.lastBoard = None
Exemplo n.º 3
0
def main():
    # 初始化
    timer = Timer()
    kafka_producer = producer.Producer()
    kafka_consumer = consumer.Consumer()

    # 到期callback
    def on_expired(message):
        print('Task expired!')
        target_topic = _.get(message, 'target_topic')
        if target_topic:
            kafka_producer.send(topic=target_topic, value=message)
            kafka_producer.flush()
        else:
            print('Enqueue: target_topic is missing in enqueue message!')

    # 订阅原始消息
    @kafka_consumer.event_emitter.on('message')
    def on_message(message):
        print('Receive delay task!')
        timer.add(
            TimerTaskEntry(delay=(_.get(message, 'value.delay') or 0),
                           task=on_expired,
                           message=message.value))

    # 恢复上一次停机前状态
    timer.recover(task=on_expired)
    # 持久化当前状态
    timer.persist()
    # 启动Timer
    timer.start()
    # 启动原始消息订阅
    kafka_consumer.tail()
Exemplo n.º 4
0
    def __init__(self):
        """
        Description
            Blink LED without delay function.

            RealTime (int pin, int millis_period, boolean state)

        Parameters
            pin: Arduino LED pin
            millis_period: Time period to define blink delay (milliseconds)
            state: Initial LED state

        Returns
            void
        """
        self.timer = Timer(1000)
Exemplo n.º 5
0
    def __init__(self,
                 sock,
                 node_listen_addr,
                 ip_addresses,
                 other_end_listen_addr=None):

        super(Connection, self).__init__()
        self.daemon = True
        self.socket = sock
        self.node_listen_addr = node_listen_addr
        self.other_end_listen_addr = other_end_listen_addr
        """
        ping_status:
        Integer telling how many ping messages have not been answered. Value -1 means that an answer has been
        received during that cycle.
        """
        self.ping_status = -1
        self.ping_timer = Timer(PING_INTERVAL)

        self.read_queue = multiprocessing.Queue()
        self.write_queue = multiprocessing.Queue()
        self.ip_addresses = ip_addresses
Exemplo n.º 6
0
    def test_add(self):
        """
        添加任务测试
        :return:
        """
        timer = Timer(wheel_size=5)
        keys = [0, 0.1, 0.3, 0.8, 1, 2, 3, 4, 5, 8, 9, 10, 18, 24, 26, 30]
        for key in keys:
            timer.add(
                TimerTaskEntry(delay=key * 1000, task=self._print, key=key))

        time.sleep(keys[-1])
        timer.shutdown()
Exemplo n.º 7
0
class SigGen():
    """
    description:
    """

    __version__ = 0.01

    def __init__(self):
        """
        Description
            Blink LED without delay function.

            RealTime (int pin, int millis_period, boolean state)

        Parameters
            pin: Arduino LED pin
            millis_period: Time period to define blink delay (milliseconds)
            state: Initial LED state

        Returns
            void
        """
        self.timer = Timer(1000)

    def period(self, period):
        """
        Description
            Sine wave.

            object.sine()

        Parameters
            void

        Returns
            float: sine signal
        """
        self.timer.set(period)

    def sine(self):
        """
        Description
            Sine wave.

            object.sine()

        Parameters
            void

        Returns
            float: sine signal
        """
        spread = ((-math.cos((self.step() * math.pi) * 2.0)) + 1) / 2
        return spread

    def square(self):
        """
        Description
            Square wave.

            object.square()

            Waveform with 1000 milliseconds duration:

            1 ┐    ┌────┐
              │    │    │
              └────┘    └
              0   500   1000

        Parameters
            void

        Returns
            float: square signal
        """
        if self.step() < 0.5:
            spread = 0
        else:
            spread = 1
        return spread

    def step(self):
        """
        Description
            A time baseline to provide x axis to signal generation.

            step()

        Parameters
            void

        Returns
            float: time baseline from 0 to 1.
        """
        self.timer.check()
        return self.timer.status()
Exemplo n.º 8
0
class Connection(multiprocessing.Process):
    def __init__(self,
                 sock,
                 node_listen_addr,
                 ip_addresses,
                 other_end_listen_addr=None):

        super(Connection, self).__init__()
        self.daemon = True
        self.socket = sock
        self.node_listen_addr = node_listen_addr
        self.other_end_listen_addr = other_end_listen_addr
        """
        ping_status:
        Integer telling how many ping messages have not been answered. Value -1 means that an answer has been
        received during that cycle.
        """
        self.ping_status = -1
        self.ping_timer = Timer(PING_INTERVAL)

        self.read_queue = multiprocessing.Queue()
        self.write_queue = multiprocessing.Queue()
        self.ip_addresses = ip_addresses

    def run(self):
        process_print("New Connection() process running")

        # If socket is not created already, do it now.
        if self.socket is None:
            self.socket = connect(self.other_end_listen_addr[0],
                                  self.other_end_listen_addr[1])
            if self.socket is None:
                self.die()

            self.send_join_request()
            self.recv_join_response()
            self.register_connection(self.other_end_listen_addr)
        else:
            join_request = self.recv_join_request()
            self.other_end_listen_addr = (join_request.header.sender_ip,
                                          join_request.header.sender_port)
            self.send_join_response(join_request)
            self.register_connection(self.other_end_listen_addr)

        self.ping_timer.start()

        while True:
            if self.ping_timer.has_expired():
                self.ping_status += 1
                self.send_ping_a()
                self.ping_timer.start()

            read_sockets, _, _ = select.select(
                [self.read_queue._reader, self.socket], [], [], PING_INTERVAL)
            for sock in read_sockets:
                if sock == self.socket:
                    try:
                        header = self.recv_header()
                    except ValueError:
                        continue
                    body = recvall(self.socket, header.payload_len)

                    if header.msg_type == TYPE_QUERY_HIT:
                        self.write_queue.put(Message(header, body, None))

                    elif header.msg_type == TYPE_PING:
                        if header.time_to_live == 1:
                            self.respond_to_type_a_ping(header.msg_id)
                        else:
                            pass  # TODO: receive type b pings

                    elif header.msg_type == TYPE_PONG:
                        # Type A pong
                        if len(body) == 0:
                            self.ping_status = -1
                        else:
                            pass  # TODO: receive type b pongs

                    elif header.msg_type == TYPE_QUERY:
                        self.write_queue.put(
                            Message(header, body, [],
                                    [self.other_end_listen_addr]))

                else:
                    self.handle_read_queue()

    def handle_read_queue(self):
        message = self.read_queue.get()
        if isinstance(message, Message):
            self.send_message(message)

    def respond_to_type_a_ping(self, msg_id):
        header_obj = Header(TYPE_PONG, self.node_listen_addr[0],
                            self.node_listen_addr[1], 0, 1, msg_id)
        byte_header = header_obj.get_bytes()
        try:
            self.socket.sendall(byte_header)
        except socket.error:
            self.die()

    def recv_join_request(self):
        """
        :return: listen address (ip, port tuple) of the sender
        """
        header = self.recv_header()
        return Message(header)
        # TODO: validation

    def send_message(self, message):
        byte_header = message.header.get_bytes()
        try:
            self.socket.sendall(byte_header)
            self.socket.sendall(message.body)
            # process_print("sent message: " + str(byte_header) + " and body : " + str(message.body))  # DEBUG
        except socket.error:
            self.die()

    def send_join_request(self):
        header_obj = Header(TYPE_JOIN, self.node_listen_addr[0],
                            self.node_listen_addr[1], 0, 1)
        byte_header = header_obj.get_bytes()
        try:
            self.socket.sendall(byte_header)
        except socket.error:
            self.die()

    def send_ping_a(self):
        header_obj = Header(TYPE_PING, self.node_listen_addr[0],
                            self.node_listen_addr[1], 0, 1)
        byte_header = header_obj.get_bytes()
        try:
            self.socket.sendall(byte_header)
        except socket.error:
            self.die()

    def recv_join_response(self):
        header = self.recv_header()
        bytes_payload = recvall(self.socket, JOIN_RESPONSE_PAYLOAD_LEN)
        payload = struct.unpack("!H", bytes_payload)[0]
        if payload != JOIN_ACC:
            self.die()

    def send_join_response(self, request):
        header_obj = Header(TYPE_JOIN, self.node_listen_addr[0],
                            self.node_listen_addr[1],
                            JOIN_RESPONSE_PAYLOAD_LEN, 1,
                            request.header.msg_id)
        payload_bytes = struct.pack("!H", JOIN_ACC)
        try:
            self.socket.sendall(header_obj.get_bytes() + payload_bytes)
        except socket.error:
            self.die()

    def recv_header(self):
        bytes_header = recvall(self.socket, HEADER_LENGTH)
        if bytes_header is None:
            self.die()
        header_obj = unpack_header(bytes_header)
        return header_obj

    def register_connection(self, other_end_listen_addr):
        registration = InterprocessMessage(InterprocessMessage.REGISTER,
                                           other_end_listen_addr)
        self.write_queue.put(registration)

    def die(self):
        if self.socket is not None:
            self.socket.close()
        process_print("Process died")
        os._exit(0)
Exemplo n.º 9
0
                             '0 for not computing 1-log on all advantages')
    parser.add_argument('--sample_size', type=int, default=20)
    parser.add_argument('--fine_tune', action='store_true', help='fine tune with std rouge')
    parser.add_argument('--train_example_quota', type=int, default=-1,
                        help='how many train example to train on: -1 means full train data')
    parser.add_argument('--length_limit', type=int, default=-1,
                        help='length limit output')
    parser.add_argument('--ext_model', type=str, default="simpleRNN",
                        help='lstm_summarunner, gru_summarunner, bag_of_words, simpleRNN')
    parser.add_argument('--prt_inf', action='store_true')

    args = parser.parse_args()

    if args.length_limit > 0:
        args.oracle_length = 2

    torch.cuda.set_device(args.device)

    print('generate config')
    with open(args.vocab_file, "rb") as f:
        vocab = pickle.load(f, encoding='bytes')
    print(vocab)

    extract_net = extractive_training(args, vocab)


if __name__ == '__main__':
    timer = Timer()
    with timer:
        main()
Exemplo n.º 10
0
class Tris(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.tris = False
        self.tris_board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
        self.turn = 0
        self.initializer = None
        self.guest = None
        self.running = False
        self.timeout_timer = Timer(60)
        self.lastBoard = None

    async def DrawBoard(self, ctx, tris_board):
        self.lastBoard = await ctx.channel.send("""`+---+---+---+
| %c | %c | %c |
+---+---+---+
| %c | %c | %c |
+---+---+---+
| %c | %c | %c |
+---+---+---+`""" % (tris_board[0], tris_board[1], tris_board[2],
                     tris_board[3], tris_board[4], tris_board[5],
                     tris_board[6], tris_board[7], tris_board[8]))
        check = self.check_board()
        if check == 404:
            await ctx.channel.send(get_string(ctx, 'pareggio'))
            self.end_game()
        elif check != False:
            winner = self.initializer if check == 'x' else self.guest
            await ctx.channel.send(
                get_string(ctx, 'vincitore_e') + winner.mention)
            self.end_game()

    @commands.command()
    async def tris(self, ctx, member: discord.Member):
        # Inizio
        react = ['✅', '❌']
        # Devo sistemarla in qualche modo xDDD
        if self.running == True:
            await ctx.channel.send(get_string(ctx, 'partita_in_corso'))
            return
        if ctx.author == member:
            await ctx.channel.send(get_string(ctx, 'solo'))
            return
        if member.bot:
            await ctx.channel.send(get_string(ctx, 'gioco_con_bot'))
            return
        msg = await ctx.channel.send(
            f"{member.mention} {get_string(ctx, 'sfida')}")
        self.running = True
        # Aggiungi reazioni ad un messaggio per fare la sfida
        for r in react:
            await msg.add_reaction(r)

        def check_react(reaction, user):
            # Controllo cosa mette l'utente
            if user != member or reaction.message.id != msg.id or not str(
                    reaction.emoji) in react:
                return False
            return True

        try:
            res, user = await self.bot.wait_for('reaction_add',
                                                check=check_react,
                                                timeout=15)
        except asyncio.TimeoutError:
            await ctx.channel.send(
                f'{member.mention} {get_string(ctx, "timeout")}')
            self.running = False
            return

        # In caso accetta
        if react[0] in str(res.emoji):
            await ctx.channel.send(
                f'{member.mention} {get_string(ctx, "accept")}')
        # Se rifiuta
        elif react[1] in str(res.emoji):
            await ctx.channel.send(
                f'{member.mention} {get_string(ctx, "decline")}')
            self.running = False
            return

        # Numeri per far vedere come si gioca
        num_tris_board = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
        await ctx.channel.send('Iniziando sessione di tris...')
        if member == self.bot.user:
            await ctx.send.channel('Non puoi sfidare il bot!')
            return
        # Disegno tavola iniziale
        await self.DrawBoard(ctx, num_tris_board)
        await ctx.channel.send(get_string(ctx, 'reg_tris'))
        self.tris = True
        self.initializer = ctx.author
        self.guest = member
        loop = asyncio.get_event_loop()
        # Inizio timer della morte
        self.timeout_timer.call_at_end(lambda: (self.timeout(ctx, loop)))
        t = Thread(target=self.timeout_timer.start)
        t.start()

    def timeout(self, ctx, loop):
        loop.create_task(ctx.channel.send(get_string(ctx, 'timeout60')))
        self.end_game()

    @commands.Cog.listener()
    async def on_message(self, ctx):
        # Controllo se persona ha i diritti di giocare
        if not self.tris or ctx.author == self.bot.user or (
                ctx.author != self.initializer and ctx.author != self.guest):
            return
        else:
            # Controllo se ha scritto un numero
            num = re.search(numbers, ctx.content)
            # Controllo di chi e' il turno
            if self.turn % 2 == 0 and ctx.author != self.initializer:
                await ctx.channel.send(
                    get_string(ctx, 'turno_di') + self.initializer.mention +
                    '!')
                return
            if self.turn % 2 == 1 and ctx.author != self.guest:
                await ctx.channel.send(
                    get_string(ctx, 'turno_di') + self.guest.mention + '!')
                return
            if num == None:
                await ctx.channel.send(get_string(ctx, 'number_19'))
                return
            num = int(num.group()) - 1
            # Controllo se casella gia' occupata
            if self.tris_board[num] != ' ':
                await ctx.channel.send(get_string(ctx, 'occupato'))
                await self.DrawBoard(ctx, self.tris_board)
                return
            self.tris_board[num] = 'x' if self.turn % 2 == 0 else 'o'
            # Aumento turno
            self.turn += 1
            if self.lastBoard != None:
                await self.lastBoard.delete()
                await ctx.delete()
            # Disegno tavola
            await self.DrawBoard(ctx, self.tris_board)
            # Reset timer della morte
            self.timeout_timer.reset()

    def check_board(self):
        # Orizzontale
        if self.tris_board[0] == self.tris_board[1] and self.tris_board[
                0] == self.tris_board[2] and self.tris_board[0] != ' ':
            return self.tris_board[0]
        if self.tris_board[3] == self.tris_board[4] and self.tris_board[
                3] == self.tris_board[5] and self.tris_board[3] != ' ':
            return self.tris_board[3]
        if self.tris_board[6] == self.tris_board[7] and self.tris_board[
                6] == self.tris_board[8] and self.tris_board[6] != ' ':
            return self.tris_board[6]
        #Verticale
        if self.tris_board[0] == self.tris_board[3] and self.tris_board[
                0] == self.tris_board[6] and self.tris_board[0] != ' ':
            return self.tris_board[0]
        if self.tris_board[1] == self.tris_board[4] and self.tris_board[
                1] == self.tris_board[7] and self.tris_board[1] != ' ':
            return self.tris_board[1]
        if self.tris_board[2] == self.tris_board[5] and self.tris_board[
                2] == self.tris_board[8] and self.tris_board[2] != ' ':
            return self.tris_board[2]
        #Obliquo
        if self.tris_board[0] == self.tris_board[4] and self.tris_board[
                0] == self.tris_board[8] and self.tris_board[0] != ' ':
            return self.tris_board[0]
        if self.tris_board[2] == self.tris_board[4] and self.tris_board[
                2] == self.tris_board[6] and self.tris_board[2] != ' ':
            return self.tris_board[2]
        # Tutte piene
        if not ' ' in self.tris_board:
            return 404
        return False

    def end_game(self):
        # Reset allo stato iniziale
        self.tris = False
        self.initializer = None
        self.guest = None
        self.tris_board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
        self.turn = 0
        self.timeout_timer.stop()
        self.running = False

    @tris.error
    async def error(self, ctx, error):
        if isinstance(error, commands.MissingRequiredArgument):
            await ctx.send(get_string(ctx, 'da_solo'))
        elif isinstance(error, commands.MemberNotFound):
            await ctx.send(get_string(ctx, 'immaginary'))