def test_non_string_input(self): # Filters shouldn't break if passed non-strings self.assertEqual(addslashes(123), '123') self.assertEqual(linenumbers(123), '1. 123') self.assertEqual(lower(123), '123') self.assertEqual(make_list(123), ['1', '2', '3']) self.assertEqual(slugify(123), '123') self.assertEqual(title(123), '123') self.assertEqual(truncatewords(123, 2), '123') self.assertEqual(upper(123), '123') self.assertEqual(urlencode(123), '123') self.assertEqual(urlize(123), '123') self.assertEqual(urlizetrunc(123, 1), '123') self.assertEqual(wordcount(123), 1) self.assertEqual(wordwrap(123, 2), '123') self.assertEqual(ljust('123', 4), '123 ') self.assertEqual(rjust('123', 4), ' 123') self.assertEqual(center('123', 5), ' 123 ') self.assertEqual(center('123', 6), ' 123 ') self.assertEqual(cut(123, '2'), '13') self.assertEqual(escape(123), '123') self.assertEqual(linebreaks_filter(123), '<p>123</p>') self.assertEqual(linebreaksbr(123), '123') self.assertEqual(removetags(123, 'a'), '123') self.assertEqual(striptags(123), '123')
def get_cities_by_province(self, request, *args, **kwargs): """ Get an ordered array of all cities within given province --- # YAML (must be separated by `---`) type: name: required: true type: string id: required: true type: integer omit_serializer: false parameters: - name: province description: Province where cities are needed. Case insensitive required: true type: string(2) paramType: query responseMessages: - code: 400 message: Province nonexistent """ cities = City.objects.filter(province=upper(request.QUERY_PARAMS.get('province', None))) cities = ([[city.name, city.id] for city in cities]) if len(cities) < 1: return HttpResponse(status=400, ) # Bad Request return Response(cities)
def create(self, **required_fields): required_fields['postal_code'] = upper(required_fields['postal_code']) address = self.model(**required_fields) address.save() return address
def get_cities_by_province(self, request, *args, **kwargs): """ Get an ordered array of all cities within given province --- # YAML (must be separated by `---`) type: name: required: true type: string id: required: true type: integer omit_serializer: false parameters: - name: province description: Province where cities are needed. Case insensitive required: true type: string(2) paramType: query responseMessages: - code: 400 message: Province nonexistent """ cities = City.objects.filter( province=upper(request.QUERY_PARAMS.get('province', None))) cities = ([[city.name, city.id] for city in cities]) if len(cities) < 1: return HttpResponse(status=400, ) # Bad Request return Response(cities)
def byline_sans_by(obj, type): """Get the byline from an article, properly pluralized, but without the 'By' before the name(s)""" str = '' try: count = obj.contributors.count() if count is 0: return filter.upper('No Writer Attributed') if 'sponsor' in type: if type == 'sponsor_url': return mark_safe(obj.contributors.all()[0].get_absolute_url()) elif type == 'sponsor_name': name = '' if obj.contributors.all()[0].first_name != ' ': name += obj.contributors.all()[0].first_name + ' ' if obj.contributors.all()[0].middle_name != '': name += obj.contributors.all()[0].middle_name + ' ' if obj.contributors.all()[0].last_name != ' ': name += obj.contributors.all()[0].last_name return mark_safe(name) elif type == 'sponsor_tcbs': str += human_list(linkify(obj.contributors.all()[0])) return mark_safe(str) elif type == 'sponsor_byline_second': try: str += human_list(linkify(obj.contributors.all()[1])) except: str += 'missing second contributor' return mark_safe(str) elif type == 'sponsor_byline': if count == 2: str += human_list(linkify(obj.contributors.all()[1])) else: str += human_list(linkify(obj.contributors.all()[0])) return mark_safe(str) links = linkify(obj.contributors.all()) str += human_list(links) if type == 'short': return mark_safe(str) # byline_type = getattr(obj, 'byline_type', None) if hasattr(obj, 'byline_type'): byline_type = obj.get_byline_type_display() else: byline_type = None if byline_type is not None and byline_type != 'None': str += ', ' + byline_type.upper() str += filter.pluralize(count).upper() return mark_safe(str) except AttributeError: return ''
def home(request): countries = requests.get('https://corona.lmao.ninja/countries').json() url_parameter = request.GET.get("q") if url_parameter != None: countries = [ ct for ct in countries if upper(url_parameter) in upper(ct['country']) ] if request.is_ajax(): html = render_to_string(template_name="countries-results-partial.html", context={"dados": countries}) data_dict = {"html_from_view": html} return JsonResponse(data=data_dict, safe=False) return render(request, 'home.html', {'dados': countries})
def search(self, request, *args, **kwargs): """ Filter non requested listings based on passed arguments. If no argument is passed all non requested listings are returned --- # YAML (must be separated by `---`) serializer: server.serializers.ListingSerializer omit_serializer: false parameters: - name: province required: false type: string(2) paramType: query - name: city required: false type: integer paramType: query - name: description required: false description: match is case insensitive and across all listing's description field type: string paramType: query - name: category required: false type: integer paramType: query responseMessages: - code: 204 message: No listing match the current search terms """ listings = Listing.objects listings = listings.filter(requested=False) province = request.QUERY_PARAMS.get('province', None) city = request.QUERY_PARAMS.get('city', None) description = request.QUERY_PARAMS.get('description', None) category = request.QUERY_PARAMS.get('category', None) if province is not None: listings = listings.filter(owner__city__province=upper(province)) if city is not None: listings = listings.filter(owner__city=city) if description is not None: listings = listings.filter(description__icontains=description) if category is not None: listings = listings.filter(category_id=category) if len(listings) < 1: return HttpResponse(status=204) # No Content return Response(ListingSerializer(listings, many=True).data)
def __init__(self, object_list, on=None, per_page=25): self.object_list = object_list self.count = len(object_list) self.pages = [] # chunk up the objects so we don't need to iterate over the whole list for each letter chunks = {} for obj in self.object_list: #if on: obj_str = unicode(getattr(obj, on)) #else: obj_str = unicode(obj) #letter = str.upper(obj_str[0]) letter = upper(unicode(obj))[0] #print letter #print obj if letter not in chunks: chunks[letter] = [] #else: chunks[letter].append(obj) # the process for assigning objects to each page print chunks current_page = NamePage(self) for letter in string.ascii_uppercase: if letter not in chunks: current_page.add([], letter) continue sub_list = chunks[letter] # the items in object_list starting with this letter new_page_count = len(sub_list) + current_page.count # first, check to see if sub_list will fit or it needs to go onto a new page. # if assigning this list will cause the page to overflow... # and an underflow is closer to per_page than an overflow... # and the page isn't empty (which means len(sub_list) > per_page)... if new_page_count > per_page and \ abs(per_page - current_page.count) < abs(per_page - new_page_count) and \ current_page.count > 0: # make a new page self.pages.append(current_page) current_page = NamePage(self) current_page.add(sub_list, letter) # if we finished the for loop with a page that isn't empty, add it if current_page.count > 0: self.pages.append(current_page)
def import_restaurant_availability(self, hours, restaurant_location): if not hours: return # RestaurantLocationAvailability Model for day, time in hours.items(): for weekday in Calendar.WEEKDAYS: if upper(day) == upper(weekday[1]): curr_weekday = weekday[0] start = time[0].get("start", None) end = time[0].get("end", None) try: restaurant_location_availability, created = RestaurantLocationAvailability.objects.get_or_create( restaurant_location=restaurant_location, weekday=curr_weekday, startHour=start.get("hour", None), startMinute=start.get("minute", None), endHour=end.get("hour", None), endMinute=end.get("minute", None)) except Exception as ex: self.handle_exception(ex, "RestaurantLocation")
def index_post(): err_msg = '' new_city = request.form.get('city') if new_city: existing_city = City.query.filter_by(name=upper(new_city)).first() if not existing_city: new_city_data = get_weather_data(new_city) if new_city_data['cod'] == 200: new_city_obj = City(name=upper(new_city)) db.session.add(new_city_obj) db.session.commit() else: err_msg = 'City does not exist in the world!' else: err_msg = 'City already exists in the database!' if err_msg: flash(err_msg, 'error') else: flash('City added successfully!') return redirect(url_for('index_get'))
def byline(obj, type): """Get the byline from an article, properly pluralized""" str = 'By ' count = obj.contributors.count() if count is 0: return filter.upper('No Writer Attributed') links = linkify(obj.contributors.all()) str += human_list(links) if type == 'short': return mark_safe(str) # byline_type = getattr(obj, 'byline_type', None) if hasattr(obj,'byline_type'): byline_type = obj.get_byline_type_display() else: byline_type = None if byline_type is not None and byline_type != 'None': str += ', ' + byline_type.upper() str += filter.pluralize(count).upper() return mark_safe(str)
def ajax_cloud_storage(request): print '-- ajax_cloud_storage:' if not request.user.is_authenticated(): return "" user = request.user profile = userprofile.objects.get(user=request.user) secret = profile.secret print request.user uploaded_files = Uploaded_Files.objects.filter(user=request.user).order_by('-pk') counter = 0 fobj = [] for f in uploaded_files: row = [] counter+=1 row.append('<a href="/media/'+str(f.file.file)+'">'+str(counter)+'</a>') row.append(naturalday(f.date_created)) row.append('<a href="/media/'+str(f.file.file)+'" target="_blank">'+clear_filename(f.file.file)+'</a> <small><a href="#" id="name" data-type="text" data-pk="1" data-original-title="Name this file" class="editable editable-click">create alias</a></small>') row.append(filesizeformat(f.file.file.size)) row.append(upper(get_file_extension(f.file.file))) row.append('<span class="label label-warning">Synchronising..</span>') if (not f.is_shared): row.append(' <a class="btn btn-success" href="#"><i class="fa fa-search-plus "></i></a> <a class="btn btn-info" href="/media/'+str(f.file.file)+'" target="_blank"><i class="fa fa-cloud-download "></i></a> <a class="btn btn-info" href="#" target="_blank"><i class="fa fa-share "></i></a> <a class="btn btn-danger" href="#"><i class="fa fa-trash-o "></i></a>') else: row.append(' <a class="btn btn-warning" href="/password/protect/file"><i class="fa fa-key "></i></a> <a class="btn btn-danger" href="#"><i class="fa fa-trash-o "></i></a><button type="button" class="btn btn-link"><i class="fa fa-link"></i> Share Link</button><span class="label label-default">'+str(f.share_link_clicks_count)+'</span>') fobj.append(row) json = { 'data': fobj } return HttpResponse(simplejson.dumps(json), mimetype='application/json')
def test_non_string_input(self): self.assertEqual(upper(123), '123')
def test_unicode(self): # lowercase e umlaut self.assertEqual(upper('\xeb'), '\xcb')
def test_upper(self): self.assertEqual(upper('Mixed case input'), 'MIXED CASE INPUT')
def test_upper(self): self.assertEqual(upper('Mixed case input'), 'MIXED CASE INPUT') # lowercase e umlaut self.assertEqual(upper('\xeb'), '\xcb')
from django.template.defaultfilters import upper, lower # str len str = "hello" print(len(str)) #upper print(upper(str)) print(lower(str)) str1 = "world : str1" str2 = str.format("test") print(str2) x = "x:hello".format(str1) print(x + str2) #Tuples and List tuple = (1, 2, 3, 4, 5) print(tuple) print(tuple[0:2]) list = [1, 2, 3, 4, 5] print(list) print(list[0:2]) list.append(6) print(list) sublist = [7, 8, 9]
#Strings and variables from django.template.defaultfilters import upper, lower DOB = 1992 #the year you are born AGE = 2019 - DOB am = "Your age is {}, and you are born in {}.".format(AGE, DOB) print(am) str = "Your name is {}.".format("Raj") print(str) str2 = "Your age is {}.".format(22) print(str2) yolo = upper("tanpis") print(yolo)
def test_unicode(self): # lowercase e umlaut self.assertEqual(upper("\xeb"), "\xcb")
def _create_or_update_place_for_event(event, upcoming_event_info): """ Adds a Place object and an UpcomingVenue object for the related venue. """ try: upcoming_venue_info = upcoming.venue.getInfo(venue_id=upcoming_event_info['venue_id'])[0] upcoming_metro_info = upcoming.metro.getInfo(metro_id=upcoming_event_info['metro_id'])[0] except: print "\tERROR: There was an error retrieving the Upcoming venue or metro information for this event." return None upcoming_venue, created_upcoming_venue = UpcomingVenue.objects.get_or_create( upcoming_venue_id=upcoming_venue_info['id'], ) if not created_upcoming_venue: place = upcoming_venue.place place.website = upcoming_venue_info['url'] place.description = upcoming_venue_info['description'] place.address1 = upcoming_venue_info['address'] place.phone1 = upcoming_venue_info['phone'] else: place = Place( name = upcoming_venue_info['name'], slug = get_unique_slug_value(Place, slugify(upcoming_venue_info['name']))[:30], website = upcoming_venue_info['url'], description = upcoming_venue_info['description'], address1 = upcoming_venue_info['address'], phone1 = upcoming_venue_info['phone'], phone2 = '', fax = '', ) if len(upcoming_venue_info['zip']) <= 5: place.zip_code = upcoming_venue_info['zip'] # Get the city from flickr's API instead of using Upcoming's data, as Flickr's is MUCH more normalized. place.city = get_city_from_flickr(city_name=upcoming_venue_info['city'], state=upper(upcoming_metro_info['state_code']), country=upcoming_metro_info['country_code']) if place.city: print "\tFound city " + str(place.city) + " using Flickr's places API." else: # If flickr doesn't get us any data, we'll use Upcoming's (shitty) data. print "\t Couldn't find the city in Flickr's API; falling back to Upcoming's." city = upcoming_venue_info['city'], state = upper(upcoming_metro_info['state_code']) if len(upcoming_metro_info['country_code']) == 2: country = upcoming_metro_info['country_code'] else: country = '' city, created_city = City.object.get_or_create( city = city, state = state, country = country, slug = slugify(asciiDammit(city) + " " + asciiDammit(state) + " " + asciiDammit(country)), ) if created_city: city.save() place.city = city place.save() upcoming_venue.place = place upcoming_venue.user_id = upcoming_venue_info['user_id'] upcoming_venue.name = upcoming_venue_info['name'] upcoming_venue.url = upcoming_venue_info['url'] upcoming_venue.private = upcoming_venue_info['private'] upcoming_venue.save() return place
def home(request): if request.method == 'POST': form = Register1(request.POST) if form.is_valid(): forename = form.cleaned_data.get('forename') surname = form.cleaned_data.get('surname') postcode = form.cleaned_data.get('postcode') email = form.cleaned_data.get('email') #request.session['_cust'] = form # DB2 Connection ibm_db_conn = ibm_db.connect( "DATABASE=GCUKPRD;HOSTNAME=prddgcd001;PORT=50002;PROTOCOL=TCPIP;UID=costaa;PWD=London07;", "", "") conn = ibm_db_dbi.Connection(ibm_db_conn) cur = conn.cursor() # count the number of customers that match surname and postcode cur.execute( """ select distinct t1.PER_GID from OPGCUK.PERSON_OPGC t1 join OPGCUK.PERSON_CONTACT_POINT_ADDR_OPGC t2 on t1.PER_GID = t2.PER_GID where t2.PER_POSTAL_ADDR_POSTCODE = ? and t1.PER_SURNAME = ? and t1.PER_FIRST_INITIAL = ?""", [upper(postcode), upper(surname), upper(forename[0])]) gid_all = [] for obj in cur.fetchall(): gid_all.append({"PER_GID": obj[0]}) gid_num = len(gid_all) gid = '' for row in gid_all: gid = row['PER_GID'] # DB2 Connection CLOSE cur.close() conn.close() if gid_num == 0: messages.warning( request, f'No customers in the database with the information provided.' ) elif gid_num == 1: messages.success( request, f'Customer {forename} {surname} @ {postcode} was found.') # phone = '' return redirect('find-dashboard', gid, forename, surname, postcode, email) else: # messages.warning(request, f'Please enter additional details required for your identification.') return redirect('find-register2', forename, surname, postcode, email) else: form = Register1() return render(request, 'find/home.html', {'form': form})
def register2(request, forename, surname, postcode, email): # DB2 Connection ibm_db_conn = ibm_db.connect( "DATABASE=GCUKPRD;HOSTNAME=prddgcd001;PORT=50002;PROTOCOL=TCPIP;UID=costaa;PWD=London07;", "", "") conn = ibm_db_dbi.Connection(ibm_db_conn) cur = conn.cursor() cur.execute( """ select distinct t1.PER_GID, t1.PER_TITLE_CODE as TITLE, t1.PER_FIRST_INITIAL as INITIAL, t1.PER_FORENAME as FORENAME, t1.PER_SURNAME as SURNAME, t1.PER_STATUS_CODE as STATUS, CASE t1.PER_GENDER_CODE WHEN '1' THEN 'MALE' WHEN '2' THEN 'FEMALE' ELSE 'Other' END as GENDER, t3.PER_CP_CAT_CODE as CONTACT_TYPE, t3.PER_CP_VALUE as CONTACT_VALUE, t2.PER_POSTAL_ADDR_POSTCODE as POSTCODE, t2.PER_POSTAL_ADDR_LINE_1 as ADDRESS_LINE1, t2.PER_POSTAL_ADDR_LINE_2 as ADDRESS_LINE2 from OPGCUK.PERSON_OPGC t1 join OPGCUK.PERSON_CONTACT_POINT_ADDR_OPGC t2 on t1.PER_GID = t2.PER_GID join OPGCUK.PERSON_CONTACT_POINT_OPGC t3 on t3.PER_GID = t1.PER_GID where t2.PER_POSTAL_ADDR_POSTCODE = ? and t1.PER_SURNAME = ? and t1.PER_FIRST_INITIAL = ?""", [upper(postcode), upper(surname), upper(forename[0])]) cust = [] for obj in cur.fetchall(): cust.append({ "PER_GID": obj[0], "TITLE": obj[1], "INITIAL": obj[2], "FORENAME": obj[3], "SURNAME": obj[4], "STATUS": obj[5], "GENDER": obj[6], "CONTACT_TYPE": obj[7], "CONTACT_VALUE": obj[8], "POSTCODE": obj[9], "ADDRESS_LINE1": obj[10], "ADDRESS_LINE2": obj[11] }) tab_len = len(cust) cur.execute( """ select distinct t2.PER_GID, t4.ITEM_ID as PLAN from OPGCUK.PERSON_ITEM_RELATIONSHIP_OPGC t2 join OPGCUK.ITEM_OPGC t3 on t3.ITEM_GID = t2.ITEM_GID and t2.ITEM_REL_CAT = 'OWN' join OPGCUK.ITEM_SOURCE_DETAIL_OPGC t4 on t4.ITEM_GID = t3.ITEM_GID join REFDATA_INT.REF_ITEM t5 on t3.ITEM_CODE = t5.ITEM_CODE and t5.COUNTRY_CODE = 'GBR' where left(t4.ITEM_ID,4) = 'PLN:' and t3.ITEM_COVER_DG_CONTR_STATUS_CODE in ('N','R','L') -- exclude Cancelled and t2.PER_GID IN ( select distinct t1.PER_GID from OPGCUK.PERSON_OPGC t1 join OPGCUK.PERSON_CONTACT_POINT_ADDR_OPGC t2 on t1.PER_GID = t2.PER_GID where t2.PER_POSTAL_ADDR_POSTCODE = ? and t1.PER_SURNAME = ? and t1.PER_FIRST_INITIAL = ?)""", [upper(postcode), upper(surname), upper(forename[0])]) plans = [] for obj in cur.fetchall(): plans.append({"PER_GID": obj[0], "PLAN": obj[1]}) # DB2 Connection CLOSE cur.close() conn.close() gid = '' if request.method == 'POST': form = Register2(request.POST) if form.is_valid(): phone = form.cleaned_data.get('phone') line1 = form.cleaned_data.get('line1') plan = form.cleaned_data.get('plan') gid_count = 0 if plan: for row in plans: if plan == row['PLAN']: gid = row['PER_GID'] gid_count = 1 else: i = 0 for row in cust: if row['CONTACT_VALUE'] == phone or line1 == row[ 'ADDRESS_LINE1'] or line1 == row['ADDRESS_LINE2']: i += 1 if i == 1: gid = row['PER_GID'] gid_count = 1 elif gid != row['PER_GID']: gid_count = gid_count + 1 if gid_count == 1: messages.success( request, f'Customer {forename} {surname} @ {postcode} was found.') # phone = '' return redirect('find-dashboard', gid, forename, surname, postcode, email) elif plan and gid_count == 0: messages.warning(request, f'Invalid Plan Number: {plan}') form = Register2() else: messages.warning(request, f'Please enter more details or Plan Number.') form = Register2() else: i = 0 for row in cust: if row['CONTACT_VALUE'] == upper( email) or forename == row['FORENAME']: i += 1 if i == 1: gid = row['PER_GID'] elif gid != row['PER_GID']: messages.warning( request, f'Please enter additional details required for your identification.' ) if i == 1: print('Found one - GID :', gid) messages.success( request, f'Thank you {forename} {surname} your account was created.') phone = '' return redirect('find-dashboard', gid, forename, surname, postcode, email) else: messages.warning( request, f'Please enter additional details required for your identification.' ) # send data to form form = Register2() args = { 'form': form, 'table': cust, 'tab_len': tab_len, 'plans': plans, 'forename': forename, 'surname': surname, 'postcode': postcode, 'email': email } return render(request, 'find/home.html', args) args = { 'form': form, 'table': cust, 'tab_len': tab_len, 'plans': plans, 'forename': forename, 'surname': surname, 'postcode': postcode, 'email': email } return render(request, 'find/home.html', args)
from django.template.defaultfilters import upper, lower # library django untuk upper dan lower nama = "Muhammad Zidane" nim = 20160801289 print(nama, nim) # Ambil data nama dengan NIM DOB = 1998 Age = 2020 - DOB AgeMessage = "Umur anda adalah {} dan lahir pada {}".format( Age, DOB) # Menambahkan variabel kedalam string print(AgeMessage) # keluaran variable akan masuk kedalam String Strlen = len(AgeMessage) # Penjabaran jumlah huruf print(Strlen) # output hasil jumlah huruf print(upper( AgeMessage)) # Mengubah huruf menjadi capital semua ( Harus import Django) print(lower(AgeMessage) ) # Mengubah huruf menjadi huruf kecil semua ( Harus import Django)
from django.template.defaultfilters import upper, lower name = "hussein alrubaye" # find number of character in string Strlen = len(name) print(Strlen) # upper case to string print(upper(name)) #lower case to string print(lower(name)) title = "your grade is {}".format(79) print(title) # concat to string str = "San Fransisco{}".format(" is nice place") print(str)
def test_upper(self): self.assertEqual(upper("Mixed case input"), "MIXED CASE INPUT")
from reconocimientos.models import Categoria, Puntuacion, Proyecto from django.template.defaultfilters import lower, upper """ Con esta lógica se obtienen los valores que hay en la base de datos para categorías, proyectos y puntuaciones, de forma tal que se puedan comparar luego cuando se generen nuevas menciones. """ n_categorias = Categoria.objects.all().values() n_puntuaciones = Puntuacion.objects.all().values() n_proyectos = Proyecto.objects.all().values() categorias = {} puntuaciones = {} proyectos = {} for c in n_categorias: categorias[c['nombre']] = c['id'] for p in n_puntuaciones: puntuacion = lower(p['denominacion']) puntuaciones[puntuacion] = p['id'] puntuacion = upper(p['denominacion']) puntuaciones[puntuacion] = p['id'] puntuaciones[''] = 6 for p in n_proyectos: proyectos[p['nombre']] = p['id']