Esempio n. 1
0
def create_room(context):
    """
    Creates a new Cisco Spark room

    :param context: button state and configuration
    :type context: ``dict``

    :return: the id of the target room
    :rtype: ``str``

    This function also adds appropriate audience to the room
    """

    logging.info("Creating Cisco Spark room '{}'".format(
        context['spark']['room']))

    url = 'https://api.ciscospark.com/v1/rooms'
    headers = {
        'Authorization': 'Bearer ' + context['spark']['CISCO_SPARK_BTTN_BOT']
    }
    payload = {'title': context['spark']['room']}
    response = requests.post(url=url, headers=headers, data=payload)

    if response.status_code != 200:
        logging.info(response.json())
        raise Exception("Received error code {}".format(response.status_code))

    logging.info("- done")
    room_id = response.json()['id']
    context['spark']['id'] = get_room(context)

    add_audience(context)

    return room_id
Esempio n. 2
0
def get_room(context):
    """
    Looks for a suitable Cisco Spark room

    :param context: button state and configuration
    :type context: ``dict``

    :return: the id of the target room
    :rtype: ``str``

    This function creates a new room if necessary
    """

    logging.info("Looking for Cisco Spark room '{}'".format(
        context['spark']['room']))

    url = 'https://api.ciscospark.com/v1/rooms'
    headers = {
        'Authorization': 'Bearer ' + context['spark']['CISCO_SPARK_BTTN_BOT']
    }
    response = requests.get(url=url, headers=headers)

    if response.status_code != 200:
        logging.info(response.json())
        raise Exception("Received error code {}".format(response.status_code))

    for item in response.json()['items']:
        if context['spark']['room'] in item['title']:
            logging.info("- found it")
            context['spark']['id'] = item['id']
            return item['id']

    logging.info("- not found")

    return create_room(context)
Esempio n. 3
0
def delete_room(context):
    """
    Deletes the target Cisco Spark room

    :param context: button state and configuration
    :type context: ``dict``

    This function is useful to restart a clean demo environment
    """

    logging.info("Deleting Cisco Spark room '{}'".format(
        context['spark']['room']))

    url = 'https://api.ciscospark.com/v1/rooms'
    headers = {
        'Authorization': 'Bearer ' + context['spark']['CISCO_SPARK_BTTN_BOT']
    }
    response = requests.get(url=url, headers=headers)

    if response.status_code != 200:
        logging.info(response.json())
        raise Exception("Received error code {}".format(response.status_code))

    actual = False
    for item in response.json()['items']:

        if context['spark']['room'] in item['title']:
            logging.info("- DELETING IT")

            url = 'https://api.ciscospark.com/v1/rooms/{}'.format(item['id'])
            headers = {
                'Authorization':
                'Bearer ' + context['spark']['CISCO_SPARK_BTTN_BOT']
            }
            response = requests.delete(url=url, headers=headers)

            if response.status_code != 204:
                raise Exception("Received error code {}".format(
                    response.status_code))

            actual = True

    if actual:
        logging.info(
            "- room will be re-created in Cisco Spark on next button depress")
    else:
        logging.info(
            "- no room with this name yet - it will be created on next button depress"
        )
Esempio n. 4
0
def build_response(endpoint, data):
    api_endpoint = "http://localhost:19002/" + endpoint
    response = requests.get(api_endpoint, params=data, headers=http_header)
    try:
        return response.json();
    except ValueError:
        return []
Esempio n. 5
0
def getweather():

    #get selection from user, create link to JSON object, convert to dictionary
    icao = request.forms.get('airports')
    url = "http://api.geonames.org/weatherIcaoJSON?ICAO=" + icao + "&username=jctcstudents"
    response = requests.get(url)
    data = response.json()

    #get weather information for chosen airport, convert units as needed
    stationName = data["weatherObservation"]["stationName"]
    elevation = data["weatherObservation"]["elevation"]
    elevation = round(float(elevation) * 3.28084, 1)
    clouds = data["weatherObservation"]["clouds"]
    dewPoint = data["weatherObservation"]["dewPoint"]
    dewPoint = round(float(dewPoint) * 1.8 + 32, 0)
    windSpeed = data["weatherObservation"]["windSpeed"]
    windSpeed = round(float(windSpeed) * 1.1508, 1)
    temperature = data["weatherObservation"]["temperature"]
    temperature = round(float(temperature) * 1.8 + 32, 0)
    humidity = data["weatherObservation"]["humidity"]

    #add data to tuple and send to table to display to user
    tpl = {
        'stationName': stationName,
        'elevation': elevation,
        'clouds': clouds,
        'dewPoint': dewPoint,
        'windSpeed': windSpeed,
        'temperature': temperature,
        'humidity': humidity
    }
    return template('weather', tpl)
Esempio n. 6
0
def flight_data():
    if not request.get_cookie('user'):
        redirect('/')

    value = request.forms.get('airports')

    response = requests.get('http://api.geonames.org/weatherIcaoJSON?ICAO=' +
                            value + '&username=jctcstudents')
    data = response.json()

    stationName = data['weatherObservation']['stationName']
    elevation = round(data['weatherObservation']['elevation'] * 3.28084, 1)
    dewPoint = round(float(data['weatherObservation']['dewPoint']) * 1.8 + 32)
    clouds = data['weatherObservation']['clouds']
    windSpeed = round(
        float(data['weatherObservation']['windSpeed']) * 1.15078, 1)
    temperature = round(
        float(data['weatherObservation']['temperature']) * 1.8 + 32)
    humidity = data['weatherObservation']['humidity']

    final_data = {
        'stationName': stationName,
        'elevation': elevation,
        'clouds': clouds,
        'dewPoint': dewPoint,
        'windSpeed': windSpeed,
        'temperature': temperature,
        'humidity': humidity
    }

    return template('airport', final_data)
Esempio n. 7
0
def post_update(context, update):
    """
    Updates a Cisco Spark room

    :param context: button state and configuration
    :type context: ``dict``

    :param update: content of the update to be posted there
    :type update: ``str`` or ``dict``

    If the update is a simple string, it is sent as such to Cisco Spark.
    Else if it a dictionary, then it is encoded as MIME Multipart.
    """

    logging.info("Posting update to Cisco Spark room")

    url = 'https://api.ciscospark.com/v1/messages'
    headers = {
        'Authorization': 'Bearer ' + context['spark']['CISCO_SPARK_BTTN_BOT']
    }

    if isinstance(update, dict):
        update['roomId'] = context['spark']['id']
        payload = MultipartEncoder(fields=update)
        headers['Content-Type'] = payload.content_type
    else:
        payload = {'roomId': context['spark']['id'], 'text': update}

    response = requests.post(url=url, headers=headers, data=payload)

    if response.status_code != 200:
        logging.info(response.json())
        raise Exception("Received error code {}".format(response.status_code))

    logging.info('- done, check the room with Cisco Spark client software')
Esempio n. 8
0
def add_person(context, person=None, isModerator='false'):
    """
    Adds a person to a room

    :param context: button state and configuration
    :type context: ``dict``

    :param person: e-mail address of the person to add
    :type person: ``str``

    :param isModerator: for moderators
    :type isModerator: `true` or `false`

    """

    url = 'https://api.ciscospark.com/v1/memberships'
    headers = {
        'Authorization': 'Bearer ' + context['spark']['CISCO_SPARK_BTTN_BOT']
    }
    payload = {
        'roomId': context['spark']['id'],
        'personEmail': person,
        'isModerator': isModerator
    }
    response = requests.post(url=url, headers=headers, data=payload)

    if response.status_code != 200:
        logging.info(response.json())
        raise Exception("Received error code {}".format(response.status_code))
Esempio n. 9
0
def test():
    response = requests.get(
        'https://api.github.com/search/repositories',
        params={'q': 'requests+language:python'},
    )

    # Inspect some attributes of the `requests` repository
    json_response = response.json()
    repository = json_response['items'][0]
    return 'It works yann coucou ' + repository["description"]
Esempio n. 10
0
def request_joke_from_api(base_url, params=None):
    if params is None:
        response = requests.get(url=base_url)
        data = response.json()
        print(">>> received response ", data)
        print(data['type'])
        if data['type'] == "twopart":
            joke = data['setup'] + ' ' + data['delivery']
        else:
            joke = data['joke']
        return construct_response("laughing", joke)
Esempio n. 11
0
def nemesis_auth(username, password):
    auth_part = "{}:{}".format(urllib.parse.quote(username), urllib.parse.quote(password))
    rest_root = NEMESIS_ROOT.format(auth=auth_part)
    rest = hammock.Hammock(rest_root)

    response = rest.user(username).GET()
    if not response.ok:
        return None

    output = response.json()
    if output["has_withdrawn"]:
        return None
    return {
        "username": output["username"],
        "teams": [team[5:] for team in output["teams"]],
        "firebase-token": "bees",
        "admin": output["is_blueshirt"],
    }
def run_log_in():
    asterix_host = "localhost"
    asterix_port = 19002
    user_id = request.forms.get('user_id');
    password = request.forms.get('password');
    #print password;
    #print user_id+','+password
    query_statement = 'use dataverse Tasks; for $n in dataset AccountInfo where $n.user_id='+str(user_id)+' return $n';
    query = {
        'query': query_statement
    };
    http_header = {
        'content-type': 'application/json'
    }
    query_url = "http://" + asterix_host + ":" + str(asterix_port) + "/query"
    ConnectionError = 1;
    HTTPError = 1;
    print query_url, query_statement;
    try:
        response = requests.get(query_url, params=query, headers=http_header)
        result = str(response.json()["results"][0]);
        # print result;
        resultArray = result.split(', ');
        resultLabel = resultArray[1];
        resultPassword = resultArray[2];
        labelArray = resultLabel.split(':');
        label = labelArray[1].replace('"', '').strip();
        passwordArray = resultPassword.split(':');
        correctPassword = passwordArray[1].replace('"', '').replace('}', '').strip();

        print password, correctPassword;

        if(password==correctPassword):
            print "correct"
            return '<p id="returnResult">1</p><p id="returnLabel">'+ label +'</p>'
        else:
            print "error"
            return '<p id="returnResult">0</p>'
    except (ConnectionError, HTTPError):
        print "Encountered connection error; stopping execution"
        sys.exit(1)

    return True
Esempio n. 13
0
 def img(self, teamNumber, year):
     #teamNumber = raw_input("please enter a team number: ")
     myRequest = (baseURL + 'team/frc' + str(teamNumber) + '/'+ str(year) + "/media")
     response = requests.get(myRequest, headers=header)
     jsonified = response.json()
     #print(jsonified)
     key = ""
     if jsonified != []:
         type = jsonified[0]['type']
         if type == "imgur":
             key = jsonified[0]['foreign_key']
             print key
             image = im.get_image(key)
             imgURL = (image.link)
         elif type == "cdphotothread":
             key = jsonified[0]['details']['image_partial']
             print(key)
             CDendURL = key
             imgURL = "https://www.chiefdelphi.com/media/img/" + str(CDendURL)
     else:
         imgURL = "http://www.404notfound.fr/assets/images/pages/img/androiddev101.jpg"
     return imgURL
Esempio n. 14
0
def load():
  global assets
  global load_errors
  global load_time
  assets = []
  load_errors = []
  print "Loading data from %s" % asset_dowload_root
  print "Set the DOWNLOAD_ROOT environment variable if you want data from somewhere else"
  for asset_filename in asset_filenames:
    try:
      response = requests.get(asset_dowload_root + asset_filename)
      assets += response.json()
    except ValueError:
      load_errors.append("Could not load '%s' from '%s'" % (asset_filename, asset_download_root))
  load_time = datetime.datetime.now().isoformat()

  for asset in assets:
    asset.setdefault('category', asset['type'])
    summary = asset['name']
    if len(summary) > SUMMARY_LENGTH:
      summary = summary[:SUMMARY_LENGTH-3] + "..."
    asset.setdefault('summary', summary) 
Esempio n. 15
0
def get_video(video, sender, chat_id):

    duration = video['duration']
    size = video['file_size']
    video_id = video['file_id']

    size = round(size / (1024 * 1024), 1)
    reply_message = f'Video Received\nDuration: {duration} seconds of size: {size} MB'

    # get the file path
    get_file_path_url = f'https://api.telegram.org/bot1291011387:AAEDG2wqE0t4XHbe_9RurkcJHJ_Fdw99rf8/getFile?file_id={video_id}'
    response = requests.get(get_file_path_url)
    try:
        file_path = response.json()['result']['file_path']
    except:
        reply_message = "Error Occured!Contact Narayan"
        return reply_message

    t = threading.Thread(target=download_video,
                         args=(file_path, sender, chat_id))
    t.start()

    return reply_message
Esempio n. 16
0
def getFinectV4(url, datetime_now):
    timeDelta = timedelta(days=7)
    values = []
    timeNow = datetime_now

    while values == [] and (datetime_now - timeNow) < timedelta(days=45):
        timeBefore = timeNow - timeDelta

        myUrl = url + "&start=" + str(timeBefore.year) + "-" + str(
            timeBefore.month) + "-" + str(timeBefore.day) + "&end=" + str(
                timeNow.year) + "-" + str(timeNow.month) + "-" + str(
                    timeNow.day)
        #        print myUrl
        response = requests.get(myUrl)
        response.raise_for_status()

        values = response.json()['data']
        timeNow = timeBefore

    if values != []:
        datetime_value = datetime.strptime("1977-01-01", '%Y-%m-%d')
        theValue = 0

        for value in values:
            #            print value
            new_datetime_value = datetime.strptime(
                value['datetime'].split('T')[0], '%Y-%m-%d')
            new_value = value['price']
            if new_datetime_value > datetime_value:
                datetime_value = new_datetime_value
                theValue = new_value


#    print theValue
#    print datetime_value

    return [str(theValue), datetime_value]
Esempio n. 17
0
def getweather():

    #get selection from user, create link to JSON object, convert to dictionary
    icao = request.forms.get('cities')
    url = "https://api.weatherapi.com/v1/current.json?key=<<API KEY>>=" + icao + "&aqi=no"
    response = requests.get(url)
    data = response.json()

    #get weather information for chosen airport, convert units as needed
    stationName = data["location"]["name"]
    clouds = data["current"]["condition"]["text"]
    windSpeed = data["current"]["wind_mph"]
    temperature = data["current"]["temp_f"]
    humidity = data["current"]["humidity"]

    #add data to tuple and send to table to display to user
    tpl = {
        'stationName': stationName,
        'clouds': clouds,
        'windSpeed': windSpeed,
        'temperature': temperature,
        'humidity': humidity
    }
    return template('weather', tpl)
Esempio n. 18
0
from bottle import run, route, run, error, static_file, template, response
import requests
import json
import os

response = requests.get('http://apis.is/concerts')
data = response.json()

#with open('petrol.json', 'r', encoding='utf-8') as f:
#    petrol = json.load(f)


@route('/')
def index():
    return template('index')


@route('/company/<id>')
def company(id):
    return template('company')


@route('/static_files/<filename>')
def server_static(filename):
    return static_file(filename, root='./static_files')


@error(404)
def error404(error):
    return '<h1>síða ekki til. 404</h1>'
Esempio n. 19
0
def get_gari():
    address = request.query.address
    uri = 'http://'+INNER_API_HOST+':'+str(INNER_API_PORT)+'/accounts/'+str(address)+'/balance'
    response = requests.get(uri)
    balance = response.json()[0]
    return {'balance': balance}
Esempio n. 20
0
    def get_team_name(self, team_no):

        myRequest = (baseURL + 'team/frc' + str(team_no))
        response = requests.get(myRequest, headers=header)
        jsonified = response.json()
        return jsonified['nickname']
Esempio n. 21
0
def getnews():
  url = ('https://newsapi.org/v2/top-headlines?'
       'country=us&'
       'apiKey=dba988d4aa5b4ba3b9b6b087651246ce')
  response = requests.get(url)
  return response.json()
Esempio n. 22
0
def getStockValues():
    timeDelta = timedelta(days=7)

    historyPath = path + "stockHistory/"
    if not os.path.exists(historyPath):
        os.makedirs(historyPath)

    templateText = "{0:20}|{1:12}|{2:12}|{3:12}"
    print(templateText.format("Name", " Paid", " Value", " Difference"))
    line = "-------------------------------------------------------------"
    print(line)
    template = "{0:20}|{1:12.2f}|{2:12.2f}|{3:12.2f}"
    templatePerc = "{0:20}|{1:12.2f}|{2:12.2f}|{3:11.2f}%"
    paidTotal = 0
    valueTotal = 0
    diffTotal = 0
    elemCnt = 0
    elements = len(data['stocks'])
    datetime_now = datetime.now()

    for elem in data['stocks']:
        stockValuesJson = {}
        url = elem['url']
        urlGoogle = ""
        datetime_value = datetime.strptime("1977-01-01", '%Y-%m-%d')
        theValue = 0

        try:
            urlv4 = elem['urlv4']
            [theValue, datetime_value] = getFinectV4(urlv4, datetime_now)
        except KeyError as error:
            pass

        if theValue == 0:
            for x in range(0, 5):
                try:
                    urlAvantage = elem['urlAvantage']
                    [theValue, datetime_value] = getAvantageValues(urlAvantage)
                    break
                except KeyError as error:
                    pass
                time.sleep(10)

        if theValue == 0:
            try:
                urlGoogle = elem['urlGoogle']
                theValue = getGoogleValues(urlGoogle)
                datetime_value = datetime_now
            except KeyError as error:
                pass

        statusJson['status'] = str(elemCnt) + " of " + str(elements)

        elemCnt = elemCnt + 1

        try:
            if theValue == 0:
                values = []
                timeNow = datetime_now

                while values == [] and (datetime_now -
                                        timeNow) < timedelta(days=45):
                    timeBefore = timeNow - timeDelta

                    myUrl = url + "?startDate=" + str(
                        timeBefore.year) + "-" + str(
                            timeBefore.month) + "-" + str(
                                timeBefore.day) + "&endDate=" + str(
                                    timeNow.year) + "-" + str(
                                        timeNow.month) + "-" + str(timeNow.day)
                    response = requests.get(myUrl)
                    response.raise_for_status()

                    values = response.json()
                    timeNow = timeBefore

                if values != []:
                    datetime_value = datetime.strptime("1977-01-01",
                                                       '%Y-%m-%d')
                    theValue = 0

                    for value in response.json():
                        new_datetime_value = datetime.strptime(
                            value['date'], '%Y-%m-%d')
                        new_value = value['value']
                        if new_datetime_value > datetime_value:
                            datetime_value = new_datetime_value
                            theValue = new_value

            if theValue != 0:
                currentInvestmentValue = float(theValue) * elem['titles']
                gain = float(theValue) * elem['titles'] - elem['paid']
                stockPaidPrice = (elem['paid'] / elem['titles'])
                gainPerc = (gain * 100) / elem['paid']

                color = bcolors.RED
                if gain > 0:
                    color = bcolors.GREEN

                print(color + template.format(elem['stock'], elem['paid'],
                                              currentInvestmentValue, gain))
                print(color + templatePerc.format(
                    datetime_value.strftime("%Y-%m-%d"), stockPaidPrice,
                    float(theValue), gainPerc))

                stockValuesJson['stock'] = elem['stock']
                stockValuesJson['paidTotal'] = elem['paid']
                stockValuesJson['investmentValue'] = currentInvestmentValue
                stockValuesJson['gain'] = gain
                stockValuesJson['date'] = datetime_value.strftime("%Y-%m-%d")
                stockValuesJson['paidPerStock'] = stockPaidPrice
                stockValuesJson['currValue'] = float(theValue)
                stockValuesJson['gainPerc'] = gainPerc

                stockValuesArrayJson.append(stockValuesJson)

                paidTotal = paidTotal + elem['paid']
                valueTotal = valueTotal + float(theValue) * elem['titles']
                diffTotal = diffTotal + float(
                    theValue) * elem['titles'] - elem['paid']

                print(bcolors.ENDC + line)

                with open(
                        historyPath + elem['stock'].replace(" ", "_") + ".csv",
                        'ab') as file:
                    file.write((datetime_value.strftime("%Y-%m-%d") + "," +
                                theValue + '\n').encode())
            else:
                color = bcolors.YELLOW
                print(color + elem['stock'])
                print(color + "Unable to retrieve values")
                print(bcolors.ENDC + line)

        except requests.exceptions.HTTPError as error:
            stockValuesJson['stock'] = elem['stock']
            stockValuesJson['paidTotal'] = elem['paid']
            stockValuesJson['investmentValue'] = 0
            stockValuesJson['gain'] = 0
            stockValuesJson['date'] = "1970-1-1"
            stockValuesJson['paidPerStock'] = 0
            stockValuesJson['currValue'] = 0
            stockValuesJson['gainPerc'] = 0

            stockValuesArrayJson.append(stockValuesJson)

            print(error.response.status_code, error.response.text)

    color = bcolors.RED
    if diffTotal > 0:
        color = bcolors.GREEN
    print(color + template.format("TOTAL:", paidTotal, valueTotal, diffTotal))
    templateSummary = "{0:46}|{1:11.2f}%"
    print(
        templateSummary.format("      ", float((diffTotal * 100) /
                                               paidTotal)) + bcolors.ENDC)

    totalsJson['paidTotal'] = paidTotal
    totalsJson['valueTotal'] = valueTotal
    totalsJson['gain'] = diffTotal
    totalsJson['gainPerc'] = float((diffTotal * 100) / paidTotal)

    for elem in data['stocks']:
        # remove duplicated
        prevLine = ""
        fileName = historyPath + elem['stock'].replace(" ", "_") + ".csv"
        origFileName = fileName + ".orig"
        shutil.move(fileName, origFileName)
        firstLine = 1
        with open(origFileName, 'rb') as fileRead:
            with open(fileName, 'wb') as fileWrite:
                for line in fileRead:
                    if firstLine == 1:
                        if line != "Date,Value\n":
                            fileWrite.write(("Date,Value\n").encode())
                        firstLine = 0
                    if line != prevLine:
                        fileWrite.write(line)
                        prevLine = line

                stocks_json.append("" + elem['stock'].replace(" ", "_"))
                paidVal_json.append(elem['paid'] / elem['titles'])

        os.remove(origFileName)

    statusJson['status'] = "Done"

    return
Esempio n. 23
0
def indexv1():
    title = request.query.title or 'Quilombo'
    lang = request.query.lang or 'en'
    print(request.environ)
    userIp = request.environ.get('HTTP_X_FORWARDED_FOR')
    f.write('Demopage %s %s %s \n' % (userIp, lang, title))
    if lang not in SecRec.suportedLangs:
        text = '%s is not supported; supported languages are: %s'
    else:

        try:
            response = requests.get(
                "https://%s.wikipedia.org/api/rest_v1/page/summary/%s" %
                (lang, title))
            r = response.json()
            text = r['extract_html']
            image = r.get('thumbnail', {}).get('source', '')
            recs = SecRec.getRecs2(title,
                                   lang,
                                   blind=False,
                                   verbose=True,
                                   giveTitles=True)
            secRec = recs['Recommendations']
            currentSec = recs['context']['CurrentSections']
            numPerLang = {}
            langtitles = recs['context']['titles']
            for l, s in recs['context']['SectionsInOtherLanguages'].items():
                numPerLang[l] = len(s)

        except:
            try:  #this try is in case that SecRec.getRecs fails, but there is still a pagepreview
                response = requests.get(
                    "https://%s.wikipedia.org/api/rest_v1/page/summary/%s" %
                    (lang, title))
                r = response.json()
                text = r['extract_html']
                image = r.get('thumbnail', {}).get('source', '')
            except:
                text = 'Article not found, please try another article'
                image = ''
            recs = {'context': {'usedMoreLike': ''}}
            secRec = []
            currentSec = ''
            langtitles = {}
            numPerLang = {}
    return template('''  

			<!DOCTYPE html>
			<html>
			<head>

			  <title>Section Recommendation Demo</title>
			  <link href="/static/bootstrap.min.css" rel="stylesheet">
			<style>
				body {
				    background-color: #EAECF0 !important;
				}

				header, main, footer {
				    margin: 10px 0 30px;
				}

				header .project-name {
				    font-size: 1.5em;
				}

				footer {
				    margin-top: 100px;
				}

								
				.main-content {
				    background-color: white;
				    padding: 15px;
				}

			p {
			  text-align: justify;
			  text-justify: inter-word;
			}
			</style>


			</head>


			<body>
			  <div class="container">
  			   <div class="row"> <h1> Section Recommendation Demo  </h1> </div>


			   <div class="row">  
				<form action="/v1">

				Wiki: 
				  <select name="lang" value="{{lang}}">

				    <option value="ar">ar.wikipedia</option>
				    <option value="ar">ar.wikipedia</option>
				    <option value="en">en.wikipedia</option>
				    <option value="es">es.wikipedia</option>
				    <option value="fr">fr.wikipedia</option>
				    <option value="ja">ja.wikipedia</option>
				    <option value="ru">ru.wikipedia</option>
				    <option value="pt">.wikipedia</option>


				    <option value="en" selected ></option>
				  </select>
				Article: <input type="text" name="title" value="{{title}}">
				 <input type="submit" value="Try Another Article"> <br>
							</form>  
			   </div>
			
			   <div class="row justify-content-md-center">
   				
				<div class="col-lg">
  			  	         <h3> {{title}} - {{lang}}.wikipedia.org </h3>  
					 <b> Article Summary: </b> <br>

					<img style="margin: 0px 15px 5px 0px" src="{{image}}" ALIGN="left"> {{!text}} 
				<br>
				%if secRec: 
				<a href='https://{{lang}}.wikipedia.org/w/index.php?title={{title}}&action=edit' target='_blank'> Go to Wikipedia and edit this article </a>
				%end
				</div>

				<div class="col-sm">

				<b>Recommended sections:</b>
				<ul><table>
				<form action="/evaluated/{{lang}}/{{title}}/">
					


					  % for item in secRec:
					     <tr> <td ><li><b>{{item}}</b> </li></td><td>  <input type="radio" name="{{item}}" value="good" > Good  </td><td><input type="radio" name="{{item}}" value="redundant"> Redundant   </td><td><input type="radio" name="{{item}}" value="NotRelated"> Not Related </td></tr>
					  % end
				</table></ul>
					 %if secRec:
					 <input type="submit" value="Evaluate"> <br>
					 %end
					 %if not secRec:
					 We can't provide section recommendations for this article.  This might be because the current article is the one with more complete set of sections among all the supported languages or we don't have good quality alignments for the remaining sections.
					 %end
					  </form> 

					</ul>
					<b>Number of sections in other languages:</b>
					%if useMoreLike:
					<br>We couldn't find sections to recommend in any of the supported languages. This page might be an <a href="https://en.wikipedia.org/wiki/Wikipedia:Stub"> Stub</a>. To provide recommendations we have used similar pages:	<br> 
					%end
					<ul>
					  % if not numPerLang:
						<li> These article does not exists in any of the other supported languages </li>
					  %end
					  % for l,n in numPerLang.items():
					    <li><b> {{l}}:</b> {{n}}  <a href="https://{{l}}.wikipedia.org/wiki/{{langtitles[l]}}">{{langtitles[l]}}</a></li>
					  % end
					</ul>
					<b>Current sections and subsections in this article are:</b>
					<ul>
					  %if currentSec and not useMoreLike:
					 <li>{{currentSec}} </li>
					 %end	
					  %if not currentSec:
					 <li>The current article has no sections yet. </li>
					 %end
					</ul>

				</div>
			    </div>
	

			   </div>

			</body>
			</html>
			''',
                    text=text,
                    image=image,
                    title=title,
                    lang=lang,
                    secRec=secRec,
                    currentSec=currentSec,
                    numPerLang=numPerLang,
                    langtitles=langtitles,
                    useMoreLike=recs['context']['usedMoreLike'])
Esempio n. 24
0
from bottle import run, route, run, error, static_file, template, response
import requests
import os
import json

response = requests.get('http://apis.is/petrol')
stats = response.json()

#with open('petrol.json', 'r', encoding='utf-8') as f:
#    petrol = json.load(f)


@route('/')
def index():
    return template('index')

@route('/company/<id>')
def company(id):
    return template('company', id=id, stats=stats)


@route('/moreinfo/<key>')
def detail(key):
    return template('moreinfo',key=key, stats=stats)



@route('/static_files/<filename>')
def server_static(filename):
    return static_file(filename, root='./static_files')
Esempio n. 25
0
def get_name():
    response.headers['Content-Type'] = 'application/json'
    response.json({'text1': 'json'})
Esempio n. 26
0
def index():
    try:
        evaluations = dict(request.query.decode())
        if evaluations.get('GenerateRandom', False):
            lang = request.query.lang or 'en'
            title = SecRec.getArticleWithRec(lang)
        else:
            lang = request.query.lang or 'en'
            title = request.query.title or SecRec.getArticleWithRec(lang)

        print(title, lang)
        userIp = request.environ.get('HTTP_X_FORWARDED_FOR')
        f.write('Demopage %s %s %s \n' % (userIp, lang, title))
        if evaluations:
            mariadb_connection = mariadb.connect(user='******',
                                                 password='******',
                                                 database='app')
            titleEval = evaluations.get('title')
            langEval = evaluations.get('lang')
            Q1 = evaluations.get('Q1', 'No Reponse')
            Q2 = evaluations.get('Q2', 'No Reponse')
            Q3 = evaluations.get('Q3', 'No Reponse')
            Q4 = evaluations.get('Q4', 'No Reponse')
            Q5 = evaluations.get('Q5', 'No Reponse')
            print('values:', userIp, titleEval, langEval, Q1, Q2, Q3, Q4, Q5)
            cmd = "INSERT INTO evaluationGeneral (ip,article,lang,Q1,Q2,Q3,Q4,Q5) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s')" % (
                userIp, titleEval, langEval, Q1, Q2, Q3, Q4, Q5)
            print(cmd)
            cursor = mariadb_connection.cursor()
            cursor.execute(cmd)
            mariadb_connection.commit()
            cursor.close()
            mariadb_connection.close()

        if lang not in SecRec.suportedLangs:
            text = '%s is not supported; supported languages are: %s'
        else:

            try:
                response = requests.get(
                    "https://%s.wikipedia.org/api/rest_v1/page/summary/%s" %
                    (lang, title))
                r = response.json()
                text = r['extract_html']
                image = r.get('thumbnail', {}).get('source', '')
                recs = SecRec.getRecs2(title,
                                       lang,
                                       blind=False,
                                       verbose=True,
                                       giveTitles=True)
                secRec = recs['Recommendations']
                currentSec = recs['context']['CurrentSections']
                numPerLang = {}
                langtitles = recs['context']['titles']
                for l, s in recs['context']['SectionsInOtherLanguages'].items(
                ):
                    numPerLang[l] = len(s)

            except:
                try:  #this try is in case that SecRec.getRecs fails, but there is still a pagepreview
                    response = requests.get(
                        "https://%s.wikipedia.org/api/rest_v1/page/summary/%s"
                        % (lang, title))
                    r = response.json()
                    text = r['extract_html']
                    image = r.get('thumbnail', {}).get('source', '')
                except:
                    text = 'Article not found, please try another article'
                    image = ''
                recs = {'context': {'usedMoreLike': ''}}
                secRec = []
                currentSec = ''
                langtitles = {}
                numPerLang = {}
        return template('''  

				<!DOCTYPE html>
				<html>
				<head>

				  <title>Section Recommendation Demo</title>
				  <link href="/static/bootstrap.min.css" rel="stylesheet">
				<style>
					body {
					    background-color: #EAECF0 !important;
					}

					header, main, footer {
					    margin: 10px 0 30px;
					}

					header .project-name {
					    font-size: 1.5em;
					}

					footer {
					    margin-top: 100px;
					}

								
					.main-content {
					    background-color: white;
					    padding: 15px;
					}

				p {
				  text-align: justify;
				  text-justify: inter-word;
				}
				</style>


				</head>

				<body>
				  <div class="container">

				   <div class="row" style="border-style:solid">  
					<form action="/">
				<table >
					 <tr> <td >Wiki:  </td><td style="margin:5px">
					  <select name="lang" value="{{lang}}">


					    <option value="{{lang if lang else 'en'}}" selected="selected">{{lang if lang else 'en'}}.wikipedia</option>
	
					    <option value="ar">ar.wikipedia</option>
					    <option value="es">es.wikipedia</option>
					    <option value="fr">fr.wikipedia</option>
					    <option value="ja">ja.wikipedia</option>
					    <option value="ru">ru.wikipedia</option>
					  </select> <br></td> 
			
					 <td >Article:</td><td> <input type="text" name="title" value="{{title}}"> <br> </td> 
					 <td><input type="submit" value="Get recommendations"> <br></td> </tr>
								</form>  
				</table>

				   </div>
			
				   <div class="row justify-content-md-center">
	   				
					<div class="col-lg">
	  			  	         <h3> {{title}} - {{lang}}.wikipedia.org </h3>  
						 <b> Article Summary: </b> <br>


						<img style="margin: 0px 15px 5px 0px" src="{{image}}" ALIGN="left"> {{!text[:-4]}} 
	<a href='https://{{lang}}.wikipedia.org/w/index.php?title={{title}}' target='_blank'> View on Wikipedia</a> </p>


					<b>Current sections and subsections in this article are:</b>
					<ul>
					%if currentSec and not useMoreLike:
						%for current in currentSec:
						<li>{{current}} </li>
						%end
					%end	
					%if not currentSec:
					<li>The current article has no sections yet. </li>
					%end
					</ul>


					</div>

					<div class="col-sm">

						<h3>Recommended sections:</h3>
						<form action="/">
						<ul>
						% for item in secRec:
							<li><b>{{item}}</b> </li>				
						%end
						</ul>



						 %if secRec:

						<b> Most or all of the recommended sections.. </b>
						<ol>
						<li>  Are relevant to the topic of this article </li>
						<input type="radio" name="Q1" value="agree" > Agree <input type="radio" name="Q1" value="disagree" > Disagree
						<li> Are important for this article to have</li>
						<input type="radio" name="Q2" value="agree" > Agree <input type="radio" name="Q2" value="disagree" > Disagree
						<li> Are redundant or conflict with the existing sections in the article</li>
						<input type="radio" name="Q3" value="agree" > Agree <input type="radio" name="Q3" value="disagree" > Disagree
						<li> Are redundant or conflict with other recommended sections</li>
						<input type="radio" name="Q4" value="agree" > Agree <input type="radio" name="Q4" value="disagree" > Disagree
						</ol>
						<ul>
						<li> <b> If I were expanding this article, I would find these recommendations useful </b></li>
						<input type="radio" name="Q5" value="agree" > Agree <input type="radio" name="Q5" value="disagree" > Disagree <br>
						 <input type="submit" value="Submit Ratings"> <br>
						 %end
						 %if not secRec:
						 We can't provide section recommendations for this article.  This might be because the current article is the one with more complete set of sections among all the supported languages, please select another article.
						 %end
	   					 <input type="hidden" name="title" value="{{title}}" />
	   					 <input type="hidden" name="lang" value="{{lang}}" />
	   					 <input type="hidden" name="GenerateRandom" value="yes" />
						  </form> 
						<form action="/"> <input type="submit" value="Skip Article"> <br>
						</ul>
	<b> Provide additional feedback </b> <br>
	<p>If you would like to provide additional feedback on
	these recommendations, please do so on the <a href='https://meta.wikimedia.org/wiki/Research_talk:Expanding_Wikipedia_articles_across_languages/Inter_language_approach/Feedback' target="_blank">talk page</a>. </p>
	<p>If you paste the template below with your feedback, it
	will help us understand your comments better.</p>

	{{'{{'}}Section_recommendation_feedback <br>
	|lang={{lang}}<br>
	|article={{title}}<br>
	|link=https://secrec.wmflabs.org/?lang={{lang}}&title={{title}}<br>
	% for n,item in enumerate(secRec):
	|section{{n+1}}={{item}}<br>				
	%end
	{{'}}'}}				</div>
				    </div>
	

				   </div>

				</body>
				</html>
				''',
                        text=text,
                        image=image,
                        title=title,
                        lang=lang,
                        secRec=secRec,
                        currentSec=currentSec,
                        numPerLang=numPerLang,
                        langtitles=langtitles,
                        useMoreLike=recs['context']['usedMoreLike'])

    except Exception as e:
        print('error - reloading', e)
        index()