Ejemplo n.º 1
0
class DataAnalyzer:
    """
    This class is used to analyze the data collected from the cookies or the url referer
    """

    def __init__(self):
        self.cookiesforsite = []
        self.p = Printer("console", False)
        #Store the sites we have browsed
        self.sites = list()

    def openfile(self, path):
        """
        Open the file of website order and generate a list of the parameters
        """
        listparams = []

        # Open the file with the order of the websites
        try:
            with open(path, 'r') as f:
                # For each website
                for line in f:
                    stripn = line.strip('\n').split(',')
                    listparams.append(stripn)

            return listparams
        except IOError, e:
            self.p.printer("I/O error({0}): {1}".format(e.errno, e.strerror))
Ejemplo n.º 2
0
    def __init__(self, args):

        self.options = {
            'url': args.url,
            'prefix': '',
            'user_agent': args.user_agent,
            'proxy': args.proxy,
            'verbosity': args.verbosity,
            'threads': 10,
            'chunk_size': 10,  # same as threads
            'run_all': args.run_all,
            'match_all': args.match_all,
            'stop_after': args.stop_after,
            'no_cache_load': args.no_cache_load,
            'no_cache_save': args.no_cache_save,
        }

        self.data = {
            'cache': Cache(),
            'results': Results(self.options),
            'fingerprints': Fingerprints(),
            'matcher': Match(),
            'colorizer': Color(),
            'printer': Printer(args.verbosity, Color()),
            'detected_cms': set(),
            'error_pages': set(),
            'queue': queue.Queue(),
            'requested': queue.Queue()
        }

        self.data['results'].set_printer(self.data['printer'])
        self.data['requester'] = Requester(self.options, self.data)
Ejemplo n.º 3
0
Archivo: wig.py Proyecto: xstpl/wig
    def __init__(self, args):
        urls = None
        if args.input_file is not None:
            args.quiet = True

            with open(args.input_file, 'r') as input_file:
                urls = []
                for url in input_file.readlines():
                    url = url.strip()
                    urls.append(url if '://' in url else 'http://' + url)

        else:
            args.url = args.url.lower()
            if '://' not in args.url:
                args.url = 'http://' + args.url

        text_printer = Printer(args.verbosity)
        cache = Cache()
        cache.printer = text_printer

        self.options = {
            'url': args.url,
            'urls': urls,
            'quiet': args.quiet,
            'prefix': '',
            'user_agent': args.user_agent,
            'proxy': args.proxy,
            'verbosity': args.verbosity,
            'threads': 10,
            'batch_size': 20,
            'run_all': args.run_all,
            'match_all': args.match_all,
            'stop_after': args.stop_after,
            'no_cache_load': args.no_cache_load,
            'no_cache_save': args.no_cache_save,
            'write_file': args.output_file,
            'subdomains': args.subdomains
        }

        self.data = {
            'cache': cache,
            'results': Results(self.options),
            'fingerprints': Fingerprints(),
            'matcher': Match(),
            'printer': text_printer,
            'detected_cms': set(),
            'error_pages': set(),
            'requested': queue.Queue()
        }

        if self.options['write_file'] is not None:
            self.json_outputter = OutputJSON(self.options, self.data)

        self.data['printer'].print_logo()

        self.results = None
Ejemplo n.º 4
0
 def __init__(self):
     self.difficulties = '12345'
     self.difficulty = 5
     self.refresh_speed = 1.25
     self.refresh_speed_interval = 0.25
     self.slowest_refresh_rate = (len(self.difficulties) +
                                  1) * self.refresh_speed_interval
     self.fastest_refresh_rate = self.refresh_speed_interval
     self.signal = signal
     self.signal.signal(signal.SIGALRM, self.raise_exception)
     self.field_size = 4
     self.user_input = None
     self.prompt_difficulty()
     self.cells = [(i, j) for i in list(xrange(self.field_size))
                   for j in list(xrange(self.field_size))]
     self.apple = Apple(self.cells)
     self.snake = Snake(self.field_size, self.cells, self.apple)
     self.printer = Printer(self.snake, self.apple, self.refresh_speed,
                            self.difficulty)
Ejemplo n.º 5
0
Archivo: wig.py Proyecto: r00tb0x/wig
    def __init__(self, args):

        urls = None
        interactive = True

        if args.input_file is not None:
            interactive = False

            with open(args.input_file, 'r') as input_file:
                urls = []
                for url in input_file.readlines():
                    u = url.strip()
                    urls.append(u if '://' in u else 'http://' + u)

        elif '://' not in args.url:
            args.url = 'http://' + args.url

        self.options = {
            'url': args.url,
            'urls': urls,
            'interactive': interactive,
            'prefix': '',
            'user_agent': args.user_agent,
            'proxy': args.proxy,
            'verbosity': args.verbosity,
            'threads': 10,
            'batch_size': 20,
            'run_all': args.run_all,
            'match_all': args.match_all,
            'stop_after': args.stop_after,
            'no_cache_load': args.no_cache_load,
            'no_cache_save': args.no_cache_save,
            'write_file': args.output_file
        }

        self.data = {
            'cache': Cache(),
            'results': Results(self.options),
            'fingerprints': Fingerprints(),
            'matcher': Match(),
            'colorizer': Color(),
            'printer': Printer(args.verbosity, Color()),
            'detected_cms': set(),
            'error_pages': set(),
            'requested': queue.Queue()
        }

        if self.options['write_file'] is not None:
            self.json_outputter = OutputJSON(self.options, self.data)
Ejemplo n.º 6
0
def printerSimulation(numSeconds, ppm: int):
    printer = Printer(ppm)
    printQueue = Queue()
    waitingTimes = []

    for currentSecond in range(numSeconds):
        if newPrintTask():
            task = Task(currentSecond)
            printQueue.enqueue(task)

        if (not printer.isBusy()) and (not printQueue.isEmpty()):
            nextTask = printQueue.dequeue()
            waitingTimes.append(nextTask.waitTime(currentSecond))
            printer.next(nextTask)

        printer.tick()

    averageWaitingTime = sum(waitingTimes) / len(waitingTimes)

    print(
        "Average waiting time is {:.^14.2f} secs and {:.>5d} tasks remaining".
        format(averageWaitingTime, printQueue.size()))
Ejemplo n.º 7
0
class Game:
    def __init__(self):
        self.difficulties = '12345'
        self.difficulty = 5
        self.refresh_speed = 1.25
        self.refresh_speed_interval = 0.25
        self.slowest_refresh_rate = (len(self.difficulties) +
                                     1) * self.refresh_speed_interval
        self.fastest_refresh_rate = self.refresh_speed_interval
        self.signal = signal
        self.signal.signal(signal.SIGALRM, self.raise_exception)
        self.field_size = 4
        self.user_input = None
        self.prompt_difficulty()
        self.cells = [(i, j) for i in list(xrange(self.field_size))
                      for j in list(xrange(self.field_size))]
        self.apple = Apple(self.cells)
        self.snake = Snake(self.field_size, self.cells, self.apple)
        self.printer = Printer(self.snake, self.apple, self.refresh_speed,
                               self.difficulty)

    def raise_exception(self, sig_num, stack_frame):
        raise KeyboardInterrupt

    def prompt_difficulty(self):
        self.signal.setitimer(self.signal.ITIMER_REAL, 5)
        try:
            self.user_input = raw_input(
                "Choose Game Difficulty By Number: [1]Easy, [2]Normal, [3]Hard, [4]Veteran, [5]Expert: "
            )
            if self.user_input:
                if self.user_input in self.difficulties:
                    self.difficulty = int(self.user_input)
                    self.field_size = int(self.user_input) * 4
                    self.refresh_speed = float(self.refresh_speed_interval) * (
                        len(self.difficulties) + 1 - int(self.user_input))
            self.signal.setitimer(self.signal.ITIMER_REAL, 0)
        except KeyboardInterrupt:
            pass

    def start_game(self):
        while True:
            self.game_status()
            self.draw_jungle()
            try:
                with_alarm(self.get_input, self.signal, self.refresh_speed)()
            except KeyboardInterrupt:
                self.snake.move_snake()

    def game_status(self):
        if self.snake.length >= len(self.cells):
            self.printer.game_over_print("Good Game, You WIN.")
            exit(1)

    def draw_jungle(self):
        self.printer.clear_screen()
        roof = ' {} '.format(' '.join('_' * self.field_size))
        print(roof)
        tile = '|{}'
        for idx, cell in enumerate(self.cells):
            content = '_'
            if cell in self.snake.body:
                content = 'o'
                if cell == self.snake.body[-1]:
                    content = 's'
            if cell == self.apple.location:
                content = '*'
            if (idx + 1) % self.field_size == 0:
                print_line += tile.format(content + '|')
                print(print_line)
            elif (idx + 1) % self.field_size == 1:
                print_line = ''
                print_line += tile.format(content)
            else:
                print_line += tile.format(content)
        self.printer.print_message()

    def get_input(self):
        user_input = raw_input()
        if user_input:
            if user_input[-1].upper():
                self.user_input = user_input[-1].upper()
                if self.user_input in DIRECTIONS.keys():
                    self.snake.user_input = self.user_input
                    self.snake.move_snake()
                if self.user_input == 'Q':
                    self.end_game()
                elif self.user_input in ['-', '+']:
                    self.change_refresh_speed()
                    self.snake.move_snake()
        return user_input

    def init_field(self):
        self.snake.create_snake()
        self.apple.generate_apple(self.snake.body)
        self.printer.game_start_print()
        with_alarm(self.player_ready, self.signal, 60)()

    def player_ready(self):
        user_input = raw_input()
        if user_input == "":
            return

    def end_game(self):
        print("Game Over")
        exit(1)

    def change_refresh_speed(self):
        if self.user_input == '-':
            if self.refresh_speed < self.slowest_refresh_rate:
                self.refresh_speed += self.refresh_speed_interval
                self.printer.refresh_speed += self.refresh_speed
                self.printer.display_message(
                    "Speed Decreased. Current Refresh Rate: {} Seconds.".
                    format(self.refresh_speed))
            else:
                self.printer.display_message(
                    "Slowest Speed. Current Refresh Rate: {} Seconds.".format(
                        self.refresh_speed))
        elif self.user_input == '+':
            if self.refresh_speed > self.fastest_refresh_rate:
                self.refresh_speed -= self.refresh_speed_interval
                self.printer.refresh_speed += self.refresh_speed
                self.printer.display_message(
                    "Speed Increased. Current Refresh Rate: {} Seconds.".
                    format(self.refresh_speed))
            else:
                self.printer.display_message(
                    "Fastest Speed. Current Refresh Rate: {} Seconds.".format(
                        self.refresh_speed))
Ejemplo n.º 8
0
def init():




    #Initilize the printer and create the GUI
    printer = Printer()
    print("\n\n\n")
    printer.add("border_top","------------------------------------------------------------------------------------------------------------",False)
    printer.add("margin_top","",False)
    printer.add("app","COMBINATION LOCK",True)
    printer.add("about","Enter the unlock code on the keypad, if the code is right, then good for you :)",True)
    printer.add("border_middle","",False)
    printer.add("status","BOOTING...",True)
    printer.add("border_middle2","",False)
    printer.add("logs","Initilizing..",True)
    printer.add("keypad","[ deactivated ]",True)
    printer.add("margin_bottom","",False)
    printer.add("border_bottom","------------------------------------------------------------------------------------------------------------",False)






    #Initlize the password variable
    lock_password = ""
    #Try to read the password file
    try:
        #We use a try here to avoid a crash if the file does not exists
        #Load the password.txt file into memory
        password_file = open("password.txt","r")
        #Store the content of the file into the password variable
        lock_password = password_file.read()
    except FileNotFoundError:
        #Except FileNotFoundError as the file might not exist
        #Assign initial default password
        lock_password = "******"






    #Create the lock buffer
    #This buffer will be used to send and recieve signals from the keypad as well as sending signals to the buzzer and leds.
    lock_buffer = Buffer(BUFFER_PINS,BUFFER_DISABLE_PIN,BUFFER_CLOCK_PIN,COLUMN_CHANGE_PIN,BUFFER_NEUTRAL_COMMAND,INTERUPT_COMMAND,NO_REAL_BUFFER)






    #Initlize the lock
    #This will create an instance of the Lock class
    global lock
    lock = Lock(lock_password,ENABLE_SIDE_CHANNEL_ATTACK,printer,lock_buffer)






    #Init the lock components (keypad, leds and buzzer)
    lock.init_keypad(KEYPAD_TYPE,KEYPAD_KEYS)
    lock.init_components(BUZZER_COMMAND,GREEN_LED_COMMAND,RED_LED_COMMAND)


    #Configure security, timeout, open hours and lockout settings.
    lock.config_attempt_timeout(ATTEMPT_TIMEOUT_DURATION,TIMEOUT_LED_PINS)
    lock.config_time_lockout(OPENS_AT,CLOSES_AT)
    lock.config_security(ENABLE_SIDE_CHANNEL_ATTACK)

    if ALLOW_MAX_LOCKOUT:
        lock.config_max_lockout(ATTEMPT_LIMIT,DEACTIVATION_DURATION)







    try:
        #This will start the lock
        lock.start()
    except KeyboardInterrupt:
        #On keyboard interrupt the we need to cleanup GPIO ports, generate chart and print good bye mike message
        lock.quit()
        printer.replace("status","Done")
        time.sleep(.2)
        print ("\n\n\n\nGood bye Mike! If you happen to be anybody else then we are in a bit of tought situation. You see this is message will always be the same. Soo.. either you change your name or you have have to remember not to read this last message on exit.")
        GPIO.cleanup()
        sys.exit(1)
Ejemplo n.º 9
0
def testPrinter():
    Printer()
    assert (Printer.exists("Canon_CP900"))
    print Printer.osPrinter()
Ejemplo n.º 10
0
import sys
sys.path.append('.')

from csv_utils.reader import Reader
from csv_utils.common import Common
from classes.printer import Printer
# from hsk_check.hsk_check import HSKCheck
#
# HSKCheck.compare_with_official()
# HSKCheck.compare_with_images()

path = Common.HSK3_PATH + "hsk3.csv"
reader = Reader(path, 'hsk3')
words = reader.generate_words()
Printer.print_definition(words)
Ejemplo n.º 11
0
    [0, 5, 0, 0, 0, 7, 0, 0, 0],
    [0, 0, 0, 0, 4, 5, 7, 0, 0],
    [0, 0, 0, 1, 0, 0, 0, 3, 0],
    [0, 0, 1, 0, 0, 0, 0, 6, 8],
    [0, 0, 8, 5, 0, 0, 0, 1, 0],
    [0, 9, 0, 0, 0, 0, 4, 0, 0]
]

puzzle4 = [
    [0, 0, 0, 0],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
    [0, 0, 0, 0]
]

printer = Printer()

sudoku_puzzle1 = Sudoku(puzzle1, 2, 2)
sudoku_puzzle2 = Sudoku(puzzle2, 3, 3)
sudoku_puzzle3 = Sudoku(puzzle3, 3, 3)
sudoku_puzzle4 = Sudoku(puzzle4, 2, 2)

forcer = BruteForce()

solvedsudoku = None

print '------------- The Sudoku Solver Brute Kracht -------------'
print 'First choose the sudoku you want to solve:'
print '1) 2x2 Sudoku - prefilled (16 positions)'
print '2) 3x3 Sudoku - empty (81 positions)'
print '3) 3x3 Sudoku - prefilled (81 positions)'
Ejemplo n.º 12
0
 def print_definition(self, rand=False):
     self._print_lesson_number("completa", rand)
     Printer.print_definition(self.words, rand)
Ejemplo n.º 13
0
 def print_chinese(self, rand=False):
     self._print_lesson_number("completa", rand)
     Printer.print_chinese(self.words, rand)
Ejemplo n.º 14
0
 def print_all(self, rand=False):
     self._print_lesson_number("completa", rand)
     Printer.print_all(words, rand)
Ejemplo n.º 15
0
 def get_words(self, word_keys=None):
     return Printer.get_words(self.words, word_keys)
Ejemplo n.º 16
0
def main():

    #The root directory
    inputDir = "/Users/manu/Desktop/wistiti/"
    #The configuration file directory
    configDir = os.path.join(inputDir, "configurations")

    #USE CONFIGURATION FILE
    #Ask user for configuration
    files = Configuration.listConfigurationFiles(configDir)
    selection = Configuration.userSelection(files)
    selectionFilepath = os.path.join(configDir, files[selection])
    cfg = Configuration(selectionFilepath)

    print cfg

    #templateFile = "./resources/test/template/COR-MARS16_elements-template-gimp.jpg"
    useTemplate = cfg.getUseTemplate()
    if (useTemplate == True):
        templateFile = cfg.getTemplateName()
    else:
        templateFile = "NoTemplate"

    #marginColor = (84,158,167)
    marginColor = cfg.getTemplateColor()
    #TODO = Manage difference between width and height margins
    templateMargin = cfg.getPrinterMarginTemplate()[0]
    photoMargin = cfg.getPrinterMarginPhoto()[0]
    #The printer
    if (cfg.getPrinterOsName() == "Canon_CP900"):
        printFormat = PrintFormat.SelphyCP900(
            dpiStretch=cfg.getPrinterDpiStretch())
    elif (cfg.getPrinterOsName() == "Dai_Nippon_Printing_DP_DS620"):
        printFormat = PrintFormat.DNPDS620(
            dpiStretch=cfg.getPrinterDpiStretch())
    elif (cfg.getPrinterOsName() == "DNPDS620"):
        print "No osname and osformat for this printer %s\n"\
              "Change the configuration file. Quit" %(cfg.getPrinterOsName())
        return
    else:
        print "No printer with this name %s, quit" % (cfg.getPrinterOsName())
        return
    printFormat.setPrinterMargin(cfg.getPrinterMargin()[0],
                                 cfg.getPrinterMargin()[1],
                                 cfg.getPrinterMarginDim)
    print printFormat
    #END OF USE CONFIGURATION FILE

    #Add a margin on the template (add new pixel for printer margin)
    templateFile = addMarginOnTemplate(templateFile,
                                       templateMargin,
                                       marginColor=marginColor)

    #Get the subdirectories that include instagram pictures
    subDirArray = getImmediateSubdirectories(inputDir)

    #User chooses the subdirectory
    userIndexSelection = userSelectionInArray(subDirArray)
    inputDir = os.path.join(inputDir, subDirArray[userIndexSelection])
    #Get the images list (jpg)
    files = listScreenShotFiles(inputDir)

    #Display information for user
    print "********************************"
    print "%s files found" % (len(files))
    print files
    print "********************************"

    userInput = ""
    index = 0
    if (len(files) == 0):
        print "No compatible file in this directory, quit..."
        return

    while (userInput != "q"):
        #Open the picture image
        filepath = os.path.join(inputDir, files[index])
        (filepathWithoutExtension, extension) = os.path.splitext(filepath)

        #fileOutput = filepathWithoutExtension + "-python" + extension
        #print filepathWithoutExtension
        #print extension
        #print fileOutput

        #Add a photo on the template
        photoPath = addPhotoOnTemplate(filepath,
                                       templateFile,
                                       margin=photoMargin)
        im = Image.open(photoPath)

        #exif_data = im._getexif()
        #print im.info
        #print exif_data
        photo = Photo(im.size[0], im.size[1])
        photo.computePpmm(printFormat)
        print "********************************"
        print "File %s on %s : %s" % (index + 1, len(files), files[index])
        print photo
        fileOutput = generateFilepathWithSuffix(photoPath, "-CP900-print")
        im.save(fileOutput, 'jpeg', dpi=(photo.ppiX, photo.ppiY))
        im2 = Image.open(fileOutput)

        #User choose the action
        userInput = raw_input("Print? print/next/display/quit [p/n/d/q]")
        #print "Resultat %s" % userInput
        if userInput == "p":
            print im2.info
            printCommand = Printer.computePrinterCommand(
                fileOutput, cfg.getPrinterOsName(), cfg.getPrinterOsFormat())
            Printer.sendPrinterJob(printCommand)
            print "INFO : YOU CAN PRINT THE SAME IMAGE"
        elif userInput == "n":
            print "Next picture"
            index += 1
        elif userInput == "d":
            print "Display"
            im.show()
        elif userInput == "q":
            print "Quit"
        else:
            print "Unknown command"

        if (index >= len(files)):
            userInput = "q"
            print "No more picture, quit..."
Ejemplo n.º 17
0
import sys

sys.path.append('.')

from csv_utils.reader import Reader
from csv_utils.common import Common
from classes.printer import Printer
# from hsk_check.hsk_check import HSKCheck

# HSKCheck.compare_with_official()
# HSKCheck.compare_with_images()

path = Common.HSK4_PATH + "hsk4.csv"
reader = Reader(path, 'hsk4')
words = reader.generate_words()
Printer.print_definition_hsk4(words)
Ejemplo n.º 18
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-o", "--out", help="output the content of the cookies.")
    parser.add_argument("-f", "--order", help="specify the file with the list of browsing sessions used for diff")
    parser.add_argument("-m", "--mod", help="show only modified cookies")
    parser.add_argument("-s", "--show", help="show the cookies", default='yes')
    args = parser.parse_args()

    da = DataAnalyzer()
    p = Printer("console", False)

    # get the list of new and modified cookies
    collected_sites = da.diff(args.order)

    total_occ = 0
    total_mods = 0
    total_cmod = 0

    for key in sorted(collected_sites.keys()):

        if args.mod == "yes" and collected_sites[key].cookiemod != 0 or args.mod is None:

            total_mods += collected_sites[key].modscount
            total_cmod += collected_sites[key].cookiemod
            total_occ += collected_sites[key].cookiesnew

            name = str(collected_sites[key].sitename)

            p.printer(str("-" + key +  ", from sites" + name + "\n\tcookies: " + str(collected_sites[key].cookiesnew))
                      + "\tmodified: " + str(collected_sites[key].cookiemod))

            if args.show == 'yes':

                p.printer("\tid, baseDomain, name, value, host, path, expiry, creationTime, lastAccessed")

                for val in collected_sites[key].sortcookies():

                    if args.mod == "yes" and val[2] == "mod" or args.mod is None:

                        p.printer("\t" + str(val[0]['id']) + "|" + str(val[0]['baseDomain']) + "|"
                        + str(val[0]['name']) + "|" + str(val[0]['value']) + "|"
                        + str(val[0]['host']) + "|" + str(val[0]['path']) + "|"
                        + dataformatter(val[0]['expiry']) + "|" + dataformatter(val[0]['creationTime'])
                        + "|" + dataformatter(val[0]['lastAccessed']) + ", " + val[1] + ", " + val[2])

    p.printer("Entries: " + str(len(collected_sites)))
    p.printer("Modifications: " + str(total_mods) + " cookie modified: " + str(total_cmod)
    + " cookie " + str(total_occ))
Ejemplo n.º 19
0
 def __init__(self):
     self.cookiesforsite = []
     self.p = Printer("console", False)
     #Store the sites we have browsed
     self.sites = list()