Example #1
0
    def objects(cls, args):
        """ List all objects of the VSD

        """
        inspector = VSDKInspector(args.version)
        objects = []

        if args.parent:
            name = Utils.get_singular_name(args.parent)
            instance = inspector.get_vsdk_instance(name)

            objects = [Utils.get_plural_name(name) for name in instance.children_rest_names]
        else:
            objects = inspector.get_all_objects()

        if args.child:
            child = Utils.get_singular_name(args.child)
            parents = []
            for name in objects:
                singular_name = Utils.get_singular_name(name)
                instance = inspector.get_vsdk_instance(singular_name)

                if child in instance.children_rest_names:
                    parents.append(name)

            objects = parents

        if args.filter:
            objects = [name for name in objects if args.filter in name]

        objects.sort()

        if not args.json:
            Printer.success('%s objects found.' % len(objects))
        Printer.output(objects, json=args.json, headers={'Name'})
Example #2
0
    def __init__(self, settings=None):
        if settings is not None and 'inline' in settings and not settings['inline']:
            # Change to "good" defaults for inline=False
            settings['mat_str'] = 'bmatrix'
            settings['mat_delim'] = None
        Printer.__init__(self, settings)

        if ('inline') in self._settings:
            warnings.warn("'inline' is deprecated, please use 'mode'. "
                "'mode' can be one of 'inline', 'plain', 'equation', or "
                "'equation*'.")
            if self._settings['inline']:
                self._settings['mode'] = 'inline'
            else:
                self._settings['mode'] = 'equation*'
        if 'mode' in self._settings:
            valid_modes = ['inline', 'plain', 'equation', \
                            'equation*']
            if self._settings['mode'] not in valid_modes:
                raise ValueError("'mode' must be one of 'inline', 'plain', " \
                    "'equation' or 'equation*'")

        mul_symbol_table = {
            None : r" ",
            "ldot" : r" \,.\, ",
            "dot" : r" \cdot ",
            "times" : r" \times "
        }

        self._settings['mul_symbol_latex'] = \
            mul_symbol_table[self._settings['mul_symbol']]

        self._delim_dict = {'(':')','[':']'}
Example #3
0
def printer_info(printer_id):
    try:
        printer = Printer(host_for_name(printer_id))
        info = {
                'name': printer.name,
                'status': printer.status,
                'pages_remaining': printer.pages_remaining,
                'toner_max': 30000,  # TODO: actually calculate this
                'trays': []
        }
        
        for index in range(1, 4):
            capacity = printer.tray_capacity(index)
            current = printer.tray_contents(index)
            tray = {
                    'index': index,
                    'capacity': capacity,
                    'current': current,
            }

            info['trays'].append(tray)
        
        return json.dumps(info)
    except PySnmpError, ex:
        return str(ex)
Example #4
0
    def get_vsdk_parent(self, parent_infos, user):
        """ Get VSDK parent object if possible
            Otherwise it will take the user

            Args:
                parent_infos: a list composed of (parent_name, uuid)

            Returns:
                A parent if possible otherwise the user in session

        """
        if parent_infos and len(parent_infos) == 2:
            name = parent_infos[0]
            uuid = parent_infos[1]

            singular_name = Utils.get_singular_name(name)
            parent = self.get_vsdk_instance(singular_name)
            parent.id = uuid

            try:
                (parent, connection) = parent.fetch()
            except Exception, ex:
                Printer.raise_error('Failed fetching parent %s with uuid %s\n%s' % (name, uuid, ex))

            return parent
Example #5
0
def imprimir_ticket_carga(
        nombre,
        dni,
        facultad,
        categoria,
        code,
        unidad,
        log,
        mensaje,
        total,
        saldo
        ):
    '''Imprime el ticket de carga'''
    printer = Printer()
    printer.print_ticket_carga(
        nombre,
        dni,
        facultad,
        categoria,
        code,
        unidad,
        log,
        mensaje,
        total,
        saldo
    )
    sleep(1)
    printer.disconnect()
Example #6
0
    def __init__(self, profile=None):
        Printer.__init__(self)

        mul_symbol_table = {
            None : r" ",
            "ldot" : r" \,.\, ",
            "dot" : r" \cdot ",
            "times" : r" \times "
        }

        self._settings = {
            "inline" : True,
            "descending" : False,
            "mainvar" : None,
            "fold_frac_powers" : False,
            "fold_func_brackets" : False,
            "mul_symbol" : None,
            "inv_trig_style" : "abbreviated",
            "mat_str" : "smallmatrix",
            "mat_delim" : "(",
        }

        self._delim_dict = {'(':')','[':']'}

        if profile is not None:
            if profile.has_key('inline'):
                if not profile['inline']:
                    #change to "good" defaults for inline=False before
                    #updating with the settings from profile
                    self._settings['mat_str'] = 'bmatrix'
                    self._settings['mat_delim'] = None
            self._settings.update(profile)

        self._settings['mul_symbol_latex'] = \
            mul_symbol_table[self._settings['mul_symbol']]
Example #7
0
    def __init__(self, profile=None):
        Printer.__init__(self)

        mul_symbol_table = {None: r" ", "ldot": r" \,.\, ", "dot": r" \cdot ", "times": r" \times "}

        self._settings = {
            "inline": True,
            "itex": False,
            "descending": False,
            "mainvar": None,
            "fold_frac_powers": False,
            "fold_func_brackets": False,
            "mul_symbol": None,
            "inv_trig_style": "abbreviated",
            "mat_str": "smallmatrix",
            "mat_delim": "(",
        }

        self._delim_dict = {"(": ")", "[": "]"}

        if profile is not None:
            if profile.has_key("inline"):
                if not profile["inline"]:
                    # change to "good" defaults for inline=False before
                    # updating with the settings from profile
                    self._settings["mat_str"] = "bmatrix"
                    self._settings["mat_delim"] = None
            self._settings.update(profile)

        self._settings["mul_symbol_latex"] = mul_symbol_table[self._settings["mul_symbol"]]
Example #8
0
def imprimir_ticket_alumno(
        nombre,
        dni,
        facultad,
        categoria,
        code,
        unidad,
        ticket,
        date,
        mensaje,
        saldo
        ):
    '''Imprime el ticket de alumnos'''
    printer = Printer()
    printer.print_ticket_alumno(
        nombre,
        dni,
        facultad,
        categoria,
        code,
        unidad,
        ticket,
        date,
        mensaje,
        saldo
    )
    sleep(1)
    printer.disconnect()
Example #9
0
File: latex.py Project: ENuge/sympy
    def __init__(self, settings=None):
        if settings is not None and "inline" in settings and not settings["inline"]:
            # Change to "good" defaults for inline=False
            settings["mat_str"] = "bmatrix"
            settings["mat_delim"] = None
        Printer.__init__(self, settings)

        if ("inline") in self._settings:
            warnings.warn(
                "'inline' is deprecated, please use 'mode'. "
                "'mode' can be one of 'inline', 'plain', 'equation', or "
                "'equation*'."
            )
            if self._settings["inline"]:
                self._settings["mode"] = "inline"
            else:
                self._settings["mode"] = "equation*"
        if "mode" in self._settings:
            valid_modes = ["inline", "plain", "equation", "equation*"]
            if self._settings["mode"] not in valid_modes:
                raise ValueError("'mode' must be one of 'inline', 'plain', " "'equation' or 'equation*'")

        mul_symbol_table = {None: r" ", "ldot": r" \,.\, ", "dot": r" \cdot ", "times": r" \times "}

        self._settings["mul_symbol_latex"] = mul_symbol_table[self._settings["mul_symbol"]]

        self._delim_dict = {"(": ")", "[": "]"}
Example #10
0
    def create_options():
        """A class factory which parses command line options and returns an options instance"""
        parser = OptionParser()
        parser.add_option('-i', '--iface', dest='iface', default='mon0',
                          help='Interface to bind to')
        parser.add_option('-t', '--timeout', dest='timeout', default=5, type='int',
                          help='Timeout for the channel hop')
        parser.add_option('-c', '--channel', dest='channel', default=-1, type='int',
                          help='Channel to bind to')
        parser.add_option('--max-channel', dest='max_channel', default=-1, type='int',
                          help='Maximum channel number')
        options, _ = parser.parse_args()

        dump_options = WifiDumpOptions()
        dump_options.iface = options.iface
        dump_options.we = WirelessExtension(dump_options.iface)
        dump_options.timeout = options.timeout
        dump_options.channel = options.channel
        dump_options.channel_hop = (-1 == options.channel)
        dump_options.max_channel = options.max_channel
        if -1 == dump_options.max_channel:
            try:
                dump_options.max_channel = dump_options.we.get_max_channel()
                Printer.verbose('CHAN: max_channel[{0}]'.format(dump_options.max_channel), verbose_level=1)
            except Exception, e:
                Printer.exception(e)
                raise
Example #11
0
def imprimir_ticket_grupal(
        nombre,
        dni,
        id_ticket,
        unidad,
        date,
        cantidad,
        codigo,
        importe,
        delegacion,
        recibo
        ):
    '''Imprime el ticket grupal'''
    printer = Printer()
    printer.print_ticket_grupal(
        nombre,
        dni,
        id_ticket,
        unidad,
        date,
        cantidad,
        codigo,
        importe,
        delegacion,
        recibo,
        'Gracias por usar el Comedor Universitario'
    )
    sleep(1)
    printer.disconnect()
Example #12
0
def check_status():
    '''Chequea el estado de la impresora'''
    printer = Printer()
    state = printer.get_status()
    if state != 1:
        state = printer.get_status()
    return state
    printer.disconnect()
Example #13
0
def scapy_layers_dot11_Dot11_rsn(self):
    """Return the payload of the RSN Dot11Elt as a Dot11EltRSN"""
    elt = self.find_elt_by_id(48)
    if elt:
        try:
            return Dot11EltRSN(str(elt))
        except Exception, e:
            Printer.error("Bad Dot11EltRSN got[{0:s}]".format(elt.info))
            Printer.exception(e)
Example #14
0
def scapy_layers_dot11_Dot11_channel(self):
    """Return the payload of the channel Dot11Elt if it exists"""
    elt = self.find_elt_by_id(3)
    if elt:
        try:
            return int(ord(elt.info))
        except Exception, e:
            Printer.error("Bad Dot11Elt channel got[{0:s}]".format(elt.info))
            Printer.exception(e)
Example #15
0
def scapy_layers_dot11_Dot11_rates(self, id=1):
    """Return the payload of the rates Dot11Elt if it exists"""
    elt = self.find_elt_by_id(id)
    if elt:
        try:
            return Dot11EltRates(str(elt)).rates
        except Exception, e:
            Printer.error("Bad Dot11EltRates got[{0:s}]".format(elt.info))
            Printer.exception(e)
Example #16
0
File: str.py Project: fperez/sympy
    def __init__(self, profile=None):
        Printer.__init__(self)

        self._settings = {
                "full_prec" : "auto",
        }

        if profile is not None:
            self._settings.update(profile)
Example #17
0
def main():
    input_file = sys.argv[1] if len(sys.argv) == 2 else 'input.txt'
    s = Solver(input_file)
    winning_state = s.solve()
    solution = [ winning_state ]
    while solution[0].prev_state is not None:
        solution.insert(0, solution[0].prev_state)
    p = Printer()
    p.print_solution(solution, 4)
Example #18
0
    def set_paths(self):
        # If we already have an existing file containing the paths data in
        # pickle format, read it in and update the paths attributes on our
        # nodes.
        if self.paths_file:

            with open(self.paths_file, 'rb') as f:
                paths_data = pickle.load(f)

                for node in self.nodes:
                    data_for_node = paths_data.get(node.node_id, None)

                    if data_for_node:
                        node.paths = data_for_node

        else:
            # Initialize a paths container that we will write to a file.
            paths_dict = {}

            Printer.pp('Performing preprocessing step to find shortest paths. Please bear with us.')

            num_nodes = len(self.nodes)

            # Iterate through every node, setting the paths attribute with the
            # shortest path to each possible destination.
            for indx, node in enumerate(self.nodes):

                # Ignore the node if it's an exit.
                if node.node_type == self.type_map['exit']:
                    continue

                node_id = node.node_id

                # Compute the paths for every possible destination, saving only
                # the next node to move to.
                for destination in self.destination_nodes:
                    destination_node_id = destination.node_id

                    node.paths[destination_node_id] = ShortestPath(self.neighbors_dict,
                                                                   node_id,
                                                                   destination_node_id).next_node()

                paths_dict[node_id] = node.paths

                if indx % 100 == 0 and indx != 0:
                    percent_done = ((indx+1)/float(num_nodes))*100
                    print('%d percent done.' % percent_done)

            pickle_outfile = 'paths.pickle'

            with open(pickle_outfile, 'wb') as f:
                pickle.dump(paths_dict, f, -1)

            print('---> Dumped paths to %s.' % pickle_outfile)

        print('---> Preprocessing done.')
Example #19
0
 def reprint(self):
     Printer.move_to_home()
     for i in range(self.height):
         row_string = ""
         for j in range(self.width):
             cell = self.matrix[i][j]
             if cell.alive:
                 row_string += "\033[32mX\033[0m"
             else:
                 row_string += "-"
         Printer.reprint(row_string)
Example #20
0
    def __init__(self, profile=None):
        Printer.__init__(self)

        self._settings = {
            "inline" : True,
            "fold_frac_powers" : False,
            "fold_func_brackets" : False,
            "mul_symbol" : None
        }

        if profile is not None:
            self._settings.update(profile)
Example #21
0
    def _set_verbose_mode(self, verbose):
        """ Defines verbosity

            Args:
                verbose: Boolean to activate or deactivate DEBUG mode

        """
        if verbose:
            Printer.info('Verbose mode is now activated.')
            self._vsdk.set_log_level(logging.DEBUG)
        else:
            self._vsdk.set_log_level(logging.ERROR)
Example #22
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-w', '--width', type=int, choices=[16, 32],
                        default=32,
                        help='width of the format in bits (default: 32)')
    parser.add_argument('file', help='Path of field specification file')
    args = parser.parse_args()
    p = Printer(args.width)
    for line in fileinput.input(args.file):
        [name, length] = line.strip().split()
        p.add_field(name, int(length))
    print p
Example #23
0
class TestPrinter(TestCase):

    def setUp(self):
        self.paper = Paper()
        self.printer = Printer()
        self.printer.insert(self.paper)

    def test_addIndentationAtTheStartOfALineAsLongAsItIsNotRemoved(self):
        driver = MethodDefinitionPrinterDriver(self.printer)
        tree = ast.parse(open("samples/method.py", 'r').read())
        driver.visit(tree)

        self.assertEqual(self.paper.text, 'public Object basic_method( Object one, Object two){\n}')
class FireLane():

	def __init__(self, rows, cols, lane):
		self.cars = []
		self.points = {}
		self.lane = lane
		self.printer = Printer(rows, cols, lane)

	def addCar(self, car):
		car.id = len(self.cars)
		self.cars.append(car)

	def numberOfCars(self):
		return len(self.cars)

	def carsThatIHaveToMove(self):
		self.generate_points(self.cars)
		cars_which_should_move = []
		for car in self.cars:
			if (self.isOnTheLane(car)):
				cars_which_should_move.append(self.which_cars_should_I_move_to_move_this_car(car)) 
		return flatten(cars_which_should_move)

	def which_cars_should_I_move_to_move_this_car(self, car):
		if (self.canIMoveThisCar(car)):
			return [car.id]		
		blocking_car = self.get_blocking_car(car)
		return [car.id , self.which_cars_should_I_move_to_move_this_car(blocking_car)]

	def get_blocking_car(self, car):
		return self.cars[self.points[car.next()]]

	def canIMoveThisCar(self, car):
		return not self.points.has_key(car.next())

	def isOnTheLane(self, car):
		return not self.before(car.start[0], car.end[0]) and not self.after(car.start[0], car.end[0])

	def before(self, start, end):
		return (start < self.lane and end < self.lane)

	def after(self, start, end):
		return (self.lane + 1 < start and self.lane + 1 < end)

	def draw(self):
		self.printer.print_board(self.cars, self.points)

	def generate_points(self, cars):
		for i in range(0, len(cars)):
			for space in cars[i].occupied_spaces():
				self.points[space] = i
Example #25
0
    def _check_arguments(cls, args):
        """ Check arguments and environment variables

        """

        args.username = args.username if args.username else os.environ.get('VSD_USERNAME', None)
        args.password = args.password if args.password else os.environ.get('VSD_PASSWORD', None)
        args.api = args.api if args.api else os.environ.get('VSD_API_URL', None)
        args.version = args.version if args.version else os.environ.get('VSD_API_VERSION', None)
        args.enterprise = args.enterprise if args.enterprise else os.environ.get('VSD_ENTERPRISE', None)
        args.json = True if os.environ.get('VSD_JSON_OUTPUT') == 'True' else args.json

        if args.username is None or len(args.username) == 0:
            Printer.raise_error('Please provide a username using option --username or VSD_USERNAME environment variable')

        if args.password is None or len(args.password) == 0:
            Printer.raise_error('Please provide a password using option --password or VSD_PASSWORD environment variable')

        if args.api is None or len(args.api) == 0:
            Printer.raise_error('Please provide an API URL using option --api or VSD_API_URL environment variable')

        if args.enterprise is None or len(args.enterprise) == 0:
            Printer.raise_error('Please provide an enterprise using option --enterprise or VSD_ENTERPRISE environment variable')

        setattr(args, "name", getattr(args, args.command, None))
        del(args.command)
Example #26
0
    def list(cls, args):
        """ List all objects

        """
        inspector = VSDKInspector(args.version)
        name = Utils.get_singular_name(args.name)
        instance = inspector.get_vsdk_instance(name)
        session = inspector.get_user_session(args)
        parent = inspector.get_vsdk_parent(args.parent_infos, session.user)

        classname = instance.__class__.__name__[2:]
        plural_classname = Utils.get_plural_name(classname)
        fetcher_name = Utils.get_python_name(plural_classname)

        try:
            fetcher = getattr(parent, fetcher_name)
        except:

            if parent.rest_name == 'me':
                parent_name = 'Root'
                error_message = '%s failed to found children %s. Maybe you forgot to specify the parent using `--in [parent] [ID]` syntax ?' % (parent_name, fetcher_name)
            else:
                parent_name = parent.rest_name
                error_message = '%s failed to found children %s. You can use command `vsd objects -c %s` to list all possible parents' % (parent_name, name, name)

            Printer.raise_error(error_message)

        (fetcher, parent, objects) = fetcher.fetch(filter=args.filter)

        if objects is None:
            Printer.raise_error('Could not retrieve. Activate verbose mode for more information')

        if not args.json:
            Printer.success('%s %s have been retrieved' % (len(objects), instance.rest_resource_name))
        Printer.output(objects, fields=args.fields, json=args.json)
def test_getPrinters():
    global mockcups

    assert isinstance(helperinstance.getPrinters(), dict)
    assert len(helperinstance.getPrinters()) == 0

    # add printer
    requestor = CloudPrintRequestor()
    requestor.setAccount("test")
    printerinstance = Printer(
        {
            "name": "Testing Printer",
            "id": "__test_printer",
            "capabilities": [{"name": "ns1:Colors", "type": "Feature"}],
        },
        requestor,
        helperinstance,
    )
    helperinstance.addPrinter(printerinstance, "test")

    # also add dummy instance with non-gcp uri
    mockcups._printers["test-dummy-non-gcp-printer"] = {
        "printer-is-shared": False,
        "printer-info": "test info",
        "printer-state-message": "",
        "printer-type": 1,
        "printer-state-reasons": ["none"],
        "printer-uri-supported": "ipp://localhost/printers/test",
        "printer-state": 3,
        "printer-location": "test location",
        "device-uri": "test://test/test",
    }

    assert len(mockcups._printers) == 2

    # test count of printers returned has increased by 1
    assert len(helperinstance.getPrinters()) == 1

    for printername in helperinstance.getPrinters():
        assert printername == "test"
        printer = helperinstance.getPrinters()[printername]
        assert printer["printer-is-shared"] is False
        assert printer["device-uri"] == "gcp://test/__test_printer"

    # delete printer
    helperinstance.deletePrinter(printerinstance.getURI())

    # test count of printers returned is same as original
    assert len(helperinstance.getPrinters()) == 0
Example #28
0
def main():

    try:
        options = WifiDumpOptions.create_options()
        scanner = WifiScanner(options)
        scanner.attach(ConsolePrinter())

        try:
            scanner.scan()
        except Exception, e:
            Printer.exception(e)

    except Exception, e:
        sys.stderr.write(repr(e))
        traceback.print_exc(file=sys.stderr)
Example #29
0
    def _get_vsdk_package(self):
        """ Returns vsdk package

        """
        if self._vsdk is None:
            try:
                self._vsdk = importlib.import_module('vspk.vsdk.%s' % self._version)
                # Printer.info('Imported vsdk.%s from VSPK.' % self._version)
            except ImportError:
                try:
                    self._vsdk = importlib.import_module('vsdk')
                except ImportError as error:
                    Printer.raise_error('Please install requirements using command line `pip install -r requirements.txt`.\n%s' % error)

        return self._vsdk
Example #30
0
    def __init__(self, settings=None):
        Printer.__init__(self, settings)
        from xml.dom.minidom import Document

        # Applying the patch of xml.dom.minidom bug
        # Date: 2011-11-18
        # Description: http://ronrothman.com/public/leftbraned/xml-dom-minidom-\
        #                   toprettyxml-and-silly-whitespace/#best-solution
        # Issue: http://bugs.python.org/issue4147
        # Patch: http://hg.python.org/cpython/rev/7262f8f276ff/

        from xml.dom.minidom import Element, Text, Node, _write_data

        def writexml(self, writer, indent="", addindent="", newl=""):
            # indent = current indentation
            # addindent = indentation to add to higher levels
            # newl = newline string
            writer.write(indent+"<" + self.tagName)

            attrs = self._get_attributes()
            a_names = attrs.keys()
            a_names.sort()

            for a_name in a_names:
                writer.write(" %s=\"" % a_name)
                _write_data(writer, attrs[a_name].value)
                writer.write("\"")
            if self.childNodes:
                writer.write(">")
                if (len(self.childNodes) == 1 and
                    self.childNodes[0].nodeType == Node.TEXT_NODE):
                    self.childNodes[0].writexml(writer, '', '', '')
                else:
                    writer.write(newl)
                    for node in self.childNodes:
                        node.writexml(writer, indent+addindent, addindent, newl)
                    writer.write(indent)
                writer.write("</%s>%s" % (self.tagName, newl))
            else:
                writer.write("/>%s"%(newl))
        Element.writexml = writexml

        def writexml(self, writer, indent="", addindent="", newl=""):
            _write_data(writer, "%s%s%s"%(indent, self.data, newl))
        Text.writexml = writexml
        # end of the patch

        self.dom = Document()
Example #31
0
 def print(self, printer: Printer):
     doc = TextDocument().add_title("Print menu")
     for request_name in self.all_request_names:
         doc.add_text(request_name).nl()
     printer.print_document(doc)
    async def parseDanMu(self, messages):
        try:
            dic = json.loads(messages)

        except:
            return
        cmd = dic['cmd']

        if cmd == 'PREPARING':

            Printer().printlist_append([
                'join_lottery', '', 'user', "房间 {:^9} 下播!将切换监听房间".format(
                    self._roomId)
            ], True)
            try:
                await utils.reconnect()
            except:
                print("切换房间失败,休眠5s后再次尝试")
                await asyncio.sleep(5)
                await utils.reconnect()

        elif cmd == 'DANMU_MSG':
            # print(dic)
            Printer().printlist_append(['danmu', '弹幕', 'user', dic])
            return
        elif cmd == 'SYS_GIFT':
            try:
                text1 = dic['real_roomid']
                text2 = dic['url']
                Printer().printlist_append([
                    'join_lottery', '', 'user', "检测到房间{:^9}的活动抽奖".format(text1)
                ], True)
                Rafflehandler().append2list_activity(text1)
                Statistics().append2pushed_activitylist()
            except:
                pass
            return
        elif cmd == 'SYS_MSG':
            if set(self.dic_bulletin) == set(dic):
                Printer().printlist_append(
                    ['join_lottery', '系统公告', 'user', dic['msg']])
            else:
                try:
                    TV_url = dic['url']
                    real_roomid = dic['real_roomid']
                    Printer().printlist_append([
                        'join_lottery', '小电视', 'user',
                        "检测到房间{:^9}的广播抽奖".format(real_roomid)
                    ], True)
                    Rafflehandler().append2list_TV(real_roomid)
                    Rafflehandler().append2list_activity(real_roomid)
                    Statistics().append2pushed_TVlist()
                    Statistics().append2pushed_activitylist()
                except:
                    print('SYS_MSG出错,请联系开发者', dic)
            return
        elif cmd == "WELCOME":
            pass
        elif cmd == "SEND_GIFT":
            pass
        elif cmd == "WELCOME_GUARD":
            pass
        elif cmd == "WISH_BOTTLE":
            pass
        elif cmd == "COMBO_END":
            pass
        elif cmd == "ENTRY_EFFECT":
            pass
        elif cmd == "ROOM_RANK":
            pass
        elif cmd == "COMBO_SEND":
            pass
        elif cmd == "ROOM_BLOCK_MSG":
            pass
        elif cmd == "SPECIAL_GIFT":
            pass
        else:
            Printer().printlist_append(
                ['join_lottery', '小电视', 'user', "出现一个未知msg{}".format(dic)],
                True)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2019/9/17 23:06
# @Author  : Dawnnnnnn
# @Contact: [email protected]
import traceback
import aiohttp
import asyncio
import time
from printer import Printer
from uuid import uuid4

printer = Printer()


# 生成获取令牌
def generate_verify_token():
    return str(uuid4()).replace('-', '')


class Request:
    def __init__(self):
        self.proxy_api = "8.8.8.8"
        # 全局session
        self.ssion = {}
        # 工作队列
        self.req_work_list = []
        self.req_done_dict = {}
        self.req_alive_num = 15
        self.req_timeout_max = 15
        self.form_data = aiohttp.FormData()
Example #34
0
 async def login_new(self):
     if bilibili().dic_bilibili['saved-session']['cookie']:
         Printer().printer(f"复用cookie","Info","green")
         bilibili().load_session(bilibili().dic_bilibili['saved-session'])
     else:
         return self.login()
Example #35
0
 async def DoSign(self):
     response = await bilibili().get_dosign()
     temp = await response.json(content_type=None)
     Printer().printer(f"签到状态:{temp['msg']}", "Info", "green")
def change_printer_dic_user():
    new_words = input('弹幕控制')
    if new_words == 'T':
        Printer().dic_user['print_control']['danmu'] = True
    else:
        Printer().dic_user['print_control']['danmu'] = False
Example #37
0
class Spider(object):
    def __init__(self, config):
        """Weibo类初始化"""
        self.config = config
        # change cookie from string to dict
        if type(self.config['cookie']) == type(u''):
            self.config['cookie'] = {
                t.strip().split("=")[0]: t.strip().split("=")[1]
                for t in self.config['cookie'].split(";")
            }
        if type(self.config['user_id_list']) == type(u""):
            user_id_list = self.config['user_id_list']
            if not os.path.isabs(user_id_list):
                user_id_list = os.path.split(
                    os.path.realpath(__file__))[0] + os.sep + user_id_list
            self.config['user_id_list'] = user_id_list
            with open(self.config['user_id_list'], 'rb') as f:
                lines = f.read().splitlines()
                lines = [line.decode('utf-8') for line in lines]
                self.config['user_id_list'] = [
                    line.split(' ')[0] for line in lines if
                    len(line.split(' ')) > 0 and line.split(' ')[0].isdigit()
                ]
        if type(self.config['since_date']) == type(0):
            self.config['since_date'] = str(
                date.today() - timedelta(self.config['since_date']))

        self.validator = Validator(self.config)
        self.validator.validate()
        self.printer = Printer()
        self.writer = Writer(self.config)
        self.downloader = Downloader(self.config)
        self.parser = Parser(self.config)

    def get_nickname(self):
        """获取用户昵称"""
        url = 'https://weibo.cn/%s/info' % (self.user['id'])
        selector = self.parser.deal_html(url, self.config['cookie'])
        nickname = selector.xpath('//title/text()')[0]
        nickname = nickname[:-3]
        if nickname == u'登录 - 新' or nickname == u'新浪':
            write_log(self.config['since_date'])
            sys.exit(u'cookie错误或已过期,请按照README中方法重新获取')
        self.user['nickname'] = nickname

    def get_user_info(self, selector):
        """获取用户昵称、微博数、关注数、粉丝数"""
        self.get_nickname()  # 获取用户昵称
        user_info = selector.xpath("//div[@class='tip2']/*/text()")

        self.user['weibo_num'] = int(user_info[0][3:-1])
        self.user['following'] = int(user_info[1][3:-1])
        self.user['followers'] = int(user_info[2][3:-1])
        self.printer.print_user_info(self.user)
        self.writer.write_user(self.user)
        print('*' * 100)

    def get_one_page(self, page):
        """获取第page页的全部微博"""
        url = 'https://weibo.cn/u/%s?page=%d' % (self.user['id'], page)
        selector = self.parser.deal_html(url, self.config['cookie'])
        info = selector.xpath("//div[@class='c']")
        is_exist = info[0].xpath("div/span[@class='ctt']")
        if is_exist:
            for i in range(0, len(info) - 2):
                weibo = self.parser.get_one_weibo(info[i])
                if weibo:
                    if weibo['id'] in self.weibo_id_list:
                        continue
                    publish_time = datetime.strptime(
                        weibo['publish_time'][:10], "%Y-%m-%d")
                    since_date = datetime.strptime(self.config['since_date'],
                                                   "%Y-%m-%d")
                    if publish_time < since_date:
                        if self.parser.is_pinned_weibo(info[i]):
                            continue
                        else:
                            return True
                    self.printer.print_one_weibo(weibo)

                    self.weibo.append(weibo)
                    self.weibo_id_list.append(weibo['id'])
                    self.got_num += 1
                    print('-' * 100)

                    self.writer.write_weibo([weibo])

    def get_weibo_info(self):
        """获取微博信息"""
        url = 'https://weibo.cn/u/%s' % (self.user['id'])
        selector = self.parser.deal_html(url, self.config['cookie'])
        self.get_user_info(selector)  # 获取用户昵称、微博数、关注数、粉丝数

        page_num = self.parser.get_page_num(selector)  # 获取微博总页数
        page1 = 0
        random_pages = random.randint(1, 5)
        for page in tqdm(range(1, page_num + 1), desc='Progress'):
            is_end = self.get_one_page(page)  # 获取第page页的全部微博
            if is_end:
                break

            # 通过加入随机等待避免被限制。爬虫速度过快容易被系统限制(一段时间后限
            # 制会自动解除),加入随机等待模拟人的操作,可降低被系统限制的风险。默
            # 认是每爬取1到5页随机等待6到10秒,如果仍然被限,可适当增加sleep时间
            if page - page1 == random_pages and page < page_num:
                sleep(random.randint(6, 10))
                page1 = page
                random_pages = random.randint(1, 5)

        if not self.config['filter']:
            print(u'共爬取' + str(self.got_num) + u'条微博')
        else:
            print(u'共爬取' + str(self.got_num) + u'条原创微博')

    def initialize_info(self, user_id):
        """初始化爬虫信息"""
        self.got_num = 0  # 爬取到的微博数
        self.weibo = []  # 存储爬取到的所有微博信息
        self.user = {'id': user_id}  # 存储爬取到的用户信息
        self.weibo_id_list = []  # 存储爬取到的所有微博id

    def start(self):
        """运行爬虫"""
        for user_id in self.config['user_id_list']:
            self.initialize_info(user_id)
            print('*' * 100)
            self.get_weibo_info()
            print(u'信息抓取完毕')
            print('*' * 100)
            if self.config['pic_download'] == 1:
                file_path = get_filepath('img', self.user['nickname'])
                self.downloader.download_files(file_path, 'img', self.weibo)
            if self.config['video_download'] == 1:
                file_path = get_filepath('video', self.user['nickname'])
                self.downloader.download_files(file_path, 'video', self.weibo)
Example #38
0
 def __init__(self):
     self.reset()
     self.printer = Printer()
Example #39
0
 def print(self, printer: Printer):
     chores_document = ChoresBoardDocument()
     printer.print_document(chores_document)
Example #40
0
 def test_reset_error_description(self):
     impresora = Printer()
     impresora.print_job()
     impresora.reset_printer()
     self.assertEqual(impresora.error_description, '')
Example #41
0
 def test_reset_printer_2(self):
     impresora = Printer()
     impresora.reset_printer()
     self.assertFalse(impresora.error_flag)
Example #42
0
 def test_reset_printer_1(self):
     impresora = Printer()
     impresora.reset_printer()
     self.assertEqual(impresora.printing, False)
Example #43
0
     [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
     [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
     [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
     [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
     [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
     [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
     [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
     [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
     [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]],
    [[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
     [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
     [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
     [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
     [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
     [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
     [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
     [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
     [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
     [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
     [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
     [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
     [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
     [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
     [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
     [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]],
]

printerOBJ = Printer(motorX, motorY, motorZ, nozzle, image)

printerOBJ.print_levels()
Example #44
0
def Transform(filename, out):
    lines = open(filename).readlines()

    printer = Printer(out)
    printer.AppendLine("// Generated by inltoas.py. DO NOT EDIT!")
    printer.AppendLine("package sixcube.protocol")
    printer.AppendLine("{")
    printer.IncIndent()
    printer.AppendLine("public final class MessageType")
    printer.AppendLine("{")
    printer.IncIndent()

    re_assign = re.compile("MSGTYPE_DECLARE_ASSIGN\((\S+),\s*(\d+)\)")
    re_declare = re.compile("MSGTYPE_DECLARE\(\s*(\S+)\s*\)")

    msgIdCheck = {}

    index = 0
    for line in lines:
        if "MSGTYPE_BEGIN_BLOCK" in line:
            pass

        # prase assign state
        what = re_assign.match(line)
        if what != None:
            msgName = what.groups()[0]
            assIndex = what.groups()[1]

            comment = GetComment(line)
            index = int(assIndex)

            if msgIdCheck.has_key(index):
                print "[ERROR]same msg id: \n\t[%s = %s]\n\t[%s = %s]" % (
                    msgIdCheck[index], index, msgName, index)
                sys.exit(-1)

            printer.AppendLine("public static var %s:int = %s; // %s" %
                               (msgName, assIndex, comment))
            msgIdCheck[index] = msgName
            continue

        # parse declcare statements
        what = re_declare.match(line)
        if what != None:
            msgName = what.groups()[0]
            comment = GetComment(line)
            assIndex = index + 1

            if msgIdCheck.has_key(assIndex):
                print "[ERROR]same msg id = %s: [%s][%s]\%s" % (
                    assIndex, msgIdCheck[assIndex], msgName)
                sys.exit(-1)

            printer.AppendLine("public static const %s:int = %s; // %s" %
                               (msgName, assIndex, comment))
            msgIdCheck[assIndex] = msgName
            index = assIndex
            continue

        line = line.strip()
        line = line.decode('gbk', 'ignore').encode('utf8')
        if line.startswith("//") or len(line) == 0:
            printer.AppendLine("%s" % line)
        else:
            printer.AppendLine("// %s" % line)

    printer.DecIndent()
    printer.AppendLine("}")
    printer.DecIndent()
    printer.AppendLine("}")
    printer.Flush()
import json
from pprint import pprint
import tensorflow as tf
from datetime import datetime
import re
import os
from printer import Printer

basePath = "/media/suthagar/Data/Corpus/Sep29/"
inputPath = basePath + "pre-processed-files/"
outputPath = basePath + "pre-processed-final-files/"
colocationsPath = basePath + "colocations/"
QUADGRAM_POS_TAG = "QGRAM"
TRIGRAM_POS_TAG = "TGRAM"
BIGRAM_POS_TAG = "BGRAM"
linePrinter = Printer()


def get_wordnet_pos(treebank_tag):
    if treebank_tag.startswith('J'):
        return 'a'
    elif treebank_tag.startswith('V'):
        return 'v'
    elif treebank_tag.startswith('N') and treebank_tag.endswith('S'):
        return 'n'
    elif treebank_tag.startswith('R'):
        return 'r'
    else:
        # all other tags get mapped to x
        return 'x'
Example #46
0
def main():
    load_config()
    p = Printer()
    if len(argv) > 2:
        method = argv[1]
        if method == "info":
            data = station_info(argv[2])
            p.print_station(data)
        elif method == "departures":
            data = station_departures(argv[2])
            if len(argv) == 4:
                p.print_station_departures(data, search=argv[3])
            else:
                p.print_station_departures(data)
        elif method == "load":
            file_path = argv[2]  # gets the file path from second argument
            # get the directory not the file name (will only work on unix filesystems for now)
            directory = file_path.split("/")[1]
            data = json.load(open(file_path))

            if directory == "info":
                p.print_station(data)
            elif directory == "departures":
                p.print_station_departures(data)
            else:
                print("Function not recognised")
        elif method == "save":
            """
			argv[2] = the method to run
			argv[3] = the parameter for selected method
			"""
            # -- getting the data to save
            func = argv[2]
            if func == "info":
                data = station_info(argv[3])
            elif func == "departures":
                data = station_departures(argv[3])
            else:
                print("Function not recognised")
                return

            # -- saving the data to file for later
            dt = datetime.today()
            file_path = os.path.join("saved", argv[2], argv[3])
            # file_path = os.path.abspath(file_path)
            file_name = dt.strftime("%Y-%m-%d_%H-%M") + ".json"
            print("Saving to", file_path)
            # create the file and folders as might be required
            if not os.path.exists(file_path):
                os.makedirs(file_path)
                f = open(os.path.join(file_path, file_name), "x")
            else:
                f = open(os.path.join(file_path, file_name), "w")
            json.dump(data, f)
            f.close()
    else:
        # codes = get_codes("wolverhampton")
        # print(codes, type(codes))
        time = datetime.today()
        print(time.strftime("%Y-%m-%d_%H-%M"))
Example #47
0
def run_main_program():
    LINES_BEFORE = 1
    LINES_AFTER = 1

    l_api: API = None

    Printer.verbose = Parser.verbose
    Printer.debug = Parser.debug
    Printer.log_filename = Parser.log_filename
    Printer.log_level = Parser.log_level
    Printer.log_max_bytes_per_file = Parser.log_max_bytes_per_file
    Printer.log_max_number_log_files = Parser.log_max_number_log_files
    Printer.log_format = Parser.log_format
    Printer.enable_logging()

    if Parser.show_usage:
        lArgParser.print_usage()
        exit(0)

    if Parser.show_examples:
        ExampleUsage.print_example_usage()
        exit(0)

    if Parser.version:
        print_version()
        exit(0)

    if Parser.test_connectivity or Parser.get_account or Parser.get_license or Parser.get_agents or Parser.get_agent_groups or \
        Parser.get_team_members or Parser.get_website_groups or Parser.get_discovered_services or \
        Parser.download_discovered_services or Parser.get_website_groups or Parser.upload_website_groups or \
        Parser.get_websites or Parser.upload_websites or Parser.get_vulnerability_templates or \
        Parser.get_vulnerability_template or Parser.get_vulnerability_types or Parser.ping_sites or \
        Parser.ping_sites_in_file or Parser.report_agents_missing_heartbeat or Parser.report_disabled_agents or \
        Parser.report_issues or Parser.get_scans or Parser.get_scheduled_scans or Parser.get_scans_by_website or \
        Parser.get_website_by_url or Parser.get_website_by_name or Parser.get_website_by_id or \
        Parser.get_websites_by_group_name or Parser.get_websites_by_group_id or Parser.get_technologies or \
        Parser.get_obsolete_technologies or Parser.get_scan_profiles or Parser.get_scan_profile or \
        Parser.get_account_managers or Parser.get_api_accounts or Parser.get_scan_accounts or \
        Parser.get_disabled_accounts or Parser.get_account_owners or Parser.get_team_member or \
        Parser.get_scan_results or Parser.upload_team_members or Parser.create_team_member or \
        Parser.get_roles or Parser.get_permissions or Parser.get_role or Parser.delete_team_member or \
        Parser.get_unused_accounts or Parser.get_teams or Parser.get_issues or Parser.download_issues or \
        Parser.report_bsc or Parser.get_unpatched_issues:
        l_api = API(p_parser=Parser)
    else:
        lArgParser.print_usage()
        Printer.print("Required arguments not provided", Level.ERROR,
                      Force.FORCE, LINES_BEFORE, LINES_AFTER)

    if Parser.test_connectivity:
        l_api.test_connectivity()
        exit(0)

    if Parser.get_account:
        l_api.get_account()
        exit(0)

    if Parser.get_license:
        l_api.get_license()
        exit(0)

    if Parser.get_agents:
        l_api.get_agents()
        exit(0)

    if Parser.get_agent_groups:
        l_api.get_agent_groups()
        exit(0)

    if Parser.get_issues:
        l_api.get_issues()
        exit(0)

    if Parser.get_unpatched_issues:
        l_api.get_unpatched_issues()
        exit(0)

    if Parser.download_issues:
        if not Parser.output_filename:
            lArgParser.print_usage()
            Printer.print("Required argument --output-file not provided",
                          Level.ERROR, Force.FORCE, LINES_BEFORE, LINES_AFTER)
            exit(0)
        l_api.download_issues()
        exit(0)

    if Parser.get_roles:
        l_api.get_roles()
        exit(0)

    if Parser.get_permissions:
        l_api.get_permissions()
        exit(0)

    if Parser.get_role:
        if not Parser.role_id:
            lArgParser.print_usage()
            Printer.print("-rid, --role-id is required but not provided",
                          Level.ERROR, Force.FORCE, LINES_BEFORE, LINES_AFTER)
            exit(0)
        l_api.get_role()
        exit(0)

    if Parser.get_teams:
        l_api.get_teams()
        exit(0)

    if Parser.get_team_member:
        if not Parser.team_member_id and not Parser.team_member_email:
            lArgParser.print_usage()
            Printer.print(
                "Either -tmid, --team-member-id or -tme, --team-member-email required but not provided",
                Level.ERROR, Force.FORCE, LINES_BEFORE, LINES_AFTER)
            exit(0)
        l_api.get_team_member()
        exit(0)

    if Parser.get_team_members:
        l_api.get_team_members()
        exit(0)

    if Parser.create_team_member:
        if not (Parser.team_member_name and Parser.team_member_email and
                Parser.team_member_sso_email and Parser.team_member_groups):
            lArgParser.print_usage()
            Printer.print(
                "Requires -tmn, --team-member-name, -tme, --team-member-email, -tmsso, --team-member-sso-email, and -tmg, --team-member-groups",
                Level.ERROR, Force.FORCE, LINES_BEFORE, LINES_AFTER)
            exit(0)
        l_api.create_team_member()
        exit(0)

    if Parser.delete_team_member:
        if not (Parser.team_member_id):
            lArgParser.print_usage()
            Printer.print("Requires -tmid, --team-member-id", Level.ERROR,
                          Force.FORCE, LINES_BEFORE, LINES_AFTER)
            exit(0)
        l_api.delete_team_member()
        exit(0)

    if Parser.upload_team_members:
        if not Parser.input_filename:
            lArgParser.print_usage()
            Printer.print("Required argument --input-file not provided",
                          Level.ERROR, Force.FORCE, LINES_BEFORE, LINES_AFTER)
            exit(0)
        l_api.upload_team_members()
        exit(0)

    if Parser.get_account_managers:
        l_api.get_account_managers()
        exit(0)

    if Parser.get_account_owners:
        l_api.get_account_owners()
        exit(0)

    if Parser.get_api_accounts:
        l_api.get_api_accounts()
        exit(0)

    if Parser.get_scan_accounts:
        l_api.get_scan_accounts()
        exit(0)

    if Parser.get_disabled_accounts:
        l_api.get_disabled_accounts()
        exit(0)

    if Parser.get_unused_accounts:
        l_api.get_unused_accounts()
        exit(0)

    if Parser.get_technologies:
        l_api.get_technologies()
        exit(0)

    if Parser.get_obsolete_technologies:
        l_api.get_obsolete_technologies()
        exit(0)

    if Parser.get_website_groups:
        l_api.get_website_groups()
        exit(0)

    if Parser.upload_website_groups:
        if not Parser.input_filename:
            lArgParser.print_usage()
            Printer.print("Required argument --input-file not provided",
                          Level.ERROR, Force.FORCE, LINES_BEFORE, LINES_AFTER)
            exit(0)
        l_api.upload_website_groups()
        exit(0)

    if Parser.get_discovered_services:
        l_api.get_discovered_services()
        exit(0)

    if Parser.download_discovered_services:
        if not Parser.output_filename:
            lArgParser.print_usage()
            Printer.print("Required argument --output-file not provided",
                          Level.ERROR, Force.FORCE, LINES_BEFORE, LINES_AFTER)
            exit(0)
        l_api.download_discovered_services()
        exit(0)

    if Parser.get_website_by_url:
        if not Parser.website_url:
            lArgParser.print_usage()
            Printer.print(
                "Required argument -wurl, --website-url not provided",
                Level.ERROR, Force.FORCE, LINES_BEFORE, LINES_AFTER)
            exit(0)
        l_api.get_website_by_url()
        exit(0)

    if Parser.get_website_by_name:
        if not Parser.website_name:
            lArgParser.print_usage()
            Printer.print("Required argument -wn, --website-name not provided",
                          Level.ERROR, Force.FORCE, LINES_BEFORE, LINES_AFTER)
            exit(0)
        l_api.get_website_by_name()
        exit(0)

    if Parser.get_website_by_id:
        if not Parser.website_id:
            lArgParser.print_usage()
            Printer.print("Required argument -wid, --website-id not provided",
                          Level.ERROR, Force.FORCE, LINES_BEFORE, LINES_AFTER)
            exit(0)
        l_api.get_website_by_id()
        exit(0)

    if Parser.get_websites:
        l_api.get_websites()
        exit(0)

    if Parser.get_websites_by_group_name:
        if not Parser.website_group_name:
            lArgParser.print_usage()
            Printer.print(
                "Required argument -wgn, --website-group-name not provided",
                Level.ERROR, Force.FORCE, LINES_BEFORE, LINES_AFTER)
            exit(0)
        l_api.get_websites_by_group_name()
        exit(0)

    if Parser.get_websites_by_group_id:
        if not Parser.website_group_id:
            lArgParser.print_usage()
            Printer.print(
                "Required argument -wgid, --website-group-id not provided",
                Level.ERROR, Force.FORCE, LINES_BEFORE, LINES_AFTER)
            exit(0)
        l_api.get_websites_by_group_id()
        exit(0)

    if Parser.upload_websites:
        if not Parser.input_filename:
            lArgParser.print_usage()
            Printer.print("Required argument --input-file not provided",
                          Level.ERROR, Force.FORCE, LINES_BEFORE, LINES_AFTER)
            exit(0)
        l_api.upload_websites()
        exit(0)

    if Parser.get_vulnerability_templates:
        l_api.get_vulnerability_templates()
        exit(0)

    if Parser.get_vulnerability_template:
        if not Parser.vulnerability_type:
            lArgParser.print_usage()
            Printer.print(
                "Required argument -vt, --vulnerability-type not provided",
                Level.ERROR, Force.FORCE, LINES_BEFORE, LINES_AFTER)
            exit(0)
        l_api.get_vulnerability_template()
        exit(0)

    if Parser.get_vulnerability_types:
        l_api.get_vulnerability_types()
        exit(0)

    if Parser.ping_sites:
        l_api.ping_sites()
        exit(0)

    if Parser.ping_sites_in_file:
        if not Parser.input_filename:
            lArgParser.print_usage()
            Printer.print("Required argument --input-file not provided",
                          Level.ERROR, Force.FORCE, LINES_BEFORE, LINES_AFTER)
            exit(0)
        l_api.ping_sites_in_file()
        exit(0)

    if Parser.report_agents_missing_heartbeat:
        exit(l_api.report_agents_missing_heartbeat())

    if Parser.report_disabled_agents:
        exit(l_api.report_disabled_agents())

    if Parser.get_scans:
        l_api.get_scans()
        exit(0)

    if Parser.get_scheduled_scans:
        l_api.get_scheduled_scans()
        exit(0)

    if Parser.get_scans_by_website:
        if not Parser.website_url and not Parser.target_url:
            lArgParser.print_usage()
            Printer.print(
                "Either -wurl, --website-url or -turl, --target-url or both required",
                Level.ERROR, Force.FORCE, LINES_BEFORE, LINES_AFTER)
            exit(0)
        l_api.get_scans_by_website()
        exit(0)

    if Parser.get_scan_profile:
        if not Parser.scan_profile_id and not Parser.scan_profile_name:
            lArgParser.print_usage()
            Printer.print(
                "Either -spid, --scan-profile-id or -spn, --scan-profile-name required",
                Level.ERROR, Force.FORCE, LINES_BEFORE, LINES_AFTER)
            exit(0)
        l_api.get_scan_profile()
        exit(0)

    if Parser.get_scan_profiles:
        l_api.get_scan_profiles()
        exit(0)

    if Parser.get_scan_results:
        if not Parser.scan_id:
            lArgParser.print_usage()
            Printer.print("-sid, --scan-id required", Level.ERROR, Force.FORCE,
                          LINES_BEFORE, LINES_AFTER)
            exit(0)
        l_api.get_scan_results()
        exit(0)

    if Parser.report_issues:
        l_api.report_issues()
        exit(0)

    if Parser.report_bsc:
        l_api.report_bsc()
        exit(0)
Example #48
0
from OnlineHeart import OnlineHeart
from Silver import Silver
from LotteryResult import LotteryResult
from Tasks import Tasks
from connect import connect
import asyncio
import utils
from printer import Printer
from statistics import Statistics
from bilibili import bilibili
import threading
import biliconsole

# print('Hello world.')
printer = Printer()
bilibili()
Statistics()

utils.fetch_user_info()
utils.fetch_bag_list()
utils.fetch_medal()

task = OnlineHeart()
task1 = Silver()
task2 = Tasks()
task3 = LotteryResult()
task4 = connect()

console_thread = threading.Thread(target=biliconsole.controler)

console_thread.start()
Example #49
0
 async def sliver2coin(self):
     if self.dic_user['coin']['on/off'] == '1':
         response1 = await bilibili().silver2coin_app()
         json_response1 = await response1.json()
         Printer().printer(f"银瓜子兑换硬币状态:{json_response1['msg']}", "Info",
                           "green")
 i = 0
 accounts = []
 for requestor in requestors:
     i += 1
     accounts.append(requestor.getAccount())
     print(str(i) + ") " + requestor.getAccount())
 print("0) Exit")
 answer = raw_input("Which account to delete (1-" + str(i) + ") ? ")
 if (answer.isdigit() and int(answer) <= i and int(answer) >= 1):
     if (Auth.DeleteAccount(accounts[int(answer) - 1]) == None):
         print(accounts[int(answer) - 1] + " deleted.")
         deleteprintersanswer = raw_input(
             "Also delete associated printers? ")
         if deleteprintersanswer.startswith(
                 "Y") or deleteprintersanswer.startswith("y"):
             printer = Printer(requestors)
             printers, connection = printer.getCUPSPrintersForAccount(
                 accounts[int(answer) - 1])
             if len(printers) == 0:
                 print "No printers to delete"
             else:
                 for cupsPrinter in printers:
                     print "Deleting " + cupsPrinter['printer-info']
                     deleteReturnValue = connection.deletePrinter(
                         cupsPrinter['printer-info'])
                     if deleteReturnValue != None:
                         print "Error deleting printer: " + str(
                             deleteReturnValue)
         else:
             print "Not deleting associated printers"
     else:
Example #51
0
 async def Daily_Task(self):
     response2 = await bilibili().get_dailytask()
     json_response2 = await response2.json()
     Printer().printer(f"双端观看直播:{json_response2['msg']}", "Info", "green")
Example #52
0
class GRunner(object):
	def __init__(self, argv):
		self.sc = None
		self.cfg = Config("kamaq.conf")
		self.dim = self.cfg.settings["num_motors"]
		self.audiodev = self.cfg.settings["sound_device"]
		cmd = None
		vec = [0.0 for x in range(self.dim)]
		speed = 3600.0
		self.limit = None
		self.speed_scale = 1.0
		self.temp = None
		self.btemp = None
		self.pid = {}
		self.zero_extruder = False
		self.webui = None
		while True:
			try:
				a = argv.pop(0)
			except IndexError:
				break
			if a == "-i":
				fname = argv.pop(0)
				cmd = a
			elif a == "-g":
				cmd = a
			elif a == "-H":
				cmd = a
			elif a == "-x":
				vec[0] = float(argv.pop(0))
			elif a == "-y":
				vec[1] = float(argv.pop(0))
			elif a == "-z":
				vec[2] = float(argv.pop(0))
			elif a == "-e":
				vec[3] = float(argv.pop(0))
			elif a == "-f":
				speed = float(argv.pop(0))
			elif a == "-h" or a == "--help":
				self.print_help()
				return
			elif a == "-s":
				self.speed_scale = float(argv.pop(0))
			elif a == "-t":
				self.temp = float(argv.pop(0))
			elif a == "-b":
				self.btemp = float(argv.pop(0))
			elif a == "-l":
				self.limit = float(argv.pop(0)) / 60.0
			elif a == "-w":
				#self.webui = WebUi(self.printer)
				#self.printer.add_webui(self.webui)
				self.run_webui()
			elif a == "--no-extrusion":
				self.zero_extruder = True
			else:
				print("Unknown command-line option:", a)
				return
		signal.signal(signal.SIGINT, self.signal_handler)
		self.loop = asyncio.get_event_loop()
		if cmd == None:
			return
		elif cmd == "-i":
			print("Executing G-Code file:", fname)
			self.run_file(fname)
		elif cmd == "-g":
			print("Executing single movement to:", repr(vec), "at speed:", speed)
			self.move_to(vec, speed)
		elif cmd == "-H":
			self.homing()
		else:
			print("Error: Unimplemented command:", cmd)
			return
		self.loop.run_forever()

	def print_help(self):
		name = sys.argv[0]
		print("%s: G-Code runner" % (name))
		print("Syntax:")
		print("   %s [-i <filename>|-g|-H] [options]\n" % (name))
		print("Commands:")
		print(" -i <filename>     : Execute all G-codes from file <filename>")
		print(" -g                : Process one move")
		print(" -H                : Home position")
		print("\nCommon options:")
		print(" -t <temp>         : Set extruder temperature")
		print(" -b <temp>         : Set heated bed temperature")
		print(" -w                : Launch web interface")
		print("\nOptions for command -g:")
		print(" -x <num>          : Move to X-coordinate <num> in millimeters (default 0)")
		print(" -y <num>          : Y-coordinate")
		print(" -z <num>          : Z-coordinate")
		print(" -e <num>          : Extruder movement")
		print(" -f <speed>        : Feedrate in mm/minute")
		print("\nOptions for command -i:")
		print(" -s <factor>       : Speed scale factor (default 1.0)")
		print(" -l <limit>        : Set feedrate limit")
		print(" --no-extrusion    : Do not move extruder")

	def end_of_file(self):
		print("EOF")
		if not self.webui:
			self.shutdown()

	def shutdown(self):
		self.printer.shutdown()
		if self.sc is not None:
			self.sc.zero_output()
			self.sc.zero_output()
			self.sc.zero_output()
			self.sc.zero_output()
			self.sc.close()
		sys.exit(0)

	def run_webui(self):
		signal.signal(signal.SIGINT, self.signal_handler)
		self.loop = asyncio.get_event_loop()
		sc = StepperCluster(self.audiodev, self.dim, self.cfg)
		self.printer = Printer(self.cfg, sc)
		self.webui = WebUi(self.printer)
		self.printer.add_webui(self.webui)
		self.printer.run()

	def signal_handler(self, signal, frame):
		print('You pressed Ctrl+C!')
		self.shutdown()

	def preheat(self):
		if not self.temp and not self.btemp:
			return
		pids = []
		if self.temp:
			pids.append(("ext", self.temp))
		if self.btemp:
			pids.append(("bed", self.btemp))
		for name, sp in pids:
			self.printer.launch_pid(name, sp)
		while True:
			leave = True
			for name, sp in pids:
				tmp = self.printer.get_temperature(name)
				if tmp < (sp - 3.0):
					leave = False
				print(name+": temp =", tmp, "sp =", sp, end=' ')
			print("")
			self.loop.run_until_complete(asyncio.sleep(1))
			if leave:
				break
		# Add some delay here to ensure good heat distribution/melting
		print("Setpoint reached.")
		for i in range(30):
			for name, sp in pids:
				tmp = self.printer.get_temperature(name)
				print(name+": temp =", tmp, "sp =", sp, end=' ')
			print("")
			self.loop.run_until_complete(asyncio.sleep(1))

	def move_to(self, vec, speed):
		print("Currently not supported. Use the web interface!")
		return
		cmd = "G1 "
		for v, n in zip(vec, ["X", "Y", "Z", "E"]):
			cmd += n + str(v) + " "
		cmd += "F" + str(speed) + " "
		f = StringIO(cmd + "\n")
		self.run_file(f)

	def run_file(self, fname):
		print("Currently not supported. Use the web interface!")
		return
		g = GCode(self.cfg, fname)
		g.set_zero_extruder(self.zero_extruder)
		m = Move(self.cfg, g, self.printer)
		self.preheat()
		self.sc = StepperCluster(self.audiodev, self.dim, self.cfg, m)
		self.sc.set_speed_scale(self.speed_scale)
		self.sc.set_max_feedrate(self.limit)
		self.scd = StepperClusterDispatcher(self.sc, self)

	def homing(self):
		f = StringIO("G28\n")
		self.run_file(f)
Example #53
0
from OnlineHeart import OnlineHeart
from Silver import Silver
from LotteryResult import LotteryResult
from Tasks import Tasks
from login import Login
from connect import connect
import asyncio
from API import API
from configloader import ConfigLoader
from printer import Printer
from bilibili import bilibili

cf = ConfigLoader("color.conf", "user.conf", "bilibili.conf")
printer = Printer(cf)
bilibili = bilibili(cf)
login = Login(bilibili)
login.success()

bilibili = login.return_bilibili()
api = API(bilibili)
api.user_info()
api.get_bag_list()
task = OnlineHeart(bilibili)
task1 = Silver(bilibili)
task2 = Tasks(bilibili)
task3 = LotteryResult(bilibili)
task4 = connect(printer, bilibili, api)

tasks = [
    task.run(),
    task1.run(),
Example #54
0
 def setUp(self):
     self.impresora = Printer()
Example #55
0
def parse_command_line(args):
    """Command line argument parser for configure."""
    description = """Within build_directory (--build-dir), runs cmake on test
specification directories (from --test-spec-dir or --xml-test-list), then
builds and runs the tests defined via CMake."""
    parser = argparse.ArgumentParser(description=description)

    CIME.utils.setup_standard_logging_options(parser)

    parser.add_argument(
        "--build-dir",
        default=".",
        help=
        """Directory where tests are built and run. Will be created if it does not exist."""
    )

    parser.add_argument("--build-optimized",
                        action="store_true",
                        help="""By default, tests are built with debug flags.
                        If this option is provided, then tests are instead built
                        in optimized mode.""")

    parser.add_argument("--machine",
                        help="The machine to create build information for.")

    parser.add_argument(
        "--machines-dir",
        help="The machines directory to take build information "
        "from. Overrides the CIME_MODEL environment variable, "
        "and must be specified if that variable is not set.")

    parser.add_argument(
        "--clean",
        action="store_true",
        help="""Clean build directory before building. Removes CMake cache and
runs "make clean".""")
    parser.add_argument("--cmake-args",
                        help="""Additional arguments to pass to CMake.""")
    parser.add_argument("--color",
                        action="store_true",
                        default=sys.stdout.isatty(),
                        help="""Turn on colorized output.""")
    parser.add_argument("--no-color",
                        action="store_false",
                        help="""Turn off colorized output.""")
    parser.add_argument(
        "--compiler",
        help="""Compiler vendor for build (supported depends on machine).
                        If not specified, use the default for this machine.""")
    parser.add_argument(
        "--enable-genf90",
        action="store_true",
        default=True,
        help="""Use genf90.pl to regenerate out-of-date sources from .F90.in
templates.

Not enabled by default because it creates in-source output, and because it
requires genf90.pl to be in the user's path.""")

    parser.add_argument("--make-j",
                        type=int,
                        default=8,
                        help="""Number of processes to use for build.""")

    parser.add_argument(
        "--use-mpi",
        action="store_true",
        help="""If specified, run unit tests with an mpi-enabled version
                        of pFUnit, via mpirun. (Default is to use a serial build without
                        mpirun.) This requires a pFUnit build with MPI support."""
    )

    parser.add_argument("--mpilib",
                        help="""MPI Library to use in build.
                        If not specified, use the default for this machine/compiler.
                        Must match an MPILIB option in config_compilers.xml.
                        e.g., for cheyenne, can use 'mpt'.
                        Only relevant if --use-mpi is specified.""")

    parser.add_argument("--mpirun-command",
                        help="""Command to use to run an MPI executable.
                        If not specified, uses the default for this machine.
                        Only relevant if --use-mpi is specified.""")
    parser.add_argument("--test-spec-dir",
                        default=".",
                        help="""Location where tests are specified.
        Defaults to current directory.""")
    parser.add_argument("-T",
                        "--ctest-args",
                        help="""Additional arguments to pass to CTest.""")
    parser.add_argument(
        "--use-env-compiler",
        action="store_true",
        default=False,
        help="""Always use environment settings to set compiler commands.

This is only necessary if using a CIME build type, if the user wants to
override the command provided by Machines.""")
    parser.add_argument("--use-openmp",
                        action="store_true",
                        help="""If specified, include OpenMP support for tests.
        (Default is to run without OpenMP support.) This requires a pFUnit build with
        OpenMP support.""")
    parser.add_argument(
        "--xml-test-list",
        help="""Path to an XML file listing directories to run tests from.""")

    args = CIME.utils.parse_args_and_handle_standard_logging_options(
        args, parser)
    output = Printer(color=args.color)

    if args.xml_test_list is None and args.test_spec_dir is None:
        output.print_error(
            "You must specify either --test-spec-dir or --xml-test-list.")
        raise Exception("Missing required argument.")

    if args.make_j < 1:
        raise Exception("--make-j must be >= 1")

    return output, args.build_dir, args.build_optimized, args.clean,\
        args.cmake_args, args.compiler, args.enable_genf90, args.machine, args.machines_dir,\
        args.make_j, args.use_mpi, args.mpilib, args.mpirun_command, args.test_spec_dir, args.ctest_args,\
        args.use_openmp, args.xml_test_list, args.verbose
Example #56
0
    async def parseDanMu(self, messages):
        try:
            dic = json.loads(messages)

        except:
            return
        cmd = dic['cmd']

        if cmd == 'PREPARING':

            Printer().printer(f"房间 {self._roomId} 下播!将切换监听房间", "Info", "green")
            try:
                await utils.reconnect()
            except:
                Printer().printer(f"切换房间失败,休眠5s后再次尝试", "Error", "red")
                await asyncio.sleep(5)
                await utils.reconnect()

        elif cmd == 'DANMU_MSG':
            Printer().printer(f"{dic}", "Message", "Cyan", printable=False)
            return
        elif cmd == 'SYS_GIFT':
            try:
                Printer().printer(f"出现了远古的SYS_GIFT,请尽快联系开发者{dic}", "Warning", "red")
            except:
                pass
            return
        elif cmd == 'SYS_MSG':
            if set(self.dic_bulletin) == set(dic):
                Printer().printer(dic['msg'], "Info", "green")
            else:
                try:
                    real_roomid = dic['real_roomid']
                    Printer().printer(f"检测到房间 {real_roomid} 的广播抽奖", "Lottery", "blue")
                    Rafflehandler().append2list_TV(real_roomid)
                    Statistics().append2pushed_TVlist()
                except:
                    print('SYS_MSG出错,请联系开发者', dic)
            return
        elif cmd == "WELCOME":
            pass
        elif cmd == "SEND_GIFT":
            pass
        elif cmd == "WELCOME_GUARD":
            pass
        elif cmd=="WELCOME_ACTIVITY":      #欢迎来到活动
            pass
        elif cmd == "WISH_BOTTLE":
            pass
        elif cmd == "COMBO_END":
            pass
        elif cmd == "ENTRY_EFFECT":
            pass
        elif cmd == "ROOM_RANK":
            pass
        elif cmd == "COMBO_SEND":
            pass
        elif cmd == "ROOM_BLOCK_MSG":
            pass
        elif cmd == "SPECIAL_GIFT":
            pass
        elif cmd == "NOTICE_MSG":
            pass
        elif cmd == "GUARD_MSG":
            pass
        elif cmd == "GUARD_BUY":
            pass
        elif cmd == "GUARD_LOTTERY_START":
            pass
        elif cmd == "PK_INVITE_INIT":
            pass
        elif cmd == "PK_CLICK_AGAIN":
            pass
        elif cmd == "PK_AGAIN":
            pass
        elif cmd == "PK_MATCH":  # pk匹配
            pass
        elif cmd == "PK_MIC_END":
            pass
        elif cmd == "PK_PRE":  # pk预备阶段
            pass
        elif cmd == "LIVE":  # 开播
            pass
        elif cmd == "PK_PROCESS":  # pk 过程值
            pass
        elif cmd == "PK_END":  # pk结束
            pass
        elif cmd == "PK_SETTLE":  # pk settle
            pass
        elif cmd == "PK_START":  # pk开始
            pass
        elif cmd == "ACTIVITY_EVENT":  # 没有用的充能值信息
            pass
        elif cmd == "WARNING":  # {'cmd': 'WARNING', 'msg': '违反直播分区规范,请立即更换至游戏区', 'roomid': 69956}
            pass
        elif cmd == "RAFFLE_END":  # 抽奖结束
            pass
        elif cmd == "RAFFLE_START":  # 抽奖开始
            pass
        elif cmd=="ROOM_SHIELD":             #未知msg{'cmd': 'ROOM_SHIELD', 'type': 1, 'user': '', 'keyword': '', 'roomid': 3051144}
            pass
        elif cmd == "TV_START":             # 未知msg{'cmd': 'TV_START', 'data': {'id': '159720', 'dtime': 180, 'msg': {'cmd': 'SYS_MSG', 'msg': 'もやしパワー:? 送给:? 管珩心-中间的字念横:? 1个小电视飞船
            pass
        elif cmd == "TV_END":               #未知msg{'cmd': 'TV_END', 'data': {'id': '159720', 'uname': '顾惜大哥哥', 'sname': 'もやしパワー', 'giftName': '100000x银瓜子', 'mobileTips': '恭喜 顾惜大哥哥 获得100000x银瓜子'
            pass
        elif cmd == "ROOM_ADMINS":         #未知msg{'cmd': 'ROOM_ADMINS', 'uids': [25866878, 7026393, 240404878, 52054996]}
            pass
        elif cmd=="ROOM_SILENT_ON":         #msg{'cmd': 'ROOM_SILENT_ON', 'data': {'type': 'level', 'level': 1, 'second': -1}, 'roomid': 5225}
            pass
        elif cmd=="ROOM_SILENT_OFF":        #msg{'cmd': 'ROOM_SILENT_OFF', 'data': [], 'roomid': 5225}
            pass
        else:
            Printer().printer(f"出现一个未知msg{dic}", "Info", "red")
            pass
 async def draw_lottery(self):
     black_list = [
         "123",
         "1111",
         "测试",
         "測試",
         "测一测",
         "ce-shi",
         "test",
         "T-E-S-T",
         "lala",
         "我是抽奖标题",
         "压测",  # 已经出现
         "測一測",
         "TEST",
         "Test",
         "t-e-s-t"
     ]  # 合理猜想
     former_lottery = queue.Queue(maxsize=4)
     [former_lottery.put(True) for _ in range(4)]
     for i in range(450, 600):
         response = await bilibili().get_lotterylist(i)
         json_response = await response.json()
         former_lottery.get()
         former_lottery.put(not json_response['code'])
         if json_response['code'] == 0:
             title = json_response['data']['title']
             check = len(json_response['data']['typeB'])
             for g in range(check):
                 join_end_time = json_response['data']['typeB'][g][
                     'join_end_time']
                 join_start_time = json_response['data']['typeB'][g][
                     'join_start_time']
                 status = json_response['data']['typeB'][g]['status']
                 ts = CurrentTime()
                 if int(join_end_time) > int(ts) > int(
                         join_start_time) and status == 0:
                     jp_list = '&'.join([
                         jp['jp_name']
                         for jp in json_response['data']['typeB'][g]['list']
                     ])
                     for k in black_list:
                         if k in title or k in jp_list:
                             Printer().printer(f"检测到 {i} 号疑似钓鱼类测试抽奖『{title}>>>{jp_list}』" + \
                                                ",默认不参与,请自行判断抽奖可参与性","Warning","red")
                             break
                     else:
                         if bilibili().black_status:
                             Printer().printer(
                                 f"黑屋休眠,跳过『{title}>>>{jp_list}』抽奖", "Info",
                                 "green")
                             continue
                         response1 = await bilibili().get_gift_of_lottery(
                             i, g)
                         json_response1 = await response1.json(
                             content_type=None)
                         Printer().printer(
                             f"参与『{title}>>>{jp_list}』抽奖回显: {json_response1}",
                             "Lottery", "cyan")
                         start_time = json_response['data']['typeB'][g][
                             "startTime"]
                         asyncio.ensure_future(
                             self.check_winner(i, g, start_time))
         else:
             if not any(former_lottery.queue):  # 检查最近4个活动id是否都-400
                 break
         await asyncio.sleep(0.2)
     del former_lottery
Example #58
0
if not os.path.exists(libpath):
    libpath = "/usr/lib/cloudprint-cups"
sys.path.insert(0, libpath)

from auth import Auth
from printer import Printer


def showUsage():
    sys.stderr.write("ERROR: Usage: " + sys.argv[0] +
                     " [list|cat drivername]\n")
    sys.exit(1)


requestors, storage = Auth.SetupAuth(False)
printer = Printer(requestors)
printers = printer.getPrinters(True)
if printers == None:
    print("ERROR: No Printers Found")
    sys.exit(1)

if (len(sys.argv) < 2):
    showUsage()

if sys.argv[1] == 'list':
    for foundprinter in printers:
        print(
            '"cupscloudprint:' + foundprinter['account'].encode(
                'ascii', 'replace').replace(' ', '-') + ':' +
            foundprinter['name'].encode('ascii', 'replace').replace(' ', '-') +
            '.ppd" en "Google" "' +
Example #59
0
 def test_printer_False_available(self):
     impresora = Printer()
     impresora.add_print_job('Imprimir')
     impresora.print_job()
     self.assertFalse(impresora.printer_available())
Example #60
0
 def print(self, printer: Printer):
     document = TextDocument().add_text(self.text)
     printer.print_document(document)