Esempio n. 1
0
 def setUp(self):
     self.client = yweather.Client()
     data_file_name = os.path.join(os.path.dirname(__file__), "data",
                                   "data_weather.xml")
     with open(data_file_name) as f:
         self.root = xml.etree.ElementTree.parse(f).getroot()
     self.client._fetch_xml = self.return_root
Esempio n. 2
0
def intent(a):
    words = getWords(a)
    # --- update khal
    if a.lower().find('call me') != -1:
        jdump('name', a[a.lower().find('call me') +
                        8:])  #plus 8 because len(call me) + 1
        return 'Okay, will call you ' + a[a.lower().find('call me') + 8:]
    # --- "what's my name"
    if a.lower().find('my name') != -1:
        return 'I call you ' + khal['name']
    # --- find if user is asking for time
    time_text = ['time']
    for each in time_text:
        if each in words:
            now = datetime.datetime.now()
            res = 'It is ' + str(now.hour) + ' ' + str(now.minute)
            return res
    # --- weather data
    weather_text = ['weather']
    non_cap_weather = [
        'show', 'tell', 'what', 'is', 'the', 'weather', 'city', 'today',
        'right', 'now'
    ]
    for each in weather_text:
        if each in words:
            potential = GeoText(' '.join(
                [x for x in words if x not in non_cap_weather])).cities
            if potential != []:
                city = potential[0]
                client = yweather.Client()
                city = client.fetch_woeid(city)
            else:
                city = khal['city_id']
            return get_weather(city, 'simple')
    return a
Esempio n. 3
0
class TrendingTweets:
    client = yweather.Client()

    def getTrends(self, countryName, apiTweet):
        woeid = (TrendingTweets.client.fetch_woeid(countryName))

        print("Top trends for " + countryName + " which has woeid " +
              str(woeid))

        trend = (apiTweet.trends_place(woeid))
        data = trend[0]
        # grab the trends
        trends = data['trends']
        # grab the name from each trend
        # print(trends)
        dict = {}
        for trend in trends:
            volume = str([trend['tweet_volume']]).replace("[",
                                                          "").replace("]", "")
            trendName = trend['name']
            # print(volume)
            if (str(volume).isdigit() is True and "#" in trendName):
                dict[trendName] = int(volume)

        a1_sorted_keys = sorted(dict, key=dict.get, reverse=True)
        for r in a1_sorted_keys:
            print(r, dict[r])

        print("")
Esempio n. 4
0
 def setUp(self):
     self.client = yweather.Client()
     data_file_name = os.path.join(os.path.dirname(__file__), "data",
                                   "data_woeid.xml")
     with open(data_file_name) as f:
         root = xml.etree.ElementTree.parse(f).getroot()
     self.woeid = root.find("results/Result/woeid").text
Esempio n. 5
0
def main():
    args = get_args()
    twitterbot = get_bot()
    client = yweather.Client()
    where_on_earth_id = (client.fetch_woeid(args.location_name)
                         if args.location_name else 1)
    if where_on_earth_id is None:
        raise ValueError(
            "could not find 'where on earth id' of the location given")
    response, trending_tweets = twitterbot.get_trending(where_on_earth_id)
    print(json.dumps(trending_tweets))
Esempio n. 6
0
def weatherReport(city):
    client = yweather.Client( )
    woeid = client.fetch_woeid(city)
    weather = client.fetch_weather(woeid, metric=False)

    location ='{},{}'.format(weather['location']['city'], weather['location']['region'])

    todaysforecast = weather['forecast'][0]

    forecast = 'Location: {} \nDate:  {} \nHigh: {}ºF \nLow: {}ºF \nCloud Coverage: {}'.format(location, todaysforecast['date'], todaysforecast['high'], todaysforecast['low'], todaysforecast['text'])

    return forecast
Esempio n. 7
0
def get_top_trends_from_twitter_api(country='Japan', exclude_hashtags=True):
    """
    what is it useful for?
    participation. from twitter API docs

    How can I participate in a trend?
    Simply post a Tweet including the exact word or phrase as it appears in the trends list
    (with the hashtag, if you see one). Due to the large number of people Tweeting about these
    specific trends, you may not always be able to find your particular Tweet in search, but
    your followers will always see your Tweets.

    twitter Ads API has a keyword insights endpoint
    ref: https://developer.twitter.com/en/docs/ads/audiences/api-reference/keyword-insights.html#
    :param filter:
    :return:
    """
    # this stupid WOEID requires yweather to get (a library), because YAHOO itself has stopped supporting it
    # WOEID
    woeid_client = yweather.Client()
    woeid = woeid_client.fetch_woeid(location=country)

    if exclude_hashtags :
        trends = api.GetTrendsWoeid(woeid, exclude='hashtags')
    else:
        trends = api.GetTrendsWoeid(woeid, exclude=None)

    output = []
    for trend in trends:
        trend = trend.AsDict()

        # get volumes
        try:
            tw_volume = int(trend['tweet_volume']),
        except:
            tw_volume = [0]

        # match time with timezone
        timestamp_str = trend['timestamp']  # this is utc
        timestamp_dt = str_2_datetime(timestamp_str, input_format=time_format_twitter_trends).replace(tzinfo=pytz.utc)

        # timestamp_local = timestamp_dt.astimezone(tz=pytz.utc)
        timestamp_utc_str = datetime_2_str(timestamp_dt, output_format=time_format_full_with_timezone)

        output.append({
            "label": trend['name'],
            "volume": tw_volume,
            "time": timestamp_utc_str,
            "query": trend['query'],
            "url": trend['url']
        })

    output_json = json.dumps(output, ensure_ascii=False)
    return output_json
Esempio n. 8
0
def get(url):
    headers = {
        'Authorization': auth['token_type'] + " " + auth['access_token']
    }
    rq = requests.get("https://api.twitter.com/1.1/" + url, headers=headers)
    return json.loads(rq.text)

    client = yweather.Client()
    WOEID = client.fetch_woeid('Earth')

    rqdata = get("trends/place.json?id=" + WOEID)

    trends = rqdata[0]['trends']
Esempio n. 9
0
def main():
    client = yweather.Client()
    woeid = client.fetch_woeid(sys.argv[1])
    weather = client.fetch_weather(woeid, metric=False)
    location = '{}, {}'.format(weather['location']['city'],
                               weather['location']['region'])
    todaysforecast = weather['forecast'][0]
    forecaststring = '{} {} high: {}, low: {} {}'.format(
        location, todaysforecast['date'], todaysforecast['high'],
        todaysforecast['low'], todaysforecast['text'])
    while True:
        if time.strftime("%H") == "12" and time.strftime("%M") == "00":
            sendText(forecaststring, sys.argv[3])
            time.sleep(86400)
Esempio n. 10
0
def trends_json():
    region = request.args.get('region')
    client = yweather.Client()
    woeid = client.fetch_woeid(region)

    api = oauth_login(session['oauth_token'], session['oauth_token_secret'],
                      config.object.TWITTER_OAUTH_CONSUMER_KEY,
                      config.object.TWITTER_OAUTH_CONSUMER_SECRET)

    try:
        response = api.trends.place(_id=woeid)
        return jsonify(status="ok", trends=response[0]['trends'])
    except:
        print("erro")
        return jsonify(status="error")
Esempio n. 11
0
    def get_woe_id(self, place: str):
        if globals.__DEBUG__:
            logging.debug("GeoHelper:get_woe_id():place:{}".format(place))

        woeid = None

        try:
            client = yweather.Client()

            woeid = client.fetch_woeid(place)
        except Exception as error:
            logging.error("GeoHelper:get_woe_id():error:{}".format(error))

            raise Exception(error)

        return woeid
def sunsetReport(city):
    client = yweather.Client()
    woeid = client.fetch_woeid(city)
    weather = client.fetch_weather(woeid, metric=False)

    sunset = weather["astronomy"]["sunset"]

    #adjust for 24-hour format in chance that sunset is in during 'am' hours
    if sunset[5:7] == 'pm':
        hour = (int(sunset[0:1]) + 12)
        minute = int(sunset[2:4])
    else:
        hour = int(sunset[0:1])
        minute = int(sunset[2:4])

    return (hour, minute)
Esempio n. 13
0
def get_trending(city, country):
    '''
    Return a list of the trending topics for a given location.
    '''
    # Get location ID
    client = yweather.Client()
    location_string = city + ", " + country
    location_id = client.fetch_woeid(location_string)
    print(location_id)

    # Get trending topics
    twitter = load_twitter()
    trending = []
    for trend in twitter.get_place_trends(id=location_id)[0]['trends']:
        trending.append(trend['name'])

    return trending
Esempio n. 14
0
def geoTweets(woeid):
    '''
    Uses Twitter trends/place API endpoint to fetch top trends in a given location.
    Location is determined by using Where On Earth ID (WOEID) from yweather. 
    Yweather will take a user string of a city or country. Twitter will only
    supply trends.json information for 467 WOEIDs. 
    Tweepy sends the GET request for the trends.json file, displaying information about
    the top 50 trends in a given location. This program focuses only on trend names and
    tweet_volume from the .json. Twitter API will return 'None' for some trends, 
    this program will eliminate those trends so that the top trends can be sorted by descending
    tweet volume.
    Each trend that has a tweet_volume != None will be added to a dictionary, which is then sorted
    using OrderedDict. The sorted dictionary gets printed to the user.
    '''

    client = yweather.Client()
    
    # api call for trends/place endpoint resulting in json output
    tmp = api.trends_place(woeid) # one list of dictionaries in json format 
    data = tmp[0] # just the dictionaries from the overall large list 

    # dump json data from api request to .json file
    with open('trend_data.json', 'w') as outfile:  
        json.dump(data, outfile)    
        
    # header for data being displayed
    print('\nTop Twitter trends as of {} in {}.'.format(data['as_of'][:10], data['locations'][0]['name']))
    print('\n   {:>20}:\t{}\n'.format('Trend','Tweet Volume') + '-'*50)

    # put trends where tweet_volume is an int and not null into dictionary
    d = {}
    for x in range(50):
        if data['trends'][x]['tweet_volume'] != None:
            d[data['trends'][x]['name']] = data['trends'][x]['tweet_volume']
        else:
            pass
    
    # sort tweets dictionary by descending tweet_volume
    sortDict = OrderedDict(sorted(d.items(), key=lambda t: t[1],reverse=True))
    count = 1
    for k, v in sortDict.items():
        print('{:02}) {:>20}:\t{:,}'.format(count, k,v))
        count += 1

    print('-'*50) # padding
Esempio n. 15
0
def get_weather():
    weather_client = yweather.Client()
    woeid = weather_client.fetch_woeid(LOCATION)
    weather = weather_client.fetch_weather(woeid)
    forecasts = weather['forecast']
    forecasts = sorted(forecasts, key=lambda k: k['date'])
    forecasts[0]['day'] = 'Today'
    forecasts[1]['day'] = 'Tomorrow'
    weather_html = ('<a href="https://weather.yahoo.com/">'
                    '\n<h3>Weather</h3></a>')
    for fc in forecasts:
        day_forecast = []
        weather_html += ('\n<li>' + fc['day'] + ': ')
        weather_html += fc['text'] + ' ('
        weather_html += fc['low'] + '-'
        weather_html += fc['high'] + ')</li>'
    weather_html += '\n</ul>'
    return weather_html
Esempio n. 16
0
def hello():
    twitter = Twitter(auth=OAuth(
        os.environ.get('access_key'), os.environ.get('access_secret'),
        os.environ.get('consumer_key'), os.environ.get('consumer_secret')))
    client = yweather.Client()
    id_location = client.fetch_woeid('India')
    print("id is ", id_location)

    results = twitter.trends.place(_id=id_location)

    print("India Trends")
    list_of_trends = []

    for location in results:
        for trend in location["trends"]:
            print(" - %s" % trend["name"])
            if "#" in trend["name"]:
                list_of_trends.append(trend["name"])
    return render_template('index.html', trends=list_of_trends)
def calculate_trend_similarity(keyword='大坂', country='Japan'):
    # set country of interest
    country_of_interest = country

    # this stupid WOEID requires yweather to get (a library), because YAHOO itself has stopped supporting it
    # WOEID
    woeid_client = yweather.Client()
    woeid = woeid_client.fetch_woeid(location=country_of_interest)

    # 1. call twitter to return trends
    # get trends global. each trend is a dictionary
    current_trends_global = api.GetTrendsCurrent()
    current_trends_global = [c.AsDict() for c in current_trends_global]

    # get trends by WOEID
    current_trends_country = api.GetTrendsWoeid(woeid=woeid)
    current_trends_country = [c.AsDict() for c in current_trends_country]

    print_list_of_dicts(current_trends_country)
    print_list_of_dicts(current_trends_global)

    # optional: get additional hashtags
    # global_hashtags_from_trends_list = get_hashtags_from_query_list(current_trends_global)
    # country_hashtags_from_trends_list = get_hashtags_from_query_list(current_trends_country)

    # turn them both into lists
    current_trends_global_list = [x['name'] for x in current_trends_global]
    current_trends_country_list = [x['name'] for x in current_trends_country]

    # calculate pairwise distance here
    global_relevance = calculate_pairwise_distance(
        keyword=keyword,
        list_of_entities=current_trends_global_list,
        debug=True)
    country_relevance = calculate_pairwise_distance(
        keyword=keyword,
        list_of_entities=current_trends_country_list,
        debug=True)

    output = {"global": global_relevance, "country": country_relevance}

    return output
Esempio n. 18
0
def solve(prompt):
    global ParameterFound
    global Start
    global Input
    ParameterFound = False
    ParameterFound2 = False
    lower_case = prompt.lower()
    corrected = autocrct(lower_case, True)
    if lower_case != corrected:
        option = GetInput("Did you mean? " + corrected + " [y/n]:")
        if option.lower() == 'y' or option.lower() == 'yes' or option.lower(
        ) == 'yeah' or option.lower() == 'ya':
            lower_case = corrected
    if lower_case.find("search ") == 0 or lower_case.find(
            "find ") == 0 or lower_case.find("fact ") == 0:
        if lower_case.find("search ") == 0:
            Print(Fact(lower_case[7:]))
        else:
            Print(Fact(lower_case[5:]))
    elif 'defin' in lower_case or 'meaning' in lower_case:
        tokens = word_tokenize(lower_case)
        if len(tokens) == 1:
            word = GetInput("What word would you like to define: ")
            word_to_define = word_tokenize(word)[0]
        else:
            if len(tokens) != 2:
                stopWords = set(stopwords.words("english"))
                stopWords.add('is')
                for a in tokens:
                    if a in stopWords:
                        tokens.remove(a)
            for b in tokens:
                if 'defin' not in b or 'meaning' not in b:
                    word_to_define = b
        try:
            Print(definition(word_to_define))
            Print("synonyms")
            Print(synonym(word_to_define))
            Print("antonyms")
            Print(antonym(word_to_define))
        except Exception:
            Print("That word does not seem to exist")
    elif 'timer' in lower_case or 'remind' in lower_case:
        tokens = word_tokenize(lower_case)
        for i in range(len(tokens)):
            if 'sec' in tokens[i]:
                if isInt(tokens[i - 1]):
                    ParameterFound = True
                    seconds = int(tokens[i - 1])
                    break
        activity_name = GetInput("What is the name of your activity:")
        while True:
            if ParameterFound:
                Print("The timer is starting it will last for " +
                      str(seconds) + " seconds")
                Timer(seconds, activity_name, root)
                break
            try:
                seconds = int(
                    GetInput("How many seconds do you want the timer for?"))
                Print("The timer is starting it will last for " +
                      str(seconds) + " seconds")
                Timer(seconds, activity_name, root)
                break
            except Exception:
                Print("Please input an integer")
    elif 'time' in lower_case and not "sentiment" in lower_case:
        Print(time.ctime())
    elif 'news' in lower_case:
        Print(TopNews())
    elif 'shut down' in lower_case or 'power down' in lower_case or 'shut off' in lower_case or 'power off' in lower_case:
        tokens = word_tokenize(lower_case)
        for i in range(len(tokens)):
            if 'sec' in tokens[i]:
                if isInt(tokens[i - 1]):
                    ParameterFound = True
                    seconds = int(tokens[i - 1])
                    break
        while True:
            if ParameterFound:
                ShutDown(seconds)
                break
            try:
                seconds = int(
                    GetInput("How many seconds do you want to shut down in?"))
                Print("The computer will shut down in " + seconds + " seconds")
                ShutDown(seconds)
                break
            except Exception:
                Print("Please input an integer")
    elif 'restart' in lower_case or 're-start' in lower_case or 're start' in lower_case:
        tokens = word_tokenize(lower_case)
        for i in range(len(tokens)):
            if 'sec' in tokens[i]:
                if isInt(tokens[i - 1]):
                    ParameterFound = True
                    seconds = int(tokens[i - 1])
                    break
        while True:
            if ParameterFound:
                Restart(seconds)
                break
            try:
                seconds = GetInput(
                    "How many seconds do you want to restart in?")
                Print("The computer will restart in " + seconds + " seconds")
                Restart(seconds)
                break
            except Exception:
                Print("Please input an integer")
    elif 'forecast' in lower_case:
        client = yweather.Client()
        WOEID = client.fetch_woeid('Singapore')
        Print(Forecast(WOEID))
    elif 'weather' in lower_case:
        client = yweather.Client()
        WOEID = client.fetch_woeid('Singapore')
        Print(CurrentWeather(WOEID))

    elif 'sing' in lower_case or 'play' in lower_case:
        while True:
            try:
                file = FileGet()
                Print(Music(file))
                break
            except Exception:
                Print("Your file may be corrupted")
    elif 'stop' in lower_case:
        StopMusic()
    elif 'create' in lower_case and 'list' in lower_case:
        tokens = word_tokenize()
        for i in range(len(tokens)):
            if 'list' in tokens[i] and i != tokens[i] - 1:
                ParameterFound = True
                list_name = tokens[i + 1]
                break
        if not ParameterFound:
            list_name = GetInput("What is the name for your list?")
            CreateList(list_name)
            Print("List successfully created")
        else:
            CreateList(list_name)
            Print("List successfully created")
    elif 'add' in lower_case and 'list' in lower_case or 'append' in lower_case and 'list' in lower_case:
        tokens = word_tokenize()
        for i in range(len(tokens)):
            if 'list' in tokens[i] and i != tokens[i] - 1 or 'to' in tokens[
                    i] and i != tokens[i] - 1:
                ParameterFound = True
                list_name = tokens[i + 1]
                break
            elif 'add' in tokens[i] or 'append' in tokens[i]:
                ParameterFound2 = True
                AddToFile = tokens[i + 1]
                break
        if not ParameterFound:
            List_name = GetInput("Which list would you like to add to?")
        if not ParameterFound2:
            AddToFile = GetInput("What would you like to add to your list?")
        Print(AddList(List_name, AddToFile))
    elif 'remove' in lower_case and 'list' in lower_case or 'delete' in lower_case and 'list' in lower_case:
        tokens = word_tokenize()
        for i in range(len(tokens)):
            if 'list' in tokens[i] and i != tokens[i] - 1 or 'from' in tokens[
                    i] and i != tokens[i] - 1:
                ParameterFound = True
                list_name = tokens[i + 1]
                break
            elif 'remove' in tokens[i] or 'delete' in tokens[i]:
                ParameterFound2 = True
                RemoveFromFile = tokens[i + 1]
                break
        if not ParameterFound:
            List_name = GetInput("which list would you like to remove from?")
        if not ParameterFound2:
            RemoveFromFile = GetInput(
                "What would you like to remove from your list?")
        Print(removeList(List_name, RemovefromFile))
    elif 'get' in lower_case and 'list' in lower_case or 'see' in lower_case and 'list' in lower_case:
        tokens = word_tokenize()
        for i in range(len(tokens)):
            if 'list' in tokens[i] and i != tokens[i] - 1:
                ParameterFound = True
                List_name = tokens[i + 1]
                break
        if not ParameterFound:
            List_name = GetInput("Which list would you like to see")
        Print(GetList(List_name))
    elif 'calc' in lower_case or 'evalu' in lower_case:
        tokens = lower_case.split(" ")
        for i in tokens:
            if isEqua(i):
                ParameterFound = True
                Equation = i
                break
        while True:
            if ParameterFound:
                Print(cal(Equation))
                break
            try:
                Equation = GetInput("Enter your formula:")
                if not isEqua(Equation):
                    int('')
                Print(cal(Equation))
                break
            except Exception:
                Print("Please input a valid equation")
    elif 'clean' in lower_case:
        Print("Choose the .csv file")
        file = FileGet()
        column = GetInput(
            "What is the name of the column that you want to clean?")
        Print("Choose the .csv file you wish to load the data")
        file2 = FileGet()
        Print(ExtractRubbish(file, file2, column))
    elif 'extract int' in lower_case or 'get numbers' in lower_case:
        Print("Choose the .csv file")
        file = FileGet()
        column = GetInput(
            "What is the name of the column that you want to extract integers from?"
        )
        column2 = GetInput(
            "What is the name of the column that you want place the new values?"
        )
        Print(str(ExtractInts(file, column, column2)))
    elif 'positivity' in lower_case or 'sentiment' in lower_case:
        Print("Choose the .csv file")
        file = FileGet()
        column = GetInput(
            "What is the name of the column that you want to extract sentiment from?"
        )
        column2 = GetInput(
            "What is the name of the column that you want place the new values?"
        )
        Print(str(ExtractSentiment(file, column, column2)))
    elif 'topic' in lower_case:
        Print("Choose the .csv file")
        file = FileGet()
        column = GetInput(
            "What is the name of the column that you want to extract topics from?"
        )
        column2 = GetInput(
            "What is the name of the column that you want place the new values?"
        )
        Print(str(ExtractTopic(file, column, column2)))
    elif 'scatter plot' in lower_case:
        Print("Choose the .csv file")
        file = FileGet()
        column = GetInput(
            "What is the name of the column that you want to extract data for the x axis?"
        )
        column2 = GetInput(
            "What is the name of the column that you want to extract data for the y axis?"
        )
        Print(PlotScatterData(file, column, column2))
    elif 'line graph' in lower_case:
        Print("Choose the .csv file")
        file = FileGet()
        column = GetInput(
            "What is the name of the column that you want to extract data for the x axis?"
        )
        column2 = GetInput(
            "What is the name of the column that you want to extract data for the y axis?"
        )
        Print(PlotGraphData(file, column, column2))
    elif 'pie chart' in lower_case:
        Print("Choose the .csv file")
        file = FileGet()
        column = GetInput(
            "What is the name of the column that you want to extract data?")
        labels = GetInput("Enter the labels seperated by commas")
        try:
            Print(PlotPieData(file, column, listFromStr(column2)))
        except Exception:
            Print("You inputted too many values")
    elif 'graph' in lower_case:
        tokens = lower_case.split(" ")
        for i in range(len(tokens)):
            if isFormula(tokens[i]):
                ParameterFound = True
                formula = tokens[i]
                break
        while True:
            if ParameterFound:
                graph(formula, -450, 460, t)
                break
            try:
                formula = GetInput("Enter your formula:")
                if not isFormula(formula):
                    int('')
                try:
                    graph(formula, -350, 360, t)
                    Print("Graphed " + formula)
                except Exception:
                    Print("Oops That formula is in the complex plane")
                break
            except Exception:
                Print("Please input a graphable formula")
    elif 'summar' in lower_case:
        tokens = word_tokenize(lower_case)
        parameter = 0
        for i in tokens:
            if 'web' in i:
                parameter = 1
                break
            elif 'text' in i or 'txt' in i:
                parameter = 2
                break
        if parameter == 0:
            WebText = GetInput(
                "Do you want to summarise text files or websites?")
            while True:
                if 'web' in WebText:
                    parameter = 1
                    break
                elif 'text' in WebText or 'txt' in WebText:
                    parameter = 2
                    break
                else:
                    Print("You did not specify the type")
        if parameter == 1:
            while True:
                url = GetInput("What website do you want to summarise")
                if isUrl(url):
                    break
                else:
                    Print("That is not a valid url. Please use https: or www")
            Print(WebSummary(url))
        elif parameter == 2:
            Print("Which text file would you like to view")
            file = FileGet()
            Print(TextSummary(file))
    elif 'simplify' in lower_case:
        tokens = lower_case.split(" ")
        for i in tokens:
            if isEqua(i):
                ParameterFound = True
                Equation = i
                break
        while True:
            if ParameterFound:
                Print(simplifyEqu(Equation))
                break
            try:
                Equation = GetInput("Enter your equation:")
                if not isEqua(Equation):
                    int('')
                Print(simplifyEqu(Equation))
                break
            except Exception:
                Print("Please input a valid equation")
    elif 'expand' in lower_case:
        tokens = lower_case.split(" ")
        for i in tokens:
            if isEqua(i):
                ParameterFound = True
                Equation = i
                break
        while True:
            if ParameterFound:
                Print(expandEqu(Equation))
                break
            try:
                Equation = GetInput("Enter your equation:")
                if not isEqua(Equation):
                    int('')
                Print(expandEqu(Equation))
                break
            except Exception:
                Print("Please input a valid equation")
    elif 'factorise' in lower_case:
        tokens = lower_case.split(" ")
        for i in tokens:
            if isEqua(i):
                ParameterFound = True
                Equation = i
                break
        while True:
            if ParameterFound:
                Print(factoriseEqu(Equation))
                break
            try:
                Equation = GetInput("Enter your equation:")
                if not isEqua(Equation):
                    int('')
                Print(factoriseEqu(Equation))
                break
            except Exception:
                Print("Please input a valid equation")
    elif 'solve' in lower_case or 'find' in lower_case:
        tokens = lower_case.split(" ")
        for i in range(len(tokens)):
            if isFormula(tokens[i]):
                ParameterFound = True
                formula = tokens[i]
                break
        while True:
            try:
                if not ParameterFound:
                    formula = GetInput("Enter your formula:")
                if not isFormula(formula):
                    int('')
                subject = GetInput("Enter what you are solving for:")
                for i in solveEqu(
                        formula.split("=")[0],
                        formula.split("=")[1], subject, True):
                    Print(i)
                break
            except Exception:
                Print("Please input a valid subject")
    elif 'derivative' in lower_case or 'differentiate' in lower_case:
        tokens = lower_case.split(" ")
        for i in range(len(tokens)):
            if isEqua(tokens[i]):
                ParameterFound = True
                formula = tokens[i]
                break
        while True:
            try:
                if not ParameterFound:
                    formula = GetInput("Enter your formula:")
                if not isEqua(formula):
                    int('')
                subject = GetInput("Enter what you are solving for:")
                Print(diffCal(formula, subject))
                break
            except Exception:
                Print("Please input a valid subject")
    elif 'integrate' in lower_case:
        tokens = lower_case.split(" ")
        for i in range(len(tokens)):
            if isEqua(tokens[i]):
                ParameterFound = True
                formula = tokens[i]
                break
        while True:
            try:
                if not ParameterFound:
                    formula = GetInput("Enter your formula:")
                if not isEqua(formula):
                    int('')
                subject = GetInput("Enter what you are solving for:")
                try:
                    Print(str(integrateCal(formula, subject)) + " + C")
                except Exception:
                    Print("Sorry you cannot integrated that :(")
                break
            except Exception:
                Print("Please input a valid subject")
    elif 'convert' in lower_case:
        tokens = word_tokenize(lower_case)
        for i in range(len(tokens)):
            if isInt(tokens[i]):
                ParameterFound = True
                num = tokens[i]
                unit = tokens[i + 1]
                break
            if tokens[i] == 'to':
                ParameterFound2 = True
                unit2 = tokens[i + 1]
        while True:
            try:
                if not ParameterFound:
                    num = GetInput("Enter your number:")
                    unit = GetInput("Enter your first unit:")
                if not ParameterFound2:
                    unit2 = GetInput("Enter the unit you will convert to:")
                Print(UnitConvert(int(num), unit, unit2))
                break
            except Exception:
                Print("Please input a valid unit")
    Start = True
Esempio n. 19
0
 def __init__(self):
     client = yweather.Client()
     woeid = client.fetch_woeid("Verona, Italy")
     self.weather = client.fetch_weather(woeid, metric=True)
Esempio n. 20
0
def get_WOEID(location):
    client = yweather.Client()
    return (client.fetch_woeid(location))
def get_woeid(location):
    return yweather.Client().fetch_woeid(location)
Esempio n. 22
0
    def on_chat_message(self, msg):
        global state, stall, stall1, can
        content_type, chat_type, chat_id = telepot.glance(msg)
        if content_type == 'text':

            # get message payload
            msg_text = msg['text']

            if (msg_text.startswith('/')):

                # parse the command excluding the '/'
                command = msg_text[1:].lower()

                # prepare the correct response based on the given command
                if (command == 'start'):
                    #display current weather at start of bot
                    weather = Weather()

                    # Lookup WOEID via http://weather.yahoo.com.
                    client = yweather.Client()
                    Singapore_NTU = client.fetch_woeid(
                        'Nanyang Technological University')
                    lookup = weather.lookup(Singapore_NTU)
                    condition = lookup.condition()
                    response = "Current Weather in NTU: " + condition[
                        'text'] + '\n\nRating Stalls or Finding Food? \nTo Rate a Stall, enter /rate\nTo Find Food, enter /find \n\nTo view all commands, enter /list'
                    bot.sendMessage(chat_id, response)

                elif (command == 'list'):
                    #dispaly list of avaiable commands
                    response = 'Here are a list of all available commands: \n/start Begin your food journey! \n/rate Rate your dining experience at stall! \n/find Find delicious food by location or cuisine! \n/feedback Send any feedback, queries or errors spotted to us! \n/quit Exit what you are doing'
                    bot.sendMessage(chat_id, response)
                elif (command == 'feedback'):
                    #set state to 4 to receive feedback from user
                    self.state = 4
                    bot.sendMessage(chat_id,
                                    'Please enter feedback your feedback!')
                elif (command == 'rate'):
                    #set state to 1 to proceed to next stage of rating process
                    self.state = 1
                    canlist = [
                        'Canteen 1', 'Canteen 2', 'Canteen 4', 'Canteen 9',
                        'Canteen 11', 'Canteen 13', 'Canteen 14', 'Canteen 16',
                        'Koufu', 'NIE Canteen', 'North Hill Canteen',
                        'North Spine Foodcourt', 'Pioneer Canteen'
                    ]
                    rm = ReplyKeyboardMarkup(
                        one_time_keyboard=True,
                        keyboard=[[KeyboardButton(text=i)] for i in canlist])
                    bot.sendMessage(chat_id, 'Choose Canteen', reply_markup=rm)

                elif (command == 'find'):
                    response = 'Filter by Canteen or Cuisine?'
                    confirm_keyboard = InlineKeyboardMarkup(inline_keyboard=[
                        [
                            InlineKeyboardButton(text='Canteen',
                                                 callback_data='can')
                        ],
                        [
                            InlineKeyboardButton(text='Cuisine',
                                                 callback_data='cui')
                        ],
                    ])
                    bot.sendMessage(chat_id,
                                    response,
                                    reply_markup=confirm_keyboard)
                elif (command == 'quit'):
                    #used to exit and reset to initial state
                    self.state = 0
            elif (self.state == 0):
                #initial state. Prompt if no valid command is entered
                bot.sendMessage(
                    chat_id,
                    "Hi, please enter /start to begin! \n\nFor feedback, please enter \n/feedback \n\nTo exit at anytime, enter /quit"
                )
            elif (self.state == 1):
                self.check = 0
                conn_string = "host='ec2-54-225-237-64.compute-1.amazonaws.com' dbname='d7dkk1sep0usei' user='******' password='******'"
                conn = psycopg2.connect(conn_string)
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM store")
                rlist = cursor.fetchall()

                #check if user input for canteen is valid (matches with that in master list from database table "store")
                for i in range(len(rlist)):
                    if (msg_text == rlist[i][0]):
                        self.check = 1
                #if input valid, we set state to the next state, and prompt user for input of stall
                if (self.check):
                    can = msg_text
                    otpt = "List of stalls in " + msg_text + "\n"
                    self.stall = []
                    #find list of stalls in selected canteen
                    for i in range(0, len(rlist)):
                        if (rlist[i][0] == msg_text):
                            otpt = otpt + rlist[i][2] + "\n"
                            self.stall.append(rlist[i][2])
                    RM = ReplyKeyboardMarkup(
                        one_time_keyboard=True,
                        keyboard=[[KeyboardButton(text=stall)]
                                  for stall in self.stall])

                    bot.sendMessage(chat_id, otpt, reply_markup=RM)
                    self.state = 2
                #if input invalid, stay at current state and prompt user for input of canteen again
                else:
                    canlist = [
                        'Canteen 1', 'Canteen 2', 'Canteen 4', 'Canteen 9',
                        'Canteen 11', 'Canteen 13', 'Canteen 14', 'Canteen 16',
                        'Koufu', 'NIE Canteen', 'North Hill Canteen',
                        'North Spine Foodcourt', 'Pioneer Canteen'
                    ]
                    rm = ReplyKeyboardMarkup(
                        one_time_keyboard=True,
                        keyboard=[[KeyboardButton(text=i)] for i in canlist])
                    bot.sendMessage(chat_id, 'Choose Canteen', reply_markup=rm)
                    self.state = 1

            elif (self.state == 2):
                self.check = 0
                #check if user input of stall is valid
                for i in range(len(self.stall)):
                    if (msg_text == self.stall[i]):
                        self.check = 1
                #for valid input, ask user to input ratings and move to next state, state 3
                if (self.check == 1):
                    self.stall1 = msg_text
                    self.state = 3
                    RM = ReplyKeyboardMarkup(
                        one_time_keyboard=True,
                        keyboard=[[KeyboardButton(text=rating)]
                                  for rating in ['5', '4', '3', '2', '1']])
                    bot.sendMessage(chat_id, "Input Ratings", reply_markup=RM)
                #for invalid stall input, prompt user for input of stall, while remaining at current state
                else:
                    bot.sendMessage(chat_id,
                                    "Input Stall: ",
                                    reply_markup=ReplyKeyboardMarkup(
                                        one_time_keyboard=True,
                                        keyboard=[[KeyboardButton(text=stall)]
                                                  for stall in self.stall]))

            elif (self.state == 3):
                #for valid rating input, attempt to save review using rate.py. check for multiple rating by single user is made in rate.py
                if ((msg_text == '1') | (msg_text == '2') | (msg_text == '3') |
                    (msg_text == '4') | (msg_text == '5')):
                    self.state = 0
                    bot.sendMessage(
                        chat_id, rate(can, self.stall1, msg_text,
                                      str(chat_id)))
                #for invalid rating input, prompt user for rating input and remain at current state
                else:
                    self.state = 3
                    bot.sendMessage(
                        chat_id,
                        "Input Ratings",
                        reply_markup=ReplyKeyboardMarkup(
                            one_time_keyboard=True,
                            keyboard=[[KeyboardButton(text=rating)]
                                      for rating in ['5', '4', '3', '2', '1']
                                      ]))
            elif (self.state == 4):
                #send feedback and userid to the admin and return to initial state
                response = str(msg_text) + '\nUserID : ' + str(chat_id)
                bot.sendMessage(408469886, response)
                bot.sendMessage(chat_id,
                                'Thank you, your feedback was recorded!')
                self.state = 0
Esempio n. 23
0
import tweepy
from tweepy import OAuthHandler
import yweather

CLIENT = yweather.Client()

CONSUMER_KEY = ''
CONSUMER_SECRET = ''
ACCESS_TOKEN = ''
ACCESS_SECRET = ''

AUTH = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
AUTH.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)

API = tweepy.API(AUTH, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
Esempio n. 24
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--config-file', '-c',
        default=os.path.expanduser('~/.tempmon/tempmon.yaml'),
        help='Where to load configuration settings. Defaults to %(default)s',
    )
    parser.add_argument(
        '--log-file', '-l',
        default=os.path.expanduser('~/.tempmon/tempmon.log'),
        help='Where to write logs. Defaults to %(default)s',
    )
    parser.add_argument(
        '--pid-file', '-p',
        default=None,
        help='Where to write the pid file. Defaults to not writing one.',
    )
    parser.add_argument(
        '--history-file',
        default=None,
        help='Where to write the recording history for playback',
    )
    parser.add_argument(
        '--verbose', '-v',
        action='store_true',
        default=False,
    )
    args = parser.parse_args()

    if args.pid_file:
        with open(args.pid_file, 'w') as f:
            f.write('%s\n' % os.getpid())

    setup_logging(args.log_file, args.verbose)

    LOG.info('Loading configuration from %s', args.config_file)
    with open(args.config_file) as f:
        config = yaml.load(f)
    plotly = config['plotly']
    username = plotly['username']
    api_key = plotly['api-key']
    sensor_tokens = plotly['sensor-stream-tokens']
    title = config.get('graph-title', 'Temperature')
    retention_period = config.get('retention-period', DEFAULT_RETENTION_PERIOD)
    frequency = config.get('frequency', DEFAULT_FREQUENCY)
    if frequency < 1:
        LOG.warning('Cannot poll more often than 1 minute')
        frequency = 1
    units = config.get('units', DEFAULT_UNITS)
    LOG.info('Polling every %s minutes, keeping %s days',
             frequency, retention_period)
    weather_stream_token = plotly['weather-stream-token']
    weather = config['weather']
    place = weather['place']
    LOG.info('Monitoring weather at %r', place)

    # Make sure we can communicate with the devices
    devs = get_sensors()
    sensor_names = []
    if len(devs) > 1:
        name_format = 'Sensor %(num)s (%(bus)s/%(ports)s)'
    else:
        name_format = 'Sensor'
    for n, dev in enumerate(devs, 1):
        bus = dev.get_bus()
        ports = dev.get_ports()
        LOG.info('Found sensor on bus %s at port %s',
                 bus, ports)
        name = name_format % {'bus': bus, 'ports': ports, 'num': n}
        sensor_names.append(name)

    # Connect to weather service
    weather_client = yweather.Client()
    location_id = weather_client.fetch_woeid(place)

    history_file = (
        args.history_file
        or
        os.path.join(os.path.dirname(args.config_file), 'tempmon.db')
    )
    history_db, history_points = db.open_db(history_file)

    # Connect to plot.ly
    max_points = 24 * (60 / frequency) * retention_period
    sensor_streams, weather_stream = create_plot(
        username,
        api_key,
        weather_stream_token,
        sensor_tokens,
        sensor_names,
        title,
        units,
        max_points,
    )

    if history_points:
        LOG.info('Posting historical data')
        weather, readings = db.get_history(history_db)
        for entry in weather:
            x = entry['date']
            try:
                weather_stream.write({'x': x, 'y': entry['temperature']})
            except Exception:
                LOG.warning('Could not update plotly', exc_info=True)
        for entry in readings:
            stream = sensor_streams[entry['token']]
            x = entry['date']
            try:
                stream.write({'x': x, 'y': entry['temperature']})
            except Exception:
                LOG.warning('Could not update plotly', exc_info=True)

    LOG.info('Starting polling')
    delay = frequency * 60
    while True:
        x = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
        history_entry = {
            'date': x,
            'weather': None,
            'sensors': []
        }
        # Reported temperature from weather service
        try:
            weather = weather_client.fetch_weather(location_id, metric=False)
            temp = weather['condition']['temp']
            db.store_weather(history_db, x, temp)
        except Exception:
            LOG.warning('Could not get weather report', exc_info=True)
        else:
            try:
                weather_stream.write({'x': x, 'y': temp})
            except Exception:
                LOG.warning('Could not update plotly', exc_info=True)
        # Temperature sensors
        sensor_log_data = []
        for dev, token in zip(devs, sensor_tokens):
            stream = sensor_streams[token]
            try:
                temp = dev.get_temperature(format=units)
                db.store_sensor_reading(history_db, x, temp, token)
                sensor_log_data.append(temp)
            except Exception:
                LOG.warning('Could not read temperature', exc_info=True)
                continue
            try:
                stream.write({'x': x, 'y': temp})
            except Exception:
                LOG.warning('Could not update plotly', exc_info=True)
                continue

        LOG.info('outside=%s sensors=%s',
                 weather['condition']['temp'],
                 ', '.join(str(x) for x in sensor_log_data))
        # Save the history
        history_db.commit()
        # delay between stream posts is expressed as a frequency
        # in minutes
        time.sleep(delay)
def get_woeid(country):
    client = yweather.Client()
    return client.fetch_woeid(country)
Esempio n. 26
0
def getWoeidOfLocation(location):
    client = yweather.Client()
    return client.fetch_woeid(location)
Esempio n. 27
0
def print_trending_in_location(woeid):
    client = yweather.Client()
    # lid = client.fetch_lid()
    # print(f"============ Trending in {lid} ===========")
    trends = api.trends_place(woeid)
    print(trends)
Esempio n. 28
0
auth = json.loads(r.text)


#print("Token type: " + auth['token_type'])
#print("Access token: " + auth['access_token'])
def get(url):
    headers = {
        'Authorization': auth['token_type'] + " " + auth['access_token']
    }
    rq = requests.get("https://api.twitter.com/1.1/" + url, headers=headers)
    return json.loads(rq.text)


def tweets(q, lang="en", count=1000):
    data = get("search/tweets.json?q=" + urllib.quote_plus(q) + \
               "&lang=" + lang + \
               "&count=" + str(count) )
    return [(tweet['text'], tweet["user"]["location"])
            for tweet in data['statuses']]


woeidgen = yweather.Client()


def trendsByLocation(location):
    woeid = woeidgen.fetch_woeid(location)
    return [
        trend['name']
        for trend in get("trends/place.json?id=" + woeid)[0]['trends']
    ]
Esempio n. 29
0
#prototype for app

import yweather
client = yweather.Client()
ID = client.fetch_woeid("New York City, New York")
#input("Enter the your city followed by your state (Ex: Seattle, Washington):"))
Info = client.fetch_weather(ID)
Location = (Info["location"]["city"], Info["location"]["region"])
Temperature = (Info["condition"]["temp"])
Condition = (Info["condition"]["text"])
print(Location)
#Displays location name,and resion/state
print(Temperature)
#displays temperature of the city
print(Condition)
#prints textual version of weather condition (ex. cloudy, light rain)
Esempio n. 30
0
from flask import Flask, request, render_template, redirect, url_for
import sys
import os
from os import listdir
from os.path import isfile, join
import foursquare
import yweather
from geopy.geocoders import Nominatim
import random

app = Flask(__name__)

clientWeather = yweather.Client()


@app.route('/', methods=['GET', 'POST'])
def home():
    return render_template('welcome.html')


@app.route('/schedule', methods=['GET'])
def schedule():

    #foursquare shit
    client = foursquare.Foursquare(client_id='JEK02X44TGMNJSE0VC1UBEB4FRNNW3UMFQ4IQOPI4BAR2GXA', \
                                    client_secret='A2Z50VTUHHXEUYJBHCQKB1LXTNVVBYBQR4SDASVTXTWUMWXS')

    city_state = request.args["city_state"]  # New York City, New York

    # weather part
    ID = clientWeather.fetch_woeid(city_state)