示例#1
0
def buildplan(frame,planname,datapath,pipeline,flag):

    """The guts of plan making.

    Pass in a data frame, planname, integer, datapath object, pipeline object.

    The data frame determines the plan display name (based on the
    instrument).  Interger is for the name, to provide each plan a
    unique id (thus the user can have the multiple plans using the
    same data).
    
    Then, this builds plan object.

    The output path is the input frame path with rawdata changed to findata.
    # FIX for other paths

    Returns the plan object
    """

#    planname = frame.aperture + frame.user.user_name + ".plan"

    displayname = makeplan_displayname(frame)

    plan = Plan(planname,frame.path,frame.instrument,pipeline,
                frame.aperture,frame.target,displayname)


    plan.finalpath = frame.path

    fullpath = os.path.join(datapath,plan.finalpath)

    if not os.access(fullpath,os.F_OK):
        os.makedirs(fullpath)
        # I KNOW, I KNOW!!!
        os.chmod(fullpath,0777)
        os.chmod(os.path.dirname(fullpath.rstrip("/")),0777)
    elif  os.path.isdir(fullpath) and flag['redo']:
        files = glob.glob(fullpath + "/*.fits*")
        for cfile in files:
            if os.path.basename(cfile) != frame.name:
                os.remove(os.path.join(cfile))
        files = glob.glob(fullpath + "/*.???")
        for cfile in files:
            os.remove(os.path.join(cfile))
        if os.path.isdir(os.path.join(fullpath,"Science")):
            files = glob.glob(fullpath + "/Science/*")
            for cfile in files:
                os.remove(os.path.join(cfile))
            os.rmdir(os.path.join(fullpath,"Science"))
        
    plan.instrument = frame.instrument

    plan.pipeline = pipeline
       
    return (plan)
示例#2
0
 def add(text, priority):
     plan = Plan()
     plan.detail = text
     plan.flag = priority
     if priority == PlanService.FINISHED:
         now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
         plan.time = now_time
         plan.create_time = now_time
     else:
         if priority < 0 or priority > PlanService.PRIORITY_MAX:
             plan.flag = 1
     return plan.get_id() if plan.save() != 0 else 0
示例#3
0
def calculate_and_display_user_mealplans():
    """Get calories and macros, calculate in helper functions and return list of user's mealplans."""

    user_id = session["user_id"]

    plan_name = request.form.get("plan_name")
    calories = float(request.form.get("calories"))
    carbohydrates = float(request.form.get("carbohydrates"))
    fat = float(request.form.get("fat"))
    protein = float(request.form.get("protein"))
    cal_or_perc = request.form.get("macro")

    if cal_or_perc == "percentage":
        carbohydrates = float(calories) * float(carbohydrates) / 400
        #divide by 100 because 100% and div by 4 because 1 g carb is 4 calories
        fat = float(calories) * float(fat) / 900
        #1 g fat is 9 kcal
        protein = float(calories) * float(protein) / 400

    new_plan = Plan(plan_name=plan_name,
                    user_id=user_id,
                    calories=calories,
                    carbohydrates=carbohydrates,
                    fat=fat,
                    protein=protein)
    db.session.add(new_plan)
    db.session.commit()

    results = calculate_calories_from_recipes_depend_on_plan(user_id)

    return render_template("calculated_mealplans.html", results=results)
示例#4
0
 def update(plan_id, flag):
     plan = Plan.get_or_none(Plan.id == plan_id)
     if plan is None:
         return False
     plan.time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
     plan.flag = flag
     return plan.save() != 0
示例#5
0
def create_plan(name, stocks_per_month, investment_per_month):
    plan = Plan(name=name,
                stocks_per_month=stocks_per_month,
                investment_per_month=investment_per_month)
    db.session.add(plan)
    db.session.commit()
    return plan
示例#6
0
def user_breakfast_preferences():
    """Get the preferences from the form, search the options for breakfast."""

    user_id = session["user_id"]

    plan_name = request.form.get("plan_name")
    calories = request.form.get("calories")
    carbohydrates = request.form.get("carbohydrates")
    fat = request.form.get("fat")
    protein = request.form.get("protein")
    # breakfast = request.form.get("breakfast")
    cal_or_perc = request.form.get("macro")

    breakfast = "egg"

    if cal_or_perc == "percentage":
        carbohydrates = float(calories) * float(carbohydrates) / 400
        #divide by 100 because 100% and div by 4 because 1 g carb is 4 calories
        fat = float(calories) * float(fat) / 900
        #1 g fat is 9 kcal
        protein = float(calories) * float(protein) / 400

    new_plan = Plan(plan_name=plan_name,
                    user_id=user_id,
                    calories=calories,
                    carbohydrates=carbohydrates,
                    fat=fat,
                    protein=protein)
    db.session.add(new_plan)
    db.session.commit()

    user_allergies = find_user_allergies(user_id)

    user_diets = find_user_diets(user_id)

    plan = Plan.query.filter_by(user_id=user_id).order_by(
        Plan.plan_id.desc()).first()
    calories = plan.calories
    carbohydrates = plan.carbohydrates
    fat = plan.fat
    protein = plan.protein

    breakfast_limit_calories = calories * 0.35
    breakfast_limit_carbohydrates = carbohydrates * 0.35
    breakfast_limit_fat = fat * 0.35
    breakfast_limit_protein = protein * 0.35

    results = get_recipes_from_api(breakfast, breakfast_limit_calories,
                                   breakfast_limit_carbohydrates,
                                   breakfast_limit_fat,
                                   breakfast_limit_protein, user_allergies,
                                   user_diets)
    user_id = session["user_id"]
    user = User.query.filter_by(user_id=user_id).first().fname

    return render_template("display_breakfast.html",
                           results=results,
                           user=user)
def add_plan_to_database(runner_id):
    """Adds a plan to the database and returns the plan object."""

    plan = Plan(runner_id=runner_id,
                start_date=session.get('start_date'),
                end_date=session.get('end_date'),
                goal_distance=session.get('goal_distance'),
                current_ability=session.get('current_ability'),
                )
    db.session.add(plan)
    db.session.commit()

    return plan
示例#8
0
def save_recipe():
    """Stores a saved recipe into database."""

    # make a new record in the plan table
    start = request.form.get("start")
    plan = Plan(
        start=start,
        user_id=session['user_id'],
    )
    db.session.add(plan)
    db.session.commit()

    recipes = []
    plan.recipes = []
    for i in range(1, 6):
        recipes.append(
            ast.literal_eval(request.form.get("recipe-{}".format(i))))
        recipe = db.session.query(Recipe).filter_by(
            recipe_id=recipes[i - 1]["id"]).first()
        if recipe is not None:
            recipe.num_saved += 1
        else:
            recipe = Recipe(recipe_id=recipes[i - 1]["id"],
                            title=recipes[i - 1]["title"],
                            url=recipes[i - 1]["url"],
                            image=recipes[i - 1]["image"],
                            prep_time=recipes[i - 1]["prepTime"],
                            num_saved=1,
                            fat=recipes[i - 1]["fat"],
                            carbohydrates=recipes[i - 1]["carbs"],
                            protein=recipes[i - 1]["protein"])
            db.session.add(recipe)

        plan.recipes.append(recipe)

    db.session.commit()

    return redirect("/mymeals")
def load_user_plan(chat_id, all_teachings):
    if os.path.isfile(config.dir_plans_name + str(chat_id)):
        with open(config.dir_plans_name + str(chat_id)) as f:
            plan_dict = json.load(f)
            plan = Plan()
            for t in plan_dict["teachings"]:
                try:
                    teaching = Teaching(t["corso_codice"], t["materia_codice"],
                                        t["materia_descrizione"],
                                        t["docente_nome"], t["componente_id"],
                                        t["url"], t["anno"], t["crediti"],
                                        t["componente_padre"],
                                        t["componente_radice"])
                    plan.add_teaching(teaching)

                # to recover plans from componente_id
                except KeyError:
                    try:
                        teaching = all_teachings[t["componente_id"]]
                        plan.add_teaching(teaching)
                    except:
                        traceback.print_exc()
                        pass

                #####

                except:
                    traceback.print_exc()
                    now = datetime.datetime.now()
                    logging.info("TIMESTAMP = " +
                                 now.strftime("%b %d %Y %H:%M:%S") +
                                 " ### EXCEPTION = " + traceback.format_exc())
        return plan

    else:
        return None
示例#10
0
 def todo_list():
     result = Plan.select().where(Plan.flag > 0, Plan.flag <= PlanService.PRIORITY_MAX).order_by(Plan.flag.desc())
     return list(result.dicts())