def main():
    global i, fails
    fails = 0
    while True:
        print "1.Authorization"
        print "2.Help"
        print "3.Exit"
        try:
            i = input('Enter number:')
        except SyntaxError:
            print colored("Please enter valid number", 'red')
        while switch(i):
            if case(1):
                try:
                    login = str(input("Enter login:"******"Enter password:"******"Reminder : string have format 'string'",
                                  'red')
                    if fails == 3:
                        raise SystemExit("Third identification is failed")
                    break
                except UnboundLocalError:
                    fails += 1
                    print colored("Reminder : string have format 'string'",
                                  'red')
                    if fails == 3:
                        raise SystemExit("Third identification is failed")
                    break
                except NameError:
                    fails += 1
                    print colored("Reminder : string have format 'string'",
                                  'red')
                    if fails == 3:
                        raise SystemExit("Third identification is failed")
                    break
                context = identification(login, password)
                if not context:
                    fails += 1
                    print colored("Password or login isn't valid", 'red')
                    if fails == 3:
                        raise SystemExit("Third identification is failed")
                else:
                    context.user.authorization(login, password)
                    if context.type == 'admin':
                        admin(context)
                    elif context.type == 'common':
                        user(context)
                    else:
                        raise KeyError
            if case(3):
                raise SystemExit
            if case(2):
                print colored("Варіант 6.Зацепін Олексій ФБ-31", 'blue')
                print colored(
                    "     Наявність латинських букв, символів кирилиці і цифр.",
                    'blue')
            print colored("Please retype number", 'red')
            break
예제 #2
0
 def run(self, ch):
     self.show_text("use 'wasd'->move, space->edit, 'c'->change labels, 'v'->save")
     self.window.refresh()
     for c in switch(ch):
         if c(ord('w')):
             self.move('up')
         if c(ord('s')):
             self.move('down')
         if c(ord('a')):
             self.move('pageup')
         if c(ord('d')):
             self.move('pagedown')
         if c(ord('q')):
             return False
         if c(ord(':')):
             idx = self.stdscr.getstr()
             try:
                 self.goto(int(idx))
             except:
                 pass
         if c(ord(' ')):
             self.article_viewer.start(self)
             self.refresh()
         if c(ord('c')):
             self.label_set.start(self)
             self.refresh()
         if c(ord('v')):
             self.article_mgr.save_label_sheet()
         if c():
             return True
     self.refresh()
     self.input_cursor_clear()
     return True
예제 #3
0
def travel(stretch, origin):
    vector = switch(lambda direction, length: direction, {
        'U': lambda direction, length: Point((0, length)),
        'R': lambda direction, length: Point((length, 0)),
        'D': lambda direction, length: Point((0, -length)),
        'L': lambda direction, length: Point((-length, 0)),
    })
    return Point(origin) + vector(**stretch)
def main():
    global i, fails
    fails = 0
    while True:
        print "1.Authorization"
        print "2.Help"
        print "3.Exit"
        try:
            i = raw_input('Enter number:')
        except SyntaxError:
            print colored("Please enter valid number", 'red')
        while switch(i):
            if case(1):
                try:
                    login = str(raw_input("Enter login:"******"Enter password:"******"Reminder : string have format 'string'", 'red')
                    if fails == 3:
                        time.sleep(5)
                        raise SystemExit("Third identification is failed")
                context = Context(login)
                with open('base.txt', 'w') as handle:
                    user_list = view_user_list()
                    for item in user_list:
                            item = list(item)
                            temp = "".join(str(item))
                            #print(temp)
                            handle.write(context.crypt.encryptStringENC(temp)+"\n")
                context = identification(login, password, context)
                if not context:
                    fails += 1
                    print colored("Password or login isn't valid", 'red')
                    if fails == 3:
                        time.sleep(5)
                        raise SystemExit("Third identification is failed")
                else:
                    context.user.authorization(login, password)
                    if context.type == 'admin':
                        admin(context)
                    elif context.type == 'common':
                        user(context)
            if case(3):
                with open('base.txt', 'w') as handle:
                    user_list = view_user_list()
                    for item in user_list:
                            item = list(item)
                            temp = "".join(str(item))
                            #print(temp)
                            handle.write(context.crypt.encryptStringENC(temp)+"\n")
                raise SystemExit
            if case(2):
                print colored("Варіант 6.Зацепін Олексій ФБ-31", 'blue')
                print colored("     Наявність латинських букв, символів кирилиці і цифр.", 'blue')
            print colored("Please retype number", 'red')
            break
예제 #5
0
 def run(self, ch):
     for c in switch(ch):
         if c(ord('0'), ord('9')):
             self.refresh("Input new Label for '"+chr(ch)+"'")
             l = self.stdscr.getstr()
             self.label[ch-ord('0')] = l
         if c(ord('q')):
             return False
     self.refresh("Press 0~9 for editing corresponding label")
     return True
예제 #6
0
 def run(self, ch):
     for case in switch(ch):
         if case(ord('q')) or case(ord(' ')):
             return False
         if case(ord('0'), ord('9')):
             self.toggle_label(self.article_list_viewer.label_set.get_label(int(chr(ch))))
             self.update_article()
         if case():
             b = self.article_list_viewer.run(ch)
             self.update_article()
             return True
     return True
예제 #7
0
    def dispatchMessage(self, message):

        for case in switch(message['type']):
            if case(20):
                # Check user credentials
                authorized = False
                if message['username'] == 'test1' and message['password'] == 'pass123':
                    authorized = True

                reply = LoginMessage()
                reply['username'] = message['username']
                reply['authorization'] = authorized
                self._clientSend(self.user.handler, reply)

                if not authorized:
                    # Bye Bye
                    self.transport.loseConnection()
예제 #8
0
    def run(self):

        self.send_cap_request()
        self.connection.settimeout(2)

        while True:
            messages = self.read()

            for tmp_msg in messages:
                debug.Debug.log(tmp_msg, received=True)
                message = TwitchIrcConnection.Event(tmp_msg)

                for case in switch(message.type.lower()):

                    if case('connection'):
                        if self.on_connection is not None:
                            self.on_connection(message)

                    elif case('ping'):
                        if self.on_ping is not None:
                            self.on_ping(message)

                    elif case('privmsg'):
                        if self.privmsg is not None:
                            self.on_ping(message)

                    elif case('join'):
                        if self.on_join_chan is not None:
                            self.on_join_chan(message)

                    elif case('part'):
                        if self.on_part_chan is not None:
                            self.on_part_chan(message)

                    elif case('mode'):
                        if message.op[0] == '+':
                            if self.on_usr_mod is not None:
                                self.on_usr_mod(message)


                        if message.op[0] == '-':
                            if self.on_usr_demod is not None:
                                self.on_usr_demod(message)
                    else:
                        print('UNHANDLED EVENT:' + message.type)
def user(context):
    global i
    while True:
        print "User session, other functions are permitted"
        print "1.Change password"
        print "2.Exit"
        try:
            i = input('Enter number:')
        except SyntaxError:
            print "Please retype number"
        while switch(i):
            if case(1):
                context.user.change_own_password()
                break
            if case(2):
                raise SystemExit
            print "Please retype number"
            break
예제 #10
0
    def dispatchMessage(self, message):

        for case in switch(message['type']):
            if case(20):
                # Check user credentials
                authorized = False
                if message['username'] == 'test1' and message[
                        'password'] == 'pass123':
                    authorized = True

                reply = LoginMessage()
                reply['username'] = message['username']
                reply['authorization'] = authorized
                self._clientSend(self.user.handler, reply)

                if not authorized:
                    # Bye Bye
                    self.transport.loseConnection()
def user(context):
    global i
    while True:
        print "User session, other functions are permitted"
        print "1.Change password"
        print "2.Exit"
        try:
            i = raw_input('Enter number:')
        except SyntaxError:
            print "Please retype number"
        while switch(i):
            if case(1):
                context.user.change_own_password()
                break
            if case(2):
                raise SystemExit
            print "Please retype number"
            break
예제 #12
0
    def run(self):

        self.send_cap_request()
        self.connection.settimeout(2)

        while True:
            messages = self.read()

            for tmp_msg in messages:
                debug.Debug.log(tmp_msg, received=True)
                message = TwitchIrcConnection.Event(tmp_msg)

                for case in switch(message.type.lower()):

                    if case('connection'):
                        if self.on_connection is not None:
                            self.on_connection(message)

                    elif case('ping'):
                        if self.on_ping is not None:
                            self.on_ping(message)

                    elif case('privmsg'):
                        if self.privmsg is not None:
                            self.on_ping(message)

                    elif case('join'):
                        if self.on_join_chan is not None:
                            self.on_join_chan(message)

                    elif case('part'):
                        if self.on_part_chan is not None:
                            self.on_part_chan(message)

                    elif case('mode'):
                        if message.op[0] == '+':
                            if self.on_usr_mod is not None:
                                self.on_usr_mod(message)

                        if message.op[0] == '-':
                            if self.on_usr_demod is not None:
                                self.on_usr_demod(message)
                    else:
                        print('UNHANDLED EVENT:' + message.type)
예제 #13
0
def decodeMessage(data):
    log.msg(repr(data))

    message = json.loads(data.strip())
    log.msg(message)
    received = None
    for case in switch(message['type']):
        if case(1):
            log.msg('Ping')
            received = Ping()
            break
        if case(2):
            log.msg('Pong')
            received = Pong()
            break
        if case(20):
            log.msg('Login')
            received = LoginMessage()
            break
    received.decode(data)
    return received
예제 #14
0
def decodeMessage(data):
    log.msg(repr(data))

    message = json.loads(data.strip())
    log.msg(message)
    received = None
    for case in switch(message['type']):
        if case(1):
            log.msg('Ping')
            received = Ping()
            break
        if case(2):
            log.msg('Pong')
            received = Pong()
            break
        if case(20):
            log.msg('Login')
            received = LoginMessage()
            break
    received.decode(data)
    return received
예제 #15
0
    def set_handler(self, handler, function):

        for case in switch(handler.lower()):
            if case('PRIVMSG'):
                self.on_chan_msg = function

            elif case('JOIN'):
                self.on_join_chan = function

            elif case('LEAVE'):
                self.on_part_chan = function

            elif case('USRJOIN'):
                self.on_usr_join_chan = function

            elif case('USRPART'):
                self.on_usr_part_chan = function

            elif case('USRMOD'):
                self.on_usr_mod = function

            elif case('USRDEMOD'):
                self.on_usr_demod = function
예제 #16
0
    def set_handler(self, handler, function):

        for case in switch(handler.lower()):
            if case('PRIVMSG'):
                self.on_chan_msg = function

            elif case('JOIN'):
                self.on_join_chan = function

            elif case('LEAVE'):
                self.on_part_chan = function

            elif case('USRJOIN'):
                self.on_usr_join_chan = function

            elif case('USRPART'):
                self.on_usr_part_chan = function

            elif case('USRMOD'):
                self.on_usr_mod = function

            elif case('USRDEMOD'):
                self.on_usr_demod = function
예제 #17
0
def read_record(file_, num_evo_entries):
    """ Read a Mathematica protein record from file and convert into dict. """

    dict_ = {}

    while True:
        next_line = file_.readline()
        for case in switch(next_line):
            if case('[ID]' + '\n'):
                id_ = file_.readline()[:-1]
                dict_.update({'id': id_})
            elif case('[PRIMARY]' + '\n'):
                primary = letter_to_num(file_.readline()[:-1], _aa_dict)
                dict_.update({'primary': primary})
            elif case('[EVOLUTIONARY]' + '\n'):
                evolutionary = []
                for residue in range(num_evo_entries):
                    evolutionary.append(
                        [float(step) for step in file_.readline().split()])
                dict_.update({'evolutionary': evolutionary})
            elif case('[SECONDARY]' + '\n'):
                secondary = letter_to_num(file_.readline()[:-1], _dssp_dict)
                dict_.update({'secondary': secondary})
            elif case('[TERTIARY]' + '\n'):
                tertiary = []
                for axis in range(NUM_DIMENSIONS):
                    tertiary.append(
                        [float(coord) for coord in file_.readline().split()])
                dict_.update({'tertiary': tertiary})
            elif case('[MASK]' + '\n'):
                mask = letter_to_num(file_.readline()[:-1], _mask_dict)
                dict_.update({'mask': mask})
            elif case('\n'):
                return dict_
            elif case(''):
                return None
    def forward(self, scores, target, mask):
        """
        args:
            scores (seq_len, bat_size, target_size_from, target_size_to) : crf scores
            target (seq_len, bat_size, 1) : golden state
            mask (size seq_len, bat_size) : mask for padding
        return:
            loss
        """
        # print(scores)
        # print(target)
        # print(mask)

        # calculate batch size and seq len
        seq_len = scores.size(0)
        bat_size = scores.size(1)

        # calculate sentence score
        tg_energy = torch.gather(scores.view(seq_len, bat_size, -1), 2,
                                 target).view(seq_len,
                                              bat_size)  # seq_len * bat_size
        tg_energy = tg_energy.masked_select(mask).sum()

        # calculate forward partition score

        # build iter
        seq_iter = enumerate(scores)
        # the first score should start with <start>
        _, inivalues = seq_iter.__next__(
        )  # bat_size * from_target_size * to_target_size
        # only need start from start_tag
        partition = inivalues[:,
                              self.start_tag, :]  # bat_size * to_target_size
        # iter over last scores
        for idx, cur_values in seq_iter:
            # previous to_target is current from_target
            # partition: previous results log(exp(from_target)), #(batch_size * from_target)
            # cur_values: bat_size * from_target * to_target
            cur_values = cur_values + partition.contiguous().view(
                bat_size, self.tagset_size, 1).expand(
                    bat_size, self.tagset_size, self.tagset_size)
            cur_partition = utils.log_sum_exp(cur_values, self.tagset_size)
            # (bat_size * from_target * to_target) -> (bat_size * to_target)

            partition = utils.switch(
                partition, cur_partition,
                mask[idx].view(bat_size,
                               1).expand(bat_size,
                                         self.tagset_size)).view(bat_size, -1)
            # partition = utils.switch(partition, cur_partition,
            #                          mask[idx].contiguous().view(bat_size, 1).expand(bat_size, self.tagset_size)).contiguous().view(bat_size, -1)
            # the following two may achieve higher speed, but raise run-time error
            # new_partition = partition.clone()
            # new_partition.masked_scatter_(mask[idx].view(-1, 1).expand(bat_size, self.tagset_size), cur_partition)  #0 for partition, 1 for cur_partition
            # partition = new_partition

        #only need end at end_tag
        partition = partition[:, self.end_tag].sum()
        # average = mask.sum()

        # average_batch
        if self.average_batch:
            loss = (partition - tg_energy) / bat_size
        else:
            loss = (partition - tg_energy)

        return loss
예제 #19
0
def certificate_chains():
    while True:     
        choice = utils.menu()
        utils.switch(choice)
def admin(context):
    global i
    while True:
        print colored("Admin session", 'yellow')
        print "1.Change own password"
        print "2.Print users list"
        print "3.Create new user with blank password"
        print "4.Block user"
        print "5.Unblock user"
        print "6.Write user list"
        print "7.Exit"
        try:
            i = raw_input('Enter number:')
        except SyntaxError:
            print "Please retype number"
        while switch(i):
            if case(1):
                context.user.change_own_password()
                break
            if case(2):
                user_list = view_user_list()
                #print colored('id login', 'blue')
                #for id, login in user_list:
                #    print colored(str(id) + ' ' + login, 'green')
                break
            if case(3):
                try:
                    new_user_login = raw_input("Enter new users login:"******"Reminder : string have format 'string'", 'red')
                    break
                new_user = User(new_user_login, ' ')
                new_user.create()
                print "Successful creation %s" % new_user
                break
            if case(4):
                try:
                    id = raw_input("Enter user_id:")
                except:
                    print colored("Reminder : string have format 'string'", 'red')
                    break
                context.user.user_blocker(id, 'block')
                break
            if case(5):
                try:
                    id = raw_input("Enter user_id:")
                except:
                    print colored("Reminder : string have format 'string'", 'red')
                    break
                context.user.user_blocker(id, 'unblock')
                break
            if case(6):
                with open('logs.csv', 'wb') as csvfile:
                    writer = csv.writer(csvfile)
                    user_list = view_user_list()
                    crypto_list = list()
                    for item in user_list:
                        item = list(item)
                        temp = "".join(str(item))
                        crypto_list.append(context.crypt.encryptStringENC(temp))
                    writer.writerows(crypto_list)
                break
            if case(7):
                with open('base.txt', 'w') as handle:
                    user_list = view_user_list()
                    for item in user_list:
                            item = list(item)
                            temp = "".join(str(item))
                            #print(temp)
                            handle.write(context.crypt.encryptStringENC(temp)+"\n")
                raise SystemExit
            print "Please retype number"
            break
예제 #21
0
        def __init__(self, raw_text):
            text = str(raw_text)

            self.raw_msg    = text
            self.tag_data   = None
            self.type       = None
            self.chan       = None
            self.usr        = None
            self.msg        = None
            self.cmd        = None
            self.args       = None
            self.op         = None
            #if it's a ping then
            if 'PING' == text[0:4]:
                self.type = 'ping'
                return

            tag_data = {}
            message_data = None

            if (text.find(';') is not -1) and text.find(';') < text.find(':'):
                tmp_data, message_data = text.split(':', 1)
                tmp_data = tmp_data.split(';')

                for tmp in tmp_data:
                    str_split = tmp.split('=')
                    tag_data[str_split[0]] = str_split[1]
            else:
                message_data = text.split(':', 1)
                message_data.pop(0)
                message_data = message_data[0]

            if tag_data != {}:
                self.tag_data = tag_data

            meta_data = None
            message = None

            if message_data.find(':') is -1:
                meta_data = message_data.split(' ')
            else:
                tmp_data = message_data.split(':', 1)
                meta_data = tmp_data[0].split(' ')
                message = tmp_data[1]


            self.type = meta_data[1].lower()

            for case in switch(self.type.lower()):

                if case('join'):
                    self.usr = meta_data[0].split('!')[0]
                    self.chan = meta_data[2].replace('#', '')

                elif case('part'):
                    self.usr = meta_data[0].split('!')[0]
                    self.chan = meta_data[2].replace('#', '')

                elif case('privmsg'):
                    self.usr = meta_data[0].split('!')[0]
                    self.chan = meta_data[2].replace('#', '')
                    self.msg = message

                elif case('userstate'):
                    pass

                elif case('roomstate'):
                    pass

                elif case('cap'):
                    pass

                elif case('mode'):
                    self.chan = meta_data[2].replace('#', '')
                    self.op   = meta_data[3]
                    self.usr  = meta_data[4]
                    pass

                elif case('notice'):
                    self.chan = meta_data[2].replace('#', '')
                    pass

                elif case('376'):
                    self.type = 'connection'

                elif case('421'):
                    self.type = 'invalid'
                    pass
예제 #22
0
    def _forward_alg(self, feats, target, mask, lengths):
        seq_length = feats.size(0)
        batch_size = feats.size(1)
        # return 0.001*torch.mm(self.transitions, Variable(torch.randn(self.tagset_size, self.tagset_size)).cuda(0)).sum()


        # scores: (seq_len, batch, to_tagsize, from_tagsize) 下一个step加上的score
        scores = self.compute_scores(feats, lengths)


        
        start_tag = Variable(torch.LongTensor(1, batch_size).fill_(self.tag_to_ix[START_TAG]))
        end_tag = Variable(torch.LongTensor(1, batch_size).fill_(self.tag_to_ix[STOP_TAG]))
        if self.config['USE_CUDA']:
            start_tag = start_tag.cuda(feats.get_device())
            end_tag = end_tag.cuda(feats.get_device())

        from_tag = torch.cat([start_tag, target], 0)
        # to_tag: (seq_len+1, batch)
        to_tag = torch.cat([target, end_tag], 0)
        # scores_add_an_end: (seq_len+1, batch, to_tagsize, from_tagsize)
        scores_add_an_end = torch.cat([scores, self.transitions.view(1, 1, self.target_size, self.target_size)
                                      .expand(1, batch_size, self.target_size, self.target_size)], 0)
        # from_tag: (seq_len+1, batch, to_tagsize, 1)
        from_tag = from_tag.view(seq_length+1, batch_size, 1, 1)\
            .expand(seq_length + 1, batch_size, self.target_size, 1)
        # from_score: (seq_len+1, batch, to_tagsize)
        from_score = torch.gather(scores_add_an_end, -1, from_tag).squeeze(-1)
        # to_tag: (seq_len+1, batch, 1)
        to_tag = to_tag.unsqueeze(-1)
        # sen_scores: (seq_len+1, batch)
        sen_scores = torch.gather(from_score, -1, to_tag).squeeze(-1)
        # mask_add_an_end: (seq_len+1, bat_size)
        one_mask = Variable(torch.ByteTensor(1, batch_size).fill_(1))
        if self.config['USE_CUDA']:
            one_mask = one_mask.cuda(feats.get_device())
        mask_add_an_end = torch.cat([one_mask, mask], 0)
        masked_sen_scores = sen_scores.masked_select(mask_add_an_end).sum()


        # Do the forward algorithm to compute the partition function
        init_alphas = torch.Tensor(1, self.target_size).fill_(VERY_NEG_NUMBER)
        # START_TAG has all of the score.
        init_alphas[0][self.tag_to_ix[START_TAG]] = 0.

        # Wrap in a variable so that we will get automatic backprop
        forward_var = Variable(init_alphas)
        if self.config['USE_CUDA']:
            forward_var = forward_var.cuda(feats.get_device())
        forward_var = forward_var.expand(batch_size, self.target_size)  # (batch, from_target)
        for idx in range(scores.size(0)):
            cur_values = scores[idx]
            # brod_forward_var: (batch, to_target, from_target)
            brod_forward_var = forward_var.unsqueeze(1).expand(batch_size, self.target_size, self.target_size)
            next_step_var = brod_forward_var + cur_values  # (batch_size, to_target, from_target)
            next_step_var = log_sum_exp(next_step_var)  # (batch, to_target)
            # (batch, to_target) 下一个循环变成from_target
            forward_var = utils.switch(forward_var.contiguous(), next_step_var.contiguous(),
                                       mask[idx].view(batch_size, 1).expand(batch_size, self.target_size)).view(batch_size, -1)
        # (B, from_target)
        terminal_var = forward_var + self.transitions[self.tag_to_ix[STOP_TAG]].unsqueeze(0).expand_as(forward_var)
        # terminal_var = util.switch(forward_var.contiguous(), terminal_var.contiguous(),
        #                           mask[idx].view(batch_size, 1).expand(batch_size, self.tagset_size)).view(batch_size,
        #                                                                                                    -1)

        alpha = log_sum_exp(terminal_var)  # (B, )
        all = alpha.sum()
        loss = (all - masked_sen_scores) / batch_size
        return loss
def admin(context):
    global i
    while True:
        print colored("Admin session", 'yellow')
        print "1.Change own password"
        print "2.Print users list"
        print "3.Create new user with blank password"
        print "4.Block user"
        print "5.Unblock user"
        print "6.Write user list in csv"
        print "7.Exit"
        try:
            i = input('Enter number:')
        except SyntaxError:
            print "Please retype number"
        while switch(i):
            if case(1):
                context.user.change_own_password()
                break
            if case(2):
                view_user_list()
                break
            if case(3):
                try:
                    new_user_login = input("Enter new users login:"******"Reminder : string have format 'string'",
                                  'red')
                    break
                except UnboundLocalError:
                    print colored("Reminder : string have format 'string'",
                                  'red')
                    break
                except NameError:
                    print colored("Reminder : string have format 'string'",
                                  'red')
                    break
                new_user = User(new_user_login, ' ')
                new_user.create()
                print "Successful creation %s" % new_user
                break
            if case(4):
                try:
                    id = input("Enter user_id:")
                except SyntaxError:
                    print colored("Reminder : string have format 'string'",
                                  'red')
                    break
                except UnboundLocalError:
                    print colored("Reminder : string have format 'string'",
                                  'red')
                    break
                except NameError:
                    print colored("Reminder : string have format 'string'",
                                  'red')
                    break
                context.user.user_blocker(id, 'block')
                break
            if case(5):
                try:
                    id = input("Enter user_id:")
                except SyntaxError:
                    print colored("Reminder : string have format 'string'",
                                  'red')
                    break
                except UnboundLocalError:
                    print colored("Reminder : string have format 'string'",
                                  'red')
                    break
                except NameError:
                    print colored("Reminder : string have format 'string'",
                                  'red')
                    break
                context.user.user_blocker(id, 'unblock')
                break
            if case(6):
                with open('logs.csv', 'wb') as csvfile:
                    writer = csv.writer(csvfile,
                                        dialect='excel',
                                        quotechar='"',
                                        quoting=csv.QUOTE_ALL)
                    user_list = view_user_list()
                    writer.writerows(user_list)
                break
            if case(7):
                raise SystemExit
            print "Please retype number"
            break
예제 #24
0
 def getType(data):
     for case in switch(data):
         if case(Debug.INFO):
             return 'INFO'
         elif case(Debug.ERROR):
             return 'ERROR'
예제 #25
0
trainx = np.array(trainx)
trainy = np.array(trainy)
trainx = trainx.reshape(-1, lstmnum, 100, 128, 3)
trainx = trainx.astype('float32')
testx = np.array(testx)
testx = testx.reshape(-1, lstmnum, 100, 128, 3)
testx = testx.astype('float32')
testy = np.array(testy)
#pdb.set_trace()
print(len(trainx))
print(len(testx))
print(podata, negdata)

modelname = sys.argv[3]
pdb.set_trace()
for case in switch(modelname):
    if case('m0'):
        model = createmodel.create_m0()
        break
    if case('m1'):
        model = createmodel.create_m1()
        break
    if case('m2'):
        model = createmodel.create_m2()
        break
    if case('m3'):
        model = createmodel.create_m3()
        break
    if case('m4'):
        model = createmodel.create_m4()
        break
예제 #26
0
        def __init__(self, raw_text):
            text = str(raw_text)

            self.raw_msg = text
            self.tag_data = None
            self.type = None
            self.chan = None
            self.usr = None
            self.msg = None
            self.cmd = None
            self.args = None
            self.op = None
            #if it's a ping then
            if 'PING' == text[0:4]:
                self.type = 'ping'
                return

            tag_data = {}
            message_data = None

            if (text.find(';') is not -1) and text.find(';') < text.find(':'):
                tmp_data, message_data = text.split(':', 1)
                tmp_data = tmp_data.split(';')

                for tmp in tmp_data:
                    str_split = tmp.split('=')
                    tag_data[str_split[0]] = str_split[1]
            else:
                message_data = text.split(':', 1)
                message_data.pop(0)
                message_data = message_data[0]

            if tag_data != {}:
                self.tag_data = tag_data

            meta_data = None
            message = None

            if message_data.find(':') is -1:
                meta_data = message_data.split(' ')
            else:
                tmp_data = message_data.split(':', 1)
                meta_data = tmp_data[0].split(' ')
                message = tmp_data[1]

            self.type = meta_data[1].lower()

            for case in switch(self.type.lower()):

                if case('join'):
                    self.usr = meta_data[0].split('!')[0]
                    self.chan = meta_data[2].replace('#', '')

                elif case('part'):
                    self.usr = meta_data[0].split('!')[0]
                    self.chan = meta_data[2].replace('#', '')

                elif case('privmsg'):
                    self.usr = meta_data[0].split('!')[0]
                    self.chan = meta_data[2].replace('#', '')
                    self.msg = message

                elif case('userstate'):
                    pass

                elif case('roomstate'):
                    pass

                elif case('cap'):
                    pass

                elif case('mode'):
                    self.chan = meta_data[2].replace('#', '')
                    self.op = meta_data[3]
                    self.usr = meta_data[4]
                    pass

                elif case('notice'):
                    self.chan = meta_data[2].replace('#', '')
                    pass

                elif case('376'):
                    self.type = 'connection'

                elif case('421'):
                    self.type = 'invalid'
                    pass
예제 #27
0
def admin(context):
    global i
    while True:
        print colored("Admin session", 'yellow')
        print "1.Change own password"
        print "2.Print users list"
        print "3.Create new user with blank password"
        print "4.Block user"
        print "5.Unblock user"
        print "6.Write user list"
        print "7.Exit"
        try:
            i = raw_input('Enter number:')
        except SyntaxError:
            print "Please retype number"
        while switch(i):
            if case(1):
                context.user.change_own_password()
                break
            if case(2):
                user_list = view_user_list()
                #print colored('id login', 'blue')
                #for id, login in user_list:
                #    print colored(str(id) + ' ' + login, 'green')
                break
            if case(3):
                try:
                    new_user_login = raw_input("Enter new users login:"******"Reminder : string have format 'string'",
                                  'red')
                    break
                new_user = User(new_user_login, ' ')
                new_user.create()
                print "Successful creation %s" % new_user
                break
            if case(4):
                try:
                    id = raw_input("Enter user_id:")
                except:
                    print colored("Reminder : string have format 'string'",
                                  'red')
                    break
                context.user.user_blocker(id, 'block')
                break
            if case(5):
                try:
                    id = raw_input("Enter user_id:")
                except:
                    print colored("Reminder : string have format 'string'",
                                  'red')
                    break
                context.user.user_blocker(id, 'unblock')
                break
            if case(6):
                with open('logs.csv', 'wb') as csvfile:
                    writer = csv.writer(csvfile)
                    user_list = view_user_list()
                    crypto_list = list()
                    for item in user_list:
                        item = list(item)
                        temp = "".join(str(item))
                        crypto_list.append(
                            context.crypt.encryptStringENC(temp))
                    writer.writerows(crypto_list)
                break
            if case(7):
                with open('base.txt', 'w') as handle:
                    user_list = view_user_list()
                    for item in user_list:
                        item = list(item)
                        temp = "".join(str(item))
                        #print(temp)
                        handle.write(
                            context.crypt.encryptStringENC(temp) + "\n")
                raise SystemExit
            print "Please retype number"
            break
예제 #28
0
 def getType(data):
     for case in switch(data):
         if case(Debug.INFO):
             return 'INFO'
         elif case(Debug.ERROR):
             return 'ERROR'
예제 #29
0
def main():
    global i, fails
    fails = 0
    while True:
        print "1.Authorization"
        print "2.Help"
        print "3.Exit"
        try:
            i = raw_input('Enter number:')
        except SyntaxError:
            print colored("Please enter valid number", 'red')
        while switch(i):
            if case(1):
                try:
                    login = str(raw_input("Enter login:"******"Enter password:"******"Reminder : string have format 'string'",
                                  'red')
                    if fails == 3:
                        time.sleep(5)
                        raise SystemExit("Third identification is failed")
                context = Context(login)
                with open('base.txt', 'w') as handle:
                    user_list = view_user_list()
                    for item in user_list:
                        item = list(item)
                        temp = "".join(str(item))
                        #print(temp)
                        handle.write(
                            context.crypt.encryptStringENC(temp) + "\n")
                context = identification(login, password, context)
                if not context:
                    fails += 1
                    print colored("Password or login isn't valid", 'red')
                    if fails == 3:
                        time.sleep(5)
                        raise SystemExit("Third identification is failed")
                else:
                    context.user.authorization(login, password)
                    if context.type == 'admin':
                        admin(context)
                    elif context.type == 'common':
                        user(context)
            if case(3):
                with open('base.txt', 'w') as handle:
                    user_list = view_user_list()
                    for item in user_list:
                        item = list(item)
                        temp = "".join(str(item))
                        #print(temp)
                        handle.write(
                            context.crypt.encryptStringENC(temp) + "\n")
                raise SystemExit
            if case(2):
                print colored("Варіант 6.Зацепін Олексій ФБ-31", 'blue')
                print colored(
                    "     Наявність латинських букв, символів кирилиці і цифр.",
                    'blue')
            print colored("Please retype number", 'red')
            break