Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
No Output
#1
Can someone help me with the following code? I am not getting any output

from datetime import datetime

import json

import StringIO

import urllib2

import smtplib

from email.mime.text import MIMEText





hours = ['00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00',

         '07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00',

         '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00',

         '21:00', '22:00', '23:00']



normalized = {1: 4.55, 2: 4.43, 3: 4.58, 4: 4.81, 5: 4.51, 6: 4.32,

              7: 3.54, 8: 3.71, 9: 4.66, 10: 4.77, 11: 4.37, 12: 4.06}





sites = [{'name': 'Atlas',

          'key': '2tGucWLG',

          'id': '2313528',

          'path': 'components',

          'installed': '100000'},

         {'name': 'Institute of Business Management',

          'key': 'Icdn3ZjZ',

          'id': '3667293',

          'path': 'sites',

          'installed': '31620'},

         {'name': 'McDonald''s Corniche Branch',

          'key': 'CmTgpuq9',

          'id': '3666787',

          'path': 'sites',

          'installed': '39680'},

         {'name': 'Daewoo',

          'key': 'NNpxBmb2',

          'id': '3692077',

          'path': 'sites',

          'installed': '63200'},

         {'name': 'Crescent Steel & Allied Products Limited',

          'key': 'k8PLXeoC',

          'id': '3694088',

          'path': 'sites',

          'installed': '20800'},

         {'name': 'Happy Home School',

          'key': 'Snh1jzUX',

          'id': '3694012',

          'path': 'sites',

          'installed': '15800'},

         {'name': 'Reflections School Korangi Creek Project',

          'key': 'frDgX5VY',

          'id': '3698900',

          'path': 'sites',

          'installed': '26380'},

         {'name': 'Jaffer Brothers Rental Yard',

          'key': 'LTdOSqo4',

          'id': '3737109',

          'path': 'sites',

          'installed': '10080'},

         {'name': 'Alsons Autoparts',

          'key': '6iU7C5zT',

          'id': '3714094',

          'path': 'sites',

          'installed': '5680'},

         {'name': 'Nadir Jaffer Residence',

          'key': 'Fqy7fhm4',

          'id': '3723750',

          'path': 'sites',

          'installed': '8680'},

         {'name': 'Habib Metro Korangi Branch',

          'key': 'kfMCRuDA',

          'id': '3677650',

          'path': 'sites',

          'installed': '14500'},

         {'name': 'Bank Al Habib Highway Branch',

          'key': 'G3ntMUmS',

          'id': '3698916',

          'path': 'sites',

          'installed': '11250'}

         ]





def build_url(item):

    return "https://kiosk.datareadings.com/v1/kiosks/%s/api/%s/%s/data?tz=Asia/Karachi&" % (item['ke

y'], item['path'], item['id'])



def build_url_hourly(item, date):

    return "%sfields=Wh_sum&gran=hourly&start=%sT00:00:00&end=%sT23:59:59" % \

        (build_url(item), date.strftime('%Y-%m-%d'), date.strftime('%Y-%m-%d'))



def build_url_avg(item):

    return "%sfields=W_avg&gran=latest" % build_url(item)



def build_dashboard_url(item):

    return "http://kiosk.datareadings.com/%s/overview" % item['key']





def get_hourly_data(item, date):

    url = build_url_hourly(item, date)

    #f = open('test_hourly.json')

    f = urllib2.urlopen(url)

    data = json.loads(f.read())

    f.close()

    return data





def get_avg_data(item):

    url = build_url_avg(item)

    #f = open('test_avg.json')

    f = urllib2.urlopen(url)

    data = json.loads(f.read())

    f.close()

    return data



def get_daily_output(data):

    total = 0

    for row in data:

        total += row.get('Wh_sum', 0)

    return total



def get_daily_max_output(data):

    max_unit = 0

    max_time = ''

    for row in data:

        if row.get('Wh_sum', 0) > max_unit:

            max_unit = row['Wh_sum']

            max_time = row['ts'].split('T')[1].split('+')[0]



    return (max_unit, max_time)



def split_hourly_data(data):

    hourly_data = {}

    for item in data:

        data_ = item[7]['data']

        for hour_row in data_:

            id_ = hourly_data.get(hour_row.get('id', 0), {})

            hour_ = hour_row.get('ts', '0000-00-00T00:00:00+05:00').split('T')[1].split('+')[0][:5]

            id_[hour_] = hour_row.get('Wh_sum', 0)

            hourly_data[hour_row.get('id')] = id_





    return hourly_data



def create_report_rows(sites):

    today = datetime.now()

    items = []



    for site in sites:

        data = get_hourly_data(site, today)

        avg = get_avg_data(site)

        total_units = get_daily_output(data['data'])

        avg_unit = avg.get('data', [{'W_avg': 0}])[0].get('W_avg', 0)

        max_unit = get_daily_max_output(data['data'])[0]

        max_percent = max_unit/float(site['installed'])

        normalized = total_units/float(site['installed'])



        items.append((site['name'], float(site['installed']), total_units, avg_unit, max_unit, max_p

ercent, normalized, data, site))



    return items, today



def get_summary_table(sites, hourly_data):

    pass











def create_report(sites):

    data, dt = create_report_rows(sites)

    hourly_data = split_hourly_data(data)

    json_data = json.dumps(data)



    html = StringIO.StringIO()

    html.write("""

       <style type='text/css'>

         body { font-family: Helvetica, sans-serif}

         table { padding: 3px; border-spacing: 0px; border-collapse: all}

         td, th { border: solid 1px #333; padding: 2px}

         td { text-align: right; padding-right: 5px;}

         td:first-child { text-align: left; }

       </style>

    """)



    html.write("""<table>

                  <thead>

                  <tr>

                    <th>Name</th>

                    <th>Installed kWp</th>

                    <th>Total Units (kWh)</th>

                    <th>Peak Power (kW)</th>

                    <th>Peak Power % (kW/kWp)</th>

                    <th>Normalized Units (kWh/kWp)</th>

                    <th>Expected</th>

                  </tr>

                  </thead>""")



    html.write("<tbody>")

    for item in sorted(data, key=lambda i: i[6], reverse=True):

        html.write("<tr>")

        html.write("<td><a href='%s' target='_new'>%s</a></td>\n" % (build_dashboard_url(item[8]),it

em[0]))

        html.write("<td>%s</td>" % '{:,.3f}'.format(item[1]/1000.0))

        html.write("<td>%s</td>" % '{:,.3f}'.format(item[2]/1000.0))

        html.write("<td>%s</td>" % '{:,.3f}'.format(item[4]/1000.0))

        html.write("<td>%s%%</td>\n" % '{:,.2f}'.format(item[5]*100))

        if item[8]['name'].startswith('Nadir'):

            html.write("<td style='color: red; font-weight: bold'>%s</td>" % '{:,.3f}'.format(item[6

]))

        else:

            html.write("<td>%s</td>" % '{:,.3f}'.format(item[6]))

        html.write("<td>%s</td>" % normalized.get(dt.month, 0))

        html.write("</tr>\n")



    html.write("</tbody></table><br /><br /><br />\n")





    html.write("<table>")

    html.write("<thead><tr>")

    html.write("<th></th>")



    for hour in hours:

        html.write("<th>%s</th>" % hour)

    html.write("</tr></thead>\n")



    html.write("<tbody>")

    for site in sorted(sites, key=lambda s: s['name']):

        html.write("<tr><td>%s</td>" % site['name'])

        hour_data = hourly_data.get(int(site['id']), {})

        for hour in hours:

            if hour_data.get(hour, 0.0) != 0:

                html.write("<td>%skW</td>\n" % '{:,.3f}'.format(hour_data.get(hour, 0.0)/1000.0))

            else:

                html.write("<td></td>")

        html.write("</tr>\n")



    html.write("</tbody>")

    html.write("</table><br /><br /><br />\n")







    html.write("<table>")

    html.write("<thead><tr>")

    html.write("<th></th>")



    for hour in hours:

        html.write("<th>%s</th>" % hour)

    html.write("</tr></thead>")



    html.write("<tbody>")

    for site in sorted(sites, key=lambda s: s['name']):

        html.write("<tr><td>%s</td>" % site['name'])

        hour_data = hourly_data.get(int(site['id']), {})

        for hour in hours:

            if hour_data.get(hour, 0.0) > 0:

                percent_utilized = hour_data.get(hour, 0.0)/float(site['installed'])



                html.write("<td>%s%%</td>" %  '{:,.2f}'.format((percent_utilized*100)))

            else:

                html.write("<td></td>")

        html.write("</tr>")



    html.write("</tbody>")
Reply
#2
Please, edit your post and use the python code tag...
Reply
#3
In addition to python tags (see the BBCode link in my signature below for instructions), edit your code down to a small chunk that reproduces the error.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#4
What do you mean by using python tags in the thread name? Is it necessary?

What exactly do you want me to do?
Reply
#5
(Sep-13-2018, 02:42 PM)syedsaa89 Wrote: What do you mean by using python tags in the thread name? Is it necessary?

What exactly do you want me to do?
read BBcode help for more info.
and yes, it is necessary, because it preserves the indentation which is important in python and also makes easier to read code.
Check also link in my signature how to create Minimal, Complete, and Verifiable example
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#6
from datetime import datetime

import json

import StringIO

import urllib2

import smtplib

from email.mime.text import MIMEText





hours = ['00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00',

'07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00',

'14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00',

'21:00', '22:00', '23:00']



normalized = {1: 4.55, 2: 4.43, 3: 4.58, 4: 4.81, 5: 4.51, 6: 4.32,

7: 3.54, 8: 3.71, 9: 4.66, 10: 4.77, 11: 4.37, 12: 4.06}





sites = [{'name': 'Atlas',

'key': '2tGucWLG',

'id': '2313528',

'path': 'components',

'installed': '100000'},

{'name': 'Institute of Business Management',

'key': 'Icdn3ZjZ',

'id': '3667293',

'path': 'sites',

'installed': '31620'},

{'name': 'McDonald''s Corniche Branch',

'key': 'CmTgpuq9',

'id': '3666787',

'path': 'sites',

'installed': '39680'},

{'name': 'Daewoo',

'key': 'NNpxBmb2',

'id': '3692077',

'path': 'sites',

'installed': '63200'},

{'name': 'Crescent Steel & Allied Products Limited',

'key': 'k8PLXeoC',

'id': '3694088',

'path': 'sites',

'installed': '20800'},

{'name': 'Happy Home School',

'key': 'Snh1jzUX',

'id': '3694012',

'path': 'sites',

'installed': '15800'},

{'name': 'Reflections School Korangi Creek Project',

'key': 'frDgX5VY',

'id': '3698900',

'path': 'sites',

'installed': '26380'},

{'name': 'Jaffer Brothers Rental Yard',

'key': 'LTdOSqo4',

'id': '3737109',

'path': 'sites',

'installed': '10080'},

{'name': 'Alsons Autoparts',

'key': '6iU7C5zT',

'id': '3714094',

'path': 'sites',

'installed': '5680'},

{'name': 'Nadir Jaffer Residence',

'key': 'Fqy7fhm4',

'id': '3723750',

'path': 'sites',

'installed': '8680'},

{'name': 'Habib Metro Korangi Branch',

'key': 'kfMCRuDA',

'id': '3677650',

'path': 'sites',

'installed': '14500'},

{'name': 'Bank Al Habib Highway Branch',

'key': 'G3ntMUmS',

'id': '3698916',

'path': 'sites',

'installed': '11250'}

]





def build_url(item):

return "https://kiosk.datareadings.com/v1/kiosks/%s/api/%s/%s/data?tz=Asia/Karachi&" % (item['ke

y'], item['path'], item['id'])



def build_url_hourly(item, date):

return "%sfields=Wh_sum&gran=hourly&start=%sT00:00:00&end=%sT23:59:59" % \

(build_url(item), date.strftime('%Y-%m-%d'), date.strftime('%Y-%m-%d'))



def build_url_avg(item):

return "%sfields=W_avg&gran=latest" % build_url(item)



def build_dashboard_url(item):

return "http://kiosk.datareadings.com/%s/overview" % item['key']





def get_hourly_data(item, date):

url = build_url_hourly(item, date)

#f = open('test_hourly.json')

f = urllib2.urlopen(url)

data = json.loads(f.read())

f.close()

return data





def get_avg_data(item):

url = build_url_avg(item)

#f = open('test_avg.json')

f = urllib2.urlopen(url)

data = json.loads(f.read())

f.close()

return data



def get_daily_output(data):

total = 0

for row in data:

total += row.get('Wh_sum', 0)

return total



def get_daily_max_output(data):

max_unit = 0

max_time = ''

for row in data:

if row.get('Wh_sum', 0) > max_unit:

max_unit = row['Wh_sum']

max_time = row['ts'].split('T')[1].split('+')[0]



return (max_unit, max_time)



def split_hourly_data(data):

hourly_data = {}

for item in data:

data_ = item[7]['data']

for hour_row in data_:

id_ = hourly_data.get(hour_row.get('id', 0), {})

hour_ = hour_row.get('ts', '0000-00-00T00:00:00+05:00').split('T')[1].split('+')[0][:5]

id_[hour_] = hour_row.get('Wh_sum', 0)

hourly_data[hour_row.get('id')] = id_





return hourly_data



def create_report_rows(sites):

today = datetime.now()

items = []



for site in sites:

data = get_hourly_data(site, today)

avg = get_avg_data(site)

total_units = get_daily_output(data['data'])

avg_unit = avg.get('data', [{'W_avg': 0}])[0].get('W_avg', 0)

max_unit = get_daily_max_output(data['data'])[0]

max_percent = max_unit/float(site['installed'])

normalized = total_units/float(site['installed'])



items.append((site['name'], float(site['installed']), total_units, avg_unit, max_unit, max_p

ercent, normalized, data, site))



return items, today



def get_summary_table(sites, hourly_data):

pass











def create_report(sites):

data, dt = create_report_rows(sites)

hourly_data = split_hourly_data(data)

json_data = json.dumps(data)



html = StringIO.StringIO()

html.write("""

<style type='text/css'>

body { font-family: Helvetica, sans-serif}

table { padding: 3px; border-spacing: 0px; border-collapse: all}

td, th { border: solid 1px #333; padding: 2px}

td { text-align: right; padding-right: 5px;}

td:first-child { text-align: left; }

</style>

""")



html.write("""<table>

<thead>

<tr>

<th>Name</th>

<th>Installed kWp</th>

<th>Total Units (kWh)</th>

<th>Peak Power (kW)</th>

<th>Peak Power % (kW/kWp)</th>

<th>Normalized Units (kWh/kWp)</th>

<th>Expected</th>

</tr>

</thead>""")



html.write("<tbody>")

for item in sorted(data, key=lambda i: i[6], reverse=True):

html.write("<tr>")

html.write("<td><a href='%s' target='_new'>%s</a></td>\n" % (build_dashboard_url(item[8]),it

em[0]))

html.write("<td>%s</td>" % '{:,.3f}'.format(item[1]/1000.0))

html.write("<td>%s</td>" % '{:,.3f}'.format(item[2]/1000.0))

html.write("<td>%s</td>" % '{:,.3f}'.format(item[4]/1000.0))

html.write("<td>%s%%</td>\n" % '{:,.2f}'.format(item[5]*100))

if item[8]['name'].startswith('Nadir'):

html.write("<td style='color: red; font-weight: bold'>%s</td>" % '{:,.3f}'.format(item[6

]))

else:

html.write("<td>%s</td>" % '{:,.3f}'.format(item[6]))

html.write("<td>%s</td>" % normalized.get(dt.month, 0))

html.write("</tr>\n")



html.write("</tbody></table><br /><br /><br />\n")





html.write("<table>")

html.write("<thead><tr>")

html.write("<th></th>")



for hour in hours:

html.write("<th>%s</th>" % hour)

html.write("</tr></thead>\n")



html.write("<tbody>")

for site in sorted(sites, key=lambda s: s['name']):

html.write("<tr><td>%s</td>" % site['name'])

hour_data = hourly_data.get(int(site['id']), {})

for hour in hours:

if hour_data.get(hour, 0.0) != 0:

html.write("<td>%skW</td>\n" % '{:,.3f}'.format(hour_data.get(hour, 0.0)/1000.0))

else:

html.write("<td></td>")

html.write("</tr>\n")



html.write("</tbody>")

html.write("</table><br /><br /><br />\n")







html.write("<table>")

html.write("<thead><tr>")

html.write("<th></th>")



for hour in hours:

html.write("<th>%s</th>" % hour)

html.write("</tr></thead>")



html.write("<tbody>")

for site in sorted(sites, key=lambda s: s['name']):

html.write("<tr><td>%s</td>" % site['name'])

hour_data = hourly_data.get(int(site['id']), {})

for hour in hours:

if hour_data.get(hour, 0.0) > 0:

percent_utilized = hour_data.get(hour, 0.0)/float(site['installed'])



html.write("<td>%s%%</td>" % '{:,.2f}'.format((percent_utilized*100)))

else:

html.write("<td></td>")

html.write("</tr>")



html.write("</tbody>")
Reply
#7
You seem to have ignored the requests to edit your code down to a small chunk that reproduces the error. We don't want to read so much code. @buran's comment has links at the bottom giving advice on how to do this.
I am trying to help you, really, even if it doesn't always seem that way
Reply
#8
You need to follow the instructions so that the indentation of your code is retained. As you posted your code, we still cannot help you, because we cannot see the indentation to be clear on the logic of the code.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#9
I have added code tag in you first post,as indentation was okay there but missed code tag.
syedsaa89 Wrote:Can someone help me with the following code? I am not getting any output
At some point you most have tested some output,
because no one write 500 lines of code then try to run it and hope for best.
Explain better what the problem is.
Reply
#10
You do not appear to be calling any of the functions you have defined, so there is no output because you haven't asked for anything to be done.
I am trying to help you, really, even if it doesn't always seem that way
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020