code
stringlengths
1
1.49M
vector
listlengths
0
7.38k
snippet
listlengths
0
7.38k
""" forlater This file loads the finished app from forlater.config.middleware. """ from forlater.config.middleware import make_app
[ [ 8, 0, 0.4375, 0.75, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 1, 0.125, 0, 0.66, 1, 306, 0, 1, 0, 0, 306, 0, 0 ] ]
[ "\"\"\"\nforlater\n\nThis file loads the finished app from forlater.config.middleware.\n\n\"\"\"", "from forlater.config.middleware import make_app" ]
from forlater.lib.base import * from time import * from sqlalchemy import * from paste.request import get_cookie_dict import os import shutil import sys import urllib import httplib class AController(BaseController): def index(self): return Response('4l8r') def send_sms_message(self): if request.GET.has_key('PhoneNumber') and request.GET.has_key('Text') and request.GET.has_key('auth') and request.GET['auth'] == 'supersecret': conn = httplib.HTTPConnection(g.sms_url_server) params = urllib.urlencode([('PhoneNumber', request.GET['PhoneNumber']), ('Text', request.GET['Text'])]) url = g.sms_url_path + "?" + params conn.request("GET", url) r1 = conn.getresponse() status = str(r1.status) data1 = r1.read() conn.close() return Response('Status: ' + status) else: return Response('not authenticated correctly...') def upload(self): c = get_cookie_dict(request.environ) if not c.has_key('auth_token') or c['auth_token'] != g.upload_auth_token: abort(401) from_number = None text = None audioFile = None audioFilename = None pictureFile = None pictureFilename = None now = localtime() now_string = strftime('%Y%m%d_%H%M%S', now) now_mysql_string = strftime('%Y-%m-%d %H:%M:%S', now) if request.POST.has_key('from'): try: # make sure from number is an actual number of lenght 10 or less # note: this would need to change for places where phone numbers have > 10 digits l = long(request.POST['from']) s = str(l) if len(s) <= 10: from_number = s except: pass if request.POST.has_key('text'): text = request.POST['text'] if request.POST.has_key('audioFile'): audioFile = request.POST['audioFile'] audioFilename = now_string + '_' + from_number + '.mp3' if request.POST.has_key('pictureFile'): pictureFile = request.POST['pictureFile'] pictureFilename = now_string + '_' + from_number + '.jpg' if (not from_number) or ((not text) and (not audioFilename) and (not pictureFilename)) : return Response('NO | This URL only accepts properly formatted POST requests') # create a new entry i = model.entries_table.insert() e = i.execute(phone=from_number, snippet_time=now_mysql_string, done=0) e_ids = e.last_inserted_ids() if len(e_ids) == 0: return Response('NO | There was an error creating a new entry') e_id = e_ids[0] if text: i = model.snippets_table.insert() e = i.execute(entry_id=e_id, content=text, type='text') if len(e.last_inserted_ids()) == 0: return Response('NO | There was an error inserting a snippet') if audioFilename: permanent_file = open(os.path.join(g.audio_file_dir, audioFilename), 'w') shutil.copyfileobj(audioFile.file, permanent_file) audioFile.file.close() permanent_file.close() i = model.snippets_table.insert() e = i.execute(entry_id=e_id, content=audioFilename, type='audio') if len(e.last_inserted_ids()) == 0: return Response('NO | There was an error inserting a snippet') if pictureFilename: permanent_file = open(os.path.join(g.picture_file_dir, pictureFilename), 'w') shutil.copyfileobj(pictureFile.file, permanent_file) pictureFile.file.close() permanent_file.close() i = model.snippets_table.insert() e = i.execute(entry_id=e_id, content=pictureFilename, type='picture') if len(e.last_inserted_ids()) == 0: return Response('NO | There was an error inserting a snippet') return Response('OK | ' + str(from_number) + ' | ' + str(text) + ' | ' + str(audioFilename) + ' | ' + str(pictureFilename)) def bork(self): raise Exception('bork')
[ [ 1, 0, 0.0091, 0.0091, 0, 0.66, 0, 130, 0, 1, 0, 0, 130, 0, 0 ], [ 1, 0, 0.0182, 0.0091, 0, 0.66, 0.1111, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 1, 0, 0.0273, 0.0091, 0, ...
[ "from forlater.lib.base import *", "from time import *", "from sqlalchemy import *", "from paste.request import get_cookie_dict", "import os", "import shutil", "import sys", "import urllib", "import httplib", "class AController(BaseController):\n\n def index(self):\n return Response('4l8...
from forlater.lib.base import * class TemplateController(BaseController): def view(self, url): """ This is the last place which is tried during a request to try to find a file to serve. It could be used for example to display a template:: def view(self, url): return render_response(url) Or, if you're using Myghty and would like to catch the component not found error which will occur when the template doesn't exist; you can use the following version which will provide a 404 if the template doesn't exist:: import myghty.exception def view(self, url): try: return render_response('/'+url) except myghty.exception.ComponentNotFound: return Response(code=404) The default is just to abort the request with a 404 File not found status message. """ abort(404)
[ [ 1, 0, 0.0357, 0.0357, 0, 0.66, 0, 130, 0, 1, 0, 0, 130, 0, 0 ], [ 3, 0, 0.5536, 0.9286, 0, 0.66, 1, 928, 0, 1, 0, 0, 321, 0, 1 ], [ 2, 1, 0.5714, 0.8929, 1, 0.15,...
[ "from forlater.lib.base import *", "class TemplateController(BaseController):\n def view(self, url):\n \"\"\"\n This is the last place which is tried during a request to try to find a \n file to serve. It could be used for example to display a template::\n \n def view(sel...
from paste import fileapp from forlater.lib.base import * from sqlalchemy import * from forlater.lib.entry import * from time import * import os import shutil class PController(BaseController): def index(self, id): user = session.get('user', None) col = model.entries_table.c if (id == None): s = select([col.id, col.snippet_time], and_(col.phone == user, col.done == 0), order_by=[col.snippet_time]) r = s.execute() c.todo = r.fetchall() r.close() s = select([col.id, col.snippet_time], and_(col.phone == user, col.done == 1), order_by=[col.snippet_time]) r = s.execute() c.done = r.fetchall() r.close() return render_response('/p_entries.myt') else: e = None try: s = select([col.id, col.phone, col.snippet_time, col.entry_time, col.done, col.prompt_xml], and_(col.phone == user, col.id == int(id))) r = s.execute() e = r.fetchone() r.close() except: raise put_error('Sorry, there was an unknown error accessing your entry. Please try again. If the problem persists, please contact your study director.') h.redirect_to(action='index', id=None) if e: if (e['prompt_xml'] == None): xml = instantiate_prompts(e) else: xml = e['prompt_xml'] c.id = id c.ep = load_entry_prompts(xml) c.ep.id = id c.e = e col = model.snippets_table.c s = select([col.id, col.content, col.type], col.entry_id == int(id)) r = s.execute() c.s = r.fetchall() r.close() return render_response('/p_entry.myt') else: put_error('Sorry, there was an unknown error accessing your entry. Please try again. If the problem persists, please contact your study director.') h.redirect_to(action='index', id=None) return def submit(self, id): user = session.get('user', None) if (user and id): col = model.entries_table.c e = None try: s = select([col.id, col.phone, col.snippet_time, col.entry_time, col.done, col.prompt_xml], and_(col.phone == user, col.id == int(id))) r = s.execute() e = r.fetchone() r.close() except: put_error('Sorry, there was an unknown error submitting your entry. Please try again. If the problem persists, please contact your study director.') h.redirect_to(action='index', id=None) if e: try: if (e['prompt_xml'] == None): xml = instantiate_prompts(e) else: xml = e['prompt_xml'] ep = load_entry_prompts(xml) except: put_error('Sorry, there was an unknown error submitting your entry. Please try again. If the problem persists, please contact your study director.') h.redirect_to(action='index', id=None) items = request.POST.items() dirty = False for (k, v) in items: i = None try: i = int(k) except: pass if (i != None): if not dirty: # need to zero out answers in case they deleted something for q in ep.questions: if q.q_type == 'multichoice' or q.q_type == 'singlechoice': for ch in q.choices: ch.response = False q.completed = False elif q.q_type == 'openshort' or q.q_type == 'openlong': q.response = None q.completed = False dirty = True q = ep.questions[i] if q.q_type == 'multichoice' or q.q_type == 'singlechoice': v_int = None try: v_int = int(v) except: pass if (v_int != None): q.choices[v_int].response = True q.completed = True elif q.q_type == 'openshort' or q.q_type == 'openlong': response = v.strip() if (len(v) > 0): q.response = v q.completed = True if dirty: try: ep.id = id write_entry_prompts(ep,xml) now = localtime() now_mysql_string = strftime('%Y-%m-%d %H:%M:%S', now) u = model.entries_table.update(model.entries_table.c.id==id).execute( done=1, entry_time=now_mysql_string) rows = u.rowcount u.close() if rows != 1: raise Exception() except: put_error('Sorry, there was an unknown error submitting your entry. Please try again. If the problem persists, please contact your study director.') h.redirect_to(action='index', id=None) put_message('Thank you! Your entry was submitted successfully!') h.redirect_to(action='index', id=None) def create(self): user = session.get('user', None) now = localtime() now_mysql_string = strftime('%Y-%m-%d %H:%M:%S', now) try: i = model.entries_table.insert() e = i.execute(phone=user, snippet_time=now_mysql_string, done=0) e_ids = e.last_inserted_ids() e.close() if len(e_ids) == 0: raise Exception() e_id = e_ids[0] except: put_error('Unknown error creating an entry. Please try again. If the problem persists, please contact your study director.') return redirect_to('/p') return redirect_to('/p/' + str(e_id)) def picture(self, id): user = session.get('user', None) s_id = 0 try: s_id = int(id.split('.')[0]) except: abort(404) col_s = model.snippets_table.c col_e = model.entries_table.c s = select([col_s.content], and_(col_s.id == s_id, and_(col_s.entry_id == col_e.id, and_(col_e.phone == user, col_s.type == 'picture')))) r = s.execute() row = r.fetchone() r.close() if row: return self._serve_file(os.path.join(g.picture_file_dir, row[0])) abort(404) return def audio(self, id): user = session.get('user', None) s_id = 0 try: s_id = int(id.split('.')[0]) except: abort(404) col_s = model.snippets_table.c col_e = model.entries_table.c s = select([col_s.content], and_(col_s.id == s_id, and_(col_s.entry_id == col_e.id, and_(col_e.phone == user, col_s.type == 'audio')))) r = s.execute() row = r.fetchone() r.close() if row: return self._serve_file(os.path.join(g.audio_file_dir, row[0])) abort(404) return def __before__(self, action, **params): user = session.get('user', None) user_type = session.get('user_type', None) if not user or not user_type or (user_type != 'p'): put_error('You are not currently logged in.') return redirect_to(controller='login', action='index') # fill in c with everything we can c.username = user c.user_type = user_type c.msg = get_message() c.error = get_error() return
[ [ 1, 0, 0.0047, 0.0047, 0, 0.66, 0, 525, 0, 1, 0, 0, 525, 0, 0 ], [ 1, 0, 0.0094, 0.0047, 0, 0.66, 0.1429, 130, 0, 1, 0, 0, 130, 0, 0 ], [ 1, 0, 0.0141, 0.0047, 0, ...
[ "from paste import fileapp", "from forlater.lib.base import *", "from sqlalchemy import *", "from forlater.lib.entry import *", "from time import *", "import os", "import shutil", "class PController(BaseController):\n def index(self, id):\n user = session.get('user', None)\n\n col = m...
from forlater.lib.base import * from sqlalchemy import * from paste import fileapp import os import shutil class RController(BaseController): def index(self): user = session.get('user', None) c.studies = None c.recent_entries = None c.users = None try: u_t = model.users_table s_t = model.studies_table r_t = model.researchers_table e_t = model.entries_table # get data for "users" table -- we want the following SQL query: # select # users.phone, # users.password, # users.study_id, # t.completed, # t.not_completed, # t.old, # researchers.username # from # users left join # (select # entries.phone, # sum(entries.done = 1) as completed, # sum(entries.done = 0) as not_completed, # sum(entries.done = 0 and IF(entry_time is null, IF(snippet_time is null, 0, HOUR(TIMEDIFF(NOW(), entries.snippet_time)) > 24), HOUR(TIMEDIFF(NOW(), entries.entry_time)))) as old # from entries # group by entries.phone) as t # on (users.phone = t.phone) left join # studies on (users.study_id = studies.id) left join # researchers on (researchers.id = studies.researcher_id); entries_by_user = select([e_t.c.phone.label('phone'), func.sum(e_t.c.done == 1).label('completed'), func.sum(e_t.c.done == 0).label('not_completed'), func.sum(and_(e_t.c.done == 0, func.if_(e_t.c.entry_time == None, func.if_(e_t.c.snippet_time == None, 0, func.hour(func.timediff(func.now(), e_t.c.snippet_time)) > 24), func.hour(func.timediff(func.now(), e_t.c.entry_time)) > 24))).label('old')], group_by=e_t.c.phone, use_labels=True); ebu_t = entries_by_user.alias('ebu'); t = u_t.outerjoin(ebu_t, u_t.c.phone == ebu_t.c.phone).outerjoin(s_t, u_t.c.study_id == s_t.c.id).outerjoin(r_t, s_t.c.researcher_id == r_t.c.id) userinfo_table = select([u_t.c.phone.label('phone'), u_t.c.password.label('password'), u_t.c.study_id.label('study_id'), ebu_t.c.completed.label('completed'), ebu_t.c.not_completed.label('not_completed'), ebu_t.c.old.label('old')], r_t.c.username == user, from_obj=[t], use_labels=True); ui_t = userinfo_table.alias('uit'); r = userinfo_table.execute() c.users = r.fetchall() r.close() # get data for "studies" table studyinfo_table = select([ui_t.c.study_id.label('study_id'), func.count(ui_t.c.phone).label('participants'), func.sum(ui_t.c.completed).label('completed'), func.sum(ui_t.c.not_completed).label('not_completed')], from_obj=[ui_t], use_labels=True, group_by=ui_t.c.study_id); si_t = studyinfo_table.alias('sit'); sij_t = s_t.outerjoin(si_t, s_t.c.id == si_t.c.study_id).outerjoin(r_t, s_t.c.researcher_id == r_t.c.id) s = select([s_t.c.id, s_t.c.name, si_t.c.participants, si_t.c.completed, si_t.c.not_completed], r_t.c.username == user, from_obj=[sij_t]) r = s.execute() c.studies = r.fetchall() r.close() # get data for "recent entries" table s = select([e_t.c.id, e_t.c.phone, u_t.c.study_id, e_t.c.entry_time], and_(e_t.c.phone == u_t.c.phone, and_(e_t.c.done == 1, and_(u_t.c.study_id == s_t.c.id, and_(s_t.c.researcher_id == r_t.c.id, r_t.c.username == user)))), order_by=desc(e_t.c.entry_time), limit=10) r = s.execute() c.recent = r.fetchall() r.close() except: c.error = "Sorry, there was an unknown database error. Please reload this page. If the problem persists, contact the 4l8r administrator." return render_response('r_index.myt') def entry(self, entry_id=None): user = session.get('user', None) c.user_about = None c.study_about = None c.e = None new_error = None try: u_t = model.users_table s_t = model.studies_table r_t = model.researchers_table e_t = model.entries_table entry_id_int = 0 try: entry_id_int = int(entry_id) except: new_error = 'Error parsing the entry id. Please try again. If the problem persists, contact the 4l8r administrator.' raise # first, check if entry is owned by a participant owned by this person, and get study name s = select([e_t.c.phone, s_t.c.name], and_(e_t.c.id == entry_id_int, and_(e_t.c.phone == u_t.c.phone, and_(u_t.c.study_id == s_t.c.id, and_(s_t.c.researcher_id == r_t.c.id, r_t.c.username == user))))) r = s.execute() e = r.fetchone() r.close() if e: c.user_about = e['phone'] c.study_about = e['name'] else: new_error = 'Error accessing entry id ' + entry_id + '. Please try again. If the problem persists, contact the 4l8r administrator.' raise Exception() # now, retreive the entry s = e_t.select(e_t.c.id == entry_id_int) r = s.execute() e = r.fetchone() r.close() if e == None: new_error = 'Error accessing entry id ' + entry_id + '. Please try again. If the problem persists, contact the 4l8r administrator.' raise Exception() else: if (e['prompt_xml'] == None): xml = instantiate_prompts(e) else: xml = e['prompt_xml'] c.id = entry_id_int c.ep = load_entry_prompts(xml) c.ep.id = entry_id_int c.e = e col = model.snippets_table.c s = select([col.id, col.content, col.type], col.entry_id == entry_id_int) r = s.execute() c.s = r.fetchall() r.close() except: if (new_error): put_error(new_error) else: raise put_error("Sorry, there was an unknown database error. Please try again. If the problem persists, contact the 4l8r administrator.") return redirect_to(action='index', entry_id=None) return render_response('r_entry.myt') def entries(self, study_id=None, user_id=None): user = session.get('user', None) c.user_about = None c.study_about = None c.entries = None new_error = None try: u_t = model.users_table s_t = model.studies_table r_t = model.researchers_table e_t = model.entries_table study_id_int = 0 try: study_id_int = int(study_id) except: new_error = 'Error parsing the study id. Please try again. If the problem persists, contact the 4l8r administrator.' raise if user_id == '0': # render all study entries # first, check if study is owned by this person, and get study name s = select([s_t.c.name], and_(s_t.c.id == study_id_int, and_(s_t.c.researcher_id == r_t.c.id, r_t.c.username == user))) r = s.execute() e = r.fetchone() r.close() if e: c.study_about = e['name'] else: new_error = 'Error accessing entries for study id ' + study_id + '. Please try again. If the problem persists, contact the 4l8r administrator.' raise Exception() # then, get all of those study results s = select([e_t.c.id, e_t.c.phone, u_t.c.study_id, e_t.c.entry_time], and_(u_t.c.phone == e_t.c.phone, and_(e_t.c.done == 1, u_t.c.study_id == study_id_int)), order_by=desc(e_t.c.entry_time)) r = s.execute() c.complete_entries = r.fetchall() r.close() s = select([e_t.c.id, e_t.c.phone, u_t.c.study_id, e_t.c.entry_time], and_(u_t.c.phone == e_t.c.phone, and_(e_t.c.done == 0, and_(e_t.c.entry_time != None, u_t.c.study_id == study_id_int))), order_by=desc(e_t.c.entry_time)) r = s.execute() c.entries_for_followup = r.fetchall() r.close() s = select([e_t.c.id, e_t.c.phone, u_t.c.study_id, e_t.c.snippet_time], and_(u_t.c.phone == e_t.c.phone, and_(e_t.c.done == 0, and_(e_t.c.entry_time == None, u_t.c.study_id == study_id_int))), order_by=desc(e_t.c.snippet_time)) r = s.execute() c.new_entries = r.fetchall() r.close() else: # render all user's entries c.user_about = user_id # first, check if participant is owned by this person, and get study name s = select([s_t.c.name], and_(u_t.c.phone == user_id, and_(u_t.c.study_id == s_t.c.id, and_(s_t.c.researcher_id == r_t.c.id, r_t.c.username == user)))) r = s.execute() e = r.fetchone() r.close() if e: c.study_about = e['name'] else: new_error = 'Error accessing entries for user id ' + user_id + '. Please try again. If the problem persists, contact the 4l8r administrator.' raise Exception() # then, get all of those study results s = select([e_t.c.id, e_t.c.phone, u_t.c.study_id, e_t.c.entry_time], and_(u_t.c.phone == e_t.c.phone, and_(e_t.c.done == 1, u_t.c.phone == user_id)), order_by=desc(e_t.c.entry_time)) r = s.execute() c.complete_entries = r.fetchall() r.close() s = select([e_t.c.id, e_t.c.phone, u_t.c.study_id, e_t.c.entry_time], and_(u_t.c.phone == e_t.c.phone, and_(e_t.c.done == 0, and_(e_t.c.entry_time != None, u_t.c.phone == user_id))), order_by=desc(e_t.c.entry_time)) r = s.execute() c.entries_for_followup = r.fetchall() r.close() s = select([e_t.c.id, e_t.c.phone, u_t.c.study_id, e_t.c.snippet_time], and_(u_t.c.phone == e_t.c.phone, and_(e_t.c.done == 0, and_(e_t.c.entry_time == None, u_t.c.phone == user_id))), order_by=desc(e_t.c.snippet_time)) r = s.execute() c.new_entries = r.fetchall() r.close() except: if (new_error): put_error(new_error) else: raise put_error("Sorry, there was an unknown database error. Please try again. If the problem persists, contact the 4l8r administrator.") return redirect_to(action='index', user_id=None, study_id=None) return render_response('r_entries.myt') def report(self, user_id=None): return Response('<em>report</em> not implemented. args: user_id=' + str(user_id)) def addstudy(self): return Response('<em>addstudy</em> not implemented.') def changepassword(self, user_id=None): user = session.get('user', None) owns_user = False if user_id != None: try: col_s = model.studies_table.c col_r = model.researchers_table.c col_u = model.users_table.c s = select([col_u.phone], and_(and_(and_(col_u.phone == user_id, col_u.study_id == col_s.id), col_s.researcher_id == col_r.id), col_r.username == user)); r = s.execute() rows = r.fetchall() r.close() if len(rows) > 0: owns_user = True else: put_error('Invalid phone number was sent when trying to change password, please try again. If the problem persists, contact the 4l8r administrator.') except: put_error("Sorry, there was an unknown database error. Please try again. If the problem persists, contact the 4l8r administrator.") else: put_error('No phone number was sent when trying to change password, please try again. If the problem persists, contact the 4l8r administrator.') if not owns_user: return redirect_to(action='index', user_id = None) elif request.params.has_key('username') and request.params.has_key('password'): username = request.params['username'] password = request.params['password'] try: u = model.users_table.update(model.users_table.c.phone==username) r = u.execute(password=password) rows = r.rowcount r.close() if rows == 1: put_message('Successfully changed password for user ' + username) else: put_error('Database error when changing password for user ' + username + '. Please try again. If the problem persists, contact the 4l8r administrator.') except: put_error('Database error when changing password for user ' + username + '. Please try again. If the problem persists, contact the 4l8r administrator.') return redirect_to(action='index', user_id=None) else: c.change_username = user_id return render_response('r_changepassword.myt') def adduser(self): user = session.get('user', None) if request.params.has_key('username') and request.params.has_key('password') and request.params.has_key('study'): username = request.params['username'] password = request.params['password'] study = 0 try: study = int(request.params['study']) except: put_error('Invalid Study ID was sent when trying to add user, please try again. If the problem persists, contact the 4l8r administrator') return redirect_to(action='index') # first, check if current researcher owns this study owns_study = False try: col_s = model.studies_table.c col_r = model.researchers_table.c s = select([col_s.id, col_s.name], and_(and_(col_r.username == user, col_s.researcher_id == col_r.id), col_s.id == study)); r = s.execute() rows = r.fetchall() r.close() if len(rows) > 0: owns_study = True else: put_error('Invalid Study ID was sent when trying to add user, please try again. If the problem persists, contact the 4l8r administrator') except: put_error("Sorry, there was an unknown database error and the user was not added. Please try again. If the problem persists, contact the 4l8r administrator.") if owns_study: try: i = model.users_table.insert() r = i.execute(phone=username, password=password, study_id=study) if len(r.last_inserted_ids()) > 0: put_message('Successfully added user ' + username) else: put_error('Database error when adding user ' + username + '. Please try again. If the problem persists, contact the 4l8r administrator.') r.close() except: put_error('Database error when adding user ' + username + '. Please try again. If the problem persists, contact the 4l8r administrator.') return redirect_to(action='index') else: c.studies = None try: col_s = model.studies_table.c col_r = model.researchers_table.c s = select([col_s.id, col_s.name], and_(col_r.username == user, col_s.researcher_id == col_r.id)); r = s.execute() c.studies = r.fetchall() r.close() except: c.error = "Sorry, there was an unknown database error. Please reload this page. If the problem persists, contact the 4l8r administrator." return render_response('r_adduser.myt') def picture(self, id): user = session.get('user', None) s_id = 0 try: s_id = int(id.split('.')[0]) except: abort(404) c_snip = model.snippets_table.c c_e = model.entries_table.c c_s = model.studies_table.c c_u = model.users_table.c c_r = model.researchers_table.c s = select([c_snip.content], and_(c_snip.id == s_id, and_(c_snip.entry_id == c_e.id, and_(c_e.phone == c_u.phone, and_(c_u.study_id == c_s.id, and_(c_s.researcher_id == c_r.id, and_(c_r.username == user, c_snip.type == 'picture'))))))) r = s.execute() row = r.fetchone() r.close() if row: return self._serve_file(os.path.join(g.picture_file_dir, row[0])) abort(404) return def audio(self, id): user = session.get('user', None) s_id = 0 try: s_id = int(id.split('.')[0]) except: abort(404) c_snip = model.snippets_table.c c_e = model.entries_table.c c_s = model.studies_table.c c_u = model.users_table.c c_r = model.researchers_table.c s = select([c_snip.content], and_(c_snip.id == s_id, and_(c_snip.entry_id == c_e.id, and_(c_e.phone == c_u.phone, and_(c_u.study_id == c_s.id, and_(c_s.researcher_id == c_r.id, and_(c_r.username == user, c_snip.type == 'audio'))))))) r = s.execute() row = r.fetchone() r.close() if row: return self._serve_file(os.path.join(g.audio_file_dir, row[0])) abort(404) return def __before__(self, action, **params): user = session.get('user', None) user_type = session.get('user_type', None) if not user or not user_type or (user_type != 'r'): put_error('You are not currently logged in.') return redirect_to(controller='login', action='index') # fill in c with everything we can c.username = user c.user_type = user_type c.msg = get_message() c.error = get_error() return
[ [ 1, 0, 0.002, 0.002, 0, 0.66, 0, 130, 0, 1, 0, 0, 130, 0, 0 ], [ 1, 0, 0.0041, 0.002, 0, 0.66, 0.2, 835, 0, 1, 0, 0, 835, 0, 0 ], [ 1, 0, 0.0081, 0.002, 0, 0.66, ...
[ "from forlater.lib.base import *", "from sqlalchemy import *", "from paste import fileapp", "import os", "import shutil", "class RController(BaseController):\n def index(self):\n user = session.get('user', None)\n\n c.studies = None\n c.recent_entries = None\n c.users = None...
from forlater.lib.base import * from sqlalchemy import * class LoginController(BaseController): def index(self): c.msg = get_message() c.error = get_error() c.attempted_username = '' if request.params.has_key('username') and request.params.has_key('password'): c.attempted_username = request.params['username'] auth_info = authenticate(request.params['username'], request.params['password']) if (auth_info): session['user'] = auth_info['username'] session['user_type'] = auth_info['type'] session.save() if (auth_info['type'] == 'p'): h.redirect_to('/p') return elif (auth_info['type'] == 'r'): h.redirect_to('/r') return c.error = 'Username (phone number) or password not recognized.' return render_response('/login.myt') def logout(self): session.clear() session.save() h.redirect_to('/') def forgot(self): c.msg = get_message() c.error = get_error() if request.params.has_key('username'): cleaned_username = g.re_strip_non_number.sub('', request.params['username']) try: s = select([model.users_table.c.password], model.users_table.c.phone == cleaned_username) r = s.execute() row = r.fetchone() r.close() if row: if send_sms(cleaned_username, 'Your password for 4l8r is: ' + row[0]): put_message('Your password has been sent to your phone as a text message.') else: put_error = 'Unknown error sending your password. Please try again. If this problem persists, please contact your study director.' return render_response('/password_request.myt') else: # user wasn't in DB, but we don't want to let them know that, so tell them we sent it. put_message('Your password has been sent to your phone as a text message.') except: c.error = 'Unknown error accessing your account records. Please try again. If this problem persists, please contact your study director.' return render_response('/password_request.myt') h.redirect_to(action='index') return return render_response('/password_request.myt') def prefs(self): user = session.get('user', None) user_type = session.get('user_type', None) if not user or not user_type: put_error('You are not currently logged in.') return redirect_to(controller='login', action='index') c.username = user c.user_type = user_type c.msg = get_message() c.error = get_error() if request.params.has_key('oldpassword') and request.params.has_key('newpassword') and request.params.has_key('repeatpassword'): if c.user_type == 'p': table = model.users_table username_col = model.users_table.c.phone password_col = model.users_table.c.password else: table = model.researchers_table username_col = model.researchers_table.c.username password_col = model.researchers_table.c.password # first, check if old password is correct try: s = select([password_col], username_col == user) r = s.execute() row = r.fetchone() r.close() if not (row and row[0] == request.params['oldpassword']): c.error = 'Your old password was incorrect. Please try again.' return render_response('/user_prefs.myt') except: c.error = 'Unknown error accessing your account records. Please try again. If this problem persists, please contact your study director.' return render_response('/user_prefs.myt') # next, check if new passwords match each other if request.params['newpassword'] != request.params['repeatpassword']: c.error = "Your new passwords don't match. Please try again." return render_response('/user_prefs.myt') # try to store the new password try: u = table.update(username_col==user) e = u.execute(password=request.params['newpassword']) rows = e.rowcount e.close() if rows != 1: raise Exception() except: c.error = 'Unknown error changing your password. Your password was not changed, please try again. If this problem persists, please contact your study director.' return render_response('/user_prefs.myt') put_message("Password successfully changed!") if c.user_type == 'p': h.redirect_to('/p') else: h.redirect_to('/r') else: return render_response('/user_prefs.myt') def authenticate(username, password): try: # first, check if user is a participant cleaned_username = g.re_strip_non_number.sub('', username) s = select([model.users_table.c.password], model.users_table.c.phone == cleaned_username) r = s.execute() row = r.fetchone() r.close() if row and row[0] == password: return {'username' : cleaned_username, 'type' : 'p'} # next, check if user is a researcher s = select([model.researchers_table.c.password], model.researchers_table.c.username == username) r = s.execute() row = r.fetchone() r.close() if row and row[0] == password: return {'username' : username, 'type' : 'r'} return None except: return None
[ [ 1, 0, 0.0073, 0.0073, 0, 0.66, 0, 130, 0, 1, 0, 0, 130, 0, 0 ], [ 1, 0, 0.0146, 0.0073, 0, 0.66, 0.3333, 835, 0, 1, 0, 0, 835, 0, 0 ], [ 3, 0, 0.427, 0.8029, 0, 0...
[ "from forlater.lib.base import *", "from sqlalchemy import *", "class LoginController(BaseController):\n def index(self):\n c.msg = get_message()\n c.error = get_error()\n c.attempted_username = ''\n if request.params.has_key('username') and request.params.has_key('password'):\n ...
import os.path from paste import fileapp from pylons.middleware import media_path, error_document_template from pylons.util import get_prefix from forlater.lib.base import * forlater_error_template = """\ <html> <head> <title>4l8r - Server Error %(code)s</title> <style> h1 { font-family: calibri,verdana,sans-serif; font-size: 18pt; color: #990000; } h2 { font-family: calibri,verdana,sans-serif; font-size: 16pt; color: #990000; } h3 { font-family: calibri,verdana,sans-serif; font-size: 14pt; color: #990000; } p { font-family: calibri,verdana,sans-serif; font-size: 11pt; } .serif { font-family: georgia,garamond,serif; } </style> </head> <body bgcolor='#ffffff' marginwidth=0 leftmargin=0 rightmargin=0> <table width='100%%' height='56' background='/images/header_bg.gif' cellpadding=0 cellspacing=0 border=0> <tr background='/images/header_bg.gif' height=56> <td width=50 height=56 alight='left' background='/images/header_bg.gif'><img src='/images/header_bg.gif' width=50 height=56></td> <td width=96 height=56 alight='left' background='/images/header_bg.gif'><img src='/images/header.gif' width=96 height=56></td> <td width=* height=56 alight='left' background='/images/header_bg.gif'><img src='/images/header_bg.gif' width=96 height=56></td> </tr> </table> <br/> <table width='100%%' cellpadding=5> <tr><td width='1'>&nbsp;</td> <td wdith='*'> <h1>Server Error %(code)s</h1> <p>%(message)s</p> </td> <td width='1'>&nbsp;</td> </body> </html> """ class ErrorController(BaseController): """ Class to generate error documents as and when they are required. This behaviour of this class can be altered by changing the parameters to the ErrorDocuments middleware in your config/middleware.py file. """ def document(self): """ Change this method to change how error documents are displayed """ """ page = error_document_template % { 'prefix': get_prefix(request.environ), 'code': request.params.get('code', ''), 'message': request.params.get('message', ''), } """ page = forlater_error_template % { 'code': request.params.get('code', ''), 'message': request.params.get('message', ''), } return Response(page) def img(self, id): return self._serve_file(os.path.join(media_path, 'img', id)) def style(self, id): return self._serve_file(os.path.join(media_path, 'style', id)) def _serve_file(self, path): fapp = fileapp.FileApp(path) return fapp(request.environ, self.start_response)
[ [ 1, 0, 0.011, 0.011, 0, 0.66, 0, 79, 0, 1, 0, 0, 79, 0, 0 ], [ 1, 0, 0.022, 0.011, 0, 0.66, 0.1667, 525, 0, 1, 0, 0, 525, 0, 0 ], [ 1, 0, 0.033, 0.011, 0, 0.66, ...
[ "import os.path", "from paste import fileapp", "from pylons.middleware import media_path, error_document_template", "from pylons.util import get_prefix", "from forlater.lib.base import *", "forlater_error_template = \"\"\"\\\n<html>\n<head>\n<title>4l8r - Server Error %(code)s</title>\n<style>\nh1 {\n fo...
""" Setup your Routes options here """ import os from routes import Mapper def make_map(global_conf={}, app_conf={}): root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) map = Mapper(directory=os.path.join(root_path, 'controllers')) # This route handles displaying the error page and graphics used in the 404/500 # error pages. It should likely stay at the top to ensure that the error page is # displayed properly. map.connect('error/:action/:id', controller='error') # All of the participant controllers map.connect('/p/picture/:id', controller='p', action='picture') map.connect('/p/audio/:id', controller='p', action='audio') map.connect('/p/submit/:id', controller='p', action='submit') map.connect('/p/create', controller='p', action='create') map.connect('/p/:id', controller='p', action='index') # All of the researcher controllers map.connect('/r', controller='r', action='index') map.connect('/r/entry/:entry_id', controller='r', action='entry') map.connect('/r/entries/:study_id/:user_id', controller='r', action='entries') map.connect('/r/report/:user_id', controller='r', action='report') map.connect('/r/addstudy', controller='r', action='addstudy') map.connect('/r/changepassword/:user_id', controller='r', action='changepassword') map.connect('/r/adduser', controller='r', action='adduser') map.connect('/r/picture/:id', controller='r', action='picture') map.connect('/r/audio/:id', controller='r', action='audio') # All of the login and action controllers map.connect(':controller/:action/:id') # Public HTML directory map.connect('*url', controller='template', action='view') return map
[ [ 8, 0, 0.0476, 0.0714, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0952, 0.0238, 0, 0.66, 0.3333, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.119, 0.0238, 0, 0.66,...
[ "\"\"\"\nSetup your Routes options here\n\"\"\"", "import os", "from routes import Mapper", "def make_map(global_conf={}, app_conf={}):\n root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n map = Mapper(directory=os.path.join(root_path, 'controllers'))\n \n # This route han...
#
[]
[]
from paste import httpexceptions from paste.cascade import Cascade from paste.urlparser import StaticURLParser from paste.registry import RegistryManager from paste.deploy.config import ConfigMiddleware, CONFIG from paste.deploy.converters import asbool from pylons.error import error_template from pylons.middleware import ErrorHandler, ErrorDocuments, StaticJavascripts, error_mapper import pylons.wsgiapp from forlater.config.environment import load_environment import forlater.lib.helpers import forlater.lib.app_globals as app_globals def make_app(global_conf, full_stack=True, **app_conf): """Create a WSGI application and return it global_conf is a dict representing the Paste configuration options, the paste.deploy.converters should be used when parsing Paste config options to ensure they're treated properly. """ # Setup the Paste CONFIG object, adding app_conf/global_conf for legacy code conf = global_conf.copy() conf.update(app_conf) conf.update(dict(app_conf=app_conf, global_conf=global_conf)) CONFIG.push_process_config(conf) # Load our Pylons configuration defaults config = load_environment(global_conf, app_conf) config.init_app(global_conf, app_conf, package='forlater') # Load our default Pylons WSGI app and make g available app = pylons.wsgiapp.PylonsApp(config, helpers=forlater.lib.helpers, g=app_globals.Globals) g = app.globals app = ConfigMiddleware(app, conf) # YOUR MIDDLEWARE # Put your own middleware here, so that any problems are caught by the error # handling middleware underneath # If errror handling and exception catching will be handled by middleware # for multiple apps, you will want to set full_stack = False in your config # file so that it can catch the problems. if asbool(full_stack): # Change HTTPExceptions to HTTP responses app = httpexceptions.make_middleware(app, global_conf) # Error Handling app = ErrorHandler(app, global_conf, error_template=error_template, **config.errorware) # Display error documents for 401, 403, 404 status codes (if debug is disabled also # intercepts 500) app = ErrorDocuments(app, global_conf, mapper=error_mapper, **app_conf) # Establish the Registry for this application app = RegistryManager(app) static_app = StaticURLParser(config.paths['static_files']) javascripts_app = StaticJavascripts() app = Cascade([static_app, javascripts_app, app]) return app
[ [ 1, 0, 0.0156, 0.0156, 0, 0.66, 0, 525, 0, 1, 0, 0, 525, 0, 0 ], [ 1, 0, 0.0312, 0.0156, 0, 0.66, 0.0833, 164, 0, 1, 0, 0, 164, 0, 0 ], [ 1, 0, 0.0469, 0.0156, 0, ...
[ "from paste import httpexceptions", "from paste.cascade import Cascade", "from paste.urlparser import StaticURLParser", "from paste.registry import RegistryManager", "from paste.deploy.config import ConfigMiddleware, CONFIG", "from paste.deploy.converters import asbool", "from pylons.error import error_...
import os import pylons.config import webhelpers from forlater.config.routing import make_map def load_environment(global_conf={}, app_conf={}): map = make_map(global_conf, app_conf) # Setup our paths root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) paths = {'root_path': root_path, 'controllers': os.path.join(root_path, 'controllers'), 'templates': [os.path.join(root_path, path) for path in \ ('components', 'templates')], 'static_files': os.path.join(root_path, 'public') } # The following template options are passed to your template engines tmpl_options = {} tmpl_options['myghty.log_errors'] = True tmpl_options['myghty.escapes'] = dict(l=webhelpers.auto_link, s=webhelpers.simple_format) # Add your own template options config options here, note that all config options will override # any Pylons config options # Return our loaded config object return pylons.config.Config(tmpl_options, map, paths)
[ [ 1, 0, 0.0357, 0.0357, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.1071, 0.0357, 0, 0.66, 0.25, 164, 0, 1, 0, 0, 164, 0, 0 ], [ 1, 0, 0.1429, 0.0357, 0, 0....
[ "import os", "import pylons.config", "import webhelpers", "from forlater.config.routing import make_map", "def load_environment(global_conf={}, app_conf={}):\n map = make_map(global_conf, app_conf)\n # Setup our paths\n root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n pa...
""" Helper functions All names available in this module will be available under the Pylons h object. """ from webhelpers import * from pylons.helpers import log from pylons.i18n import get_lang, set_lang
[ [ 8, 0, 0.375, 0.625, 0, 0.66, 0, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.75, 0.125, 0, 0.66, 0.3333, 953, 0, 1, 0, 0, 953, 0, 0 ], [ 1, 0, 0.875, 0.125, 0, 0.66, 0...
[ "\"\"\"\nHelper functions\n\nAll names available in this module will be available under the Pylons h object.\n\"\"\"", "from webhelpers import *", "from pylons.helpers import log", "from pylons.i18n import get_lang, set_lang" ]
from pylons import Response, c, g, cache, request, session from pylons.controllers import WSGIController from pylons.decorators import jsonify, validate from pylons.templating import render, render_response from pylons.helpers import abort, redirect_to, etag_cache from pylons.i18n import N_, _, ungettext import forlater.models as model import forlater.lib.helpers as h import urllib import httplib import os import shutil from paste import fileapp from forlater.lib.entry import * from sqlalchemy import * class BaseController(WSGIController): def __call__(self, environ, start_response): # Insert any code to be run per request here. The Routes match # is under environ['pylons.routes_dict'] should you want to check # the action or route vars here return WSGIController.__call__(self, environ, start_response) def _serve_file(self, path): fapp = fileapp.FileApp(path) return fapp(request.environ, self.start_response) def get_message(): msg = session.get('msg', None) if msg: del session['msg'] session.save() return msg def put_message(msg): session['msg'] = msg session.save() def get_error(): error = session.get('error', None) if error: del session['error'] session.save() return error def put_error(error): session['error'] = error session.save() def send_sms(phone_num, text): conn = httplib.HTTPConnection(g.sms_url_server) params = urllib.urlencode([('PhoneNumber', phone_num), ('Text', text)]) url = g.sms_url_path + "?" + params print url conn.request("GET", url) r1 = conn.getresponse() status = r1.status data1 = r1.read() conn.close() return (status == httplib.OK) def load_entry_prompts(xml): return parse_entry_from_file(os.path.join(g.entry_file_dir, xml)) def write_entry_prompts(ep, xml): return write_entry_to_file(ep, os.path.join(g.entry_file_dir, xml)) def instantiate_prompts(e): # get the name of the default study prompt col_s = model.studies_table.c col_u = model.users_table.c col_e = model.entries_table.c s = select([col_s.prompt_xml], and_(col_u.phone==e['phone'], col_u.study_id == col_s.id)) r = s.execute() row = r.fetchone() r.close() if not row: return None # copy the file new_filename = row[0].split('.')[0] + "_" + e['phone'] + "_" + str(e['id']) + ".xml" source = open(os.path.join(g.entry_file_dir, row[0]), 'r') dest = open(os.path.join(g.entry_file_dir, new_filename ), 'w') shutil.copyfileobj(source, dest) source.close() dest.close() # store the name of the xml file in the database u = model.entries_table.update(col_e.id==e['id']).execute(prompt_xml=new_filename) u.close() return new_filename # Include the '_' function in the public names __all__ = [__name for __name in locals().keys() if not __name.startswith('_') \ or __name == '_']
[ [ 1, 0, 0.0098, 0.0098, 0, 0.66, 0, 113, 0, 6, 0, 0, 113, 0, 0 ], [ 1, 0, 0.0196, 0.0098, 0, 0.66, 0.0417, 571, 0, 1, 0, 0, 571, 0, 0 ], [ 1, 0, 0.0294, 0.0098, 0, ...
[ "from pylons import Response, c, g, cache, request, session", "from pylons.controllers import WSGIController", "from pylons.decorators import jsonify, validate", "from pylons.templating import render, render_response", "from pylons.helpers import abort, redirect_to, etag_cache", "from pylons.i18n import N...
header_txt = """\ <html> <head> <title>4l8r%(title)s</title> <script src="/js/prototype.js" type="text/javascript"></script> <script src="/js/scriptaculous.js" type="text/javascript"></script> <style> a:link {color: #990000} a:visited {color: #990000} a:hover {color: #CC6666} a:active {color: #CC6666} h1 { font-family: calibri,verdana,sans-serif; font-size: 18pt; color: #990000; } h2 { font-family: calibri,verdana,sans-serif; font-size: 16pt; color: #990000; } h3 { font-family: calibri,verdana,sans-serif; font-size: 14pt; color: #990000; } p,li { font-family: calibri,verdana,sans-serif; font-size: 11pt; } .small { font-size: 9pt; } .serif { font-family: georgia,garamond,serif; } .login { font-family: calibri,verdana,sans-serif; font-size: 11pt; padding: 5px; align: right; } .emph { color: #990000; } .errorbox { display: block; padding: 4px; border: 1px solid #990000; background: #FFEEEE; color: #990000; } .msgbox { display: block; padding: 4px; border: 1px solid #000000; background: #EEEEEE; color: #000000; } .shortbox { display: block; padding-left: 15px; padding-right: 15px; border: 1px solid #999999; background: #EEEEEE; color: #000000; width: 300px; } </style> </head> <body bgcolor='#ffffff' marginwidth=0 marginheight=0 leftmargin=0 rightmargin=0 topmargin=0 onload='%(onload)s'> %(acct)s <table width='100%%' height='56' background='/images/header_bg.gif' cellpadding=0 cellspacing=0 border=0> <tr background='/images/header_bg.gif' height=56> <td width=50 height=56 alight='left' background='/images/header_bg.gif'><img src='/images/header_bg.gif' width=50 height=56></td> <td width=96 height=56 alight='left' background='/images/header_bg.gif'><img src='/images/header.gif' width=96 height=56></td> <td width=* height=56 alight='left' background='/images/header_bg.gif'><img src='/images/header_bg.gif' width=96 height=56></td> </tr> </table> <table width='100%%' cellpadding=5> <tr><td width='1'>&nbsp;</td> <td wdith='*'> %(error)s%(msg)s""" footer_txt = """\ </td> <td width='1'>&nbsp;</td> </body> </html> """ def header(title=None, username=None, msg=None, error=None): onload_txt = '' if title: title_txt = ' - ' + title else: title_txt = '' if username: acct_txt = '<div class="login" align="right"><strong>' + username + '</strong>&nbsp;|&nbsp;<a href="/login/prefs">Account Preferences</a>&nbsp;|&nbsp;<a href="/login/logout">Log out</a></div>\n' else: acct_txt = '<div class="login">&nbsp;</div>\n' if error: error_txt = "<p class='errorbox' id='error_box'>Error: " + error + "</p>\n" onload_txt += 'new Effect.Highlight("error_box", {startcolor: "#FF9999", duration: 4.0});' else: error_txt = '' if msg: msg_txt = "<p class='msgbox' id='msg_box'>" + msg + "</p>\n" onload_txt += 'new Effect.Highlight("msg_box", {startcolor: "#CCFFCC", duration: 4.0});' else: msg_txt = '' return header_txt % {'title' : title_txt, 'acct' : acct_txt, 'error' : error_txt, 'msg' : msg_txt, 'onload' : onload_txt} def footer(): return footer_txt
[ [ 14, 0, 0.336, 0.664, 0, 0.66, 0, 873, 1, 0, 0, 0, 0, 3, 0 ], [ 14, 0, 0.7, 0.048, 0, 0.66, 0.3333, 326, 1, 0, 0, 0, 0, 3, 0 ], [ 2, 0, 0.856, 0.248, 0, 0.66, ...
[ "header_txt = \"\"\"\\\n<html>\n<head>\n<title>4l8r%(title)s</title>\n<script src=\"/js/prototype.js\" type=\"text/javascript\"></script>\n<script src=\"/js/scriptaculous.js\" type=\"text/javascript\"></script>\n<style>\na:link {color: #990000}", "footer_txt = \"\"\"\\\n</td>\n<td width='1'>&nbsp;</td>\n</body>\n...
from xml.dom.minidom import * class Entry: def __init__(self, id=0, questions=[]): self.id = id self.questions = questions[:] def _to_xml(self, d): e = d.createElement('entry') e.setAttribute('id', str(self.id)) for q in self.questions: e.appendChild(q._to_xml(d)) return e def _from_xml(self, e): try: self.id = int(e.getAttribute('id')) except: pass self.questions = [] qxmls = e.getElementsByTagName('question') for qxml in qxmls: new_q = Question() new_q._from_xml(qxml) self.questions.append(new_q) class Question: def __init__(self, q_type='', completed=False, prompt=None, response=None, choices=[]): self.q_type = q_type self.completed = completed self.prompt = prompt self.response = response self.choices = choices[:] def _to_xml(self, d): e = d.createElement('question') e.setAttribute('type', str(self.q_type)) e.setAttribute('completed', str(self.completed)) if self.prompt: p = d.createElement('prompt') t = d.createTextNode(str(self.prompt)) p.appendChild(t) e.appendChild(p) if self.response: r = d.createElement('response') t = d.createTextNode(str(self.response)) r.appendChild(t) e.appendChild(r) for c in self.choices: e.appendChild(c._to_xml(d)) return e def _from_xml(self, e): self.q_type = e.getAttribute('type') self.completed = _parse_bool(e.getAttribute('completed')) pxmls = e.getElementsByTagName('prompt') if len(pxmls) >= 1: self.prompt = '' for n in pxmls[0].childNodes: if n.nodeType == n.TEXT_NODE: self.prompt = self.prompt + n.nodeValue.strip() rxmls = e.getElementsByTagName('response') if len(rxmls) >= 1: self.response = '' for n in rxmls[0].childNodes: if n.nodeType == n.TEXT_NODE: self.response = self.response + n.nodeValue.strip() self.choices = [] cxmls = e.getElementsByTagName('choice') for cxml in cxmls: new_c = Choice() new_c._from_xml(cxml) self.choices.append(new_c) class Choice: def __init__(self, value='', response=False): self.value = value self.response = response def _to_xml(self, d): e = d.createElement('choice') e.setAttribute('response', str(self.response)) t = d.createTextNode(str(self.value)) e.appendChild(t) return e def _from_xml(self, e): self.response = _parse_bool(e.getAttribute('response')) self.value = '' for n in e.childNodes: if n.nodeType == n.TEXT_NODE: self.value = self.value + n.nodeValue.strip() def parse_entry_from_file(filename): f = None result = None try: f = file(filename, 'r') except: return result try: x = f.read() d = parseString(x) entries = d.getElementsByTagName('entry') if len(entries) > 0: e = Entry() e._from_xml(entries[0]) result = e except: pass if f: try: f.close() except: pass return result def write_entry_to_file(e, filename): f = None result = False try: f = file(filename, 'w') except: return result try: d = getDOMImplementation().createDocument(None, None, None) d.appendChild(e._to_xml(d)) f.write(d.toprettyxml()) result = True except: pass if f: try: f.close() except: pass return result def _parse_bool(s): if s.lower() == 'true': return True else: return False
[ [ 1, 0, 0.0068, 0.0068, 0, 0.66, 0, 770, 0, 1, 0, 0, 770, 0, 0 ], [ 3, 0, 0.0918, 0.1497, 0, 0.66, 0.1667, 197, 0, 3, 0, 0, 0, 0, 11 ], [ 2, 1, 0.034, 0.0204, 1, 0....
[ "from xml.dom.minidom import *", "class Entry:\n def __init__(self, id=0, questions=[]):\n self.id = id\n self.questions = questions[:]\n def _to_xml(self, d):\n e = d.createElement('entry')\n e.setAttribute('id', str(self.id))\n for q in self.questions:", " def __ini...
import re class Globals(object): def __init__(self, global_conf, app_conf, **extra): """ Globals acts as a container for objects available throughout the life of the application. One instance of Globals is created by Pylons during application initialization and is available during requests via the 'g' variable. ``global_conf`` The same variable used throughout ``config/middleware.py`` namely, the variables from the ``[DEFAULT]`` section of the configuration file. ``app_conf`` The same ``kw`` dictionary used throughout ``config/middleware.py`` namely, the variables from the section in the config file for your application. ``extra`` The configuration returned from ``load_config`` in ``config/middleware.py`` which may be of use in the setup of your global variables. """ self.audio_file_dir = '/4l8r/audio/' self.picture_file_dir = '/4l8r/pictures/' self.entry_file_dir = '/4l8r/entries/' self.sms_url_server = '172.27.76.138:8802' self.sms_url_path = '/Send%20Text%20Message.htm' self.upload_auth_token = 'supersecret4l8r' self.re_strip_non_number = re.compile(r'[^0-9]') self.long_datetime_format = '%A, %B %d, %Y at %I:%M %p' self.short_datetime_format = '%m/%d/%Y at %I:%M %p' def __del__(self): """ Put any cleanup code to be run when the application finally exits here. """ pass
[ [ 1, 0, 0.0208, 0.0208, 0, 0.66, 0, 540, 0, 1, 0, 0, 540, 0, 0 ], [ 3, 0, 0.5312, 0.9583, 0, 0.66, 1, 512, 0, 2, 0, 0, 186, 0, 1 ], [ 2, 1, 0.4688, 0.75, 1, 0.02, ...
[ "import re", "class Globals(object):\n\n def __init__(self, global_conf, app_conf, **extra):\n \"\"\"\n Globals acts as a container for objects available throughout\n the life of the application.\n\n One instance of Globals is created by Pylons during", " def __init__(self, glo...
from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages setup( name='Forlater', version="0.8.5", #description="", #author="", #author_email="", #url="", install_requires=["Pylons>=0.9.5"], packages=find_packages(), package_data={ 'forlater': ['i18n/*/LC_MESSAGES/*.mo'], '': ['public/*.*', 'templates/*.*', 'public/images/*.*', 'public/js/*.*'], }, include_package_data=True, test_suite = 'nose.collector', entry_points=""" [paste.app_factory] main=forlater:make_app [paste.app_install] main=pylons.util:PylonsInstaller """, )
[ [ 1, 0, 0.0385, 0.0385, 0, 0.66, 0, 650, 0, 1, 0, 0, 650, 0, 0 ], [ 8, 0, 0.0769, 0.0385, 0, 0.66, 0.3333, 479, 3, 0, 0, 0, 0, 0, 1 ], [ 1, 0, 0.1154, 0.0385, 0, 0....
[ "from ez_setup import use_setuptools", "use_setuptools()", "from setuptools import setup, find_packages", "setup(\n name='Forlater',\n version=\"0.8.5\",\n #description=\"\",\n #author=\"\",\n #author_email=\"\",\n #url=\"\",\n install_requires=[\"Pylons>=0.9.5\"]," ]
#!/usr/bin/python # Load the WSGI application from the config file from paste.deploy import loadapp wsgi_app = loadapp('config:/usr/lib/cgi-bin/4l8r/production.ini') # Deploy it using FastCGI if __name__ == '__main__': from flup.server.fcgi import WSGIServer WSGIServer(wsgi_app).run()
[ [ 1, 0, 0.4, 0.1, 0, 0.66, 0, 770, 0, 1, 0, 0, 770, 0, 0 ], [ 14, 0, 0.5, 0.1, 0, 0.66, 0.5, 696, 3, 1, 0, 0, 42, 10, 1 ], [ 4, 0, 0.9, 0.3, 0, 0.66, 1, 0, ...
[ "from paste.deploy import loadapp", "wsgi_app = loadapp('config:/usr/lib/cgi-bin/4l8r/production.ini')", "if __name__ == '__main__':\n from flup.server.fcgi import WSGIServer\n WSGIServer(wsgi_app).run()", " from flup.server.fcgi import WSGIServer", " WSGIServer(wsgi_app).run()" ]
#!/usr/bin/python # Load the WSGI application from the config file from paste.deploy import loadapp wsgi_app = loadapp('config:/usr/lib/cgi-bin/4l8r/production.ini') # Deploy it using FastCGI if __name__ == '__main__': from flup.server.fcgi import WSGIServer WSGIServer(wsgi_app).run()
[ [ 1, 0, 0.4, 0.1, 0, 0.66, 0, 770, 0, 1, 0, 0, 770, 0, 0 ], [ 14, 0, 0.5, 0.1, 0, 0.66, 0.5, 696, 3, 1, 0, 0, 42, 10, 1 ], [ 4, 0, 0.9, 0.3, 0, 0.66, 1, 0, ...
[ "from paste.deploy import loadapp", "wsgi_app = loadapp('config:/usr/lib/cgi-bin/4l8r/production.ini')", "if __name__ == '__main__':\n from flup.server.fcgi import WSGIServer\n WSGIServer(wsgi_app).run()", " from flup.server.fcgi import WSGIServer", " WSGIServer(wsgi_app).run()" ]
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # $File: plot.py # $Date: Thu Mar 13 20:23:07 2014 +0800 # $Author: jiakai <jia.kai66@gmail.com> import pyximport pyximport.install() import datafilter from sample_and_record import get_db_conn import matplotlib.pyplot as plt from matplotlib import dates import sys import os.path from datetime import datetime from collections import namedtuple from copy import deepcopy class AQSample(object): __slots__ = ['time', 'local', 'us', 'cn'] def __init__(self, time, local, us, cn): for i in self.__slots__: setattr(self, i, locals()[i]) def load_sample(): result = list() cursor = get_db_conn().cursor() for i in list(cursor.execute('SELECT * FROM history')): if i['local_conc'] > 0 and i['us_conc'] > 0 and i['cn_conc'] > 0: result.append(AQSample( i['time'], i['local_conc'], i['us_conc'], i['cn_conc'])) return result def get_time_plot(plot_ax): fig = plt.figure() ax = fig.add_subplot(111) plot_ax(ax) #ax.xaxis.set_major_locator(dates.HourLocator(interval=8)) ax.xaxis.set_major_formatter(dates.DateFormatter('%m/%d %H:%M')) ax.set_ylim(bottom=0) ax.set_ylabel(r'mass concentration/$\mu gm^{-3}$') plt.legend(loc='best') plt.xticks(rotation='vertical') plt.subplots_adjust(bottom=.3) def main(output_dir): orig = load_sample() filtered = deepcopy(orig) datafilter.rescale(filtered) datafilter.smooth_gaussian(filtered) avg = deepcopy(orig) datafilter.smooth_average(avg, 3600) avg1 = [avg[0]] for i in avg[1:]: if i.time - avg1[-1].time >= 3600: avg1.append(i) avg = avg1 time = dates.date2num([datetime.fromtimestamp(i.time) for i in orig]) def plot_local(ax): ax.plot(time, [i.local for i in filtered], label='filtered') ax.plot(time, [i.local for i in orig], label='original') def plot_compare(ax): ax.plot(time, [i.local for i in filtered], label='filtered') ax.plot(time, [i.us for i in orig], label='us') ax.plot(time, [i.cn for i in orig], label='cn') fig = plt.figure() ax = fig.add_subplot(111) ax.plot([i.local for i in avg[:-1]], [i.us for i in avg[1:]], '.') ax.set_xlabel('local') ax.set_ylabel(r'us/$\mu gm^{-3}$') plt.savefig(os.path.join(output_dir, 'scatter.png')) get_time_plot(plot_local) plt.savefig(os.path.join(output_dir, 'local.png')) get_time_plot(plot_compare) plt.savefig(os.path.join(output_dir, 'compare.png')) plt.show() if __name__ == '__main__': if len(sys.argv) != 2: sys.exit('usage: {} <output dir>'.format(sys.argv[0])) main(sys.argv[1])
[ [ 1, 0, 0.068, 0.0097, 0, 0.66, 0, 732, 0, 1, 0, 0, 732, 0, 0 ], [ 8, 0, 0.0777, 0.0097, 0, 0.66, 0.0667, 984, 3, 0, 0, 0, 0, 0, 1 ], [ 1, 0, 0.0971, 0.0097, 0, 0.6...
[ "import pyximport", "pyximport.install()", "import datafilter", "from sample_and_record import get_db_conn", "import matplotlib.pyplot as plt", "from matplotlib import dates", "import sys", "import os.path", "from datetime import datetime", "from collections import namedtuple", "from copy import...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # $File: daemon.py # $Date: Mon Mar 03 09:35:26 2014 +0800 # $Author: jiakai <jia.kai66@gmail.com> from sample_and_record import insert_db_entry import time MIN_UPTIME = 120 SAMPLE_DELTA = 300 def get_uptime(): with open('/proc/uptime') as fin: return map(float, fin.read().split())[0] if __name__ == '__main__': if get_uptime() < MIN_UPTIME: time.sleep(MIN_UPTIME) while True: insert_db_entry() time.sleep(SAMPLE_DELTA)
[ [ 1, 0, 0.2917, 0.0417, 0, 0.66, 0, 516, 0, 1, 0, 0, 516, 0, 0 ], [ 1, 0, 0.375, 0.0417, 0, 0.66, 0.2, 654, 0, 1, 0, 0, 654, 0, 0 ], [ 14, 0, 0.4583, 0.0417, 0, 0.6...
[ "from sample_and_record import insert_db_entry", "import time", "MIN_UPTIME = 120", "SAMPLE_DELTA = 300", "def get_uptime():\n with open('/proc/uptime') as fin:\n return map(float, fin.read().split())[0]", " return map(float, fin.read().split())[0]", "if __name__ == '__main__':\n if ...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # $File: dataproc.py # $Date: Tue Mar 11 00:25:03 2014 +0800 # $Author: jiakai <jia.kai66@gmail.com> import math class LinearFunction(object): k = None b = None def __init__(self, x0, y0, x1, y1): self.k = (y1 - y0) / (x1 - x0) self.b = y0 - self.k * x0 assert abs(self.eval(x0) - y0) < 1e-5 assert abs(self.eval(x1) - y1) < 1e-5 def eval(self, x): return self.k * x + self.b AQI_TABLE = [ [12.1, 51], [35.5, 101], [55.5, 151], [150.5, 201], [250.5, 301], [350.5, 401], [500, 500] ] # pcs: m^{-3} lowratio2pcs = LinearFunction(0, 0, 9.8e-2, 6000/283e-6).eval # ug/m^3 * volume _PCS2CONCENTRATION_COEFF = 1.65e6/1e-6 * math.pi*4/3*(2.5e-6/2)**3 def pcs2concentration(pcs): """ug/m^3""" return _PCS2CONCENTRATION_COEFF * pcs def concentration2aqi(con): if con < 0: return con iprev = [0, 0] for i in AQI_TABLE: if con < i[0]: return LinearFunction(iprev[0], iprev[1], i[0], i[1]).eval(con) iprev = i return con def aqi2concentration(aqi): if aqi < 0: return aqi iprev = [0, 0] for i in AQI_TABLE: if aqi < i[1]: return LinearFunction(iprev[1], iprev[0], i[1], i[0]).eval(aqi) iprev = i return aqi def lowratio2concentration(lr): return pcs2concentration(lowratio2pcs(lr)) def lowratio2aqi(lr): return concentration2aqi(lowratio2concentration(lr))
[ [ 1, 0, 0.1029, 0.0147, 0, 0.66, 0, 526, 0, 1, 0, 0, 526, 0, 0 ], [ 3, 0, 0.2132, 0.1765, 0, 0.66, 0.1111, 741, 0, 2, 0, 0, 186, 0, 4 ], [ 14, 1, 0.1471, 0.0147, 1, ...
[ "import math", "class LinearFunction(object):\n k = None\n b = None\n\n def __init__(self, x0, y0, x1, y1):\n self.k = (y1 - y0) / (x1 - x0)\n self.b = y0 - self.k * x0\n assert abs(self.eval(x0) - y0) < 1e-5", " k = None", " b = None", " def __init__(self, x0, y0, x1,...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # $File: sample_and_record.py # $Date: Wed Mar 12 23:03:06 2014 +0800 # $Author: jiakai <jia.kai66@gmail.com> from gevent import monkey monkey.patch_all() import gevent import re import json import urllib2 import subprocess import os import os.path import sqlite3 import calendar import sys from datetime import datetime from dataproc import lowratio2concentration, aqi2concentration DB_PATH = os.path.join(os.path.dirname(__file__), 'data', 'history.db') LOCAL_SAMPLE_EXE = os.path.join(os.path.dirname(__file__), 'getsample') def get_conc_aqicn(): """:return: tuple(<US data>, <Haidian data>)""" URL = 'http://aqicn.org/city/beijing' def parse_page(page): p0 = page.find('var localCityData =') p0 = page.find('{', p0) p1 = page.find(';', p0) p1 = page.rfind(']') data = page[p0:p1+1] + '}' return json.loads(data) page = urllib2.urlopen(URL).read() data = parse_page(page)['Beijing'] rst = [-1, -1] for i in data: if 'US Embassy' in i['city']: assert rst[0] == -1 rst[0] = int(i['aqi']) if 'Haidian Wanliu' in i['city']: assert rst[1] == -1 rst[1] = int(i['aqi']) return map(aqi2concentration, rst) def get_conc_bjair(): """:return: tuple(<US data>, <CN data>)""" URL = 'http://www.beijing-air.com' page = urllib2.urlopen(URL).read().decode('utf-8') data = re.split( ur'PM2.5浓度:([0-9]*)', page, re.MULTILINE) return map(int, [data[3], data[1]]) get_conc = get_conc_bjair def init_db(conn): c = conn.cursor() c.execute("""CREATE TABLE history (time INTEGER PRIMARY KEY, pm1_ratio REAL, pm25_ratio REAL, local_conc REAL, us_conc REAL, cn_conc REAL, err_msg TEXT)""") for col in 'local', 'us', 'cn': c.execute("""CREATE INDEX idx_{0}_conc ON history ({0}_conc)""".format( col)) conn.commit() def get_db_conn(): exist = os.path.exists(DB_PATH) conn = sqlite3.connect(DB_PATH) if not exist: init_db(conn) conn.row_factory = sqlite3.Row return conn def get_local_sample(): """:return: list(pm1 ratio, pm25 ratio)""" subp = subprocess.Popen(LOCAL_SAMPLE_EXE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = subp.communicate() if subp.poll() is not None: if subp.returncode: raise RuntimeError( 'failed to run local sampler: ret={}\n{}\n{}\n'.format( subp.returncode, stdout, stderr)) lines = stdout.split('\n') return map(float, lines[:2]) def insert_db_entry(): time = calendar.timegm(datetime.utcnow().timetuple()) pm1_ratio, pm25_ratio, local_conc, us_conc, cn_conc = [-1] * 5 err_msg = None job = gevent.spawn(get_conc) try: pm1_ratio, pm25_ratio = get_local_sample() local_conc = lowratio2concentration(pm1_ratio - pm25_ratio) except Exception as exc: err_msg = 'failed to sample locally: {}'.format(exc) job.join() try: if job.successful(): us_conc, cn_conc = job.value else: raise job.exception except Exception as exc: if err_msg is None: err_msg = '' err_msg = 'failed to retrieve AQI: {}'.format(exc) conn = get_db_conn() conn.cursor().execute( """INSERT INTO history VALUES (?, ?, ?, ?, ?, ?, ?)""", (time, pm1_ratio, pm25_ratio, local_conc, us_conc, cn_conc, err_msg)) conn.commit() if __name__ == '__main__': if sys.argv[1:] == ['test']: print get_conc_aqicn() print get_conc_bjair() else: insert_db_entry()
[ [ 1, 0, 0.0519, 0.0074, 0, 0.66, 0, 703, 0, 1, 0, 0, 703, 0, 0 ], [ 8, 0, 0.0593, 0.0074, 0, 0.66, 0.0435, 472, 3, 0, 0, 0, 0, 0, 1 ], [ 1, 0, 0.0741, 0.0074, 0, 0....
[ "from gevent import monkey", "monkey.patch_all()", "import gevent", "import re", "import json", "import urllib2", "import subprocess", "import os", "import os.path", "import sqlite3", "import calendar", "import sys", "from datetime import datetime", "from dataproc import lowratio2concentra...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # $File: update_db.py # $Date: Tue Mar 11 00:07:07 2014 +0800 # $Author: jiakai <jia.kai66@gmail.com> import sys sys.path.append('..') from sample_and_record import get_db_conn, init_db from dataproc import aqi2concentration, lowratio2concentration def update_db(): conn = get_db_conn() conn.cursor().execute("""ALTER TABLE history RENAME TO history00""") init_db(conn) c = conn.cursor() for i in list(c.execute('SELECT * from history00')): print i[0] c.execute( """INSERT INTO history VALUES (?, ?, ?, ?, ?, ?, ?)""", (i[0], i[1], i[2], lowratio2concentration(i[1] - i[2]), aqi2concentration(i[4]), aqi2concentration(i[5]), i[6])) conn.commit() if __name__ == '__main__': update_db()
[ [ 1, 0, 0.2121, 0.0303, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 8, 0, 0.2424, 0.0303, 0, 0.66, 0.2, 243, 3, 1, 0, 0, 0, 0, 1 ], [ 1, 0, 0.303, 0.0303, 0, 0.66, ...
[ "import sys", "sys.path.append('..')", "from sample_and_record import get_db_conn, init_db", "from dataproc import aqi2concentration, lowratio2concentration", "def update_db():\n conn = get_db_conn()\n conn.cursor().execute(\"\"\"ALTER TABLE history RENAME TO history00\"\"\")\n init_db(conn)\n\n ...
# -*- coding: utf-8 -*- from __future__ import with_statement # This isn't required in Python 2.6 __metaclass__ = type from contextlib import closing, contextmanager import os, sys, traceback import os.path from mod_python import apache, util from util import parse_qs today = date.today ver = sys.version_info if ver[0]<2 and ver[1]<5: raise EnvironmentError('Must have Python version 2.5 or higher.') try: import json except ImportError: raise EnvironmentError('Must have the json module. (It is included in Python 2.6 or can be installed on version 2.5.)') try: from PIL import Image except ImportError: raise EnvironmentError('Must have the PIL (Python Imaging Library).') path_exists = os.path.exists normalize_path = os.path.normpath absolute_path = os.path.abspath make_url = urlparse.urljoin split_path = os.path.split split_ext = os.path.splitext euncode_urlpath = urllib.quote_plus encode_json = json.JSONEcoder().encode def encodeURLsafeBase64(data): return base64.urlsafe_b64encode(data).replace('=','').replace(r'\x0A','') def image(*args): raise NotImplementedError class Filemanager: """Replacement for FCKEditor's built-in file manager.""" def __init__(self, fileroot= '/'): self.fileroot = fileroot self.patherror = encode_json( { 'Error' : 'No permission to operate on specified path.', 'Code' : -1 } ) def isvalidrequest(self, **kwargs): """Returns an error if the given path is not within the specified root path.""" assert split_path(kwargs['path'])[0]==self.fileroot assert not kwargs['req'] is None def getinfo(self, path=None, getsize=true, req=None): """Returns a JSON object containing information about the given file.""" if not self.isvalidrequest(path,req): return (self.patherror, None, 'application/json') thefile = { 'Filename' : split_path(path)[-1], 'File Type' : '', 'Preview' : path if split_path(path)[-1] else 'images/fileicons/_Open.png', 'Path' : path, 'Error' : '', 'Code' : 0, 'Properties' : { 'Date Created' : '', 'Date Modified' : '', 'Width' : '', 'Height' : '', 'Size' : '' } } imagetypes = set('gif','jpg','jpeg','png') if not path_exists(path): thefile['Error'] = 'File does not exist.' return (encode_json(thefile), None, 'application/json') if split_path(path)[-1]=='/': thefile['File Type'] = 'Directory' else: thefile['File Type'] = split_ext(path) if ext in imagetypes: img = Image(path).size() thefile['Properties']['Width'] = img[0] thefile['Properties']['Height'] = img[1] else: previewPath = 'images/fileicons/' + ext.upper + '.png' thefile['Preview'] = previewPath if path_exists('../../' + previewPath) else 'images/fileicons/default.png' thefile['Properties']['Date Created'] = os.path.getctime(path) thefile['Properties']['Date Modified'] = os.path.getmtime(path) thefile['Properties']['Size'] = os.path.getsize(path) req.content_type('application/json') req.write(encode_json(thefile)) def getfolder(self, path=None, getsizes=true, req=None): if not self.isvalidrequest(path,req): return (self.patherror, None, 'application/json') result = [] filtlist = file_listdirectory(path) for i in filelist: if i[0]=='.': result += literal(self.getinfo(path + i, getsize=getsizes)) req.content_type('application/json') req.write(encode_json(result)) def rename(self, old=None, new=None, req=None): if not self.isvalidrequest(path=new,req=req): return (self.patherror, None, 'application/json') if old[-1]=='/': old=old[:-1] oldname = split_path(path)[-1] path = string(old) path = split_path(path)[0] if not path[-1]=='/': path += '/' newname = encode_urlpath(new) newpath = path + newname os.path.rename(old, newpath) result = { 'Old Path' : old, 'Old Name' : oldname, 'New Path' : newpath, 'New Name' : newname, 'Error' : 'There was an error renaming the file.' # todo: get the actual error } req.content_type('application/json') req.write(encode_json(result)) def delete(self, path=None, req=None): if not self.isvalidrequest(path,req): return (self.patherror, None, 'application/json') os.path.remove(path) result = { 'Path' : path, 'Error' : 'There was an error renaming the file.' # todo: get the actual error } req.content_type('application/json') req.write(encode_json(result)) def add(self, path=None, req=None): if not self.isvalidrequest(path,req): return (self.patherror, None, 'application/json') try: thefile = util.FieldStorage(req)['file'] #TODO get the correct param name for the field holding the file newName = thefile.filename with open(newName, 'rb') as f: f.write(thefile.value) except: result = { 'Path' : path, 'Name' : newName, 'Error' : file_currenterror } else: result = { 'Path' : path, 'Name' : newName, 'Error' : 'No file was uploaded.' } req.content_type('text/html') req.write(('<textarea>' + encode_json(result) + '</textarea>')) def addfolder(self, path, name): if not self.isvalidrequest(path,req): return (self.patherror, None, 'application/json') newName = encode_urlpath(name) newPath = path + newName + '/' if not path_exists(newPath): try: os.mkdir(newPath) except: result = { 'Path' : path, 'Name' : newName, 'Error' : 'There was an error creating the directory.' # TODO grab the actual traceback. } def download(self, path=None, req=None): if not self.isvalidrequest(path,req): return (self.patherror, None, 'application/json') name = path.split('/')[-1] req.content_type('application/x-download') req.filename=name req.sendfile(path) myFilemanager = Filemanager(fileroot='/var/www/html/dev/fmtest/UserFiles/') #modify fileroot as a needed def handler(req): #req.content_type = 'text/plain' #req.write("Hello World!") if req.method == 'POST': kwargs = parse_qs(req.read()) elif req.method == 'GET': kwargs = parse_qs(req.args) #oldid = os.getuid() #os.setuid(501) try: method=str(kwargs['mode'][0]) methodKWargs=kwargs.remove('mode') methodKWargs['req']=req myFilemanager.__dict__['method'](**methodKWargs) return apache.OK except KeyError: return apache.HTTP_BAD_REQUEST except Exception, (errno, strerror): apache.log_error(strerror, apache.APLOG_CRIT) return apache.HTTP_INTERNAL_SERVER_ERROR #os.setuid(oldid)
[ [ 1, 0, 0.0069, 0.0035, 0, 0.66, 0, 777, 0, 1, 0, 0, 777, 0, 0 ], [ 14, 0, 0.0104, 0.0035, 0, 0.66, 0.0417, 203, 2, 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0.0208, 0.0035, 0, 0...
[ "from __future__ import with_statement # This isn't required in Python 2.6", "__metaclass__ = type", "from contextlib import closing, contextmanager", "import os, sys, traceback", "import os.path", "from mod_python import apache, util", "from util import parse_qs", "today = date.today", "ver = sys.v...
from sys import stdin x, = map(float, stdin.readline().strip().split()) print abs(x)
[ [ 1, 0, 0.3333, 0.3333, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.6667, 0.3333, 0, 0.66, 0.5, 190, 3, 2, 0, 0, 53, 10, 4 ], [ 8, 0, 1, 0.3333, 0, 0.66, ...
[ "from sys import stdin", "x, = map(float, stdin.readline().strip().split())", "print(abs(x))" ]
from sys import stdin a, b = map(int, stdin.readline().strip().split()) print b, a
[ [ 1, 0, 0.25, 0.25, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.5, 0.25, 0, 0.66, 0.5, 127, 3, 2, 0, 0, 53, 10, 4 ], [ 8, 0, 0.75, 0.25, 0, 0.66, 1, ...
[ "from sys import stdin", "a, b = map(int, stdin.readline().strip().split())", "print(b, a)" ]
from sys import stdin n, = map(int, stdin.readline().strip().split()) print n*(n+1)/2
[ [ 1, 0, 0.3333, 0.3333, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.6667, 0.3333, 0, 0.66, 0.5, 773, 3, 2, 0, 0, 53, 10, 4 ], [ 8, 0, 1, 0.3333, 0, 0.66, ...
[ "from sys import stdin", "n, = map(int, stdin.readline().strip().split())", "print(n*(n+1)/2)" ]
from sys import stdin a, b, c = map(int, stdin.readline().strip().split()) print "%.3lf" % ((a+b+c)/3.0)
[ [ 1, 0, 0.3333, 0.3333, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.6667, 0.3333, 0, 0.66, 0.5, 256, 3, 2, 0, 0, 53, 10, 4 ], [ 8, 0, 1, 0.3333, 0, 0.66, ...
[ "from sys import stdin", "a, b, c = map(int, stdin.readline().strip().split())", "print(\"%.3lf\" % ((a+b+c)/3.0))" ]
from sys import stdin n = stdin.readline().strip().split()[0] print '%c%c%c' % (n[2], n[1], n[0])
[ [ 1, 0, 0.25, 0.25, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.5, 0.25, 0, 0.66, 0.5, 773, 6, 0, 0, 0, 0, 0, 3 ], [ 8, 0, 0.75, 0.25, 0, 0.66, 1, ...
[ "from sys import stdin", "n = stdin.readline().strip().split()[0]", "print('%c%c%c' % (n[2], n[1], n[0]))" ]
from sys import stdin n, = map(int, stdin.readline().strip().split()) money = n * 95 if money >= 300: money *= 0.85 print "%.2lf" % money
[ [ 1, 0, 0.2, 0.2, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.4, 0.2, 0, 0.66, 0.25, 773, 3, 2, 0, 0, 53, 10, 4 ], [ 14, 0, 0.6, 0.2, 0, 0.66, 0.5, ...
[ "from sys import stdin", "n, = map(int, stdin.readline().strip().split())", "money = n * 95", "if money >= 300: money *= 0.85", "print(\"%.2lf\" % money)" ]
from sys import stdin from math import * x1, y1, x2, y2 = map(float, stdin.readline().strip().split()) print "%.3lf" % hypot((x1-x2), (y1-y2))
[ [ 1, 0, 0.25, 0.25, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.5, 0.25, 0, 0.66, 0.3333, 526, 0, 1, 0, 0, 526, 0, 0 ], [ 14, 0, 0.75, 0.25, 0, 0.66, 0....
[ "from sys import stdin", "from math import *", "x1, y1, x2, y2 = map(float, stdin.readline().strip().split())", "print(\"%.3lf\" % hypot((x1-x2), (y1-y2)))" ]
from sys import stdin f, = map(float, stdin.readline().strip().split()) print "%.3lf" % (5*(f-32)/9)
[ [ 1, 0, 0.3333, 0.3333, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.6667, 0.3333, 0, 0.66, 0.5, 899, 3, 2, 0, 0, 53, 10, 4 ], [ 8, 0, 1, 0.3333, 0, 0.66, ...
[ "from sys import stdin", "f, = map(float, stdin.readline().strip().split())", "print(\"%.3lf\" % (5*(f-32)/9))" ]
from sys import stdin n, m = map(int, stdin.readline().strip().split()) a = (4*n-m)/2 b = n-a if m % 2 == 1 or a < 0 or b < 0: print "No answer" else: print a, b
[ [ 1, 0, 0.2, 0.2, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.4, 0.2, 0, 0.66, 0.3333, 51, 3, 2, 0, 0, 53, 10, 4 ], [ 14, 0, 0.6, 0.2, 0, 0.66, 0.6667,...
[ "from sys import stdin", "n, m = map(int, stdin.readline().strip().split())", "a = (4*n-m)/2", "b = n-a" ]
from sys import stdin a, b, c = map(int, stdin.readline().strip().split()) if a*a + b*b == c*c or a*a + c*c == b*b or b*b + c*c == a*a: print "yes" elif a + b <= c or a + c <= b or b + c <= a: print "not a triangle" else: print "no"
[ [ 1, 0, 1, 1, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ] ]
[ "from sys import stdin" ]
from sys import stdin n, = map(int, stdin.readline().strip().split()) print ["yes", "no"][n % 2]
[ [ 1, 0, 0.3333, 0.3333, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.6667, 0.3333, 0, 0.66, 0.5, 773, 3, 2, 0, 0, 53, 10, 4 ], [ 8, 0, 1, 0.3333, 0, 0.66, ...
[ "from sys import stdin", "n, = map(int, stdin.readline().strip().split())", "print [\"yes\", \"no\"][n % 2]" ]
from sys import stdin from math import * n, = map(int, stdin.readline().strip().split()) rad = radians(n) print "%.3lf %.3lf" % (sin(rad), cos(rad))
[ [ 1, 0, 0.2, 0.2, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.4, 0.2, 0, 0.66, 0.25, 526, 0, 1, 0, 0, 526, 0, 0 ], [ 14, 0, 0.6, 0.2, 0, 0.66, 0.5, ...
[ "from sys import stdin", "from math import *", "n, = map(int, stdin.readline().strip().split())", "rad = radians(n)", "print(\"%.3lf %.3lf\" % (sin(rad), cos(rad)))" ]
from sys import stdin a = map(int, stdin.readline().strip().split()) a.sort() print a[0], a[1], a[2]
[ [ 1, 0, 0.2, 0.2, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.4, 0.2, 0, 0.66, 0.3333, 475, 3, 2, 0, 0, 53, 10, 4 ], [ 8, 0, 0.6, 0.2, 0, 0.66, 0.6667,...
[ "from sys import stdin", "a = map(int, stdin.readline().strip().split())", "a.sort()", "print(a[0], a[1], a[2])" ]
from sys import stdin from math import * r, h = map(float, stdin.readline().strip().split()) print "Area = %.3lf" % (pi*r*r*2 + 2*pi*r*h)
[ [ 1, 0, 0.25, 0.25, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.5, 0.25, 0, 0.66, 0.3333, 526, 0, 1, 0, 0, 526, 0, 0 ], [ 14, 0, 0.75, 0.25, 0, 0.66, 0....
[ "from sys import stdin", "from math import *", "r, h = map(float, stdin.readline().strip().split())", "print(\"Area = %.3lf\" % (pi*r*r*2 + 2*pi*r*h))" ]
from sys import stdin from calendar import isleap year, = map(int, stdin.readline().strip().split()) if isleap(year): print "yes" else: print "no"
[ [ 1, 0, 0.3333, 0.3333, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.6667, 0.3333, 0, 0.66, 0.5, 917, 0, 1, 0, 0, 917, 0, 0 ], [ 14, 0, 1, 0.3333, 0, 0.66, ...
[ "from sys import stdin", "from calendar import isleap", "year, = map(int, stdin.readline().strip().split())" ]
s = i = 0 while True: term = 1.0 / (i*2+1) s += term * ((-1)**i) if term < 1e-6: break i += 1 print "%.6lf" % s
[ [ 14, 0, 0.1429, 0.1429, 0, 0.66, 0, 553, 1, 0, 0, 0, 0, 1, 0 ], [ 5, 0, 0.5714, 0.7143, 0, 0.66, 0.5, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 1, 0.4286, 0.1429, 1, 0.98, ...
[ "s = i = 0", "while True:\n term = 1.0 / (i*2+1)\n s += term * ((-1)**i)\n if term < 1e-6: break\n i += 1", " term = 1.0 / (i*2+1)", " if term < 1e-6: break", "print(\"%.6lf\" % s)" ]
from sys import stdin n, m = map(int, stdin.readline().strip().split()) print "%.5lf" % sum([1.0/i/i for i in range(n,m+1)])
[ [ 1, 0, 0.3333, 0.3333, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.6667, 0.3333, 0, 0.66, 0.5, 51, 3, 2, 0, 0, 53, 10, 4 ], [ 8, 0, 1, 0.3333, 0, 0.66, ...
[ "from sys import stdin", "n, m = map(int, stdin.readline().strip().split())", "print(\"%.5lf\" % sum([1.0/i/i for i in range(n,m+1)]))" ]
from sys import stdin from decimal import * a, b, c = map(int, stdin.readline().strip().split()) getcontext().prec = c print Decimal(a) / Decimal(b)
[ [ 1, 0, 0.2, 0.2, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.4, 0.2, 0, 0.66, 0.25, 349, 0, 1, 0, 0, 349, 0, 0 ], [ 14, 0, 0.6, 0.2, 0, 0.66, 0.5, ...
[ "from sys import stdin", "from decimal import *", "a, b, c = map(int, stdin.readline().strip().split())", "getcontext().prec = c", "print(Decimal(a) / Decimal(b))" ]
from itertools import product from math import * def issqrt(n): s = int(floor(sqrt(n))) return s*s == n aabb = [a*1100+b*11 for a,b in product(range(1,10),range(10))] print ' '.join(map(str, filter(issqrt, aabb)))
[ [ 1, 0, 0.1111, 0.1111, 0, 0.66, 0, 808, 0, 1, 0, 0, 808, 0, 0 ], [ 1, 0, 0.2222, 0.1111, 0, 0.66, 0.25, 526, 0, 1, 0, 0, 526, 0, 0 ], [ 2, 0, 0.5556, 0.3333, 0, 0....
[ "from itertools import product", "from math import *", "def issqrt(n):\n s = int(floor(sqrt(n)))\n return s*s == n", " s = int(floor(sqrt(n)))", " return s*s == n", "aabb = [a*1100+b*11 for a,b in product(range(1,10),range(10))]", "print(' '.join(map(str, filter(issqrt, aabb))))" ]
from sys import stdin from math import * n = int(stdin.readline().strip()) print sum(map(factorial, range(1,n+1))) % (10**6)
[ [ 1, 0, 0.2, 0.2, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.4, 0.2, 0, 0.66, 0.3333, 526, 0, 1, 0, 0, 526, 0, 0 ], [ 14, 0, 0.6, 0.2, 0, 0.66, 0.6667,...
[ "from sys import stdin", "from math import *", "n = int(stdin.readline().strip())", "print(sum(map(factorial, range(1,n+1))) % (10**6))" ]
from sys import stdin def cycle(n): if n == 1: return 0 elif n % 2 == 1: return cycle(n*3+1) + 1 else: return cycle(n/2) + 1 n = int(stdin.readline().strip()) print cycle(n)
[ [ 1, 0, 0.1111, 0.1111, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 2, 0, 0.5, 0.4444, 0, 0.66, 0.3333, 276, 0, 1, 1, 0, 0, 0, 2 ], [ 4, 1, 0.5556, 0.3333, 1, 0.88,...
[ "from sys import stdin", "def cycle(n):\n if n == 1: return 0\n elif n % 2 == 1: return cycle(n*3+1) + 1\n else: return cycle(n/2) + 1", " if n == 1: return 0\n elif n % 2 == 1: return cycle(n*3+1) + 1\n else: return cycle(n/2) + 1", " if n == 1: return 0", " elif n % 2 == 1: return cycle(n*3+1) + 1...
for abc in range(123, 329): big = str(abc) + str(abc*2) + str(abc*3) if(''.join(sorted(big)) == '123456789'): print abc, abc*2, abc*3
[ [ 6, 0, 0.75, 1, 0, 0.66, 0, 38, 3, 0, 0, 0, 0, 0, 4 ], [ 14, 1, 1, 0.5, 1, 0.8, 0, 235, 4, 0, 0, 0, 0, 0, 3 ] ]
[ "for abc in range(123, 329):\n big = str(abc) + str(abc*2) + str(abc*3)", " big = str(abc) + str(abc*2) + str(abc*3)" ]
from sys import stdin print len(stdin.readline().strip())
[ [ 1, 0, 0.5, 0.5, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 8, 0, 1, 0.5, 0, 0.66, 1, 535, 3, 1, 0, 0, 0, 0, 4 ] ]
[ "from sys import stdin", "print(len(stdin.readline().strip()))" ]
from sys import stdin def solve(a, b, c): for i in range(10, 101): if i % 3 == a and i % 5 == b and i % 7 == c: print i return print 'No answer' a, b, c = map(int, stdin.readline().strip().split()) solve(a, b, c)
[ [ 1, 0, 0.0909, 0.0909, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 2, 0, 0.5, 0.5455, 0, 0.66, 0.3333, 599, 0, 3, 0, 0, 0, 0, 3 ], [ 6, 1, 0.5, 0.3636, 1, 0.42, ...
[ "from sys import stdin", "def solve(a, b, c):\n for i in range(10, 101):\n if i % 3 == a and i % 5 == b and i % 7 == c:\n print(i)\n return\n print('No answer')", " for i in range(10, 101):\n if i % 3 == a and i % 5 == b and i % 7 == c:\n print(i)\n return", " if i % 3 == a and...
from sys import stdin data = map(int, stdin.readline().strip().split()) n, m = data[0], data[-1] data = data[1:-1] print len(filter(lambda x: x < m, data))
[ [ 1, 0, 0.2, 0.2, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.4, 0.2, 0, 0.66, 0.25, 929, 3, 2, 0, 0, 53, 10, 4 ], [ 14, 0, 0.6, 0.2, 0, 0.66, 0.5, ...
[ "from sys import stdin", "data = map(int, stdin.readline().strip().split())", "n, m = data[0], data[-1]", "data = data[1:-1]", "print(len(filter(lambda x: x < m, data)))" ]
from sys import stdin a = map(int, stdin.readline().strip().split()) print "%d %d %.3lf" % (min(a), max(a), float(sum(a)) / len(a))
[ [ 1, 0, 0.3333, 0.3333, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.6667, 0.3333, 0, 0.66, 0.5, 475, 3, 2, 0, 0, 53, 10, 4 ], [ 8, 0, 1, 0.3333, 0, 0.66, ...
[ "from sys import stdin", "a = map(int, stdin.readline().strip().split())", "print(\"%d %d %.3lf\" % (min(a), max(a), float(sum(a)) / len(a)))" ]
from sys import stdin n = int(stdin.readline().strip()) print "%.3lf" % sum([1.0/x for x in range(1,n+1)])
[ [ 1, 0, 0.3333, 0.3333, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.6667, 0.3333, 0, 0.66, 0.5, 773, 3, 1, 0, 0, 901, 10, 3 ], [ 8, 0, 1, 0.3333, 0, 0.66, ...
[ "from sys import stdin", "n = int(stdin.readline().strip())", "print(\"%.3lf\" % sum([1.0/x for x in range(1,n+1)]))" ]
from itertools import product sol = [a*100+b*10+c for a,b,c in product(range(1,10), range(10), range(10)) if a**3+b**3+c**3 == a*100+b*10+c] print '\n'.join(map(str, sol))
[ [ 1, 0, 0.3333, 0.3333, 0, 0.66, 0, 808, 0, 1, 0, 0, 808, 0, 0 ], [ 14, 0, 0.6667, 0.3333, 0, 0.66, 0.5, 723, 5, 0, 0, 0, 0, 0, 4 ], [ 8, 0, 1, 0.3333, 0, 0.66, ...
[ "from itertools import product", "sol = [a*100+b*10+c for a,b,c in product(range(1,10), range(10), range(10)) if a**3+b**3+c**3 == a*100+b*10+c]", "print('\\n'.join(map(str, sol)))" ]
from sys import stdin n = int(stdin.readline().strip()) count = n*2-1 for i in range(n): print ' '*i + '#'*count count -= 2
[ [ 1, 0, 0.1667, 0.1667, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.3333, 0.1667, 0, 0.66, 0.3333, 773, 3, 1, 0, 0, 901, 10, 3 ], [ 14, 0, 0.5, 0.1667, 0, ...
[ "from sys import stdin", "n = int(stdin.readline().strip())", "count = n*2-1", "for i in range(n):\n print(' '*i + '#'*count)\n count -= 2", " print(' '*i + '#'*count)" ]
#! /usr/bin/env python # coding=utf-8 ############################################################################# # # # File: common.py # # # # Copyright (C) 2008-2010 Du XiaoGang <dugang.2008@gmail.com> # # # # Home: http://gappproxy.googlecode.com # # # # This file is part of GAppProxy. # # # # GAppProxy is free software: you can redistribute it and/or modify # # it under the terms of the GNU General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # GAppProxy is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with GAppProxy. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################# import os, sys def we_are_frozen(): """Returns whether we are frozen via py2exe. This will affect how we find out where we are located.""" return hasattr(sys, "frozen") def module_path(): """ This will get us the program's directory, even if we are frozen using py2exe""" if we_are_frozen(): return os.path.dirname(sys.executable) return os.path.dirname(__file__) dir = module_path() VERSION = "2.0.0" LOAD_BALANCE = 'http://gappproxy-center.appspot.com/available_fetchserver.py' GOOGLE_PROXY = 'www.google.cn:80' DEF_LISTEN_PORT = 8000 DEF_LOCAL_PROXY = '' DEF_FETCH_SERVER = '' DEF_CONF_FILE = os.path.join(dir, 'proxy.conf') DEF_CERT_FILE = os.path.join(dir, 'CA.cert') DEF_KEY_FILE = os.path.join(dir, 'CA.key') class GAppProxyError(Exception): def __init__(self, reason): self.reason = reason def __str__(self): return '<GAppProxy Error: %s>' % self.reason
[ [ 1, 0, 0.4444, 0.0159, 0, 0.66, 0, 688, 0, 2, 0, 0, 688, 0, 0 ], [ 2, 0, 0.5079, 0.0794, 0, 0.66, 0.0769, 232, 0, 0, 1, 0, 0, 0, 1 ], [ 8, 1, 0.5, 0.0317, 1, 0.26,...
[ "import os, sys", "def we_are_frozen():\n \"\"\"Returns whether we are frozen via py2exe.\n This will affect how we find out where we are located.\"\"\"\n\n return hasattr(sys, \"frozen\")", " \"\"\"Returns whether we are frozen via py2exe.\n This will affect how we find out where we are located....
#!/usr/bin/env python import sys, os # do the UNIX double-fork magic, see Stevens' "Advanced # Programming in the UNIX Environment" for details (ISBN 0201563177) try: pid = os.fork() if pid > 0: # exit first parent sys.exit(0) except OSError, e: print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror) sys.exit(1) # decouple from parent environment os.chdir("/") os.setsid() os.umask(0) # do second fork try: pid = os.fork() if pid > 0: sys.exit(0) except OSError, e: print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror) sys.exit(1) pid = str(os.getpid()) f = open('/data/data/org.gaeproxy/python.pid','a') f.write(" ") f.write(pid) f.close() dir = os.path.abspath(os.path.dirname(sys.argv[0])) sys.path.append(os.path.join(dir, 'src.zip')) del sys, os, dir import ProxyServer ProxyServer.main()
[ [ 1, 0, 0.3333, 0.3333, 0, 0.66, 0, 509, 0, 2, 0, 0, 509, 0, 0 ], [ 1, 0, 1, 0.3333, 0, 0.66, 1, 644, 0, 1, 0, 0, 644, 0, 0 ] ]
[ "import sys, os", "import ProxyServer" ]
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import wsgiref.handlers import os from google.appengine.ext import webapp from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext import db from google.appengine.ext.webapp import template from google.appengine.api import urlfetch class Category(db.Model): cid = db.IntegerProperty() name = db.StringProperty() class Books(db.Model): name = db.StringProperty() descrption = db.TextProperty() date = db.DateTimeProperty(auto_now_add=True) tags = db.ListProperty(db.Key) category = db.IntegerProperty() visits = db.IntegerProperty() download = db.LinkProperty() class Comments(db.Model): book = db.ReferenceProperty(Books,collection_name='comments') author = db.UserProperty() content = db.StringProperty(multiline=True) date = db.DateTimeProperty(auto_now_add=True) class Tags(db.Model): tag = db.StringProperty() @property def entrys(self): return Entry.gql("where tags = :1" ,self.key()) class SingleBlogHandler(webapp.RequestHandler): def get(self): query = db.Query(Entry) query.filter('') class BookHandler(webapp.RequestHandler): def get(self): entries = Books.all().order('-date').fetch(limit=5) tags = {} for entry in entries: entry.fetched_tags = [] for tag_key in entry.tags: if not tag_key in tags: tags[tag_key] = Tags.get(tag_key) entry.fetched_tags.append(tags[tag_key]) if users.get_current_user(): url = users.create_logout_url(self.request.uri) url_linktext = 'Logout' else: url = users.create_login_url(self.request.uri) url_linktext = 'Login' template_values = { 'entries' : entries, 'url' : url, 'url_linktext' : url_linktext, } path = os.path.join(os.path.dirname(__file__), 'book.html') self.response.out.write(template.render(path, template_values)) class AddBookPage(webapp.RequestHandler): def get(self): template_values = { } path = os.path.join(os.path.dirname(__file__), 'addbook.html') self.response.out.write(template.render(path,template_values)) class AddBookHandler(webapp.RequestHandler): def post(self): entry = Books() entry.name = self.request.get('name') entry.description = self.request.get('description') entry.download = self.request.get('download') tag_string = self.request.get('tags') for tag_str in tag_string.split(','): tag = Tags() tag.tag = tag_str tag.put() if tag.key() not in entry.tags: entry.tags.append(tag.key()) entry.put() self.redirect('/') def main(): application = webapp.WSGIApplication([('/',BookHandler), ('/write',AddBookPage), ('/add',AddBookHandler), ],debug=True) wsgiref.handlers.CGIHandler().run(application) if __name__ == '__main__': main()
[ [ 1, 0, 0.1654, 0.0079, 0, 0.66, 0, 709, 0, 1, 0, 0, 709, 0, 0 ], [ 1, 0, 0.1732, 0.0079, 0, 0.66, 0.0625, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.189, 0.0079, 0, 0...
[ "import wsgiref.handlers", "import os", "from google.appengine.ext import webapp", "from google.appengine.ext import webapp", "from google.appengine.api import users", "from google.appengine.ext import db", "from google.appengine.ext.webapp import template", "from google.appengine.api import urlfetch"...
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import wsgiref.handlers import os from google.appengine.ext import webapp from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext import db from google.appengine.ext.webapp import template from google.appengine.api import urlfetch class Category(db.Model): cid = db.IntegerProperty() name = db.StringProperty() class Books(db.Model): name = db.StringProperty() descrption = db.TextProperty() date = db.DateTimeProperty(auto_now_add=True) tags = db.ListProperty(db.Key) category = db.IntegerProperty() visits = db.IntegerProperty() download = db.LinkProperty() class Comments(db.Model): book = db.ReferenceProperty(Books,collection_name='comments') author = db.UserProperty() content = db.StringProperty(multiline=True) date = db.DateTimeProperty(auto_now_add=True) class Tags(db.Model): tag = db.StringProperty() @property def entrys(self): return Entry.gql("where tags = :1" ,self.key()) class SingleBlogHandler(webapp.RequestHandler): def get(self): query = db.Query(Entry) query.filter('') class BookHandler(webapp.RequestHandler): def get(self): entries = Books.all().order('-date').fetch(limit=5) tags = {} for entry in entries: entry.fetched_tags = [] for tag_key in entry.tags: if not tag_key in tags: tags[tag_key] = Tags.get(tag_key) entry.fetched_tags.append(tags[tag_key]) if users.get_current_user(): url = users.create_logout_url(self.request.uri) url_linktext = 'Logout' else: url = users.create_login_url(self.request.uri) url_linktext = 'Login' template_values = { 'entries' : entries, 'url' : url, 'url_linktext' : url_linktext, } path = os.path.join(os.path.dirname(__file__), 'book.html') self.response.out.write(template.render(path, template_values)) class AddBookPage(webapp.RequestHandler): def get(self): template_values = { } path = os.path.join(os.path.dirname(__file__), 'addbook.html') self.response.out.write(template.render(path,template_values)) class AddBookHandler(webapp.RequestHandler): def post(self): entry = Books() entry.name = self.request.get('name') entry.description = self.request.get('description') entry.download = self.request.get('download') tag_string = self.request.get('tags') for tag_str in tag_string.split(','): tag = Tags() tag.tag = tag_str tag.put() if tag.key() not in entry.tags: entry.tags.append(tag.key()) entry.put() self.redirect('/') def main(): application = webapp.WSGIApplication([('/',BookHandler), ('/write',AddBookPage), ('/add',AddBookHandler), ],debug=True) wsgiref.handlers.CGIHandler().run(application) if __name__ == '__main__': main()
[ [ 1, 0, 0.1654, 0.0079, 0, 0.66, 0, 709, 0, 1, 0, 0, 709, 0, 0 ], [ 1, 0, 0.1732, 0.0079, 0, 0.66, 0.0625, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.189, 0.0079, 0, 0...
[ "import wsgiref.handlers", "import os", "from google.appengine.ext import webapp", "from google.appengine.ext import webapp", "from google.appengine.api import users", "from google.appengine.ext import db", "from google.appengine.ext.webapp import template", "from google.appengine.api import urlfetch"...
import xmlrpclib from SimpleXMLRPCServer import SimpleXMLRPCServer def debug(message): print "[Debug] " + message return "OK" def info(message): print "[Infor] " + message server = SimpleXMLRPCServer(("localhost",8888)) print "Listening on port 8888" server.register_function(debug,"debug") server.serve_forever()
[ [ 1, 0, 0.0833, 0.0833, 0, 0.66, 0, 251, 0, 1, 0, 0, 251, 0, 0 ], [ 1, 0, 0.1667, 0.0833, 0, 0.66, 0.1429, 73, 0, 1, 0, 0, 73, 0, 0 ], [ 2, 0, 0.4167, 0.25, 0, 0.66...
[ "import xmlrpclib", "from SimpleXMLRPCServer import SimpleXMLRPCServer", "def debug(message):\n print(\"[Debug] \" + message)\n return \"OK\"", " print(\"[Debug] \" + message)", " return \"OK\"", "def info(message):\n print(\"[Infor] \" + message)", " print(\"[Infor] \" + message)", ...
import os import sys sys.path.append('/var/www/python/application') os.environ['PYTHON_EGG_CACHE'] = '/var/www/python/application/.python-egg' def application(environ, start_response): status = '200 OK' output = 'path /var/www/python/application' response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(output)))] start_response(status, response_headers) return [output]
[ [ 1, 0, 0.0625, 0.0625, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.125, 0.0625, 0, 0.66, 0.25, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 8, 0, 0.25, 0.0625, 0, 0.66,...
[ "import os", "import sys", "sys.path.append('/var/www/python/application')", "os.environ['PYTHON_EGG_CACHE'] = '/var/www/python/application/.python-egg'", "def application(environ, start_response):\n status = '200 OK'\n output = 'path /var/www/python/application'\n\n response_headers = [('Content-t...
s = i = 0 while True: term = 1.0 / (i*2+1) s += term * ((-1)**i) if term < 1e-6: break i += 1 print "%.6lf" % s
[ [ 14, 0, 0.1429, 0.1429, 0, 0.66, 0, 553, 1, 0, 0, 0, 0, 1, 0 ], [ 5, 0, 0.5714, 0.7143, 0, 0.66, 0.5, 0, 1, 0, 0, 0, 0, 0, 0 ], [ 14, 1, 0.4286, 0.1429, 1, 0.07, ...
[ "s = i = 0", "while True:\n term = 1.0 / (i*2+1)\n s += term * ((-1)**i)\n if term < 1e-6: break\n i += 1", " term = 1.0 / (i*2+1)", " if term < 1e-6: break", "print(\"%.6lf\" % s)" ]
from sys import stdin a = map(int, stdin.readline().strip().split()) print "%d %d %.3lf" % (min(a), max(a), float(sum(a)) / len(a))
[ [ 1, 0, 0.3333, 0.3333, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.6667, 0.3333, 0, 0.66, 0.5, 475, 3, 2, 0, 0, 53, 10, 4 ], [ 8, 0, 1, 0.3333, 0, 0.66, ...
[ "from sys import stdin", "a = map(int, stdin.readline().strip().split())", "print(\"%d %d %.3lf\" % (min(a), max(a), float(sum(a)) / len(a)))" ]
from sys import stdin from math import * n = int(stdin.readline().strip()) print sum(map(factorial, range(1,n+1))) % (10**6)
[ [ 1, 0, 0.2, 0.2, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.4, 0.2, 0, 0.66, 0.3333, 526, 0, 1, 0, 0, 526, 0, 0 ], [ 14, 0, 0.6, 0.2, 0, 0.66, 0.6667,...
[ "from sys import stdin", "from math import *", "n = int(stdin.readline().strip())", "print(sum(map(factorial, range(1,n+1))) % (10**6))" ]
from sys import stdin def solve(a, b, c): for i in range(10, 101): if i % 3 == a and i % 5 == b and i % 7 == c: print i return print 'No answer' a, b, c = map(int, stdin.readline().strip().split()) solve(a, b, c)
[ [ 1, 0, 0.0909, 0.0909, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 2, 0, 0.5, 0.5455, 0, 0.66, 0.3333, 599, 0, 3, 0, 0, 0, 0, 3 ], [ 6, 1, 0.5, 0.3636, 1, 0.94, ...
[ "from sys import stdin", "def solve(a, b, c):\n for i in range(10, 101):\n if i % 3 == a and i % 5 == b and i % 7 == c:\n print(i)\n return\n print('No answer')", " for i in range(10, 101):\n if i % 3 == a and i % 5 == b and i % 7 == c:\n print(i)\n return", " if i % 3 == a and...
from itertools import product sol = [a*100+b*10+c for a,b,c in product(range(1,10), range(10), range(10)) if a**3+b**3+c**3 == a*100+b*10+c] print '\n'.join(map(str, sol))
[ [ 1, 0, 0.3333, 0.3333, 0, 0.66, 0, 808, 0, 1, 0, 0, 808, 0, 0 ], [ 14, 0, 0.6667, 0.3333, 0, 0.66, 0.5, 723, 5, 0, 0, 0, 0, 0, 4 ], [ 8, 0, 1, 0.3333, 0, 0.66, ...
[ "from itertools import product", "sol = [a*100+b*10+c for a,b,c in product(range(1,10), range(10), range(10)) if a**3+b**3+c**3 == a*100+b*10+c]", "print('\\n'.join(map(str, sol)))" ]
from sys import stdin n = int(stdin.readline().strip()) count = n*2-1 for i in range(n): print ' '*i + '#'*count count -= 2
[ [ 1, 0, 0.1667, 0.1667, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.3333, 0.1667, 0, 0.66, 0.3333, 773, 3, 1, 0, 0, 901, 10, 3 ], [ 14, 0, 0.5, 0.1667, 0, ...
[ "from sys import stdin", "n = int(stdin.readline().strip())", "count = n*2-1", "for i in range(n):\n print(' '*i + '#'*count)\n count -= 2", " print(' '*i + '#'*count)" ]
from sys import stdin n, m = map(int, stdin.readline().strip().split()) print "%.5lf" % sum([1.0/i/i for i in range(n,m+1)])
[ [ 1, 0, 0.3333, 0.3333, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.6667, 0.3333, 0, 0.66, 0.5, 51, 3, 2, 0, 0, 53, 10, 4 ], [ 8, 0, 1, 0.3333, 0, 0.66, ...
[ "from sys import stdin", "n, m = map(int, stdin.readline().strip().split())", "print(\"%.5lf\" % sum([1.0/i/i for i in range(n,m+1)]))" ]
from sys import stdin print len(stdin.readline().strip())
[ [ 1, 0, 0.5, 0.5, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 8, 0, 1, 0.5, 0, 0.66, 1, 535, 3, 1, 0, 0, 0, 0, 4 ] ]
[ "from sys import stdin", "print(len(stdin.readline().strip()))" ]
from sys import stdin from decimal import * a, b, c = map(int, stdin.readline().strip().split()) getcontext().prec = c print Decimal(a) / Decimal(b)
[ [ 1, 0, 0.2, 0.2, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.4, 0.2, 0, 0.66, 0.25, 349, 0, 1, 0, 0, 349, 0, 0 ], [ 14, 0, 0.6, 0.2, 0, 0.66, 0.5, ...
[ "from sys import stdin", "from decimal import *", "a, b, c = map(int, stdin.readline().strip().split())", "getcontext().prec = c", "print(Decimal(a) / Decimal(b))" ]
from itertools import product from math import * def issqrt(n): s = int(floor(sqrt(n))) return s*s == n aabb = [a*1100+b*11 for a,b in product(range(1,10),range(10))] print ' '.join(map(str, filter(issqrt, aabb)))
[ [ 1, 0, 0.1111, 0.1111, 0, 0.66, 0, 808, 0, 1, 0, 0, 808, 0, 0 ], [ 1, 0, 0.2222, 0.1111, 0, 0.66, 0.25, 526, 0, 1, 0, 0, 526, 0, 0 ], [ 2, 0, 0.5556, 0.3333, 0, 0....
[ "from itertools import product", "from math import *", "def issqrt(n):\n s = int(floor(sqrt(n)))\n return s*s == n", " s = int(floor(sqrt(n)))", " return s*s == n", "aabb = [a*1100+b*11 for a,b in product(range(1,10),range(10))]", "print(' '.join(map(str, filter(issqrt, aabb))))" ]
from sys import stdin data = map(int, stdin.readline().strip().split()) n, m = data[0], data[-1] data = data[1:-1] print len(filter(lambda x: x < m, data))
[ [ 1, 0, 0.2, 0.2, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.4, 0.2, 0, 0.66, 0.25, 929, 3, 2, 0, 0, 53, 10, 4 ], [ 14, 0, 0.6, 0.2, 0, 0.66, 0.5, ...
[ "from sys import stdin", "data = map(int, stdin.readline().strip().split())", "n, m = data[0], data[-1]", "data = data[1:-1]", "print(len(filter(lambda x: x < m, data)))" ]
for abc in range(123, 329): big = str(abc) + str(abc*2) + str(abc*3) if(''.join(sorted(big)) == '123456789'): print abc, abc*2, abc*3
[ [ 6, 0, 0.75, 1, 0, 0.66, 0, 38, 3, 0, 0, 0, 0, 0, 4 ], [ 14, 1, 1, 0.5, 1, 0.56, 0, 235, 4, 0, 0, 0, 0, 0, 3 ] ]
[ "for abc in range(123, 329):\n big = str(abc) + str(abc*2) + str(abc*3)", " big = str(abc) + str(abc*2) + str(abc*3)" ]
from sys import stdin n = int(stdin.readline().strip()) print "%.3lf" % sum([1.0/x for x in range(1,n+1)])
[ [ 1, 0, 0.3333, 0.3333, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.6667, 0.3333, 0, 0.66, 0.5, 773, 3, 1, 0, 0, 901, 10, 3 ], [ 8, 0, 1, 0.3333, 0, 0.66, ...
[ "from sys import stdin", "n = int(stdin.readline().strip())", "print(\"%.3lf\" % sum([1.0/x for x in range(1,n+1)]))" ]
from sys import stdin def cycle(n): if n == 1: return 0 elif n % 2 == 1: return cycle(n*3+1) + 1 else: return cycle(n/2) + 1 n = int(stdin.readline().strip()) print cycle(n)
[ [ 1, 0, 0.1111, 0.1111, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 2, 0, 0.5, 0.4444, 0, 0.66, 0.3333, 276, 0, 1, 1, 0, 0, 0, 2 ], [ 4, 1, 0.5556, 0.3333, 1, 0.44,...
[ "from sys import stdin", "def cycle(n):\n if n == 1: return 0\n elif n % 2 == 1: return cycle(n*3+1) + 1\n else: return cycle(n/2) + 1", " if n == 1: return 0\n elif n % 2 == 1: return cycle(n*3+1) + 1\n else: return cycle(n/2) + 1", " if n == 1: return 0", " elif n % 2 == 1: return cycle(n*3+1) + 1...
from sys import stdin n, = map(int, stdin.readline().strip().split()) money = n * 95 if money >= 300: money *= 0.85 print "%.2lf" % money
[ [ 1, 0, 0.2, 0.2, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.4, 0.2, 0, 0.66, 0.25, 773, 3, 2, 0, 0, 53, 10, 4 ], [ 14, 0, 0.6, 0.2, 0, 0.66, 0.5, ...
[ "from sys import stdin", "n, = map(int, stdin.readline().strip().split())", "money = n * 95", "if money >= 300: money *= 0.85", "print(\"%.2lf\" % money)" ]
from sys import stdin from math import * x1, y1, x2, y2 = map(float, stdin.readline().strip().split()) print "%.3lf" % hypot((x1-x2), (y1-y2))
[ [ 1, 0, 0.25, 0.25, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.5, 0.25, 0, 0.66, 0.3333, 526, 0, 1, 0, 0, 526, 0, 0 ], [ 14, 0, 0.75, 0.25, 0, 0.66, 0....
[ "from sys import stdin", "from math import *", "x1, y1, x2, y2 = map(float, stdin.readline().strip().split())", "print(\"%.3lf\" % hypot((x1-x2), (y1-y2)))" ]
from sys import stdin n, = map(int, stdin.readline().strip().split()) print ["yes", "no"][n % 2]
[ [ 1, 0, 0.3333, 0.3333, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.6667, 0.3333, 0, 0.66, 0.5, 773, 3, 2, 0, 0, 53, 10, 4 ], [ 8, 0, 1, 0.3333, 0, 0.66, ...
[ "from sys import stdin", "n, = map(int, stdin.readline().strip().split())", "print [\"yes\", \"no\"][n % 2]" ]
from sys import stdin n, m = map(int, stdin.readline().strip().split()) a = (4*n-m)/2 b = n-a if m % 2 == 1 or a < 0 or b < 0: print "No answer" else: print a, b
[ [ 1, 0, 0.2, 0.2, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.4, 0.2, 0, 0.66, 0.3333, 51, 3, 2, 0, 0, 53, 10, 4 ], [ 14, 0, 0.6, 0.2, 0, 0.66, 0.6667,...
[ "from sys import stdin", "n, m = map(int, stdin.readline().strip().split())", "a = (4*n-m)/2", "b = n-a" ]
from sys import stdin from math import * n, = map(int, stdin.readline().strip().split()) rad = radians(n) print "%.3lf %.3lf" % (sin(rad), cos(rad))
[ [ 1, 0, 0.2, 0.2, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.4, 0.2, 0, 0.66, 0.25, 526, 0, 1, 0, 0, 526, 0, 0 ], [ 14, 0, 0.6, 0.2, 0, 0.66, 0.5, ...
[ "from sys import stdin", "from math import *", "n, = map(int, stdin.readline().strip().split())", "rad = radians(n)", "print(\"%.3lf %.3lf\" % (sin(rad), cos(rad)))" ]
from sys import stdin from calendar import isleap year, = map(int, stdin.readline().strip().split()) if isleap(year): print "yes" else: print "no"
[ [ 1, 0, 0.3333, 0.3333, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.6667, 0.3333, 0, 0.66, 0.5, 917, 0, 1, 0, 0, 917, 0, 0 ], [ 14, 0, 1, 0.3333, 0, 0.66, ...
[ "from sys import stdin", "from calendar import isleap", "year, = map(int, stdin.readline().strip().split())" ]
from sys import stdin a, b = map(int, stdin.readline().strip().split()) print b, a
[ [ 1, 0, 0.25, 0.25, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.5, 0.25, 0, 0.66, 0.5, 127, 3, 2, 0, 0, 53, 10, 4 ], [ 8, 0, 0.75, 0.25, 0, 0.66, 1, ...
[ "from sys import stdin", "a, b = map(int, stdin.readline().strip().split())", "print(b, a)" ]
from sys import stdin f, = map(float, stdin.readline().strip().split()) print "%.3lf" % (5*(f-32)/9)
[ [ 1, 0, 0.3333, 0.3333, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.6667, 0.3333, 0, 0.66, 0.5, 899, 3, 2, 0, 0, 53, 10, 4 ], [ 8, 0, 1, 0.3333, 0, 0.66, ...
[ "from sys import stdin", "f, = map(float, stdin.readline().strip().split())", "print(\"%.3lf\" % (5*(f-32)/9))" ]
from sys import stdin a, b, c = map(int, stdin.readline().strip().split()) if a*a + b*b == c*c or a*a + c*c == b*b or b*b + c*c == a*a: print "yes" elif a + b <= c or a + c <= b or b + c <= a: print "not a triangle" else: print "no"
[ [ 1, 0, 1, 1, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ] ]
[ "from sys import stdin" ]
from sys import stdin a = map(int, stdin.readline().strip().split()) a.sort() print a[0], a[1], a[2]
[ [ 1, 0, 0.2, 0.2, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.4, 0.2, 0, 0.66, 0.3333, 475, 3, 2, 0, 0, 53, 10, 4 ], [ 8, 0, 0.6, 0.2, 0, 0.66, 0.6667,...
[ "from sys import stdin", "a = map(int, stdin.readline().strip().split())", "a.sort()", "print(a[0], a[1], a[2])" ]
from sys import stdin n, = map(int, stdin.readline().strip().split()) print n*(n+1)/2
[ [ 1, 0, 0.3333, 0.3333, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.6667, 0.3333, 0, 0.66, 0.5, 773, 3, 2, 0, 0, 53, 10, 4 ], [ 8, 0, 1, 0.3333, 0, 0.66, ...
[ "from sys import stdin", "n, = map(int, stdin.readline().strip().split())", "print(n*(n+1)/2)" ]
from sys import stdin x, = map(float, stdin.readline().strip().split()) print abs(x)
[ [ 1, 0, 0.3333, 0.3333, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.6667, 0.3333, 0, 0.66, 0.5, 190, 3, 2, 0, 0, 53, 10, 4 ], [ 8, 0, 1, 0.3333, 0, 0.66, ...
[ "from sys import stdin", "x, = map(float, stdin.readline().strip().split())", "print(abs(x))" ]
from sys import stdin a, b, c = map(int, stdin.readline().strip().split()) print "%.3lf" % ((a+b+c)/3.0)
[ [ 1, 0, 0.3333, 0.3333, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.6667, 0.3333, 0, 0.66, 0.5, 256, 3, 2, 0, 0, 53, 10, 4 ], [ 8, 0, 1, 0.3333, 0, 0.66, ...
[ "from sys import stdin", "a, b, c = map(int, stdin.readline().strip().split())", "print(\"%.3lf\" % ((a+b+c)/3.0))" ]
from sys import stdin from math import * r, h = map(float, stdin.readline().strip().split()) print "Area = %.3lf" % (pi*r*r*2 + 2*pi*r*h)
[ [ 1, 0, 0.25, 0.25, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 1, 0, 0.5, 0.25, 0, 0.66, 0.3333, 526, 0, 1, 0, 0, 526, 0, 0 ], [ 14, 0, 0.75, 0.25, 0, 0.66, 0....
[ "from sys import stdin", "from math import *", "r, h = map(float, stdin.readline().strip().split())", "print(\"Area = %.3lf\" % (pi*r*r*2 + 2*pi*r*h))" ]
from sys import stdin n = stdin.readline().strip().split()[0] print '%c%c%c' % (n[2], n[1], n[0])
[ [ 1, 0, 0.25, 0.25, 0, 0.66, 0, 509, 0, 1, 0, 0, 509, 0, 0 ], [ 14, 0, 0.5, 0.25, 0, 0.66, 0.5, 773, 6, 0, 0, 0, 0, 0, 3 ], [ 8, 0, 0.75, 0.25, 0, 0.66, 1, ...
[ "from sys import stdin", "n = stdin.readline().strip().split()[0]", "print('%c%c%c' % (n[2], n[1], n[0]))" ]
#!/usr/bin/env python # vim: set filetype=python expandtab tabstop=2 shiftwidth=2 autoindent smartindent: # -*- coding: utf-8 -*- # from google.appengine.ext import db from google.appengine.api import users class Categories(db.Expando): """ categories of different places data model """ name = db.StringProperty(required=True) subname = db.StringProperty(required=True) description = db.StringProperty(required=True, multiline=True) class Place(db.Expando): """ a single place """ name = db.StringProperty(required=True) category = db.ReferenceProperty(Categories) #latitude = db.StringProperty(required=True) #longitude = db.StringProperty(required=True) place = db.GeoPtProperty(required=True) description = db.StringProperty(required=True, multiline=True) class Event(db.Expando): """ event happens in a place during particular time """ name = db.StringProperty(required=True) place = db.ReferenceProperty(Place) startdate = db.DateTimeProperty(required=True) stopdate = db.DateTimeProperty(required=True) description = db.StringProperty(required=True, multiline=True) def main(): c = Categories(key_name='hotel', name=u'宾馆', subname=u'五星级宾馆', description=u'价格最低500起') c.put() p = Place(key_name='dachong', name=u'大冲宾馆', category=c, place="22, 114", description=u'公司对面') p.put() e = Event(key_name='chistmas', name=u'圣诞打折', place=p, startdate=datetime.datetime(2007, 8, 20, 10, 10), stopdate=datetime.datetime(2007, 9, 20, 10, 10), description=u'圣诞旅游打折') e.put() if __name__ == '__main__': main()
[ [ 1, 0, 0.1064, 0.0213, 0, 0.66, 0, 167, 0, 1, 0, 0, 167, 0, 0 ], [ 1, 0, 0.1277, 0.0213, 0, 0.66, 0.1667, 279, 0, 1, 0, 0, 279, 0, 0 ], [ 3, 0, 0.2447, 0.1277, 0, ...
[ "from google.appengine.ext import db", "from google.appengine.api import users", "class Categories(db.Expando):\n \"\"\" categories of different places data model \"\"\"\n \n name = db.StringProperty(required=True)\n subname = db.StringProperty(required=True)\n description = db.StringProperty(required=T...
print 'Content-Type: text/plain' print '' print 'Hello, world!'
[ [ 8, 0, 0.25, 0.25, 0, 0.66, 0, 535, 3, 1, 0, 0, 0, 0, 1 ], [ 8, 0, 0.5, 0.25, 0, 0.66, 0.5, 535, 3, 1, 0, 0, 0, 0, 1 ], [ 8, 0, 0.75, 0.25, 0, 0.66, 1, 535...
[ "print('Content-Type: text/plain')", "print('')", "print('Hello, world!')" ]
#!/usr/bin/env python # vim: set filetype=python expandtab tabstop=2 shiftwidth=2 autoindent smartindent: # -*- coding: utf-8 -*- # from google.appengine.ext import webapp import os # test print envs class PrintEnvironment(webapp.RequestHandler): def get(self): for name in os.environ.keys(): self.response.out.write("%s = %s<br />\n" % (name, os.environ[name]))
[ [ 1, 0, 0.4, 0.0667, 0, 0.66, 0, 167, 0, 1, 0, 0, 167, 0, 0 ], [ 1, 0, 0.4667, 0.0667, 0, 0.66, 0.5, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 3, 0, 0.8333, 0.2667, 0, 0.66, ...
[ "from google.appengine.ext import webapp", "import os", "class PrintEnvironment(webapp.RequestHandler):\n def get(self):\n for name in os.environ.keys():\n self.response.out.write(\"%s = %s<br />\\n\" % (name, os.environ[name]))", " def get(self):\n for name in os.environ.keys():\n self.resp...
#!/usr/bin/env python # vim: set filetype=python expandtab tabstop=2 shiftwidth=2 autoindent smartindent: # -*- coding: utf-8 -*- # import cgi import datetime import logging from google.appengine.ext import db from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.api import images #logging.getLogger().setLevel(logging.DEBUG) class Greeting(db.Model): author = db.UserProperty() content = db.StringProperty(multiline=True) avatar = db.BlobProperty() date = db.DateTimeProperty(auto_now_add=True) class MainPage(webapp.RequestHandler): def get(self): self.response.out.write('<html><body>') query_str = "SELECT * FROM Greeting ORDER BY date DESC LIMIT 10" greetings = db.GqlQuery (query_str) for greeting in greetings: if greeting.author: self.response.out.write('<b>%s</b> wrote:' % greeting.author.nickname()) else: self.response.out.write('An anonymous person wrote:') self.response.out.write("<div><img src='img?img_id=%s'></img>" % greeting.key()) self.response.out.write(' %s</div>' % cgi.escape(greeting.content)) self.response.out.write(""" <form action="/sign" enctype="multipart/form-data" method="post"> <div><label>Message:</label></div> <div><textarea name="content" rows="3" cols="60"></textarea></div> <div><label>Avatar:</label></div> <div><input type="file" name="img"/></div> <div><input type="submit" value="Sign Guestbook"></div> </form> </body> </html>""") class Image (webapp.RequestHandler): def get(self): greeting = db.get(self.request.get("img_id")) if greeting.avatar: self.response.headers['Content-Type'] = "image/png" self.response.out.write(greeting.avatar) else: self.response.out.write("No image") class Guestbook(webapp.RequestHandler): def post(self): greeting = Greeting() if users.get_current_user(): greeting.author = users.get_current_user() greeting.content = self.request.get("content") avatar = images.resize(self.request.get("img"), 32, 32) greeting.avatar = db.Blob(avatar) greeting.put() self.redirect('/')
[ [ 1, 0, 0.0704, 0.0141, 0, 0.66, 0, 934, 0, 1, 0, 0, 934, 0, 0 ], [ 1, 0, 0.0845, 0.0141, 0, 0.66, 0.0909, 426, 0, 1, 0, 0, 426, 0, 0 ], [ 1, 0, 0.0986, 0.0141, 0, ...
[ "import cgi", "import datetime", "import logging", "from google.appengine.ext import db", "from google.appengine.api import users", "from google.appengine.ext import webapp", "from google.appengine.ext.webapp.util import run_wsgi_app", "from google.appengine.api import images", "class Greeting(db.Mo...
#!/usr/bin/env python # vim: set filetype=python expandtab tabstop=2 shiftwidth=2 autoindent smartindent: # -*- coding: utf-8 -*- # from google.appengine.ext import webapp from google.appengine.ext import db import os class Point(db.Expando): """ save a point with a comment """ lat = db.StringProperty(required=True) lng = db.StringProperty(required=True) comment = db.StringProperty(required=True) # test print envs class SavePoint(webapp.RequestHandler): def get(self): lat = self.request.get('lat') lng = self.request.get('lng') comment = self.request.get('comment') p = Point(lat=lat, lng=lng, comment=comment) key = p.put() self.response.out.write('Point (%s,%s [%s]) Saved with key (%d) Succ!' % (lat, lng, comment, key.id_or_name()))
[ [ 1, 0, 0.2143, 0.0357, 0, 0.66, 0, 167, 0, 1, 0, 0, 167, 0, 0 ], [ 1, 0, 0.25, 0.0357, 0, 0.66, 0.25, 167, 0, 1, 0, 0, 167, 0, 0 ], [ 1, 0, 0.2857, 0.0357, 0, 0.66...
[ "from google.appengine.ext import webapp", "from google.appengine.ext import db", "import os", "class Point(db.Expando):\n \"\"\" save a point with a comment \"\"\"\n \n lat = db.StringProperty(required=True)\n lng = db.StringProperty(required=True)\n comment = db.StringProperty(required=True)", " ...
#!/usr/bin/env python # vim: set filetype=python expandtab tabstop=2 shiftwidth=2 autoindent smartindent: # -*- coding: utf-8 -*- # from google.appengine.ext import db from google.appengine.api import users class Categories(db.Expando): """ categories of different places data model """ name = db.StringProperty(required=True) subname = db.StringProperty(required=True) description = db.StringProperty(required=True, multiline=True) class Place(db.Expando): """ a single place """ name = db.StringProperty(required=True) category = db.ReferenceProperty(Categories) #latitude = db.StringProperty(required=True) #longitude = db.StringProperty(required=True) place = db.GeoPtProperty(required=True) description = db.StringProperty(required=True, multiline=True) class Event(db.Expando): """ event happens in a place during particular time """ name = db.StringProperty(required=True) place = db.ReferenceProperty(Place) startdate = db.DateTimeProperty(required=True) stopdate = db.DateTimeProperty(required=True) description = db.StringProperty(required=True, multiline=True) def main(): c = Categories(key_name='hotel', name=u'宾馆', subname=u'五星级宾馆', description=u'价格最低500起') c.put() p = Place(key_name='dachong', name=u'大冲宾馆', category=c, place="22, 114", description=u'公司对面') p.put() e = Event(key_name='chistmas', name=u'圣诞打折', place=p, startdate=datetime.datetime(2007, 8, 20, 10, 10), stopdate=datetime.datetime(2007, 9, 20, 10, 10), description=u'圣诞旅游打折') e.put() if __name__ == '__main__': main()
[ [ 1, 0, 0.1064, 0.0213, 0, 0.66, 0, 167, 0, 1, 0, 0, 167, 0, 0 ], [ 1, 0, 0.1277, 0.0213, 0, 0.66, 0.1667, 279, 0, 1, 0, 0, 279, 0, 0 ], [ 3, 0, 0.2447, 0.1277, 0, ...
[ "from google.appengine.ext import db", "from google.appengine.api import users", "class Categories(db.Expando):\n \"\"\" categories of different places data model \"\"\"\n \n name = db.StringProperty(required=True)\n subname = db.StringProperty(required=True)\n description = db.StringProperty(required=T...
#!/usr/bin/env python # vim: set filetype=python expandtab tabstop=2 shiftwidth=2 autoindent smartindent: # -*- coding: utf-8 -*- # from google.appengine.api import urlfetch from google.appengine.ext import webapp # test fetch url class Fetch(webapp.RequestHandler): def get(self): self.response.out.write(""" <html> <head>Fetch A Url</head> <body> <form action="/fetchme" enctype="multipart/form-data" method="post"> <div><label>Plese input a valid url(begin with http):</label></div> <div><input type="text" name="url"/></div> <div><input type="submit" value="Fetch me!"></div> </body> </html>""") class Fetchme(webapp.RequestHandler): def post(self): url = self.request.get("url") result = urlfetch.fetch(url) if result.status_code == 200: self.response.out.write(result.content) else : self.response.out.write(str(result.headers))
[ [ 1, 0, 0.1667, 0.0333, 0, 0.66, 0, 279, 0, 1, 0, 0, 279, 0, 0 ], [ 1, 0, 0.2, 0.0333, 0, 0.66, 0.3333, 167, 0, 1, 0, 0, 167, 0, 0 ], [ 3, 0, 0.4833, 0.4, 0, 0.66, ...
[ "from google.appengine.api import urlfetch", "from google.appengine.ext import webapp", "class Fetch(webapp.RequestHandler):\n def get(self):\n self.response.out.write(\"\"\"\n <html>\n <head>Fetch A Url</head> \n <body>\n <form action=\"/fetchme\" enctype=\"multipart/form...
#!/usr/bin/env python # vim: set filetype=python expandtab tabstop=2 shiftwidth=2 autoindent smartindent: # -*- coding: utf-8 -*- # import os import wsgiref.handlers #import cgi import datetime import logging from google.appengine.api import mail from google.appengine.api import memcache from google.appengine.api import urlfetch from google.appengine.api import users from google.appengine.api import images from google.appengine.ext import db #from google.appengine.ext.db import djangoforms from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext.webapp import util from google.appengine.ext.webapp.util import run_wsgi_app from django.utils import simplejson from printenv import PrintEnvironment from savePoint import SavePoint from guestbook import * from fetchurl import * from jsonrpc import * logging.getLogger().setLevel(logging.DEBUG) # path router application = webapp.WSGIApplication([ ('/', MainPage), ('/img', Image), ('/sign', Guestbook), ('/printenv', PrintEnvironment), ('/savepoint', SavePoint), ('/fetch', Fetch), ('/fetchme', Fetchme), ('/rpc', RPCHandler) ], debug=True) def main(): run_wsgi_app(application) if __name__ == '__main__': main()
[ [ 1, 0, 0.0943, 0.0189, 0, 0.66, 0, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 1, 0, 0.1132, 0.0189, 0, 0.66, 0.0435, 709, 0, 1, 0, 0, 709, 0, 0 ], [ 1, 0, 0.1509, 0.0189, 0, ...
[ "import os", "import wsgiref.handlers", "import datetime", "import logging", "from google.appengine.api import mail", "from google.appengine.api import memcache", "from google.appengine.api import urlfetch", "from google.appengine.api import users", "from google.appengine.api import images", "from...
#!/usr/bin/env python # vim: set filetype=python expandtab tabstop=2 shiftwidth=2 autoindent smartindent: # -*- coding: utf-8 -*- # from google.appengine.ext import webapp import os # test print envs class PrintEnvironment(webapp.RequestHandler): def get(self): for name in os.environ.keys(): self.response.out.write("%s = %s<br />\n" % (name, os.environ[name]))
[ [ 1, 0, 0.4, 0.0667, 0, 0.66, 0, 167, 0, 1, 0, 0, 167, 0, 0 ], [ 1, 0, 0.4667, 0.0667, 0, 0.66, 0.5, 688, 0, 1, 0, 0, 688, 0, 0 ], [ 3, 0, 0.8333, 0.2667, 0, 0.66, ...
[ "from google.appengine.ext import webapp", "import os", "class PrintEnvironment(webapp.RequestHandler):\n def get(self):\n for name in os.environ.keys():\n self.response.out.write(\"%s = %s<br />\\n\" % (name, os.environ[name]))", " def get(self):\n for name in os.environ.keys():\n self.resp...
#!/usr/bin/env python # vim: set filetype=python expandtab tabstop=2 shiftwidth=2 autoindent smartindent: # -*- coding: utf-8 -*- # # test json rpc call from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from django.utils import simplejson class RPCHandler(webapp.RequestHandler): """ Allows the functions defined in the RPCMethods class to be RPCed.""" def __init__(self): webapp.RequestHandler.__init__(self) self.methods = RPCMethods() def get(self): func = None action = self.request.get('action') if action: if action[0] == '_': self.error(403) # access denied return else: func = getattr(self.methods, action, None) if not func: self.error(404) # file not found return args = {} keys = self.request.arguments() for arg in keys: if arg != 'action': args[arg] = self.request.get(arg) result = func(args) self.response.out.write(simplejson.dumps(result)) def post(self): args = simplejson.loads(self.request.body) #func, args = args[0], args[1:] func = args['action'] del args['action'] if func[0] == '_': self.error(403) # access denied return func = getattr(self.methods, func, None) if not func: self.error(404) # file not found return result = func(args) self.response.out.write(simplejson.dumps(result)) class RPCMethods: """ Defines the methods that can be RPCed. NOTE: Do not allow remote callers access to private/protected "_*" methods. """ def Add(self, *args): # The JSON encoding may have encoded integers as strings. # Be sure to convert args to any mandatory type(s). #ints = [int(arg) for arg in args] #return int(args[0]) + int(args[1]) tagsdic = args[0] sum = 0 for key in tagsdic: sum += int(tagsdic[key]) #return sum return '{"sum": "%d"}' % sum def Sub(self, *args): tagsdict = args[0] def main(): # path router application = webapp.WSGIApplication([ ('/rpc', RPCHandler) ], debug=True) run_wsgi_app(application) if __name__ == '__main__': main()
[ [ 1, 0, 0.0745, 0.0106, 0, 0.66, 0, 167, 0, 1, 0, 0, 167, 0, 0 ], [ 1, 0, 0.0851, 0.0106, 0, 0.66, 0.1667, 327, 0, 1, 0, 0, 327, 0, 0 ], [ 1, 0, 0.0957, 0.0106, 0, ...
[ "from google.appengine.ext import webapp", "from google.appengine.ext.webapp.util import run_wsgi_app", "from django.utils import simplejson", "class RPCHandler(webapp.RequestHandler):\n \"\"\" Allows the functions defined in the RPCMethods class to be RPCed.\"\"\"\n\n def __init__(self):\n webapp.Reques...
#!/usr/bin/env python # vim: set filetype=python expandtab tabstop=2 shiftwidth=2 autoindent smartindent: # -*- coding: utf-8 -*- # from google.appengine.api import urlfetch from google.appengine.ext import webapp # test fetch url class Fetch(webapp.RequestHandler): def get(self): self.response.out.write(""" <html> <head>Fetch A Url</head> <body> <form action="/fetchme" enctype="multipart/form-data" method="post"> <div><label>Plese input a valid url(begin with http):</label></div> <div><input type="text" name="url"/></div> <div><input type="submit" value="Fetch me!"></div> </body> </html>""") class Fetchme(webapp.RequestHandler): def post(self): url = self.request.get("url") result = urlfetch.fetch(url) if result.status_code == 200: self.response.out.write(result.content) else : self.response.out.write(str(result.headers))
[ [ 1, 0, 0.1667, 0.0333, 0, 0.66, 0, 279, 0, 1, 0, 0, 279, 0, 0 ], [ 1, 0, 0.2, 0.0333, 0, 0.66, 0.3333, 167, 0, 1, 0, 0, 167, 0, 0 ], [ 3, 0, 0.4833, 0.4, 0, 0.66, ...
[ "from google.appengine.api import urlfetch", "from google.appengine.ext import webapp", "class Fetch(webapp.RequestHandler):\n def get(self):\n self.response.out.write(\"\"\"\n <html>\n <head>Fetch A Url</head> \n <body>\n <form action=\"/fetchme\" enctype=\"multipart/form...