Esempio n. 1
0
 def __init__(self, rows, columns, start_position, verbosity=0, closed=False, move_limit=None, time_limit=None):
     self.verbosity = Verbose(verbosity)
     self.closed = closed
     self.board = Board(rows, columns, self.verbosity.verbose_int)
     self.start_position = self._generate_start_position(start_position)
     self.retrace = 0 #just in case I want to set up a retrace counter
     self.end_positions = None
     self.move_limit = move_limit
     self.time_limit = time_limit
Esempio n. 2
0
 def __init__(self, position, verbosity=0):
     #self.current_position = position
     self.visited_positions = [position]
     self.possible_positions = []
     if ChessPiece.knight_moves == None:
         ChessPiece.knight_moves = self.create_moves()
     self.moves = ChessPiece.knight_moves
     self.verbosity = Verbose(verbosity)
Esempio n. 3
0
    def files(self, files, verbose=Verbose()):
        if type(files) in types.StringTypes:
            files = [files]

        f = fileinput.input(files, inplace=1)
        for line in f:
            if f.isfirstline():
                verbose(1, 'Translating %s' % os.path.basename(f.filename()))
            sys.stdout.write(self.string(line))
        f.close()
Esempio n. 4
0
 def __init__(self, rows, columns, verbosity=0):
     self.rows = int(rows)
     self.columns = int(columns)
     self.size = self.rows * self.columns
     #for both row and column, calculate how many moves a position is away from the edge of the board then add 1
     self.moves = {
         2: 2,
         3: 3,
         4: 4,
         5: 6,
         6: 8
     }  #shows how many moves are possible given how close the position is to the edge of the board
     self.verbosity = Verbose(verbosity)
Esempio n. 5
0
 def __init__(self, row, column, board, verbosity=0):
     self.row = row
     self.column = column
     self.coordinate = (row, column)
     self.str_coordinate = str(row) + '.' + str(column)
     self.board = board
     self.verbosity = Verbose(verbosity)
     self.fits_on_board = self._check_board()
     self.failures = []
     self.retrace = False
     if self.fits_on_board:
         self.weight = self.board.get_weight(self.row, self.column)
     else:
         self.weight = None
Esempio n. 6
0
 def __init__(self):
     self.args = self.init()
     self.v = Verbose(self.args.verbose)
     self.dir_octal = 0o0755
     self.file_octal = 0o0644
Esempio n. 7
0
class Program:
    def __init__(self):
        self.args = self.init()
        self.v = Verbose(self.args.verbose)
        self.dir_octal = 0o0755
        self.file_octal = 0o0644

    def init(self):
        parser = argparse.ArgumentParser()
        parser.add_argument(
            "--domain",
            "-d",
            action="store",
            dest="domain",
            help=
            "If left blank, permissions will run on all domains in the webroot",
            type=str,
            default=False)
        parser.add_argument("--verbose",
                            "-v",
                            action="store_true",
                            help="Print all actions taken by this script")

        required = parser.add_argument_group("required arguments")
        required.add_argument(
            "--webroot",
            "-w",
            action="store",
            dest="webroot",
            help=
            "Set the webroot of where all the domain directories exist, e.g. /var/www/html",
            type=str,
            required=True)
        required.add_argument(
            "--siteroot",
            "-s",
            action="store",
            dest="siteroot",
            help=
            "Set the siteroot of that all the domains share, e.g. public/html",
            type=str,
            required=True)
        required.add_argument(
            "--web-user",
            "-b",
            action="store",
            dest="web_user",
            help="Set the username of the webserver, e.g. www-data",
            type=str,
            required=True)
        required.add_argument("--admin-user",
                              "-a",
                              action="store",
                              dest="admin_user",
                              help="Set the username of your user",
                              type=str,
                              required=True)
        required.add_argument("--level",
                              "-l",
                              action="store",
                              dest="level",
                              help="Set strictness level",
                              type=int,
                              required=True)

        try:
            return parser.parse_args()
        except IOError as err:
            self.exit_program(err)

    def exit_program(self, msg):
        print(msg)
        sys.exit(2)

    def chown(self, path, uid, gid):
        self.v.print("chown: " + path)
        os.chown(path, uid, gid)

    def chmod(self, path, octal):
        self.v.print("chmod: " + path)
        os.chmod(path, octal)

    def get_uids(self):
        try:
            admin_user_uid = pwd.getpwnam(self.args.admin_user).pw_uid
            web_user_uid = pwd.getpwnam(self.args.web_user).pw_uid
        except KeyError as err:
            self.exit_program(err)

        return [admin_user_uid, web_user_uid]

    def recursive_ownership_and_permission_change(self, sitepath, uid, gid):
        for root, dirs, files in os.walk(sitepath):
            for d in dirs:
                dir_path = os.path.join(root, d)
                self.chown(dir_path, uid, gid)
                self.chmod(dir_path, self.dir_octal)
            for f in files:
                file_path = os.path.join(root, f)
                self.chown(file_path, uid, gid)
                self.chmod(file_path, self.file_octal)

        self.chown(sitepath, uid, gid)
        self.chmod(sitepath, self.dir_octal)

    def strict_permissions(self, sitepath):
        wp_content_dir = sitepath + "wp-content"
        themes_dir = sitepath + "wp-content/themes"

        uids = self.get_uids()
        self.recursive_ownership_and_permission_change(sitepath, uids[0],
                                                       uids[0])

        if os.path.isdir(wp_content_dir):
            self.recursive_ownership_and_permission_change(
                wp_content_dir, uids[1], uids[1])

        if os.path.isdir(themes_dir):
            self.recursive_ownership_and_permission_change(
                themes_dir, uids[0], uids[0])

    def lax_permissions(self, sitepath):
        uids = self.get_uids()
        git_dir = sitepath + ".git"
        gitignore = sitepath + ".gitignore"
        self.recursive_ownership_and_permission_change(sitepath, uids[1],
                                                       uids[1])

        if os.path.isdir(git_dir):
            self.recursive_ownership_and_permission_change(
                git_dir, uids[0], uids[0])

        if os.path.isfile(gitignore):
            self.chown(gitignore, uids[0], uids[0])
            self.chmod(gitignore, self.file_octal)

    def domain_execute(self, sitepath, directory):
        if not os.path.isdir(sitepath):
            print("The specified sitepath does not exist: " + sitepath)
            return False

        if not os.path.isdir(sitepath +
                             "wp-admin"):  # Check if directory uses WordPress
            print(directory + " does not use WordPress, skipping...")
            return False

        if self.args.level == 1:
            self.strict_permissions(sitepath)
        elif self.args.level == 2:
            self.lax_permissions(sitepath)

    def run(self):
        self.args.webroot = self.args.webroot.rstrip("/") + "/"
        self.args.siteroot = self.args.siteroot.lstrip("/")
        self.args.siteroot = self.args.siteroot.rstrip("/") + "/"

        if not os.path.isdir(self.args.webroot):
            self.exit_program("The specified webroot does not exist: " +
                              self.args.webroot)

        if self.args.domain:
            sitepath = self.args.webroot + self.args.domain + "/" + self.args.siteroot
            self.domain_execute(sitepath, self.args.domain)
        else:
            for directory in os.listdir(self.args.webroot):
                if directory.startswith("."): continue

                sitepath = self.args.webroot + directory + "/" + self.args.siteroot

                if not self.domain_execute(sitepath, directory): continue
Esempio n. 8
0
class Tour(object):

    def __init__(self, rows, columns, start_position, verbosity=0, closed=False, move_limit=None, time_limit=None):
        self.verbosity = Verbose(verbosity)
        self.closed = closed
        self.board = Board(rows, columns, self.verbosity.verbose_int)
        self.start_position = self._generate_start_position(start_position)
        self.retrace = 0 #just in case I want to set up a retrace counter
        self.end_positions = None
        self.move_limit = move_limit
        self.time_limit = time_limit
        
    def run(self):
        self.knight = Knight(self.start_position, self.verbosity.verbose_int)
        self.knight.add_to_board(self.board)
        if self.closed == True:
            self.end_positions = self.knight.get_possible_moves()
        count = 0
        duration = 0
        largest_tour = 0
        start = time.time()
        complete = False
        while len(self.knight.visited_positions) < self.board.size and self._check_limit(count, duration):
            #garner stats
            largest_tour = self.verbosity.min_max(self, largest_tour)
            self.verbosity.potential_OBOB(self)
            self.verbosity.progress(count)
            if len(self.knight.visited_positions) < 4:
                largest_tour = len(self.knight.visited_positions)
            if self.time_limit != None and count%1000 == 0:
                duration = time.time()-start
                
            #find the next move
            possible_positions = self.knight.get_possible_moves()
            self.verbosity.possible_moves(self.knight.get_current_position(), possible_positions)
            if len(possible_positions) == 0:
                    previous_position = self.knight.retrace()
                    t = Trace(count, previous_position, retrace=True)
                    count += 1
                    continue  
            initial_moves = []
            for position in possible_positions: #the position already has a weight when it's created
                if self._check_closed_tour(position, count) == True:
                    #either the tour is complete, or the knight retraced and we return to the while loop
                    complete = True
                    break
                move = Move(position, self.knight.get_visited_positions()[:])
                initial_moves.append(move)
            if len(initial_moves) != 0 and complete != True:
                best_move = Move.choose_best_move(initial_moves, self.end_positions)
                if not self.knight.set_position(best_move.get_position()):
                    raise MoveError(best_move.get_position())
                t = Trace(count, best_move.get_position(), retrace=False)
            count += 1
        end_time = round(time.time() - start,3)
        return self.knight, count, self.board, end_time
    
    def _check_closed_tour(self, position, count):
        if len(self.knight.visited_positions) == (self.board.size -1) and self.closed == True:
            if position in self.end_positions:
                t = Trace(count, position, retrace=False)
                self.knight.set_position(position)                
                #final position of the closed tour has been reached
            else:
                previous_position = self.knight.retrace()
                t = Trace(count, previous_position, retrace=True)
            return True 
    
    def _check_limit(self, count, duration):
        if self.move_limit != None and count > self.move_limit:
            raise GameError()
        elif self.time_limit != None and duration > self.time_limit:
            raise GameError()
        else:
            return True
    
    def _generate_start_position(self, start_position):
        error1 = "The %s value of your start position must be an integer.  Please enter the starting location in the following format: 4.5"
        error2 = "the %s (the %s value of the starting position) does not fit on the board"
        row_column = start_position.split(".")      
        assert len(row_column) is 2, "start position must contain exactly one '.' period"
        try:
            row = int(row_column[0])
        except ValueError:
            print error1 %("first")
            exit(1)
        try:
            column = int(row_column[1])
        except ValueError:
            print error1 %("second")
            exit(1)
            
        assert 0 < row <= self.board.rows, error2 %("row","first")             
        assert 0 < column <= self.board.columns, error2 %("column","second")       
        return Position(row, column, self.board, self.verbosity.verbose_int)