Ejemplo n.º 1
0
def main():
    easy_dices = [
        './images/easy/dice1.jpg', './images/easy/dice2.jpg',
        './images/easy/dice3.jpg', './images/easy/dice4.jpg',
        './images/easy/dice5.jpg', './images/easy/dice6.jpg',
        './images/easy/dice7.jpg', './images/easy/dice8.jpg',
        './images/easy/dice9.jpg', './images/easy/dice10.jpg'
    ]
    medium_dices = [
        './images/medium/dice1.jpg', './images/medium/dice2.jpg',
        './images/medium/dice3.jpg', './images/medium/dice4.jpg',
        './images/medium/dice5.jpg', './images/medium/dice6.jpg',
        './images/medium/dice7.jpg', './images/medium/dice8.jpg',
        './images/medium/dice9.jpg', './images/medium/dice10.jpg'
    ]
    hard_dices = [
        './images/hard/dice1.jpg', './images/hard/dice2.jpg',
        './images/hard/dice3.jpg', './images/hard/dice4.jpg',
        './images/hard/dice5.jpg', './images/hard/dice6.jpg',
        './images/hard/dice7.jpg', './images/hard/dice8.jpg',
        './images/hard/dice9.jpg', './images/hard/dice10.jpg'
    ]
    pictures = []
    for easy_dice, medium_dice, hard_dice in zip(easy_dices, medium_dices,
                                                 hard_dices):
        pictures.append(Picture(easy_dice))
        pictures.append(Picture(medium_dice))
        pictures.append(Picture(hard_dice))

    for picture in pictures:
        picture.process_picture()
        result(result)
Ejemplo n.º 2
0
 def test_max():
     expr = max(map(partition(goals, 'team'), len))
     home = randint(0, 3)
     away = randint(0, 3)
     state = gen_state(home, away)
     expected = {-1: {'away'}, 0: {'home', 'away'}, 1: {'home'}}
     assert result(expr, state) == expected[cmp(home, away)]
Ejemplo n.º 3
0
 def test_attr():
     expr = attr(nth(goals, 0), 'team')
     home = randint(0, 1)
     away = randint(0, 1 - home)
     state = gen_state(home, away)
     expected = {(0, 0): None, (1, 0): 'home', (0, 1): 'away'}
     assert result(expr, state) == expected[(home, away)]
Ejemplo n.º 4
0
def post():
    # get post data
    json_data = request.get_json()

    try:
        # input check by ma.Schema
        json_check = user_schema.load(json_data)
        # get json of server response
        result_json = result.result(200, "ping successful")[0].get_json()
        # logging post data
        result.write_log('info', "data: {}".format(json_data))
    except:
        return result.result(400, "please check your parameters")

    result_json['data'] = json_check

    return jsonify(result_json)
Ejemplo n.º 5
0
def calculate_time(out):
    # print(transform_hex_data(out[4]) << 8)
    # print(transform_hex_data(out[5]))
    sport_time = (transform_hex_data(out[4]) << 8) + transform_hex_data(out[5])
    real_time = sport_time / 100
    result_bean = result.result(transform_hex_data(out[1]), real_time)
    # print(result_bean.to_string())
    return result_bean
Ejemplo n.º 6
0
 def addResult(self, algoId, results, centerIds, timeConsumed):
     for centerId in range(len(centerIds)):
         if centerIds[centerId][0] == -1:
             assert centerIds[centerId][1] == -1
             centerIds = resize(centerIds, (centerId + 1, 2))
             break
     results.append(
         result(algoId, self.points, self.calcMinRadius(centerIds),
                centerIds, timeConsumed))
Ejemplo n.º 7
0
def simulate(match):
    alldata = list()
    teams = getteamsplaying(match)
    team1, team2 = teams[0], teams[2]
    print "Teams:", team1, team2
    t1p, t2p = teams[1], teams[3]
    if teams[5][0] != 'Tba':
        maps = list(teams[5])
        print "Maps: ", maps
    else:
        #Predict Maps
        maps = predict_map(team1, team2, teams[4])
        print "Predicted maps: ", maps
    for i in maps:
        stats = simulation(getstats(t1p, t2p, i))
        print i, stats
        alldata.append(stats)
    result(alldata)
Ejemplo n.º 8
0
def image():
    json_data = request.get_json()

    try:
        image_url = json_data['image']
        local_image_filename = wget.download(image_url)

        find_image_dict = find_image(test_model, local_image_filename)
        # get json of server response
        result_json = result.result(200, "ping successful")[0].get_json()
        # logging post data
        result.write_log('info', "data: {}".format(find_image_dict))

        if os.path.exists(local_image_filename):
            os.remove(local_image_filename)
    except:
        return result.result(400, "please check your parameters")

    result_json['data'] = find_image_dict
    return jsonify(result_json)
Ejemplo n.º 9
0
def searchLucene(requestParameter):
    "this method is used to search Lucene"
    searchResults = []
    requestParameter = requestParameter.replace("/"," ")
    # 1. open the index
    if __name__ == "luceneSearch":
        lucene.initVM()
    analyzer = StandardAnalyzer(Version.LUCENE_4_10_1)
    index = SimpleFSDirectory(File("Home/WishMatcherIndex"))
    reader = IndexReader.open(index)
    n_docs = reader.numDocs()
    print("Index contains %d documents." % n_docs)

    # 2. parse the query from the command line
    fields=["AdLine","FieldString","FieldRelatedWords"]    
    parser = MultiFieldQueryParser(Version.LUCENE_CURRENT, fields, analyzer)
    parser.setDefaultOperator(QueryParserBase.OR_OPERATOR)
    query = MultiFieldQueryParser.parse(parser,requestParameter)
    print(query)

    # 3. search the index for the query
    # We retrieve and sort all documents that match the query.
    # In a real application, use a TopScoreDocCollector to sort the hits.
    searcher = IndexSearcher(reader)
    hits = searcher.search(query, n_docs).scoreDocs

    # 4. display results
    print("Found %d hits:" % len(hits))
    for i, hit in enumerate(hits):
        doc = searcher.doc(hit.doc)
        product = doc.get("AdLine")
        url = doc.get("URL")
        if(doc.get("AdId") != 1200):
            product = product[:-1]
            url = url[:-1]
        print("%d. %s" % (i + 1, doc.get("AdLine")))
        r = result(str(product),str(url))
        searchResults.append(r)

    # 5. close resources
    #searcher.close()
    print(searchResults)
    return searchResults
Ejemplo n.º 10
0
from result import result

print result('./testCases/main.txt')
Ejemplo n.º 11
0
structure_1 = structure_1.transpose()
structure_2 = structure_2.transpose()

opening_bracket_fs = structure_1[0:1, ]
closing_bracket_fs = structure_1[1:2, ]
length_first = structure_1[2:3, ]

opening_bracket_ss = structure_2[0:1, ]
closing_bracket_ss = structure_2[1:2, ]
length_second = structure_2[2:3, ]

wp = 1
wd = 1
sl = 1

opening_bracket_fs = np.array(opening_bracket_fs)
closing_bracket_fs = np.array(closing_bracket_fs)
opening_bracket_ss = np.array(opening_bracket_ss)
closing_bracket_ss = np.array(closing_bracket_ss)
length_first = np.array(length_first)
length_second = np.array(length_second)

allignment = []
allignment = np.array(allignment)
allignment = allignComponents(opening_bracket_fs, closing_bracket_fs,
                              opening_bracket_ss, closing_bracket_ss, wp, wd,
                              sl, no_inter_first, no_inter_second,
                              length_first, length_second)
print("Allignement Similarity between two structure :\n", allignment)
result(allignment, no_inter_first, no_inter_second)
Ejemplo n.º 12
0
                y, x = prepareData(pf, s)
                dimensione = len(x) / 100 * dim
                prob = svm_problem(y[:dimensione], x[:dimensione])
                x = x[dimensione:]
                y = y[dimensione:]

                for classificazione in classificazioni:
                    print "---- ---- --> inizio ciclo su classificazione : ", classificazione
                    for k in kernel:

                        if k == ' -t 2':
                            print "\n---- ---- ----> inizio ciclo su kernel : ", k
                        else:
                            print "---- ---- ----> inizio ciclo su kernel : ", k

                        r = result(classificazione, k, s, dim, pf, prob, x, y)
                        if k == ' -t 2':
                            print ""
                        results.append(r)

                if len(results) % 500 == 0:
                    pickle.dump(
                        results,
                        open("DatiElaborati/result" + str(count) + "_utili",
                             "wb"))
                    print ""
                    print "---- ---- ----> salvataggio <---- ---- ---- ", len(
                        results)
                    print ""
                    count += 1
                    results = []
Ejemplo n.º 13
0
            input(
                "Abracadabra, which number is in my mind? Tell me number between "
                + str(game.fromNum) + " and " + str(game.toNum) + ": "))
        numGuess = numGuess + 1
        if UserGuess < game.fromNum or UserGuess > game.toNum:
            raise ValueError
        elif int(UserGuess) == game.secret:
            print("Uh wow! That is absolutly correct. Congrats my dear!")
            break
        else:
            wrongGuesses = wrongGuesses + 1
            print("Nope! Far, far away! That is not my number!")
    except ValueError:
        print("Oops! That was no valid number. Try again...")

newGame = result(score=numGuess, player_name=player, date=str(game.today))

#Define variable für JSON File
listContent = {}
listContent['games'] = []


#Open and read JSON File
def get_score_list():
    with open(filename) as json_file:
        listContent = json.load(json_file)
    return listContent


listContent = get_score_list()
Ejemplo n.º 14
0
def method_404(e):
    return result.result(404, "requested URL was not found on the server")
Ejemplo n.º 15
0
def upload():
	file = dm.getfile("Select apparel image")
	if (file == ''): return
	return rs.result(file)
Ejemplo n.º 16
0
    process.wait()
    output = process.stdout.readlines()
    start = False
    #stdoutput = process.communicate()
    for line in output:
        if(line[0] == '|'):
            continue
        elif(start == True):
            if(line[0] >= '0' and line[0] <= '9'):
                parts = line.split(' ')
                length = len(parts)
                detail = ''
                for i in range(1,length):
                    detail += parts[i] + '  '
                result.portservice[parts[0]] = detail
            else:
                start = False
        elif(line.startswith('PORT')):
            start = True
            continue
        elif(line.startswith('OS details')):
            parts = line.split(':')
            result.operatingsystem = parts[1]
    #print stdoutput

t = result.result()
nmap("10.0.0.55", t)
print t.operatingsystem
for key in t.portservice.keys():
    print key + ':' + t.portservice[key]
Ejemplo n.º 17
0
#!/usr/bin/env python
# coding=utf-8
import result
import numpy as np

threshold = np.arange(1600, 2800, 2)
result.result(threshold, "conv3")
Ejemplo n.º 18
0
def ping():
    return result.result(200, "ping successful",
                         "Welcome to restful api server.")
Ejemplo n.º 19
0
def main_black(T=60,server='localhost'):

    # white positive
    free_winpath_white=2 #king can go in a position in which could win
    kill_black=1.9
    protection_king=2   #white protecting the king from being killed
    pass_kill= 0.1

    #white negative
    checker_in_escape=0.5
    dangerous_neig_white=0.5
    white_obstructing=1
    white_not_protecting=1.9
    killed = 1.8

    #king positive:
    h_w_win=0
    free_winpath_king=2 #re si porta in posizione vittoria grazie al suo movimento
    king_kills_black=1.8
    pass_kill_king=0.1

    #king negative
    dangerous_neig_king=0.5
    killed_king = 0

    #black:
    h_black_win=500

    #black heuristic
    black_win = 1000
    black_loose = 1000
    black_checker_death=5
    white_checker_death=4
    strategic_position=3
    move_strategic_position=2
    black_near_king=4





    Tablut_dict={'EMPTY':0,'BLACK':'B','WHITE':'W','KING':'K','THRONE':0}
    l1=['a','b','c','d','e','f','g','h','i']
    l2=['1','2','3','4','5','6','7','8','9']
    l3=[]
    for i in l1:
        for j in l2:
            l3.append(i+j)
    Board_dict={}
    ind=0
    for i in range(9):
        for j in range(9):
            Board_dict[str([j,i])]=l3[ind]
            ind+=1

    escape_value=11
    castle_value=50
    empty_camps_value = 98
    full_camps_value = 99
    white_value=10
    black_value=1
    king_value=8




    Tablut_connection = C1.Player(1,'barbarians',server)
    sys.setrecursionlimit(10000)
    while True:
        try :

            board=Tablut_connection.read()
            board = board.decode()
            board = json.loads(board)
            turn = board['turn']
            board=board['board']
            board_java=np.array(board)


            king_indexes = list(zip(*np.where(board_java == 'KING')))
            ik = king_indexes[0][0]
            jk = king_indexes[0][1]
            # king indexes

            if turn == 'BLACK':




                for i in range(9):
                    for j in range(9):

                            board[i][j]=Tablut_dict[board[i][j]]


                indices = [[i, x] for i in range(9) for x in range(9) if board[i][x] == 'B']
                illegal_moves = [[0, 3], [0, 4], [0, 5], [1, 4], [8, 3], [8, 4], [8, 5], [7, 4], [3, 0], [4, 0], [5, 0],
                                 [4, 1], [3, 8], [4, 8], [5, 8], [4, 7],[4,4]]


                moves = []
                for j in indices:
                    board_conv = bl.convert_board(copy.deepcopy(board), illegal_moves, j)
                    moves = act.black_checker_actions(board_conv, j, moves, copy.deepcopy(illegal_moves))


                random.shuffle(moves)

                h_max = -1000000
                move = []
                for action in moves:
                    new_board = bl.move_on_board(board, action)

                    h_b = heu.utility(new_board,action[0], action[1][0], action[1][1], illegal_moves,black_win, black_loose,black_checker_death,white_checker_death,strategic_position,move_strategic_position,black_near_king)

                    #print(h_b, sep=' ', end='', flush=True)


                    M, M_tiles, M_converted = create_M(board_java)
                    #action=np.array(action)
                    M,M_converted=result(M,M_converted,king_indexes,black_value,white_value,castle_value,empty_camps_value, full_camps_value, king_value, action, turn='BLACK')
                    M=np.array(M)
                    white_positions = list(zip(*np.where(M == white_value)))

                    list_actions_white = []
                    for indexes in white_positions:
                        list_actions_white += actions_white(M, indexes[0], indexes[1], 9, 9)

                    king_actions = actions_king(M, ik, jk, 9, 9, escape_value)
                    list_actions_white = np.array(list_actions_white)

                    h_w_max = -10000
                    # random.shuffle(list_actions)  # shuffle method maybe is not going to contain all the actions, but some repeated??
                    pass_kill_king, killed_king = 0.1, 1000
                    pass_kill, killed = 0.1, 4.5

                    for action_king in king_actions:
                        action_king = np.array(action_king)
                        M_result, M_converted_result = apply_action(M, M_converted, action_king)
                        # the Matrix given in output from apply action has still the checkers to be eliminated if killed
                        i = action_king[0, 0]
                        j = action_king[0, 1]
                        ik_result = action_king[1, 0]
                        jk_result = action_king[1, 1]

                        h_w = heuristic_king(M_result, M_tiles, ik_result, jk_result, pass_kill_king, killed_king,h_w_win,
                                             free_winpath_king, dangerous_neig_king, king_kills_black, escape_value,
                                             castle_value, empty_camps_value, full_camps_value, white_value,
                                             black_value, king_value
                                             )

                        if h_w > h_w_max:
                            h_w_max = h_w






                    for white_action in list_actions_white:

                        M_result, M_converted = apply_action(M, M_converted, white_action)
                        h_w = heuristic_white(M_result,M_tiles, white_action, ik, jk, pass_kill_king, killed_king, pass_kill, killed,
                                              free_winpath_white, white_obstructing, checker_in_escape,
                                              dangerous_neig_white, kill_black, protection_king, white_not_protecting,
                                              escape_value, castle_value, empty_camps_value, full_camps_value,
                                              white_value,
                                              black_value, king_value)
                        if h_w >= h_w_max:
                            h_w_max = h_w

                    h= h_b - h_w_max
                    if h > h_max:
                        h_max = h

                        move = action

                #print('actions', moves)
                #print('choosen', h_max)
                #print(np.array(board))

                #print(move)

                #print("{'from':"+Board_dict[str(move[0])]+",'to':"+Board_dict[str(move[1])]+",'turn':'BLACK'}")
                Tablut_connection.send("{'from':"+Board_dict[str(move[0])]+",'to':"+Board_dict[str(move[1])]+",'turn':'BLACK'}")


        except SyntaxError:
            pass
Ejemplo n.º 20
0
 def test_len():
     expr = len(goals)
     home = randint(0, 3)
     away = randint(0, 3)
     state = gen_state(home, away)
     assert result(expr, state) == home + away
Ejemplo n.º 21
0
def upload(screen):
    file = dm.getfile("Select a shoe image")
    fade(screen, 360, 640)
    load.loading()
    fade(screen, 360, 640)
    return rs.result(file)
    def execute_all(self, task, storage=None):
        """
        execute all parametrizations as defined in task object

        Parameters
        ----------

        task -- the task which is broken down into the individual execution points
        storage -- if set to a string, will store the result in that path as JSON. If set to a file, will use that.

        Returns
        -------

        results -- the results of the computation in a list of result objects.
        """
        instruction = task._task_type
        #print "running a total number of points of", task.get_total_points()
        setters = {}
        if instruction == bt.RUN_FG:
            class_n = task.class_name
            time.sleep(1)
            module_n = str(task.module_name)
            module = __import__(module_n, fromlist=[str(class_n)])
            self.block_class = getattr(module, task.class_name)
        elif instruction == bt.RUN_GRC:
            if not hasattr(self, "temp_outdir"):
                self.temp_outdir = tempfile.mkdtemp(suffix="_py",
                                                    prefix="gr-mtb-")
            temp_grc_file = tempfile.NamedTemporaryFile(suffix=".grc",
                                                        delete=False,
                                                        dir=self.temp_outdir)

            temp_grc_file.write(task.grcxml)
            temp_grc_file.close()

            platform = Platform()
            data = platform.parse_flow_graph(temp_grc_file.name)

            fg = platform.get_new_flow_graph()
            fg.import_data(data)
            fg.grc_file_path = os.path.abspath(temp_grc_file.name)
            fg.validate()

            if not fg.is_valid():
                raise StandardError("Compilation error")
            class_n = fg.get_option("id")
            filepath = os.path.join(self.temp_outdir, class_n + ".py")
            gen = platform.get_generator()(fg, filepath)
            gen.write()

            module = imp.load_source(class_n, filepath)
            self.block_class = getattr(module, class_n)
        results = []
        print "processing {:d} points".format(task.get_total_points())
        for inst, values in self.parameterize(task, self.block_class):
            datadict = self._execute(inst, task.sinks)
            results.append(result(values, datadict))
        try:
            if storage and not hasattr(storage, "write"):
                outfile = open(str(storage), 'w')
                json.dump([r.to_dict() for r in results], outfile)
                outfile.close()
            elif storage:
                json.dump([r.to_dict() for r in results], storage)
        except IOError as e:
            print e
        return results
Ejemplo n.º 23
0
def main():
    print "# KNN Classifier"
    parser = ld.parse_arguments()

    stopwords = None
    if parser.stopwords_path:
        stopwords = ld.load_stopwords(parser.stopwords_path)

    # priting args
    print '\t-k = ' + str(parser.k)
    print '\t-d = ' + parser.distance

    # loading the necessary data
    (vocabulary, neigh_classes) = ld.load_train(parser.train_path, stopwords)

    print "# Tamanho do vocabulário:", len(vocabulary)

    # transforming each item to a v-dimensional space
    (train, test) = space.transform(vocabulary, parser.train_path,
                                    parser.test_path)

    # output file
    out_path = parser.distance + '_' + str(parser.k)
    out_path += '.txt'
    out_file = open(out_path, 'w')

    # knn classification
    print "# Classifying", len(train) * parser.percentage
    for item in test:
        dist_heap = []

        # calculates the distance to every point in the training set
        for i in xrange(int(len(train) * parser.percentage)):
            point = train[i]
            distance = 0.0

            if parser.distance == 'cosine':
                distance = spd.cosine(item, point)
            elif parser.distance == 'jaccard':
                distance = spd.jaccard(item, point)
            elif parser.distance == 'euclidean':
                distance = spd.euclidean(item, point)
            elif parser.distance == 'hamming':
                distance = spd.hamming(item, point)
            elif parser.distance == 'correlation':
                distance = spd.correlation(item, point)
            elif parser.distance == 'manhattan':
                distance = spd.cityblock(item, point)
            else:
                print >> stderr, "ERRO! -  Distância informada inválida."
                exit()

            tup = (distance, i)
            heapq.heappush(dist_heap, tup)

        # return the highest k similar points
        top_k = heapq.nsmallest(parser.k, dist_heap)

        # classifing
        classification = np.zeros(2)
        for (_, idi) in top_k:
            classe = neigh_classes[idi]
            classification[int(classe)] += 1

        # DEBUG
        print classification,

        # outputing classification
        if(classification[0] >= classification[1]):
            print >> out_file, '0'
            print '0'
        else:
            print >> out_file, '1'
            print '1'

    print
    print "# Resultados salvos no arquivo: " + out_path
    out_file.close()
    result.result("../data/imdb_test", out_path)
Ejemplo n.º 24
0
#!/usr/bin/env python
# coding=utf-8
import result
import numpy as np

D_array = np.linspace(0.344344049692, 1.35239160061, 500)
result.result(D_array, "pool1")

D_array = np.linspace(0.374729394913, 1.34376788139, 500)
result.result(D_array, "conv2")

D_array = np.linspace(0.301110446453, 1.29882144928, 500)
result.result(D_array, "pool2")

D_array = np.linspace(0.311531066895, 1.29718482494, 500)
result.result(D_array, "conv3")

D_array = np.linspace(0.301401376724, 1.32344532013, 500)
result.result(D_array, "conv4")

D_array = np.linspace(0.353400379419, 1.40551733971, 500)
result.result(D_array, "conv5")

D_array = np.linspace(0.300964653492, 1.38409125805, 500)
result.result(D_array, "pool5")

D_array = np.linspace(0.274265795946, 1.40312755108, 500)
result.result(D_array, "fc6")

D_array = np.linspace(0.172954037786, 1.38578188419, 500)
result.result(D_array, "fc7")
Ejemplo n.º 25
0
from simulation import game

from snake_ladder import Snakes
from result import result

pecurialsnakes = [[68, 58], [60, 50], [51, 41], [26, 16], [90, 80], [82, 72],
                  [15, 5], [24, 14], [22, 12], [64, 54], [20, 10], [59, 49],
                  [19, 9], [45, 35], [21, 11], [52, 42], [46, 36], [23, 13],
                  [76, 66], [57, 47], [39, 29]]
aveg = []
for x in range(2, 101):
    countlist = []
    snake = Snakes(0, 0)
    sim = game(x, snake.snakes_ladders)
    for i in range(0, 100000):
        countlist.append(sim.gamesimulation())
    re = result(countlist)
    print(re.results())
    aveg.append(re.results())
with open("D:\\maths\\thesis\\algo_thesis\\results\simulation2_100.txt",
          "a") as fp:
    for f in aveg:
        fp.write(str(f) + "\n")
Ejemplo n.º 26
0
#!/usr/bin/env python
# coding=utf-8
import result
import numpy as np

D_array=np.linspace(0.344344049692,1.35239160061,500)
result.result(D_array,"pool1")
 
D_array=np.linspace(0.374729394913,1.34376788139,500)
result.result(D_array,"conv2")
 
D_array=np.linspace(0.301110446453,1.29882144928,500)
result.result(D_array,"pool2")
 
D_array=np.linspace(0.311531066895,1.29718482494,500)
result.result(D_array,"conv3")
 
D_array=np.linspace(0.301401376724,1.32344532013,500)
result.result(D_array,"conv4")
 
D_array=np.linspace(0.353400379419,1.40551733971,500)
result.result(D_array,"conv5")
 
D_array=np.linspace(0.300964653492,1.38409125805,500)
result.result(D_array,"pool5")
 
D_array=np.linspace(0.274265795946,1.40312755108,500)
result.result(D_array,"fc6")
 
D_array=np.linspace(0.172954037786,1.38578188419,500)
result.result(D_array,"fc7")
Ejemplo n.º 27
0
def main():
    print "# KNN Classifier"
    parser = ld.parse_arguments()

    # priting args
    print '\t-k = ' + str(parser.k)
    print '\t-d = ' + parser.distance

    stopwords = None
    if parser.stopwords_path:
        stopwords = ld.load_stopwords(parser.stopwords_path)

    voc = load_vocabulary(parser.train_path, stopwords)
    answers = load_answers(parser.train_path)

    train = transform(voc, parser.train_path)
    test = transform(voc, parser.test_path)

    # output file
    out_path = '../results/' + parser.distance + '_' + str(parser.k)
    out_path += '.txt'
    out_file = open(out_path, 'w')

    for point in test:
        neighbors = []
        for i in xrange(len(train)):
            neigh = train[i]
            distance = 0.0

            if parser.distance == 'cosine':
                distance = spd.cosine(neigh, point)
            elif parser.distance == 'jaccard':
                distance = spd.jaccard(neigh, point)
            elif parser.distance == 'euclidean':
                distance = spd.euclidean(neigh, point)
            elif parser.distance == 'dice':
                distance = spd.dice(neigh, point)
            elif parser.distance == 'correlation':
                distance = spd.correlation(neigh, point)
            elif parser.distance == 'manhattan':
                distance = spd.cityblock(neigh, point)
            else:
                print >> stderr, "ERRO! -  Distância informada inválida."
                exit()

            tup = (distance, i)
            heapq.heappush(neighbors, tup)

        # return the highest k similar points
        top_k = heapq.nsmallest(parser.k, neighbors)

        # classifing
        classification = np.zeros(2)
        for (_, idi) in top_k:
            classe = answers[idi]
            classification[int(classe)] += 1

        # outputing classification
        if(classification[0] >= classification[1]):
            print >> out_file, '0'
            print '0'
        else:
            print >> out_file, '1'
            print '1'

    # outputing the results'
    print
    print "# Resultados salvos no arquivo: " + out_path
    out_file.close()
    result.result("../data/imdb_test", out_path)
Ejemplo n.º 28
0
def main_white(T=60,server='localhost'):

    free_winpath=4  #king can go in a position in which could win
    kill_black=4
    protection_king=10   #white protecting the king from being killed
    pass_kill= 0.1

    #white negative
    checker_in_escape=0.5
    dangerous_neig=0.5
    white_obstructing=1
    white_not_protecting=4
    killed = 4

    #king positive:
    h_w_win=10000
    free_winpath=10
    king_kills_black=3
    pass_kill_king=0.1

    #king negative
    dangerous_neig=0.5
    killed_king = 100000

    #black positive:
    black_win = 1000,
    white_checker_death = 4
    strategic_position = 3
    black_near_king = 4

    #black negative:
    black_loose = 4
    black_checker_death = 5
    move_strategic_position = 2





    Tablut_dict = {'EMPTY': 0, 'BLACK': 'B', 'WHITE': 'W', 'KING': 'K', 'THRONE': 0}
    l1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
    l2 = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
    l3 = []

    for i in l1:
        for j in l2:
            l3.append(i + j)  # all possible movements in the java coordinates A1, B1....

    Board_dict = {}
    ind = 0
    for i in range(9):
        for j in range(9):
            Board_dict[str([j, i])] = l3[ind]  # key: A1 value: 00.... (movements)
            ind += 1

    escape_value = 11
    castle_value = 50
    empty_camps_value = 98
    full_camps_value = 99
    white_value = 10
    black_value = 1
    king_value = 8




    Tablut_connection = C1.Player(0, 'barbarians',server)  # 1=black, 0=white
    sys.setrecursionlimit(10000)

    next = True
    first_move = True
    while next:
        #next=input('Wanna see next state?')
        try:

            board = Tablut_connection.read()
            board = board.decode()
            board = json.loads(board)
            turn = board['turn']
            board = board['board']  # array 2D with labels 'EMPTY','BLACK','WHITE','KING','THRONE'
            board = np.array(board)

            out=False

           #print('NEW STATE:\n', board)

            king_indexes = list(zip(*np.where(board == 'KING')))  # king indexes
            ik = king_indexes[0][0]
            jk = king_indexes[0][1]

            if turn == 'WHITE':




                if first_move:
                    move = [[4, 3], [7, 3]]
                    first_move = False
                else:
                    # tic= time()
                    M, M_tiles, M_converted = create_M(board)
                    #print('current M:\n', M)

                    white_positions = list(zip(*np.where(M == white_value)))

                    list_actions = []
                    for indexes in white_positions:
                        list_actions += actions_white(M, indexes[0], indexes[1], 9, 9)
                    # each element in the list_actions has this format: [old_index_i,old_index_j],[new_index_i,new_index_j]
                    # which rapresent the movement to do for a checker

                    king_actions = actions_king(M, ik, jk, 9, 9, escape_value)
                    #print('king actions:\n', king_actions)
                    # list_actions += king_actions
                    list_actions = np.array(list_actions)

                    h_max = -10000
                    list_actions=np.random.permutation(list_actions)
                    king_actions = np.random.permutation(king_actions)

                    for action_king in king_actions:
                        action_king = np.array(action_king)
                        M_action_app_k, M_conv_action_app_k = apply_action(M, M_converted, action_king)
                        # the Matrix given in output from apply action has still the checkers to be eliminated if killed
                        i = action_king[0, 0]
                        j = action_king[0, 1]
                        ik_result = action_king[1, 0]
                        jk_result = action_king[1, 1]

                        h_w = heuristic_king(M_action_app_k, M_tiles, ik_result, jk_result, pass_kill_king, killed_king,h_w_win,
                                             free_winpath, dangerous_neig,king_kills_black,
                                              escape_value, castle_value, empty_camps_value, full_camps_value, white_value,
                                              black_value)
                        if h_w==h_w_win:
                            move=action_king
                            #print('king wins with move:',move)
                            out=True
                            break

                        M_new, M_new_conv = result(M, M_converted, king_indexes, black_value, white_value,
                                                        castle_value, empty_camps_value, full_camps_value, king_value, action_king,
                                                        turn)

                        #print('resulting matrix for the action',action_king)
                        #print(M_new)

                        # black :

                        M_black_conv = conv_matrix(M_new_conv)

                        indices = [[i, x] for i in range(9) for x in range(9) if M_black_conv[i][x] == 'B']
                        illegal_moves = [[0, 3], [0, 4], [0, 5], [1, 4], [8, 3], [8, 4], [8, 5], [7, 4], [3, 0], [4, 0],[5, 0], [4, 1], [3, 8], [4, 8], [5, 8], [4, 7], [4, 4]]



                        list_black_actions = []
                        for j in indices:
                            board_black = bl.convert_board(copy.deepcopy(M_black_conv), illegal_moves,j)

                            list_black_actions = act.black_checker_actions(board_black.tolist(), j, list_black_actions, copy.deepcopy(illegal_moves))

                        h_black_max=-100000
                        for black_action in list_black_actions:


                            new_state = bl.move_on_board(M_black_conv, black_action)
                            h_b = heu.utility(new_state.tolist(), black_action[0], black_action[1][0], black_action[1][1], illegal_moves)

                            #print('heuristic black value for the action',black_action,' : ',h_b)
                            if h_b==black_win:
                                h_black_max=h_b
                                #print('if you do the king action', action_king, ' then the black could do this: ',black_action, 'which has this heuristic: ',h_b)
                                break

                            if  h_b > h_black_max:
                                 h_black_max = h_b
                                 #print('if you do the king action', action_king, ' then the black could do this: ',black_action, 'which has this heuristic: ',h_b)




                        h=h_w - h_black_max
                        if h > h_max:
                            h_max = h
                            move = action_king


                    if not(out):

                        for action in list_actions:
                            #print('action white:', action)
                            M_action_app,M_conv_action_app = apply_action(M, M_converted, action)
                            h_w = heuristic_white(M_action_app,M_tiles, action, ik, jk, pass_kill_king, killed_king, pass_kill, killed,
                                                  free_winpath,white_obstructing, checker_in_escape,dangerous_neig,kill_black,protection_king,white_not_protecting,
                                                escape_value, castle_value, empty_camps_value,
                                                full_camps_value, white_value, black_value, king_value)

                            M_new, M_new_conv = result(M, M_converted, king_indexes, black_value, white_value,
                                                       castle_value, empty_camps_value, full_camps_value, king_value,
                                                       action,
                                                       turn)
                            #print('result matrix after applying the action white',action)
                            #print(M_new)

                            M_black_conv = conv_matrix(M_new_conv)
                            indices = [[i, x] for i in range(9) for x in range(9) if M_black_conv[i][x] == 'B']
                            illegal_moves = [[0, 3], [0, 4], [0, 5], [1, 4], [8, 3], [8, 4], [8, 5], [7, 4], [3, 0], [4, 0],
                                             [5, 0], [4, 1], [3, 8], [4, 8], [5, 8], [4, 7], [4, 4]]



                            list_black_actions = []
                            for j in indices:
                                board_black = bl.convert_board(copy.deepcopy(M_black_conv), illegal_moves,j)
                                list_black_actions = act.black_checker_actions(board_black.tolist(), j, list_black_actions,
                                                                               copy.deepcopy(illegal_moves))

                            h_black_max=-100000
                            for black_action in list_black_actions:
                                new_state = bl.move_on_board(board_black, black_action)
                                h_b = heu.utility(M_black_conv.tolist(), black_action[0], black_action[1][0], black_action[1][1],
                                                  illegal_moves)

                                #print('heuristic black value for the action',black_action,' : ',h_b)

                                if h_b == black_win:
                                    h_black_max = h_b
                                    #print('if you do the white action', action, ' then the black could do this: ',
                                          #black_action, 'which has this heuristic: ',h_b)
                                    break

                                if h_b > h_black_max:
                                    h_black_max = h_b
                                    #print('if you do the white action', action, ' then the black could do this: ',
                                          #black_action, 'which has this heuristic: ',h_b)

                            h = h_w - h_black_max
                            if h > h_max:
                                h_max = h
                                move = action

                move=np.array(move)
                move = [[move[0,0],move[0,1]],[move[1,0],move[1,1]]]
                #print('best action:',move)
                #Mnew, M_conv_new = result(M, M_converted, king_indexes, black_value, white_value, castle_value,
                                          #empty_camps_value,
                                          #full_camps_value, king_value, move, turn)
                #print('M_predicted for the white action ',move, '\n',M)
                #print('M_conv_predicted:','\n',M_conv_new)


                #print("{'from':" + Board_dict[str(move[0])] + ",'to':" + Board_dict[str(move[1])] + ",'turn':'WHITE'}")
                Tablut_connection.send("{'from':"+Board_dict[str(move[0])]+",'to':"+Board_dict[str(move[1])]+",'turn':'WHITE'}")


                # print(time()-tic)  #in seconds.


            #if turn == 'BLACK':
             #    Mnew, M_conv_new = result(M, M_converted, king_indexes, black_value, white_value, castle_value,
                                      #empty_camps_value,
                                      #full_camps_value, king_value, move, turn)
              #   print('M_predicted for the white action ', move, '\n', M)
               #  print('M_conv_predicted:', '\n', M_conv_new)

        except SyntaxError:
            pass


    #prova.send("{'from':'e2','to':'f2','turn':'BLACK'}")
#prova.send("{'from':'e2','to':'f2','turn':'BLACK'}")
Ejemplo n.º 29
0
def branch(key):
    linker = key
    answer = request.form.get("answer")
    path = request.form.get("path")
    column = counter.ColumnList[len(counter.ColumnList) - 1]
    question = counter.QuestionList[len(counter.QuestionList) - 1]

    del PathList[len(PathList) - 1]
    PathList.append(int(path))

    counter.ListMaker(int(answer), column, question)
    count = counter.GetCount()

    if PathList[len(PathList) -
                1] == 1 and counter.QuestionList[len(counter.QuestionList) -
                                                 1] == counter.QuestionList[0]:
        return redirect('https://abunatorroute.azurewebsites.net/return/' +
                        linker)

    elif PathList[len(PathList) - 1] == 1:
        del counter.SQLList[len(counter.SQLList) - 1]
        del counter.SQLList[len(counter.SQLList) - 1]
        del counter.ColumnList[len(counter.ColumnList) - 1]
        del counter.QuestionList[len(counter.QuestionList) - 1]
        return render_template('/main.html',\
        key = linker,\
        question = counter.QuestionList[len(counter.QuestionList)-1])

    elif count == 1:
        resultList = result.result()
        no = resultList[0]
        name = resultList[1]
        dealing = resultList[2]
        rank = resultList[3]
        userNo = linker[0:10]
        result.insert(userNo, name)
        return render_template('/result.html',\
        number = no,\
        name = name,\
        dealing = dealing,\
        rank = rank,\
        key = linker)

    elif count == 0 or len(counter.ColumnList) >= 50:
        return render_template('/unknown.html', key=linker)

    elif count >= 2:
        column = Examine.getCulumn()
        question = Examine.getQuestion(column)
        if not question in counter.QuestionList:
            counter.ColumnList.append(column)
            counter.QuestionList.append(question)
            return render_template('/main.html',\
            key = linker,\
            question = question)
        else:
            while question in counter.QuestionList:
                column = Examine.getCulumn()
                question = Examine.getQuestion(column)
            counter.ColumnList.append(column)
            counter.QuestionList.append(question)
            return render_template('/main.html',\
            key = linker,\
            question = question)
    else:
        return render_template('/error.html',\
        key = linker)
Ejemplo n.º 30
0
from market import *
from market import supports


most_goals = max(map(partition(goals, 'team'), len))
total_goals = len(goals)
first_goal = attr(nth(goals, 0), 'team')

assert supports(result, most_goals)
assert supports(result, total_goals)
assert supports(trend, most_goals)
assert supports(trend, total_goals)
assert supports(selns, most_goals)
assert supports(selns, total_goals)

print result(most_goals, football_state)
print result(most_goals, football_nil)
print selns(most_goals)
print trend(most_goals, football_nil, football_state)
print trend(most_goals, football_nil, football_nil)

print result(total_goals, football_state)
print result(total_goals, football_nil)
print selns(total_goals)
print trend(total_goals, football_nil, football_state)

calculate = gfootball(football_state)
print calculate(most_goals)
print calculate(total_goals)
print calculate(first_goal)
Ejemplo n.º 31
0
    name = 'hayCara'
    columns = [('OpenCV', [1], ['delta4','sum'])]
    properties.append((name, columns))

    rev3 = review(excelOpenCV, properties)
    rev.add(rev3)

    #print rev.agreement('hayCara', ['Viviana', 'Manuela'], '%')
    headers11 = ['Acuerdo']
    headers12 = ['Desacuerdo']
    headers1 = rev.getReviewers('hayCara', names=1)
    headers11.extend(headers1)
    headers12.extend(headers1)
    data11 = rev.agreement('hayCara', ':', '%')
    data12 = rev.disagreement('hayCara', ':', '%')
    res1 = result('Hay al menos una cara', [headers11, headers12], [data11, data12])
    res1.toExcel('hayCara.xls') 
    #print rev.videosOfDisagreement('hayCara', ['EmocionesCIAE_M', 'EmocionesCIAE_R'])
    headers21 = ['Acuerdo']
    headers22 = ['Desacuerdo']
    headers2 = rev.getReviewers('numFaces', names=1)
    headers21.extend(headers2)
    headers22.extend(headers2)
    data21 = rev.agreement('numFaces', ':', '%')
    data22 = rev.disagreement('numFaces', ':', '%')
    res2 =  result('No. de Caras', [headers21, headers22], [data21, data22])
    res2.toExcel('numCaras.xls')

    print rev.videosOfDisagreement('hayCara',['Ximena','OpenCV'])
    def execute_all(self, task, storage=None):
        """
        execute all parametrizations as defined in task object

        Parameters
        ----------

        task -- the task which is broken down into the individual execution points
        storage -- if set to a string, will store the result in that path as JSON. If set to a file, will use that.

        Returns
        -------

        results -- the results of the computation in a list of result objects.
        """
        instruction = task._task_type
        # print "running a total number of points of", task.get_total_points()
        setters = {}
        if instruction == bt.RUN_FG:
            class_n = task.class_name
            time.sleep(1)
            module_n = str(task.module_name)
            module = __import__(module_n, fromlist=[str(class_n)])
            self.block_class = getattr(module, task.class_name)
        elif instruction == bt.RUN_GRC:
            if not hasattr(self, "temp_outdir"):
                self.temp_outdir = tempfile.mkdtemp(suffix="_py", prefix="gr-mtb-")
            temp_grc_file = tempfile.NamedTemporaryFile(suffix=".grc", delete=False, dir=self.temp_outdir)

            temp_grc_file.write(task.grcxml)
            temp_grc_file.close()

            platform = Platform()
            data = platform.parse_flow_graph(temp_grc_file.name)

            fg = platform.get_new_flow_graph()
            fg.import_data(data)
            fg.grc_file_path = os.path.abspath(temp_grc_file.name)
            fg.validate()

            if not fg.is_valid():
                raise StandardError("Compilation error")
            class_n = fg.get_option("id")
            filepath = os.path.join(self.temp_outdir, class_n + ".py")
            gen = platform.get_generator()(fg, filepath)
            gen.write()

            module = imp.load_source(class_n, filepath)
            self.block_class = getattr(module, class_n)
        results = []
        print "processing {:d} points".format(task.get_total_points())
        for inst, values in self.parameterize(task, self.block_class):
            datadict = self._execute(inst, task.sinks)
            results.append(result(values, datadict))
        try:
            if storage and not hasattr(storage, "write"):
                outfile = open(str(storage), "w")
                json.dump([r.to_dict() for r in results], outfile)
                outfile.close()
            elif storage:
                json.dump([r.to_dict() for r in results], storage)
        except IOError as e:
            print e
        return results
Ejemplo n.º 33
0
 def test_main(self):
     self.assertEqual(result("./testCases/main.txt"), "1 2 4 5 3")
Ejemplo n.º 34
0
def method_405(e):
    return result.result(405,
                         "http method is not allowed for the requested URL")
Ejemplo n.º 35
0
 def close(self, status=0):
     self.lib.result(status)
     result(self.lib)
Ejemplo n.º 36
0
def main():
  positions = [1,10,100,1000]
  num_trials = 10000
  result(positions, num_trials)
Ejemplo n.º 37
0
"""
Author: Anthony C. Emmanuel
Title: Simultaneous Equation Solver
Version: 1
Language: Python 3.6
Date: 02-08-2017
License: GPL Latest"""

import result as rs
import compute as cp
import inputs as ip
import numpy as np

print(
    "Simultaneous Equation Solver\nAuthor:Anthony C. Emmanuel\nDate:02-08-2017\n"
)

while True:
    getva = ip.inputs()
    a, b = getva
    z = cp.compute(a, b)
    print("\nThe result: \n")
    rs.result(z)
    print("\n")
Ejemplo n.º 38
0
		# 	day = int(raw_input("Enter the day : "))
		# 	df = download_data(sym,day)
		# 	df = change_adder(df)
		# 	make_oscillator(df)
		# 	continue

		if(x==7):
			kite_init()
			continue

		if(x==8):
			start_ticking()
			continue

		if(x==9):
			result()
			continue


		if(x==11):
			r1 = int(input("\nEnter start for range : "))
			r2 = int(input("Enter end for range : "))
			if(r1 == 0): new = True
			else: new = False
			for i in range(r1,r2):
				df = download_data(all_stocks.iat[i,0],1)
				# print df
				if(len(df)<=75):
					add_to_blacklist(all_stocks[i:i+1],new)
					new = False
					print all_stocks[i:i+1]+"  "+str(len(df))
Ejemplo n.º 39
0
    def init_ui(self):
        # 添加栅格布局
        # 布局只能添加到Widget里
        # 所以先添加一个Widget
        grid = QGridLayout()
        # 这个叫widget的是主widget。左侧为一列功能键,右侧为页面
        self.widget = QWidget()
        self.widget.setObjectName("main")
        self.widget.setLayout(grid)
        self.setCentralWidget(self.widget)
        grid.setSpacing(15)

        # 这里是左侧的一堆功能键
        self.btn_welcome = QPushButton(qtawesome.icon('fa.sellsy'), '欢迎光临',
                                       self)
        self.btn_welcome.clicked[bool].connect(self.button_clicked)
        self.btn_welcome.setObjectName("left")
        self.btn_input = QPushButton(qtawesome.icon('fa.music'), '期权参数', self)
        self.btn_input.clicked[bool].connect(self.button_clicked)
        self.btn_input.setObjectName("left")
        self.btn_result = QPushButton(qtawesome.icon('fa.download'), '查看价格',
                                      self)
        self.btn_result.clicked[bool].connect(self.button_clicked)
        self.btn_result.setObjectName("left")
        self.btn_result.setEnabled(False)
        self.btn_list = QPushButton(qtawesome.icon('fa.film'), '算法一览', self)
        self.btn_list.clicked[bool].connect(self.button_clicked)
        self.btn_list.setObjectName("left")
        self.btn_about = QPushButton(qtawesome.icon('fa.star'), '关于我们', self)
        self.btn_about.clicked[bool].connect(self.button_clicked)
        self.btn_about.setObjectName("left")
        self.btn_quit = QPushButton(qtawesome.icon('fa.question'), '退出系统',
                                    self)
        self.btn_quit.clicked[bool].connect(self.button_clicked)
        self.btn_quit.setObjectName("left")
        grid.addWidget(self.btn_welcome, 4, 0)
        grid.addWidget(self.btn_input, 5, 0)
        grid.addWidget(self.btn_result, 6, 0)
        grid.addWidget(self.btn_list, 7, 0)
        grid.addWidget(self.btn_about, 8, 0)
        grid.addWidget(self.btn_quit, 9, 0)

        # 这里是每个功能键的页面
        self.page_welcome = page.page(grid, self)
        welcome.welcome(self.page_welcome)
        self.page_result = page.page(grid, self)
        result.result(self.page_result)
        self.page_list = page.page(grid, self)
        list.list(self.page_list)
        self.page_about = page.page(grid, self)
        about.about(self.page_about)
        self.page_quit = page.page(grid, self)
        quit.quit(self.page_quit)
        self.page_input = page.page(grid, self)
        input.input(self.page_input)
        self.page_welcome.show(self)

        # 给布局添加上左侧功能键和LOGO
        logo = QLabel(self)
        directory = "img/logo2.png"
        pix = QPixmap(directory)
        logo.setPixmap(pix)
        grid.addWidget(logo, 1, 0, 3, 1)

        # 设置标题logo
        self.setWindowIcon(QIcon(directory))
        # 居中并绘制
        self.resize(1280, 720)
        self.center()
        self.setWindowTitle('MiniSQL')
        # 导入qss样式
        directory = "style.qss"
        with open(directory, 'r') as f:
            qss_style = f.read()
        self.setStyleSheet(qss_style)
        self.show()
        self.button_change(self.btn_welcome)
Ejemplo n.º 40
0
    m = re.search(r'>([a-zA-Z0-9]*?)</span>', content)
    if m:
        return m.group(1)
    else:
        return 'Not Found'


def md5_crack(md5, result):
    result.bruteforce_md5['www.2d5.net'] = md5_2d5(md5)
    result.bruteforce_md5['www.somd5.com'] = md5_somd5(md5)
    result.bruteforce_md5['www.md5.cc'] = md5_md5cc(md5)

    #print md5_2d5(md5)
    #print md5_somd5(md5)
    #print md5_md5cc(md5)


if __name__ == '__main__':
    r = result.result()
    #process = hydra('10.1.10.115', 'ssh')
    #while 1:
    #    status = hydra_getstatus(process)
    #    print status
    #    if status == 'Done':
    #        break
    md5_crack('47BCE5C74F589F4867DBD57E9CA9F8E8', r)
    for key in r.bruteforce_md5.keys():
        print key + '|' + r.bruteforce_md5[key]
    #bruteforce_wordpress('http://jwjcc.bfsu.edu.cn/wp-login.php', 'jwjcc', r)
    #print r.bruteforce_wordpress
Ejemplo n.º 41
0
def hello_world():
    test = result.result(200, "ping successful",
                         "Welcome to restful api server.")
    return str(test[1])