def register_command(self,update: Update, context:CallbackContext) -> None: user_id = update.effective_user.id try: zipcode = context.args[0] dist = int(context.args[1]) if dist < 0: update.message.reply_text("Distance must greater than 0") return zipcodes.is_real(zipcode=zipcode) user = user_info.User(user_id, zipcode) updatter = user_info.UserUpdatter(user, dist, update, context) self.users[user_id] = updatter except (IndexError, ValueError): update.message.reply_text('Usage: /register <zipcode> <dist>')
def zip_code(self, new_zip_code): # Raise TypeError if the provided code is not a valid zip code if zipcodes.is_real(new_zip_code): self._zip_code = new_zip_code else: raise TypeError(f'{new_zip_code} is not a valid zip code')
def get_data_from_zipcode(zipcode): """get data from NYT csv based on a zip-code lookup""" #return -1 if zipcode doesn't exist if not zipcodes.is_real(zipcode): return -1 try: zipcode_result = zipcodes.matching(zipcode) state = states_code_to_full[zipcode_result[0]['state']] county = zipcode_result[0]['county'].replace('County', '').strip() #special case for NYC for NYT data if "New York" in county: county = "New York City" return { 'state': state, 'county': county, 'confirmed': data[data.county == county][data.state == state][['cases']].iat[0, 0], 'deaths': data[data.county == county][data.state == state][['deaths' ]].iat[0, 0], } except: return -1
def get_zip_code(state): """ Validates if zip code is a real US zip code. Uses the package zipcodes to verify if input is a valid U.S Zip Code. See readMe.md for instructions to install the zipcodes package. Searches for the zip code in the State provided, if no zip code is found - prompts for new zip code. Args: state (String): The state provided by the User """ found = False zip_code = input("What is your zipcode?: ").upper().strip() exit_lab(zip_code) state_zip_codes = zipcodes.filter_by(state=state) for state_dict in state_zip_codes: if zip_code == state_dict.get("zip_code"): found = True try: if not zipcodes.is_real(zip_code) or not found: print("Please enter a valid US Zip Code for", state + ".") return get_zip_code(state) except ValueError: print("Please enter a valid US Zip Code for", state + ".") return get_zip_code(state) return zip_code
def checkZip(): """Processes results from the <Gather> prompt in /voice""" # Start our TwiML response resp = VoiceResponse() # If Twilio's request to our app included already gathered digits, # process them if 'Digits' in request.values: # Get which digit the caller chose choice = request.values['Digits'] resp.say("Here is the zipcode you entered:", voice='alice') resp.say(choice[0]) resp.say(choice[1]) resp.say(choice[2]) resp.say(choice[3]) resp.say(choice[4]) # validate zipcode if (zipcodes.is_real(choice)): resp.redirect('/list_places') resp.say("Zip code not valid.", voice='alice') resp.redirect('/answer') return str(resp)
def is_valid_zip5(zip: str): if len(zip) != 5: return False else: try: return zipcodes.is_real(zip) except: return False
def validate_zip_usa(zip): """ Validates a zip code in USA Args: zip code (String): The zip code number to validate in String format Returns: boolean: True if valid, False otherwise. """ return bool(zip and zipcodes.is_real(zip))
def clean_zipcode(self): zipcode = self.cleaned_data['zipcode'][:5] if Location.objects.filter(owner_id=self.owner, zipcode=zipcode).exists(): raise forms.ValidationError( "You already have this zipcode in your list.") elif zipcodes.is_real(zipcode) == False: raise forms.ValidationError("You must enter a real US zipcode.") return zipcode
def _get_zipcode(cls, zipcode: str) -> int: try: if is_real(zipcode): return int(zipcode) except TypeError: pass return cls._random_zip()
def _random_zip() -> int: """ Because what doesn't matter is close food but good food :return: zip_code :rtype: str """ random_zip = 0 while not is_real(str(random_zip)): range_start = 10**4 range_end = (10**5) - 1 random_zip = randint(range_start, range_end) return random_zip
def main(): parser = argparse.ArgumentParser( description="Query Honda's API to find the elusive Clarity.") parser.add_argument('--year', dest='year', action='store', default="2020", help='set the model year to look for') args = parser.parse_args() modelyear = args.year found = {} dealer_filename = "{}_clarity_dealers.txt".format(modelyear) zips_matches_filename = "{}_clarity_zips_matches.txt".format(modelyear) with open(dealer_filename, 'a+') as f: with open(zips_matches_filename, 'a+') as matches: for i in range(1, 100000, 1): #for i in range(7700, 7735, 1): zipcode = str(i).zfill(5) if zipcodes.is_real(zipcode): url = "https://automobiles.honda.com/platform/api/v3/inventoryAndDealers?productDivisionCode=A&modelYear={}&modelGroup=clarity-plug-in-hybrid&zipCode={}&maxDealers=5&showOnlineRetailingURL=false&preferredDealerId=".format( modelyear, zipcode) #print(url) #print(zipcode) r = requests.get(url) if r.status_code != 200: #print("[*] not zip: {}, status: {}".format(zipcode,r.status_code)) continue else: #print("[*] found zip: {}, status: {}".format(zipcode,r.status_code)) pass inv_cnt = len(r.json()['inventory']) if inv_cnt > 0: for n in r.json()['inventory']: dealer_num = n['DealerNumber'] for d in r.json()['dealers']: if d['DealerNumber'] == dealer_num: dealername = d['Name'] dealer_zip_four = d['ZipCode'] save_str = "dealer_zip: {}; dealer: {}, city: {}, state: {}, web: {}, count: {}".format( dealer_zip_four, dealername, d['City'], d['State'], d['WebAddress'], inv_cnt) if dealer_zip_four not in found.keys(): # we'll miss any dealers where there are two in # the same zip+4. this should be minimal found[dealer_zip_four] = save_str f.write('%s\n' % save_str) print("match: {}".format(save_str)) matches.write("%s\n" % zipcode)
def getIncomeZipcodes(): income_zipcodes = [] client = MongoClient(mongodb_atlas_connection) db = client['income'] collection = db['zipcode'] for document in collection.find(): zipcode = document['zip'] print("GOT ZIPCODE", zipcode) if len(zipcode) > 0 and zipcode.isnumeric() and zipcodes.is_real( str(zipcode)): income_zipcodes.append(zipcode) client.close() return income_zipcodes
def check_is_zip(df, column_name): nulls = 0 for val in df[column_name]: if val is not None and not is_nan(val): try: if type(val) is not str: val = str(int(val)) res = zipcodes.is_real(val) if not res: return False except: return False else: nulls += 1 if nulls != df.shape[0]: return True return False
def check_zip(wi, zp, mframe, r, btr): try: if 10000 <= int(zp) <= 99999: if zipcodes.is_real(zp): wi.set_state(zipcodes.matching(zp)[0]['state']) fin = open("user_zip_codes.txt", 'r') lines = list(dict.fromkeys(fin.readlines())) fin.close() f = open("user_zip_codes.txt", "a") f.write(zp + "\n") f.close() found = bool(False) for i in range(len(lines)): if lines[i].strip() == zp.strip(): found = bool(True) print(found) print("OUt of loop bool " + str(found)) if not found: print("in iff statement") new_cities[zp] = Label(mframe, text=zp).grid(row=r + 2, column=1) new_buttons[zp] = tkinter.Button( mframe, text="View", command=lambda t=int(zp): grab_weather(wi, t)) new_buttons[zp].grid(row=r + 2, column=2) r += 1 btr += 1 grab_weather(wi, zp) else: messagebox.showinfo("Zip Code does not exist") else: messagebox.showinfo("Invalid Zip Code, Must be in ##### format") except ValueError: messagebox.showinfo("Invalid Zip Code, Must be in ##### format") except TypeError: messagebox.showinfo("Invalid Zip Code, Must be in ##### format")
def zipcode_num_to_string(zipcode): """ Attempts to standardize a string/integer/float that contains a U.S. zipcode. Front-pads with zeroes and uses the \ :py:mod:`zipcodes` library to ensure that the zipcode is real. If the zipcode doesn't validate successfully, \ ``None`` will be returned. :param zip: Object that contains a sequence of digits (string, integer, float) :type zip: str or float or int :return: A 5-digit string, or None :rtype: str or NoneType Usage:: from pewtils import zipcode_num_to_string >>> zipcode_number = 6463 >>> zipcode_num_to_string(zipcode_number) '06463' >>> not_zipcode_number = 345678 >>> zipcode_num_to_string(not_zipcode_number) >>> """ if is_not_null(zipcode): try: zipcode = str(int(str(zipcode).strip()[:5].split(".")[0])) except (TypeError, ValueError): zipcode = None if zipcode: zipcode = zipcode.zfill(5) if zipcodes.is_real(zipcode): return zipcode else: return None else: zipcode = None return zipcode
def validate(self, document): """Validates zipcodes Args: document: User input to questionary prompt References: Zipcodes: https://pypi.org/project/zipcodes/ Returns: True if user zipcode is valid number with len=5 and according to zipcodes package """ ok = False if document.text.isdigit() and len(document.text) == 5: # Only take non-Hawaii and non-Alaska zipcodes ok = zipcodes.is_real(document.text) and \ (zipcodes.matching(document.text)[0]['state'] != 'HI') and \ (zipcodes.matching(document.text)[0]['state'] != 'AK') if not ok: raise ValidationError( message='Please enter a valid zipcode', cursor_position=len(document.text)) # Move cursor to end
def zipValidation(zipCode): #print (zipcodes.is_real (zipCode)) return zipcodes.is_real(str(zipCode))
def get_avg_temperature(request): sum, count, latitude, longitude = 0, 0, 0, 0 # global sum and count for calculating avg # Validate lat/lon value with Google Maps API #Google Map API_key gmKey = 'AIzaSyBppiO9jO5ZvtF9EzNPZh4OEr_wmfaTS1s' #Google Map API url gmUrl = 'https://maps.googleapis.com/maps/api/geocode/json' # Set response content-type as json headers = {'content-type': 'application/json'} try: #check if zipcode was provided #if yes, then get latitude and longitude from zipcode if ('zipcode' in request.GET): zipcode = request.GET.get('zipcode') #check if zipcode is real or not #if not throw error if (not zipcodes.is_real(zipcode)): data = build_error('Invalid Zipcode Provided') return HttpResponse(json.dumps(data), headers, status=400) #retrieve latitude and longitude values zipcode_data = zipcodes.matching(zipcode) #append query parameters zipcode and api key gmZipcodeUrl = gmUrl + '?address=' + zipcode + '&key=' + gmKey #connect to Google Maps url and get json response api_response_dict = requests.get(url=gmZipcodeUrl).json() latitude, longitude = float( api_response_dict['results'][0]['geometry']['location']['lat'] ), float( api_response_dict['results'][0]['geometry']['location']['lat']) #else just retrieve longitude and latitude value from the request params else: # latitude, longitude = float(request.GET.get('latitude')), float(request.GET.get('longitude')) latitude, longitude = request.GET.get('latitude'), request.GET.get( 'longitude') #append query parameters lat and lon to url gmValidationUrl = gmUrl + '?latlng=' + str(latitude) + ',' + str( longitude) + '&key=' + gmKey #connect to Google Maps url and get json response is_valid_latlon = requests.get(url=gmValidationUrl).json() # if error message in response, then throw error for invalid lat/long values if 'error_message' in json.dumps(is_valid_latlon): data = build_error( 'Latitude and Longitude params should be valid float values' ) return HttpResponse(json.dumps(data), headers, status=400) # if zipcodes is not fully 4 digit code, throw ValueError Exception except ValueError: data = build_error('Invalid Zipcode Provided') return HttpResponse(json.dumps(data), headers, status=400) #throw general exception message for any other error except: data = build_error( 'Latitude and Longitude params should be valid float values') return HttpResponse(json.dumps(data), headers, status=400) # Get list of filters from query params filters = request.GET.getlist('filters') # check if filters are provided, if not send back error response if not filters: data = build_error('Please enter valid filters') return HttpResponse(json.dumps(data), headers, status=400) # else iterate over filters and call following flask api service else: for service in filters: #if service is for noaa if 'noaa' == service: url = 'http://127.0.0.1:5000/noaa?latlon=' + str( latitude) + ',' + str(longitude) url_data = get_json(url) sum += int(url_data['today']['current']['fahrenheit']) count += 1 #if service is for accuweather elif 'accuweather' == service: url = 'http://127.0.0.1:5000/accuweather?latitude=' + str( latitude) + '&longitude=' + str(longitude) url_data = get_json(url) sum += int(url_data['simpleforecast']['forecastday'][0] ['current']['fahrenheit']) count += 1 #if service is for weather.com elif 'weather.com' == service: url = 'http://127.0.0.1:5000/weatherdotcom' params = json.dumps({"lat": latitude, "lon": longitude}) headers = {'content-type': 'application/json'} url_data = post_json(url, params, headers) sum += int(url_data['query']['results']['channel']['condition'] ['temp']) count += 1 # if count is 0, then no valid filters were provided that match our flask service if count == 0: data = build_error('Please send valid filters') return HttpResponse(json.dumps(data), headers, status=400) # else calculate avg of total temperature calculated else: data = {} data['avg_current_temperature'] = float(sum / count) # send the Httpresponse back return HttpResponse(json.dumps(data), headers)
def test_is_real(self): self.assertTrue(zipcodes.is_real("06469")) self.assertFalse(zipcodes.is_real("06463")) with self.assertRaises(TypeError): zipcodes.is_real(None)
def validate_zip(zip_code: str): try: return is_real(zip_code) except ValueError: return False
def validate_batch(df): """Validates input in CSV. Please see module documentation for valid input. Args: df (pandas dataframe obj): Pandas dataframe that must contain service_type Returns: True if batch passes validation """ print("Validating input...") fedex_services_dict = joblib.load(paths.fedex_service_types_to_time_window) ups_services_dict = joblib.load(paths.ups_service_types_to_time_window) all_ok = True for row in df.itertuples(): # Validate da1te input try: datetime.datetime.strptime(row.shipment_date, '%Y-%m-%d') except ValueError: print( f"Found incorrect date input `{row.shipment_date}` in row {row.Index}. Please make sure dates are in YYYY-MM-DD format before trying again." ) all_ok = False # Validate zip codes ok = False if row.sender_zip.isdigit() and len(row.sender_zip) == 5: ok = zipcodes.is_real(row.sender_zip) and \ (zipcodes.matching(row.sender_zip)[0]['state'] != 'HI') and \ (zipcodes.matching(row.sender_zip)[0]['state'] != 'AK') if not ok: print( f"Found invalid sender zipcode `{row.sender_zip}` in row {row.Index}.\nPlease amend zipcode before trying again." ) all_ok = False # Validate zip codes ok = False if row.recipient_zip.isdigit() and len(row.recipient_zip) == 5: ok = zipcodes.is_real(row.recipient_zip) if not ok: print( f"Found invalid sender zipcode `{row.recipient_zip}` in row {row.Index}. Please amend zipcode before trying again." ) all_ok = False # Validate weight try: weight = float(row.weight) except ValueError: print( f"Found invalid weight `{row.weight}` in row {row.Index}. Please amend weight before trying again." ) all_ok = False # Validate shipper ok = False if row.shipper.lower() in ['fedex', 'ups']: ok = True if ok == False: print( f"Found invalid shipper `{row.shipper}` in row {row.Index}. Model only takes fedex and ups now. Please amend shipper before trying again." ) all_ok = False # Validate service_type ok = False if row.shipper.lower() in ['fedex']: if row.service_type.lower() in list(fedex_services_dict.keys()): ok = True elif row.shipper.lower() in ['ups']: if row.service_type.lower() in list(ups_services_dict.keys()): ok = True if ok == False: print( f"Found invalid service type `{row.service_type}` in row {row.Index}. Please amend service type before trying again." ) all_ok = False # Validate zone ok = False try: if int(row.zone) in range(2, 9): ok = True if not ok: print( f"Found invalid zone `{row.zone}` in row {row.Index}. ", "Model only takes zones between 2 and 8. Please amend zone before trying again." ) except ValueError: print(f"Zone must be a number") all_ok = False return all_ok """Combines all preprocessing functions. Invoked by main.
def index_or_create(request): # Shelter - index view # Shows an index of all shelters if request.method == 'GET': # Get data from the get request try: zip_code = request.GET['zip'][:5] except KeyError: zip_code = '36830' # temporary, eventually we will use the user's last queried zip try: radius = request.GET['radius'] except KeyError: radius = 10 # Scrub data # Scrub zip # If the zip code is empty, return the splash page with an error # message if not zip_code: messages.error(request, 'Invalid ZIP. Please try again.') return redirect('shelterme:splash') # If the zip code is not in a valid form or real, return the splash # page with an error message try: if not is_real(zip_code): messages.error(request, 'Invalid ZIP. Please try again.') return redirect('shelterme:splash') except ValueError: messages.error(request, 'Invalid ZIP. Please try again.') return redirect('shelterme:splash') # Scrub radius if not radius: radius = 10 else: try: radius = int(radius) except ValueError: messages.error(request, 'Invalid radius. Please try again.') return redirect('shelterme:splash') if radius < 1 or radius > 50: messages.error( request, 'Radius can\'t be less than 1 or greater than 50. \ Please try again.') return redirect('shelterme:splash') # Retrieve list of locations within radius of zip locs = get_locations_within_radius(zip_code, radius) # Retrieve locations from the db locations = [] for loc in locs: tmp_loc = Location.objects.filter(city=loc['city'], state=loc['state']) if tmp_loc: locations.append(tmp_loc[0]) if not locations: messages.error( request, 'We don\'t have your location in our database. \ Sorry!') return redirect('shelterme:splash') # Render template with all of the location's shelter data return render(request, 'shelterme/index.html', {'locations': locations}) # Shelter -- create view # Creates a new shelter with data from the new view form elif request.method == 'POST': # NEXT # TODO Authentication # Get data from post form to create a new shelter name = request.POST['shelter_name'] street_addr = request.POST['street_address'] city = request.POST['city'] city = city[0].upper() + city[1:len(city)].lower() state = request.POST['state'] state = state.upper() zip = request.POST['zip_code'] max_cap = request.POST['max_capacity'] photourl = request.POST['photourl'] # Retrieve location from the db try: loc = get_object_or_404(Location, city=city, state=state) # If the location doesn't exist: except Http404: # If the location is valid: add it to the db if valid_city_state_zip(city, state, zip): loc = Location(city=city, state=state) loc.save() # Else -- the location isn't valid -- return an error message # and redirect to index page else: messages.error( request, 'Unable to locate the location. \ What a shame!') return redirect('splash') # TODO eventually we want to redirect to the index page # of the user's last zip query # Create new shelter shelter = Shelter(name=name, street_addr=street_addr, location=loc, zip=zip, max_capacity=max_cap, current_capacity=0, photo=photourl, owner='User') shelter.save() # Redirect to show page return redirect('shelterme:show', id=shelter.id) # Neither GET nor POST -- return error else: messages.error('This URL only responds to GET and PUT requests.') return redirect('splash')
def is_valid_zip_code(zip_code): try: return zipcodes.is_real(zip_code) except Exception: return False
import zipcodes # Simple zip-code matching. usr_zip = '80232' hospital_cities = {"Denver": 7203453668, "somewhere": 123456789} if (zipcodes.is_real(usr_zip)): myzip = zipcodes.matching(usr_zip) for dictionary in myzip: city = dictionary['city'] if city in hospital_cities: print("calling: " + str(hospital_cities[city])) else: print("Error: no vaccine information available for zip") else: print("Error: invalid zip code")
#We are looking through the user's library scope = 'user-library-read playlist-modify-public' sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope)) #Command line argument is the username and your zipcode if len(sys.argv) > 2: username = sys.argv[1] zipcode = sys.argv[2] else: print("Usage: %s username %s zipcode" % (sys.argv[0],)) sys.exit() # Make sure the user inputted a real zipcode if not zipcodes.is_real(zipcode): print("Usage: You must input a valid zipcode" % (sys.argv[0],)) sys.exit() # Token to authenticate spotify token = util.prompt_for_user_token(username, scope) sp = spotipy.Spotify(auth=token) # Weather App Id WEATHER_APP_ID = environ.get('WEATHER_APP_ID') # Setting up the open weather map api WEATHER_API_BASE_URL = "http://api.openweathermap.org/data" WEATHER_API_VERSION = "2.5"
def main(): # name of this stage, typically a name to reference the assertion # assertion: lambda which returns unittest callable with self's (testcase's) context # predicates: lambda or sequence of lambdas to call and pass to the assertion unittests_schema = [ { "name": "true", "assertion": lambda self: self.assertTrue, "predicates": [ lambda: zipcodes.is_real("06905"), lambda: zipcodes._contains_nondigits("1234a"), # bad length lambda: callable_raise_exc( lambda: zipcodes._clean("000000"), ValueError ), # bad characters lambda: callable_raise_exc( lambda: zipcodes._clean("0000a"), ValueError ), # ensure zips argument works lambda: len( zipcodes.similar_to( "2", zips=zipcodes.filter_by(active=True, city="Windsor") ) ) == 3, ], }, { "name": "false", "assertion": lambda self: self.assertFalse, "predicates": [ lambda: zipcodes.is_real("91239"), # digits and "-" are acceptable lambda: zipcodes._contains_nondigits("12345"), lambda: zipcodes._contains_nondigits("1234-"), ], }, { "name": "equal", "assertion": lambda self: self.assertEqual, "predicates": [ # valid_zipcode_length parameter (lambda: zipcodes._clean("0646", 4), lambda: "0646"), # default behavior (lambda: zipcodes._clean("06469"), lambda: "06469"), (lambda: zipcodes.list_all(), lambda: zipcodes._zips), ( lambda: zipcodes.filter_by(city="Old Saybrook"), lambda: [ { "zip_code": "06475", "zip_code_type": "STANDARD", "active": True, "city": "Old Saybrook", "acceptable_cities": [], "unacceptable_cities": ["Fenwick"], "state": "CT", "county": "Middlesex County", "timezone": "America/New_York", "area_codes": ["860"], "world_region": "NA", "country": "US", "lat": "41.3015", "long": "-72.3879", } ], ), ( lambda: zipcodes.similar_to("1018"), lambda: [ { "acceptable_cities": [], "active": False, "area_codes": ["212"], "city": "New York", "country": "US", "county": "New York County", "lat": "40.71", "long": "-74", "state": "NY", "timezone": "America/New_York", "unacceptable_cities": ["J C Penney"], "world_region": "NA", "zip_code": "10184", "zip_code_type": "UNIQUE", }, { "acceptable_cities": [], "active": True, "area_codes": ["212"], "city": "New York", "country": "US", "county": "New York County", "lat": "40.7143", "long": "-74.0067", "state": "NY", "timezone": "America/New_York", "unacceptable_cities": [], "world_region": "NA", "zip_code": "10185", "zip_code_type": "PO BOX", }, ], ), ( lambda: zipcodes.similar_to("1005"), lambda: [ { "zip_code": "10055", "zip_code_type": "STANDARD", "active": True, "city": "New York", "acceptable_cities": [], "unacceptable_cities": ["Manhattan"], "state": "NY", "county": "New York County", "timezone": "America/New_York", "area_codes": ["212"], "world_region": "NA", "country": "US", "lat": "40.7579", "long": "-73.9743", } ], ), ( lambda: zipcodes.similar_to("10001"), lambda: [ { "zip_code": "10001", "zip_code_type": "STANDARD", "active": True, "city": "New York", "acceptable_cities": [], "unacceptable_cities": [ "Empire State", "G P O", "Greeley Square", "Macys Finance", "Manhattan", ], "state": "NY", "county": "New York County", "timezone": "America/New_York", "area_codes": ["718", "917", "347", "646"], "world_region": "NA", "country": "US", "lat": "40.7508", "long": "-73.9961", } ], ), ], }, ] generate_unittests(unittests_schema) logger.info("Zipcodes version: {}".format(zipcodes.__version__)) unittest.main()