def case_2_organization(self): driver = self.driver organization_del(driver) # 清空机构 organization(driver) # 创建机构 meeting_room_del(driver, 1) # 清空会议室 meeting_room(driver, 0) # 创建会议室 meeting_type_del(driver, 1) # 清空会议类型 meeting_type(driver, 0) # 创建会议类型 user_del(driver) # 清空用户 user(driver) # 创建用户 meeting_del(driver) # 清空会议 meeting(driver) # 创建会议 while (1): sleep(1) try: driver.find_element_by_xpath("//span[text()='会议列表']").click() driver.find_element_by_xpath("//span[text()='自动化大会0']").click() break except: pass sleep(1) meeting_staff(driver) # 参会人员 meeting_agenda(driver) # 会议议程 meeting_file(driver) # 会议资料 meeting_file_del(driver) # 删除资料 meeting_agenda_del(driver) # 删除议程 meeting_summary(driver) # 会议纪要 meeting_vote(driver) # 会议投票 meeting_vote_del(driver) # 删除投票 meeting_questionnaire(driver) # 会议问卷 meeting_questionnaire_del(driver) # 删除问卷 meeting_message(driver) # 会议通知 meeting_message_del(driver) # 删除通知
def test_user(): u1 = user(userName="******") u2 = user(userName="******") print "Created new user u1" print "u1.userName: "******"u1.numMessagesToKeep: " + str(u1.numMessagesToKeep)
def menu(client) : while True : client.send("dialog --menu \"Menu List\" 30 50 8 1 \"User Management\" 2 \"Directory Management\" 3 \"File Management\" 4 \"Software Management\" 5 \"Device Partition Management\" 6 \"Logical Volume Management\" 7 \"Server Management\" 8 \"Exit\" ") choice = client.recv(10) if choice == "1" : import user user.user(client) elif choice == "2" : import dirs dirs.dirs(client) elif choice == "3" : import files files.files(client) elif choice == "4" : import software software.software(client) elif choice == "5" : import dpm dpm.dpm(client) elif choice == "6" : import lvm lvm.lvm(client) elif choice == "7" : import sm sm.sm(client) elif choice == "8" : client.send("recieve only") client.send("dialog --infobox \"Thank You... \n Exiting....\" 5 18") client.send("false")
def __init__(self): global once if once is not None: return None once = 1 global userObjs userObjs = { "Jane": user.user(), "Joe": user.user(), "Fred": user.user(), "Anne": user.user() } global users users = { "Jane": "123", "Joe": "abc", "Fred": "spacepirate", "Anne": "netflix" } global admins admins = [] global voters voters = [] admins.append("Anne") voters.append("Jane") voters.append("Fred") voters.append("Joe") global adminopts adminopts = { "Instructions": "I see you are an admin! Welcome! Please choose from the following options", "type": "MultipleChoice", "1": "Create Election", "2": "Edit Election", "3": "View Results" } global voteropts voteropts = { "Instructions": "I see you are a voter, please choose from the following options", "type": "MultipleChoice", "1": "Candidate A", "2": "Candidate B", } global incorrectpass incorrectpass = { "Instructions": "Password Incorrect", "type": "PasswordFail", } global incorrectuser incorrectuser = { "Instructions": "Username Incorrect", "type": "UsernameFail",} return None
def registrar(self, u, p): if(len(u)>20 or len(p)>20): return False if(len(self.users)==0): u = user(u, p) self.users.append(u) else: print self.buscar(u) if self.buscar(u) == None : self.users.append(user(u,p)) return True
def login(self, event): usuario = self.email.get() senha = self.senha.get() if (usuario == '' or senha == ''): tkMessageBox.showwarning('Campos Vazios', 'erro de leitura dos campos') self.email['bg'] = 'red' self.senha['bg'] = 'red' else: try: user.user(usuario, senha, '', '') except: tkMessageBox.showerror( 'ERRO!', 'NAO ESTA AVANCANDO A JANELA DO USUARIO')
def get_user(self, nick ): query = 'SELECT * FROM users WHERE nick like \'{0}\''.format(nick) print query cur = self.dbmgr.execute(query) row = cur.fetchone() userg = user('','','','2012-01-01','',0,'',0) if row is not None : userg = user(row["nick"], row["seen"], row["command"], row["last"], row["perm"], row["karma"], row["pass"], row["pipianlvl"]) return userg
def __init__(self, userID): self.userID = userID self.user = user(userID) self.lastXImages = 30 self.lastXUsers = 40 self.topXUsers = 20 self.numRecommendations = 10
def recommend_similar_users(self, mode): a = user(self.uid) a.find_similar_users() result = {} su = a.similar_users rp = a.reco_algo(mode) er = a.error result['similar_users'] = su result['recommended_problems'] = rp result['error'] = er result = json.dumps(result, indent=4, separators=(',', ': ')) os.write(self.result_file,result) res = "\nShowing similar users and problem recommendations for: \n" + self.uid + "\nUser similarity: \n" os.write(self.log_file,res) print res res = json.dumps(su, indent=4, separators=(',', ': ')) os.write(self.log_file,res) print res res = "\nRecommended problems: \n" os.write(self.log_file,res) print res res = json.dumps(rp, indent=4, separators=(',', ': ')) os.write(self.log_file,res) print res res = "\nEstimated error in rating: \n" + str(er) os.write(self.log_file,res) print res
def addUser(self, uname, pwd): """ :uname type: string :pwd type: string :rtype: int """ us = user.user(uname, pwd) print('正在添加用户' + uname) print('正在登录') if us.login() == True: print('登录成功') print('正在检查是否为已存在用户') with open('users', 'r+') as file_user: for line in file_user.readlines(): if line[0] == '#': continue mat = re.match(uname + '\t', line) if mat != None: print('这个用户已存在') print('==================') return 2 print('用户' + uname + '添加成功') print('==================') file_user.write(uname + '\t' + pwd + '\n') return 0 else: print('登录失败') print('==================') return 1
def login(): print request.args.get('action') msg = "Login" if request.args.get('action') == 'login': u = user() if u.tryLogin(request.form.get('email'), request.form.get('password')): session['login_time'] = time.time() session['user_data'] = u.data[0] return header() + "Login Successful <br> Welcome " + str( u.data[0]['fname']) + mainMenu() + footer() else: msg = "Login failed" elif request.args.get('action') == 'logout': session['login_time'] = None session['user_data'] = None msg = 'Logout successful.' return header() + msg + ''' <div > <form action="/?action=login" method="POST"> Email:<br> <input type="text" name="email"/> <br><br> Password:<br> <input type="password" name="password"/> <br><br> <input type="submit" value="Login"/> </form> </div> ''' + footer()
def list_users(): if not checkSession(2): return redirect("/mainmenu") html = ''' <b> Users </b> <table style="width:600px;"> <tr style="background-color:#bbb;"> <td>User_ID</td> <td>Name</td> <td>Email</td> <td>Role</td> </tr>''' u = user() u.getAll() i = 0 for row in u.data: c = '#eee;' if i % 2 == 0: c = '#ddd;' html += '''<tr style="background-color:''' + c + ''''"> <td> <a href="/user/''' + str(row['user_id']) + '''">''' + str( row['user_id']) + '''</a> </td> <td>''' + str(row['fname']) + '''</td> <td>''' + str(row['email']) + '''</td> <td>''' + str(row['role']) + '''</td> </tr>''' i += 1 html += '''</table> <a href="user/new">Create New User</a><br><br> <a href="/mainmenu">Main Menu</a><br>''' return header() + html + footer()
def start(message): global users number = tools.find(users, message.chat.id) lang = 'ru' if message.from_user.language_code == 'ru' else 'us' lang = 'ua' if message.from_user.language_code == 'uk' else 'us' if number is None: client = user.user(id=message.chat.id, name=message.from_user.first_name, surname=message.from_user.last_name) client.settings['language'] = lang users.append(client) number = tools.find(users, message.chat.id) bot.send_message( message.chat.id, languages.assembly['hi'][users[number].settings['language']] + ' ' + users[number].name + '.\n' + languages.assembly['greeting'][users[number].settings['language']], reply_markup=keyboard) bot.send_message(message.chat.id, languages.assembly['choose a language'][ users[number].settings['language']], reply_markup=language_selection)
def adduser(): u = user(context) u.surname = 'Mazarei' u.common_name = 'Masoud' u.password = '******' u.user_id = 'm.mazarei' u.save()
def parseAndMergeArgs( self, parser ): """ Parse the CLI args using the parser passed in. Configure logger, override loaded values with CLI args/values Return parsed args """ c = conf.conf args = parser.parse_args( sys.argv[ 2: ] ) # before we can do anything, config the logger dblog.configFromArgs( args ) # start log a pretty initial entry / log-header dblog.logSandwich( self.PROG_NAME ) # set config, args.config defaults to c.FILENAME_DEFAULT self.configParser = c.loadConf( args.config ) # dump for debugging purposes self.dumpConf( ) dblog.logLettuce( logging.DEBUG ) self.dumpRunArgs( args ) dblog.logLettuce( logging.DEBUG ) # merge args into configs, will print at info level self.mergeArgsAndConfigs( args ) # set data manager self.dataMgr = datamgr.datamgr( self ) # set user preferences self.user = user.user( typingWpm = self.getConf( c.OPTIONS, c.OPTION_TYPING_WPM ), typingRand = self.getConf( c.OPTIONS, c.OPTION_TYPING_ERR ) ) return args
def __init__(self, my_artists=['150', '989', '194647', '390392', '511147', '532992']): self.artist_IDs = my_artists with open('user_friends.csv', 'rb') as csvfile: self.edges = list(csv.reader(csvfile))[1:] print "edges done" with open('user_artists.csv', 'rb') as csvfile: all_artist_data = list(csv.reader(csvfile))[1:] self.user_artist_data = [x for x in all_artist_data if x[1] in self.artist_IDs] print "user_artist_data done" Gg, Cg = create_graph(self.edges) self.graph = Gg print "graph done" self.c_graph = Cg print "c_graph done" t_users = {} for user_n in Gg.nodes(): name = user_n artists = self.get_artists(name) #TODO: implement t_users[name] = user.user(name, artists) self.users = t_users print "users done" self.cds_sold = 0 self.art_analisys = {} for aa in self.artist_IDs: self.art_analisys[aa] = 0
def get_user_by_id(db_conn, id): cursor = db_conn.cursor() query = ''' SELECT e.entity, e.username, e.first_name, e.last_name, e.email_address, r.label FROM tb_entity e JOIN tb_role r ON e.role = r.role WHERE e.entity = %(id)s AND e.disabled = FALSE ''' cursor.execute(query, {"id":id}) rows = cursor.fetchall() if len(rows) > 1: raise ValueError, "IDs are not unique (this shouldn't be allowed by the schema)" if len(rows) < 1: raise ValueError, "User with that id does not exist: %s" % (id) return user.user(rows[0][0], rows[0][1], rows[0][2], rows[0][3], rows[0][4], rows[0][5])
def getUser(username_local, server_name_local): #连接服务器 try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((server_name, remote_server_port)) sock.settimeout(15) #检测服务器是否关闭 except socket.timeout: print "Error:timeout" return None sock.send('{"action":"login","uid":0,"username":"******","ip":"%s"}' %(username_local,server_name_local)) userdata = sock.recv(1024) print userdata u = user.user() u.set(json.loads(userdata)) while True: print "[FLOATER FIND] try to find fellow" sock.send('{"action":"find"}') fellow = sock.recv(1024) if fellow != "None": print "[FLOATER FOUND]", fellow userData = json.loads(fellow) u.set(userData) break time.sleep(5) sock.send('{"action":"close"}') sock.close() GUI.setRemote(u)
def getUser(self, username, server): # 连接服务器 time.sleep(3) try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((config.server_name, config.remote_server_port)) sock.settimeout(15) # 检测服务器是否关闭 except Exception: info("connection error", "error") return None sock.send('{"action":"login","uid":0,"username":"******","ip":"%s"}' % (username, server)) userdata = sock.recv(1024) print userdata u = user.user() u.set(json.loads(userdata)) while True: print "[FLOATER FIND] try to find fellow" sock.send('{"action":"find"}') fellow = sock.recv(1024) if fellow != "None": print "[FLOATER FOUND]", fellow userData = json.loads(fellow) u.set(userData) break time.sleep(3) sock.send('{"action":"close"}') sock.close() global username_remote username_remote = userData["username"] global server_name_remote server_name_remote = userData["ip"]
def _run_issuer(self): self.logger.info('Starting issuer user thread') user_code = self._config.get(self._test_name,'issuer_user') user_sip = ast.literal_eval(self._config.get(self._test_name,'issuer_user_devices'))['sip'] user_gsm = ast.literal_eval(self._config.get(self._test_name,'issuer_user_devices'))['gsm'] user_actions = self._config.get(self._test_name,'issuer_user_actions') self.logger.info('Initalizing issuer user: user_code:%s, sip:%s, gsm:%s, actions:%s',user_code,user_sip,user_gsm,user_actions) u = user.user(user_code,sip=user_sip,gsm=user_gsm) self.logger.info('Starting issuer user') u.start(dispsip=user_sip, dispgsm=user_gsm) sleep(10) for act in user_actions.split(','): if act == 'gsm_dial': self.logger.info('Launching GSM dial action') u.gsm_dial('00447730520578') sleep(10) elif act == 'gsm_sms': self.logger.info('Launching GSM sms action') u.send_gsm_sms('00447730520578') sleep(10) self.logger.info('Issuer actions finished. Collecting issuer metrics and stoping user') self.add_metrics(u.get_metrics(sip=user_sip,gsm=user_gsm)) u.stop(dispsip=user_sip, dispgsm=user_gsm)
def b_user(id, msg, lis): if not (id in user.users()): user.add_user(id, '') lis[id] = user(id) #userlis[id] = user (id) ituser = lis[id] imd = ituser.mode if ituser.name == '' and ituser.mode == '0': ituser.smode('name') elif ituser.mode == 'name2': ituser.set_name(msg) ituser.smode('name3') elif imd == 'rename2': ituser.set_name(msg) ituser.smode('rename3') elif ituser.mode == 'name': send_message({ "to": id, "type": "TEXT", "body": "واقعا بابت تصمیمت خوشحال شدم(گرچه همه زحمتا با منه;)\nراستی اسمتو نگفتی!؟" }) ituser.smode('name2')
def createuser(self): #向用户字典中添加一对键值对(卡号-用户) name = input('请输入您的姓名:') idcard = input('请输入您的身份证号:') phone = input('请输入您的电话号码:') prestoremony = int(input('请输入预存款金额:')) if prestoremony < 0: print('预存款输入有误') return -1 onepasswd = input('请设置密码:') if not self.checkpasswd(onepasswd): print('密码输入错误,开户失败') return -1 cardid = self.randomcardid() card1 = card(cardid, onepasswd, prestoremony) user0 = user(name, idcard, phone, card1) #0-身份证号,1-密码,2-余额,3-锁定状态 alluser = [ user0.idcard, user0.card.cardpasswd, user0.card.cardmoney, user0.card.lock ] #0-用户名,1-电话号码,2-卡号 userinfo = [user0.name, user0.phone, user0.card.cardid] #print(list(user1)) self.alluser[cardid] = alluser self.userinfo[idcard] = userinfo print('开户成功!请记住卡号(%s)' % cardid)
def run(n_replications, n_steps, mean, cov, sigma, featurelist): total_reward = 0 var = 0 total_regret = 0 for sample in range(n_replications): User = user.user(mean, cov, sigma) User.generate_user() Server = server.server(mean, cov, sigma, featurelist, n_steps) maxrate = User.maxrate(featurelist) reward = 0 for i in range(n_steps): restaurant = Server.recommand() rate = User.rate(restaurant) reward += rate Server.update(restaurant, rate) reward = reward * 1.0 / n_steps #print 'rating', reward * n_steps total_reward += reward var += reward * reward total_regret += maxrate - reward mean_reward = total_reward * 1.0 / n_replications var = var * 1.0 / n_replications - mean_reward * mean_reward CI = [mean_reward - 1.96 * np.sqrt(var/n_replications), mean_reward + 1.96 * np.sqrt(var/n_replications)] mean_regret = total_regret * 1.0 / n_replications return mean_regret, mean_reward, CI
def __init__(self): self.user = user.user() self.view = "login" self.mode = "" self.current_input = "" self.running = False self.input_mode = True
def get_all_users(limit=None, sort='old', subreddit=None): user_list = [] cur_connection = DatabaseManager.get_connection() cursor = cur_connection.cursor() query = """SELECT * FROM users """ if subreddit is not None: query += """ Where subreddit='{subreddit}' """.format( subreddit=subreddit) query += """ ORDER BY last_update ASC, username ASC """ if limit is not None: query += """ LIMIT {limit} """.format(limit=limit) result = DatabaseManager._execute_robust(cursor, query) for row in result: new_user = user(row[0], row[1], row[2]) user_list.append(new_user) return user_list
def add_user(u, password): global users global voters global userObjs userObjs[u] = user.user() users[u] = password voters.append(u)
def getUser(self, username, server): #连接服务器 time.sleep(3) try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((config.server_name, config.remote_server_port)) sock.settimeout(15) #检测服务器是否关闭 except Exception: info("connection error", "error") return None sock.send('{"action":"login","uid":0,"username":"******","ip":"%s"}' % (username, server)) userdata = sock.recv(1024) print userdata u = user.user() u.set(json.loads(userdata)) while True: print "[FLOATER FIND] try to find fellow" sock.send('{"action":"find"}') fellow = sock.recv(1024) if fellow != "None": print "[FLOATER FOUND]", fellow userData = json.loads(fellow) u.set(userData) break time.sleep(3) sock.send('{"action":"close"}') sock.close() global username_remote username_remote = userData["username"] global server_name_remote server_name_remote = userData["ip"]
def register_session(sock, sock_msgs): # receive "NICK nick\r\n" msg = sio.try_read(sock, sock_msgs) nick = msg.replace("NICK ", "") # receive "USER user_name * * :real_name\r\n" msg = sio.try_read(sock, sock_msgs) first, second = msg.split(" * * :") user_name = first.replace("USER ", "") real_name = second client = user(nick, user_name, real_name) client.set_sock(sock) # send confirmation message # <thisIP> 001 <nick> :Welcome to the # Internet Relay Network <nick>!<user>@<theirIP>\r\n theirIP, _ = sock.getpeername() thisIP = socket.getfqdn() msg = "{} {} {} :Welcome to the ".format(thisIP, RPL_WELCOME, client.nick) msg += "Internet Relay Network " msg += "{}!{}@{}\r\n".format(client.nick, client.whoami, theirIP) sio.try_write(sock, msg) return client
def loginevent(self): inputed_login = self.login.get('1.0', 'end-1c') inputed_password = self.password.get('1.0', 'end-1c') q = get_all_log_pass() self.cur.execute(q) tmp = self.cur.fetchall() print(tmp) res = "" for i in range(len(tmp)): if tmp[i][0] == inputed_login and tmp[i][1] == inputed_password: if inputed_login == "admin": res = "admin" else: res = "user" if res == "admin": self.remove_all() #... elif res == "user": self.remove_all() user_page = user(self.r, self.bgc, inputed_login, self.cur) user_page.place_start() return True #... else: self.errorlabel.place(x=300, y=275) return False
def make_iplist(self,rawlist): u = user() count = 0 output = [] number = len(rawlist["address_detail"]) for _ in range(number): detail = str(rawlist["address_detail"][count][1]).split('|') if len(detail) == 2: username = detail[0] date = detail[1] status = "Ok" # check if username exists already username_exists = int(u.check_user(username)) if not username_exists == 1: status = "Orphaned" else: username = detail[0] date = None status = "Manually Created" ip = str(rawlist["address_ip"][count][1]) output.append({"username": username, "ip": ip, "status": status, "datetime": date}) count += 1 return output
def login(self,userinfo): if userinfo[0] == "" or userinfo[1] == "": return if self.conn is None: messagebox.showerror("Error","fail to connect to mysql database!") return try: search_sql = "select user_pass from person where user_name = '%s' and priot = %d;"%(userinfo[0],userinfo[1]) self.cursor = self.conn.cursor() self.cursor.execute(search_sql) rs = self.cursor.fetchone() if rs is None: messagebox.showerror("Error","nothing fetch") else: if userinfo[2] in rs: messagebox.showinfo("Success","login success") self.getCommission() if userinfo[1] == 1: us = manager.user(userinfo) else: us = user.user(userinfo) else: messagebox.showerror("Error","count and password error") except pymysql.Error as e: self.conn.rollback() print(e)
def run_example(): #first lets get the auth code from the client request_token_url = huddleAuthServer + "request?response_type=code" + "&client_id=" + consumer_key + "&redirect_uri=" + redirect_uri print "Get Your Authorization Code and paste it back into python\n" + request_token_url code = raw_input('--> ') auth = oAuth.oAuth(huddleAuthServer, code, consumer_key, redirect_uri) #store our access token tokenStore = auth.handleAccessToken() #now we can make calls to the api api = huddleApi.huddleApi(huddleApiServer, tokenStore) getWorkspaces = user.user(api.getUser()) print "You currently have " + str( getWorkspaces.getWorkSpaceSize()) + " workspaces!" for i in range(getWorkspaces.getWorkSpaceSize()): print "\nWorkspace : " + str( getWorkspaces.getWorkSpaceTitle(i)) + " has the following links: " for x in range(getWorkspaces.getWorkSpaceLinks(i)): print getWorkspaces.getWorkSpaceLinkRel( i, x) + ":" + getWorkspaces.getWorkSpaceLinkHref(i, x) os.system("pause")
def run(n_replications, n_steps, mean, cov, sigma, featurelist): total_reward = 0 var = 0 total_regret = 0 for sample in range(n_replications): User = user.user(mean, cov, sigma) User.generate_user() Server = server.server(mean, cov, sigma, featurelist, n_steps) maxrate = User.maxrate(featurelist) reward = 0 for i in range(n_steps): restaurant = Server.recommand() rate = User.rate(restaurant) reward += rate Server.update(restaurant, rate) reward = reward * 1.0 / n_steps #print 'rating', reward * n_steps total_reward += reward var += reward * reward total_regret += maxrate - reward mean_reward = total_reward * 1.0 / n_replications var = var * 1.0 / n_replications - mean_reward * mean_reward CI = [ mean_reward - 1.96 * np.sqrt(var / n_replications), mean_reward + 1.96 * np.sqrt(var / n_replications) ] mean_regret = total_regret * 1.0 / n_replications return mean_regret, mean_reward, CI
def __init__(self, loginnickname): self.myuser = user.user(loginnickname) self.root = Tk() self.root.title('聊天主界面0.0.1') self.root.geometry('350x600+400+50') #个人信息区域 self.head = Canvas(self.root, bg='orange') self.head.create_oval(30, 30, 80, 80) self.head.place(x=5, y=5, heigh=120, width=340) #好友区域 self.frend = Canvas(self.root, bg='pink') self.frend.place(x=5, y=130, heigh=420, width=340) #设置区域 self.setting = Canvas(self.root, bg='yellow') self.setting.place(x=5, y=555, heigh=40, width=340) #好友栏 self.frendstext = scrolledtext.ScrolledText(self.frend) self.frendstext.place(x=5, y=5, heigh=410, width=330) #自己的昵称名标签 self.myselfnicknamelable = Label(self.head, text=self.myuser.getnickname()) self.myselfnicknamelable.place(x=100, y=30) friendnum = 10 for i in range(friendnum): Thread(target=self.friendbuttonthread, args=('用户' + str(i + 1), )).start()
def setUp(self): root = Tk() bg_color = "white" user_login = "******" cur = Mock() cur.fetchall.return_value = [("1"), ()] self.t_user = user(root, "white", user_login, cur)
def recommend_similar_users(self, mode): a = user(self.uid) a.find_similar_users() result = {} su = a.similar_users rp = a.reco_algo(mode) er = a.error result['similar_users'] = su result['recommended_problems'] = rp result['error'] = er result = json.dumps(result, indent=4, separators=(',', ': ')) os.write(self.result_file, result) res = "\nShowing similar users and problem recommendations for: \n" + self.uid + "\nUser similarity: \n" os.write(self.log_file, res) print res res = json.dumps(su, indent=4, separators=(',', ': ')) os.write(self.log_file, res) print res res = "\nRecommended problems: \n" os.write(self.log_file, res) print res res = json.dumps(rp, indent=4, separators=(',', ': ')) os.write(self.log_file, res) print res res = "\nEstimated error in rating: \n" + str(er) os.write(self.log_file, res) print res
def __init__(self): # 그래픽 업데이트를 체크하기 위한 변수 self.check = True # 센서 노드(비콘 노드)의 수 self.node_num = 0 # 유저 노드의 객체 (user 파일 참조) self.user = us.user((0, 0)) # 현재 사용되는 channel : dict 형태로 저장됨 self.channel_list = {} for i in range(11, 27): self.channel_list[i] = [] # channel별 간섭의 레벨 : dict 형태로 저장됨 # 기본 간섭은 0Mbps self.interference_level = {} for i in range(11, 27): self.interference_level[i] = 0 # 센서 노드를 위한 grid map : dict 형태로 저장됨 # 값이 0이면 node가 없는 것 / 값이 1이면 node가 있는 것 self.grid_map = {} for i in range(1, 21): for j in range(1, 21): self.grid_map[(i,j)] = 0 # 유저 노드를 위한 grid map : dict 형태로 저장됨 # 유저 노드의 실제 위치를 저장 # 값이 0이면 user가 없는 것 / 값이 1이면 user가 있는 것 self.user_grid = {} for i in range(1, 21): for j in range(1, 21): self.user_grid[(i,j)] = 0 # 유저 노드를 위한 grid map : dict 형태로 저장됨 # 유저 노드의 예측 위치를 저장 # 값이 0이면 user가 없는 것 / 값이 1이면 user가 있는 것 self.esti_grid = {} for i in range(1, 21): for j in range(1, 21): self.esti_grid[(i,j)] = 0 # KNN 구현을 위해 생성한 Radio map self.radio_map = {} for i in range(1, 21): for j in range(1, 21): self.radio_map[(i,j)] = [] # 시뮬레이션 중인지 체크를 위한 변수 # True면 시뮬레이션 중 self.in_simul = False # 채널에 따른 packet loss exponent를 랜덤하게 설정 # 0.6에서 1.4 사이 self.ple_seed ={} for i in range(11,27): self.ple_seed[i] = random.uniform(0.6, 1.4)
def get_by_id(self, id): cur = self.conn.cursor() cur.execute("""SELECT id, email, first_name, last_name, google_id, facebook_id FROM users WHERE id=%s""", (id,)) row = cur.fetchone() cur.close() return user.user(row[0], row[1], row[2], row[3], row[4], row[5])
def __init__(self, msg): self._msg = msg # user self._user = user(self._msg.get('user')) # self._created_at = self._msg.get('created_at') self._id = self._msg.get('id') self._text = self._msg.get('text')
def __init__(self, address, port, connections, server): self.server = server server = socket.socket ( socket.AF_INET, socket.SOCK_STREAM ) server.bind ( ( address, port ) ) server.listen ( connections ) while True: channel, details = server.accept() self.uid = self.uid + 1 self.users.append(user.user(channel, self.uid)) wsthread.WebSocketThread (channel, details, self).start()
def authenticate_user(self): #return True if self.db: # First check for delegation backdoor if self.opts.get('on_behalf_of') and self.opts.get("access_token") in self.db.config.get('delegate_tokens'): self.user = user.user(cache = self.cache) self.user.id = self.opts['on_behalf_of'] return True else: # Must be normal or admin access_token self.user = user.user(access_token = self.opts.get("access_token",""), #slc_server = self.db.config.get("slc_server_host",user.default_slc_server), #url_path = self.db.config.get("slc_token_check_path",user.default_url_path), admin_access_tokens = self.db.config.get("admin_access_tokens",{}), delegate_tokens = self.db.config.get("delegate_tokens",[]), cache = self.cache) #print "USER STR",self.user,":",self.user.access_token,":",self.opts,":",self.opts.get("access_token",""),":" return self.user.authenticate() self.errors.append("No DB connection. Cannot authenticate user.") return False
def set_users_set(self, rootdir="E:\\rthings\\code\\python\\weibo\\output\\jieba\\user"): for parent_, dirnames_, filenames_ in os.walk(rootdir): parent = parent_.decode('gbk').encode('utf-8') for filename_ in filenames_: # 输出文件信息 filename = filename_.decode('gbk').encode('utf-8') if filename.startswith("user_segment_user_weibo_"): user_id = filename[-10:-1] filenamefull = os.path.join(parent, filename) user_item = user.user(user_id=user_id) user_item.set_segment_result_list(filename_segment=filenamefull) user_item.set_result_set() self.users_set[user_id] = user_item
def getMatchedImage(inUser): """Get an image can match this user, keep it simple and stupid""" if len(LoadedImage.loadedImages) > 0: for img in reversed(LoadedImage.loadedImages): imgUser = fetchUserByID(img.authorID) if (inUser.openid != imgUser.openid) and not(inUser.combinedHistory.get(str(img._id), None)): inUser.combinedHistory[str(img._id)] = 'used' return img dfImage = Image() dfImage.author = user('openid') dfImage.author.nickName = '羽毛粉丝' dfImage.url = 'http://www.enjoyxue.com/static/IMG_0493.JPG' return dfImage
def sign_up(self, message, sender): """ Create a user object for a given person and add the object to the recipient_list @param message: body of text message @param sender: sender of text message """ split_vals = message.split(" ") que = split_vals.pop(0) username = "******".join(split_vals) if sender not in self.recipient_set: new_user = user.user(username, sender) self.recipient_set.add(sender) self.recipient_list.append(new_user)
def get_all(self): cur = self.conn.cursor() cur.execute("""SELECT id, email, first_name, last_name, google_id, facebook_id FROM users""") rows = cur.fetchall() cur.close() users = [] for row in rows: users.append(user.user(row[0], row[1], row[2], row[3], row[4], row[5])) return users
def login(username, password): if username == 'admin': return False select_query = "SELECT username, password, address FROM users \ WHERE username = ? AND password = ? LIMIT 1" cursor.execute(select_query, (username, password)) current_user = cursor.fetchone() if(current_user): return user(current_user[0], current_user[2]) return False
def main(): domain = "" project = "" project_type = '' estrue = True while(domain==""): domain = raw_input("\033[92mDominio (Sin www):\033[0m ") while(project==""): project = raw_input("\033[92mNombre del proyecto:\033[0m ") while estrue: project_type = raw_input("\033[92mTipo de proyecto\n" "--> python\n" "--> php\n" "Pon uno de los tipos permitidos:\033[0m ") if project_type == "php": estrue = False if project_type =="python": estrue = False #Comprobamos si nginx esta instalado nginx_check() #Llamamos al modulo de usuario user(project) dirweb(project) if project_type == "python": #Comprobamos si esta instalado supervisor supervisor_check() #Comprobamos si esta instalado virtualenv o virtualenvwrapper virtualenv_check() #Al ser python creamos una virtualenv para el proyecto virtualenv(project) #Llamamos la modulo de nginx nginx_main(domain, project, project_type) #si el projecto esta en python, llamamos a supervisor para generar la configuracion if project_type == "python": supervisor_conf(project)
def load(self): if(os.path.isfile("usuarios")): f = open("usuarios","rb") self.users=[] while(True): u = f.read(20) p = f.read(20) while u: u = self.shor(u) p = self.shor(p) self.users.append(user(u, p)) u = f.read(20) p = f.read(20) break f.close()
def check(buffer, msg, i, s): u_info = msg[0] i_msg = buffer[buffer.find(buffer.split()[3])+1:] spker = user.user() spker.l_name = u_info[1:u_info.find("!")] spker.n_name = u_info[(u_info.find("!")+2):u_info.find("@")] if "[enter]#" in buffer: j_ch = buffer[buffer.find("[enter]")+7:] i.join(j_ch) with s: s.insert_channel(j_ch) if "[exit]#" in buffer: e_ch = buffer[buffer.find("[exit]")+6:] i.part(e_ch) with s: s.insert_channel(msg[2]) s.insert_log(spker.l_name, msg[1], msg[2], i_msg)
def _run_receiver(self): self.logger.info('Starting receiver user thread') user_code = self._config.get(self._test_name,'receiver_user') user_sip = ast.literal_eval(self._config.get(self._test_name,'receiver_user_devices'))['sip'] user_gsm = ast.literal_eval(self._config.get(self._test_name,'receiver_user_devices'))['gsm'] waiting_time = self._config.get(self._test_name,'receiver_user_waiting_time') self.logger.info('Initalizing receiver user: user_code:%s, sip:%s, gsm:%s, waiting_time:%s s',user_code,user_sip,user_gsm,waiting_time) u = user.user(user_code,sip=user_sip,gsm=user_gsm) self.logger.info('Starting receiver user') u.start(dispsip=user_sip, dispgsm=user_gsm) self.logger.info('Entering reveicer user in sleeping mode for %s seconds',waiting_time) sleep(float(waiting_time)) self.logger.info('Receiver waiting time finished. Collecting receiver metrics and stoping user') self.add_metrics(u.get_metrics(sip=user_sip,gsm=user_gsm)) u.stop(dispsip=user_sip, dispgsm=user_gsm)
def main(): global client global my global host_id host_id = 'stackoverflow.com' setup_logging() if 'ChatExchangeU' in os.environ: email = os.environ['ChatExchangeU'] else: email = raw_input('>> What is your email? \n') if 'ChatExchangeP' in os.environ: password = os.environ['ChatExchangeP'] else: password = raw_input('>> What is your password? \n') client = user.user(host_id, email, password) my = client.get_me() room = bot.join(client, 113461, chat_event) if 'first_start' in sys.argv: commit = os.popen('git log --pretty=format:"%h" -n 1').read() room.send_message('Super Goggles is up! Running on commit: [`' + commit + '`](https://github.com/Jacob-Gray/super-goggles/commit/' + commit + ')') while True: message = raw_input('<< ') if message == 'die': room.send_message('Shutting down...') time.sleep(0.4) break elif message == 'pull': os._exit(3) else: room.send_message(message) os._exit(6)
def __init__( self ): """ Do argument setup / description, and execute subcommand """ cmdStr = '' for cmd, desc in sorted( self.commands.items() ): cmdStr += ' %s%s\n' % ( cmd.ljust( 10, ' ' ), desc ) parser = argparse.ArgumentParser( prog = self.PROG_NAME, description = '', usage = '''%(prog)s <command> [<args>] The most commonly used %(prog)s commands are: ''' + cmdStr ) parser.add_argument( 'command', help = 'Subcommand to run' ) args = parser.parse_args( sys.argv[ 1:2 ] ) if ( not hasattr( self, args.command ) ) or ( args.command not in self.commands.keys() ): print( 'Unrecognized command' ) parser.print_help( ) exit( 1 ) # setup our default member vars self.user = user.user( ) self.processedUrls = { } self.historian = historian.historian( self ) self.configParser = conf.conf( ).genDefault( ) self.txtFile = False self.skipHandling = False self.browsers = { } self.urllist = [ ] self.blacklist = [ ] self.whitelist = [ ] self.stats = { 'tick': datetime.now( ), 'tock': None, 'visited': 0, 'skipped': 0, 'handled': 0 } # use CLI command == function name, use it getattr( self, args.command )( )
def run_example(): #first lets get the auth code from the client request_token_url = huddleAuthServer + "request?response_type=code" + "&client_id=" + consumer_key + "&redirect_uri=" + redirect_uri print "Get Your Authorization Code and paste it back into python\n" + request_token_url code = raw_input('--> ') auth = oAuth.oAuth(huddleAuthServer, code, consumer_key, redirect_uri) #store our access token tokenStore = auth.handleAccessToken() #now we can make calls to the api api = huddleApi.huddleApi(huddleApiServer, tokenStore) getWorkspaces = user.user(api.getUser()) print "You currently have " + str(getWorkspaces.getWorkSpaceSize()) + " workspaces!" for i in range(getWorkspaces.getWorkSpaceSize()): print "\nWorkspace : " + str(getWorkspaces.getWorkSpaceTitle(i)) + " has the following links: " for x in range(getWorkspaces.getWorkSpaceLinks(i)): print getWorkspaces.getWorkSpaceLinkRel(i, x) + ":" + getWorkspaces.getWorkSpaceLinkHref(i, x) os.system("pause")
def clientthread(connection, address): #infinite loop so that function do not terminate and thread do not end. auser = user.user() while True: try: buf = connection.recv(1024) data = json.loads(buf) if data["action"] == "login": newUser = auser.login(data["username"], data["ip"]) print "[FLOATER LOGIN] ", data["ip"] connection.send(json.dumps(newUser)) elif data["action"] == "find": result = auser.findFellow() print "[FLOATER FIND FELLOW] user:"******"find", result connection.send(str(result)) elif data["action"] == "logout": auser.logout() connection.send(str("{statu: OK}")) elif data["action"] == "close": print"[FLOATER CLOSE CONNECTION] ", address break else: auser.logout() print"[FLOATER CLOSE CONNECTION] ", address break except Exception as e: auser.logout() print"[FLOATER CLOSE CONNECTION] ", address print e, traceback.print_exc() connection.close() exit() return time.sleep(1) #came out of loop connection.close() time.sleep(10) auser.logout() print "cleared peer info"
def startUser(self): self.user = user(self.api) self.api.user = self.user
def user(self, username, connection): if username not in self.users: self.users[username] = user.user(username, connection) else: self.users[username].connection = connection return self.users[username]
try: from user import user except ImportError as exc: print("Error: failed to import settings module ({})".format(exc)) try: import db except ImportError as exc: print("Error: failed to import settings module ({})".format(exc)) print "Starting generating user based reco : ", time.strftime("%d-%m-%Y %H:%M") #config options = {} options['tag_based'] = 0 options['normalize'] = 0 options['sample_data'] = 0 options['penalize'] = 1 conn = db.connect() cursor = conn.cursor() sql = "SELECT erd_handle, cfs_handle FROM user" result = db.read(sql, cursor) for u in result: a = user(erd_handle = u[0][3:], cfs_handle = u[1][3:], options = options) a.reco_algo(1) print 'Recommendation generated for ' + u[0][3:] print "Finished generating problem based reco : ", time.strftime("%d-%m-%Y %H:%M")