Example #1
0
    def collect(self, id_data, id_sentence, id_user, sen_res, token_res_sur,
                token_res_pro, au_size, ex_time, sum_token_res, score):
        try:
            status = 'false'
            mydb = connect()
            mycursor = mydb.cursor()

            # fetch the sentence from database server
            mycursor.execute(
                "INSERT INTO collect_data(id_data,id_sentence,id_user,sen_res,token_res_sur,token_res_pro,au_size,ex_time,sum_token_res,score) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
                (id_data, id_sentence, id_user, sen_res, token_res_sur,
                 token_res_pro, au_size, ex_time, sum_token_res, score))
            mydb.commit()
            status = 'true'

        except mysql.connector.Error as error:
            mydb.rollback()  # rollback if any exception occured
            print(
                "Failed insert record to collect_data table {}".format(error))
        finally:
            # closing database connection.
            if (mydb.is_connected()):
                mycursor.close()
                mydb.close()
                #print("MySQL connection is closed")
            return status
Example #2
0
    def getSentence(self,id):
        try:
            mydb =connect()
            mycursor = mydb.cursor()

            # fetch the sentence from database server
            mycursor.execute(f"SELECT jap_sentence FROM sentence where id_sentence={id}")
            myresult = mycursor.fetchall()

            for row in myresult:
                #id = int(row[0])
                sentence = row[0]
                #time = row[2]

            #obj_sentence = Sentence(id, sentence, time)
            #obj_sentence.display()
            #jsondata = obj_sentence.to_dict_set()
            #jsdata = json.dumps(jsondata, indent=4, sort_keys=True, default=str)
            #js_data = json.loads(jsdata)
            return sentence

        except mysql.connector.Error as error:
            mydb.rollback()  # rollback if any exception occured
            print("Failed Selecting record from python_users table {}".format(error))
        finally:
            # closing database connection.
            if (mydb.is_connected()):
                mycursor.close()
                mydb.close()
                print("MySQL connection is closed")
Example #3
0
    def getLastID(self):
        try:
            id = ""
            mydb = connect()
            mycursor = mydb.cursor()

            # fetch the sentence from database server
            mycursor.execute(
                "SELECT id_data FROM collect_data ORDER BY id_data desc LIMIT 1"
            )
            myresult = mycursor.fetchall()

            for row in myresult:
                id = int(row[0])

            if (id == ""):
                id = 0

        except mysql.connector.Error as error:
            mydb.rollback()  # rollback if any exception occured
            print("Failed Selecting record from collect_data table {}".format(
                error))
        finally:
            # closing database connection.
            if (mydb.is_connected()):
                mycursor.close()
                mydb.close()
                #print("MySQL connection is closed")
            return id


#INSERT INTO collect_data VALUES(1,"委員を選ぶことです","委員を選ぶことです","[委員,を,選ぶ,こと,です]","[委員,を,選ぶ,こと,です]",300000,2000,5,5,1)

#CollectData.collect(CollectData.getLastID()+1,"委員を選ぶことです","委員を選ぶことです","[委員,を,選ぶ,こと,です]","[委員,を,選ぶ,こと,です]",300000,2000,5,5,1)
Example #4
0
    def getuser(self, username, passw):
        try:
            mydb = connect()
            mycursor = mydb.cursor()

            # fetch the sentence from database server
            mycursor.execute("SELECT * FROM user where username=%s AND password=%s",(username, passw))
            myresult = mycursor.fetchall()

            for row in myresult:
                id = int(row[0])
                roles = row[1]
                name = row[2]
                username = row[3]
                passw = row[4]
                time = row[5]


            obj_user = User(id, roles, name, username, passw, time)
            jsondata = obj_user.to_dict_set()
            jsdata = json.dumps(jsondata, indent=4, sort_keys=True, default=str)
            js_data = json.loads(jsdata)

        except Exception as error:
            mydb.rollback()  # rollback if any exception occured
            print("Failed Selecting record from python_users table {}".format(error))
        finally:
            # closing database connection.
            if (mydb.is_connected()):
                mycursor.close()
                mydb.close()
                #print("MySQL connection is closed")
                return (js_data)
Example #5
0
def getQuestionsPaginated(loggedIn, page): 
	'''
	Takes in the current database as a string, a boolean value representing whether or not a SHE is currently logged in, and the question number to start on. 

	Returns a list (ul) string of the questions in the questions table of the database starting from the given start parameter until 10 questions past that. 
	If a SHE is logged in, this list features <edit> buttons, otherwise, it is just a simple list
	'''

	start = (page - 1) * 10 # convert the page value to a "start" value

	conn = dbConnect.connect()
	curs = conn.cursor(MySQLdb.cursors.DictCursor) # results as Dictionaries

	try: 
		fstart = int(start)
		statement = "SELECT DATE_FORMAT(ts, '%W %M %d, %Y') AS formatted_ts, question, answer, id FROM questions WHERE status='completed' ORDER BY ts DESC LIMIT {start}, 10;".format(start=fstart)
		curs.execute(statement)
		lines = []
		lines.append("<ul class='list-group'>")
		while True:
			row = curs.fetchone()
			if row == None: 
				lines.append("</ul>")
				return "\n".join(lines)
			row['ts'] = row['formatted_ts'] # rename formatted_ts to be ts
			if loggedIn: # add the 'edit' button if a SHE is logged in
				lines.append("<li class='list-group-item'><span class='question'>{question}</span><br><br><span class='answer'>{ans}</span><br><br><a class='btn btn-primary' href='answerQuestions.cgi?questionSubmit=True&q_selection={id}' role='button'>Edit Answer</a><br><span class='timestamp'>Asked on: {ts}</span>".format(ts=row['ts'], question=row['question'], ans=row['answer'], id=row['id']))
			else:
				lines.append("<li class='list-group-item'><span class='question'>{question}</span><br><br><span class='answer'>{ans}</span><br><br><span class='timestamp'>Asked on: {ts}</span>".format(ts=row['ts'], question=row['question'], ans=row['answer']))
	except ValueError: # except for when start isn't something that can be parsed into an int
		return "There was an error"
Example #6
0
def connect_db(hostname, username, password, database, charset, cursorType):
    return dbConnect.connect(hostname=hostname,
                             username=username,
                             password=password,
                             database=database,
                             charset=charset,
                             cursorType=cursorType)
Example #7
0
    def __init__(self, url):
        self.headers = {
            "user-agent":
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36"
        }
        self.newsUrl = url
        self.url = requests.get(self.newsUrl, headers=self.headers)
        self.news = self.url.content
        soup = BeautifulSoup(self.news, "html.parser")
        liste = soup.find(
            "div",
            class_="posts-grid posts-grid-3 clearfix").find_all("article")
        self.db = connect()
        self.news_sum = False
        self.news_content = False
        self.news_date = False
        self.news_link = False
        self.current_doc = []
        self.datas = []

        self.my_json = {"neuNews": []}
        with open(r"D:\PycharmProjects\PYTHON\NeuNews.json",
                  "r",
                  encoding="utf-8") as file:
            data = json.load(file)
        for item in data["neuNews"]:
            try:
                self.current_doc.append(item["News Link"])
            except:
                pass
        self.haber(liste)
Example #8
0
    def getscores(self, id_user):
        try:
            list_score = []
            mydb = connect()
            mycursor = mydb.cursor()

            # fetch the sentence from database server
            mycursor.execute(
                "SELECT * FROM score WHERE id_user=%s ORDER BY submitted asc" %
                id_user)
            myresult = mycursor.fetchall()

            for row in myresult:
                list_score.append(
                    Score(id_user, int(row[1]), int(row[2]), (row[3])))

            json_score = [obj.to_dict_set() for obj in list_score]
            jsdata = json.dumps({"list_score": json_score},
                                indent=4,
                                sort_keys=True,
                                default=str)
            jsdataj = json.loads(jsdata)

        except mysql.connector.Error as error:
            mydb.rollback()  # rollback if any exception occured
            print("Failed Selecting record from python_users table {}".format(
                error))
        finally:
            # closing database connection.
            if (mydb.is_connected()):
                mycursor.close()
                mydb.close()
                #print("MySQL connection is closed")
                return jsdataj
Example #9
0
    def getSentences(self,number):
        try:
            list_sentences = []
            mydb =connect()
            mycursor = mydb.cursor()

            # fetch the sentence from database server
            mycursor.execute(f"SELECT id_sentence,jap_sentence,last_update FROM sentence ORDER BY id_sentence asc LIMIT {number} ")
            myresult = mycursor.fetchall()

            for row in myresult:
                list_sentences.append(Sentence(row[0], row[1], row[2]))

            json_listsentence = [obj.to_dict_set() for obj in list_sentences]
            jsdata = json.dumps({"list_sentence": json_listsentence}, indent=4, sort_keys=True, default=str)
            jsdataj = json.loads(jsdata)
            return jsdataj

        except mysql.connector.Error as error:
            mydb.rollback()  # rollback if any exception occured
            print("Failed Selecting record from python_users table {}".format(error))
            jsdataj = 'NULL'
        finally:
            # closing database connection.
            if (mydb.is_connected()):
                mycursor.close()
                mydb.close()
Example #10
0
    def getLastsentence(self):
        try:
            mydb =connect()
            mycursor = mydb.cursor()

            # fetch the sentence from database server
            mycursor.execute("SELECT * FROM sentence ORDER BY id_sentence desc LIMIT 1")
            myresult = mycursor.fetchall()

            for row in myresult:
                id = int(row[0])
                sentence = row[1]
                time = row[2]

            obj_sentence = Sentence(id, sentence, time)
            obj_sentence.display()
            jsondata = obj_sentence.to_dict_set()
            jsdata = json.dumps(jsondata, indent=4, sort_keys=True, default=str)
            js_data = json.loads(jsdata)
            return js_data

        except mysql.connector.Error as error:
            mydb.rollback()  # rollback if any exception occured
            print("Failed Selecting record from python_users table {}".format(error))
        finally:
            # closing database connection.
            if (mydb.is_connected()):
                mycursor.close()
                mydb.close()
Example #11
0
    def addKunci(self, kunci):
        try:
            kunci
            mydb = connect()
            mycursor = mydb.cursor()

            # fetch the sentence from database server
            mycursor.execute(
                f"INSERT INTO kunci(jap_kunci) values (\"{kunci}\") ")

            mydb.commit()
            print("Record inserted successfully into python_users table")
            result = 'true'

        except mysql.connector.Error as error:
            mydb.rollback()  # rollback if any exception occured
            print("Failed inserting record into python_users table {}".format(
                error))
            result = 'false'
        finally:
            # closing database connection.
            if (mydb.is_connected()):
                mycursor.close()
                mydb.close()
                print("MySQL connection is closed")
            return result
def addQuestion(question): 
	'''
	Adds the provided question to the questions table in the given database. 
	'''
	conn = dbConnect.connect()
	curs = conn.cursor(MySQLdb.cursors.DictCursor) # results as Dictionaries
	statement = "INSERT INTO questions (question, status) VALUES (%s, 'not-started');"
	curs.execute(statement, (question,))
Example #13
0
def userExists(username):
	'''
	Returns True if a user exists in the database (checks for username), False otherwise
	'''
	conn = dbConnect.connect()
	curs = conn.cursor(MySQLdb.cursors.DictCursor) # results as Dictionaries
	statement = "SELECT login_id FROM login WHERE login_id = %s;"
	curs.execute(statement, (username,))
	return curs.fetchone()
Example #14
0
def checkInfo(username, password): 
	'''
	Checks that the given login information is correct - returns True or False
	'''
	conn = dbConnect.connect()
	curs = conn.cursor(MySQLdb.cursors.DictCursor) 
	statement = "SELECT login_id FROM login WHERE login_id = %s AND passhash = SHA1(%s);"
	curs.execute(statement, (username, password))
	row = curs.fetchone()
	return row # return whether or not the log in was successful
Example #15
0
def getCompletedCount(): 
	'''
	Returns the number of questions in the questions table for purposes of pagination.
	'''

	conn = dbConnect.connect()
	curs = conn.cursor(MySQLdb.cursors.DictCursor)

	statement = "SELECT count(*) AS total FROM questions where status='completed';"
	curs.execute(statement)
	row = curs.fetchone()
	return row['total']
def getSelectedQuestion(id): 
	'''
		Returns False if the question with the requested id does not exist in the database, returns the question's row otherwise.
	'''

	conn = dbConnect.connect()
	curs = conn.cursor(MySQLdb.cursors.DictCursor)
	statement = "SELECT * FROM questions WHERE id=%s"
	curs.execute(statement, id)
	row = curs.fetchone()
	if row: # only one result
		return row
	else: 
		return False # shouldn't happen
Example #17
0
    def __init__(self):

        self.conn = connect()
        self.cursor = self.conn.cursor()

        #création du logger
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.DEBUG)

        formatter = logging.Formatter(
            "%(asctime)s:%(levelname)s:%(name)s:%(funcName)s:%(message)s")

        fileHandler = logging.FileHandler(
            "/var/www/sio/app/logs/cfast-ath.log", 'w', 'utf-8')
        fileHandler.setFormatter(formatter)

        self.logger.addHandler(fileHandler)
Example #18
0
def getQuestions(): 
	'''
	Takes in the current database as a string and a boolean value representing whether or not a SHE is currently logged in. 

	Returns a list (ul) string of all of the questions in the questions table of the database
	If a SHE is logged in, this list features <edit> buttons, otherwise, it is just a simple list
	'''
	conn = dbConnect.connect()
	curs = conn.cursor(MySQLdb.cursors.DictCursor) # results as Dictionaries
	statement = "SELECT DATE_FORMAT(ts, '%W %M %d, %Y') as formatted_ts, question, answer, id FROM questions WHERE status='completed' ORDER BY ts DESC;"
	curs.execute(statement)
	questions = []
	while True:
		row = curs.fetchone()
		if row == None: 
			return questions
		row['ts'] = row['formatted_ts'] # rename formatted_ts to be ts
		questions.append(row)
Example #19
0
def addUser(database, username, password):
	''' 
	Adds login information to the database for the given username/password

	Returns True if adding the user to the database was successful, false otherwise (username already taken)
	'''
	conn = dbConnect.connect(database, username)
	curs = conn.cursor(MySQLdb.cursors.DictCursor) # results as Dictionaries

	statement = "SELECT login_id FROM login WHERE login_id = %s;"
	curs.execute(statement, username)
	if curs.fetchone(): # username is already taken
		return False

	# if you get to this point, the username is good
	statement = "INSERT INTO login (login_id, passhash) VALUES (%s, SHA1(%s));"
	curs.execute(statement, (username, password))
	return True
def updateAnswer(q_id, answer, update_type): 
	'''
	Adds the provided question to the questions table in the given database. 
	'''
	conn = dbConnect.connect()
	curs = conn.cursor(MySQLdb.cursors.DictCursor)
	statement = "SELECT * FROM questions WHERE id=%s"
	curs.execute(statement, (q_id,))
	row = curs.fetchone() # only one result
	timestamp = row['ts']
	# timestamp automatically changes on update - so you have to replace it with the old value
	if update_type == 'publish':
		statement = "update questions set status='completed', answer=%s, ts=%s where id=%s"
		# change the status to completed
	if update_type == 'save': 
		statement = "update questions set status='in-progress', answer=%s, ts=%s where id=%s"
		# change the status to in-progress
	curs.execute(statement, (answer, timestamp, q_id))
Example #21
0
def addUser(username, password):
	''' 
	Adds login information to the database for the given username/password
	Adds a row to both the login table and the profile_info table

	Returns True if adding the user to the database was successful, false otherwise (e.g. username already taken)
	'''
	conn = dbConnect.connect()
	curs = conn.cursor(MySQLdb.cursors.DictCursor)

	if userExists(username): return False

	# if you get to this point, the username is good
	statement = "INSERT INTO login (login_id, passhash) VALUES (%s, SHA1(%s));"
	curs.execute(statement, (username, password))

	statement = "INSERT INTO profile_info (login_id) VALUES (%s);"
	curs.execute(statement, (username,))
	return True
Example #22
0
    def adduser(self,name, username, password):
        try:
            status="false"
            mydb =connect()
            mycursor = mydb.cursor()

            # fetch the sentence from database server
            mycursor.execute("INSERT INTO `user`(`name`, `username`, `password`) VALUES (%s, %s, %s)",(name, username, password))
            mydb.commit()
            status="true"

        except mysql.connector.Error as error:
            mydb.rollback()  # rollback if any exception occured
            print("Failed Adding record from user table {}".format(error))
        finally:
            # closing database connection.
            if (mydb.is_connected()):
                mycursor.close()
                mydb.close()
                #print("MySQL connection is closed")
                return (status)
def getUnpublishedQuestions(): 
	'''
		Returns a list of the questions if there are questions to answer, otherwise returns False.
	'''
	conn = dbConnect.connect()
	curs = conn.cursor(MySQLdb.cursors.DictCursor) # results as Dictionaries
	statement = "SELECT DATE_FORMAT(ts, '%W %M %d, %Y') as formatted_ts, question, answer, status, id FROM questions WHERE status='not-started' OR status='in-progress' ORDER BY ts DESC;"
	curs.execute(statement)

	questions = []
	count = 0
	while True:
		row = curs.fetchone()
		if row == None: 
			if count > 0: # there were questions to answer
				return questions
			else: 
				return False
		count+=1
		row['ts'] = row['formatted_ts'] # rename formatted_ts to be ts
		questions.append(row)
Example #24
0
    def updateTime(self,id):
        try:
            time = datetime.datetime.now()
            status="false"
            mydb =connect()
            mycursor = mydb.cursor()

            # fetch the sentence from database server
            mycursor.execute(f"UPDATE user SET last_login=%s WHERE id_user=%s",(time,id))
            mydb.commit()
            status="true"

        except mysql.connector.Error as error:
            mydb.rollback()  # rollback if any exception occured
            print("Failed Updating record from user table {}".format(error))
        finally:
            # closing database connection.
            if (mydb.is_connected()):
                mycursor.close()
                mydb.close()
                #print("MySQL connection is closed")
                return (status)
def makeQuestionSelect(database): 
	conn = dbConnect.connect(database, USER)
	curs = conn.cursor(MySQLdb.cursors.DictCursor) # results as Dictionaries
	statement = "SELECT * FROM questions WHERE status='not-started' OR status='in-progress' ORDER BY ts DESC;"
	curs.execute(statement)
	lines = []
	lines.append("<fieldset class='list-group form-group'>")
	count = 0
	while True:
		row = curs.fetchone()
		if row == None: 
			if count > 0: # there were questions to answer
				lines.append("</fieldset>")
				lines.append("<input type='submit' class='btn btn-primary' name=questionSubmit value='Answer Selected Question'>")
				return "\n".join(lines)
			else: 
				return "<div class='signin-alert alert alert-info' role='alert'>There are no questions to answer at this time.</div>"
		count+=1
		lines.append("<div class='list-group-item'><input class='form-control' type='radio' name='q_selection' value={id}> <span class='question'>{question}</span><p>Status: {status}<p>Time submitted: {ts}".format(id=row['id'], question=row['question'], status=row['status'], ts=row['ts']))
		if row['status'] == 'in-progress': 
			lines.append("<p>In-Progress Answer: {curr_answer}".format(curr_answer=row['answer']))
		lines.append("</div>")
Example #26
0
    def setscore(self, id_user, score):
        try:
            status = 'false'
            mydb = connect()
            mycursor = mydb.cursor()

            # fetch the sentence from database server
            mycursor.execute("INSERT INTO score(id_user,score) VALUES(%s,%s) ",
                             (id_user, score))
            mydb.commit()
            status = 'true'

        except mysql.connector.Error as error:
            mydb.rollback()  # rollback if any exception occured
            print("Failed Selecting record from python_users table {}".format(
                error))
        finally:
            # closing database connection.
            if (mydb.is_connected()):
                mycursor.close()
                mydb.close()
                #print("MySQL connection is closed")
                return status
Example #27
0
def getQuestions(database, loggedIn): 
	'''
	Takes in the current database as a string and a boolean value representing whether or not a SHE is currently logged in. 

	Returns a list (ul) string of all of the questions in the questions table of the database
	If a SHE is logged in, this list features <edit> buttons, otherwise, it is just a simple list
	'''
	conn = dbConnect.connect(database, USER)
	curs = conn.cursor(MySQLdb.cursors.DictCursor) # results as Dictionaries
	statement = "SELECT DATE_FORMAT(ts, '%W %M %d, %Y') as formatted_ts, question, answer, id FROM questions WHERE status='completed' ORDER BY ts DESC;"
	curs.execute(statement)
	lines = []
	lines.append("<ul class='list-group'>")
	while True:
		row = curs.fetchone()
		if row == None: 
			lines.append("</ul>")
			return "\n".join(lines)
		row['ts'] = row['formatted_ts'] # rename formatted_ts to be ts
		if loggedIn: # add the 'edit' button if a SHE is logged in
			lines.append("<li class='list-group-item'><span class='question'>{question}</span><br><br><span class='answer'>{ans}</span><br><br><a class='btn btn-primary' href='answerQuestions.cgi?questionSubmit=True&q_selection={id}' role='button'>Edit Answer</a><br><span class='timestamp'>Asked on: {ts}</span>".format(ts=row['ts'], question=row['question'], ans=row['answer'], id=row['id']))
		else:
			lines.append("<li class='list-group-item'><span class='question'>{question}</span><br><br><span class='answer'>{ans}</span><br><br><span class='timestamp'>Asked on: {ts}</span>".format(ts=row['ts'], question=row['question'], ans=row['answer']))
Example #28
0
    def removeSentences(self, id_str):
        try:
            id = int(id_str)
            mydb =connect()
            mycursor = mydb.cursor()
            # fetch the sentence from database server
            mycursor.execute(f"DELETE FROM sentence WHERE  id_sentence=({id})")

            mydb.commit()
            print(f"Row with id={id} deleted successfully")
            result = 'true'

        except mysql.connector.Error as error:
            mydb.rollback()  # rollback if any exception occured
            print("Failed delete row from sentence table {}".format(error))
            result = 'false'
        finally:
            # closing database connection.
            if (mydb.is_connected()):
                mycursor.close()
                mydb.close()
                #print("MySQL connection is closed")
            return result
Example #29
0
def getProfileContent(canEdit): 
	'''
	Returns the name to display in the "About X" string (username if there is no name in the database) as the 
	first element in a tuple, and the page content for the the person's profile page as the second element. 

	canEdit is a boolean that represents whether or not the logged in user is looking at their own page, and therefore
	should have editing capabilities.
	'''

	conn = dbConnect.connect()
	curs = conn.cursor(MySQLdb.cursors.DictCursor)
	statement = "SELECT * FROM profile_info WHERE login_id=%s;"
	curs.execute(statement, (username,))
	row = curs.fetchone() # should only be one result
	name = row['name']
	about = row['about']
	class_year = row['class_yea r']

	if not name: name = row['login_id'] # if there is not a name in the database, treat the login_id as the name for displaying purposes

	if row: # double check, tho
		if canEdit: # make editable fields
			content += "<form method=post action='profile.cgi?user="******"'><fieldset class='form-group'>"
			content += "<label for='name'>Name</label><input name='name' class='form-control' value='" + name + "'>"
			content += "<label for='class_year'>Class Year</label><input name='class_year' class='form-control' value='" + class_year_placeholder + "' maxlength='4'>"
			# content += "<label for='picfile'>Profile Image</label><input type='file' name='picfile'>"
			content += "<label for='about'>About</label><textarea class='form-control' name='about' rows='10'>"+about_placeholder+"</textarea>"
			content += "</fieldset><input type='submit' class='btn btn-primary' name='update' value='Update'></form>"
		else: # just display the content
			if class_year: 
				content += "<p><i>Class of " + class_year + "</i>"
			if about:
				content += "<p><b>About:</b><p>" + about
			else: 
				content += "<p>This user has no about at the moment."
	return (name, content)
Example #30
0
def getSHEs(): 
	'''
	documentation needed
	'''
	conn = dbConnect.connect()
	curs = conn.cursor(MySQLdb.cursors.DictCursor)
	statement = "SELECT * FROM login;"
	curs.execute(statement)
	allSHEs = []
	while True:
		row = curs.fetchone()
		if row == None: 
			return allSHEs
		else:
			# try to get the name from the profile_info table, and display that. Otherwise display the username.
			info_curs = conn.cursor(MySQLdb.cursors.DictCursor)
			info_statement = "SELECT name FROM profile_info WHERE login_id = %s"
			info_curs.execute(info_statement, (row['login_id'],))
			info_row = info_curs.fetchone()
			name = info_row['name']
			if name: 
				allSHEs.append({'login_id': row['login_id'], 'name': name})
			else:
				allSHEs.append({'login_id': row['login_id']})
def makeAnswerForm(database, id): 
	conn = dbConnect.connect(database, USER)
	curs = conn.cursor(MySQLdb.cursors.DictCursor)
	statement = "SELECT * FROM questions WHERE id=%s"
	curs.execute(statement, id)
	row = curs.fetchone()
	if row: # only one result
		s = "<fieldset class='form-group'>"
		s += "<p class='question'>{q}</p><br><br>".format(q=row['question'])
		s += "<input type=text name='id' value={id} style='display:none'>".format(id=row['id'])
		s += "<label for='answer'>Answer:</label><br>"
		if row['status'] == 'in-progress' or row['status'] == 'completed': # if an answer already exists, complete or not 
			s += "<textarea class='form-control' name='answer' cols='40' rows='10'>{ans}</textarea><br>".format(ans=row['answer'].replace('<br />', '\n'))
		else: 
			s += "<textarea class='form-control' name='answer' cols='40' rows='10'></textarea><br>"
		s += "</fieldset><div class='btn-group' role='group'>"
		if row['status'] == 'completed': 
			s += "<input class='btn btn-primary' type='submit' name='save' value='Unpublish & Save'>"
		else: 
			s += "<input class='btn btn-primary' type='submit' name='save' value='Save'>"
		s += "<input class='btn btn-primary' type='submit' name='publish' value='Publish'></div>"
		return s
	else: 
		return "ERROR: couldn't find selected question in the database" # shouldn't happen
        print "End processing"
        
        
        ret = [ ret_date, ret_time, ret_lat, ret_lon, ret_alt, ret_sp, ret_temp, ret_press, ret_head, ret_gy, ret_ac, count ]
        self.prev_data = ret
        return ret
        
    def err_process(self,   data):
        length = len(data)
        if length >= 1:
            return data[length-1]
        else:
            return "---"
            
    def better_process(self, data):
        length = len(data)
        a = 0.8
        datum = float(data[0])
        if length >= 3:
            for i in range(1, length):
                datum = a*data[i-1] + (1 - a)*datum
        return float(datum)
            
        
if __name__ == '__main__':
    
    db = dbConnect.connect()
    dbLink.createRawTable(db)
    p = Processor(db)
    p.process(0)
Example #33
0
        data = json.dumps(info)

        #! a décommenter pour lancer la requête
        # res_insertRef = requests.put(insertRef, data=data ,headers=headers)
        # if (res_insertRef.status_code == 200):
        #     result += "--Put info: OK \n"
        # else:
        #     result += "Error: %s, %s \n" % (res_insertRef.status_code, res_insertRef)

    print(result)


#* ------ /Functions ------- *#

#* ------ Main ------- *#
conn = connect()  #initialise la connection à la bdd Athénéo

# Récupération depuis le fichier CSV
refsCfast = []
refsInternesCeso = []

#récupération des données depuis le fichier csv
with open('cfast-api/test.csv', encoding="utf-8") as csvDataFile:
    csvReader = csv.reader(csvDataFile)
    for row in csvReader:
        refsCfast.append(row[0])
        refsInternesCeso.append(row[1])

#* Action sur l'api

#TODO Faire des fonction dans le fichier insertRefforClient
Example #34
0
            diff = from_df.difference(from_db)
            inter = from_db.intersection(from_df)

            print("insert : ", diff)
            if len(diff) > 0:
                insert_to_db(diff, cur, conn, df_dict)

            print("update : ", inter)
            if len(inter) > 0:
                if cols:
                    update_db_col(inter, cur, conn, df_dict, cols)
                else:
                    update_db(inter, cur, conn, df_dict)

    except Exception as e:
        print(e)


if __name__ == "__main__":
    cur, conn = connect()

    # create_yotpo_reviews_src(cur,conn)
    # populate_data(cur,conn)
    # print(select_query(cur,conn))
    # print(conn.encoding)
    # conn.close()
    # df = pd.read_csv("dummy.csv")
    # col = ['marks']
    # inter = {1,2}
    # update_db_col(inter,cur,conn,df,col)
Example #35
0
    def __init__(self, master):
        self.master = master
        master.title("GOATS GUI")
        self.w, self.h = self.master.winfo_screenwidth()-100, self.master.winfo_screenheight()-100
        self.master.geometry("%dx%d+0+0" % (self.w, self.h))
        self.master.state("zoomed")


        self.cursor = dbConnect.connect().cursor()

        self.colors = colors = ["#2EF004", "#5DEF03", "#8AEE03", "#B8ED02",
            "#E5EB02", "#EAC201", "#E99301", "#E76500", "#E63600", "#E50800"]

        self.imageLoc = None
        self.imageLocationOptions = self.setLocations()
        self.imageMeasurementOptions = ["None"]
        self.imageLabel = None
        self.imagesFromMeasurements= {"None": None}
        self.graphDataOptions = ["Health", "Insects"]
        self.graphDataLocations = self.setLocations()[1:]
        self.graphLoc = self.graphDataLocations[0]
        self.graphType = self.graphDataOptions[0]
        self.data = [[],[]]
        self.graphCanvas = None
        self.graph_toolbar = None
        self.figure = None
        self.ax = None

        self.tabs = self.form_notebook()

        self.grid_db_data()
        self.refOne = tk.Button(self.tabs[0], text="Refresh", command=self.refreshOne)
        self.refOne.place(relx=.9, rely=.9)

        self.draw_graph()
        self.refTwo = tk.Button(self.tabs[1], text="Refresh", command=self.refreshTwo)
        self.refTwo.place(relx=.9, rely=.9)

        self.graphDataMenu = ttk.Combobox(self.tabs[1], values=self.graphDataOptions, state="readonly")
        self.graphDataMenu.current(0)
        self.graphDataMenu.pack()

        self.graphDataMenuLocation = ttk.Combobox(self.tabs[1], values=self.graphDataLocations, state="readonly")
        self.graphDataMenuLocation.current(0)
        self.graphDataMenuLocation.pack()

        self.subTwo = tk.Button(self.tabs[1], text="Submit", command=self.update_graph)
        self.subTwo.pack()

        self.draw_image()
        self.refThree = tk.Button(self.tabs[2], text="Refresh", command=self.refreshThree)
        self.refThree.place(relx=.9, rely=.9)

        self.imageLocationOptionMenu = ttk.Combobox(self.tabs[2], values=self.imageLocationOptions, state="readonly")
        self.imageLocationOptionMenu.current(0)
        self.imageLocationOptionMenu.grid(row=2, column=1)
        self.subThree = tk.Button(self.tabs[2], text="Submit", command=self.resetImageLocationOptions)
        self.subThree.place(y=25)

        self.imageMeasurementOptionMenu = ttk.Combobox(self.tabs[2], values=self.imageMeasurementOptions, state="disabled")
        self.imageMeasurementOptionMenu.current(0)
        self.imageMeasurementOptionMenu.grid(row=2, column=1)
        self.imageMeasurementOptionMenu.place(y=50)
        self.subThreeTwo = tk.Button(self.tabs[2], text="Submit", command=self.resetImageMeasurementOptions)
        self.subThreeTwo.place(y=75)
        self.subThreeTwo.config(state='disabled')
Example #36
0
from datetime import datetime, date, timedelta
import urllib3
urllib3.disable_warnings()

today = date.today()
today = today.strftime("%d-%m-%Y")
TEST_CUT_OFF_DATE = datetime.strptime(today, '%d-%m-%Y')
COUNT = 0
MAX_COUNT = 500
FIELD = ""

FORMAT = '%(asctime)-15s  %(message)s'
logging.basicConfig(filename='cve.log', format=FORMAT)
logger = logging.getLogger('vce_log')

conn = db.connect()


def getNewCVEs(min_date, max_date):
    headers = {
        "time_modifier": "between",
        "time_start": min_date,
        "time_end": max_date,
        "time_type": FIELD,
        "cvss_modifier": "above",
        "cvss_score": "4",
        "limit": "100",
        "data": "json"
    }
    r = requests.get('https://cve.circl.lu/api/query',
                     headers=headers,
Example #37
0
def timed_job():
    #start_time = time.time()
    connect()
Example #38
0
def updateInfo(username, name, class_year, about):
	conn = dbConnect.connect()
	curs = conn.cursor(MySQLdb.cursors.DictCursor)
	statement = "UPDATE profile_info SET name=%s, about=%s, class_year=%s WHERE login_id=%s;"
	curs.execute(statement, (name, about, class_year, username))
Example #39
0
    def __init__(self):
        #GPIO Setup
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(12,GPIO.IN,pull_up_down=GPIO.PUD_DOWN)
        GPIO.setup(22,GPIO.IN,pull_up_down=GPIO.PUD_DOWN)
        
        GPIO.add_event_detect(12, GPIO.RISING, callback=self.buttonEvent, bouncetime=1000)
        GPIO.add_event_detect(22, GPIO.RISING, callback=self.saveEvent, bouncetime=1000)
        
        #Sensor Instantiation
        self.accSensor   = accel.Accelerometer()
        self.magSensor   = mag.Magnetometer()
        self.gyroSensor  = gyro.Gyroscope()
        self.pressSensor = press.Pressure()
        self.tempSensor  = temp.Temperature()

        #Calibrate
        self.cal = process_bmp.bmp_processor()
        self.cal.calibrate(self.pressSensor.press)

        #Create the databases
        self.db = dbConnect.connect()
        dbLink.createRawTable(self.db)
        dbLink.createProcessedTable(self.db)
        dbLink.createSaveTable(self.db)
        dbLink.createDateTime(self.db)
    
        #Processor
        self.processor = process.Processor(self.db, self.cal)
        self.last_index = 0
        
        #Set the GPS poller
        self.gpsP = gpsPoll.GpsPoller()

        self.common_delay_time = 0.5
        
        #Initialize the display
        self.edisplay = edisplay.EDisplay()
        
        #Initialize sensor vars
        self.acc = 0
        self.gyro = 0
        self.temp = 0
        self.press = 0
        self.mag = 0
        
        #Initialize gps vars
        self.date = 0
        self.time = 0
        self.lat = 0
        self.lon = 0
        self.speed = 0
        self.alt = 0
        
        self.key_in = 0
        
        self.disp_data = [0,0,0,0,0,0,0,0,0,0,0]
        self.saving_text = "no"
        
        
        self.start_data = True
        self.saving_flag = "no"
        #Initialize saving vars
        self.saving = False
        self.saveStartTime = 0
        self.saveStartDate = 0
        self.saveEndTime = 0
        self.saveEndDate = 0