Exemplo n.º 1
0
def connect(creds='creds.secret', access='client.secret') -> dropbox.Dropbox:
    """
    Authorises application w/ user and loads client
    """
    parent = Path(__file__).resolve().parent
    app = loadcreds(parent / creds)
    access_p = parent / access

    user = None
    if access_p.exists():
        with open(access_p, 'rb') as token:
            user = pickle.load(token)

    if not user:
        flow = dropbox.DropboxOAuth2FlowNoRedirect(*app)
        redirect = flow.start()
        print(
            f"Redirecting for authorisation: {redirect}\nCtl-C to continue...")
        wbopen(redirect)
        token = input("Copy access token here: ").strip()
        if not token:
            print("Error: bad input", file=stderr)
            exit(1)
        user = flow.finish(token)
        with open(access_p, 'wb+') as token:
            pickle.dump(user, token)
    return dropbox.Dropbox(user.access_token)
Exemplo n.º 2
0
    def plot(self, *args, **kwargs):
        res = self.__callplot(*args, **kwargs)
        if "error" in res and res["error"] == "" and self.open:
            from webbrowser import open as wbopen

            wbopen(res["url"])
        return res
def open_page():
    """
    Open web page in browser
    :return:
    """

    wbopen("http://127.0.0.1:8080/")
Exemplo n.º 4
0
def get_refresh_token(client_id, client_secret):
    scopes = ["read", "edit", "history"]
    reddit = praw.Reddit(
        client_id=client_id,
        client_secret=client_secret,
        redirect_uri="http://localhost:9575",
        user_agent="CDR_Get_Refresh_Token"
    )
    state = str(randint(0, 65000))
    url = reddit.auth.url(scopes, state, "permanent")
    wbopen(url)
    client = receive_connection()
    data = client.recv(1024).decode("utf-8")
    param_tokens = data.split(" ", 2)[1].split("?", 1)[1].split("&")
    params = {
        key: value for (key, value) in [token.split("=") for token in param_tokens]
    }
    if state != params["state"]:
        client.send("HTTP/1.1 200 OK\r\n\r\nState Mismatch\nExpected {} Received: {}".format(state, params["state"])
                    .encode("utf-8"))
        client.close()
        return None
    elif "error" in params:
        client.send("HTTP/1.1 200 OK\r\n\r\n{}".format(params["error"]).encode("utf-8"))
        client.close()
        return None
    client.send("HTTP/1.1 200 OK\r\n\r\nSuccess, the refresh token should have been automatically entered in CDR.\n"
                "You may close this window."
                .encode("utf-8"))
    client.close()
    return reddit.auth.authorize(params["code"])
Exemplo n.º 5
0
	def plot(self, *args, **kwargs):
		res = self.__callplot(*args, **kwargs)
		if 'error' in res and res['error'] == '' and self.open:
			try:
				from webbrowser import open as wbopen
				wbopen(res['url'])
			except:
				pass
		return res
Exemplo n.º 6
0
def filters():
    if request.method == "POST":
        # Retrieve user inputs
        valence = request.form["valence"]
        popularity = request.form["popularity"]

        # Set valence settings
        minValence = float(0)
        maxValence = float(1)
        if valence == "Happy Music":
            minValence = float(0.75)
        elif valence == "Sad Music":
            maxValence = float(0.25)

        # Set popularity settings
        minPopularity = 0
        maxPopularity = 100
        if popularity == "Popular Music":
            minPopularity = 75
        elif popularity == "Unpopular Music":
            maxPopularity = 25

        # Get recommended tracks
        recommendations = sp.recommendations(
            seed_artists=artistList,
            seed_genres=genreList,
            limit=50,
            country="AU",
            min_valence=float(minValence),
            max_valence=float(maxValence),
            min_popularity=minPopularity,
            max_popularity=maxPopularity)['tracks']
        trackList = []
        for recommendedTrack in range(len(recommendations)):
            trackList.append(recommendations[recommendedTrack]['uri'])

        # Get playlist URI
        playlistCode = sp.current_user_playlists(limit=1)['items'][0]['uri']

        # Get playlist embed code
        uriSplit = playlistCode.split("playlist:")
        uriEmbed = uriSplit[1]
        embedCode = "https://open.spotify.com/embed/playlist/" + uriEmbed

        # Add tracks to playlist
        sp.user_playlist_add_tracks(username,
                                    playlist_id=playlistCode,
                                    tracks=trackList)

        # Open playlist
        wbopen(playlistCode)
        return render_template("success.html", embedCode=embedCode)
    else:
        return render_template("filters.html")
Exemplo n.º 7
0
def disp_reddit():
    reddit = Reddit_Scraper(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, version=0.1)
    prmpt.out("Displaying latest release news collected by Reddit")
    prmpt.out("Date format is: MM/DD/YYYY")
    urls = reddit.scrape(subreddit='sneakers', flair='release', limit=500, sort_by='top', posts_from='month')
    prmpt.out("Enter the number of the post to open || Enter e to exit to main menu")
    inp = input(">>> ")
    
    while not inp in urls and not inp == 'e':
        inp = input(">>> ")
    
    if inp == 'e':
        clr()
        disp_main()
        return

    wbopen(urls[inp])
    disp_reddit()
Exemplo n.º 8
0
def plot(figure_or_data, **plot_options):
    """returns a url with the graph
        opens the graph in the browser if plot_options['auto_open'] is True
    """
    if isinstance(figure_or_data, dict):
        figure = figure_or_data
    elif isinstance(figure_or_data, list):
        figure = {'data': figure_or_data}
    else:
        raise exceptions.PlotlyError("The `figure_or_data` positional argument "
                                     "must be either `dict`-like or "
                                     "`list`-like.")

    res = _send_to_plotly(figure, **plot_options)
    if ('error' in res) and ('auto_open' in plot_options):  # TODO: OK?
        if (res['error'] == '') and plot_options['auto_open']:
            try:
                from webbrowser import open as wbopen
                wbopen(res['url'])
            except:  # TODO: what should we except here? this is dangerous
                pass
    return res
Exemplo n.º 9
0
def plot(figure_or_data, **plot_options):
    """returns a url with the graph
        opens the graph in the browser if plot_options['auto_open'] is True
    """
    if isinstance(figure_or_data, dict):
        figure = figure_or_data
    elif isinstance(figure_or_data, list):
        figure = {'data': figure_or_data}
    else:
        raise exceptions.PlotlyError(
            "The `figure_or_data` positional argument "
            "must be either `dict`-like or "
            "`list`-like.")

    res = _send_to_plotly(figure, **plot_options)
    if ('error' in res) and ('auto_open' in plot_options):  # TODO: OK?
        if (res['error'] == '') and plot_options['auto_open']:
            try:
                from webbrowser import open as wbopen
                wbopen(res['url'])
            except:  # TODO: what should we except here? this is dangerous
                pass
    return res
Exemplo n.º 10
0
def plot(figure_or_data, validate=True, **plot_options):
    """Create a unique url for this plot in Plotly and optionally open url.

    plot_options keyword agruments:
    filename (string) -- the name that will be associated with this figure
    fileopt ('new' | 'overwrite' | 'extend' | 'append') -- 'new' creates a
        'new': create a new, unique url for this plot
        'overwrite': overwrite the file associated with `filename` with this
        'extend': add additional numbers (data) to existing traces
        'append': add additional traces to existing data lists
    world_readable (default=True) -- make this figure private/public
    auto_open (default=True) -- Toggle browser options
        True: open this plot in a new browser tab
        False: do not open plot in the browser, but do return the unique url

    """
    if isinstance(figure_or_data, dict):
        figure = figure_or_data
    elif isinstance(figure_or_data, list):
        figure = {'data': figure_or_data}
    else:
        raise exceptions.PlotlyError("The `figure_or_data` positional argument "
                                     "must be either `dict`-like or "
                                     "`list`-like.")
    if validate:
        try:
            tools.validate(figure, obj_type='Figure')
        except exceptions.PlotlyError as err:
            raise exceptions.PlotlyError("Invalid 'figure_or_data' argument. "
                                         "Plotly will not be able to properly "
                                         "parse the resulting JSON. If you "
                                         "want to send this 'figure_or_data' "
                                         "to Plotly anyway (not recommended), "
                                         "you can set 'validate=False' as a "
                                         "plot option.\nHere's why you're "
                                         "seeing this error:\n\n{}".format(err))
    for entry in figure['data']:
        for key, val in entry.items():
            try:
                if len(val) > 40000:
                    msg = ("Woah there! Look at all those points! Due to "
                           "browser limitations, Plotly has a hard time "
                           "graphing more than 500k data points for line "
                           "charts, or 40k points for other types of charts. "
                           "Here are some suggestions:\n"
                           "(1) Trying using the image API to return an image "
                           "instead of a graph URL\n"
                           "(2) Use matplotlib\n"
                           "(3) See if you can create your visualization with "
                           "fewer data points\n\n"
                           "If the visualization you're using aggregates "
                           "points (e.g., box plot, histogram, etc.) you can "
                           "disregard this warning.")
                    warnings.warn(msg)
            except TypeError:
                pass
    plot_options = _plot_option_logic(plot_options)
    res = _send_to_plotly(figure, **plot_options)
    if res['error'] == '':
        if plot_options['auto_open']:
            try:
                from webbrowser import open as wbopen
                wbopen(res['url'])
            except:  # TODO: what should we except here? this is dangerous
                pass
        return res['url']
    else:
        raise exceptions.PlotlyAccountError(res['error'])
Exemplo n.º 11
0
def main():
    """Provide the program's entry point when directly executed."""
    config = ConfigParser()
    config.read(DATA_PATH + "/praw.ini")
    client_id = config["credentials"]["client_id"]
    client_secret = config["credentials"]["client_secret"]
    scopes = ["privatemessages", "read"]

    reddit = praw.Reddit(
        client_id=client_id.strip(),
        client_secret=client_secret.strip(),
        redirect_uri="http://localhost:9575",
        user_agent="praw_refresh_token_example",
    )
    state = str(random.randint(0, 65000))
    url = reddit.auth.url(scopes, state, "permanent")
    print("If it didn't automatically open, click the following link: " + url)
    wbopen(url)
    sys.stdout.flush()

    client = receive_connection()
    data = client.recv(1024).decode("utf-8")
    param_tokens = data.split(" ", 2)[1].split("?", 1)[1].split("&")
    params = {
        key: value
        for (key, value) in [token.split("=") for token in param_tokens]
    }

    if state != params["state"]:
        send_message(
            client,
            "State mismatch. Expected: {} Received: {}".format(
                state, params["state"]),
        )
        return 1
    elif "error" in params:
        send_message(client, params["error"])
        return 1

    refresh_token = reddit.auth.authorize(params["code"])
    try:
        del config
        config = ConfigParser()
        config["credentials"] = {
            "client_id": client_id,
            "client_secret": client_secret,
            "refresh_token": refresh_token
        }
        with open(DATA_PATH + "/praw.ini", "w") as f:
            config.write(f)
    except:
        send_message(
            client,
            "WARNING: VALUE HAS NOT BEEN AUTOMATICALLY ENTERED!\nCopy paste the following 3 lines into"
            " the praw.ini file and delete everything that was there originally:\n[credentials]\n"
            "client_id = {}\nclient_secret = {}\nrefresh_token = {}\n".format(
                client_id, client_secret, refresh_token))
    else:
        send_message(
            client,
            "Value has successfully been automatically entered, you can close this window now."
        )
    return 0
Exemplo n.º 12
0
def _open_url(url):
    try:
        from webbrowser import open as wbopen
        wbopen(url)
    except:  # TODO: what should we except here? this is dangerous
        pass
Exemplo n.º 13
0
 def run_search(self):
     self.search_query = self.search_query.replace(" ", "+")
     # performs a search for the query on youtube
     wbopen("https://www.youtube.com/results?search_query={}".format(
         self.search_query))
Exemplo n.º 14
0
 def plot(self, *args, **kwargs):
     res = self.__callplot(*args, **kwargs)
     if 'error' in res and res['error'] == '' and self.open:
         from webbrowser import open as wbopen
         wbopen(res['url'])
     return res
Exemplo n.º 15
0
Arquivo: main.py Projeto: Houet/Japon
 def help(self):
     """ return https://github.com/Houet/Japon """
     return wbopen("https://github.com/Houet/Japon")
Exemplo n.º 16
0
def _open_url(url):
    try:
        from webbrowser import open as wbopen
        wbopen(url)
    except:  # TODO: what should we except here? this is dangerous
        pass
Exemplo n.º 17
0
    print("Anime non presente nel database")
    answer = input("Si desidera inserirlo? Y/n ")
    if answer.lower() == "y":
        animeInsert(animeName)
    quit()

epNum = findEpNum(animeName)
desEpNum = epNum + numEp
index = string.find("Ep_") + 3
while (epNum < desEpNum):
    epNum += 1
    epNumStr = str(epNum)
    if (len(epNumStr) == 1):
        epNumStr = '0' + epNumStr
    string = string[:index] + epNumStr + string[-12:]
    try:
        urllib.request.urlopen(string)
        wbopen(string)
        sleep(5)
        cur.execute("UPDATE anime SET num=? WHERE name=?", (epNum, animeName))
        db.commit()
    except HTTPError:
        print("Episodio non esistente o link anime modificato")
        pass
    else:
        while (downloadIsNotCompleted()):
            pass
        print(str(animeName) + "-" + str(epNum), "scaricato correttamente")

if db:
    db.close()
Exemplo n.º 18
0
def plot(figure_or_data, validate=True, **plot_options):
    """Create a unique url for this plot in Plotly and optionally open url.

    plot_options keyword agruments:
    filename (string) -- the name that will be associated with this figure
    fileopt ('new' | 'overwrite' | 'extend' | 'append') -- 'new' creates a
        'new': create a new, unique url for this plot
        'overwrite': overwrite the file associated with `filename` with this
        'extend': add additional numbers (data) to existing traces
        'append': add additional traces to existing data lists
    world_readable (default=True) -- make this figure private/public
    auto_open (default=True) -- Toggle browser options
        True: open this plot in a new browser tab
        False: do not open plot in the browser, but do return the unique url

    """
    if isinstance(figure_or_data, dict):
        figure = figure_or_data
    elif isinstance(figure_or_data, list):
        figure = {'data': figure_or_data}
    else:
        raise exceptions.PlotlyError(
            "The `figure_or_data` positional argument "
            "must be either `dict`-like or "
            "`list`-like.")
    if validate:
        try:
            tools.validate(figure, obj_type='Figure')
        except exceptions.PlotlyError as err:
            raise exceptions.PlotlyError(
                "Invalid 'figure_or_data' argument. "
                "Plotly will not be able to properly "
                "parse the resulting JSON. If you "
                "want to send this 'figure_or_data' "
                "to Plotly anyway (not recommended), "
                "you can set 'validate=False' as a "
                "plot option.\nHere's why you're "
                "seeing this error:\n\n{}".format(err))
    for entry in figure['data']:
        for key, val in entry.items():
            try:
                if len(val) > 40000:
                    msg = ("Woah there! Look at all those points! Due to "
                           "browser limitations, Plotly has a hard time "
                           "graphing more than 500k data points for line "
                           "charts, or 40k points for other types of charts. "
                           "Here are some suggestions:\n"
                           "(1) Trying using the image API to return an image "
                           "instead of a graph URL\n"
                           "(2) Use matplotlib\n"
                           "(3) See if you can create your visualization with "
                           "fewer data points\n\n"
                           "If the visualization you're using aggregates "
                           "points (e.g., box plot, histogram, etc.) you can "
                           "disregard this warning.")
                    warnings.warn(msg)
            except TypeError:
                pass
    plot_options = _plot_option_logic(plot_options)
    res = _send_to_plotly(figure, **plot_options)
    if res['error'] == '':
        if plot_options['auto_open']:
            try:
                from webbrowser import open as wbopen
                wbopen(res['url'])
            except:  # TODO: what should we except here? this is dangerous
                pass
        return res['url']
    else:
        raise exceptions.PlotlyAccountError(res['error'])
Exemplo n.º 19
0
def open_url(url):
    """根据URL打开浏览器 ."""
    from webbrowser import open as wbopen
    wbopen(url)
Exemplo n.º 20
0
from spotipy import Spotify
from spotipy.util import prompt_for_user_token
from flask import Flask, render_template, request
from webbrowser import open as wbopen

# Initialise globals
app = Flask(__name__)
username = ""
artistList = []
genreList = []
sp = Spotify

# Open browser
wbopen('http://127.0.0.1:5000/')


@app.route("/", methods=["POST", "GET"])
def login():
    if request.method == "POST":
        # Retrieve username
        global username, sp
        username = request.form["usernameInput"]

        # Authorisation
        token = prompt_for_user_token(
            username=username,
            scope=
            'playlist-read-private user-top-read user-library-read playlist-modify-private playlist-modify-public',
            client_id='YOUR_CLIENT_ID_GOES_HERE',
            client_secret='YOUR_CLIENT_SECRET_GOES_HERE',
            redirect_uri='http://localhost:8080')
Exemplo n.º 21
0
	def plot(self, *args, **kwargs):
		res = self.__callplot(*args, **kwargs)
		if res['error'] == '' and self.open:
			from webbrowser import open as wbopen
			wbopen(res['url'])
		return res
import requests
from webbrowser import open as wbopen


def get_article():
    """Pulls JSON from wikipedia API using requests module"""
    url = ("https://en.wikipedia.org/w/api.php?action=query&list="
           "random&rnnamespace=0&rnlimit=10&format=json")
    resp = requests.get(url, headers={"User-agent": "Simple Test"})
    data = resp.json()

    if "error" not in data.keys():
        return data
    else:
        print("Error fecthing articles.")


while True:
    articles = get_article()
    for article in articles["query"]["random"]:
        resp = ""
        while resp.lower().strip() not in ("y", "yes", "n", "no"):
            resp = input("Would you like to read about " + article["title"] +
                         "? [y/n]\n>>")
        if resp.lower().strip() in ("y", "yes"):
            wbopen("https://en.wikipedia.org/wiki?curid=" + str(article["id"]))
            input("Press the [enter] key to continue")
        elif resp.lower().strip() in ("n", "no"):
            continue