Exemple #1
0
def bisection():
    func = request.form['function']
    xi = float(request.form['xi'])
    xs = float(request.form['xs'])
    iterations = float(request.form['iterations'])
    tolerance = float(request.form['tolerance'])

    methods = Methods(func)
    table = methods.bisection(xi, xs, tolerance, iterations)
    print(list(table))

    if request.form.get('prueba', None):
        return json.dumps(table, default=decimal_default)
    aproximacionesx = []
    aproximacionesy = []
    for row in table[2][1:]:
        aproximacionesx.append(float(row[3]))
        aproximacionesy.append(float(row[4]))
    aproximacionesx.pop(0)
    aproximacionesy.pop(0)
    return render_template('resultsTable.html',
                           results=table[2],
                           func=func.replace("**", "^"),
                           aprox=aproximacionesx,
                           aproy=aproximacionesy)
Exemple #2
0
def multiple():

    func = request.form['function']
    x0 = float(request.form['x0'])
    tolerance = float(request.form['tolerance'])
    iterations = float(request.form['iterations'])

    methods = Methods(func)
    table = methods.multipleRoots(x0, tolerance, iterations)
    if request.form.get('prueba', None):
        return json.dumps(table, default=decimal_default)
    aproximacionesx = []
    aproximacionesy = []
    for row in table[2][1:]:
        aproximacionesx.append(float(row[1]))
        aproximacionesy.append(float(row[2]))
    aproximacionesx.pop(0)
    aproximacionesy.pop(0)
    print(func)
    print(aproximacionesy)
    # print(aproximacionesx)

    if request.form.get('prueba', None):
        return json.dumps(table, default=decimal_default)
    return render_template('resultsTable.html',
                           results=table[2],
                           func=func.replace("**", "^"),
                           aprox=aproximacionesx,
                           aproy=aproximacionesy)
 def test_sortit(self):
     list1 = [5, 1, 2, 3, 3, 3, 1, 4, 5, 5, 6, 4, 4, 7]
     list2 = [5, 3, 1, 1, 1, 8, 8, 8, 9, 7, 3, 1, 1, 1]
     self.assertEqual(Methods.sortit2(list1),
                      [1, 1, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 7])
     self.assertEqual(Methods.sortit2(list2),
                      [1, 1, 1, 1, 1, 1, 3, 3, 5, 7, 8, 8, 8, 9])
    def __init__(self, model_name, config_filename):
        """
            initialization function
        """

        self._config_filename = config_filename

        self._graph = tf.Graph()
        self._model_name = model_name
        self._mode = "train"

        main_config = parser_config(self._config_filename, "main")
        model_config = parser_config(self._config_filename, self._model_name)

        configs = {**main_config, **model_config}

        self._transforms_method = Methods("transform")

        self._transforms_method.register("textcnn", "transform.textcnn")
        self._transforms_method.register("main", "transform.main")

        self._transforms_method.exe(self._model_name, config=configs, config_filename=self._config_filename)
        self._transforms_method.exe("main", config=configs, config_filename=self._config_filename)

        self._config = Config(configs)

        with self._graph.as_default():
            self._input = tf.placeholder(tf.int32, [None, self._config.text_length], name="input")
            self._target = tf.placeholder(tf.float32, [None, 2], name="target")
Exemple #5
0
def run_game():
    # Create a board
    game = Connect4()

    # Initialize the game and create a screen object
    pygame.init()
    screen = pygame.display.set_mode(game.size)
    pygame.display.set_caption("Connect4 Game")
    my_font = pygame.font.SysFont("monospace", 75)

    # Creat methods
    methods = Methods()

    # Print game board
    game.print_board()
    game.draw_board(screen)

    game.turn = 0

    # Start the main loop of the game
    while not game.game_over:
        pygame.display.update()

################################## Connect 4 ###########################################################################
        turn = game.check_event(screen)
        if turn == game.PLAYER:
            col = int(math.floor(game.pos_x / game.SQUARESIZE))
            if game.is_valid_location(col):
                row = game.get_next_open_row(col)
                h = game.ij2h(row, col)
                game.get_move(screen, h, game.PLAYER_PIECE)

        elif turn == game.AI:
            # best_loc, score = methods.mini_max(game, 0, True)
            best_loc, score = methods.alpha_beta_pruning(game, 7, -math.inf, math.inf, True)
            # best_loc, score = methods.monte_carlo(game, 4)
            game.get_move(screen, best_loc, game.AI_PIECE)
            print(best_loc, score)

########################################################################################################################

        if game.game_over:
            if game.winning_move(game.PLAYER_PIECE):
                label = my_font.render("Human wins!!", 1, game.RED)
                screen.blit(label, (120, 50))
                print("Human wins!!")
            elif game.winning_move(game.AI_PIECE):
                label = my_font.render("AI wins!!", 2, game.YELLOW)
                screen.blit(label, (120, 50))
                print("AI wins!!")
            else:
                label = my_font.render("It's a draw!!", 2, game.BLACK)
                screen.blit(label, (120, 50))
                print("It's a draw!!")

            pygame.display.update()
            pygame.time.wait(10000)
Exemple #6
0
def main():
    """ main method used for obtaing a root of a formula """

    x_value = Symbol("x")
    function = x_value**4 - x_value - 10

    mtd = Methods(function, x_value, n_iter=100)
    mtd.bisection_method(1, 2)
    mtd.regula_falsi(1, 2)
    mtd.newton_method(2)
    mtd.secant_method(1, 2)
 def getFromDB(self):
     try:
         conn = sqlite3.connect('combination.db')
         cursor = conn.cursor()
         cursor.execute('SELECT * FROM comb ORDER BY RANDOM() LIMIT 1')
         rows = cursor.fetchall()
         row = rows[0]
         key = row[0]
         text = row[1]
         m = Methods()
         return key, m.dictFromText(text)
     except sqlite3.Error as e:
         raise e
Exemple #8
0
    def getComb(self, key):
        try:
            conn = sqlite3.connect('combination.db')
            cursor = conn.cursor()
            cursor.execute('SELECT * FROM comb WHERE key = ?', (key, ))
            rows = cursor.fetchall()
            row = list(rows[0])
            text_combination = row[1]
            m = Methods()
            combination = m.dictFromText(text_combination)
            return combination

        except Exception as e:
            raise e
 def __init__(self):
     self.methods = Methods()
     self.x_column = 'x'
     self.n_column = 'N'
     self.columns = [
         'Analytical Solution', 'Euler Method', 'Improved Euler Method',
         'Runge-Kuffa Method'
     ]
     self.column_colors = {
         'Analytical Solution': 'Violet',
         'Euler Method': 'Blue',
         'Improved Euler Method': 'Red',
         'Runge-Kuffa Method': 'Green'
     }
    def get_information(comments, start_id, count, get_comment_info, loaded_comment_ids):
        result = list()
        try:
            if not start_id:
                result = Methods.get_one_object_info_from_scratch(
                    comments, get_comment_info, count, loaded_comment_ids)
            else:
                result = Methods.get_one_object_info_not_from_scratch(
                    comments, get_comment_info, start_id, count, loaded_comment_ids)

        except Exception as ex:
            Logs.print_current_function_name_and_line_number(ex)

        return result
 def get_the_publishes_info(publishes, user_id, start_id, count, longitude, latitude, loaded_publish_ids):
     result = list()
     # index = 0
     # params = [longitude, latitude, user_id]
     if not start_id:
         result = Methods.get_one_object_info_from_scratch(
             publishes,
             Discovery.get_publish_info4discovery,
             count,
             loaded_publish_ids,
             longitude,
             latitude,
             user_id
         )
         # for publish in publishes:
         #     if str(publish.id) in loaded_publish_ids:
         #         continue
         #     temp = Discovery.get_publish_info4discovery(publish, longitude, latitude, user_id)
         #     if temp and (index < count):
         #         result.append(temp)
         #         index += 1
         #         if index == count:
         #             break
     else:
         result = Methods.get_one_object_info_not_from_scratch(
             publishes,
             Discovery.get_publish_info4discovery,
             start_id,
             count,
             loaded_publish_ids,
             longitude,
             latitude,
             user_id
         )
         # publish_ids = [publish.id for publish in publishes]
         # if start_id in publish_ids:
         #     index_id = publish_ids.index(start_id)
         #     length = len(publish_ids) - index_id
         #     for i in xrange(length):
         #         publish = publishes[index_id + i]
         #         if str(publish.id) in loaded_publish_ids:
         #             continue
         #         temp = Discovery.get_publish_info4discovery(publish, longitude, latitude, user_id)
         #         if temp and (index < count):
         #             result.append(temp)
         #             index += 1
         #             if index == count:
         #                 break
     return result
Exemple #12
0
def stephensen():
    func = request.form['function']
    xn = float(request.form['xn'])
    iterations = float(request.form['iterations'])
    tolerance = float(request.form['tolerance'])

    methods = Methods(func)
    table = methods.stephensen(xn, tolerance, iterations)
    if request.form.get('prueba', None):
        return json.dumps(table, default=decimal_default)
    return render_template('resultsTable.html',
                           results=table[2],
                           func=func.replace("**", "^"),
                           aprox=aproximacionesx,
                           aproy=aproximacionesy)
 def test_mecha_coach(self):
     list1 = ["Alice", "Bob", "Charly", "Dan"]
     self.assertEqual(Methods.mecha_coach(list1), [
         [["Alice", "Bob"], ["Charly", "Dan"]],
         [["Alice", "Charly"], ["Bob", "Dan"]],
         [["Alice", "Dan"], ["Bob", "Charly"]],
     ])
Exemple #14
0
class PartnerOrderAction(APIView):
    def __init__(self):
        self.m = Methods()

    @csrf_exempt
    def post(self, request):
        client = self.m.get_redis_client()
        resp = {'status': 'failed'}
        action_type = request.data.get('action_type')
        order_id = request.data.get('order_id')
        o = Orders.objects.filter(order_id=order_id)
        if o:
            o = o[0]
            if action_type == "accept":
                o.status = "ACCEPTED"
                o.save()
                resp['status'] = 'success'
            elif action_type == "ass_driver":
                driver_id = client.get('driveronline')
                if driver_id:
                    driver = Driver.objects.get(id=driver_id)
                    o.driver = driver
                    o.status = "DRVR_ASS"
                    o.save()
                    resp['status'] = 'success'
        return Response(resp, status=200)
Exemple #15
0
 def __init__(self, min_year, max_year):
     self.min_year = min_year
     self.max_year = max_year
     self.max_rank = 60
     self.topn = 10
     self.path = '../data'
     self.file_prefix = 'rushing_'
     self.df = pd.DataFrame()
     self.to_int_vars = [
         'Year', 'RK', 'ATT', 'YDS', 'LONG', '20+', 'TD', 'FUM', '1D'
     ]
     self.to_flt_vars = ['YDS/G', 'YDS/A']
     self.funcs = Methods()
     self.points = Points()
     self.feature_vector = [
         u'RK', u'is_runner', u'games_played', u'n_years', u'td_per_game',
         u'att_per_game', u'r_yards_game', u'r_20p_game', u'r_fum_game',
         u'r_yds_att', u'log_long', u'r_1d_game', u'avg_career_rank',
         u'previous_rank1_clean', u'previous_rank2_clean',
         u'previous_rank3_clean', u'previous_rank4_clean',
         u'previous_rank5_clean', u'lst_rank_delta', u'r_td_rec',
         u'log_yards'
     ]
     self.dep_var = [
         u'y_future_rank', u'y_top5', 'y_sqrt_future_rank',
         'y_future_points', 'y_sqr_future_points'
     ]
Exemple #16
0
def incremental():

    func = request.form['function']
    x0 = float(request.form['x0'])
    delta = float(request.form['delta'])
    iterations = int(request.form['iterations'])

    methods = Methods(func)
    table = methods.incremental_searches(x0, delta, iterations)
    print(table[1])

    if request.form.get('prueba', None):
        return json.dumps(table, default=decimal_default)
    return render_template('resultsTable.html',
                           results=table[1],
                           func=func.replace("**", "^"),
                           aprox=[],
                           aproy=[])
Exemple #17
0
def muller():

    func = request.form['function']
    xi = float(request.form['xi'])
    xs = float(request.form['xs'])
    iterations = float(request.form['iterations'])
    tolerance = float(request.form['tolerance'])

    methods = Methods(func)
    table = methods.muller(xi, xs, tolerance, iterations)

    if request.form.get('prueba', None):
        return json.dumps(table, default=decimal_default)
    return render_template('resultsTable.html',
                           results=table[2],
                           func=func.replace("**", "^"),
                           aprox=[],
                           aproy=[])
Exemple #18
0
class GetLiveColor(APIView):
    def __init__(self):
        self.m = Methods()

    def post(self, request):
        resp = {'s': False}
        url = request.data.get('url')
        if url:
            site = self.m.DetectSite(url)
            if site:
                image_url = self.m.GetImageUrl(url)
                image_path = self.m.SaveFile(image_url)
                dominant_color, colors = self.m.Analyse(image_path)
                self.m.CleanUp(image_path)
                resp['s'] = True
                resp['d'] = dominant_color
                resp['c'] = colors
                resp['i'] = image_url
        return Response(resp, 200)
Exemple #19
0
def home():
    f = open("examples.txt")
    lines = f.readlines()
    methods = []
    for i in range(0, len(lines), 3):
        method = Methods(lines[i], lines[i+1], lines[i+2])
        methods.append(method)


    # songs = ["No Diggity", "Hypnotize", "99 Problems", "Party in the USA"]
    return render_template('form.html', methods=methods)
Exemple #20
0
class DriverLogout(APIView):
    def __init__(self):
        self.m = Methods()

    def post(self, request):
        resp = {'status': 'failed'}
        mobile = request.data.get('mobile')
        client = self.m.get_redis_client()
        client.delete('driveronline')
        resp['status'] = 'success'
        return Response(resp, status=200)
Exemple #21
0
class DriverLogin(APIView):
    def __init__(self):
        self.m = Methods()

    def post(self, request):
        resp = {'status': 'failed'}
        mobile = request.data.get('mobile')
        password = request.data.get('password')
        driver = Driver.objects.filter(mobile=mobile, password=password)
        if driver:
            client = self.m.get_redis_client()
            client.set('driveronline', driver[0].id)
            resp['status'] = 'success'
            resp['driver_name'] = driver[0].name
        return Response(resp, status=200)
Exemple #22
0
class AutoAssignDriver(APIView):
    def __init__(self):
        self.m = Methods()

    def get(self, request):
        client = self.m.get_redis_client()
        curr_time = datetime.now().strftime("%Y-%m-%d %H:%M")
        orders = Orders.objects.filter(scheduled=curr_time)
        driver_id = client.get('driveronline')
        if driver_id:
            for o in orders:
                driver = Driver.objects.get(id=driver_id)
                o.driver = driver
                o.status = "DRVR_ASS"
                o.save()
        return Response({"key": "value"})
Exemple #23
0
class ESP_Calculator_app(tk.Tk):

    pathfinder = Methods()

    photo = pathfinder.resource_path("ESP_logo.png")

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.title_font = tkfont.Font(family='Helvetica',
                                      size=18,
                                      weight="bold",
                                      slant="italic")
        self.button_font = tkfont.Font(family='Helvetica',
                                       size=12,
                                       weight="bold",
                                       slant="italic")
        self.unit_font = tkfont.Font(family='Helvetica',
                                     size=9,
                                     weight="bold",
                                     slant="italic")  #need to put this in

        # the container is where we'll stack a bunch of frames
        # on top of each other, then the one we want visible
        # will be raised above the others
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)

        self.frames = {}
        for F in (StartPage, PressurePage, SpeedPage, CurrencyPage,
                  LengthPage):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

            # put all of the pages in the same location;
            # the one on the top of the stacking order
            # will be the one that is visible.
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")

    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()
Exemple #24
0
 def __init__(self, min_year, max_year):
     self.min_year=min_year
     self.max_year=max_year
     self.max_rank=60
     self.topn = 5
     self.path='../data'
     self.file_prefix='passing_'
     self.df = pd.DataFrame()
     self.to_int_vars = ['RK', 'COMP', 'ATT', 'YDS', 'LONG', 'TD', 'INT', 'SACK']
     self.to_flt_vars = ['YDS/G', 'AVG', 'RATE', 'PCT']
     self.funcs=Methods()
     self.points=Points()
     self.feature_vector=[u'RK', u'is_qb', u'games_played', u'n_years', u'td_per_game', u'comp_per_game',
                          u'int_per_game', u'sack_per_game', u'log_yards', u'r_att_comp', u'r_yards_game',
                          u'r_att_game', u'percent_comp', u'avg_career_rank', u'previous_rank1_clean',
                          u'previous_rank2_clean', u'previous_rank3_clean', u'previous_rank4_clean',
                          u'previous_rank5_clean', u'lst_rank_delta']
     self.dep_var=[u'y_future_rank', u'y_top5', 'y_sqrt_future_rank', 'y_future_points', 'y_sqr_future_points']
Exemple #25
0
def calculations():
    wire_1 = []
    wire_1 = []
    with open('../../input/2019/day3.txt') as f:
        wire_1 = f.readline().strip()
        wire_2 = f.readline().strip()

    wire_1_map = calc_coords(wire_1.split(','))
    wire_2_map = calc_coords(wire_2.split(','))

    all_coords = wire_1_map.keys() & wire_2_map.keys()
    min_steps = min([wire_1_map[c] + wire_2_map[c] for c in all_coords])
    print('second star: ' + str(min_steps))

    distances = []

    for c in all_coords:
        distances.append(Methods.manhattan(c[0], c[1]))

    return min(distances)
Exemple #26
0
    def max_error(self, input):

        N_start = input[4]
        N_end = input[5]

        x0 = input[0]
        X = input[2]

        n = N_start

        n_x = []
        n_euler = []
        n_euler_imp = []
        n_fk = []

        methods = Methods()
        while n <= N_end:
            n_x.append(n)
            h = abs(X - x0) / n
            input[3] = n

            exact = []
            euler_new_y = []
            euler_imp_new_y = []
            rk_new_y = []
            table_x = []

            table_x = methods.set_x(input, table_x)
            exact = methods.exact_solution(input, table_x, exact)

            euler_new_y = methods.euler_method(input, table_x, euler_new_y)
            euler_imp_new_y = methods.improved_euler_method(
                input, table_x, euler_imp_new_y)
            rk_new_y = methods.runge_kutta_method(input, table_x, rk_new_y)

            n_euler.append(self.get_max_point(exact, euler_new_y))
            n_euler_imp.append(self.get_max_point(exact, euler_imp_new_y))
            n_fk.append(self.get_max_point(exact, rk_new_y))
            n += 1
        return n_x, n_euler, n_euler_imp, n_fk
from urllib.request import urlretrieve
from urllib.request import urlopen
from urllib.error import HTTPError
from bs4 import BeautifulSoup
from methods import Methods as m
import os


path = 'https://www.lamoda.ru'
m.make_sure_path_exists('woman_shoes_premium')
html = urlopen(path+'/c/1265/shoes-premium-obuv/')
bsObj1 = BeautifulSoup(html, "html.parser")

try:
    for link in bsObj1.find("ul", {"class":"cat-nav dt102_1"}).find("ul", {"class":"cat-nav cat-nav-sub dt102_2"}).find("ul", {"class":"cat-nav cat-nav-sub dt102_3"}).findAll("li", {"class":"cat-nav-item dt102_li3"}):
        endpoint = link.find("a", {"class":"link"})

        m.make_sure_path_exists('woman_shoes_premium/'+endpoint.contents[0])
        category_html = urlopen(path+endpoint.attrs['href'])
        bsObj2 = BeautifulSoup(category_html, "html.parser")

        j = 1
        for link in bsObj2.find("div", {"class":"products-catalog__list"}).findAll("div", {"class":"products-list-item"}):
            if 'data-gallery' in link.attrs:
                category_link = link.attrs['data-gallery'].strip('[').strip(']').strip('"')
                r = category_link.split('" , "')
                for i in range(len(r)):
                    urlretrieve('https:'+r[i], m.getImagesDir()+'woman_shoes_premium/'+endpoint.contents[0]+'/'+endpoint.contents[0]+'.'+str(j)+'.'+str(i)+'.jpeg')
                j += 1
            else:
                print(link.attrs)
Exemple #28
0
from urllib.request import urlretrieve
from urllib.request import urlopen
from urllib.error import HTTPError
from bs4 import BeautifulSoup
from methods import Methods as m
import os

path = 'https://www.lamoda.ru'
m.make_sure_path_exists('woman_clothes_premium')
html = urlopen(path + '/c/1303/clothes-premium-odezda/')
bsObj1 = BeautifulSoup(html, "html.parser")

try:
    for link in bsObj1.find("ul", {
            "class": "cat-nav dt102_1"
    }).find("ul", {
            "class": "cat-nav cat-nav-sub dt102_2"
    }).find("ul", {
            "class": "cat-nav cat-nav-sub dt102_3"
    }).findAll("li", {"class": "cat-nav-item dt102_li3"}):
        endpoint = link.find("a", {"class": "link"})

        m.make_sure_path_exists('woman_clothes_premium/' +
                                endpoint.contents[0])
        category_html = urlopen(path + endpoint.attrs['href'])
        bsObj2 = BeautifulSoup(category_html, "html.parser")

        j = 1
        for link in bsObj2.find("div", {
                "class": "products-catalog__list"
        }).findAll("div", {"class": "products-list-item"}):
Exemple #29
0
 def basic(self):
     testcase = "LoveLace, Ada"
     expected = "Ada LoveLace"
     self.assertEqual(Methods.rearrage_name(testcase), expected)
 def test_if_method_merges_two_sorted_arrays(self):
     Methods = MergeSort()
     list1 = [1, 2, 1, 11, 6, 5, 7, 10, 5, 4, 3, 5, 6, 11]
     self.assertEqual(Methods.sort(list1),
                      [1, 1, 2, 3, 4, 5, 5, 5, 6, 6, 7, 10, 11, 11])
Exemple #31
0
from urllib.request import urlretrieve
from urllib.request import urlopen
from urllib.error import HTTPError
from bs4 import BeautifulSoup
from methods import Methods as m
import os

path = 'https://www.lamoda.ru'
m.make_sure_path_exists('woman_clothes')
html = urlopen(path + '/c/355/clothes-zhenskaya-odezhda/')
bsObj1 = BeautifulSoup(html, "html.parser")

try:
    for link in bsObj1.find("ul", {
            "class": "cat-nav dt102_1"
    }).find("ul", {
            "class": "cat-nav cat-nav-sub dt102_2"
    }).findAll("li", {"class": "cat-nav-item dt102_li2"}):
        result = link.find("a", {"class": "link"})

        m.make_sure_path_exists('woman_clothes/' + result.contents[0])
        category_html = urlopen(path + result.attrs['href'])
        bsObj2 = BeautifulSoup(category_html, "html.parser")

        j = 1
        for link in bsObj2.find("div", {
                "class": "products-catalog__list"
        }).findAll("div", {"class": "products-list-item"}):
            if 'data-gallery' in link.attrs:
                category_link = link.attrs['data-gallery'].strip('[').strip(
                    ']').strip('"')
Exemple #32
0
class experiment:
    def __init__(self):
        self.method = Methods()


    def testNB(self):
        badWords = ['f**k','damn','work','c**t','bitch','w***e','asshole']

        lines = self.openFile("testing.txt")
        results_NB = []
        results_NB_noC = []
        results_NB_bad = []
        results_NB_noC_bad = []


        for toCheck in lines:
            status = toCheck.split(";")[1]

            results_NB.append(self.method.rate_status(status,2,[]))
            results_NB_noC.append(self.method.rate_status(status,3,[]))
            results_NB_bad.append(self.method.rate_status(status,2,badWords))
            results_NB_noC_bad.append(self.method.rate_status(status,3,badWords))


        scores = [0,0,0,0]
        scoresn =[0,0,0,0]
        for i in range(len(lines)):
            rate = lines[i].split(";")[0]
            if rate == 'negative':
                if rate == results_NB[i]:
                    scoresn[0] +=1
                if rate == results_NB_noC[i]:
                    scoresn[1] +=1
                if rate == results_NB_bad[i]:
                    scoresn[2] +=1
                if rate == results_NB_noC_bad[i]:
                    scoresn[3] +=1
            if rate == results_NB[i]:
                scores[0] +=1
            if rate == results_NB_noC[i]:
                scores[1] +=1
            if rate == results_NB_bad[i]:
                scores[2] +=1
            if rate == results_NB_noC_bad[i]:
                scores[3] +=1

        print(scores)
        print(scoresn)

    def openFile(self,name):
        this = open(name,'r')
        toReturn = []
        for i in this.readlines():
            toReturn.append(i[:-1])
        return toReturn

    def testKNN(self):
        badWords= "f**k damn work c**t bitch w***e asshole horny shit"
        lines = self.openFile("testing.txt")

        results_KNN = []
        results_KNN_noC = []
        results_KNN_bad = []
        results_KNN_noC_bad = []

        for toCheck in lines:
            status = toCheck.split(";")[1]

            results_KNN.append(self.method.kNN_getClass(status,2,""))
            results_KNN_noC.append(self.method.kNN_getClass(status,3,""))
            results_KNN_bad.append(self.method.kNN_getClass(status,2,badWords))
            results_KNN_noC_bad.append(self.method.kNN_getClass(status,3,badWords))


        scores = [0,0,0,0]
        scoresn =[0,0,0,0]
        for i in range(len(lines)):

            rate = lines[i].split(";")[0]
            if rate == 'negative':
                if rate == results_KNN[i]:
                    scoresn[0] +=1
                if rate == results_KNN_noC[i]:
                    scoresn[1] +=1
                if rate == results_KNN_bad[i]:
                    scoresn[2] +=1
                if rate == results_KNN_noC_bad[i]:
                    scoresn[3] +=1
            if rate == results_KNN[i]:
                scores[0] +=1
            if rate == results_KNN_noC[i]:
                scores[1] +=1
            if rate == results_KNN_bad[i]:
                scores[2] +=1
            if rate == results_KNN_noC_bad[i]:
                scores[3] +=1

        print(scores)
        print(scoresn)
# Wojciech Wróblewski 250349 kompilator

import sys
from parser import OneBeerLexer, OneBeerParser
from methods import Methods
from errors import Errors

error = Errors()
argument = sys.argv
length_arguments = len(argument)
if length_arguments < 3:
    error.run_error()

file_in = sys.argv[1]
file_out = sys.argv[2]
lexer = OneBeerLexer()
parser = OneBeerParser()

with open(file_in) as file:
    text = file.read()
    parse_tree = parser.parse(lexer.tokenize(text))
    machine = Methods(parse_tree, file_out)
    machine.get_assembler()
Exemple #34
0
 def __init__(self):
     self.method = Methods()