def stats(): # get the list of exercises under this userid data = db.execute( "SELECT id, name, target, date FROM exercises WHERE userid = :userid", userid=session["user_id"]) if len(data) == 0: # if the user have no exercise added, it alerts the user on how he can add it flash( "You current have no exercises added! Get moving! Click on 'New Exercise' to add a new exercise" ) for row in data: temp = db.execute( "SELECT SUM(count) FROM history WHERE exerciseid = :exerciseid", exerciseid=row["id"]) # if user have not completed any work out for that particular exercise if temp[0]["SUM(count)"] == None: # set his count to 0 row["count"] = 0 else: row["count"] = convert(temp[0]["SUM(count)"]) # if users have a target set if row["target"] != "": # find difference between current count and target row["diff"] = row["count"] - float(row["target"]) row["diff"] = convert(row["diff"]) row["target"] = convert(row["target"]) # if target date is not left blank if row["date"] != "": # get the target date tdate = datetime.strptime(row["date"], "%Y-%m-%d").date() today = datetime.today().date() # find out how many days are between target date and today row["tdiff"] = (tdate - today).days row["date"] = tdate.strftime("%d %b %Y") # if the difference is negative (yet to hit target) if row["diff"] < 0: # if days left is 0 if row["tdiff"] == 0: row["gpd"] = abs(row["diff"]) else: # find out how many count per day to hit target row["gpd"] = abs(convert(row["diff"] / row["tdiff"])) # if user did not have a target count but has a target date elif row["date"] != "": tdate = datetime.strptime(row["date"], "%Y-%m-%d") row["date"] = tdate.strftime("%d %b %Y") flash("Click on Fitness60 to add more workouts! Get Moving!") return render_template("stats.html", data=data)
def convertJSONtoXML(self, json_file, xml_file="output.xml"): """ .. method:: convertJSONtoXML(json_file, xml_file) This method converts the JSON in the given file to the XML and outputs to the given file. The implementer of this method is responsible for opening both files, reading from the JSON file and writing to the XML file. He must ensure that all the proper error handling is performed. :param str json_file: A string representing a file path to a JSON file. :param str xml_file: A string representing a file path to output XML after converting it from the given JSON file :returns: True if success, else False :rtype: Boolean """ json_data = open(json_file) data = json.load(json_data) json_data.close() output = [] add_output_line = output.append if type(data) in [dict, list]: if self.root_object == True: add_output_line('<%s>%s</%s>' % ( self.root_object_name, convert(data), self.root_object_name, )) else: add_output_line('%s' % (convert(data))) else: add_output_line('%s' % convert(data, add_name=False)) output_file = open(xml_file, "wb") output_file.write(''.join(output).encode('utf-8')) output_file.close() print("XML output is successfully saved to : {}".format(xml_file)) return True
def index(): if request.method == "GET": # Select all of this user's exercise exercise = db.execute( "SELECT name, id FROM exercises WHERE userid = :userid", userid=session["user_id"]) # if the user have no exercise they are redireced to the page to add new exercise if len(exercise) == 0: # tell users that they have to add a new exercise flash("You currently have no exercises. Add an exercise!") return redirect("/new") # get a random exercise which the user has yet to reach his goal random = db.execute("SELECT name,target, target-SUM(count) FROM\ exercises LEFT JOIN history ON exercises.id = history.exerciseid\ WHERE exercises.userid=:userid AND target !=''\ GROUP BY exercises.id\ HAVING target-SUM(count)>0 OR target-SUM(count) IS NULL\ ORDER BY RANDOM() LIMIT 1", userid=session["user_id"]) # if there is a random exercise if len(random) != 0: if random[0]["target-SUM(count)"] == None: random[0]["target-SUM(count)"] = random[0]["target"] random[0]["target-SUM(count)"] = convert( random[0]["target-SUM(count)"]) random[0]["target"] = convert(random[0]["target"]) return render_template("index.html", exercise=exercise, random=random) else: # HTML ensures that at least a count is chosen # Get the current time time = datetime.now().strftime("%d %b %Y %A %I %M %p") # insert work out into history database db.execute( "INSERT INTO history (exerciseid, userid, count, notes, time)\ VALUES (:exerciseid, :userid, :count, :notes, :time)", exerciseid=request.form.get("name"), userid=session["user_id"], count=request.form.get("count"), notes=request.form.get("note"), time=time) # return a message to indicate that work out has been added successfully flash("Work out added!") return redirect("/")
def testGetAllScripts2(self): yamlStr = '\n'.join([ "{", " example1: {", " test: //src1//,", " script: stack test 1,", " },", " example2: {", " test: //src2//,", " script: stack test 1,", " }", "}" ]) configRaw = yaml.load(yamlStr) config = convert(configRaw) name1 = config[0]['name'] name2 = config[1]['name'] names = sorted([name1, name2]) notices = ''.join(map(notice, names)) expected = [ notices + 'stack test 1' ] actual = getAllScripts(config) self.assertCountEqual(expected, actual)
def testGetScripts7(self): yamlStr = '\n'.join([ "{", " example1: {", " test: //src1//,", " script: stack test 1,", " },", " example2: {", " test: //src2//,", " script: stack test 2,", " }", "}" ]) configRaw = yaml.load(yamlStr) config = convert(configRaw) files = [ 'base/src1/path1.hs', 'base/src1/path2.hs' ] name1 = config[0]['name'] expected = [ notice(name1) + 'stack test 1' ] actual = getScripts(config, files) self.assertCountEqual(expected, actual)
def testConvert1(self): yamlStr = '\n'.join([ "{", " example1: {", " test: /^src//,", " script: stack test,", " }", "}" ]) configRaw = yaml.load(yamlStr) config = convert(configRaw) actual = len(config) expected = 1 self.assertEqual(expected, actual) expected = ['name', 'test', 'script'] actual = config[0].keys() self.assertCountEqual(expected, actual) expected = 'example1' actual = config[0]['name'] self.assertEqual(expected, actual) expected = re.compile('^src/') actual = config[0]['test'] self.assertEqual(expected, actual) expected = 'stack test' actual = config[0]['script'] self.assertEqual(expected, actual)
def history(): # get all work out completed by this user_id data = db.execute( "SELECT time, count, notes, exerciseid FROM history WHERE\ userid = :userid", userid=session["user_id"]) if len(data) == 0: # if user have no work out recorded, it alerts the user on how he can add it flash( " You current have no work out recorded! Get moving! Click on 'Fitness60' to add a new work out" ) # for each work out for row in data: # get the name of the exercise temp = db.execute("SELECT name FROM exercises WHERE id= :exerciseid", exerciseid=row["exerciseid"]) row["name"] = temp[0]["name"] # convert the count to integer if the count is a whole number row["count"] = convert(row["count"]) # Format the time temptime = row["time"].split(" ") row["date"] = f"{temptime[0]} {temptime[1]} {temptime[2]}, {temptime[3]}" row["time"] = f"{temptime[4]}:{temptime[5]}{temptime[6]}" flash("Click on Fitness60 to add more workouts! Get Moving!") return render_template("history.html", data=data)
def testGetScripts5(self): yamlStr = '\n'.join([ "{", " example: {", " test: /src$/,", " script: stack test,", " }", "}" ]) configRaw = yaml.load(yamlStr) config = convert(configRaw) files = ['base/src/path.hs'] expected = [] actual = getScripts(config, files) self.assertCountEqual(expected, actual)
def testGetScripts4(self): yamlStr = '\n'.join([ "{", " example: {", " test: /^src//,", " script: stack test,", " }", "}" ]) configRaw = yaml.load(yamlStr) config = convert(configRaw) files = ['src/path.hs'] name = config[0]['name'] expected = [notice(name) + 'stack test'] actual = getScripts(config, files) self.assertCountEqual(expected, actual)
def addMWDRealTime(self,name,timestamp,value): logging.info(str("Processing:")+str(name)+repr(timestamp)+str(value)) mwdrt = [name,timestamp,value] if mwdrt in last: logging.info(str('Duplicate Found! Ignoring')) if name == '': logging.info(str("No Name attached to data!")) logging.info(str("buffer size:"+str(len(last)))) #pop the first if len(last) > last_length: last.pop(0) #value = float(value) kwargs = {'well':db_settings.get_active_well(), 'time_stamp':timestamp} kwargs['type'], axis, value = convert(name, value) if axis != '': kwargs['value_'+axis] = str(value) else: kwargs['value'] = str(value) logging.info(str("Final Value:")+str(kwargs)) t = ToolMWDRealTime(**kwargs) t.save() #append to the back last.append(mwdrt) return 'OK'
def fetch_mongo_data(sql_count): '''Fetch data from Mongodb database''' # Client connection ###### client = MongoClient('CLIENT ID INSERT HERE') # Removed for security # Database Name db = client['Cluster0'] # Collection Name col = db['entries'] # Start point for fetch data to avoid duplication/use of memory start_point = sql_count # Select data and store in list mongo_db = list(col.find({}, {'_id': 0, 'dateString': 1, 'sgv': 1})) mongo_count = len(mongo_db) print("\n###########################\nMongo records:", mongo_count) glucose_data = [] id = 1 # if statement to begin fetch at start point? for record in mongo_db: try: record.get('sgv') mmol = convert(record['sgv']) tz_data = timezone(record['dateString']) (db_datetime, ntz) = tz_data # Unpack tuple dt_split = db_datetime.split() date = dt_split[0] time = dt_split[1][:5] data_list = [id, date, time, mmol] glucose_data.append(data_list) id += 1 except KeyError: continue glucose_data = glucose_data[start_point:] mongo_fetch_data = (ntz, glucose_data) return mongo_fetch_data
def goals(): if request.method == "GET": # Select all of the user's exercises exercise = db.execute("SELECT * FROM exercises WHERE userid = :userid", userid=session["user_id"]) for row in exercise: if row["target"] != "": row["target"] = convert(row["target"]) # check if target date is empty if row["date"] != "": # if target date is not empty format the date temp = datetime.strptime(row["date"], "%Y-%m-%d") row["date"] = temp.strftime("%d %b %Y") return render_template("goals.html", exercise=exercise, today=today) else: db.execute( "UPDATE exercises SET target = :target, date= :date WHERE id= :id", target=request.form.get("target"), date=request.form.get("date"), id=request.form.get("name")) flash("Your goal is updated! Kepp working to hit your goals!") return redirect("/goals")
def testGetAllScripts1(self): yamlStr = '\n'.join([ "{", " example1: {", " test: //src1//,", " script: stack test 1,", " },", " example2: {", " test: //src2//,", " script: stack test 2,", " }", "}" ]) configRaw = yaml.load(yamlStr) config = convert(configRaw) name1 = config[0]['name'] name2 = config[1]['name'] expected = [ notice(name1) + 'stack test 1', notice(name2) + 'stack test 2' ] actual = getAllScripts(config) self.assertCountEqual(expected, actual)
def testConvert2(self): yamlStr = '\n'.join([ "{", " example1: {", " test: /^src1//,", " script: stack test 1,", " },", " example2: {", " test: /^src2//,", " script: stack test 2,", " }", "}" ]) configRaw = yaml.load(yamlStr) config = convert(configRaw) actual = len(config) expected = 2 self.assertEqual(expected, actual) for i, rec in enumerate(config): expected = ['name', 'test', 'script'] actual = rec.keys() self.assertCountEqual(expected, actual) expected = "example"+str(i+1) actual = rec['name'] self.assertCountEqual(expected, actual) expected = re.compile("^src"+str(i+1)+"/") actual = rec['test'] self.assertEqual(expected, actual) expected = "stack test "+str(i+1) actual = rec['script'] self.assertEqual(expected, actual)