Ejemplo n.º 1
0
    def display_installed_software(self, computer_id):
        computer = API.getComputer(computer_id)
        clear()
        print(
            style.bold("\nListe des logiciels installés sur l'ordinateur " +
                       computer['name'] + " :\n"))

        count = 0
        for software in computer['softwares']:
            print(API.getSoftware(software)['name'])

        print("\n")
        print(Separator())
        print("\n")

        options = [
            {
                'type':
                'list',
                'name':
                'menu_software_detail',
                'message':
                'Selectionner un des menus avec les flèches du clavier.',
                'choices':
                ['Editer les logiciels installés',
                 Separator(), "Retour"]
            },
        ]

        res = prompt(options)  ##On affiche le formulaire

        try:
            res_index = options[0]['choices'].index(
                res["menu_software_detail"])

            if res_index == 0:  ##Formulaire d'edition de l'ordinateur
                self.edit_software_in_computer(computer_id)

            elif res_index == 2:  ##Retour
                clear()
                self.display_computer_detail(computer_id)
        except:
            self.display_installed_software(computer_id)
Ejemplo n.º 2
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)
Ejemplo n.º 3
0
def _print_update_instructions(package):
    '''
    '''
    print(style.yellow('A new version of', style.bold(package), 'is available.\nRun',
                       style.bold('pip install -U', package), 'to upgrade.'), end='\n'*2)
Ejemplo n.º 4
0
                                def repl(match):

                                    return style.bold(match.group(0))
Ejemplo n.º 5
0
                                def repl(match):

                                    return style.bold(match.group(0))
Ejemplo n.º 6
0
async def parse_feed():
    d = feedparser.parse(feed_url)

    feed = d.entries
    if not await valid_feed(d):
        logging.warning("Empty feed; backing out..")
        return

    discord_message = ""
    for e in feed:
        sp = BeautifulSoup(e.summary, 'html.parser')
        if not await valid_entry(e, sp):
            logging.warning("Unwanted or malformed feed item; backing out..")
            continue

        identifier = e.id
        author = sp.span['title'].strip() if sp.span else '--'
        message = sp.blockquote.string.strip(
        ) if sp.blockquote.string else '--'
        url = 'https://github.com' + sp.code.a[
            'href'] if sp.code and sp.code.a and sp.code.a['href'] else '--'
        wilcox = author in wilcox_aliases
        date = datetime.fromtimestamp(mktime(
            e.updated_parsed)) if e.updated_parsed else '--'

        entry = {
            'identifier': identifier,
            'author': author,
            'url': url,
            'wilcox': wilcox,
            'date': date
        }

        entry.update({
            'message':
            '\u200b\n{}\n{}\n{}\n\n'.format(style.bold(author + ':'), message,
                                            url)
        })

        # if wilcox:
        #     entry.update({'message': '\u200b\n{}\n{}\n{}\n{}\n{}\n\n'.format(
        #         wilcox_alert, style.bold(author + ':'),
        #         message, url, wilcox_alert)
        #     })
        # else:
        #     entry.update({'message': '\u200b\n{}\n{}\n{}\n\n'.format(
        #         style.bold(author + ':'), message,
        #         url)
        #     })

        if await is_new(entry):
            discord_message = ''.join([entry['message'], discord_message])
            cursor.execute(
                """
                INSERT INTO entries(
                    identifier, author, message,
                    url, wilcox, date
                )
                    VALUES(
                    :identifier, :author, :message,
                    :url, :wilcox, :date
                )
            """, entry)

            db.commit()

    await send(discord_message)
Ejemplo n.º 7
0
#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
Ejemplo n.º 8
0
	for test_index in range(1,len(test_data)):
		if(not min_required_data_present_in(test_index,test_data)):
			print blue(test_name) + warn(": Insuffecient data to run test")
			test_not_executed += 1
			continue

		test_name = replace_with_global_data(get_test_name(test_index,test_data,test_file_name))

		request_data = get_request_data(test_index,test_data)
		for request_key, request_value in request_data.iteritems():
			request_data[request_key]=replace_with_global_data(request_data[request_key])

		request_method = get_request_method(test_index,test_data)
		request_url = get_request_url(test_index,test_data)
        	
		response = None 
		try:
			if(request_method.lower() == POST):
				response = requests.post(request_url,data=request_data)
			else:
				response = requests.get(request_url,params=request_data)
		except:
			pass

		check_test_result(test_name,test_index,response,test_data)

print header("Results:")
print blue("Total tests: ") + bold(str(test_count)) + blue(", Tests passed : ") + bold(str(test_passed)) + blue(", Tests failed : ") + bold(str(test_failed))+ blue(", Tests not executed : ") + bold(str(test_not_executed))

Ejemplo n.º 9
0
    def edit_computer_detail(self, computer_id):
        clear()

        computer = API.getComputer(computer_id)

        print(
            style.bold("\nEdition de l'ordinateur " + computer['name'] +
                       " :\n"))

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

        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",
            'default':
            str(computer["specs"]["processor"]["plateform"])
        }, {
            'type': 'input',
            'name': 'brand',
            'message': 'Marque du processeur :',
            'default': str(computer["specs"]["processor"]["brand"])
        }, {
            'type': 'input',
            'name': 'speed',
            'message': 'Vitese du processeur :',
            'default': str(computer["specs"]["processor"]["speed"])
        }, {
            'type':
            'input',
            'name':
            'size_cache',
            'message':
            'Taille du Cache :',
            'default':
            str(computer["specs"]["processor"]["size_cache"])
        }, {
            'type': 'input',
            'name': 'model',
            'message': 'Modèle de processeur :',
            'default': str(computer["specs"]["processor"]["model"])
        }]
        RAM = [{
            'type': 'input',
            'name': 'number',
            'message': 'Nombre de RAM :',
            'validate': lambda val: self._checkSelectedIndex(val, 10),
            'default': str(computer["specs"]["RAM"]["number"])
        }, {
            'type': 'input',
            'name': 'total_size',
            'message': 'Taille totale de la RAM :',
            'default': str(computer["specs"]["RAM"]["total_size"])
        }]
        graphic_card = [{
            'type':
            'input',
            'name':
            'brand',
            'message':
            'Marque de la carte graphique :',
            'default':
            str(computer["specs"]["graphic_card"]["brand"])
        }, {
            'type':
            'input',
            'name':
            'memory',
            'message':
            'Taille Mémoire de la carte graphique :',
            'default':
            str(computer["specs"]["graphic_card"]["memory"])
        }, {
            'type':
            'input',
            'name':
            'model',
            'message':
            'Modèle de la carte graphique :',
            'default':
            str(computer["specs"]["graphic_card"]["model"])
        }]
        video_ports = [{
            'type':
            'checkbox',
            'message':
            'Selectionner les ports disponibles',
            'name':
            'video_port',
            'choices': [{
                'name':
                'VGA',
                'checked':
                True if 'VGA' in computer["specs"]["video_port"] else False
            }, {
                'name':
                'HDMI',
                'checked':
                True if 'HDMI' in computer["specs"]["video_port"] else False
            }, {
                'name':
                'Display-Port',
                'checked':
                True
                if 'Display-Port' in computer["specs"]["video_port"] else False
            }, {
                'name':
                'DVI-A',
                'checked':
                True if 'DVI-A' in computer["specs"]["video_port"] else False
            }, {
                'name':
                'DVI-D',
                'checked':
                True if 'DVI-D' in computer["specs"]["video_port"] else False
            }, {
                'name':
                'USB-C',
                'checked':
                True if 'USB-C' in computer["specs"]["video_port"] else False
            }]
        }]
        screen = [{
            'type': 'input',
            'name': 'screen_res',
            'message': "Résolution de l'écran :",
            'validate': lambda val: self._checkSelectedIndex(val, 10000),
            'default': str(computer["specs"]["screen"]["screen_res"])
        }, {
            'type': 'input',
            'name': 'screen_size_x',
            'message': "Largeur de l'écran (en px) :",
            'validate': lambda val: self._checkSelectedIndex(val, 10000),
            'default': str(computer["specs"]["screen"]["screen_size"][0])
        }, {
            'type': 'input',
            'name': 'screen_size_y',
            'message': "Longueur de l'écran (en px) :",
            'validate': lambda val: self._checkSelectedIndex(val, 30000),
            'default': str(computer["specs"]["screen"]["screen_size"][1])
        }]
        network_card = [{
            'type':
            'input',
            'name':
            'speed',
            'message':
            'Vitesse de la carte réseau :',
            'default':
            str(computer['specs']["network_card"]["speed"])
        }, {
            'type':
            'input',
            'name':
            'brand',
            'message':
            'Marque de la carte réseau :',
            'default':
            str(computer['specs']["network_card"]["brand"])
        }]
        purchase = [{
            'type': 'input',
            'name': 'maker',
            'message': "Fabricant de l'ordinateur:",
            'default': str(computer['specs']["maker"])
        }, {
            'type': 'input',
            'name': 'provider',
            'message': "Fournisseur de l'ordinateur:",
            'default': str(computer['specs']["provider"])
        }, {
            'type':
            'input',
            'name':
            'purchase_date_timestamp',
            'message':
            "Date d'achat :",
            'validate':
            lambda val: self._checkDate(val),
            'default':
            str(
                datetime.fromtimestamp(
                    computer["specs"]["purchase_date_timestamp"]).strftime(
                        "%d/%m/%Y"))
        }]

        user = [{
            'type': 'input',
            'name': 'name',
            'message': 'Nom :',
            'default': str(computer["user"]['name'])
        }, {
            'type': 'input',
            'name': 'username',
            'message': "Nom d'utilisateur :",
            'default': str(computer["user"]['username'])
        }]
        specs_tech = [{
            'type':
            'checkbox',
            'message':
            'Selectionner les characteristiques technique',
            'name':
            'specs_tech',
            'choices': [{
                'name':
                'Lecteur CD',
                'checked':
                True if computer["specs"]["CD_player"] else False
            }, {
                'name': 'Wifi',
                'checked': True if computer["specs"]["wifi"] else False
            }, {
                'name':
                'Bluetooth',
                'checked':
                True if computer["specs"]["bluetooth"] else False
            }]
        }]
        USB = [{
            'type': 'input',
            'name': 'nb_USB_port',
            'message': "Combien l'ordinateur à t'il de ports USB ? :",
            'validate': lambda val: self._checkSelectedIndex(val, 10),
            'default': str(computer["specs"]['nb_USB_port'])
        }]
        nbStorage = [{
            'type': 'input',
            'name': 'nb_storage',
            'message': "Combien d'espaces de stockage l'ordinateur a t'il ? :",
            'validate': lambda val: self._checkSelectedIndex(val, 10),
            'default': str(len(computer["specs"]['storage']))
        }]

        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),
                    'default':
                    str(computer['specs']['storage'][i]['port'])
                    if len(computer['specs']['storage']) > i else ""
                }, {
                    'type':
                    'input',
                    'name':
                    'type',
                    'message':
                    'Type :',
                    'default':
                    str(computer['specs']['storage'][i]['type'])
                    if len(computer['specs']['storage']) > i else ""
                }, {
                    'type':
                    'input',
                    'name':
                    'size',
                    'message':
                    'Taille :',
                    'default':
                    str(computer['specs']['storage'][i]['size'])
                    if len(computer['specs']['storage']) > i else ""
                }]))

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

        if confirmData:
            new_computer = {
                "name": nameData,
                "softwares": [],
                "specs": {
                    "processor":
                    processorData,
                    "RAM":
                    RAMData,
                    "graphic_card":
                    graphic_cardData,
                    "video_port":
                    video_portsData,
                    "screen": {
                        "screen_res":
                        screenData["screen_res"],
                        "screen_size": [
                            screenData["screen_size_x"],
                            screenData["screen_size_y"]
                        ]
                    },
                    "nb_USB_port":
                    USBData,
                    "storage":
                    storageData,
                    "network_card":
                    network_cardData,
                    "CD_player":
                    "Lecteur CD" in specs_techData["specs_tech"],
                    "wifi":
                    "Wifi" in specs_techData["specs_tech"],
                    "bluetooth":
                    "Bluetooth" in specs_techData["specs_tech"],
                    "maker":
                    purchaseData["maker"],
                    "provider":
                    purchaseData["provider"],
                    "purchase_date_timestamp":
                    purchaseData["purchase_date_timestamp"]
                },
                "user": userData,
                "localisation": computer["localisation"]
            }
            API.setComputer(computer_id, new_computer)

        self.display_computer_detail(computer_id)
Ejemplo n.º 10
0
    def display_computer_detail(self, computer_id):

        computer = API.getComputer(
            computer_id)  ##Demander l'id de l'ordi à l'utilisateur

        clear()

        print("Ordinateur : " + str(computer['name']) + "\n")
        print(Separator())
        print(style.bold("\nSpécifications techniques :"))

        #Computer
        print(style.blue("\nProcesseur :"))
        print(
            style.light_cyan("\t" + "Architecture : ") +
            str(computer["specs"]["processor"]["plateform"]) + " bits")
        print(
            style.light_cyan("\t" + "Marque : ") +
            str(computer["specs"]["processor"]["brand"]))
        print(
            style.light_cyan("\t" + "Vitesse : ") +
            str(computer["specs"]["processor"]["speed"]))
        print(
            style.light_cyan("\t" + "Cache : ") +
            str(computer["specs"]["processor"]["size_cache"]))
        print(
            style.light_cyan("\t" + "Modèle : ") +
            str(computer["specs"]["processor"]["model"]))

        #RAM
        print(style.blue("\nRAM :"))
        print(
            style.light_cyan("\t" + "Nombre de barette : ") +
            str(computer["specs"]["RAM"]["number"]))
        print(
            style.light_cyan("\t" + "Taille : ") +
            str(computer["specs"]["RAM"]["total_size"]))

        #Graphic card
        print(style.blue("\nCarte graphique :"))
        print(
            style.light_cyan("\t" + "Marque : ") +
            str(computer["specs"]["graphic_card"]["brand"]))
        print(
            style.light_cyan("\t" + "Mémoire : ") +
            str(computer["specs"]["graphic_card"]["memory"]))
        print(
            style.light_cyan("\t" + "Modèle : ") +
            str(computer["specs"]["graphic_card"]["model"]))

        #Video port
        print(style.blue("\nPorts vidéo :"))
        print(
            style.light_cyan("\t" + "Ports vidéo : ") +
            ', '.join(computer["specs"]["video_port"]))

        #Screen
        print(style.blue("\nEcran :"))
        print(
            style.light_cyan("\t" + "Résolution : ") +
            str(computer["specs"]["screen"]['screen_res']))
        print(
            style.light_cyan("\t" + "Taille : ") +
            str(computer["specs"]["screen"]['screen_size']).strip(
                '[]').replace(', ', 'x') + "px")

        #Connectors
        print(style.blue("\nConnectique :"))
        print(
            style.light_cyan("\t" + "Lecteur CD : ") +
            ("Oui" if computer["specs"]["CD_player"] else "Non"))
        print(
            style.light_cyan("\t" + "Ports USB : ") +
            str(computer["specs"]["nb_USB_port"]))

        #Stockage
        print(style.blue("\nStockage :"))

        n_storage = 1
        for storage in computer["specs"]['storage']:
            print(style.light_cyan("\tStockage " + str(n_storage) + " :"))
            print(style.magenta("\t\tType : ") + str(storage["type"]))
            print(style.magenta("\t\tPort : ") + str(storage["port"]))
            print(style.magenta("\t\tTaille : ") + str(storage["size"]))
            n_storage += 1

        #Network card
        print(style.blue("\nCarte réseau :"))
        print(
            style.light_cyan("\t" + "Vitesse : ") +
            str(computer["specs"]["network_card"]['speed']))
        print(
            style.light_cyan("\t" + "Marque : ") +
            str(computer["specs"]["network_card"]['brand']))

        #User
        print(style.blue("\nUtilisateur :"))
        print(
            style.light_cyan("\t" + "Nom : ") + str(computer["user"]['name']))
        print(
            style.light_cyan("\t" + "Nom  d'utilisation : ") +
            str(computer["user"]['username']))

        #Other
        print(style.blue("\nAutre :"))
        print(
            style.light_cyan("\t" + "WiFi : ") +
            ("Oui" if computer["specs"]["wifi"] else "Non"))
        print(
            style.light_cyan("\t" + "Bluetooth : ") +
            ("Oui" if computer["specs"]["bluetooth"] else "Non"))
        print(
            style.light_cyan("\t" + "Fabriquant : ") +
            str(computer["specs"]["maker"]))
        print(
            style.light_cyan("\t" + "Fournisseur : ") +
            str(computer["specs"]["provider"]))
        print(
            style.light_cyan("\t" + "Date d'achat : ") +
            datetime.fromtimestamp(computer["specs"]["purchase_date_timestamp"]
                                   ).strftime("%d/%m/%Y"))

        print("\n")
        print(Separator())

        print(style.bold("\nLocalisation :\n"))
        print(style.blue("Salle :"))

        if API.getRoom(computer["localisation"]) != None:
            print(
                style.light_cyan("\t" + "Nom : ") +
                API.getRoom(computer["localisation"])["room_name"])
            print(
                style.light_cyan("\t" + "Batiment : ") +
                API.getRoom(computer["localisation"])["building_name"])

        print("\n")
        print(Separator())
        print("\n")

        options = [
            {
                'type':
                'list',
                'name':
                'menu_computer_detail',
                'message':
                'Selectionner un des menus avec les flèches du clavier.',
                'choices': [
                    "Editer", "Logiciels installés",
                    "Ajouter une salle à cet ordinateur",
                    Separator(), "Retour"
                ]
            },
        ]

        res = prompt(options)  ##On affiche le formulaire

        try:
            res_index = options[0]['choices'].index(
                res["menu_computer_detail"])

            if res_index == 0:  ##Formulaire d'edition de l'ordinateur
                self.edit_computer_detail(computer_id)
            elif res_index == 1:  ##Formulaire des logiciels
                clear()
                self.display_installed_software(computer_id)
            elif res_index == 2:
                clear()
                self.display_rooms()
                self.ask_for_room(computer_id)
            elif res_index == 4:  ##Retour
                clear()
                if not self.computer_id:
                    self.display_options()
                else:
                    pass
        except:
            self.display_computer_detail(computer_id)
Ejemplo n.º 11
0
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()