Пример #1
0
 def insert_record(self):
     #create object of class connection
     con1 = Connection()
     con = con1.conn()
     #create cursor means create object of cursor
     cur = con.cursor()
     #insert record  into table Employee table
     q = "insert into employee values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
     #input from user
     empid = int(input("Enter Employee id=>"))
     dno = int(input("Enter department number=>"))
     deptn = input("Enter department name=>")
     desig = input("Enter designation=>")
     emn = input("Enter Employee name=>")
     a = int(input("Enter employee age=>"))
     c = input("Enter Empolyee city=>")
     email = input("Enter Email=>")
     p = input("Enter password=>")
     m = input("Enter mobile number=>")
     bs = float(input("Enter basic salary=>"))
     #create tuple
     val = (empid, dno, deptn, desig, emn, a, c, email, p, m, bs)
     #insert Query run
     try:
         cur.execute(q, val)
     except:
         print("Query Error")
     else:
         #save in database use commit()
         con.commit()
         print("Record Insert successfully")
         #close connection
         cur.close()
         con.close()
Пример #2
0
    def update_salary(self):
        con1 = Connection()
        con = con1.conn()
        empid = int(input("Enter employee id"))
        basic_salary = float(input("Enter  salary"))

        q = "UPDATE employee SET basic_salary=%s where empid=%s"
        cur = con.cursor()
        q = "select salary from employee where empid=%s"
        cur.execute(q, empid)
        result = cur.fetchall()
        sal = result[0]
        #print("current salary",sal)
        s1 = sal[0]
        print("current salary", s1)
        s1 = s1 + s1 * s / 100
        print("after salary", s1)
        val = (s1, empid)

        try:
            cur.execute(q, val)
            con.commit()
            print("Record update successfully")
        #print("record update successfully")
        except:
            print("Record not found")
        cur.close()
        con.close()
Пример #3
0
    def insert_record(self):
        #create object of class Connection
        con1=Connection()
        con=con1.conn()
        #create cursor means create object of cursor
        cur=con.cursor()

        #query fire of insert means to insert record into table Employee table
        q="insert into Employee values(%s,%s,%s,%s,%s)"
        
        #input from user
        eid=int(input("Enter Employee Id : "))
        n=input("Enter Employee Name ")  #varchar type in table=string
        a=int(input("Enter Employee Age : "))
        m=input("Enter Employee Mobile No.  :")
        s=int(input("Enter Employee Salary :"))
        #create tuple
        val=(eid,n,a,m,s)
        #Insert Query run
        try:
            cur.execute(q,val)
        except:
            print("Query Error")
        else:
        #save in database  use commit()
            con.commit()
            print("Record Insert Successfully")
        #close connection
            cur.close()
            con.close()
Пример #4
0
 def update_Salary(self):
     con1=Connection()
     con=con1.conn()
     eid=int(input("Enter employee id no. to be updated : "))
     s=int(input("Enter Increment salary of Employee : "))
     #Fire delete Query
     query="UPDATE Employee SET Salary=%s WHERE Empid=%s"
     #prepared cursor
      #create object of class Connection
     
     cur=con.cursor() #to keep cursor on particular path
     q="SELECT Salary FROM Employee where Empid=%s"
     cur.execute(q,eid)
     result=cur.fetchall()
     sal=result[0]
     #print(sal)
     #print(type(sal))
     s1=sal[0]
     print("Current Salary " ,s1)
     s1=s1+s1*s/100
     print("After Increment , New Salary =",s1)
     val=(s1,eid)
     
     
     #run update query
     try:
         cur.execute(query,val)
         con.commit() #to changes permanently in table
         print(" Record Update  successfully")
     except:
         print("Record not found")
         cur.close()
Пример #5
0
 def __init__(self, host='localhost', port=61613, user='', passcode='', ver=1.0, stdin=sys.stdin, stdout=sys.stdout):
     Cmd.__init__(self, 'Tab', stdin, stdout)
     ConnectionListener.__init__(self)
     self.conn = Connection([(host, port)], user, passcode, wait_on_receipt=True, version=ver)
     self.conn.set_listener('', self)
     self.conn.start()
     self.transaction_id = None
     self.version = ver
     self.__subscriptions = {}
     self.__subscription_id = 1
     self.prompt = '> '
Пример #6
0
 def view_record(self):
     con1 = Connection()
     con = con1.conn()
     query = "SELECT * FROM employee"
     cur = con.cursor()
     #run select query
     cur.execute(query)
     result = cur.fetchall()
     print(result)
     cur.close()
     con.close()
Пример #7
0
class Bot(object):
    '''The Bot class is the core of the bot. It creates the connection and the responder. All messages
    that are received come through here, and are dispatched accordingly.'''
    
    def __init__(self, path, default, quiet):
        '''Constructs the bot object. Takes path, default, and quiet arguments from the command
        line input and sets the bot accordingly. Initializes logging, creates instances of
        necessary classes. Loads plugins, begins the connection.'''
        self._config_path = path
        self._default = default
        self._quiet = quiet
        self.logger = logging.getLogger("GorillaBot")
        self._configuration = Configure(self._config_path, self._default, self._quiet)
        settings = self._configuration.get_configuration()
        
        self.GorillaConnection = Connection(self, settings["host"], settings["port"],
                                            settings["nick"], settings["ident"],
                                            settings["realname"], settings["chans"],
                                            settings["botop"], settings["fullop"])
        self.GorillaCommander = CommandManager(self, self.GorillaConnection)
        self.GorillaConnection._connect()
        
    def dispatch(self, line):
        '''Determines the type of message received:
                If the message is a ping, it pongs back.
                If the message is from NickServ, it determines identification status.
                If the message contains a reply code, it forwards it to parse_number.
                If the message is a PRIVMSG, it forwards it to parse_message.'''
        
        # Probably will want to remove this at some point in the future, but for now I'm going
        # to hold on to it for debugging.
        self.logger.debug(line)
        
        # Responds to ping messages. Doesn't bother to send it to the CommandManager.
        if "PING" in line[0]:
            self.logger.debug("Ping received.")
            self.GorillaConnection.pong(line[1][1:])
            
        # Identifies messages from NickServ, sends to CommandManager
        elif "NickServ" in line[0]:
            self.GorillaCommander.nickserv_parse(line)
            
        # Identifies server message codes, sends to CommandManager
        elif len(line[1])==3:
            self.GorillaCommander.process_numcode(line[1], line)
            
        # Identifies PRIVMSGs, sends to CommandManager
        elif line[1]=="PRIVMSG":
            self.GorillaCommander.check_command(line)
           
        # Nick changes 
        elif line[1] == "NICK":
            self.GorillaCommander.nick_change(line)
Пример #8
0
class Bot(object):
    '''The Bot class is the core of the bot. It creates the connection and the responder. All messages
    that are received come through here, and are dispatched accordingly.'''
    def __init__(self, path, default, quiet):
        '''Constructs the bot object. Takes path, default, and quiet arguments from the command
        line input and sets the bot accordingly. Initializes logging, creates instances of
        necessary classes. Loads plugins, begins the connection.'''
        self._config_path = path
        self._default = default
        self._quiet = quiet
        self.logger = logging.getLogger("GorillaBot")
        self._configuration = Configure(self._config_path, self._default,
                                        self._quiet)
        settings = self._configuration.get_configuration()

        self.GorillaConnection = Connection(
            self, settings["host"], settings["port"], settings["nick"],
            settings["ident"], settings["realname"], settings["chans"],
            settings["botop"], settings["fullop"])
        self.GorillaCommander = CommandManager(self, self.GorillaConnection)
        self.GorillaConnection._connect()

    def dispatch(self, line):
        '''Determines the type of message received:
                If the message is a ping, it pongs back.
                If the message is from NickServ, it determines identification status.
                If the message contains a reply code, it forwards it to parse_number.
                If the message is a PRIVMSG, it forwards it to parse_message.'''

        # Probably will want to remove this at some point in the future, but for now I'm going
        # to hold on to it for debugging.
        self.logger.debug(line)

        # Responds to ping messages. Doesn't bother to send it to the CommandManager.
        if "PING" in line[0]:
            self.logger.debug("Ping received.")
            self.GorillaConnection.pong(line[1][1:])

        # Identifies messages from NickServ, sends to CommandManager
        elif "NickServ" in line[0]:
            self.GorillaCommander.nickserv_parse(line)

        # Identifies server message codes, sends to CommandManager
        elif len(line[1]) == 3:
            self.GorillaCommander.process_numcode(line[1], line)

        # Identifies PRIVMSGs, sends to CommandManager
        elif line[1] == "PRIVMSG":
            self.GorillaCommander.check_command(line)

        # Nick changes
        elif line[1] == "NICK":
            self.GorillaCommander.nick_change(line)
Пример #9
0
 def __init__(self):
     self.conn = Connection()
     Thread.__init__(self)
     WhiteBoard.__init__(self)
     self._init_mouse_event()
     self.setDaemon(True)
     self.isMouseDown = False
     self.x_pos = None
     self.y_pos = None
     self.last_time = None
     self.line_x1, self.line_y1 = None, None
     self.line_x2, self.line_y2 = None, None
Пример #10
0
 def View_Record(self):
     #create object of class Connection
     con1=Connection()
     con=con1.conn()
              #Fire Select Query
     query="SELECT * FROM Employee"
                 #prepared cursor
     cur=con.cursor()
                 #run select query
     cur.execute(query)
     result=cur.fetchall()  #fetchone() to display only first record
     print(result)
     cur.close()
     con.close()
Пример #11
0
 def delete_record(self):
     con1 = Connection()
     con = con1.conn()
     empid = int(input("Enter employee id no. to be delete=>"))
     q = "delete from employee where empid=%s"
     cur = con.cursor()
     try:
         cur.execute(q, empid)
         con.commit()
         print("record delete successfully")
     except:
         print("record not found")
     cur.close()
     con.close()
Пример #12
0
 def Search_Record(self):
     eid=int(input("Enter employee id no. to be Searched : "))
     #create object of class Connection
     con1=Connection()
     con=con1.conn()
              #Fire Select Query
     query="SELECT * FROM Employee where Empid=%s"
                 #prepared cursor
     cur=con.cursor()
                 #run select query
     cur.execute(query,eid)
     result=cur.fetchall()  #fetchone() to display only first record
     print(result)
     cur.close()
     con.close()
Пример #13
0
 def delete(self):
     con1=Connection()
     con=con1.conn()
     eid=int(input("Enter Employee id no. to be deleted : "))
     #Fire delete Query
     query="delete FROM Employee WHERE Empid=%s"
     #prepared cursor
     cur=con.cursor()
     #run delete query
     try:
         cur.execute(query,eid)
         self.con.commit() #to changes permanently in table
         print("Delete Record successfully")
     except:
         print("Record not found")
     cur.close()
     con.close()
Пример #14
0
    def search_record(self):
        empid = int(input("Enter Employee id"))
        con1 = Connection()
        con = con1.conn()
        query = "SELECT * FROM employee  where empid=%s"

        cur = con.cursor()
        try:
            cur.execute(query, empid)
            con.commit()
        except Exception:
            print("Query Error")
        else:
            result = cur.fetchall()
            print(result)
        cur.close()
        con.close()
Пример #15
0
    def __init__(self, path, default, quiet):
        '''Constructs the bot object. Takes path, default, and quiet arguments from the command
        line input and sets the bot accordingly. Initializes logging, creates instances of
        necessary classes. Loads plugins, begins the connection.'''
        self._config_path = path
        self._default = default
        self._quiet = quiet
        self.logger = logging.getLogger("GorillaBot")
        self._configuration = Configure(self._config_path, self._default,
                                        self._quiet)
        settings = self._configuration.get_configuration()

        self.GorillaConnection = Connection(
            self, settings["host"], settings["port"], settings["nick"],
            settings["ident"], settings["realname"], settings["chans"],
            settings["botop"], settings["fullop"])
        self.GorillaCommander = CommandManager(self, self.GorillaConnection)
        self.GorillaConnection._connect()
Пример #16
0
class Patient(object):
    '''
    has a tiny percentage of the footprint (and loading time) of the
    main patient class
    '''
    TOOTH_FIELDS = ("ur8", "ur7", "ur6", "ur5", 'ur4', 'ur3', 'ur2', 'ur1',
                    'ul1', 'ul2', 'ul3', 'ul4', 'ul5', 'ul6', 'ul7', 'ul8',
                    "lr8", "lr7", "lr6", "lr5", 'lr4', 'lr3', 'lr2', 'lr1',
                    'll1', 'll2', 'll3', 'll4', 'll5', 'll6', 'll7', 'll8')
    DECIDUOUS = ('***', '***', '***', 'ulE', 'ulD', 'ulC', 'ulB', 'ulA', 'urA',
                 'urB', 'urC', 'urD', 'urE', '***', '***', '***', '***', '***',
                 '***', 'lrE', 'lrD', 'lrC', 'lrB', 'lrA', 'llA', 'llB', 'llC',
                 'llD', 'llE', '***', '***', '***')

    connection = Connection()

    def __init__(self, sno):
        '''
        initiate the class with default variables, then load from database
        '''
        if sno <= 0:
            raise PatientNotFoundException

        self.serialno = sno
        db = self.connection.connection
        cursor = db.cursor()
        cursor.execute(self.query, (sno, ))
        row = cursor.fetchone()

        if not row:
            raise PatientNotFoundException

        self.dent1, self.dent0, self.dent3, self.dent2 = row[:4]
        for i, field in enumerate(self.TOOTH_FIELDS):
            self.__dict__[field] = row[i + 4]

    @property
    def query(self):
        query = 'SELECT dent1, dent0, dent3, dent2, '
        for field in self.TOOTH_FIELDS:
            query += "%sst, " % field
        return '%s from patients where serialno = %%s' % query.rstrip(", ")

    #@property
    def chartgrid(self):
        grid = ""
        chart_dict = {}
        for quad in (self.dent1, self.dent0, self.dent3, self.dent2):
            grid += from_signed_byte(quad)

        for i, tooth in enumerate(self.TOOTH_FIELDS):
            if grid[i] == "0":
                chart_dict[tooth] = tooth
            else:
                chart_dict[tooth] = self.DECIDUOUS[i]
        return chart_dict
Пример #17
0
 def __init__(self, host='localhost', port=61613, user='', passcode='', ver=1.0, stdin=sys.stdin, stdout=sys.stdout):
     Cmd.__init__(self, 'Tab', stdin, stdout)
     ConnectionListener.__init__(self)
     self.conn = Connection([(host, port)], user, passcode, wait_on_receipt=True, version=ver)
     self.conn.set_listener('', self)
     self.conn.start()
     self.transaction_id = None
     self.version = ver
     self.__subscriptions = {}
     self.__subscription_id = 1
     self.prompt = '> '
Пример #18
0
 def __init__(self, path, default, quiet):
     '''Constructs the bot object. Takes path, default, and quiet arguments from the command
     line input and sets the bot accordingly. Initializes logging, creates instances of
     necessary classes. Loads plugins, begins the connection.'''
     self._config_path = path
     self._default = default
     self._quiet = quiet
     self.logger = logging.getLogger("GorillaBot")
     self._configuration = Configure(self._config_path, self._default, self._quiet)
     settings = self._configuration.get_configuration()
     
     self.GorillaConnection = Connection(self, settings["host"], settings["port"],
                                         settings["nick"], settings["ident"],
                                         settings["realname"], settings["chans"],
                                         settings["botop"], settings["fullop"])
     self.GorillaCommander = CommandManager(self, self.GorillaConnection)
     self.GorillaConnection._connect()
Пример #19
0
    await queue.join()

    # cancel all workers
    log.debug('cancelling workers')
    for w in workers:
        w.cancel()

    # wait until all worker tasks are cancelled
    await asyncio.gather(*workers)


if __name__ == '__main__':
    util.patchAsyncio()
    ib = IB()
    barSize = '30 secs'
    wts = 'TRADES'
    # object where data is stored
    store = ArcticStore(f'{wts}_{barSize}')

    # the bool is for cont_only
    holder = ContractHolder(ib, 'contracts.csv',
                            store, wts, barSize, False, aggression=1)

    asyncio.get_event_loop().set_debug(True)
    # util.logToConsole(DEBUG)
    Connection(ib, partial(main, holder), watchdog=True)

    log.debug('script finished, about to disconnect')
    ib.disconnect()
    log.debug('disconnected')
Пример #20
0
from connect import Connection

conn = Connection()
conn.connect_to_fantasy_commander()

query = """
                SELECT 
                        name,
                        year,
                        team,
                        hr,
                        war
                FROM fangraphs_batter_standard 
                WHERE team = 'steamer'
                """

conn.cursor.execute(query)

for row in conn.cursor:
  print row
Пример #21
0
 def __init__(self, host='localhost', port=61613, user='', passcode=''):
     self.conn = Connection([(host, port)], user, passcode)
     self.conn.set_listener('', self)
     self.conn.start()
     self.__commands = get_commands()
     self.transaction_id = None
Пример #22
0
class StompCLI(ConnectionListener):
    """
    A command line interface to the stomp.py client.  See \link stomp::internal::connect::Connection \endlink
    for more information on establishing a connection to a stomp server.
    """
    def __init__(self, host='localhost', port=61613, user='', passcode=''):
        self.conn = Connection([(host, port)], user, passcode)
        self.conn.set_listener('', self)
        self.conn.start()
        self.__commands = get_commands()
        self.transaction_id = None

    def __print_async(self, frame_type, headers, body):
        """
        Utility function to print a message and setup the command prompt
        for the next input
        """
        sysout("\r  \r", end='')
        sysout(frame_type)
        for header_key in headers.keys():
            sysout('%s: %s' % (header_key, headers[header_key]))
        sysout('')
        sysout(body)
        sysout('> ', end='')
        sys.stdout.flush()

    def on_connecting(self, host_and_port):
        """
        \see ConnectionListener::on_connecting
        """
        self.conn.connect(wait=True)

    def on_disconnected(self):
        """
        \see ConnectionListener::on_disconnected
        """
        sysout("lost connection")

    def on_message(self, headers, body):
        """
        \see ConnectionListener::on_message
        
        Special case: if the header 'filename' is present, the content is written out
        as a file
        """
        if 'filename' in headers:
            content = base64.b64decode(body.encode())
            if os.path.exists(headers['filename']):
                fname = '%s.%s' % (headers['filename'], int(time.time()))
            else:
                fname = headers['filename']
            f = open(fname, 'wb')
            f.write(content)
            f.close()
            self.__print_async("MESSAGE", headers, "Saved file: %s" % fname)
        else:
            self.__print_async("MESSAGE", headers, body)

    def on_error(self, headers, body):
        """
        \see ConnectionListener::on_error
        """
        self.__print_async("ERROR", headers, body)

    def on_receipt(self, headers, body):
        """
        \see ConnectionListener::on_receipt
        """
        self.__print_async("RECEIPT", headers, body)

    def on_connected(self, headers, body):
        """
        \see ConnectionListener::on_connected
        """
        self.__print_async("CONNECTED", headers, body)

    def ack(self, args):
        """
        Usage:
            ack <message-id>

        Required Parameters:
            message-id - the id of the message being acknowledged

        Description:
            The command 'ack' is used to acknowledge consumption of a message from a subscription using client
            acknowledgment. When a client has issued a 'subscribe' with the ack flag set to client, any messages
            received from that destination will not be considered to have been consumed (by the server) until
            the message has been acknowledged.
        """
        if len(args) < 2:
            sysout("Expecting: ack <message-id>")
        elif not self.transaction_id:
            self.conn.ack(headers={'message-id': args[1]})
        else:
            self.conn.ack(headers={'message-id': args[1]},
                          transaction=self.transaction_id)

    def abort(self, args):
        """
        Usage:
            abort

        Description:
            Roll back a transaction in progress.
        """
        if not self.transaction_id:
            sysout("Not currently in a transaction")
        else:
            self.conn.abort(transaction=self.transaction_id)
            self.transaction_id = None

    def begin(self, args):
        """
        Usage:
            begin

        Description:
            Start a transaction. Transactions in this case apply to sending and acknowledging -
            any messages sent or acknowledged during a transaction will be handled atomically based on the
            transaction.
        """
        if self.transaction_id:
            sysout("Currently in a transaction (%s)" % self.transaction_id)
        else:
            self.transaction_id = self.conn.begin()
            sysout('Transaction id: %s' % self.transaction_id)

    def commit(self, args):
        """
        Usage:
            commit

        Description:
            Commit a transaction in progress.
        """
        if not self.transaction_id:
            sysout("Not currently in a transaction")
        else:
            sysout('Committing %s' % self.transaction_id)
            self.conn.commit(transaction=self.transaction_id)
            self.transaction_id = None

    def disconnect(self, args):
        """
        Usage:
            disconnect

        Description:
            Gracefully disconnect from the server.
        """
        try:
            self.conn.disconnect()
        except NotConnectedException:
            pass  # ignore if no longer connected

    def send(self, args):
        """
        Usage:
            send <destination> <message>

        Required Parameters:
            destination - where to send the message
            message - the content to send

        Description:
            Sends a message to a destination in the messaging system.
        """
        if len(args) < 3:
            sysout('Expecting: send <destination> <message>')
        elif not self.transaction_id:
            self.conn.send(destination=args[1], message=' '.join(args[2:]))
        else:
            self.conn.send(destination=args[1],
                           message=' '.join(args[2:]),
                           transaction=self.transaction_id)

    def sendreply(self, args):
        """
        Usage:
            sendreply <destination> <correlation-id> <message>

        Required Parameters:
            destination - where to send the message
            correlation-id - the correlating identifier to send with the response
            message - the content to send

        Description:
            Sends a reply message to a destination in the messaging system.
        """
        if len(args) < 4:
            sysout(
                'expecting: sendreply <destination> <correlation-id> <message>'
            )
        else:
            self.conn.send(destination=args[1],
                           message="%s\n" % ' '.join(args[3:]),
                           headers={'correlation-id': args[2]})

    def sendfile(self, args):
        """
        Usage:
            sendfile <destination> <filename>

        Required Parameters:
            destination - where to send the message
            filename - the file to send

        Description:
            Sends a file to a destination in the messaging system.
        """
        if len(args) < 3:
            sysout('Expecting: sendfile <destination> <filename>')
        elif not os.path.exists(args[2]):
            sysout('File %s does not exist' % args[2])
        else:
            s = open(args[2], mode='rb').read()
            msg = base64.b64encode(s).decode()
            if not self.transaction_id:
                self.conn.send(destination=args[1],
                               message=msg,
                               filename=args[2])
            else:
                self.conn.send(destination=args[1],
                               message=msg,
                               filename=args[2],
                               transaction=self.transaction_id)

    def subscribe(self, args):
        """
        Usage:
            subscribe <destination> [ack]

        Required Parameters:
            destination - the name to subscribe to

        Optional Parameters:
            ack - how to handle acknowledgements for a message; either automatically (auto) or manually (client)

        Description:
            Register to listen to a given destination. Like send, the subscribe command requires a destination
            header indicating which destination to subscribe to. The ack parameter is optional, and defaults to
            auto.
        """
        if len(args) < 2:
            sysout('Expecting: subscribe <destination> [ack]')
        elif len(args) > 2:
            sysout('Subscribing to "%s" with acknowledge set to "%s"' %
                   (args[1], args[2]))
            self.conn.subscribe(destination=args[1], ack=args[2])
        else:
            sysout('Subscribing to "%s" with auto acknowledge' % args[1])
            self.conn.subscribe(destination=args[1], ack='auto')

    def unsubscribe(self, args):
        """
        Usage:
            unsubscribe <destination>

        Required Parameters:
            destination - the name to unsubscribe from

        Description:
            Remove an existing subscription - so that the client no longer receive messages from that destination.
        """
        if len(args) < 2:
            sysout('Expecting: unsubscribe <destination>')
        else:
            sysout('Unsubscribing from "%s"' % args[1])
            self.conn.unsubscribe(destination=args[1])

    def stats(self, args):
        """
        Usage:
            stats [on|off]
            
        Description:
            Record statistics on messages sent, received, errors, etc. If no argument (on|off) is specified,
            dump the current statistics.
        """
        if len(args) < 2:
            stats = self.conn.get_listener('stats')
            if stats:
                sysout(stats)
            else:
                sysout('No stats available')
        elif args[1] == 'on':
            self.conn.set_listener('stats', StatsListener())
        elif args[1] == 'off':
            self.conn.remove_listener('stats')
        else:
            sysout('Expecting: stats [on|off]')

    def run(self, args):
        """
        Usage:
            run <filename>
            
        Description:
            Execute commands in a specified file
        """
        if len(args) == 1:
            sysout("Expecting: run <filename>")
        elif not os.path.exists(args[1]):
            sysout("File %s was not found" % args[1])
        else:
            filecommands = open(args[1]).read().split('\n')
            for x in range(len(filecommands)):
                split = filecommands[x].split()
                if len(split) < 1:
                    continue
                elif split[0] in self.__commands:
                    getattr(self, split[0])(split)
                else:
                    sysout('Unrecognized command "%s" at line %s' %
                           (split[0], x))
                    break

    def help(self, args):
        """
        Usage:
            help [command]

        Description:
            Display info on a specified command, or a list of available commands
        """
        if len(args) == 1:
            sysout(
                'Usage: help <command>, where command is one of the following:'
            )
            sysout('    ')
            for f in self.__commands:
                sysout('%s ' % f, end='')
            sysout('')
            return
        elif not hasattr(self, args[1]):
            sysout('There is no command "%s"' % args[1])
            return

        func = getattr(self, args[1])
        if hasattr(func, '__doc__') and getattr(func, '__doc__') is not None:
            sysout(func.__doc__)
        else:
            sysout('There is no help for command "%s"' % args[1])

    man = help

    def version(self, args):
        sysout('Stomp.py Version %s.%s' % internal.__version__)

    ver = version

    def quit(self, args):
        pass

    exit = quit
Пример #23
0
#! /usr/bin/env python

from connect import Connection
from parse import *
import time

## Load Settings
settings = settings_load()

## Create Connection
connection = Connection(settings)

## Connect to Server
connection.connect()

## Register on Server
connection.register()

## Create modules array
modules = []

while 1:
    if connection.ssl ==-True:
        buffer = connection.sock.read(4096)
    else:
        buffer = connection.sock.recv(4096)
    print buffer
    lines = splitline(buffer)
    for line in lines:
        message = parse(line)
        if message.type == "NOTICE":
Пример #24
0
class StompCLI(Cmd, ConnectionListener):
    """
    A command line interface to the stomp.py client.  See \link stomp::internal::connect::Connection \endlink
    for more information on establishing a connection to a stomp server.
    """
    def __init__(self, host='localhost', port=61613, user='', passcode='', ver=1.0, stdin=sys.stdin, stdout=sys.stdout):
        Cmd.__init__(self, 'Tab', stdin, stdout)
        ConnectionListener.__init__(self)
        self.conn = Connection([(host, port)], user, passcode, wait_on_receipt=True, version=ver)
        self.conn.set_listener('', self)
        self.conn.start()
        self.transaction_id = None
        self.version = ver
        self.__subscriptions = {}
        self.__subscription_id = 1
        self.prompt = '> '

    def __print_async(self, frame_type, headers, body):
        """
        Utility function to print a message and setup the command prompt
        for the next input
        """
        self.__sysout("\r  \r", end='')
        self.__sysout(frame_type)
        for header_key in headers.keys():
            self.__sysout('%s: %s' % (header_key, headers[header_key]))
        self.__sysout('')
        self.__sysout(body)
        self.__sysout('> ', end='')
        self.stdout.flush()
        
    def __sysout(self, msg, end="\n"):
        self.stdout.write(str(msg) + end)
        
    def __error(self, msg, end="\n"):
        self.stdout.write(colors.BOLD + colors.RED + str(msg) + colors.NO_COLOR + end)

    def on_connecting(self, host_and_port):
        """
        \see ConnectionListener::on_connecting
        """
        self.conn.connect(wait=True)

    def on_disconnected(self):
        """
        \see ConnectionListener::on_disconnected
        """
        self.__error("lost connection")

    def on_message(self, headers, body):
        """
        \see ConnectionListener::on_message
        
        Special case: if the header 'filename' is present, the content is written out
        as a file
        """
        if 'filename' in headers:
            content = base64.b64decode(body.encode())
            if os.path.exists(headers['filename']):
                fname = '%s.%s' % (headers['filename'], int(time.time()))
            else:
                fname = headers['filename']
            f = open(fname, 'wb')
            f.write(content)
            f.close()
            self.__print_async("MESSAGE", headers, "Saved file: %s" % fname)
        else:
            self.__print_async("MESSAGE", headers, body)

    def on_error(self, headers, body):
        """
        \see ConnectionListener::on_error
        """
        self.__print_async("ERROR", headers, body)

    def on_receipt(self, headers, body):
        """
        \see ConnectionListener::on_receipt
        """
        self.__print_async("RECEIPT", headers, body)

    def on_connected(self, headers, body):
        """
        \see ConnectionListener::on_connected
        """
        self.__print_async("CONNECTED", headers, body)
        
    def help_help(self):
        self.__sysout('Quick help on commands')
        
    def default(self, line):
        self.__error('Unknown command: %s' % line.split()[0])
        
    def emptyline(self):
        pass
        
    def help(self, usage, description, required = [], optional = []):        
        required.insert(0, '')
        rparams = "\n\t".join(required)
        
        optional.insert(0, '')
        oparams = "\n\t".join(optional)
        
        m = {
            'hl' : colors.BOLD + colors.GREEN,
            'nc' : colors.NO_COLOR,
            'usage' : usage,
            'description' : description,
            'required' : rparams.rstrip(),
            'optional' : oparams.rstrip()
        }
        
        if rparams.rstrip() != '':
            rparams = '''%(hl)sRequired Parameters:%(nc)s%(required)s\n\n''' % m
            m['required'] = rparams
            
        if oparams.rstrip() != '':
            oparams = '''%(hl)sOptional Parameters:%(nc)s%(optional)s\n\n''' % m
            m['optional'] = oparams
        
        self.__sysout('''%(hl)sUsage:%(nc)s
\t%(usage)s

%(required)s%(optional)s%(hl)sDescription:%(nc)s
\t%(description)s
        ''' % m)
     
    def do_quit(self, args):
        self.conn.stop()
        sys.exit(0)
    do_exit = do_quit
    do_EOF = do_quit
    
    def help_quit(self):
        self.help('exit', 'Exit the stomp client')
    help_exit = help_quit
    
    def help_EOF(self):
        self.__sysout('')
        
    def do_subscribe(self, args):
        args = args.split()
        if len(args) < 1:
            self.__error('Expecting: subscribe <destination> [ack]')
            return
        
        name = args[0]
        if name in self.__subscriptions:
            self.__error('Already subscribed to %s' % name)
            return
        
        ack_mode = 'auto'
        if len(args) >= 2:
            ack_mode = args[1]   
        
        sid = self.__subscription_id
        self.__subscription_id += 1

        self.__sysout('Subscribing to "%s" with acknowledge set to "%s", id set to "%s"' % (name, ack_mode, sid))
        self.conn.subscribe(destination=name, ack=ack_mode, id=sid)            
        self.__subscriptions[name] = SubscriptionInfo(sid, ack_mode)
            
    def help_subscribe(self):
        self.help('subscribe <destination> [ack]',
            '''Register to listen to a given destination. Like send, the subscribe command requires a destination
\theader indicating which destination to subscribe to. The ack parameter is optional, and defaults to
\tauto.''', [ 'destination - the name to subscribe to' ], [ 'ack - how to handle acknowledgements for a message; either automatically (auto) or manually (client)' ])

    def do_unsubscribe(self, args):
        args = args.split()
        if len(args) < 1:
            self.__error('Expecting: unsubscribe <destination>')
            return
    
        if args[0] not in self.__subscriptions.keys():
            self.__sysout('Subscription %s not found' % args[0])
            return
        
        self.__sysout('Unsubscribing from "%s"' % args[0])
        self.conn.unsubscribe(destination=args[0], id=self.__subscriptions[args[0]].id)
        del self.__subscriptions[args[0]]

    def help_unsubscribe(self):
        self.help('unsubscribe <destination>', 'Remove an existing subscription - so that the client no longer receive messages from that destination.',
                [ 'destination - the name to unsubscribe from' ], [ 'ack - how to handle acknowledgements for a message; either automatically (auto) or manually (client)' ])

    def do_disconnect(self, args):
        try:
            self.__sysout("")
            self.conn.disconnect()
        except NotConnectedException:
            pass # ignore if no longer connected

    def help_disconnect(self):
        self.help('disconnect <destination>', 'Gracefully disconnect from the server.')

    def do_send(self, args):
        args = args.split()
        if len(args) < 2:
            self.__error('Expecting: send <destination> <message>')
        elif not self.transaction_id:
            self.conn.send(destination=args[0], message=' '.join(args[1:]))
        else:
            self.conn.send(destination=args[0], message=' '.join(args[1:]), transaction=self.transaction_id)
            
    def complete_send(self, text, line, begidx, endidx):
        mline = line.split(' ')[1] 
        offs = len(mline) - len(text) 
        return [s[offs:] for s in self.__subscriptions if s.startswith(mline)]
    complete_unsubscribe = complete_send
    complete_sendrec = complete_send
    complete_sendreply = complete_send
    complete_sendfile = complete_send
            
    def help_send(self):
        self.help('send <destination> <message>', 'Sends a message to a destination in the messaging system.',
            [ 'destination - where to send the message', 'message - the content to send' ])

    def do_sendrec(self, args):
        args = args.split()
        receipt_id = str(uuid.uuid4())
        if len(args) < 2:
            self.__error('Expecting: sendrec <destination> <message>')
        elif not self.transaction_id:
            self.conn.send(destination=args[0], message=' '.join(args[1:]), receipt=receipt_id)
        else:
            self.conn.send(destination=args[0], message=' '.join(args[1:]), transaction=self.transaction_id, receipt=receipt_id)

    def help_sendrec(self):
        self.help('sendrec <destination> <message>', 'Sends a message to a destination in the messaging system and blocks for receipt of the message.',
                    [ 'destination - where to send the message', 'message - the content to send' ])
                    
    def do_sendreply(self, args):
        args = args.split()
        if len(args) < 3:
            self.__error('Expecting: sendreply <destination> <correlation-id> <message>')
        else:
            self.conn.send(destination=args[0], message="%s\n" % ' '.join(args[2:]), headers={'correlation-id': args[1]})

    def help_sendreply(self):
        self.help('sendreply <destination> <correlation-id> <message>', 'Sends a reply message to a destination in the messaging system.',
                [ 'destination - where to send the message', 'correlation-id - the correlating identifier to send with the response', 'message - the content to send' ])

    def do_sendfile(self, args):
        args = args.split()
        if len(args) < 2:
            self.__error('Expecting: sendfile <destination> <filename>')
        elif not os.path.exists(args[1]):
            self.__error('File %s does not exist' % args[1])
        else:
            s = open(args[1], mode='rb').read()
            msg = base64.b64encode(s).decode()
            if not self.transaction_id:
                self.conn.send(destination=args[0], message=msg, filename=args[1])
            else:
                self.conn.send(destination=args[0], message=msg, filename=args[1], transaction=self.transaction_id)

    def help_sendfile(self):
        self.help('sendfile <destination> <filename>', 'Sends a file to a destination in the messaging system.',
                [ 'destination - where to send the message', 'filename - the file to send' ])

    def do_version(self, args):
        self.__sysout('%s%s [Protocol version %s]%s' % (colors.BOLD, stomppy_version, self.conn.version, colors.NO_COLOR))
    do_ver = do_version
    
    def help_version(self):
        self.help('version', 'Display the version of the client')
    help_ver = help_version
    
    def check_ack_nack(self, cmd, args):
        if self.version >= 1.1 and len(args) < 2:
            self.__error("Expecting: %s <message-id> <subscription-id>" % cmd)
            return None
        elif len(args) < 1:
            self.__error("Expecting: %s <message-id>" % cmd)
            return None
            
        hdrs = { 'message-id' : args[0] }
            
        if self.version >= 1.1:
            if len(args) < 2:
                self.__error("Expecting: %s <message-id> <subscription-id>" % cmd)
                return
            hdrs['subscription'] = args[1]
            
        return hdrs
    
    def do_ack(self, args):
        args = args.split()
        hdrs = self.check_ack_nack('ack', args)
        if hdrs is None:
            return
            
        if not self.transaction_id:
            self.conn.ack(headers = hdrs)
        else:
            self.conn.ack(headers = hdrs, transaction=self.transaction_id)
            
    def help_ack(self):
        self.help('ack <message-id> [subscription-id]', '''The command 'ack' is used to acknowledge consumption of a message from a subscription using client
\tacknowledgment. When a client has issued a 'subscribe' with the ack flag set to client, any messages
\treceived from that destination will not be considered to have been consumed (by the server) until
\tthe message has been acknowledged.''', [ 'message-id - the id of the message being acknowledged' ], [ 'subscription-id the id of the subscription (only required for STOMP 1.1)' ] )
            
    def do_nack(self, args):
        args = args.split()
        hdrs = self.check_ack_nack('nack', args)
        if hdrs is None:
            return
            
        if not self.transaction_id:
            self.conn.nack(headers = hdrs)
        else:
            self.conn.nack(headers = hdrs, transaction=self.transaction_id)
    
    def help_nack(self):
        self.help('nack <message-id> [subscription]', '''The command 'nack' is used to acknowledge the failure of a message from a subscription using client
\tacknowledgment. When a client has issued a 'subscribe' with the ack flag set to client, any messages
\treceived from that destination will not be considered to have been consumed (by the server) until
\tthe message has been acknowledged (ack or nack).''', [ 'message-id - the id of the message being acknowledged' ])

    def do_abort(self, args):
        if not self.transaction_id:
            self.__error("Not currently in a transaction")
        else:
            self.conn.abort(transaction = self.transaction_id)
            self.transaction_id = None
    do_rollback = do_abort

    def help_abort(self):
        self.help('abort', 'Roll back a transaction in progress.')
    help_rollback = help_abort

    def do_begin(self, args):
        if self.transaction_id:
            self.__error("Currently in a transaction (%s)" % self.transaction_id)
        else:
            self.transaction_id = self.conn.begin()
            self.__sysout('Transaction id: %s' % self.transaction_id)
            
    def help_begin(self):
        self.help('begin', '''Start a transaction. Transactions in this case apply to sending and acknowledging -
\tany messages sent or acknowledged during a transaction will be handled atomically based on the
\ttransaction.''')

    def do_commit(self, args):
        if not self.transaction_id:
            self.__error("Not currently in a transaction")
        else:
            self.__sysout('Committing %s' % self.transaction_id)
            self.conn.commit(transaction=self.transaction_id)
            self.transaction_id = None
            
    def help_commit(self):
        self.help('commit', 'Commit a transaction in progress.')

    def do_stats(self, args):
        args = args.split()
        if len(args) < 1:
            stats = self.conn.get_listener('stats')
            if stats:
                self.__sysout(stats)
            else:
                self.__error('No stats available')
        elif args[0] == 'on':
            self.conn.set_listener('stats', StatsListener())
        elif args[0] == 'off':
            self.conn.remove_listener('stats')
        else:
            self.__error('Expecting: stats [on|off]')
            
    def help_stats(self):
        self.help('stats [on|off]', '''Record statistics on messages sent, received, errors, etc. If no argument (on|off) is specified,
\tdump the current statistics.''')

    def do_run(self, args):
        args = args.split()
        if len(args) == 0:
            self.__error("Expecting: run <filename>")
        elif not os.path.exists(args[0]):
            self.__error("File %s was not found" % args[0])
        else:
            lines = open(args[0]).read().split('\n')
            for line in lines:
                self.onecmd(line)

    def help_run(self):
        self.help('run <filename>', 'Execute commands in a specified file')
Пример #25
0
from crop_faces import Crop_faces
from connect import Connection

crop_faces = Crop_faces('./crops/', './crops_data.json',
                        './models/model_faces.pb')
connect = Connection('cam1')
Пример #26
0
import json
from connect import Connection

connection = Connection()


def lsp_request(msg):
    connection.send(msg)
    response = connection.receive()
    print(json.dumps(response, indent=4, sort_keys=True))


def main():
    connection.connect("127.0.0.1", 9090)

    # Initialize LSP server
    lsp_request({
        "method": "initialize",
        "params": {
            "rootUri": "file:///home/ec2-user/environment/example"
        },
        "jsonrpc": "2.0",
        "id": 0,
    })
    input("Press Enter to continue...")

    # Send request to find definition for class "Hello"
    lsp_request({
        "method": "textDocument/definition",
        "params": {
            "textDocument": {
Пример #27
0
 def __init__(self, host='localhost', port=61613, user='', passcode=''):
     self.conn = Connection([(host, port)], user, passcode)
     self.conn.set_listener('', self)
     self.conn.start()
     self.__commands = get_commands()
     self.transaction_id = None
Пример #28
0
class StompCLI(ConnectionListener):
    """
    A command line interface to the stomp.py client.  See \link stomp::internal::connect::Connection \endlink
    for more information on establishing a connection to a stomp server.
    """
    def __init__(self, host='localhost', port=61613, user='', passcode=''):
        self.conn = Connection([(host, port)], user, passcode)
        self.conn.set_listener('', self)
        self.conn.start()
        self.__commands = get_commands()
        self.transaction_id = None

    def __print_async(self, frame_type, headers, body):
        """
        Utility function to print a message and setup the command prompt
        for the next input
        """
        sysout("\r  \r", end='')
        sysout(frame_type)
        for header_key in headers.keys():
            sysout('%s: %s' % (header_key, headers[header_key]))
        sysout('')
        sysout(body)
        sysout('> ', end='')
        sys.stdout.flush()

    def on_connecting(self, host_and_port):
        """
        \see ConnectionListener::on_connecting
        """
        self.conn.connect(wait=True)

    def on_disconnected(self):
        """
        \see ConnectionListener::on_disconnected
        """
        sysout("lost connection")

    def on_message(self, headers, body):
        """
        \see ConnectionListener::on_message
        
        Special case: if the header 'filename' is present, the content is written out
        as a file
        """
        if 'filename' in headers:
            content = base64.b64decode(body.encode())
            if os.path.exists(headers['filename']):
                fname = '%s.%s' % (headers['filename'], int(time.time()))
            else:
                fname = headers['filename']
            f = open(fname, 'wb')
            f.write(content)
            f.close()
            self.__print_async("MESSAGE", headers, "Saved file: %s" % fname)
        else:
            self.__print_async("MESSAGE", headers, body)

    def on_error(self, headers, body):
        """
        \see ConnectionListener::on_error
        """
        self.__print_async("ERROR", headers, body)

    def on_receipt(self, headers, body):
        """
        \see ConnectionListener::on_receipt
        """
        self.__print_async("RECEIPT", headers, body)

    def on_connected(self, headers, body):
        """
        \see ConnectionListener::on_connected
        """
        self.__print_async("CONNECTED", headers, body)

    def ack(self, args):
        """
        Usage:
            ack <message-id>

        Required Parameters:
            message-id - the id of the message being acknowledged

        Description:
            The command 'ack' is used to acknowledge consumption of a message from a subscription using client
            acknowledgment. When a client has issued a 'subscribe' with the ack flag set to client, any messages
            received from that destination will not be considered to have been consumed (by the server) until
            the message has been acknowledged.
        """
        if len(args) < 2:
            sysout("Expecting: ack <message-id>")
        elif not self.transaction_id:
            self.conn.ack(headers = { 'message-id' : args[1] })
        else:
            self.conn.ack(headers = { 'message-id' : args[1] }, transaction=self.transaction_id)

    def abort(self, args):
        """
        Usage:
            abort

        Description:
            Roll back a transaction in progress.
        """
        if not self.transaction_id:
            sysout("Not currently in a transaction")
        else:
            self.conn.abort(transaction = self.transaction_id)
            self.transaction_id = None

    def begin(self, args):
        """
        Usage:
            begin

        Description:
            Start a transaction. Transactions in this case apply to sending and acknowledging -
            any messages sent or acknowledged during a transaction will be handled atomically based on the
            transaction.
        """
        if self.transaction_id:
            sysout("Currently in a transaction (%s)" % self.transaction_id)
        else:
            self.transaction_id = self.conn.begin()
            sysout('Transaction id: %s' % self.transaction_id)

    def commit(self, args):
        """
        Usage:
            commit

        Description:
            Commit a transaction in progress.
        """
        if not self.transaction_id:
            sysout("Not currently in a transaction")
        else:
            sysout('Committing %s' % self.transaction_id)
            self.conn.commit(transaction=self.transaction_id)
            self.transaction_id = None

    def disconnect(self, args):
        """
        Usage:
            disconnect

        Description:
            Gracefully disconnect from the server.
        """
        try:
            self.conn.disconnect()
        except NotConnectedException:
            pass # ignore if no longer connected

    def send(self, args):
        """
        Usage:
            send <destination> <message>

        Required Parameters:
            destination - where to send the message
            message - the content to send

        Description:
            Sends a message to a destination in the messaging system.
        """
        if len(args) < 3:
            sysout('Expecting: send <destination> <message>')
        elif not self.transaction_id:
            self.conn.send(destination=args[1], message=' '.join(args[2:]))
        else:
            self.conn.send(destination=args[1], message=' '.join(args[2:]), transaction=self.transaction_id)

    def sendreply(self, args):
        """
        Usage:
            sendreply <destination> <correlation-id> <message>

        Required Parameters:
            destination - where to send the message
            correlation-id - the correlating identifier to send with the response
            message - the content to send

        Description:
            Sends a reply message to a destination in the messaging system.
        """
        if len(args) < 4:
            sysout('expecting: sendreply <destination> <correlation-id> <message>')
        else:
            self.conn.send(destination=args[1], message="%s\n" % ' '.join(args[3:]), headers={'correlation-id': args[2]})

    def sendfile(self, args):
        """
        Usage:
            sendfile <destination> <filename>

        Required Parameters:
            destination - where to send the message
            filename - the file to send

        Description:
            Sends a file to a destination in the messaging system.
        """
        if len(args) < 3:
            sysout('Expecting: sendfile <destination> <filename>')
        elif not os.path.exists(args[2]):
            sysout('File %s does not exist' % args[2])
        else:
            s = open(args[2], mode='rb').read()
            msg = base64.b64encode(s).decode()
            if not self.transaction_id:
                self.conn.send(destination=args[1], message=msg, filename=args[2])
            else:
                self.conn.send(destination=args[1], message=msg, filename=args[2], transaction=self.transaction_id)
            
    def subscribe(self, args):
        """
        Usage:
            subscribe <destination> [ack]

        Required Parameters:
            destination - the name to subscribe to

        Optional Parameters:
            ack - how to handle acknowledgements for a message; either automatically (auto) or manually (client)

        Description:
            Register to listen to a given destination. Like send, the subscribe command requires a destination
            header indicating which destination to subscribe to. The ack parameter is optional, and defaults to
            auto.
        """
        if len(args) < 2:
            sysout('Expecting: subscribe <destination> [ack]')
        elif len(args) > 2:
            sysout('Subscribing to "%s" with acknowledge set to "%s"' % (args[1], args[2]))
            self.conn.subscribe(destination=args[1], ack=args[2])
        else:
            sysout('Subscribing to "%s" with auto acknowledge' % args[1])
            self.conn.subscribe(destination=args[1], ack='auto')

    def unsubscribe(self, args):
        """
        Usage:
            unsubscribe <destination>

        Required Parameters:
            destination - the name to unsubscribe from

        Description:
            Remove an existing subscription - so that the client no longer receive messages from that destination.
        """
        if len(args) < 2:
            sysout('Expecting: unsubscribe <destination>')
        else:
            sysout('Unsubscribing from "%s"' % args[1])
            self.conn.unsubscribe(destination=args[1])

    def stats(self, args):
        """
        Usage:
            stats [on|off]
            
        Description:
            Record statistics on messages sent, received, errors, etc. If no argument (on|off) is specified,
            dump the current statistics.
        """
        if len(args) < 2:
            stats = self.conn.get_listener('stats')
            if stats:
                sysout(stats)
            else:
                sysout('No stats available')
        elif args[1] == 'on':
            self.conn.set_listener('stats', StatsListener())
        elif args[1] == 'off':
            self.conn.remove_listener('stats')
        else:
            sysout('Expecting: stats [on|off]')
            
    def run(self, args):
        """
        Usage:
            run <filename>
            
        Description:
            Execute commands in a specified file
        """
        if len(args) == 1:
            sysout("Expecting: run <filename>")
        elif not os.path.exists(args[1]):
            sysout("File %s was not found" % args[1])
        else:
            filecommands = open(args[1]).read().split('\n')
            for x in range(len(filecommands)):
                split = filecommands[x].split()
                if len(split) < 1:
                    continue
                elif split[0] in self.__commands:
                    getattr(self, split[0])(split)
                else:
                    sysout('Unrecognized command "%s" at line %s' % (split[0], x))
                    break

    def help(self, args):
        """
        Usage:
            help [command]

        Description:
            Display info on a specified command, or a list of available commands
        """
        if len(args) == 1:
            sysout('Usage: help <command>, where command is one of the following:')
            sysout('    ')
            for f in self.__commands:
                sysout('%s ' % f, end='')
            sysout('')
            return
        elif not hasattr(self, args[1]):
            sysout('There is no command "%s"' % args[1])
            return

        func = getattr(self, args[1])
        if hasattr(func, '__doc__') and getattr(func, '__doc__') is not None:
            sysout(func.__doc__)
        else:
            sysout('There is no help for command "%s"' % args[1])
    man = help

    def version(self, args):
        sysout('Stomp.py Version %s.%s' % internal.__version__)
    ver = version
    
    def quit(self, args):
        pass
    exit = quit
Пример #29
0
class queriesClass:
    """class for queries about limits etc."""
    db = Connection()
    merged1 = None
    user_id = None
    userPreferences = None
    count = 0
    list_length = 25
    dfList = None
    toPrint = None
    alreadyTry = False
    userNum = 0
    usersUsed = None

    def __init__(self):
        self.db.connect()

#here we get the user \new user id from the sign up system

    def return_suggested_products(self, userID):

        #for now we are not counting the avarage list length, because we still
        #dont have enough receipts and the function returns small amount (10), so after checking the avarage
        #receipts size for family, and suggested list size for existing costumer, we decide to take first 25 products
        #and suggedst it to new user
        #when our data will grow, we can use this function
        ##############self.countAvarageListSize()

        query = "SELECT [limit_id] FROM  [db_shopagent].[dbo].[user_ref_limits] WHERE [user_id]=" + userID
        self.userPreferences = pd.DataFrame(
            pd.read_sql(query, self.db.connection))  #get user limits
        self.user_id = userID  #save userID for later if we will need it

        #if the user do not exist\have no limits
        if (self.userPreferences.empty):
            self.noLimits()

        #if the user have only one limit
        elif (len(self.userPreferences.index) == 1):
            self.count = 0
            #self.checkIfPartialOrNot(self.userPreferences.iloc[0]['limit_id'])
            self.returnDfOfOneLimitQuery(self.userPreferences)

        #if the user have few limits
        else:
            #print(userPreferences.iloc[0]['limit_id'])
            self.returnFewLimitsQuery(self.userPreferences)

        #there is no option to get empty list, because even if a mistake accured and
        #there is no user with the given id, we still want to return suggestion list

        #after all the calculations we return the suggestion
        self.printToCsv(self.dfList)
        return (self.dfList)

    #if the user have no limits, we take from the db array of all existing limits, because
    #we can reccomend everything for this user
    def noLimits(self):
        query = "SELECT [limit_id] FROM  [db_shopagent].[dbo].[user_ref_limits]"
        userPreferences = pd.DataFrame(pd.read_sql(
            query, self.db.connection))  #get all limits
        self.alreadyTry = False
        self.returnFewLimitsQuery(userPreferences)

    #a function to check if the preferences of the user is partial (only part of the family have this limit)
    def checkIfPartialOrNot(self, limitId):
        #variable user_id saves the info of the user
        queryForPart = "SELECT [Partial] FROM [db_shopagent].[dbo].[user_ref_limits] WHERE [limit_id]=" + str(
            limitId) + " And [user_id]=" + str(self.user_id)
        val = pd.DataFrame(pd.read_sql(queryForPart,
                                       self.db.connection))  #get user limits

        #if the match not partial we can continue to finding the list
        if (val.iloc[0]['Partial'] == 0):
            self.returnDfOfOneLimitQuery(limitId)

        #what should we do if the user have only one limit and it's partial?
        else:
            self.learningForPatial()

    #function to count avarage list size, for now the database not big enough, so we decided to give a reccomendation of 25
    #products
    def countAvarageListSize(self):
        countReceipt = pd.DataFrame(
            pd.read_sql("SELECT COUNT (*) FROM [db_shopagent].[dbo].[receipt]",
                        self.db.connection))
        countProducts = pd.DataFrame(
            pd.read_sql("SELECT COUNT (*) FROM [db_shopagent].[dbo].[receipt]",
                        self.db.connection))
        a = int(countReceipt.iloc[0])
        b = int(countProducts.iloc[0])
        self.list_length = round(a / b) * 10

    #we use this function if we get empty suggestion list, because then its relevant
    def learningForPatial(self, limitNum):
        #if i'm partial or full and there is no suggested list for the user, i can learn from any one- and from those who are single too.
        #after that i'm doing merge, and sending it to calculate list, to find the best options

        #when the user have few limits we get an int variable, and when there is
        #only one limit we get a data frame, so we have to check what do we get
        #to use the right variable in our query
        few_values = {}
        if (self.count == 0):
            a = limitNum.iloc[0]['limit_id']
            query = "SELECT [user_id] FROM [db_shopagent].[dbo].[user_ref_limits] WHERE [limit_id]=" + str(
                a)  #+" AND [Partial]=0"
            A = pd.DataFrame(pd.read_sql(
                query, self.db.connection))  #users wity "full" limit dataframe

        else:

            A = pd.DataFrame(columns=['user_id'])
            if (limitNum.size > 1):
                index = 0
                for index, row in limitNum.iterrows():
                    query = "SELECT [user_id] FROM [db_shopagent].[dbo].[user_ref_limits] WHERE [limit_id]=" + str(
                        row['limit_id'])  #+" AND [Partial]=0"
                    few_values[index] = pd.DataFrame(
                        pd.read_sql(query, self.db.connection)
                    )  #users wity "full" limit dataframe

                index = 0
                while (index < len(few_values)):
                    A = pd.concat([A, few_values[index]])
                    index = index + 1

        self.user_id = A.size
        #    query="SELECT [user_id] FROM [db_shopagent].[dbo].[user_ref_limits] WHERE [limit_id]="+str(a)+" AND [Partial]=1"
        query_shoppingList = "SELECT [user_id],[receipt_id] FROM [db_shopagent].[dbo].[receipt_ref_user]"
        query_items = "SELECT [receipt_id],[product_id],[quantity] FROM [db_shopagent].[dbo].[receipet_ref_product]"

        queryForFew = "SELECT [limit_id] FROM  [db_shopagent].[dbo].[user_ref_limits]"
        userPreferences = pd.DataFrame(
            pd.read_sql(queryForFew, self.db.connection))  #get all limits

        #data frame of all users with choosen
        A = pd.DataFrame(pd.read_sql(query,
                                     self.db.connection))  #users by limits
        B = pd.DataFrame(pd.read_sql(query_shoppingList,
                                     self.db.connection))  #receipt by users
        C = pd.DataFrame(pd.read_sql(query_items,
                                     self.db.connection))  #products by receipy

        B.append(self.usersUsed)
        B = B.drop_duplicates(keep=False)

        self.usersUsed = B
        self.usersUsed = pd.concat([self.usersUsed, B])

        A.append(userPreferences)
        if (A.empty or B.empty):
            self.merged1 = None
            self.noLimits()

        else:
            #only users and receipt
            merged = pd.merge(A, B, on='user_id')

            #user receipt and products
            self.merged1 = pd.merge(merged, C, on='receipt_id')
            #print(merged,'\n')
            #print(self.merged1,'\n')

            #i dont need the user or the receipt id anymore
            self.merged1.__delitem__('user_id')
            self.merged1.__delitem__('receipt_id')
            #print(self.merged1)

            #how many users - different- we have
            n_users = merged.user_id.unique().shape[0]
            #how many differen products we have
            n_product = self.merged1.product_id.unique().shape[0]
            #print(n_users,n_product)

            #i collecting the items to groups- by counting the numbers they were bought
            self.merged1.groupby('product_id')
            #print(self.merged1)

            self.alreadyTry = True
            self.calculateList(limitNum)

            #if after all the manipulation we still don't have suggested list for the costumer we will give him
            #basic suggested list for user with no limits
            if (self.dfList == None):
                self.noLimits()

    #there is similarity to leartningForPartial function, but here we choose only users with "full" limits
    #where the limits is not partial
    def returnDfOfOneLimitQuery(self, limitNum):

        #when the user have few limits we get an int variable, and when there is
        #only one limit we get a data frame, so we have to check what do we get
        #to use the right variable in our query
        if (self.count == 0):
            a = limitNum.iloc[0]['limit_id']

        else:
            a = limitNum

        query = "SELECT [user_id] FROM [db_shopagent].[dbo].[user_ref_limits] WHERE [limit_id]=" + str(
            a) + " AND [Partial]=0"
        query_shoppingList = "SELECT [user_id],[receipt_id] FROM [db_shopagent].[dbo].[receipt_ref_user]"
        query_items = "SELECT [receipt_id],[product_id],[quantity] FROM [db_shopagent].[dbo].[receipet_ref_product]"

        queryOnlyOne = """select [user_id] from [db_shopagent].[dbo].[user_ref_limits] where [user_id] in 
        (select user_id from [db_shopagent].[dbo].[user_ref_limits] 
                    group by [user_id],[limit_id]
                   having count(*) =1 and [limit_id]=""" + str(
            limitNum) + ") AND [Partial]=0"

        A = pd.DataFrame(pd.read_sql(
            query, self.db.connection))  #users wity "full" limit dataframe
        B = pd.DataFrame(pd.read_sql(query_shoppingList,
                                     self.db.connection))  #receipt by users
        C = pd.DataFrame(pd.read_sql(query_items,
                                     self.db.connection))  #products by receipy

        B.append(self.usersUsed)
        B = B.drop_duplicates(keep=False)

        self.usersUsed = B

        #we can get empty data frames of users with the limits that we need.
        #but in the function of few limits we have to check all the limits, and it
        #not important for us in this function to get non empty array, because we will take care of it
        #at the function

        self.user_id = A.size

        #only users and receipt
        merged = pd.merge(A, B, on='user_id')

        #user receipt and products
        self.merged1 = pd.merge(merged, C, on='receipt_id')
        #print(merged,'\n')
        #print(self.merged1,'\n')

        #i dont need the user or the receipt id anymore
        self.merged1.__delitem__('user_id')
        self.merged1.__delitem__('receipt_id')
        #print(self.merged1)

        #how many users - different- we have
        n_users = merged.user_id.unique().shape[0]
        #how many differen products we have
        n_product = self.merged1.product_id.unique().shape[0]
        #print(n_users,n_product)

        #i collecting the items to groups- by counting the numbers they were bought
        #self.merged1.groupby('product_id')['quantity'].sum()
        #print(self.merged1)

        if (self.count == 0):
            self.calculateList(limitNum)

    def calculateList(self, limitsArray):

        #self.merged1 = self.merged1.groupby(['product_id']).agg({'quantity': 'count'}).reset_index()
        #print(self.merged1)
        #grouped_sum =  products_grouped['quantity'].median()
        #products_grouped['percentage']  = products_grouped['quantity'].div(grouped_sum)*100
        #products_grouped.sort_values(['quantity', 'product_id'], ascending = [0,1])
        #ab=self.merged1.loc[self.merged1['product_id'] == 573]
        #n=ab['quantity'].median()
        #dfMed.loc[0] = [str(ab.iloc[0]['product_id']),n]
        #print (dfMed)
        #dfMed.iloc[0]=sign

        #i prefered not delete this part because it worked well enough and if there would be an errors
        #maybe i will use part of it
        ###################################################################################################
        self.usersUsed = None
        mm = pd.DataFrame(columns=['product_id', 'quantity'])

        #we don't want that one user will affect all the list (for example 150 milk bottels was bought by one user)
        #so we calculate the median
        if (self.merged1.empty):
            self.learningForPatial(limitsArray)
        mm = self.merged1.groupby(
            'product_id')['quantity'].median().reset_index()

        #if the suggested list size (25 for now) smaller then the suggested shopping list
        #we will return less products
        if (self.list_length > mm.size):
            self.list_length = mm.size

        #we take the products with largest median
        #we take the products with largest median
        mm = mm.nlargest(self.list_length, 'quantity')

        self.dfList = mm['product_id'].tolist()
        print('Ans:' + str(self.dfList))
        if (self.dfList == None):
            self.learningForPatial(limitsArray)

#        self.printToCsv(self.dfList)
#print print
#when we get few limits for one user

    def returnFewLimitsQuery(self, limitsArray):
        df = pd.DataFrame(columns=['product_id', 'quantity'])
        df1 = pd.DataFrame(columns=['product_id', 'quantity'])
        df2 = pd.DataFrame(columns=['product_id', 'quantity'])
        df3 = pd.DataFrame(columns=['product_id', 'quantity'])

        isinA = {}
        self.count = 1  #variable to use in another functions, because we use there a function of
        dataframe_collection = {}

        #"oneLimitQuery, we need to return to our function and this variable help us to decide
        if (self.alreadyTry == False):

            for index, row in limitsArray.iterrows():
                self.returnDfOfOneLimitQuery(row['limit_id'])
                #we append all the dataframes that we get after calculation of every limit by itself
                #and then we send it to "calculate list
                dataframe_collection[index] = self.merged1
                self.merged1 = None

            #new_df = pd.merge(A_df, B_df,  how='left', left_on=['A_c1','c2'], right_on = ['B_c1','c2'])

            index = 0
            while (index < len(dataframe_collection)):
                sign = [df, dataframe_collection[index]]
                df = pd.concat(sign)
                print("dsf")
                if (index == 0):
                    new_df = df
                elif (dataframe_collection[index].empty):
                    new_df.append(dataframe_collection[index])
                else:
                    new_df = pd.merge(new_df,
                                      dataframe_collection[index],
                                      on=['product_id'])

                index = index + 1

            if (new_df.empty):
                new_df['quantity'] = ""

            else:
                if 'Total' in new_df:
                    new_df = new_df.drop('Total', 1)
                if 'quantity_x' in new_df:
                    new_df = new_df.ix[:, ~new_df.columns.duplicated()]
                    new_df['quantity'] = new_df['quantity_x']
                else:
                    new_df['quantity'] = ""

            if 'quantity_x' in new_df:
                new_df = new_df.drop('quantity_x', 1)
            if 'quantity_y' in new_df:
                new_df = new_df.drop('quantity_y', 1)

            #df2['Total']=df2['Total'] =  df.groupby('product_id')['quantity'].sum()
            #df2=df = df2[pd.notnull(df2['Total'])] #remve all row where all value is 'NaN' exists
            #df2['quantity']=df2['Total']
            #df2 = df2.drop('Total', 1)

            #print(df2.sort_values('product_id', ascending=False))
            #df1=df2.groupby('product_id').count()
            self.merged1 = new_df

            self.alreadyTry = True
            self.calculateList(limitsArray)

        else:
            if (self.count == 0):
                self.learningForPatial(limitsArray)

            else:
                self.dfList = None
                return

    #at the futer if we will use a server instade of calculating new list every time
    #we can save template of suggested list for every limit
    #and recalculate it only at the end of the day for example

    def printToCsv(self, dfta):
        df = pd.DataFrame(columns=['product_id', 'product_name'])
        for row in dfta:
            A = pd.DataFrame(
                pd.read_sql(
                    "SELECT [product_id],[product_name] FROM [db_shopagent].[dbo].[products] WHERE [product_id]="
                    + str(row), self.db.connection))  #users by limits
            sign = [df, A]
            df = pd.concat(sign)
        df.to_csv("cvName", encoding='utf-8')
Пример #30
0
class StompCLI(Cmd, ConnectionListener):
    """
    A command line interface to the stomp.py client.  See \link stomp::internal::connect::Connection \endlink
    for more information on establishing a connection to a stomp server.
    """
    def __init__(self,
                 host='localhost',
                 port=61613,
                 user='',
                 passcode='',
                 ver=1.0,
                 stdin=sys.stdin,
                 stdout=sys.stdout):
        Cmd.__init__(self, 'Tab', stdin, stdout)
        ConnectionListener.__init__(self)
        self.conn = Connection([(host, port)],
                               user,
                               passcode,
                               wait_on_receipt=True,
                               version=ver)
        self.conn.set_listener('', self)
        self.conn.start()
        self.transaction_id = None
        self.version = ver
        self.__subscriptions = {}
        self.__subscription_id = 1
        self.prompt = '> '

    def __print_async(self, frame_type, headers, body):
        """
        Utility function to print a message and setup the command prompt
        for the next input
        """
        self.__sysout("\r  \r", end='')
        self.__sysout(frame_type)
        for header_key in headers.keys():
            self.__sysout('%s: %s' % (header_key, headers[header_key]))
        self.__sysout('')
        self.__sysout(body)
        self.__sysout('> ', end='')
        self.stdout.flush()

    def __sysout(self, msg, end="\n"):
        self.stdout.write(str(msg) + end)

    def __error(self, msg, end="\n"):
        self.stdout.write(colors.BOLD + colors.RED + str(msg) +
                          colors.NO_COLOR + end)

    def on_connecting(self, host_and_port):
        """
        \see ConnectionListener::on_connecting
        """
        self.conn.connect(wait=True)

    def on_disconnected(self):
        """
        \see ConnectionListener::on_disconnected
        """
        self.__error("lost connection")

    def on_message(self, headers, body):
        """
        \see ConnectionListener::on_message
        
        Special case: if the header 'filename' is present, the content is written out
        as a file
        """
        if 'filename' in headers:
            content = base64.b64decode(body.encode())
            if os.path.exists(headers['filename']):
                fname = '%s.%s' % (headers['filename'], int(time.time()))
            else:
                fname = headers['filename']
            f = open(fname, 'wb')
            f.write(content)
            f.close()
            self.__print_async("MESSAGE", headers, "Saved file: %s" % fname)
        else:
            self.__print_async("MESSAGE", headers, body)

    def on_error(self, headers, body):
        """
        \see ConnectionListener::on_error
        """
        self.__print_async("ERROR", headers, body)

    def on_receipt(self, headers, body):
        """
        \see ConnectionListener::on_receipt
        """
        self.__print_async("RECEIPT", headers, body)

    def on_connected(self, headers, body):
        """
        \see ConnectionListener::on_connected
        """
        self.__print_async("CONNECTED", headers, body)

    def help_help(self):
        self.__sysout('Quick help on commands')

    def default(self, line):
        self.__error('Unknown command: %s' % line.split()[0])

    def emptyline(self):
        pass

    def help(self, usage, description, required=[], optional=[]):
        required.insert(0, '')
        rparams = "\n\t".join(required)

        optional.insert(0, '')
        oparams = "\n\t".join(optional)

        m = {
            'hl': colors.BOLD + colors.GREEN,
            'nc': colors.NO_COLOR,
            'usage': usage,
            'description': description,
            'required': rparams.rstrip(),
            'optional': oparams.rstrip()
        }

        if rparams.rstrip() != '':
            rparams = '''%(hl)sRequired Parameters:%(nc)s%(required)s\n\n''' % m
            m['required'] = rparams

        if oparams.rstrip() != '':
            oparams = '''%(hl)sOptional Parameters:%(nc)s%(optional)s\n\n''' % m
            m['optional'] = oparams

        self.__sysout('''%(hl)sUsage:%(nc)s
\t%(usage)s

%(required)s%(optional)s%(hl)sDescription:%(nc)s
\t%(description)s
        ''' % m)

    def do_quit(self, args):
        self.conn.stop()
        sys.exit(0)

    do_exit = do_quit
    do_EOF = do_quit

    def help_quit(self):
        self.help('exit', 'Exit the stomp client')

    help_exit = help_quit

    def help_EOF(self):
        self.__sysout('')

    def do_subscribe(self, args):
        args = args.split()
        if len(args) < 1:
            self.__error('Expecting: subscribe <destination> [ack]')
            return

        name = args[0]
        if name in self.__subscriptions:
            self.__error('Already subscribed to %s' % name)
            return

        ack_mode = 'auto'
        if len(args) >= 2:
            ack_mode = args[1]

        sid = self.__subscription_id
        self.__subscription_id += 1

        self.__sysout(
            'Subscribing to "%s" with acknowledge set to "%s", id set to "%s"'
            % (name, ack_mode, sid))
        self.conn.subscribe(destination=name, ack=ack_mode, id=sid)
        self.__subscriptions[name] = SubscriptionInfo(sid, ack_mode)

    def help_subscribe(self):
        self.help(
            'subscribe <destination> [ack]',
            '''Register to listen to a given destination. Like send, the subscribe command requires a destination
\theader indicating which destination to subscribe to. The ack parameter is optional, and defaults to
\tauto.''', ['destination - the name to subscribe to'], [
                'ack - how to handle acknowledgements for a message; either automatically (auto) or manually (client)'
            ])

    def do_unsubscribe(self, args):
        args = args.split()
        if len(args) < 1:
            self.__error('Expecting: unsubscribe <destination>')
            return

        if args[0] not in self.__subscriptions.keys():
            self.__sysout('Subscription %s not found' % args[0])
            return

        self.__sysout('Unsubscribing from "%s"' % args[0])
        self.conn.unsubscribe(destination=args[0],
                              id=self.__subscriptions[args[0]].id)
        del self.__subscriptions[args[0]]

    def help_unsubscribe(self):
        self.help(
            'unsubscribe <destination>',
            'Remove an existing subscription - so that the client no longer receive messages from that destination.',
            ['destination - the name to unsubscribe from'], [
                'ack - how to handle acknowledgements for a message; either automatically (auto) or manually (client)'
            ])

    def do_disconnect(self, args):
        try:
            self.__sysout("")
            self.conn.disconnect()
        except NotConnectedException:
            pass  # ignore if no longer connected

    def help_disconnect(self):
        self.help('disconnect <destination>',
                  'Gracefully disconnect from the server.')

    def do_send(self, args):
        args = args.split()
        if len(args) < 2:
            self.__error('Expecting: send <destination> <message>')
        elif not self.transaction_id:
            self.conn.send(destination=args[0], message=' '.join(args[1:]))
        else:
            self.conn.send(destination=args[0],
                           message=' '.join(args[1:]),
                           transaction=self.transaction_id)

    def complete_send(self, text, line, begidx, endidx):
        mline = line.split(' ')[1]
        offs = len(mline) - len(text)
        return [s[offs:] for s in self.__subscriptions if s.startswith(mline)]

    complete_unsubscribe = complete_send
    complete_sendrec = complete_send
    complete_sendreply = complete_send
    complete_sendfile = complete_send

    def help_send(self):
        self.help('send <destination> <message>',
                  'Sends a message to a destination in the messaging system.',
                  [
                      'destination - where to send the message',
                      'message - the content to send'
                  ])

    def do_sendrec(self, args):
        args = args.split()
        receipt_id = str(uuid.uuid4())
        if len(args) < 2:
            self.__error('Expecting: sendrec <destination> <message>')
        elif not self.transaction_id:
            self.conn.send(destination=args[0],
                           message=' '.join(args[1:]),
                           receipt=receipt_id)
        else:
            self.conn.send(destination=args[0],
                           message=' '.join(args[1:]),
                           transaction=self.transaction_id,
                           receipt=receipt_id)

    def help_sendrec(self):
        self.help(
            'sendrec <destination> <message>',
            'Sends a message to a destination in the messaging system and blocks for receipt of the message.',
            [
                'destination - where to send the message',
                'message - the content to send'
            ])

    def do_sendreply(self, args):
        args = args.split()
        if len(args) < 3:
            self.__error(
                'Expecting: sendreply <destination> <correlation-id> <message>'
            )
        else:
            self.conn.send(destination=args[0],
                           message="%s\n" % ' '.join(args[2:]),
                           headers={'correlation-id': args[1]})

    def help_sendreply(self):
        self.help(
            'sendreply <destination> <correlation-id> <message>',
            'Sends a reply message to a destination in the messaging system.',
            [
                'destination - where to send the message',
                'correlation-id - the correlating identifier to send with the response',
                'message - the content to send'
            ])

    def do_sendfile(self, args):
        args = args.split()
        if len(args) < 2:
            self.__error('Expecting: sendfile <destination> <filename>')
        elif not os.path.exists(args[1]):
            self.__error('File %s does not exist' % args[1])
        else:
            s = open(args[1], mode='rb').read()
            msg = base64.b64encode(s).decode()
            if not self.transaction_id:
                self.conn.send(destination=args[0],
                               message=msg,
                               filename=args[1])
            else:
                self.conn.send(destination=args[0],
                               message=msg,
                               filename=args[1],
                               transaction=self.transaction_id)

    def help_sendfile(self):
        self.help('sendfile <destination> <filename>',
                  'Sends a file to a destination in the messaging system.', [
                      'destination - where to send the message',
                      'filename - the file to send'
                  ])

    def do_version(self, args):
        self.__sysout(
            '%s%s [Protocol version %s]%s' %
            (colors.BOLD, stomppy_version, self.conn.version, colors.NO_COLOR))

    do_ver = do_version

    def help_version(self):
        self.help('version', 'Display the version of the client')

    help_ver = help_version

    def check_ack_nack(self, cmd, args):
        if self.version >= 1.1 and len(args) < 2:
            self.__error("Expecting: %s <message-id> <subscription-id>" % cmd)
            return None
        elif len(args) < 1:
            self.__error("Expecting: %s <message-id>" % cmd)
            return None

        hdrs = {'message-id': args[0]}

        if self.version >= 1.1:
            if len(args) < 2:
                self.__error("Expecting: %s <message-id> <subscription-id>" %
                             cmd)
                return
            hdrs['subscription'] = args[1]

        return hdrs

    def do_ack(self, args):
        args = args.split()
        hdrs = self.check_ack_nack('ack', args)
        if hdrs is None:
            return

        if not self.transaction_id:
            self.conn.ack(headers=hdrs)
        else:
            self.conn.ack(headers=hdrs, transaction=self.transaction_id)

    def help_ack(self):
        self.help(
            'ack <message-id> [subscription-id]',
            '''The command 'ack' is used to acknowledge consumption of a message from a subscription using client
\tacknowledgment. When a client has issued a 'subscribe' with the ack flag set to client, any messages
\treceived from that destination will not be considered to have been consumed (by the server) until
\tthe message has been acknowledged.''',
            ['message-id - the id of the message being acknowledged'], [
                'subscription-id the id of the subscription (only required for STOMP 1.1)'
            ])

    def do_nack(self, args):
        args = args.split()
        hdrs = self.check_ack_nack('nack', args)
        if hdrs is None:
            return

        if not self.transaction_id:
            self.conn.nack(headers=hdrs)
        else:
            self.conn.nack(headers=hdrs, transaction=self.transaction_id)

    def help_nack(self):
        self.help(
            'nack <message-id> [subscription]',
            '''The command 'nack' is used to acknowledge the failure of a message from a subscription using client
\tacknowledgment. When a client has issued a 'subscribe' with the ack flag set to client, any messages
\treceived from that destination will not be considered to have been consumed (by the server) until
\tthe message has been acknowledged (ack or nack).''',
            ['message-id - the id of the message being acknowledged'])

    def do_abort(self, args):
        if not self.transaction_id:
            self.__error("Not currently in a transaction")
        else:
            self.conn.abort(transaction=self.transaction_id)
            self.transaction_id = None

    do_rollback = do_abort

    def help_abort(self):
        self.help('abort', 'Roll back a transaction in progress.')

    help_rollback = help_abort

    def do_begin(self, args):
        if self.transaction_id:
            self.__error("Currently in a transaction (%s)" %
                         self.transaction_id)
        else:
            self.transaction_id = self.conn.begin()
            self.__sysout('Transaction id: %s' % self.transaction_id)

    def help_begin(self):
        self.help(
            'begin',
            '''Start a transaction. Transactions in this case apply to sending and acknowledging -
\tany messages sent or acknowledged during a transaction will be handled atomically based on the
\ttransaction.''')

    def do_commit(self, args):
        if not self.transaction_id:
            self.__error("Not currently in a transaction")
        else:
            self.__sysout('Committing %s' % self.transaction_id)
            self.conn.commit(transaction=self.transaction_id)
            self.transaction_id = None

    def help_commit(self):
        self.help('commit', 'Commit a transaction in progress.')

    def do_stats(self, args):
        args = args.split()
        if len(args) < 1:
            stats = self.conn.get_listener('stats')
            if stats:
                self.__sysout(stats)
            else:
                self.__error('No stats available')
        elif args[0] == 'on':
            self.conn.set_listener('stats', StatsListener())
        elif args[0] == 'off':
            self.conn.remove_listener('stats')
        else:
            self.__error('Expecting: stats [on|off]')

    def help_stats(self):
        self.help(
            'stats [on|off]',
            '''Record statistics on messages sent, received, errors, etc. If no argument (on|off) is specified,
\tdump the current statistics.''')

    def do_run(self, args):
        args = args.split()
        if len(args) == 0:
            self.__error("Expecting: run <filename>")
        elif not os.path.exists(args[0]):
            self.__error("File %s was not found" % args[0])
        else:
            lines = open(args[0]).read().split('\n')
            for line in lines:
                self.onecmd(line)

    def help_run(self):
        self.help('run <filename>', 'Execute commands in a specified file')
Пример #31
0
#! python3
import traceback
from connect import Connection
from parse import *
import time
import select

try:
    settings = settings_load()
except IOError:
    print("No settings file found, please run file run_me_first.py")
    raise SystemExit

connection = Connection(settings)
connection.connect()
connection.registration()
connection.sock.setblocking(0)
module_dict = get_module_objects()
timestamps = {}
for item in module_dict:
    timestamps[item] = time.ctime(os.path.getmtime(item))

while True:
    try:
        ready = select.select([connection.sock], [], [], 5)
        if ready[0]:
            if connection.ssl == True:
                buffer = connection.sock.read(4096)
            else:
                buffer = connection.sock.recv(4096)
            buffer = str(buffer, "utf-8")
Пример #32
0
class Client(Thread, WhiteBoard):
    Objects = {
        'line': 'L',
        'oval': 'O',
        'circle': 'C',
        'rectangle': 'R',
        'square': 'S',
        'erase': 'E',
        'drag': 'DR'
    }

    def __init__(self):
        self.conn = Connection()
        Thread.__init__(self)
        WhiteBoard.__init__(self)
        self._init_mouse_event()
        self.setDaemon(True)
        self.isMouseDown = False
        self.x_pos = None
        self.y_pos = None
        self.last_time = None
        self.line_x1, self.line_y1 = None, None
        self.line_x2, self.line_y2 = None, None

    def _init_mouse_event(self):
        self.drawing_area.bind("<Motion>", self.motion)
        self.drawing_area.bind("<ButtonPress-1>", self.left_but_down)
        self.drawing_area.bind("<ButtonRelease-1>", self.left_but_up)

    def left_but_down(self, event=None):
        self.isMouseDown = True
        self.x_pos = event.x
        self.y_pos = event.y
        self.last_time = time.time()
        self.line_x1, self.line_y1 = event.x, event.y
        if self.isMouseDown and self.drawing_tool == 'eraser':
            self.send_del_msg(event)

    def left_but_up(self, event=None):
        self.isMouseDown = False
        print(event.x, event.y)
        self.last_time = None
        self.line_x2, self.line_y2 = event.x, event.y
        if self.drawing_tool == 'text':
            self.draw_text()
        else:
            self.draw_one_obj()

    def draw_text(self):
        text_to_draw = UserDialog._text
        msg = ('T', self.line_x1, self.line_y1, 'red', text_to_draw)
        self.conn.send_message(msg)

    def draw_one_obj(self):
        tool = self.drawing_tool
        if tool not in Client.Objects.keys():
            return
        else:
            cmd_type = Client.Objects[tool]
            msg = (cmd_type, self.line_x1, self.line_y1, self.line_x2,
                   self.line_y2, 'red')
            self.conn.send_message(msg)

    def send_del_msg(self, event):
        canvas_item_id_tuple = self.drawing_area.find_overlapping(
            event.x - 2, event.y - 2, event.x + 2, event.y + 2)
        print(canvas_item_id_tuple)
        if len(canvas_item_id_tuple) > 0:
            to_delete_id = max(canvas_item_id_tuple)
            tags = self.drawing_area.gettags(to_delete_id)
            msgid = tags[0]
            msg = ('Z', msgid)
            self.conn.send_message(msg)

    def motion(self, event=None):
        if self.isMouseDown and self.drawing_tool == 'pencil':
            now = time.time()
            if now - self.last_time < 0.02:
                print('too fast')
                return
            self.last_time = now
            msg = ('D', self.x_pos, self.y_pos, event.x, event.y, 'red')
            self.conn.send_message(msg)
            self.x_pos = event.x
            self.y_pos = event.y
        elif self.isMouseDown and self.drawing_tool == 'eraser':
            self.send_del_msg(event)

    def run(self):
        # print('run')aa
        while True:
            msg = self.conn.receive_msg()
            self.draw_from_msg(msg)
            if msg == 'xxx':
                pass
Пример #33
0
from connect import Connection

conn = Connection()
conn.connect_to_fantasy_commander()

query = """
                SELECT 
                        name,
                        year,
                        team,
                        hr,
                        war
                FROM fangraphs_batter_standard 
                WHERE team = 'steamer'
                """

conn.cursor.execute(query)

for row in conn.cursor:
    print row
Пример #34
0
    for w in workers:
        w.cancel()

    # wait until all worker tasks are cancelled
    await asyncio.gather(*workers)


if __name__ == '__main__':
    util.patchAsyncio()
    ib = IB()
    barSize = '30 secs'
    wts = 'TRADES'
    # object where data is stored
    store = ArcticStore(f'{wts}_{barSize}')

    holder = ContractHolder(ib,
                            'contracts.csv',
                            store,
                            wts,
                            barSize,
                            True,
                            aggression=0.5)

    asyncio.get_event_loop().set_debug(True)
    # util.logToConsole(DEBUG)
    Connection(ib, partial(main, holder), watchdog=False)

    log.debug('script finished, about to disconnect')
    ib.disconnect()
    log.debug('disconnected')
Пример #35
0
        self.admin = admin

class Conteudo(Base):
    __tablename__ = 'conteudo'

    id = Column(Integer, primary_key=True)
    texto = Column(String(50))
    complete = Column(BOOLEAN) 
    user_id = Column(Integer)

    def __init__(self, texto, complete, user_id):
        self.texto = texto
        self.complete = complete
        self.user_id = user_id

connection = Connection.session()

def token_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        token = None
        
        if 'access-token' in request.headers:
            token = request.headers['access-token']
        if not token:
            return jsonify({'mensagem' : 'Está faltando informar o token'}), 401
        
        try:
            data = jwt.decode(token, app.config['SECRET_KEY'])
            current_user = connection.query(Users).filter_by(public_id=data['public_id']).first()
        except:
Пример #36
0
def main():
    test = Connection("raspy","postgres","192.168.0.103","yolo","dht")
    test.connect()
    test.cursor()
    test.create()

    test.commit()
    test.close()