Beispiel #1
0
    def settInnNode(self, node):
        nyttRack = Rack()

        # Lager et nytt rack om det ikke er noen racks i regneklyngen.
        if self.antRacks() == 0:
            self._regneklynge.append(nyttRack)

        # lastRack blir lik det siste rack objektet i self._regneklynge.
        lastRack = self._regneklynge[-1]

        # Sjekker først om nodene i lastRack er lik maksimum noder per rack.
        # Hvis ja, legger jeg til et rack-objekt i regneklynge og setter inn et
        # node-objekt.
        if lastRack.getAntNoder() == self._noderPerRack:
            self._regneklynge.append(nyttRack)
            nyttRack.settInn(node)

        # Deretter sjekker jeg om nodene i lastRack er færre enn maksimum noder
        # per rack.
        # Hvis ja, legger jeg til et node-objekt i lastRack.
        elif lastRack.getAntNoder() < self._noderPerRack:
            lastRack.settInn(node)

        # Til slutt, sjekker jeg om nodene i lastRack er flere enn maksimum
        # noder per rack.
        # Hvis ja, legger jeg til et rack-objekt i regneklynge og setter inn et
        # node-objekt i lastRack.
        elif lastRack.getAntNoder() > self._noderPerRack:
            self._regneklynge.append(nyttRack)
            lastRack.settInn(node)
Beispiel #2
0
 def create(source_id,
            destination_id,
            name,
            panel_type,
            num_of_ports,
            connector,
            height=-1):
     source_rack = Rack.find_one(by_id=source_id)
     destination_rack = Rack.find_one(by_id=destination_id)
     if not source_rack:
         log("Source rack not found")
         return False
     if not destination_rack:
         log("Destination rack not found")
         return False
     json_props = dict(id=uuid.uuid4(),
                       name=name,
                       panel_type=panel_type,
                       num_of_ports=num_of_ports,
                       connector=connector,
                       status="active",
                       height=height)
     source_rack_props = "{ id: \"" + str(source_id) + "\" }"
     destination_rack_props = "{ id: \"" + str(destination_id) + "\" }"
     cypher_query = """
     MATCH (a:Rack {}), (b:Rack {}) CREATE (a)-[c:{} {}]->(b) RETURN c
     """.format(source_rack_props, destination_rack_props,
                panel_type.upper(), json_to_properties(json_props))
     return db.run(cypher_query).evaluate()
Beispiel #3
0
 def test_simple(self):
     unsorted = [10, 40, 11, 59, 0, 1]
     rack = Rack(60)
     for i in range(len(unsorted)):
         rack.add(unsorted[i])
         correct = unsorted[:i+1]
         correct.sort()
         self.assertEqual(correct,rack.balls())
Beispiel #4
0
 def __init__(self, id:int):
     self.screen_w, self.screen_h = Play.screen.get_size()
     self.recipe_id = id
     self.__set_level()
     self.counter = Counter(self.screen_w, self.screen_h, (0.00, 0.7, 1, 1))
     self.rack = Rack(self.screen_w, self.screen_h, self.recipe_id)
     self.label = TextBox(self.screen_w // 2, 20, "wybierz produkty według listy i przeciągnij je na ladę",
                          color=(200, 200, 200))
Beispiel #5
0
 def settInnNode(self, node):
     if len(self._listeRacks) == 0:
         self._listeRacks.append(Rack())
         self._listeRacks[-1].settInn(node)
     elif self._noderPerRack > self._listeRacks[-1].getAntNoder():
         self._listeRacks[-1].settInn(node)
     else:
         self._listeRacks.append(Rack())
         self._listeRacks[-1].settInn(node)
Beispiel #6
0
 def settInnNode(self, node):
     # sjekker hvis det er ledig plass inn i rack og hvis ikke oppretter jeg en ny
     if len(self._rack) == 0:
         self._rack.append(Rack())
         self._rack[0].settInn(node)
     else:
         for rack in self._rack:
             if rack.getAntNoder() < self._noderPerRack:
                 rack.settInn(node)
             elif self._rack.index(rack) == len(self._rack) - 1:
                 self._rack.append(Rack())
Beispiel #7
0
    def __init__(self, name, game, score=0, rack=None):
        """creates a player with a name, if name starts with 'AI', create
           an AI bot, game is the current game to add player to"""

        self.name = name
        self.game = game
        self.score = score
        self.isAI = False
        if rack == None:
            self.rack = Rack(game.bag)
        else:
            self.rack = Rack(game.bag, rack)
        self.__repr__ = self.name
Beispiel #8
0
    def add_node(self, node):
        # Add a new rack if other racks are full
        if not self.racks[self.rack_index].has_capacity():
            self.racks.append(Rack(self.nodes_per_rack))
            self.rack_index += 1

        self.racks[self.rack_index].add_node(node)
Beispiel #9
0
    def __init__(self, fabric_config_dict):
        if fabric_config_dict.has_key("fabric"):
            for key in self.required_keys:
                if not fabric_config_dict['fabric'].has_key(key):
                    util.log_error_and_exit(
                        "Fabric configuration file is missing " + key)
            try:
                self.edge_facing_capacity = int(
                    fabric_config_dict["fabric"]["edge_facing_capacity"])
            except ValueError:
                util.log_error_and_exit(
                    "Invalid value found for total edge facing capacity in provided fabric configuration"
                )

            for rack in fabric_config_dict['fabric']['racks']:
                rack['rack_id'] = self.rack_id
                self.total_racks += rack['rack_count']
                self.racks.append(Rack(rack))
                self.rack_facing_capacity += self.racks[
                    self.
                    rack_id].total_required_fabric_network_capacity * self.racks[
                        self.rack_id].rack_count
                self.rack_id += 1
        self.network_addressing = Network_addressing(
            fabric_config_dict['fabric']['addressing'])
        print "Total rack facing capacity required: " + str(
            self.rack_facing_capacity)
        print "Total edge facing capacity required: " + str(
            self.edge_facing_capacity)
Beispiel #10
0
def generateThreeLayer(k):
	# initialize essential parameters 
	num_ports_per_switch = k	# number of ports per switch
	num_pod = k					# number of pods
	num_servers = int(k/2)			# number of hosts under a ToR switch 
	num_tor = int(k/2)				# number of ToR switches in a pod 
	num_agg = int(k/2)				# number of aggregation switches in a pod 
	num_core = int((k**2)/4)			# number of core switches 
	total_servers = int((k**3)/4)	# number of total servers 

	# initialize component generation 
	num_racks = num_pod * num_tor
	list_of_racks = []
	cpu_cores = 16
	for i in range(num_racks):
		rack = Rack(str(i))
		for j in range(num_servers):
			server = Server(i*(num_servers)+j,"server"+str(i)+"-"+str(j), cpu_cores)
			rack.accumulate(server)
		list_of_racks.append(rack)

	list_of_tors = []
	for i in range(num_tor * num_pod):
		tor = Switch("ToR"+str(i), "ToR", k)
		list_of_tors.append(tor)

	list_of_agg= []
	for i in range(num_agg * num_pod):
		agg = Switch("Agg"+ str(i), "Agg", k)
		list_of_agg.append(agg)

	list_of_core = []
	for i in range(num_core):
		core = Switch("Core"+str(i), "Core", k)
		list_of_core.append(core)

	list_of_links = []
	num_links = int(3 * (k**3) / 4)
	capacity = 1024 	# Mbits
	delay = 1			# ms
	for i in range(num_links):
		link = Link("link"+str(i), capacity, delay)
		list_of_links.append(link)

	return list_of_racks, list_of_tors, list_of_agg, list_of_core, list_of_links
Beispiel #11
0
 def settInnNode(self, node):
     for j in range(len(self._rk)):
         if self._rk[j].getAntNoder() < self.npr:
             self._rk[j].settInn(node)
             break
         elif j == len(
                 self._rk) - 1 and self._rk[j].getAntNoder() >= self.npr:
             self._rk.append(Rack())
             self._rk[-1].settInn(node)
Beispiel #12
0
def rack(id=None):
    if request.method == "GET":
        if id:
            return jsonify(Rack.find(by_id=id))
        return jsonify(Rack.free_find())
    if request.method == "POST":
        if request.headers.get('Content-Type', '') == "application/json":
            received_data = request.json
        else:
            received_data = dict(request.form)
            for key in received_data:
                if type(received_data[key]) == list and len(
                        received_data[key]) == 1:
                    received_data[key] = received_data[key][0]
                else:
                    return jsonify(error="Unable to parse json"), 400
        mandatory_fields = ["name", "site", "building", "room"]
        if all(elem in received_data.keys() for elem in mandatory_fields):
            return jsonify(Rack.create(**received_data)), 201
        else:
            return jsonify(error="Mandatory keys are missing",
                           mandatory_fields=mandatory_fields), 400
    if request.method == "PUT":
        if request.headers.get('Content-Type', '') == "application/json":
            received_data = request.json
        else:
            received_data = dict(request.form)
            for key in received_data:
                if type(received_data[key]) == list and len(
                        received_data[key]) == 1:
                    received_data[key] = received_data[key][0]
                else:
                    return jsonify(error="Unable to parse json"), 400
        return jsonify(
            Rack.update(rack_id=id,
                        name=received_data.get("name", None),
                        site=received_data.get("site", None),
                        building=received_data.get("building", None),
                        room=received_data.get("room", None))), 200
    if request.method == "DELETE":
        if id:
            return jsonify(Rack.delete(by_id=id))
        else:
            return jsonify(error="Must provide ID for DELETE method"), 400
Beispiel #13
0
 def find_all_between_racks(rack1_id, rack2_id):
     if not Rack.find_one(by_id=rack1_id):
         log("Rack 1 not found")
         return False
     if not Rack.find_one(by_id=rack2_id):
         log("Rack 2 not found")
         return False
     cypher_query = """
     MATCH (a)-[r]->(b) WHERE a.id=\"{}\" AND b.id=\"{}\" return r
     """.format(rack1_id, rack2_id)
     r1 = db.run(cypher_query).data()
     cypher_query = """
     MATCH (a)-[r]->(b) WHERE a.id=\"{}\" AND b.id=\"{}\" return r
     """.format(rack2_id, rack1_id)
     r2 = db.run(cypher_query).data()
     if r1 and r2:
         return [i["r"] for i in r1] + [i["r"] for i in r2]
     if r1:
         return [i["r"] for i in r1]
     return [i["r"] for i in r2]
Beispiel #14
0
 def leggTilNode(self, prosessorerINode, minneGBINode):
     #Opprett nytt Node-objekt m/gjevne verdiar
     node = Node(prosessorerINode, minneGBINode)
     #sett ingen racks er ledige
     ledigeRacks = False
     #For kvart element i lista _racks...
     for i in self._racks:
         #Viss elementet, racket, har ledig plass...
         if i.sjekkLedigPlass():
             #Legg til noden i racket
             i.leggTilNode(node)
             #sett at det er ledige racks
             ledigeRacks = True
     #Om ingen racks er ledige...
     if not ledigeRacks:
         #Lag eit nytt rack m/kapasitet _noderPerRack
         rack = Rack(self._noderPerRack)
         #Legg det nye racket inn i lista _racks
         self._racks.append(rack)
         #Legg noden inn i det nye racket
         rack.leggTilNode(node)
Beispiel #15
0
def results(tiles, dd, t, rows):

    rack = Rack(tiles, dd, t)
    cutoffs = {0: 15, 1: 10, 2: 7, 3: 0}

    time_0 = time.time()

    if rack.num_letters >= cutoffs[min(rack.num_blanks, 3)]:
        res = rack.frequency_solve()
        solver = 'F'
    else:
        res = rack.permute_solve()
        solver = 'P'

    time_1 = time.time()
    time_ms = 1000 * (time_1 - time_0)

    if len(res) < 1:
        print("\nNo valid words found. ({}-Solve runtime: {:.2f} ms)".format(
            solver, time_ms))
        return

    entries = []  # cells of the table
    lines = [""] * rows  # rows of the table
    pad_wc, pad_bc = 4, 8  # padding within column, padding between columns
    shift = pad_wc + len(res[0])

    for play in res:
        spaces = shift - len(play) if len(play) < 10 else shift - 1 - len(play)
        entries.append(play + (" " * spaces) + str(len(play)))
    print("\nLongest words: ({}-Solve runtime: {:.2f} ms)".format(
        solver, time_ms))

    for i, entry in enumerate(entries):
        spaces = " " * pad_bc if i >= rows else ""
        lines[i % rows] += spaces + entry

    for line in lines:
        if line:
            print(line)
Beispiel #16
0
def generateTwoLayer(num_of_servers, num_of_racks, num_of_core):

	list_of_racks = []
	cpu_cores = 1
	total_ram = 1.0
	total_storage = 1.0
	for i in range(num_of_racks):
		rack = Rack(str(i))
		for j in range(num_of_servers):
			server = Server(i*(num_of_servers)+j,"server"+str(i)+"-"+str(j), cpu_cores, total_ram, total_storage)
			server.tor = "ToR"+str(i)
			rack.accumulate(server)
		list_of_racks.append(rack)

	list_of_tors = []
	for i in range(num_of_racks):
		tor = Switch("ToR"+str(i), "ToR", num_of_servers+num_of_core)
		list_of_tors.append(tor)

	list_of_core = []
	for i in range(num_of_core):
		core = Switch("Core"+str(i), "Core", num_of_racks)
		list_of_core.append(core)

	list_of_links = []
	num_of_tor_links = int(num_of_servers*num_of_racks)
	capacity_tor = 1000 # Mbits
	num_of_other_links = int(num_of_racks*num_of_core)
	capacity_other = 10000 # Mbits
	delay = 90
	for i in range(num_of_tor_links):
		link = Link("link"+str(i), capacity_tor, delay)
		list_of_links.append(link)
	for i in range(num_of_other_links):
		link = Link("link"+str(num_of_tor_links+i), capacity_other, delay)
		list_of_links.append(link)

	return list_of_racks, list_of_tors, list_of_core, list_of_links
Beispiel #17
0
    def settInnNode(self, node):
        added = False

        if len(self._klynge) < 1:
            etRack = Rack()
            etRack.settInn(node)
            self._klynge.append(etRack)
        else:
            for rack in self._klynge:
                if rack.getAntNoder() < self._noderPerRack:
                    rack.settInn(node)
                    added = True
            if added == False:
                etRack = Rack()
                etRack.settInn(node)
                self._klynge.append(etRack)
Beispiel #18
0
class Level(Play):

    def __init__(self, id:int):
        self.screen_w, self.screen_h = Play.screen.get_size()
        self.recipe_id = id
        self.__set_level()
        self.counter = Counter(self.screen_w, self.screen_h, (0.00, 0.7, 1, 1))
        self.rack = Rack(self.screen_w, self.screen_h, self.recipe_id)
        self.label = TextBox(self.screen_w // 2, 20, "wybierz produkty według listy i przeciągnij je na ladę",
                             color=(200, 200, 200))

    def __set_level(self):
        self.recipe = Play.data.recipes[self.recipe_id]
        self.recipe.set_price()

    def __resize(self):
        self.rack.resize(self.screen_w, self.screen_h)
        self.counter.resize(self.screen_w, self.screen_h)

    def run(self):
        self.recipe.check()
        product = None
        running = True
        while running:
            Play.screen.fill((255, 255, 230))
            self.counter.draw()
            self.rack.draw()
            for event in pg.event.get():
                if event.type == pg.VIDEORESIZE:
                    try:
                        self.screen_w, self.screen_h = event.size
                        self.__resize()
                    except:
                        pass
                elif event.type == pg.QUIT:
                    quit()
                elif event.type == pg.KEYDOWN:
                    if event.key == pg.K_ESCAPE:
                        return
                elif event.type == pg.MOUSEBUTTONDOWN:
                    product = self.rack.click(pos=pg.mouse.get_pos())
                    if product is not None and product is not False:
                        self.counter.test_product(product, lay=False)
                elif event.type == pg.MOUSEBUTTONUP:
                    if product is not None and product is not False:
                        self.counter.test_product(product, lay=True)
                        product = None
                        self.recipe.check()
                if self.rack.click(event=event) is False:
                    return
            if product is not None and product is not False:
               product.current_image.move(pg.mouse.get_pos())
               product.current_image.draw()

            self.label.draw()
            pg.display.update()
            self.clock.tick(self.FPS)
Beispiel #19
0
    def settInnNode(self, node):
        """
		Plasserer en node inn i et rack med ledig plass, eller i et nytt
		Tar parameter node som er referanse til noden som skal settes inn i datastrukturen
		"""
        # hvis siste index(rack objekt) har liste som har ikke plass.
        #(Den kaller paa metode for rack getAntNoder som sjekker hvor mange noder er i rack)
        # Og hvis den lik grense til hvor mange noder det er per Rack. Saa lages det ny rack objekt
        # Som har ny liste for noder. Deretter velger den igjen siste objekt i listeRack (dvs. den nyeste
        # objekt med tumt liste) Og legger til node

        # Men hvis siste rack objekt i _listeRack har plass i sin liste med noder
        # saa settes node objekt i den rack objekt liste
        if self._listeRacs[-1].getAntNoder() == self._noderPerRack:
            self._listeRacs.append(Rack())
            self._listeRacs[-1].settInn(node)
        elif self._listeRacs[-1].getAntNoder() < self._noderPerRack:
            self._listeRacs[-1].settInn(node)
Beispiel #20
0
 def __init__(self, clusterfile):
     #Tar inn txt fila med spisfikasjonene
     self._allNodes = clusterfile
     #Lager en liste som skal inneholde alle racks, den starter med å lage et rack Objekt
     self._listOfRacks = []
     self._counter = 0
     #Går igjennom alle linjene i tekstfila
     for line in self._allNodes:
         #Sjekker om det er første linje, da den setter max noder i en rack
         if self._counter == 0:
             self._maxNodes = int(line)
             #Lager en liste som skal inneholde alle racks, den starter med å lage et rack Objekt
             self._listOfRacks.append(Rack(self._maxNodes))
             #Setter counter = 1 så den kjører else: for resten av fila
             self._counter = 1
         else:
             #Setter nodeMemoProc som en liste med [node, minne, prosessorer]
             nodeMemoProc = line.split()
             for i in range(int(nodeMemoProc[0])):
                 self.addNode(int(nodeMemoProc[1]), int(nodeMemoProc[2]))
Beispiel #21
0
class Player(object):
    """Player of Scrabble"""

    def __init__(self, name, game, score=0, rack=None):
        """creates a player with a name, if name starts with 'AI', create
           an AI bot, game is the current game to add player to"""

        self.name = name
        self.game = game
        self.score = score
        self.isAI = False
        if rack == None:
            self.rack = Rack(game.bag)
        else:
            self.rack = Rack(game.bag, rack)
        self.__repr__ = self.name

    def display(self):
        """displays player's name and score"""

        print self.name + ": " + str(self.score)
        sys.stdout.flush()

    def display_rack(self):
        """displays player's rack"""

        self.rack.display()

    def swap(self, letters):
        """swaps letters in a player's rack"""

        self.rack.swap(letters)

    def shuffle(self):
        """shuffles letters in a player's rack"""

        self.rack.shuffle()

    def get_score(self):
        """returns player's current score"""

        return self.score

    def get_name(self):
        """returns a player's name"""

        return self.name
Beispiel #22
0
    def __init__(self, file_name):
        self.nodes_per_rack = 0
        self.racks = []

        # =============================================
        # Til deg som retter:
        # =============================================
        # Spar deg selv og hopp over denne kreften her!
        # c':
        # ---------------------------------------------
        cluster_file = open(file_name)
        for line in cluster_file:
            if not line.startswith("#") and line.strip():
                line = line.split()
                if len(line) == 1:
                    self.nodes_per_rack = int(line[0])
                    self.racks.append(Rack(self.nodes_per_rack))
                    self.rack_index = 0
                if len(line) == 3:
                    for i in range(int(line[0])):
                        self.add_node(Node(int(line[1]), int(line[2])))
        cluster_file.close()
Beispiel #23
0
    def __init__(self, filnavn):
        """
		Oppretter tom regneklynge for racks
		Leser data om regneklynge fra fil, bygger datastrukturen
		Tar parameter filnavn, som er navn til fil med data for regneklyngen
		"""
        self._listeRacs = [
        ]  # liste med alle racks objekter i regneklynge objekt
        # Her appender jeg rack objekt, for aa lage den forste rack objekt
        # Det hjelper aa lage looper videre, som sjekker om det er nok plass i rack liste.
        self._listeRacs.append(Rack())
        fil = open(filnavn)
        # For loopemn som gaar gjennom alle linjer i fil
        self._noderPerRack = int(fil.readline())
        for linje in fil:
            biter = linje.strip().split()  # liste med alle deler i linje
            # loopen som gaar gjennom antall noder (biter[0] for antall noder)
            for i in range(int(biter[0])):
                # node objekt lik Node(minne, prosessorer)  - biter[1],biter[2] tok jeg fra liste som ble lagt tidligere
                node = Node(int(biter[1]), int(biter[2]))
                self.settInnNode(
                    node
                )  # bruker metode settInnNode som jobber med de node objektene videre
Beispiel #24
0
def handle_config(cmd_parts):
    global hardware, hardware_configs
    global images, image_configs
    global flavors, flavor_configs
    global curr_command, racks, instances, instance_on_server, server_instances, machines_on_racks
    global hardware_configs_fixed
    if (len(cmd_parts) != 4):
        sys.stderr.write("ERROR: Invalid command.")
        logger.info(curr_command + ": Failure")
        return

    if (cmd_parts[2] == "--hardware"):
        file = cmd_parts[3]
        my_file = "../p1_config/" + file

        if (os.path.exists(my_file)):

            if hardware:
                hardware_configs = {}
                racks = {}
                instances = {}
                instance_on_server = {}
                server_instances = {}
                machines_on_racks = {}
                racks = {}
                instances = {}
                instance_on_server = {}
                server_instances = {}
                machines_on_racks = {}
                hardware_configs_fixed = {}

            hardware = True

            with open(my_file) as f:
                lines = f.readlines()

            num_racks = int(lines[0])

            for x in range(1, num_racks + 1):
                rack = lines[x].split(" ")
                r = Rack(rack[0], rack[1])
                racks[rack[0]] = r

            num_configs = int(lines[num_racks + 1])

            for x in range(num_racks + 2, num_racks + num_configs + 2):
                cfg = lines[x].split(" ")
                h = NewHardware(cfg[0], cfg[1], cfg[2], cfg[3], cfg[4], cfg[5])
                hf = NewHardware(cfg[0], cfg[1], cfg[2], cfg[3], cfg[4],
                                 cfg[5])
                hardware_configs[cfg[0]] = h
                hardware_configs_fixed[cfg[0]] = hf

                if machines_on_racks.get(cfg[1]) == None:
                    machines_on_racks[cfg[1]] = []
                machines_on_racks[cfg[1]].append(cfg[0])

            sys.stdout.write(
                str(len(hardware_configs)) +
                ' physical servers now available.' + "\n")
            logger.info(curr_command + ": Success")

        else:
            sys.stderr.write("ERROR: File you specified does not exist." +
                             "\n")
            logger.info(curr_command + ": Failure")

    elif (cmd_parts[2] == "--images"):
        file = cmd_parts[3]
        my_file = "../p1_config/" + file

        if (os.path.exists(my_file)):

            images = True

            with open(my_file) as f:
                lines = f.readlines()

            num_configs = int(lines[0])

            for x in range(1, num_configs + 1):
                cfg = lines[x].split(" ")
                img = NewImage(cfg[0], cfg[1], cfg[2])
                image_configs[cfg[0]] = img

            sys.stdout.write(
                str(len(image_configs)) + ' images now available.' + "\n")
            logger.info(curr_command + ": Success")

        else:
            sys.stderr.write("ERROR: File you specified does not exist." +
                             "\n")
            logger.info(curr_command + ": Failure")

    elif (cmd_parts[2] == "--flavors"):
        file = cmd_parts[3]
        my_file = "../p1_config/" + file

        if (os.path.exists(my_file)):

            flavors = True

            with open(my_file) as f:
                lines = f.readlines()

            num_configs = int(lines[0])

            for x in range(1, num_configs + 1):
                cfg = lines[x].split(' ')
                flv = Flavor(cfg[0], cfg[1], cfg[2], cfg[3])
                flavor_configs[cfg[0]] = flv

            sys.stdout.write(
                str(len(flavor_configs)) + ' VM flavors now available.' + "\n")
            logger.info(curr_command + ": Success")
        else:
            sys.stderr.write("ERROR: File you specified does not exist." +
                             "\n")
            logger.info(curr_command + ": Failure")

    else:
        sys.stderr.write("ERROR: Invalid command." + "\n")
        logger.info(curr_command + ": Failure")
Beispiel #25
0
 def newRack(self):
     self._listOfRacks.append(Rack(self._maxNodes))
Beispiel #26
0
	def __init__(self, maksNoder):
		self._rackListe = []
		self._maksNoder = maksNoder
		self._rackListe.append(Rack(self._maksNoder))
Beispiel #27
0
	def leggTilNode(self, minne, prosessorer):
		if self._rackListe[-1].ledigPlass():
			self._rackListe[-1].leggTilNode(minne, prosessorer)
		else:
			self._rackListe.append(Rack(self._maksNoder))
			self._rackListe[-1].leggTilNode(minne, prosessorer)
Beispiel #28
0
 def __init__(self, noderPerRack):
     self._rk = [Rack()]
     self.npr = noderPerRack  # @param noderPerRack max antall noder som kan plasseres i et rack
Beispiel #29
0
import flask
import settings


#Views
from main import Main
from rack import Rack

app = flask.Flask(__name__)
app.secret_key = settings.secret_key


#Routes
app.add_url_rule('/',
                view_func=Main.as_view('main'),
                methods=['GET'])
app.add_url_rule('/<page>/',
                view_func=Main.as_view('main'),
                methods=['GET'])
app.add_url_rule('/rack',
                view_func=Rack.as_view('rack'),
                methods=['GET', 'POST'])

@app.errorhandler(404)
def page_not_found(error):
     return flask.render_template('404.html'), 404

app.debug = True
app.run()
Beispiel #30
0
def solve_tiles(tiles, dd, pref, suff, substring, includes, t=100):
    time_0 = time.time()

    def get_runtime():
        return round(1000 * (time.time() - time_0), 2)

    for c in tiles:
        if not (65 <= ord(c) <= 90) and not (97 <= ord(c) <= 122) and c != '?':
            return ['Invalid Input', get_runtime(), []]
    for x in [pref, suff, substring]:
        for c in x:
            if not (65 <= ord(c) <= 90) and not (97 <= ord(c) <=
                                                 122) and c != '-':
                return ['Invalid Input', get_runtime(), []]
    for c in includes:
        if not (65 <= ord(c) <= 90) and not (97 <= ord(c) <= 122):
            return ['Invalid Input', get_runtime(), []]

    for c in pref + suff + substring:
        if c != '-':
            tiles += c

    rack = Rack(tiles, dd, t, pref, suff, substring, includes)
    cutoffs = {0: 15, 1: 10, 2: 7, 3: 0}

    if rack.num_letters >= cutoffs[min(rack.num_blanks, 3)]:
        res = rack.frequency_solve()
        solver = 'F'
    else:
        res = rack.permute_solve()
        solver = 'P'

    if len(res) < 1:
        return ['No Valid Words', get_runtime(), []]

    def blanks(s, r):
        nb = r.num_blanks
        pool = Counter(r.tiles + r.pref + r.suff + r.substring)
        b = ''
        res = []
        for c in s:
            if c not in pool:
                b += c
            else:
                if pool[c] > 0:
                    pool[c] -= 1
                else:
                    b += c
        j = 0
        for i in range(len(s)):
            if j + 1 > len(b):
                return res
            if s[i] == b[j]:
                j += 1
                res.append(i)
        return res

    return [
        '{}-Solve'.format(solver),
        get_runtime(),
        [[word, len(word), set(blanks(word, rack))] for word in res[:t]]
    ]