예제 #1
0
 def update_result(self, submissionId, judgeResult, runTime, runMemory,
         compilerOutput, coreOutput, validatorOutput, programOutput, dateTime):
     request = UpdateResultRequest(self._siteId, submissionId, judgeResult, runTime, runMemory,
         compilerOutput, coreOutput, validatorOutput, programOutput, dateTime)
     client = Client()
     response = client.send_request(request, 'Update Result')
     return response
예제 #2
0
class Master():
  def __init__(self):
    self.client = None
    self.server = None

  def call(self, host, port):
    if self.client==None:
      self.client = Client(self)
      self.client.call(host, port)
  
  def callOn(self, addr):
    if self.client == None:
      self.client = Client(self)
      thread.start_new_thread(
        self.client.call, addr)

  def serve(self):
    if self.server==None:
      self.server = Server(self)
      self.server.listen()

  def serveOn(self, socket):
    if self.server==None:
      self.server = Server(self)
      thread.start_new_thread(
          self.server.listenTo, (socket,))
예제 #3
0
def get_address( host, prog, vers, prot, port=None ):
  if port:
    return (host,port)
  pmap = Client(host)
  port = pmap.getport( mapping( prog, vers, prot, 0 ) )
  del pmap
  return (host,port)
예제 #4
0
    def get_submission(self):
        dateTime = time.strftime('%Y-%m-%d %X', time.localtime(time.time()))
        request = GetSubmissionRequest(self._siteId, config.availableCompiler, config.availableValidator, dateTime)
        client = Client()
        response = client.send_request(request, 'Get Submission')
	# config.logger.debug('I am proxy.')
        return response
예제 #5
0
def ypad(request):
    identifier = request.matchdict["id"]
    client = Client(identifier)
    return request_context(request, client, {
            'tool': "ypad",
            'document': client.ypad()
    })
예제 #6
0
파일: event.py 프로젝트: sduverger/fpwm
def event_map_window(event):
    debug("map request: %r\n" % event.__dict__)
    wk = current_workspace()
    cl = wk.get_client(event.window)
    if cl is None:
        need_configure = False
        ignored, cls = ignored_client(event.window)
        if ignored:
            if cls == "QuakeConsole":
                runtime.quake_console = event.window
                quakeconsole_show()
                return
            else:
                gmx = runtime.con.core.GetGeometry(event.window).reply()
                if gmx.border_width == 0:
                    gmx.x -= 1
                    gmx.y -= 1
                    need_configure = True
                geo = Geometry(gmx.x, gmx.y, gmx.width, gmx.height, 1)
        else:
            geo = None

        cl = Client(runtime.con, event.window, event.parent, wk, geo, ignored)
        runtime.clients[cl.id] = cl
        wk.add(cl)

        if need_configure:
            cl.real_configure_notify()
            cl.stack_above()

    wk.map(cl)
    current_workspace().update_focus(cl)
예제 #7
0
def description(request):
    identifier = request.matchdict["id"]
    client = Client(identifier)
    return request_context(request, client, {
            'tool': "description",
            'document': client.description()
    })
예제 #8
0
파일: lobby.py 프로젝트: halcat0x15a/nsg
class Lobby(object):

    def __init__(self):
        identity = id(object())
        self.server = create_server(identity)
        self.client = Client(identity, host())
        self.title = Text("IP List", fontsize=160, color=BLACK)
        self.next = Text("Next", fontsize=160, color=BLACK)
        self.ip_list = []

    def _index_bounds(self, i):
        x, y, width, height = IP_BOUNDS
        return (x, y - i * 50, width, height)

    def draw(self):
        self.title.draw(TITLE_BOUNDS)
        self.next.draw(NEXT_BOUNDS)
        for i, ip in enumerate(self.ip_list):
            text = Text(str(ip), fontsize=80, color=BLACK)
            text.draw(self._index_bounds(i))
            del text

    def action(self, controller):
        if controller.button_a and scene.contains(NEXT_BOUNDS, controller.pos()):
            self.client.send(CHARACTER_SELECT)
            return HostCharacterSelect(self.server, self.client)
        self.ip_list = self.client.send(None) 
        return self
예제 #9
0
파일: PT.py 프로젝트: CityU-HAN/Theano-MPI
 def __init__(self, port, config, device):
     Client.__init__(self, port = port)
     PTBase.__init__(self, config = config, device = device)
     
     ###
     
     self.config['worker_id'] = self.worker_id
예제 #10
0
 def start(self):
     global client
     if (len(self.email) > 0 and len(self.password) > 0):
         self.email = str(self.email[0])
         self.password = str(base64.b64decode(self.password[0]))
         client = Client(self.email, self.password)
         response = client.login()
     
         if (response['result'] == 'ok'):
             startup = client.notify_startup()
             if (not startup):
                 print_message("Could not startup!")
             else:
                 print_message("Notified!")
     
     else:
         Mbox("Budibox", "Credentials undefined or incorrect. Please login again.") 
         
         # Create the QML user interface.
         view = QDeclarativeView()
         view.setSource(QUrl('qml/main.qml'))
         view.setWindowTitle("Budibox")
         view.setWindowIcon(QIcon("qml/budibox.jpg"))
         
         context = view.rootContext()
         context.setContextProperty("send_data",Receive_data())
         
         # Display the user interface and allow the user to interact with it.
         view.setGeometry(360, 360, 360, 360)
         view.setMaximumSize(360, 360)
         view.show()
         
         app.exec_()
def test_ping(mocker):
    "Test handling of PING message"
    mocker.patch.object(Client, '_openConnection', autospec=True)
    client_obj = Client(mocker.MagicMock())
    mocker.patch.object(client_obj, 'queueMessage', autospec=True)
    assert client_obj.handleMsg("E(123def,1516565652,Ping())")
    client_obj.queueMessage.assert_called_once_with("Pong(1516565652,0)")
예제 #12
0
class Sender(Thread):

    def __init__(self, config):
        Thread.__init__(self)
        self.config = config
        self.store = None
        self.start()
                
    def run(self):
        while True:
            while self.store == None:
                print("Sender:\t\tConectando a MongoDB")
                self.store = DB().connect(self.config['db_host'], self.config['db_name'], self.config['client_name'])
                time.sleep(1)      

            try:
                reg = self.store.find_one()
                if reg != None:
                    self.cli = Client(self.config['sender_host'], self.config['sender_port'])
                    self.cli.send(reg['data'])
                    print('Sender:\t\t['+self.config['client_name']+'] -> '+ reg['id'] + ' - ' + reg['data'])
                    self.store.remove(reg)
            except:
                print('Sender:\t\tError en MongoDB, reintentando...')
                time.sleep(1)
예제 #13
0
파일: humanclient.py 프로젝트: KDE/kajongg
 def remote_tableRemoved(self, tableid, message, *args):
     """update table list"""
     Client.remote_tableRemoved(self, tableid, message, *args)
     self.__updateTableList()
     if message:
         if self.name not in args or not message.endswith('has logged out'):
             logWarning(m18n(message, *args))
예제 #14
0
    def do_setclient(self):
        """Change default email client"""
        from client import Client
        client = Client(self.wf)
        app_path = self.args.query
        log.debug('Setting new client to : {}'.format(app_path))

        if app_path == 'DEFAULT':  # Reset to system default
            del self.wf.settings['default_app']
            msg = 'Email client set to System Default'
            log.info(msg)
            self.notify(msg)
            run_alfred('{} '.format(CONFIG_KEYWORD))
            return

        if not os.path.exists(app_path):
            msg = "Application doesn't exist : {}".format(app_path)
            self.notify(msg)
            raise ValueError(msg)

        client.default_app = app_path
        msg = 'Email client set to : {}'.format(client.default_app['name'])
        log.info(msg)
        self.notify(msg)
        run_alfred('{} '.format(CONFIG_KEYWORD))
예제 #15
0
파일: login.py 프로젝트: destan19/pychat
class TestDialog(QDialog,login_ui.Ui_Dialog):
	def __init__(self,parent=None):
		super(TestDialog,self).__init__(parent)
		firstui=login_ui.Ui_Dialog()
		self.setupUi(self)
		self.password.setEchoMode(QtGui.QLineEdit.Password)
		self.loginButton.clicked.connect(self.buttonPressed)
	def buttonPressed(self):
		
		username_text=self.username.text()
		password_text=self.password.text()
		username=unicode(username_text).encode("utf-8")
		password=unicode(password_text).encode("utf-8")
		if not username or not password:
			self.statusLabel.setText(u"没有输入用户名或密码")
			return
		self.client=Client(string.atoi(username),string.atoi(password))		
		self.client.connect_to_server("192.168.17.134",80)
		if self.client.con is None:
			self.statusLabel.setText(u"连接服务器失败")
			return
		res=self.client.login()
		print res
		if res == 1:
			self.statusLabel.setText("login success")
			self.accept();
			self.mDialog=MainDialog(self.client)
			self.mDialog.show()
		else:
			self.statusLabel.setText("username or password error")
예제 #16
0
def Main():
	
    signal.signal(signal.SIGINT, signalHandler)
    print "Client Running"
    host = sys.argv[1]
    client = Client(host)
    client.getHistory()
예제 #17
0
class OneClick(object):
    client = None

    def __init__(self):
        self.client = Client()

    def init_inscription(self, email, response_url, username):
        params = {"email": email, "username": username, "responseURL": response_url}
        d = Document(action="initInscription", params=params)
        response = self.client.request("initInscription", d.doc, {})
        return response

    def finish_inscription(self, token):
        params = {"token": token}
        d = Document(action="finishInscription", params=params)
        response = self.client.request("finishInscription", d.doc, {})
        return response

    def authorize(self, amount, tbk_user, username, buy_order):
        params = {"amount": amount, "tbkUser": tbk_user, "username": username, "buyOrder": buy_order}
        d = Document(action="Authorize", params=params)
        response = self.client.request("Authorize", d.doc, {})
        return response

    def reverse(self, buy_order):
        params = {"buyOrder": buy_order}
        d = Document(action="codeReverseOneClick", params=params)
        response = self.client.request("codeReverseOneClick", d.doc, {})
        return response

    def remove_user(self, tbk_user, username):
        params = {"tbkUser": tbk_user, "username": username}
        d = Document(action="removeUser", params=params)
        response = self.client.request("removeUser", d.doc, {})
        return response
def test_reply_pong(mocker):
    "Test handling of PONG message which requests a response"
    mocker.patch.object(Client, '_openConnection', autospec=True)
    client_obj = Client(mocker.MagicMock(), timeProvider=lambda: 1516566052)
    mocker.patch.object(client_obj, 'queueMessage', autospec=True)
    assert client_obj.handleMsg("E(123def,1516565852,Pong(1516565652,1))")
    client_obj.queueMessage.assert_called_once_with("Pong(1516565852,0)")
예제 #19
0
파일: bot.py 프로젝트: jkent/jkent-pybot
    def __init__(self, core, configfile):
        self.core = core

        self.configfile = configfile
        self.config = ConfigParser()
        self.config.read(configfile)
        
        host = self.config.get('base', 'host')
        port = self.config.getint('base', 'port')
        try:
            ssl = self.config.getboolean('base', 'ssl')
        except:
            ssl = False
        
        Client.__init__(self, (host, port), ssl)
        self.hooks = HookManager(self)
        self.plugins = PluginManager(self)

        self.hooks.install_owner(self)

        self.nick = None
        self.channels = {}
        superuser = self.config.get('base', 'superuser')
        self.allow_rules = {'*': {'ANY': 1}, superuser: {'ANY': 1000}}
        self.deny_rules = {}
        self._name = '_bot'

        autoload = self.config.get('base', 'autoload').split()
        for name in autoload:
            self.plugins.load(name)

        self.connect()
예제 #20
0
def links(request):
    identifier = request.matchdict["id"]
    client = Client(identifier)
    return request_context(request, client, {
            'tool': "links",
            'document': client.links()
    })
def main():
    parser = argparse.ArgumentParser(description='List your Captricity jobs.')
    parser.add_argument('--endpoint', required=True, help='the URL to the API definition resource, like https://shreddr.captricity.com/api/backbone/schema')
    parser.add_argument('--apitoken', required=True, help='the api token associated with your Captricity account')
    parser.add_argument('--job', required=True, type=int, help='the ID number for the job resource')
    parser.add_argument('image', type=file, nargs='+', help='image files which you would like to upload')

    args = parser.parse_args()

    # Creating the client will fetch the API descriptor and set up the api methods
    client = Client(api_token=args.apitoken, endpoint=args.endpoint)

    # Fetch the job to make sure that it exists and to get its display name
    job = client.read_job(args.job)
    print 'Uploading images to job "%s"' % job['name']

    # We need to group the instance images into instance sets. To do so, we need to find the page count of the form that is used for the job
    # We take advantage of the fact that the job's document resource metadata is included in the metadata for the job
    page_count = job['document']['sheet_count']

    # Once we know the page count, we will process the image list in batches, grouping them into image sets
    # Note that we assume the images were provided in the correct order
    for i in range(int(math.ceil(len(args.image) / float(page_count)))):
        # For each group of images in an image set, we create the instance set on the captricity server first.
        # We will also name the image sets by the first image in the set
        # Also store the new instance set so we know which one to post images to
        iset = client.create_instance_sets(job['id'], {'name': args.image[i].name})
        print 'Uploading image set', i
        # We will then upload each image to the image set in order until the image set is full
        for page_number, image in enumerate(args.image[i*page_count:(i*page_count)+page_count]):
            print '\t', image.name
            client.create_iset_instance(iset['id'], page_number, {'image' : image, 'image_name' : image.name})
예제 #22
0
def attachments(request):
    identifier = request.matchdict["id"]
    client = Client(identifier)
    return request_context(request, client, {
            'tool': "attachments",
            'document': client.attachments()
    })
예제 #23
0
def main():
    current_filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'providers')
    providers = [os.path.splitext(f)[0] for f in os.listdir(current_filepath) if os.path.isfile(os.path.join(current_filepath, f))]
    providers = list(set(providers))
    providers.remove('base')
    providers.remove('__init__')


    parser = argparse.ArgumentParser(description='Create, Update, Delete, List DNS entries')
    parser.add_argument("provider_name", help="specify the DNS provider to use", choices=providers)
    parser.add_argument("action", help="specify the action to take", default='list', choices=['create', 'list', 'update', 'delete'])
    parser.add_argument("domain", help="specify the domain, supports subdomains as well")
    parser.add_argument("type", help="specify the entry type", default='TXT', choices=['A', 'CNAME', 'MX', 'SOA', 'TXT'])

    parser.add_argument("--name", help="specify the record name")
    parser.add_argument("--content", help="specify the record content")
    parser.add_argument("--ttl", help="specify the record time-to-live")
    parser.add_argument("--priority", help="specify the record priority")
    parser.add_argument("--identifier", help="specify the record for update or delete actions")


    parser.add_argument("--auth-username", help="specify username used to authenticate to DNS provider")
    parser.add_argument("--auth-password", help="specify password used to authenticate to DNS provider")
    parser.add_argument("--auth-token", help="specify token used authenticate to DNS provider")
    parser.add_argument("--auth-otp-token", help="specify OTP/2FA token used authenticate to DNS provider")

    parsed_args = parser.parse_args()
    print parsed_args
    client = Client(parsed_args)
    client.execute()
예제 #24
0
def social(request):
    identifier = request.matchdict["id"]
    client = Client(identifier)
    return request_context(request, client, {
            'tool': "social",
            'document': client.social()
    })
예제 #25
0
 def __init__(self, name="user1"):
     self.name = name
     self.mx1 = Client.get("mx1")
     if len(RelayAgents) == 2:
         self.mx2 = Client.get("mx2")
     self.packets = {
         PacketTypes.DISCOVER: [],
         PacketTypes.OFFER: [],
         PacketTypes.REQUEST: [],
         PacketTypes.DECLINE: [],
         PacketTypes.ACK: [],
         PacketTypes.NAK: [],
         PacketTypes.RELEASE: [],
         PacketTypes.INFORM: [],
         PacketTypes.OTHER: [],
     }
     self._current_packet_send = None
     self._current_packet_receive = None
     self._last_xid = 0
     self._mx = None
     self.mac_addr_str = Users[self.name]["chaddr"]
     self.Agent_Circuit_ID = Users[self.name]["Agent_Circuit_ID"]
     self.Agent_Remote_ID = Users[self.name]["Agent_Remote_ID"]
     logging.info("Default User params %s", Users[self.name])
     logging.info('User created with name = "%s"', self.name)
예제 #26
0
    def __init__(self):
        Singleton.__init__(self)
        Client.__init__(self)

        self.prefs = PluginPrefs("jamendo")
        self.username = self.get_preference("username", "")
        self.password = self.get_preference("password", "")
예제 #27
0
    def test_same_socket_init_connect(self):
        print "testing connection to server..."
        client_aux = Client()
        client_aux.connect('localhost', 5000)

        self.assertEqual(self.client.host, client_aux.host)
        self.assertEqual(self.client.port, client_aux.port)
예제 #28
0
파일: server.py 프로젝트: DerekK19/pywss
    def start(self):

        self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.__socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #reuse the address as soon as possible
        self.__socket.setblocking(False)
        self.__socket.bind((self.location, self.port))
        self.__socket.listen(self.max_queued_connections)

        self.running = True

        print "Waiting for clients from ws://{0}:{1}".format(self.location, self.port)

        while self.running:
            try:
                client_socket, client_address = self.__socket.accept()

                client = Client(self.__next_client, client_socket, client_address, self.location, self.port)
                client.event_data_received += self.__on_data_received
                client.event_connected += self.__on_client_connected
                client.event_disconnected += self.__on_client_disconnected

                self.__next_client += 1

                client.start()

            except socket.error, msg:
                if not msg.errno in socket_errors:
                    raise
예제 #29
0
class OutlineLayout(Widget):
    """ A class that configures the default
	layout of the interface
	"""

    # Initialize the Client Class
    def __init__(self, **kwargs):
        self.cli = Client()
        super(OutlineLayout, self).__init__(**kwargs)

        # Drop down menu for future use

    def menu_drop_down(self):
        menudrop = MenuDropDown(pos=(0, Window.height - 100))
        menudrop.open
        menudrop.bind(on_select=lambda instance, x: setattr(self, "text", x))
        self.add_widget(menudrop)

        # Edit Menu for Future Use

    def edit_drop_down(self):
        editdrop = EditDropDown(pos=(60, Window.height - 100))
        editdrop.open
        editdrop.bind(on_select=lambda instance, x: setattr(self, "text", x))
        self.add_widget(editdrop)

        # Login Function

    def login(self, username, passwd):

        # Tell Client to Log in
        check = self.cli.login(username, passwd)

        # Login was successful
        if check == 1:

            # Display Popup
            close = Button(text="Close")
            popup = Popup(title="Login Successful", content=close, size_hint=(None, None), size=(150, 100))
            close.bind(on_press=popup.dismiss)
            popup.open()

            # Login Failed
        else:
            # Display Popup
            close = Button(text="Close")
            popup = Popup(title="Login Failed", content=close, size_hint=(None, None), size=(150, 100))
            close.bind(on_press=popup.dismiss)
            popup.open()

            # Play all songs in the playlist

    def play(self):
        self.cli.play_song()

        # Update the List of Songs

    def refresh(self):
        self.cli.update_song_list()
예제 #30
0
def reset_time_asleep():
	_results = Client(HOST,'testkey').get({'param':'find_nodes',
		'query':{'type':'action','action':'tablet-asleep'}})
	
	if not _results.has_key('results'):
		return -1
	
	Client(HOST,'testkey').delete_nodes(_results['results'])
예제 #31
0
 def set_data(self, data):
     self.client = Client(data['username'], data['server'], data['port'])
     self.username = data['username']
     self.client.listen(self.handle)
예제 #32
0
        #   Turn on warping: on mouseclick, move
        #   Insert a new object into the zone.
        #   Show a palette of objects in-world, sorted by last used or number of instances
        #   Yank the current object into the buffer
        #   Spawn the object in the buffer under currentpos

    def update(self):
        self.view.fitInView(self.scene.itemsBoundingRect(), Qt.KeepAspectRatio)


if __name__ == "__main__":
    # Create a Qt application
    app = QApplication(sys.argv)

    # make a client instance:
    client = Client()

    # Show form for logging in
    #     login_form = LoginForm()
    #     login_form.show()
    qtclient = QtClient()
    qtclient.open_login()

    # Show list of characters, and maybe a graphics view of them.
    charselect = None

    # Create a QGraphicsScene and View and show it.
    worldviewerdebug = None
    worldviewer = None

    # Enter Qt application main loop
예제 #33
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (C) 2020 Wilmer Perez / Arturo <*****@*****.**>
Hola wilmer cómo estás mira ya aprendí a como manejar el trabajo colaborativo
hola bro trabajo colaborativo

This file is part of clientUDP.

clientUDP is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

clientUDP is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Foobar.  If not, see <https://www.gnu.org/licenses/>.
"""
from client import Client

if __name__ == '__main__':
    exit(Client().start())
예제 #34
0
 def setUp(self):
     self.server = Server(host='0.0.0.0', port='6969')
     self.client = Client()
def main(rounds, config, step):
    msg_sizes = ["1 K", "32 K", "128 K", "512 K", "1 M", "2 M", "4 M", "8 M"]
    delay = 2
    uid = os.uname().nodename
    pid = str(os.getpid())
    home = pathlib.Path.home()
    res = str(home) + "/results/"
    scenario = step.split('/')[-1]
    outliers = 1
    if rounds - 2 * outliers < 1:
        print("Can't have more outliers than rounds!", file=sys.stderr)
        rounds = 2 * outliers + 1
    results = configparser.ConfigParser()
    c = Client(config)
    print(f"Running filesize test at {uid}")
    for msg_size in msg_sizes:
        msg = os.urandom(to_bytes(*msg_size.split()))
        res_file = res + scenario + '_' + msg_size + '_' + '_' + uid + '.' + pid + '.log'
        results['Meta'] = {}
        results['Meta']['start_time'] = str(time())
        results['Meta']['uid'] = str(uid)
        results['Meta']['test'] = 'file size'
        results['Meta']['rounds'] = str(rounds)
        results['Meta']['outliers'] = str(2 * outliers)
        results['Meta']['file_size'] = str(msg_size)
        results['Times_write'] = {}
        results['Times_read'] = {}
        results['Average_write'] = {}
        results['Average_read'] = {}
        for r in range(rounds):
            sleep(delay)
            # DO WORK HERE
            time_in_write = time()
            c.write(msg)
            time_out_write = time() - time_in_write
            time_in_read = time()
            c.read()
            time_out_read = time() - time_in_read
            results['Times_write'][f"run{r}"] = str(time_out_write)
            results['Times_read'][f"run{r}"] = str(time_out_read)
        # Writer
        times_write = sorted(
            [float(v) for v in results['Times_write'].values()])
        no_outliers_write = times_write[outliers:-outliers]
        results['Average_write']['average'] = str(sum(times_write) / (rounds))
        results['Average_write']['average_no_outliers'] = str(
            sum(no_outliers_write) / (rounds - 2 * outliers))
        # Reader
        times_read = sorted([float(v) for v in results['Times_read'].values()])
        no_outliers_read = times_read[outliers:-outliers]
        results['Average_read']['average'] = str(sum(times_read) / (rounds))
        results['Average_read']['average_no_outliers'] = str(
            sum(no_outliers_read) / (rounds - 2 * outliers))

        pathlib.Path(res).mkdir(exist_ok=True, parents=True)
        try:
            with open(res_file, 'a') as f:
                results.write(f)
            print(f"Write test done!")
        except OSError as e:
            print(f"Error writing to file {res_file}: {e}", file=sys.stderr)
예제 #36
0
#! /usr/bin/python

import sys
sys.path.append('../src')
from task import *
from runner import Runner
from project import Project
from client import Client
from runner import Runner
from commands import getoutput

example = Task(project=Project("example project"),
               client=Client("an_example_client"),
               task_name="this_is_just_a_test")

example.add_deployment([{
    CMD: "echo lalala",
    INFO: lambda x: x
}, {
    CMD: "ls",
    INFO: lambda x: x
}])

#example.set_check_for_new_commits( "cvs -nq up -dP | grep ^[UP]" )

example.add_subtask("teeesting", ["echo Should not write this!"])
example.add_subtask("just a CD", ["cd /tmp"])

local = True

if local:
예제 #37
0
파일: test.py 프로젝트: drmtmych/learn
def run(host, port):

    client1 = Client(host, port, timeout=5)
    client2 = Client(host, port, timeout=5)

    try:
        client1.connection.sendall(b"malformed command test\n")
        client1._read()
        client2.connection.sendall(b"malformed command test\n")
        client2._read()
    except ClientSocketError as err:
        print(f"Ошибка общения с сервером: {err.__class__}: {err}")
        sys.exit(1)
    except ClientProtocolError:
        pass
    else:
        print("Неверная команда, отправленная серверу, должна возвращать "
              "ошибку протокола")
        sys.exit(1)

    try:
        client1.put("k1", 0.25, timestamp=1)
        client2.put("k1", 2.156, timestamp=2)
        client1.put("k1", 0.35, timestamp=3)
        client2.put("k2", 30, timestamp=4)
        client1.put("k2", 40, timestamp=5)
        client1.put("k2", 40, timestamp=5)
    except Exception as err:
        print(f"Ошибка вызова client.put(...) {err.__class__}: {err}")
        sys.exit(1)

    expected_metrics = {
        "k1": [(1, 0.25), (2, 2.156), (3, 0.35)],
        "k2": [(4, 30.0), (5, 40.0)],
    }

    try:
        metrics = client1.get("*")
        if metrics != expected_metrics:
            print(f"client.get('*') вернул неверный результат. Ожидается:"
                  f" {expected_metrics}. Получено: {metrics}")
            sys.exit(1)
    except Exception as err:
        print(f"Ошибка вызова client.get('*') {err.__class__}: {err}")
        sys.exit(1)

    expected_metrics = {"k2": [(4, 30.0), (5, 40.0)]}

    try:
        metrics = client2.get("k2")
        if metrics != expected_metrics:
            print(f"client.get('k2') вернул неверный результат. Ожидается:"
                  f"{expected_metrics}. Получено: {metrics}")
            sys.exit(1)
    except Exception as err:
        print(f"Ошибка вызова client.get('k2') {err.__class__}: {err}")
        sys.exit(1)

    try:
        result = client1.get("k3")
        if result != {}:
            print(f"Ошибка вызова метода get с ключом, который еще не был"
                  f"добавлен. Ожидается: пустой словарь. Получено: {result}")
            sys.exit(1)
    except Exception as err:
        print(f"Ошибка вызова метода get с ключом, который еще не был"
              f"добавлен: {err.__class__} {err}")
        sys.exit(1)

    print("Похоже, что все верно! Попробуйте отправить решение на проверку.")
예제 #38
0
def init(ts, db):
    print("- Initialization of the example module is being run now:")
    # For example here you can open your database connection
    # Or, for example, you can subscribe to an action of the clients or channels
    Client.subscribe("exampleaction")
    Channel.subscribe("exampleaction")
예제 #39
0
import matplotlib.pyplot as plt

from client import Client
from old_versions.server import Server

FILE_NUM = int(1e2)
REQUEST_NUM = int(1e4)
client = Client(FILE_NUM, REQUEST_NUM)

print(FILE_NUM)
print(REQUEST_NUM)
print(client.file_pool_size)

plt.figure(figsize=(15, 8))
plt.xlabel("time")
plt.ylabel("file id")
plt.title("trace(yellow is requested)")
plt.imshow(client.trace.reshape((FILE_NUM, REQUEST_NUM)), aspect='auto')
plt.show()

little_server_a_hit_rate = []
little_server_b_hit_rate = []
big_server_hit_rate = []
cache_size_array = []
for cache_size in range(client.file_pool_size // 10, client.file_pool_size // 2, client.file_pool_size // 100):
    cache_size_array.append(cache_size / client.file_pool_size)
    little_server_a = Server(cache_size)
    little_server_b = Server(cache_size)
    big_server = Server(cache_size * 2)
    for request_file in client.make_requests():
        if request_file.fid & 0b10:
예제 #40
0
import socket
from client import Client

CLIENT_PORT = 22222

if __name__ == "__main__":
    client = Client(CLIENT_PORT)
예제 #41
0

if __name__ == '__main__':
    # create socket instance
    s = socket.socket()
    # local host name
    host = socket.gethostname()
    # set server/proxy port
    port = 23456
    log.info("""
        ___    ______ ______ ______   ______ __     ____ ______ _   __ ______
       /   |  / ____//_  __// ____/  / ____// /    /  _// ____// | / //_  __/
      / /| | / /      / /  / /_     / /    / /     / / / __/  /  |/ /  / /
     / ___ |/ /___   / /  / __/    / /___ / /___ _/ / / /___ / /|  /  / /
    /_/  |_|\____/  /_/  /_/       \____//_____//___//_____//_/ |_/  /_/
     """)
    s.connect((host, port))

    # client1 = Client(socket=s)
    # t1 = Thread(target=produce, args=(1, 200, 10, client1.data_buffer))
    # client1.produce_thread = t1
    # client1.start()
    # produce(1,200,10,client1.data_buffer)

    client1 = Client(socket=s)
    t1 = Thread(target=produce,
                args=(int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]),
                      client1.data_buffer))
    client1.produce_thread = t1
    client1.start()
예제 #42
0
    def run(self):
        print("Connected de :", clientAddress)
        print('run')
        '''
		DESCRIPTION:
			função criada para enviar e receber dados entre o cliente e servidor
		'''
        test = 1

        while (test != 0):

            dados = self.csocket.recv(1024).decode()
            message = dados.split('π∛')

            if message[0] == 'add_client':
                c = Client(message[1], message[2], message[3])
                if self.bank.get_client(message[3]) is False:
                    a = Account(message[4], c, message[5], message[6], '1000')
                    if self.bank.get_account(message[4]) is False:
                        self.bank.add_client(c)
                        self.bank.add_account(a)

                        print('Conta Criada Com Sucesso!')
                        self.csocket.send('True'.encode())
                    else:
                        print('Número de Conta Em Uso!')
                        self.csocket.send('False1'.encode())
                else:
                    print('CPF Em Uso!')
                    self.csocket.send('False2'.encode())

            elif message[0] == 'authenticated':  # Logar
                authenticated = self.bank.login(message[1], message[2])
                if authenticated is True:
                    print('Login Realizado Sucesso')
                    self.csocket.send('True'.encode())
                else:
                    print('Login Não Realizado!')
                    self.csocket.send('False'.encode())

            elif message[
                    0] == 'menuName':  # Mostrar o nome do usuario na tela de menu
                self.csocket.send(str(self.bank.nameAndSurname()).encode())

            elif message[
                    0] == 'menuBalance':  # Mostrar o saldo do usuario na tela de menu
                self.csocket.send(str(self.bank.menuBalance()).encode())

            elif message[0] == 'withdraw':  # Sacar
                self.sinc.acquire()
                account = self.bank.withdraw(message[1])
                if account == 'True':
                    self.csocket.send('True'.encode())
                    self.sinc.release()
                elif account == 'Negativo':
                    self.csocket.send('Negativo'.encode())
                    self.sinc.release()
                elif account == 'Indisponível':
                    self.csocket.send('Indisponível'.encode())
                    self.sinc.release()

            elif message[0] == 'deposit':  # Depositar
                self.sinc.acquire()
                account = self.bank.deposit(message[1])
                if account == 'True':
                    self.csocket.send('True'.encode())
                    self.sinc.release()
                elif account == 'Negativo':
                    self.csocket.send('Negativo'.encode())
                    self.sinc.release()

            elif message[0] == 'transfer':  # Transferir
                self.sinc.acquire()
                account = self.bank.transfer(message[1], message[2])
                if account == 'True':
                    self.csocket.send('True'.encode())
                    self.sinc.release()
                elif account == 'False':
                    self.csocket.send('False'.encode())
                    self.sinc.release()
                elif account == 'Negativo':
                    self.csocket.send('Negativo'.encode())
                    self.sinc.release()
                elif account == 'Inválido':
                    self.csocket.send('Inválido'.encode())
                    self.sinc.release()

            elif message[0] == 'extract':  # Extrato
                # account = self.bank.get_account_2()
                # extracts = account.extract.display_extract()
                # print('Tirou Extrato!')
                self.csocket.send(''.encode())

            elif message[0] == 'backLogin':
                self.bank.sairApp()
                self.csocket.send('True'.encode())
예제 #43
0
from client import Client
import time
from threading import Thread

c1 = Client("Client1")
c2 = Client("Client2")


def update_messages():
    """
    updates the local list of messages
    :return: None
    """
    msgs = []
    run = True
    while run:
        time.sleep(0.1)  # update every 1/10 of a second
        new_messages = c1.get_messages()  # get any new messages from client
        msgs.extend(new_messages)  # add to local list of messages

        for msg in new_messages:  # display new messages
            print(msg)

            if msg == "{quit}":
                run = False
                break


Thread(target=update_messages).start()

c1.send_message("Hello :)")
예제 #44
0
 def setUpClass(cls):
     cls.client = Client("127.0.0.1", 10000, timeout=None)
예제 #45
0
class Dialog(tk.Frame):
    def __init__(self, parent, controller):
        self.started = False
        self.id_to_delete_on_start = []
        self.ready = False
        self.his_ready = False
        self.my_turn = False
        self.my_hash = ""
        self.my_score = 0
        self.her_score = 0
        self.my_boats = []
        self.her_hash = ""
        self.join_time = datetime.datetime.now()
        tk.Frame.__init__(self, parent, bg=color_sombre)
        self.controller = controller
        self.battleship_grid_tk = tk.Canvas(self,
                                            width=670,
                                            height=440,
                                            bd=0,
                                            highlightthickness=0,
                                            bg="#010101",
                                            relief="flat")
        self.battleship_grid_tk.grid(column=0, row=1, sticky="NSEW")
        self.draft = tk.Canvas(self, width=670, height=440)
        self.draft.delete(tk.ALL)
        self.create_grid()
        btn_ValidGame = tk.Button(self,
                                  text="Valider",
                                  activebackground=color_clair,
                                  activeforeground=color_button_battleship,
                                  bd=0,
                                  overrelief='flat',
                                  highlightcolor=color_button_battleship,
                                  relief="flat",
                                  command=lambda: self.launch_game())
        btn_ValidGame.grid(column=0, row=1, sticky="SE")
        self.st = scrolledtext.ScrolledText(self,
                                            state='disabled',
                                            bg=color_sombre,
                                            fg=color_text_hightlight,
                                            font='NotoSansMono')
        # action_man_bold = font.load('Action Man', bold=True)
        self.st.grid(column=1, row=1, sticky='NSEW')
        self.msg_entry = tk.Entry(self,
                                  bg=color_clair,
                                  fg=color_text_clair,
                                  relief="flat",
                                  insertbackground=color_text_clair)
        self.msg_entry.grid(column=1, row=2, sticky="W", ipadx=247)

        btn_column = tk.Button(
            self,
            text="Send ->",
            bg=color_clair,
            fg=color_text_clair,
            activebackground=color_clair,
            activeforeground=color_text_clair,
            bd=0,
            overrelief='flat',
            highlightcolor=color_text_hightlight,
            relief="flat",
            command=lambda: self.send_msg({
                'msg': self.msg_entry.get(),
            }))
        btn_column.grid(column=1, row=2, sticky="E")

        self.st.tag_config('sys', foreground='orange')
        self.st.tag_config('you',
                           foreground='#fff',
                           background='#16a085',
                           justify="right")
        self.st.tag_config('msg', foreground='#fff', background='#34495e')
        self.create_boat()
        self.create_page("En attente d'un autre joueur")

    def findXCenter(self, canvas, item):
        coords = canvas.bbox(item)
        xOffset = (500 / 2) - ((coords[2] - coords[0]) / 2)
        return xOffset

    def create_page(self, text):
        self.id_to_delete_on_start.append(
            self.battleship_grid_tk.create_rectangle(0,
                                                     0,
                                                     670,
                                                     440,
                                                     fill="#feca57",
                                                     stipple="gray50"))
        id = self.battleship_grid_tk.create_text(320,
                                                 200,
                                                 fill="#341f97",
                                                 font="Noto 30",
                                                 text=text)
        self.id_to_delete_on_start.append(id)
        xOffset = self.findXCenter(self.battleship_grid_tk, id)
        self.battleship_grid_tk.move(id, xOffset, 0)

    def delete_start_page(self):
        for i in self.id_to_delete_on_start:
            self.battleship_grid_tk.delete(i)

    def create_boat(self):
        self.boats = []
        for index, size in enumerate(BOAT):
            tags = "boat{}".format(index + 1)
            total_size = (size * 40)
            total_space = (index * 40)
            total_space += 5 * (index + 1)
            self.boats.append([False, (0, 0, 0, 0), tags])
            self.battleship_grid_tk.create_rectangle(430 + total_space,
                                                     20,
                                                     430 + 40 + total_space,
                                                     20 + total_size,
                                                     fill="#95a5a6",
                                                     outline='#7f8c8d',
                                                     tags=tags)
            self.battleship_grid_tk.tag_bind(
                tags,
                "<ButtonRelease-1>",
                lambda e, tags=tags: self.release_check(e.x, e.y, e, tags, 0))
            self.battleship_grid_tk.tag_bind(
                tags,
                "<Button1-Motion>",
                lambda e, tags=tags: self.move_selected(e.x, e.y, e, tags, 0))
            self.battleship_grid_tk.tag_bind(tags, "<Button-2>",
                                             lambda e: print("press"))
            self.battleship_grid_tk.tag_bind(
                tags, "<Button-3>", lambda e, tags=tags: self.rotate(tags))

    def determine_boat_from_key(self, key):
        letter, number = key[:4], key[4:]
        return letter, int(number)

    def determine_boat_coord_init(self, index):
        index = index - 1
        size = BOAT[index]
        total_size = (size * 40)
        total_space = (index * 40)
        total_space += 5 * (index + 1)
        return 430 + total_space, 20, 430 + 40 + total_space, 20 + total_size

    def rotate(self, tags, to_rinit=False):
        letter, number = self.determine_boat_from_key(tags)
        number = number - 1
        coord = self.battleship_grid_tk.coords(tags)
        if to_rinit:
            if self.boats[number][0]:
                self.boats[number][0] = False
                self.battleship_grid_tk.coords(tags, *self.boats[number][1])
        else:
            if not self.boats[number][0]:
                self.boats[number][1] = coord
                self.boats[number][0] = True
                self.battleship_grid_tk.coords(
                    tags, coord[0], coord[1],
                    coord[0] - abs(coord[1] - coord[3]),
                    coord[1] + abs(coord[2] - coord[0]))
            else:
                # print(self.boats[number][1])
                self.boats[number][0] = False
                self.battleship_grid_tk.coords(tags, *self.boats[number][1])

    def create_grid(self):
        self.battleship_grid = []
        for index_x, letter in enumerate(COLUNM_REF):
            self.battleship_grid_tk.create_text((index_x * 40) + 40,
                                                8,
                                                fill="#37f122",
                                                text=letter.capitalize())
            self.battleship_grid_tk.create_text(8, (index_x * 40) + 40,
                                                fill="#37f122",
                                                text=index_x)
            line = []
            for index_y, number in enumerate(range(0, 10)):
                key = "{}{}".format(letter, number)
                case = {
                    'name':
                    key,
                    'type':
                    None,
                    'canva':
                    self.battleship_grid_tk.create_rectangle(
                        (index_x * 40) + 19, (index_y * 40) + 19,
                        (index_x * 40) + 40 + 19, (index_y * 40) + 40 + 19,
                        fill="#010101",
                        outline='#37f122',
                        tags=key)
                }
                self.draft.create_rectangle(
                    (index_x * 40) + 19, (index_y * 40) + 19,
                    (index_x * 40) + 40 + 19, (index_y * 40) + 40 + 19,
                    fill="#010101",
                    outline='#37f122',
                    tags=key)
                line.append(case)
                self.battleship_grid_tk.tag_bind(
                    key,
                    "<Button-1>",
                    lambda event, key=key: self.clicked(key))
            self.battleship_grid.append(line)

    def release_check(self, x1, y1, key, tags, min_pixels=5):
        clic = x1, y1
        letter, number = self.determine_boat_from_key(tags)
        canva = self.battleship_grid_tk.coords(tags)
        pos = self.determine_boat_coord_init(number)
        x = pos[0] - canva[0]
        y = pos[1] - canva[1]
        if canva[2] > 500 or canva[3] > 419:
            self.battleship_grid_tk.move(tags, x, y)
            self.rotate(tags, to_rinit=True)

    def move_selected(self, x1, y1, key, tags, min_pixels=5):
        # print(key)
        clic = x1, y1
        canva = self.battleship_grid_tk.coords(tags)
        nearest = self.draft.find_closest(*clic)
        # self.battleship_grid_tk.itemconfig("bateau1", fill='red')
        if not "boat" in nearest:
            nearest_coord = self.draft.coords(nearest)
            # print(nearest_coord)
            # print(canva)
            x = nearest_coord[0] - canva[0]
            y = nearest_coord[1] - canva[1]
            if nearest_coord[0] > 18 and nearest_coord[
                    1] > 18 and nearest_coord[0] < 400 and nearest_coord[
                        1] < 400:
                if canva[0] < 700 and canva[1] < 400 and canva[
                        2] < 700 and canva[3] <= 419:
                    self.battleship_grid_tk.move(tags, x, y)
                # if canva[3] > 419:

    def launch_game(self):
        collision = self.check_colision()
        if collision:
            print(collision)
        else:
            for boat in self.boats:
                self.battleship_grid_tk.itemconfig(boat[2],
                                                   stipple="gray25",
                                                   state='disabled')
                self.my_boats.extend(self.determine_keys_from_boat(boat[2]))
            data = {
                'type': 'game',
                'hash': self.my_hash.hexdigest(),
                'data': {
                    'ready': True,
                },
            }
            self.ready = True
            self.client.send(data)
            if self.my_turn and self.his_ready:
                self.show_message("C'est a vous de commencer !", "sys")
            else:
                self.show_message("C'est au joueur d'en face de joué !", "sys")

    def check_colision(self):
        collision = False
        for boat in self.boats:
            if collision:
                return collision
            for boat_check in self.boats:
                if collision:
                    return collision
                if boat[2] != boat_check[2]:
                    coord_boat = self.battleship_grid_tk.coords(boat[2])
                    coord_boat_check = self.battleship_grid_tk.coords(
                        boat_check[2])
                    if int(coord_boat_check[0]) > int(coord_boat[2]) or\
                        int(coord_boat_check[2]) < int(coord_boat[0]) or\
                        int(coord_boat_check[1]) > int(coord_boat[3]) or\
                       int(coord_boat_check[3]) < int(coord_boat[1]):
                        # self.show_message("PAS DE COLLISION", "sys")
                        if coord_boat[0] < 18 or coord_boat[
                                1] < 18 or coord_boat[2] > 420 or coord_boat[
                                    3] > 420:
                            collision = True
                            self.show_message(
                                "Vos bateaux doivent être dans la grille",
                                "sys")
                            return collision

                    else:
                        collision = True
                        self.show_message(
                            "Vos bateaux ne doivent pas se toucher", "sys")
                        return collision
        return collision

    def determine_pos_from_key(self, key):
        letter, number = key[:1], key[1:]
        column = int(COLUNM_REF.index(letter))
        line = int(number)
        val = self.battleship_grid[column][line]
        column += 1
        line += 1
        return column, line, val['canva']

    def determine_keys_from_boat(self, tags):
        list_boats_keys = []
        coords = self.battleship_grid_tk.coords(tags)
        new_coords = (int((coords[0] - 19) / 40), int(
            (coords[1] - 19) / 40), int((coords[2] - 19) / 40 - 1),
                      int((coords[3] - 19) / 40 - 1))
        if new_coords[0] == new_coords[2]:
            for i in range(new_coords[1], new_coords[3] + 1):
                list_boats_keys.append('{}{}'.format(COLUNM_REF[new_coords[0]],
                                                     i))
        else:
            for a in range(new_coords[0], new_coords[2] + 1):
                if new_coords[1] == new_coords[3]:
                    list_boats_keys.append('{}{}'.format(
                        COLUNM_REF[a], new_coords[1]))
        return list_boats_keys

    def clicked(self, key):
        if self.ready and self.his_ready and self.started and self.my_turn:
            column, line, canva = self.determine_pos_from_key(key)
            self.battleship_grid_tk.itemconfig(canva,
                                               fill='black',
                                               state='disabled')
            self.battleship_grid_tk.create_line(column * 40 - 20,
                                                line * 40 - 20,
                                                column * 40 + 20,
                                                line * 40 + 20,
                                                fill='red')
            self.battleship_grid_tk.create_line(column * 40 + 20,
                                                line * 40 - 20,
                                                column * 40 - 20,
                                                line * 40 + 20,
                                                fill='red')
            data = {
                'type': 'game',
                'hash': self.my_hash.hexdigest(),
                'data': {
                    'key': key,
                },
            }
            self.client.send(data)
            print(key)

    def exploded(self, key):
        if self.ready and self.his_ready and self.started:
            column, line, canva = self.determine_pos_from_key(key)
            self.battleship_grid_tk.itemconfig(canva, fill='blue')
            self.battleship_grid_tk.create_line(column * 40 - 20,
                                                line * 40 - 20,
                                                column * 40 + 20,
                                                line * 40 + 20,
                                                fill='green')
            self.battleship_grid_tk.create_line(column * 40 + 20,
                                                line * 40 - 20,
                                                column * 40 - 20,
                                                line * 40 + 20,
                                                fill='green')

    def touched(self, key):
        if self.ready and self.his_ready and self.started:
            column, line, canva = self.determine_pos_from_key(key)
            self.battleship_grid_tk.itemconfig(canva, fill='#6F1E51')
            self.battleship_grid_tk.create_line(column * 40 - 20,
                                                line * 40 - 20,
                                                column * 40 + 20,
                                                line * 40 + 20,
                                                fill='green')
            self.battleship_grid_tk.create_line(column * 40 + 20,
                                                line * 40 - 20,
                                                column * 40 - 20,
                                                line * 40 + 20,
                                                fill='green')

    def set_data(self, data):
        self.client = Client(data['username'], data['server'], data['port'])
        self.username = data['username']
        self.client.listen(self.handle)

    def send_msg(self, data):
        to_be_send = {
            'type': 'message',
            'hash': self.my_hash.hexdigest(),
            'data': {
                'message': data['msg'],
            },
        }
        if data['msg'] == '':
            self.show_message("Vous ne pouvez pas envoyer de message vide",
                              "sys")
        else:
            self.client.send(to_be_send)

    def show_message(self, msg, msg_type):
        msg = emoji.emojize(msg)
        msg = with_surrogates(msg)

        def append():
            self.st.configure(state='normal')
            self.st.insert(tk.END, msg + '\n', msg_type)
            self.st.configure(state='disabled')
            self.st.yview(tk.END)

        self.st.after(0, append)

    def handle(self, msg):
        msg_parsed = json.loads(msg)
        print(msg_parsed)
        if msg_parsed['username'] == self.username:
            username = "******"
            msg_type = "you"
        else:
            username = msg_parsed['username']
            msg_type = "msg"
        if 'type' in msg_parsed['message']:
            if msg_parsed['message']['type'] == "message" and (
                    msg_parsed['message']['hash'] == self.my_hash.hexdigest()
                    or msg_parsed['message']['hash']
                    == self.her_hash.hexdigest()):
                if msg_parsed['username'] == self.username:
                    message = "{} < {}".format(
                        msg_parsed['message']['data']['message'], username)
                else:
                    message = "{} > {}".format(
                        username, msg_parsed['message']['data']['message'])
                self.show_message(message, msg_type)
            elif msg_parsed['message']['type'] == "join":
                join_payload = {
                    'type': 'join',
                    'data': {
                        'election': self.client.election,
                    },
                }
                if (self.join_time -
                        datetime.datetime.now()).total_seconds() > 10:
                    self.join_time = datetime.datetime.now()
                    self.client.send(join_payload)
                if msg_parsed['message']['data'][
                        'election'] > self.client.election and msg_parsed[
                            'username'] != self.username and self.started == False:
                    self.started = True
                    self.my_hash = hashlib.md5(
                        (str(self.client.election) + self.username).encode())
                    self.her_hash = hashlib.md5(
                        (str(msg_parsed['message']['data']['election']) +
                         msg_parsed['username']).encode())
                    print(self.my_hash.hexdigest())
                    print(self.her_hash.hexdigest())
                    print("IL COMMENCE")
                    self.delete_start_page()
                    self.client.send(join_payload)
                elif msg_parsed[
                        'username'] != self.username and self.started == False:
                    self.started = True
                    self.my_hash = hashlib.md5(
                        (str(self.client.election) + self.username).encode())
                    self.her_hash = hashlib.md5(
                        (str(msg_parsed['message']['data']['election']) +
                         msg_parsed['username']).encode())
                    print(self.my_hash.hexdigest())
                    print(self.her_hash.hexdigest())
                    self.my_turn = True
                    print("TU COMMENCE")
                    self.delete_start_page()
                    self.client.send(join_payload)
            elif msg_parsed['message']['type'] == "game" and msg_parsed[
                    'message']['hash'] == self.her_hash.hexdigest():
                if "ready" in msg_parsed['message']['data']:
                    self.show_message("Le joueur d'en face est prêt !", "sys")
                    if self.my_turn and self.ready:
                        self.show_message("C'est à vous de commencer !", "sys")
                    self.his_ready = True
                if "result" in msg_parsed['message']['data']:
                    if msg_parsed['message']['data']['result']:
                        self.my_turn = True
                        self.show_message("C'est encore à vous", "sys")
                        self.my_score += 1
                        self.touched(
                            msg_parsed['message']['data']['result_key'])
                    else:
                        self.my_turn = False
                    if self.my_score == 17:
                        self.create_page("Vous avez gagné")

                        win = {
                            'type': 'game',
                            'hash': self.my_hash.hexdigest(),
                            'data': {
                                'winner': self.my_hash.hexdigest(),
                                'looser': self.her_hash.hexdigest(),
                            },
                        }
                        self.client.send(win)

                if "key" in msg_parsed['message']['data']:
                    if msg_parsed['message']['data']['key'] in self.my_boats:
                        touched = {
                            'type': 'game',
                            'hash': self.my_hash.hexdigest(),
                            'data': {
                                'result': True,
                                'result_key':
                                msg_parsed['message']['data']['key']
                            }
                        }
                        self.exploded(msg_parsed['message']['data']['key'])
                        self.client.send(touched)
                        self.her_score += 1
                        self.my_turn = False
                        if self.her_score == 17:
                            self.create_page("Vous avez perdu")

                            # loose = {
                            #     'type': 'win',
                            #     'hash': self.my_hash.hexdigest(),
                            #     'data':
                            #     {
                            #         'winner': self.her_hash.hexdigest(),
                            #         'looser': self.my_hash.hexdigest()
                            #     },
                            # }
                            # self.client.send(loose)
                    else:
                        missed = {
                            'type': 'game',
                            'hash': self.my_hash.hexdigest(),
                            'data': {
                                'result': False,
                            },
                        }
                        self.show_message("C'est à vous", "sys")
                        self.client.send(missed)
                        self.my_turn = True
                    print(msg_parsed['message']['data']['key'])
            else:
                print(msg_parsed['message'])
                        default=0)
    parser.add_argument('--include_physical_measurements',
                        action='store_true',
                        help='True if physical measurements should be created')
    parser.add_argument('--include_biobank_orders',
                        action='store_true',
                        help='True if biobank orders should be created')
    parser.add_argument(
        '--hpo',
        help=
        'The HPO name to assign participants to; defaults to random choice.')
    parser.add_argument('--create_biobank_samples',
                        action='store_true',
                        help='True if biobank samples should be created')
    parser.add_argument(
        '--create_samples_from_file',
        help=
        'Creates PM&B for existing participants from a csv file; requires path'
        ' to file. File is expected to contain a single column of ID"s with a '
        'leading env. identifier. i.e. P')
    rdr_client = Client(parser=parser)
    if rdr_client.args.num_participants == 0 and not rdr_client.args.create_biobank_samples and not\
      rdr_client.args.create_samples_from_file:
        parser.error(
            '--num_participants must be nonzero unless --create_biobank_samples is true.'
        )
    if rdr_client.args.create_samples_from_file:
        generate_data_from_file(rdr_client, rdr_client.args)
    else:
        generate_fake_data(rdr_client, rdr_client.args)
예제 #47
0
class GameGUI(tk.Frame):
    def __init__(self, master):
        super().__init__(master)
        self.master = master
        self.mainFrame = tk.Frame(self)
        self.client = Client(self.onPeerRequestJoinGame, self.getPeersMove)
        self.btnGrid = [[None, None, None], [None, None, None],
                        [None, None, None]]
        self.pack()
        self.mainFrame.pack()
        self.createMainScreen()

    def createMainScreen(self):
        """ Creates the main screen when the GUI is launched allowing the user
        to connect to a game server with an IP Address and Port of their choice.
        """
        userInputFrame = tk.Frame(self.mainFrame)
        serverIpLabel = tk.Label(userInputFrame, text='Server IP:')
        serverIpEntry = tk.Entry(userInputFrame)
        serverPortLabel = tk.Label(userInputFrame, text='Server Port:')
        serverPortEntry = tk.Entry(userInputFrame)
        nicknameLabel = tk.Label(userInputFrame, text='Nickname:')
        nicknameEntry = tk.Entry(userInputFrame)
        p2pPortLabel = tk.Label(userInputFrame, text='P2P Port:')
        p2pPortEntry = tk.Entry(userInputFrame)
        userInputFrame.pack()
        serverIpLabel.grid(row=0, column=0)
        serverIpEntry.grid(row=0, column=1)
        serverPortLabel.grid(row=1, column=0)
        serverPortEntry.grid(row=1, column=1)
        nicknameLabel.grid(row=2, column=0)
        nicknameEntry.grid(row=2, column=1)
        p2pPortLabel.grid(row=3, column=0)
        p2pPortEntry.grid(row=3, column=1)

        buttonFrame = tk.Frame(self.mainFrame)
        connectButton = tk.Button(buttonFrame, text='Connect')
        quitButton = tk.Button(buttonFrame, text='QUIT', command=self.onQuit)
        buttonFrame.pack()
        connectButton.pack()
        quitButton.pack()

        errorMsgFrame = tk.Frame(self.mainFrame)
        errorMsgLabel = tk.Label(errorMsgFrame)
        errorMsgFrame.pack()
        errorMsgLabel.pack()

        def onConnectButtonPressed():
            def onSuccess():
                self.createGameRoomScreen()

            def onError(errorMsg=''):
                errorMsgLabel['text'] = errorMsg

            serverIP = serverIpEntry.get()
            serverPort = serverPortEntry.get()
            nickname = nicknameEntry.get()
            p2pPort = p2pPortEntry.get()

            if serverIP and serverPort and nicknameEntry and p2pPort:
                serverPort = int(serverPort)
                p2pPort = int(p2pPort)
                self.connectToGameServer(serverIP, serverPort, nickname,
                                         p2pPort, onSuccess, onError)
            else:
                onError('All fields are required')

        connectButton['command'] = onConnectButtonPressed

    def createGameRoomScreen(self):
        """ Creates game room screen user sees once they have successfully
        connected to the game server. This screen will query the server for a
        list of available games and list them. The user will have the ability
        to join one of the available games or play agains the game server.
        """
        # Clear screen and deallocate all previous widgets
        if self.mainFrame is not None:
            self.mainFrame.destroy()
            self.mainFrame = tk.Frame(self)
            self.mainFrame.pack()

        welcomeBanner = tk.Frame(self.mainFrame)
        welcomeBannerMsg = tk.Label(welcomeBanner,
                                    text='Welcome {}'.format(
                                        self.client.nickname))
        welcomeBanner.pack()
        welcomeBannerMsg.pack()

        menuBar = tk.Frame(self.mainFrame)
        playComputerBtn = tk.Button(menuBar, text='Play computer')
        quitBtn = tk.Button(menuBar, text='Quit', command=self.onQuit)
        menuBar.pack()
        playComputerBtn.grid(row=0, column=0)
        quitBtn.grid(row=0, column=1)

        errorMsgFrame = tk.Frame(self.mainFrame)
        errorMsgLabel = tk.Label(errorMsgFrame)
        errorMsgFrame.pack()
        errorMsgLabel.pack()

        def onPlayServerBtnPressed():
            def onError(errorMsg):
                errorMsgLabel['text'] = errorMsg

            self.playAgainstServer(onError)

        playComputerBtn['command'] = onPlayServerBtnPressed

        self.availableGamesFrame = tk.Frame(self.mainFrame)
        availableGamesLable = tk.Label(self.availableGamesFrame,
                                       text='Available Games:')
        self.availableGamesFrame.pack()
        availableGamesLable.grid(row=0, column=0)

        self.updateListOfAvailableGames()

    def connectToGameServer(self, ipAddr: str, port: int, nickname: str,
                            p2pPort: int, onSuccess: Callable,
                            onError: Callable[[str], None]):
        """ Connect to game server.

        Arguments:
        ----------
        ipAddr    - IP Address of game server
        port      - Port number that game server is listening on.
        nickname  - Unique name of user on the game server
        p2pPort   - The port that the user will uses for P2P connection.
        onSuccess - Callback to be called if connection is successfull.
        onError   - Callback to be called if connection fails.
        """
        try:
            self.client.connectToServer(ipAddr, port)
            self.client.joinServer(nickname, p2pPort)
        except Exception as error:
            onError(str(error))
        else:
            onSuccess()

    def getListOfAvailableGames(self, onSuccess: Callable[[List], None],
                                onError: Callable[[str], None]):
        try:
            availableGames = self.client.getListOfAvailableGames()
        except Exception as error:
            onError(str(error))
        else:
            onSuccess(availableGames)

    def updateListOfAvailableGames(self):
        def onError(errorMsg):
            error = tk.Label(self.mainFrame, text=errorMsg)
            error.pack()

        def onJoinGamePressed(opponentName, opponentIP, opponentPort):
            self.playAgainstPeer(opponentName, opponentIP, opponentPort,
                                 onError)

        def onSuccess(availableGames):
            if self.availableGamesFrame:
                self.availableGamesFrame.destroy()
                self.availableGamesFrame = tk.Frame(self.mainFrame)
                availableGamesLable = tk.Label(self.availableGamesFrame,
                                               text='Available Games:')
                self.availableGamesFrame.pack()
                availableGamesLable.grid(row=0, column=0)

            for index, game in enumerate(availableGames):
                opponentName = tk.Label(self.availableGamesFrame,
                                        text=game['nickname'])
                joinGameBtn = tk.Button(self.availableGamesFrame, text='Join')
                opponentName.grid(row=index + 1, column=0)
                joinGameBtn.grid(row=index + 1, column=1)
                joinGameBtn['command'] = partial(onJoinGamePressed,
                                                 game['nickname'], game['ip'],
                                                 game['port'])

        self.getListOfAvailableGames(onSuccess, onError)
        self.updateJob = self.after(5000, self.updateListOfAvailableGames)

    def playAgainstServer(self, onError):
        if self.updateJob is not None:
            self.after_cancel(self.updateJob)
        try:
            self.client.joinGame('server')
        except Exception as error:
            onError(str(error))
        else:
            self.opponent = 'server'
            self.createTicTacToeScreen()
            if self.client.ticTacToe.getTurnPlayer() == 'server':
                self.getServerMove()

    def playAgainstPeer(self, name, ip, port, onError):
        if self.updateJob is not None:
            self.after_cancel(self.updateJob)
        try:
            self.client.joinGame(name, ip, port)
        except Exception as error:
            onError(str(error))
        else:
            self.opponent = name
            self.createTicTacToeScreen()

    def onPeerRequestJoinGame(self):
        if self.updateJob is not None:
            self.after_cancel(self.updateJob)
        self.opponent = self.client.opponentName
        self.createTicTacToeScreen()

    def createTicTacToeScreen(self):
        # Clear screen and deallocate all previous widgets
        if self.mainFrame is not None:
            self.mainFrame.destroy()
            self.mainFrame = tk.Frame(self)
            self.mainFrame.pack()

        buttonFrame = tk.Frame(self.mainFrame)
        returnBtn = tk.Button(buttonFrame,
                              text='Return to Game Room',
                              command=self.createGameRoomScreen)
        quitButton = tk.Button(buttonFrame, text='QUIT', command=self.onQuit)
        buttonFrame.pack()
        returnBtn.pack()
        quitButton.pack()

        ticTacToeFrame = tk.Frame(self.mainFrame)
        ticTacToeFrame.pack()

        self.infoLabel = tk.Label(self.mainFrame)
        self.infoLabel['text'] = self.client.ticTacToe.getTurnPlayer(
        ) + "'s turn"
        self.infoLabel.pack()

        def onPositionPressed(row, col):
            def onSuccess():
                currentPlayer = self.client.ticTacToe.getTurnPlayer()
                self.infoLabel['text'] = currentPlayer + "'s turn"
                self.btnGrid[row][col]['text'] = 'X'

            def onError(errorMsg):
                self.infoLabel['text'] = errorMsg

            self.makeMove(self.opponent, (row, col), onSuccess, onError)

            if self.client.ticTacToe.checkWinCondition():
                self.onHasWinner(self.client.ticTacToe.checkWinCondition(),
                                 self.infoLabel)
            elif not self.client.ticTacToe.hasPossibleMoves():
                self.onStaleMate(self.infoLabel)
            else:
                if self.opponent == 'server':
                    self.getServerMove()
                    self.infoLabel[
                        'text'] = self.client.ticTacToe.getTurnPlayer(
                        ) + "'s turn"
                    if self.client.ticTacToe.checkWinCondition():
                        self.onHasWinner(
                            self.client.ticTacToe.checkWinCondition(),
                            self.infoLabel)
                    elif not self.client.ticTacToe.hasPossibleMoves():
                        self.onStaleMate(self.infoLabel)

        for row in range(0, 3):
            for col in range(0, 3):
                btn = tk.Button(ticTacToeFrame,
                                font='Times 20 bold',
                                bg='white',
                                fg='black',
                                height=2,
                                width=4)
                btn['command'] = partial(onPositionPressed, row, col)
                btn.grid(row=row, column=col)
                self.btnGrid[row][col] = btn

    def makeMove(self, opponent, move, onSuccess, onError):
        try:
            self.client.makeMove(self.opponent, move)
        except Exception as error:
            onError(str(error))
        else:
            onSuccess()

    def getServerMove(self):
        row, col = self.client.getMove('server')
        self.btnGrid[row][col]['text'] = 'O'

    def getPeersMove(self, move):
        row, col = move
        self.btnGrid[row][col]['text'] = 'O'
        if self.client.ticTacToe.checkWinCondition():
            self.onHasWinner(self.client.ticTacToe.checkWinCondition(),
                             self.infoLabel)
        elif not self.client.ticTacToe.hasPossibleMoves():
            self.onStaleMate(self.infoLabel)

    def onHasWinner(self, winner, label):
        label['text'] = winner + ' Wins!!!'
        for row in self.btnGrid:
            for btn in row:
                btn['state'] = 'disabled'

    def onStaleMate(self, label):
        label['text'] = 'Stale Mate!'
        for row in self.btnGrid:
            for btn in row:
                btn['state'] = 'disabled'

    def onQuit(self):
        """ Close all socket connections and close GUI. """
        self.client.leaveServer()
        self.master.destroy()
예제 #48
0
class DesktopApp(Window):
	def __init__(self, master):
		super(DesktopApp, self).__init__(master)
		# Connection to Broker
		self.client = Client()
		self.client.connect()
		# Bind MQTT client on_message
		self.client.client.on_message=self.on_message
		self.client.subscribe()

		# Data history
		# fmt = [time_stamp],[avg_curve]
		self.top_history = [[],[]]
		self.bottom_history = [[],[]]
		# reference values (degrees)
		self.top_ref = 25
		self.bottom_ref = 10

		# Set MQTT Client loop to start as soon as Window opens
		self.master.after(0, self.client_loop)

	# Call MQTT client loop method every 5s
	# expecting to recieve a message every 300 seconds
	# keeps GUI responsive as loop() is blocking
	def client_loop(self):
		self.client.client.loop()
		self.master.after(5000, self.client_loop)

	# Call Window.plotter() to update graph
	def plot(self):
		# Plot top and bottom sesnor history
		self.plotter(self.top_history, self.bottom_history, self.top_ref, self.bottom_ref)

	# Callback method when the MQTT client recieves a message
	# Updates graph plot with new data
	def on_message(self, client, userdata, message):
		print("Recieved a log")
		# Load JSON into Python data types
		payload = json.loads(message.payload)
		top_record, bottom_record = payload[0]['curverecord'], payload[1]['curverecord']

		# Add to history
		self.top_history[0].append(top_record[0]) # time_stamp
		self.top_history[1].append(top_record[1]) # curve
		self.bottom_history[0].append(bottom_record[0]) # time_stamp
		self.bottom_history[1].append(bottom_record[1]) # curve

		# Re-plot
		self.plot()

	# Clear and reset graph
	# Overriden to also clear data stored
	def clear_graph(self):
		self.top_history = [[],[]]
		self.bottom_history = [[],[]]
		# reference line
		self.top_ref = []
		self.bottom_ref = []
		self.ax.cla()
		self.set_axis()
		self.graph.draw()

	# Disconnect then close the application
	def safe_exit(self):
		# Disconnect
		self.client.disconnect()
		# Close application
		exit()
예제 #49
0
 def __init__(self, symbol, populate=True):
     self.symbol, self.client = symbol.upper(), Client()
     self.stock_id = self.client.get(stock(self.symbol))['results'][0]['id']
     self.options = self.build_chain() if populate else None
예제 #50
0
class QBot(Bot):
    def __init__(self, sess, save, learning_rate, momentum, timeout, n_turns,
                 save_iterations, mode, key, url):
        super().__init__(sess)
        self.save = save  #boolean
        self.learning_rate = learning_rate
        self.momentum = momentum

        self.depth = 1
        self.connection = Client(self, timeout, url, key, mode, self.depth)
        self.connection_thread = threading.Thread(target=open_connection)
        self.replay_memory = []
        build_model()

        #ensures that concurrency problems are eliminated
        self.lock = RLock()

    #is called when the client receives the next board state
    def callback(self, state):
        with self.lock:
            #add to training pool
            self.replay_memory.append(to_state_matrix(state))

    def to_state_matrix(self, state):
        pass

    '''  
	TODO -- implement Swish activation function
	Reference: 
	Searching for Activation Functions (2017) 
	https://arxiv.org/abs/1710.05941
	'''

    @staticmethod
    def swish(x):
        return x * tf.nn.sigmoid(x)

    def build_model(self):
        self.input_height = 12
        self.input_width = 12
        self.input_channels = 23 * self.depth
        self.conv_n_maps = [32, 64, 64]
        self.conv_kernel_sizes = [(3, 3), (3, 3), (2, 2)]
        self.conv_strides = [2, 1, 1]
        self.conv_paddings = ["SAME"] * 3
        self.conv_activation = [tf.nn.relu] * 3
        self.n_hidden_in = 100 * input_channels  #with one stride of 2
        n_hidden = 256
        hidden_activation = tf.nn.relu
        n_outputs = len(Action)
        initializer = tf.contrib.layers.variance_scaling_initializer(
        )  #He initialization

        self.init = tf.global_variables_initializer()
        self.saver = tf.train.Saver()

        if not self.ignore_checkpoint:
            self.load_model()

        def q_network(X_state, name):
            prev_layer = tf.cast(X_state, tf.int8)
            with tf.variable_scope(name) as scope:
                for n_maps, kernel_size, strides, padding, activation in zip(
                        conv_n_maps, conv_kernel_sizes, conv_strides,
                        conv_paddings, conv_activation):
                    prev_layer = tf.layers.conv2d(
                        prev_layer,
                        filters=n_maps,
                        kernel_size=kernel_size,
                        strides=strides,
                        padding=padding,
                        activation=activation,
                        kernel_initializer=initializer)
                last_conv_layer_flat = tf.reshape(prev_layer,
                                                  shape=[-1, n_hidden_in])
                hidden = tf.layers.dense(last_conv_layer_flat,
                                         n_hidden,
                                         activation=hidden_activation,
                                         kernel_initializer=initializer)
                outputs = tf.layers.dense(hidden,
                                          n_outputs,
                                          kernel_initializer=initializer)
            trainable_vars = tf.get_collection(
                tf.GraphKeys.TRAINABLE_VARIABLES, scope=scope.name)
            trainable_vars_by_name = {
                var.name[len(scope.name):]: var
                for var in trainable_vars
            }
            return outputs

        X_state = tf.placeholder(tf.bool,
                                 shape=[
                                     None, self.input_height, self.input_width,
                                     self.input_channels
                                 ])

        online_scope = "q_networks/online"
        target_scope = "q_networks/target"

        online_q_values = q_network(X_state, name=online_scope)
        target_q_values = q_network(X_state, name=target_scope)

        copier = ModelParametersCopier(online_scope, target_scope)

        with tf.variable_scope("train"):
            X_action = tf.placeholder(tf.int32, shape=[None])
            y = tf.placeholder(tf.float32, shape=[None, 1])
            q_value = tf.reduce_sum(online_q_values *
                                    tf.one_hot(X_action, n_outputs),
                                    axis=1,
                                    keep_dims=True)
            error = tf.abs(y - q_value)
            clipped_error = tf.clip_by_value(error, 0.0, 1.0)
            linear_error = 2 * (error - clipped_error)
            loss = tf.reduce_mean(tf.square(clipped_error) + linear_error)

            global_step = tf.Variable(0, trainable=False, name='global_step')
            optimizer = tf.train.MomentumOptimizer(self.learning_rate,
                                                   self.momentum,
                                                   use_nesterov=True)
            training_op = optimizer.minimize(loss, global_step=global_step)

        q_placeholder = tf.placeholder(tf.float32, shape=())
        loss_placeholder = tf.placeholder(tf.float32, shape=())
        #self.baseline_placeholder = tf.placeholder(tf.float32, shape=())
        tf.summary.scalar("Mean Max Q Value", q_placeholder)
        tf.summary.scalar("Loss value", loss_placeholder)
        #tf.summary.scalar("baseline",self.baseline_placeholder)
        summary = tf.summary.merge_all()

    def epsilon_greedy(self, q_values, step):
        epsilon = max(eps_min,
                      eps_max - (eps_max - eps_min) * step / eps_decay_steps)
        if np.random.rand() < epsilon:
            return np.random.randint(n_outputs)  # random action
        else:
            return np.argmax(q_values)  # optimal action

    def sample_memories(self, batch_size):
        indices = np.random.permutation(len(self.replay_memory))[:batch_size]
        cols = [[], [], [], [],
                []]  # state, action, reward, next_state, continue
        for idx in indices:
            memory = self.replay_memory[idx]
            for col, value in zip(cols, memory):
                col.append(value)
        cols = [np.array(col) for col in cols]
        return cols[0], cols[1], cols[2].reshape(-1,
                                                 1), cols[3], cols[4].reshape(
                                                     -1, 1)

    def train(self):
        #training phase
        #hyperparams
        #n_iterations = 1 #iters to train on
        #n_max_steps = 2000 #max steps per episode (to prevent infinite loop)
        #n_games_per_update = 10 #10 games per iter
        #save_iterations = 50 #save every 10 iters
        #discount_rate = 0.95
        #n_test_games = 50
        train_writer = tf.summary.FileWriter('summary/train', sess.graph)
        test_writer = tf.summary.FileWriter('summary/test', sess.graph)
        if os.path.isfile(checkpoint_path + ".index"):
            saver.restore(sess, checkpoint_path)
        else:
            init.run()
            copier.make(sess)
            #copy_online_to_target.run()

        #open the connection and start playing the game. retry until the connection opens
        open_connection()

        while True:

            step = global_step.eval()
            if step >= n_steps:
                break
            iteration += 1
            print(
                "\rIteration {}\tTraining step {}/{} ({:.1f})%\tLoss {:5f}\tMean Max-Q {:5f}   "
                .format(iteration, step, n_steps, step * 100 / n_steps,
                        loss_val, mean_max_q),
                end="")
            if done:  # game over, start again
                obs = env.reset()
                for skip in range(skip_start):  # skip the start of each game
                    obs, reward, done, info = env.step(0)
                state = preprocess_observation(obs)

            # Online DQN evaluates what to do
            q_values = online_q_values.eval(feed_dict={X_state: [state]})
            action = epsilon_greedy(q_values, step)

            # Online DQN plays
            obs, reward, done, info = env.step(action)
            next_state = preprocess_observation(obs)

            # Let's memorize what happened
            replay_memory.append(
                (state, action, reward, next_state, 1.0 - done))
            state = next_state

            # Compute statistics for tracking progress (not shown in the book)
            total_max_q += q_values.max()
            game_length += 1
            if done:
                mean_max_q = total_max_q / game_length
                total_max_q = 0.0
                game_length = 0

            if iteration < training_start or iteration % training_interval != 0:
                continue  # only train after warmup period and at regular intervals

            # Sample memories and use the target DQN to produce the target Q-Value
            X_state_val, X_action_val, rewards, X_next_state_val, continues = (
                sample_memories(batch_size))
            next_q_values = target_q_values.eval(
                feed_dict={X_state: X_next_state_val})
            max_next_q_values = np.max(next_q_values, axis=1, keepdims=True)
            y_val = rewards + continues * discount_rate * max_next_q_values

            # Train the online DQN
            _, loss_val = sess.run([training_op, loss],
                                   feed_dict={
                                       X_state: X_state_val,
                                       X_action: X_action_val,
                                       y: y_val
                                   })

            # Regularly copy the online DQN to the target DQN
            if step % copy_steps == 0:
                copier.make(sess)

            # And save regularly
            if step % save_steps == 0:
                saver.save(sess, checkpoint_path)

            #write stats regularly
            if step % 20 == 0:
                sum = sess.run(summary,
                               feed_dict={
                                   q_placeholder: mean_max_q,
                                   loss_placeholder: loss_val
                               })
                train_writer.add_summary(sum, step)

            #check the status of the game

    #walls is matrix
    def legal(self, pos, walls: np.ndarray, action) -> bool:
        direction_vec = Pos.get_pos_vector(action.value)
        candidate = pos.clone().add(direction_vec)
        if walls[candidate.x][candidate.y] == 0:
            return True
        return False

    def open_connection(self):
        while True:
            self.connection.start()

    #state given as a JSON object
    #method predicts the next optimal move
    def move(self, state):
        self.game = Game(state)
예제 #51
0
파일: ssm.py 프로젝트: aminnekoufar/ssm
# -*- coding: utf-8 -*-
from sys import path
path.append('..')
from client import Client
bot_token = '*'
bot = Client(bot_token)
send = bot.send_text
try:
    messages = bot.get_messages()
    for message in messages:
        to = format(message['from'])
        if str(format(message['body'])) == "start":
            if str(format(message['body'])) == "SignUp":
                [error,
                 success] = send(to,
                                 'لطفا نام و نام خانوادگی خود را وارد کنید')
                if success:
                    print('Message sent successfully')
                else:
                    print('Sending message failed: {}'.format(error))
        else:
            # print("New message from {} \nType: {}\nBody: {}" .format(message['from'], message['type'], message['body']))

            # 2 rows. each row is a list of button dictionaries, each button is a dictionary os {'text': 'your text', 'command: 'your command'}
            keyboard = bot.make_keyboard([[{
                'text': 'ثبت نام',
                'command': 'SignUp'
            }, {
                'text': 'Row1Button2',
                'command': 'back'
            }], [{
예제 #52
0
 def train(self):
     self.connection = Client(self, timeout, url, key, mode, self.depth)
예제 #53
0
# -*- coding: utf-8 -*-

from login import *
from client import Client
from readExcel import readExcel
import random
from MyProtoco import MyProtocol

a = 0x0007 & 0x3fffffff
auth = ""
for i in range(0, 7):
    current_code = random.randint(0, 9)
    auth += str(current_code)

excel = readExcel(r'C:\Users\admin\PycharmProjects\LEA\LCS\proto\test.xlsx')
data = excel.body
d = Proto()
d = [d.Login(), d.Logout()]
t = [
    login_pb2.GS2C_Login(),
    login_pb2.GS2C_Logout(),
    error_pb2.GS2C_ERRORCODE()
]
result = Client().client(d, t, [])
b = MyProtocol()
b.init(result)
c = b.header.index(a)
print(b.databody[c])
예제 #54
0
def run(host, port):
    client1 = Client(host, port, timeout=5)
    client2 = Client(host, port, timeout=5)
    command = "wrong command test\n"

    try:
        data = client1.get(command)
    except ClientError:
        pass
    except BaseException as err:
        print(f"Error connection: {err.__class__}: {err}")
        sys.exit(1)
    else:
        print("Wrong command sent to the server must return error")
        sys.exit(1)

    command = 'some_key'
    try:
        data_1 = client1.get(command)
        data_2 = client1.get(command)
    except ClientError:
        print('The server reterned a response to a valid request, which'
              ' client identified as incorrect')
    except BaseException as err:
        print(
            f"The server must maintain a connection between requests"
            f"the second request to the server failed: {err.__class__}: {err}")
        sys.exit(1)

    assert data_1 == data_2 == {}, \
        "When a client requests to receive data on a non existing key, the server" \
        "must return a response with an empty data field"

    try:
        data_1 = client1.get(command)
        data_2 = client2.get(command)
    except ClientError:
        print('The server reterned a response to a valid request, which'
              ' client identified as incorrect')
    except BaseException as err:
        print(f"The server must support connection with several clients: "
              f"{err.__class__}: {err}")
        sys.exit(1)

    assert data_1 == data_2 == {}, \
        "When a client requests to receive data on a non existing key, the server " \
        "must return a response with an empty data field"

    try:
        client1.put("k1", 0.25, timestamp=1)
        client2.put("k1", 2.156, timestamp=2)
        client1.put("k1", 0.35, timestamp=3)
        client2.put("k2", 30, timestamp=4)
        client1.put("k2", 40, timestamp=5)
        client1.put("k2", 41, timestamp=5)
    except Exception as err:
        print(f"Call error client.put(...) {err.__class__}: {err}")
        sys.exit(1)

    expected_metrics = {
        "k1": [(1, 0.25), (2, 2.156), (3, 0.35)],
        "k2": [(4, 30.0), (5, 41.0)],
    }

    try:
        metrics = client1.get("*")
        if metrics != expected_metrics:
            print(f"client.get('*') returned incorrect result. Expected: "
                  f"{expected_metrics}. Received: {metrics}")
            sys.exit(1)
    except Exception as err:
        print(f"Call error client.get('*') {err.__class__}: {err}")
        sys.exit(1)

    expected_metrics = {"k2": [(4, 30.0), (5, 41.0)]}

    try:
        metrics = client2.get("k2")
        if metrics != expected_metrics:
            print(f"client.get('k2') returned incorrect result. Expected: "
                  f"{expected_metrics}. Received: {metrics}")
            sys.exit(1)
    except Exception as err:
        print(f"Call error client.get('k2') {err.__class__}: {err}")
        sys.exit(1)

    try:
        result = client1.get("k3")
        if result != {}:
            print(
                f"Error calling get method with a key that has not been added yet. "
                f"Expected: empty dictionare. Received: {result}")
            sys.exit(1)
    except Exception as err:
        print(
            f"Error calling get method with a key that has not been added yet: "
            f"{err.__class__} {err}")
        sys.exit(1)

    print("Everything alright.")
예제 #55
0
        XML = server.sections()

    # test XML from MyPlex
    if testMyPlexXML:
        print "*** XML from MyPlex"
        XML = getXMLFromPMS('https://plex.tv', '/pms/servers', None, token)
        XML = getXMLFromPMS('https://plex.tv', '/pms/system/library/sections',
                            None, token)

    # test MyPlex Sign In
    if testMyPlexSignIn:
        print "*** MyPlex Sign In"
        options = {'PlexConnectUDID': '007'}

        (user, token) = MyPlexSignIn(username, password, options)
        if user == '' and token == '':
            print "Authentication failed"
        else:
            print "logged in: %s, %s" % (user, token)

    # test MyPlex Sign out
    if testMyPlexSignOut:
        print "*** MyPlex Sign Out"
        MyPlexSignOut(token)
        print "logged out"

    # test sending client commands
    if testLocalClient:
        client = Client('127.0.0.1')
        client.play()
예제 #56
0
from client import Client

client = Client(9002)
client.run()
예제 #57
0
import socket
from client import Client
from server import Server
import time
import json

answer = input('You are [C]lient or [S]erver?')

if answer.lower() == 'c':
    address = input('Input server address > ').split(':')

    client = Client(address[0], int(address[1]))
    client.connect()

    print('Connecting to server...')
    while client.status == 0:
        time.sleep(0.3)

    if client.status == 1:
        nick = input('Your nick > ')
        while len(nick) < 3 or len(nick) > 20:
            print('Nick can be from 3 to 20 characters')
            nick = input('Your nick > ')

        client.nick = nick
        client.send({'type': 'nick', 'data': nick})

        password = input('Server password > ')
        client.send({'type': 'password', 'data': password})

        while client.status == 1:
예제 #58
0
fetch = get_config(getConfig_Url)
if not fetch:
    logger.critical('Initial loading config.json failure, Aborting start.')
    exit()
# 启动V2Ray服务
logger.info("Starting v2ray service")
with open(getCwd + '/config.json', 'w', encoding='UTF-8') as file:
    file.write(json.dumps(fetch))
rc = subprocess.Popen(
    [getCwd + "/v2ray/v2ray", "-config", getCwd + "/config.json"])
time.sleep(5)

# 下面进入循环
localUserInfo = []
while True:
    conn = Client(localIP, localPort)
    # 取得用户信息
    users_json = get_user_info(getUserInfo_Url)
    # 比较本地和远程配置文件
    remote_config = get_config(getConfig_Url)
    if remote_config:
        with open(getCwd + '/config.json', 'r', encoding='UTF-8') as file:
            current_config = str(json.loads(file.read()))
        if str(remote_config) != current_config:
            logger.info(
                "The config.json have been changed. Updating the local config.json."
            )
            rc.kill()
            with open(getCwd + '/config.json', 'w', encoding='UTF-8') as file:
                file.write(json.dumps(remote_config))
            rc = subprocess.Popen(
예제 #59
0
from client import Client

if __name__ == "__main__":
    # # cart = client.init()
    # cart = Client(cart='ULtXMhOuqcRHPpa2aKy1')
    # # client.activate(cart)
    # cart.activate()
    # # client.add_item(cart, 'test_item')
    # cart.add_item('item id')
    # # client.remove_item(cart, 'test_item')
    # cart.remove_item('item id')
    # # print(client.get_items(cart))
    # print(cart.get_items())
    # # client.complete(cart)
    # cart.complete()
    # # client.deactivate(cart)
    # cart.deactivate()

    cart = Client(cart='ULtXMhOuqcRHPpa2aKy1')
    cart.store_transaction('womvkAsNMvAIdKpnW2h3')
예제 #60
0
 def setUp(self):
     self._mock_client_socket = mock.Mock()
     self._client = Client(self._mock_client_socket)