예제 #1
0
def edit(request):
    ctx = {'title': '게시판'}
    ctx['authority'] = '0'
    if Login.get_current_user(request) == -1:
        return render(request, 'login_please.html')
    user = Login.get_current_user(request)
    ctx['user_id'] = Login.get_current_user(request).user_id
    ctx['number'] = Login.get_current_user(request).new_message
    date = request.GET.get('date')
    uid = request.GET.get('id')
    memo = board.objects.get(date=date, author=uid)
    if memo.author != user.user_id:
        ctx['authority'] = '1'
    if request.method == "POST":
        user = Login.get_current_user(request)
        memo.title = request.POST.get('title')
        memo.text = request.POST.get('content')
        memo.author = user.user_id
        memo.date = str(time.time())
        memo.category = request.POST.get('category')
        if memo.category == 'notice' and (memo.author != "parksjin01" and memo.author != "damotorie"):
            ctx['authority'] = '1'
            return render(request, 'write.html', ctx)
        memo.save()
        redirect_url = '/board/?c=' + request.POST.get('category')
        return redirect(redirect_url)
    ctx['Title'] = memo.title
    ctx['Content'] = memo.text
    ctx['category'] = memo.category
    return render(request, 'edit_memo.html', ctx)
예제 #2
0
def verifica_login():
	#Almacena lo que se ingreso en las cajas
	usuario1 = check_user.get()
	clave1 = check_password.get()

	global password_counter
	global username_counter

	entry_user_login.delete(0,END)
	entry_password_login.delete(0,END)

		#CHECK USERNAME AND PASSWORD AND DEPENDING ON THE OUTPUT DO:
	#AND TO FINISH, CREATE A WINDOW WITH THE MESSAGE

	#The windows already close without killing the program. what you need is a counter and a function capable to saying "Fk u" when the chances run out.

	
	if Login.CheckUsername(usuario1): #the username exists
		if Login.CheckPw(usuario1, clave1): #the password is correct
			message_window("Todo bien master")
		else:
			password_counter = password_counter -1
			if password_counter == 0:
				message_window("Se acabaron los intentos.")
				close_window(login_window)
			else:
				message_window("La contraseña esta mal master. Tienes %i intentos restantes."%password_counter)
			
	else:
		username_counter = username_counter -1
		if username_counter == 0:
				message_window("Se acabaron los intentos.")
				close_window(login_window)
		else:
			message_window("El usuario no existe master. Tienes %i intentos restantes."%username_counter)
예제 #3
0
def exitUsernameScreen(app):
    app.newUser_canvas.destroy()
    app.unEntry = None
    app.notify = None
    app.labels = None
    app._login.clear()
    Login.requestUsername(app)
def run(user_data, db_list, completed_log, error_log, login_fail_log):
    import sys
    modules_path = r'C:\Python_Scripts\Advantx_3.0\Modules'
    sys.path.append(modules_path)
    import Functions
    import Logs
    import Login
    import time
    import Error_Checking
    import Open_Database
    for DB in db_list:
        db_login = Open_Database.open_ADV(DB, login_fail_log)
        if db_login == 1:
            Login.login()
            error = Error_Checking.get_Errors(DB, login_fail_log)
            if error == 9:
                Functions.open_userTables()
                for user_info in user_data:
                    user = user_info[1] + "," + user_info[0]
                    gng = Functions.find_user(user, user_info)
                    if gng == 0:
                        Functions.add_user(DB,user_info)
                        Logs.log_complete(user_info, completed_log)
                    else:
                        Functions.update_access_level(user_info)
                        Logs.log_complete(user_info, completed_log)
            else:
                Logs.login_failed(DB, login_fail_log)
            Functions.close_app()
            time.sleep(2)
        if db_login == 0:
            pass
예제 #5
0
파일: Message.py 프로젝트: onetera/sp
def getMessage(msgidx, readStamp=True):
	""" 쪽지를 읽어온다 """
	
	mData = Archive("MsgInBox").getValues(msgidx, "Content,Receiver,Sender,Attachments,IsRead")
	
	if mData == None:
		raise SpartaUserError("존재하지 않는 쪽지번호 입니다")
	
	if mData["Receiver"] != Login.getID() and mData["Sender"] != Login.getID():
		raise SpartaUserError("메세지를 볼수있는 권한이 없습니다")
	
	if readStamp and (mData["IsRead"] == False):
		# 스탬핑 처리
		Archive("MsgInBox").Edit(msgidx, IsRead=True)
		
		# 보낸 편지에도 읽기 스템핑
		r_idx = Archive("MsgSent").getValue("MsgSent.RelateIDX == "+str(msgidx), "IDX")
		if r_idx:
			Archive("MsgSent").Edit(r_idx, IsRead=True)			   
	
	outText = mData["Content"]
	
	if mData["Attachments"]:		
		outText += u'<table class="filedownBox"><tr><td>첨부</td><td><a href="/getfile/message/%s">%s</a></td></tr></table>' % ( msgidx, mData["Attachments"])
	
	return outText
예제 #6
0
    def test_add_load(self):
        """QQ登录测试"""
        width = self.driver.get_window_size()['width']
        height = self.driver.get_window_size()['height']

        Login.login(self)
        sleep(4)
        self.driver.find_element_by_android_uiautomator(
            'new UiSelector().description("帐户及设置")').click()
        sleep(1)
        self.driver.find_element_by_android_uiautomator(
            'new UiSelector().description("设置")').click()
        sleep(2)
        self.driver.find_element_by_xpath(
            '//android.widget.TextView[contains(@text, "帐号管理")]').click()
        self.driver.swipe(width / 2, height / 2, width / 2, height / 4, 1000)
        self.driver.find_element_by_name("退出当前帐号").click()
        self.driver.find_element_by_xpath(
            '//android.widget.TextView[contains(@text, "确认退出")]').click()

        try:

            sleep(2)
            self.driver.swipe(width / 2, height / 2, 114, height / 2, 1000)
            sleep(2)
        except Exception as e:
            print(e)
def tambah_admin(admin_data, admin_id, hdata):
    admin = [i for i in admin_data]
    while True:
        os.system("cls")
        print("=" * 80)
        print("ATM CGK".center(79))
        print("_" * 80)
        print("Tambah Admin".center(80))
        print("=" * 80)
        new_adm = input(f"{'':20}Masukan Admin baru\t= ").strip()
        new_name = " "
        if new_adm in admin:
            print("admin sudah ada".center(80))
            os.system("pause")
            continue
        elif new_adm == "0":
            break
        elif new_adm == "":
            continue
        elif any(i.isnumeric() for i in new_adm):
            print(f"\n{'':20}User jangan ada angka dong")
            time.sleep(2)
            continue
        elif len(new_adm) < 5:
            print("Rekening kependekan".center(80))
            time.sleep(2)
            continue
        c = input(f"\n{'':20}Masukan nama anda\t= ")
        if c[0] == "":
            continue
        new_name = ""
        for i in c.split(" "):
            new_name += i.capitalize() + " "
        if new_name == "":
            print(f"{'':20}Invalid input")
            os.system("pause")
            continue
        elif any(i.isnumeric() for i in new_name):
            print(f"\n{'':20}Nama kau bagus sikit")
            time.sleep(2)
            continue
        os.system("cls")
        print("=" * 80)
        print("ATM CGK".center(79))
        print("_" * 80)
        print("Tambah Admin".center(80))
        print("=" * 80)
        print(f"\n{'':20}Masukan password \t= ", end="")
        Login.add_new_adm()
        new_pass = Login.add_new_adm.password
        if len(new_pass) < 4:
            print(f"{'':20}Password anda kependekan")
            os.system("pause")
            continue
        else:
            admin_data[new_adm] = {"name" : new_name[:-1],"pass" : new_pass\
            ,"auth" : "admin","status" : "active"}
            record.add_adm(new_adm, admin_id, hdata)
            print(f"\n{'':20}Berhasil")
        break
 def back():
     back = tkinter.messagebox.askyesno("Breast Cancer Prediction",
                                        "Do you want to back?")
     if (back == True):
         root.destroy()
         import Nav1_Login as lg
         lg.log_out()
예제 #9
0
def config_upload(ip):
    #ip=raw_input("Enter the IP address of the PDU")
    global driver
    driver = Login.login(ip)
    #output=File_Creation.file_create()
    print("############UPLOAD REQUIRED CONFIGURATION##########")
    #output.write("############UPLOAD REQUIRED CONFIGURATION##########")
    se = driver.find_elements_by_tag_name("svg")
    se[4].click()
    part = driver.find_elements_by_tag_name("a")
    part[2].click()
    time.sleep(4)
    driver.find_element_by_xpath(".//*[contains(text(), 'Action')]").click()
    time.sleep(3)
    driver.find_element_by_xpath(
        ".//*[contains(text(), 'Upload Configuration')]").click()
    time.sleep(2)
    cnf = driver.find_elements_by_tag_name("input")
    time.sleep(2)
    path = os.getcwd() + "/conf.ini"
    cnf[0].send_keys(path)
    time.sleep(1)
    up = driver.find_elements_by_tag_name("button")
    time.sleep(2)
    up[1].click()
    print(
        "PLEASE WAIT WHILE THE REQUIRED CONFIGURATION FLASH AND REBOOT THE PDU.IT MAY TAKE 40 sec .\n.PLEASE WAIT...."
    )
    for i in xrange(40, 0, -1):
        sys.stdout.write(str(i) + ' ')
        sys.stdout.flush()
        time.sleep(1)
    Login.login(ip)
    #output.close()
    return driver
예제 #10
0
def Crawler(number, weibo_url):
    Login.login()  #首先进行模拟登录
    fp4 = open("chinese_weibo.txt","w+")  #初始化写入文件
    for n in range(number):
        n = n + 1
        url = 'http://weibo.com/' + weibo_url + '?is_search=0&visible=0&is_tag=0&profile_ftype=1&page=' + str(n)
        # url = 'http://s.weibo.com/weibo/%s&Refer=index'%weibo_url
        print U"爬取URL:",url
        content = Getraw_HTML.get_rawHTML(url)  # 调用获取网页源文件的函数执行
        print u"获取第 %d  成功 , 并写入到 raw_html.txt"%n
        Gettext_CH.Handel(content, fp4)         # 调用解析页面的函数
        print u"获取第 %d 微博内容成功, 并写入到 chinese_weibo.txt"%n
        #time.sleep(1)
    fp4.close()
    ########## 数据爬取完毕!
    # 对爬取到的微博进行去重处理
    fp = open('chinese_weibo.txt', 'r')
    contents = []
    for content in fp.readlines():
        content = content.strip()
        contents.append(content)
    fp.close()
    set_contents = list(set(contents))
    set_contents.sort(key=contents.index)
    fp_handel = open('chinese_weibo.txt', 'w+')
    for content in set_contents:
        fp_handel.write(content)
        fp_handel.write('\n')
    fp_handel.close()
예제 #11
0
파일: Listen.py 프로젝트: parksjin01/2017-
def search(request):
    key, extend = request.GET.get('key'), request.GET.get('e')
    context = {}
	# 서버에 헤당 검색어를 포함한 동영상있는지 확인한다.
    db = youtube.objects.filter(title__contains=key)
    if Login.get_current_user(request) != -1:
        context['user_id'] = Login.get_current_user(request).user_id
    else:
        return render(request, 'login_please.html')
    user_youtube = json.loads(Login.get_current_user(request).youtube)
    if len(db) > 0:
        tmp_db = []
        for d in db:
            video_id = d.url.split('?v=')[1]
			# If user has same Youtube URL in user database, make link attached to dictation. 
			# If not make link attached to video caption download 
            if d.url in user_youtube:
                tmp_db.append(('/video/' + d.hashed_url, d.title, IMG_URL % video_id))
            else:
                tmp_db.append(('/video/add/'+video_id, d.title, IMG_URL %video_id))
        context['db'] = tmp_db
	# There are two options.
	# First extend is '0' which means don't search video with Youtube API
	# Second extend is '1' which means search video with Youtube API. You can get more results.
    if extend == '1':
        video = youtube_search(video_name=key, max_results=20)
        context['video'] = video
    return render(request, "search.html", context)
예제 #12
0
def pretragaPoZanru():
    listaProjekcija = Menadzer.azuriraj()
    listaFilmova = Menadzer.azurirajFilmove()
    prikazZanrova()
    zanrovi = dodavanjeZanrova()

    netacanUnos = True
    while netacanUnos:
        try:
            unosZanra = int(input())
            netacanUnos = False
        except ValueError:
            netacanUnos = True
            print("Unos rijeci nije dozvoljen, pokusajte ponovo")

    if netacanUnos == False:
        unosZanra -= 1
        if unosZanra >= 0 and unosZanra <= len(zanrovi):
            print()
            print("Izabrali ste zanr: " + zanrovi[unosZanra])
            for i in listaFilmova:
                if zanrovi[unosZanra] in i["zanr"]:
                    for j in listaProjekcija:
                        if i["naziv"] == j["film"]:
                            print("Film: " + j["film"] + "\n   Datum: " +
                                  j["datum"] + " - " + j["vrijemePocetka"] +
                                  "\n   Duzina: " + j["duzina"] +
                                  "\n   Cijena: " + j["cijena"] +
                                  "\n   Sala: " + j["sala"] +
                                  "\n   Slobodno mjesta: " +
                                  j["slobodnoMjesta"])

    print("")
    Login.redirect()
예제 #13
0
파일: Listen.py 프로젝트: parksjin01/2017-
def video_list(request):
    tube = youtube.objects.order_by('-date').all()
    ctx = {}
    video = []
    user = Login.get_current_user(request)
	#로그인이 되어있지 않다면 login_please.html 띄우기
    if user == -1:
        return render(request, "login_please.html")
    user_youtube = json.loads(user.youtube)
    for vod in tube:
		#user_youtube 동영상 url이 없을경우
        if vod.url not in user_youtube:
            continue
        cap = vod.caption
        line = 0
		#운영체제별 개행문자
        if '\r\n' in cap:
            line = cap.strip().split('\r\n\r\n')[-1].split('\r\n')[0]
        else:
            line = cap.strip().split('\n\n')[-1].split('\n')[0]
        img = IMG_URL % (vod.url.split('?v=')[1])
        tmp_fmt = "'%s'"
        description = vod.description
        if len(description) > 200:
            description = description[:200] + ' ...'
		#비디오 추가
        video.append(('/video/' + vod.hashed_url, vod.title, description, img, tmp_fmt % (img + '!@#' + line)))
    ctx['video'] = video
    ctx['title'] = 'ML(MyLang) Video List'
    ctx['user_id'] = Login.get_current_user(request).user_id
    ctx['number'] = Login.get_current_user(request).new_message
    return render(request, 'show_list.html', ctx)
예제 #14
0
def pretragaNavigacija():

    netacanUnos = True
    while netacanUnos:
        try:
            unosBroja = int(
                input("Unesite redni broj po kojem zelite pretrazivati: "))
            netacanUnos = False
        except ValueError:
            print("Unos rijeci nije dozvoljen, pokusajte ponovo")
            netacanUnos = True

        if netacanUnos == False:
            if unosBroja == 1:
                print("Unesite ID projekcije: ")
                Pretraga.pretragaPoID()
            elif unosBroja == 2:
                print("Unesite naziv filma: ")
                Pretraga.pretragaPoNazivu()
            elif unosBroja == 3:
                print("Unesite redni broj zanra filma: ")
                Pretraga.pretragaPoZanru()
            elif unosBroja == 4:
                print("Unesite redni broj sale: ")
                Pretraga.pretragaPoSali()
            elif unosBroja == 5:
                Login.redirect()
            else:
                print("Unesite jedan od ponudjenih brojeva")
                netacanUnos = True
                pretragaPrikaz()
예제 #15
0
파일: Main.py 프로젝트: Cyrotian/Reminder
def main():
    sg.theme('DarkBlue1')
    button_font_size = 20
    layout = [
        [sg.Text('Reminder', justification='center', size=(1000, 1), font=('Sans', 30))],
        [sg.Text('')],
        [sg.Button('Login', font=('Sans', 15), size=(15, 1))],
        [sg.Text('')],
        [sg.Button('Create Account', font=('Sans', 15), size=(15, 1))],
        [sg.Text('')],
        [sg.Button('Exit', font=('Sans', 15), size=(15, 1))]
    ]

    window = sg.Window('Reminder', layout, size=(300, 300), grab_anywhere=True, element_justification='c')

    while True:
        event, values = window.read()
        if event == "Exit" or event == sg.WIN_CLOSED:
            break

        if event == "Login":
            window.close()
            lg.main()
            break

        if event == "Create Account":
            window.close()
            ca.main()
            break
    def register(event=None):
        Database()
        if USERNAME.get() == "" or PASSWORD.get() == "" and Name.get(
        ) == "" and Phone.get() == "" and Age.get() == "":
            lbl_text.config(text="Please complete the required field!",
                            fg="red")
        else:
            cursor.execute(
                "SELECT * FROM `member` WHERE `username` = ? AND `password` = ?",
                (USERNAME.get(), PASSWORD.get()))
            if cursor.fetchone() is not None:
                messagebox.showinfo("Information", "Registration Successful")
                root.destroy()
                import Login as lg
                lg.log_out()
                USERNAME.set("")
                PASSWORD.set("")


#                lbl_text.config(text="")
            else:
                lbl_text.config(text="Invalid username or password", fg="red")
                USERNAME.set("")
                PASSWORD.set("")
        cursor.close()
        conn.close()
예제 #17
0
def user_settings_verify(ip):
    driver = Login.login(ip)
    #=File_Creation.file_create()
    ################VERIFYING ROLE OF THE USER#######
    print("################VERIFYING ROLE OF THE USER#######")
    #.write("\n################VERIFYING ROLE OF THE USER#######")
    print("CHECKING THE PRIVILAGE OF THE USER")
    #.write("\nCHECKING THE PRIVILAGE OF THE USER")
    time.sleep(3)
    try:
        a = driver.find_elements_by_tag_name("svg")
        a[4].click()
        print("THE USER HAS ADMINISTRATOR PRIVILAGE")
        #.write("\nTHE USER HAS ADMINISTRATOR PRIVILAGE")
    except:
        print("THE ROLE OF THE USER IS LIMITED TO **USER**")
        #.write("\nTHE ROLE OF THE USER IS LIMITED TO **USER**")
    print("CHANGING THE ROLE OF THE USER")
    driver.find_element_by_xpath(".//*[contains(text(), 'TEST')]").click()
    time.sleep(1)
    driver.find_element_by_xpath(".//*[contains(text(), 'Log Out')]").click()
    time.sleep(3)
    Login.login(ip)
    driver.find_element_by_xpath(".//*[contains(text(), 'admin')]").click()
    time.sleep(1)
    driver.find_element_by_xpath(
        ".//*[contains(text(), 'User Accounts')]").click()
    time.sleep(1)
    a = driver.find_elements_by_tag_name("svg")
    a[10].click()
    time.sleep(2)
    pas = driver.find_element_by_name("cpassword")
    pas.send_keys("1234567!")
    a = driver.find_elements_by_tag_name("label")
    a[3].click()
    time.sleep(1)
    driver.find_element_by_xpath(".//*[contains(text(),'Save')]").click()
    time.sleep(1)
    driver.find_element_by_xpath(".//*[contains(text(),'OK')]").click()
    print("\nLOGGING OUT WITH THE CURRENT USER TO VERIFY NEW ROLE")
    time.sleep(5)
    driver.find_element_by_xpath(".//*[contains(text(), 'admin')]").click()
    time.sleep(1)
    driver.find_element_by_xpath(".//*[contains(text(), 'Log Out')]").click()
    time.sleep(3)
    Login.login(ip)
    print("CHECKING THE PRIVILAGE OF THE USER")
    time.sleep(1)
    try:
        a = driver.find_elements_by_tag_name("svg")
        a[4].click()
        print("THE USER HAS ADMINISTRATOR PRIVILAGE.ROLE CHANGED SUCCESFULLY")
        #.write("\nTHE USER HAS ADMINISTRATOR PRIVILAGE.ROLE CHANGED SUCCESFULLY")
    except:
        print("THE ROLE OF THE USER IS LIMITED TO **USER**")
        #.write("\nTHE ROLE OF THE USER IS LIMITED TO **USER**")

    #.close()
    return driver
예제 #18
0
def tambah_rekening(admin_id, user_data, hdata):
    rekening = [i for i in user_data]
    while True:
        os.system("cls")
        print("=" * 80)
        print("ATM CGK".center(79))
        print("_" * 80)
        print("Tambah Rekening".center(80))
        print("=" * 80)
        new_rek = input(f"{'':20}Masukan Rekening baru\t= ").strip()
        if new_rek in rekening:
            print("Rekening sudah ada".center(80))
            os.system("pause")
            continue
        elif new_rek == "0":
            break
        elif new_rek == "":
            continue
        elif any(i.isalpha() for i in new_rek):
            print(f"{'':22}Rekening ada huruf yah?")
            time.sleep(2)
            continue
        elif len(new_rek) < 5:
            print("Rekening kependekan".center(80))
            time.sleep(2)
            continue
        c = input(f"\n{'':20}Masukan nama anda\t\t= ")
        if c[0] == " ":
            continue
        new_name = ""
        for i in c.split(" "):
            new_name += i.capitalize() + " "
        if new_name == "":
            print(f"{'':20}Invalid input")
            os.system("pause")
            continue
        elif any(i.isnumeric() for i in new_name):
            print(f"\n{'':20}Nama kau bagus sikit")
            time.sleep(2)
            continue
        os.system("cls")
        print("=" * 80)
        print("ATM CGK".center(79))
        print("_" * 80)
        print("Tambah Rekening".center(80))
        print("=" * 80)
        print(f"\n{'':20}Masukan password [0-9]\t= ", end="")
        Login.add_new_rek()
        new_pass = Login.add_new_rek.password
        if len(new_pass) < 4:
            print(f"\n{'':20}Password anda kependekan")
            os.system("pause")
            continue
        else:
            user_data[new_rek] = {"name" : new_name[:-1],"pass" : new_pass\
            ,"saldo":0,"auth" : "user","status" : "active"}
            record.add_rek(admin_id, new_rek, hdata)
            print(f"\n{'':20}Berhasil")
        break
예제 #19
0
 async def dayonece():
     now = datetime.now().strftime('%H:%M')
     if now == '07:00':
         oldpoint = Login.my_points(1)
         channel = client.get_channel(CHANNEL_ID)
         Login.pointgatya()
         newpoint = int(Login.my_points(1)) - int(oldpoint)
         await channel.send(newpoint + "\n" + "ガチャ終了")
예제 #20
0
    def conditioncheck(self,roleid,user):
        self.roleid = roleid
        if self.roleid == 1 or self.roleid == 2:
            if self.crud == 1:
                cso = CreateSO()
                cso.initCall(user)

            elif self.crud == 2:
                uso = UpdateSO()
                uso.initCall(user)

            elif self.crud == 3:
                dso= DeleteSO()
                dso.initCall(user)

            elif self.crud==4:
                vso = ViewSO()
                vso.initCall(user)
            
            elif self.crud  == 5:
                iws = ItemwiseSales()
                iws.initCall(user)

            elif self.crud == 0:
                loginModule = Login.Login()
                loginModule.initialCall(user)
            else:
                print("Please choose correct number!!!\n")
                self.initCall(user)
        
        elif self.roleid == 3:
            if self.crud == 1:
                cso = CreateSO()
                cso.initCall(user)
            
            elif self.crud == 2:
                uso = UpdateSO()
                uso.initCall(user)
            
            elif self.crud==3:
                vso = ViewSO()
                vso.initCall(user)

            elif self.crud == 4:
                iws = ItemwiseSales()
                iws.initCall(user)
            
            elif self.crud ==0:
                loginModule = Login.Login()
                loginModule.initialCall(user)
            
            else:
                print("Please choose correct number!!!\n")
                self.initCall(user)
        
        else:
            print("Role Id is undefined.Please contact admin!!!")
            return
예제 #21
0
def createPostPage():
    if 'user' in session:

        if request.method == "POST":

            if request.files["image"]:
                image = request.files["image"]
                imagePresent = True

            else:
                imagePresent = False

            if "description" in request.form:

                description = request.form["description"]
                print(request.form["description"])

            else:

                description = ''

            if imagePresent:

                fileExtenstion = '.' + image.filename.split('.')[1]
                newfilename = str(
                    Login.getMostRecentPostId()[0]) + fileExtenstion

                print(
                    url_for('static',
                            filename='post-pics/' + newfilename +
                            fileExtenstion))

                Login.createPost(image=imagePresent,
                                 description=description,
                                 username=session['user'],
                                 imageName=newfilename)

                image.save(
                    os.path.join(app.config['POST_FOLDER'], image.filename))
                os.rename(
                    os.path.join(app.config['POST_FOLDER'], image.filename),
                    os.path.join(app.config['POST_FOLDER'], newfilename))

            else:
                Login.createPost(image=imagePresent,
                                 description=description,
                                 username=session['user'],
                                 imageName=None)

            return redirect(url_for("newsfeedPage"))

        else:
            return render_template("create-post.html", user=session['user'])

    else:
        return redirect(url_for("landingPage"))
예제 #22
0
파일: Listen.py 프로젝트: parksjin01/2017-
def dictation(request, name):
    if request.method == 'POST':
        vod = youtube.objects.get(hashed_url=name)
        cur_date = request.COOKIES.get('youan')
        tmp = tmp_answer.objects.get(cur_date=cur_date, cur_user=request.COOKIES.get('ec'))
        answer = tmp.answer
        question = tmp.question
        answer = pickle.loads(binascii.unhexlify(answer))
        user = request.POST.getlist('blank')
        score = check_answer(user, answer)
        idx = 0
		#
        for correct in answer:
			#정오답 표시
            if correct == user[idx]:
                tmp_idx = question.index('<input type=text name=blank></input>')
                question = question[:tmp_idx]+('<span style="border-bottom: solid; border-bottom-color: deepblue;">%s</span>' %user[idx])+question[tmp_idx+36:]
            else:
                tmp_idx = question.index('<input type=text name=blank></input>')
                question = question[:tmp_idx] + (
                '<span style="border-bottom: solid; border-bottom-color: deeppink;">%s</span>' % user[idx]) + question[tmp_idx+36:]
            idx += 1
        message = {
            'video': '<iframe width="560" height="315" src="https://www.youtube.com/embed/' + vod.url.split('?v=')[
                1] + '"frameborder="0"></iframe>', 'title':'듣기 평가', 'result': question
        }

        message['score'] = score
        message['user_id'] = Login.get_current_user(request).user_id
        message['number'] = Login.get_current_user(request).new_message
        user = user_info.objects.get(user_email=base64.b64decode(request.COOKIES.get('ec')))
		#점수기록
        level = []
        if user.listening_level == '':
            user.level = json.dumps(level)
        level = json.loads(str(user.listening_level))
        try:
            score = [score, time.time()]
            level = [score] + level
        finally:
            user.listening_level = json.dumps(level)
            user.save()
        tmp.delete()
        return render(request, 'dictation.html', message)
	#영상이 없을경우 에러
    vod = get_object_or_404(youtube, hashed_url=name)
    user = Login.get_current_user(request)
	#로그인이 되어있지 않다면 login_please.html 띄우기
    if user == -1:
        return render(request, "login_please.html")
    try:
        his = history.objects.filter(cur_user=base64.b64encode(user.user_email))[0]
    except Exception, e:
        print e
        his = history()
예제 #23
0
def updateCompanyInfo(companyname,employees_num,major,annualsale,introduce,web,address):
    basicDB = BasicDB()
    conn = basicDB.conn
    curs = conn.cursor()

    sql="update company set companyname='"+companyname+"', employees_num="+employees_num+", major='"+major+\
        "', annualsales='"+annualsale+"', introduce='"+introduce+"', web='"+web+"',address='"+address+\
        "' where id='"+Company.ID+"';"
    curs.execute(sql)
    conn.commit()

    Login.saveCompanyInfo();
예제 #24
0
def main():
    print("Enter Your choise")
    print("1. SignUp")
    print('2. LogIn')
    print()
    choise=input()
    if(choise=='1'):
        Login.signup()
    elif(choise=='2'):
        username = input ("Enter Mail Id")
        password = input ("Enter Password")
        Login.login(username,password)
예제 #25
0
    def leaving(self):
        self.db.commit()
        # user뿐 아니라 다른 table에서도 다 지워야 함
        # is_Delete 값 변경
        sql = "UPDATE User SET Is_deleted = 'Y' WHERE User_ID = '%d'" % self.user_ID
        self.cursor.execute(sql)
        self.db.commit()
        print("\nSUCCESS : DELETE Your ID")
        print("Leaving Drello. JOIN AGAIN.")

        input("\n\nPlease Enter to go to NEXT ! :")
        Login.start(self.db)
예제 #26
0
def home(request):
    message = {}
    message['title'] = 'ML(MyLanguage)'
    try:
        user_email = request.COOKIES.get('ec')
        answers = tmp_answer.objects.filter(cur_user=user_email)
        message['user_id'] = Login.get_current_user(request).user_id
        message['number'] = Login.get_current_user(request).new_message
        for answer in answers:
            answer.delete()
    except Exception, e:
        print e
예제 #27
0
파일: Message.py 프로젝트: onetera/sp
def removeMessage(msgidx):
	
	mData = Archive("MsgInBox").getValues(msgidx, "Receiver,Sender,Attachments")
	
	if mData == None:
		raise SpartaUserError("존재하지 않는 쪽지번호 입니다")
	
	if mData["Receiver"] != Login.getID() and (not CheckAdmin()) and mData["Sender"] != Login.getID():
		raise SpartaAccessError("메세지를 삭제할 수 있는 권한이 없습니다")
	
	r = Archive("MsgInBox").Remove( msgidx )
	#[TODO] 파일삭제 처리!!!	
	return r
예제 #28
0
def completeQuest():
    Input.KeyPress(0x01)
    pyautogui.moveTo(301, 527)
    Input.click()
    try:
        x, y = pyautogui.locateCenterOnScreen(
            r'C:\Users\Administrator\PycharmProjects\DNF_Automation\Downtown'
            r'\QuestCompleted1.png',
            region=(0, 0, 800, 600))
        pyautogui.moveTo(x, y)
        Input.click()
    except:
        Login.restart()
    return
예제 #29
0
def post_weibo():
    user = Login('*****@*****.**', 'weibospider')
    user.login()

    db = pymongo.MongoClient().weibodata
    rank = db.sortedplace
    places = rank.find()
    first = places[0]['地点']
    second = places[1]['地点']
    third = places[2]['地点']
    fourth = places[3]['地点']
    fifth = places[4]['地点']

    content = ''.join([
        '最近上海微博签到人数最多的地点~在此~\n第一:', first, '\n第二:', second, '\n第三:', third,
        '\n第四:', fourth, '\n第五:', fifth, '\n小伙伴们要来玩的话可以优先考虑这些地方哟~'
    ])
    post_data = {
        "location": "v6_content_home",
        "text": content,
        "appkey": "",
        "style_type": "1",
        "pic_id": "",
        "pdetail": "",
        "rank": "0",
        "rankid": "",
        "module": "stissue",
        "pub_source": "main_",
        "pub_type": "dialog",
        "_t": "0"
    }
    post = urllib.parse.urlencode(post_data).encode('utf-8')
    headers = {
        "Referer":
        "http://weibo.com/u/6058180728/home",
        "User-Agent":
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"
    }

    timer = int(time.time() * 1000)
    url = 'http://www.weibo.com/aj/mblog/add?ajwvr=6&__rnd=' + str(timer)
    try:
        request = urllib.request.Request(url=url, data=post, headers=headers)
        response = urllib.request.urlopen(request)
        html = response.read().decode('utf-8')
        #print(html)
        print("发布成功!")
    except urllib.error as e:
        print(e.code)
예제 #30
0
def add_memo_comment(request):
    cur_board = board.objects.get(date=request.GET.get('date'), author=request.GET.get('id'))
    comments = json.loads(cur_board.comment)
    comment = []
    comment.append(Login.get_current_user(request).user_id)
    comment.append(time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(float(time.time()))))
    comment.append('/memo/alert?date=%s&id=%s&num=%s' %(request.GET.get('date'), request.GET.get('id'), len(comments)))
    comment.append('/memo/delete?date=%s&id=%s&num=%s' % (request.GET.get('date'), request.GET.get('id'), len(comments)))
    comment.append('/memo/reply?date=%s&id=%s&num=%s' %(request.GET.get('date'), request.GET.get('id'), len(comments)))
    comment.append(request.POST.get('comment'))
    comment.append(Login.get_current_user(request).uid)
    comments.append(comment)
    cur_board.comment = json.dumps(comments)
    cur_board.save()
    return redirect('/board/show?date=%s&id=%s' %(request.GET.get('date'), request.GET.get('id')))
예제 #31
0
def mypage_vocabulary(request):
    user = user_info.objects.get(user_email=base64.b64decode(request.COOKIES.get('ec')))
    ctx = {'title': 'ML(MyLang) mypage'}
    ctx['user_id'] = Login.get_current_user(request).user_id
    ctx['number'] = Login.get_current_user(request).new_message
    error = ''
    voca = []
    try:
        voca_scores = json.loads(user.vocabulary_level)
        assert len(voca_scores) != 0
        for score in voca_scores:
            voca.append([time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(score[1])), score[0]])
    except Exception, e:
        print e
        error += '아직 한번도 단어시험을 보신적이 없습니다.\n'
예제 #32
0
def event_data_download(ip):
    ######VERIFY THE DATA LOG AND EVENT LOG DOWNLOAD####
    global driver
    driver = Login.login(ip)
    ##output=File_Creation.file_create()
    print("######VERIFY THE DATA LOG AND EVENT LOG DOWNLOAD####")
    #output.write("######VERIFY THE DATA LOG AND EVENT LOG DOWNLOAD####")
    time.sleep(3)
    os_user = getpass.getuser()
    print("CHECKING THE DOWNLOAD FOLDER FOR THE EVENT LOG")
    time.sleep(1)

    if (os.path.isfile("C:\Users/" + str(os_user) +
                       "/Downloads/logs.csv") == True):
        print("THE EVENT FILE HAS DOWNLOADED SUCCESFULLY")
        #output.write("THE EVENT FILE HAS DOWNLOADED SUCCESFULLY")
    else:
        print("ERROE!!THE EVENT DOWNLOAD WAS UNSUCCESSFULL")
        #output.write("ERROE!!THE EVENT DOWNLOAD WAS UNSUCCESSFULL")
    time.sleep(1)
    if (os.path.isfile("C:\Users/" + str(os_user) +
                       "/Downloads/logs.csv") == True):
        print("THE DATALOG FILE HAS DOWNLOADED SUCCESFULLY")
        #output.write("THE DATALOG FILE HAS DOWNLOADED SUCCESFULLY")
    else:
        print("ERROE!!THE DATALOG DOWNLOAD WAS UNSUCCESSFULL")
        #output.write("ERROE!!THE DATALOG DOWNLOAD WAS UNSUCCESSFULL")
    #output.close()
    return
    def __init__(self, url, login_url):
        threading.Thread.__init__(self)
        self.url = url
        self.login = Login.Login(login_url)

        self.message = False
        self.keywords_withParams_List = []
 def setUp(self):
     global login_cookie
     login_cookie = None
     login_cookie = Login.login()
     if [] in login_cookie:
         raise AssertionError("Login is not successful.")
     else:
         print "Login is done successfully."
예제 #35
0
 def testLogin(self):
     br=Login.login(self.driver,self.baseurl)
     log=ResultLog.resultLog()
     time.sleep(10)
     result=br.find_element_by_css_selector("a.red").is_displayed()
     print result
     if result:
         log.info("用户已登录2")
     else:
         log.info(u"用户登录失败")
예제 #36
0
파일: Message.py 프로젝트: onetera/sp
def sendMessage( receiver, subject, content, attachments=None, withSMS=None ):
	""" 쪽지함에 쪽지를 발송	
	"""
	#[TODO] To,CC,BCC에 대한 처리 필요 
	#[TODO] IF not logined !!
	
	smsList = []
	msgIDXs = []
	msgSave = { "Subject": subject, "Content": content, "Sender": Login.getID(), "SenderName": Login.getName() }
   
	if "<" in receiver:
		#ex) Address Parsing :: "정기영" <*****@*****.**>, "김태희" <*****@*****.**>  -> ["*****@*****.**",  "*****@*****.**"]
		addrsList = re.findall("\<([._,a-zA-Z0-9:\#\@]+)\>+", receiver)
	else:	 
		addrsList = [n.strip() for n in receiver.split(",")]
	
	for recID in addrsList:
		
		userData = Archive("User").getValues( "User.UserID == "+ recID, "Name,HandPhone" )
		if userData:
			msgSave["Receiver"] = recID
			
			result_IDX = Archive("MsgInBox").New(**msgSave)
			
			if result_IDX:
				msgIDXs.append( result_IDX )
				if userData["HandPhone"] and not userData["HandPhone"].replace("-","") in smsList:
					smsList.append( str(userData["HandPhone"].replace("-","")) )
				
				sentMsg = { "RelateIDX": result_IDX, "Subject": subject, "Content": content, "Receiver": recID, "ReceiverName": userData["Name"], "Sender": Login.getID() } 
				r = Archive("MsgSent").New( **sentMsg )
	
	if attachments:
		#[TODO] 임시 코드입니다. 멀티센딩에서 업된 파일에 대한 레퍼런스 카운트가 이상적이나 일단 그냥 복제형태로 갑니다.
		if type(attachments) == unicode:
			attachments = attachments.encode("utf8")
		
		uploadFile = Files.getRootDir() + attachments
		fileName = os.path.split(attachments)[1]
		
		if os.path.exists( uploadFile ):
			for ridx in msgIDXs:
				if str(ridx).isdigit():
					targetFile = "/data/message/%s.%s" % ( fileName, ridx )
					shutil.copy2( uploadFile, Files.getSpartaDir() + targetFile )
					msgMod = { "IDX" : ridx, "Attachments" : "%s" % fileName }
					r = Archive( "MsgInBox" ).New( **msgMod )
			os.remove(uploadFile)
	
	if withSMS and smsList:		   
		SMS.send( sendMsg=u"스팔타쪽지>"+msgSave["Subject"], recvList=smsList )
	
	return len(msgIDXs)
예제 #37
0
    def OnInit(self):
        ftp = FTPClient()
        login = Login()
        explorer = Explorer()
        
        start = login.ShowModal()

        if start == wx.ID_OK:
            login.disable()
            
            ftp.setHostname(login.getHostname())
            ftp.setUsername(login.getUsername())
            ftp.setPassword(login.getPassword())
                       
            ftp.connect()
            ftp.login()
            
            explorer.setFTP(ftp)
            explorer.Show()
            
            login.Destroy()
        else:
            return False
            
        return True
예제 #38
0
    def test_add_load(self):
        """QQ登录测试"""
        width = self.driver.get_window_size()['width']
        height = self.driver.get_window_size()['height']

        Login.login(self)
        sleep(4)
        self.driver.find_element_by_android_uiautomator('new UiSelector().description("帐户及设置")').click()
        sleep(1)
        self.driver.find_element_by_android_uiautomator('new UiSelector().description("设置")').click()
        sleep(2)
        self.driver.find_element_by_xpath('//android.widget.TextView[contains(@text, "帐号管理")]').click()
        self.driver.swipe(width / 2, height / 2, width / 2, height / 4, 1000)
        self.driver.find_element_by_name("退出当前帐号").click()
        self.driver.find_element_by_xpath('//android.widget.TextView[contains(@text, "确认退出")]').click()

        try:

            sleep(2)
            self.driver.swipe(width / 2, height / 2, 114, height / 2, 1000)
            sleep(2)
        except Exception as e:
            print(e)
예제 #39
0
def menu(host, T, t_host):
	while True:
		print ("Scegli azione PEER:\nlogin\t - Login\nquit\t - Quit\n\n")
		choice = input()

		if (choice == "login" or choice == "l"):
			t_host, sessionID = logi.login(host, t_host)
			if sessionID != bytes(const.ERROR_LOG, "ascii"):
				tfunc.success("Session ID: " + str(sessionID, "ascii"))

				listPartOwned = {}

				daemonThreadP = daemon.PeerDaemon(host, listPartOwned)
				daemonThreadP.setName("DAEMON PEER")
				daemonThreadP.setDaemon(True)
				daemonThreadP.start()

				waitingDownload = []

				while True:
					if len(waitingDownload) == 0:
						print ("\n\nScegli azione PEER LOGGATO:\nadd\t - Add File\nsearch\t - Search and Download\nlogout\t - Logout\n\n")
						choice_after_log = input()

						if (choice_after_log == "add" or choice_after_log == "a"):
							add.add(host, sessionID, t_host, listPartOwned)

						elif (choice_after_log == "search" or choice_after_log == "s"):
							src.search(sessionID, host, t_host, listPartOwned, waitingDownload)

						elif (choice_after_log == "logout" or choice_after_log == "l"):
							if (logo.logout(host, t_host, sessionID) > 0):

								break

						else:
							tfunc.error("Wrong Choice!")
					else:
						time.sleep(1)

			else:
				tfunc.error("Errore Login")	

		elif (choice == "quit" or choice == "q"):
			if T:
				logo.quit(host)
			break

		else:
			tfunc.error("Wrong Choice")
예제 #40
0
파일: Project.py 프로젝트: onetera/sp
def getActiveProjects():
	
	accLevel = Login.getLevel()
	
	#[TIP] 프로젝트는 Active 된 것들만 보여짐  
	RDB = Archive("Project").Search(columns="Project.IDX,Project.Code,Project.Name", 
									 where="Project.StatCode == ACT", 
									 order="Project.SortNumber ASC", 
									 accfield="Project.AccessView", acclevel=accLevel)
	outData = []
	for row in RDB[1]:			  
		outData.append( (row["Project_IDX"], row["Project_Code"], row["Project_Name"]) )
	
	return outData
예제 #41
0
파일: Convert.py 프로젝트: onetera/sp
def FixPath(uncPath):
	# Temp function 
	# \\rfsv01\~~
	# //rfsv01
	# smb://
	
	brName = Login.getBrowserName()
	osType = Login.getOSType()						  
	
	if (osType == "posix"):
		uncPath = uncPath.replace("\\", "/")			
		if uncPath.startswith("file://"): 
			uncPath = uncPath[7:]				 
		if not uncPath.startswith("sparta://"): 
			if uncPath.startswith("\\\\") or uncPath.startswith("//"):
				uncPath = uncPath[2:].replace("//","/")
			uncPath = "sparta://"+uncPath
	
	elif (osType == "nt"):
		# 웹 경로			  
		if uncPath[0] == "/" and uncPath[1] != "/":
			return uncPath
			 
		if uncPath.startswith("smb://"): 
			uncPath = uncPath[6:]
		if uncPath.startswith("file://"): 
			uncPath = uncPath[7:]
				
		uncPath = uncPath.replace("/", "\\")
		 
		if brName == "MSIE":
			if not uncPath.startswith("\\\\"):
				uncPath = "\\\\" + uncPath
		else:
			uncPath = "file://" + uncPath
	   
	return uncPath
예제 #42
0
파일: nMessage.py 프로젝트: onetera/sp
def removeMessage(msgidx):
	
	msg_receiver_q = Session.query(MsgReceiver).filter_by(idx = msgidx).first()
	
	if None == msg_receiver_q:
		raise SpartaUserError("존재하지 않는 쪽지입니다")

	# 로그인한 사용자가 메시지를 받은 사용자가 아닌 경우 삭제할 수 없다는 메시지를 출력하게 한다.
	if msg_receiver_q.ReceiverID != Login.getID() and (not CheckAdmin()):
		raise SpartaAccessError("메시지를 삭제할 수 있는 권한이 없습니다")

	msg_receiver_q.IsDelete = u"1"

	Session.commit()

	# 항상 1을 반환한다.
	return 1
예제 #43
0
파일: User.py 프로젝트: onetera/sp
def setPassword( userid, newpassword):
	
	if userid != Login.getID() and (not CheckAdmin()):
		raise SpartaAccessError("패스워드를 변경할수 있는 권한이 없습니다.")
		
	useridx = getIDX( userid )
	
	if useridx:
		hashedPass = hashlib.md5( newpassword ).hexdigest()    
		r = 0 < Archive("User").Edit( useridx, Password=hashedPass )
		
	else:
		raise SpartaError("[버그] 아이디의 IDX 정보가 잘못되었습니다.")
	
	if r:
		return True
	else:
		raise SpartaError("패스워드를 수정하지 못했습니다.")
예제 #44
0
파일: Bot.py 프로젝트: heftekharm/goly_bot
def check(bot, update):
    print(users)
    if UP_States.get(str(update.message.chat_id) , -1) == REGISTERED:
            try:   
                login = Login.login(users[str(update.message.chat_id)])
                print (str(update.message.from_user.first_name) + '  =>  Check')
                login.encryptUserPassword()
                login.logIn()
                html = login.html                
                scpr = Scrapper.scrapper(html)
                scpr.make()
                bot.sendMessage(update.message.chat_id, text=scpr.text)
                print (str(update.message.from_user.first_name) + '  =>  Succecfull')
            except BaseException as ex :
                print (ex.args);
                bot.sendMessage(update.message.chat_id, text="An error has occured")
    else:
        bot.sendMessage(update.message.chat_id, text="Please set up username and password at first.")   
예제 #45
0
파일: nMessage.py 프로젝트: onetera/sp
def cancelMessage(sentidx):
	
	mData = Archive("MsgSent").getValues(msgidx, "RelateIDX,Sender,Attachments")
	
	if mData == None:
		raise SpartaUserError("존재하지 않는 쪽지번호 입니다")
	
	if mData["Sender"] != Login.getID() and (not CheckAdmin()):
		raise SpartaUserError("메세지를 삭제할 수 있는 권한이 없습니다") 
	
	rData = Archive("MsgInBox").getValue( mData["RelateIDX"], "IDX,IsRead")
	
	if rData:
		if rData["IsRead"] == False:
			return removeMessage( rData["IDX"] )
		else:
			raise SpartaUserError("발송된 메세지는 이미 읽은 메세지입니다")
	else:
		raise SpartaUserError("발송된 메세지는 이미 삭제되었습니다")
	
	return int(0)
예제 #46
0
파일: nMessage.py 프로젝트: onetera/sp
def getMessage(msgReceiver_idx, readStamp=True):
	""" 쪽지를 읽어온다 """

	msgReceiver_q = Session.query(MsgReceiver).outerjoin(Msg).add_entity(Msg)

	msg = msgReceiver_q.filter(MsgReceiver.idx == msgReceiver_idx).first()

	if None == msg:
		raise SpartaUserError("존재하지 않는 쪽지입니다")

	# 로그인 중인 사용자와 메시지를 받은 사용자 ID를 비교하여 일치하지 않으면 권한 오류를 발생시킨다.
	if Login.getID() != msg[0].ReceiverID:
		raise SpartaUserError("메시지를 볼 수 있는 권한이 없습니다")
   
	# 읽음여부 수정
	if u"0" == msg[0].IsRead:
		msg[0].IsRead = u"1"

	Session.commit()

	outText = msg[1].Content

	# 첨부파일 가져오기
	msgAttach_q = Session.query(MsgAttach).filter_by(Msg_IDX = msg[1].idx).all()

	attach_text = []

	if len(msgAttach_q) > 0:
		attach_text.append("<table class=\"filedownBox\">")
		attach_text.append(u"<tr><td rowspan=\"%d\">첨부</td><td>" % len(msgAttach_q))

		for attach_item in msgAttach_q:
			attach_text.append("<a href=\"/getfile/nmessage/%d\">%s</a><br />" % (attach_item.idx, attach_item.OriginalFileName) )

		attach_text.append("</td></tr></table>")

	attach_text = "".join(attach_text)

	return "<p>%s</p>%s" % (outText, attach_text)
예제 #47
0
파일: nMessage.py 프로젝트: onetera/sp
def removeSendMessage(sendidx):

	# 메시지 정보를 가져온다.
	msg_q = Session.query(Msg).filter(Msg.idx == sendidx)
	if msg_q.count() == 0:
		raise SpartaUserError("존재하지 않는 쪽지입니다")

	msg = msg_q.first()

	if msg.SenderID != Login.getID() and (not CheckAdmin()):
		raise SpartaAccessError("메시지를 삭제할 수 있는 권한이 없습니다") 

	# 수신자 지우기
	receiver_q = Session.query(MsgReceiver).filter(MsgReceiver.Msg_IDX == sendidx)
	if receiver_q.count() > 0:
		# 수신자중에 한명이라도 메시지를 읽지 않았다면 쪽지를 삭제하지 못하게 한다.
		for receiver_user in receiver_q.all():
			if receiver_user.IsDelete == u"0":
				return u"%s 사용자가 아직 쪽지를 읽지 않았습니다" % receiver_user.ReceiverID
		
		receiver_q.delete()
		Session.commit()

	# 우선 첨부파일 정보를 가져온다.
	attach_q = Session.query(MsgAttach).filter(MsgAttach.Msg_IDX == sendidx).all()
	if len(attach_q) > 0:
		for attach_info in attach_q:
			# File Exists
			if os.path.exists(attach_info.NewFileName):
				os.unlink(attach_info.NewFileName)
		Session.delete(attach_info)
		Session.commit()

	# 본 메시지 삭제
	msg_q = Session.delete(msg)
	Session.commit()
	
	return 1
예제 #48
0
파일: main.py 프로젝트: elielprado/ESOF
def init():
    global logged
    
    while True:
        if logged == 0:
            print('Seja bem vindo!')

        opt2 = int(raw_input('\nDigite 1 para logar como *aluno ou 2 para logar como *professor: '))
        username = ''
        senha = ''
        email = ''

        if opt2 == 2:
            print('\nOla professor, entre com seus dados')
            email = raw_input('Email: ')
            senha = raw_input('Senha: ')
            login = Login()
            login.logInProfessor(email, senha)
        elif opt2 == 1:
            print('\nCaro aluno, entre com seus dados')
            username = raw_input('User: '******'Senha: ')
            login = Login()
            login.logInAluno(username, senha)
예제 #49
0
#!/usr/bin/env python

# ----------------
# ShowDatabases.py
# ----------------

import Login
import Query

print("ShowDatabases.py")

c = Login.login()
assert(str(type(c)) == "<type '_mysql.connection'>")

t = Query.query(c, "show databases")
assert(type(t) is tuple)

assert(t == \
    (('information_schema',), \
     ('downing',), \
     ('downing_cs327e',), \
     ('downing_cs370',), \
     ('downing_cs371p',), \
     ('downing_cs373',), \
     ('downing_cs378',), \
     ('downing_dml',), \
     ('downing_test',), \
     ('drupal_dml',)))

print("Done.")
예제 #50
0
파일: Run.py 프로젝트: lovedonle/CI
'''
Created on 2015.2.25

@author: cfds
'''
import unittest
import CustomerMgt, Login, SecurityMgt, RouteMgt 
from WebpayCommon.HTMLTestRunner import HTMLTestRunner as htr

CutomerMgt_suite = CustomerMgt.suite()
Login_suite = Login.suite()
RouteMgt_suite = RouteMgt.suite()
SecurityMgt_suite = SecurityMgt.suite()

alltests = unittest.TestSuite((CutomerMgt_suite,Login_suite,RouteMgt_suite,SecurityMgt_suite))
#output the results to console
runner = unittest.TextTestRunner()
runner.run(alltests)

#output the results to a report file
#filename = r'test_result/result1.html'
#fp = file(filename, 'wb')
#runner =htr(stream=fp,title='BOSS testing result',description='BOSS automation test report')
#runner.run(alltests)

예제 #51
0
 def testAddProdect(self):
     br=Login.login(self.driver,self.baseurl)
     log=ResultLog.resultLog()
     br.maximize_window()
     time.sleep(5)
     # m="我的会员中心".decode("utf-8")
     #br.find_element_by_xpath("//div[@class='mod-login']/div[3]/div[2]/a[contains(text(),m)]").click()
     #br.find_element_by_link_text(u"我的会员中心").click()
     br.find_element_by_css_selector("a.red").click()
     time.sleep(5)
     br.switch_to_window(br.window_handles[1])
     br.find_element_by_link_text(u"我是供应商").click()
     time.sleep(3)
     br.find_element_by_link_text(u"产品管理").click()
     br.find_element_by_link_text(u"发布信息").click()
     br.find_element_by_id("userItem").click()#网站栏目选择
     br.find_element_by_link_text(u"供应信息").click()
     br.find_element_by_css_selector("button.btn.selectOk").click()
     br.find_element_by_id("newsItem").click()#产品类别选择
     time.sleep(5)
     br.find_element_by_css_selector("a[Data-id='1000001008']").click()
     time.sleep(2)
     br.find_element_by_css_selector("a[Data-id='1000001008001']").click()
     time.sleep(2)
     br.find_element_by_css_selector("a[Data-id='1000001008001001']").click()
     time.sleep(2)
     br.find_element_by_xpath("//*[@id='seeNewsItemsBody']/div[3]/button").click()#产品类别选择对话框的确定按钮
     br.find_element_by_id("infoTitle").send_keys(self.tit.decode("utf-8"))#产品标题
     br.find_element_by_id("infoFlag").send_keys("wwg")#关键词
     br.find_element_by_id("proBrandName").find_element_by_css_selector("option[value=\"生鸡蛋\"]").click()#品牌名称
     br.find_element_by_id("proStandard").send_keys("wwg")#规格
     br.find_element_by_id("proCompany").send_keys("wwg")#生产厂家
     js1="$(\"input[Data-provide='datetimepicker'    ]\").removeAttr('readonly');$(\"input[Data-provide='datetimepicker']\").attr('value','2014-08-09')"
     br.execute_script(js1)#生产日期
     br.find_element_by_id("infoPrice").send_keys("1")#批发价
     br.find_element_by_id("pricelast").send_keys("1")#零售价
     br.find_element_by_id("infoCon").send_keys("2222")#供应量
     br.find_element_by_id("proMinNum").send_keys("1")#最小起订量
     br.find_element_by_id("province").find_element_by_css_selector("option[value=\"10008\"]").click()
     br.find_element_by_id("city").find_element_by_css_selector("option[value=\"10009\"]").click()#发货地
     br.find_element_by_id("proDaysLimit").send_keys("1")#发货期限
     br.find_element_by_xpath("//*[@id='img_list']/p[1]/a/img").click()
     time.sleep(3)
     br.find_element_by_xpath("//*[@id='tabNavi']/ul/li[2]").click()
     br.find_element_by_id("imgFile").send_keys("E:\\wwg\\xampp\\php\\php.gif")
     time.sleep(2)
     br.find_element_by_id("upToServer").click()#图片
     br.find_element_by_id("infoBrief").send_keys("wwg")#产品简介
     content="wwg"
     #js2="document.getElementsByClassName(\"ke-iframe\")[0].contentWindow.document.body.innerHTML=\"%s\" " %(u"是打发士大夫士大夫是地方")
     js2="KE.text('infoContent','123wwg')"
     br.execute_script(js2)#产品详情
     js3="document.getElementsByClassName(\"ke-iframe\")[1].contentWindow.document.body.innerHTML=\"%s\"" %(content)
     br.execute_script(js3)#配送说明
     time.sleep(10)
     br.find_element_by_id("saveBtn").click()
     time.sleep(8)
     br.find_element_by_link_text(u"身份认证").click()
     br.find_element_by_link_text(u"产品管理").click()
     br.find_element_by_link_text(u"信息管理").click()
     time.sleep(5)
     #调用数据库查询验证产品发布是否成功
     oracle.ora(self.tit.decode("utf-8").encode("gbk"))
     #通过页面元素判断产品发布是否成功
     try:
         product=br.find_element_by_link_text("safdfsdfsdfsdfsdfdsf").is_displayed()
         if product:
             log.info("通过界面验证产品:%s发布成功" %self.tit)
         else:
             log.info("通过界面验证产品:%s没有发布成功" %self.tit)
     except:
         log.info("没有找到此元素")
예제 #52
0
# -*- coding: utf-8 -*-
import WeiboLogin
import Login
import urllib2
import re
import sys
reload(sys)
sys.setdefaultencoding("utf-8")


#调用模拟登录的程序,从网页中抓取指定URL的数据,获取原始的HTML信息存入raw_html.txt中
def get_rawHTML(url):
	#Login.login()
	content = urllib2.urlopen(url).read()
	fp_raw = open("f://emotion/mysite/weibo_crawler/raw_html.txt","w+")
	fp_raw.write(content)
	fp_raw.close()                #获取原始的HTML写入文件
	#print "成功爬取指定网页源文件并且存入raw_html.txt"
	return content   #返回值为原始的HTML文件内容

if __name__ == '__main__':
	Login.login()   #先调用登录函数
	#url = 'http://weibo.com/yaochen?is_search=0&visible=0&is_tag=0&profile_ftype=1&page=1#feedtop'   #姚晨
	url = 'http://weibo.com/fbb0916?is_search=0&visible=0&is_tag=0&profile_ftype=1&page=1#feedtop'   #自行设定要抓取的网页
	get_rawHTML(url)

def main():
	Login.init()
예제 #54
0
import Constant as const
import Tracker as tracker
import Configuration as config
import Menu as m
import sys
import Login as logi

####### VARIABILI 

T = False
sessionID = ""

host = ""
t_host = ["", const.TPORT]

####### INIZIALIZZAZIONE
T, host, t_host = config.readArgs(sys.argv)

####### DEMONE TRACKER
if T:
	daemonThreadT = tracker.TrackerDaemon(host)
	daemonThreadT.setName("DAEMON T")
	#daemonThreadT.setDaemon(True)
	daemonThreadT.start()

	logi.try_connection(host)

####### MENU
m.menu(host, T, t_host)
예제 #55
0
파일: __init__.py 프로젝트: onetera/sp
def getLoginID():
	return Login.getID()
예제 #56
0
파일: __init__.py 프로젝트: onetera/sp
def getLoginName():
	return Login.getName()
예제 #57
0
	#fp2 = open("chinese_weibo.txt","a")  #初始化写入文件
	for readline in read:
		utf8_readline = unicode(readline,'utf-8')
		if pattern.search(utf8_readline):   #如果在该句话中能找到中文文本则进行处理
			#print readline #测试
			split_readline = readline.split(' ')  #由空格对文本进行分割,split_readline是一个list
			for c in split_readline:
				c = re.sub(r'发布者:[.]*','',c)   #去掉“发布者”
				c = re.sub(r'百度[.]*','',c)   #去掉“百度”
				c = re.sub(r'正在加载中[.]*','',c)
				c = re.sub(r'360安全浏览[.]*','',c)
				c = re.sub(r'抱歉[.]*','',c)
				c = re.sub(r'.*?高速浏览.*','',c)
				#print c,len(c)
				if len(c) > 16:  #提出过短的文本,utf-8编码中一个中文为3个字节长度
					fp2.write(c)
					#print "c",c
	fp1.close()
	#fp2.close()  #文件关闭
	#print "成功解析网页提取微博并且存入chinese_weibo.txt"

if __name__ == '__main__':
	#自行设定要抓取的网页,抓取范冰冰微博的1到5页
	Login.login()
	for i in range(4):
		i = i + 1
		url = 'http://weibo.com/yaochen?is_search=0&visible=0&is_tag=0&profile_ftype=1&page=' + str(i) + '#feedtop'
		#url = 'http://weibo.com/fbb0916?is_search=0&visible=0&is_tag=0&profile_ftype=1&page=' + str(i) + '#feedtop'
		content = get_rawHTML(url)
		Handel(content)   #测试,调用该函数执行
예제 #58
0
# Log into the site and determine which UI is in play
# Open the test project and select the LoD saved view

myScriptPath = "c:\\SikuliX\\Scripts\\"
myImagePath = "c:\\SikuliX\\Scripts\\ScriptImages"
# all systems
if not myScriptPath in sys.path: sys.path.append(myScriptPath) 
if not myImagePath in sys.path: sys.path.append(myImagePath)
# supposing there is a logon.sikuli
from sikuli import *
import Login
Login.loginass()
wait(Pattern("1443118496832.png").similar(0.90), 30)
while not(Pattern("1443118548158.png").similar(0.90)):
    type(Key.PAGEDOWN)
click(Pattern("1443118548158.png").similar(0.90))
wait(Pattern("1443040796608.png").similar(0.90), 20)
click(Pattern("1443041607627.png").similar(0.90))
wait(Pattern("1443119206468.png").similar(0.90), 30)
click(Pattern("1443041734609.png").similar(0.90).targetOffset(9,2))
if    exists(Pattern("1443125556799.png").similar(0.90)):
    click(Pattern("1443125583928.png").similar(0.90).targetOffset(14,2))
    wait(Pattern("1443125622616.png").similar(0.90).targetOffset(-30,12))
    click(Pattern("1443125622616.png").similar(0.90).targetOffset(-30,12))
    wait(Pattern("1443041734609.png").similar(0.90).targetOffset(9,2), 30)
    click(Pattern("1443041734609.png").similar(0.90).targetOffset(9,2))
else:    wait(Pattern("1443041808222.png").similar(0.90), 10)
click(Pattern("1443041808222.png").similar(0.90).targetOffset(41,2))
wait(Pattern("1443041884554.png").similar(0.90))
click(Pattern("1443042073987.png").similar(0.90).targetOffset(-1,16))
예제 #59
0
파일: nMessage.py 프로젝트: onetera/sp
def getNoReadCount():
	""" 읽지않은 쪽지 갯수를 반환한다 """
	return Session.query(MsgReceiver).filter(and_(MsgReceiver.IsRead == u'0', MsgReceiver.ReceiverID == Login.getID())).count()
예제 #60
0
파일: nMessage.py 프로젝트: onetera/sp
def sendMessage( receiver, receiverCC, receiverBCC, subject, content, attachments=None, withSMS=None ):
	""" 쪽지함에 쪽지를 발송"""
	
	#[TODO] IF not logined !!

	withEmail = True

	emailList = []
	smsList = []
	msgIDXs = []

	receiverTo = getReceiver(receiver)
	receiverCc = getReceiver(receiverCC)
	receiverBcc = getReceiver(receiverBCC)
	
	# 쪽지 내용 저장
	msg = Msg()
	msg.SenderID = unicode(Login.getID())
	msg.SenderName = unicode(Login.getName())
	msg.Subject = unicode(subject)
	msg.Content = unicode(content)
	msg.withSMS = unicode(withSMS)
	msg.CreateDate = datetime.datetime.now() 
	
	Session.add(msg)
	Session.commit()
	
	# To들에게 보내기
	setMsgReceiver(receiverTo, msg.idx, "0")
	# CC들에게 보내기
	setMsgReceiver(receiverCc, msg.idx, "1")
	# BCC들에게 보내기
	setMsgReceiver(receiverBcc, msg.idx, "2")

	# SMS 발송 관련 처리
	if withSMS:
		smsList = list()
		receiverList = receiverTo + receiverCc +receiverBcc
		for msg_receiver in receiverList:
			if type(msg_receiver) != dict:
				continue
			smsList.append(msg_receiver["HandPhone"])

		if len(smsList) > 0:
			SMS.send(sendMsg=u"[sparta] %s" % msg.Content[:70], recvList=smsList)
	
	if withEmail:
		senderData = getReceiver("<%s>" % Login.getID())[0]["GwID"]
		emailList = list()
		receiverList = receiverTo + receiverCc +receiverBcc
		for msg_receiver in receiverList:
			if type(msg_receiver) != dict:
				continue			
			if str(msg_receiver["GwID"]).startswith("D"):
				emailList.append( str(msg_receiver["GwID"])+"@idea.co.kr" )
		if len(emailList) > 0:
			sendEmail("*****@*****.**" % senderData, msg.Subject, msg.Content, recvList=emailList)
   
	if attachments:
		objUpload = Upload()
		objUpload.MsgInitialize()
		
		for attach_item in attachments:
			new_file = objUpload.upload_file_move(attach_item)

			rowMsgAttach = MsgAttach()
			rowMsgAttach.Msg_IDX = unicode(msg.idx)
			rowMsgAttach.OriginalFileName = unicode(new_file["O_PATH"])
			rowMsgAttach.NewFileName = unicode(new_file["D_PATH"])
			rowMsgAttach.FileSize = unicode(new_file["SIZE"])

			Session.add(rowMsgAttach)

		Session.commit()
	return len(receiverTo)