Ejemplo n.º 1
0
    def test_init(self):
        # new blank instance
        new_blank = Forward()
        self.assertEquals(new_blank.targets, [])
        self.assertEquals(new_blank.instances, {})
        self.assertTrue(isinstance(new_blank, Forward))

        # new success instance
        new_success = Forward(targets=[[
            '192.168.1.1', 'vlb', 'admin', 'admin_pw', {
                'port': 22,
                'timeout': 30
            }
        ], ['192.168.1.1', 'vlb', 'admin', 'admin_pw']])
        self.assertEquals(new_success.targets, [[
            '192.168.1.1', 'vlb', 'admin', 'admin_pw', {
                'port': 22,
                'timeout': 30
            }
        ], ['192.168.1.1', 'vlb', 'admin', 'admin_pw']])
        self.assertTrue(isinstance(new_success, Forward))

        # new fail instance
        with self.assertRaises(ForwardError):
            new_fail = Forward(targets=[['192.168.1.1', 'vlb', 'admin', 234]])
def main():

    player_manager = PlayerManager("Los Angeles Lakers", "file.txt")
    player1 = Forward(23, "Lebron", "James", 201, 81, 2003, "forward", 1028,
                      690)
    player2 = Center(12, "Dwight", "Howard", 210, 90, 2002, "center", 1054,
                     "Aggresive")
    player3 = Guard(10, "Rajon", "Rondo", 190, 76, 2004, "guard", 909, 1203)

    player_manager.add_player(player1)
    player_manager.add_player(player2)
    player_manager.add_player(player3)

    print_report(player_manager)

    player_manager.delete_player(12)
    player_manager.delete_player(10)

    print_report(player_manager)

    player1 = Forward(23, "Yeet", "James", 69, 81, 2003, "forward", 1028, 690)
    player_manager.update_player(player1)

    print_report(player_manager)

    print(player_manager.get_player(23))
def add_player():
    """ Adds a player to the player manager """
    content = request.json

    try:
        if content["player_type"] == "center":
            center = Center(content["player_id"], content["first_name"],
                            content["last_name"], content["height"],
                            content["weight"], content["year_drafted"],
                            content["player_type"], content["num_rebounds"],
                            content["play_type"])
            player_manager.add_player(center)
        elif content["player_type"] == "forward":
            forward = Forward(content["player_id"], content["first_name"],
                              content["last_name"], content["height"],
                              content["weight"], content["year_drafted"],
                              content["player_type"],
                              content["num_shots_took"],
                              content["num_shots_made"])
            player_manager.add_player(forward)
        elif content["player_type"] == "guard":
            guard = Guard(content["player_id"], content["first_name"],
                          content["last_name"], content["height"],
                          content["weight"], content["year_drafted"],
                          content["player_type"], content["num_steals"],
                          content["num_assists"])
            player_manager.add_player(guard)

        response = app.response_class(status=200, )

    except ValueError as e:
        response = app.response_class(response=str(e), status=400)

    return response
Ejemplo n.º 4
0
    def test_get_instances(self):
        new_blank = Forward()
        new_blank.addTargets(['192.168.113.123'],
                             'bclinux7',
                             'north_king',
                             'wolf_spirit',
                             timeout=40,
                             port=25)
        new_blank.addTargets(['192.168.113.124-192.168.113.126'], 'vlb',
                             'south_king', 'fish_spirit')
        instances = new_blank.getInstances(preLogin=False)
        node123 = instances['192.168.113.123']
        node124 = instances['192.168.113.124']
        node125 = instances['192.168.113.125']
        node126 = instances['192.168.113.126']

        self.assertTrue(
            isinstance(
                node123,
                getattr(
                    importlib.import_module('forward.devclass.%s' %
                                            'bclinux7'), 'BCLINUX7')))
        self.assertTrue(
            isinstance(
                node125,
                getattr(importlib.import_module('forward.devclass.%s' % 'vlb'),
                        'VLB')))
Ejemplo n.º 5
0
 def estimate(self, x, T):
     self.__init_storage(T)
     for t in range(T):
         fw, bw = Forward(self.A, self.B,
                          self.rho), Backward(self.A, self.B, self.rho)
         P, _ = fw.evaluate(x), bw.evaluate(x)
         self.__update(fw.alpha, bw.beta, x)
         self.__store(np.log(P), t)
Ejemplo n.º 6
0
 def scaled_estimate(self, x, T):
     self.__init_storage(T)
     for t in range(T):
         fw, bw = Forward(self.A, self.B,
                          self.rho), Backward(self.A, self.B, self.rho)
         P, _ = fw.scaled_evaluate(x), bw.scaled_evaluate(x, fw.C)
         self.__scaled_update(fw.alpha, bw.beta, fw.C, x)
         self.__store(np.log(fw.C).sum(), t)
def main(_):
    graph = tf.Graph()
    model_params = ModelParams()
    model_params.update()
    with graph.as_default():
        model = Forward(model_params)
    with tf.Session(graph=graph, config=config) as sess:
        train(sess, model)
Ejemplo n.º 8
0
 def setUp(self):
     """ Sets up data and calls logPoint """
     self.logPoint()
     self.player_manager = PlayerManager("Los Angeles Lakers", "file.txt")
     self.player1 = Forward(1, "Lebron", "James", 201, 81, 2003, "forward",
                            1028, 690)
     self.player_manager.add_player(self.player1)
     self.assertIsNotNone(self.player_manager)
Ejemplo n.º 9
0
def main():
    para_cfg_obj = ParaCfg('../config/appConfig.cfg')

    logger_obj = Logger(para_cfg_obj.LOGFILE_PATH)
    track_logger = logger_obj.get_logger()

    para_cfg_obj.to_log(track_logger)

    forward_obj = Forward(track_logger, para_cfg_obj)
    forward_obj.run()
Ejemplo n.º 10
0
    def setUp(self):
        """ Sets up data and calls logPoint """
        self.logPoint()

        self.player_manager = PlayerManager("Los Angeles Lakers")
        self.player1 = Forward(1, "Lebron", "James", 201, 81, 2003, 1028, 690)
        self.player2 = Center(2, "Dwight", "Howard", 210, 90, 2002, 1054,
                              "Aggresive")
        self.player3 = Guard(3, "Rajon", "Rondo", 190, 76, 2004, 909, 1203)
        self.player_manager.add_player(self.player1)
        self.player_manager.add_player(self.player2)
        self.player_manager.add_player(self.player3)
        self.assertIsNotNone(self.player_manager)
Ejemplo n.º 11
0
 def on_accept(self):
     forward = Forward().start(self.fwd[0], self.fwd[1])
     clientsock, clientaddr = self.pserver.accept()
     if forward:
         print clientaddr, "has connected"
         self.input_list.append(clientsock)
         self.input_list.append(forward)
         self.channel[clientsock] = forward
         self.channel[forward] = clientsock
     else:
         print "Can't establish connection with remote server.",
         print "Closing connection with client side", clientaddr
         clientsock.close()
Ejemplo n.º 12
0
 def _read_players_from_file(self):
     """ Reads players from file """
     with open(self._filepath, 'r') as input_file:
         players = json.load(input_file)
         for json_data in players:
             type = json_data["player_type"]
             if type == "center":
                 player_id = json_data["player_id"]
                 first_name = json_data["first_name"]
                 last_name = json_data["last_name"]
                 height = json_data["height"]
                 weight = json_data["weight"]
                 year_drafted = json_data["year_drafted"]
                 player_type = json_data["player_type"]
                 num_rebounds = json_data["num_rebounds"]
                 play_type = json_data["play_type"]
                 player = Center(player_id, first_name, last_name, height,
                                 weight, year_drafted, player_type,
                                 num_rebounds, play_type)
             elif type == "forward":
                 player_id = json_data["player_id"]
                 first_name = json_data["first_name"]
                 last_name = json_data["last_name"]
                 height = json_data["height"]
                 weight = json_data["weight"]
                 year_drafted = json_data["year_drafted"]
                 player_type = json_data["player_type"]
                 num_shots_took = json_data["num_shots_took"]
                 num_shots_made = json_data["num_shots_made"]
                 player = Forward(player_id, first_name, last_name, height,
                                  weight, year_drafted, player_type,
                                  num_shots_took, num_shots_made)
             elif type == "guard":
                 player_id = json_data["player_id"]
                 first_name = json_data["first_name"]
                 last_name = json_data["last_name"]
                 height = json_data["height"]
                 weight = json_data["weight"]
                 year_drafted = json_data["year_drafted"]
                 player_type = json_data["player_type"]
                 num_steals = json_data["num_steals"]
                 num_assists = json_data["num_assists"]
                 player = Guard(player_id, first_name, last_name, height,
                                weight, year_drafted, player_type,
                                num_steals, num_assists)
             self._players.append(player)
         return self._players
def compute_initial_embedding(db, dim, batch_size, epochs):
    samples = get_samples(db, args.num_samples, partition=0)

    row_idx = {
        r: i
        for i, (_, r,
                _) in enumerate(db.iter_rows(db.predict_rel, partition=0))
    }
    scheme_idx = {s: i for i, s in enumerate(samples.keys())}
    model = Forward(dim, len(samples), row_idx, scheme_idx)

    loader = preproc_data(samples, model, batch_size)
    train(model, loader, epochs)

    embedding = model.get_embedding()
    embedding = {r: embedding[i] for r, i in row_idx.items()}
    return embedding, model
Ejemplo n.º 14
0
 def test_add_targets(self):
     new_blank = Forward()
     new_blank.addTargets(['192.168.113.123'],
                          'bclinux7',
                          'north_king',
                          'wolf_spirit',
                          timeout=40,
                          port=25)
     new_blank.addTargets(['192.168.113.124-192.168.113.126'], 'vlb',
                          'south_king', 'fish_spirit')
     self.assertEquals(
         new_blank.targets,
         [[
             '192.168.113.123', 'bclinux7', 'north_king', 'wolf_spirit', {
                 'timeout': 40,
                 'port': 25
             }
         ], ['192.168.113.124', 'vlb', 'south_king', 'fish_spirit', {}],
          ['192.168.113.125', 'vlb', 'south_king', 'fish_spirit', {}],
          ['192.168.113.126', 'vlb', 'south_king', 'fish_spirit', {}]])
Ejemplo n.º 15
0
def test(opt):
    # cuDNN auto-tuning.
    if opt.autotune:
        torch.backends.cudnn.benchmark = True

    # Create model.
    net = InferenceNet(opt)
    if opt.chkpt_num > 0:
        net = load_chkpt(net, opt)
    net = net.cuda()
    if not opt.no_eval:
        net.eval()

    # Forward scan.
    fwd = Forward(net, opt)
    for data_name in opt.data_names:
        print(data_name)
        scanner = make_forward_scanner(data_name, opt)
        output = fwd(scanner)
        save_output(data_name, output, opt)
Ejemplo n.º 16
0
    def setUp(self):
        engine = create_engine('sqlite:///test_players.sqlite')

        # Create all the tables
        Base.metadata.create_all(engine)
        Base.metadata.bind = engine
        """ Sets up data and calls logPoint """
        self.logPoint()

        self.player_manager = PlayerManager("test_players.sqlite")
        self.player1 = Forward(1, "Lebron", "James", 201, 81, 2003, "forward",
                               1028, 690)
        self.player2 = Center(2, "Dwight", "Howard", 210, 90, 2002, "guard",
                              1054, "Aggresive")
        self.player3 = Guard(3, "Rajon", "Rondo", 190, 76, 2004, "center", 909,
                             1203)
        self.player_manager.add_player(self.player1)
        self.player_manager.add_player(self.player2)
        self.player_manager.add_player(self.player3)
        self.assertIsNotNone(self.player_manager)
def update_player(player_id):
    """ Updates an existing player"""

    content = request.json
    player = player_manager.get_player(player_id)
    if player == None:
        response = app.response_class(status=404)

    try:
        if content["player_type"] == "center":
            center = Center(content["player_id"], content["first_name"],
                            content["last_name"], content["height"],
                            content["weight"], content["year_drafted"],
                            content["player_type"], content["num_rebounds"],
                            content["play_type"])
            player_manager.update_player(center)
        elif content["player_type"] == "forward":
            forward = Forward(content["player_id"], content["first_name"],
                              content["last_name"], content["height"],
                              content["weight"], content["year_drafted"],
                              content["player_type"],
                              content["num_shots_took"],
                              content["num_shots_made"])
            player_manager.update_player(forward)
        elif content["player_type"] == "guard":
            guard = Guard(content["player_id"], content["first_name"],
                          content["last_name"], content["height"],
                          content["weight"], content["year_drafted"],
                          content["player_type"], content["num_steals"],
                          content["num_assists"])
            player_manager.update_player(guard)

        response = app.response_class(status=200)

    except ValueError as e:
        response = app.response_class(response=str(e), status=404)
    return response
Ejemplo n.º 18
0
            I = cv2.imread(img, 1)
            _, fname = os.path.split(img)
            gt = int(fname.split('_')[4])
            score = self.predictor(I)
            if (score >= 0.5 and gt == 1) or (gt < 0.5 and gt == 0):
                accu += 1
                
        with open(opj(self.perf_dir, 'result.csv'), 'w') as f:
            f.write('{}\n'.format(accu/len(images)))

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('src')
    parser.add_argument("perf_dir")
    parser.add_argument("--model_path")
    parser.add_argument("--model_cfg")
    args = parser.parse_args()

    predictor = Forward(args.model_path, args.model_cfg)
    perf = Perf(predictor, args.src, args.perf_dir, err_save=False)
    perf.proc()








Ejemplo n.º 19
0
import telebot
import logging
from config import TOKEN, CHAT, admins_id
from log import log
from variables import *
from forward import Forward

hidden_forward = Forward(False)
for_ban = []


def initial_bot(use_logging=True, level_name='DEBUG'):
    bot = telebot.TeleBot(TOKEN)
    logger = log('bot', 'bot.log', 'INFO')
    working = {'disable': False}

    @bot.message_handler(commands=['start'])
    def start_handler(message: telebot.types.Message):
        bot.send_message(message.from_user.id, start_mess)
        logger.info(f"It's start handler. Message from {message.from_user.id}")

    @bot.message_handler(commands=['help'])
    def help_handler(message: telebot.types.Message):
        bot.send_message(message.from_user.id, help_mess)
        logger.info(f"It's help handler. Message from {message.from_user.id}")

    @bot.message_handler(commands=['disable'])
    def toggle_handler(message: telebot.types.Message):
        logger.info(
            f"It's disable handler. Message from {message.from_user.id}. Hidden_forward is {hidden_forward}"
        )
from  create_dataset import Create_Xor
from activation import Activation
from forward import Forward
from backward import Backward

myDataset = Create_Xor()

#myDataset.print_shape()
#myDataset.print_XY()

#recuperation X,Y
X =  myDataset.get_X()
Y = myDataset.get_Y()

#creation d'un objet 'annForward'en definissant mes layers
annForward = Forward([2,3,1])

#start loop iterations

learning_rate = 0.0075
num_iterations = 2
np.random.seed(1)
#track the cost
costs = []
print_cost = True
#boucle de 0 à nombre d'iterations:
    
for i in range (0,num_iterations):
        
    #forward propagation l layers
    annForward.forward_layers(X)
Ejemplo n.º 21
0
        os.makedirs(perf_dir, exist_ok=True)
        self.predictor, self.imgsrc, self.perf_dir = predictor, imgsrc, perf_dir
        self.err_save = err_save

    def proc(self):
        accu = 0
        images = get_spec_files(self.imgsrc, ext=IMG_EXT, oswalk=True)
        for i, img in enumerate(images):
            print('{}/{}'.format(i, len(images)))
            I = cv2.imread(img, 1)
            _, fname = os.path.split(img)
            gt = int(fname.split('_')[4])
            score = self.predictor(I)
            if (score >= 0.5 and gt == 1) or (gt < 0.5 and gt == 0):
                accu += 1

        with open(opj(self.perf_dir, 'result.csv'), 'w') as f:
            f.write('{}\n'.format(accu / len(images)))


if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('src')
    parser.add_argument("perf_dir")
    args = parser.parse_args()

    predictor = Forward()
    perf = Perf(predictor, args.src, args.perf_dir, err_save=False)
    perf.proc()
Ejemplo n.º 22
0
from forward import HMM, Forward
from backward import Backward
from math import log
from logsum import log_sum

f = Forward("dev.txt", "hmm-trans.txt", "hmm-emit.txt", "hmm-prior.txt")
b = Backward("dev.txt", "hmm-trans.txt", "hmm-emit.txt", "hmm-prior.txt")
dev_file = "dev.txt"

with open(dev_file, 'r') as file:
    for line in file:
        words = line.rstrip('\n\r').split(" ")
        dev_a = list()
        dev_b = list()
        # calculate conditional probability
        for i in range(len(words)):
            t = i + 1
            if t == 1:
                f.initialize_alpha(words[0], dev_a)
            else:
                f.calculate_alpha(words[i], t, dev_a)
        T = len(words)
        t = T
        for i in range(len(words)):
            if t == T:
                beta_T = [log(1) for x in range(b.hmm.N)]
                dev_b.append(beta_T)
            else:
                b.calculate_beta(dev_b, words[t], t - 1, T - 1)
            t -= 1