Example #1
0
def nds_loop(doInit):
	ndutil.setTimezone()

	ndlCom = NdlCom('nDroid-Storage', '127.0.0.1', 12322)
	ndlCom.doCom('Initiating')

	ndlCom.doCom('Loading Configuration')
	cnfManager = CnfManager()
	cnfManager.load('./nds.cnf')
	cnfData = cnfManager.getCnfData()

	ndutil.enableDir(cnfData['storageDir'])

	ndlCom.doCom('Connecting to DB')
	dbManager = DbManager(cnfData['dbHost'], cnfData['dbUser'], cnfData['dbPass'], cnfData['dbName'])
	if doInit:
		dbManager.create_table()
		os.system('rm -fr %s/*' % cnfData['storageDir'])

	msgManager = MsgManager()

	netManager = NetManager()
	netManager.setStorageDir(cnfData['storageDir'])
	netManager.setFileMode(cnfData['fileMode'])
	netManager.setNdlCom(ndlCom)
	netManager.setDbManager(dbManager)
	netManager.setMsgManager(msgManager)

	reactor.listenUDP(cnfData['comPort'], netManager)
	ndlCom.doCom('Listening Com Port')
	reactor.run()
Example #2
0
 def exposed_create_table(self):
     self.db = DbManager('localhost', 'root', '', 'testowa')
     self.db.executesql(
         "CREATE TABLE IF NOT EXISTS programs (id integer PRIMARY KEY AUTO_INCREMENT, program_name VARCHAR(128) NOT NULL, code_text VARCHAR(4096) NOT NULL, date_added TIMESTAMP DEFAULT CURRENT_TIMESTAMP)"
     )
     self.db.executesql(
         "CREATE TABLE IF NOT EXISTS programs_diffs (id integer PRIMARY KEY AUTO_INCREMENT, program1_id integer NOT NULL, program2_id integer NOT NULL, similarity float NOT NULL DEFAULT 0, diff VARCHAR(4096) NULL)"
     )
Example #3
0
def ncd_loop(doInit, dlThreadNum):
	ndutil.setTimezone()

#read config
	cnfManager = CnfManager()
	cnfManager.load('./ndc.cnf')
	cnfData = cnfManager.getCnfData()

#check dirs
	ndutil.enableDir(cnfData['dirWorking'])
	ndutil.enableDir(cnfData['dirStore'])

#ndlcom
	logger = Logger('nDroid-Crawler', cnfData['ndlComHost'], cnfData['ndlComPort'])
	logger.logger('Initiating')

	dbManager = DbManager(cnfData['dbHost'], cnfData['dbUser'], cnfData['dbPass'], cnfData['dbName'])
	if doInit:
		dbManager.create_table()
		os.system('rm -f %s/*' % cnfData['dirWorking'])
		os.system('rm -f %s/*' % cnfData['dirStore'])

	#logger.logger('Customizing Spiders')
	#spiderGenerator = SpiderGenerator('template', 'spider/spiders')
	#for spider in cnfData['spiders']:
	#	spiderGenerator.gen_spider(spider, cnfData[spider]['startPage'], cnfData[spider]['stopPage'])

	rpQueue = Queue()
	pdQueue = Queue()
	dpQueue = Queue()
	pdLock = threading.Lock()

	rpcMonitor = RpcMonitor(logger, cnfData['rpcPort'], cnfData['rpcAuth'], 'RpcMonitor')
	rpcMonitor.setGlobalInfo(ndutil.getCurrentTimeStr(), 'Standalone', dlThreadNum)
	rpcMonitor.setDownloadTotal(pdQueue.qsize())
	rpcMonitor.setPdQueueSize(pdQueue.qsize())
	
	botScheduler = BotScheduler(logger, rpcMonitor, cnfData['spiders'], cnfData['spiderCnfs'], 'BotScheduler')
	receiver = Receiver(logger, rpcMonitor, rpQueue, cnfData['receiverPort'], 'Receiver')
	preProcessor = PreProcessor(logger, rpcMonitor, rpQueue, pdQueue, pdLock, dbManager, 'PreProcessor')
	downloader = Downloader([logger, rpcMonitor, pdQueue, dpQueue, pdLock, dlThreadNum, cnfData['dirWorking']], 'Downloader')
	processor = Processor(logger, rpcMonitor, dpQueue, pdLock, pdQueue, dbManager, cnfData['dirWorking'], cnfData['dirStore'], 'Processor')

	logger.logger('Starting Threads')
	rpcMonitor.start()
	botScheduler.start()
	receiver.start()
	preProcessor.start()
	downloader.start()
	processor.start()
	
	processor.join()
	downloader.join()
	preProcessor.join()
	receiver.join()
	botScheduler.join()
	rpcMonitor.join()
Example #4
0
def create_game_logs_table(db_manager: DbManager):
    sql_create_game_logs_table = """
    CREATE TABLE IF NOT EXISTS GameLogs (
    id                   INTEGER PRIMARY KEY AUTOINCREMENT,
    player_id            TEXT,
    team_game_number     INTEGER,
    player_game_number   INTEGER,
    is_playoffs          INTEGER,
    season               INTEGER,
    date                 DATE,
    team                 TEXT,
    at_home              INTEGER,
    opponent             TEXT,
    game_started         INTEGER,
    seconds_played       INTEGER,
    field_goals          INTEGER,
    field_goal_attempts  INTEGER,
    three_points         INTEGER,
    three_point_attempts INTEGER,
    free_throws          INTEGER,
    free_throw_attempts  INTEGER,
    offensive_rebounds   INTEGER,
    defensive_rebounds   INTEGER,
    assists              INTEGER,
    steals               INTEGER,
    blocks               INTEGER,
    turnovers            INTEGER,
    fouls                INTEGER,
    points               INTEGER,
    plus_minus           INTEGER,
    fanduel_score        REAL) """

    if db_manager.execute(sql_create_game_logs_table) is None:
        print("Error creating GameLogs table.")
Example #5
0
    def login(self):
        login = self.logEntry.get()
        password = self.passwordEntry.get()

        if '' in (login, password):
            messagebox.showerror(lp[self.language]['error'],
                                 lp[self.language]['fill_all_entries'])
            Window.delete_entries(self.passwordEntry)
            return

        log_in_db = DbManager.get_column_values('Users', 'login')

        if login not in log_in_db:
            messagebox.showerror(
                lp[self.language]['error'],
                lp[self.language]['incorrect_login'].format(login=login))
            Window.delete_entries(self.logEntry, self.passwordEntry)
            return

        if password != DbManager.get_column_value_where(
                'Users', 'password', 'login', login):
            messagebox.showerror(lp[self.language]['error'],
                                 lp[self.language]['incorrect_password'])
            Window.delete_entries(self.passwordEntry)
            return

        self.user = {
            'id':
            DbManager.get_column_value_where('Users', 'id', 'login', login),
            'login':
            login,
            'password':
            password,
            'email':
            DbManager.get_column_value_where('Users', 'email', 'login', login),
            'pin':
            DbManager.get_column_value_where('Users', 'pin', 'login', login)
        }

        MailManager.send_mail(self.language,
                              self.user['email'],
                              msg_type='alert',
                              data=login)
        self.root.destroy()

        main_window = MainWindow(self.language, self.user)
        main_window.root.mainloop()
Example #6
0
    def check_pin(self, pin, btn):
        if pin.get() != DbManager.get_column_value_where(
                'Users', 'pin', 'id', self.user['id']):
            messagebox.showerror('Error', 'Invalid PIN.')
            pin.delete(0, 'end')
            return
        btn['btn'].destroy()
        pin.destroy()

        password = tk.Label(self.scrollframe.viewPort,
                            text=DbManager.get_column_value_where(
                                'Accounts', 'password', 'id', btn['acc_id']),
                            bg=self.bg_color)
        password.grid(row=btn['y'], column=3)

        # % same here, adding shown password label to accountsRowsWidgets eliminates the bug
        self.accountsRowsWidgets.append({'shown_password': password})
Example #7
0
def get_player_ids(db_manager: DbManager) -> PlayerIds:
    get_ids_query = 'SELECT id FROM Players'
    result = db_manager.execute(get_ids_query)
    player_ids = []
    if result is not None:
        player_ids = [player_id[0] for player_id in result.fetchall()]
    
    return player_ids
    def add_account(self):
        validation_result = self.validation()

        if validation_result:
            title = validation_result[0]
            login = validation_result[1]
            associated_email = validation_result[2]
            password = validation_result[3]

            user_id = DbManager.get_column_value_where('Users', 'id', 'login',
                                                       self.user['login'])
            DbManager.insert(
                'Accounts',
                'title, login, associated_email, password, user_id',
                (title, login, associated_email, password, user_id))

            self.refreshAccountListMethod()
            Window.close_top_level(self, self.toDisable)
Example #9
0
def create_players_table(db_manager: DbManager):
    sql_create_players_table = """
        CREATE TABLE IF NOT EXISTS Players (
        id   TEXT PRIMARY KEY,
        name TEXT NOT NULL);
        """

    if db_manager.execute(sql_create_players_table) is None:
        print("Error creating Players table.")
Example #10
0
    def save_new_security(self):
        old_security = self.oldSecurityEntry.get()
        new_security = self.newSecurityEntry.get()
        confirm_security = self.confirmSecurityEntry.get()

        if not (old_security and new_security and confirm_security):
            messagebox.showerror('Error', 'All fields required.')
            Window.delete_entries(self.oldSecurityEntry, self.newSecurityEntry,
                                  self.confirmSecurityEntry)
            return

        if old_security != DbManager.get_column_value_where(
                'Users', self.mode, 'id', self.user["id"]):
            messagebox.showerror('Error', 'Invalid old PIN.')
            Window.delete_entries(self.oldSecurityEntry, self.newSecurityEntry,
                                  self.confirmSecurityEntry)
            return

        if self.mode == 'password':
            if len(new_security) < 8:  # minimum password length
                messagebox.showerror(
                    'Error', 'Password must be at least 8 characters long.')
                Window.delete_entries(self.oldSecurityEntry,
                                      self.newSecurityEntry,
                                      self.confirmSecurityEntry)
                return

        if new_security != confirm_security:
            messagebox.showerror(
                'Error',
                '\'New password\' and \'Confirm password\' entries don\'t match.'
            )
            Window.delete_entries(self.oldSecurityEntry, self.newSecurityEntry,
                                  self.confirmSecurityEntry)
            return

        DbManager.update('Users', self.mode, new_security, 'id',
                         self.user['id'])  # mode is pwd or pin
        messagebox.showinfo(
            'Success',
            f'Your {self.mode} has been successfully changed.\nRemember not to share it '
            'with anyone else.')
        self.master.user[self.mode] = new_security  # update user
        Window.close_top_level(self, self.master.toDisable)
Example #11
0
    def remind_password(self):
        login = self.widgetsForEntries[1].get()
        email = self.widgetsForEntries[3].get()

        if '' in (login, email):
            messagebox.showerror(lp[self.language]['error'],
                                 lp[self.language]['fill_all_entries'])
            return

        if not re.match(r'[^@]+@[^@]+\.[^@]+', email):
            messagebox.showerror(lp[self.language]['error'],
                                 lp[self.language]['invalid_email'])
            return

        log_in_db = DbManager.get_column_values('Users', 'login')

        if login not in log_in_db:
            messagebox.showerror(
                lp[self.language]['error'],
                lp[self.language]['incorrect_login'].format(login=login))
            return

        if email != DbManager.get_column_value_where('Users', 'email', 'login',
                                                     login):
            messagebox.showerror(
                lp[self.language]['error'],
                lp[self.language]['email_doesnt_match'].format(email=email))
            return

        password = DbManager.get_column_value_where('Users', 'password',
                                                    'login', login)

        if MailManager.send_mail(self.language,
                                 email,
                                 msg_type='password_request',
                                 data=password,
                                 data2=login):
            messagebox.showinfo(
                lp[self.language]['password_reminder_req'],
                lp[self.language]['password_reminder_accepted'])
        Window.close_top_level(self, self.btnsToDisable)
Example #12
0
 def load_account_data(self, acc_id):
     self.accTitleEntry.insert(
         0,
         DbManager.get_column_value_where('Accounts', 'title', 'id',
                                          acc_id))
     self.loginEntry.insert(
         0,
         DbManager.get_column_value_where('Accounts', 'login', 'id',
                                          acc_id))
     self.associatedEmailEntry.insert(
         0,
         DbManager.get_column_value_where('Accounts', 'associated_email',
                                          'id', acc_id))
     self.passwordEntry.insert(
         0,
         DbManager.get_column_value_where('Accounts', 'password', 'id',
                                          acc_id))
     self.passwordConfirmEntry.insert(
         0,
         DbManager.get_column_value_where('Accounts', 'password', 'id',
                                          acc_id))
     self.accId = acc_id
Example #13
0
def ndc_loop():
	ndutil.setTimezone()

	logger = Logger('nDroid-CD', '127.0.0.1', 12322)
	logger.logger('Initiating')

	logger.logger('Loading Config')
	cnfManager = CnfManager()
	cnfManager.load('./ndc.cnf')
	cnfData = cnfManager.getCnfData()

	fsQueue = Queue()
	fsLock = threading.Lock()
	sfQueue = Queue()
	sfLock = threading.Lock()

	logger.logger('Connecting to DB')
	dbManager = DbManager(cnfData['dbHost'], cnfData['dbUser'], cnfData['dbPass'], cnfData['dbName'])
	dbManager.create_table()

	netManager = NetManager()
	netManager.setNdlCom(logger)
	netManager.setDbManager(dbManager)
	netManager.setFsQueue(fsQueue, fsLock)

	logger.logger('Starting Threads')
	fileSender = FileSender([logger, fsQueue, fsLock, sfQueue, sfLock, cnfData['host'], cnfData['fileUrl'], cnfData['apiKey'], cnfData['interval']], 'FileSender')
	scanSender = ScanSender([logger, fsQueue, fsLock, sfQueue, sfLock, cnfData['host'], cnfData['scanUrl'], cnfData['apiKey'], cnfData['interval'], dbManager], 'ScanSender')

	fileSender.start()
	scanSender.start()

	reactor.listenUDP(cnfData['comPort'], netManager)
	logger.logger('Listening Com Port')
	reactor.run()

	scanSender.join()
	fileSender.join()
Example #14
0
    def reset_pin(self):
        new_pin = self.widgetsForEntries[1].get()
        pin_confirm = self.widgetsForEntries[3].get()

        if not (new_pin and pin_confirm):
            messagebox.showerror(
                'Error', 'New PIN and PIN confirmation are both required.')
            Window.delete_entries(self.widgetsForEntries[1],
                                  self.widgetsForEntries[3])
            return

        if new_pin != pin_confirm:
            messagebox.showerror('Error',
                                 'New PIN and PIN confirmation do not match.')
            Window.delete_entries(self.widgetsForEntries[1],
                                  self.widgetsForEntries[3])
            return

        DbManager.update('Users', 'pin', new_pin, 'id', self.user['id'])
        self.user['pin'] = new_pin
        messagebox.showinfo('Success',
                            'Your new PIN has been successfully set.')

        Window.close_top_level(self, self.btnsToDisable)
Example #15
0
    def export(self):
        pin = self.widgetsForEntries[1].get()
        password = self.widgetsForEntries[3].get()

        if not (pin and password):
            messagebox.showerror(lp[self.language]['error'],
                                 lp[self.language]['pin_and_password_req'])
            Window.delete_entries(self.widgetsForEntries[1],
                                  self.widgetsForEntries[3])
            return

        if pin == DbManager.get_column_value_where('Users', 'pin', 'id', self.user['id']) \
                and password == DbManager.get_column_value_where('Users', 'password', 'id', self.user['id']):
            Window.close_top_level(self, self.btnsToDisable)

            path = filedialog.askdirectory()
            path += '/exported_accounts.txt'

            accounts = DbManager.get_user_accounts(self.user['id'])

            try:
                with open(path, 'w') as file:
                    for account in accounts:
                        row = 'title: ' + account['title'] + '\tlogin: '******'login'] + '\tassociated email: ' + \
                              account['associated_email'] + '\tpassword: '******'password'] + '\n'
                        file.write(row)
                messagebox.showinfo(lp[self.language]['data_exported'],
                                    lp[self.language]['data_exported_info'])

            except PermissionError:
                pass
        else:
            messagebox.showerror(lp[self.language]['error'],
                                 lp[self.language]['pin_or_password_invalid'])
            Window.delete_entries(self.widgetsForEntries[1],
                                  self.widgetsForEntries[3])
Example #16
0
class App:
    def __init__(self):
        self.db = DbManager()

    def ekleme(self):
        #ad, soyad, telefon, okul_no, tc, mail, sifre, yetki
        name = "test"
        surname = "Şalış"
        phone = "5061429571"
        school_number = "02185076051"
        tc = "12345678910"
        mail = "*****@*****.**"
        password = "******"
        yetki = 3
        no = 6
        test = Kullanicilar(no, name, surname, phone, school_number, tc, mail,
                            password, yetki)
        #self.db.addKullanici(test)
        gelen = self.db.getKullanicilar()
        self.db.editKullanici(test)

        for i in gelen:
            print(i.id, i.ad, i.soyad, i.telefon, i.tc, i.okul_no, i.mail,
                  i.sifre, i.yetki)
Example #17
0
def nda_loop(doInit):
    ndutil.setTimezone()

    ndlCom = NdlCom('nDroid-ADB', '127.0.0.1', 12322)
    ndlCom.doCom('Initiating')

    ndlCom.doCom('Loading Config')
    cnfManager = CnfManager()
    cnfManager.load('./nda.cnf')
    cnfData = cnfManager.get_cnf_data()

    ndlCom.doCom('Connecting to DB')
    dbManager = DbManager(cnfData['dbHost'], cnfData['dbUser'], cnfData['dbPass'], cnfData['dbName'])

    if doInit:
        dbManager.create_table()

    netManager = NetManager()
    netManager.setNdlCom(ndlCom)
    netManager.setDbManager(dbManager)

    reactor.listenUDP(cnfData['comPort'], netManager)
    ndlCom.doCom('Listening Com Port')
    reactor.run()
Example #18
0
    def edit_account(self):
        validation_result = self.validation()

        if validation_result:
            title = validation_result[0]
            login = validation_result[1]
            associated_email = validation_result[2]
            password = validation_result[3]

            DbManager.update('Accounts', 'title', title, 'id', self.accId)
            DbManager.update('Accounts', 'login', login, 'id', self.accId)
            DbManager.update('Accounts', 'associated_email', associated_email,
                             'id', self.accId)
            DbManager.update('Accounts', 'password', password, 'id',
                             self.accId)

            self.refreshAccountListMethod()
            Window.close_top_level(self, self.toDisable)
Example #19
0
    def validation(self):
        title = self.accTitleEntry.get()
        login = self.loginEntry.get()
        associated_email = self.associatedEmailEntry.get()
        password = self.passwordEntry.get()
        password_confirm = self.passwordConfirmEntry.get()
        pin = self.pinEntry.get()

        if not (login or associated_email):
            Window.delete_entries(self.passwordEntry,
                                  self.passwordConfirmEntry, self.pinEntry)
            messagebox.showerror(
                'Error', 'Only login or associated email may remain empty.')
            return None

        if not (title and password):
            Window.delete_entries(self.passwordEntry,
                                  self.passwordConfirmEntry, self.pinEntry)
            messagebox.showerror('Error', 'Title and password are required.')
            return None

        if password != password_confirm:
            Window.delete_entries(self.passwordEntry,
                                  self.passwordConfirmEntry, self.pinEntry)
            messagebox.showerror(
                'Error', 'Password and password confirmation don\'t match.')
            return None

        if associated_email:
            if not re.match(r'[^@]+@[^@]+\.[^@]+', associated_email):
                Window.delete_entries(self.passwordEntry,
                                      self.passwordConfirmEntry,
                                      self.associatedEmailEntry, self.pinEntry)
                messagebox.showerror('Error', 'Invalid email.')
                return None

        if self.mode == 'Edit' and pin != DbManager.get_column_value_where(
                'Users', 'pin', 'id', self.user['id']):
            Window.delete_entries(self.pinEntry)
            messagebox.showerror('Error', 'Invalid PIN.')
            return None

        return title, login, associated_email, password,
Example #20
0
def update_players_table():
    db_manager = DbManager(NBA_DB)
    
    existing_player_ids = set()
    if not players_table_exists(db_manager):
        create_players_table(db_manager)
    else:
        existing_player_ids.update(get_player_ids(db_manager))
    
    if not game_logs_table_exists(db_manager):
        create_game_logs_table(db_manager)

    active_players = get_active_players()
    for player in active_players:
        time.sleep(1)
        player_id = player[0]
        print(player_id)
        if not player_id in existing_player_ids:
            insert_player(db_manager, player)
    
        stats = get_player_stats(player_id, 2020)
        for game_log in stats:
            insert_game_log(db_manager, game_log)
Example #21
0
 def __init__(self):
     self.db = DbManager()
Example #22
0
class App:
    def __init__(self):
        self.db = DbManager()

    def initApp(self):
        msg = "*****\n1-Öğrenci Listesi\n2-Öğrenci Ekle\n3-Öğrenci Güncelle\n4-Öğrenci Sil\n5-Öğretmen Ekle\n6-Sınıflara Göre Dersler\n7-Çıkış(E/Ç)"
        while True:
            print(msg)
            islem = input("Seçim: ")
            if islem == '1':
                self.displayStudents()
            elif islem == '2':
                self.addStudent()
            elif islem == '3':
                self.editStudent()
            elif islem == '4':
                self.deleteStudent()
            elif islem == 'E' or islem == 'Ç':
                break
            else:
                print('yanlış seçim')

    def deleteStudent(self):
        classid = self.displayStudents()
        studentid = int(input('öğrenci id: '))

        self.db.deleteStudent(studentid)

    def editStudent(self):
        classid = self.displayStudents()
        studentid = int(input('öğrenci id: '))

        student = self.db.getStudentById(studentid)

        student[0].name = input('name:') or student[0].name
        student[0].surname = input('surname:') or student[0].surname
        student[0].gender = input('cinsiyet (E/K):') or student[0].gender
        student[0].classid = input('sınıf: ') or student[0].classid

        #or student[0].x demek kullanıcı herhangi bir degisiklik yapmazsa eski hali kalsın dedik.

        year = input("yıl: ") or student[0].birthdate.year
        month = input("ay: ") or student[0].birthdate.month
        day = input("gün: ") or student[0].birthdate.day

        student[0].birthdate = datetime.date(year, month, day)
        self.db.editStudent(student[0])

    def addStudent(self):
        self.displayClasses()

        classid = int(input('hangi sınıf: '))
        number = input('numara: ')
        name = input('ad')
        surname = input('soyad')
        year = int(input('yıl'))
        month = int(input('ay'))
        day = int(input('gün'))
        birthdate = datetime.date(year, month, day)
        gender = input('cinsiyet (E/K)')

        student = Student(None, number, name, surname, birthdate, gender,
                          classid)
        self.db.addStudent(student)

    def displayClasses(self):
        classes = self.db.getClasses()
        for c in classes:
            print(f'{c.id}: {c.name}')

    def displayStudents(self):
        self.displayClasses()
        classid = int(input('hangi sınıf: '))

        students = self.db.getStudentsByClassId(classid)
        print("Öğrenci Listesi")
        for std in students:
            print(f'{std.id}-{std.name} {std.surname}')

        return classid
Example #23
0
class Module4Server(Service):

    filename = 'test.py'
    db = DbManager('localhost', 'root', '', 'testowa')
    message_for_client = ''
    client_program_id = 0
    db_thread = threading.Thread()

    def exposed_create_table(self):
        self.db = DbManager('localhost', 'root', '', 'testowa')
        self.db.executesql(
            "CREATE TABLE IF NOT EXISTS programs (id integer PRIMARY KEY AUTO_INCREMENT, program_name VARCHAR(128) NOT NULL, code_text VARCHAR(4096) NOT NULL, date_added TIMESTAMP DEFAULT CURRENT_TIMESTAMP)"
        )
        self.db.executesql(
            "CREATE TABLE IF NOT EXISTS programs_diffs (id integer PRIMARY KEY AUTO_INCREMENT, program1_id integer NOT NULL, program2_id integer NOT NULL, similarity float NOT NULL DEFAULT 0, diff VARCHAR(4096) NULL)"
        )

    def exposed_save_code(self, code: list):
        file = open(self.filename, 'w')
        file.truncate()
        code_text = ''
        for line in code:
            file.write(line)
            code_text += line

        self.db_thread = threading.Thread(target=self.save_into_db,
                                          args=(code_text, ))
        self.db_thread.start()

        file.close()
        return

    def save_into_db(self, code: str):
        sql = "INSERT INTO programs (program_name, code_text) VALUES (\'" + self.filename + "\',\'" + code + "\')"
        self.db.executesql(sql)
        self.db.commit_changes()
        self.client_program_id = self.db.cursor.lastrowid
        return self.client_program_id

    def exposed_execute_code(self, val: str):
        try:
            if val.isdigit() == False:
                raise ValueError()

            fib = subprocess.call("python " + self.filename + ' ' + val)
            return str(fib)

        except ValueError:
            er_comment = "Niepoprawna wartosc argumentu"
            return er_comment

        except:
            er_comment = "Blad w programie obliczajacym ciag Fib"
            return er_comment

    def exposed_compare_code(self, n: int):
        sql = "SELECT * FROM programs"
        self.db.executesql(sql)
        rows = self.db.get_result()
        row = next((x for x in rows if x['id'] == n), None)
        if row == None:
            return
        code = str(row['code_text'])
        message = ''
        new_id_text = '=========\nID = '
        sim = 'Similarity = '
        for r in rows:
            r_id = int(r['id'])
            if r_id == n:
                continue

            code2 = str(r['code_text'])
            c1 = code.splitlines(False)
            c2 = code2.splitlines(False)
            diff = difflib.unified_diff(c1, c2)
            match = difflib.SequenceMatcher(None, code, code2)
            m = match.ratio()
            str_diff = ''
            sql = ''
            temp_text = new_id_text + str(r['id']) + '\n'
            message += temp_text
            temp_text = sim + str(m) + '\n'
            message += temp_text
            for line in diff:
                str_diff += line
                message += line + '\n'
            sql = "INSERT INTO programs_diffs (program1_id, program2_id, similarity, diff) VALUES (" + str(
                n) + "," + str(r_id) + "," + str(m) + ",\'" + str_diff + "\')"
            self.db.executesql(sql)
            self.db.commit_changes()
        self.message_for_client = message

    def exposed_get_message(self):
        return self.message_for_client

    def exposed_get_program_id(self):
        if self.db_thread.is_alive:
            self.db_thread.join()
        return self.client_program_id
Example #24
0
import unittest
from module_4_server import Module4Server
from dbmanager import DbManager

server = Module4Server()
db = DbManager('localhost', 'root', '', 'testowa')

class TestServer(unittest.TestCase):
    def test_create_table(self):
        server.exposed_create_table()

    def test_save_code(self):
        query = "SELECT COUNT(*) FROM programs"
        db.executesql(query)
        rows = db.get_result()
        db.commit_changes()
        table_size_before = rows[0]['COUNT(*)']

        content = ''
        with open('code.txt', 'r') as file:
            content = file.readlines()

        server.exposed_save_code(content)

        db.executesql(query)
        rows = db.get_result()
        db.commit_changes()
        table_size_after = rows[0]['COUNT(*)']
        self.assertEqual(table_size_before + 1, table_size_after)      

    def test_execute_code(self):
Example #25
0
 def delete_account(self, acc_id):
     if messagebox.askokcancel(
             title='Delete account',
             message='Are you sure you want to delete this account?'):
         DbManager.delete('Accounts', 'id', acc_id)
         self.display_accounts()
Example #26
0
class App:
    def __init__(self):
        self.db = DbManager(
        )  # () koymazsak self parametresi eksik hatası veriyor ve çalışmıyor UNUTMA!!!!!! ()

    def initApp(self):
        msg = "*******\n1-Öğrenci Listesi\n2-Öğrenci Ekle\n3-Öğrenci Güncelle\n4-Öğrenci Sil\n5-Öğretmen Ekle\n6-Sınıflara Göre Dersler\n7-Çıkış(E/Ç)"
        while True:
            print(msg)
            islem = input("Seçiminiz Nedir: ")

            if islem == "1":
                self.displayStudents()
            elif islem == "2":
                self.addStudent()
            elif islem == "3":
                self.editStudent()
            elif islem == "4":
                self.deleteStudent()
            elif islem == "5":
                pass
            elif islem == "6":
                pass
            elif islem == "E" or islem == "Ç":
                break
            else:
                print("Yanlış Seçim...")

    def deleteStudent(self):
        classid = self.displayStudents()
        studentid = int(input("Öğrenci Id: "))

        self.db.deleteStudent(studentid)

    def editStudent(self):
        classid = self.displayStudents()
        studentid = int(input("Öğrenci Id: "))

        student = self.db.getStudentById(studentid)

        student[0].name = input("Adı: ") or student[
            0].name  # giriş yapmazsa önceki kayılı olan değer yüklensin diye bu şekilde yazdık
        student[0].surname = input("Soyadı: ") or student[0].surname
        student[0].gender = input("Cinsiyet (E/K) : ") or student[0].gender
        student[0].classid = int(input("Sınıf Id : ")) or student[0].classid

        year = input("Yıl : ") or student[0].birthdate.year
        month = input("Ay : ") or student[0].birthdate.month
        day = input("Gün : ") or student[0].birthdate.day

        student[0].birthdate = datetime.date(year, month, day)

        self.db.editStudent(student[0])

    def addStudent(self):
        self.displayClasses()
        classid = int(input("hangi sınıf: "))
        number = int(input("Öğrenci Numarası: "))
        name = input("Öğrenci Adı: ")
        surname = input("Öğrenci Soyadı: ")
        year = int(input("Doğum yılı: "))
        month = int(input("Ay: "))
        day = int(input("Gün: "))
        birthdate = datetime.date(year=year, month=month, day=day)
        gender = input("Cinsiyet(E/K): ")
        student = Student(None, number, name, surname, birthdate, gender,
                          classid)
        self.db.addStudent(student)

    def displayClasses(self):
        clss = self.db.getClasses()  # sınıflar bununla gelecek
        for i in clss:
            print(f"{i.id} : {i.name}")

    def displayStudents(self):
        self.displayClasses()
        classid = int(
            input("hangi sınıf: ")
        )  # tüm sınıfların listesini gösterip oradan seçmesini isteyeceğiz
        students = self.db.getStudentByClassId(classid)
        print("Öğrenci Listesi")
        for std in students:  # öğrencileri sıralı biçimde göstermek için index numaralarını da aldık bu şekilde
            print(f"{std.id}--{std.name} {std.surname}")
        return classid
Example #27
0
def main(gtfs_zip_or_dir, feed_url, db_file, interval):
    loader = transitfeed.Loader(feed_path=gtfs_zip_or_dir, memory_db=False)
    schedule = loader.Load()
    agency = schedule.GetAgencyList()[0]
    global time_zone
    time_zone = pytz.timezone(agency.agency_timezone)

    db_manager = DbManager(db_file)

    if not schedule.GetShapeList():
        logging.error("This feed doesn't contain shape.txt file. Exit...")
        return

    active_trips = ActiveTrips()

    logging.info("Start at local time {}".format(datetime.now()))
    while True:
        cnt, all = 0, 0
        before = time.time()
        feed = read_feed(feed_url)
        for entity in feed.entity:
            if entity.HasField('vehicle'):
                trip_id = entity.vehicle.trip.trip_id
                try:
                    trip = schedule.GetTrip(trip_id)
                except KeyError as e:
                    logging.warning(
                        "Faulty trip_id for entity: {}".format(entity))
                    continue
                all += 1
                vehiclePoint = Point.FromLatLng(
                    entity.vehicle.position.latitude,
                    entity.vehicle.position.longitude)
                try:
                    trip_state = TripState(trip, vehiclePoint,
                                           entity.vehicle.stop_id)
                except VehicleOutOfPolylineException as e:
                    logging.warning(
                        "Vehicle {1} is out of shape for trip_id {0}".format(
                            trip_id, (entity.vehicle.position.latitude,
                                      entity.vehicle.position.longitude)))
                    continue
                except StopFarFromPolylineException as e:
                    logging.warning(
                        "Couldn't reach all stops for trip_id {}".format(
                            trip_id))
                    continue

                cur_trip_progress = active_trips.get_trip_progress(trip_id)
                new_progress = trip_state.get_trip_progress()
                if trip_state.get_distance_to_end_stop(
                ) < 100 and cur_trip_progress == new_progress:
                    continue
                if cur_trip_progress is not None and new_progress < cur_trip_progress:
                    logging.warning(
                        "The trip_id {} seems to go backwards. Timestamp {}".
                        format(trip_id, entity.vehicle.timestamp))
                    continue
                if not active_trips.is_trip_active(
                        trip_id) and trip_state.get_prev_stop_seq() > 2:
                    continue

                prev_timestamp = active_trips.get_timestamp_for_trip(trip_id)
                if active_trips.is_trip_active(trip_id):
                    speed = trip_state.get_avrg_speed(
                        entity.vehicle.timestamp - prev_timestamp,
                        new_progress - cur_trip_progress)
                    if speed > 120:  #sanity check
                        logging.warning(
                            "Trip {} is trying to advance too quick -> {}km/h, timestamp {}"
                            .format(trip_id, speed, entity.vehicle.timestamp))
                        continue

                if entity.vehicle.timestamp != prev_timestamp:
                    cnt += 1
                    estimated_time = trip_state.get_estimated_scheduled_time()
                    stop_progress = trip_state.get_stop_progress()
                    delay = calculate_delay(
                        _normalize_time(entity.vehicle.timestamp),
                        estimated_time)
                    active_trips.add_update_trip(trip_id,
                                                 entity.vehicle.timestamp,
                                                 new_progress)
                    start_day = active_trips.get_day_for_trip(trip_id)
                    db_manager.insert_log(entity.vehicle.trip.route_id,
                                          trip_id,
                                          trip_state.get_prev_stop_seq(),
                                          entity.vehicle.timestamp, start_day,
                                          delay, new_progress, stop_progress)

        try:
            db_manager.commit()
        except OperationalError as e:
            logging.warning("Hard drive overload")
            continue

        active_trips.clean_inactive_trips(feed.header.timestamp)
        proc_time = time.time() - before
        logging.info("Procesing time {}. Saved {} out of {} records".format(
            proc_time, cnt, all))
        if interval - proc_time > 0:
            time.sleep(interval - proc_time)
        else:
            logging.warning("Processing is taking too long")
Example #28
0
class App:
    def __init__(self):
        self.db = DbManager()

    def initApp(self):
        msg = "*****\n1-Öğrenci Listesi\n2-Öğrenci Ekle\n3-Öğrenci Güncelle\n4-Öğrenci Sil\n5-Öğretmen Ekle\n6-Sınıflara Göre Dersler\n7-Çıkış (E/Ç)"
        while True:
            print(msg)
            islem = input("Seçim: ")
            if islem == "1":
                self.displayStudents()
            elif islem == "2":
                self.addStudent()
            elif islem == "3":
                self.editStudet()
            elif islem == "4":
                self.deleteStudent()
            elif islem == "5":
                pass
            elif islem == "E" or islem == "Ç":
                break
            else:
                print(" Yanlış Seçim..!")

    def deleteStudent(self):
        classid = self.displayStudents()
        studentid = int(input(" Öğrenci Id: "))

        self.db.deleteStudent(studentid)

    def editStudet(self):
        classid = self.displayStudents()
        studentid =int(input("Öğrenci Id : "))

        student = self.db.getStudenstById(studentid)

        student[0].name = input("Name : ") or student[0].name
        student[0].surname = input("SurName : ") or student[0].surname
        student[0].gender = input("Cinsiyet (E/K) : ") or student[0].gender
        student[0].classid = input("Sınıf : ") or student[0].classid
        
        year = input("Yıl: ") or student[0].birthdate.year
        month =input("Ay: ") or student[0].birthdate.month
        day = input("Gün: ") or student[0].birthdate.day

        student[0].birthdate = datetime.date(year,month,day)
        self.db.editStudent(student[0])



    
    def addStudent(self):
        self.displayClasses()
        classid = int(input("Hangi Sınıf: "))
        number = input("Öğrenci No: ")
        name = input("Ad: ")
        surname = input("Soyad: ")
        year = int(input("Yıl: "))
        month = int(input("Ay: "))
        day = int(input("Gün: "))
        birthdate = datetime.date(year,month,day)
        gender = input("Cinsiyet: (E/K)")

        student = Student(None,number, name,surname,birthdate,gender,classid)
        self.db.addStudent(student)

    def displayClasses(self):
        classes = self.db.getClasses()
        for i in classes:
            print(f"{i.id}: {i.name}")


    def displayStudents(self):
                
        classes = self.db.getClasses()
        for i in classes:
            print(f"{i.id}: {i.name}")
        classid = int(input("Hangi Sınıf: "))

        students = self.db.getStudentByClassId(classid)
        print("Öğrenci Listesi:")
        for std in students:
            print(f"{std.id}--{std.studentNumber}-{std.name} {std.surname}")
        return classid
Example #29
0
class App:
    def __init__(self):
        self.db = DbManager()

    def initApp(self):
        msg = "*****\n1-Öğrenci Listesi\n2-Öğrenci Ekle\n3-Öğrenci Güncelle\n4-Öğrenci Sil\n5-Öğretmen Listesi\n6-Öğretmen Ekle\n7-Öğretmen Güncelle\n8-Öğretmen Sil\n9-Sınıflara Göre Dersler\n7-Çıkış(E/Ç)"
        while True:
            print(msg)
            islem = input("Seçim: ")
            if islem == '1':
                self.displayStudents()
            elif islem == '2':
                self.addStudent()
            elif islem == '3':
                self.editStudent()
            elif islem == '4':
                self.deleteStudent()
            elif islem == '5':
                self.displayTeachers()
            elif islem == '6':
                self.addTeacher()
            elif islem == '7':
                self.editTeacher()
            elif islem == '8':
                self.deleteTeacher()
            elif islem == '9':
                self.getLessonsByClass()
            elif islem == 'E' or islem == 'Ç':
                break
            else:
                print("yanlış seçim")

    def deleteStudent(self):
        classid = self.displayStudents()
        studentid = int(input("öğrenci id: "))

        self.db.deleteStudent(studentid)

    def editStudent(self):
        classid = self.displayStudents()
        studentid = int(input("öğrenci id: "))

        student = self.db.getStudentById(studentid)

        student[0].name = input("name: ") or student[0].name
        student[0].surname = input("surname: ") or student[0].surname
        student[0].gender = input("gender (E/K): ") or student[0].gender
        student[0].classid = input("class: ") or student[0].classid

        year = input("year: ") or student[0].birthdate.year
        month = input("month: ") or student[0].birthdate.month
        day = input("day: ") or student[0].birthdate.day

        student[0].birthdate = datetime.date(year, month, day)
        self.db.editStudent(student[0])

    def addStudent(self):
        self.displayClasses()

        classid = int(input("hangi sınıf: "))
        number = input("numara: ")
        name = input("ad: ")
        surname = input("soyad: ")
        year = int(input("yıl: "))
        month = int(input("ay: "))
        day = int(input("gün: "))
        birthdate = datetime.date(year, month, day)
        gender = input("cinsiyet (E/K)")

        student = Student(None, number, name, surname, birthdate, gender,
                          classid)
        self.db.addStudent(student)

    def displayClasses(self):
        classes = self.db.getClasses()
        for c in classes:
            print(f"{c.id}: {c.name}")

    def displayStudents(self):

        self.displayClasses()
        classid = int(input("hangi sınıf: "))

        students = self.db.getStudentsByClassId(classid)
        print("Öğrenci Listesi")
        for std in students:
            print(f"{std.id}-{std.name} {std.surname}")

        return classid

    def deleteTeacher(self):
        self.displayTeachers()
        ogretmenid = int(input("öğretmen id: "))

        self.db.deleteTeacher(ogretmenid)

    def editTeacher(self):
        self.displayTeachers()
        ogretmenid = int(input("öğretmen id: "))

        ogretmen = self.db.getTeacherById(ogretmenid)

        ogretmen[0].branch = input("branch: ") or ogretmen[0].branch
        ogretmen[0].name = input("name: ") or ogretmen[0].name
        ogretmen[0].surname = input("surname: ") or ogretmen[0].surname
        ogretmen[0].gender = input("gender (E/K): ") or ogretmen[0].gender

        year = input("year: ") or ogretmen[0].birthdate.year
        month = input("month: ") or ogretmen[0].birthdate.month
        day = input("day: ") or ogretmen[0].birthdate.day

        ogretmen[0].birthdate = datetime.date(year, month, day)
        self.db.editTeacher(ogretmen[0])

    def addTeacher(self):

        branch = input("branş: ")
        name = input("ad: ")
        surname = input("soyad: ")
        year = int(input("yıl: "))
        month = int(input("ay: "))
        day = int(input("gün: "))
        birthdate = datetime.date(year, month, day)
        gender = input("cinsiyet (E/K)")

        ogretmen = Teacher(None, branch, name, surname, birthdate, gender)
        self.db.addTeacher(ogretmen)

    def displayTeachers(self):

        ogretmenler = self.db.getTeachers()
        print("Öğretmen Listesi")
        for std in ogretmenler:
            print(f"{std.id}-{std.name} {std.surname}")

    def getLessonsByClass(self):

        self.cursor = connection.cursor()
        self.cursor.execute(
            "SELECT class.Name, lesson.Name FROM lesson INNER JOIN class ON lesson.Id = class.Id GROUP BY(class.Id)"
        )
        result = self.cursor.fetchall()
        for i in result:
            print(f"Sınıf: {i[0]} - Dersler: {i[1]}")
Example #30
0
#coding=utf-8
import sys
import json
import os

sys.path.append("..")
from dbmanager import DbManager
from common import Common
os.chdir("../")

cfg = Common.loadConfig()
#print cfg['db']
db = DbManager()
db.initConn(cfg['db'])
sql = "show databases like 'cms_site_%'"
n,data = db.executeQuery(0,sql)
for row in data:
	pid = row[0].replace('cms_site_','')
	#创建statistics表
	sql = "CREATE TABLE IF NOT EXISTS `cms_template_statistics` (`template_id` int(11) NOT NULL COMMENT '模板id',`document_count` int(11) NOT NULL COMMENT '文档数',UNIQUE KEY `template_id` (`template_id`),KEY `document_count` (`document_count`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;"
	n,createdata = db.execute(pid,sql)
	print sql
	print '@@@@@@@@'
	sql = "show tables like 'cms_tbl_%'"
	n ,tbldata = db.executeQuery(pid,sql)
	for tbl in tbldata:
		tid = tbl[0].replace('cms_tbl_','')
		sql = 'select count(document_id) as doc_count from '+tbl[0]
		n,statdata = db.executeQuery(pid,sql)
		for stat in statdata:
			print 'TID:',tid,' Count:',stat[0]
Example #31
0
    def display_accounts(self):
        self.showButtons.clear()
        self.toDisable.clear()
        for row in self.accountsRowsWidgets:
            for widget in row.values():
                widget.destroy()

        self.accountsRowsWidgets.clear()
        accounts = DbManager.get_user_accounts(self.user['id'])

        for i in range(len(accounts)):
            title = tk.Label(self.scrollframe.viewPort,
                             text=accounts[i]['title'],
                             bg=self.bg_color)
            title.grid(row=i + 1, column=0)

            login = tk.Label(self.scrollframe.viewPort,
                             text=accounts[i]['login'],
                             bg=self.bg_color)
            login.grid(row=i + 1, column=1)

            associated_email = tk.Label(self.scrollframe.viewPort,
                                        text=accounts[i]['associated_email'],
                                        bg=self.bg_color)
            associated_email.grid(row=i + 1, column=2)

            # SHOW BTN
            show_btn = tk.Button(self.scrollframe.viewPort,
                                 text=lp[self.language]['enter_pin_to_show'],
                                 bg='white')
            show_btn.grid(row=i + 1, column=3)
            self.showButtons.append({
                'btn': show_btn,
                'y': i + 1,
                'x': self.passwordWidth,
                'acc_id': accounts[i]['id']
            })
            self.showButtons[i]['btn'][
                'command'] = lambda btn=self.showButtons[
                    i]: self.show_password(btn)

            # EDIT BTN
            edit_btn = tk.Button(self.scrollframe.viewPort,
                                 text=lp[self.language]['edit'],
                                 bg='white',
                                 command=lambda index=i: self.edit_account(
                                     accounts[index]['id']))
            edit_btn.grid(row=i + 1, column=99)
            self.editButtons.append({
                'btn': edit_btn,
                'x': self.editWidth,
                'y': 0.05 * i
            })

            # DELETE BTN
            delete_btn = tk.Button(self.scrollframe.viewPort,
                                   text=lp[self.language]['delete'],
                                   bg='red',
                                   fg='white',
                                   command=lambda index=i: self.delete_account(
                                       accounts[index]['id']))
            delete_btn.grid(row=i + 1, column=100)

            row = {
                'title': title,
                'login': login,
                'associated_email': associated_email,
                'show_btn': show_btn,
                'edit_btn': edit_btn,
                'delete_btn': delete_btn
            }

            self.accountsRowsWidgets.append(row)

            self.toDisable.append(edit_btn)
            self.toDisable.append(delete_btn)

        self.toDisable.append(self.addAccountBtn)
Example #32
0
_PROFIT_ = Decimal(0.001)

decimal_precision = 1000000  # 6

openpos = False
pos = Position('null', -99, -99)
net = Decimal(0)
capital = Decimal(1000)
count = 0

lastdate = None

lastbuy = None
lastsell = None

manager = DbManager()
manager.connect('kraken.db')

pd.options.display.width = 0


def data_writer(data):
    t = time.localtime()
    current_time = time.strftime("%H:%M:%S", t)
    f = open("tetherdata.txt", "a")
    f.write(data + "\n")


def margin_check():
    bid_ask = c.getBidAsk('USDTZUSD')
    bidmargin = bid_ask[0] - 1
Example #33
0
 def __init__(self):
     self.db = DbManager(
     )  # () koymazsak self parametresi eksik hatası veriyor ve çalışmıyor UNUTMA!!!!!! ()
Example #34
0
 def getSession(self):
     dbManager = DbManager.getInstance()
     if dbManager:
         return dbManager.getSession()
     else:
         return None
Example #35
0
    def register(self):
        login = self.regLogEntry.get()
        password = self.regPasswordEntry.get()
        password_confirm = self.regPasswordConfirmEntry.get()
        email = self.regEmailEntry.get()
        pin = self.regPinEntry.get()

        if '' in (login, password, password_confirm, email, pin):
            messagebox.showerror(lp[self.language]['error'],
                                 lp[self.language]['fill_all_entries'])
            Window.delete_entries(self.regPasswordEntry,
                                  self.regPasswordConfirmEntry,
                                  self.regPinEntry)
            return

        login_in_db = DbManager.get_column_values('Users', 'login')

        if login in login_in_db:
            messagebox.showerror(
                lp[self.language]['error'],
                lp[self.language]['login_used'].format(login=login))
            Window.delete_entries(self.regLogEntry, self.regPasswordEntry,
                                  self.regPasswordConfirmEntry,
                                  self.regEmailEntry, self.regPinEntry)
            return

        if len(password) < 8:  # password minimum length
            messagebox.showerror(lp[self.language]['error'],
                                 lp[self.language]['min_8_chars'])
            Window.delete_entries(self.regPasswordEntry,
                                  self.regPasswordConfirmEntry,
                                  self.regPinEntry)
            return

        if password != password_confirm:
            messagebox.showerror(lp[self.language]['error'],
                                 lp[self.language]['confirm_dont_match'])
            Window.delete_entries(self.regPasswordEntry,
                                  self.regPasswordConfirmEntry,
                                  self.regEmailEntry, self.regPinEntry)
            return

        if not re.match(r'[^@]+@[^@]+\.[^@]+', email):
            messagebox.showerror(lp[self.language]['error'],
                                 lp[self.language]['invalid_email'])
            Window.delete_entries(self.regPasswordEntry,
                                  self.regPasswordConfirmEntry,
                                  self.regEmailEntry, self.regPinEntry)
            return

        verification_code = random.randint(100000, 999999)
        MailManager.send_mail(self.language,
                              email,
                              msg_type='thanks',
                              data=login,
                              data2=verification_code)
        entered_code = simpledialog.askinteger(
            lp[self.language]['email_verification'],
            lp[self.language]['please_verify_email'])

        if entered_code != verification_code:
            messagebox.showerror(lp[self.language]['error'],
                                 lp[self.language]['invalid_veri_code'])
            Window.delete_entries(self.regLogEntry, self.regPasswordEntry,
                                  self.regPasswordConfirmEntry,
                                  self.regEmailEntry, self.regPinEntry)
            return

        if entered_code == verification_code:
            DbManager.insert('Users', 'login, password, email, pin',
                             (login, password, email, pin))
            Window.delete_entries(self.regLogEntry, self.regPasswordEntry,
                                  self.regPasswordConfirmEntry,
                                  self.regEmailEntry, self.regPinEntry)
            messagebox.showinfo(
                lp[self.language]['success'],
                lp[self.language]['user_created'].format(user=login))