예제 #1
0
def __main_process__(input_string):  # the game model
    global game, counter, game_limit, game_hints, main_word, bool_index
    global game_score

    if len(input_string) == 1:  # if user input was a single char
        indexes = H.search(main_word, input_string)

        if len(indexes) != 0:
            H.update(bool_index, indexes)
            counter += len(indexes)
    else:  # less or more than one words compare differently

        if input_string == main_word:
            H.game_done(bool_index)
            game_score += game_hints
            game = False
        elif input_string == "hint()":  # using the hints
            if game_hints > 0:
                H.hint(bool_index, main_word)
                game_hints -= 1
                game_limit += 1
                counter += 1
            else:
                return

    if counter == word_len:
        game_score += 1
        game = False

    if game_limit == 0:
        game = False
        game_limit += 1

    game_limit -= 1
예제 #2
0
    def update_movie(movie_id):
        try:
            movie = Movies.query.filter(Movies.id == movie_id).first_or_404()
            if not movie:
                raise

            movie_props = ['title', 'release_date', 'actors']
            movie_data = {}

            for prop in movie_props:
                if prop in request.get_json():
                    movie_data[prop] = request.get_json()[prop]

            movie_data = validate_movie(**movie_data, updating=True)

            for prop, val in movie_data.items():
                setattr(movie, prop, val)

            update()
            response = {
                'success': True,
                'movies': [movie.format()]
            }
        except UnprocessableEntity:
            raise
        except NotFound:
            raise
        except Exception:
            print(sys.exc_info())
            raise BadRequest

        return jsonify(response)
예제 #3
0
    def update_actor(actor_id):
        try:
            actor = Actors.query.filter(Actors.id == actor_id).first_or_404()

            actor_props = ['name', 'gender', 'age', 'movies']
            actor_data = {}

            for prop in actor_props:
                if prop in request.get_json():
                    actor_data[prop] = request.get_json()[prop]

            actor_data = validate_actor(**actor_data, updating=True)

            for prop, val in actor_data.items():
                setattr(actor, prop, val)

            update()
            response = {
                'success': True,
                'actors': [actor.format()]
            }
        except UnprocessableEntity:
            raise
        except NotFound:
            raise
        except Exception:
            print(sys.exc_info())
            raise BadRequest

        return jsonify(response)
예제 #4
0
def update():
    if 'editid' in s:
        userid = s['editid']
    else:
        userid = s['name']
    form = UpdateForm(request.form)
    get_info = models.get_info(userid)
    if request.method == 'POST':
        user = models.update(
            form.role.data, userid, form.password.data,
            form.email.data, form.name.data
        )
        if user != 1:
            hriks(
                "ERROR! Already on this role, or you hadn't updated anything"
            )
            return redirect(url_for('update'))
        else:
            hriks(
                'Successfully role changed for  %s to %s' % (
                    userid, form.role.data)
            )
            s['editid'] = None
            return redirect(url_for('users'))
    return render(
        'forms/update.html', form=form,
        userid=userid, get_info=get_info
    )
예제 #5
0
파일: app.py 프로젝트: imclab/flight-status
def manage(taxonomy):
    if taxonomy not in models.TAXONOMY['types']:
        return render_template("404.html"), 404
    if request.method == 'POST':
        if request.form['action'] == "NEW":
            models.add_new(taxonomy, request.form)
        elif request.form['action'] == "DELETE":
            models.delete(taxonomy, request.form['key'])
        elif request.form['action'] == "UPDATE":
            models.update(taxonomy, request.form)
        elif "ADD_MEMBER" in request.form['action']:
            member_typ = request.form['action'][10:]
            models.add_member(taxonomy, member_typ, request.form)

    name = views.key2name(taxonomy)
    collection = views.get_all(taxonomy)
    fields = models.get_fields(taxonomy)
    return render_template('manage.html', name=name, collection=collection, fields=fields)
예제 #6
0
def post(request):
    """Post to Twitter"""
    form = PostForm(request.REQUEST)
    u = session_user(request.session)

    tw = Twitter(request.session["access_token"])

    if request.method == u"POST" and not form.errors:
        status = form.cleaned_data["status"]
        in_reply_to = form.cleaned_data.get("in_reply_to", u"")

        if status.startswith(u"d "):
            recipient = status.split()[1]
            if not is_follower(tw, recipient):
                return cant_dm(request, recipient)

        try:
            update(tw, request.session["screen_name"], status, in_reply_to)
        except:
            return fail(request, _(u"Couldn't post to Twitter, they are lame."
                u" Refresh to try again."))

        return HttpResponseRedirect(reverse("home"))

    if request.method == u"GET":
        status = request.GET.get("status", u"")
        if status.startswith(u"d "):
            recipient = status.split()[1]
            if not is_follower(tw, recipient):
                return cant_dm(request, recipient)

        form["status"].field.required = False

    if "in_reply_to" in form.errors:
        return fail(request, _(u"%s is not a valid status to reply to." %
                request.REQUEST["in_reply_to"]))

    ctx = {
        "form":     form,
        "user":     u,
    }
    return render_to_response(u"followize/post.html", ctx)
예제 #7
0
def manage(taxonomy):
    if taxonomy not in models.TAXONOMY['types']:
        return render_template("404.html"), 404
    if request.method == 'POST':
        if request.form['action'] == "NEW":
            models.add_new(taxonomy, request.form)
        elif request.form['action'] == "DELETE":
            models.delete(taxonomy, request.form['key'])
        elif request.form['action'] == "UPDATE":
            models.update(taxonomy, request.form)
        elif "ADD_MEMBER" in request.form['action']:
            member_typ = request.form['action'][10:]
            models.add_member(taxonomy, member_typ, request.form)

    name = views.key2name(taxonomy)
    collection = views.get_all(taxonomy)
    fields = models.get_fields(taxonomy)
    return render_template('manage.html',
                           name=name,
                           collection=collection,
                           fields=fields)
예제 #8
0
def id(id):
    book = Book.query.filter_by(id=id).first()
    #id = book.id
    form = SelectForm(title=book.title,
                      author=book.author,
                      quantity=book.quantity,
                      price=book.price)

    if form.validate_on_submit():
        if form.delete.data:

            models.remove(id=id)
            return home()
        elif form.update.data:
            title = form.title.data
            author = form.author.data
            quantity = form.quantity.data
            price = form.price.data
            models.update(id, title, author, quantity, price)
            return home()

    return render_template("id.html", form=form)
예제 #9
0
    def prediction_show(self):
        '''
        show prediction, and emit signal with prediction to controller
        :return:
        '''
        # draw probability plot
        plot = models.update()
        cmd = None
        # write result
        if len(global_vars.jsonarray) > 0:
            prediction = max(global_vars.jsonarray,
                             key=lambda x: global_vars.jsonarray[x])
            if global_vars.jsonarray[prediction] * 100 > self.threshold:
                self.label_predict.setText(GESTURE_CLASSES[int(prediction)])
                cmd = GESTURE_CLASSES[int(prediction)]
        else:
            self.label_predict.setText('nothing')
        showImage = QtGui.QImage(plot.data, plot.shape[1], plot.shape[0],
                                 QtGui.QImage.Format_RGB888)
        self.label_probability.setPixmap(QtGui.QPixmap.fromImage(showImage))

        # emit sigal
        if cmd is not None and self.controller.status == 'online':
            self.signal_command_send.emit(cmd)
예제 #10
0
파일: app.py 프로젝트: s8888/STUDY_GROUP
 def put(self, book_id):
     # PUT http://[hostname]/api/books/[book_id] 更新書本資料
     args = self.reqparse.parse_args()
     return models.update(book_id, args)
예제 #11
0
 def put(self):
     update(request.json["id"], request.json["name"],
            request.json["status"], request.json["limit"])
예제 #12
0
def Main():
    global turn_on_prediction, model, binaryMode, bkgrndSubMode, mask, takebkgrndSubMask, x0, y0, width, height, saveImg, gestname, path
    quietMode = False

    font = cv2.FONT_HERSHEY_SIMPLEX
    size = 0.5
    fx = 10
    fy = 350
    fh = 18

    # Call CNN model loading callback
    while True:
        ans = int(input(banner))
        if ans == 1:
            model = models.load_model()
            if torch.cuda.is_available():
                model.cuda()
            break
        elif ans == 2:
            global_vars.use_gpu = False
            model = models.load_model()
            break
        elif ans == 3:
            model = models.load_model(False)
            models.trainModel(model)
            input("Press any key to continue")
            break

        else:
            print("Get out of here!!!")
            return 0

    ## Grab camera input
    cap = cv2.VideoCapture(0)
    cv2.namedWindow('Original', cv2.WINDOW_NORMAL)

    # set rt size as 640x480
    ret = cap.set(3, 640)
    ret = cap.set(4, 480)

    framecount = 0
    fps = ""
    start = time.time()

    plot = np.zeros((512, 512, 3), np.uint8)

    while (True):  # 持续识别
        ret, frame = cap.read()
        max_area = 0

        frame = cv2.flip(frame, 3)
        frame = cv2.resize(frame, (640, 480))

        # 图像预处理
        if ret == True:
            if bkgrndSubMode == True:
                roi = bkgrndSubMask(frame, x0, y0, width, height, framecount, plot)
            elif binaryMode == True:
                roi = binaryMask(frame, x0, y0, width, height, framecount, plot)
            else:
                roi = skinMask(frame, x0, y0, width, height, framecount, plot)


            framecount = framecount + 1
            end = time.time()
            timediff = (end - start)
            if (timediff >= 1):
                # timediff = end - start
                fps = 'FPS:%s' % (framecount)
                start = time.time()
                framecount = 0

            # roi = frame[y0:y0 + height, x0:x0 + width]
            # if turn_on_prediction == True and (framecount % 5) == 4:
            #     t = threading.Thread(target=myNN.guessGesture, args=[model, roi,False])
            #     t.start()

        cv2.putText(frame, fps, (10, 20), font, 0.7, (0, 255, 0), 2, 1)
        cv2.putText(frame, 'Options:', (fx, fy), font, 0.7, (0, 255, 0), 2, 1)
        cv2.putText(frame, 'b - Toggle Binary/SkinMask', (fx, fy + fh), font, size, (0, 255, 0), 1, 1)
        cv2.putText(frame, 'x - Toggle Background Sub Mask', (fx, fy + 2 * fh), font, size, (0, 255, 0), 1, 1)
        cv2.putText(frame, 'g - Toggle Prediction Mode', (fx, fy + 3 * fh), font, size, (0, 255, 0), 1, 1)
        cv2.putText(frame, 'q - Toggle Quiet Mode', (fx, fy + 4 * fh), font, size, (0, 255, 0), 1, 1)
        cv2.putText(frame, 'n - To enter name of new gesture folder', (fx, fy + 5 * fh), font, size, (0, 255, 0), 1, 1)
        cv2.putText(frame, 's - To start capturing new gestures for training', (fx, fy + 6 * fh), font, size,
                    (0, 255, 0), 1, 1)
        cv2.putText(frame, 'ESC - Exit', (fx, fy + 7 * fh), font, size, (0, 255, 0), 1, 1)

        ## If enabled will stop updating the main openCV windows
        ## Way to reduce some processing power :)
        if not quietMode:
            cv2.imshow('Original', frame)
            cv2.imshow('ROI', roi)

            if turn_on_prediction == True:
                # plot = np.zeros((512, 512, 3), np.uint8)
                plot = models.update()
                cv2.imshow('Gesture Probability', plot)

        ############## Keyboard inputs ##################
        key = cv2.waitKey(5) & 0xff

        ## Use Esc key to close the program
        if key == 27:
            break

        ## Use b key to toggle between binary threshold or skinmask based filters
        elif key == ord('b'):
            binaryMode = not binaryMode
            bkgrndSubMode = False
            if binaryMode:
                print("Binary Threshold filter active")
            else:
                print("SkinMask filter active")

        ## Use x key to use and refresh Background SubMask filter
        elif key == ord('x'):
            takebkgrndSubMask = True
            bkgrndSubMode = True
            print("BkgrndSubMask filter active")


        ## Use g key to start gesture predictions via CNN
        elif key == ord('g'):
            turn_on_prediction = not turn_on_prediction
            print("Prediction Mode - {}".format(turn_on_prediction))

        ## Use i,j,k,l to adjust ROI window
        elif key == ord('i'):
            y0 = y0 - 5
        elif key == ord('k'):
            y0 = y0 + 5
        elif key == ord('j'):
            x0 = x0 - 5
        elif key == ord('l'):
            x0 = x0 + 5

        ## Quiet mode to hide gesture window
        elif key == ord('q'):
            quietMode = not quietMode
            print("Quiet Mode - {}".format(quietMode))

        ## Use s key to start/pause/resume taking snapshots
        ## numOfSamples controls number of snapshots to be taken PER gesture
        elif key == ord('s'):
            saveImg = not saveImg

            if gestname != '':
                saveImg = True
            else:
                print("Enter a gesture group name first, by pressing 'n'")
                saveImg = False

        ## Use n key to enter gesture name
        elif key == ord('n'):
            gestname = input("Enter the gesture folder name: ")
            try:
                os.makedirs(gestname)
            except OSError as e:
                # if directory already present
                if e.errno != 17:
                    print('Some issue while creating the directory named -' + gestname)

            path = "./" + gestname + "/"

        # elif key != 255:
        #    print key

    # Realse & destroy
    cap.release()
    cv2.destroyAllWindows()