コード例 #1
0
ファイル: test_style.py プロジェクト: Caronagrp/CaronaCerto
    def test_enabling(self):
        # test manually enabling and disabling
        style.enabled = False
        self.assertEqual('test', style.red('test'))

        style.enabled = True
        self.assertIn('test', str(style.red('test')))
        self.assertIn('31', str(style.red('test')))
コード例 #2
0
ファイル: rooms.py プロジェクト: Totodore/Projet-I1
    def display_delete(self):  ##Formulaire de suppression de salle

        remove_id = self.form_get_id_room(
        )  ##Demande à l'user l'id de la salle

        confirm = [{
            'type':
            'confirm',
            'name':
            "confirm",
            'message':
            "Etes-vous sur de supprimer la salle " +
            API.getRooms()[remove_id]["room_name"] + " ?"
        }]
        res = prompt(confirm)["confirm"]  ##Affiche le formulaire
        clear()

        ##Traitement de la réponse
        if res == True:
            API.removeRoom(remove_id)  ##Suppression dans la BDD
            print(style.green("La salle à bien été supprimée !"))
        else:
            print(style.red("Action annulée"))

        ##Afficher les options
        self.display_options()
コード例 #3
0
    def display_delete(self):  ##Formulaire de suppression de logiciel

        remove_id = self.form_get_id_soft(
        )  ##Demande à l'user l'id du logiciel

        confirm = [  #méthode de confirmation
            {
                'type':
                'confirm',
                'name':
                "confirm",
                'message':
                "Etes-vous sur de supprimer le logiciel " +
                API.getSoftwares()[remove_id]["name"] + " ?"
            }
        ]
        res = prompt(confirm)["confirm"]  ##Affiche le formulaire
        clear()

        ##Traitement de la réponse
        if res == True:
            API.removeSoftware(remove_id)  ##Suppression dans la BDD
            print(style.green("Le logiciel à bien été supprimée !"))
        else:
            print(style.red("Action annulée"))

        ##Afficher les options
        self.display_options()
コード例 #4
0
def giveCommands(server, commands):
    '''
    The parameter "commands" is either a dictionary or a list. It contains 
    commands to be passed through to the command line. If interactive commands
    are required, it is a dictionary, with each key command having its own 
    interactive commands, e.g. when a [Y/N] is prompted. When interactive 
    commands are not used, a list of commands is passed instead.
    '''

    privateKey = get_key(server)
    username = get_username(server)
    IP_address = get_IP(server)

    k = paramiko.RSAKey.from_private_key_file(privateKey)
    c = paramiko.SSHClient()
    c.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    print("\n\nConnecting to " + server + "...")
    c.connect(hostname=IP_address, username=username, pkey=k)
    print("Connected.\n")

    for command in commands:
        print("Executing", style.cyan(command))
        stdin, stdout, stderr = c.exec_command(command)
        if type(commands) == dict and commands[command]:
            for interactiveCommand in commands[command]:
                print("Entering", style.cyan(interactiveCommand))
                stdin.write(interactiveCommand)
                stdin.write('\n')
                stdin.flush()
        print("Output:", style.magenta(stdout.read().decode()))
        print("Errors:", style.red(stderr.read().decode()))
    c.close()
コード例 #5
0
def TaggerWriteNone(files):

    print(style.red(ENV_ERROR_DISCOGS_NULL))

    for file in files:
        try:
            file_extension = file.rsplit('.', 1)[1]
            f = None

            if file_extension == 'flac':
                f = FLAC(file)

            if file_extension == 'mp3':
                f = EasyID3(file)

            f['custom'] = ENV_TAGGING_TODO

            f.save()

            print(f['tracknumber'][0] + ' done')
        except:
            print(style.red(ENV_ERROR_TAGGING))
            continue
コード例 #6
0
    def remove_computer_display(self):

        computer_id = self.form_get_id_computer()

        confirm = [{
            'type':
            'confirm',
            'name':
            "confirm",
            'message':
            "Etes-vous sur de supprimer l'ordinateur de " +
            API.getComputers()[computer_id]["user"]["name"] + " ?"
        }]
        res = prompt(confirm)["confirm"]

        clear()

        if res == True:
            API.removeComputer(computer_id)
            print(style.green("L'ordinateur a bien été supprimé !"))
        else:
            print(style.red("Action annulée"))

        self.display_options()
コード例 #7
0
ファイル: index.py プロジェクト: bamdadsabbagh/tagger
import traceback

folders = Folder(ENV_PATHS)
# print(style.green('\n' + MY_PATH))

for folder in folders:

    print(style.yellow('\n---\n'))

    print(style.green(folder))
    print()

    files = File(folder)
    try:
        discogs = Discogs(files)
    except Exception as e:
        print(style.red('some error happened...'))
        logging.error(traceback.format_exc())
        continue

    if discogs == ENV_TAGGING_DONE:
        print(style.yellow(ENV_TAGGING_DONE))
        continue

    if discogs == ENV_TAGGING_TODO:
        print(style.yellow(ENV_TAGGING_TODO))
        continue

    Tagger(files, discogs)

print('\n')
コード例 #8
0
ファイル: test_style.py プロジェクト: Caronagrp/CaronaCerto
    def test_len(self):
        # test if the lenght is independet of the style
        styled_string = style.red('test')

        self.assertEqual(len(styled_string), len('test'))
        self.assertTrue(len(str(styled_string)) > len(styled_string))
コード例 #9
0
ファイル: test_style.py プロジェクト: Caronagrp/CaronaCerto
 def test_non_string_seperator(self):
     # test if a non string seperator raises a TypeError
     with self.assertRaises(TypeError):
         style.red('test1', 'test2', sep=0)
コード例 #10
0
ファイル: test_style.py プロジェクト: Caronagrp/CaronaCerto
 def test_seperator(self):
     # test custom seperator
     self.assertIn('test1, test2', style.red('test1', 'test2', sep=', '))
コード例 #11
0
    def addComputer(self):

        name = [
            {
                'type': 'input',
                'name': 'name',
                'message': "Nom de l'ordinateur",
                'validate': lambda val: True if val != "" else "Nom invalide"
            },
        ]

        processor = [{
            'type':
            'input',
            'name':
            'plateform',
            'message':
            'Platforme du processeur:',
            'validate':
            lambda val: True if val == "32" or val == "64" else
            "Veuillez rentrer '32' ou '64' bits"
        }, {
            'type': 'input',
            'name': 'brand',
            'message': 'Marque du processeur :',
        }, {
            'type': 'input',
            'name': 'speed',
            'message': 'Vitese du processeur :',
        }, {
            'type': 'input',
            'name': 'size_cache',
            'message': 'Taille du Cache :',
        }, {
            'type': 'input',
            'name': 'model',
            'message': 'Modèle de processeur :',
        }]
        RAM = [{
            'type': 'input',
            'name': 'number',
            'message': 'Nombre de RAM :',
            'validate': lambda val: self._checkSelectedIndex(val, 10)
        }, {
            'type': 'input',
            'name': 'total_size',
            'message': 'Taille totale de la RAM :',
        }]
        graphic_card = [{
            'type': 'input',
            'name': 'brand',
            'message': 'Marque de la carte graphique :',
        }, {
            'type': 'input',
            'name': 'memory',
            'message': 'Taille Mémoire de la carte graphique :',
        }, {
            'type': 'input',
            'name': 'model',
            'message': 'Modèle de la carte graphique :',
        }]
        video_ports = [{
            'type':
            'checkbox',
            'message':
            'Selectionner les ports disponibles',
            'name':
            'video_port',
            'choices': [{
                'name': 'VGA'
            }, {
                'name': 'HDMI'
            }, {
                'name': 'Display-Port'
            }, {
                'name': 'DVI-A'
            }, {
                'name': 'DVI-D'
            }, {
                'name': 'USB-C'
            }]
        }]
        screen = [{
            'type': 'input',
            'name': 'screen_res',
            'message': "Résolution de l'écran :",
            'validate': lambda val: self._checkSelectedIndex(val, 10000)
        }, {
            'type': 'input',
            'name': 'screen_size_x',
            'message': "Largeur de l'écran (en px) :",
            'validate': lambda val: self._checkSelectedIndex(val, 10000)
        }, {
            'type': 'input',
            'name': 'screen_size_y',
            'message': "Longueur de l'écran (en px) :",
            'validate': lambda val: self._checkSelectedIndex(val, 30000)
        }]
        network_card = [{
            'type': 'input',
            'name': 'speed',
            'message': 'Vitesse de la carte réseau :',
        }, {
            'type': 'input',
            'name': 'brand',
            'message': 'Marque de la carte réseau :',
        }]
        purchase = [{
            'type': 'input',
            'name': 'maker',
            'message': "Fabricant de l'ordinateur:",
        }, {
            'type': 'input',
            'name': 'provider',
            'message': "Fournisseur de l'ordinateur:",
        }, {
            'type': 'input',
            'name': 'purchase_date_timestamp',
            'message': "Date d'achat (au format JJ/MM/AAAA):",
            'validate': lambda val: self._checkDate(val)
        }]

        user = [{
            'type': 'input',
            'name': 'name',
            'message': 'Nom :',
        }, {
            'type': 'input',
            'name': 'username',
            'message': "Nom d'utilisateur :",
        }]
        specs_tech = [{
            'type':
            'checkbox',
            'message':
            'Selectionner les characteristiques technique',
            'name':
            'specs_tech',
            'choices': [{
                'name': 'Lecteur CD'
            }, {
                'name': 'Wifi'
            }, {
                'name': 'Bluetooth'
            }]
        }]
        USB = [{
            'type': 'input',
            'name': 'nb_USB_port',
            'message': "Combien l'ordinateur à t'il de ports USB ? :",
            'validate': lambda val: self._checkSelectedIndex(val, 10)
        }]
        nbStorage = [{
            'type': 'input',
            'name': 'nb_storage',
            'message': "Combien d'espaces de stockage l'ordinateur a t'il ? :",
            'validate': lambda val: self._checkSelectedIndex(val, 10)
        }]

        nameData = prompt(name)["name"]
        processorData = prompt(processor)
        RAMData = prompt(RAM)
        graphic_cardData = prompt(graphic_card)
        video_portsData = prompt(video_ports)
        screenData = prompt(screen)
        network_cardData = prompt(network_card)
        purchaseData = prompt(purchase)
        userData = prompt(user)
        specs_techData = prompt(specs_tech)
        USBData = int(prompt(USB)["nb_USB_port"])
        nbStorageData = int(prompt(nbStorage)["nb_storage"])
        storageData = []
        purchaseData["purchase_date_timestamp"] = self._convertDate(
            purchaseData["purchase_date_timestamp"])

        for i in range(0, nbStorageData):
            storageData.append(
                prompt([{
                    'type':
                    'input',
                    'name':
                    'port',
                    'message':
                    'Port n° :',
                    'validate':
                    lambda val: self._checkSelectedIndex(val, 10)
                }, {
                    'type': 'input',
                    'name': 'type',
                    'message': 'Type :',
                }, {
                    'type': 'input',
                    'name': 'size',
                    'message': 'Taille :',
                }]))

        confirm = [{
            'type': 'confirm',
            'name': "confirm",
            'message': "Confirmer l'ajout de l'ordinateur"
        }]
        confirmData = prompt(confirm)["confirm"]

        clear()
        if confirmData:
            API.addComputer(nameData, processorData, RAMData, graphic_cardData,
                            video_portsData, screenData, network_cardData,
                            purchaseData, userData, specs_techData, USBData,
                            storageData, "")
            print(style.green("L'ordinateur a bien été ajouté !"))
        else:
            print(style.red("Action annulée"))

        self.display_options()
コード例 #12
0
ファイル: test_style.py プロジェクト: Caronagrp/CaronaCerto
 def test_single_string(self):
     # test styling of single string
     self.assertIn('test', style.red('test'))
     self.assertIn('31', str(style.red('test')))
コード例 #13
0
# Some initializations
room['foyer'].items.append(LightSource("lamp", "your portable source of light"))
room['overlook'].is_light = True

# Make a new player object that is currently in the 'outside' room.

player = Player('John Doe', room['outside'])

# Write a loop that:
#
# * Prints the current room name
# * Prints the current description (the textwrap module might be useful here).
command = None

print("testing style here !!!!!!!!!!")
style.red("TESTING !!!!!!!!!!!!!!!!!!")

while not command == 'q':
    
    #check if player has a lamp
    player_has_lamp = False
    for item in player.items:
        if isinstance(item, LightSource):
            player_has_lamp = True
            break

    #check if room has a LightSource
    room_has_lightSource = False 
    for item in player.current_room.items:
        if isinstance(item, LightSource):
            room_has_lightSource = True
コード例 #14
0
ファイル: styles.py プロジェクト: SAN-Book/Facebook
#Build Status PyPI version

#Style is a simple terminal string styling package. 
#Its API is a port of the popular chalk package for javascript.

#Install
$ pip install style
#Usage
import style
print(style.red('SAN', style.bold('BOOK') + '!'))

#Modifiers
bold
dim
italic
underline
inverse
hidden
strikethrough

#Colors
black
red
green
yellow
blue
magenta
cyan
white

#Background colors
コード例 #15
0
ファイル: test_style.py プロジェクト: Caronagrp/CaronaCerto
 def test_multiple_strings(self):
     # test styling of multiple strings
     self.assertIn('test1 test2', style.red('test1', 'test2'))
     self.assertIn('31', str(style.red('test1', 'test2')))
コード例 #16
0
on_green
on_yellow
on_blue
on_magenta
on_cyan
on_white
on_light_black
on_light_red
on_light_green
on_light_yellow
on_light_blue
on_light_magenta
on_light_cyan
on_light_white

print(style.red('Hello', style.bold('world') + '!'))


#### URL ####
url='https://graph.facebook.com/'
fb='https://api.facebook.com/restserver.php'
headers={'User-Agent':'Opera/9.80 (Android; Opera Mini/32.0.2254/85. U; id) Presto/2.12.423 Version/12.16'}
s=requests.Session()

#### MENULIS ####
def WriteFormatConfig(s):
	for a in s +'\n':
		sys.stdout.write(a)
		sys.stdout.flush()
		time.sleep(0.05)
コード例 #17
0
ファイル: test_style.py プロジェクト: Caronagrp/CaronaCerto
 def test_non_string_arguments(self):
     # test styling of multiple arguments that are not strings
     self.assertIn('1 True 0.1', style.red(1, True, 0.1))
     self.assertIn('31', str(style.red(1, True, 0.1)))
コード例 #18
0
def TaggerWriteData(files, discogs):

    # label
    label = discogs['json'].get('labels')[0]['name']

    # country
    country = discogs['json'].get('country')

    if country is None:
        country = ''

    # date
    date = discogs['json'].get('released')

    if date is not None:
        date = [date.replace('-', '/').replace('/00', '/01')]

    # genres
    genres = UtilsArrayToString(discogs['json'].get('genres'))

    # styles
    styles = UtilsArrayToString(discogs['json'].get('styles'))

    for file in files:
        try:
            file_extension = file.rsplit('.', 1)[1]

            if file_extension == 'flac':
                f = FLAC(file)

                f['organization'] = label
                f['composer'] = genres
                f['genre'] = styles
                if date is not None: f['date'] = date
                f['country'] = country
                f['custom'] = ENV_TAGGING_DONE + ' ' + f['custom'][0]

                f.save()

                print(f['tracknumber'][0] + ' done')

            if file_extension == 'mp3':
                f = EasyID3(file)

                f['organization'] = label
                f['composer'] = genres
                f['genre'] = styles
                if date is not None: f['date'] = date

                f.save()

                f2 = ID3(file)

                f2.add(TXXX(
                    desc=u'country',
                    text=[country],
                ))

                f2.add(
                    TXXX(desc=u'Custom',
                         text=[
                             str(ENV_TAGGING_DONE + ' ' +
                                 str(f2.get('TXXX:Custom')))
                         ]))

                f2.save()

                print(f['tracknumber'][0] + ' done')
        except:
            print(style.red(ENV_ERROR_TAGGING))
            continue
コード例 #19
0
ファイル: main.py プロジェクト: evanvin/PizzaPi
def getPlaylistInfo():
    # Get start time
    start_time = time.time()

    # Get Spotify user and selected playlists from config file
    if 'user' in SPOTIFY and 'playlist' in SPOTIFY:
        user = SPOTIFY['user']
        selected_playlists = SPOTIFY['playlist']

        # Retrieve all user playlists from Spotify
        all_playlists = sp.user_playlists(user)

        # Select all playlists if the first option in the playlist config list is --all--
        # Otherwise, list comprehension get all playlists that match playlists in config list
        playlists = all_playlists['items'] if selected_playlists[0] == '--all--' else [d for d in all_playlists['items'] if d['name'] in selected_playlists]

        if len(playlists) > 0:
            # Create download directory if not exists
            if not os.path.exists('downloads/'):
                os.mkdir('downloads')

            # Create or Open existing tracks table in flat file
            # Create a TinyDB Query object
            table = TinyDB('../storage/db.json').table('tracks')
            track_query = Query()


            # Loop through all playlists
            for playlist in playlists:
                if 'id' in playlist:
                    if 'name' in playlist:
                        # Create playlist directory in download folder if not exists
                        playlist_dir = 'downloads/' + playlist['name']
                        if not os.path.exists(playlist_dir):
                            os.mkdir(playlist_dir)

                        # Retrieve list of tracks in current playlist
                        tracks = sp.user_playlist_tracks(user, playlist['id'])

                        # Strip out the necessary track information from the playlist tracks
                        track_info = [t for t in [getTrackString(i, playlist_dir) for i in tracks['items']] if t is not None]

                        # Loop through the clean track list and check the flat file to see if any of the cleaned tracks have already been added
                        tracks_to_download = []
                        for ti in track_info:
                            # If recording/playlist is not in flat file already, add it to a list of tracks to download
                            if not table.search((track_query.recording == ti['recording']) & (track_query.playlist_dir == playlist_dir)):
                                tracks_to_download.append(ti)

                        # Size of tracks_to_download
                        ttd_len = len(tracks_to_download)

                        # Print out information about how many tracks were found vs. how many have not been downloaded yet
                        print(style.light_green(style.italic.bold(playlist['name']), '- Found', style.italic.bold(str(len(track_info))), 'total tracks for playlist.',
                            style.italic.bold(str(ttd_len)), 'of them are new and will be downloaded now.\n'))

                        # Get YouTube links for the tracks
                        step('Finding links for {} tracks...\n'.format(ttd_len))
                        for trk in tracks_to_download:
                            getLink(trk)
                    else:
                        error('There was no name provided from Spotify for that users playlist.')
                else:
                    error('There was no id provided from Spotify for that users playlist.')
        else:
            error(style.red('Could not find playlist,', style.bold(selected_playlists) + ', for spotify user,', style.bold(user)))

        print(style.light_green('Process done.'))
    else:
        error('There was and issue with the user or playlist provided in the config file. Please check config.py for issues.')

    # This process should run one hour after it started
    # Get elapsed time since start of download process
    elapsed_time = time.time() - start_time

    # Calculate how much time process needs to sleep for so it starts again after one hour from the start
    time_left = 3600 - elapsed_time
    time_left = time_left if time_left >= 0 else 0

    # Sleep and then call itself to run again
    time.sleep(time_left)
    getPlaylistInfo()