def search(lat, lng, distance): """ Searches the Foursquare API (Max Limit = 50) :param lat: Latitude of the request :param long: Longitude of the request :param distance: Distance to search (meters) :returns: List of retrieved venues """ url = 'https://api.foursquare.com/v2/venues/explore?ll=%s,%s&intent=browse&radius=%s&limit=50&categoryId=%s&client_id=%s&client_secret=%s&v=%s' % ( lat, lng, distance, CATEGORY_ID, CLIENT_ID, CLIENT_SECRET, time.strftime("%Y%m%d")) venue_list = [] try: data = make_request(url) for item in data['response']['groups'][0]['items']: venue = item['venue'] venue_list.append( Business(venue['name'], venue['location']['address'], venue['rating'], venue['ratingSignals'], venue['stats']['checkinsCount'])) except Exception, e: print e
def search(lat, lng, distance): """ Searches the Foursquare API (Max Limit = 50) :param lat: Latitude of the request :param long: Longitude of the request :param distance: Distance to search (meters) :returns: List of retrieved venues """ url = SEARCH_URL.format(lat, lng, distance, CATEGORY_ID, CLIENT_ID, CLIENT_SECRET, time.strftime("%Y%m%d")) venue_list = [] try: data = make_request(url) for item in data['response']['groups'][0]['items']: venue = item['venue'] venue_list.append( Business(venue['name'], venue['location']['address'], venue['rating'], venue['ratingSignals'], venue['stats']['checkinsCount'])) except Exception, e: print e
def split_data(businessfile, reviewfile, number_sets, train_weight): all_sets = {} for i in range(1, number_sets+1): all_sets["train" + str(i)] = {} all_sets["test" + str(i)] = {} with open(businessfile) as rst: for line in rst: jline = json.loads(line) b_id = jline['business_id'] set_num = rd.randint(1, number_sets) isTrain = rd.randint(1, 10) if isTrain > train_weight: dict_type = "test" else: dict_type = "train" dict_temp = {} if (dict_type + str(set_num)) in all_sets.keys(): dict_temp = all_sets[dict_type + str(set_num)] dict_temp[b_id] = Business(jline) all_sets[dict_type + str(set_num)] = dict_temp all_keys = all_sets.keys() with open(reviewfile) as rvw: for line in rvw: jline = json.loads(line) b_id = jline['business_id'] for i_dict in all_keys: if b_id in all_sets[i_dict].keys(): dict_temp = all_sets[i_dict] dict_temp[b_id].add_review(jline) all_sets[i_dict] = dict_temp return all_sets
def test_b_withdraw(self): account2 = Business("kenny", "19920010877490827", "788978742", 25000, 4321) testNewbalance = account2.b_withdraw(2000, 4321) self.assertEqual(testNewbalance, 23000)
def __init__(self, redis, features={}): Generator.__init__(self, redis, features) self.logger = logging.getLogger(__name__) for field in ['contact', 'npc']: if not hasattr(self, field): setattr(self, field, NPC(self.redis)) if not hasattr(self, 'business'): setattr(self, 'business', Business(self.redis)) if not hasattr(self, 'text'): for field in ['hook', 'request']: if hasattr(self, field): self.template = getattr(self, field) + ' ' + self.template for field in ['requirement', 'disclaimer', 'payment']: if hasattr(self, field): self.template = self.template + ' ' + getattr(self, field) self.template = self.template + ' Contact ' + self.contact.name.fullname self.template = self.template + ' at the ' + self.business.name.fullname if hasattr(self, 'detail'): self.template = self.template + ' ' + self.detail self.template += '.' self.text = self.render_template(self.template) self.text = self.render_template(self.text) self.text = self.text[0].capitalize() + self.text[1:]
def search(lat, lng, distance, query): """ Searches the Foursquare API (Max Limit = 50) :param lat: Latitude of the request :param long: Longitude of the request :param distance: Distance to search (meters) :param query: The niche, i.e. restaurants, bars, etc :returns: List of retrieved venues """ url = SEARCH_URL.format(lat, lng, distance, query, F_CLIENT_ID, F_CLIENT_SECRET, time.strftime("%Y%m%d")) venue_list = [] data = requests.get(url).json() for i in range(0, len(data['response']['groups'][0]['items'])): try: item = data['response']['groups'][0]['items'][i] venue = item['venue'] venue_list.append( Business(venue['name'], venue['location']['address'], venue['rating'], venue['ratingSignals'], (venue['location']['lat'], venue['location']['lng']))) except: pass return venue_list
def search(lat, lng, distance): """ Searches the Yelp API (Max Limit = 20) :param lat: Latitude of the request :param long: Longitude of the request :param distance: Distance to search (meters) :returns: List of retrieved businesses """ params = {} params['term'] = 'nightlife,night_club,restaurant' params['ll'] = '{},{}'.format(lat, lng) params['radius_filter'] = distance session = rauth.OAuth1Session(consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET, access_token=TOKEN, access_token_secret=TOKEN_SECRET) request = session.get('https://api.yelp.com/v2/search', params=params) data = request.json() session.close() business_list = [] for business in data['businesses']: business_list.append( Business(business['name'], business['location']['display_address'][0], business['rating'], business['review_count'], 'N/A')) return business_list
def test_login_store2(self): wd = self.wd self.open_home_page(wd) self.login(wd, Credentional(username="******", password="******")) self.add_company( wd, Business(inn="222222222222", ogrn="012345678912345", phone="+71234567799", email="*****@*****.**")) self.logout(wd)
def test_b_transfer(self): account2 = Business("kenny", "19920010877490827", "788978742", 25000, 4321) amount = 30000 self.assertGreater(amount, account2.balance) testamount = account2.b_transfer(30000, 4321) self.assertEqual(testamount, 0) testpassword = account2.b_transfer(4000, 9087) self.assertEqual(testpassword, "")
def defineStatus(self): while True: print 'Aguardando conexao' con, cliente = self.tcpconn.accept() print 'Concetado por', cliente while True: msg = con.recv(1024) if not msg: break print cliente, msg jsonstatus = Business.Business().getStatus(int(msg)) print jsonstatus print 'Finalizando conexao do cliente', cliente con.close() return msg
def getBusinesses(): ret = [] with open("data/edinburgh_restaurants.json") as f: data = f.readlines() data = map(lambda x: x.rstrip(), data) data_json_str = "[" + ','.join(data) + "]" data_df = pd.read_json(data_json_str) for i in range(0, data_df.shape[0]): datai = data_df.iloc[i] b = Business() b.setID(datai["business_id"]) b.setReviewCount(datai["review_count"]) ret.append(b) return ret
def search(lat, lng, distance, query): """ Searches the Yelp API (Max Limit = 20) :param lat: Latitude of the request :param long: Longitude of the request :param distance: Distance to search (meters) :param query: The niche, i.e. restaurants, bars, etc :returns: List of retrieved businesses """ payload = { 'grant_type': 'client_credentials', 'client_id': Y_ID, 'client_secret': Y_S } token = requests.post('https://api.yelp.com/oauth2/token', params=payload).json()["access_token"] headers = {'Authorization': 'Bearer ' + token} params = {} params['term'] = query params['longitude'] = lng params['latitude'] = lat params['radius_filter'] = distance data = requests.get("https://api.yelp.com/v3/businesses/search", params=params, headers=headers).json() business_list = [] for i in range(0, 5): try: business = data['businesses'][i] business_list.append( Business(business['name'], business['location']['display_address'][0], business['rating'], business['review_count'], (business["coordinates"]["latitude"], business["coordinates"]["longitude"]))) except: pass return business_list
def search_place(place_id): """ Searches Google for a specific Place :param id: Google Place ID :returns: Business object """ url = PLACE_URL.format(place_id, G_API_KEY) data = requests.get(url).json() place = data['result'] try: return Business(place['name'], place['formatted_address'].split(',')[0], place['rating'], len(place['reviews']), (place["geometry"]["location"]["lat"], place["geometry"]["location"]["lng"])) except: pass
def get_business_info(query): # create url for API request api_url = "https://maps.googleapis.com/maps/api/place/findplacefromtext/json" response = requests.get(api_url + "?input=" + query + "&inputtype=textquery&key=" + api_key + "&fields=name,formatted_address,place_id") if response.status_code != 200: raise ApiError("An error with status code {} occurred".format( response.status_code)) else: json_response = response.json() # store API info in business object print(json_response) business = Business() # TODO: throw appropriate exception if daily request quota for this API is reached business.name = json_response["candidates"][0]["name"] business.location = json_response["candidates"][0]["formatted_address"] business.place_id = json_response["candidates"][0]["place_id"] return business
def search_place(place_id): """ Searches Google for a specific Place :param id: Google Place ID :returns: Business object """ url = PLACE_URL.format(place_id, GOOGLE_API_KEY) try: data = make_request(url) place = data['result'] return Business(place['name'], place['formatted_address'].split(',')[0], place['rating'], place['user_ratings_total'], 'N/A') except Exception, e: print e
def __init__(self, redis, features={}): Generator.__init__(self, redis, features) self.logger = logging.getLogger(__name__) if not hasattr(self, 'region'): print "noregion!!!" self.region = region.Region(self.redis) self.gatheringplace = Business(self.redis, {'kind': 'bus_' + self.gatheringplace}) if not hasattr(self, 'leader'): self.leader = leader.Leader(self.redis, {"location": self}) #self.leader = Leader(self.redis) if not hasattr(self, 'name'): self.name = Name(self.redis, 'city') self.citizen = NPC(self.redis) self.calculate_population() self.calculate_racial_breakdown() self.select_subraces()
def Connect(self): # configure how many client the server can listen simultaneously print("server is started and listening on port >>>>>>>>", self.port) self.server_socket.listen(5) conn, address = self.server_socket.accept() print("Connection from: " + str(address)) while True: print("Looping while loop") data = conn.recv(1024).decode() if not data: # if data is not received break break print("Country Selected : ", data) scrape = Scrape() scrape.data_list() business = Business() country_data = business.countryData(data) print(type(country_data)) msg = pickle.dumps(country_data) print("done pickling") conn.send(msg) print("DATA SENT TO THE CLIENT.... ")
from business import Business import json # token=Login().login() #Bearer #token='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvaG90Zml4LnNodWl4aW9uZ2tlamkubmV0XC9hcHBcL0xvZ2luQnlINSIsImlhdCI6MTU1OTIxNzM5NSwiZXhwIjoxNTU5MjE3OTk1LCJuYmYiOjE1NTkyMTczOTUsImp0aSI6ImtZYTQ0bWdYTk45bHJEYnAiLCJzdWIiOjQwOTA3LCJwcnYiOiI2ZDliZGYzYTkwNTc2YTdhNjJmOGNjNWQyYzViYjZmOGVhY2FkODE3IiwiaWQiOjQwOTA3LCJyb2xlIjoiVVNFUiIsImlzX3VzZXIiOnRydWUsInJvbGVfaWQiOjAsInJlc2V0X3RpbWUiOiIyMDE5LTA1LTA1IDE2OjE3OjEyIiwib3BlbmlkIjoib0hGWEkxQXgydVBLWWFYWXVqSjZpQlR4elVScyIsInRoaXJkX3BhcnRfaWQiOjEzNTkyNH0.cDc6CXnfCXQ9MOf2hdQbDEA4wI6HjIZ0geNff5BULnA' businesstoken='Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvaG90Zml4LnNodWl4aW9uZ2tlamkubmV0XC9CdXNpbmVzc0F1dGhzIiwiaWF0IjoxNTU5MzA5MDE4LCJleHAiOjE1NjA1MTg2MTgsIm5iZiI6MTU1OTMwOTAxOCwianRpIjoiZmNEaUNkR2JoMEdESlJWYyIsInN1YiI6MzUsInBydiI6IjQ4NTA2NTc3M2QxNTAzNGQ0MjU1YWY2MzQwMzFhNGQyYzQyYTU1NGUiLCJpZCI6MzUsInJvbGUiOiJCVVNJTkVTUyIsImFjY291bnRfaWQiOjM1LCJyZXNldF90aW1lIjpudWxsLCJyb2xlX2lkIjozNSwiaXNfYnVzaW5lc3MiOnRydWUsImJ1c2luZXNzX2lkIjozNX0.oQDaZkrjEo-GmAecinSlfWdk8Vr8QUQ5SECy_IM28fM' # memberinfo=member() # info=memberinfo.userinfo(token) #用户信息 # show=showping() # indexshow=show.indexshowping(token) # shownoe=show.showpinginfo(indexshow[0],token) # print(shownoe) # order=order() # sub_order_id=order.myorder(token)[0] # order_id=order.myorder(token)[1] # bulidorder=order.bulidorder(token) #创建订单 # trade_no=bulidorder[0] #short_no=bulidorder[1] #pyorder=order.payorder(token,trade_no) #余额购买 # qxzhifuorder=order.qxzhifuorder(token,short_no) # 取消已支付订单 # s=order.myorder(token) # s=order.nopayquxiao(token,trade_no) businessadmin=Business() #take=businessadmin.takeshoping(businesstoken,my) # fahuo=businessadmin.fahuo(businesstoken,order_id,sub_order_id) buildshoping=businessadmin.post_products_keyattr(businesstoken)
def getStatus(idsensor): msg = Business.Business().getStatus(idsensor) return msg
else: json_response = response.json() # store API info in business object print(json_response) business = Business() # TODO: throw appropriate exception if daily request quota for this API is reached business.name = json_response["candidates"][0]["name"] business.location = json_response["candidates"][0]["formatted_address"] business.place_id = json_response["candidates"][0]["place_id"] return business # Takes in place_id parameter and returns a URL to the specified place in google maps # "https://www.google.com/maps/search/?api=1&query=Google&query_place_id=ChIJN1t_tDeuEmsRUsoyG83frY4" # Note: Maps URLs have a character limit of 2048 characters # TODO: Add validation for character limit def get_maps_url(place_id): query = "" # temp query, add as param later maps_url = "https://www.google.com/maps/search/?api=1&query=" + query + "&query_place_id=" + place_id return maps_url # Temporary data for testing (since maps API has a daily request quota of about 5) business = Business() business.name = "200 Waterloo Ave" business.location = "200 Waterloo Ave, Guelph, ON N1H 3J5, Canada" business.place_id = "ChIJn_pSxreaK4gRBaqeg1MbXa8" # business = get_business_info("200 Waterloo Ave") print(get_maps_url(business.place_id)) business = get_business_info("") print(business.name + "\n" + business.location + "\n" + business.place_id)
def setUp(self): self.business = Business() self.app = app.test_client()
@author: rafaelbraga ''' import socket from business import Business #from socketserver import SocketServer if __name__ == '__main__': tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) orig = ('', 5000) tcp.bind(orig) tcp.listen(1) tcpconn = tcp while True: print 'Aguardando conexao' con, cliente = tcpconn.accept() print 'Concetado por', cliente while True: msg = con.recv(1024) if not msg: break print cliente, msg jsonstatus = Business.Business().getStatus(int(msg)) print jsonstatus print 'Finalizando conexao do cliente', cliente con.close() #so = SocketServer.SocketServer('', 5000) #msg = so.defineStatus() #print msg
from util import next_weekday # Opening hours for each week day. If not specified, it is considered closed days = [ # Standard days with fixed opening hours Day(Days.MONDAY, [['09:00', '14:00'], ['14:45', '18:00']]), Day(Days.TUESDAY, [['09:00', '14:00'], ['14:45', '18:00']]), Day(Days.WEDNESDAY, [['09:00', '14:00'], ['14:45', '18:00']]), Day(Days.THURSDAY, [['09:00', '14:00'], ['14:45', '18:00']]), Day(Days.FRIDAY, [['09:00', '14:00'], ['14:45', '16:45']]), Day(Days.SATURDAY, [['09:00', '10:00'], ['11:00', '12:00'], ['13:00', '14:00'], ['15:00', '16:45']]), ] # Create a new Business instance business = Business(days) if False: nextDate = business.closest(datetime.datetime(2015, 5, 11, 10, 0)) print nextDate if False: start = datetime.datetime(2015, 5, 11, 10, 0) end = datetime.datetime(2015, 5, 14, 10, 0) dates = business.timeline(start, end, interval=1) print dates # # datetime.datetime(2015, 8, 7) == Friday # Both values in the same day
print(brunch.calculate_bill(['pancakes', 'home fries', 'coffee'])) print(early_bird.calculate_bill( ['salumeria plate', 'mushroom ravioli (vegan)'])) #<-------franchise-------># flagship_store = Franchise("1232 West End Road", [ brunch, early_bird, dinner, kids]) new_installment = Franchise("12 East Mulberry Street", [ brunch, early_bird, dinner, kids]) print(flagship_store) print(new_installment) flagship_store.available_menus(12) new_installment.available_menus(17) #<------business------># basta = Business("Basta Fazoolin' with my Heart", [ flagship_store, new_installment]) arepas_place_menu = { 'arepa pabellon': 7.00, 'pernil arepa': 8.50, 'guayanes arepa': 8.00, 'jamon arepa': 7.50 } arepas_place = Franchise("189 Fitzgerald Avenue", arepas_place_menu) arepa = Business("Take a' Arepa", arepas_place)
import unittest from business import Business # initializing the business account information account2 = Business("kenny", "19920010877490827", "788978742", 25000, 4321) class Testbusiness(unittest.TestCase): # testing if the function b_transfer returns the right things when the password is not right # or when the amount inputted is greater than the balance def test_b_transfer(self): amount = 30000 self.assertGreater(amount, account2.balance) testamount = account2.b_transfer(30000, 4321) self.assertEqual(testamount, 0) testpassword = account2.b_transfer(4000, 9087) self.assertEqual(testpassword, "") # testing if the function b_withdraw return the right New balance when all conditions are met def test_b_withdraw(self): testNewbalance = account2.b_withdraw(2000, 4321) self.assertEqual(testNewbalance, 23000)
def setUp(self): self.bus = Business()
def getStatus(): idsensor = request.args.get("idsensor") idsensor = int(idsensor) msg = Business.Business().getStatus(idsensor) return msg, 200
normal_print_list = [ "business_id", "business_name", "business_rating", "rating" ] for item in summary.items(): if item[0] in normal_print_list: print(str(item[0]) + ": " + str(item[1])) else: print(str(item[0]) + ": ") # for content in item[1]: # print(content) for data in item[1].items(): # print(str(data[0]) + ": " + str(data[1])) print("------------------" + str(data[0]) + "------------------") for data_1 in data[1].items(): if data_1[0] in normal_print_list: print(str(data_1[0]) + ": " + str(data_1[1])) else: review_list = [] for item_1 in data_1[1]: review_list.append(item_1) print( str(data_1[0]) + ": " + "; ".join(review_list)) if __name__ == "__main__": business_module = Business() main()
def test_create_business(self): business = Business() response = business.create_business("andela", "TRM") self.assertEqual(response["message"], "Business created successfully")
import pymongo from app import create_app from persistence_gateway import UserRepository, TemplateRepository import os def __get_env_variable(env_variable_name, default_value): env_variables = os.environ env_variable_value = default_value if env_variable_name in env_variables.keys(): env_variable_value = env_variables[env_variable_name] return env_variable_value secret = __get_env_variable('SPICEBLUE_AUTHORIZATION_SECRET', "secret") authorization = Authorization(secret) default_uri = "mongodb+srv://test:[email protected]/mydatabase?retryWrites=true&w=majority" database_uri = __get_env_variable("SPICEBLUE_CONNECTION_STRING", default_uri) mongo_client = pymongo.MongoClient(database_uri) templates_db = mongo_client["mydatabase"] template_repository = TemplateRepository(templates_db) user_repository = UserRepository(templates_db) template_service = Business(template_repository, authorization, user_repository) app = create_app(template_service) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', port=80)