예제 #1
0
	def submitParsingRequest(self,
							parsingRequest):

		gearmanClient = Client(ClientManager.JOB_SERVER_ADDRESS_LIST,
								parsingRequest)
		gearmanClient.run()
		gearmanClient = None
예제 #2
0
 def test_connect_from_server_if_encrypted_message_cannot_be_decrypted_to_two_elements_will_return_error_signal(
         self):
     client = Client(client_id=None, client_key=3197, server=None, server_id=None)
     random_value_from_server = 11
     encrypted_message = encrypt('{0}:{1}'.format('nonce', 'session-key'), self.client_key)
     response = client.process_message_from_server((random_value_from_server, encrypted_message))
     self.assertEqual(response, client.error_signal)
예제 #3
0
def run_client(host, port):
    selfClient = Client(host, int(port))
    selfClient._connect()
    input.append(selfClient.clientSocket)
    input.append(sys.stdin)
    running = True
    print "Connection established. Please set your name with /name to start chatting."   

 
    while running is True: 
        inready,outready,exready = select.select(input,[],[]) 

        for s in inready:
            # Receiving information from the other user (the server).
            if s == selfClient.clientSocket:
                data = s.recv(SIZE)
                if data:
                    print data
                else:
                    s.close()
                    print ERROR_MSG['conClosed']
                    running = False
                    break
            # Sending information to the other users via the server.
            if s == sys.stdin: 
                userText = sys.stdin.readline() 
                line = userText.rstrip("\r\n")
                selfClient.clientSocket.send(line)

    selfClient._close()
예제 #4
0
 def __init__(self, connectID,server):
     try:
         Client.__init__(self, connectID,server)
         self.__initData()
     except BaseException,e:
         print "Player Init Error"
         print e
예제 #5
0
class App(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.connect_button.clicked.connect(self.start)
        self.ui.send_button.clicked.connect(self.send_msg)

        self.client = None

    def start(self):
        server = self.ui.server_text.text()
        username = self.ui.user_text.text()


        self.client = Client(username, server)
        self.client.new_message.connect(self.print_msg)

        self.ui.chat_text.setEnabled(True)
        self.ui.message_text.setEnabled(True)
        self.ui.send_button.setEnabled(True)

    def send_msg(self):
        message = self.ui.message_text.text()
        self.ui.message_text.clear()
        self.client.send(message)

    def print_msg(self, message):
        self.ui.chat_text.append(message)
예제 #6
0
def main():

    # Establish the server cluster
    s1 = Server()
    s2 = Server()
    s3 = Server()
    s4 = Server()
    s5 = Server()

    s1.setNeighbors([s2, s3, s4, s5])
    s2.setNeighbors([s1, s3, s4, s5])
    s3.setNeighbors([s2, s1, s4, s5])
    s4.setNeighbors([s2, s3, s1, s5])
    s5.setNeighbors([s2, s3, s4, s1])

    t1 = Thread(target=s1.electionTimeout)
    t1.start()
    time.sleep(5)
    t2 = Thread(target=s2.electionTimeout)
    t2.start()
    t3 = Thread(target=s3.electionTimeout)
    t3.start()
    t4 = Thread(target=s4.electionTimeout)
    t4.start()
    t5 = Thread(target=s5.electionTimeout)
    t5.start()

    # Connect the client to the cluster leader
    c1 = Client()
    c1.connectClientToLeader(s2.neighbors)

    # Use the command line
    c1.waitForCommands()
예제 #7
0
    def setUp(self):
        self.done = False
        self.cFactory = pb.PBClientFactory()
        self.realm = WBRealm()
        self.realm.server = WbServer()
        self.wbServer = self.realm.server
        self.p = portal.Portal(self.realm)
        self.c = WBChecker()
        self.p.registerChecker(self.c)
        self.sFactory = pb.PBServerFactory(self.p)
        self.sFactory.protocol = WBBroker
        self.server = reactor.listenTCP(28789, self.sFactory)

        self.myClient = Client()
        self.myClient2 = Client()
        self.client = reactor.connectTCP("localhost", 28789, self.cFactory)
        self.client2 = reactor.connectTCP("localhost", 28789, self.cFactory)
        def1 = self.cFactory.login(credentials.UsernamePassword("Waldo","waldo"), client=self.myClient.cc)
        def1.addCallback(self.getRoot, 1)
        def1.addErrback(self.failure, "Error al conectarse el cliente1")
        deferredResult(def1)

        def2 = self.cFactory.login(credentials.UsernamePassword("Matias","matias"), client=self.myClient2.cc)
        def2.addCallback(self.getRoot, 2)
        def2.addErrback(self.failure, "Error al conectarse el cliente2")
        deferredResult(def2)
예제 #8
0
class SharedirsSet(object):
    def do_set(self, sharedirs, callback):
        sharedirs_element = Element('sharedirs')
        #TODO : gérer l'utf-8 (é) ...
        for sharedir in sharedirs:
           sharedir_element = SubElement(sharedirs_element, 'sharedir', {'name':sharedir.name, 'path':sharedir.path})
        self.client = Client(sharedirs_element, AnalyseSharedirs(callback))
        self.client.start()
예제 #9
0
파일: cli.py 프로젝트: Darot/ZEUS-FH
def run_http_post():
    #initialize a progressbar
    p = Progressbar(flow)
    client = Client(p)
    #run the wanted client method
    if args.endurance == None:
        client.send_http_post(ip, httpport, flow, delay, size)
    else:
        client.send_http_post_time(ip, httpport, endurance, delay, size)
예제 #10
0
파일: Eve.py 프로젝트: aryeko/MITM
    def __init__(self):
        self.Alice = Client()
        self.Alice.open_connection()

        self.Bob = Client()
        self.Bob.open_connection()

        self.Eve = Client()
        self.Eve.open_connection()

        self.alice_stolen_password = ""
예제 #11
0
파일: cli.py 프로젝트: Darot/ZEUS-FH
def run_zmq_sub():
    #initialize a progressbar
    p = Progressbar(flow)
    time.sleep(6)
    client = Client(p)
    #run the wanted client method
    if args.endurance == None:
        client.subscriber(flow, ip, port)
    else:
        client.subscriber_time(endurance, ip, port)
    print "Transmission complete!"
예제 #12
0
파일: cli.py 프로젝트: Darot/ZEUS-FH
def run_req():
    #initialize a progressbar
    p = Progressbar(flow)
    time.sleep(6)
    #new Client instanz
    client = Client(p)
    #run the wanted client method
    if args.endurance == None:
        client.sendAsync(flow, size, delay, ip, port)
    else:
        client.sendAsync_time(endurance, size, delay, ip, port)
    print "Transmission complete!"
예제 #13
0
파일: search.py 프로젝트: Jerk31/pyrex
class Search(object):
    def __init__(self, query):
        self.query = query
        
    def do_search(self, callback):
        search_element = Element('search', 
                        {'ttl': '3', 'id': str(randint(1, 10000000))})
        query_element = SubElement(search_element, 'query')
        query_element.text = self.query
    
        self.client = Client(search_element, AnalyseResults(callback))
        self.client.start()
예제 #14
0
class StatisticsGet(object):
    def __init__(self, callback, hostname=Configuration.ip_daemon):
        self.hostname = hostname
        self.callback = callback

    def do_get(self):
        search_element = Element('statistics', {'type': 'get'})
        self.client = Client(search_element, AnalyseStatistics(self.callback), self.hostname)
        self.client.start()

    def cancel(self):
        self.client.cancel()
예제 #15
0
파일: main.py 프로젝트: mgold/Packets
def mkDevice(screen, x, y, id):
    if id.isdigit():
        subnet = Subnet(screen, x, y)
        subnet.IP = IP(int(id))
        return subnet
    elif id == "N":
        dns = DNS(screen, x, y)
        dns.IP = str(ord(list(id)[0]))
        return dns
    elif id.isupper():
        router = Router(screen, x, y)
        router.IP = str(ord(list(id)[0]))
        router.selected = router.IP == "66"
        return router
    elif id.islower():
        if id == "h":
            host = Client(screen, x, y)
            host.name = "Alice"
            host.corespondent = "Bob"
        elif id == "x":
            host = Client(screen, x, y)
            host.name = "Bob"
            host.corespondent = "Alice"
        else:
            host = Host(screen, x ,y)
        host.IP = str(ord(list(id)[0]))
        return host
    else:
        print "Unrecognized unique identifier in sprite map"
        return None
예제 #16
0
class ConfDaemon(object):
    def __init__(self, callback, nickname=None, time_between_scan=None, nb_ips_scan_lan=None, ip_range=None, ips_remote_control=None, ftp_enabled=None, ftp_port=None, ftp_maxlogins=None, ftp_show_downloads=None):
        self.callback           = callback
        self.nickname           = nickname
        self.time_between_scan  = time_between_scan
        self.nb_ips_scan_lan    = nb_ips_scan_lan
        self.ip_range           = ip_range
        self.ips_remote_control = ips_remote_control
        self.ftp_enabled        = ftp_enabled
        self.ftp_port           = ftp_port
        self.ftp_maxlogins      = ftp_maxlogins
        self.ftp_show_downloads = ftp_show_downloads
        
    def set_conf(self):
        set_conf_element = Element('conf', {'type':'set'})
        # Nickname
        nickname_element = SubElement(set_conf_element, 'nickname')
        nickname_element.text = self.nickname
        # Time between scan
        time_between_scan_element = SubElement(set_conf_element, 'time_between_scan')
        time_between_scan_element.text = str(self.time_between_scan)
        # Nb IP à scanner
        nb_ips_scan_lan_element = SubElement(set_conf_element, 'nb_ips_scan_lan')
        nb_ips_scan_lan_element.text = str(self.nb_ips_scan_lan)
        # Plage IP
        ip_range_element = SubElement(set_conf_element, 'ip_range')
        ip_range_element.text = self.ip_range
        # IP config daemon
        ips_remote_control_element = SubElement(set_conf_element, 'ips_remote_control')
        ips_remote_control_element.text = self.ips_remote_control
        # FTP activé
        ftp_enabled_element = SubElement(set_conf_element, 'ftp_enabled')
        ftp_enabled_element.text = self.ftp_enabled and "true" or "false"
        # Port FTP
        ftp_port_element = SubElement(set_conf_element, 'ftp_port')
        ftp_port_element.text = str(self.ftp_port)
        # Max Connex simultanées FTP
        ftp_maxlogins_element = SubElement(set_conf_element, 'ftp_maxlogins')
        ftp_maxlogins_element.text = str(self.ftp_maxlogins)
        # Afficher dwl FTP
        ftp_show_downloads_element = SubElement(set_conf_element, 'ftp_show_downloads')
        ftp_show_downloads_element.text = self.ftp_show_downloads and "true" or "false"
        # On envoie au client
        self.client = Client(set_conf_element, AnalyseConfDaemon(self.callback))
        self.client.start()
        
    def get_conf(self):
        get_conf_element = Element('conf', {'type':'get'})
        self.client = Client(get_conf_element, AnalyseConfDaemon(self.callback))
        self.client.start()
예제 #17
0
def client_function():
    print "Connecting to a server..."
    sys.stdout.write("Server?: ")
    host = stdin.readline().rstrip("\n")
    sys.stdout.write("Port?: ")
    port = stdin.readline().rstrip("\n")
    c = Client(host, int(port))
    c.send_packet("hello!")
    sleep(.01)
    i = 0
    #wait to get packetConfirm
    while i < 3:
        c.Loop()
        sleep(.1)
        i += 1
예제 #18
0
 def do_search(self, callback):
     search_element = Element('search', {'ttl': '3', 'id': str(randint(1, 10000000))})
     query_element = SubElement(search_element, 'query')
     query_element.text = self.query
     if self.protocol: 
         protocol_element = SubElement(search_element, 'protocol')
         protocol_element.text = self.protocol
     elif self.type_share:
         type_share_element = SubElement(search_element, 'type')
         type_share_element.text = self.type_share
     elif self.extensions:
         extensions_element = SubElement(search_element, 'extensions')
         extensions_element.text = self.extensions
     elif self.sizeinf:
         sizeinf_element = SubElement(search_element, 'sizeinf')
         sizeinf_element.text = str(self.sizeinf)
     elif self.sizesup:
         sizesup_element = SubElement(search_element, 'sizesup')
         sizesup_element.text = str(self.sizesup)
     elif self.dateinf:
         dateinf_element = SubElement(search_element, 'dateinf')
         dateinf_element.text = self.dateinf
     elif self.datesup:
         datesup_element = SubElement(search_element, 'datesup')
         datesup_element.text = self.datesup            
     self.client = Client(search_element, AnalyseResults(callback))
     self.client.start()
예제 #19
0
 async def handleConnection(self, reader, writer):
     client_id = await self.getIdForClient()
     client = Client(reader, writer, client_id)
     print('New connection from {}'.format(client.addr))
     await self.addClient(client)
     await self.sendAvailableGames(client)
     await self.listenForCommand(client)
	def testEntitiesHaveSecondaries(self):
		for e in self._entityCollection:
			if not 0 <= 1 < len(e):
				continue

			for sk in e[1]:
				self.assertIsInstance(getattr(e[0](Client(), {'id': 1}), sk), e[1][sk])
예제 #21
0
    def __init__(self, *args, **kwargs):
        self.failed = 0
        super().__init__(*args, **kwargs)
        self.listeners = []
        self.listening = False
        self.open = False
        print("Client connected!")

        self.client = None

        if "clientid" in cherrypy.request.cookie:
            cookie_id = cherrypy.request.cookie["clientid"].value
            if cookie_id in ClientHandler.clients.keys():
                self.client = ClientHandler.clients[cookie_id]
                if self.client.sender and self.client.sender.open:
                    self.client.sender.close(1000, "Closing outdated connection")
                    print(self.client.sender.close)
                self.client.reinit(self.api, None, self, self)
                self.client.id = cookie_id
                print("Reconnected cient {}".format(cookie_id))

        if not self.client:
            self.client = Client(self.api, None, self, self)
            self.client.id = str(uuid.uuid4())
            ClientHandler.clients[self.client.id] = self.client
            print("Connected new client {}".format(self.client.id))

        updater = ClientUpdater(self.universe, self.client, self.api)
        self.universe.updaters.append(updater)
예제 #22
0
class ClientPrepareMessageForServerTest(unittest.TestCase):
    def setUp(self):
        self.client = Client(client_id='client_id', client_key=123, server='mockServer', server_id=None)

    def test_first_element_of_message_is_a_number(self):
        result = self.client.prepare_message_for_server()
        self.assertTrue(isinstance(result[0], int))
예제 #23
0
	def __init__(self) :
		super(ClientCreateDialog, self).__init__(u"Nouveau client", u"Ok", u"Annuler")
		
		self.m_client		= Client()
		self.m_clientForm	= ClientForm()
		self.m_clientForm.setClient(self.m_client)
		self.setContent(self.m_clientForm, 9)
예제 #24
0
def login(username, password):
    import calendar

    result = cursor.execute(
        'SELECT failed_logins, last_login FROM clients WHERE username = ? LIMIT 1', (username,)).fetchone()
    failed_attempts = int(result[0])
    last_login = int(result[1])
    date = datetime.datetime.now() + datetime.timedelta(minutes=5)
    timestamp = calendar.timegm(date.utctimetuple())

    if failed_attempts > 5 and last_login - timestamp > 300:
        cursor.execute(
            'UPDATE clients SET failed_logins = 0 WHERE username = ?', (username,))
        conn.commit()

    if failed_attempts > 5:
        print('Login attempts exceeded')
        return False

    cursor.execute(
        '''SELECT id, username, balance, message FROM clients WHERE username = ? AND password = ? LIMIT 1''', (username, password))
    user = cursor.fetchone()

    if user and failed_attempts < 6:
        return Client(user[0], user[1], user[2], user[3])
    else:
        date = datetime.datetime.now()
        timestamp = calendar.timegm(date.utctimetuple())
        cursor.execute(
            '''UPDATE clients SET last_login = ?, failed_logins = failed_logins + 1 WHERE username = ? ''', (timestamp, username))
        conn.commit()
        return False
	def testHandlersAllSupportedFilters(self):
		client = Client()
		client.debugReturn = {
			'data': '{"x": [], "meta": {"pagination": {}}}',
			'status': 200
		}

		for e in self._handlerCollection:
			if 0 <= 1 < len(e) and e[1] == 'requiresIDInConstructor':
				inst = e[0](client, 999)
			else:
				inst = e[0](client)

			inst.all({'include': ''})
			inst.all({'limit': 10})
			inst.all({'page': 2})
class ClientTests(unittest.TestCase):

    def setUp(self):
        self.test_client = Client(1, "Ivo", 200000.00, "Bitcoin mining makes me rich")

    def test_client_id(self):
        self.assertEqual(self.test_client.get_id(), 1)

    def test_client_name(self):
        self.assertEqual(self.test_client.get_username(), "Ivo")
    
    def test_client_balance(self):
        self.assertEqual(self.test_client.get_balance(), 200000.00)

    def test_client_message(self):
        self.assertEqual(self.test_client.get_message(), "Bitcoin mining makes me rich")
예제 #27
0
 def set_conf(self):
     set_conf_element = Element('conf', {'type':'set'})
     # Nickname
     nickname_element = SubElement(set_conf_element, 'nickname')
     nickname_element.text = self.nickname
     # Time between scan
     time_between_scan_element = SubElement(set_conf_element, 'time_between_scan')
     time_between_scan_element.text = str(self.time_between_scan)
     # Nb IP à scanner
     nb_ips_scan_lan_element = SubElement(set_conf_element, 'nb_ips_scan_lan')
     nb_ips_scan_lan_element.text = str(self.nb_ips_scan_lan)
     # Plage IP
     ip_range_element = SubElement(set_conf_element, 'ip_range')
     ip_range_element.text = self.ip_range
     # IP config daemon
     ips_remote_control_element = SubElement(set_conf_element, 'ips_remote_control')
     ips_remote_control_element.text = self.ips_remote_control
     # FTP activé
     ftp_enabled_element = SubElement(set_conf_element, 'ftp_enabled')
     ftp_enabled_element.text = self.ftp_enabled and "true" or "false"
     # Port FTP
     ftp_port_element = SubElement(set_conf_element, 'ftp_port')
     ftp_port_element.text = str(self.ftp_port)
     # Max Connex simultanées FTP
     ftp_maxlogins_element = SubElement(set_conf_element, 'ftp_maxlogins')
     ftp_maxlogins_element.text = str(self.ftp_maxlogins)
     # Afficher dwl FTP
     ftp_show_downloads_element = SubElement(set_conf_element, 'ftp_show_downloads')
     ftp_show_downloads_element.text = self.ftp_show_downloads and "true" or "false"
     # On envoie au client
     self.client = Client(set_conf_element, AnalyseConfDaemon(self.callback))
     self.client.start()
예제 #28
0
파일: Gui.py 프로젝트: djgwilt/TicTacToe
class Gui:
    def __init__(self, name):

        self._name = name
        self._client = Client()
        self._counter = 0

        root = Tk()
        root.title(self._name)
        frame = Frame(root)
        frame.pack()

        Button(frame, text='Quit', command=self._quit).pack(fill=X)

        Button(frame, text='Send', command=self._send).pack(fill=X)

        scroll = Scrollbar(frame)
        console = Text(frame, height=4, width=50)
        scroll.pack(side=RIGHT, fill=Y)
        console.pack(side=LEFT, fill=Y)

        scroll.config(command=console.yview)
        console.config(yscrollcommand=scroll.set)

        self._root = root
        self._console = console

    def _quit(self):
        self._client.quit()
        self._running = False

    def _send(self):
        message = f"{self._name} {self._counter}"
        self._counter += 1
        get_event_loop().create_task(self._client.send(message))

    async def run_client(self):
        await self._client.run()

    async def run_gui(self):
        self._running = True
        while self._running:
            await sleep(0.1)
            if self._client.can_recv:
                msg = await self._client.recv()
                self._console.insert(END, f"{msg}\n")
            self._root.update()
예제 #29
0
	def __init__(self, root, address, session_id):
		'initial setup for the connected client'
		
		Client.__init__(self, root, None, address, session_id)
		
		self.static = True # can't be removed... don't want to anyway :)
		self.logged_in = True
		self.access = 'admin'
		self.accesslevels = ['admin', 'mod', 'user', 'everyone']
		
		self.bot = 1
		self.username = '******'
		self.password = '******'
		self.cpu = '9001'
		self.lobby_id = 'ChanServ'
		self._root.usernames[self.username] = self
		self._root.console_write('Successfully logged in static user <%s> on session %s.'%(self.username, self.session_id))
예제 #30
0
def login(conn, cursor, username, password):
    cursor.execute('''SELECT id, username, balance, message FROM clients WHERE username = ? AND password = ? LIMIT 1''', (username, password))
    user = cursor.fetchone()

    if(user):
        return Client(user[0], user[1], user[2], user[3])
    else:
        return False
    def testAskfolderListMethod_withExistAndNoEmpltyFolder_returnsListOfTheFolders(
            self):
        folder = 'folder1'
        protocole = Protocole_xml()
        mock_connexion = unittest.mock.Mock()
        xmlFolder1 = protocole.generateXmlFormat("dossier", "folder2")
        xmlFolder2 = protocole.generateXmlFormat("dossier", "folder3")
        xmlFolderList = protocole.generateXmlFormat("listeDossiers")
        xmlFolderList.childNodes[0].appendChild(xmlFolder1.childNodes[0])
        xmlFolderList.childNodes[0].appendChild(xmlFolder2.childNodes[0])
        returnValue = xmlFolderList.toxml()
        mock_connexion.receive.return_value = returnValue
        client = Client(mock_connexion, protocole)

        clientAnswer = client.folderList(folder)
        expected_answer = "folder2/folder3/"
        self.assertEquals(clientAnswer, expected_answer)
예제 #32
0
class ApiV1:
    def __init__(self, api_url, base_path, host, private_key, public_key):
        self._client = Client(api_url, base_path, host, private_key,
                              public_key)
        self.order = Order(self._client)

    def info(self):
        return self._client.do_get('/info', 'info')
예제 #33
0
 def __init__(self, redis, RedisHandler, audit, loop, ip, port,
              LegacyStock):
     self.LegacyStock = LegacyStock
     self.redis = redis
     self.RedisHandler = RedisHandler
     self.audit = audit
     self.client = Client(loop)
     self.dbmURL = f'http://{ip}:{port}'
예제 #34
0
def login(username, password):
    select_query = "SELECT id, username, balance, message FROM clients WHERE username = ? AND password = ? LIMIT 1;"
    cursor.execute(select_query, (username, password))
    user = cursor.fetchone()
    if (user):
        return Client(user[0], user[1], user[2], user[3])
    else:
        return False
예제 #35
0
class Main(QtWidgets.QMainWindow
           ):  #TODO: low prio use Qthread to intialize CLient
    def __init__(self):
        super(Main, self).__init__()
        self.mainWindow = uic.loadUi("resources/MainWindow.ui", self)
        self.mainWindow.input.returnPressed.connect(self.enter)
        data = CustomDialog().getData()
        if data == ":":
            quit()
        else:
            data = data.split(":")
            self.client = Client(data[0], data[1], self.mainWindow)

    def enter(self):
        input = self.mainWindow.input.text()
        self.client.sendInput(input)
        self.mainWindow.input.clear()
예제 #36
0
    def __init__(self, parent=None):
        super().__init__(parent)
        # initialize client
        self.client = Client()

        # initialize user
        self.user = User()

        # other users received
        self.others = []

        # initiliaze room's info
        self.rooms_info = list()

        self.setUp_home()

        self.setCurrentIndex(0)
예제 #37
0
def main():
    locale.setlocale(locale.LC_ALL, 'de_DE')

    with open('lichess.token') as f:
        token = f.read().strip()
    client = Client(team_id='schachklub-langen-e-v', token=token)

    Scheduler(client).schedule_future_tournaments()
예제 #38
0
    def connection(self):
        self.connecte = True
        self.connexion = Client(self.hote, self.port)
        print("connexion")
        self.connexion2 = Client(self.hote, self.port2)
        self.update_graph = graph_thread(
            self.graphGyro, self.graphAcc, self.graphMagneto, self.graphTemp,
            self.graphBatt, self.taille_Gyro_x, self.taille_Acc_x,
            self.taille_Magneto_x, self.taille_Temp_x, self.taille_Batt_x,
            self.Donnees)
        self.text_thread = Text_MAJ(self.connexion, self.connexion2)

        #print("init du thread")
        self.text_thread.start()
        self.update_graph.start()
        #self.update_graph.start()
        self.Timer.start()
예제 #39
0
class TestOop1MajorClient(unittest.TestCase):
    def setUp(self):
        self.client_data = \
            ('Carrie Cordon',
             '*****@*****.**',
             '404-444-1111',
             'VISA',
             'PAID',
             'Doesn\'t pay on time',
             'Give notice to pay.')

        self.client = Client(self.client_data)

    def test_add_credits(self):
        self.assertEqual(0, self.client.credits)
        self.client.add_credits(5)
        self.assertEqual(5, self.client.credits)
예제 #40
0
 def __init__(self, name, ip):
     super(ChatWidget, self).__init__()
     self.name = name
     self.usersNames = []
     self.handler = Client(name)
     self.handler.connect(ip, 7776)
     self.usersList = QTextEdit()
     self.chatText = QTextEdit()
     self.inputLine = QLineEdit()
     self.styleSetUp()
     self.layoutSetUp()
     thread1 = Thread(target=self.handler.myrecive,
                      args=(
                          self.chatText,
                          self.usersNames,
                      ))
     thread1.start()
 def connect_clients(self):
     while True:
         client_socket, address = self.server_socket.accept()
         client = Client(client_socket)
         self.connected_clients.append(client)
         t = threading.Thread(target=self.communicate_client,
                              args=(client, ))
         t.start()
예제 #42
0
	def __init__(self, root, address, session_id):
		'initial setup for the connected client'
		
		Client.__init__(self, root, None, address, session_id)
		
		self.static = True # can't be removed... don't want to anyway :)
		self.logged_in = True
		self.access = 'admin'
		self.accesslevels = ['admin', 'mod', 'user', 'everyone']
		
		self.bot = 1
		self.username = '******'
		self.password = '******'
		self.cpu = '9001'
		self.lobby_id = 'ChanServ'
		self._root.usernames[self.username] = self
		self._root.console_write('Successfully logged in static user <%s> on session %s.'%(self.username, self.session_id))
예제 #43
0
class ClientTests(unittest.TestCase):
    def setUp(self):
        self.test_client = Client(1, "Ivo", 200000.00,
                                  "Bitcoin mining makes me rich")

    def test_client_id(self):
        self.assertEqual(self.test_client.get_id(), 1)

    def test_client_name(self):
        self.assertEqual(self.test_client.get_username(), "Ivo")

    def test_client_balance(self):
        self.assertEqual(self.test_client.get_balance(), 200000.00)

    def test_client_message(self):
        self.assertEqual(self.test_client.get_message(),
                         "Bitcoin mining makes me rich")
예제 #44
0
class unittest_Client(unittest.TestCase):
    def setUp(self, logFile='log/Client.log'):
        self.logger = Logger(logFile, 'DEBUG', 'Sub')
        self.logger = self.logger.getLogger()
        self.client1 = Client('client-ftp', self.logger)
        self.client2 = Client('client-am', self.logger)

    def test_Client(self):
        self.client1.readConfig()
        self.assertEqual(self.client1.name, 'client-ftp')
        self.assertEqual(self.client1.protocol, 'ftp')
        self.assertEqual(self.client1.getDestInfos('TOTO'), (None, None))
        self.assertEqual(
            self.client1.getDestInfos(
                'iceglbgrib2:iceglb:CMC:GRIB:BIN:2012061800'),
            ('iceglbgrib2:iceglb:CMC:GRIB:BIN:2012061800',
             '//isis_feed/ftp/cmc_grib2'))
        self.assertEqual(self.client1.fx_script(), 'Done')
        self.assertEqual(self.client1.destfn_script(), 'Done')
        self.assertEqual(
            self.client1.getDestInfos(
                'MAPS_GFACN:GFA:CMC:CHART:PNG:2012061800'),
            ('MAPS_GFACN:GFA:CMC:CHART:PNG:2012061800',
             '//isis_feed/ftp/prdnamed'))
        self.assertEqual(self.client1.destfn_execfile, 'script3.py')
예제 #45
0
def main():

    # Setup
    c = Client('localhost', 8000)
    c.run()

    secret = listen_for_secret(c)

    # Loop

    while True:

        incoming = decrypt_incoming(c.recv(), secret)

        command = incoming & 255
        potential = (incoming >> 8) & 255
        challenge = incoming >> 16

        print(
            f"Receiving-> command = {command}, potential = {potential}, challenge = {challenge}"
        )

        response = solve_challenge(challenge)
        print(f"Challenge response: {response}")
        c.send(encrypt_response(response, secret))
        secret = mutate_secret(response, secret)
        print(f"Secret mutated. New secret is: {secret}")

        time.sleep(0.2)
예제 #46
0
def testClientConnectionToWithoutLeadershipChangeInCluster():
    # Establish cluster
    s1 = Server()
    s2 = Server()
    s3 = Server()
    
    # Set cluster membership
    s1.setNeighbors([s2, s3])
    s2.setNeighbors([s1, s3])
    s3.setNeighbors([s1, s2])
    
    # Create cluster leader
    # Request an election
    s2.requestVotes()
    
    # Connect the client to the cluster leader through a non-leader
    c1 = Client()
    c1.connectClientToLeader(s1.neighbors)
    assertion(c1.clusterLeader.uuid == s2.uuid, "Client is connected to the leader.")
    
    c1.connectClientToLeader(s2.neighbors)
    assertion(c1.clusterLeader.uuid == s2.uuid, "Client is connected to the leader.")
    
    c1.connectClientToLeader(s3.neighbors)
    assertion(c1.clusterLeader.uuid == s2.uuid, "Client is connected to the leader.")
예제 #47
0
    def __init__(self, parent):
        wx.Frame.__init__(self,
                          parent,
                          id=wx.ID_ANY,
                          title=u"聊天界面",
                          pos=wx.DefaultPosition,
                          size=wx.Size(600, 600),
                          style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL)

        self.SetSizeHints(wx.DefaultSize, wx.DefaultSize)

        bSizer1 = wx.BoxSizer(wx.VERTICAL)

        self.m_textCtrl2 = wx.TextCtrl(self, wx.ID_ANY, wx.EmptyString,
                                       wx.DefaultPosition, wx.Size(600, 400),
                                       wx.TE_MULTILINE | wx.TE_READONLY)
        bSizer1.Add(self.m_textCtrl2, 0, wx.ALL, 5)

        self.m_textCtrl1 = wx.TextCtrl(self, wx.ID_ANY, wx.EmptyString,
                                       wx.DefaultPosition, wx.Size(600, 100),
                                       wx.TE_MULTILINE | wx.TE_PROCESS_ENTER)
        bSizer1.Add(self.m_textCtrl1, 0, wx.ALL, 5)

        self.m_button = wx.Button(self, wx.ID_ANY, u"发送消息", wx.DefaultPosition,
                                  wx.Size(600, 30), 0)
        bSizer1.Add(self.m_button, 0, wx.ALL, 5)

        self.SetSizer(bSizer1)
        self.Layout()
        self.m_timer = wx.Timer()
        self.m_timer.SetOwner(self, wx.ID_ANY)

        self.Centre(wx.BOTH)

        # Connect Events
        self.Bind(wx.EVT_CLOSE, self.close)
        self.m_textCtrl1.Bind(wx.EVT_TEXT_ENTER, self.click)
        self.m_button.Bind(wx.EVT_BUTTON, self.click)
        self.Bind(wx.EVT_TIMER, self.fresh, id=wx.ID_ANY)

        # 建立客户端对象
        self.client = Client()
        # 多线程走起
        self.thread = ResponseSync(self)
        self.thread.start()
예제 #48
0
파일: XMLClient.py 프로젝트: kotas/reflec
    def __init__(self, node):
        address = node.get("address")
        server  = node.get("server")
        max     = node.findtext("max")
        media   = node.find("media")

        try:
            max = int(max)
        except ValueError:
            max = None

        params = {}
        if address: params["address"] = address
        if server:  params["server"]  = server
        if max:     params["max"]     = int(max)
        if media:   params["media"]   = media.items()

        Client.__init__(self, **params)
예제 #49
0
def main():
    '''key = 'abcdefghijklmnop'
    cipher = AES.new(bytes(key, 'utf-8'), AES.MODE_ECB)
    msg = cipher.encrypt(bytes('TechTutorialsX!!TechTutorialsX!!', 'utf-8'))
    print(len(msg))
    print(type(msg))
    print(msg)

    with open("filename", "wb") as newFile:
        newFile.write(msg)

    with open("filename", "rb") as newFile:
        data = newFile.read()
    decipher = AES.new(bytes(key, 'utf-8'), AES.MODE_ECB)
    print(decipher.decrypt(data).decode('utf-8'))'''

    client = Client('127.0.0.1', 14900)
    client.start_client()
예제 #50
0
    def __init__(self, buckets=(1, 1, 6, 12,), n_episodes=1000, n_win_ticks=195, min_alpha=0.1, min_epsilon=0.1, gamma=1.0, ada_divisor=25, max_env_steps=None, quiet=False, monitor=False):
        self.buckets = buckets # down-scaling feature space to discrete range
        self.n_episodes = n_episodes # training episodes 
        self.n_win_ticks = n_win_ticks # average ticks over 100 episodes required for win
        self.min_alpha = min_alpha # learning rate
        self.min_epsilon = min_epsilon # exploration rate
        self.gamma = gamma # discount factor
        self.ada_divisor = ada_divisor # only for development purposes
        self.quiet = quiet

        self.env = Client('id-rw-server-openai', 'CartPole-v0')
        self.env.Init("localhost", DAPR_GRPC_PORT)

        if max_env_steps is not None: self.env._max_episode_steps = max_env_steps
        actionSpaceInfo = self.env.ActionSpaceInfo()

        print(f"Action Space: {actionSpaceInfo.discrete.n}")
        self.Q = np.zeros(self.buckets + (actionSpaceInfo.discrete.n,))
예제 #51
0
 def setUp(self):
     self.client = Client(name='name',
                          g='generator',
                          p='size',
                          input_queue='input_queue',
                          output_queue='output_queue',
                          rsa_obj='rsa-objc',
                          keys='keys',
                          server_id='server_id')
예제 #52
0
def fill_clients(file_name):
  clients = []

  with open(file_name) as f:
    for line in f:
      cliente = line[:-1].split(',')
      client = Client(cliente[0],int(cliente[1]),int(cliente[2]),cliente[3],cliente[4],cliente[5],float(cliente[6]),float(cliente[7]),float(cliente[8]))
      clients.append(client)
    return clients
예제 #53
0
    def get_targets_from_csv(csv_filename):
        '''
            Returns list of Target objects parsed from CSV file
        '''
        targets = []
        import csv
        with open(csv_filename, 'rb') as csvopen:
            lines = (line.replace('\0', '') for line in csvopen)
            csv_reader = csv.reader(lines, delimiter=',')
            hit_clients = False
            for row in csv_reader:
                # Each "row" is a list of fields for a target/client

                if len(row) == 0: continue

                if row[0].strip() == 'BSSID':
                    # This is the "header" for the list of Targets
                    hit_clients = False
                    continue

                elif row[0].strip() == 'Station MAC':
                    # This is the "header" for the list of Clients
                    hit_clients = True
                    continue

                if hit_clients:
                    # The current row corresponds to a "Client" (computer)
                    try:
                        client = Client(row)
                    except IndexError:
                        # Skip if we can't parse the client row
                        continue

                    if 'not associated' in client.bssid:
                        # Ignore unassociated clients
                        continue

                    # Add this client to the appropriate Target
                    for t in targets:
                        if t.bssid == client.bssid:
                            t.clients.append(client)
                            break

                else:
                    # The current row corresponds to a "Target" (router)
                    target = Target(row)

                    if target.essid_len == 0:
                        # Ignore empty/blank ESSIDs
                        continue

                    if target.channel == "-1":
                        # Ignore -1 channel
                        continue

                    targets.append(target)
        return targets
예제 #54
0
def update_deposit_amount(logged_user, amount):
    new_amount = logged_user.get_balance() + amount
    username = logged_user.get_username()
    sql_manager.update_amount(username, new_amount)
    id = logged_user.get_id()
    message = logged_user.get_message()
    email = logged_user.get_email()
    logged_user = Client(id, username, new_amount, message, email)
    return logged_user
 def __init__(self, audit, cache_ip, cache_port, dbm_ip, dbm_port, loop):
     self.audit = audit
     self.client = Client(loop)
     self.cache_url = f'http://{cache_ip}:{cache_port}'
     self.dbm_url = f'http://{dbm_ip}:{dbm_port}'
     self.scheduler = self._setupScheduler()
     self.results = []
     self.triggers = {}
     self.prices = {}
예제 #56
0
def main():
    """
    go to : https://developer.srgssr.ch/apis/rts-archives-v3
    create your app,
    get your consumer key and secret
    remember, that package is only for accessing the "RTS Archives v3" (broadcast) API
    todo: add other endpoint
    """

    # pass an object with your credentials for generating a token and
    # instantiate a client access to the API
    # username = consumer key
    # password = consumer secret
    obj = {"username": "******", "password": "******"}

    cl = Client(obj)

    # get your token trough the Client.token parameter
    print(cl.token)

    # pass an object with the desired request
    # inside to the Client.request() method
    querystring = {
        "query": "'id'='103'",
        "rows": "1",
        "start": "0",
        "minPublicationDate": "1960",
        "maxPublicationDate": "2020",
        "sort": "publicationDate"
    }

    results = cl.request(querystring)
    data = results.json()

    # results can be a little bit "too generous"
    # refine the results with the Client.filter() method

    filtered = cl.filter_data(data, ['program', 'id'],
                              103)  # program id : 103 = Temps Présent

    # save the result with the Client.save() method
    # pass a data and a mongodb collection in parameters

    res = cl.save_data(data, collection)
예제 #57
0
 def setUp(self,logFile='log/SenderFTP.log'):
   self.logger = Logger(logFile, 'DEBUG', 'Sub')    
   self.logger = self.logger.getLogger()    
   self.client = Client('client-test',self.logger)  
   self.cacheManager = CacheManager(maxEntries=3, timeout=5 * 3600)
   #Le sender doit etre capable de connecter au serveur ftp pour continuer le test.
   self.sender = SenderFTP(self.client, self.logger, self.cacheManager)
   file1 = open("txq/client-test/3/test","w")
   file1.close()
   self.files = ['txq/client-test/3/test']
예제 #58
0
    def __init__(self, root, address, session_id):
        "initial setup for the connected client"

        Client.__init__(self, root, None, address, session_id)

        self.static = True  # can't be removed... don't want to anyway :)
        self.logged_in = True
        self.access = "admin"
        self.accesslevels = ["admin", "mod", "user", "everyone"]

        self.bot = 1
        self.username = "******"
        self.password = "******"
        self.cpu = "9001"
        self.lobby_id = "ChanServ"
        self._root.usernames[self.username] = self
        self._root.console_write(
            "Successfully logged in static user <%s> on session %s." % (self.username, self.session_id)
        )
def login(username, password):
    cursor.execute(
        "SELECT id, username, balance, message FROM clients WHERE username = ? AND password = ? VALUES(?,?) LIMIT 1",
        (username, password))
    user = cursor.fetchone()

    if (user):
        return Client(user[0], user[1], user[2], user[3])
    else:
        return False
예제 #60
0
class ThrowSocketHandler(tornado.websocket.WebSocketHandler):
    _client = None
    _tmp_files = {}
    _downloaded = []

    def allow_draft76(self):
        return True

    def open(self):
        self._client = ""
        self._tmp_files = {}
        self._downloaded = []
        global _clients

        while True:
            print _clients
            tmp_id = str(random.randint(0,999999)).zfill(10)
            print tmp_id
            if id not in _clients: 
                self._client = Client(tmp_id)
                _clients[tmp_id] = self
                break
        
        print _clients
        
        self._client._files = {}
        tmp_msg = Msg(None, self._client.client_id)
        tmp_msg.set_type(MsgCon.TYPE_CONN_DETAILS)
        tmp_msg.set_body(self._client.get_details())
        self.write_message(str(tmp_msg))
                
    def on_close(self): 
        id = self._client.client_id
        self._client.cleanUp()
        self._client = None
        del self._client
        _clients[id] = None
        del _clients[id] 

    def on_message(self, message):
        parsed = tornado.escape.json_decode(message)
        process(self, parsed)