def wrapped(*args, **kwargs): formatted_args = ", ".join(util.shorten(arg) for arg in args) if len(kwargs) > 0: formatted_kwargs = ("%s=%s" % (util.shorten(k), util.shorten(v)) \ for (k, v) in kwargs.iteritems()) formatted_args += ", %s" % ", ".join(formatted_kwargs) message("%s(%s)" % (fn.__name__, formatted_args), verbose=True) return fn(*args, **kwargs)
def track(self): if not self.values: return 'Enter a UPS tracking number' num = self.values[0] link = 'https://wwwapps.ups.com/WebTracking/track?track=yes&trackNums=%s' % num return shorten(link)
def edit_reviews(): # Gets the information on the venue. c = db.venue(request.args(0)) or redirect(URL('default', 'index')) # Building ordering. last_comparison_r = db((db.comparison.venue_id == c.id) & (db.comparison.user == auth.user.email) & (db.comparison.is_valid == True) ).select(orderby=~db.comparison.date).first() if last_comparison_r is None: current_ordering = [] compar_id = None current_grades = {} else: current_ordering = last_comparison_r.ordering compar_id = last_comparison_r.id # Dictionary submission id: grade. str_grades = simplejson.loads(last_comparison_r.grades) current_grades = {long(key):float(value) for (key, value) in str_grades.iteritems()} submissions = {} for subm_id in current_ordering: # Finds the task. st = db((db.task.submission_id == subm_id) & (db.task.user == auth.user.email)).select().first() subm = db.submission(subm_id) line = SPAN(A(st.submission_name, _href=URL('submission', 'view_submission', args=['v', st.id])), " (Comments: ", util.shorten(st.comments), ") ") submissions[subm_id] = line expired = (datetime.utcnow() < c.rate_open_date or datetime.utcnow() > c.rate_close_date) # Link for editing ordering. if (compar_id is None) or expired: ordering_edit_link = None else: ordering_edit_link = A(T("Edit grades and ordering"), _href=URL('rating', 'edit_ordering', args=[c.id, compar_id])) # View/Editing comments. q = ((db.task.venue_id == c.id) & (db.task.user == auth.user.email) & (db.task.completed_date < datetime.utcnow())) db.task.assigned_date.writable = db.task.assigned_date.readable = False db.task.completed_date.writable = db.task.completed_date.readable = False db.task.rejection_comment.writable = False db.task.comments.writable = db.task.comments.readable = True db.task.submission_name.label = T('Submission') db.task.submission_name.represent = lambda v, r: A(v, _href=URL('submission', 'view_submission', args=['v', r.id])) grid = SQLFORM.grid(q, details=True, csv=False, create=False, editable=(not expired), searchable=False, deletable=False, args=request.args[:1], ) return dict(grid=grid, title=c.name, current_ordering=current_ordering, submissions=submissions, current_grades=current_grades, ordering_edit_link=ordering_edit_link)
def get(self): next = None PAGESIZE = 30 util.insertUsersideCookies(self) self.session = True user = UserInfo() user.whoIs(self) bookmark = self.request.get("bookmark") if bookmark: bookmark = Key(self.request.get("bookmark")) else: if user.user: bookmark = Key.from_path('MySketchesSketch','-%023d' % (int(user.user_id)) + SKETCH_ZEROS) else: bookmark = Key.from_path('MySketchesSketch','-%023d' % (0) + SKETCH_ZEROS) if user.user: endKey = Key.from_path('MySketchesSketch','-%023d' % (int(user.user_id) + 1) + SKETCH_ZEROS) else: endKey = Key.from_path('MySketchesSketch','-%023d' % (1) + SKETCH_ZEROS) logging.info('starting key ' + str(bookmark)) logging.info('starting key name' + bookmark.name()) q = db.GqlQuery("SELECT * FROM MySketchesSketch WHERE __key__ >= :1 AND __key__ < :2",bookmark,endKey) sketches = q.fetch(PAGESIZE+1) if len(sketches) == PAGESIZE + 1: next = str(sketches[-1].key()) sketches = sketches[:PAGESIZE] logging.info('next key ' + next) logging.info('next key name ' + sketches[-1].key().name()) if next is None: next = "" for sketch in sketches: sketch.stringtags = util.shorten(" ".join(sketch.tags),18) template_values = { 'sketches':sketches, 'bookmark':bookmark, 'next':next, 'action':"mySketches", 'headerTitle':"My sketches", } self.generate('galleryTemplate.html',template_values)
def distaste(self): if self.values: roasted = shorten(self.values[0]) if roasted: open(self.settings.directory.distaste, 'a').write(roasted + '\n') self.chat("Another one rides the bus") return lines = [] for line in open(self.settings.directory.distaste): lines.append(line) self.chat(choice(lines))
def distaste(self): if self.values: roasted = shorten(url) if roasted: open(DISTASTE, 'a').write(roasted + '\n') self.chat("Another one rides the bus") return lines = [] for line in open(DISTASTE): lines.append(line) self.chat(choice(lines))
def edit_reviews(): # Gets the information on the venue. c = db.venue(request.args[0]) or redirect(URL('default', 'index')) # Building ordering. last_comparison_r = db((db.comparison.venue_id == c.id) & (db.comparison.author == auth.user_id) & (db.comparison.is_valid == True) ).select(orderby=~db.comparison.date).first() if last_comparison_r is None: current_ordering = [] compar_id = None else: current_ordering = last_comparison_r.ordering compar_id = last_comparison_r.id submissions = {} for sub_id in current_ordering: # Finds the task. st = db((db.task.submission_id == sub_id) & (db.task.user_id == auth.user_id)).select().first() subm = db.submission(sub_id) line = SPAN(A(st.submission_name, _href=URL('submission', 'view_submission', args=[sub_id])), " (Comments: ", util.shorten(st.comments), ") ", A(T('Download'), _class='btn', _href=URL('download_reviewer', args=[st.id, subm.content]))) submissions[sub_id] = line expired = (datetime.utcnow() < c.rate_open_date or datetime.utcnow() > c.rate_close_date) # Link for editing ordering. if (compar_id is None) or expired: ordering_edit_link = None else: ordering_edit_link = A(T("Edit ordering"), _href=URL('rating', 'edit_ordering', args=[c.id, compar_id])) # View/Editing comments. q = ((db.task.venue_id == c.id) & (db.task.user_id == auth.user_id)) db.task.assigned_date.writable = False db.task.completed_date.writable = False grid = SQLFORM.grid(q, details=True, csv=False, create=False, editable=(not expired), searchable=False, deletable=False, args=request.args[:1], ) return dict(grid=grid, title=c.name, current_ordering=current_ordering, submissions=submissions, ordering_edit_link=ordering_edit_link)
def get(self): next = None PAGESIZE = 30 util.insertUsersideCookies(self) user = UserInfo() user.whoIs(self) if user.email == '*****@*****.**': self.generate('limboPage.html') return; bookmark = self.request.get("bookmark") if bookmark: bookmark = Key(self.request.get("bookmark")) else: bookmark = Key.from_path('GallerySketch',SKETCH_ZEROS) logging.info('starting key ' + str(bookmark)) logging.info('starting key name' + bookmark.name()) q = db.GqlQuery("SELECT * FROM GallerySketch WHERE __key__ >= :1", bookmark) sketches = q.fetch(PAGESIZE+1) if len(sketches) == PAGESIZE + 1: next = str(sketches[-1].key()) sketches = sketches[:PAGESIZE] logging.info('next key ' + next) logging.info('next key name ' + sketches[-1].key().name()) if next is None: next = "" for sketch in sketches: sketch.stringtags = util.shorten(" ".join(sketch.tags),18) template_values = { 'sketches':sketches, 'bookmark':bookmark, 'next':next, 'action':"gallery", 'headerTitle':"Gallery", } self.generate('galleryTemplate.html',template_values)
def weather(self): if not self.values: return "Please enter a zip/location" if not self.secrets.weather_api: return "wunderground api key is not set" if not self.values: params = "autoip.json?geo_ip=%s" % self.lastip else: params = "%s.json" % self.values[0] base = "http://api.wunderground.com/api/%s/conditions/q/" % self.secrets.weather_api url = base + params try: request = Browser(url) except: return "Couldn't get weather." if not request: return "Couldn't get weather." try: json = request.json() json = json['current_observation'] except: return "Couldn't parse weather." location = json['display_location']['full'] condition = json['weather'] temp = json['temperature_string'] humid = json['relative_humidity'] wind = json['wind_string'] feels = json['feelslike_string'] hourly = 'http://www.weather.com/weather/hourbyhour/l/%s' % self.values[ 0] radar = shorten('http://www.weather.com/weather/map/interactive/l/%s' % self.values[0]) base = "%s, %s, %s, Humidity: %s, Wind: %s, Feels like: %s, Radar: %s" return base % (location, condition, temp, humid, wind, feels, radar)
def weather(self): if not self.values: return "Please enter a zip/location" if not self.secrets.weather_api: return "wunderground api key is not set" if not self.values: params = "autoip.json?geo_ip=%s" % self.lastip else: params = "%s.json" % self.values[0] base = "http://api.wunderground.com/api/%s/conditions/q/" % self.secrets.weather_api url = base + params try: request = Browser(url) except: return "Couldn't get weather." if not request: return "Couldn't get weather." try: json = request.json() json = json['current_observation'] except: return "Couldn't parse weather." location = json['display_location']['full'] condition = json['weather'] temp = json['temperature_string'] humid = json['relative_humidity'] wind = json['wind_string'] feels = json['feelslike_string'] hourly = 'http://www.weather.com/weather/hourbyhour/l/%s' % self.values[0] radar = shorten('http://www.weather.com/weather/map/interactive/l/%s' % self.values[0]) base = "%s, %s, %s, Humidity: %s, Wind: %s, Feels like: %s, Radar: %s" return base % (location, condition, temp, humid, wind, feels, radar)
def urlparse(self, url): if self.cleanse(url) == False: return [url] fubs = 0 title = "Couldn't get title" site = Browser(url) if site.error: self.chat('Total fail: %s' % site.error) return [url] roasted = shorten(url) if not roasted: roasted = "Couldn't roast" fubs += 1 self.chat('%s @ %s' % (unescape(site.title()), roasted)) return [url]
def showquote(self, context): if not self.stock: return False name = "%s (%s)" % (self.company, self.symbol.upper()) changestring = str( self.change) + " (" + ("%.2f" % self.perc_change) + "%)" if self.change < 0: changestring = colorize(changestring, 'red') else: changestring = colorize(changestring, 'lightgreen') message = [ name, str(self.price), changestring, ] otherinfo = [ # ("pretty title", "dataname") ("Exchange", "exchange"), ("Trading volume", "volume"), ("Market cap", "market_cap"), ] # TODO: Don't do this for not in channel, ensure it's a privmsg only. Currently not compatible with channeling # if context != CHANNEL: # for item in otherinfo: # pretty, id = item # addon = pretty + ": " + getattr(self, id, 'N/A') # message.append(addon) link = 'http://finance.yahoo.com/q?s=' + self.symbol roasted = shorten(link) message.append(roasted) output = ', '.join(message) return output
def showquote(self, context): if not self.stock: return False name = "%s (%s)" % (self.company, self.symbol.upper()) changestring = str(self.change) + " (" + ("%.2f" % self.perc_change) + "%)" if self.change < 0: changestring = colorize(changestring, 'red') else: changestring = colorize(changestring, 'lightgreen') message = [ name, str(self.price), changestring, ] otherinfo = [ # ("pretty title", "dataname") ("Exchange", "exchange"), ("Trading volume", "volume"), ("Market cap", "market_cap"), ] # TODO: Don't do this for not in channel, ensure it's a privmsg only. Currently not compatible with channeling # if context != CHANNEL: # for item in otherinfo: # pretty, id = item # addon = pretty + ": " + getattr(self, id, 'N/A') # message.append(addon) link = 'http://finance.yahoo.com/q?s=' + self.symbol roasted = shorten(link) message.append(roasted) output = ', '.join(message) return output
def upload(): try: file = request.files['file'] msg = 'New file upload' if 'msg' in request.form: msg = request.form['msg'] timestamp = int(time.time()) name = "%s-%s" % (timestamp, file.filename) path = 'server/static/uploads/%s' % name file.save(path) except Exception as e: return str(e) + "\n" url = shorten('%s/static/uploads/%s' % (conf.misc.website, name)) line = "%s %s" % (msg, url) #secret.primary_channel) messages = open('/tmp/uploads.msgs', 'a') messages.write(line + "\n") messages.close() return "File saved: %s\n" % url
def get(self): util.insertUsersideCookies(self) user = UserInfo() user.whoIs(self) if user.email == '*****@*****.**': self.generate('limboPage.html') return q = db.GqlQuery("SELECT * FROM GallerySketch") sketches = q.fetch(28) counter = 28 for sketch in sketches: sketch.stringtags = util.shorten(" ".join(sketch.tags), 18) sketch.counter = counter counter = counter + 1 template_values = { 'sketches': sketches, } self.generate('frontPageTemplate.html', template_values)
def get(self): util.insertUsersideCookies(self) user = UserInfo() user.whoIs(self) if user.email == '*****@*****.**': self.generate('limboPage.html') return; q = db.GqlQuery("SELECT * FROM GallerySketch") sketches = q.fetch(28) counter = 28 for sketch in sketches: sketch.stringtags = util.shorten(" ".join(sketch.tags),18) sketch.counter = counter counter = counter + 1 template_values = { 'sketches':sketches, } self.generate('frontPageTemplate.html',template_values)
received_message_b64 = bytes.decode(base64.b64encode(received_message)) logger.info(srvr + "Received a super-secret message {}".format( stylize(received_message_b64, colored.fg("blue")))) if 'localhost' in validator_address: logger.info(srvr + step + "Validating the message with on-premise validator") else: logger.info(srvr + step + "Validating the message with remote validator") received_message_hash = bytes.decode( base64.b64encode(hashlib.sha512(received_message).digest())) response = requests.get(validator_address + "/" + quote(received_message_hash, safe="+="), headers=api._auth) if response.ok: logger.info(srvr + ok + "Message {} successfully verified".format( stylize(received_message_b64, colored.fg("green")))) json = response.json() shortened = {key: shorten(json[key]) for key in json} logger.info(srvr + "Relevant proof information (shortened):") logger.info(srvr + stylize(shortened, colored.fg("blue"))) else: logger.error(srvr + nok + "Failed to verify the message {} ({} - {})".format( stylize(received_message_b64, colored.fg("blue")), stylize(response.status_code, colored.fg("red")), stylize(response.content, colored.fg("red")))) # endregion
logger.warning("Grades cannot be converted: " + str(k) + ":" + str(v)) # Now we need to find the names of the submissions (for the user) that were # used in this last ordering. # We create a submission_id to line mapping, that will be passed in json to the view. submissions = {} for i in last_ordering: # Finds the task. st = db((db.task.submission_id == i) & (db.task.user_id == auth.user_id)).select().first() if st != None: v = access.validate_task(db, st.id, auth.user_id) if v != None: (_, subm, cont) = v line = SPAN(A(st.submission_name, _href=URL('submission', 'view_submission', args=[i])), " (Comments: ", util.shorten(st.comments), ") ", A(T('Download'), _class='btn', _href=URL('submission', 'download_reviewer', args=[st.id, subm.content]))) submissions[i] = line # Adds also the last submission. v = access.validate_task(db, t.id, auth.user_id) if v == None: # Should not happen. session.flash('You cannot view this submission.') redirect(URL('default', 'index')) (_, subm, cont) = v line = SPAN(A(t.submission_name, _href=(URL('submission', 'view_submission', args=[t.id]))), " ", A(T('Download'), _class='btn', _href=URL('submission', 'download_reviewer', args=[t.id, subm.content]))) submissions[t.submission_id] = line
def assert_not_is_instance(type, value): if isinstance(value, type): raise error.ProletarianTestException("Expected '%s' to not be of type '%s'" % (util.shorten(value), util.shorten(type)))
def assert_not_in(container, value): if value in container: raise error.ProletarianTestException("Expected '%s' to not be in '%s'" % (util.shorten(value), util.shorten(container)))
def assert_false(value): if value != False: raise error.ProletarianTestException("Expected '%s' to be false" % \ util.shorten(value))
def shorten(self): if not self.values: return 'Shorten what?' return shorten(self.values[0])
def get(self,originaluserIDasString): next = None PAGESIZE = 30 util.insertUsersideCookies(self) # we get it in the form davidedc-2jaidlbSQRSE and we only want 2jaidlbSQRSE userIDasString = originaluserIDasString.partition('-')[2] logging.info('most weird: sometimes this ends with justcorners.js : ' + userIDasString) userIDasString = userIDasString.partition('/')[0] if userIDasString != "anonymous": userIDasString = '%023d' % (util.toBase10(userIDasString,62)) logging.info('coverting to 23 digits: ' + userIDasString) logging.info('after cleanup, query starts from ' + "-"+userIDasString + ZERO_FILL) logging.info('query ends at ' + '-%023d' % (int(userIDasString) + 1) + ZERO_FILL) else: userIDasString = '%023d' % (0) logging.info('searching for anonymous sketches, user id is 23 zeroes') self.session = True user = UserInfo() user.whoIs(self) # we'll be using this variable later and it better not be null if user.user_id == None: user.user_id = "0"; logging.info('comparing ' + ('%023d' % int(user.user_id)) + " to " + userIDasString) if ('%023d' % int(user.user_id)) != userIDasString: logging.info('user is looking at someone else\'s sketches, showing only public sketches from AuthorSketchesSketch table') bookmark = self.request.get("bookmark") if self.request.get("bookmark"): bookmark = Key(self.request.get("bookmark")) else: bookmark = Key.from_path('AuthorSketchesSketch',"-"+userIDasString + ZERO_FILL) endKey = Key.from_path('AuthorSketchesSketch','-%023d' % (int(userIDasString) + 1) + ZERO_FILL) q = db.GqlQuery("SELECT * FROM AuthorSketchesSketch WHERE __key__ >= :1 AND __key__ < :2",bookmark,endKey) else: logging.info('user is looking at his own sketches, showing private and public sketches from MySketchesSketch table') if self.request.get("bookmark"): bookmark = Key(self.request.get("bookmark")) else: bookmark = Key.from_path('MySketchesSketch','-%023d' % (int(user.user_id)) + SKETCH_ZEROS) endKey = Key.from_path('MySketchesSketch','-%023d' % (int(user.user_id) + 1) + SKETCH_ZEROS) q = db.GqlQuery("SELECT * FROM MySketchesSketch WHERE __key__ >= :1 AND __key__ < :2",bookmark,endKey) logging.info('starting key ' + str(bookmark)) logging.info('end key ' + str(endKey)) sketches = q.fetch(PAGESIZE+1) logging.info('number of sketches found: ' + str(len(sketches))) if len(sketches) == PAGESIZE + 1: next = str(sketches[-1].key()) sketches = sketches[:PAGESIZE] if next is None: next = "" for sketch in sketches: sketch.stringtags = util.shorten(" ".join(sketch.tags),18) template_values = { 'sketches':sketches, 'bookmark':bookmark, 'next':next, 'action':"sketchesByUploader", 'userIDasString':originaluserIDasString, 'headerTitle':"By submitter", } self.generate('galleryTemplate.html',template_values)
def get(self): originaluserIDasString = "anonymous" # this big blot inserted by Davide Della Casa self.session = True user = UserInfo() user.whoIs(self) if not user.is_current_user_admin: self.redirect('/index.html') next = None PAGESIZE = 30 util.insertUsersideCookies(self) # we get it in the form davidedc-2jaidlbSQRSE and we only want 2jaidlbSQRSE userIDasString = "anonymous" userIDasString = '%023d' % (0) logging.info('searching for anonymous sketches, user id is 23 zeroes') self.session = True user = UserInfo() user.whoIs(self) # we'll be using this variable later and it better not be null if user.user_id == None: user.user_id = "0"; logging.info('comparing ' + ('%023d' % int(user.user_id)) + " to " + userIDasString) logging.info('admin looking at anonymous sketches') # note that we can fetch the sketches from the AuthorSketchesSketch table # because all anonymous sketches are public. bookmark = self.request.get("bookmark") if self.request.get("bookmark"): bookmark = Key(self.request.get("bookmark")) else: bookmark = Key.from_path('AuthorSketchesSketch',"-"+userIDasString + ZERO_FILL) endKey = Key.from_path('AuthorSketchesSketch','-%023d' % (int(userIDasString) + 1) + ZERO_FILL) q = db.GqlQuery("SELECT * FROM AuthorSketchesSketch WHERE __key__ >= :1 AND __key__ < :2",bookmark,endKey) logging.info('starting key ' + str(bookmark)) logging.info('end key ' + str(endKey)) ANONYMOUSSKETCHESFETCHSIZE = 1000 sketches = q.fetch(ANONYMOUSSKETCHESFETCHSIZE+1) logging.info('number of sketches found: ' + str(len(sketches))) if len(sketches) == ANONYMOUSSKETCHESFETCHSIZE + 1: next = str(sketches[-1].key()) sketches = sketches[:ANONYMOUSSKETCHESFETCHSIZE] if next is None: next = "" for sketch in sketches: sketch.stringtags = util.shorten(" ".join(sketch.tags),18) template_values = { 'sketches':sketches, 'bookmark':bookmark, 'next':next, 'action':"sketchesByUploader", 'userIDasString':originaluserIDasString, 'headerTitle':"By submitter", } self.generate('allAnonymousSketchesTemplate.html',template_values)
def linker(self, urls): for url in urls: # Special behaviour for Twitter URLs match_twitter_urls = re.compile( 'http[s]?://(www.)?twitter.com/.+/status/([0-9]+)') twitter_urls = match_twitter_urls.findall(url) if len(twitter_urls): self.tweet(twitter_urls) return if url.find('gist.github') != -1: return if randint(1, 5) == 1: try: self.commands.get('tweet', self.default)(url) except: pass fubs = 0 title = "Couldn't get title" site = Browse(url) if site.error: self.chat('Total fail: %s' % site.error) continue roasted = shorten(url) if not roasted: roasted = "Couldn't roast" fubs += 1 try: ext = site.headers()['content-type'].split('/')[1] except: ext = False images = [ 'gif', 'png', 'jpg', 'jpeg', ] if ext in images: title = 'Image' # Switch this to a Browse method if STORE_IMGS: fname = url.split('/').pop() path = IMGS + fname self.butler.do(savefromweb, (url, path, self.lastsender), 'Thumb @ %s') elif ext == 'pdf': title = 'PDF Document' else: title = site.title() # If you have a delicious account set up. Yes, delicious # still exists. Could be updated to a cooler link # collecting service. if STORE_URLS: postdelicious(url, title, self.lastsender) if fubs == 2: self.chat("Total fail") else: self.chat("%s @ %s" % (unescape(title), roasted))
# Reads the keys from the datastore. keys_to_read = [x for x in keys_to_read if x is not None] key_to_val = keystore_multi_read(keys_to_read) for i in sub_info: sub_info[i]['name'] = key_to_val.get(sub_info[i]['name_key'], 'Submission') sub_info[i]['comm'] = key_to_val.get(sub_info[i]['comm_key'], '') # ---qui--- # We create a submission_id to line mapping, that will be passed in json to the view. submissions = {} for i in last_ordering: short_comments = util.shorten(sub_info[i]['comm']) line = SPAN(A(sub_info[i]['name'], _href=URL('submission', 'view_submission', args=['e', st.id])), " (Comments: ", short_comments, ") ") submissions[i] = line # Adds also the last submission. line = A(sub_info[t.submission_id]['name'], _href=(URL('submission', 'view_submission', args=['e', t.id]))) submissions[t.submission_id] = line this_submission_name = sub_info[t.submission_id]['name'] # Used to check each draggable item and determine which one we should # highlight (because its the current/new record). new_comparison_item = t.submission_id
# Now we need to find the names of the submissions (for the user) that were # used in this last ordering. # We create a submission_id to line mapping, that will be passed in json to the view. submissions = {} for i in last_ordering: # Finds the task. st = db((db.task.submission_id == i) & (db.task.user == auth.user.email)).select().first() if st != None: ok, v = access.validate_task(db, st.id, auth.user.email) if ok: (_, subm, cont) = v line = SPAN( A(st.submission_name, _href=URL('submission', 'view_submission', args=[i])), " (Comments: ", util.shorten(st.comments), ") ", A(T('Download'), _class='btn', _href=URL('submission', 'download_reviewer', args=[st.id, subm.content]))) submissions[i] = line # Adds also the last submission. ok, v = access.validate_task(db, t.id, auth.user.email) if not ok: # Should not happen. session.flash = T(v) redirect(URL('default', 'index')) (_, subm, cont) = v line = SPAN( A(t.submission_name,
def linker(self, urls): for url in urls: # Special behaviour for Twitter URLs match_twitter_urls = re.compile('http[s]?://(www.)?twitter.com/.+/status/([0-9]+)') twitter_urls = match_twitter_urls.findall(url) if len(twitter_urls): self.tweet(twitter_urls) return if url.find('gist.github') != -1: return if randint(1, 5) == 1: try: self.commands.get('tweet', self.default)(url) except: pass fubs = 0 title = "Couldn't get title" site = Browse(url) if site.error: self.chat('Total fail: %s' % site.error) continue roasted = shorten(url) if not roasted: roasted = "Couldn't roast" fubs += 1 try: ext = site.headers()['content-type'].split('/')[1] except: ext = False images = [ 'gif', 'png', 'jpg', 'jpeg', ] if ext in images: title = 'Image' # Switch this to a Browse method if STORE_IMGS: fname = url.split('/').pop() path = IMGS + fname self.butler.do(savefromweb, (url, path, self.lastsender), 'Thumb @ %s') elif ext == 'pdf': title = 'PDF Document' else: title = site.title() # If you have a delicious account set up. Yes, delicious # still exists. Could be updated to a cooler link # collecting service. if STORE_URLS: postdelicious(url, title, self.lastsender) if fubs == 2: self.chat("Total fail") else: self.chat("%s @ %s" % (unescape(title), roasted))
def assert_not_equal(first, second): if expected == actual: raise error.ProletarianTestException("Expected '%s' != '%s'" % \ (util.shorten(first), util.shorten(second)))
except Exception, e: logger.warning("Grades cannot be converted: " + str(k) + ":" + str(v)) # Now we need to find the names of the submissions (for the user) that were # used in this last ordering. # We create a submission_id to line mapping, that will be passed in json to the view. submissions = {} for i in last_ordering: # Finds the task. st = db((db.task.submission_id == i) & (db.task.user == auth.user.email)).select().first() if st != None: ok, v = access.validate_task(db, st.id, auth.user.email) if ok: (_, subm, cont) = v line = SPAN(A(st.submission_name, _href=URL('submission', 'view_submission', args=['v', st.id])), " (Comments: ", util.shorten(st.comments), ") ") submissions[i] = line # Adds also the last submission. ok, v = access.validate_task(db, t.id, auth.user.email) if not ok: # Should not happen. session.flash = T(v) redirect(URL('default', 'index')) (_, subm, cont) = v line = A(t.submission_name, _href=(URL('submission', 'view_submission', args=['v', t.id]))) submissions[t.submission_id] = line # Used to check each draggable item and determine which one we should # highlight (because its the current/new record). new_comparison_item = t.submission_id
def assert_true(value): if value != True: raise error.ProletarianTestException("Expected '%s' to be true" % \ util.shorten(value))
def assert_equal(expected, actual): if expected != actual: raise error.ProletarianTestException("Expected '%s' but got '%s'" % \ (util.shorten(expected), util.shorten(actual)))
def edit_reviews(): # Gets the information on the venue. c = db.venue(request.args[0]) or redirect(URL('default', 'index')) # Building ordering. last_comparison_r = db((db.comparison.venue_id == c.id) & (db.comparison.user == auth.user.email) & (db.comparison.is_valid == True)).select( orderby=~db.comparison.date).first() if last_comparison_r is None: current_ordering = [] compar_id = None current_grades = {} else: current_ordering = last_comparison_r.ordering compar_id = last_comparison_r.id # Dictionary submission id: grade. str_grades = simplejson.loads(last_comparison_r.grades) current_grades = { long(key): float(value) for (key, value) in str_grades.iteritems() } submissions = {} for subm_id in current_ordering: # Finds the task. st = db((db.task.submission_id == subm_id) & (db.task.user == auth.user.email)).select().first() subm = db.submission(subm_id) line = SPAN( A(st.submission_name, _href=URL('submission', 'view_submission', args=[subm_id])), " (Comments: ", util.shorten(st.comments), ") ", A(T('Download'), _class='btn', _href=URL('submission', 'download_reviewer', args=[st.id, subm.content]))) submissions[subm_id] = line expired = (datetime.utcnow() < c.rate_open_date or datetime.utcnow() > c.rate_close_date) # Link for editing ordering. if (compar_id is None) or expired: ordering_edit_link = None else: ordering_edit_link = A(T("Edit ordering"), _href=URL('rating', 'edit_ordering', args=[c.id, compar_id])) # View/Editing comments. q = ((db.task.venue_id == c.id) & (db.task.user == auth.user.email) & (db.task.completed_date < datetime.utcnow())) db.task.assigned_date.writable = False db.task.completed_date.writable = False db.task.rejection_comment.writable = False grid = SQLFORM.grid( q, details=True, csv=False, create=False, editable=(not expired), searchable=False, deletable=False, args=request.args[:1], ) return dict(grid=grid, title=c.name, current_ordering=current_ordering, submissions=submissions, current_grades=current_grades, ordering_edit_link=ordering_edit_link)