Exemplo n.º 1
0
def send_warning(user_id, message, seconds):
	""" Sends Timing warning to user for specified amount of time """

	print 'in send warning'
	time.sleep(seconds - 2)
	print 'after sleep'
	ut.send_response(message + str(seconds) + ' seconds.', user_id)
Exemplo n.º 2
0
def create_payment():
    form = PaymentForm()
    if form.validate_on_submit():
        payment = request.get_json()

        if not is_exists_invoices(invoice_list=[
                payment['number_invoice_provider'],
                payment['number_invoice_reciever']
        ]):
            return send_response(
                content={'message': 'Invoices does not exists'},
                status_code=404)

        key = get_payment_key()
        code_confirm = randint(100, 1000)

        db.session.add(
            Payment(key=key,
                    amount_money=payment['amount_money'],
                    number_invoice_provider=payment['number_invoice_provider'],
                    number_invoice_reciever=payment['number_invoice_reciever'],
                    code_confirm=code_confirm,
                    status_id=1))
        db.session.commit()

        send_code_confirm_payment_to_client(code=code_confirm)

        return send_response(content={'message': 'ok'}, status_code=200)

    return send_response(content=form.errors, status_code=400)
Exemplo n.º 3
0
def set(user, user_id, text):

	muscle_groups = defaultdict(list)

	text_muscles = [x.strip() for x in re.split(',|and',text) if x.strip()]
	
	#=====[ Check to see if each item in text matches against a muscle group ]=====
	for muscle in text_muscles:
		
		#=====[ Checks for individual muscles: e.g. lats, traps]=====
		if muscle in muscles:
			muscle_groups['specific'].append(muscle)
		#=====[ Checks for muscle groups: e.g. back, legs ]=====
		elif muscle in grouped_muscles:
			muscle_groups['group'].append(muscle)

	#=====[ If no muscle groups found, inform user of possible muscle groups to specify ]===== 
	if not len(muscle_groups):
		ut.send_response(GOAL_EXERCISES, user_id)
		return 
			
	#=====[ Update user object ]=====            
	user.goals = muscle_groups
	for key in user.goals.keys():
		print key
		for key2 in user.goals[key]:
			print key2
	ut.update(user_id, user)
	
	message = UPDATED_GOALS + ', '.join(user.goals['specific'])
	message += ', ' + ', '.join(user.goals['group']) if user.goals['group'] else ''

	ut.send_response(message, user_id)
Exemplo n.º 4
0
def respond(message, user):
	""" 
		Step 1: Extracts relevant info from user message 
		Step 2: Evaluate user status
		Step 3: send appropriate response 
	"""

	try:

		status = user.status
		if command.process(user, message):
			return

		if status == "intro":
			intro.process(user, message)

		elif status == "idle":
			idle.process(user, message)

		elif status == "workout":
			workout_log.process(user, message)

		elif status == "feedback":

			feedback.process(user, message)


	#=====[ If error caught, send user an error message and keep in same state ]=====
	except Exception as e:
		print e
		ut.send_response(ERROR_MESSAGE, user_id)
Exemplo n.º 5
0
def end_user_workout(user, user_id, workout):

	print 'in end workout'
	#=====[ Clear process timers to remind user to start next set ]=====
	clear_timers(user)

	#=====[ Record current workout and end time. Update user ]=====
	if workout.end():

		ut.send_response(END_WORKOUT_MESSAGE, user_id)

		#=====[ Send workout summary, stats, and spider chart ]=====
		ut.send_response(workout.get_summary(), user_id)
		ut.send_response(workout.get_stats(), user_id)

		ut.send_response(workout.summarize_muscle_groups(4), user_id)
		#=====[ Add workout to list of past workouts and put in idle mode ]=====
		user.add_workout(workout)

	else:
		user.current_workout = None
		user.status = 'idle'
		ut.update(user_id, user)
		
		ut.send_response(NO_WORKOUT_LOGGED, user_id)
	
	ut.update(user_id, user)
Exemplo n.º 6
0
def register_me(route_id):
    try:
        response = requests.get(SESSIONS_SERVICE_URL + 'identify/',
                                headers=clean_hh(request))
        if response.status_code != 200:
            return send_error(request, 403)
    except ConnectionError:
        return send_response(request, {'status': 'Session service is down'})

    user = response.json()['data']
    print({'USER': user})

    headers = {}

    headers.update({
        'X_EMAIL': user['email'],
        'X_SECRET': user['password'],
    })

    print({'HEADERS': headers})

    try:
        response = requests.post(ROUTE_SERVICE_URL +
                                 'route/%s/register/' % route_id,
                                 headers=headers)
        if response.status_code == 200:
            return send_response(request, {'status': 'OK'})
        return send_error(request, response.status_code)
    except ConnectionError:
        return send_response(request, {'status': 'Route service is down'})
Exemplo n.º 7
0
def personal_view():
    try:
        response = requests.get(SESSIONS_SERVICE_URL + 'identify/',
                                headers=clean_hh(request))
        if response.status_code != 200:
            return send_error(request, 403)
    except ConnectionError as e:
        return send_response(request, {'status': 'Session service is down'})

    user = response.json()['data']
    headers = {'X_EMAIL': user['email']}
    try:
        response = requests.get(COMPANY_SERVICE_URL + 'companies/',
                                headers=headers)
        if response.status_code == 200:
            companies = json.loads(response.text)
            user['companies'] = companies['data']
    except ConnectionError as e:
        user['companies'] = {'error': 'Company service is down'}

    try:
        response = requests.get(ROUTE_SERVICE_URL + 'my_routes/',
                                headers=headers)
        if response.status_code == 200:
            routes = json.loads(response.text)
            user['routes'] = routes['data']
    except ConnectionError as e:
        user['routes'] = {'error': 'Routes service is down'}

    return send_response(request, {'status': 'OK', 'data': user})
Exemplo n.º 8
0
def register_view(route_id):
    """
    curl -X post 'http://127.0.0.1:9093/route/586f9570050df411919ca465/register/' -H 'X_EMAIL: [email protected]' -H 'X_SECRET: ewifyw521763eyuwfgeuwYTWDYA'
    """
    idid = int(route_id)
    if not idid:
        return send_error(request, 404)

    email = request.headers.environ.get('HTTP_X_EMAIL')
    if not email:
        return send_error(request, 404)

    route = mongo.db.route.find({'self_id': idid})

    if route.count() == 0:
        return send_error(request, 404)

    route = cursor_to_list(route)[0]
    users_on_route = route.get('users', [])
    if email not in users_on_route:
        users_on_route.append(email)
        result = mongo.db.route.update_one({'self_id': idid},
                                           {'$set': {
                                               'users': users_on_route
                                           }})
        return send_response(request, {
            'status': 'OK',
            'updated': result.matched_count
        })
    else:
        return send_response(request, {'status': 'OK', 'updated': 0})
Exemplo n.º 9
0
def start(user):

	user_id = user.get_id()

	#=====[ Start workout ]=====
	user.status = "feedback"
	user.status_state = 0
	ut.update(user_id, user)

	ut.send_response(FEEDBACK_QUESTION, user_id)
Exemplo n.º 10
0
	def subroutine_intro(self, user_id):
		sub_state = self.workout_state[0]

		subroutine = self.template.workout.subroutines[sub_state]
		response = 'Subroutine is:\n'

		for exercise in subroutine.exercises:
			response += exercise + '\n'

		ut.send_response(response, user_id)
Exemplo n.º 11
0
def get_route_view(route_id):
    """
    curl -X get 'http://127.0.0.1:9093/route/586f956f050df411919ca464'
    curl -X delete 'http://127.0.0.1:9093/route/586f956f050df411919ca464'
    """
    idid = int(route_id)
    if not idid:
        return send_error(request, 404)

    if request.method == 'GET':
        route = mongo.db.route.find({'self_id': idid})
        route = cursor_to_list(route)
        print({'method': 'get', 'route': route})
        if len(route) > 0:
            return send_response(request, route[0])
        else:
            return send_error(request, 404)

    elif request.method == 'PATCH':
        #TODO: check company owner

        json_s = request.get_json(force=True)
        print(json_s)
        json_d = json.loads(json_s)
        print({"jayson": json_d})
        if json_d is None:
            return send_error(request, 400)

    #    route = {field: json_d[field] for field in ROUTE_FIELDS if json_d[field] is not None}
        route = {}
        for field in ROUTE_FIELDS:
            if field in json_d:
                value = json_d[field]
                if value is not None:
                    route.update({field: value})

        print({'method': 'patch', 'route': route})
        if len(route) == 0:
            return send_error(request, 400)

        route['updated'] = datetime.now()
        result = mongo.db.route.update({'self_id': idid}, {'$set': route})
        return send_response(request, {
            'status': 'OK',
            'updated': result['nModified']
        })

    elif request.method == 'DELETE':
        #TODO: check company owner

        result = mongo.db.route.delete_one({'self_id': idid})
        return send_response(request, {
            'self_id': idid,
            'deleted': result.deleted_count
        })
Exemplo n.º 12
0
def show_balance_invoice(num):
    try:
        invoice = Invoice.query.filter_by(num=num).first()
        return send_response(content={
            'message': 'ok',
            'balance': str(invoice.balance)
        },
                             status_code=200)
    except (KeyError, AttributeError):
        return send_response(
            content={'message': 'Number invoice does not exists'},
            status_code=404)
Exemplo n.º 13
0
	def __init__(self, user_id, workout_template):

		self.workout = Workout()
		print 'templates'
		self.template = pickle.loads(templates.find_one()['template_object'])
		print 'after templates'
		self.state = NOT_STARTED
		self.workout_state = None
		self.prev_user_set = None

		self.template.intro = 'Chest and Triceps'
		ut.send_response(self.template.intro, user_id)
		ut.send_response(START_WORKOUT, user_id)
Exemplo n.º 14
0
def confirm_payment():
    req = request.get_json()

    payment = Payment.query.filter_by(
        number_invoice_provider=req['invoice'],
        code_confirm=req['code_confirm']).scalar()

    if payment:
        return send_response(content={
            'message': 'ok',
            'key': payment.key
        },
                             status_code=200)

    return send_response(content={'message': 'Invalid code'}, status_code=400)
Exemplo n.º 15
0
def access_token_view():
    grant_type = request.form.get('grant_type')
    code = request.form.get('code')
    if grant_type.lower() != 'authorization_code' or not code:
        return send_error(request, 400)

    app = extract_client(request, OAUTH2_APPS)
    grant = mongo.db.OAuth2Code.find({
        'app': app['client_id'],
        'token': code,
        'expires': {
            '$gt': datetime.now()
        }
    })
    if grant.count() == 0:
        return send_error(request, 404)

    grant = cursor_to_list(grant)[0]
    token = {
        'expires': datetime.now() + timedelta(seconds=36000),
        'access_token': generate_token(),
        'refresh_token': generate_token(),
        'token_type': 'Bearer',
        'user': grant['user'],
    }
    mongo.db.OAuth2Access.insert(token)
    mongo.db.OAuth2Code.delete_one({'token': code, 'app': app['client_id']})
    token['expires'] = 36000
    return send_response(request, token)
Exemplo n.º 16
0
def login_view():
    if request.method == 'GET':
        auth = session.get('email')
        if auth:
            return render_template('yet_auth.html', email=auth)
        return render_template('login.html', url=request.url)

    elif request.method == 'POST':
        email = request.form.get('email')
        password = request.form.get('password')
        if not email or not password:
            return send_error(request, 400)

        password = get_hash(password.encode('ascii')).hexdigest()
        users_cursor = mongo.db.user.find({
            'email': email,
            'password': password
        })
        if users_cursor.count() == 0:
            return send_error(request, 404)

        user = cursor_to_list(users_cursor)[0]
        session['email'] = user['email']

        if 'next' in request.args:
            redirect_uri = unquote(request.args.get('next'))
            return redirect(redirect_uri)
        return send_response(request, {'status': 'Authorized'})
Exemplo n.º 17
0
def process_video(video_path, fps):

    video_frames = get_frames(video_path, fps)

    face_img_queue = mp.Queue()
    video_preds_queue = mp.Queue()

    face_detection_process = mp.Process(target=run_retinaface,
                                        args=(video_frames, face_img_queue))

    face_detection_process.start()
    video_face_imgs = face_img_queue.get()
    face_detection_process.join()

    emotion_detection_process = mp.Process(target=run_emotion_net,
                                           args=(video_face_imgs,
                                                 video_preds_queue))

    emotion_detection_process.start()
    video_frame_preds = video_preds_queue.get()
    emotion_detection_process.join()

    print('Video Successfully Processed')

    pred_dict = to_dict(video_frame_preds)
    r = send_response(pred_dict)

    if (r.status_code == 200):
        print("Predictions succesfully posted.")

    return video_frame_preds
Exemplo n.º 18
0
def process(user, message):

	user_id, text = ut.get_info(user, message)

	if "start" in text and "workout" in text:

		#=====[ Start guided workout ]=====
		if "guided" in text:
			workout_template = True
			workout_log.start(user, workout_template)

		#=====[ Manually log workout ]=====
		else:
			workout_log.start(user)

	#=====[ Send default message ]=====
	else:

		ut.send_response(DEFAULT_IDLE_MESSAGE, user_id)
Exemplo n.º 19
0
def process_request(connection, peer_info, request):
    utils.Logging.debug("Entering peer.process_request")
    if request.command == "RFCQuery":
        data = handle_rfcs_query(peer_info.rfc_index_head)
        status = "200"
        utils.send_response(connection, records.P2PResponse(status, data))
    elif request.command == "GetRFC":
        if "rfc" in request.data:
            metadata = read_rfc_metadata()
            if metadata:
                rfc = None
                for rfc_meta in metadata["rfcs"]:
                    if rfc_meta["number"] == request.data["rfc"]:
                        rfc = rfc_meta
                        break
                rfc_file = get_rfc_path(rfc)
                if rfc and os.path.exists(rfc_file):
                    utils.send_rfc(connection, rfc_file, rfc["format"])
                else:
                    status = "100"
                    data = {
                        "message":
                        "Requested RFC %s not found" % request.data["rfc"]
                    }
                    utils.send_response(connection,
                                        records.P2PResponse(status, data))
            else:
                status = "100"
                data = {
                    "message":
                    "Requested RFC %s not found" % request.data["rfc"]
                }
                utils.send_response(connection,
                                    records.P2PResponse(status, data))
        else:
            data = {"message": "Received GetRFC request without rfc field"}
            status = "300"
            utils.send_response(connection, records.P2PResponse(status, data))
    else:
        data = {"message": "Request message has an invalid command"}
        status = "300"
        utils.send_response(connection, records.P2PResponse(status, data))
Exemplo n.º 20
0
def auth():
    try:
        api_key = request.get_json()['api_key']
    except KeyError:
        return send_response(
            content={'message': 'Not sended api_key'},
            status_code=400
        )

    if not api_key:
        return send_response(
            content={'message': 'Api key required'},
            status_code=401
        )

    if not is_valid_api_key(api_key=api_key):
        return send_response(
            content={'message': 'Api key is not valid'},
            status_code=401
        )
Exemplo n.º 21
0
def my_routes_view():
    email = request.headers.environ.get('HTTP_X_EMAIL')
    print(request.headers)
    print(email)

    if not email:
        return send_error(request, 403)

    routes = mongo.db.route.find({'users': email})
    routes = cursor_to_list(routes)
    return send_response(request, {'status': 'OK', 'data': routes})
Exemplo n.º 22
0
def generate_spider(user_id, muscles):
    """ Generates a spider chart showing user's muscle_groups """

    values = muscles.values()
    values = [int(100*val/sum(values)) for val in values]
    labels = muscles.keys()

    #=====[ If just one muscle was worked, return to user with simple message ]=====
    if len(values) == 1:
        ut.send_response('Seems like you worked out a lot of ' + labels[0], user_id)
        return False

    #=====[ set font, linestyle, and fit parameters for chart ]=====
    font_size = 6
    label_font_size = 8
    matplotlib.rcParams.update({'font.size': font_size})
    matplotlib.rcParams.update({'figure.autolayout': True})
    plt.rc('grid', color='k', linewidth=1, linestyle=':',alpha=0.25)

    #=====[ Instantiate polar plot ]=====
    N = len(labels)
    theta = radar_factory(N, frame='circle')

    fig = plt.figure(figsize=(3,3))
    ax = fig.add_subplot(1,1,1,projection='radar')

    #=====[ Plot values, ideal values, and set labels ]=====
    ax.plot(theta, values, color='b')
    ax.fill(theta, values, color='b',alpha = 0.25)
    ax.set_varlabels(labels)
    ax.set_yticklabels([])

    #=====[ Get x,y locations for setting labels on spider chat ]=====
    radians = np.arange(np.pi/2,np.pi*9/4,np.pi*2/len(values))

    #=====[ Added percentage labels to each macro nutrient ]=====
    for idx, val in enumerate(values):
        ax.text(radians[idx],val + 5, str(val) + '%', fontsize=label_font_size,ha='center',va='center',color='k')

    fig.savefig('spider.png',dpi=300)
    return True
Exemplo n.º 23
0
def start(user, workout_template=None):
	""" Initializes users workout fields """

	user_id = user.get_id()
	
	user.time = datetime.datetime.now()
	user.status ="workout"

	#=====[ Updates user status state depending on whether workout is guided for free, manual entry ]=====
	if workout_template:
		user.status_state = GUIDED_WORKOUT
		user.workout_guider = WorkoutGuider(user_id, workout_template)

		#=====[ START GUIDED WORKOUT ]=====
	
	else:
		user.current_workout = Workout()
		user.status_state = FREE_WORKOUT
		ut.send_response(START_WORKOUT_MESSAGE, user_id)

	ut.update(user_id, user)
Exemplo n.º 24
0
def main():
    config = utils.load_config(args.config)
    head = None
    # sock = utils.listen4clients((utils.get_ip_address(), config["rs"]["port"]))
    sock = utils.listen4clients(
        (config["rs"]["hostname"], config["rs"]["port"]))
    last_time_updated = int(time.time())

    # Serve incoming connections
    while True:
        try:
            utils.Logging.info(records.display_swarm_table(head))
            connection, request = utils.accept_request(sock)
            periodic_ttl_reduction(head, last_time_updated)
            head, response = process_request(head, request)
            last_time_updated = int(time.time())
            utils.send_response(connection, response)
        except KeyboardInterrupt:
            utils.Logging.exit("Registration server shutting down")
            break
    sock.close()
Exemplo n.º 25
0
def routes_view():
    """
    curl -X get 'http://127.0.0.1:9093/routes/?size=2&page=1'
    """

    try:
        routes = mongo.db.route.find({}).sort('created', DESCENDING)
        result = paginate(request, data=routes)
        return send_response(request, result)

    except Error as e:
        return send_error(request, e.code)
Exemplo n.º 26
0
def create_company_view():
    """
    curl -X POST -H "Content-Type: application/json" 'http://127.0.0.1:9092/company/' \
    -d '{"abbreviation": "TTS", "name": "Transport Travel System", "info": null, "user": "******"}'
    """

    #TODO: create with owner
    json_s = request.get_json()
    if json_s is None:
    	return send_error(request, 400)
    json_d = json.loads(json_s)
    if json_d is None:
    	return send_error(request, 400)

    company = {field: json_d.get(field) for field in COMPANY_FIELDS}
    found = mongo.db.company.find({'abbreviation': company['abbreviation']}).count()
    if found > 0:
        return send_response(request, {'status': 'Such abbr already exists'})

    company['created'] = datetime.now()
    mongo.db.company.insert(company)
    return send_response(request, {'status': 'OK', 'data': company})
Exemplo n.º 27
0
def get_company_view(abbr):
    """
    curl -X GET 'http://localhost:9092/company/TTS/'
    curl -X PATCH -d '{"info": "Hello"}' -H "Content-Type: application/json" 'http://127.0.0.1:9092/company/TTS/'
    curl -X DELETE 'http://localhost:9092/company/TTS/'
    """

    if request.method == 'GET':
        company = mongo.db.company.find({'abbreviation': abbr})
        company = cursor_to_list(company)
        print({'method': 'get', 'company': company})
        
        if len(company) > 0:
            return send_response(request, company[0])
        else:
            return send_error(request, 404)

    elif request.method == 'PATCH':
        #TODO: check owner
        json_s = request.get_json()
        if json_s is None:
            return send_error(request, 400)
        json_d = json.loads(json_s)
        if json_d is None:
            return send_error(request, 400)

        company = {field: json_d.get(field) for field in COMPANY_FIELDS if field in json_d}
        if len(company) == 0:
            return send_error(request, 400)

        company['updated'] = datetime.now()
        result = mongo.db.company.update_one({'abbreviation': abbr}, {'$set': company})
        return send_response(request, {'status': 'OK', 'updated': result.modified_count})

    elif request.method == 'DELETE':
        #TODO: check owner

        result = mongo.db.company.delete_one({'abbreviation': abbr})
        return send_response(request, {'abbreviation': abbr, 'deleted': result.deleted_count})
Exemplo n.º 28
0
def companies_view():
    """
    curl -X GET 'http://localhost:9092/companies/?size=2&page=2'
    """

    find_params = {}
    email = request.headers.environ.get('HTTP_X_EMAIL')
    if email:
        find_params['user'] = email

    try:
        companies = mongo.db.company.find(find_params).sort('created', DESCENDING)
        result = paginate(request, data=companies)
        return send_response(request, result)

    except Error as e:
        return send_error(request, e.code)
Exemplo n.º 29
0
def create_route_view():
    """
    curl -X POST -H "Content-Type: application/json" 'http://127.0.0.1:9093/route/' \
    -d '{"name": "North Russia", "departure": "2015-10-10 12:00:00", "arrival": "2015-10-15 18:00:00", "price": 100, "company": "TTS"}'
    """

    #TODO: check company owner
    json_s = request.get_json(force=True)
    json_d = json.loads(json_s)
    if json_d is None:
        return send_error(request, 400)

    #route = {field: request.json.get(field) for field in ROUTE_FIELDS}
    route = {}
    for field in ROUTE_FIELDS:
        if field in json_d:
            value = json_d[field]
            if value is not None:
                route.update({field: value})
        else:
            route.update({field: None})

    if route['company'] is None:
        return send_error(request, 404)

    response = requests.get(COMPANY_SERVICE_URL + 'company/' +
                            route['company'])
    if response.status_code == 404:
        return send_error(request, 404)

    route['created'] = datetime.now()
    # max_response = mongo.db.route.find().sort({'self_id': -1}).limit(1)
    max_response = mongo.db.route.find({}, {'self_id': 1})

    print({'max_response': max_response})
    if max_response.count() == 0:
        route['self_id'] = int(1)
    else:
        max_id = 1
        for r in max_response:
            if r['self_id'] > max_id:
                max_id = r['self_id']
        route['self_id'] = int(max_id) + 1
    mongo.db.route.insert(route)
    return send_response(request, {'status': 'OK', 'data': route})
Exemplo n.º 30
0
	def process(self, text, user, user_id):
		""" 
			Processes user input for a given state

			state = NOT_STARTED ---> ask user to start
			state = IN_WORKOUT ---> log current set reported by user

			Returns bool representing successful parse and whether we should move on to next set

		"""

		#=====[ If user has not started workout ]=====
		if self.state == NOT_STARTED:
			if 'yes' in text:

				#=====[ hard coding timers for now ]=====
				self.template.workout.timer = [45, 60]
				user.timer = self.template.workout.timer
				ut.update(user_id, user)

				self.state = IN_WORKOUT
				self.workout_state = (0, -1)
				return (True, True)

			else:
				ut.send_response(START_WORKOUT,user_id)
				return (False, False)

		#=====[ If in workout, log state ]=====
		elif self.state == IN_WORKOUT:
			sub_state, set_state = self.workout_state

			user_set = ut.extract_exercise(text)

			if user_set:

				template_workout = self.template.workout
				sub_state, set_state = self.workout_state

				xsets = template_workout.subroutines[sub_state].get_flattened_sets()
				user_set.exercise = xsets[set_state].exercise

				#=====[ Log set and give feedback ]=====
				workout_log.log_set(user_set, self.workout, user, user_id)
				ut.send_response('Got your last set to be: ' + str(user_set), user_id)

				self.prev_user_set = user_set
				return (self.cur_set_feedback(user_set, xsets[set_state], user_id), True)
			else:
				ut.send_response('Exercise not recognized, please retry', user_id)
				return (False, False)
Exemplo n.º 31
0
def identify_view():
    auth_header = request.headers.environ.get('HTTP_AUTHORIZATION', '')
    if not auth_header.startswith('Bearer'):
        return send_error(request, 403)

    token = auth_header[7:]
    grant = mongo.db.OAuth2Access.find({
        'access_token': token,
        'expires': {
            '$gt': datetime.now()
        }
    })
    if grant.count() == 0:
        return send_error(request, 403)

    grant = cursor_to_list(grant)[0]
    user_cursor = mongo.db.user.find({'email': grant['user']})
    if user_cursor.count() != 1:
        return send_error(request, 403)

    user_data = cursor_to_list(user_cursor)[0]
    return send_response(request, {'status': 'OK', 'data': user_data})
Exemplo n.º 32
0
def login():
    if session.get('user_id'):
        return send_response({'message':'you are already logged in'})
    auth = request.authorization
    if auth:
        username =  auth.username
        password = auth.password
        user = current_app.db.users.find_one({'username':username})
        if user:
            if current_app.bcrypt.check_password_hash(user['password'], password):
                session['user_id'] = user['user_id']
                return send_response({'message':'login successful'})
            else:
                return send_response({'message':'wrong passphrase'},status=400)
        else:
            if not username:
                return send_response({'message':'provide a username'},status=400)
            else:
                return send_response({'message':'unknown user "{0}"'.format(username)},status=400)
    else:
        return send_response({'message':'username and password required'},status=400)
Exemplo n.º 33
0
def process(user, message):

	user_id, text = ut.get_info(user, message)

	#==========[ Command used to list all super commands for the workout logger ]==========#
	#																				       #
	#	usage: " list commands "									   					   #
	#																					   #
	########################################################################################

	if ('list' in text and 'commands' in text) or text == 'ls':

		ut.send_response('Here are a list of commands:\n\n' + '\n'.join(command_list.keys()), user_id)


	#=====[ Command used to log thoughts/improvements while using the workout logger ]=====#
	#																				       #
	#	usage: " sudo log: [suggestion to improve] "									   #
	#																					   #
	########################################################################################

	elif 'sudo' in text and 'log' in text and ':' in text:

		with open('to_improve_log','a') as f:
			f.write(text.split(':')[1].strip() + '\n\n')

		ut.send_response(MESSAGE_LOGGED, user_id)

	############################################################################
	############################################################################
	#################TODO TODO TODO TODO TODO TODO TODO#########################
	####################IMPLEMENT LISTING WORKOUTS##############################
	############################################################################

	elif 'list' in text and 'template' in text and 'workouts' in text:

		saved_workouts = '1. Chest Gains | Sets: 24\nTime: 1 hour\nMuscles: Chest, Triceps\n\n2. Ab Attack | Sets: 15\nTime: 20 minutes\nMuscles: Abs, Obliques\n\n3. Leg Day | Sets: 28\nTime: 1 hour 20 minutes\nMuscles: Quads, Hamstrings, Calves'
		ut.send_response(saved_workouts, user_id)


	#=========================[ Command used list recent workouts ]========================#
	#																				       #
	#	usage: " list workouts "									   					   #
	#																					   #
	########################################################################################

	elif 'list' in text and 'workouts' in text:

		ut.send_response('\n'.join([str(idx + 1) + '. ' + str(workout) for idx, workout in enumerate(reversed(user.workouts))]), user_id)


	#=====================[ Command used to review most recent workout ]===================#
	#																				       #
	#	usage: " review last workout "									   				   #
	#																					   #
	########################################################################################

	elif 'review' in text and 'last' in text and 'workout' in text:

		workout = user.workouts[-1]

		ut.send_response(workout.get_summary(), user_id)
		ut.send_response(workout.get_stats(),user_id)

		ut.send_response(workout.summarize_muscle_groups(4), user_id)
		# index = index if len(workout.muscle_groups) >= index else len(workout.muscle_groups)

		# if generate_spider(user_id, dict(workout.muscle_groups.most_common(index))):
		# 	ut.send_response('Check out the muscles you targeted:\nfile:///Users/Brandon/Desktop/Projects/workout_logger/spider.png', user_id)

	
	#==================[ Command used to review a particular workout ]=====================#
	#																				       #
	#	usage: " review workout: [index] "									   			   #
	#																					   #
	########################################################################################

	elif 'review' in text and 'workout' in text:

		try: 
			
			idx = int(ut.extract_int(text))
			workout = user.workouts[-idx]

			ut.send_response(user.workouts[-idx].get_summary(), user_id)
			ut.send_response(user.workouts[-idx].get_stats(), user_id)

			ut.send_response(workout.summarize_muscle_groups(4), user_id)

			# index = 4 if len(workout.muscle_groups) > 3 else len(workout.muscle_groups)

			# if generate_spider(user_id, dict(workout.muscle_groups.most_common(index))):
			# 	ut.send_response('Check out the muscles you targeted:\nfile:///Users/Brandon/Desktop/Projects/workout_logger/spider.png', user_id)

		except Exception as e:
			
			print e


	#==================[ Command used to remove a particular workout ]=====================#
	#																				       #
	#	usage: " remove workout: [index] "									   			   #
	#																					   #
	########################################################################################

	elif 'remove' in text and 'workout' in text:

		try: 
			
			idx = int(ut.extract_int(text))
			workout = user.workouts[-idx]

			ut.send_response('Deleted workout: ' + str(workout), user_id)

			del user.workouts[-idx]

			ut.update(user_id, user)

		except Exception as e:
			
			print e


	#=============[ Command used to review a weeks worth of workout stats ]================#
	#																				       #
	#	usage: " review week "									   			   			   #
	#																					   #
	########################################################################################

	elif 'review' in text and 'week' in text:

		info = 'Here\'s your week in review: \n\n'

		info += 'Total Volume: ' + str(user.get_volume(7)) + '\n'
		info += 'Total Sets: ' + str(user.get_num_sets(7)) + '\n' 
		info += 'Total Time: ' + "{0:.2f}".format(float(user.get_total_set_time(7)/3600.0)) + ' hours' + '\n'
		info += 'Avg. Set Time: ' + "{0:.2f}".format(user.get_avg_set_time(7)) + '\n'

		ut.send_response(info, user_id)

		ut.send_response(user.get_muscle_groups(7, 7), user_id)
		
		if hasattr(user, 'goals'):
			goal.review(user, user_id, 7, 7)

		# index = 6 if len(workout.muscle_groups) > 5 else len(workout.muscle_groups)

		# if generate_spider(user_id, dict(user.get_muscle_groups(7).most_common(index))):
		# 	ut.send_response('Check out the muscles you targeted most:\nfile:///Users/Brandon/Desktop/Projects/workout_logger/spider.png', user_id)
		
	elif 'q:' in text or 'query:' in text:
		exercise = text.split(':')[1].strip()
		info = 'You queried for: %s\n\n' % exercise
		print 'before query'
		sets = user.query_exercise(exercise)
		print 'after query'
		if sets:
			for date in sets:
				workout_sets = sets[date]

				info += "Workout on %s:\n" % date

				for xset in workout_sets:
					info += "%s reps of %s @ %s\n" % (xset.reps, xset.exercise, xset.weight)

			ut.send_response(info, user_id)
		else:
			ut.send_response("Sorry, I couldn't find any sets of " + exercise, user_id)


	#==================[ Command used to drop a user from the database ]===================#
	#																				       #
	#	usage: " reset db "									   			   			   	   #
	#																					   #
	########################################################################################

	elif text == 'reset db':
		
		ut.send_response('BYE FOREVER! :( ', user_id)
		ut.remove_user(user_id)


	#==================[ Command used set goals for targeted muscles ]=====================#
	#																				       #
	#	usage: " set goals: muslce1, muscle2, muscle3"			   			   			   #
	#																					   #
	########################################################################################

	elif 'set' in text and 'goal' in text:

		muscle_groups = text.split(':')

		#=====[ Check to make sure there are muscle groups specified after a colon ]=====
		if len(muscle_groups) == 1:
			ut.send_response(SET_GOALS, user_id)

		#=====[ set goals for user ]=====
		goal.set(user, user_id, muscle_groups[1])

	#================[ Command used set timers at specified intervals ]====================#
	#																				       #
	#	usage: " set timer for 45 and 60 seconds"			   			   			       #
	#																					   #
	########################################################################################

	elif 'set' in text and 'timer' in text:

		times = re.split(',|and',text)
		found_time = False

		#=====[ Checks each comma separated value for a time ]=====
		for time_candidate in times:

			time = extract_int(time_candidate)

			#=====[ If time for timer extracted, save info ]=====
			if time:
				
				found_time = True

				if hasattr(user,'timer'):
					user.timer.append(time)
				else:
					user.timer = [time]

		#=====[ Tell user how to set timer ]=====
		if not found_time:
			ut.send_response(HOW_TO_SET_TIMER, user_id)
		else:
			ut.send_response(SET_TIMER + ', '.join([str(x) for x in user.timer]) + ' seconds', user_id	)
			ut.update(user_id, user)

	#========================[ Command used to clear all timers ]==========================#
	#																				       #
	#	usage: " clear timer "			   			   			       					   #
	#																					   #
	########################################################################################

	elif 'clear' in text and 'timer' in text:

		user.timer = []
		ut.send_response(CLEARED_TIMER, user_id)
		ut.update(user_id, user)

	#========================[ Command used to exit to idle mode ]=========================#
	#																				       #
	#	usage: " exit "			   			   			       					  	 	   #
	#																					   #
	########################################################################################

	elif text == 'exit':
		
		user.status = 'idle'
		ut.send_response(IDLE_MODE, user_id)
		ut.update(user_id, user)

	#=====================[ Command used to get help for any command ]=====================#
	#																				       #
	#	usage: " help [command] "			   			   			       				   #
	#																					   #
	########################################################################################

	elif 'help' in text:

		user_command = text.replace('help','').strip()

		#=====[ Check if user command is in our command shortcut list. If so, send appropriate help response ]=====
		for command in command_shortcuts:
			
			if user_command in command_shortcuts[command]:
				
				ut.send_response(command_list[command], user_id)
				return True

		#=====[ Tell user that we couldn't find specified command and send list of commands ]=====
		ut.send_response(HELP_COMMAND, user_id)
		ut.send_response('Here are a list of commands:\n\n' + '\n'.join(command_list.keys()), user_id)

	#===================[ Command used to learn how to log a workout ]=====================#
	#																				       #
	#	usage: " how to log?" | "how do I log a workout? "  			       				   #
	#																					   #
	########################################################################################

	elif 'how' in text and 'log' in text:

		user.status = "intro"
		user.status_state = 1
		intro.process(user, message, instructions=True)

	#==========================[ Command used to greet user ]==============================#
	#																				       #
	#	usage: Greet Tony: 'Hi'  			       			   							   #
	#																					   #
	########################################################################################
	
	elif text in greetings:

		ut.send_response(GREETING, user_id)

	elif 'thank' in text:

		ut.send_response(NO_PROBLEM, user_id)
		ut.send_response(np.random.choice(INSPIRATIONAL),user_id)

	else:

		return False

	return True
Exemplo n.º 34
0
                            valid_to_str, "%d/%m/%Y").replace(
                            tzinfo=pytz.utc)
                        valid_to_out = hh_format(valid_to)
                    pt = sess.query(MeterType).filter(
                        MeterType.code == code).first()
                    if pt is None:
                        yield ','.join(
                            (
                                '"' + str(v) + '"' for v in (
                                    'insert', 'meter_type', code, description,
                                    valid_from_out, valid_to_out))) + "\n"

                    elif (description, valid_from, valid_to) != (
                            pt.description, pt.valid_from, pt.valid_to):
                        yield ','.join(
                            (
                                '"' + str(v) + '"' for v in (
                                    'update', 'meter_type', code, description,
                                    valid_from_out, valid_to_out))) + "\n"
            else:
                raise Exception("The table " + table + " is not recognized.")

        finally:
            if sess is not None:
                sess.close()

    utils.send_response(
        inv, content, file_name=table + '_' + version + '_general_import.csv')
else:
    raise UserException("HTTP method not recognized.")
Exemplo n.º 35
0
	def next_set(self, user_id):
		sub_state, set_state = self.workout_state

		# Get the subroutine of the current set
		curr_subroutine = self.template.workout.subroutines[sub_state]

		set_state += 1

		if set_state >= curr_subroutine.num_sets:
			set_state = 0
			sub_state += 1

		if sub_state >= len(self.template.workout.subroutines):
			return None


		# Update curr_subroutine after updating indexes
		curr_subroutine = self.template.workout.subroutines[sub_state]
		sets_per_cycle = len(curr_subroutine.exercises)
		subroutine_mode = curr_subroutine.mode

		# Update object workout state
		self.workout_state = (sub_state, set_state)

		# set_state == 0 means we are starting a new subroutine
		if set_state == 0:
			self.subroutine_intro(user_id)

			self.workout.add_subroutine()

			next_subroutine = self.template.workout.subroutines[sub_state]
			self.workout.new_subroutine(next_subroutine.mode, next_subroutine.exercises)

		# If we are at the beginning of a cycle in a circuit
		if subroutine_mode == "circuit" and set_state % sets_per_cycle == 0:
			response = "Next Cycle of Circuit: \n"

			sets = self.template.workout.subroutines[sub_state].get_flattened_sets()
		
			for i in range(sets_per_cycle):
				xset = sets[set_state + i]
				response += xset.exercise + ' ' + str(xset) + "\n"

			ut.send_response(response, user_id)

		# TODO: FOR BRANDON
		# get_feedback - current user set, current template set, next template set (None for diff subroutine)

		response = "Your next set is: "

		sets = self.template.workout.subroutines[sub_state].get_flattened_sets()
		xset = sets[set_state]

		response += xset.exercise + ' ' + str(xset.reps) + " reps\n"

		message = True
		#=====[ Give feedback for up and coming set ]=====
		if self.prev_user_set:
			message = self.next_set_feedback(self.prev_user_set, xset, user_id)

		ut.send_response(response, user_id)

		print 'message to return is:', message
		print self.workout_state
		print set_state
		
		if self.workout_state:
			return (message, False) if set_state != 0 else (message, True)
		else:
			return (self.workout_state, False)
Exemplo n.º 36
0
            if hh_before(era.finish_date, finish_date):
                chunk_finish = era.finish_date
            else:
                chunk_finish = finish_date

            yield imp_mpan_core_str + ',' + exp_mpan_core_str + ',' + \
                hh_format(chunk_start) + ',' + hh_format(chunk_finish) + ','
            supply_source = computer.SupplySource(
                sess, chunk_start, chunk_finish, forecast_date, era, is_import,
                None, caches)
            supply_source.contract_func(contract, 'virtual_bill')(
                supply_source)
            bill = supply_source.dc_bill
            for title in bill_titles:
                yield '"' + str(bill.get(title, '')) + '",'
                if title in bill:
                    del bill[title]
            keys = bill.keys()
            keys.sort()
            for k in keys:
                yield ',"' + k + '","' + str(bill[k]) + '"'
            yield '\n'

    except:
        yield traceback.format_exc()
    finally:
        if sess is not None:
            sess.close()

utils.send_response(inv, content, file_name='hhdc_vbs.csv')
Exemplo n.º 37
0
def review(user, user_id, days=7, num_muscles=7):
	""" Provides feedback on muscles targeted over the past week """

	#=====[ Get muscle groups and target muscle groups ]=====
	values, labels = user.get_muscle_groups(days, num_muscles, False)
	target_muscles = user.goals

	#=====[ Initialize holders ]=====
	summary = ''
	not_targeted = []
	barely_targeted = []
	not_targeted_groups = defaultdict(list)
	barely_targeted_groups = defaultdict(list)

	#=====[ Get indices of muscles that have been heavily focused on ]=====
	focus_idxs = [idx for idx, val in enumerate(values) if val > 30]

	if focus_idxs:
		ut.send_response("You've focused heavily on " + ', '.join([labels[idx] for idx in focus_idxs]), user_id)

	#=====[ Check to see if each specific target muscle has been worked out and, if it has, to what degree ]=====
	for muscle in target_muscles['specific']:
		if muscle not in labels:

			not_targeted.append(muscle)

		else:
			
			idx = labels.index(muscle)
			
			if values[idx] < 10:
				barely_targeted.append(muscle)

	#=====[ Check to see which (if any) specific target muscles within specified larger muscle groups have been worked out, 
	#=====[ and, if they have, to what degree 
	for muscle_group in target_muscles['group']:

		for muscle in grouped_muscles[muscle_group]:

			if muscle not in labels:

				not_targeted_groups[muscle_group].append(muscle)

			else:
				
				idx = labels.index(muscle)
				
				if values[idx] < 10:
					barely_targeted_groups[muscle_group].append(muscle)

	#=====[ Formulate muscle review message for specific muscles ]=====
	message = ''
	
	for muscle in not_targeted:

		message += 'You have not targeted ' + ', '.join(not_targeted) + ' at all. '

	for muscle in barely_targeted:

		message += 'You have not focused much on ' + ', '.join(barely_targeted) + '. '

	#=====[ Send update for specific muscles ]=====
	if message:
		ut.send_response(message, user_id)

	message = ''

	#=====[ Formulate muscle review message for muscle groups ]=====
	for muscle_group in not_targeted_groups:

		message += "You wanted to focus on " + muscle_group + ", but you have not worked out " + ', '.join(not_targeted_groups[muscle_group]) + '. '

	for muscle_group in barely_targeted_groups:

		message += "For " + muscle_group + ", you've barely worked out " + ', '.join(barely_targeted_groups[muscle_group]) + '. '

	if message: 
		ut.send_response(message, user_id)
Exemplo n.º 38
0
                    elif cur_sup is not None and \
                            prev_sup is not None and cur_sup != prev_sup:
                        add_event(
                            events, era.start_date, "Change Of Supplier", None,
                            mpan_core)

                prev_era = era

            if len(events) > 0:
                site = sess.query(Site).join(SiteEra).filter(
                    SiteEra.is_physical == true(),
                    SiteEra.era == last_era).one()

                for event in events:
                    vals = [
                        event['mpan-core'], site.code, site.name,
                        event['date'].strftime("%Y-%m-%d %H:%M"),
                        event['code']]
                    yield '\n' + ','.join(
                        '"' + str(val) + '"' for val in vals) + ','
            else:
                yield ' '
    except:
        yield traceback.format_exc()
    finally:
        sess.close()

utils.send_response(
    inv, content, status=200, mimetype='text/csv',
    file_name='output.csv')
Exemplo n.º 39
0
def method_not_allowed(e):
    return send_response(content={'message': 'Method not allowed'},
                         status_code=405)
Exemplo n.º 40
0
                                    else:
                                        metering_type = 'nhh'

            for group in site.groups(sess, start_date, finish_date, True):
                for supply in group.supplies:
                    sources.add(supply.source.code)
                    generator_type = supply.generator_type
                    if generator_type is not None:
                        generator_types.add(generator_type.code)

                for hh in group.hh_data(sess):
                    for stream in streams:
                        totals[stream] += hh[stream]

            assoc_str = ','.join(sorted(list(assoc)))
            sources_str = ','.join(sorted(list(sources)))
            generators_str = ','.join(sorted(list(generator_types)))
            yield ','.join('"' + str(v) + '"' for v in (
                site.code, site.name, assoc_str, sources_str, generators_str,
                start_date.strftime("%Y-%m-%d %H:%M"),
                finish_date.strftime("%Y-%m-%d %H:%M"), totals['imp_net'],
                totals['displaced'], totals['exp_net'], totals['used'],
                totals['exp_gen'], totals['imp_gen'], metering_type)) + '\n'
    except:
        yield traceback.format_exc()
    finally:
        if sess is not None:
            sess.close()

utils.send_response(inv, content, file_name='sites_duration.csv')
Exemplo n.º 41
0
                        sorted(
                            set(
                                sup.generator_type.code for sup in
                                group.supplies
                                if sup.generator_type is not None)))
                    group_start_str = hh_format(group.start_date)
                    group_finish_str = hh_format(group.finish_date)
                    for hh in group.hh_data(sess):
                        hh_start = hh['start_date']
                        if hh_start.hour == 0 and hh_start.minute == 0:
                            yield "\r\n" + \
                                ','.join(
                                    '"' + str(val) + '"' for val in [
                                        site.code, site.name, associates,
                                        source_codes, gen_types,
                                        group_start_str, group_finish_str,
                                        'used', hh_start.strftime('%Y-%m-%d')])
                        used_gen_kwh = hh['imp_gen'] - hh['exp_net'] - \
                            hh['exp_gen']
                        used_3p_kwh = hh['imp_3p'] - hh['exp_3p']
                        used_kwh = hh['imp_net'] + used_gen_kwh + used_3p_kwh
                        yield ',' + str(round(used_kwh, 2))
        except:
            yield traceback.format_exc()
        finally:
            if sess is not None:
                sess.close()

utils.send_response(
    inv, content, status=200, mimetype=mime_type, file_name=file_name)
Exemplo n.º 42
0
                        "",
                        era.pc.code,
                        "",
                        era.mtc.code,
                        "",
                        llfc.code,
                        "",
                        ssc,
                        "",
                        supplier_contract.party.participant.code,
                        "",
                        dc,
                        "",
                        mop,
                        "",
                        supply.gsp_group.code,
                        "",
                        msn,
                        "",
                        meter_type,
                        "In Chellow, but not in ECOES.",
                    ]
                )
        except:
            yield traceback.format_exc()
        finally:
            if sess is not None:
                sess.close()

    utils.send_response(inv, content, file_name="output.csv")
Exemplo n.º 43
0
                        None)
                    disp_func(site_ds)
                    bill = site_ds.supplier_bill
                    for title in bill_titles:
                        if title in bill:
                            val = bill[title]
                            if isinstance(val, datetime.datetime):
                                val = hh_format(val)
                            else:
                                val = str(val)
                            yield ',"' + val + '"'
                            del bill[title]
                        else:
                            yield ',""'

                    keys = bill.keys()
                    keys.sort()
                    for k in keys:
                        yield ',"' + k + '","' + str(bill[k]) + '"'
                    yield '\n'

                month_start += relativedelta(months=1)
                month_finish = month_start + relativedelta(months=1) - HH
    except:
        yield traceback.format_exc()
    finally:
        if sess is not None:
            sess.close()

utils.send_response(inv, content, file_name='displaced.csv')
Exemplo n.º 44
0
@import url(https://fonts.googleapis.com/css?family=Overclock);
table {
    border: thin solid gray;
    border-collapse: collapse;
}

td {
    border: thin solid gray;
    padding-left: 0.2em;
    padding-right: 0.2em;
}
th {
    border: thin solid gray;
}
#title {
    font-size: xx-large;
}
.logo {
    color: green;
}


body {
    line-height: 1.2;
    font-size: 0.9em;
    font-family: 'Overclock', sans-serif;
    background-color: rgb(255, 236, 139);
}
'''
utils.send_response(inv, content, 200, mimetype='text/css')
Exemplo n.º 45
0
#!/usr/bin/env python

import cgitb; cgitb.enable()
import sys
import os
sys.path.append(os.path.dirname(__file__))
import utils
from utils import Headers

#utils.send_response('test')

origin = os.environ.get('HTTP_ORIGIN', '*')

headers = Headers()
headers['Access-Control-Allow-Origin'] = origin
headers['Access-Control-Allow-Credentials'] = 'true'
headers['Set-Cookie'] = 'sessionid=1234'
headers['Set-Cookie'] = 'sessionid2=5678; HttpOnly'


html = """
Please enter your name:
<input type="text" id="name" />
<button onclick="document.cookie='name='+document.getElementById('name').value;location.reload()">Save</button>
"""

if utils.get_cookie('name'):
    html = "Hello %s" % (utils.get_cookie('name') or 'nobody')

utils.send_response(html, headers)
Exemplo n.º 46
0
def process(user, message, instructions=False):
	""" Introduces a user to the workout chatbot and to logging workouts """

	user_id, text, status_state = ut.get_info(user, message, True)

	if status_state == 0:

		#=====[ Send introduction messages to user ]=====
		ut.send_response(WELCOME_MESSAGE, user_id)
		ut.send_response(COMMAND_INTRO, user_id)
		ut.send_response(WORKOUT_INTRO, user_id)

		user.status_state = 1

	#=====[ Begins teaching a user how to log a workout ]=====	
	elif status_state == 1:

		#=====[ Check if user said yes to learning about working out ]=====
		for word in yes_words:			
			if word in text:
				instructions = True
				break

		if instructions:
			#=====[ Send instructions for starting workout, logging sets, and ask if they want to learn about logging circuits ]=====
			ut.send_response(WORKOUT_START_INSTRUCTIONS, user_id)
			ut.send_response(WORKOUT_SET_INITIALIZATION, user_id)
			ut.send_response(WORKOUT_SET_CONTINUATION, user_id)
			ut.send_response(LEARN_ABOUT_CIRCUITS, user_id)

			user.status_state = 2

		else:
			
			user.status = "idle"
			user.status_state = 0
			ut.send_response(DONE_INSTRUCTIONS, user_id)


	#=====[ Processes message when user is learning about logging workouts. Currently, just checks to see if user wants to learn 
	#=====[ about logging circuits ]=====
	elif status_state == 2:

		user_id, text = ut.get_info(user, message)

		#=====[ Check if user gave a 'yes' word. If so gives information about logging circuits ]=====
		for word in yes_words:
			
			if word in text:
			
				#=====[ Teach user how to log circuits ]=====
				ut.send_response(WORKOUT_CIRCUIT_INITIALIZATION, user_id)
				ut.send_response(WORKOUT_CIRCUIT_CONTINUATION, user_id)

		ut.send_response(ASK_SEE_EXAMPLE, user_id)
		user.status_state = 3

	elif status_state == 3:

		#=====[ Update user into idle mode regardless of whether they wish to learn about circuits or not ]=====
		user.status = "idle"
		user.status_state = 0
		ut.update(user_id, user)

		#=====[ Check if user gave a 'yes' word. If so gives information about logging circuits ]=====
		for word in yes_words:
			
			if word in text:
			
				#=====[ Teach user how to log circuits ]=====
				ut.send_response(WORKOUT_EXAMPLE, user_id)
				return

		#=====[ Checks if user gave a 'no' word ]=====
		for word in no_words:

			if word in text:

				ut.send_response(DONE_INSTRUCTIONS, user_id)
				return

		#=====[ If no 'yes' or 'no' word found, then just assume user doesn't want to learn about logging circuits ]=====
		ut.send_response(ASSUME_DONE_INSTRUCTIONS, user_id)

	#=====[ update user (primarily state) in db ]=====
	ut.update(user_id, user)
Exemplo n.º 47
0
Monad.getUtils()['impt'](globals(), 'db', 'utils', 'templater')
inv = globals()['inv']


def content():
    sess = None
    try:
        sess = db.session()
        yield "Supply Id, Note Index, Category, Is Important?, Body\n"

        for supply in sess.query(db.Supply).order_by(db.Supply.id):
            try:
                supply_note = eval(supply.note)
            except SyntaxError:
                continue
            for i, note in enumerate(supply_note['notes']):
                vals = [
                    supply.id, i, note['category'], note['is_important'],
                    note['body']]
                vals = map(unicode, vals)
                for i, val in enumerate(vals):
                    vals[i] = val.replace('"', '""')
                yield ','.join('"' + v + '"' for v in vals) + '\n'
    except:
        yield traceback.format_exc()
    finally:
        if sess is not None:
            sess.close()

utils.send_response(inv, content, file_name='notes.csv')
Exemplo n.º 48
0
                    yield ','.join('"' + str(value) + '"' for value in [
                        data_source.mpan_core, site.code, site.name,
                        data_source.supplier_account,
                        hh_format(data_source.start_date),
                        hh_format(data_source.finish_date)])

                    computer.contract_func(
                        caches, contract, 'virtual_bill', None)(data_source)
                    bill = data_source.supplier_bill
                    for title in bill_titles:
                        if title in bill:
                            val = str(bill[title])
                            del bill[title]
                        else:
                            val = ''
                        yield ',"' + val + '"'

                    for k in sorted(bill.keys()):
                        yield ',"' + k + '","' + str(bill[k]) + '"'
                    yield '\n'

            month_start += relativedelta(months=1)
            month_finish = month_start + relativedelta(months=1) - HH
    except:
        yield traceback.format_exc()
    finally:
        if sess is not None:
            sess.close()

utils.send_response(inv, content, file_name='virtual_bills.csv')
Exemplo n.º 49
0
def exchange_format():
    if not request.is_json:
        return send_response(
            content={'message': 'Not valid format data. Need JSON!'},
            status_code=400
        )
Exemplo n.º 50
0
                    ss.mpan_core, site.code, site.name, ss.supplier_account,
                    hh_format(ss.start_date), hh_format(ss.finish_date)])

                computer.contract_func(
                    caches, sup_con, 'virtual_bill', None)(ss)
                bill = ss.supplier_bill
                for title in bill_titles:
                    if title in bill:
                        val_raw = bill[title]
                        if isinstance(val_raw, datetime.datetime):
                            val = hh_format(val_raw)
                        else:
                            val = str(val_raw)

                        yield ',"' + val + '"'
                        del bill[title]
                    else:
                        yield ',""'

                for k in sorted(bill.keys()):
                    yield ',"' + k + '","' + str(bill[k]) + '"'
                yield '\n'
            day_start += relativedelta(days=1)
    except:
        yield traceback.format_exc()
    finally:
        if sess is not None:
            sess.close()

utils.send_response(inv, content, file_name='daily_supplier_virtual_bill.csv')
Exemplo n.º 51
0
                Snag.start_date < cutoff_date).order_by(
                Site.code, Supply.id, Channel.imp_related,
                Channel.channel_type, Snag.description,
                Snag.start_date, Snag.id):
            snag_start = snag.start_date
            snag_finish = snag.finish_date
            if snag_finish is None:
                snag_finish_str = ''
                duration = now - snag_start
                age_of_snag = datetime.timedelta(0)
            else:
                snag_finish_str = snag_finish.strftime("%Y-%m-%d %H:%M")
                duration = snag_finish - snag_start
                age_of_snag = now - snag_finish

            yield ','.join('"' + str(val) + '"' for val in [
                days_hidden, snag.id, era.imp_mpan_core, era.exp_mpan_core,
                site.code, site.name, snag.description, channel.imp_related,
                channel.channel_type, snag_start.strftime("%Y-%m-%d %H:%M"),
                snag_finish_str,
                age_of_snag.days + float(age_of_snag.seconds) / (3600 * 24),
                duration.days + float(duration.seconds) / (3600 * 24),
                snag.is_ignored]) + '\n'
    except:
        yield traceback.format_exc()
    finally:
        if sess is not None:
            sess.close()

utils.send_response(inv, content, file_name=file_name)
Exemplo n.º 52
0
def process(user, message):

	user_id, text = ut.get_info(user, message)
	workout = user.get_last_workout()

	rating = extract_int(text)
	print rating

	#On feedback question
	if user.status_state == 0:

		if "yes" in text or "ok" in text:
			ut.send_response(RATING_QUESTION, user_id)
			user.status_state = 1

		elif "no" in text:
			ut.send_response(NO_FEEDBACK, user_id)
			user.status = "idle"
			user.status_state = 0

		else:
			ut.send_response(FEEDBACK_CLARIFY, user_id)
			ut.send_response(FEEDBACK_QUESTION, user_id)

		ut.update(user_id, user)


	# On rating question
	elif user.status_state == 1:

		if rating:

			if rating >= 1 and rating <= 10:
				workout.rating = rating
				ut.send_response(QUESTION_END, user_id)
				user.status_state = 2
				ut.update(user_id, user)
				ut.send_response(DIFFICULTY_QUESTION, user_id)
				return

		# If anything goes wrong, send a clarifying message
		ut.send_response(RATING_CLARIFY, user_id)
		ut.send_response(RATING_QUESTION, user_id)

		


	# On difficulty question
	elif user.status_state == 2:
		
		if rating:
			if rating >= 1 and rating <= 5:
				workout.rating = rating
				ut.send_response(QUESTION_END, user_id)
				user.status_state = 3
				ut.update(user_id, user)
				ut.send_response(TIREDNESS_QUESTION, user_id)
				return

		# If anything goes wrong, send a clarifying message
		ut.send_response(DIFF_TIRED_CLARIFY, user_id)
		ut.send_response(DIFFICULTY_QUESTION, user_id)


	# On tiredness question
	elif user.status_state == 3:
		
		if rating:

			if rating >= 1 and rating <= 5:
				workout.rating = rating
				ut.send_response(FEEDBACK_END, user_id)
				user.status = "idle"
				user.status_state = 0
				ut.update(user_id, user)
				return

		# If anything goes wrong, send a clarifying message
		ut.send_response(DIFF_TIRED_CLARIFY, user_id)
		ut.send_response(TIREDNESS_QUESTION, user_id)