예제 #1
0
def create():
    form = LessonForm()

    if form.validate_on_submit():
        print request.form
        #4/0
        lesson = Lesson()
        lesson.title = request.form.get('title')
        lesson.time = request.form.get('time')
        lesson.audience = request.form.get('audience')
        lesson.goals = request.form.get('goals')
        lesson.summary = request.form.get('summary')
        session.add(lesson)
        session.flush()

        for index,step_entry in enumerate(form.steps.entries):
            step = Step()
            step.title = step_entry.title.data
            step.body = step_entry.body.data
            step.order = index
            step.lesson = lesson
            session.add(step)
            session.flush()

        session.commit()
        return redirect(url_for('view', uid=lesson.id))

    return render_template('create.html', form=form)
예제 #2
0
파일: saver.py 프로젝트: danbao/todpy
 def save_new_step(self, sce_save, step):
     step = step[step.keys()[0]]
     step_save = Step().fill(sce_save, step['step_name'], step['co_name'], step['co_file_name'],
                             step['co_firstlineno'], step['co_argcount'],
                             self.replace_u(step['co_varnames']), step['description'], step['action_type'], 
                             json.dumps(step['co_variables']))
     step_save.save()
     return step_save
예제 #3
0
def create_new_apptour(post_text):
    if post_text.get("tour").get("status") == "incomplete":
        print("saving new tour")
    else:
        print("creating new tour")
    tour = Tour(
        tour_name=post_text.get("tour").get("tour_name"),
        status=post_text.get("tour").get("status"),
        tour_description=post_text.get("tour").get("tour_description"),
        tour_groups=transform_tour_groups_field(post_text.get("tour").get("tour_groups")),
        tour_image=post_text.get("tour").get("tour_image"),
        tour_create_date=datetime.now()
    )
    tour.save(force_insert=True)
    connect_apptour_to_users(tour_id=tour.id)
    for step in post_text.get("steps"):
        step = Step(
            placement=step.get('placement'),
            title=step.get('title'),
            element=step.get('element'),
            content=step.get('content'),
            path=step.get('path'),
            order=step.get('order'),
            tour=tour
        )
        step.save(force_insert=True)
예제 #4
0
def navigate_user():
    """ display a map with basic pins of each route """
    route_id = request.form.get('route_details')

    route = Route.query.filter(Route.route_id == route_id).first()
    route_waypoints = route.waypoints

    start_point = route_waypoints[0]
    end_point = route_waypoints[-1]


    path = Path(start_point=start_point,
                end_point=end_point,
                )
    db.session.add(path)
    db.session.commit()

    path_id_tup = db.session.query(func.max(Path.path_id)).first()
    path_id = path_id_tup[0]

    step_start = start_point
    # step_end = route_waypoints[1]
    step = Step(path_id=path_id,
                start_point=step_start,
                # end_point=step_end,
                )
    db.session.add(step)
    db.session.commit()

    return render_template('navigation.html', route_id=route_id,
                                              path_id=path_id)
예제 #5
0
파일: courses.py 프로젝트: Valikovanast/new
def create_step(course_id, theme_id):
    step = Step(content_type=request.form.get('content_type'),
                theme_id=theme_id)
    db.session.add(step)
    db.session.commit()

    if step.content_type == 'text':
        text = bleach.clean(request.form.get('text'))
        page = Page(step_id=step.id, text=text)
        db.session.add(page)
        db.session.commit()

        image_ids = request.form.getlist('image_id')
        images = Image.query.filter(Image.id.in_(image_ids))
        for img in images:
            img.object_type = page.__tablename__
            img.object_id = page.id
            img.active = True
            db.session.add(img)
        db.session.commit()

    return redirect(
        url_for(
            'courses.show_content',
            course_id=course_id,
            theme_id=theme_id,
            step_id=step.id,
        ))
예제 #6
0
def getSteps(data, recipeId):
    steps = []
    for i in range(1, 20, 1):
        try:
            desc = data[STEP_ID + str(i)]
            steps.append(Step(recipeId, desc))
        except:
            break
    return steps
예제 #7
0
def update_existing_apptour(post_text):
    #check to se if creating a new apptour or making a previously incomplete(i.e., saved) apptour complete
    existing_tour = Tour.objects.get(id=post_text.get("tour").get("id"))
    if existing_tour.status == "incomplete":
        #creating new tour from existing saved tour
        if post_text.get("tour").get("status") == "incomplete":
            print("saving saved tour")
        else:
            print("creating saved tour")
        tour = Tour(
            tour_name=post_text.get("tour").get("tour_name"),
            id=post_text.get("tour").get("id"),
            status=post_text.get("tour").get("status"),
            tour_description=post_text.get("tour").get("tour_description"),
            tour_groups=transform_tour_groups_field(post_text.get("tour").get("tour_groups")),
            tour_image=post_text.get("tour").get("tour_image"),
            tour_create_date=datetime.now()
        )
        tour.save(force_update=True)
    else:
        #updaing an existing tour
        if post_text.get("tour").get("status") == "incomplete":
            print("saving previously created tour")
            print("warning: the previoius version and the newer version will both be unaccessable to the users at this time")
        else:
            print("updating previously created tour")
        tour = Tour(
            tour_name=post_text.get("tour").get("tour_name"),
            id=post_text.get("tour").get("id"),
            status=post_text.get("tour").get("status"),
            tour_description=post_text.get("tour").get("tour_description"),
            tour_groups=transform_tour_groups_field(post_text.get("tour").get("tour_groups")),
            tour_image=post_text.get("tour").get("tour_image"),
            tour_create_date=existing_tour.tour_create_date,
            tour_update_date=datetime.now()
        )
        tour.save(force_update=True)
    Step.objects.filter(tour__id=post_text.get("tour").get("id")).delete()
    for step in post_text.get("steps"):
        step = Step(
            placement=step.get('placement'),
            title=step.get('title'),
            element=step.get('element'),
            content=step.get('content'),
            path=step.get('path'),
            order=step.get('order'),
            tour=tour
        )
        step.save(force_insert=True)
예제 #8
0
    def select_messages(self, **kwargs):
        self._selected_grbs = self._get_gids(**kwargs)

        if len(self._selected_grbs) > 0:
            self._gid_main_res = self._selected_grbs[0]
            grid = GribGridDetails(self._selected_grbs[0])
            # some cumulated messages come with the message at step=0 as instant, to permit aggregation
            # cumulated rainfall rates could have the step zero instant message as kg/m^2, instead of kg/(m^2*s)
            if len(self._selected_grbs) > 1:
                unit = grib_get(self._selected_grbs[1], 'units')
                type_of_step = grib_get(self._selected_grbs[1], 'stepType')
            else:
                type_of_step = grib_get(self._selected_grbs[0], 'stepType')
                unit = grib_get(self._selected_grbs[0], 'units')
            type_of_level = grib_get(self._selected_grbs[0], 'levelType')

            missing_value = grib_get(self._selected_grbs[0], 'missingValue')
            all_values = {}
            all_values_second_res = {}
            grid2 = None
            input_step = self._step_grib
            for g in self._selected_grbs:

                start_step = grib_get(g, 'startStep')
                end_step = grib_get(g, 'endStep')
                points_meridian = grib_get(g, 'Nj')
                if '{}-{}'.format(start_step,
                                  end_step) == self._change_step_at:
                    # second time resolution
                    input_step = self._step_grib2

                key = Step(start_step, end_step, points_meridian, input_step)

                if points_meridian != grid.num_points_along_meridian and grid.get_2nd_resolution(
                ) is None:
                    # found second resolution messages
                    grid2 = GribGridDetails(g)
                    self._gid_ext_res = g

                values = grib_get_double_array(g, 'values')
                if not grid2:
                    all_values[key] = values
                elif points_meridian != grid.num_points_along_meridian:
                    all_values_second_res[key] = values

            if grid2:
                key_2nd_spatial_res = min(all_values_second_res.keys())
                grid.set_2nd_resolution(grid2, key_2nd_spatial_res)
            return Messages(all_values, missing_value, unit, type_of_level,
                            type_of_step, grid, all_values_second_res)
        # no messages found
        else:
            raise ValueError('No messages in grib file')
예제 #9
0
def create():
    form = LessonForm()

    if form.validate_on_submit():
        print request.form
        #4/0
        lesson = Lesson()
        lesson.title = request.form.get('title')
        lesson.time = request.form.get('time')
        lesson.audience = request.form.get('audience')
        lesson.goals = request.form.get('goals')
        lesson.summary = request.form.get('summary')
        session.add(lesson)
        session.flush()

        for index, step_entry in enumerate(form.steps.entries):
            step = Step()
            step.title = step_entry.title.data
            step.body = step_entry.body.data
            step.order = index
            step.lesson = lesson
            session.add(step)
            session.flush()

        session.commit()
        return redirect(url_for('view', uid=lesson.id))

    return render_template('create.html', form=form)
예제 #10
0
def fetchStepByEmailStep(email, step):
    cursor = mysql.connection.cursor()
    cursor.execute(
        "select email,step, deadline, expectedOutput, tasks from step where email='%s' and step='%s'"
        % (email, step))
    stepRaw = cursor.fetchone()
    if stepRaw is None:
        return None
    step = Step()
    step.email = stepRaw[0]
    step.step = stepRaw[1]
    step.deadline = stepRaw[2]
    step.expectedOutput = stepRaw[3]
    step.tasks = stepRaw[4].split(",")
    mysql.connection.commit()
    cursor.close()
    return step
예제 #11
0
파일: views.py 프로젝트: danbao/todpy
def get_feature_dto(feature):
    workspace = WorkSpace.objects.get(pk=feature.workspace)
    workspace_path = workspace.getFolderPath()
    dict = Step.getStepByFolder(workspace_path)
    file_path = FeatureFileGenerator.get_workspace_entrance(workspace)
    feature = lettuce.Feature.from_file(file_path)
    feature_dto = FeatureDto(feature.name, feature.description)
    scenarios = []
    for sce in feature.scenarios:
        s_dto = ScenarioDto('id_missing', sce.name)
        for s_item in sce.steps:
            co_func, patten, result = match_definision(s_item, dict)
            action_type, varlist_tuple, variables = extract_func_info(co_func, s_item, result)
            step_dto = StepDto()
            func_code = co_func.func_code
            step_dto.fill(func_code.co_filename, func_code.co_firstlineno, func_code.co_argcount,
                          varlist_tuple, func_code.co_name, patten, action_type, variables, patten,
                          'id_no_use')
            s_dto.steps.append(step_dto)
        scenarios.append(s_dto)
    feature_dto.fill_scenarios(scenarios)
    return feature_dto
예제 #12
0
def add_instruction(instruction, **kwargs):
    """
    Adds a travel instruction to the database.
    """
    logger.info(f"Adding instruction to database: {kwargs}")
    end_lat, end_lng = kwargs.pop('location')
    if not instruction:  # inserts an empty instruction in the db with the reachable flag set to false
        warning_overview = Overview(**{**kwargs, **{'reachable': False, 'end_lat': end_lat, 'end_lng': end_lng}})
        db.session.add(warning_overview)
        db.session.commit()
        logger.info(f"Added unreachable instruction: {warning_overview}")
        return
    previous_overviews = list(get_overviews_by_date(kwargs['user_id'], kwargs['start_date'].replace(year=1995),instruction['true_start'] - datetime.timedelta(seconds=1)))
    logger.info(previous_overviews)
    previous_date = previous_overviews[-1].end_date if previous_overviews else datetime.datetime.now()
    # If the event is not a return instruction and cannot be reached in time from the previous event mark unreachable
    if previous_date + datetime.timedelta(seconds=instruction['duration']) > instruction['true_start'] and kwargs['departure']:
        kwargs['reachable'] = False
        logger.warning(f"Instruction has been marked as unreachable.")
    steps = instruction.pop('steps')
    instruction.pop('true_start')
    overview = Overview(**{**instruction, **kwargs})
    del kwargs['start_date'], kwargs['end_date'], kwargs['departure'], kwargs['flex_duration'], kwargs['reachable'], kwargs['next_is_base']
    for i, step in enumerate(steps):
        if step['travel_mode'] == 'TRANSIT':  # gets datetime objects from strings, only present in transit
            try:
                step['departure_time'] = parser.parse(step['departure_time'])
                step['arrival_time'] = parser.parse(step['arrival_time'])
            except KeyError:
                pass
        step['event_id'] = kwargs['id']
        step['id'] = i
        step = Step(**{**kwargs, **step}, overview=overview)
        db.session.add(step)
    db.session.add(overview)
    db.session.commit()
    logger.info(f"Stored instruction {overview}: {overview.start_address} -> {overview.end_address}")
예제 #13
0
def fetchStepNotExceed(email):
    cursor = mysql.connection.cursor()
    cursor.execute(
        "select email,step, deadline, expectedOutput, tasks from step where deadline >= now() and email='%s'"
        % (email))
    sr = cursor.fetchall()

    stepList = []

    for sr in sr:
        if sr is not None:
            step = Step()
            step.email = sr[0]
            step.step = sr[1]
            step.deadline = sr[2]
            step.expectedOutput = sr[3]
            step.tasks = sr[4].split(",")
            stepList.append(step)

    mysql.connection.commit()
    cursor.close()

    return stepList
예제 #14
0
def add_recipe(request):
    context = {}
    context['urlform'] = AddRecipebyURLForm()
    context['recipeform'] = RecipeForm()
    context['instructionform'] = InstructionsForm()
    context['ingredientsform'] = IngredientsForm()
    context['autocompleteform'] = AutocompleteSearchForm()
    context['profile'] = Profile.objects.get(user=request.user)
    if request.method == 'GET':
        return render(request, 'foodchaser/add_recipe.html', context)
    elif request.method != 'POST':
        return render(request, 'foodchaser/add_recipe.html', context)

    user = request.user
    recipeform = RecipeForm(request.POST, request.FILES)
    instructionform = InstructionsForm(request.POST, request.FILES)
    ingredientsform = IngredientsForm(request.POST)

    context['recipeform'] = recipeform
    context['instructionform'] = instructionform
    context['ingredientsform'] = ingredientsform

    # for debugging use, don't remove
    if not recipeform.is_valid() or not instructionform.is_valid() \
       or not ingredientsform.is_valid():
        return render(request, 'foodchaser/add_recipe.html', context)

    # Store ingredient
    name = ingredientsform.cleaned_data['name']
    category = find_category(name)
    ingredient = Ingredient(name=name, allergy=category)

    ingredient.save()

    ingredientunit = IngredientUnit(name=ingredientsform.cleaned_data['name'],\
                            quantity =  ingredientsform.cleaned_data['quantity'], \
                            unit = ingredientsform.cleaned_data['unit'], \
                            notes = ingredientsform.cleaned_data['notes'], \
                            ingredient = ingredient)

    ingredientunit.save()
    ingredientunit.ingreID = ingredientunit.id
    ingredientunit.save()

    # Store instructions
    step = Step(text = instructionform.cleaned_data['text'], \
                preptime = instructionform.cleaned_data['preptime'], \
                cooktime = instructionform.cleaned_data['cooktime'], \
                picture = instructionform.cleaned_data['picture'])

    step.save()
    step.stepID = step.id
    step.save()

    recipe = Recipe(
        recipe_name = recipeform.cleaned_data['recipe_name'], \
        description = recipeform.cleaned_data['description'], \
        category1 = recipeform.cleaned_data['category1'], \
        category2 = recipeform.cleaned_data['category2'], \
        spicy = recipeform.cleaned_data['spicy'], \
        estimated_time= recipeform.cleaned_data['estimated_time'],\
        owner = user,\
        photo = recipeform.cleaned_data['photo'])

    recipe.save()
    recipe.ingredients.add(ingredientunit)
    recipe.steps.add(step)

    # Add additional ingredients and steps
    # Parse additional steps
    i = 2
    while (('text' + str(i)) in request.POST):
        request.POST['text'] = request.POST['text' + str(i)]
        request.POST['preptime'] = request.POST['preptime' + str(i)]
        request.POST['cooktime'] = request.POST['cooktime' + str(i)]

        if (('picture' + str(i)) in request.FILES):
            request.FILES['picture'] = request.FILES['picture' + str(i)]
        else:
            request.FILES['picture'] = None

        instructionf = InstructionsForm(request.POST, request.FILES)
        if not instructionf.is_valid():
            return render(request, 'foodchaser/add_recipe.html', context)

        step = Step(text = instructionf.cleaned_data['text'], \
                preptime = instructionf.cleaned_data['preptime'], \
                cooktime = instructionf.cleaned_data['cooktime'], \
                picture = instructionf.cleaned_data['picture'])
        step.save()
        step.stepID = step.id
        step.save()
        recipe.steps.add(step)
        i += 1

    # Parse additional ingredients
    i = 2
    while (('name' + str(i)) in request.POST):
        request.POST['name'] = request.POST['name' + str(i)]
        request.POST['quantity'] = request.POST['quantity' + str(i)]
        request.POST['unit'] = request.POST['unit' + str(i)]
        request.POST['notes'] = request.POST['notes' + str(i)]
        ingredientsf = IngredientsForm(request.POST)
        if not ingredientsf.is_valid():
            return render(request, 'foodchaser/add_recipe.html', context)

        # Store ingredient
        name = ingredientsf.cleaned_data['name']
        category = find_category(name)
        ingredient = Ingredient(name=name, allergy=category)
        ingredient.save()
        ingredientunit = IngredientUnit(name = ingredientsf.cleaned_data['name'],\
                            quantity = ingredientsf.cleaned_data['quantity'], \
                            unit = ingredientsf.cleaned_data['unit'], \
                            notes = ingredientsf.cleaned_data['notes'], \
                            ingredient = ingredient)

        ingredientunit.save()
        ingredientunit.ingreID = ingredientunit.id
        ingredientunit.save()
        recipe.ingredients.add(ingredientunit)
        i += 1

    recipe.save()
    recipes = Recipe.objects.all().filter(owner=request.user)

    context['recipes'] = recipes
    context['user'] = user
    context['profile'] = Profile.objects.get(user=request.user)

    # Add scores on the user ranking
    userlevel = LevelData.objects.get(user=request.user)
    update_level_data(userlevel)

    return render(request, 'foodchaser/recipebox_maindish.html', context)
예제 #15
0
def edit(request, id):
    context = {}
    context['urlform'] = AddRecipebyURLForm()
    context['autocompleteform'] = AutocompleteSearchForm()

    recipe = get_object_or_404(Recipe, id=id)
    context['recipe'] = recipe
    context['user'] = request.user
    ingredients = recipe.ingredients.all()
    steps = recipe.steps.all()

    ingredientforms = []
    stepforms = []

    for ingredient in ingredients:
        ingredientforms.append(IngredientsForm(instance=ingredient))
    for step in steps:
        stepforms.append(InstructionsForm(instance=step))

    context['ingredientforms'] = ingredientforms
    context['stepforms'] = stepforms

    context['ingredients'] = ingredients
    context['steps'] = steps
    context['user'] = request.user
    context['rating'] = RatingForm()
    context['comment'] = CommentForm()
    context['comments'] = recipe.comments.all()
    context['profile'] = Profile.objects.get(user=request.user)
    # Just display the registration form if this is a GET request
    if request.method == 'GET':
        recipeform = RecipeForm(instance=recipe)  # Creates form from the
        context['recipeform'] = recipeform  # existing entry.
        return render(request, 'foodchaser/edit_recipe.html', context)

    # if method is POST, get form data to update the model
    rform = RecipeForm(request.POST, request.FILES, instance=recipe)
    if not rform.is_valid():
        context['recipeform'] = rform
        return render(request, 'foodchaser/edit_recipe.html', context)

    rform.save()
    # Add additional ingredients and steps
    # Parse additional steps
    i = 1
    while (('text' + str(i)) in request.POST):
        request.POST['text'] = request.POST['text' + str(i)]
        request.POST['preptime'] = request.POST['preptime' + str(i)]
        request.POST['cooktime'] = request.POST['cooktime' + str(i)]
        if ('stepID' + str(i) in request.POST):
            request.POST['stepID'] = request.POST['stepID' + str(i)]
        else:
            request.POST['stepID'] = ''

        if (('picture' + str(i)) in request.FILES):
            request.FILES['picture'] = request.FILES['picture' + str(i)]
        else:
            request.FILES['picture'] = None

        instructionf = InstructionsForm(request.POST, request.FILES)
        if not instructionf.is_valid():
            return render(request, 'foodchaser/edit_recipe.html', context)

        # Store step
        if (not recipe.steps.all().filter(
                stepID=instructionf.cleaned_data['stepID'])):
            step = Step(text = instructionf.cleaned_data['text'], \
                    preptime = instructionf.cleaned_data['preptime'], \
                    cooktime = instructionf.cleaned_data['cooktime'], \
                    picture = instructionf.cleaned_data['picture'])

            step.save()
            step.stepID = step.id
            step.save()
            recipe.steps.add(step)

        i += 1

    # Parse additional ingredients
    i = 1
    while (('name' + str(i)) in request.POST):
        request.POST['name'] = request.POST['name' + str(i)]
        request.POST['quantity'] = request.POST['quantity' + str(i)]
        request.POST['unit'] = request.POST['unit' + str(i)]
        request.POST['notes'] = request.POST['notes' + str(i)]
        if ('ingreID' + str(i) in request.POST):
            request.POST['ingreID'] = request.POST['ingreID' + str(i)]
        else:
            request.POST['ingreID'] = ''
        ingredientsf = IngredientsForm(request.POST)
        if not ingredientsf.is_valid():
            return render(request, 'foodchaser/edit_recipe.html', context)

        # Store ingredient
        if (not recipe.ingredients.all().filter(
                ingreID=ingredientsf.cleaned_data['ingreID'])):
            name = ingredientsf.cleaned_data['name']
            category = find_category(name)
            ingredient = Ingredient(name=name, allergy=category)
            ingredient.save()
            ingredientunit = IngredientUnit(name = ingredientsf.cleaned_data['name'],\
                            quantity = ingredientsf.cleaned_data['quantity'], \
                            unit = ingredientsf.cleaned_data['unit'], \
                            notes = ingredientsf.cleaned_data['notes'], \
                            ingredient = ingredient)

            ingredientunit.save()
            ingredientunit.ingreID = ingredientunit.id
            ingredientunit.save()
            recipe.ingredients.add(ingredientunit)

        i += 1

    ingredients = recipe.ingredients.all()
    steps = recipe.steps.all()
    context['ingredients'] = ingredients
    context['steps'] = steps
    recipes = Recipe.objects.all().filter(owner=request.user)

    context['recipes'] = recipes
    return render(request, 'foodchaser/recipe_view.html', context)
예제 #16
0
def make_step(section: Tag) -> Step:
    img: Tag = section.select_one("img").get("data-srclarge")
    sub_steps = [make_sub_step(sub_step) for sub_step in section.select(".step")]
    return Step(pic=img, sub_steps=sub_steps)
예제 #17
0
def parseStep(lines):
    nextLines = int(lines.pop(0))
    time = float(lines.pop(0).split("Time=").pop())
    particles = [parseParticle(lines.pop(0)) for _ in range(nextLines)]
    return Step(time, particles)
예제 #18
0
파일: views.py 프로젝트: danbao/todpy
def search_steps(request):
    key_word = request.GET.get('key_word')
    type = request.GET.get('type')
    response_data = Step.searchStep(key_word, type)
    return HttpResponse(json.dumps(response_data, cls=DataEncoder), content_type="application/json")
예제 #19
0
파일: views.py 프로젝트: danbao/todpy
def index(request):
    steps = Step.getStepByFolder('../simple-selenium')
    return render(request, 'auto/index.html', {'steps': steps})
예제 #20
0
def setRecipeSteps(recipe, param):
    for step in param:
        recipeStep = Step()
        recipeStep.stepDetails = step
        db.session.add(recipeStep)
        recipeStep.recipe.append(recipe)
예제 #21
0
def add_recipe(request):
    context = {}
    context['urlform'] = AddRecipebyURLForm()
    context['recipe'] = RecipeForm()
    context['instruction'] = AddInstructionsForm()
    context['ingredients'] = AddIngredientsForm()      
    context['autocompleteform'] = AutocompleteSearchForm()
    
    if request.method == 'GET':
        return render(request, 'foodchaser/add_recipe.html', context)

    user = request.user
    recipef = RecipeForm(request.POST, request.FILES)
    instructionf = AddInstructionsForm(request.POST, request.FILES)
    ingredientsf = AddIngredientsForm(request.POST)
    
    if not recipef.is_valid() or not instructionf.is_valid() or not \
    ingredientsf.is_valid():
        return render(request, 'foodchaser/add_recipe.html', context)
    
    # Store ingredient
    ingredient = Ingredient(name = ingredientsf.cleaned_data['item'])
    
    ingredient.save()
    
    ingredientunit = IngredientUnit(quantity =  ingredientsf.cleaned_data['quantity'], \
                            unit = ingredientsf.cleaned_data['unit'], \
                            notes = ingredientsf.cleaned_data['notes'], \
                            ingredient = ingredient)
     
    ingredientunit.save()
    
    # Store instructions
    step = Step(description = instructionf.cleaned_data['des'], \
                preptime = instructionf.cleaned_data['preptime'], \
                cooktime = instructionf.cleaned_data['cooktime'], \
                picture = instructionf.cleaned_data['stepPic'])
    
    step.save()
    
    recipe = Recipe(name = recipef.cleaned_data['name'], \
                    description = recipef.cleaned_data['description'], \
                    category1 = recipef.cleaned_data['category1'], \
                    category2 = recipef.cleaned_data['category2'], \
                    spicy = recipef.cleaned_data['spicy'], \
                    estimated_time= recipef.cleaned_data['estimated_time'],\
                    owner = user,\
                    picture = recipef.cleaned_data['picture'])

    recipe.save()
    recipe.ingredients.add(ingredientunit)
    recipe.steps.add(step)

    # Add additional ingredients and steps
    # Parse additional steps
    i = 2
    while (('des'+str(i)) in request.POST):
        request.POST['des'] = request.POST['des'+str(i)]
        request.POST['preptime'] = request.POST['preptime'+str(i)]
        request.POST['cooktime'] = request.POST['cooktime'+str(i)]
        if (('stepPic'+str(i)) in request.FILES):
            request.FILES['stepPic'] = request.FILES['stepPic'+str(i)]
        else:
            request.FILES['stepPic'] = None
            
        instructionf = AddInstructionsForm(request.POST, request.FILES)
        if not instructionf.is_valid():
            return render(request, 'foodchaser/add_recipe.html', context)

        step = Step(description = instructionf.cleaned_data['des'], \
                preptime = instructionf.cleaned_data['preptime'], \
                cooktime = instructionf.cleaned_data['cooktime'], \
                picture = instructionf.cleaned_data['stepPic'])
        step.save()
        recipe.steps.add(step)
        i += 1

    # Parse additional ingredients
    i = 2
    while (('item'+str(i)) in request.POST):
        request.POST['item'] = request.POST['item'+str(i)]
        request.POST['quantity'] = request.POST['quantity'+str(i)]
        request.POST['unit'] = request.POST['unit'+str(i)]
        request.POST['notes'] = request.POST['notes'+str(i)]
            
        ingredientsf = AddIngredientsForm(request.POST)
        if not ingredientsf.is_valid():
            return render(request, 'foodchaser/add_recipe.html', context)

        # Store ingredient
        ingredient = Ingredient(name = ingredientsf.cleaned_data['item'])
        ingredient.save()
        ingredientunit = IngredientUnit(quantity = ingredientsf.cleaned_data['quantity'], \
                            unit = ingredientsf.cleaned_data['unit'], \
                            notes = ingredientsf.cleaned_data['notes'], \
                            ingredient = ingredient)
     
        ingredientunit.save()
        recipe.ingredients.add(ingredientunit)
        i += 1
    
    recipe.save()
    recipes = Recipe.objects.all().filter(owner = request.user)
    
    context['recipes'] = recipes
    context['user'] = user
    
    return render(request, 'foodchaser/recipebox_maindish.html', context)
예제 #22
0
    # Store test performance after each args.save_interval iterations
    SAV.perf.te_vs_iterations = []

    # Expose model modules that has_codes
    model = get_mods(
        model,
        optimizer='Adam',
        optimizer_params={'lr': args.lr_weights},
        scheduler=lambda epoch: 1 / 2**(epoch // args.lr_half_epochs))
    model[-1].optimizer.param_groups[0]['lr'] = args.lr_out

    if args.model.lower() == 'binary':
        from models import Step
        # Add Dropout and discretize first hidden layer (as in Diff Target propagation paper)
        model[2] = nn.Sequential(nn.Dropout(p=0.2), nn.Tanh(), Step())
        # Add Dropout before last linear layer
        model[4][0] = nn.Sequential(nn.Dropout(p=0.2), nn.Tanh())

    # Initial mu and increment after every mini-batch
    mu = args.mu
    mu_max = 10 * args.mu

    for epoch in range(1, args.epochs + 1):
        print('\nEpoch {} of {}. mu = {:.4f}, lr_out = {}'.format(
            epoch, args.epochs, mu, model[-1].scheduler.get_lr()))

        for batch_idx, (data, targets) in enumerate(train_loader):
            data, targets = data.to(device), targets.to(device)

            # (1) Forward