def main(): while True: clear() choice = get_user_choice(main_menu) if choice == 1: pet_name = input("What would you like to name your pet? ") print("Please choose the type of pet:") type_choice = get_user_choice(adoption_menu) if type_choice == 1: pets.append(Pet(pet_name)) elif type_choice == 2: pets.append(CuddlyPet(pet_name)) print("You now have %d pets" % len(pets)) if choice == 2: for pet in pets: pet.get_love() if choice == 3: for pet in pets: pet.eat_food() if choice == 4: for pet in pets: pet.get_toy(Toy()) if choice == 5: for pet in pets: print(pet) input("") if choice == 6: for pet in pets: pet.be_alive() if choice == 7: clear() print("Thanks for adopting and taking care of your pet.") return False
def main(): while True: choice = get_user_choice(main_menu) if choice == 1: print("Please choose the type of pet:") type_choice = get_user_choice(adoption_menu) if type_choice == 1: pets.append(Pet(pet_name)) elif type_choice == 2: pets.append(CuddlyPet(pet_name)) print("You now have %d pets" % len(pets)) if choice == 2: for pet in pets: pet.get_love() if choice == 3: for pet in pets: pet.eat_food() if choice == 4: for pet in pets: print(pet) if choice == 5: for pet in pets: pet.get_toy(Toy()) if choice == 6: # Pet levels naturally lower. for pet in pets: pet.be_alive()
def get_toy(self): """Get all the actual toy in clearance.""" self.Logger.debug("Start to get the toys") temp = {} extract = BadDragonApi(self.Logger) self.actualise_toy_name() self.Logger.debug("Start to parse the toys") for i in range(0, extract.number_of_toy()): toy = extract.get_toy(i) if toy['sku'].lower() in self.Options.ProductName: temp[toy['id']] = Toy( self.option_from_type(toy['sku'], self.Options.ProductName), self.Options.ProductType[toy['sku'].lower()], self.option_from_type(toy['size'], self.Options.SizeOptions), self.option_from_type(toy['colorTheme']['name'] if toy['colorTheme'] else None, self.Options.ColorOptions), self.option_from_type(toy['firmness'], self.Options.FirmnessOptions), self.option_from_type(toy['cumtube'], self.Options.CumTubValues), self.option_from_type(toy['suction_cup'], self.Options.SuctionCupValues), self.option_from_type(toy['is_flop'], self.Options.FlopOption), toy['external_flop_reason'], toy['id']) else: self.Logger.warning("Error {} is not in the dictionary".format(toy['sku'])) self.Logger.info("Get {} toy in stock".format(len(temp))) return temp
def play_elf(self, output, elf_object, toy_id, toy_duration, work_start_time=None): """ :param elf_id: Elf id :param toy_id: Toy_Id :param work_start_time: Minute since Jan, 2014 :return: """ hrs = Hours(); ref_time = datetime.datetime(2014, 1, 1, 0, 0); if work_start_time == None: work_start_time = elf_object.next_available_time; elf_object.next_available_time, work_duration = \ self.assign_elf_to_toy(work_start_time, elf_object, toy_duration, hrs); elf_object.update_elf(hrs, Toy(toy_id, '2014 01 01 01 01' ,toy_duration), work_start_time, work_duration); #Every toy has default arrival time(irrelevant) tt = ref_time + datetime.timedelta(seconds=60*work_start_time) time_string = " ".join([str(tt.year), str(tt.month), str(tt.day), str(tt.hour), str(tt.minute)]) if elf_object.id in output: output[elf_object.id].append((toy_id, time_string, work_duration, work_start_time)); #work_start_time will be used to print in sorted order else: output[elf_object.id] = [(toy_id, time_string, work_duration, work_start_time)]; return tt.year;
def show_toys(): if request.method == "POST": new_toy = Toy(request.form['toyname'], request.form['image_url']) toys.append(new_toy) return redirect(url_for('show_toys')) else: return render_template('index.html', toys = toys)
def powerAvailableEstimation(big_jobs, boosters, hrs): ''' Assume a rating of 0.25, total gain in ratings that can be obtained for different jobs ''' total_gain = 0.0; ratio_big_jobs_boosters = len(big_jobs) / float( len(big_jobs) + len(boosters) ); #Dummy Elf dummy_elf = Elf(0); dummy_elf.rating = 0.25; work_start_time = 540; #All boosters are played with maximum sanctioned time shuffle(boosters); for job in boosters: #Assume the work starts at 9:00 on start of the day next_available_time, work_duration = \ assign_elf_to_toy(work_start_time, dummy_elf, job[1], hrs); dummy_elf.update_elf(hrs, Toy(0, '2014 01 01 01 01' ,job[1]), work_start_time, work_duration); #Every toy has default arrival time(irrelevant) #Flip a coin and play a big job based on above probability if random.random() < ratio_big_jobs_boosters: #Big Job Played - Measure the gain if dummy_elf.rating > 0.25: total_gain += (dummy_elf.rating - 0.25); #Reinitialize the dummy_elf dummy_elf = Elf(0); dummy_elf.rating = 0.25; return total_gain;
def main(): while True: choice = get_user_choice(main_menu) #allowing user to adopt a pet if choice == 1: pet_name = input("What would you like to name your pet? ") print("Please choose the type of pet:") type_choice = get_user_choice(adoption_menu) if type_choice == 1: pets.append(Pet(pet_name)) elif type_choice == 2: pets.append(CuddlyPet(pet_name)) print("You now have %d pets" % len(pets)) if choice == 2: for pet in pets: pet.get_love() if choice == 3: for pet in pets: pet.eat_food() #View pet status if choice == 4: for pet in pets: print(pet) if choice == 5: for pet in pets: pet.get_toy(Toy()) if choice == 6: # Pet levels naturally lower. for pet in pets: pet.be_alive()
def main(): while True: choice = get_user_choice(main_menu) if choice == 1: pet_name = input("What would you like to name your pet?\n") print("Please choose the type of pet:") type_choice = get_user_choice(adoption_menu) if type_choice == 1: pets.append(Pet(pet_name)) elif type_choice == 2: pets.append(CuddlyPet(pet_name)) pets.append(Pet(pet_name)) print("You now hae %s pets" % len(pets)) if choice == 2: for pet in pets: pet.get_love() if choice == 3: for pet in pets: pet.eat_food() if choice == 4: for pet in pets: print(pet) if choice == 5: for pet in pets: pet.get_toy(Toy()) if choice == 6: for pet in pets: pet.be_alive() if choice == 7: print("Thanks for playing!!!") break
def index(): if request.method == "POST": # gather the value of an input with a name attribute of "name" toys.append(Toy(request.form['name'])) # respond with a redirect to the route which has a function called "index" (in this case that is '/toys') return redirect(url_for('index')) # if the method is GET, just return index.html return render_template('index.html', toys=toys)
def series_solver(strip_lengths): """ The basic solver. Just run a depth first search, no tricks. """ toy = Toy(strip_lengths) toy.run() return toy.rel_solutions()
def __init__(self, name, globalP): self.env = Toy() self.name = name self.policy = Policy(env=self.env, state_shape=N_F, n_actions=N_A, globalP=globalP, scope=name + '/Policy')
def solution_firstAvailableElf(toy_file, soln_file, myelves): """ Creates a simple solution where the next available elf is assigned a toy. Elves do not start work outside of sanctioned hours. :param toy_file: filename for toys file (input) :param soln_file: filename for solution file (output) :param myelves: list of elves in a priority queue ordered by next available time :return: """ hrs = Hours() ref_time = datetime.datetime(2014, 1, 1, 0, 0) row_count = 0 with open(toy_file, 'rb') as f: toysfile = csv.reader(f) toysfile.next() # header row with open(soln_file, 'wb') as w: wcsv = csv.writer(w) wcsv.writerow(['ToyId', 'ElfId', 'StartTime', 'Duration']) for row in toysfile: current_toy = Toy(row[0], row[1], row[2]) # get next available elf elf_available_time, current_elf = heapq.heappop(myelves) work_start_time = elf_available_time if current_toy.arrival_minute > elf_available_time: work_start_time = current_toy.arrival_minute # work_start_time cannot be before toy's arrival if work_start_time < current_toy.arrival_minute: print 'Work_start_time before arrival minute: {0}, {1}'.\ format(work_start_time, current_toy.arrival_minute) exit(-1) current_elf.next_available_time, work_duration = \ assign_elf_to_toy(work_start_time, current_elf, current_toy, hrs) current_elf.update_elf(hrs, current_toy, work_start_time, work_duration) # put elf back in heap heapq.heappush(myelves, (current_elf.next_available_time, current_elf)) # write to file in correct format tt = ref_time + datetime.timedelta(seconds=60 * work_start_time) time_string = " ".join([ str(tt.year), str(tt.month), str(tt.day), str(tt.hour), str(tt.minute) ]) wcsv.writerow([ current_toy.id, current_elf.id, time_string, work_duration ])
async def asyncio_subprocess(strip_lengths, start, end): """ Subprocess for concurrent_asyncio """ toy = Toy(strip_lengths) toy.start(start) toy.run(finish_state=end) # print(start, toy.rel_solutions()) return toy.rel_solutions()
def subprocess(strip_lengths, start, end): """ Subprocess for embarrassinly parallel """ toy = Toy(strip_lengths) toy.start(start) toy.run(finish_state=end) # print(start, toy.rel_solutions()) return toy.rel_solutions()
def __init__(self, name, globalP): self.env = Toy() self.name = name self.policy = Policy(name + '/Policy', env=self.env, state_shape=self.env.observation_shape, n_actions=16) self.policy.build() self.pull_global_op = get_pull_global(globalP, self.policy) self.update_global_op = get_update_global(globalP, self.policy)
def main(): while True: choice = get_user_choice(main_menu) if choice == 1: pet_name = input( u"\n\u001b[32;1m Please enter the name of your new pet: \u001b[0m\n" ) print( u"\u001b[35;1m\n What type of pet would you like to adopt? \u001b[0m\n" ) type_choice = get_user_choice(adoption_menu) if type_choice == 1: pets.append(Pet(pet_name)) elif type_choice == 2: pets.append(PlayfulPet(pet_name)) print(u"\n\u001b[35;1m Extra playful!! \u001b[0m\n") print("You now have %d new pet(s) \n" % len(pets)) if choice == 2: for pet in pets: pet.get_love() print(u"\u001b[32;1m This is fun! Let's play all day\u001b[0m") if choice == 3: print( u"\n\u001b[32;1m What kind of treat would you like to give your pet? \u001b[0m\n" ) for pet in pets: type_treat = get_pet_treat(treat_list) my_treat = treat_list[type_treat] print(my_treat.message) results = my_treat.give_treat() pet.happiness += results[1] pet.hunger -= results[0] if choice == 4: for pet in pets: pet.eat_food() print(u"\u001b[32;1m YUM! That hit the spot! \u001b[0m") if choice == 5: for pet in pets: pet.nap_time() print(u"\u001b[32;1m Nap time!...I'm sleepy. \u001b[0m") if choice == 6: for pet in pets: print(pet) if choice == 7: for pet in pets: pet.get_toy(Toy()) if choice == 8: for pet in pets: pet.life() if choice == 9: exit(print(u"\u001b[42m Please, come back soon! \u001b[0m\n"))
def toy_from_database(self): """Sync the toy list with the toy in the database.""" data = self.Database.get_toys() self.Logger.debug('Toy in database : {}'.format(data)) dic = {} for toy in data: dic[toy[0]] = Toy( self.option_from_type(toy[1], self.Options.ProductName), self.option_from_type(toy[3], self.Options.ProductType), self.option_from_type(toy[2], self.Options.SizeOptions), toy[4], self.option_from_type(toy[5], self.Options.FirmnessOptions), self.option_from_type(toy[6], self.Options.CumTubValues), self.option_from_type(toy[7], self.Options.SuctionCupValues), self.option_from_type(toy[8], self.Options.FlopOption), toy[9], toy[0]) self.ToyInShop = dic
def main(): main = Menu("Please choose an option:", main_menu) type = Menu("Please choose the type of pet:", adoption_menu) treat = Menu("Please choose the type of treat:", treat_menu) while True: choice = main.get_choice() if choice == 1: pet_name = input("What would you like to name your pet? ") type_choice = type.get_user_choice() if type_choice == 1: pets.append(Pet(pet_name)) elif type_choice == 2: pets.append(CuddlyPet(pet_name)) print("You now have %d pets" % len(pets)) if choice == 2: for pet in pets: pet.get_love() print("Pets have been loved!") if choice == 3: for pet in pets: pet.eat_food() print("Pets have been fed!") if choice == 4: for pet in pets: print(pet) if choice == 5: for pet in pets: pet.get_toy(Toy()) print("Pets got a toy!") if choice == 6: treat_choice = treat.get_user_choice() if treat_choice == 1: treat_type = ColdPizza() if treat_choice == 2: treat_type = Bacon() if treat_choice == 3: treat_type = VeganSnack for pet in pets: pet.get_treat(treat_type) print("Pets got a treat!") if choice == 7: for pet in pets: pet.be_alive() print("Pets did nothing!")
def read_toys(toy_file): """ Reads the toy file and returns a dictionary of Toys. Toy file format: ToyId, Arrival_time, Duration ToyId: toy id Arrival_time: time toy arrives. Format is: YYYY MM DD HH MM (space-separated) Duration: duration in minutes to build toy :param toy_file: toys input file :param hrs: hours object :param num_toys: total number of toys to build :return: Dictionary of toys """ toy_dict = {} with open(toy_file, 'rb') as f: fcsv = csv.reader(f) fcsv.next() # header row for row in fcsv: new_toy = Toy(row[0], row[1], row[2]) toy_dict[new_toy.id] = new_toy return toy_dict
def main(): app = Menu("Please choose an option", main_menu) types = Menu("Please choose a type of pet", adoption_menu) treats = Menu("please choose a type of treat", treat_menu) while True: choice = app.get_user_choice() if choice == 1: pet_name = input("What would you like the pet name to be?") type_choice = types.get_user_choice() if type_choice == 1: pets.append(Pet(pet_name)) elif type_choice == 2: pets.append(CuddlyPet(pet_name)) num_pets = len(pets) print(f"You now have {num_pets} pets") elif choice == 2: for pet in pets: pet.get_love() elif choice == 3: for pet in pets: pet.eat_food() elif choice == 4: for pet in pets: print(pet) elif choice == 5: for pet in pets: pet.get_toy(Toy()) elif choice == 6: for pet in pets: pet.be_alive() elif choice == 7: print("Please choose your type of treat:") treat_choice = treats.get_user_choice if treat_choice == 1: for pet in pets: pet.eat_treat(ColdPizza()) elif treat_choice == 2: for pet in pets: pet.eat_treat(Bacon()) elif treat_choice == 3: for pet in pets: pet.eat_treat(VeganSnack())
def main(): app = Menu('Please choose an Option: ', main_menu) types = Menu('Please choose a Pet Option: ', adoption_menu) treats = Menu('Please choose a Treat Option: ', menu_menu) while True: choice = app.get_choice() if choice == 1: pet_name = input('What do you want to name your pet?') type_choice = types.get_choice() if (type_choice == 1): pets.append(Pet(pet_name)) elif (type_choice == 2): pets.append(CuddlyPet(pet_name)) print(f'\n\nYou now have {len(pets)} pets') elif choice == 2: for pet in pets: pet.get_love() elif choice == 3: treat_choice = treats.get_choice() food_to_feed = 0 if(treat_choice == 1): food_to_feed = ColdPizza() elif(treat_choice == 2): food_to_feed = Bacon() elif(treat_choice == 3): food_to_feed = VeganSnack() for pet in pets: pet.eat_food(food_to_feed) elif choice == 4: for pet in pets: print(pet) elif choice == 5: for pet in pets: pet.get_toy(Toy()) elif choice == 6: for pet in pets: pet.be_alive() print(pet)
def solution_noovertime(toy_file, soln_file, myelves): """ Creates a simple solution where the next available elf is assigned a toy. Elves do not start work outside of sanctioned hours. :param toy_file: filename for toys file (input) :param soln_file: filename for solution file (output) :param myelves: list of elves in a priority queue ordered by next available time :return: """ hrs = Hours() ref_time = datetime.datetime(2014, 1, 1, 0, 0) row_count = 0 with open(toy_file, 'rb') as f: toysfile = csv.reader(f) toysfile.next() # header row available_toys = OrderedDict([]) for row in toysfile: available_toys[row[0]] = Toy(row[0], row[1], row[2]) with open(soln_file, 'wb') as w: wcsv = csv.writer(w) wcsv.writerow(['ToyId', 'ElfId', 'StartTime', 'Duration']) toys_assigned = [ 9999, ] start_times = np.array([a.next_available_time for a in myelves]) while len(available_toys.keys()) > 0: print 'available_toys ', len(available_toys.keys()) tot_ass = 0 to_pop = [] for toycount, currtoy in available_toys.items(): best_times2 = np.where(currtoy.arrival_minute >= start_times, np.nan, start_times) best_times = np.argsort(best_times2) for elfpos in best_times: try: work_start_time = int(best_times2[elfpos]) except ValueError: break current_elf = myelves[elfpos] # work_start_time cannot be before toy's arrival #if work_start_time < current_toy.arrival_minute: # print 'Work_start_time before arrival minute: {0}, {1}'.\ # format(work_start_time, current_toy.arrival_minute) # exit(-1) next_available_time, work_duration, unsanctioned = \ assign_elf_to_toy(work_start_time, current_elf, currtoy, hrs) if (unsanctioned == 0 or toys_assigned[-1] == 0 or current_elf.rating > 3.5): current_elf.next_available_time = next_available_time current_elf.update_elf(hrs, currtoy, work_start_time, work_duration) start_times[elfpos] = current_elf.next_available_time # write to file in correct format tt = ref_time + datetime.timedelta(seconds=60 * work_start_time) time_string = " ".join([ str(tt.year), str(tt.month), str(tt.day), str(tt.hour), str(tt.minute) ]) wcsv.writerow([ currtoy.id, current_elf.id, time_string, work_duration ]) tot_ass += 1 del available_toys[toycount] break toys_assigned.append(tot_ass) print 'productivities' print[a.rating for a in myelves] print toys_assigned return
def _adjustColor(self, color): return (int(c * self.brightness) for c in color) def color(self, x, y, color): self.trellis.color(x, y, self._adjustColor(color)) def width(self): return 8 def height(self): return 8 trellisWrapper = TrellisWrapper(trellis, 0.5) toy = Toy(trellisWrapper) def buttonEvent(x, y, edge): toy.onEvent(x, y, edge == NeoTrellis.EDGE_RISING) for y in range(8): for x in range(8): trellis.activate_key(x, y, NeoTrellis.EDGE_RISING) trellis.activate_key(x, y, NeoTrellis.EDGE_FALLING) trellis.set_callback(x, y, buttonEvent) def tick(cmd=None): toy.tick(cmd)
def index(): if request.method == "POST": toys.append(Toy(request.form["name"])) return redirect(url_for("index")) return render_template("index.html", toys=toys)
from flask import Flask, render_template, redirect, url_for, request from flask_modus import Modus from toy import Toy app = Flask(__name__) modus = Modus(app) duplo = Toy(name="duplo") lego = Toy(name="lego") knex = Toy(name="knex") toys = [duplo, lego, knex] @app.route("/toys", methods=["GET", "POST"]) def index(): if request.method == "POST": toys.append(Toy(request.form["name"])) return redirect(url_for("index")) return render_template("index.html", toys=toys) @app.route("/toys/new") def new(): return render_template("new.html") @app.route("/toys/<int:id>", methods=["GET", "PATCH", "DELETE"]) def show(id): found_toy = next(toy for toy in toys if toy.id == id)
def main(): while True: choice = get_user_choice(main_menu) if choice == 1: pet_name = input("What would you like to name your pet? ") print("Please choose the type of pet:") type_choice = get_user_choice(adoption_menu) if type_choice == 1: pets.append(Pet(pet_name)) print( "Good choice, these pets are great to start your journey as pet owner.\n" ) elif type_choice == 2: pets.append(CuddlyPet(pet_name)) print( "Great choice, these pets are great for one's mental health and great anxiety reducers. But they do require lots of attention.\n" ) print("You now have %d pets.\n" % len(pets)) ### first part of the main menu #### when a choice is made it starts the loop of choices elif choice == 2: for pet in pets: pet.get_love() if pet.happiness >= 8 and pet.happiness < 10: print( f"{pet_name}, is very happy, may want rest a bit. \n") elif pet.happiness >= 10: print(f"{pet_name} is very tired and needs to rest. \n") elif choice == 3: for pet in pets: pet.eat_food() if pet.fullness >= 8 and pet.fullness < 10: print( f"{pet_name}, is statisfied, you can stop feeding it. \n" ) elif pet.fullness >= 10: print( f"{pet_name} has over eatten, and now needs to sleep. \n" ) elif choice == 4: for pet in pets: print(pet) elif choice == 5: for pet in pets: pet.get_toy(Toy()) elif choice == 6: # Pet levels naturally lower. for pet in pets: pet.be_alive() if pet.happiness <= 3 and pet.happiness > 0: print( f"{pet_name} is sad, you may want to play with your pet.\n" ) elif pet.fullness <= 3 and pet.fullness > 0: print( f"{pet_name} is hungry, you may want to feed your pet.\n" ) elif pet.fullness <= 0: print( f"{pet_name}, has died of hunger. Expect a call from the authorities!!!\n" ) break elif pet.happiness <= 0: print( f"{pet_name}, has run away, you may want to reflect of your life choices!\n" ) break ### when this choice is made, depending on the level pet is already, parameter is set to notify the user of pets health and happiness. elif choice == 7: print("Thanks for playing, tell your friends! \n") break
def index(): if request.method == "POST": toys.append(Toy(request.form['name'])) return redirect(url_for('index')) return render_template('index.html', toys=toys)
from toy import Toy import tensorflow_tools as tf_tool from policy import Policy import imageio from collections import namedtuple tc = tf.nn.rnn_cell Batch = namedtuple("Batch", [ "states", "actions", "last_actions", "states_", "rewards", "conditions", "values", "reward_total" ]) LR = 2e-5 OPT = tf.train.AdamOptimizer(LR) N_WORKERS = multiprocessing.cpu_count() GLOBAL_POLICY_NET_SCOPE = 'Global_Policy' env = Toy() N_F = env.observation_shape N_A = 16 MAX_EPISODE = 3000000 MAX_EP_STEPS = 20 def get_data(policy, batch_size, train=True, chooce_max=False, fixed=False): batch_states = [] batch_actions = [] batch_last_actions = [] batch_states_ = [] batch_rewards = [] batch_conditions = [] batch_values = [] reward_total = 0
def global_optimizer(sub_file, myToys, hrs, NUM_ELVES, output): """ Score the submission file, performing constraint checking. Returns the time (in minutes) when final present is complete. :param sub_file: submission file name. Headers: ToyId, ElfId, Start_Time, Duration :param myToys: toys dictionary :param hrs: hours object :return: time (in minutes) when final present is complete """ file_handler = open(output, "wb") hrs = Hours() ref_time = datetime.datetime(2014, 1, 1, 0, 0) threshold_minute = hrs.convert_to_minute('2450 1 1 0 0') basket_toys_above_th = [] basket_toys_below_th = [] #Unchanged elf_availability = {} #Maintains the earliest time when elves finish their last jobs for i in range(1, NUM_ELVES + 1): elf_availability[i] = [0, 0] row_count = 0 with open(sub_file, 'rb') as f: fcsv = csv.reader(f) fcsv.next() # header for row in fcsv: row_count += 1 if row_count % 50000 == 0: print 'Starting toy: {0}'.format(row_count) current_toy = int(row[0]) current_elf = int(row[1]) start_minute = hrs.convert_to_minute(row[2]) duration = int(row[3]) if start_minute > threshold_minute: basket_toys_above_th.append(current_toy) else: basket_toys_below_th.append((row[0], row[1], row[2], row[3])) if elf_availability[current_elf][0] < start_minute: elf_availability[current_elf][0] = start_minute elf_availability[current_elf][1] = duration myelves = [] for i in elf_availability.keys(): elf = Elf(i) elf.rating = 0.25 elf.next_available_time = elf_availability[current_elf][0] + int( math.ceil(elf_availability[current_elf][1] / elf.rating)) heapq.heappush(myelves, (elf.next_available_time, elf)) while len(basket_toys_above_th) > 0: #Retrive the toy object current_toy_duration = myToys[basket_toys_above_th[0]] #Pick the next available elf and execute it elf_available_time, current_elf = heapq.heappop(myelves) work_start_time = elf_available_time current_elf.next_available_time, work_duration = \ assign_elf_to_toy(work_start_time, current_elf, current_toy_duration, hrs) current_elf.update_elf(hrs, Toy(basket_toys_above_th[0], '2014 01 01 01 01' ,current_toy_duration), \ work_start_time, work_duration) # put elf back in heap heapq.heappush(myelves, (current_elf.next_available_time, current_elf)) tt = ref_time + datetime.timedelta(seconds=60 * work_start_time) time_string = " ".join([ str(tt.year), str(tt.month), str(tt.day), str(tt.hour), str(tt.minute) ]) #Add it to the basket below the threshold basket_toys_below_th.append((basket_toys_above_th[0], current_elf.id, time_string, work_duration)) del basket_toys_above_th[0] basket_toys_below_th = sorted( basket_toys_below_th, key=lambda element: hrs.convert_to_minute(element[2])) file_handler.write("ToyId,ElfId,StartTime,Duration\n") for obj in basket_toys_below_th: file_handler.write( str(obj[0]) + "," + str(obj[1]) + "," + str(obj[2]) + "," + str(obj[3]) + "\n") file_handler.close()
#!/usr/bin/python from flask import Flask, render_template, redirect, url_for, request from flask_modus import Modus from toy import Toy app = Flask(__name__) modus = Modus(app) duplo = Toy(name='duplo') lego = Toy(name='lego') knex = Toy(name='knex') toys = [duplo, lego, knex] @app.route('/toys/new') def new(): return render_template('new.html') @app.route('/toys', methods=["GET", "POST"]) def index(): if request.method == "POST": # gather the value of an input with a name attribute of "name" toys.append(Toy(request.form['name'])) # respond with a redirect to the route which has a function called "index" (in this case that is '/toys') return redirect(url_for('index')) # if the method is GET, just return index.html return render_template('index.html', toys=toys)