index int64 | repo_name string | branch_name string | path string | content string | import_graph string |
|---|---|---|---|---|---|
64,761 | ldaug99/Hue-Sync-Universal | refs/heads/master | /Hue_Python/configManager/__init__.py | from .configManager import configManager as cm | {"/Hue_Python/lightManager/__init__.py": ["/Hue_Python/lightManager/lightManager.py"], "/Hue_Python/mainThread/__init__.py": ["/Hue_Python/mainThread/mainThread.py"], "/Hue_Python/configManager/__init__.py": ["/Hue_Python/configManager/configManager.py"], "/Hue_Python/camManager/__init__.py": ["/Hue_Python/camManager/camManager.py"], "/Hue_Python/apiManager/apiManager.py": ["/Hue_Python/apiManager/__init__.py"], "/Hue_Python/apiManager/__init__.py": ["/Hue_Python/apiManager/apiManager.py"]} |
64,762 | ldaug99/Hue-Sync-Universal | refs/heads/master | /Hue_Python/camManager/camManager.py | import cv2
import numpy
class camManager():
### Static class variables ###
KWARG_VERBOSE = "verbose"
# Initialization
def __init__(self, index = 0, **kwargs):
# Get variables
self.__verbose = kwargs.get(camManager.KWARG_VERBOSE, False)
# Define instance varaibles
self.__webcam = cv2.VideoCapture(index) # Get camera
self.__showFrame = False
def isReady(self):
check, frame = self.__webcam.read()
return self.__webcam.isOpened() and check
def retryOpen(self, index = 0):
if self.__webcam.isOpened():
self.__webcam.release()
return self.__webcam.open(index)
def release(self):
self.__webcam.release()
cv2.destroyAllWindows()
cv2.waitKey(0)
cv2.waitKey(0)
cv2.waitKey(0)
cv2.waitKey(0)
cv2.waitKey(0)
def showFrame(self, state):
self.__showFrame = state
if not self.__showFrame:
cv2.destroyAllWindows()
cv2.waitKey(0)
cv2.waitKey(0)
cv2.waitKey(0)
cv2.waitKey(0)
cv2.waitKey(0)
def getFrame(self):
if self.__webcam.isOpened():
check, frame = self.__webcam.read()
if check:
if self.__showFrame:
cv2.imshow("Picture", frame)
cv2.waitKey(1)
return check, frame
else:
print("Exception on camManager() -> getFrame(): Unable to get picture from webcam.")
return False, None
else:
print("Exception on camManager() -> getFrame(): Unable to communication with webcam.")
return False, None
def getAvgColor(self):
check, frame = self.getFrame()
if check:
avg_color_per_row = numpy.average(frame, axis=0)
avg_color = numpy.average(avg_color_per_row, axis=0)
b = avg_color[0]
g = avg_color[1]
r = avg_color[2]
if self.__verbose:
print("Average color is [{} {} {}] (R, G, B)".format(r, g, b))
return r, g, b
else:
print("Exception on camManager() -> getAvgColor(): Unable to get color from None frame.")
return None, None, None
def getDomColor(self):
check, frame = self.getFrame()
if check:
pixels = numpy.float32(self.__frame.reshape(-1, 3))
n_colors = 5
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 200, .1)
flags = cv2.KMEANS_RANDOM_CENTERS
_, labels, palette = cv2.kmeans(pixels, n_colors, None, criteria, 10, flags)
_, counts = numpy.unique(labels, return_counts=True)
dominant = palette[numpy.argmax(counts)]
r = dominant[0]
g = dominant[1]
b = dominant[2]
if self.__verbose:
print("Dominant color is [{} {} {}] (R, G, B)".format(r, g, b))
return r, g, b
else:
print("Exception on camManager() -> getDomColor(): Unable to get color from None frame.")
return None, None, None | {"/Hue_Python/lightManager/__init__.py": ["/Hue_Python/lightManager/lightManager.py"], "/Hue_Python/mainThread/__init__.py": ["/Hue_Python/mainThread/mainThread.py"], "/Hue_Python/configManager/__init__.py": ["/Hue_Python/configManager/configManager.py"], "/Hue_Python/camManager/__init__.py": ["/Hue_Python/camManager/camManager.py"], "/Hue_Python/apiManager/apiManager.py": ["/Hue_Python/apiManager/__init__.py"], "/Hue_Python/apiManager/__init__.py": ["/Hue_Python/apiManager/apiManager.py"]} |
64,763 | ldaug99/Hue-Sync-Universal | refs/heads/master | /Hue_Python/scrap/Python-CLIP-API/other/scrap.py | def scanNetwork():
hostIP = getHostIP()
if hostIP == None:
print("Scan aborted.")
return False
devices = None
timeout = 0.001
for i in range(2, 256):
addr = "https://192.168.87." + str(i) + "/description.xml"
try:
response = requests.get(addr, verify = False, timeout = timeout)
except:
continue
if response.status_code == response.ok:
if isHue(response):
if devices == None:
devices = {addr}
else:
devices.add(addr)
print("Found device on address {}.".format(addr))
requests.close()
print(devices)
input("Done scanning")
def isHue(response): # Return true if device is a Hue bridge
try:
description = response.text
if (description.find("Philips hue")):
return True
except:
pass
return False | {"/Hue_Python/lightManager/__init__.py": ["/Hue_Python/lightManager/lightManager.py"], "/Hue_Python/mainThread/__init__.py": ["/Hue_Python/mainThread/mainThread.py"], "/Hue_Python/configManager/__init__.py": ["/Hue_Python/configManager/configManager.py"], "/Hue_Python/camManager/__init__.py": ["/Hue_Python/camManager/camManager.py"], "/Hue_Python/apiManager/apiManager.py": ["/Hue_Python/apiManager/__init__.py"], "/Hue_Python/apiManager/__init__.py": ["/Hue_Python/apiManager/apiManager.py"]} |
64,764 | ldaug99/Hue-Sync-Universal | refs/heads/master | /Hue_Python/scrap/Python-CLIP-API/Hue_old/common/__init__.py | __all__ = ["HTTPS"] | {"/Hue_Python/lightManager/__init__.py": ["/Hue_Python/lightManager/lightManager.py"], "/Hue_Python/mainThread/__init__.py": ["/Hue_Python/mainThread/mainThread.py"], "/Hue_Python/configManager/__init__.py": ["/Hue_Python/configManager/configManager.py"], "/Hue_Python/camManager/__init__.py": ["/Hue_Python/camManager/camManager.py"], "/Hue_Python/apiManager/apiManager.py": ["/Hue_Python/apiManager/__init__.py"], "/Hue_Python/apiManager/__init__.py": ["/Hue_Python/apiManager/apiManager.py"]} |
64,765 | ldaug99/Hue-Sync-Universal | refs/heads/master | /Hue_Python/scrap/Python-CLIP-API/test/fileOpenTest.py | import os
import json
fileName = "test_json.txt"
script_path = os.path.realpath(__file__)
dir_path = os.path.dirname(script_path)
print("Script path is {}".format(script_path))
print("Directory path is {}".format(dir_path))
filename = "test_json.txt"
files = os.listdir(dir_path)
print(files)
print("Filename is in files:")
if filename in files:
print("True")
else:
print("False")
#print(os.listdir(dir_path))
#print(dir_path + "\\" + "empty_file.txt")
#with open(dir_path + "\\" + "empty_file.txt", "r") as file:
# data = json.load(file)
#print(data)
#print(data != None)
#file = open(fileName, "r")
#print(file)
test = False
data = {"Noice": True}
#with open(dir_path + "\\" + "test_file.txt", "w") as file:
# test = json.dump(data, file)
#print(test)
#input("wait")
data = {
"Noice": True,
"indeed": True
}
#with open(dir_path + "\\" + "test_file.txt", "w") as file:
# test = json.dump(data, file)
#input("wait")
fileData = None
with open(dir_path + "\\" + "test_file.txt", "r") as file:
fileData = json.load(file)
print(fileData)
#with open(dir_path + "\\" + "test_file.txt", "w") as file:
# test = json.dump(fileData, file) | {"/Hue_Python/lightManager/__init__.py": ["/Hue_Python/lightManager/lightManager.py"], "/Hue_Python/mainThread/__init__.py": ["/Hue_Python/mainThread/mainThread.py"], "/Hue_Python/configManager/__init__.py": ["/Hue_Python/configManager/configManager.py"], "/Hue_Python/camManager/__init__.py": ["/Hue_Python/camManager/camManager.py"], "/Hue_Python/apiManager/apiManager.py": ["/Hue_Python/apiManager/__init__.py"], "/Hue_Python/apiManager/__init__.py": ["/Hue_Python/apiManager/apiManager.py"]} |
64,766 | ldaug99/Hue-Sync-Universal | refs/heads/master | /Hue_Python/scrap/Python-CLIP-API/Hue_old/keySetup.py | from common import HTTPS
import time
def getAPIkey(address, **kwargs):
'''
Gets API key from Hue bridge on the passed IP address.
Parameters:
address: IP address of bridge.
(optional) deviceName: Name to register with the bridge.
(optional) retrys: Maximum number of retrys.
(optional) delay: Delay between each retry.
Returns:
string or None: API key from bridge, or None on fault.
'''
__key = None # Presume key is None
__name = kwargs.get('deviceName', None) # Get optional input "deviceName"
__retrys = kwargs.get('retrys', 100)
__delay = kwargs.get('delay', 10)
__retry_num = kwargs.get('__retry_num', 0)
if __name == None:
__name = input("Input device name: ")
params = {"devicetype":__name} # JSON paramaters to send
response_code, data = HTTPS.request(HTTPS.POST, address, "/api", params = params) # Send post reqiest to /api with parameters
if response_code == 200: # Check if api got message, code 200 indicates succesfull request
if data != None: # Check if data is none
if "error" in data[0]: #and 101 in data[0]["error"]: # If link button not pressed
__retry_num = __retry_num + 1 # Increment retry attempt counter
if __retry_num > __retrys:
print("Maximum number of retrys reached. Stopping...")
return None
print("Press link button on Hue Bridge")
#input("Press enter to retry connection") # Wait for input
time.sleep(__delay) # Sleep for 5 seconds
__key = getAPIkey(address, deviceName = __name) # Retry function
elif "success" in data[0]: # If successfull request
try:
__key = data[0]["success"]["username"] # Save api key
print("Got API key: {}".format(__key))
except:
pass
else:
print("Exception on getAPIkey(): Method didn't return data, which was unexpected")
else:
print("Exception on getAPIkey(): Method returned response code {}, which was unexpected.".format(response_code))
return __key | {"/Hue_Python/lightManager/__init__.py": ["/Hue_Python/lightManager/lightManager.py"], "/Hue_Python/mainThread/__init__.py": ["/Hue_Python/mainThread/mainThread.py"], "/Hue_Python/configManager/__init__.py": ["/Hue_Python/configManager/configManager.py"], "/Hue_Python/camManager/__init__.py": ["/Hue_Python/camManager/camManager.py"], "/Hue_Python/apiManager/apiManager.py": ["/Hue_Python/apiManager/__init__.py"], "/Hue_Python/apiManager/__init__.py": ["/Hue_Python/apiManager/apiManager.py"]} |
64,767 | ldaug99/Hue-Sync-Universal | refs/heads/master | /Hue_Python/scrap/Python-CLIP-API/Hue_old/configManager.py | import os
import bridgeFinder
from keySetup import *
class configManager():
__configFileName = "config.txt" # Config file name
__address = None
__key = None
def __init__(self):
self.__getConfig()
def getAddress(self):
return self.__address
def getKey(self):
return self.__key
def __getConfig(self): # Load config gile
isFile, path = self.__getFile()
if isFile:
self.__loadConfig(path)
else:
self.__makeConfig(path)
self.__verifyConfig(self.__address, self.__key)
def __getFile(self):
dir_path = os.path.dirname(os.path.realpath(__file__))
root = None
for root, dirs, files in os.walk(dir_path):
for file in files:
if str(file) == self.__configFileName:
return True, root + "\\" + file
#path = os.path.abspath(self.__file__) # Get working path
#files = os.listdir(path) # Get files in path
#print("Paths is {}".format(path))
#for file in files:
# if str(file) == self.__configFileName:
# return True
return False, root + "\\" + self.__configFileName
def __loadConfig(self, path): # Load ip and key from config file
print("Getting API address and key from config file.")
with open(path, "r") as file:
data = json.load(file)
try:
self.__address = data["address"]
self.__key = data["key"]
return True
except:
print("Exception on __loadConfig(): Invalid config file format.")
return False
def __makeConfig(self, path): # Make config file, get ip and key and save to file
action = input("No config found. Make one? (Yes/No)")
if action == "Yes" or action == "yes" or action == "y":
devices = bridgeFinder.scanNetwork()
if devices == None:
print("No Hue bridge found.")
input("Press any key to exit...")
exit()
elif len(devices) > 1:
print("More then one Hue bridge found, which was unexpected.")
input("Press any key to exit...")
exit()
self.__address = devices[0] # Save api addres to script variable
self.__key = getAPIkey(self.__address) # Save key to script variable
print("Key is: {}".format(self.__key))
data = {"address": self.__address, "key": self.__key}
with open(path, "w") as file:
json.dump(data, file)
else:
input("Press any key to exit...")
exit()
def __verifyConfig(self, __address, __key):
print("Verifying address {} and key {}".format(__address, __key))
if __address == None or __key == None or len(__address) < 1 or len(__key) < 1:
print("Invalid API address or key.")
input("Press any key to exit...")
exit()
else:
print("Ok") | {"/Hue_Python/lightManager/__init__.py": ["/Hue_Python/lightManager/lightManager.py"], "/Hue_Python/mainThread/__init__.py": ["/Hue_Python/mainThread/mainThread.py"], "/Hue_Python/configManager/__init__.py": ["/Hue_Python/configManager/configManager.py"], "/Hue_Python/camManager/__init__.py": ["/Hue_Python/camManager/camManager.py"], "/Hue_Python/apiManager/apiManager.py": ["/Hue_Python/apiManager/__init__.py"], "/Hue_Python/apiManager/__init__.py": ["/Hue_Python/apiManager/apiManager.py"]} |
64,768 | ldaug99/Hue-Sync-Universal | refs/heads/master | /Hue_Python/camManager/scrap/camScript.py | import cv2
import time
import numpy
class cam():
SNAPINTERVAL = 0.01 # Update every 100 milliseconds
def __init__(self):
self.__lastUpdate = time.time()
self.__webcam = cv2.VideoCapture(0)
# Wait for start
time.sleep(1)
def run(self):
while 1==1:
self.__timeNow = time.time()
while (self.__timeNow - self.__lastUpdate) < cam.SNAPINTERVAL:
pass
#command = input("Input a command: ")
#self.__processCommand(command)
self.__snapPicture()
self.__lastUpdate = self.__timeNow
#self.__timeNow = time.time()
#if (self.__timeNow - self.__lastUpdate) > snapInterval:
# self.__snapPicture():
#else:
# command = input("Input a command: ")
# self.__processCommand(command)
# # Wait for input
# self.__waitForCommand()
def stop(self):
self.__webcam.release()
cv2.destroyAllWindows()
def __waitForCommand(self):
while 1==1:
command = input("Input a command: ")
self.__processCommand(command)
def __processCommand(self, command):
switcher = {
"snap": self.__snapPicture,
"dom": self.__getDominante,
"avg": self.__getAverage,
"stop": self.stop
}
function = switcher.get(command, self.__comInvalid)
function()
def __snapPicture(self):
if self.__webcam != None:
self.__check, self.__frame = self.__webcam.read()
print(self.__check) #prints true as long as the webcam is running
#print(frame) #prints matrix values of each framecd
if self.__check:
k = cv2.waitKey(1)
cv2.imshow("Picture", self.__frame)
else:
print("Unable to get picture")
else:
print("No communication to webcam")
def __getAverage(self):
if self.__check:
avg_color_per_row = numpy.average(self.__frame, axis=0)
avg_color = numpy.average(avg_color_per_row, axis=0)
print(avg_color)
def __getDominante(self):
if self.__check:
pixels = numpy.float32(self.__frame.reshape(-1, 3))
n_colors = 5
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 200, .1)
flags = cv2.KMEANS_RANDOM_CENTERS
_, labels, palette = cv2.kmeans(pixels, n_colors, None, criteria, 10, flags)
_, counts = numpy.unique(labels, return_counts=True)
dominant = palette[numpy.argmax(counts)]
print(dominant)
def __comInvalid(self):
print("No") | {"/Hue_Python/lightManager/__init__.py": ["/Hue_Python/lightManager/lightManager.py"], "/Hue_Python/mainThread/__init__.py": ["/Hue_Python/mainThread/mainThread.py"], "/Hue_Python/configManager/__init__.py": ["/Hue_Python/configManager/configManager.py"], "/Hue_Python/camManager/__init__.py": ["/Hue_Python/camManager/camManager.py"], "/Hue_Python/apiManager/apiManager.py": ["/Hue_Python/apiManager/__init__.py"], "/Hue_Python/apiManager/__init__.py": ["/Hue_Python/apiManager/apiManager.py"]} |
64,769 | ldaug99/Hue-Sync-Universal | refs/heads/master | /Hue_Python/scrap/Python-CLIP-API/Hue/apiManager.py | import os
class apiManager():
### Static class variables ###
ADDR = "address"
KEY = "key"
### Instance variables ###
self.__config = {ADDR: None, KEY: None}
self.__verbose = False
def __init__(self, **kwargs):
isConfigured = False
isSaveToFile = False
self.__verbose = kwargs.get("verbose", False)
self.__config[ADDR] = kwargs.get("APIaddress", None)
self.__config[KEY] = kwargs.get("APIkey", None)
fileName = kwargs.get("configFile", None)
# Check if address and key is given
if self.__config[ADDR] != None or self.__config[KEY] != None:
isConfigured = True
if self.__verbose:
print("API address is {}, with key {}".format(self.__config[ADDR], self.__config[KEY]))
# Check if config file name is given
if fileName != None:
if isConfigured:
with open(path, "w") as file:
json.dump(data, file)
print("API address and key not defined.")
def run():
if self.__address == None
| {"/Hue_Python/lightManager/__init__.py": ["/Hue_Python/lightManager/lightManager.py"], "/Hue_Python/mainThread/__init__.py": ["/Hue_Python/mainThread/mainThread.py"], "/Hue_Python/configManager/__init__.py": ["/Hue_Python/configManager/configManager.py"], "/Hue_Python/camManager/__init__.py": ["/Hue_Python/camManager/camManager.py"], "/Hue_Python/apiManager/apiManager.py": ["/Hue_Python/apiManager/__init__.py"], "/Hue_Python/apiManager/__init__.py": ["/Hue_Python/apiManager/apiManager.py"]} |
64,770 | ldaug99/Hue-Sync-Universal | refs/heads/master | /Hue_Python/camManager/__init__.py | from .camManager import camManager as wm | {"/Hue_Python/lightManager/__init__.py": ["/Hue_Python/lightManager/lightManager.py"], "/Hue_Python/mainThread/__init__.py": ["/Hue_Python/mainThread/mainThread.py"], "/Hue_Python/configManager/__init__.py": ["/Hue_Python/configManager/configManager.py"], "/Hue_Python/camManager/__init__.py": ["/Hue_Python/camManager/camManager.py"], "/Hue_Python/apiManager/apiManager.py": ["/Hue_Python/apiManager/__init__.py"], "/Hue_Python/apiManager/__init__.py": ["/Hue_Python/apiManager/apiManager.py"]} |
64,771 | ldaug99/Hue-Sync-Universal | refs/heads/master | /Hue_Python/apiManager/HTTPS.py | import requests
GET = 0; PUT = 1; POST = 2; DELETE = 3;
defaultTimeout = 10
defaultVerify = False
def request(rtype, address, api, **kwargs):
'''
Send HTTPS request method to address.
Parameters:
rtype: Method type: GET, PUT, POST, DELETE.
address: Request address.
api: API address.
(optional) params: Paramaters for request.
(optional) verify: Verify certificate.
(optional) timeout: Maksimum time to wait for reply.
Returns:
string or None: API key from bridge, or None on fault.
'''
response = None
kwargs = {
"rtype": rtype,
"address": "https://" + address + api,
"params": kwargs.get('params', {}),
"verify": kwargs.get('verify', defaultVerify),
"timeout": kwargs.get('timeout', defaultTimeout),
"verbose": kwargs.get('verbose', False),
"dataType": kwargs.get('dataType', "json"),
"debug": kwargs.get('debug', False)
} # Create paramater dictionary, which can be passed to the specific request function
if kwargs["verbose"]:
print("Sending request type {} to address {}, with data {}".format(rtype, "https://" + address + api, kwargs.get('params', {})))
response = __sendRequest(**kwargs)
response_code = __getResponseCode(response) # Get response code
if kwargs["dataType"] == "json":
data = __getData(response) # Get data
elif kwargs["dataType"] == "text":
data = __getText(response)
if kwargs["verbose"]:
print("Request returned response {} and data {}".format(response_code,data))
return response_code, data # Return response and data
def __sendRequest(**kwargs): # Determine request type
debug = kwargs.get("debug", False)
if debug:
#return __debugHTTPS(**kwargs)
pass
else:
rtype = kwargs.get("rtype", None)
switcher = {
0: __getRequest,
1: __putRequest,
2: __postRequest,
3: __deleteRequest
}
function = switcher.get(rtype, lambda: "Exception on __requestType(), invalid function call")
return function(**kwargs)
def __getRequest(**kwargs):
response = None
try:
response = requests.get(
kwargs.get('address', "1.1.1.1"),
verify = kwargs.get('verify', defaultVerify),
timeout = kwargs.get('timeout', defaultTimeout)
)
except:
print("Exception on __getRequest(): Unable to send request.")
return response
def __putRequest(**kwargs):
response = None
try:
response = requests.put(
kwargs.get('address', "1.1.1.1"),
json = kwargs.get('params', {}),
verify = kwargs.get('verify', defaultVerify),
timeout = kwargs.get('timeout', defaultTimeout)
)
except:
print("Exception on __putRequest(): Unable to send request.")
return response
def __postRequest(**kwargs):
response = None
try:
response = requests.post(
kwargs.get('address', "1.1.1.1"),
json = kwargs.get('params', {}),
verify = kwargs.get('verify', defaultVerify),
timeout = kwargs.get('timeout', defaultTimeout)
)
except:
print("Exception on __postRequest(): Unable to send request.")
return response
def __deleteRequest(**kwargs):
response = None
try:
response = requests.delete(
kwargs.get('address', "1.1.1.1"),
json = kwargs.get('params', {}),
verify = kwargs.get('verify', defaultVerify),
timeout = kwargs.get('timeout', defaultTimeout)
)
except:
print("Exception on __deleteRequest(): Unable to send request.")
return response
def __getResponseCode(response): # Get response code form requests, or None on fault
code = None
try:
code = response.status_code
except:
print("Exception on __getResponseCode(): No status code returned.")
return code
def __getData(response): # Check for data in response
data = None
try:
data = response.json()
except:
print("Exception on __getData(): No data returned.")
return data
def __getText(response):
data = None
try:
data = response.text
except:
print("Exception on __getText(): No data returned.")
return data
#def __debugHTTPS(**kwargs):
# rtype = kwargs.get("rtype", None)
# if rtype ==
| {"/Hue_Python/lightManager/__init__.py": ["/Hue_Python/lightManager/lightManager.py"], "/Hue_Python/mainThread/__init__.py": ["/Hue_Python/mainThread/mainThread.py"], "/Hue_Python/configManager/__init__.py": ["/Hue_Python/configManager/configManager.py"], "/Hue_Python/camManager/__init__.py": ["/Hue_Python/camManager/camManager.py"], "/Hue_Python/apiManager/apiManager.py": ["/Hue_Python/apiManager/__init__.py"], "/Hue_Python/apiManager/__init__.py": ["/Hue_Python/apiManager/apiManager.py"]} |
64,772 | ldaug99/Hue-Sync-Universal | refs/heads/master | /Hue_Python/camManager/scrap/colorThread.py | from threading import Thread
import matplotlib.pyplot as plt
class colorThread(Thread):
def __init__(self, r, g, b):
Thread.__init__(self)
self.r = r; self.g = g; self.b = b
self.__doRun = True # Kill thread when false
def run(self):
plt.imshow([[(self.r, self.g, self.b)]])
plt.show()
while self.__doRun:
pass
def stop(self):
self.__doRun = False | {"/Hue_Python/lightManager/__init__.py": ["/Hue_Python/lightManager/lightManager.py"], "/Hue_Python/mainThread/__init__.py": ["/Hue_Python/mainThread/mainThread.py"], "/Hue_Python/configManager/__init__.py": ["/Hue_Python/configManager/configManager.py"], "/Hue_Python/camManager/__init__.py": ["/Hue_Python/camManager/camManager.py"], "/Hue_Python/apiManager/apiManager.py": ["/Hue_Python/apiManager/__init__.py"], "/Hue_Python/apiManager/__init__.py": ["/Hue_Python/apiManager/apiManager.py"]} |
64,773 | ldaug99/Hue-Sync-Universal | refs/heads/master | /Hue_Python/camManager/scrap/camThread.py | from threading import Thread
import time
import cv2
import numpy
class camThread(Thread):
def __init__(self):
Thread.__init__(self)
self.__doRun = True # Kill thread when false
self.__webcam = cv2.VideoCapture(0)
self.__sleepTime = 0.1 # Time to sleep between each picture
self.ct = None
def run(self):
while self.__doRun:
self.__snapPicture()
self.__getAverage()
self.__sleep()
self.__webcam.release()
cv2.destroyAllWindows()
def stop(self):
print("Stopping {}".format(self.getName()))
self.__doRun = False
def setFs(self, fs):
self.__sleepTime = 1 / fs
def __sleep(self):
#print('%s sleeping for %d seconds...' % (self.getName(), self.__sleepTime))
time.sleep(self.__sleepTime)
def __snapPicture(self):
if self.__webcam != None:
self.__check, self.__frame = self.__webcam.read()
#print(self.__check) #prints true as long as the webcam is running
#print(frame) #prints matrix values of each framecd
if self.__check:
k = cv2.waitKey(1)
cv2.imshow("Picture", self.__frame)
else:
print("Unable to get picture")
else:
print("No communication to webcam")
def __getAverage(self):
if self.__check:
if self.ct != None:
self.ct.stop()
avg_color_per_row = numpy.average(self.__frame, axis=0)
avg_color = numpy.average(avg_color_per_row, axis=0)
r = avg_color[0]
g = avg_color[1]
b = avg_color[2]
print(avg_color)
def __getDominante(self):
if self.__check:
pixels = numpy.float32(self.__frame.reshape(-1, 3))
n_colors = 5
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 200, .1)
flags = cv2.KMEANS_RANDOM_CENTERS
_, labels, palette = cv2.kmeans(pixels, n_colors, None, criteria, 10, flags)
_, counts = numpy.unique(labels, return_counts=True)
dominant = palette[numpy.argmax(counts)]
print(dominant)
| {"/Hue_Python/lightManager/__init__.py": ["/Hue_Python/lightManager/lightManager.py"], "/Hue_Python/mainThread/__init__.py": ["/Hue_Python/mainThread/mainThread.py"], "/Hue_Python/configManager/__init__.py": ["/Hue_Python/configManager/configManager.py"], "/Hue_Python/camManager/__init__.py": ["/Hue_Python/camManager/camManager.py"], "/Hue_Python/apiManager/apiManager.py": ["/Hue_Python/apiManager/__init__.py"], "/Hue_Python/apiManager/__init__.py": ["/Hue_Python/apiManager/apiManager.py"]} |
64,774 | ldaug99/Hue-Sync-Universal | refs/heads/master | /Hue_Python/scrap/Python-CLIP-API/Hue_old/Hue.py | from configManager import configManager
from lightManager import lightManager
class Hue:
__apiKey = None # API key
__apiAddress = None # IP address to Bridge
__cManager = None
__lManager = None
def __init__(self):
self.run()
def run(self):
self.__cManager = configManager()
self.__apiKey = self.__cManager.getKey()
self.__apiAddress = self.__cManager.getAddress()
print("Bridge address is {} with key {}".format(self.__apiAddress, self.__apiKey))
if self.__apiAddress != None and self.__apiKey != None:
self.__lManager = lightManager(self.__apiAddress, self.__apiKey, verbose = True)
lights = self.__lManager.getLights()
self.waitForCommand()
def getAddress(self):
return self.__apiAddress
def getKey(self):
return self.__apiKey
def waitForCommand(self):
while 1==1:
command = input("Input a command: ")
self.__processCommand(command)
def __processCommand(self, command):
switcher = {
"help": self.__comHelp,
"add": self.__comAddLight,
"remove": self.__comRemoveLight,
"lights": self.__comLights,
"colorL": self.__comColorL
}
function = switcher.get(command, self.__comInvalid)
function()
def __comHelp(self):
print(" Avaliable commands:")
print(" help - Prints help.")
print(" add - Adds light to group.")
print(" remove - Removes light from group.")
print(" lights - Prints avalibale lights.")
print(" colorL - Set color of light or group.")
print(" colorG - Set color of light or group.")
print(" ")
pass
def __comAddLight(self):
self.__comLights()
lightID = input("Input light ID: ")
group = input("Input light group: ")
if group in self.__lManager.getGroups():
self.__lManager.addLight(lightID, group)
print(self.__lManager.getGroupSetup())
def __comRemoveLight(self):
lightID = input("Input light ID: ")
pass
def __comColorL(self):
lightID = input("Input light ID: ")
sat = input("Input light saturation: ")
bri = input("Input light brightness: ")
hue = input("Input light hue: ")
self.__lManager.setColor(lightID, hue, sat, bri)
def __comColorG(self):
groupID = input("Input group name: ")
pass
def __comLights(self):
print(" Avaliable lights: {}".format(self.__lManager.getLights()))
print(" ")
pass
def __comInvalid(self):
print(" Invalid command.")
print(" ")
self.__comHelp() | {"/Hue_Python/lightManager/__init__.py": ["/Hue_Python/lightManager/lightManager.py"], "/Hue_Python/mainThread/__init__.py": ["/Hue_Python/mainThread/mainThread.py"], "/Hue_Python/configManager/__init__.py": ["/Hue_Python/configManager/configManager.py"], "/Hue_Python/camManager/__init__.py": ["/Hue_Python/camManager/camManager.py"], "/Hue_Python/apiManager/apiManager.py": ["/Hue_Python/apiManager/__init__.py"], "/Hue_Python/apiManager/__init__.py": ["/Hue_Python/apiManager/apiManager.py"]} |
64,775 | ldaug99/Hue-Sync-Universal | refs/heads/master | /Hue_Python/scrap/Python-CLIP-API/test/test-https-request.py | #import os
#import certifi
#import urllib3
import requests
import json
import time
import sys
#[{'success': {'username': '7wg5y9ytGcQmrjmegai7sxzzcMuFBZxJOlzL8zLL'}}]
#path = os.getcwd()
#path = path + "\\" + "CLIP-API-Debugger-Certificate.cer"
#https = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where())
#response = requests.get('https://192.168.87.114/debug/clip.html', verify = path)
#response = requests.get('https://192.168.87.114/debug/clip.html', verify = certifi.where())
#response = https.requests('GET', 'https://192.168.87.114/debug/clip.html')
#address = "https://192.168.87.114/"
#debug/clip.html
#api/newdeveloper
#api
#apiCommand = "api/7wg5y9ytGcQmrjmegai7sxzzcMuFBZxJOlzL8zLL/lights" # Get info on all lights
#apiCommand = "api/7wg5y9ytGcQmrjmegai7sxzzcMuFBZxJOlzL8zLL/lights/4/state"
#address = address + apiCommand
#PARAMS = {"devicetype":"apiTest#WizardsDesktop"}
#PARAMS = {"on":True}
#from contextlib import contextmanager
#import sys, os
#@contextmanager
#def suppress_stdout():
# with open(os.devnull, "w") as devnull:
# old_stdout = sys.stdout
# sys.stdout = devnull
# try:
# yield
# finally:
# sys.stdout = old_stdout
lightID = "8"
bri = "241"
sat = "241"
hue = "50000"
#address = "https://192.168.87.183/api/jVfvoEykjhjr5JU448bac1XruOG-jYVMW1s6WCAY/lights/"
#address = "https://192.168.1.57/api/h0Ov2zL9X7i7plHOBc2HTH8p4n0SAjxyjpSfe6fv/lights/4/state"
address = "https://192.168.87.114/api/7wg5y9ytGcQmrjmegai7sxzzcMuFBZxJOlzL8zLL/lights/2/state"
#params = {"bri": int(bri), "hue": int(hue), "on": True, "sat": int(sat), "transitiontime": 1}
params = {"on": True, "xy": [0.25, 0.70], "bri": 255, "transitiontime": 0}
response = requests.put(address, json = params, verify = False)
#no = False
#response = requests.get(address, verify = False) # Dump all data
try:
data = response.json()
print(json.dumps(data, sort_keys=True, indent=3))
except:
pass
#response = requests.get(address, verify = False)
#with suppress_stdout():
# for hue in range(0, 65000, 500):
# PARAMS = {"on":True, "sat":254, "bri":254,"hue":hue}
# print(json.dumps(PARAMS))
# response = requests.put(address, json = PARAMS, verify = False)
#response = requests.post(url = address, json = PARAMS, verify = False)
#print(response)
#if data != None:
# print(json.dumps(data, sort_keys=True, indent=4))
# time.sleep(0.00001)
#lights = None
#for i in range(1, len(data) + 1):
# name = None
# try:
# name = data[str(i)]["name"]
# except:
# pass
# light = {"id": str(i), "name": name}
# if lights == None:
# lights = [light]
# else:
# lights.append(light)
#print(lights)
#input("Press Enter to continue...")
#print(https)
#requests.get('https://api.github.com') | {"/Hue_Python/lightManager/__init__.py": ["/Hue_Python/lightManager/lightManager.py"], "/Hue_Python/mainThread/__init__.py": ["/Hue_Python/mainThread/mainThread.py"], "/Hue_Python/configManager/__init__.py": ["/Hue_Python/configManager/configManager.py"], "/Hue_Python/camManager/__init__.py": ["/Hue_Python/camManager/camManager.py"], "/Hue_Python/apiManager/apiManager.py": ["/Hue_Python/apiManager/__init__.py"], "/Hue_Python/apiManager/__init__.py": ["/Hue_Python/apiManager/apiManager.py"]} |
64,776 | ldaug99/Hue-Sync-Universal | refs/heads/master | /Hue_Python/scrap/Python-CLIP-API/Hue_old/lightManager.py | from common import HTTPS
import time
class lightManager():
__address = None
__key = None
__verbose = False
__lights = None
__lastUpdate = 0
__updateInterval = 1000
CENTER = 0
LEFT = 1
RIGHT = 2
TOP = 3
BOTTOM = 4
__groups = ["center", "left", "right", "top", "bottom"]
__lightGroups = {
__groups[CENTER]: [],
__groups[LEFT]: [],
__groups[RIGHT]: [],
__groups[TOP]: [],
__groups[BOTTOM]: []
}
def __init__(self, address, key, **kwargs):
self.__address = address
self.__key = key
self.__verbose = kwargs.get('verbose', False)
def addLight(self, lightID, group = "center"):
if not self.__getDuplicatesInGroup(lightID, group):
lights = self.getLights()
for lid in range(0, self.__getNumOfLights(lights)):
if str(lights[lid]["id"]) == lightID:
self.__lightGroups[group].append(lights[lid])
if self.__verbose:
print("Added {} to group {}, {}".format(lightID, group, self.__lightGroups))
return True
else:
if self.__verbose:
print("Light {} aldready in group {}".format(lightID, group))
return False
def __getDuplicatesInGroup(self, lightID, group):
indexes = []
for lid in range(0, self.__getNumOfLights(self.__lightGroups[group])):
if str(self.__lightGroups[group][lid]["id"]) == lightID:
indexes.append(lid)
return indexes
def removeLight(self, lightID):
pass
def getLights(self):
if self.__lights == None or (time.time() - self.__lastUpdate) > self.__updateInterval:
self.__lights = self.__requestLightsFromBridge()
if self.__verbose:
print("Found {} lights with data {}".format(len(self.__lights), self.__lights))
return self.__lights
def setColor(self, lightID, hue, sat, bri):
params = {"bri": int(bri), "hue": int(hue), "on": True, "sat": int(sat)}
response_code, data = HTTPS.request(HTTPS.PUT, self.__address, "/api/" + self.__key + "/lights/" + lightID + "/state", params = params)
print("Bridge responded with {}".format(response_code))
def setGroupColor(self, groupe, RGB):
pass
def getGroupSetup(self):
return self.__lightGroups
def getGroups(self):
return self.__groups
def __saveGroup(self):
pass
def __requestLightsFromBridge(self):
response_code, data = HTTPS.request(HTTPS.GET, self.__address, "/api/" + self.__key + "/lights")
lights = []
lightData = []
if data != None:
for light in data:
lights.append(light)
if len(lights) > 0:
for i in range(0, len(lights)):
lightID = lights[i]
lightName = data[lightID]["name"]
lightData.append({"id": lightID, "name": lightName})
return lightData | {"/Hue_Python/lightManager/__init__.py": ["/Hue_Python/lightManager/lightManager.py"], "/Hue_Python/mainThread/__init__.py": ["/Hue_Python/mainThread/mainThread.py"], "/Hue_Python/configManager/__init__.py": ["/Hue_Python/configManager/configManager.py"], "/Hue_Python/camManager/__init__.py": ["/Hue_Python/camManager/camManager.py"], "/Hue_Python/apiManager/apiManager.py": ["/Hue_Python/apiManager/__init__.py"], "/Hue_Python/apiManager/__init__.py": ["/Hue_Python/apiManager/apiManager.py"]} |
64,777 | ldaug99/Hue-Sync-Universal | refs/heads/master | /Hue_Python/configManager/configManager.py | import os
import json
class configManager():
### Static class variables ###
DEFAULT_CONFIG_NAME = "config.txt"
FILE_SUBFOLDER = "//config"
KWARG_DIR = "dir"
KWARG_NAME = "file"
KWARG_VERBOSE = "verbose"
KWARG_DEFAULT = "default"
# Initialization
def __init__(self, **kwargs):
# Get variables
self.__path = {configManager.KWARG_DIR: kwargs.get(configManager.KWARG_DIR, None), configManager.KWARG_NAME: kwargs.get(configManager.KWARG_NAME, None)}
self.__verbose = kwargs.get(configManager.KWARG_VERBOSE, False)
# Check if path is given:
if self.__path[configManager.KWARG_DIR] == None or self.__path[configManager.KWARG_DIR] == configManager.KWARG_DEFAULT:
if self.__verbose:
print("No directory given, using default.")
__script = os.path.realpath(__file__)
__dir = os.path.dirname(__script)
self.__path[configManager.KWARG_DIR] = __dir + configManager.FILE_SUBFOLDER + "\\"
if self.__verbose:
print("Using directory {}".format(self.__path[configManager.KWARG_DIR]))
# Check if filename is given
if self.__path[configManager.KWARG_NAME] == None:
if self.__verbose:
print("No filename given, using default.")
self.__path[configManager.KWARG_NAME] = configManager.DEFAULT_CONFIG_NAME
if self.__verbose:
print("Using filename {}".format(self.__path[configManager.KWARG_NAME]))
def loadData(self, module, key):
fileData = self.__getDataFromFile()
entryData = None
if fileData != None:
if module in fileData:
if key in fileData[module]:
entryData = fileData[module][key]
if self.__verbose:
print("Found data {} at module {} and key {}".format(entryData, module, key))
else:
if self.__verbose:
print("Exception on configManager() -> __loadFromFile(): Key not found in data.")
else:
if self.__verbose:
print("Exception on configManager() -> __loadFromFile(): Module name not found in data.")
else:
if self.__verbose:
print("No config file found.")
return entryData
def saveData(self, module, key, data):
fileData = self.__getDataFromFile()
if fileData != None:
if module in fileData:
moduleData = fileData[module]
moduleData[key] = data
fileData[module] = moduleData
else:
fileData[module] = {key: data}
else:
fileData = {module: {key: data}}
result = False
with open(self.__path[configManager.KWARG_DIR] + self.__path[configManager.KWARG_NAME], "w") as file:
result = json.dump(fileData, file, indent=4, sort_keys=True)
if result == None:
return True
else:
return False
def __getDataFromFile(self):
fileData = None
try:
with open(self.__path[configManager.KWARG_DIR] + self.__path[configManager.KWARG_NAME], "r") as file:
try:
fileData = json.load(file)
except:
if self.__verbose:
print("Config file empty.")
except:
if self.__verbose:
print("No config file found.")
return fileData | {"/Hue_Python/lightManager/__init__.py": ["/Hue_Python/lightManager/lightManager.py"], "/Hue_Python/mainThread/__init__.py": ["/Hue_Python/mainThread/mainThread.py"], "/Hue_Python/configManager/__init__.py": ["/Hue_Python/configManager/configManager.py"], "/Hue_Python/camManager/__init__.py": ["/Hue_Python/camManager/camManager.py"], "/Hue_Python/apiManager/apiManager.py": ["/Hue_Python/apiManager/__init__.py"], "/Hue_Python/apiManager/__init__.py": ["/Hue_Python/apiManager/apiManager.py"]} |
64,778 | ldaug99/Hue-Sync-Universal | refs/heads/master | /Hue_Python/scrap/Python-CLIP-API/other/CLIP-Interface.py | import os
import requests
import json
filename = "config.txt"
apiAddress = ""
apiKey = ""
def readInput(message):
return input(message)
def setIPaddress(ipAddress):
apiAddress = ipAddress
def setAPIkey(key):
apiKey = key
def getAPIkey(ipAddres, **kwargs):
__name = kwargs.get('deviceName', None)
__key = kwargs.get('apiKey', None)
if __name == None:
__name = input("Input device name: ")
params = {"devicetype":__name} # JSON paramaters to send
#response_code, data = sendRequest(POST, ipAddres, "/api", params = params) # Send post reqiest to /api with parameters
response_code = 200
data = [{"success":{"username":"7wg5y9ytGcQmrjmegai7sxzzcMuFBZxJOlzL8zLL"}}]
if response_code == 200: # Check if api got message, code 200 indicates succesfull request
if data != None: # Check if data is none
if "error" in data[0]: #and 101 in data[0]["error"]: # If link button not pressed
print("Press link button on Hue Bridge")
input("Press enter to retry connection") # Wait for input
getAPIkey(ipAddres, deviceName = __name, apiKey = __key) # Retry function
elif "success" in data[0]: # If successfull request
try:
__key = data[0]["success"]["username"] # Save api key
print("Got API key: {}".format(__a__keypiKey))
except:
pass
else:
print("Method didn't return data, which was unexpected")
else:
print("Method returned response code {}, which was unexpected.".format(getResponseCode(response)))
return __key
#def getIPmask(hostIP):
# found_last = False
# last_pos = 0
# while(found_last):
# point = hostIP.find(".", last_pos)
# last_pos = point
# if (hostIP.find(".", last_pos) == -1)
# found_last = True
# IPmask = hostIP.
# return
#while 1==1: # Main loop
# loadConfig() # Load config
#scanNetwork()
#print(getIPmask("192.168.1.87"))
getConfig()
| {"/Hue_Python/lightManager/__init__.py": ["/Hue_Python/lightManager/lightManager.py"], "/Hue_Python/mainThread/__init__.py": ["/Hue_Python/mainThread/mainThread.py"], "/Hue_Python/configManager/__init__.py": ["/Hue_Python/configManager/configManager.py"], "/Hue_Python/camManager/__init__.py": ["/Hue_Python/camManager/camManager.py"], "/Hue_Python/apiManager/apiManager.py": ["/Hue_Python/apiManager/__init__.py"], "/Hue_Python/apiManager/__init__.py": ["/Hue_Python/apiManager/apiManager.py"]} |
64,779 | ldaug99/Hue-Sync-Universal | refs/heads/master | /Hue_Python/scrap/Python-CLIP-API/Hue_old/apiManager.py |
class apiManager:
ADDR = "address"
KEY = "key"
self.__config = {ADDR: None, KEY: None}
self.__address = None
self.__key = None
def __init__(self, **kwargs):
self.__config[ADDR] = kwargs.get("APIaddress", None)
self.__config[KEY] = kwargs.get("APIkey", None)
if self.__config[ADDR] == None or self.__config[KEY] == None:
print("API address and key not defined.")
def run():
if self.__address == None
| {"/Hue_Python/lightManager/__init__.py": ["/Hue_Python/lightManager/lightManager.py"], "/Hue_Python/mainThread/__init__.py": ["/Hue_Python/mainThread/mainThread.py"], "/Hue_Python/configManager/__init__.py": ["/Hue_Python/configManager/configManager.py"], "/Hue_Python/camManager/__init__.py": ["/Hue_Python/camManager/camManager.py"], "/Hue_Python/apiManager/apiManager.py": ["/Hue_Python/apiManager/__init__.py"], "/Hue_Python/apiManager/__init__.py": ["/Hue_Python/apiManager/apiManager.py"]} |
64,780 | ldaug99/Hue-Sync-Universal | refs/heads/master | /Hue_Python/scrap/test_scrap.py |
cm = configManager.cm(dir = "default", file = "l_config.txt", verbose = True)
address = cm.loadData("apiMan", "address")
key = cm.loadData("apiMan", "key")
print("Loaded address {} and key {} from config.".format(address, key))
print(am.isReady())
print(am.getAPIconfig())
print(am.getLights())
cm = configManager.cm(dir = "default", file = "l_config.txt", verbose = True)
address = cm.loadData("apiMan", "address")
key = cm.loadData("apiMan", "key")
print("Loaded address {} and key {} from config.".format(address, key))
print(am.isReady())
print(am.getAPIconfig())
print(am.getLights())
lm = lightManager.lm(verbose = True)
test = cm.loadData(lm.CONFIG_NAME, lm.CONFIG_KEY)
lm.setConfig(test)
test2 = {
"center": ["1", "2"],
"left": ["3", "4"],
"right": ["5"],
"top": [],
"bottom": []
}
print(lm.getConfig())
lm.addLightToGroup("3", "center")
print(lm.getConfig())
lm.addLightToGroup("3", "center")
print(lm.getConfig())
lm.addLightToGroup("1", "left")
print(lm.getConfig())
lm.removeLightFromGroup("1", "left")
print(lm.getConfig())
lm.removeLightFromGroup("1", "left")
print(lm.getConfig())
#cm.saveData(lm.CONFIG_NAME, lm.CONFIG_KEY, test)
lm.removeLightFromGroup("1", "center")
print(lm.getConfig())
print(lm.getLightsInGroup("center"))
| {"/Hue_Python/lightManager/__init__.py": ["/Hue_Python/lightManager/lightManager.py"], "/Hue_Python/mainThread/__init__.py": ["/Hue_Python/mainThread/mainThread.py"], "/Hue_Python/configManager/__init__.py": ["/Hue_Python/configManager/configManager.py"], "/Hue_Python/camManager/__init__.py": ["/Hue_Python/camManager/camManager.py"], "/Hue_Python/apiManager/apiManager.py": ["/Hue_Python/apiManager/__init__.py"], "/Hue_Python/apiManager/__init__.py": ["/Hue_Python/apiManager/apiManager.py"]} |
64,781 | ldaug99/Hue-Sync-Universal | refs/heads/master | /Hue_Python/apiManager/apiManager.py | import time
from rgbxy import Converter
from . import bridgeFinder
from . import keySetup
from . import HTTPS
class apiManager():
### Static class variables ###
CONFIG_NAME = "apiMan"
CONFIG_ADDR = "address"
CONFIG_KEY = "key"
KWARG_ADDR = CONFIG_ADDR
KWARG_KEY = CONFIG_KEY
KWARG_VERBOSE = "verbose"
UPDATE_INTERVAL = 100
#HS_COLORMODE = "hs"
#XY_COLORMODE = "xy"
KWARG_BRI = "bri" # Kwarg to force brightness to a certain value
HUE_C = [
[0.649926, 0.103455, 0.197109],
[0.234327, 0.743075, 0.022598],
[0.000000, 0.053077, 1.035763]
]
GAMUT_C = [
[0.6068909, 0.1735011, 0.2003480],
[0.2989164, 0.5865990, 0.1144845],
[0.0000000, 0.0660957, 1.1162243]
]
CIE_XYZ = [
[0.49000, 0.31000, 0.20000],
[0.17697, 0.81240, 0.01063],
[0.00000, 0.01000, 0.99000]
]
matrix = [
[0.4123865632529917, 0.35759149092062537, 0.18045049120356368],
[0.21263682167732384, 0.7151829818412507, 0.07218019648142547],
[0.019330620152483987, 0.11919716364020845, 0.9503725870054354]
]
REF_WHITE = HUE_C
def __init__(self, **kwargs):
self.__lights = None
self.__lastUpdate = 0
# Get variables
self.__api = {apiManager.KWARG_ADDR: kwargs.get(apiManager.KWARG_ADDR, None), apiManager.KWARG_KEY: kwargs.get(apiManager.KWARG_KEY, None)}
self.__verbose = kwargs.get(apiManager.KWARG_VERBOSE, False)
self.__froceBri = kwargs.get(apiManager.KWARG_BRI, None)
self.__converter = Converter()
if not self.isReady():
if self.__verbose:
print("No API address or key given - Run configAPI()")
def setAPIconfig(address, key):
if address != None and key != None:
self.__api = {apiManager.KWARG_ADDR: address, apiManager.KWARG_KEY: key}
return True
else:
return False
def isReady(self):
return self.__api[apiManager.KWARG_ADDR] != None and self.__api[apiManager.KWARG_KEY] != None
def configAPI(self):
if not self.isReady():
devices = bridgeFinder.scanNetwork()
if devices != None:
if len(devices) > 1:
print("More then one bridge found, which was unexpected.")
else:
address = devices[0]
key = keySetup.getAPIkey(address)
if key == None:
print("Could not obtain key from API.")
return False
self.__api[apiManager.KWARG_ADDR] = address
self.__api[apiManager.KWARG_KEY] = key
return True
else:
print("No bridge found, cannot configure API.")
return False
def getAPIconfig(self):
return self.__api
def getLights(self, force = False):
timeNow = time.time()
if force == True or self.__lights == None or (timeNow - self.__lastUpdate) > apiManager.UPDATE_INTERVAL:
self.__lights = self.__requestLightsFromBridge()
self.__lastUpdate = timeNow
if self.__verbose:
print("Found {} lights with data {}".format(len(self.__lights), self.__lights))
return self.__lights
def __requestLightsFromBridge(self):
response_code, data = HTTPS.request(HTTPS.GET, self.__api[apiManager.KWARG_ADDR], "/api/" + self.__api[apiManager.KWARG_KEY] + "/lights")
#self.__lightConfig = {}
lights = []
lightData = []
if data != None:
for light in data:
lights.append(light)
if len(lights) > 0:
for i in range(0, len(lights)):
try:
lightID = lights[i]
lightName = data[lightID]["name"]
#ligthMode = data[lightID]["state"]["colormode"]
lightData.append({"id": lightID, "name": lightName})
#lightData.append({"id": lightID, "name": lightName, "colormode": ligthMode})
#self.__lightConfig[lightID] = ligthMode
except:
print("Exception on apiManager() -> __requestLightsFromBridge(): Light data does not contain expected entries")
return lightData
#def setColor(self, lightID, sR, sG, sB, sbri):
def setColor(self, lightID, sR, sG, sB):
# https://medium.com/hipster-color-science/a-beginners-guide-to-colorimetry-401f1830b65a
#params = self.__determineColormode(lightID, int(sR), int(sG), int(sB))
#params = self.__convertRGBtoXY(int(sR), int(sG), int(sB), int(sbri))
#params = self.__convertRGBtoXY(int(sR), int(sG), int(sB))
params = self.__easyXY(int(sR), int(sG), int(sB))
if params != None:
response_code, data = HTTPS.request(HTTPS.PUT, self.__api[apiManager.KWARG_ADDR], "/api/" + self.__api[apiManager.KWARG_KEY] + "/lights/" + lightID + "/state", params = params, dataType = "json", verbose = True)
print("Bridge responded with {} and data {}".format(response_code, data))
if response_code < 202:
return True
return False
def __easyXY(self, R, G, B):
param = self.converter(R, G, B)
x = param[0]
y = param[1]
return self.__getXYparams(x, y, 254)
# def __determineColormode(self, lightID, R, G, B):
# try:
# colormode = self.__lightConfig[lightID]
# except:
# colormode = apiManager.HS_COLORMODE
# print("Exception on apiManager() -> __determineColormode(): No config found for lightID {}".format(lightID))
# switcher = {
# apiManager.XY_COLORMODE: self.__convertRGBtoXY,
# apiManager.HS_COLORMODE: self.__convertRGBtoHS
# }
# function = switcher.get(colormode, lambda: self.__invalidColormode)
# return function(R, G, B)
# def __invalidColormode(self, R, G, B):
# return self.__convertRGBtoHS(R, G, B)
#def __convertRGBtoXY(self, R, G, B, bri):
def __convertRGBtoXY(self, R, G, B):
if R != 0 and G != 0 and B != 0:
fR, fG, fB = self.__RGBtoFloat(R, G, B)
# Convert RGB ot XYZ
tx = fR * apiManager.REF_WHITE[0][0] + fG * apiManager.REF_WHITE[0][1] + fB * apiManager.REF_WHITE[0][2]
ty = fR * apiManager.REF_WHITE[1][0] + fG * apiManager.REF_WHITE[1][1] + fB * apiManager.REF_WHITE[1][2]
tz = fR * apiManager.REF_WHITE[2][0] + fG * apiManager.REF_WHITE[2][1] + fB * apiManager.REF_WHITE[2][2]
if self.__verbose:
print("Calculated x {}, y {} and z {}".format(tx,ty,tz))
# Find x and y
x = round(tx / (tx + ty + tz), 2)
y = round(ty / (tx + ty + tz), 2)
#### Check if within color gamut capabilities of light - WIP
#bri = round((254 * ty) + (254 - ty) * (bri / 255))
if self.__froceBri != None:
bri = self.__froceBri
else:
bri = round(254 * ty)
if self.__verbose:
print("RBG to XYZ returnes: xy [{} , {}], brightness {}".format(x,y,bri))
return self.__getXYparams(x, y, int(bri))
else:
if self.__verbose:
print("Color input zero, setting brightness zero")
return self.__getXYparams(0.4, 0.4, 0)
# def __convertRGBtoHS(self, R, G, B):
# # Convert RGB to fraction of RGB from 0 to 1.
# fR, fG, fB = self.__RGBtoFloat(R, G, B)
# # Get maximum value
# Cmax = max(fR, fG, fB)
# # Get minimum value
# Cmin = min(fR, fG, fB)
# # Get difference
# delta = Cmax - Cmin
# # Get hue
# hue = 0
# if delta == 0:
# pass
# elif Cmax == fR:
# hue = (65535/6) * (((fG - fB) / delta) % 6)
# elif Cmax == fG:
# hue = (65535/6) * (((fB - fR) / delta) + 2)
# elif Cmax == fB:
# hue = (65535/6) * (((fR - fG) / delta) + 4)
# # Get brightness
# bri = ((Cmax - Cmin) / 2)
# # Get saturation
# sat = 0
# if delta != 0:
# sat = 255 * (delta / (1 - abs((2 * bri) - 1)))
# # Get brightness (of 0 to 255)
# bri = 255 * bri
# return self.__getHSparams(int(hue), int(sat), int(bri))
def __RGBtoFloat(self, R, G, B):
# Convert RGB to float value (ratioes from 0 to 1 - instead of between 0 255)
return R / 255.0, G / 255.0, B / 255.0
def __getXYparams(self, x, y, bri):
return {"on": True, "bri": bri, "xy": [x, y], "transitiontime": 0}
# def __getHSparams(self, hue, sat, bri):
# return {"bri": bri, "hue": hue, "on": True, "sat": sat, "transitiontime": 1} | {"/Hue_Python/lightManager/__init__.py": ["/Hue_Python/lightManager/lightManager.py"], "/Hue_Python/mainThread/__init__.py": ["/Hue_Python/mainThread/mainThread.py"], "/Hue_Python/configManager/__init__.py": ["/Hue_Python/configManager/configManager.py"], "/Hue_Python/camManager/__init__.py": ["/Hue_Python/camManager/camManager.py"], "/Hue_Python/apiManager/apiManager.py": ["/Hue_Python/apiManager/__init__.py"], "/Hue_Python/apiManager/__init__.py": ["/Hue_Python/apiManager/apiManager.py"]} |
64,782 | ldaug99/Hue-Sync-Universal | refs/heads/master | /Hue_Python/main.py | import configManager
import apiManager
import lightManager
import camManager
import mainThread
import time
class hue():
KWARG_VERBOSE = "verbose"
KWARG_CONFIG = "config"
def __init__(self, **kwargs):
# Get variables
self.__verbose = kwargs.get(hue.KWARG_VERBOSE, False)
self.__config = kwargs.get(hue.KWARG_CONFIG, {"dir": "default", "file": "config.txt"})
# Initialize pathages
# Config manager
self.__cm = configManager.cm(dir = self.__config["dir"], file = self.__config["file"], verbose = self.__verbose)
address = self.__cm.loadData("apiMan", "address")
key = self.__cm.loadData("apiMan", "key")
# API manager
if address != None and key != None:
self.__am = apiManager.am(address = address, key = key, verbose = self.__verbose, bri = 254)
else:
self.__am = apiManager.am(verbose = self.__verbose)
if not self.__am.isReady():
self.__am.configAPI()
apiConfig = self.__am.getAPIconfig()
self.__cm.saveData(self.__am.CONFIG_NAME, self.__am.CONFIG_ADDR, apiConfig[self.__am.CONFIG_ADDR])
self.__cm.saveData(self.__am.CONFIG_NAME, self.__am.CONFIG_KEY, apiConfig[self.__am.CONFIG_KEY])
# Light manager
self.__lm = lightManager.lm(verbose = self.__verbose)
lightData = self.__cm.loadData(self.__lm.CONFIG_NAME, self.__lm.CONFIG_KEY)
if lightData != None:
self.__lm.setConfig(lightData)
# Camera manager
self.__wm = camManager.wm(0, verbose = self.__verbose)
if not self.__wm.isReady():
if not self.__wm.retryOpen():
print("Exception on hue() -> __init__(): Unable to start camera manager.")
return False
# Main thread
self.__mt = mainThread.mt(self.__lm, self.__am, self.__wm, verbose = self.__verbose)
self.__mt.setName("mainThread")
self.__mt.start()
time.sleep(0.5)
if not self.__mt.isRunning():
try:
self.__mt.join()
except:
pass
print("Exception on hue() -> __init__(): Unable to start main thread.")
# Done setup
if self.__verbose:
print("Module initialization complete")
def cleanup(self):
self.__wm.release()
self.__mt.stop()
self.__mt.join()
def getLights(self):
return self.__am.getLights()
def addLightToGroup(self, lightID, group):
lights = self.getLights()
for entry in lights:
if entry["id"] == lightID:
if self.__lm.addLightToGroup(lightID, group):
self.__cm.saveData(self.__lm.CONFIG_NAME, self.__lm.CONFIG_KEY, self.__lm.getConfig())
return True
return False
def removeLightFromGroup(self, lightID, group):
lights = []
if lightID == "*":
lightsInGroup = self.__lm.getLightsInGroup(group)
if lightsInGroup != None:
for light in lightsInGroup:
lights.append(light)
else:
lights = lightID
for light in lights:
if not self.__lm.removeLightFromGroup(light, group):
return False
self.__cm.saveData(self.__lm.CONFIG_NAME, self.__lm.CONFIG_KEY, self.__lm.getConfig())
return True
def getGroups(self):
return(self.__lm.getConfig())
def setLight(self, lightID, r, g, b):
return self.__am.setColor(lightID, r, g, b)
def setGroupLight(self, group, r, g, b):
lights = self.__lm.getLightsInGroup(group)
for lightID in lights:
self.__am.setColor(lightID, r, g, b)
if lights == None:
return False
return True
def setUpdateFrequency(self, fs):
if self.__mt.isRunning():
self.__mt.setFs(int(fs))
else:
print("Exception on hue() -> setUpdateFrequency(): mainThread not running.")
def startColorCapture(self):
if self.__mt.isRunning():
self.__mt.startCapture()
else:
print("Exception on hue() -> startColorCapture(): mainThread not running.")
def stopColorCapture(self):
if self.__mt.isRunning():
self.__mt.stopCapture()
else:
print("Exception on hue() -> stopColorCapture(): mainThread not running.")
def showFrame(self, state):
self.__wm.showFrame(state) | {"/Hue_Python/lightManager/__init__.py": ["/Hue_Python/lightManager/lightManager.py"], "/Hue_Python/mainThread/__init__.py": ["/Hue_Python/mainThread/mainThread.py"], "/Hue_Python/configManager/__init__.py": ["/Hue_Python/configManager/configManager.py"], "/Hue_Python/camManager/__init__.py": ["/Hue_Python/camManager/camManager.py"], "/Hue_Python/apiManager/apiManager.py": ["/Hue_Python/apiManager/__init__.py"], "/Hue_Python/apiManager/__init__.py": ["/Hue_Python/apiManager/apiManager.py"]} |
64,783 | ldaug99/Hue-Sync-Universal | refs/heads/master | /Hue_Python/scrap/Python-CLIP-API/Hue_old/main.py | from Hue import Hue
print("Setting up.")
hue = Hue()
while 1==1:
pass | {"/Hue_Python/lightManager/__init__.py": ["/Hue_Python/lightManager/lightManager.py"], "/Hue_Python/mainThread/__init__.py": ["/Hue_Python/mainThread/mainThread.py"], "/Hue_Python/configManager/__init__.py": ["/Hue_Python/configManager/configManager.py"], "/Hue_Python/camManager/__init__.py": ["/Hue_Python/camManager/camManager.py"], "/Hue_Python/apiManager/apiManager.py": ["/Hue_Python/apiManager/__init__.py"], "/Hue_Python/apiManager/__init__.py": ["/Hue_Python/apiManager/apiManager.py"]} |
64,784 | ldaug99/Hue-Sync-Universal | refs/heads/master | /Hue_Python/apiManager/__init__.py | from .apiManager import apiManager as am
#import apiManager.HTTPS as HTTPS
#import apiManager.keySetup as keySetup
#import apiManager.bridgeFinder as bridgeFinder
from . import HTTPS as HTTPS
from . import keySetup as keySetup
from . import bridgeFinder as bridgeFinder | {"/Hue_Python/lightManager/__init__.py": ["/Hue_Python/lightManager/lightManager.py"], "/Hue_Python/mainThread/__init__.py": ["/Hue_Python/mainThread/mainThread.py"], "/Hue_Python/configManager/__init__.py": ["/Hue_Python/configManager/configManager.py"], "/Hue_Python/camManager/__init__.py": ["/Hue_Python/camManager/camManager.py"], "/Hue_Python/apiManager/apiManager.py": ["/Hue_Python/apiManager/__init__.py"], "/Hue_Python/apiManager/__init__.py": ["/Hue_Python/apiManager/apiManager.py"]} |
64,785 | ldaug99/Hue-Sync-Universal | refs/heads/master | /Hue_Python/scrap/Python-CLIP-API/test/kwargs.py |
def method(**kwargs):
print(kwargs)
def method2(**kwargs):
method(**kwargs)
keywords = {"key1": "test1", "key2": "test2"}
method2(**keywords) | {"/Hue_Python/lightManager/__init__.py": ["/Hue_Python/lightManager/lightManager.py"], "/Hue_Python/mainThread/__init__.py": ["/Hue_Python/mainThread/mainThread.py"], "/Hue_Python/configManager/__init__.py": ["/Hue_Python/configManager/configManager.py"], "/Hue_Python/camManager/__init__.py": ["/Hue_Python/camManager/camManager.py"], "/Hue_Python/apiManager/apiManager.py": ["/Hue_Python/apiManager/__init__.py"], "/Hue_Python/apiManager/__init__.py": ["/Hue_Python/apiManager/apiManager.py"]} |
64,786 | ldaug99/Hue-Sync-Universal | refs/heads/master | /Hue_Python/camManager/scrap/cam_test2.py | import cv2
video = cv2.VideoCapture(0)
print(video)
check, frame = video.read()
print(check)
print(frame)
video.release() | {"/Hue_Python/lightManager/__init__.py": ["/Hue_Python/lightManager/lightManager.py"], "/Hue_Python/mainThread/__init__.py": ["/Hue_Python/mainThread/mainThread.py"], "/Hue_Python/configManager/__init__.py": ["/Hue_Python/configManager/configManager.py"], "/Hue_Python/camManager/__init__.py": ["/Hue_Python/camManager/camManager.py"], "/Hue_Python/apiManager/apiManager.py": ["/Hue_Python/apiManager/__init__.py"], "/Hue_Python/apiManager/__init__.py": ["/Hue_Python/apiManager/apiManager.py"]} |
64,805 | measure-your-life-squad/measure-your-life | refs/heads/develop | /api_backend_server/tests/conftest.py | import os
import sys
import pathlib
web_app_dir = "web_app"
backend_root_path = pathlib.Path(__file__).parent.parent.absolute()
web_app_path = os.path.join(backend_root_path, web_app_dir)
sys.path.append(web_app_path)
| {"/api_backend_server/tests/unit_tests/test_users.py": ["/api_backend_server/web_app/apis/users.py", "/api_backend_server/web_app/models/__init__.py"], "/api_backend_server/tests/unit_tests/test_statistics.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/apis/statistics.py"], "/api_backend_server/tests/unit_tests/test_activities_api.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/models/__init__.py"]} |
64,806 | measure-your-life-squad/measure-your-life | refs/heads/develop | /api_backend_server/web_app/apis/users.py | import datetime
import uuid
from typing import Tuple
import jwt
from flask import request, jsonify, current_app, Response, render_template
from werkzeug.security import generate_password_hash
from mongoengine.errors import NotUniqueError, ValidationError
from models import Users
from api_utils.auth_utils import admin_scope_required
from api_utils.email_utils import send_confirmation_email
from api_utils.auth_utils import (
get_url_serializer_and_salt,
confirm_token,
)
def save_user(**kwargs):
try:
Users(**kwargs).save()
except NotUniqueError:
payload = {"message": "username or email address already in use"}
http_code = 409
except ValidationError as e:
if e.message and "Invalid email address" in e.message:
payload = {"message": f"invalid email address: {kwargs['email']}"}
http_code = 422
else:
raise e
else:
payload = {"message": "registered successfuly", "user_id": kwargs["public_id"]}
http_code = 200
return dict(payload=payload, http_code=http_code)
def confirm_email(token):
safe_url_token_tools = get_url_serializer_and_salt()
try:
email = confirm_token(token, **safe_url_token_tools)
(user,) = Users.objects(email=email)
except Exception:
# TODO: introduce auth logging
return render_template(
"account_confirmation.html",
top_m="This confirmation link is invalid or has expired.",
bottom_m="You can resend the account confirmation link via the form below.",
invalid=True,
)
if user.email_confirmed:
return render_template(
"account_confirmation.html",
top_m="Your account is already confirmed!",
bottom_m="Don't worry about confirming it again :)",
)
else:
user.update(set__email_confirmed=True)
return render_template(
"account_confirmation.html",
top_m=f"Thanks {user.username}! Your account has been successfully confirmed.",
bottom_m="Enjoy each and every feature of Measure-Your-Life app :)",
)
def resend_confirmation_email():
data = request.form
# TODO: some weird bug that those templates are returned as jsons although set as
# text/html in openapi definition :/
if not Users.validate_if_existing_user(email=data["email"]):
return render_template(
"account_confirmation.html",
top_m="This email address is not linked to any account :(",
bottom_m="You can sign up via the application though!",
)
send_email_response = send_confirmation_email(data["email"])
if send_email_response in range(200, 300):
return render_template(
"account_confirmation.html",
top_m="Confirmation email resent successfully!",
bottom_m="You can check your mailbox.",
)
else:
return render_template(
"account_confirmation.html",
top_m="Oops, something went wrong :(",
bottom_m="Please try again later.",
)
def signup_user() -> Tuple[Response, int]:
data = request.get_json()
data["password"] = generate_password_hash(data["password"], method="sha256")
data["public_id"] = str(uuid.uuid4())
data["admin"] = False
data["email_confirmed"] = False
# TODO: saving and deleting the user in case of email confirmation failures are
# atomic operations - they should be refactored to a single transaction
# (pymongo use may be necessary, mongoengine does not support transactions)
saving_user_outcome = save_user(**data)
if saving_user_outcome["http_code"] != 200:
return jsonify(saving_user_outcome["payload"]), saving_user_outcome["http_code"]
send_email_response = send_confirmation_email(data["email"])
if send_email_response in range(200, 300):
return jsonify(saving_user_outcome["payload"]), saving_user_outcome["http_code"]
else:
Users.delete_user(saving_user_outcome["payload"]["user_id"])
return jsonify({"message": "Oops, something went wrong :("}), 500
def login_user(token_info: dict) -> Response:
token = jwt.encode(
{
"public_id": token_info["public_id"],
"exp": datetime.datetime.utcnow() + datetime.timedelta(minutes=30),
"scope": token_info["sub"],
},
current_app.config["SECRET_KEY"],
)
return jsonify(
{
"token": token.decode("UTF-8"),
"email_confirmed": token_info["email_confirmed"],
}
)
@admin_scope_required
def get_all_users(token_info: dict) -> Tuple[Response, int]:
users = Users.objects.only(
"public_id", "username", "admin", "email", "email_confirmed"
).exclude("id")
return jsonify({"users": users}), 200
| {"/api_backend_server/tests/unit_tests/test_users.py": ["/api_backend_server/web_app/apis/users.py", "/api_backend_server/web_app/models/__init__.py"], "/api_backend_server/tests/unit_tests/test_statistics.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/apis/statistics.py"], "/api_backend_server/tests/unit_tests/test_activities_api.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/models/__init__.py"]} |
64,807 | measure-your-life-squad/measure-your-life | refs/heads/develop | /api_backend_server/tests/integration_tests/test_hello_webserver.py | import requests
def test_get_hello_message():
response = requests.get("http://localhost:80")
assert response.json()["message"] == "Hello from Python backend server"
| {"/api_backend_server/tests/unit_tests/test_users.py": ["/api_backend_server/web_app/apis/users.py", "/api_backend_server/web_app/models/__init__.py"], "/api_backend_server/tests/unit_tests/test_statistics.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/apis/statistics.py"], "/api_backend_server/tests/unit_tests/test_activities_api.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/models/__init__.py"]} |
64,808 | measure-your-life-squad/measure-your-life | refs/heads/develop | /api_backend_server/tests/unit_tests/test_users.py | from api_backend_server.web_app.apis.users import save_user
from api_backend_server.web_app.models import Users
import pytest
from mongoengine import connect
@pytest.fixture(scope='function')
def mongo(request):
db = connect('mongoenginetest', host='mongomock://localhost')
yield db
db.drop_database('mongoenginetest')
db.close()
def test_save_user_should_succeed(mongo):
fresh_user_save = save_user(public_id='3b241101-e2bb-4255-8caf-4136c566a962',
username='testusername',
password='testpassword',
email='testmail@mail.com')
fresh_user2_save = save_user(public_id='3b241101-e2bb-4255-8caf-4136c566a964',
username='2testusername2',
password='testpassword',
email='2testmail2@mail.com')
fresh_user = Users.objects().first()
assert fresh_user.username == 'testusername'
assert fresh_user_save['payload'] == {"message": "registered successfuly",
"user_id":
'3b241101-e2bb-4255-8caf-4136c566a962'}
assert fresh_user_save['http_code'] == 200
assert fresh_user2_save['payload'] == {"message": "registered successfuly",
"user_id":
'3b241101-e2bb-4255-8caf-4136c566a964'}
assert fresh_user2_save['http_code'] == 200
def test_save_user_not_unique_error_username(mongo):
fresh_user = save_user(public_id='3b241101-e2bb-4255-8caf-4136c566a964',
username='testusername',
password='testpassword',
email='1testmail1@mail.com')
repeated_user = save_user(public_id='3b241101-e2bb-4255-8caf-4136c566a964',
username='testusername',
password='testpassword',
email='2testmail2@mail.com')
assert fresh_user['payload'] == {"message": "registered successfuly",
"user_id":
'3b241101-e2bb-4255-8caf-4136c566a964'}
assert fresh_user['http_code'] == 200
assert repeated_user['payload'] == {
"message": "username or email address already in use"}
assert repeated_user['http_code'] == 409
def test_save_user_not_unique_error_email(mongo):
fresh_user = save_user(public_id='3b241101-e2bb-4255-8caf-4136c566a964',
username='1testusername1',
password='testpassword',
email='testmail@mail.com')
repeated_user = save_user(public_id='3b241101-e2bb-4255-8caf-4136c566a964',
username='2testusername2',
password='testpassword',
email='testmail@mail.com')
assert fresh_user['payload'] == {"message": "registered successfuly",
"user_id":
'3b241101-e2bb-4255-8caf-4136c566a964'}
assert fresh_user['http_code'] == 200
assert repeated_user['payload'] == {
"message": "username or email address already in use"}
assert repeated_user['http_code'] == 409
def test_save_user_validation_error(mongo):
fresh_user = save_user(public_id='3b241101-e2bb-4255-8caf-4136c566a964',
username='testusername',
password='testpassword',
email='testmailmail.com')
assert fresh_user['payload'] == {
"message": f"invalid email address: testmailmail.com"}
assert fresh_user['http_code'] == 422
| {"/api_backend_server/tests/unit_tests/test_users.py": ["/api_backend_server/web_app/apis/users.py", "/api_backend_server/web_app/models/__init__.py"], "/api_backend_server/tests/unit_tests/test_statistics.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/apis/statistics.py"], "/api_backend_server/tests/unit_tests/test_activities_api.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/models/__init__.py"]} |
64,809 | measure-your-life-squad/measure-your-life | refs/heads/develop | /api_backend_server/web_app/apis/categories.py | from typing import Tuple
from flask import jsonify, Response
from models import Categories
def get_available_categories(token_info: dict) -> Tuple[Response, int]:
categories = Categories.objects.only("public_id", "name", "icon_name").exclude("id")
return jsonify({"categories": categories})
def _get_specific_category(category_id: str) -> str:
try:
(category,) = Categories.objects(public_id=category_id)
except ValueError as e:
if (
len(e.args) > 0
and e.args[0] == "not enough values to unpack (expected 1, got 0)"
):
raise ValueError(
f"Category with id={category_id} does not exist in the Database"
) from e
else:
raise e
return category
| {"/api_backend_server/tests/unit_tests/test_users.py": ["/api_backend_server/web_app/apis/users.py", "/api_backend_server/web_app/models/__init__.py"], "/api_backend_server/tests/unit_tests/test_statistics.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/apis/statistics.py"], "/api_backend_server/tests/unit_tests/test_activities_api.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/models/__init__.py"]} |
64,810 | measure-your-life-squad/measure-your-life | refs/heads/develop | /api_backend_server/web_app/database.py | import connexion
from flask_mongoengine import MongoEngine
db = MongoEngine()
def initialize_db(app: connexion.App) -> None:
db.init_app(app)
| {"/api_backend_server/tests/unit_tests/test_users.py": ["/api_backend_server/web_app/apis/users.py", "/api_backend_server/web_app/models/__init__.py"], "/api_backend_server/tests/unit_tests/test_statistics.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/apis/statistics.py"], "/api_backend_server/tests/unit_tests/test_activities_api.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/models/__init__.py"]} |
64,811 | measure-your-life-squad/measure-your-life | refs/heads/develop | /api_backend_server/web_app/apis/root.py | from flask import jsonify, Response
def hello() -> Response:
return jsonify(message="Hello from Python backend server")
| {"/api_backend_server/tests/unit_tests/test_users.py": ["/api_backend_server/web_app/apis/users.py", "/api_backend_server/web_app/models/__init__.py"], "/api_backend_server/tests/unit_tests/test_statistics.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/apis/statistics.py"], "/api_backend_server/tests/unit_tests/test_activities_api.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/models/__init__.py"]} |
64,812 | measure-your-life-squad/measure-your-life | refs/heads/develop | /api_backend_server/tests/integration_tests/integration_utils.py | from uuid import UUID
import re
def is_valid_uuid(id_to_test):
try:
UUID(str(id_to_test))
return True
except ValueError:
return False
def is_valid_jwt(token_to_test):
match = re.search(
r"^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.[A-Za-z0-9-_.+/=]*$",
token_to_test
)
return bool(match)
| {"/api_backend_server/tests/unit_tests/test_users.py": ["/api_backend_server/web_app/apis/users.py", "/api_backend_server/web_app/models/__init__.py"], "/api_backend_server/tests/unit_tests/test_statistics.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/apis/statistics.py"], "/api_backend_server/tests/unit_tests/test_activities_api.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/models/__init__.py"]} |
64,813 | measure-your-life-squad/measure-your-life | refs/heads/develop | /api_backend_server/web_app/api_utils/email_utils.py | import os
import logging
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
from flask import url_for, render_template
from api_utils.auth_utils import (
get_url_serializer_and_salt,
generate_confirmation_token,
)
FROM_EMAIL = "no_reply@myl.com"
FORMATTER = logging.Formatter("%(asctime)s — %(name)s — %(levelname)s — %(message)s")
email_logger = logging.getLogger(__name__)
email_logger.setLevel(logging.INFO)
console_handler = logging.StreamHandler()
console_handler.setFormatter(FORMATTER)
email_logger.addHandler(console_handler)
def send_email(email_address, msg, subject):
# TODO: try to split SendGrid client instantiation with send email api
message = Mail(
from_email=FROM_EMAIL,
to_emails=email_address,
subject=subject,
html_content=msg,
)
try:
sg = SendGridAPIClient(os.environ.get("SENDGRID_API_KEY"))
except Exception as e:
email_logger.error(e)
return 401
try:
response = sg.send(message)
except Exception as e:
email_logger.error(e)
return 500
else:
email_logger.info(
f"Sent email to {email_address}, "
f"SendGrid status code: {response.status_code}"
)
return response.status_code
def send_confirmation_email(email):
safe_url_token_tools = get_url_serializer_and_salt()
token = generate_confirmation_token(email, **safe_url_token_tools)
confirm_url = url_for(".apis_users_confirm_email", token=token, _external=True)
subject = "MYL - Please confirm your email address"
msg = render_template("activate_email.html", confirm_url=confirm_url)
return send_email(email, msg, subject)
| {"/api_backend_server/tests/unit_tests/test_users.py": ["/api_backend_server/web_app/apis/users.py", "/api_backend_server/web_app/models/__init__.py"], "/api_backend_server/tests/unit_tests/test_statistics.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/apis/statistics.py"], "/api_backend_server/tests/unit_tests/test_activities_api.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/models/__init__.py"]} |
64,814 | measure-your-life-squad/measure-your-life | refs/heads/develop | /api_backend_server/web_app/apis/statistics.py | from typing import Tuple, Union
from math import ceil
from flask import Response, jsonify
from mongoengine import Document, QuerySet
from models import Activities, Categories
from api_utils import auth_utils
from apis.activities import _parse_to_utc_iso8610
CATEGORIES = {
"WORK": "1",
"DUTIES": "2",
"LEISURE": "3",
}
NO_DATA_RESPONSE = {
"WORK": 0.0,
"WORK_AVG": 0,
"DUTIES": 0.0,
"DUTIES_AVG": 0,
"LEISURE": 0.0,
"LEISURE_AVG": 0,
}
MINS_IN_DAY = 1440
def _calculate_category_duration(activities: QuerySet, category_id: str) -> float:
category = Categories.get_specific_category(category_id=category_id)
activities = [
activity
for activity in activities
if activity.category == category
]
sum_duration = sum([activity.duration for activity in activities])
return sum_duration
def _calculate_time_window(activities: Document) -> float:
min_start = min([activity.activity_start for activity in activities])
max_end = max([activity.activity_end for activity in activities])
time_window = (max_end - min_start).total_seconds() / 60
return time_window
def _calculate_daily_average(sum_duration: float, time_window: float) -> int:
days_rounded_up = ceil(time_window / MINS_IN_DAY)
daily_average = sum_duration / days_rounded_up
return int(daily_average)
def _calculate_category_share(sum_duration: float, time_window: float):
share = sum_duration / time_window
return share
def _build_shared_json(time_window: float, activities: QuerySet) -> dict:
result = {}
for cat, cat_id in CATEGORIES.items():
duration = _calculate_category_duration(activities, cat_id)
share = _calculate_category_share(duration, time_window)
result.update({cat: share})
return result
def _build_averages_json(time_window: float, activities: QuerySet) -> dict:
result = {}
for cat, cat_id in CATEGORIES.items():
duration = _calculate_category_duration(activities, cat_id)
average = _calculate_daily_average(duration, time_window)
result.update({f"{cat}_AVG": average})
return result
@auth_utils.confirmed_user_required
def get_rolling_meter(
token_info: dict,
include_unassigned: bool = True,
start_range: Union[str, None] = None,
end_range: Union[str, None] = None,
) -> Tuple[Response, int]:
if start_range and end_range:
start_parsed = _parse_to_utc_iso8610(start_range).replace(tzinfo=None)
end_parsed = _parse_to_utc_iso8610(end_range).replace(tzinfo=None)
activities = Activities.objects(user_id=token_info["public_id"]).exclude("id")
activities = [
activity
for activity in activities
if (activity.activity_start >= start_parsed)
and (activity.activity_end <= end_parsed)
]
else:
activities = Activities.objects(user_id=token_info["public_id"]).exclude("id")
if include_unassigned:
time_window = _calculate_time_window(activities)
else:
time_window = sum([activity.duration for activity in activities])
if time_window == 0:
return jsonify(
NO_DATA_RESPONSE
)
share_response = _build_shared_json(time_window, activities)
average_response = _build_averages_json(time_window, activities)
share_response.update(average_response)
return jsonify(share_response)
@auth_utils.confirmed_user_required
def get_oldest_date(token_info: dict) -> Tuple[Response, int]:
oldest_activity = (
Activities.objects(user_id=token_info["public_id"])
.aggregate(
[{"$group": {"_id": 0, "oldest_date": {"$min": "$activity_start"}, }}]
)
.next()
)
oldest_activity.pop("_id", None)
return jsonify(oldest_activity)
| {"/api_backend_server/tests/unit_tests/test_users.py": ["/api_backend_server/web_app/apis/users.py", "/api_backend_server/web_app/models/__init__.py"], "/api_backend_server/tests/unit_tests/test_statistics.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/apis/statistics.py"], "/api_backend_server/tests/unit_tests/test_activities_api.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/models/__init__.py"]} |
64,815 | measure-your-life-squad/measure-your-life | refs/heads/develop | /api_backend_server/web_app/app.py | from server import app
import database
if __name__ == "__main__":
database.initialize_db(app.app)
app.run(host="0.0.0.0", debug=True, use_reloader=False)
| {"/api_backend_server/tests/unit_tests/test_users.py": ["/api_backend_server/web_app/apis/users.py", "/api_backend_server/web_app/models/__init__.py"], "/api_backend_server/tests/unit_tests/test_statistics.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/apis/statistics.py"], "/api_backend_server/tests/unit_tests/test_activities_api.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/models/__init__.py"]} |
64,816 | measure-your-life-squad/measure-your-life | refs/heads/develop | /api_backend_server/web_app/api_utils/auth_utils.py | from functools import wraps
from typing import Callable
import six
from flask import jsonify, current_app
from werkzeug.security import check_password_hash
from werkzeug.exceptions import Unauthorized
import jwt
from jwt.exceptions import DecodeError
from itsdangerous import URLSafeTimedSerializer
from models import Users
def get_url_serializer_and_salt():
serializer = URLSafeTimedSerializer(current_app.config["SECRET_KEY"])
salt = current_app.config["SECURITY_PASSWORD_SALT"]
return dict(serializer=serializer, salt=salt)
def generate_confirmation_token(email, serializer, salt):
return serializer.dumps(email, salt=salt)
def confirm_token(token, serializer, salt, expiration=86400):
try:
email = serializer.loads(token, salt=salt, max_age=expiration)
except Exception:
# TODO: introduce auth logging
return False
return email
def basic_auth(username: str, password: str, required_scopes: str = None) -> dict:
info = None
# TODO: refactor to use Users static method to check if user exists and get user
# document (violates DRY)
try:
(user,) = Users.objects(username=username)
except ValueError as e:
if (
len(e.args) > 0
and e.args[0] == "not enough values to unpack (expected 1, got 0)"
):
raise ValueError(
f"User with username={username} not found in the Database"
) from e
else:
raise ValueError(
f"More than one user with username={username} found in the Database"
) from e
if check_password_hash(user.password, password):
if user.admin:
info = {"sub": "admin", "public_id": str(user.public_id)}
else:
info = {"sub": "user", "public_id": str(user.public_id)}
info.update(email_confirmed=user.email_confirmed)
return info
def decode_token(token: str) -> dict:
try:
return jwt.decode(token, current_app.config["SECRET_KEY"])
except DecodeError as e:
six.raise_from(Unauthorized, e)
def admin_scope_required(f: Callable) -> Callable:
@wraps(f)
def wrapper(*args, **kwargs):
if kwargs["token_info"]["scope"] == "admin":
return f(*args, **kwargs)
else:
return jsonify(
{
"detail": "The server could not verify that you are authorized to access the URL requested. You either supplied the wrong credentials (e.g. a bad password), or your browser doesn't understand how to supply the credentials required.", # NOQA
"status": 401,
"title": "Unauthorized",
"type": "about:blank",
}
)
return wrapper
def confirmed_user_required(f: Callable) -> Callable:
@wraps(f)
def wrapper(*args, **kwargs):
(user,) = Users.objects(public_id=kwargs["token_info"]["public_id"])
if user.email_confirmed:
return f(*args, **kwargs)
else:
return jsonify(
{
"detail": "This operation is allowed only for confirmed user accounts. Please confirm your email address.", # NOQA
"status": 401,
"title": "Unauthorized",
"type": "about:blank",
}
)
return wrapper
| {"/api_backend_server/tests/unit_tests/test_users.py": ["/api_backend_server/web_app/apis/users.py", "/api_backend_server/web_app/models/__init__.py"], "/api_backend_server/tests/unit_tests/test_statistics.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/apis/statistics.py"], "/api_backend_server/tests/unit_tests/test_activities_api.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/models/__init__.py"]} |
64,817 | measure-your-life-squad/measure-your-life | refs/heads/develop | /api_backend_server/web_app/apis/activities.py | import uuid
import datetime
from typing import Tuple
import logging
from dateutil import parser as dp
from dateutil import tz
from flask import request, jsonify, Response
from models import Activities, Categories
from api_utils import auth_utils
FORMATTER = logging.Formatter("%(asctime)s — %(name)s — %(levelname)s — %(message)s")
activity_logger = logging.getLogger(__name__)
activity_logger.setLevel(logging.INFO)
console_handler = logging.StreamHandler()
console_handler.setFormatter(FORMATTER)
activity_logger.addHandler(console_handler)
@auth_utils.confirmed_user_required
def create_activity(token_info: dict) -> Tuple[Response, int]:
data = request.get_json()
start = _parse_to_utc_iso8610(data["activity_start"])
end = _parse_to_utc_iso8610(data["activity_end"])
if _validate_time_overlapping(start, end, token_info):
return (
jsonify(
{
"message": "Change start or end time of activity due to overlapping activities" # NOQA
}
),
422,
)
activity_id = str(uuid.uuid4())
category = Categories.get_specific_category(data["category_id"])
duration = _calculate_duration_in_mins(start, end)
Activities(
activity_id=activity_id,
name=data["name"],
user_id=token_info["public_id"],
activity_start=start,
activity_end=end,
category=category,
duration=duration,
).save()
return jsonify({"activity_id": activity_id}), 200
def _validate_time_overlapping(
activity_start, activity_end, token_info: dict, activity_id: str = None
):
activity_logger.info(activity_id)
if activity_id:
activities = Activities.objects(
user_id=token_info["public_id"], activity_id__ne=activity_id
).exclude("id")
else:
activities = Activities.objects(user_id=token_info["public_id"]).exclude("id")
activities_starting_time_and_ending_time = [
{
"activity_start": activity.activity_start,
"activity_end": activity.activity_end,
}
for activity in activities
]
for i in range(len(activities_starting_time_and_ending_time)):
if (
activity_start.replace(tzinfo=None)
< activities_starting_time_and_ending_time[i]["activity_end"]
and activity_end.replace(tzinfo=None)
> activities_starting_time_and_ending_time[i]["activity_start"]
):
return True
return False
@auth_utils.confirmed_user_required
def get_user_activities(token_info: dict) -> Tuple[Response, int]:
activities = Activities.objects(user_id=token_info["public_id"]).exclude("id")
parsed_activities = [
{
"activity_id": activity.activity_id,
"user_id": activity.user_id,
"name": activity.name,
"category": activity.category.public_id,
"activity_start": _convert_unix_to_iso8610(activity.activity_start),
"activity_end": _convert_unix_to_iso8610(activity.activity_end),
}
for activity in activities
]
return jsonify({"activities": parsed_activities}), 200
@auth_utils.confirmed_user_required
def delete_user_activity(token_info: dict, activity_id: str) -> Tuple[Response, int]:
Activities.delete_specific_activity(activity_id)
return jsonify({"message": f"Activity {activity_id} successfully deleted."}), 200
@auth_utils.confirmed_user_required
def edit_user_activity(token_info: dict, activity_id: str) -> Tuple[Response, int]:
data = request.get_json()
category = Categories.get_specific_category(data.pop("category_id"))
start = _parse_to_utc_iso8610(data["activity_start"])
end = _parse_to_utc_iso8610(data["activity_end"])
if _validate_time_overlapping(start, end, token_info, activity_id=activity_id):
return (
jsonify(
{
"message": "Change start or end time of activity due to overlapping activities" # NOQA
}
),
422,
)
data.update(category=category)
data.update(duration=_calculate_duration_in_mins(start, end))
data["activity_start"] = start
data["activity_end"] = end
updated_activity = Activities.edit_specific_activity(activity_id, **data)
print(updated_activity)
return jsonify({"message": f"Activity {activity_id} successfully updated."}), 200
def _convert_unix_to_iso8610(unix_timestamp: datetime) -> str:
iso_timestamp = unix_timestamp.astimezone(tz.UTC).isoformat()
return iso_timestamp
def _parse_to_utc_iso8610(string_timestamp: str) -> datetime:
return dp.isoparse(string_timestamp).astimezone(tz.UTC)
def _calculate_duration_in_mins(start: datetime, end: datetime) -> float:
duration = (end - start).total_seconds() / 60
return duration
| {"/api_backend_server/tests/unit_tests/test_users.py": ["/api_backend_server/web_app/apis/users.py", "/api_backend_server/web_app/models/__init__.py"], "/api_backend_server/tests/unit_tests/test_statistics.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/apis/statistics.py"], "/api_backend_server/tests/unit_tests/test_activities_api.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/models/__init__.py"]} |
64,818 | measure-your-life-squad/measure-your-life | refs/heads/develop | /api_backend_server/tests/integration_tests/test_users_apis.py | from collections import namedtuple
import string
import random
import pytest
import requests
from requests.auth import HTTPBasicAuth
import integration_utils
def get_random_string(string_length=5):
letters = string.ascii_lowercase
return "".join([random.choice(letters) for i in range(0, string_length)])
@pytest.fixture(scope="module")
def credentials():
Credentials = namedtuple("Credentials", "username password email")
credentials = Credentials(
username=get_random_string(),
password="test_username_password",
email=f"{get_random_string()}@email.com",
)
return credentials
def test_user_signup(credentials):
payload = {
"username": credentials.username,
"password": credentials.password,
"email": credentials.email,
}
response = requests.post("http://localhost:80/api/users/register", json=payload)
response_json = response.json()
assert response_json["message"] == "registered successfuly"
assert integration_utils.is_valid_uuid(response_json["user_id"])
def test_user_login(credentials):
response = requests.post(
"http://localhost:80/api/users/login",
auth=HTTPBasicAuth(credentials.username, credentials.password),
)
response_json = response.json()
assert integration_utils.is_valid_jwt(response_json["token"])
| {"/api_backend_server/tests/unit_tests/test_users.py": ["/api_backend_server/web_app/apis/users.py", "/api_backend_server/web_app/models/__init__.py"], "/api_backend_server/tests/unit_tests/test_statistics.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/apis/statistics.py"], "/api_backend_server/tests/unit_tests/test_activities_api.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/models/__init__.py"]} |
64,819 | measure-your-life-squad/measure-your-life | refs/heads/develop | /api_backend_server/tests/unit_tests/test_statistics.py | from api_backend_server.web_app.apis.activities import _parse_to_utc_iso8610
from api_backend_server.web_app.apis.statistics import (
_calculate_daily_average,
_calculate_category_share
)
simple_activity_data = {'activity_id': "6fdfa589-412c-489f-92fa-b472ee9fae7c",
'name': "activity_sample",
'user_id': "4f175f70-d192-42a4-bd74-6f5b5baf7963",
'activity_start': _parse_to_utc_iso8610(
"2020-05-15T14:30:25+00:00"),
'activity_end': _parse_to_utc_iso8610(
"2020-05-15T16:30:25+00:00"),
'category_id': '1',
'duration': 120.0,
}
def test__calculate_daily_average():
sum_duration = float(320)
time_window = float(3250)
result = _calculate_daily_average(sum_duration, time_window)
assert result == 106
def test__calculate_category_share():
sum_duration = float(320)
time_window = float(3250)
result = _calculate_category_share(sum_duration, time_window)
assert result == 0.09846153846153846
| {"/api_backend_server/tests/unit_tests/test_users.py": ["/api_backend_server/web_app/apis/users.py", "/api_backend_server/web_app/models/__init__.py"], "/api_backend_server/tests/unit_tests/test_statistics.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/apis/statistics.py"], "/api_backend_server/tests/unit_tests/test_activities_api.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/models/__init__.py"]} |
64,820 | measure-your-life-squad/measure-your-life | refs/heads/develop | /api_backend_server/web_app/server.py | import os
import connexion
def server_setup() -> connexion.App:
"""Server factory for a Flask application in connextion App wrapper"""
app = connexion.App(__name__, specification_dir="./")
app.add_api("openapi.yaml")
app.app.config["SECRET_KEY"] = os.getenv("SECRET_KEY")
app.app.config["SECURITY_PASSWORD_SALT"] = os.getenv("SECURITY_PASSWORD_SALT")
app.app.config["MONGODB_SETTINGS"] = {
"db": os.getenv("MONGODBNAME", "mongodev"),
"host": "mongo",
"port": 27017,
"username": os.getenv("APISERVERUSR"),
"password": os.getenv("APISERVERPWD"),
}
return app
app = server_setup()
| {"/api_backend_server/tests/unit_tests/test_users.py": ["/api_backend_server/web_app/apis/users.py", "/api_backend_server/web_app/models/__init__.py"], "/api_backend_server/tests/unit_tests/test_statistics.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/apis/statistics.py"], "/api_backend_server/tests/unit_tests/test_activities_api.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/models/__init__.py"]} |
64,821 | measure-your-life-squad/measure-your-life | refs/heads/develop | /api_backend_server/tests/unit_tests/test_activities_api.py | from api_backend_server.web_app.apis.activities import (
_parse_to_utc_iso8610,
_convert_unix_to_iso8610,
_calculate_duration_in_mins,
_validate_time_overlapping,
)
from api_backend_server.web_app.models import Activities
import datetime
from pytz import timezone
import pytest
from mongoengine import connect
@pytest.fixture(scope='function')
def mongo(request):
db = connect('mongoenginetest', host='mongomock://localhost')
yield db
db.drop_database('mongoenginetest')
db.close()
def test__parse_to_utc_iso8610_should_succeed():
# given
received_timestamp = "2020-05-15T18:30:25,860283993+02:00"
utc = timezone("UTC")
in_utc_time = utc.localize(datetime.datetime(2020, 5, 15, 16, 30, 25, 860283))
# when
result = _parse_to_utc_iso8610(received_timestamp)
# then
assert result == in_utc_time
def test__parse_to_utc_iso8610_should_throw_exception():
# given
invalid_timestamp = "15-05-2015 18:30:25,860283993"
# then
with pytest.raises(Exception):
_parse_to_utc_iso8610(invalid_timestamp)
def test__convert_unix_to_iso8610():
# given
utc = timezone("UTC")
unix_timestamp = utc.localize(datetime.datetime.utcfromtimestamp(1588248502))
# when
result = _convert_unix_to_iso8610(unix_timestamp)
# then
assert result == "2020-04-30T12:08:22+00:00"
def test__calculate_duration_in_mins():
# given
start = datetime.datetime(2020, 5, 15, 16, 30, 25)
end = datetime.datetime(2020, 5, 15, 20, 45, 25)
# when
duration = _calculate_duration_in_mins(start, end)
# then
assert duration == float(255)
simple_activity_data = {'activity_id': "6fdfa589-412c-489f-92fa-b472ee9fae7c",
'name': "activity_sample",
'user_id': "4f175f70-d192-42a4-bd74-6f5b5baf7963",
'activity_start': _parse_to_utc_iso8610(
"2020-05-15T14:30:25+00:00"),
'activity_end': _parse_to_utc_iso8610(
"2020-05-15T16:30:25+00:00"),
'category_id': "1",
'duration': 120.0,
}
def test__validate_time_overlapping_overlap_not_occurs(mongo):
new_activity_start = "2020-05-15T05:30:25+00:00"
new_activity_end = "2020-05-15T07:30:25+00:00"
Activities(activity_id=simple_activity_data['activity_id'],
name=simple_activity_data['name'],
user_id=simple_activity_data['user_id'],
activity_start=simple_activity_data['activity_start'],
activity_end=simple_activity_data['activity_end'],
category=simple_activity_data['category_id'],
duration=simple_activity_data['duration'],
).save()
token_info_for_test = {'public_id': '4f175f70-d192-42a4-bd74-6f5b5baf7963'}
result = _validate_time_overlapping(_parse_to_utc_iso8610(new_activity_start),
_parse_to_utc_iso8610(new_activity_end),
token_info_for_test)
assert result is False
def test__validate_time_overlapping_overlap_occurs(mongo):
new_activity_start = "2020-05-15T15:30:25+00:00"
new_activity_end = "2020-05-15T19:30:25+00:00"
Activities(activity_id=simple_activity_data['activity_id'],
name=simple_activity_data['name'],
user_id=simple_activity_data['user_id'],
activity_start=simple_activity_data['activity_start'],
activity_end=simple_activity_data['activity_end'],
category=simple_activity_data['category_id'],
duration=simple_activity_data['duration'],
).save()
token_info_for_test = {'public_id': '4f175f70-d192-42a4-bd74-6f5b5baf7963'}
result = _validate_time_overlapping(_parse_to_utc_iso8610(new_activity_start),
_parse_to_utc_iso8610(new_activity_end),
token_info_for_test)
assert result is True
def test_delete_specific_activity(mongo):
Activities(activity_id=simple_activity_data['activity_id'],
name=simple_activity_data['name'],
user_id=simple_activity_data['user_id'],
activity_start=simple_activity_data['activity_start'],
activity_end=simple_activity_data['activity_end'],
category=simple_activity_data['category_id'],
duration=simple_activity_data['duration'],
).save()
result = Activities.delete_specific_activity("6fdfa589-412c-489f-92fa-b472ee9fae7c")
assert result is True
| {"/api_backend_server/tests/unit_tests/test_users.py": ["/api_backend_server/web_app/apis/users.py", "/api_backend_server/web_app/models/__init__.py"], "/api_backend_server/tests/unit_tests/test_statistics.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/apis/statistics.py"], "/api_backend_server/tests/unit_tests/test_activities_api.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/models/__init__.py"]} |
64,822 | measure-your-life-squad/measure-your-life | refs/heads/develop | /api_backend_server/web_app/models/__init__.py | from mongoengine import (
Document,
UUIDField,
StringField,
BooleanField,
ReferenceField,
DateTimeField,
IntField,
EmailField,
FloatField,
)
class Users(Document):
public_id = UUIDField(binary=False, required=True, unique=True)
username = StringField(max_length=50, unique=True)
password = StringField(max_length=150)
admin = BooleanField(default=False)
email = EmailField(required=True, unique=True)
email_confirmed = BooleanField(default=False)
@staticmethod # Custom constructor
def get_specific_user(public_id: str) -> Document:
(user,) = Users.objects(public_id=public_id)
return user
@staticmethod # TODO: refactor for an instance method (may be aware of its id)
def delete_user(public_id: str) -> bool:
(user,) = Users.objects(public_id=public_id)
user.delete()
@staticmethod
def validate_if_existing_user(**kwargs):
try:
(user,) = Users.objects(**kwargs)
except ValueError as e:
if (
len(e.args) > 0
and e.args[0] == "not enough values to unpack (expected 1, got 0)"
):
return False
else:
return True
class Categories(Document):
public_id = IntField(required=True, unique=True)
name = StringField(max_length=50)
icon_name = StringField(max_length=50)
@staticmethod # Custom constructor
def get_specific_category(category_id: str) -> Document:
try:
(category,) = Categories.objects(public_id=category_id)
except ValueError as e:
if (
len(e.args) > 0
and e.args[0] == "not enough values to unpack (expected 1, got 0)"
):
raise ValueError(
f"Category with id={category_id} does not exist in the Database"
) from e
else:
raise e
return category
class Activities(Document):
activity_id = UUIDField(binary=False, required=True)
name = StringField(max_length=50)
user_id = UUIDField(binary=False)
activity_start = DateTimeField()
activity_end = DateTimeField()
category = ReferenceField(Categories)
duration = FloatField(min_value=0)
@staticmethod # Custom constructor
def get_specific_activity(activity_id: str) -> Document:
try:
(activity,) = Activities.objects(activity_id=activity_id)
except ValueError as e:
if (
len(e.args) > 0
and e.args[0] == "not enough values to unpack (expected 1, got 0)"
):
raise ValueError(
f"Activity with id={activity_id} does not exist in the Database"
) from e
else:
raise e
return activity
@staticmethod # TODO: refactor for an instance method (to be aware of its id)
def delete_specific_activity(activity_id: str) -> bool:
activity = Activities.get_specific_activity(activity_id=activity_id)
activity.delete()
return True
@staticmethod # TODO: refactor for an instance method (to be aware of its id)
def edit_specific_activity(activity_id: str, **kwargs: dict) -> Document:
activity = Activities.get_specific_activity(activity_id=activity_id)
updated_activity = activity.update(**kwargs)
return updated_activity
| {"/api_backend_server/tests/unit_tests/test_users.py": ["/api_backend_server/web_app/apis/users.py", "/api_backend_server/web_app/models/__init__.py"], "/api_backend_server/tests/unit_tests/test_statistics.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/apis/statistics.py"], "/api_backend_server/tests/unit_tests/test_activities_api.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/models/__init__.py"]} |
64,823 | measure-your-life-squad/measure-your-life | refs/heads/develop | /api_backend_server/tests/integration_tests/test_activities_apis.py | from collections import namedtuple
import pytest
import requests
from requests.auth import HTTPBasicAuth
import integration_utils
def _get_credentials():
Credentials = namedtuple("Credentials", "username password email")
credentials = Credentials(
username="dummyuser",
password="minor security threat",
email="dummyuser@myl.com",
)
return credentials
@pytest.fixture(scope="module")
def activity():
Activity = namedtuple("Activity", "name category_id activity_start activity_end")
activity = Activity(
name="dummy_activity",
category_id="1",
activity_start="2020-04-30 09:34:35.414677+02:00",
activity_end="2020-04-30 11:34:35.414677+02:00"
)
return activity
@pytest.fixture
def valid_jwt_token(scope="module"):
credentials = _get_credentials()
response = requests.post(
"http://localhost:80/api/users/login",
auth=HTTPBasicAuth(credentials.username, credentials.password),
)
response_json = response.json()
return response_json["token"]
def test_create_activity_should_succeed(activity, valid_jwt_token):
"""This test is primarily designed for a run on an ephemeral Continous Integration
agent - it will fail if executed more than once against persistent storage database
due to overlapping activity start/end times."""
auth_token = valid_jwt_token
header = {'Authorization': 'Bearer ' + auth_token}
payload = {
"name": activity.name,
"category_id": activity.category_id,
"activity_start": activity.activity_start,
"activity_end": activity.activity_end
}
response = requests.post(
"http://localhost:80/api/activities",
headers=header,
json=payload,
)
response_json = response.json()
print(response_json)
assert integration_utils.is_valid_uuid(response_json["activity_id"])
| {"/api_backend_server/tests/unit_tests/test_users.py": ["/api_backend_server/web_app/apis/users.py", "/api_backend_server/web_app/models/__init__.py"], "/api_backend_server/tests/unit_tests/test_statistics.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/apis/statistics.py"], "/api_backend_server/tests/unit_tests/test_activities_api.py": ["/api_backend_server/web_app/apis/activities.py", "/api_backend_server/web_app/models/__init__.py"]} |
64,836 | nickhs/vowel | refs/heads/master | /config/staging.py | ../../vowel_private/staging.py | {"/models/share.py": ["/app.py"], "/models/friendship.py": ["/app.py"], "/models/user.py": ["/app.py"], "/bootstrap.py": ["/createdb.py", "/app.py"], "/models/base.py": ["/app.py"], "/models/article.py": ["/app.py"], "/routes/user.py": ["/app.py", "/models/__init__.py"], "/routes/article.py": ["/app.py", "/models/__init__.py"], "/routes/home.py": ["/app.py", "/models/__init__.py", "/bi/parse_article.py"], "/bi/parse_article.py": ["/app.py"]} |
64,837 | nickhs/vowel | refs/heads/master | /models/share.py | import inspect
from app import db
from base import ModelMixin
class Share(ModelMixin, db.Model):
__tablename__ = 'share'
originator_id = db.Column(db.Integer, db.ForeignKey('user.id'))
receiver_id = db.Column(db.Integer, db.ForeignKey('user.id'))
article_id = db.Column(db.Integer, db.ForeignKey('article.id'))
read_date = db.Column(db.DateTime)
parsed = db.Column(db.Boolean, default=False)
def __init__(self, origin, receiver, article):
super(Share, self).__init__()
self.__add_relation(origin, 'originator_id')
self.__add_relation(receiver, 'receiver_id')
self.__add_relation(article, 'article_id')
def __add_relation(self, item, attr):
if not hasattr(self, attr):
raise Exception("Passed in invalid attribute: %s" % attr)
if inspect.isclass(type(item)):
# Assume it's the right class
# FIXME check the class meta?
setattr(self, attr, item.id)
elif type(item) is str:
setattr(self, attr, item)
else:
raise Exception("Unknown type received: %s" % type(item))
| {"/models/share.py": ["/app.py"], "/models/friendship.py": ["/app.py"], "/models/user.py": ["/app.py"], "/bootstrap.py": ["/createdb.py", "/app.py"], "/models/base.py": ["/app.py"], "/models/article.py": ["/app.py"], "/routes/user.py": ["/app.py", "/models/__init__.py"], "/routes/article.py": ["/app.py", "/models/__init__.py"], "/routes/home.py": ["/app.py", "/models/__init__.py", "/bi/parse_article.py"], "/bi/parse_article.py": ["/app.py"]} |
64,838 | nickhs/vowel | refs/heads/master | /models/friendship.py | from app import db
from base import ModelMixin
class Friendship(ModelMixin, db.Model):
__tablename__ = 'friendship'
originator_id = db.Column(db.Integer, db.ForeignKey('user.id'))
receiver_id = db.Column(db.Integer, db.ForeignKey('user.id'))
| {"/models/share.py": ["/app.py"], "/models/friendship.py": ["/app.py"], "/models/user.py": ["/app.py"], "/bootstrap.py": ["/createdb.py", "/app.py"], "/models/base.py": ["/app.py"], "/models/article.py": ["/app.py"], "/routes/user.py": ["/app.py", "/models/__init__.py"], "/routes/article.py": ["/app.py", "/models/__init__.py"], "/routes/home.py": ["/app.py", "/models/__init__.py", "/bi/parse_article.py"], "/bi/parse_article.py": ["/app.py"]} |
64,839 | nickhs/vowel | refs/heads/master | /models/user.py | from app import db
from base import ModelMixin
from passlib.apps import custom_app_context as pwd_context
from datetime import datetime
roles_users = db.Table('roles_users',
db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))
class User(ModelMixin, db.Model):
__tablename__ = 'user'
# FIXME unique?
public_name = db.Column(db.String(80), unique=True)
email = db.Column(db.String(80), unique=True)
password = db.Column(db.String(255))
active = db.Column(db.Boolean(), default=False)
confirmed_at = db.Column(db.DateTime())
last_login_at = db.Column(db.DateTime())
current_login_at = db.Column(db.DateTime())
last_login_ip = db.Column(db.String(80)) # FIXME set to IP type?
current_login_ip = db.Column(db.String(80)) # FIXME set to IP type?
login_count = db.Column(db.Integer(), default=0)
roles = db.relationship('Role', secondary=roles_users,
backref=db.backref('users', lazy='dynamic'))
originating_shares = db.relationship('Share', backref='originator',
lazy='dynamic', foreign_keys='Share.originator_id')
receiving_shares = db.relationship('Share', backref='receiver',
lazy='dynamic', foreign_keys='Share.receiver_id')
def __init__(self, email, password=None, active=False, roles=[]):
super(User, self).__init__()
self.email = email
if password:
self.set_password(password, False)
self.active = active
self.roles += roles
def get_name(self):
return self.email
def set_password(self, password, save=True):
pwd_hash = pwd_context.encrypt(password)
self.password = pwd_hash
if save:
self.save()
def check_password(self, password, request=None):
ok = pwd_context.verify(password, self.password)
if not ok:
return False
if request:
self.last_login_at = self.current_login_at
self.current_login_at = datetime.utcnow()
self.last_login_ip = self.current_login_ip
self.current_login_ip = request.remote_addr
self.login_count += 1
self.save()
return True
def is_active(self):
return self.active
def get_id(self):
return self.id
@classmethod
def get_by_username(cls, username):
return cls.query.filter(cls.email == username).first()
def is_authenticated(self):
return True
def is_anonymous(self):
return False
class Role(ModelMixin, db.Model):
__tablename__ = 'role'
name = db.Column(db.String(80), unique=True)
description = db.Column(db.String(255))
| {"/models/share.py": ["/app.py"], "/models/friendship.py": ["/app.py"], "/models/user.py": ["/app.py"], "/bootstrap.py": ["/createdb.py", "/app.py"], "/models/base.py": ["/app.py"], "/models/article.py": ["/app.py"], "/routes/user.py": ["/app.py", "/models/__init__.py"], "/routes/article.py": ["/app.py", "/models/__init__.py"], "/routes/home.py": ["/app.py", "/models/__init__.py", "/bi/parse_article.py"], "/bi/parse_article.py": ["/app.py"]} |
64,840 | nickhs/vowel | refs/heads/master | /config/base.py | DEBUG = True
SECRET_KEY = 'not_a_secret'
PORT = 8000
SQLALCHEMY_DATABASE_URI = 'sqlite://'
# Flask-Security
SECURITY_REGISTERABLE = True
# Flask-Mail
MAIL_SERVER = 'smtp.mandrillapp.com'
MAIL_PORT = 587
MAIL_USE_TLS = True
MAIL_USE_SSL = False
MAIL_USERNAME = 'fixme@fixme.com'
MAIL_PASSWORD = 'fixme'
# Flask Debug Toolbar
DEBUG_TB_INTERCEPT_REDIRECTS = False
# Article Parsing
ARTICLE_PARSE_ENDPOINT = "http://api.diffbot.com/v2/article"
| {"/models/share.py": ["/app.py"], "/models/friendship.py": ["/app.py"], "/models/user.py": ["/app.py"], "/bootstrap.py": ["/createdb.py", "/app.py"], "/models/base.py": ["/app.py"], "/models/article.py": ["/app.py"], "/routes/user.py": ["/app.py", "/models/__init__.py"], "/routes/article.py": ["/app.py", "/models/__init__.py"], "/routes/home.py": ["/app.py", "/models/__init__.py", "/bi/parse_article.py"], "/bi/parse_article.py": ["/app.py"]} |
64,841 | nickhs/vowel | refs/heads/master | /bootstrap.py | from createdb import run as init_db
from app import user_datastore, db
def run():
init_db()
user_datastore.create_user(email='test@vowel.io', password='test')
db.session.commit()
if __name__ == '__main__':
run()
| {"/models/share.py": ["/app.py"], "/models/friendship.py": ["/app.py"], "/models/user.py": ["/app.py"], "/bootstrap.py": ["/createdb.py", "/app.py"], "/models/base.py": ["/app.py"], "/models/article.py": ["/app.py"], "/routes/user.py": ["/app.py", "/models/__init__.py"], "/routes/article.py": ["/app.py", "/models/__init__.py"], "/routes/home.py": ["/app.py", "/models/__init__.py", "/bi/parse_article.py"], "/bi/parse_article.py": ["/app.py"]} |
64,842 | nickhs/vowel | refs/heads/master | /models/base.py | from datetime import datetime
from app import db
class ModelMixin(object):
id = db.Column(db.Integer, primary_key=True)
created_date = db.Column(db.DateTime)
modified_date = db.Column(db.DateTime)
deleted = db.Column(db.Boolean, default=False)
def __init__(self, **kwargs):
self.created_date = datetime.utcnow()
self.modified_date = datetime.utcnow()
columns = self.__table__.columns
for key, value in kwargs.iteritems():
if key in columns:
setattr(self, key, value)
else:
raise Exception("Got key: %s without matching table attribute" % key)
def _change_made(self):
self.modified_date = datetime.utcnow()
def remove(self):
self._change_made()
self.deleted = True
self.save()
def delete(self):
self._change_made()
db.session.delete(self)
db.session.commit()
def save(self):
self._change_made()
db.session.add(self)
db.session.commit()
def __repr__(self):
return "<%s: %s>" % (self.__class__.__name__, self.id)
def to_dict(self, included=set(), excluded=set()):
exclude = set(['modified_date', 'deleted'])
exclude.update(excluded)
exclude.difference_update(included)
if 'deleted' in excluded and self.deleted:
return
ret = {}
for column in self.__table__.columns:
if column.name in exclude:
continue
ret[column.name] = getattr(self, column.name)
return ret
| {"/models/share.py": ["/app.py"], "/models/friendship.py": ["/app.py"], "/models/user.py": ["/app.py"], "/bootstrap.py": ["/createdb.py", "/app.py"], "/models/base.py": ["/app.py"], "/models/article.py": ["/app.py"], "/routes/user.py": ["/app.py", "/models/__init__.py"], "/routes/article.py": ["/app.py", "/models/__init__.py"], "/routes/home.py": ["/app.py", "/models/__init__.py", "/bi/parse_article.py"], "/bi/parse_article.py": ["/app.py"]} |
64,843 | nickhs/vowel | refs/heads/master | /fabfile.py | from fabric.api import run, cd, env
env.hosts = ["nickhs.com"]
env.use_ssh_config = True
env.reject_unknown_hosts = False
def deploy():
with cd("/srv/vowel_private"):
run("git pull")
with cd("/srv/vowel"):
run("git pull")
def full_deploy():
deploy()
with cd("/srv/vowel"):
run("pip install -r requirements.txt")
run("supervisorctl restart vowel")
| {"/models/share.py": ["/app.py"], "/models/friendship.py": ["/app.py"], "/models/user.py": ["/app.py"], "/bootstrap.py": ["/createdb.py", "/app.py"], "/models/base.py": ["/app.py"], "/models/article.py": ["/app.py"], "/routes/user.py": ["/app.py", "/models/__init__.py"], "/routes/article.py": ["/app.py", "/models/__init__.py"], "/routes/home.py": ["/app.py", "/models/__init__.py", "/bi/parse_article.py"], "/bi/parse_article.py": ["/app.py"]} |
64,844 | nickhs/vowel | refs/heads/master | /models/article.py | from datetime import datetime
from urlparse import urlparse
from app import db
from base import ModelMixin
class Article(ModelMixin, db.Model):
__tablename__ = 'article'
url = db.Column(db.String(255))
icon = db.Column(db.String(255))
title = db.Column(db.String(255))
text = db.Column(db.Text)
date = db.Column(db.DateTime)
author = db.Column(db.String(255))
parse_date = db.Column(db.DateTime)
shares = db.relationship('Share', backref='article',
lazy='dynamic')
def __init__(self, url):
super(Article, self).__init__()
self.url = url
def is_parsed(self):
if self.parse_date is None:
return False
if self.parse_date > datetime.utcnow():
return True
return False
def get_domain(self):
return urlparse(self.url).netloc
| {"/models/share.py": ["/app.py"], "/models/friendship.py": ["/app.py"], "/models/user.py": ["/app.py"], "/bootstrap.py": ["/createdb.py", "/app.py"], "/models/base.py": ["/app.py"], "/models/article.py": ["/app.py"], "/routes/user.py": ["/app.py", "/models/__init__.py"], "/routes/article.py": ["/app.py", "/models/__init__.py"], "/routes/home.py": ["/app.py", "/models/__init__.py", "/bi/parse_article.py"], "/bi/parse_article.py": ["/app.py"]} |
64,845 | nickhs/vowel | refs/heads/master | /createdb.py | from app import db
from models import *
def run():
print "WARNING: This is a destructive action"
db.drop_all()
db.create_all()
if __name__ == '__main__':
run()
| {"/models/share.py": ["/app.py"], "/models/friendship.py": ["/app.py"], "/models/user.py": ["/app.py"], "/bootstrap.py": ["/createdb.py", "/app.py"], "/models/base.py": ["/app.py"], "/models/article.py": ["/app.py"], "/routes/user.py": ["/app.py", "/models/__init__.py"], "/routes/article.py": ["/app.py", "/models/__init__.py"], "/routes/home.py": ["/app.py", "/models/__init__.py", "/bi/parse_article.py"], "/bi/parse_article.py": ["/app.py"]} |
64,846 | nickhs/vowel | refs/heads/master | /routes/__init__.py | from site import about, send_text_file
from home import home
from user import login, logout, register
from article import article
__all__ = [
'home',
'about',
'send_text_file',
'login',
'logout',
'register',
'article',
]
| {"/models/share.py": ["/app.py"], "/models/friendship.py": ["/app.py"], "/models/user.py": ["/app.py"], "/bootstrap.py": ["/createdb.py", "/app.py"], "/models/base.py": ["/app.py"], "/models/article.py": ["/app.py"], "/routes/user.py": ["/app.py", "/models/__init__.py"], "/routes/article.py": ["/app.py", "/models/__init__.py"], "/routes/home.py": ["/app.py", "/models/__init__.py", "/bi/parse_article.py"], "/bi/parse_article.py": ["/app.py"]} |
64,847 | nickhs/vowel | refs/heads/master | /routes/user.py | from flask.ext.login import logout_user, login_required, login_user
from flask import redirect, url_for, flash, render_template, request
from flask.ext.wtf import Form
from wtforms import TextField, PasswordField
from wtforms.validators import DataRequired
from app import app
from models import User
class LoginForm(Form):
username = TextField('username', validators=[DataRequired()])
password = PasswordField('password', validators=[DataRequired()])
class RegisterForm(Form):
email = TextField('email', validators=[DataRequired()])
password = PasswordField('password', validators=[DataRequired()])
@app.route("/logout")
# FIXME do login check manually?
@login_required
def logout():
logout_user()
return redirect(url_for('home'))
@app.route("/login", methods=["GET", "POST"])
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.get_by_username(form.username.data)
if not user:
flash('That didn\'t work :(. Never seen you before.')
return render_template('login.html', form=form)
if user.check_password(form.password.data, request) == False:
flash('That didn\'t work :(. Check yo self.')
return render_template('login.html', form=form)
login_user(user)
flash("Logged in successfully.")
return redirect(request.args.get("next") or url_for("home"))
return render_template("login.html", form=form)
@app.route('/register', methods=['GET', 'POST'])
def register():
form = RegisterForm()
if form.validate_on_submit():
user = User(form.email.data, form.password.data, True)
user.save()
flash('Signed up!')
return redirect(url_for('home'))
return render_template('register.html', form=form)
| {"/models/share.py": ["/app.py"], "/models/friendship.py": ["/app.py"], "/models/user.py": ["/app.py"], "/bootstrap.py": ["/createdb.py", "/app.py"], "/models/base.py": ["/app.py"], "/models/article.py": ["/app.py"], "/routes/user.py": ["/app.py", "/models/__init__.py"], "/routes/article.py": ["/app.py", "/models/__init__.py"], "/routes/home.py": ["/app.py", "/models/__init__.py", "/bi/parse_article.py"], "/bi/parse_article.py": ["/app.py"]} |
64,848 | nickhs/vowel | refs/heads/master | /routes/article.py | from flask import abort
from app import app
from models import Article
@app.route('/article/<int:article_id>', methods=['GET'])
def article(article_id):
article = Article.query.get(article_id)
if not article:
return abort(404)
return abort(200)
| {"/models/share.py": ["/app.py"], "/models/friendship.py": ["/app.py"], "/models/user.py": ["/app.py"], "/bootstrap.py": ["/createdb.py", "/app.py"], "/models/base.py": ["/app.py"], "/models/article.py": ["/app.py"], "/routes/user.py": ["/app.py", "/models/__init__.py"], "/routes/article.py": ["/app.py", "/models/__init__.py"], "/routes/home.py": ["/app.py", "/models/__init__.py", "/bi/parse_article.py"], "/bi/parse_article.py": ["/app.py"]} |
64,849 | nickhs/vowel | refs/heads/master | /models/__init__.py | from user import User, Role
from friendship import Friendship
from article import Article
from share import Share
__all__ = [
'User',
'Friendship',
'Article',
'Share',
'Role'
]
| {"/models/share.py": ["/app.py"], "/models/friendship.py": ["/app.py"], "/models/user.py": ["/app.py"], "/bootstrap.py": ["/createdb.py", "/app.py"], "/models/base.py": ["/app.py"], "/models/article.py": ["/app.py"], "/routes/user.py": ["/app.py", "/models/__init__.py"], "/routes/article.py": ["/app.py", "/models/__init__.py"], "/routes/home.py": ["/app.py", "/models/__init__.py", "/bi/parse_article.py"], "/bi/parse_article.py": ["/app.py"]} |
64,850 | nickhs/vowel | refs/heads/master | /routes/home.py | from flask.ext.login import current_user
from flask import render_template, flash, request, jsonify
from flask.ext.wtf import Form
from wtforms import TextField
from wtforms.validators import DataRequired
from app import app
from models import Article, User, Share
from bi.parse_article import parse_article
from bi.utils import request_wants_json
class SendLinkForm(Form):
url = TextField('url', validators=[DataRequired()])
friend = TextField('friend', validators=[DataRequired()])
@app.route('/', methods=['POST', 'GET'])
def home():
if request_wants_json(request):
return _home_json()
else:
return _home_html()
def _home_json():
if not current_user.is_authenticated():
return jsonify({'success': False, 'reason': 'Not Authenticted'})
form = SendLinkForm()
if form.validate_on_submit():
msg = _create_share(form)
return jsonify({
'success': True,
'message': msg
})
# FIXME specify why validation failed
return jsonify({
'success': True,
'shares': _get_received()
})
def _home_html():
"""Render website's home page."""
if not current_user.is_authenticated():
return render_template('splash.html')
form = SendLinkForm()
if form.validate_on_submit():
msg = _create_share(form)
flash(msg, 'success')
return render_template('home.html', user=current_user, form=form, shares=_get_received())
def _create_share(form):
article = Article.query.filter_by(url=form.url.data).first()
if not article:
article = Article(form.url.data)
article.save()
user = User.query.filter_by(email=form.friend.data).first()
if not user:
user = User(form.friend.data)
user.save()
share = Share(current_user, user, article)
share.save()
parse_article(article, share)
return "Successfully shared to %s" % user.get_name()
def _get_received(limit=10):
received = current_user.receiving_shares.filter(Share.parsed == True) \
.filter(Share.read_date == None) \
.order_by(Share.created_date.desc()) \
.limit(limit).all()
return received
| {"/models/share.py": ["/app.py"], "/models/friendship.py": ["/app.py"], "/models/user.py": ["/app.py"], "/bootstrap.py": ["/createdb.py", "/app.py"], "/models/base.py": ["/app.py"], "/models/article.py": ["/app.py"], "/routes/user.py": ["/app.py", "/models/__init__.py"], "/routes/article.py": ["/app.py", "/models/__init__.py"], "/routes/home.py": ["/app.py", "/models/__init__.py", "/bi/parse_article.py"], "/bi/parse_article.py": ["/app.py"]} |
64,851 | nickhs/vowel | refs/heads/master | /app.py | """
Flask Documentation: http://flask.pocoo.org/docs/
Jinja2 Documentation: http://jinja.pocoo.org/2/documentation/
Werkzeug Documentation: http://werkzeug.pocoo.org/documentation/
"""
import os
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.mail import Mail
from flask.ext.debugtoolbar import DebugToolbarExtension
from flask.ext.login import LoginManager
from raven.contrib.flask import Sentry
app = Flask(__name__)
app.config.from_object('config.base')
deploy_type = os.environ.get('VOWEL_DEPLOY', 'development')
if deploy_type in ['dev', 'development']:
app.config.from_object('config.development')
if deploy_type in ['stag', 'staging']:
app.config.from_object('config.staging')
elif deploy_type in ['prod', 'production']:
app.config.from_object('config.production')
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', 'this_should_be_configured')
app.config['PORT'] = int(os.environ.get('PORT', 8000))
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL')
app.config['DEBUG'] = bool(os.environ.get('DEBUG', False))
if app.config['SQLALCHEMY_DATABASE_URI']:
db = SQLAlchemy(app)
if app.config.get('SENTRY_DSN', None):
sentry = Sentry(app)
config = app.config
mail = Mail(app)
toolbar = DebugToolbarExtension(app)
_pyflakes = toolbar
login_manager = LoginManager(app)
| {"/models/share.py": ["/app.py"], "/models/friendship.py": ["/app.py"], "/models/user.py": ["/app.py"], "/bootstrap.py": ["/createdb.py", "/app.py"], "/models/base.py": ["/app.py"], "/models/article.py": ["/app.py"], "/routes/user.py": ["/app.py", "/models/__init__.py"], "/routes/article.py": ["/app.py", "/models/__init__.py"], "/routes/home.py": ["/app.py", "/models/__init__.py", "/bi/parse_article.py"], "/bi/parse_article.py": ["/app.py"]} |
64,852 | nickhs/vowel | refs/heads/master | /bi/parse_article.py | from datetime import datetime
from app import config, app
import requests
def parse_article(article, share):
if article.is_parsed():
return notify_new_article(article, share)
endpoint = config['ARTICLE_PARSE_ENDPOINT']
payload = {
'token': config.get('DIFFBOT_TOKEN', None),
'url': article.url
}
resp = requests.get(endpoint, params=payload)
if not resp.ok:
app.logger.error('Failed to parse %s (error code: %s). Reason: %s'
% (article, resp.status_code, resp.json() if resp.json() else 'unknown'))
return
json = resp.json()
if 'resolved_url' in json:
article.url = json['resolved_url']
elif 'url' in json:
article.url = json['url']
else:
app.logger.warning("Parse article did not return any url for %s (%s)" % (article, json))
article.icon = json.get('icon')
article.title = (json['title'][:252] + '...') if len(json['title']) > 255 else json['title']
article.text = json['text']
article.date = json['date']
article.author = json.get('author', '')
article.parse_date = datetime.utcnow()
share.parsed = True
article.save()
share.save()
notify_new_article(article, share)
def notify_new_article(article, share):
# FIXME todo sent notification mails
app.logger.debug("Sending mail to %s from %s about %s" % (share.receiver, share.originator, article.title))
| {"/models/share.py": ["/app.py"], "/models/friendship.py": ["/app.py"], "/models/user.py": ["/app.py"], "/bootstrap.py": ["/createdb.py", "/app.py"], "/models/base.py": ["/app.py"], "/models/article.py": ["/app.py"], "/routes/user.py": ["/app.py", "/models/__init__.py"], "/routes/article.py": ["/app.py", "/models/__init__.py"], "/routes/home.py": ["/app.py", "/models/__init__.py", "/bi/parse_article.py"], "/bi/parse_article.py": ["/app.py"]} |
64,879 | wagolemusa/FlaskAPis | refs/heads/master | /fibonacciNumbers.py | class fibNumbers:
def fibonaccil(self, number):
num = [1,2]
for i in range (2, number):
num.append(num[i-2]+num[i-1])
return num
def sum_even_fibonaccil(self, number=1000):
sum = 0
for i in self.fibonaccil(number):
if i % 2 == 0 and i < 4000000:
sum = sum+i
return sum
test = fibNumbers()
print (test.sum_even_fibonaccil())
# class fibonacciNumbers:
# def fibonacci(self, number):
# output = [1,2]
# for each in range(2,number):
# output.append(output[each-2]+output[each-1])
# return output
# def sum_of_even_fibonacci(self, number=1000):
# sum = 0
# for each in self.fibonacci(number):
# if each%2 == 0 and each<4000000:
# sum = sum+each
# return sum
# if __name__ == '__main__':
# test = fibonacciNumbers()
# print (test.sum_of_even_fibonacci()) | {"/fibotest.py": ["/fibonacciNumbers.py"]} |
64,880 | wagolemusa/FlaskAPis | refs/heads/master | /test.py | from app import app
import unittest
class FlaskTestCase(unittest.TestCase):
#Ensure that flask was sett up correctly
def test_index(self):
tester = app.test_client(self)
response = tester.get('/login', content_type='html/text')
self.assertEqual(response.status_code, 200)
# Ensure that login page loads correctly
def test_login_page_loads(self):
tester = app.test_client(self)
response = tester.get('/login', content_type='html/text')
self.assertFalse(b'Please try again.' in response.data)
# Ensure that login correctly
def test_correct_login(self):
tester = app.test_client(self)
response = tester.post(
'/login',
data=dict(username="admin", password="admin"),
follow_redirects=True
)
self.assertIn(b'You are just login', response.data)
# Test Wrong credentails
def test_incorrect_login(self):
tester = app.test_client(self)
response = tester.post(
'/login',
data=dict(username="wrong", password="wrong"),
follow_redirects=True
)
self.assertIn(b'Invalid credentials. Please try again', response.data)
# test loggout
def test_logout(self):
tester = app.test_client(self)
response = tester.post(
'/login',
data=dict(username="admin", password="admin"),
follow_redirects=True
)
self.assertIn(b'You were just Logged out', response.data)
#Ensure that main page requires login
def test_main_route_requires_login(self):
tester = app.test_client(self)
response = tester.get('/', follow_redirects=True)
self.assertTrue(b'You need to first Login', response.data)
def test_post_show_up(self):
tester = app.test_client(self)
response = tester.post(
'/login',
data=dict(username="admin", password="admin"),
follow_redirects=True
)
self.assertIn(b'Im well', response.data)
if __name__ =='__main__':
unittest.main() | {"/fibotest.py": ["/fibonacciNumbers.py"]} |
64,881 | wagolemusa/FlaskAPis | refs/heads/master | /config.py | import os
# defualt config
class BaseConfig(object):
DEBUG = False
SECRET_KEY = 'Y\x87\xc3\x87\x0c\x8c\x96rwo\x1e*\xeb\xd8/\xac\x1avw(\xbf\xe8@\xdf'
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
class DevelopmentConfig(BaseConfig):
DEBUG = True
class ProductionConfig(BaseConfig):
DEBUG = False | {"/fibotest.py": ["/fibonacciNumbers.py"]} |
64,882 | wagolemusa/FlaskAPis | refs/heads/master | /db_create.py | from app import db
from models import BlogPost
# create the database and the db tables
db.create_all()
#insert
db.session.add(BlogPost("Good", "Im good."))
db.session.add(BlogPost("Well", "Im well"))
db.session.add(BlogPost("Pin install", "Otherwise, you will not be able topackages from PyPI."))
# commit the changes
db.session.commit() | {"/fibotest.py": ["/fibonacciNumbers.py"]} |
64,883 | wagolemusa/FlaskAPis | refs/heads/master | /fibotest.py | import unittest
# from fibonacci import fibonacciNumbers
from fibonacciNumbers import *
class testFibonacciNumbers(unittest.TestCase):
def test_fibonacci(self):
self.assertEqual(fibonacciNumbers().fibonacci(10),
[1, 2, 3, 5, 8, 13, 21, 34, 55, 89])
self.assertEqual(len(fibonacciNumbers().fibonacci(10)),
10)
self.assertEqual(fibonacciNumbers().fibonacci(10)[8],
55)
def test_sum_of_even_fibonacci(self):
self.assertEqual(fibonacciNumbers().sum_of_even_fibonacci(10),44)
self.assertEqual(fibonacciNumbers().sum_of_even_fibonacci(),4613732)
if __name__ == '__main__':
unittest.main() | {"/fibotest.py": ["/fibonacciNumbers.py"]} |
64,884 | Khyst/aws_manage | refs/heads/master | /procedure/migrations/0006_auto_20200130_1702.py | # Generated by Django 2.2.1 on 2020-01-30 08:02
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('procedure', '0005_auto_20200130_1634'),
]
operations = [
migrations.AddField(
model_name='user',
name='user_image',
field=models.ImageField(default='', upload_to=''),
),
migrations.AlterField(
model_name='refpost',
name='obj',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='procedure.Subject'),
),
]
| {"/procedure/admin.py": ["/procedure/models.py"], "/procedure/views.py": ["/procedure/models.py"]} |
64,885 | Khyst/aws_manage | refs/heads/master | /procedure/migrations/0005_auto_20200130_1634.py | # Generated by Django 2.2.1 on 2020-01-30 07:34
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('procedure', '0004_auto_20200130_1616'),
]
operations = [
migrations.AddField(
model_name='subject',
name='category',
field=models.IntegerField(default=0),
),
migrations.AlterField(
model_name='refpost',
name='obj',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='procedure.Subject'),
),
]
| {"/procedure/admin.py": ["/procedure/models.py"], "/procedure/views.py": ["/procedure/models.py"]} |
64,886 | Khyst/aws_manage | refs/heads/master | /procedure/migrations/0003_auto_20200130_1514.py | # Generated by Django 2.2.1 on 2020-01-30 06:14
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('procedure', '0002_auto_20200130_1508'),
]
operations = [
migrations.RenameField(
model_name='refpost',
old_name='Comment',
new_name='comment',
),
migrations.RenameField(
model_name='refpost',
old_name='Reference',
new_name='reference',
),
migrations.RenameField(
model_name='subject',
old_name='Time',
new_name='time',
),
migrations.AlterField(
model_name='refpost',
name='obj',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='procedure.Subject'),
),
]
| {"/procedure/admin.py": ["/procedure/models.py"], "/procedure/views.py": ["/procedure/models.py"]} |
64,887 | Khyst/aws_manage | refs/heads/master | /procedure/admin.py | from django.contrib import admin
from .models import Subject, refPost, timeAmount, schedule
# Register your models here.
#admin.site.register(User)
admin.site.register(Subject)
admin.site.register(refPost)
admin.site.register(timeAmount)
admin.site.register(schedule) | {"/procedure/admin.py": ["/procedure/models.py"], "/procedure/views.py": ["/procedure/models.py"]} |
64,888 | Khyst/aws_manage | refs/heads/master | /procedure/views.py | from django.shortcuts import render
from django.core.paginator import Paginator
from .models import Subject, refPost
# Create your views here.
def schedule(request):
return render(request, 'schedule.html')
def create(request):
return render(request, 'create.html')
def list(request):
return render(request, 'list.html')
def procedure(request):
"""Whole QuerySet of models (User, Subject, refPost)"""
#user = User.objects.all()
subject = Subject.objects.all()
ref = refPost.objects.all()
"""particular QuerySet of models (User, Subject, refPost)"""
"""====================================================================================================================================================="""
# ---------------------------------------------------------------------------------------------------------------------------------------------------------
# *all() : Returns a copy of the current QuerySet (or QuerySet subclass).
# This can be useful in situations where you might want to pass in either a model manager or a QuerySet and do further filtering on the result.
# ---------------------------------------------------------------------------------------------------------------------------------------------------------
# *get() : there is only one object that matches your query, you can use the get() method on a Manager which returns the object directly:
# -> If there are no results that match the query, get() will raise a DoesNotExist exception.
# ---------------------------------------------------------------------------------------------------------------------------------------------------------
# *filter() : always give you a QuerySet, even if only a single object matches the query - in this case, it will be a QuerySet containing a single element.
# -> single element with filter() : using filter() with a slice of [0]
# ---------------------------------------------------------------------------------------------------------------------------------------------------------
"""
user_1 = User.objects.get(user_name="khyst")
subject_1 = Subject.objects.get(title="Python Learnig")
ref_1 = refPost.objects.filter()
"""
# *** Exception of Method: get() *** ( from django.core.exceptions )
# ---------------------------------------------------------------------------------------------------------------------------------------------------------
# get() raises MultipleObjectsReturned
# if more than one object was found. The MultipleObjectsReturned exception is an attribute of the model class.
# ---------------------------------------------------------------------------------------------------------------------------------------------------------
# get() raises a DoesNotExist exception
# if an object wasn’t found for the given parameters. This exception is an attribute of the model class
# ---------------------------------------------------------------------------------------------------------------------------------------------------------
"""
user_1 = User.objects.filter()
subject_1 = Subject.objects.filter()
ref_1 = refPost.objects.filter()
"""
"""====================================================================================================================================================="""
#user_1 = User.objects.get(user_name="khyst")
#subject_1 = Subject.objects.get(title="Python Learnig")
#ref_1 = refPost.objects.filter()
# Backward Accessing
"""
querysetOfUsertoSubject = user_1.subject_set(title="Python Learning")
querysetOfUsbjectorefPost = subject_1.refpost_set()
"""
# Foreward Accessing
# querysetOfSubjecttoUser = subject_1.user.user_name
# querysetOfrefPosttoSubject = ref_1.subject.title
paginator = Paginator(subject,5)
#request된 페이지가 뭔지를 알아내고 ( request페이지를 변수에 담아냄 )
page = request.GET.get('page')
#request된 페이지를 얻어온 뒤 return 해 준다
subject_post = paginator.get_page(page)
return render(request, 'plan.html', { 'subject':subject, 'ref':ref, 'subject_post':subject_post }) # Dictionery 형태로 QuereySet을 전달
"""
- ICON class name -
*Developing : ni ni-atom
*License : ni ni-badge
*Blog : fa fa-home
*Language :
*Brain :
*Psychology :
*Workout :
*Activity :
"""
def swtich_icon(request):
pass
| {"/procedure/admin.py": ["/procedure/models.py"], "/procedure/views.py": ["/procedure/models.py"]} |
64,889 | Khyst/aws_manage | refs/heads/master | /procedure/migrations/0001_initial.py | # Generated by Django 2.2.1 on 2020-01-30 06:05
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('user_name', models.CharField(max_length=100)),
('email', models.CharField(max_length=100)),
],
),
migrations.CreateModel(
name='subject',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=100)),
('procedure', models.IntegerField()),
('this_week_proceed', models.IntegerField()),
('last_study', models.DateTimeField()),
('Time', models.IntegerField()),
('author', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='procedure.User')),
],
),
migrations.CreateModel(
name='refPost',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Reference', models.TextField()),
('Comment', models.TextField()),
('intro_image', models.ImageField(upload_to='')),
('obj', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='procedure.subject')),
],
),
]
| {"/procedure/admin.py": ["/procedure/models.py"], "/procedure/views.py": ["/procedure/models.py"]} |
64,890 | Khyst/aws_manage | refs/heads/master | /procedure/migrations/0009_auto_20200202_0031.py | # Generated by Django 2.2.1 on 2020-02-01 15:31
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('procedure', '0008_auto_20200131_2027'),
]
operations = [
migrations.CreateModel(
name='schedule',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=200)),
('contents', models.TextField()),
('start_date', models.DateField()),
('end_date', models.DateField()),
('category', models.IntegerField()),
('is_repeat_event', models.BooleanField()),
],
),
migrations.AlterField(
model_name='refpost',
name='obj',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='procedure.Subject'),
),
]
| {"/procedure/admin.py": ["/procedure/models.py"], "/procedure/views.py": ["/procedure/models.py"]} |
64,891 | Khyst/aws_manage | refs/heads/master | /procedure/models.py | from django.db import models
class Subject(models.Model):
#author = models.OneToOneField(User, on_delete=models.CASCADE)
#author은 User과 subject를 1:N 구조로 이어주는 Key
title = models.CharField(max_length=100)
procedure = models.IntegerField()
this_week_proceed = models.IntegerField()
last_study = models.DateTimeField()
time = models.IntegerField()
category = models.IntegerField(default=0)
def __str__(self):
return self.title
class refPost(models.Model):
obj = models.ForeignKey(Subject, on_delete=models.CASCADE)
#obj는 Subject과 refPost를 1:다 구조로 이어주는 Key
o_id = models.IntegerField(default=0)
reference = models.TextField()
comment = models.TextField()
intro_image = models.ImageField()
def __str__(self):
return self.title
class timeAmount(models.Model):
totalWeeklyAmount = models.IntegerField()
totalMonthlyAmount = models.IntegerField()
def __str__(self):
return self.title
class schedule(models.Model):
title = models.CharField(max_length=200)
contents = models.TextField()
# period_date is (start_date ~ end_date)
start_date = models.DateField()
end_date = models.DateField()
category = models.IntegerField()
is_repeat_event = models.BooleanField()
def __str__(self):
return self.title
| {"/procedure/admin.py": ["/procedure/models.py"], "/procedure/views.py": ["/procedure/models.py"]} |
64,916 | DDVD233/PhysicsModeling | refs/heads/master | /variables.py | import numpy as np
import math
import scipy.constants as const
g = const.g # gravitational constant
x_length = 0.21 # Length of x
y_length = 1.117 # Length of y
length_ratio = y_length/x_length # y/x
rod_length = x_length + y_length # total length of rod
counterweight = 11.79 # Mass of the counterweight
fruit_weight = 0.02 # Mass of the fruit (kg)
initial_angle = -40 # Horizontal level arm Initial angle (degree)
launch_angle = 70 # Launch Angle (degree)
launch_angle_radian = launch_angle * math.pi / 180
rod_weight = 0.168 # mass of the rod
# When the coefficient is very large, it could cause stack overflow
dt = 1e-4 # integration time step (delta t)
'''
v0 = 35 # Average speed at t=0
v0min = 30 # Minimum Speed
v0max = 40 # Maximum Speed
'''
time = np.arange(0, 2000, dt) # create time axis
c = 0.47 # Drag Coefficient
p = 1.225 # Density of the air (kg/m^3)
A = 0.0113 # Surface Area (m^2)
inity = 1.597 # Initial height (m)
windx = 0 # Wind velocity in the x direction(vector) (m/s)
wind_y = 0 # Wind velocity in the y direction(vector) (m/s)
| {"/Projectile.py": ["/variables.py", "/Launching.py"]} |
64,917 | DDVD233/PhysicsModeling | refs/heads/master | /Launching.py | import math
def rod_mass_calculation(rod_weight, ratio):
x = rod_weight / (1 + ratio)
y = rod_weight * ratio / (1 + ratio)
return x, y
def total_mass_calculation(rod_weight, counterweight, fruit_weight):
total_mass = (rod_weight + counterweight + fruit_weight)
return total_mass
def lever_system_changing_height_calculation(total_mass, mass_x, mass_y, initial_angle,
launch_angle, counterweight, fruit_weight, x_length, y_length):
changing_angle = math.sin(-initial_angle * math.pi / 180) + math.sin(launch_angle * math.pi / 180)
# See paper for detail
# Because in this equation we are assuming the initial angle is positive, while in the variable it's negative,
# we added a minus sign before it.
mx_sum = counterweight * x_length + x_length / 2 * mass_x - fruit_weight * y_length - y_length / 2 * mass_y
changing_height = changing_angle * mx_sum / total_mass
return changing_height
def gravitational_potential_energy_calculation(total_mass, changing_height, g):
gravitational_potential_energy = total_mass * changing_height * g
return gravitational_potential_energy
def lever_system_monment_of_inertia_calculation(rod_weight, rod_length, counterweight, x_length, fruit_weight,
y_length):
moment_of_inertia = (1 / 3) * rod_weight * (rod_length ** 2) + counterweight * (x_length ** 2) + fruit_weight * (
y_length ** 2)
return moment_of_inertia
def final_angular_velocity_calculation(gravitational_potential_energy, moment_of_inertia):
final_angular_velocity = math.sqrt((2 * gravitational_potential_energy) / moment_of_inertia)
return final_angular_velocity
def final_velocity_calculation(rod_weight, length_ratio, counterweight, fruit_weight
, x_length, y_length, initial_angle, launch_angle_radian, g, rod_length):
mass_x, mass_y = rod_mass_calculation(rod_weight, length_ratio) # mass of x and y
total_mass = total_mass_calculation(rod_weight, counterweight, fruit_weight)
changing_height = lever_system_changing_height_calculation(total_mass, mass_x, mass_y, initial_angle,
launch_angle_radian
, counterweight, fruit_weight, x_length, y_length)
gravitational_potential_energy = gravitational_potential_energy_calculation(total_mass, changing_height, g)
moment_of_inertia = lever_system_monment_of_inertia_calculation(rod_weight, rod_length, counterweight,
x_length, fruit_weight, y_length)
final_angular_velocity = final_angular_velocity_calculation(gravitational_potential_energy, moment_of_inertia)
final_velocity = final_angular_velocity * y_length
print('Final Velocity:', final_velocity)
return final_velocity
| {"/Projectile.py": ["/variables.py", "/Launching.py"]} |
64,918 | DDVD233/PhysicsModeling | refs/heads/master | /Projectile.py | from variables import *
import matplotlib.pyplot as plt
from Launching import final_velocity_calculation
def coef_calculation(c, p, A, mass):
coef = 0.5 * c * p * A / mass
return coef
coef = coef_calculation(c, p, A, fruit_weight)
def traj_fr(coef, angle, v0, inity): # function that computes trajectory for some launch angle & velocity
vx0 = math.cos(math.pi / 2 - angle) * v0 # compute x components of starting velocity
vy0 = math.sin(math.pi / 2 - angle) * v0 # compute y components of starting velocity
x = np.zeros(len(time)) # initialize x array
y = np.zeros(len(time)) # initialize y array
vx = np.zeros(len(time)) # initialize vx array
vy = np.zeros(len(time)) # initialize vy array
ax = np.zeros(len(time)) # initialize ax array
ay = np.zeros(len(time)) # initialize ay array
x[0], y[0] = 0, inity # initial position at t=0s, ie motion starts at (0,0)
vx[0] = vx0
vy[0] = vy0
if windx > vx[0]:
ax[0] = coef * ((vx[0] - windx) ** 2)
else:
ax[0] = -coef * ((vx[0] - windx) ** 2)
if wind_y > vy[0]:
ay[0] = coef * ((wind_y - vy[0]) ** 2) - g
else:
ay[0] = -coef * ((wind_y - vy[0]) ** 2) - g
# When the wind velocity is greater than the initial velocity, the "air resistance" actually accelerates the fruit
i = 0
while y[i] >= 0: # loop continuous until y becomes <0, ie projectile hits ground
if vy[i] > wind_y:
ay[i + 1] = -coef * ((wind_y - vy[i]) ** 2) - g
else:
ay[i + 1] = coef * ((wind_y - vy[i]) ** 2) - g
if windx > vx[i]:
ax[i + 1] = coef * ((vx[i] - windx) ** 2)
else:
ax[i + 1] = -coef * ((vx[i] - windx) ** 2)
vx[i + 1] = vx[i] + (ax[i + 1] + ax[i]) * dt / 2
vy[i + 1] = vy[i] + (ay[i + 1] + ay[i]) * dt / 2
x[i + 1] = x[i] + (vx[i + 1] + vx[i]) * dt / 2
y[i + 1] = y[i] + (vy[i + 1] + vy[i]) * dt / 2
i += 1 # increment i for next iteration
x = x[0:i + 1] # truncate x array
y = y[0:i + 1] # truncate y array
# print('Max: X:', maxy_x, 'Y:', maxy)
return x, y, (dt * i), x[i] # return x, y, flight time, range of projectile
def plot_graph(v, launch_angle, explanation):
(x, y, duration, distance) = traj_fr(coef, launch_angle, v,
inity) # define variables for output of traj_fr function
print(explanation, ' Distance: ', distance)
print('Duration: ', duration)
plt.plot(x, y, label=explanation) # quick plot of x vs y to check trajectory
return x, y
launch_angle = launch_angle / 180 * math.pi # Convert to radian
v0 = final_velocity_calculation(rod_weight, length_ratio, counterweight, fruit_weight
, x_length, y_length, initial_angle, launch_angle_radian, g, rod_length)
# plot_graph(v0, launch_angle_radian, "Average")
angle_data = np.zeros(len(time))
distance_data = np.zeros(len(time))
maximum_distance = 0
maximum_distance_angle = 0
for degree in range(0, 90):
print('Angle: ', degree)
angle = degree * math.pi / 180
v0 = final_velocity_calculation(rod_weight, length_ratio, counterweight, fruit_weight
, x_length, y_length, initial_angle, degree, g, rod_length)
x, y, duration, distance = traj_fr(coef, angle, v0, inity)
# plot_graph(v0, angle, "Average")
angle_data[degree] = degree
distance_data[degree] = distance
if distance > maximum_distance:
maximum_distance = distance
maximum_distance_angle = degree
print('Distance: ', distance)
print('Duration: ', duration)
angle_data = angle_data[0:90]
distance_data = distance_data[0:90]
print('Maximum distance:', maximum_distance)
print('Angle for maximum distance', maximum_distance_angle)
plt.plot(angle_data, distance_data, color="blue", linewidth=2.5, linestyle="-")
# -----------------Annotate----------------------
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
annotate_angle_text = 'Optimization Angle=' + str(maximum_distance_angle) + '°'
plt.annotate(annotate_angle_text, xy=(maximum_distance_angle, maximum_distance), xycoords='data',
xytext=(+10, +20), textcoords='offset points', fontsize=10,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
annotate_distance_text = 'Maximum Distance\n=' + str(round(maximum_distance, 3)) + "m"
plt.annotate(annotate_distance_text, xy=(maximum_distance_angle, maximum_distance/2), xycoords='data',
xytext=(+5, +5), textcoords='offset points', fontsize=10)
plt.plot([maximum_distance_angle, maximum_distance_angle], [0, maximum_distance], color='blue'
, linewidth=2.5, linestyle="--")
plt.scatter([maximum_distance_angle, ], [maximum_distance, ], 50, color='blue')
# -----------------Annotate----------------------
plt.xlabel('Angle (Degree)')
plt.ylabel('Distance (m)')
# plt.legend(loc='upper left')
plt.show()
| {"/Projectile.py": ["/variables.py", "/Launching.py"]} |
64,931 | palashsarkar18/csv-file-generator | refs/heads/master | /credentials.py | user = "****" # Enter your username here to access postgresql locally
password = "********" # Enter password here to access postgresql locally
database_name = "YOUR DATABASE NAME" # Enter your postgreSQL database name here. | {"/config.py": ["/credentials.py"]} |
64,932 | palashsarkar18/csv-file-generator | refs/heads/master | /application.py | from flask import Flask, request, jsonify, json, send_file
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.dialects.postgresql import JSON
import csv
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
# Model here
class Data_Table(db.Model):
__tablename__ = 'data_table'
id = db.Column(db.Integer, primary_key=True)
data = db.Column(JSON)
def __init__(self, data):
self.data=data
def __repr__(self):
return '<json data: %r>' % self.data
# Views here
@app.route('/')
def home():
"""The following function retrieves data in GET and stores it in a PostgreSQL database
"""
all_args = json.dumps(request.args.to_dict())
new_data = Data_Table(all_args)
db.session.add(new_data)
db.session.commit()
return jsonify(request.args.to_dict())
@app.route('/download')
def csv_file():
"""The following function generates a csv file
"""
filename = 'folder/csv_file.csv'
data = Data_Table.query.all()
[data_keys, data_json] = determining_KeysNData(data)
with open(filename, 'wb') as output_file:
dict_writer = csv.DictWriter(output_file, data_keys)
dict_writer.writeheader()
dict_writer.writerows(data_json)
return send_file(filename, as_attachment=True)
@app.route('/delete')
def deleting_content_in_database():
"""This function deletes all elements in database.
"""
data = Data_Table.query.all()
for item in data:
db.session.delete(item)
db.session.commit()
return "Successful deletion of data in database"
def determining_KeysNData(data):
"""This function determines the keys present in the database
"""
data_keys = []
data_json = []
for item in data:
data_json.append(json.loads(item.data))
for element in json.loads(item.data):
if element not in data_keys:
data_keys.append(element)
return [data_keys, data_json]
| {"/config.py": ["/credentials.py"]} |
64,933 | palashsarkar18/csv-file-generator | refs/heads/master | /config.py | import os
from credentials import user, password, database_name
if os.environ.get('DATABASE_URL') is None:
SQLALCHEMY_DATABASE_URI = "postgresql://" + user + ":" + password + "@localhost/" + database_name
else:
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
| {"/config.py": ["/credentials.py"]} |
64,984 | bawenna/precision-map | refs/heads/master | /app.py | import io
import json
from waitress import serve
from flask import Flask, request, render_template, make_response
from utils import extension_validation, process_data_for_output
app = Flask(__name__)
@app.route('/', methods=["POST", "GET"])
def form():
if request.method == 'POST':
f = request.files['data_file']
if not f:
context = {"error": True, "error_message": "No File"}
else:
file_check = extension_validation(f.filename)
if file_check:
stream = io.StringIO(f.stream.read().decode("utf-8-sig"), newline=None)
final_data, error = process_data_for_output(stream)
if error:
context = {"error": True, "error_message": error}
else:
context = {"output": json.dumps(final_data, indent=2), "enable_output": True}
else:
context = {"error": True, "error_message": "Incorrect format"}
else:
context = dict()
return render_template("base.html", **context)
@app.route('/sample', methods=["GET"])
def get_sample_json():
si = io.StringIO()
try:
file = open("sample.json", "r").read()
except Exception as e:
# just in case when sample.json is not available
file = '''{"reference":{"ref-temp":50,"ref-hum":50},"data":{"temp-1":{"humidity":[{"timestamp":"2007-04-05T22:12","data":45}],"thermometer":[{"timestamp":"2007-04-05T22:00","data":72.4}]},"temp-2":{"thermometer":[{"timestamp":"2007-04-05T22:12","data":69.4}]}}}'''
si.write(json.loads(json.dumps(file)))
output = make_response(si.getvalue())
output.headers["Content-Disposition"] = "attachment; filename=sample.json"
output.headers["Content-type"] = "text/json"
return output
if __name__ == "__main__":
serve(app, host='0.0.0.0', port=5000)
| {"/app.py": ["/utils.py"]} |
64,985 | bawenna/precision-map | refs/heads/master | /utils.py | import json
import statistics
def get_precision(mean, average_room_temp):
pre = average_room_temp - mean
if pre < 0:
pre = -1 * pre
return pre
def extension_validation(filename, ext: list = ["json"]) -> bool:
"""
Validated the extension of files
:param filename:
:param ext: default json
:return: bool
"""
files_split = filename.split(".")
ext_for_file = files_split[-1]
if ext_for_file in ext:
return True
return False
def process_data_for_output(inputdata):
try:
formatted_data_objects = json.loads(inputdata.read())
reference = formatted_data_objects.get("reference")
information = formatted_data_objects.get("data")
ref_humidity_reading = reference.get("ref-hum")
ref_temp_reading = reference.get("ref-temp")
final_data = dict()
for name, objects in information.items():
for type, value in objects.items():
if type == 'thermometer':
# extract all the temperature data for calculation
temp_data = [x['data'] for x in value]
reading = statistics.mean(temp_data)
# required at least two datapoints
stdev = statistics.stdev(temp_data)
precision = get_precision(reading, ref_temp_reading)
if precision <= 0.5 and stdev < 3:
final_data[f"{name}_{type}"] = "ultra-precise"
elif precision <= 0.5 and stdev < 5:
final_data[f"{name}_{type}"] = "very precise"
else:
final_data[f"{name}_{type}"] = "precise"
elif type == 'humidity':
# init an array to store each percentage for later
percentage_diff_array = []
for x in value:
diff = ref_humidity_reading - x['data'] if ref_humidity_reading - x['data'] > 0 else x['data'] - ref_humidity_reading
percentage_diff = ((diff / ref_humidity_reading) * 100)
percentage_diff_array.append(percentage_diff)
percentage_diff_mean = statistics.mean(percentage_diff_array)
if percentage_diff_mean > 1:
final_data[f"{name}_{type}"] = "discard"
else:
final_data[f"{name}_{type}"] = "keep"
else:
final_data[f"{name}_{type}"] = "Unable to identify"
return final_data, None
except Exception as e:
return None, e
| {"/app.py": ["/utils.py"]} |
64,990 | Fingernight1/FacadeStream | refs/heads/main | /scanner.py | import streamlit as st
from sources.MachineLearningUtils import *
from sources.FrontendUtils import *
# Parameters:
# Saving prediction locally?
is_save_result = True
# Max height and max width: inputs greater than this shape will be resized.
max_height = 750
max_width = 750
# File Path
model_path = './models'
# prediction_path = './prediction'
result_path = './results'
st.set_page_config(page_title='Facade Segmentation', page_icon='🏠', initial_sidebar_state='expanded')
st.title('Facade Segmentation')
uploaded_files = st.sidebar.file_uploader('Upload Facade Images', ['png', 'jpg', 'jpeg'], accept_multiple_files=True)
# Hide setting bar and footer
hide_streamlit_style = """
<style>
#MainMenu {visibility: hidden;}
footer {visibility: hidden;}
</style>
"""
st.markdown(hide_streamlit_style, unsafe_allow_html=True)
image_list, name_list = process_upload_files(uploaded_files, max_height, max_width)
displaySideBarImage(image_list, name_list)
devices_map = get_devices()
model_list = get_model_list(model_path)
if (model_list == []):
# download_flag = st.button('Download the model')
cols = st.columns(2)
download_stage = cols[1].markdown('Model not found 😧 Please download the model. 📦')
if (cols[0].button('Download Model')):
download_stage.markdown('Downloading... ⏳')
download_default_model(model_path)
download_stage.markdown('Downloaded 🎉')
model_list = get_model_list(model_path)
cols = st.columns(2)
selected_model = cols[0].selectbox('Model', model_list)
cuda_message = ' - CUDA is available' if torch.cuda.is_available() else ''
# [*devices_map] will return a list of dictionary key, a list of devices' name.
device_key = cols[1].selectbox('Device' + cuda_message, [*devices_map])
device_value = devices_map[device_key]
if (model_list != []):
device = torch.device(device_value)
analysis_flag = st.button('Run it! ')
if analysis_flag:
# Image to device
img_device_list = []
for image in image_list:
# img_device = image.to(device)
img_device_list.append(image)
model = deeplabv3ModelGenerator(model_path + "/" + selected_model, device)
# Turn on model's evaluation mode
model.eval()
# turn off auto grad machine
with torch.no_grad():
run_prediction(model, device, img_device_list, name_list, result_path, is_save_result)
| {"/scanner.py": ["/sources/MachineLearningUtils.py", "/sources/FrontendUtils.py"], "/sources/FrontendUtils.py": ["/sources/MachineLearningUtils.py"]} |
64,991 | Fingernight1/FacadeStream | refs/heads/main | /sources/FrontendUtils.py | import streamlit as st
from PIL import Image
from sources.MachineLearningUtils import *
import gdown
def name_without_extension(filename):
return ".".join(str(filename).split('.')[:-1])
def process_upload_files(uploaded_files, max_height=500, max_width=500):
image_list = []
name_list = []
# process uploaded images
for up_file in uploaded_files:
filename = up_file.name
name_list.append(filename)
img = np.array(Image.open(up_file).convert('RGB'))
img = resize_image(img, max_height, max_width)
image_list.append(img)
return image_list, name_list
def displaySideBarImage(image_list, name_list):
input_size = len(image_list)
for i in range(input_size):
img = image_list[i]
name = name_list[i]
st.sidebar.image(img, caption=name)
def save_uploaded_images(input_path):
for ufile in uploaded_files:
_img = Image.open(ufile)
_img = _img.save(input_path + '/' + ufile.name)
return
def displayPrediction(filename, _img, _pred, _anno, _wwr):
# Display in 3 columns.
# col0: original image,
# col1: prediction (colormap),
# col0: prediction (annotation),
cols = st.beta_columns(3)
cols[0].image(_img, use_column_width=True, caption='Image: {}'.format(filename))
cols[1].image(_pred, use_column_width=True, caption='Segmentation')
cols[2].image(_anno, use_column_width=True, caption='Annotation')
# Markdown
st.markdown("> Estimated Window-to-Wall Ratio: **{}**".format(_wwr))
# st.markdown("> Estimated Window-to-Wall Ratio: " + "**" + wwr_percentage + "**")
st.markdown("------")
return
def run_prediction(model, device, image_list, name_list, result_path, is_save_result=False):
input_size = len(image_list)
for i in range(input_size):
img = image_list[i]
filename = name_without_extension(name_list[i])
# predict prediction, annotated image, and estimated Window-to-Wall Ratio
pred_img, anno_image, wwr = predict(model, img, device)
displayPrediction(filename, img, pred_img, anno_image, wwr)
# save prediction if is_save_result is true
if (is_save_result):
save_result(pred_img, anno_image, wwr, result_path, filename)
return
def download_default_model(dir):
google_drive_url = 'https://drive.google.com/uc?export=download&id=1rJ3edeARtcprrgs14lj5iZLTLkn9kufw'
output = dir + '/deeplabv3_resnet101.pth'
gdown.download(google_drive_url, output, quiet=False)
# gdown.cached_download(google_drive_url, output, md5=md5)
# Get all cuda devices...Usually just one CPU or one GPU.
def get_devices():
devices = []
devices_map = {}
# Cuda devices
device_count = torch.cuda.device_count()
for i in range(device_count):
device_name = torch.cuda.get_device_name(i) + ' [%s]'%str(i)
devices.append(device_name)
devices_map[device_name] = 'cuda:' + str(i)
# CPU option
cpu_name = 'CPU'
devices.append(cpu_name)
devices_map[cpu_name] = 'cpu'
return devices_map
# Scan model_path
def get_model_list (dir):
models = []
if not os.path.exists(dir):
os.mkdir(dir)
for model_name in os.listdir(dir):
extension = model_name.split('.')[-1]
if extension == 'pt' or extension == 'pth':
models.append(model_name)
return models
| {"/scanner.py": ["/sources/MachineLearningUtils.py", "/sources/FrontendUtils.py"], "/sources/FrontendUtils.py": ["/sources/MachineLearningUtils.py"]} |
64,992 | Fingernight1/FacadeStream | refs/heads/main | /sources/MachineLearningUtils.py | from torchvision import transforms
import torchvision
import torch
import numpy as np
import cv2
import os
transforms_image = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
def resize_image(image, max_height, max_width):
image = np.array(image)
height, width, _ = image.shape
scale_height = max_height / height
scale_width = max_width / width
scale = min(scale_height, scale_width, 1)
image = cv2.resize(image, None, fx=scale, fy=scale, interpolation=cv2.INTER_AREA)
return image
def deeplabv3ModelGenerator(model_path, device):
num_classes = 9
model = init_deeplab(num_classes)
state_dict = torch.load(model_path, map_location=device)
model = model.to(device)
model.load_state_dict(state_dict)
return model
# One image at a time.
def predict(model, image, device):
# make sure image is a np-array
# image = resize_image(image)
print('Start Prediction')
prediction_indexed = label_image(model, image, device)
print('Start decoding')
prediction = decode_segmap(prediction_indexed)
print('Decoded')
print('Start annotation')
annotation = annotate_image(image, prediction_indexed)
print('End annotation')
wwr_estimation = get_wwr_by_pixel(prediction_indexed)
wwr_percentage = str(round(wwr_estimation * 100, 2)) + "%"
return prediction, annotation, wwr_percentage
def save_result(pred, anno, wwr, path, filename):
create_folder(path)
save_image(pred, path, 'segmentation', filename)
save_image(anno, path, 'annotation', filename)
save_wwr(wwr, path, filename)
return
def save_image(_img, path, foldername, filename):
folder_path = "{}/{}".format(path, foldername)
create_folder(folder_path)
full_path = "{}/{}.jpg".format(folder_path, filename)
# CV2 write
bgr_img = cv2.cvtColor(_img, cv2.COLOR_RGB2BGR)
cv2.imwrite(full_path, bgr_img)
return
def save_wwr(wwr, path, filename, mode='a'):
# append mdoe (if the file doesn't exist create it and open in append mode)
wwr_result_filename = "wwr_estimation.csv"
full_path = "{}/{}".format(path, wwr_result_filename)
print(full_path)
f = open(full_path, mode)
f.write("{},{}\n".format(filename, wwr))
def get_wwr_by_pixel(prediction_indexed):
# 0 Void, or various
# 1 Wall
# 2 Car
# 3 Door
# 4 Pavement
# 5 Road
# 6 Sky
# 7 Vegetation
# 8 Windows
window_count = np.sum(prediction_indexed == 8)
wall_count = np.sum(prediction_indexed == 1)
door_count = np.sum(prediction_indexed == 3)
return window_count / (window_count + wall_count + door_count)
def annotate_image(image, pred_indexed):
annotate_colors = {
0: (0, 0, 0), # Various
1: (128, 0, 0), # Wall
2: (128, 0, 128), # Car
3: (128, 128, 0), # Door
4: (128, 128, 128), # Pavement
5: (128, 64, 0), # Road
6: (0, 128, 128), # Sky
7: (0, 128, 0), # Vegetation
8: (0, 0, 128) # Windows
}
image = np.array(image)
dim_factor = 0.5
image = image * dim_factor
r = image[:, :, 0]
g = image[:, :, 1]
b = image[:, :, 2]
anno_factor = 0.5
for label in annotate_colors:
idx = pred_indexed == label
r[idx] += annotate_colors[label][0] * anno_factor
g[idx] += annotate_colors[label][1] * anno_factor
b[idx] += annotate_colors[label][2] * anno_factor
rgb = np.stack([r, g, b], axis=2)
rgb = rgb.clip(0, 255)
image = rgb.astype('uint8')
return image
# Define the helper function
def decode_segmap(pred_indexed, nc=9):
label_colors = {
0: (0, 0, 0), # Various
1: (128, 0, 0), # Wall
2: (128, 0, 128), # Car
3: (128, 128, 0), # Door
4: (128, 128, 128), # Pavement
5: (128, 64, 0), # Road
6: (0, 128, 128), # Sky
7: (0, 128, 0), # Vegetation
8: (0, 0, 128) # Windows
}
r = np.zeros_like(pred_indexed).astype(np.uint8)
g = np.zeros_like(pred_indexed).astype(np.uint8)
b = np.zeros_like(pred_indexed).astype(np.uint8)
for label in range(0, nc):
idx = pred_indexed == label
r[idx] = label_colors[label][0]
g[idx] = label_colors[label][1]
b[idx] = label_colors[label][2]
rgb = np.stack([r, g, b], axis=2)
return rgb
def label_image(model, image, device):
image = transforms_image(image)
image = image.unsqueeze(0)
image = image.to(device)
outputs = model(image)["out"]
_, preds = torch.max(outputs, 1)
preds = preds.to("cpu")
preds_np = preds.squeeze(0).cpu().numpy().astype(np.uint8)
return preds_np
def init_deeplab(num_classes):
model_deeplabv3 = torchvision.models.segmentation.deeplabv3_resnet101()
model_deeplabv3.aux_classifier = None
model_deeplabv3.classifier = torchvision.models.segmentation.deeplabv3.DeepLabHead(2048, num_classes)
return model_deeplabv3
def create_folder(folder_path):
if not os.path.exists(folder_path):
os.mkdir(folder_path)
return
# def clear_folder(folder_path):
# # Check if the image uploading folder exist
# # If yes, delete all file under this path
# if os.path.exists(folder_path):
# for img_name in os.listdir(folder_path):
# filepath = os.path.join(folder_path, img_name)
# print(filepath)
# os.remove(filepath)
# # if the folder doesn't exist, create an empty folder.
# else:
# os.mkdir(folder_path)
# return
| {"/scanner.py": ["/sources/MachineLearningUtils.py", "/sources/FrontendUtils.py"], "/sources/FrontendUtils.py": ["/sources/MachineLearningUtils.py"]} |
65,012 | kh06089/2019-LMSLite | refs/heads/master | /courses/migrations/0021_assignment_restrict_date.py | # Generated by Django 2.1.7 on 2019-04-30 01:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('courses', '0020_auto_20190430_0043'),
]
operations = [
migrations.AddField(
model_name='assignment',
name='restrict_date',
field=models.DateTimeField(blank=True, default=None, null=True),
),
]
| {"/courses/forms.py": ["/LMSLite/helpers.py", "/courses/models.py"], "/LMSLite/views.py": ["/courses/models.py"], "/LMSLite/helpers.py": ["/courses/models.py"], "/courses/admin.py": ["/courses/models.py", "/courses/forms.py"], "/courses/views.py": ["/LMSLite/helpers.py", "/courses/models.py", "/courses/forms.py"], "/courses/migrations/0016_auto_20190415_1610.py": ["/courses/models.py"]} |
65,013 | kh06089/2019-LMSLite | refs/heads/master | /courses/migrations/0021_auto_20190430_1304.py | # Generated by Django 2.1.7 on 2019-04-30 17:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('courses', '0020_quiz_average'),
]
operations = [
migrations.AlterField(
model_name='quiz',
name='average',
field=models.FloatField(blank=True, default=-1, null=True),
),
]
| {"/courses/forms.py": ["/LMSLite/helpers.py", "/courses/models.py"], "/LMSLite/views.py": ["/courses/models.py"], "/LMSLite/helpers.py": ["/courses/models.py"], "/courses/admin.py": ["/courses/models.py", "/courses/forms.py"], "/courses/views.py": ["/LMSLite/helpers.py", "/courses/models.py", "/courses/forms.py"], "/courses/migrations/0016_auto_20190415_1610.py": ["/courses/models.py"]} |
65,014 | kh06089/2019-LMSLite | refs/heads/master | /courses/migrations/0004_auto_20190309_2028.py | # Generated by Django 2.1.7 on 2019-03-09 20:28
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('courses', '0003_auto_20190309_1707'),
]
operations = [
migrations.RemoveField(
model_name='course',
name='prof',
),
migrations.RemoveField(
model_name='course',
name='students',
),
]
| {"/courses/forms.py": ["/LMSLite/helpers.py", "/courses/models.py"], "/LMSLite/views.py": ["/courses/models.py"], "/LMSLite/helpers.py": ["/courses/models.py"], "/courses/admin.py": ["/courses/models.py", "/courses/forms.py"], "/courses/views.py": ["/LMSLite/helpers.py", "/courses/models.py", "/courses/forms.py"], "/courses/migrations/0016_auto_20190415_1610.py": ["/courses/models.py"]} |
65,015 | kh06089/2019-LMSLite | refs/heads/master | /courses/migrations/0002_delete_assignment.py | # Generated by Django 2.1.7 on 2019-03-07 06:51
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('courses', '0001_initial'),
]
operations = [
migrations.DeleteModel(
name='Assignment',
),
]
| {"/courses/forms.py": ["/LMSLite/helpers.py", "/courses/models.py"], "/LMSLite/views.py": ["/courses/models.py"], "/LMSLite/helpers.py": ["/courses/models.py"], "/courses/admin.py": ["/courses/models.py", "/courses/forms.py"], "/courses/views.py": ["/LMSLite/helpers.py", "/courses/models.py", "/courses/forms.py"], "/courses/migrations/0016_auto_20190415_1610.py": ["/courses/models.py"]} |
65,016 | kh06089/2019-LMSLite | refs/heads/master | /courses/forms.py | import csv
from django import forms
from LMSLite.helpers import create_quiz, send_email
from .models import Course, Quiz, Homework, Grade, Survey
class CourseAdminCreationForm(forms.ModelForm):
class Meta:
model = Course
fields = ('course_name', 'description')
def save(self, commit=True):
# Save the provided password in hashed format
course = super(CourseAdminCreationForm, self).save(commit=False)
if commit:
course.save()
course.prof.courses.add(course)
for student in course.students.all():
student.courses.add(course)
return course
class CourseAdminChangeForm(forms.ModelForm):
class Meta:
model = Course
fields = ('course_name', 'description', 'students')
class SurveyEditForm(forms.Form):
file_address = ''
def generate_survey_form(self, input):
questions = create_quiz(input)
for x, question in enumerate(questions, start=1):
self.fields['Question' + str(x) + 'type'] = forms.ChoiceField(
choices={(1, 'MC'), (2, 'SR'), (3, 'MA'), (4, 'FIB'), (5, 'TF'), (6, 'ESS')},
initial=question.type,
label='')
self.fields['Question ' + str(x)] = forms.CharField(
max_length=1000,
initial=question.label,
widget=forms.Textarea(attrs={'rows': 1,
'cols': 40,
'onchange': 'updateQuestion(this.id)',
'style': 'height: 5rem;'}))
for y, answer in enumerate(question.answers, start=1):
self.fields['Question' + str(x) + 'Answer' + str(y)] = forms.CharField(
label='Answer ' + str(y),
max_length=1000,
initial=answer,
widget=forms.Textarea(attrs={'rows': 1,
'cols': 40,
'onchange': 'updateMAcheckbox(this.id)',
'style': 'height: 2rem;'}))
def __init__(self, *args, **kwargs):
super(SurveyEditForm, self).__init__(*args, **kwargs)
self.generate_survey_form(self.file_address)
class SurveyFileForm(forms.ModelForm):
class Meta:
model = Survey
fields = ('assignment_name', 'open_date', 'due_date', 'restrict_date', 'file')
widgets = {
'restrict_date': forms.TextInput(attrs={'autocomplete': 'off'}),
'open_date': forms.TextInput(attrs={'autocomplete': 'off'}),
'due_date': forms.TextInput(attrs={'autocomplete': 'off'}),
'assignment_name': forms.TextInput(attrs={'autocomplete': 'off'}),
}
def save(self, commit=True, course=None, prof=None):
survey = super(SurveyFileForm, self).save(commit=False)
if commit:
survey.prof = prof
survey.course_id = course
survey.type = 1
survey.save()
course.surveys.add(Survey.objects.get(id=survey.id))
for student in course.students.all():
student.surveys.add(Survey.objects.get(id=survey.id))
student.save()
course.save()
send_email(course.students.all(), survey)
return survey
class QuizEditForm(forms.Form):
file_address = ''
def generate_quiz_form(self, input):
questions = create_quiz(input)
for x, question in enumerate(questions, start=1):
self.fields['Question' + str(x) + 'type'] = forms.ChoiceField(
choices={(1, 'MC'), (2, 'SR'), (3, 'MA'), (4, 'FIB'), (5, 'TF'), (6, 'ESS')},
initial=question.type,
label='')
self.fields['Question ' + str(x)] = forms.CharField(
max_length=1000,
initial=question.label,
widget=forms.Textarea(attrs={'rows': 1,
'cols': 40,
'onchange': 'updateQuestion(this.id)',
'style': 'height: 5rem;'}))
for y, answer in enumerate(question.answers, start=1):
if answer in question.cAnswers:
self.fields['Question' + str(x) + 'Answer' + str(y)] = forms.CharField(
label='Answer ' + str(y),
max_length=1000,
initial=answer,
widget=forms.Textarea(attrs={'id':'Question' + str(x) + 'Answer' + str(y) +'correct',
'onchange': 'updateMAcheckbox(this.id)',
'rows': 1,
'cols': 40,
'style': 'height: 2rem;'}))
else:
self.fields['Question' + str(x) + 'Answer' + str(y)] = forms.CharField(
label='Answer ' + str(y),
max_length=1000,
initial=answer,
widget=forms.Textarea(attrs={'rows': 1,
'cols': 40,
'style': 'height: 2rem;'}))
def __init__(self, *args, **kwargs):
super(QuizEditForm, self).__init__(*args, **kwargs)
self.generate_quiz_form(self.file_address)
class QuizFileForm(forms.ModelForm):
class Meta:
model = Quiz
fields = ('assignment_name', 'open_date', 'due_date', 'restrict_date', 'quiz_code', 'file', 'grade_viewable', 'restricted', )
widgets = {
'restrict_date': forms.TextInput(attrs={'autocomplete': 'off'}),
'open_date': forms.TextInput(attrs={'autocomplete': 'off'}),
'due_date': forms.TextInput(attrs={'autocomplete': 'off'}),
'quiz_code': forms.TextInput(attrs={'autocomplete': 'off'}),
'assignment_name': forms.TextInput(attrs={'autocomplete': 'off'}),
}
def save(self, commit=True, course=None, prof=None):
quiz = super(QuizFileForm, self).save(commit=False)
if commit:
quiz.prof = prof
quiz.course_id = course
quiz.type = 0
quiz.save()
course.quizes.add(Quiz.objects.get(id=quiz.id))
for student in course.students.all():
student.quizes.add(Quiz.objects.get(id=quiz.id))
student.save()
course.save()
send_email(course.students.all(), quiz)
return quiz
class HomeworkCreationForm(forms.ModelForm):
class Meta:
model = Homework
fields = ('assignment_name', 'open_date', 'due_date', 'restrict_date', 'file',)
widgets = {
'restrict_date': forms.TextInput(attrs={'autocomplete': 'off'}),
'open_date': forms.TextInput(attrs={'autocomplete': 'off'}),
'due_date': forms.TextInput(attrs={'autocomplete': 'off'}),
'assignment_name': forms.TextInput(attrs={'autocomplete': 'off'}),
}
def save(self, commit=True, course=None, prof=None):
homework = super(HomeworkCreationForm, self).save(commit=False)
if commit:
homework.prof = prof
homework.course_id = course
homework.type = 2
homework.save()
course.homeworks.add(Homework.objects.get(id=homework.id))
for student in course.students.all():
student.homeworks.add(Homework.objects.get(id=homework.id))
student.save()
course.save()
send_email(course.students.all(), homework)
return homework
class GradeEditForm(forms.ModelForm):
class Meta:
model = Grade
fields = ('grade_value', )
| {"/courses/forms.py": ["/LMSLite/helpers.py", "/courses/models.py"], "/LMSLite/views.py": ["/courses/models.py"], "/LMSLite/helpers.py": ["/courses/models.py"], "/courses/admin.py": ["/courses/models.py", "/courses/forms.py"], "/courses/views.py": ["/LMSLite/helpers.py", "/courses/models.py", "/courses/forms.py"], "/courses/migrations/0016_auto_20190415_1610.py": ["/courses/models.py"]} |
65,017 | kh06089/2019-LMSLite | refs/heads/master | /LMSLite/views.py | import datetime
from django.http import HttpResponse
from django.shortcuts import render
from django.utils.encoding import smart_str
from accounts.models import Professor, Student
from courses.models import Quiz, Assignment, Homework, Survey
def index(request):
context_dict = {}
quizzes = []
homeworks = []
surveys = []
if request.user.is_authenticated and request.user.role == 1:
d = datetime.datetime.today()
prof = Professor.objects.get(id=request.user.id)
courses = prof.courses.all()
x = 0
for course in courses:
for quiz in course.quizes.all():
if quiz.due_date.replace(tzinfo=None) > d and x < 5:
quizzes.append(quiz)
x+=1
x = 0
for homework in course.homeworks.all():
if homework.due_date.replace(tzinfo=None) > d and x < 5:
homeworks.append(homework)
x+=1
x = 0
for survey in course.surveys.all():
if survey.due_date.replace(tzinfo=None) > d and x < 5:
surveys.append(survey)
x+=1
context_dict['courses'] = courses
elif request.user.is_authenticated and request.user.role == 2:
d = datetime.datetime.today()
std = Student.objects.get(id=request.user.id)
courses = std.courses.all()
x = 0
for course in courses:
for quiz in course.quizes.all():
if quiz.due_date.replace(tzinfo=None) > d and x < 5:
quizzes.append(quiz)
x += 1
x = 0
for homework in course.homeworks.all():
if homework.due_date.replace(tzinfo=None) > d and x < 5:
homeworks.append(homework)
x += 1
x = 0
for survey in course.surveys.all():
if survey.due_date.replace(tzinfo=None) > d and x < 5:
surveys.append(survey)
x += 1
context_dict['courses'] = courses
context_dict['homeworks'] = homeworks
context_dict['surveys'] = surveys
context_dict['quizzes'] = quizzes
return render(request, 'index.html', context_dict)
def download(request, id):
assignment = Assignment.objects.get(id=id)
if assignment.type == 0:
quiz = Quiz.objects.get(id=id)
fName = quiz.file.name.split('/')[-1]
response = HttpResponse(quiz.file, content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(fName)
elif assignment.type == 2:
hw = Homework.objects.get(id=id)
fName = hw.file.name.split('/')[-1]
response = HttpResponse(hw.file, content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(fName)
elif assignment.type == 1:
survey = Survey.objects.get(id=id)
fName = survey.file.name.split('/')[-1]
response = HttpResponse(survey.file, content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(fName)
return response
| {"/courses/forms.py": ["/LMSLite/helpers.py", "/courses/models.py"], "/LMSLite/views.py": ["/courses/models.py"], "/LMSLite/helpers.py": ["/courses/models.py"], "/courses/admin.py": ["/courses/models.py", "/courses/forms.py"], "/courses/views.py": ["/LMSLite/helpers.py", "/courses/models.py", "/courses/forms.py"], "/courses/migrations/0016_auto_20190415_1610.py": ["/courses/models.py"]} |
65,018 | kh06089/2019-LMSLite | refs/heads/master | /LMSLite/urls.py | """LMSLite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from django.conf.urls import include
from courses import views as courseView
from accounts import views as accountView
from LMSLite import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^$', views.index, name='index'),
path('auth/', include('django.contrib.auth.urls')),
path('profile/', accountView.profile_view, name='profile'),
path('courses/<int:id>/', courseView.course_view, name='course_page'),
path('courses/<int:cid>/quizzes/',courseView.quiz_list_view, name='quiz_list'),
path('courses/<int:cid>/quizzes/<int:id>/start/', courseView.quiz_view, name='quiz_page'),
path('courses/<int:cid>/surveys/<int:id>/start/', courseView.take_survey_view, name='survey_page'),
path('courses/<int:cid>/quizzes/<int:id>/', courseView.pre_quiz_view, name='quiz_start'),
path('courses/<int:cid>/surveys/<int:id>/', courseView.pre_survey_view, name='pre_survey'),
path('courses/<int:cid>/surveys/',courseView.survey_list_view, name='survey_list'),
path('courses/Assignments/files/<int:id>/', views.download, name='download'),
path('courses/<int:id>/Homework/', courseView.homework_view, name='homework_list'),
path('courses/<int:cid>/Homework/<int:id>/', courseView.homework_submit_view, name='submit_assign'),
path('courses/<int:cid>/grades/', courseView.grade_view, name='assignment_list'),
path('courses/<int:cid>/grades/<int:id>/submission', courseView.submission_view, name='submission_view'),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) | {"/courses/forms.py": ["/LMSLite/helpers.py", "/courses/models.py"], "/LMSLite/views.py": ["/courses/models.py"], "/LMSLite/helpers.py": ["/courses/models.py"], "/courses/admin.py": ["/courses/models.py", "/courses/forms.py"], "/courses/views.py": ["/LMSLite/helpers.py", "/courses/models.py", "/courses/forms.py"], "/courses/migrations/0016_auto_20190415_1610.py": ["/courses/models.py"]} |
65,019 | kh06089/2019-LMSLite | refs/heads/master | /courses/models.py | from django.db import models
def quiz_upload_address(instance, filename):
name, ext = filename.split('.')
filename = instance.assignment_name
file_path = '{account_id}/Quizzes/{Assignment}/{filename}.{ext}'.format(
account_id=instance.course_id.course_name, Assignment=instance.assignment_name, filename=filename+'_key', ext=ext)
return file_path
def survey_upload_address(instance, filename):
name, ext = filename.split('.')
filename = instance.assignment_name
file_path = '{account_id}/Surveys/{Assignment}/{filename}.{ext}'.format(
account_id=instance.course_id.course_name, Assignment=instance.assignment_name, filename=filename + '_key', ext=ext)
return file_path
def homework_upload_address(instance, filename):
name, ext = filename.split('.')
filename = instance.assignment_name
file_path = '{account_id}/Homework/{Assignment}/{filename}.{ext}'.format(
account_id=instance.course_id.course_name, Assignment=instance.assignment_name, filename=filename + '_key', ext=ext)
return file_path
def response_upload_address(instance, filename):
name, ext = filename.split('.')
filename = instance.assignment.assignment_name
file_path = '{account_id}/Responses/{filename}.{ext}'.format(
account_id=instance.assignment.course_id.course_name, filename=filename + '_' + instance.stdnt.email.split('@')[0], ext=ext)
return file_path
class Assignment(models.Model):
assignment_name = models.CharField(max_length=255, blank=True)
open_date = models.DateTimeField(blank=True)
due_date = models.DateTimeField(blank=True)
restrict_date = models.DateTimeField(blank=True, default=None, null=True)
prof = models.ForeignKey('accounts.Professor', on_delete=models.CASCADE)
course_id = models.ForeignKey('courses.Course', on_delete=models.CASCADE)
TYPE_CHOICES = (
(2, 'homework'),
(1, 'survey'),
(0, 'quiz'),
)
type = models.SmallIntegerField(choices=TYPE_CHOICES, blank=True)
def __str__(self):
return self.assignment_name
class Quiz(Assignment):
average = models.FloatField(blank=True,default=0, null=True)
quiz_code = models.CharField(max_length=8, blank=True, default=None, null=True)
restricted = models.BooleanField()
grade_viewable = models.BooleanField()
file = models.FileField(upload_to=quiz_upload_address, blank=True)
def __str__(self):
return self.assignment_name
class Survey(Assignment):
file = models.FileField(upload_to=survey_upload_address, blank=True)
def __str__(self):
return self.assignment_name
class Homework(Assignment):
file = models.FileField(upload_to=homework_upload_address, blank=True)
def __str__(self):
return self.assignment_name
class Grade(models.Model):
assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE, blank=True, default=None)
grade_value = models.FloatField(blank=True, default=None)
stdnt = models.ForeignKey('accounts.Student', on_delete=models.CASCADE, blank=True, default=None)
file = models.FileField(blank=True, default=None)
class Course(models.Model):
prof = models.ForeignKey('accounts.Professor', on_delete=models.CASCADE, blank=True, default=None)
students = models.ManyToManyField('accounts.Student')
course_name = models.CharField(max_length=255, unique=True)
description = models.TextField(blank=True)
quizes = models.ManyToManyField(Quiz)
surveys = models.ManyToManyField(Survey)
homeworks = models.ManyToManyField(Homework)
def __str__(self):
return self.course_name
| {"/courses/forms.py": ["/LMSLite/helpers.py", "/courses/models.py"], "/LMSLite/views.py": ["/courses/models.py"], "/LMSLite/helpers.py": ["/courses/models.py"], "/courses/admin.py": ["/courses/models.py", "/courses/forms.py"], "/courses/views.py": ["/LMSLite/helpers.py", "/courses/models.py", "/courses/forms.py"], "/courses/migrations/0016_auto_20190415_1610.py": ["/courses/models.py"]} |
65,020 | kh06089/2019-LMSLite | refs/heads/master | /courses/migrations/0005_auto_20190312_2015.py | # Generated by Django 2.1.7 on 2019-03-12 20:15
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('accounts', '0007_auto_20190308_2257'),
('courses', '0004_auto_20190309_2028'),
]
operations = [
migrations.CreateModel(
name='Assignment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('assignment_name', models.CharField(blank=True, max_length=255)),
('open_date', models.DateTimeField(auto_now_add=True)),
('due_date', models.DateTimeField(auto_now_add=True)),
('grade', models.BigIntegerField(blank=True, default=None)),
('type', models.SmallIntegerField(blank=True, choices=[(2, 'homework'), (1, 'survey'), (0, 'quiz')])),
],
),
migrations.CreateModel(
name='Homework',
fields=[
('assignment_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='courses.Assignment')),
('link', models.CharField(blank=True, max_length=255)),
],
bases=('courses.assignment',),
),
migrations.CreateModel(
name='Quiz',
fields=[
('assignment_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='courses.Assignment')),
('grade_viewable', models.BooleanField()),
],
bases=('courses.assignment',),
),
migrations.CreateModel(
name='Survey',
fields=[
('assignment_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='courses.Assignment')),
],
bases=('courses.assignment',),
),
migrations.AddField(
model_name='assignment',
name='course_id',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='courses.Course'),
),
migrations.AddField(
model_name='assignment',
name='prof',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='accounts.Professor'),
),
migrations.AddField(
model_name='course',
name='homeworks',
field=models.ManyToManyField(to='courses.Homework'),
),
migrations.AddField(
model_name='course',
name='quizes',
field=models.ManyToManyField(to='courses.Quiz'),
),
migrations.AddField(
model_name='course',
name='surveys',
field=models.ManyToManyField(to='courses.Survey'),
),
]
| {"/courses/forms.py": ["/LMSLite/helpers.py", "/courses/models.py"], "/LMSLite/views.py": ["/courses/models.py"], "/LMSLite/helpers.py": ["/courses/models.py"], "/courses/admin.py": ["/courses/models.py", "/courses/forms.py"], "/courses/views.py": ["/LMSLite/helpers.py", "/courses/models.py", "/courses/forms.py"], "/courses/migrations/0016_auto_20190415_1610.py": ["/courses/models.py"]} |
65,021 | kh06089/2019-LMSLite | refs/heads/master | /courses/migrations/0008_auto_20190327_2020.py | # Generated by Django 2.1.7 on 2019-03-27 20:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('courses', '0007_auto_20190327_2011'),
]
operations = [
migrations.AddField(
model_name='course',
name='description',
field=models.TextField(blank=True),
),
migrations.AlterField(
model_name='quiz',
name='file',
field=models.FileField(blank=True, upload_to='quizes'),
),
migrations.AlterField(
model_name='survey',
name='file',
field=models.FileField(blank=True, upload_to='surveys'),
),
]
| {"/courses/forms.py": ["/LMSLite/helpers.py", "/courses/models.py"], "/LMSLite/views.py": ["/courses/models.py"], "/LMSLite/helpers.py": ["/courses/models.py"], "/courses/admin.py": ["/courses/models.py", "/courses/forms.py"], "/courses/views.py": ["/LMSLite/helpers.py", "/courses/models.py", "/courses/forms.py"], "/courses/migrations/0016_auto_20190415_1610.py": ["/courses/models.py"]} |
65,022 | kh06089/2019-LMSLite | refs/heads/master | /LMSLite/helpers.py | import csv
from django.core.files.storage import default_storage
import smtplib
from courses.models import Course
class Question:
type = 0
label = ''
answers = []
cAnswers = []
def __init__(self, pType, pLabel, pAnswers, cAns):
self.label = pLabel
self.answers = pAnswers
self.cAnswers = cAns
self.type = pType
def reset_quiz(input, output, post):
qtype = []
with open(input, "rt") as fin:
reader = csv.reader(fin, delimiter='\t') # parse by tab
reader = (line for line in reader if line) # ignore blank lines
for questy in reader:
qtype.append(questy)
fin.close()
i = 0
j = 0
string = 'Question '
with default_storage.open(output, "wt") as fout:
for line in qtype:
for ans in qtype[i]:
string += str(i+1)
if j % 2 != 0 and qtype[i][j] == 'Correct':
qtype[i][j] = 'Incorrect'
if qtype[i][0] == 'TF':
if qtype[i][2] == 'True':
qtype[i][2] = 'False'
else:
qtype[i][2] = 'True'
if string in post:
if qtype[i][0] == 'MC':
qtype[i][qtype[i].index(post[string])+1] = 'Correct'
elif qtype[i][0] == 'SR' or qtype[i][0] == 'TF' or qtype[i][0] == 'ESS':
qtype[i][2] = post[string]
elif qtype[i][0] == 'MA':
for answer in qtype[i][2:]:
if answer in post.getlist(string):
qtype[i][qtype[i].index(answer)+1] = 'Correct'
elif qtype[i][0] == 'FIB':
for answer in qtype[i][2:]:
qtype[i][2] = post[string]
string = 'Question '
j += 1
j = 0
fout.write('\t'.join(qtype[i]))
fout.write('\n')
i += 1
fout.close()
return fout
def create_quiz(input):
qtype = []
questions = []
with open(input, "r") as file:
reader = csv.reader(file, delimiter='\t') # parse by tab
reader = (line for line in reader if line) # ignore blank lines
for questy in reader:
qtype.append(questy)
i = 0 # initialize index
while i < len(qtype):
if qtype[i][0] == "MC":
if 'Correct' in qtype[i]:
questions.append(
Question(
pType=1,
pLabel=qtype[i][1],
pAnswers=qtype[i][::2],
cAns=qtype[i][qtype[i].index("Correct") - 1]))
questions[i].answers = questions[i].answers[1:]
else:
questions.append(
Question(
pType=1,
pLabel=qtype[i][1],
pAnswers=qtype[i][::2],
cAns=[]))
questions[i].answers = questions[i].answers[1:]
if qtype[i][0] == "SR": # Short Answer
questions.append(Question(pType=2, pLabel=qtype[i][1], pAnswers=qtype[i][2:], cAns=qtype[i][2]))
if qtype[i][0] == "MA": # Multiple Select
cAns = []
for k in range(len(qtype[i])):
if qtype[i][k] == "Correct":
cAns.append(qtype[i][k - 1])
questions.append(Question(pType=3, pLabel=qtype[i][1], pAnswers=qtype[i][2::2], cAns=cAns))
if qtype[i][0] == "FIB":
cAns = []
j = 2
while j < len(qtype[i]):
cAns.append((qtype[i][j]))
j += 1
questions.append(Question(pType=4, pLabel=qtype[i][1], pAnswers=cAns[0:1], cAns=cAns))
if qtype[i][0] == "TF": # True or False
questions.append(Question(pType=5, pLabel=qtype[i][1], pAnswers=qtype[i][2:], cAns=qtype[i][2]))
if qtype[i][0] == "ESS": # Esaay Question
questions.append(Question(pType=6, pLabel=qtype[i][1], pAnswers=qtype[i][2:], cAns=qtype[i][2]))
i += 1
return questions
def grade_quiz(input, key):
first = []
second = []
with open(key, "r") as f1:
read1 = csv.reader(f1, delimiter='\t') # parse by tab
read1 = (line for line in read1 if line) # ignore blank lines
for ques in read1:
first.append(ques)
with open(input, "r") as f2:
read2 = csv.reader(f2, delimiter='\t') # parse by tab
read2 = (line for line in read2 if line) # ignore blank lines
for questy in read2:
second.append(questy)
i = 0
correct = 0
gradeable=0
while i < len(first):
if first[i][0] == "MC":
gradeable += 1
if first[i] == second[i]:
correct += 1
if first[i][0] == "TF":
gradeable += 1
if first[i] == second[i]:
correct += 1
if first[i][0] == "MA":
j = 3
gradeable += 1
correctCounter = 0
incorrectCounter = 0
studentCorrectCounter = 0
while j < len(first[i]):
if first[i][j] == "Correct":
correctCounter += 1
if first[i][j] == second[i][j] and first[i][j] == "Correct":
studentCorrectCounter += 1 # (1 / ((len(first[i][2:]) / 2)))
elif first[i][j] == "Incorrect" and second[i][j] == "Correct":
incorrectCounter += 1
elif second[i][j] == "Incorrect" and first[i][j] == "Correct":
incorrectCounter += 0
j += 2
if ((1/correctCounter*studentCorrectCounter)-(1/correctCounter*incorrectCounter)) >= 0:
correct += (1/correctCounter*studentCorrectCounter)-(1/correctCounter*incorrectCounter)
else:
correct += 0
i += 1
return round(100 *(correct/gradeable),2)
def send_email(students, assignment):
emails = []
for student in students:
emails.append(student.email)
for i in range(len(emails)):
if assignment.type == 0:
s = smtplib.SMTP('smtp.zoho.com', 587)
s.starttls()
s.login("lmslite.no-reply@gsulms.com", "openLMS2019*")
message = "Subject:{subj}\n\n" \
"{prof} has posted a new {type}.\n" \
"Course: {course}\n" \
"Assignment: {name}\n" \
"Due Date: {date}".format(
subj=assignment.course_id.course_name,
prof=assignment.prof.first_name +" "+ assignment.prof.last_name,
type="Quiz",
course=assignment.course_id.course_name,
name=assignment.assignment_name,
date=assignment.due_date)
elif assignment.type == 1:
s = smtplib.SMTP('smtp.zoho.com', 587)
s.starttls()
s.login("lmslite.no-reply@gsulms.com", "openLMS2019*")
message = "Subject:{subj}\n\n" \
"{prof} has posted a new {type}.\n" \
"Course: {course}\n" \
"Assignment: {name}\n" \
"Due Date: {date}".format(
subj=assignment.course_id.course_name,
prof=assignment.prof.first_name +" "+ assignment.prof.last_name,
type="Survey",
course=assignment.course_id.course_name,
name=assignment.assignment_name,
date=assignment.due_date)
elif assignment.type == 2:
s = smtplib.SMTP('smtp.zoho.com', 587)
s.starttls()
s.login("lmslite.no-reply@gsulms.com", "openLMS2019*")
message = "Subject:{subj}\n\n" \
"{prof} has posted a new {type}.\n" \
"Course: {course}\n" \
"Assignment: {name}\n" \
"Due Date: {date}".format(
subj=assignment.course_id.course_name,
prof=assignment.prof.first_name +" "+ assignment.prof.last_name,
type="Homework",
course=assignment.course_id.course_name,
name=assignment.assignment_name,
date=assignment.due_date)
s.sendmail("lmslite.no-reply@gsulms.com", emails[i], message)
s.quit()
def update_quiz(input, post):
n = 1
for key, value in post.items():
if key.startswith("Question "):
n = n + 1
# prints out each question with answers
with default_storage.open(input, 'w+b') as file:
for i in range(1, n):
for key, value in post.items():
if ('Question%stype' % i) in post:
if post['Question%stype' % i] == '1':
post['Question%stype' % i] = 'MC'
file.write("%s\t%s" % (post['Question%stype' % i], post['Question %s' % i]))
bool = False
for key, value in post.items():
if key == ('Question%sRadioGrp' % i):
bool = True
if key.startswith("Question%sAnswer" % i):
if bool:
file.write("\t{value}\t{val}".format(value=value, val='Correct'))
bool = False
else:
file.write("\t{value}\t{val}".format(value=value, val='Incorrect'))
file.write("\n")
if post['Question%stype' % i] == '2':
post['Question%stype' % i] = 'SR'
file.write("%s\t%s\t%s\n" % (
post['Question%stype' % i], post['Question %s' % i], post['Question%sAnswer1' % i]))
if post['Question%stype' % i] == '3':
post['Question%stype' % i] = 'MA'
file.write("%s\t%s" % (post['Question%stype' % i], post['Question %s' % i]))
for key, val in post.items():
if val in post.getlist('Question%sCheckboxGrp' % i) and key.startswith('Question%sAnswer' %i):
file.write("\t{value}\t{bool}".format(value=(val), bool='Correct'))
elif key.startswith('Question%sAnswer' %i):
file.write("\t{value}\t{bool}".format(value=(val), bool='Incorrect'))
file.write("\n")
if post['Question%stype' % i] == '4':
post['Question%stype' % i] = 'FIB'
file.write("%s\t%s\t%s\n" % (
post['Question%stype' % i], post['Question %s' % i], post['Question%sAnswer1' % i]))
if post['Question%stype' % i] == '5':
post['Question%stype' % i] = 'TF'
file.write("%s\t%s\t%s\n" % (
post['Question%stype' % i], post['Question %s' % i], post['Question%sAnswer1' % i]))
if post['Question%stype' % i] == '6':
post['Question%stype' % i] = 'ESS'
file.write("%s\t%s\t%s\n" % (
post['Question%stype' % i], post['Question %s' % i], " "))
file.close()
def print_grades(id):
sum = 0
row_count = 0
course = Course.objects.get(id=id)
with default_storage.open(course.course_name + '/grade_report.csv', 'w+b') as report:
w = csv.writer(report, quoting=csv.QUOTE_NONE, escapechar='\t')
assignments = list(course.quizes.all()) + list(course.homeworks.all())
assignment_names = []
for assignment in assignments:
assignment_names.append(assignment.assignment_name)
w.writerow(["Student", ','.join(assignment_names), "Grade"])
for student in Course.objects.get(id=id).students.all():
sum = 0
student_grade_list = ['0']*len(assignment_names)
for grade in student.grades.all():
if grade.assignment.course_id == course:
if grade.assignment.assignment_name in assignment_names:
i = assignment_names.index(grade.assignment.assignment_name)
student_grade_list[i] = str(grade.grade_value)
sum = sum + grade.grade_value
if len(student_grade_list) > 0:
average = sum / len(assignment_names)
w.writerow([student.first_name + " " + student.last_name, ','.join(student_grade_list), average])
return report
| {"/courses/forms.py": ["/LMSLite/helpers.py", "/courses/models.py"], "/LMSLite/views.py": ["/courses/models.py"], "/LMSLite/helpers.py": ["/courses/models.py"], "/courses/admin.py": ["/courses/models.py", "/courses/forms.py"], "/courses/views.py": ["/LMSLite/helpers.py", "/courses/models.py", "/courses/forms.py"], "/courses/migrations/0016_auto_20190415_1610.py": ["/courses/models.py"]} |
65,023 | kh06089/2019-LMSLite | refs/heads/master | /accounts/migrations/0010_auto_20190404_2027.py | # Generated by Django 2.1.7 on 2019-04-04 20:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0009_auto_20190404_2021'),
]
operations = [
migrations.AlterField(
model_name='user',
name='profile_photo',
field=models.FileField(blank=True, upload_to='user-profile-photos'),
),
]
| {"/courses/forms.py": ["/LMSLite/helpers.py", "/courses/models.py"], "/LMSLite/views.py": ["/courses/models.py"], "/LMSLite/helpers.py": ["/courses/models.py"], "/courses/admin.py": ["/courses/models.py", "/courses/forms.py"], "/courses/views.py": ["/LMSLite/helpers.py", "/courses/models.py", "/courses/forms.py"], "/courses/migrations/0016_auto_20190415_1610.py": ["/courses/models.py"]} |
65,024 | kh06089/2019-LMSLite | refs/heads/master | /accounts/migrations/0015_auto_20190430_0051.py | # Generated by Django 2.1.7 on 2019-04-30 00:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('courses', '0020_auto_20190430_0043'),
('accounts', '0014_student_quizes'),
]
operations = [
migrations.AddField(
model_name='student',
name='homeworks',
field=models.ManyToManyField(blank=True, default=None, to='courses.Homework'),
),
migrations.AddField(
model_name='student',
name='surveys',
field=models.ManyToManyField(blank=True, default=None, to='courses.Survey'),
),
]
| {"/courses/forms.py": ["/LMSLite/helpers.py", "/courses/models.py"], "/LMSLite/views.py": ["/courses/models.py"], "/LMSLite/helpers.py": ["/courses/models.py"], "/courses/admin.py": ["/courses/models.py", "/courses/forms.py"], "/courses/views.py": ["/LMSLite/helpers.py", "/courses/models.py", "/courses/forms.py"], "/courses/migrations/0016_auto_20190415_1610.py": ["/courses/models.py"]} |
65,025 | kh06089/2019-LMSLite | refs/heads/master | /courses/migrations/0024_merge_20190430_1352.py | # Generated by Django 2.1.7 on 2019-04-30 17:52
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('courses', '0021_assignment_restrict_date'),
('courses', '0023_auto_20190430_1310'),
]
operations = [
]
| {"/courses/forms.py": ["/LMSLite/helpers.py", "/courses/models.py"], "/LMSLite/views.py": ["/courses/models.py"], "/LMSLite/helpers.py": ["/courses/models.py"], "/courses/admin.py": ["/courses/models.py", "/courses/forms.py"], "/courses/views.py": ["/LMSLite/helpers.py", "/courses/models.py", "/courses/forms.py"], "/courses/migrations/0016_auto_20190415_1610.py": ["/courses/models.py"]} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.