Beispiel #1
0
 def view(self, noteid=""):
     notetext = {}
     dbmgr = DatabaseManager("scribler.db")
     for row in dbmgr.query("select * from notes where _id = '" + noteid + "'"):
         notetext["title"] = row[1]
         notetext["body"] = row[2]
     return notetext
 def concept_as_rdf(self, REQUEST, cp, ns="1"):
     """ Return a concept in RDF format """
     conn = DatabaseManager()
     try:
         conn.openConnection(self)
     except OperationalError, error:
         return None
Beispiel #3
0
 def delete(self, noteid="", allnotes="one"):
     dbmgr = DatabaseManager("scribler.db")
     if allnotes == "one":
         status = dbmgr.query(
             "delete from notes where _id = '" + noteid + "'")
     else:
         status = dbmgr.query("delete from notes")
     return status.rowcount
 def getDefinitionSources(self):
     """ return definition sources """
     conn = DatabaseManager()
     try:
         conn.openConnection(self)
     except OperationalError, error:
         # write log
         return ({}, 1)
 def GetAllRelations(self):
     """ return all relations """
     conn = DatabaseManager()
     try:
         conn.openConnection(self)
     except OperationalError, error:
         # write log
         return ((), 1)
Beispiel #6
0
 def GetBackbone(self):
     """ return data for backbone.rdf """
     conn = DatabaseManager()
     try:
         conn.openConnection(self)
     except OperationalError, error:
         #write log
         return ((), 1)
Beispiel #7
0
    def GetConceptName(self, concept_ns, concept_id, langcode):
        """ return a concepts name in requested language """

        conn = DatabaseManager()
        try:
            conn.openConnection(self)
        except OperationalError, error:
            #write log
            return (0, 1)
 def getAlphabet(self, lang, theme, case, theme_ns=""):
     """ return the alphabet (default small letters) for a given language """
     conn = DatabaseManager()
     try:
         conn.openConnection(self)
     except OperationalError, error:
         # write log
         conn.closeConnection()
         return ((), [], 1, "")
    def GetLanguageDirection(self, lang):
        """ get a language by its code """

        conn = DatabaseManager()
        try:
            conn.openConnection(self)
        except OperationalError, error:
            # write log
            return ({}, 1)
Beispiel #10
0
    def GetConceptsName(self, langcode, start=0, letter=0, ns=1):
        """ return the concepts name for a given language """

        conn = DatabaseManager()
        try:
            conn.openConnection(self)
        except OperationalError, error:
            #write log
            return ((), [], 1)
    def GetLanguages(self, concept_ns=None, concept_id=None):
        """ get languages """

        conn = DatabaseManager()
        try:
            conn.openConnection(self)
        except OperationalError, error:
            # write log
            return None
 def GetGroupsAndThemes(self, langcode):
     """ return all the groups and all the themes for a given language """
     errors = 0
     conn = DatabaseManager()
     try:
         conn.openConnection(self)
     except OperationalError, err:
         # write log
         errors = 1
         return ((), (), (), err)
Beispiel #13
0
    def GetGroupConcepts(self, params, langcode=None, REQUEST=None):
        """ return all the narrower concepts beloging to a group """

        relations = []
        top_cp = []

        conn = DatabaseManager()
        try:
            conn.openConnection(self)
        except OperationalError, error:
            self.error_log.raising(sys.exc_info())
            return ((), 1)
def main(argv):
	opts = get_command_args(argv)
	dm = DatabaseManager()

	if (opts['data']):
		pprint(dm.get_data(opts['redcap']))
	if (opts['match']):
		pprint(dm.get_matches(opts['redcap'],opts['bool'],opts['value']))
	if (opts['search']):
		pprint(dm.get_searches(opts['redcap'],opts['bool'],opts['value']))

	if (opts['mach']):
		pprint(dm.get_ml_data(opts['redcap']))
def main():

	print "Reading minID"
	fp = open('ids.txt', 'r')
	for line in fp:
		ids = line.strip().split(",")
		minID = ids[0]
		maxID = ids[1]
	fp.close()

	print "minID: ", minID
	print "maxID: ", maxID

	dbm = DatabaseManager()

	print "running query..."

	places = dbm.runQuery("SELECT id, bounding_box FROM Places \
						   WHERE lat_1 IS NULL AND id >= {0} AND id < {1}".format(minID, maxID))

	print "query done!"
	cont = 0.0;

	for row in places:
		try:
			idPlace = row[0]
			bounding_box = row[1]
			tmp = re.sub(r'u\'','\'', bounding_box)
			tmp = re.sub(r'\'','"', tmp)
			obj = json.loads(tmp)
			box_coords = obj['coordinates'][0]
			
			lat_1 = box_coords[0][1]
			long_1 = box_coords[0][0]
			lat_2 = box_coords[1][1]
			long_2 = box_coords[1][0]
			lat_3 = box_coords[2][1]
			long_3 = box_coords[2][0]
			lat_4 = box_coords[3][1]
			long_4 = box_coords[3][0]

			query = u"""UPDATE Places SET lat_1={0}, long_1={1}, lat_2={2}, long_2={3},lat_3={4}, long_3={5}, lat_4={6}, long_4={7} WHERE id = {8}""".format(lat_1, long_1, lat_2, long_2, lat_3, long_3, lat_4, long_4, idPlace)
			
			print cont

			dbm.runCommit(query)

		except Exception as e:
			print "error with id=", row[0]
			print e
		cont += 1
Beispiel #16
0
    def GetGroups(self, langcode=None, REQUEST=None):
        """ return all the super_groups with all their childrens """

        results = {} #{(id_super, def_super):[{id:id_group, def:def_group},...]}

        if langcode is None:
            return ((), 1)

        conn = DatabaseManager()
        try:
            conn.openConnection(self)
        except OperationalError, err:
            self.error_log.raising(sys.exc_info())
            return ((), 1)
Beispiel #17
0
    def GetThemeConcepts(self, theme, langcode, start=0, letter=0, namespace=4):
        """ return all the concepts for a given theme tagged with their language """

        def wrap_concept(concept):
            return concept

        th_name = ''

        conn = DatabaseManager()
        try:
            conn.openConnection(self)
        except OperationalError, error:
            #write log
            return ((), [], 1, '')
Beispiel #18
0
    def GetThemes(self, lang=None, REQUEST=None, namespace=4):
        """ return all the themes for a given langcode """

        flag = 0
        if lang is None:
            return ((), 1)

        conn = DatabaseManager()
        conn.openConnection(self)

        try:
            res = self._get_themes(namespace, lang, conn)
        except OperationalError, err:
            print err
            flag = 1
    def __init__(self, subreddit, username, db_name, debug=False):

        '''
            initializer for the ReputationManager
            pre:  the subreddit it's going to manage in, and the name of the database
                  and if debug mode is turned on or not, default is False
            post: the ReputationManager class is initialized
        '''

        user_agent = 'Reputation-Manager v1.2.1 /u/cutety'
        self.r = praw.Reddit(user_agent=user_agent,log_requests=0)
        self.o = OAuth2Util.OAuth2Util(self.r, print_log=False)
        self.subreddit = subreddit
        self.username = username
        print('Initializing database...')
        self.db = DatabaseManager(db_name)

        # the functions are associated with the identifiers position in this list
        # this is done so identifier can be changed at anytime and the same function
        # will be done without having to change any other code
        self.identifiers = ['!offer', '!accept', '!success', '!scam', '!report',
                            '!cancel', '!retract']

        # configure logging
        logging.basicConfig(filename='REPMLog.log',
                            level=logging.DEBUG,
                            format='%(asctime)s %(message)s')
        self.debug = debug
Beispiel #20
0
def db_setup(db_name: str) -> None:
    try:
        # access db
        with DatabaseManager(db_name) as db:
            # create a table for input files archives
            db.execute("""CREATE TABLE IF NOT EXISTS input_reports(
                        date TEXT, 
                        hours_worked REAL, 
                        employee_id INTEGER, 
                        job_group TEXT,
                        PRIMARY KEY (date, employee_id, job_group))""")

            # create a table for storing unique report ids
            db.execute("""CREATE TABLE IF NOT EXISTS report_ids(
                       id INTEGER,
                       PRIMARY KEY (id))""")

            # create a table for job groups
            db.execute("""CREATE TABLE IF NOT EXISTS job_group(
                       job_group TEXT,
                       rate REAL,
                       PRIMARY KEY (job_group))""")

            # insert data for job group table
            db.execute(
                """INSERT OR IGNORE INTO job_group VALUES('A', 20), ('B', 30)"""
            )

    except sqlite3.Error as e:
        print("db_setup Error: %s" % e.args[0])
        db.__exit__()

    print("------ Finish Database Setup -------")
Beispiel #21
0
  def run(self):
    self._running = True
    while self._running:
      try:
        restQuery = self._socket.recv(1024)
        print restQuery
      except Exception as exc:
        print self._socket.getsockname(), exc
        break

      # Database connection
      db = DatabaseManager(DatabaseConfig.host)

      # Get SQL Query from REST
      sqlQuery = DatabaseManager.getSQLqueryFromREST(restQuery)

      # Get the result from SQL Server
      carObjects = db.SelectFromDatabase(sqlQuery)

      # Build a JSON String from the result
      jsonString = JSONBuilder.getJSON(carObjects)

      #Send to the server the result
      self._socket.send(jsonString)

    self._socket.close()
Beispiel #22
0
    def get_soil_humidity(self):
        ir = InputReader()

        res = ir.read_analogic_sensor(analog_pin["soil_humidity"])
        db = DatabaseManager()

        if (res <= 200):
            valDB = db.store_moisture(0)
            return 0
        elif (res >= 510):
            valDB = db.store_moisture(100)
            return 100
        else:
            temp = (10 * res - 2000) / 31
            valDB = db.store_moisture(int(temp))
            return int(temp)
Beispiel #23
0
class UpdateALayout(tkinter.Frame):
    def __init__(self, tkinter, row=0, column=0):
        super().__init__(tkinter)
        self.databaseM = DatabaseManager()
        self.parent = tkinter
        self.row = row
        self.column = column
        self.create_layout()

    def create_layout(self):
        label = tkinter.Label(self.parent,
                              text="Aktualizovat vybrané anime",
                              font=Font(size=40))
        label.grid(row=self.row,
                   column=self.column,
                   columnspan=self.column + 2)

        label = tkinter.Label(self.parent,
                              text="Vyber anime, které chceš aktualizovat")
        label.grid(row=self.row + 1, column=self.column)

        self.select_anime = ttk.Combobox(
            self.parent, value=self.databaseM.return_database())
        self.select_anime.grid(row=self.row + 1, column=self.column + 1)

    def update_data(self):
        self.create_layout()
    def handle_jawbone_login(self, data):
        c = Client(token_endpoint='https://jawbone.com/auth/oauth2/token',
                   client_id='nEXyCKO3F3s',
                   client_secret='c9a66fc619ccb0e7c2c4e90e59200dfba8aea5de',
                   token_transport=transport_headers)
        c.request_token(grant_type='authorization_code', code=data['code'])

        #createInfo(c.access_token,c.token_expires)
        query = DatabaseManager('key.db')
        #maybe check if table doesn't exist and create it in DBMR__init__)
        query.updateInfo("UPDATE userinfo SET key = ?, expires = ?",
                         c.access_token, c.token_expires)
        del query

        self.dump_client(c)
        return
Beispiel #25
0
def get_report_id_from_db(db_name: str) -> list:
    with DatabaseManager(db_name) as db:
        db.execute("SELECT * FROM report_ids")
        tup = db.fetchall()
        # convert tuples to a list
        result = list(sum(tup, ()))
        return result
Beispiel #26
0
    def GetConceptDetails(self, concept_id, langcode, concept_ns=1):
        """ return all the information available for a given concept """
        nt_list = []
        bt_list = []
        rt_list = []
        ct_name = {}
        ct_trans = []
        ct_definition = ''
        ct_note = ''
        errors = 0

        conn = DatabaseManager()
        try:
            conn.openConnection(self)
        except OperationalError, error:
            #write log
            return ({}, [], [], [], [], '', '', '', (), (), (), (), 1)
Beispiel #27
0
 def __init__(self, parent):
     super().__init__(parent)
     self.parent = parent
     self.dManager = DatabaseManager()
     self.parent.title("Moje anime")
     self.parent.minsize(900, 600)
     self.parent.resizable(True, True)
     self.create_widgets()
Beispiel #28
0
    def __init__(self, filename: str):
        super().__init__()
        self.setupUi(self)
        self.setWindowModality(qtc.Qt.ApplicationModal)  # block input to all other windows
        self.setWindowFlag(qtc.Qt.Window)  # dialog box without min or max buttons
        self.setWindowFlag(qtc.Qt.FramelessWindowHint)  # borderless window that cannot be resized

        self.__filename = filename

        self.__db_manager = DatabaseManager(self.__filename)

        self.__timer = qtc.QTimer()       # a timer to display messages for a designated amount of time
        self.__timer.setSingleShot(True)

        # Set up the model-view structure for the 'Checked In' list.
        # As the data in the model changes, the view is updated automatically.
        # The QStringListModel is the easiest to implement since it does not require a customized model.
        checked_in_list = self.get_checked_in_list()
        self.__checked_in_model = qtc.QStringListModel(checked_in_list)
        self.checkedInList.setModel(self.__checked_in_model)

        self.checkedInList.setFocusPolicy(qtc.Qt.NoFocus)
        self.checkedInList.setVerticalScrollBarPolicy(qtc.Qt.ScrollBarAlwaysOn)
        self.checkedInList.setHorizontalScrollBarPolicy(qtc.Qt.ScrollBarAlwaysOff)
        self.checkedInList.setAutoScroll(False)
        self.checkedInList.setAutoScrollMargin(400)
        self.checkedInList.setEditTriggers(qtw.QAbstractItemView.NoEditTriggers)
        self.checkedInList.setSelectionMode(qtw.QAbstractItemView.NoSelection)

        self.barcode.setEchoMode(qtw.QLineEdit.Password)  # hide the barcode number that was scanned, like a password

        # When a barcode is scanned, the 'returnPressed' signal emits which calls the 'barcode_scanned' slot.
        self.barcode.returnPressed.connect(lambda: self.barcode_scanned(self.barcode.text()))

        # Use the timer to clear the message. The self.refresh_window() method will start the timer.
        # The static method qtc.QTimer.singleShot() will perform a similar operation, however
        #   if two students check in within the allotted time (3 seconds in this case)
        #   then the first message will be cut short (as it should be) but
        #   the second message will only display for the remaining time from the first message.
        self.__timer.timeout.connect(self.message.clear)

        if platform.system() == 'Windows':
            self.show()
        else:
            self.showFullScreen()
        self.check_database()  # check if the database file exists after the main window displays
Beispiel #29
0
def getDataFromGitHubIntoDB(repositoryName):

    manager = GitConnectionManager()

    collaboratorData = GitCollaboratorData(
        manager.getConnection()).getCollaboratorData(repositoryName)
    print("Got Collaborator Data !")
    commitData = GitCommitData(
        manager.getConnection()).getCommitData(repositoryName)
    print("Got Commit Data !")
    (pullRequestData, pullReviewData) = GitPullRequestData(
        manager.getConnection()).getPullRequestData(repositoryName)
    print("Got Pull Request Data !")

    DatabaseManager.populateRepository(repositoryName, collaboratorData,
                                       commitData, pullRequestData,
                                       pullReviewData)
    print("Data Inserted !")
Beispiel #30
0
class Server():
    def __init__(self):
        self.initQueues()
        print('[ SERVER ] Making a connection to Database...')
        self.dbConncetion = DatabaseManager()
        print('[ SERVER ] Initialising Gateway...')
        self.gatewayConnection = Gateway(self.dbConncetion, self.requestQueue,
                                         self.responseQueue)

    def initQueues(self):
        self.requestQueue = multiprocessing.Queue(1000)
        self.responseQueue = multiprocessing.Queue(1000)

    def waitForExit(self):
        print('[ SERVER ] Exiting...')
        self.gatewayConnection.processExit()
        self.dbConncetion.closeConnection()
        print('[ SERVER ] Closed.')
    def setUp(self):
        sqlite_file = 'test.db'
        self.db = DatabaseManager(sqlite_file, '__ADMIN__')

        filename = "Test_Files/DatabaseManagerTest_15.csv"
        self.ingestor = Ingestor(filename)
        self.ingestor.readCSV()

        tempHeaders = self.ingestor.getCSVHeaders()
        self.searchCritera = [
            tempHeaders[0], tempHeaders[1], tempHeaders[2], tempHeaders[4],
            tempHeaders[5], tempHeaders[6]
        ]
        searchCriteraTwoD = self.ingestor.getHeaderIndex(
            self.searchCritera, tempHeaders)
        self.ingestor.searchRows(searchCriteraTwoD, self.ingestor.getRows())
        self.searchCritera = self.db.remove_spaces(self.searchCritera)
        self.new_table = 'Test_15'
 def __init__(self, redcap, directory, articles, searchwords=[]):
     self.articles = articles
     self.directory = directory
     ml_data = DatabaseManager().get_ml_data(redcap)
     if (not searchwords):
         self.allwords = self.get_allwords()
     else:
         self.allwords = searchwords
     self.train(redcap, ml_data)
Beispiel #33
0
    def run(self):

        print("Comment Stream Thread Started")

        if self.sub is None:
            return

        while True:
            metaList = RedditManager.fetchCommentMetaRecent(self.sub)

            DatabaseManager.updateCommentList(metaList)

            for post_meta in metaList:
                DatabaseManager.ensure_user_exists(post_meta.username,
                                                   post_meta.subreddit)

            time.sleep(10)

            pass
Beispiel #34
0
 def __init__(self, parent):
     super().__init__(parent)
     self.parent = parent
     self.dManager = DatabaseManager()
     self.parent.title("Anime page")
     self.parent.minsize(900, 600)
     self.parent.resizable(True, True)
     self.addAnimeL = None
     self.selectL = None
     self.create_widgets()
    def __init__(self, window_title, db_file_loc, tables,
                 protected_table_prefix):
        super().__init__()
        #Creating the window
        self.title = window_title
        self.setWindowTitle(self.title)
        self.protected_table_prefix = protected_table_prefix
        self.tablesInDB = tables
        #Database manager stuff
        self.db = DatabaseManager(db_file_loc, protected_table_prefix)

        #Create array with tables already in the database to be
        #put in the common files radio button box
        self.default_lists = []
        for table in tables:
            tempList = []
            for columnName in self.db.get_headers(table):
                tempList.append(columnName)
            self.default_lists.append(tempList)

        self.layout = QGridLayout()
Beispiel #36
0
    def viewallskip(self, limit=1, offset=1):
        listtext = []
        dbmgr = DatabaseManager("scribler.db")
        if limit == 1:
            for row in dbmgr.query("select * from notes"):
                notetext = {}
                notetext["_id"] = row[0]
                notetext["title"] = row[1]
                notetext["body"] = row[2]
                notetext["datecreated"] = row[4]
                listtext.append(notetext)
        elif limit > 1:
            for row in dbmgr.query("select * from notes limit '" + str(limit) + "' OFFSET '" + str(offset) + "'"):
                notetext = {}
                notetext["_id"] = row[0]
                notetext["title"] = row[1]
                notetext["body"] = row[2]
                notetext["datecreated"] = row[4]
                listtext.append(notetext)

        return listtext
Beispiel #37
0
    def searchskip(self, query="", limit=1, offset=1):
        listtext = []
        dbmgr = DatabaseManager("scribler.db")
        if limit == 1:
            for row in dbmgr.query("select * from notes where title LIKE '%" + query + "%' or content LIKE '%" + query + "%'"):
                notetext = {}
                notetext["_id"] = row[0]
                notetext["title"] = row[1]
                notetext["body"] = row[2]
                notetext["datecreated"] = row[4]
                listtext.append(notetext)
        elif limit > 1:
            for row in dbmgr.query("select * from notes where title LIKE '%" + query + "%' or content LIKE '%" + query + "%' limit '" + str(limit) + "' OFFSET '" + str(offset) + "'"):
                notetext = {}
                notetext["_id"] = row[0]
                notetext["title"] = row[1]
                notetext["body"] = row[2]
                notetext["datecreated"] = row[4]
                listtext.append(notetext)

        return listtext
class CrudOperations(object):
    dbmgr = None

    def __init__(self):  # constructor initiates database connection instance
        self.dbmgr = DatabaseManager("cmapp.db")

        """Performs insert in db to save a notetext
        """

    def save(self, **content):  # content contains the name and mobile number of contacts
        contactname = ""
        contactnumber = ""
        if len(content) == 2:
            # Both name and mobile number exist
            contactname = content['contactname']
            contactnumber = content['contactnumber']
        elif len(content) == 1:  # only title exists
            return "Cannot save to db only one argument provided , two are expected"
        # save to db
        self.dbmgr.query(
            "insert into contactsDB(Contactname,Content,sent,datecreated) VALUES('" + contactname + "','" + contactnumber + "','NO','" + self.gettime() + "')")
Beispiel #39
0
    def run(self):

        print("Post Maintenance Thread Started")

        DAY_HALF_SECONDS = 60 * 60 * 24 * 1.5

        while True:

            try:

                current_time = datetime.datetime.utcnow().timestamp()

                post_list = DatabaseManager.get_all_posts(
                    dateLimit=current_time - DAY_HALF_SECONDS)

                post_sub_list = []

                count = 0

                while count < len(post_list):

                    cur_post = post_list[count]

                    cur_post.fetch()

                    if count % 10 == 0:

                        DatabaseManager.updatePostList(post_sub_list)

                        post_sub_list = []

                    post_sub_list.append(post_list[count])

                    count += 1

            except:

                print("Post Main Thread Exception: " + str(sys.exc_info()[0]))

                pass
def save_video_list_by_playlist(playlist):
    pytplaylist = pyTubePlaylist(playlist.url)
    pytplaylist.populate_video_urls()
    videos = []
    for videoUrl in pytplaylist.video_urls:
        try:
            CurrentVideo = YouTube(videoUrl)
        except:
            print "Error parsing videoUrl:- {0}", videoUrl
        try:
            url = videoUrl
            title = CurrentVideo.title
            duration = CurrentVideo.length
            views = CurrentVideo.views
            thumbnailUrl = CurrentVideo.thumbnail_url
            fullimageUrl = thumbnailUrl
            playlistUrl = playlist.url
            video = Video(url, title, duration, views, thumbnailUrl,
                          fullimageUrl, playlistUrl)
            videos.append(video)
        except:
            print "Error occured Extracting Data videoUrl :- {0}", videoUrl
    db = DatabaseManager()
    for vid in videos:
        try:
            db.insert_video(vid)
        except:
            print "Error occurred inserting video to db , VideoUrl :-{0}", videoUrl
        db.insert_playlist(playlist)
Beispiel #41
0
    def run(self):

        print("User Stream Thread Started")

        while True:

            try:

                post_list = DatabaseManager.get_all_posts()

                for cur_post in post_list:

                    DatabaseManager.ensure_user_exists(cur_post.username,
                                                       cur_post.subreddit)

                comment_list = DatabaseManager.get_all_comments()

                for cur_comment in comment_list:

                    DatabaseManager.ensure_user_exists(cur_comment.username,
                                                       cur_comment.subreddit)

            except:

                print("User Stream Thread Exception: " +
                      str(sys.exc_info()[0]))
                pass
Beispiel #42
0
    def searchThesaurus(self, term, langcode='en', ns=1):
        """ """
        if not term:
            return []

        conn = DatabaseManager()
        conn.openConnection(self)

        collation = self._get_language_collation(langcode, conn)
        err, res, msg = conn.query(sql_find_concept(term, langcode, collation))
        if err:
            # log error
            return []

        conn.closeConnection()

        results = []
        for i in res:
            if i['scope_name'] is None:
                i['scope_name'] = ''
            if i['concept_alt_name'] is None:
                i['concept_alt_name'] = ''
            results.append(ConceptLink(ns, i['concept_id'], i['concept_name'], i['scope_name'], i['concept_alt_name']))

        return results
Beispiel #43
0
def main():

    DatabaseManager.init_connection('test.sqlite')

    DatabaseManager.create_tables()

    RedditManager.login_threads_from_file("config.yml")

    ThreadedServices.setup_threads("BotParty")

    #    RedditManager.get_bans("BotParty")

    #   RedditManager.get_messages()

    #    ThreadedServices.setup_threads(SUBREDDIT)

    #    ThreadedServices.setup_threads("OnionHate")

    #    ThreadedServices.setup_threads("OnionHate")

    while True:
        time.sleep(0)
Beispiel #44
0
class DatabaseManagerTest:
    def __init__(self):
        self.manager = DatabaseManager()
        self.cmanager = CSVManager()

        #manager.exportReplayDatabase()

    def createDatabase(self):
        pass

    def importDatabase(self, databasePath):
        return self.manager.read(databasePath)

    def exportDatabase(self, data, header, filePath, createBackup):
        self.cmanager.write(data, header, filePath, createBackup)

    def dropTest(self, colName, database):
        return self.manager.delCol(colName, database)

    def swapTest(self, cols, database):
        return self.manager.swapCols(cols, database)

    def delDuplicatesTest(self, database):
        return self.manager.delDupes(database)

    def databaseTester(self):
        testReplay = '87B11D4743F1EAE859CAC9B48DAA8E89.replay'

        # testDB = pd.read_csv(defaultDatabasePath)
        # print(testDB)

        dbm = DatabaseManager()
        dbm.read()
        #print(dbm.database)

        row = dbm.getRow(testReplay)
        print(row)
        value = row.iloc[0]['GUID']
        print(value)
Beispiel #45
0
    def viewall(self, limit=1):
        listtext = []
        dbmgr = DatabaseManager("scribler.db")
        if limit == 1:
            for row in dbmgr.query("select * from notes"):
                notetext = {}
                notetext["_id"] = row[0]
                notetext["title"] = row[1]
                notetext["body"] = row[2]
                notetext["datecreated"] = row[4]
                listtext.append(notetext)
        elif limit > 1:

            for row in dbmgr.query("select * from notes limit '" + str(limit) + "'"):
                notetext = {}
                notetext["_id"] = row[0]
                notetext["title"] = row[1]
                notetext["body"] = row[2]
                notetext["datecreated"] = row[4]
                listtext.append(notetext)

        return listtext  # list containing dictionary entries of notes
def SetTpUpdateNSlUpdateOrder_DOWN(task, childOrder):
    tpFound = False
    slFound = False

    tpOfPosition = 0
    tpOrderID = 0

    slOfPosition = 0
    slOrderID = 0
    for order in childOrder:
        if order['order_type'] == 'LIMIT':
            tpFound = True
            tpOrderID = order['order_id']
            tpOfPosition = order['price']
        elif order['order_type'] == 'SL':
            slFound = True
            slOrderID = order['order_id']

    dbInstance = DatabaseManager.GetInstance()

    # This level is already 1 down of current tp, so we need to get next level type then set tpupdate n slupdate task
    levelType = task[2]
    tmpNxtLevel = dbInstance.GetNextLevel(task[0], levelType)
    if tmpNxtLevel.__len__() == 0:
        return
    #levelType = tmpNxtLevel[0][0]

    if tpFound:
        levelPrice = tpOfPosition * (1 + 0.0005)
        nxtLevel = dbInstance.GetNextLevel(task[0], levelType)
        if nxtLevel.__len__() > 0:
            nextTP = nxtLevel[0][1]
            nextLevelType = nxtLevel[0][0]
            dbInstance.CreateNewTask(task[0], task[1], nextLevelType,
                                     levelPrice, nextTP, 0.0,
                                     TASK_TYPE_ENUM[2],
                                     LEVEL_CROSS_TYPE_ENUM[1], tpOrderID)

    if slFound:
        levelPrice = tpOfPosition(1 + 0.0003)
        # Only first time we need prev level, for other time, we need next level
        prevLevel = dbInstance.GetPrevLevel(task[0], levelType)
        if prevLevel.__len__() > 0:
            nextSL = prevLevel[0][1]
            nxtLevel = dbInstance.GetNextLevel(task[0], levelType)
            if nxtLevel.__len__() > 0:
                nextLevelType = nxtLevel[0][0]
                dbInstance.CreateNewTask(task[0], task[1], nextLevelType,
                                         levelPrice, 0.0, nextSL,
                                         TASK_TYPE_ENUM[3],
                                         LEVEL_CROSS_TYPE_ENUM[1], slOrderID)
Beispiel #47
0
    def main(self):

        self.__dbManager = DatabaseManager()

        print('')
        print(
            'Welcome to our library! What would you like to do? Please enter the number of option.'
        )
        print('1. Sign up a new account')
        print('2. Log in with Password')
        print('3. Log in with Facial Recognition')
        print('4. Exit')

        option = TakeInput.inputInteger(1, 4)

        if option == 1:
            self.register()
        elif option == 2:
            self.loginWithPassword()
        elif option == 3:
            self.loginWithFacial()
        else:
            self.logout()
Beispiel #48
0
    def __init__(self):
        """Init"""
        if not hasattr(ServerManager, 'instance'):
            ServerManager.instance = self
        else:
            self.log("Error: singleton already defined")
            sys.exit(-1)

        self.__running = True
        self.__db = DatabaseManager(DatabaseType.CSV, cfg.db_addr)
        # Instantiate the port manager for all games + admin messages
        self.__port_manager = PortManager(cfg.lower_bound, cfg.upper_bound)
        # Instantiate the message manager exclusively for admin messages
        self.__message_manager = WebsocketMessageManager(cfg.admin)
        self.__pid = os.getpid()
        self.__public_requests = ThreadsafeQueue()
        self.__game_pids = ThreadsafeQueue()
        self.__logger = Logger(cfg.log_addr)
        self.__http_proc = threading.Thread(target=self.serveHTTP)
        self.__pub_polling = threading.Thread(target=self.pollPublic)
        self.log("Server Initialized")
        self.__http_proc.start()
        self.__pub_polling.start()
def SetTpUpdateOrder_DOWN(task):
    # Now before setting another order, check whether this order is still open or not
    if OrderClosed(task[8]):
        return
    levelType = task[2]
    levelPrice = task[4] * (1 + 0.0005)

    dbInstance = DatabaseManager.GetInstance()
    nxtLevel = dbInstance.GetNextLevel(task[0], levelType)
    if nxtLevel.__len__() > 0:
        nextTP = nxtLevel[0][1]
        nextLevelType = nxtLevel[0][0]
        dbInstance.CreateNewTask(task[0], task[1], nextLevelType, levelPrice,
                                 nextTP, 0.0, TASK_TYPE_ENUM[2],
                                 LEVEL_CROSS_TYPE_ENUM[1], task[8])
Beispiel #50
0
class Model():
    instance = None
    
    def __init__(self):
        Model.instance = self
        self.db = DatabaseManager("periodic.sqlite")
        self.computer = ConcentrationComputer()
        self.balance = Balance()
        
    def getElements(self):
        """
            Retourne les elements chimiques depuis la base de données
        """
        elements = self.db.fetchElements()
        return elements
Beispiel #51
0
        def salvaDados():
            id_aluno = listaAlunos.get()
            id_prof = listaProf.get()
            id_disciplina = listaD.get()
            nota1 = fldnota1.get()
            nota2 = fldnota2.get()

            if id_aluno == "":
                messagebox.showinfo("Erro", "Informe um aluno!")

            elif id_prof == "":
                messagebox.showinfo("Erro", "Informe um professor!")

            elif id_disciplina == "":
                messagebox.showinfo("Erro", "Informe uma disciplina!")

            elif nota1 == "" or nota2 == "":
                messagebox.showinfo("Erro", "Informe os valores das notas!")

            else:
                DatabaseManager.insert(
                    "notes",
                    [contaID, id_aluno, id_prof, id_disciplina, nota1, nota2])
                messagebox.showinfo("Aviso", "Dados inseridos no banco!")
Beispiel #52
0
    def _get_concept_relatives(self, concept_ns, concept_id, target_ns=None, relation_uri=None):
        """ get all concepts related to a given concept """
        conn = DatabaseManager()
        conn.openConnection(self)

        err, res, msg = conn.query(sql_get_concept_relatives(concept_ns, concept_id, target_ns, relation_uri))

        conn.closeConnection()

        return res
Beispiel #53
0
    def fetch_namespaces(self):
        conn = DatabaseManager()
        conn.openConnection(self)

        err, res, msg = conn.query(sql_get_namespaces())
        if err:
            print err, msg

        conn.closeConnection()
        return res
Beispiel #54
0
    def fetch_concept_property_translations(self, concept_ns, concept_id, prop_name):
        conn = DatabaseManager()
        conn.openConnection(self)

        err, res, msg = conn.query(sql_get_concept_property(concept_ns, concept_id, prop_name))
        if err:
            print err, msg

        conn.closeConnection()
        return res
Beispiel #55
0
    def __init__(self, parent=None):
        """
            Face Detection Init. Instantiate all the classes required by face detection module.
        """

        super().__init__(parent)
        self.constants = Constants()
        self.db_manager = DatabaseManager()

        self._red = (0, 0, 255)
        self._width = 2

        self.image = QtGui.QImage()
        self.process_this_frame = True
        self.foundNewFace = False
        self.foundFace = False
def SetSlUpdateOrder_DOWN(task):
    # Now before setting another order, check whether this order is still open or not
    if OrderClosed(task[8]):
        return
    levelType = task[2]
    nextSL = task[3]  # current level(old tp) will be new sl
    dbInstance = DatabaseManager.GetInstance()
    currentLevel = dbInstance.GetCurrentLevel(task[0], levelType)
    if currentLevel.__len__() > 0:
        nxtLevel = dbInstance.GetNextLevel(task[0], levelType)
        if nxtLevel.__len__() > 0:
            nextLevelType = nxtLevel[0][0]
            nextLevelPrice = currentLevel[0][1] * (1 + 0.0003)
            dbInstance.CreateNewTask(task[0], task[1], nextLevelType,
                                     nextLevelPrice, 0.0, nextSL,
                                     TASK_TYPE_ENUM[3],
                                     LEVEL_CROSS_TYPE_ENUM[1], task[8])
Beispiel #57
0
def main(argv):
    opts = get_command_args(argv)
    dm = DatabaseManager()

    if (opts['data']):
        pprint(dm.get_data(opts['redcap']))
    if (opts['match']):
        pprint(dm.get_matches(opts['redcap'], opts['bool'], opts['value']))
    if (opts['search']):
        pprint(dm.get_searches(opts['redcap'], opts['bool'], opts['value']))

    if (opts['mach']):
        pprint(dm.get_ml_data(opts['redcap']))
    def Handle_LogIn(self):
        print("button pressed")
        db = DatabaseManager(self.db_file_loc, self.protected_table_prefix)
        username = self.user_name_tf.text()
        password = self.password_tf.text()

        try:
            if db.is_valid_string(username) and db.is_valid_string(password):
                #Both user name and password have to be valid strings to continue
                if not db.doesTableExist(self.account_info_table_name):
                    print("Must create account before")

                #Gets the account from the databse with the same password
                #If the isn't a match then it returns none
                row_with_entered_pass = db.get_row_at(
                    self.account_info_table_name,
                    column_name=account_columns[0],
                    column_value=password)
                #                 print(row_with_entered_pass)

                if not row_with_entered_pass == None:
                    #If the there is a password match then save the info
                    password_db = row_with_entered_pass[0]
                    user_name_db = row_with_entered_pass[1]

                    if password_db == password and user_name_db == username:
                        #If the user name and password entered match the
                        #user name and password in the db then it's a valid login
                        self.valid_login()
                    else:
                        ErrorBox = QtWidgets.QMessageBox()
                        ErrorBox.warning(
                            self, 'No Account Found',
                            "No account found for the combination of user name and password",
                            ErrorBox.Ok)

                else:
                    ErrorBox = QtWidgets.QMessageBox()
                    ErrorBox.warning(
                        self, 'No Account Found',
                        "No account found for the combination of user name and password",
                        ErrorBox.Ok)
            else:
                raise Exception()
        except:
            ErrorBox = QtWidgets.QMessageBox()
            ErrorBox.critical(
                self, 'Text Entry Error',
                "Text entries can only have letters numbers, and underscores",
                ErrorBox.Ok)
Beispiel #59
0
    def get_light(self):
        ir = InputReader()

        res = ir.read_analogic_sensor(analog_pin["light"])
        db = DatabaseManager()

        if (res <= 200):
            valDB = db.store_light(0)
            return 0, "Dark"
        elif (res > 200 and res <= 400):
            valDB = db.store_light(1)
            return 1, "Dim"  #shadow
        elif (res > 400 and res <= 700):
            valDB = db.store_light(2)
            return 2, "Light"
        elif (res > 700 and res <= 900):
            valDB = db.store_light(3)
            return 3, "Bright"
        else:
            valDB = db.store_light(4)
            return 4, "Very Bright"
Beispiel #60
0
def generate_output_report(db: str) -> list:
    try:
        with DatabaseManager(db) as db:
            db.execute("""
                    SELECT employee_id, pay_period, amount_paid
                    FROM (
                        SELECT r.employee_id , SUM(r.amount_paid) as amount_paid,
                            CASE
                                WHEN strftime('%d',r.date) < '16' 
                                THEN strftime('%m-%Y', Date(r.date,'start of month')) || ' - ' 
                                     || strftime('%m-%Y', Date(r.date,'start of month','+14 day'))
                                ELSE strftime('%m-%Y', Date(r.date,'start of month','+15 day')) || ' - ' 
                                     || strftime('%m-%Y', Date(r.date,'start of month','+1 month','-1 day'))
                            END month_year_key,
                            CASE
                                WHEN strftime('%d',r.date) < '16' 
                                THEN strftime('%d/%m/%Y', Date(r.date,'start of month')) || ' - ' 
                                     || strftime('%d/%m/%Y', Date(r.date,'start of month','+14 day'))
                                ELSE strftime('%d/%m/%Y', Date(r.date,'start of month','+15 day')) || ' - ' 
                                     || strftime('%d/%m/%Y', Date(r.date,'start of month','+1 month','-1 day'))
                            END pay_period
                            FROM (
                                SELECT i.date, i.employee_id, i.hours_worked*j.rate AS amount_paid 
                                FROM input_reports i
                                JOIN job_group j 
                                ON i.job_group = j.job_group 
                                ORDER BY i.employee_id, i.date ASC) r
                            GROUP BY pay_period, employee_id
                            ORDER BY employee_id, month_year_key, pay_period ASC)"""
                       )

            output_report = db.fetchall()
        return output_report

    except sqlite3.Error as e:
        print("db_setup Error: %s" % e.args[0])
        db.__exit__()