Esempio n. 1
0
def readAtomData(filename):
    """
    Reads in the atoms of a .data file and assigns them the symmetry function symmFun
    Returns an array of atoms for each time step (each combined as an array)
    """

    if not filename.endswith("data"):
        helper.print_warning("WARNING: the atom file " + filename +
                             " is not a .data file")

    f = open(filename, 'r')
    step_data = []
    energy = 0
    box_data = []
    atomData = []
    thermoData = []

    with open(filename, 'r') as f:
        for line in f:
            sline = line.strip().lower().split()
            if sline[0] == "end":
                atomData.append([getAtoms(step_data), getBox(box_data)])
                thermoData.append(energy)
                box_data = []
                step_data = []
            if sline[0] == "lattice":
                box_data.append(line)
            elif sline[0] == "atom":
                step_data.append(line)
            elif sline[0] == "energy":
                energy = float(sline[1])

    return atomData, thermoData
Esempio n. 2
0
    def interpreter_flow(self, klass):
        """Tests stuff"""
        namespace = namedtuple(
            'Namespace',
            'filename extension_mode override_file modeline text_editors style')
        filename = os.path.join(tempfile.mkdtemp(
            prefix='letscode' + klass.name + '_'), "filename")
        args = namespace(
            filename, 'auto', 'n', 'both', MODELINE_SUPPORTED_EDITORS, None)
        real_file = klass.get_actual_filename_to_use(args)

        # Cannot run if file does not exist
        self.assertFalse(os.path.isfile(real_file))
        self.assertFalse(klass.perform_action('run', args))

        # Can create
        self.assertTrue(klass.perform_action('create', args))
        self.assertTrue(os.path.isfile(real_file))

        if klass.is_ready():
            # Can run
            self.assertTrue(klass.perform_action('run', args))

            # Can run on its own
            if klass.nb_line_shebang:
                self.assertTrue(subprocess_call_wrapper([real_file]))
        else:
            print_warning("%s is not ready to be run" % klass.name)

        # Removing file -> code does not run
        os.remove(real_file)
        self.assertFalse(klass.perform_action('run', args))
Esempio n. 3
0
def upload_option(profile: NaClProfile):
    """
    The interface to upload profile to server,
    working with ds_client module's send().
    :param profile: current working profile object
    :return: None
    """
    option = input(
        "Do you want to also upload it to the server? (y/n)\n").upper()
    server = profile.dsuserver
    username = profile.username
    password = profile.password
    message = profile.get_posts()
    bio = profile.bio
    # decrypt the bio from the local DSU file / current profile
    bio = profile.nacl_profile_decrypt(bio)

    if option == 'Y':
        print("Send post (p)")
        print("Update bio (b)")
        print("Send post and update bio (pb)")
        option = input()
        client.send(profile, option, server, PORT, username, password, message,
                    bio)

    elif option == 'N':
        print_ok("Done.")

    else:
        print_warning('please enter either y or n\n')
        upload_option(profile)
Esempio n. 4
0
def main_func():
    """
    The function wrapper.
    :return: None
    """
    in_commands = input()
    commands = input_analyzer(in_commands)
    commands[0] = commands[0].upper()

    # for test purpose

    if test_mode:
        print_error("[Test mode]The command list after process: " +
                    str(commands))
    if commands[0] == 'L':
        command_L(commands)
    elif commands[0] == 'C':
        command_C(commands)
    elif commands[0] == 'D':
        command_D(commands)
    elif commands[0] == 'R':
        command_R(commands)
    elif commands[0] == 'Q':
        command_Q()
    elif commands[0] == 'H':
        helper()
    elif commands[0] == 'M':
        modify_profile()
    else:
        print_warning("Incorrect COMMAND")
Esempio n. 5
0
def readAtomData(filename):
    """
    Reads in the atoms of a .data file and assigns them the symmetry function symmFun
    Returns an array of atoms for each time step (each combined as an array)
    """

    if not filename.endswith("data"):
        helper.print_warning("WARNING: the atom file " + filename + " is not a .data file")
    
    f = open(filename, 'r')
    step_data = []
    energy = 0
    box_data = []
    atomData = []
    thermoData = []

    with open(filename, 'r') as f:
        for line in f:
            sline = line.strip().lower().split()
            if sline[0] == "end":
                atomData.append([getAtoms(step_data), getBox(box_data)])
                thermoData.append(energy)
                box_data = []
                step_data = []
            if sline[0] == "lattice":
                box_data.append(line)
            elif sline[0] == "atom":
                step_data.append(line)
            elif sline[0] == "energy":
                energy = float(sline[1])
                
    return atomData, thermoData
Esempio n. 6
0
def getFc(i):
    if i == 1:
        return f1
    elif i == 2:
        return f2
    else:
        helper.print_warning("WARNING: " + str(i) + " unrecognized cutoff function number")
Esempio n. 7
0
def getFc(i):
    if i == 1:
        return f1
    elif i == 2:
        return f2
    else:
        helper.print_warning("WARNING: " + str(i) +
                             " unrecognized cutoff function number")
Esempio n. 8
0
def comment_string(string, inline_comment, block_comment):
    """Return string commented in the best way"""
    if block_comment is not None and (inline_comment is None or '\n' in string):
        return comment_string_with_block(string, block_comment)
    elif inline_comment is not None:
        assert block_comment is None or '\n' not in string
        return comment_string_with_inline(string, inline_comment)
    else:
        print_warning('Cannot comment string')
        return ''  # Empty string is safe and shoudn't cause troubles
Esempio n. 9
0
def command_L(commands):
    """
    Functionalities within command L.
    List the contents of the user specified directory.
    :param commands: the input command
    :return: None
    """
    if len(commands) < 2:
        print_warning('There needs to be at least 1 input for COMMAND L')
    else:
        p = Path(commands[1])
        try:
            all_items, dirs, files = command_L_get_items(p)
        except WindowsError:
            print_error("ERROR")

        if len(commands) == 2:
            for i in files:
                print(i)
            for i in dirs:
                print(i)

        elif len(commands) == 3:
            # options -r -f

            if commands[2] == '-r':
                r = command_L_r(p, [])
                for i in r:
                    print(i)
            elif commands[2] == '-f':
                command_L_f(p)
            else:
                print_warning('Option here should be either -r or -f')

        elif len(commands) == 4:
            # options -s -e -r-f

            if commands[2] == '-s':
                command_L_s(p, commands[3])
            elif commands[2] == '-e':
                command_L_e(p, commands[3])
            elif commands[2] == '-r' and commands[3] == '-f':
                command_L_r_f(p)

        elif len(commands) == 5:
            # options -r-s -r-e
            if commands[2] == '-r' and commands[3] == '-s':

                command_L_r_s(p, commands[4])

            elif commands[2] == '-r' and commands[3] == '-e':

                command_L_r_e(p, commands[4])
Esempio n. 10
0
    def compilation_flow(self, klass):
        """Tests stuff"""
        namespace = namedtuple(
            'Namespace',
            'filename extension_mode override_file modeline text_editors style')
        filename = os.path.join(tempfile.mkdtemp(
            prefix='letscode' + klass.name + '_'), "filename")
        args = namespace(
            filename, 'auto', 'n', 'both', MODELINE_SUPPORTED_EDITORS, None)
        real_file = klass.get_actual_filename_to_use(args)
        output_file = klass.get_output_filename(real_file)

        # Cannot compile or run if file does not exist
        self.assertFalse(os.path.isfile(real_file))
        self.assertFalse(os.path.isfile(output_file))
        self.assertFalse(klass.perform_action('compile', args))
        self.assertFalse(klass.perform_action('run', args))

        # Cannot run before compilation
        self.assertTrue(klass.perform_action('create', args))
        self.assertFalse(klass.perform_action('run', args))

        # Can create
        self.assertTrue(klass.perform_action('create', args))
        self.assertTrue(os.path.isfile(real_file))
        self.assertFalse(os.path.isfile(output_file))

        if klass.is_ready():
            # Can compile and run
            self.assertTrue(klass.perform_action('compile', args))
            self.assertTrue(os.path.isfile(output_file))
            self.assertTrue(klass.perform_action('run', args))

            # Removing output file -> cannot run
            os.remove(output_file)
            self.assertFalse(os.path.isfile(output_file))
            self.assertFalse(klass.perform_action('run', args))

            # Can run after re-compilation
            self.assertTrue(klass.perform_action('compile', args))
            self.assertTrue(os.path.isfile(output_file))
            self.assertTrue(klass.perform_action('run', args))
        else:
            print_warning("%s is not ready to be run" % klass.name)

        os.remove(real_file)

        if klass.is_ready():
            # Removing file -> code is still running and compilation fails
            self.assertTrue(klass.perform_action('run', args))
            self.assertFalse(klass.perform_action('compile', args))
Esempio n. 11
0
def getSymmFunctions(symmFunctInfo):
    to_return = []
    with open(symmFunctInfo, "r") as f:
        for line in f:
            sline = list(map(helper.reduce_type, line[:line.find("#")].strip().split()))
            if len(sline) < 2:
                continue
            if sline[0] == 2:
                to_return.append(SymmFunct2(*sline[1:]))
            elif sline[0] == 3:
                to_return.append(SymmFunct3(*sline[1:]))
            else:
                helper.print_warning("WARNING: " + str(sline[0]) + " unrecognized symmetry function type")
    return to_return
Esempio n. 12
0
def getG(i):
    if i == 1:
        return g1
    elif i == 2:
        return g2
    elif i == 3:
        return g3
    elif i == 4:
        return g4
    elif i == 9:
        return g9
    else:
        helper.print_warning("WARNING: " + str(i) + " unrecognized g function number")
        return g1
Esempio n. 13
0
def send(np: NaClProfile,
         send_type,
         server: str,
         port: int,
         username: str,
         password: str,
         message: list,
         bio: str = None):
    '''
    The send function joins a ds server and sends a message, bio, or both
    :param np: it is the NaClProfile object passed in from the main program
    :param send_type: the sending type of this send (post / bio / post and bio)
    :param server: The ip address for the ICS_32 DS server.
    :param port: The port where the ICS_32 DS server is accepting connections.
    :param username: The user name to be assigned to the message.
    :param password: The password associated with the username.
    :param message: The list of posts to be sent to the server.
    :param bio: Optional, a bio for the user.
    '''
    global token
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        sock.connect((str(server), port))
    except socket.gaierror:
        print_warning('The address or port seems incorrect')
    else:
        done = "Upload done."

        send_types = ['p', 'b', 'pb']
        # make sure the send type is a valid one
        if send_type in send_types:
            # join the server
            join(sock, username, password, np.public_key)
            # if connected successfully, the token will be given a value
            # otherwise it's an empty string.
            if token != '':

                if send_type == 'p':
                    post(sock, message, np)
                    print_ok(done)
                elif send_type == 'b':
                    _bio(sock, bio, np)
                    print_ok(done)
                elif send_type == 'pb':
                    post(sock, message, np)
                    _bio(sock, bio, np)
                    print_ok(done)
        else:
            print_error("Please provide a valid send type.\n" "Upload failed.")
Esempio n. 14
0
def getG(i):
    if i == 1:
        return g1
    elif i == 2:
        return g2
    elif i == 3:
        return g3
    elif i == 4:
        return g4
    elif i == 9:
        return g9
    else:
        helper.print_warning("WARNING: " + str(i) +
                             " unrecognized g function number")
        return g1
Esempio n. 15
0
def getSymmFunctions(symmFunctInfo):
    to_return = []
    with open(symmFunctInfo, "r") as f:
        for line in f:
            sline = list(
                map(helper.reduce_type, line[:line.find("#")].strip().split()))
            if len(sline) < 2:
                continue
            if sline[0] == 2:
                to_return.append(SymmFunct2(*sline[1:]))
            elif sline[0] == 3:
                to_return.append(SymmFunct3(*sline[1:]))
            else:
                helper.print_warning("WARNING: " + str(sline[0]) +
                                     " unrecognized symmetry function type")
    return to_return
Esempio n. 16
0
def command_C(commands):
    """
    Functionalities within command C,
    will read the input and create a new file.
    :param commands: the input command
    :return: None
    """

    if len(commands) != 4:
        print_warning('There needs to be exactly 3 inputs for COMMAND C')
    else:

        p = commands[1] + '\\'
        name = commands[3]
        extention = '.dsu'
        path = p + name + extention

        if test_mode:
            print_error("[Test mode]COMMAND C's path: " + path)

        if commands[2] == '-n':
            try:
                path = Path(path)
                # create the dsu file
                path.touch()
                # for Profile creation (after the dsu file is created)
                create_profile(str(path))
            except FileNotFoundError:
                print_warning('This is a invalid directory')
        else:
            print_warning("This option is invalid for COMMAND C")
Esempio n. 17
0
def command_R(commands):
    """
    Functionalities within command R, print the content of a DSU file.
    :param commands: the input command
    :return: None
    """
    if len(commands) < 2:
        print_warning('There needs to be at least 1 input for COMMAND R')
    elif len(commands) == 2:
        path = Path(commands[1])

        if not str(path).endswith('.dsu'):
            print_warning('It needs to be a DSU file with .dsu suffix')
        else:
            try:
                with open(str(path), 'r') as f:
                    if path.stat().st_size == 0:
                        print_warning('EMPTY')
                    else:
                        output = f.readlines()
                        for i in range(len(output)):
                            if i == len(output) - 1:
                                # should not print a newline at the end
                                print(output[i], end='')
                            else:
                                print(output[i])
            except FileNotFoundError:
                print_warning(
                    'This file or directory does not exist: \'{}\''.format(
                        str(path)))
    # -l option to load
    elif len(commands) == 3 and commands[2] == '-l':
        profile = NaClProfile()
        profile.load_profile(commands[1])
        display_profile(profile)
        upload_option(profile)
    else:
        print_warning("The format for COMMAND R seems not right")
Esempio n. 18
0
def command_D(commands):
    """
    Functionalities within command D, allow the user to delete a DSU file.
    :param commands: the input command
    :return: None
    """
    if len(commands) < 2:
        print_warning('There needs to be at least 1 input for COMMAND D')
    else:
        path = Path(commands[1])

        if not str(path).endswith('.dsu'):
            print_warning('It needs to be a DSU file with .dsu suffix')
        else:
            try:
                path.unlink()
                print_ok(str(path) + ' DELETED')
            except FileNotFoundError:
                print_warning("File not found!")
Esempio n. 19
0
def main():
    toolAckMessage = "Amazon Macie is not a free service. By using this tool you acknowledge you are responsible for all charges and actions!"
    print_headline("Amazon Macie Activation Process Tool")
    print("!!!!!!!!!!")
    print_warning(toolAckMessage)
    print_info(
        "See Amazon Macie pricing: https://aws.amazon.com/macie/pricing/")
    print("!!!!!!!!!!")
    cont = confirmation("Do you wish to continue?")

    if not cont:
        sys.exit(0)

    print_padding(len(toolAckMessage), '-')

    selectedOrg = select("Select organization root:", get_roots(),
                         lambda x: x['Name'])
    selectedOu = select("Select Child OU:", list_ous(selectedOrg['Id']),
                        lambda x: x['Name'])

    allAccounts = confirmation("Do you want to use all accounts in the OU?")
    accounts = list_accounts(selectedOu['Id'])
    selectedAccounts = accounts

    if allAccounts == False:
        selectedAccounts = [
            select("Select Target Account:", accounts, lambda x: x['Name'])
        ]

    rawTags = ask(
        "What tags should be added to the Macie enrolled accounts? (Format: key:value;key:value)"
    )

    tags = {}

    for t in rawTags.split(';'):
        spl = t.split(':')
        tags[spl[0]] = spl[1]

    listOfAccountConfirm = '\n'.join(
        sorted(entry['Id'] for entry in selectedAccounts))
    agree = confirmation(
        'Accounts:\n{2}\nDo you wish to enable Macie in {0} account{1}?'.
        format(len(selectedAccounts),
               's' if len(selectedAccounts) == 0 else '',
               listOfAccountConfirm))

    if agree == False:
        sys.exit(0)

    # Create Macie Client  and set the parent account as the delgated org account
    parentAccountId = get_account_id()
    rootMacie = boto3.client('macie2')

    print('Making {0} the Macie admin account'.format(parentAccountId))

    try:
        rootMacie.enable_organization_admin_account(
            adminAccountId=parentAccountId)
        print('Enabling auto-enable in {0}'.format(parentAccountId))
        rootMacie.update_organization_configuration(autoEnable=True)
    except:
        pass

    for selectedAccount in selectedAccounts:
        print('Associating {0} with master account {1} and enabling Macie'.
              format(selectedAccount['Id'], parentAccountId))

        rootMacie.create_member(account={
            'accountId': selectedAccount['Id'],
            'email': selectedAccount['Email']
        },
                                tags=tags)
    pass
Esempio n. 20
0
 def checkDim(self, other):
     #Prints dimension warnings as needed
     if len(self.pos) != len(other.pos):
         helper.print_warning("WARNING: two compared atoms have different position dimensions")
Esempio n. 21
0
def helper():
    print(
        "\nThis color represents an input prompt or normal system information."
    )
    print_ok("This color represents successful or approved operations.")
    print_warning(
        "This color represents user's illegal inputs or unexpected operations."
    )
    print_error("This color represents systematic error or test mode message "
                "that should be handled by developers.\n")

    print("""Usage format: [COMMAND] [INPUT] [[-]OPTION] [INPUT]
    
    Some tips:
    If you want to CREATE a file, go to COMMAND: C
    If you want to MODIFY a file, go to COMMAND: M
    If you want to UPLOAD a file, go to COMMAND: R
    
    COMMAND: L - List the contents of the user specified directory.

                OPTIONs:
                -r Output directory content recursively.
                -f Output only files, excluding directories in the results.
                -s Output only files that match a given file name.
                -e Output only files that match a give file extension.

                Example usage:
                L c:\\users\\mark\\a1
                L c:\\users\\mark\\a1 -r
                L c:\\users\\mark\\a1 -f
                L c:\\users\\mark\\a1 -r -s readme.txt
                L c:\\users\\mark\\a1 -s readme.txt
                L c:\\users\\mark\\a1 -r -e jpg

    COMMAND: Q - Quit the program.

                Example usage:
                Simply press Q.

    COMMAND: C - Create a new file in the specified directory.
                 And you need to enter DSU server, username, and
                 password by the following prompt.

                 After the creation of DSU file and profile, the
                 program will ask you if you want to upload things
                 to the DSU server.

                OPTIONs:
                -n Specify the name to be used for a new file.

                Example usage:
                C c:\\users\\mark\\a1 -n mark

    COMMAND: M - Modify a saved DSU file and the profile relates to it.
                 After the command is typed in, the system will load up
                 a DSU file to a Profile object to modify the data.
                 It will prompt you how to modify and save the data.

                Example usage:
                M (just put in 'M' and wait for the prompt)

    COMMAND: D - Delete the file.

                Example usage:
                D c:\\users\\mark\\a1\\mark.dsu

    COMMAND: R - Read the contents of a file and upload it to the server.


                OPTIONs:
                -l load the specified file from the path, If you want to 
                upload a file directly, use this.

                After the loading of DSU file and profile, the
                program will ask you if you want to upload things
                to the DSU server.

                Example usage:
                R c:\\users\\mark\\a1\\mark.dsu
                R c:\\users\\mark\\a1\\mark.dsu -l
                
    API Supports:
    
                When you are writing posts, you have some API add-ins support
                available for better writing! All the keywords will be transcluded
                before the DSU file is saved. You will see "Transcluding..." when
                the file is being transcluded.
                
                OpenWeather API:
                You can simply add '@weather' in your post at anywhere, and the
                '@weather' script will translate to the current weather in Irvine.
                Supports for your current location will be added later.
                               
                LastFM API:
                You can simply add '@lastfm' in your post at anywhere, and the
                '@lastfm' script will translate to the United Stats' top hit 
                song on LastFM in current time period.
                Supports for other countries will be added later.
                
                Joke API:
                You can simply add '@extracredit' in your post at anywhere, and the
                '@extracredit' script will translate to a random joke.
                
                !CAUTION!: this api may not be accessible in some regions since
                the IP address of the api's server is blocked in some area, if
                you encounter a trancluding problem or connection issue, please
                connect to UCI's VPN when you are using this feature. 
              """)
Esempio n. 22
0
def modify_profile():
    """
    Load up the profile DSU file for modification.
    :return: None
    """
    path = input('Input the DSU file\'s path which you want to modify.\n'
                 'For example: C:\\Users\\ThinkPad\\Desktop\\test\\mark.dsu\n')
    profile = NaClProfile()
    try:
        profile.load_profile(path)
    except DsuFileError:
        print_warning('This might not be a valid path.')
    else:
        prompt = """\nWhich part you want to modify?
        server (se)
        username (u)
        password (pwd)
        bio (b)
        posts (p)
        save modification(s)"""

        print_ok(path + " is ready for modification.\n")

        # keep prompting the user to choose an option for modification
        while True:
            display_profile(profile)
            print(prompt)

            option = input().lower()
            if option == "u":
                mod = input("Enter the new username: \n")
                profile.username = mod

            elif option == "se":
                mod = input("Enter the new server address: \n")
                profile.dsuserver = mod

            elif option == "pwd":
                mod = input("Enter the new password: \n")
                profile.password = mod

            elif option == "b":
                mod = input("Enter the new bio: \n")
                profile.bio = profile.nacl_profile_encrypt(mod)

            elif option == "p":
                # get users option
                option = input("Add (a) or delete (d) a post?\n").lower()

                if option == "a":
                    entry = input("Write your entry below:\n")
                    post = Profile.Post()
                    post.set_entry(entry)
                    profile.add_post(post)
                    print_ok("Entry added.")

                elif option == 'd':
                    entry = int(input("Which entry you want to delete?\n"))
                    profile.del_post(entry)
                    print_ok('Entry deleted.')

                else:
                    print_warning("Please enter either a or d.")

            elif option == "s":
                profile = posts_transclude(profile)
                profile.save_profile(path)
                display_profile(profile)
                print_ok("All saved.")
                break
            else:
                print_warning("Please enter a valid option. Or "
                              "input 's' to save (quit).")
Esempio n. 23
0
 def checkDim(self, other):
     #Prints dimension warnings as needed
     if len(self.pos) != len(other.pos):
         helper.print_warning(
             "WARNING: two compared atoms have different position dimensions"
         )