Esempio n. 1
0
def get_connection(connection_name):
    """Получение подключения"""
    if connection_name not in get_available_connections():
        print('Unknown connection %s' % connection_name)
        s_exit(UNKNOWN)

    return Mc().__getattribute__(connection_name)
Esempio n. 2
0
def start():
    """
    Start the client application by allocating a logger, parsing args and then forwarding the args on to the client
    """
    basicConfig(format='%(levelname)s [%(asctime)s]: %(message)s', level=DEBUG)
    logger = getLogger()
    try:
        try:
            args = get_args()

            if not args.verbose:
                logger.setLevel(CRITICAL)

            ui = Interface()
            if not args.username:
                args.username = ui.request_username()

            if not args.password:
                args.password = ui.request_pass()

            # Create a client
            s = Client(args.server_addr, args.port, args.username,
                       args.password, ui, logger)

            # Create an event loop
            loop = Loop()
            # Bind Client to event Loop
            s.start(loop)
        except KeyboardInterrupt:
            s_exit(1)
        else:
            # Run the event loop
            loop.run()
            s_exit(0)
    except ArgumentError as e:
        print("Argument Error: {}".format(e))
        s_exit(1)
Esempio n. 3
0
			print "Servers available to run:", " ".join(proclist.iterkeys())
			szTmp1 = raw_input("Enter which servers you want to stop: (nothing=all)\ne.g. srv1 srv2 srv3\n>>> ")
			if szTmp1.strip():
				szWhichServ=szTmp1
				for iChan in szTmp1.strip().split():
					if iChan not in proclist.iterkeys():
						print "Server not found:", iChan
						continue
					print "Channels available to run for %s:"%iChan, " ".join([str(i) for i in proclist[iChan]["chan"]])
					szTmp2 = raw_input("Enter which additional channels you want to stop: (nothing=all)\ne.g. 1 2 99\n>>> ")
					if szTmp2.strip():
						# print szTmp1, szTmp2
						szWhichChan[iChan]=szTmp2
		# print proclist,whichlist
		if bIsAll:
			staStart(level=dwLevel)
		else:
			tmpWhichServ,tmpWhichChan=[],{}
			if szWhichServ:
				tmpWhichServ=szWhichServ.split()
			if szWhichChan:
				for iKey in szWhichChan.iterkeys():
					tmpWhichChan[iKey]=set([int(i) for i in szWhichChan[iKey].split()])
			# print tmpWhichServ, "\n", tmpWhichChan
			staStart(serv=tmpWhichServ, chan=tmpWhichChan, level=dwLevel)
	except g_GetoptError, err:
		s_exit(err)
#


Esempio n. 4
0
        # Signal's
        self.cancel_button.clicked.connect(self.close)
        self.submit_button.clicked.connect(self.authenticate)

        # Code End
        self.show()  # Show LoginWindow

    def authenticate(self) -> bool:

        username: str = self.username_input.text()
        password: str = self.password_input.text()
        user_access: bool = USER_CHECK(username, password)

        if user_access:
            self.authenticated.emit(username)  # Send Signal To authenticated
            qtw.QMessageBox.information(self, "Logged in",
                                        f"{username}, logged in.")
            return True

        else:
            qtw.QMessageBox.critical(
                self, "Failed", "Your UserName or Password is incorrect.")
            return False


if __name__ == "__main__":
    app = qtw.QApplication(s_argv)
    w = LoginWindow()
    s_exit(app.exec_())
Esempio n. 5
0
# Validate that the python version is at least 3.6
from sys import version_info

from pyuv import Loop

from .Interface import Interface
from .client import Client

if version_info <= (
        3,
        6,
):
    from sys import stderr

    stderr.write("Invalid Python version, needs 3.6 or above")
    s_exit(1)


def validate_ip_arg(ip_or_hostname: str) -> str:
    """
    Validate that an IP address or hostname is valid
    Raise ArgumentError if the address is invalid
    :param ip_or_hostname: ip address or hostname
    :return: The same IP address
    """
    try:
        inet_aton(ip_or_hostname)
        return ip_or_hostname
    except socket_error:
        try:
            return gethostbyname(ip_or_hostname)
Esempio n. 6
0
def show_version():
    print(PROGNAME, VERSION, '\n', DESCRIPTION, '\nAuthor:', AUTHOR,
          '\nRelease date:', RELEASE_DATE)


if __name__ == '__main__':
    try:
        # парсим аргументы командной строки
        my_parser = create_parser()
        namespace = my_parser.parse_args()

        # вывод версии
        if namespace.version:
            show_version()
            s_exit(OK)

        cn = Mc(connection=Mc.MS_44_1_CONNECT).connect()
        requests_info = cn.execute_query(get_requests_info_query, dicted=True)

        for request_info in requests_info:
            additional_information = json.loads(
                request_info['additional_information'])
            additional_information['status'] = int(
                additional_information['status'])
            additional_information[
                'status_description'] = additional_information.get(
                    'status_description', '')

            # если статус 0, то просто ответ, в сраку его
            if additional_information['status'] == 0:
        cn_trade = Mc(connection=PROCEDURE_223_TYPES[namespace.type]
                      ['connection_trade']).connect()

        if namespace.auction:
            all_published_procedures_info = cn_procedures.execute_query(
                get_one_trade_awaiting_procedures_info_query %
                namespace.auction,
                dicted=True)
        else:
            all_published_procedures_info = cn_procedures.execute_query(
                get_all_trade_awaiting_procedures_info_query, dicted=True)

        # если поиск по базе с текущими условиями ничего не дал, то указываем, что ничего не нашлось
        if namespace.auction and not all_published_procedures_info:
            print('Nothing to check')
            s_exit(UNKNOWN)

        # выполняем все проверки
        for row in all_published_procedures_info:
            row['procedure_type'] = namespace.type
            row['short_procedure_type'] = namespace.type[3:]
            check_catalog_procedure_exist_record_c(row)
            check_offer_date_p(row)
            check_regulated_datetime_c(row)
            check_procedure_status_p(row)
            check_lot_status_c(row)

            check_offer_date_c(row)
            check_protocol_request_status_matching_p(row)
            check_catalog_procedure_exist_record_p(row)
            check_protocol_count_p(row)
        else:
            output_message = "NO LEGAL MOVES FOR {}".format(
                string_of_location_to_check)
        print(output_message)
        return 0
    except ParseException:
        print("Failed to parse input")
        return 1
    except BoardStateValidator.InCheckmate as ex:
        print("Invalid board state: {color} is in checkmate".format(
            color=ex.color.value))
        return 1
    except BoardStateValidator.OpponentInCheck:
        print("Invalid board state: Opponent cannot be in check")
        return 1
    except BoardStateValidator.TooManyKings:
        print("Invalid board state: Each player must have exactly one king")
        return 1
    except BoardStateValidator.TooManyPawns:
        print(
            "Invalid board state: Each player cannot have more than 8 pawns or promoted pieces"
        )
        return 1


if __name__ == '__main__':
    # If run from the command line, call main() and exit with it's return code
    from sys import exit as s_exit

    s_exit(main())
Esempio n. 9
0
def check_arguments(args):
    for arg in args:
        if globals()[arg] is None:
            print('Argument %s not set' % arg)
            s_exit(UNKNOWN)
def start():
    """
    Start the server application by parsing the args
    """
    basicConfig(format='%(levelname)s [%(asctime)s]: %(message)s', level=DEBUG)
    logger = getLogger()
    loop = Loop()
    try:
        # Parse args
        args = get_args()

        # Set the log level if not in verbose mode
        if not args.verbose:
            logger.setLevel(INFO)
        if args.quiet:
            logger.setLevel(WARNING)

        # Allocate a database and register some test users
        db = DictionaryDB(logger)
        db.register_user(b"cam", b"mac", 1200)
        db.register_user(b"jen", b"nej", 1200)
        db.register_user(b"kain", b"niak", 1200)
        db.register_user(b"andrei", b"ierdna", 1200)
        db.register_user(b"neil", b"lien", 1200)
        db.register_user(b"safa", b"afas", 1200)
        db.register_user(b"colbert", b"trebloc", 1200)
        db.register_user(b"khanh", b"hnahk", 1200)

        # Allocate a Queue
        queue = UserQueue(logger)

        # Create Session Callback
        def create_session(socket: TCP):
            """
            Wrapper for the Session constructor that defaults the queue and db parameters
            :param socket: TCP connection to create the session with
            :return: A new session
            """
            return Session(socket, queue, db, logger)

        # Allocate a Server
        s = Server(args.listen_addr, args.listen_port, create_session, logger)

        # Allocate an advertiser
        a = Advertiser(args.listen_addr, args.broadcast_addr, args.listen_port,
                       args.udp_port, logger)

        # Allocate a Signal Handler
        sig = Signal(loop)

        def on_signal(sig_handler: Signal, signal: int):
            """
            On SIGINT, stop all things depending on the loop and close the loop
            :param sig_handler: Signal handler that caught the signal
            :param signal: The signal that was received
            """
            logger.info(
                "Caught signal {signal}, shutting down".format(signal=signal))
            sig_handler.stop()
            queue.stop()
            a.stop()
            s.close()
            loop.stop()

        # Bind the objects to the event loop
        sig.start(on_signal, SIGINT)
        s.start(loop)
        a.start(loop)
        queue.register_loop(loop)

        # Run the event Loop
        loop.run()
        s_exit(0)
    except ArgumentError:
        logger.error("Argument Error: ", exc_info=True)
        s_exit(1)