def ModifyAddresses(): conn = dbconn() # retrieve all addresses # addresses = conn.execute_read_query("SELECT * FROM addresses") # address = addresses[0] # retrieve isp plan and occupant # isp = conn.execute_read_query("SELECT * FROM ISPs")[0][0] # occupant = conn.execute_read_query("SELECT * FROM people")[0][0] if request.method == 'POST': address_street = request.form['street'] address_city = request.form['city'] address_state = request.form['state'] address_postal_code = request.form['postal_code'] address_country = request.form['country'] isp = request.form['plan_id'] # hidden ISP Plan occupant = request.form['Occupant'] address = Address(conn) # Address object address.add_address(address_street, address_city, address_state, address_postal_code, address_country, isp, occupant) # addresses = conn.execute_read_query("SELECT * FROM addresses") return redirect("/addresses/list") return render_template('address.html')
def sched(self): d = Config.getSection("Scheduler") if not d == []: #print d while True: sleeptime = None for elem in d: rhythm = eval(elem[1].split("|")[1]) # when has the thread to wake up next time for specific value? tmp = rhythm - round(time.time()) % rhythm if not sleeptime: sleeptime = tmp if sleeptime > tmp: sleeptime = tmp time.sleep(sleeptime) execute = [] for elem in d: rhythm = eval(elem[1].split("|")[1]) if rhythm - round(time.time()) % rhythm == rhythm: execute.append(elem) for elem in execute: addr = Address(elem[1].split("|")[0]) print addr.__str__() print EventEngine.root.getByAddress(addr.__str__()).use()
def Address_tests(): print "+-----------------------------+" print "| Address Tests |" print "+-----------------------------+" # There should be a valid subnet for each valid ip. They should share the same index. If you add more then make sure you add a subnet that works with the ip AT THE SAME INDEX AS EACHOTHER. valid_ip = ["255.255.255.255", "1.1.1.1", "30.25.255.10", "0.0.0.0"] valid_subnets = [ "255.255.255.0/24", "1.1.1.0/31", "30.25.255.0/28", "0.0.0.0/32" ] invalid_ip = ["0.0.0.256", "-1.1.1.1", "1.1.1.1.1", "1000.80.10.2"] invalid_subnets = [] for idx in range(len(valid_ip)): assert (Address.isValidIPv4(valid_ip[idx])) print "[+] Successfully validated IP '{}'".format(valid_ip[idx]) assert (Address.isValidSubnet(valid_subnets[idx])) print "[+] Successfully validated subnet '{}'".format( valid_subnets[idx]) assert (Address.isMemberOfSubnet(valid_ip[idx], valid_subnets[idx])) print "[+] Successfully verified that '{0}' is a member of '{1}'".format( valid_ip[idx], valid_subnets[idx]) for ip in invalid_ip: assert (not Address.isValidIPv4(ip)) print "[+] Successfully caught invalid IP '{}'".format(ip) print "Address Tests Succeeded!"
def run(self): while self.alive: succ = self.node.get_successor() if succ is not None and isinstance(succ, Address) == False: succ = Address.get_address_from_string(succ) if succ is None or succ == self.node.local_address: self.node.fillsuc() succ = self.node.get_successor() if succ is not None and succ != self.node.local_address: succ_pre_q = queryadd(succ, Message.getjson("get_your_pre")) if succ_pre_q is None: self.node.delete_successor() else: succ_pre = Address.get_address_from_string( succ_pre_q["payload"]) if succ_pre is not None: if succ_pre == succ: self.node.notify(succ) else: succ_offset = find_offset(self.node.id, hashadd(succ)) succ_pre_offset = find_offset( self.node.id, hashadd(succ_pre)) if succ_pre_offset > 0 and succ_pre_offset < succ_offset: self.node.update_ith_finger(1, succ_pre) time.sleep(1)
def CNN_Identifier(): unique_words = 1000 word_depth = 500 pdf_to_text('Test_pdf','Test_text') with open(os.path.join(Address(1), r"model_architecture.json"), 'r') as f: model = model_from_json(f.read()) model.load_weights(os.path.join(Address(1), r"model_weights.h5")) with open(os.path.join(Address(1), r"word_list.txt"), "rb") as file: freq = pickle.load(file) ##########################################################DEBUG final_output = [] type_list = ['ADC', 'CDC', 'Opamp', 'LDO', 'PLL', 'SRAM', 'Temperature_Sensor', 'DCDC', 'BDRT', 'counters', 'Digital_Potentiometers', 'DSP', 'IO'] for file in os.listdir(os.path.join(Address(1), r"Test_pdf")): #Ideally this will be using Test_text, but I was having issues raw_test_data = convert(os.path.join(Address(1), r"Test_pdf", file)) clean_test_data = [clean(raw_test_data, word_depth)] test_data = numpy.expand_dims(array_creater(clean_test_data, freq, word_depth), axis = 3) results = model.predict(test_data) final_output.append(type_list[numpy.argmax(results)]) return final_output ########################################################
def loadAddresses( self, filename, overwrite = False ): # Is job in a valid state to upload addresses if not (self._status == JobStatus.New or (self._status != JobStatus.Uploaded and overwrite )): raise Error('Addresses already uploaded for job '+str(self._id)) try: # If already uploaded then reset status, which clears out old addresses Database.beginTransaction() if self._status != JobStatus.New: self.setStatus( JobStatus.New ) self.save(True) reader = self._getReader() reader.load( filename ) for ad in reader.addresses(): Address.createAddress( self, ad, ad.transform() ) # Identify clusters of co-located addresses Database.execute('elc_createAddressClusters', self._id ) # Link to roads, address points, TAs Database.execute('elc_ensureLocationsValid',self._id) Database.execute('elc_refreshJobLinks',self._id) self.setStatus( JobStatus.Working ) self.save() Database.commit() except: Database.rollback() raise
def setUp(self) -> None: self.ur = User() self.ur2 = User() self.ad = Address() self.ad2 = Address() self.dbu = DBTools() self.logic = Logic()
def testInsert(self): adao = AddressDAO() address = Address() address.ip = self.ip address.port = self.port aid = adao.insertOrUpdate(address) assert aid != None, 'error inserting address'
def WorkBook_getArray(self): with open(self.filename) as f: prisonList = list(csv.DictReader(f)) prisonArr = [] print "Reading in data..." count = 0 for prison in prisonList: prisonAddress = Address(prison["facility_address1"], prison["city"], prison["state"], prison["zip"][0:5]) curPrison = Prison(prison["type"], prison["facility_name"], prisonAddress) # Backup address check if the previous check (by street/ # address) failed: searches by prison name if not prisonAddress.hasAddress: prisonAddress.hasAddress = curPrison.Prison_getLocation() if not prisonAddress.hasAddress: sys.stderr.write("Query overflow: Please try again later\n") return None prisonArr.append(curPrison) #Gives status update of reading in the data count += 1 if count % 10 == 0: print "Finished reading in {} prisons...".format(count) print "Finished reading in prisons" self.prisonArr = prisonArr
def feed(self, value, erase_last = True): self.last_value = value new_iter = copy.copy(self.last_iteration) all_types = Locator.get_typemap(value) if self.type == 'unknown' else [self.type] for type in all_types: if type not in new_iter: try: new_iter[type] = [ Address(x, self.mw.process, type) for x in self.mw.mem_search(value, type, start_offset=self.start, end_offset=self.end) ] except struct.error: new_iter[type] = [] else: l = [] for address in new_iter[type]: try: found = self.mw.process.read(address, type) if int(found) == int(value): l.append(Address(address, self.mw.process, type)) except Exception as e: pass new_iter[type] = l if erase_last: del self.last_iteration self.last_iteration = new_iter return new_iter
def update_all_database_addresses(): ref = get_address_firebase() addresses = ref.get() for key, value in addresses.items(): a = Address(value['streetAddress'], 0, 0) a.get_google_geo_location() cur_address_db = ref.child(key) cur_address_db.update({'lat': a.latitude, 'long': a.longitude})
def setUp(self): testlog.debug('Instantiate null address, address.setter list') self._address = Address(user_text) self._address_setters = [ i for i in dict( inspect.getmembers(Address, predicate=inspect.ismethod)) if i[:3] == 'set' ]
def batch(self, text=""): print "executing profile" for address in self.information: addr = Address(address) print addr.__str__() self.root().getByAddress(addr.__str__()).use() print "profile acrivated" return "should have been generated automatically" + self.token
def general(self, string=None): address = Address(self.information) if not self.getParent().arg: print '\n *** sensors - NO-USE- trying to use: ', address , " with: " , self.getParent().arg return EventEngine.root.getByAddress(address.__str__()).use() print '\n *** sensors - USE - trying to use: ', address , 'with : ' , self.getParent().arg string = self.getText(string) return EventEngine.root.getByAddress(address.__str__()).use(self.getParent().arg)
def get_all_database_address(): ref = get_address_firebase() database_addresses = ref.get() addresses = [] for key, value in database_addresses.items(): a = Address(value['streetAddress'], value['lat'], value['long']) a.firebasekey = key addresses.append(a) return addresses
def triggerMotion(self,var): global lastMotion global active lastMotion = time.ctime() print "\n *********** ", lastMotion , " Motion Event Received - State: ", active if active: #print(dir(EventEngine.root)) addr = Address('/Defaults/notification') EventEngine.root.getByAddress(addr.__str__()).use('[openAMI] - Scenario set to : Chillout')
def general(self, string=None): address = Address(self.information) if not string: # return EventEngine.root.getByAddress( return EventEngine.root.getByAddress(address.__str__()).use() string = self.getText(string) return EventEngine.root.getByAddress(address.__str__()).use(string)
def Init(persons=[]): p1 = Person(Name('Alan', 'Turing'), Address('Bletchley Park', 'Bletchley Park')) p2 = Person(Name('Alan', 'Turing'), Address('Cambridge', 'Cambridge')) p3 = Person(Name('Joan', 'Clarke'), Address('Bletchley Park', 'Bletchley Park')) p4 = Person(Name('Joan', 'Clarke'), Address('London', 'London')) p5 = Person(Name('Grace', 'Hopper'), Address('New York', 'New York')) persons.extend((p1, p2, p3, p4, p5)) print('MinRelationLevel:' + str(FindMinRelationLevel(p1, p4, persons)))
def toggle(self, var): global states x = int(var) if states[x]: states[x] = False addr = Address(self.getParent().getAddress() + "/Port" + var + "/OFF") else: states[x] = True addr = Address(self.getParent().getAddress() + "/Port" + var + "/ON") print "\n *** toggled: ", var, " addr: ", addr EventEngine.root.getByAddress(addr.__str__()).use()
def get_addresses_within_location(street_address, dist_limit): comp_addr = Address(street_address, 0, 0) comp_addr.get_google_geo_location() addresses = get_all_database_address() addr_within_limit = [] for address in addresses: dist = float(comp_addr.calc_distance(address)) if dist < float(dist_limit): address.dist = dist addr_within_limit.append(address) addr_within_limit = sorted(addr_within_limit, key=lambda addr: addr.dist) return addr_within_limit
def find(self, id): query = "SELECT * FROM %s WHERE id = %s" % (self.tablename, id) self.cursor.execute(query) rs = self.cursor.fetchall() if not rs: return None address = Address() for row in rs: address.id = row[0] address.ip = row[1] address.port = row[2] return address
def findByIpPort(self, ip, port): query = "SELECT * FROM %s WHERE ip = '%s' AND port = %s" % (self.tablename, ip, port) logging.debug(query) self.cursor.execute(query) rs = self.cursor.fetchall() if not rs: return None address = Address() for row in rs: address.id = row[0] address.ip = row[1] address.port = row[2] return address
def playRandom(self, string=""): address = Address(self.information) data = EventEngine.root.getByAddress(address.__str__()).content.items() print data elem = None if data != []: index = random.randint(0, len(data) - 1) elem = data[index] if elem: print elem elem[1].use()
def ResetDataBase(): # instantiate the connection object conn = dbconn() # reset all tables in the database person_obj = Person(conn) person_obj.reset_table() address_obj = Address(conn) address_obj.reset_table() dataplan_obj = DataPlan(conn) dataplan_obj.reset_table() isp_obj = ISP(conn) isp_obj.reset_table() return redirect(url_for('home'))
def __init__(self, ip_addr, port, connect_to=None, seed=False): Thread.__init__(self) self.local_address = Address(ip_addr, port) self.seed = seed self.id = hashadd(self.local_address) print("\nNode initialized with id {0} at address {1}\n".format( self.id, self.local_address.to_string())) self.set_predecessor(self.local_address) self.init_finger_table() self.listener = Listener(self) self.stabilizer = Stabilize(self) self.finger_fixer = FixFingers(self) self.predecessor_stabilizer = CheckPredecessor(self) self.contact_addr = connect_to self.file = filesList
def join_(self, receiving_node_addr): response = queryadd(receiving_node_addr, Message.getjson("find_succ_for_id", self.id)) if response is not None and response["subject"] == "set_your_succ": self.update_ith_finger( 1, Address.get_address_from_string(response["payload"])) response = queryadd(self.finger_table[1], Message.getjson("get_your_pre")) if response is not None and response["subject"] == "my_pre": self.set_predecessor( Address.get_address_from_string(response["payload"])) self.notify(self.finger_table[1])
def handleMeta(self, info, data): #trace("Point.handleMeta:" + str(info) + " " + str(data)) # FILTER if not info.msg.startswith("meta."): #trace("not a meta message:" + info.msg) return # NOT HANDLED if not (info.msg.endswith(".req") or info.msg.endswith(".ind")): #trace("not a meta request:" + info.msg) return # NOT HANDLED # we only process meta messages for this pointId #trace("filter? us:(" + str(self.addr) + " sender:" + str(info)) if info.dst.pointId == None: return # NOT HANDLED #TODO: If this is a remote, then self.addr is the remote address if not Address.match(self.addr, info.dst): return # NOT HANDLED #trace("filter match Point") # DECODE verb = info.msg[5:-4] # Get the middle verb msgtype = info.msg[-3:] # last 3 always the type self.dispatch(verb, msgtype, info.src, info.dst, data)
def cast(self,adr): '''Casts address from current type to requested address-type, eg AddressFeature -> AddressChange @param adr: Address being converted @type adr: Address @return: Address cast to the self type ''' return Address.clone(adr, self.get())
def simpleHandler(self, d): address = Address("/Defaults/Notification") """a very simple handler for incoming calls, prints to stdout""" if d[1] == 'RING': print 'Incoming call from: %s to: %s' % (d[3], d[4]) EventEngine.root.getByAddress(address.__str__()).use('Incoming call from: %s to: %s' % (d[3], d[4])) elif d[1] == 'CALL': print 'Outgoing call from: %s to: %s via: %s' % (d[4], d[5], d[6]) EventEngine.root.getByAddress(address.__str__()).use('Outgoing call from: %s to: %s via: %s' % (d[4], d[5], d[6])) elif d[1] == 'DISCONNECT': print 'Call ended!' #EventEngine.root.getByAddress(address.__str__()).use('Call ended!') self.log.append("<br/>\n"+d.__str__())
def page_classification(training_folder, testing_folder): path_extracted = Address(1).split("\n") base_dir = path_extracted[0] pages_pdf_dir = p_join( base_dir, 'tmp_pdf') # create a temporary directory to split pages pages_txt_dir = p_join( base_dir, 'tmp_txt') # create a temporary directory to convert into texts if isdir(pages_pdf_dir): rmtree(pages_pdf_dir) if isdir(pages_txt_dir): rmtree(pages_txt_dir) # labels and training directory perfect_label = 'perfect' bad_label = 'bad' perfect_path = [p_join(training_folder, perfect_label), perfect_label] bad_path = [p_join(training_folder, bad_label), bad_label] SOURCES = [perfect_path, bad_path] # crop test pdf into test pages pdf_cropper_for_extraction.pdf_cropper_multiple(testing_folder, pages_pdf_dir) # convert test pages to text page_classification_result = [] for pdf_folder in listdir(pages_pdf_dir): page_pdf = p_join(pages_pdf_dir, pdf_folder) page_text = p_join(pages_txt_dir, pdf_folder) pdf_to_text(page_pdf, page_text) classifier_result = supervised_classifier(SOURCES, page_text) page_classification_result = page_classification_result + classifier_result rmtree(pages_pdf_dir) rmtree(pages_txt_dir) return page_classification_result
def _create(self, nodeName, nodeId=None): # trace("_create") # convenience cache self.meta = self.owner.meta self.nodeName = nodeName if nodeId != None: nodeId = str(nodeId) ownerId = self.meta.getOwnerId(self.owner.ownerName) if ownerId == None: raise ValueError("Owner has not been created") # CREATE NODE if not already created actualNodeId = self.meta.getNodeId(ownerId=None, nodeName=nodeName) if actualNodeId != None: raise ValueError("Node already exists") actualNodeId = self.meta.create(nodeName, nodeId) if actualNodeId == None: raise ValueError("node not created") self.nodeId = actualNodeId self.data = self._makeData(self.owner.databaseId) self.addr = Address(self.owner.ownerId, self.nodeId, databaseId=self.owner.databaseId) self.setState(Node.CREATED) #trace("Node registers listener for handleMeta") #TODO could be more restrictive in registration #i.e. dst=(o), so that filtering is done earlier. anyAddr = Address.EMPTY self.meta.registerListener(None, anyAddr, anyAddr, self.handleMeta)
def page_classification(subject): Path_extracted=Address(1).split("\n") Path_extracted1=Path_extracted[0] #label pages as perfect, good and bad, training set in three folders perfect_label = 'perfect' good_label = 'good' bad_label = 'bad' #pages_path = os.path.join(os.path.join(Path_extracted1, 'All_pages_text'), subject) pages_path = os.path.join(os.path.join(Path_extracted1, 'small_training_set_text'), subject) perfect_path = [os.path.join(pages_path,'perfect'), perfect_label] good_path = [os.path.join(pages_path,'good'), good_label] bad_path = [os.path.join(pages_path,'bad'), bad_label] SOURCES = [perfect_path, good_path, bad_path] #clean up files in test folders pageDir = os.path.join(Path_extracted1, 'Test_pages') textDir = os.path.join(Path_extracted1, 'Test_pages_text') for folder in os.listdir(pageDir): shutil.rmtree(os.path.join(pageDir, folder)) for folder in os.listdir(textDir): shutil.rmtree(os.path.join(textDir, folder)) #crop test pdf into test pages pdfDir = os.path.join(Path_extracted1, 'Test_pdf') pageDir = os.path.join(Path_extracted1, 'Test_pages') pdf_cropper_for_extraction.pdf_cropper_multiple(pdfDir, pageDir) pageDir = os.path.join(Path_extracted1, 'Test_pages') #convert test pages to text for pdf_folder in os.listdir(pageDir): page_pdf = os.path.join('Test_pages', pdf_folder) page_text = os.path.join('Test_pages_text', pdf_folder) pdf_to_text(page_pdf,page_text) page_classifier_result = supervised_classifier_ngram(SOURCES, page_text) print(page_classifier_result)
def __init__(self, customer_id, name, street, number, city, zip, country, age, license_id): self.customer_id = customer_id self.name = name self.address = Address(street, number, city, zip, country) self.age = age self.license_id = license_id
def readAddresses(self, fileName, sheetName): workBook = pyxl.load_workbook(fileName) sheet = workBook.get_sheet_by_name(sheetName) arrAddresses = [] for row in range(2, sheet.max_row + 1): print('*** Address ', row - 1, ': ***') # Address 1 address1 = sheet['A' + str(row)].value print(' - Address 1: ', address1) # Address 2 address2 = sheet['B' + str(row)].value print(' - Address 2: ', address2) # City city = sheet['C' + str(row)].value print(' - City: ', city) # State code stateCode = sheet['D' + str(row)].value print(' - State code: ', stateCode) # State state = sheet['E' + str(row)].value print(' - State: ', state) # Zip code zip = sheet['F' + str(row)].value print(' - Zip: ', zip) addressObj = Address(address1, address2, city, stateCode, state, zip) arrAddresses.append(addressObj) return arrAddresses
def handleMeta(self, info, data): #trace("# Node.handleMeta info=" + str(info) + " data=" + str(data)) # FILTER if not info.msg.startswith("meta."): #trace("not a meta message:" + info.msg) return # NOT HANDLED # we only process meta messages for a (o d.n) address if info.dst.ownerId == None or info.dst.databaseId == None or info.dst.nodeId == None \ or info.dst.pointId != None: #trace("not a Node message") return # NOT HANDLED #trace("myaddr: " + str(self.addr)) #trace("dst:" + str(info.dst)) if not Address.match(self.addr, info.dst): #trace("not for my Node") return # NOT HANDLED #trace("matched for my node") # DECODE verb = info.msg[5:-4] # Get the middle verb msgtype = info.msg[-3:] # last 3 always the type self.dispatch(verb, msgtype, info.src, info.dst, data)
def cast(self, adr): '''Casts address from current type to requested address-type, eg AddressFeature -> AddressChange @param adr: Address being converted @type adr: Address @return: Address cast to the self type ''' return Address.clone(adr, self.get())
def readAddresses(self): filename = 'D:\AutomationTest\Scripts\SertaTA\RealAddresses.xlsx' workBook = pyxl.load_workbook(filename) sheet = workBook.get_sheet_by_name('SERTA') arrAddresses = [] for row in range(2, sheet.max_row + 1): print('*** Address ', row - 1, ': ***') # Address 1 address1 = sheet['A' + str(row)].value print(' - Address 1: ', address1) # Address 2 address2 = sheet['B' + str(row)].value print(' - Address 2: ', address2) # City city = sheet['C' + str(row)].value print(' - City: ', city) # State code stateCode = sheet['D' + str(row)].value print(' - State code: ', stateCode) # State state = sheet['E' + str(row)].value print(' - State: ', state) # Zip code zip = sheet['F' + str(row)].value print(' - Zip: ', zip) addressObj = Address(address1, address2, city, stateCode, state, zip) arrAddresses.append(addressObj) return arrAddresses
def closestprecedfinger(self, search_id): if search_id is None: return search_id_offset = find_offset(self.id, search_id) for i in range(M, 0, -1): ith_finger = self.finger_table[i] if ith_finger is None: continue if isinstance(ith_finger, Address) == False and len(ith_finger) > 10: ith_finger = Address.get_address_from_string(ith_finger) else: continue ith_finger_id = hashadd(ith_finger) ith_finger_offset = find_offset(self.id, ith_finger_id) if ith_finger_offset > 0 and ith_finger_offset < search_id_offset: query = queryadd(ith_finger, Message.getjson("areyoualive")) if query["subject"] == "iamalive": return ith_finger self.finger_table[i] = None return self.local_address
def __init__(self, street, number, zip_code, city, n_rooms, sale_price): # Address.__init__(self, street,number,zip_code,city) # self.addr = addr self.obj_addr = Address(street, number, zip_code, city) self.n_rooms = n_rooms self.sale_price = sale_price
def __init__(self, first=None, last=None, gender=None, phone=None, city=None, country=None, zip_code=None): """ Constructor of PhoneBook class. All parameters are optional :param first: first name of person :type first : str :param last: last name of person :type last : str :param gender: gender(sex) of person. Valid values are M / F :type gender : str :param phone: Phone Number of person. Valid format is xxxx-xxxxxxx :type phone: str :param city: City Person Belongs to :type city: str :param country: Country person belongs to :type country: str :param zip_code: Zip code of the City :type zip_code: str """ self.person = Person(first, last, gender) self.phone = phone self.address = Address(city, country, zip_code)
def __init__(self): # Constructor for Repository class self.__address = {} self.__driver = {} with open("addresses", "r") as file: data = file.read() data = data.split("\n") if len(data) != 1: for address in data: address = address.split(",") self.__address[int(address[0].strip())] = Address( int(address[0].strip()), address[1].strip(), int(address[2].strip()), int(address[3].strip())) with open("drivers", "r") as file: data = file.read() data = data.split("\n") if len(data) != 1: for driver in data: driver = driver.split(",") self.__driver[driver[0].strip()] = Driver( driver[0].strip(), int(driver[1].strip()), int(driver[2].strip()))
def __init__(self, csv_list): # the node are addresses self.nodes = [] # edge two addresses in the distance between them self.edges = [] location1 = 0 location2 = 0 for row in csv_list: name = row[0] street = row[1] city = row[2] state = row[3] zip = row[4] address = Address(street, city, state, zip) self.nodes.append(address) location2 = 0 # distances in the csv file begin here for column in row[5:]: try: edge = Distance(column, self.nodes[location1], self.nodes[location2]) self.edges.append(edge) location2 = location2 + 1 except IndexError: pass continue location1 = location1 + 1
def update_ith_finger(self, pos, address): if isinstance(address, Address) == False and address is not None: address = Address.get_address_from_string(address) if pos == 1: print("Successor for {0} set to id {1}".format( self.id, hashadd(address))) if pos > 0 and pos <= 2**M: self.finger_table[pos] = address
def get_address_from_string(str): if len(str) > 10: split = str.split(":") ip = split[0] port = split[1] return Address(ip, port) else: return None
def __init__(self, **kwargs): self.billing_address = Address() self.drivers_license = DriversLicense() self.ssn = None self.email = None self.profileid = None self.acctid = None self.__dict__.update(kwargs) self._payment_methods = []
def override(self,var): #self.getParent().addContainer("cmd",var,var,None) print "\n ****", self , var global backend backend = var for addr in self.getParent().getAddressList(): a = Address("/"+addr) info = EventEngine.root.getByAddress(a.__str__()).information if "Boxee" in info: repl = "Boxee" elif "Madplay" in info: repl = "Madplay" elif "LastFM" in info: repl = "LastFM" else: pass EventEngine.root.getByAddress(a.__str__()).information = info.replace(repl,var)
def setScenario(self, var): print "\n **** Scenario set to: " , var global scenario if scenario == 'default': newaddr = Address('/Scenarios/'+var+'/toggleState') EventEngine.root.getByAddress(newaddr.__str__()).use() elif var == 'default': oldaddr = Address('/Scenarios/'+scenario+'/toggleState') EventEngine.root.getByAddress(oldaddr.__str__()).use() else: newaddr = Address('/Scenarios/'+var+'/toggleState') EventEngine.root.getByAddress(newaddr.__str__()).use() oldaddr = Address('/Scenarios/'+scenario+'/toggleState') EventEngine.root.getByAddress(oldaddr.__str__()).use() scenario = var
def run(self): while True: #get value from poti val = self.mega.getAdcPortPin(1, 1) val = (val-30)/738.*100 #print str(int(val)), #print self.mega.getPortPin(0, 0), #print self.mega.getPortPin(0, 1), #print self.mega.getPortPin(0, 2) if self.mega.getPortPin(0,0) == 0: self.mega.setPortPin(2,7,1) address = Address("/Defaults/Play") EventEngine.root.getByAddress(address.__str__()).use("http://www.mondayjazz.com/mixes/mj099_now_just_listen_by_dj_blueprint.mp3") time.sleep(.5) if self.mega.getPortPin(0,1) == 0: self.mega.setPortPin(2,7,0) address = Address("/Defaults/Stop") EventEngine.root.getByAddress(address.__str__()).use() time.sleep(.5) if self.mega.getPortPin(0,2) == 0: address = Address("/Defaults/Stop") EventEngine.root.getByAddress(address.__str__()).use() address = Address("/FeedReader/Random") EventEngine.root.getByAddress(address.__str__()).use() time.sleep(.5) #if not str(int(self.lastval)).__eq__(str(int(val))): # print "Default Volume"+str(val)+", "+str(int(self.lastval))+", "+str(int(val)) # address = Address("/Defaults/SetVol") # print EventEngine.root.getByAddress(address.__str__()) # EventEngine.root.getByAddress(address.__str__()).use(val) # self.lastval = val time.sleep(.3)
def setUp(self): testlog.debug('Instantiate null address, address.setter list') self._address = Address(user_text) self._address_setters = [i for i in dict(inspect.getmembers(Address, predicate=inspect.ismethod)) if i[:3]=='set']
def use(self, str=None): address = Address("/Defaults/audioplay") EventEngine.root.getByAddress(address.__str__()).use(self.information)
def play(self, string="http://www.munich-radio.de:8000"): string = self.getText(string) address = Address(Config.audioPlay) EventEngine.root.getByAddress(address.__str__()).use(string)
def stop(self, string=""): string = self.getText(string) address = Address(Config.audioStop) EventEngine.root.getByAddress(address.__str__()).use(string)
class Client(object): def __init__(self, **kwargs): self.billing_address = Address() self.drivers_license = DriversLicense() self.ssn = None self.email = None self.profileid = None self.acctid = None self.__dict__.update(kwargs) self._payment_methods = [] def serialize(self): data = { 'profile':"%s/%s" % (self.profileid, self.acctid) if self.profileid and self.acctid else None, 'ssnl4':self.ssn[-4:] if self.ssn else None, 'email':self.email, 'merchid':Config.MERCHANT_ID, 'defaultacct':'Y', 'profileupdate':'Y', 'account':'0000000000000', } data.update(self.billing_address.serialize()) data.update(self.drivers_license.serialize()) return data def deserialize(self, data): for key, value in data.items(): setattr(self, key, value) return self @property def id(self): return self.profileid @property def payment_methods(self): if len(self._payment_methods) == 0: response = requests.get("%s/profile/%s//%s" % (Config.BASE_URL, self.id, Config.MERCHANT_ID), auth=(Config.USERNAME, Config.PASSWORD)).json() out = [] for account in response: # credit / debit cards need the expiry field in the profile if 'expiry' in account: out.append(CreditCard(**account)) # bank accounts are saved as accttype == ECHK elif account.get('accttype', None) == 'ECHK': out.append(BankAccount(**account)) for account in out: account.client = self self._payment_methods = out return self._payment_methods def add_payment_method(self, method): method.client = self self._payment_methods.append(method) def delete(self): requests.delete("%s/profile/%s//%s" % (Config.BASE_URL, self.id, Config.MERCHANT_ID), auth=(Config.USERNAME, Config.PASSWORD)) def save(self): # need to get own profileid to pass onto payment_methods resp = self.deserialize(requests.put("%s/profile" % (Config.BASE_URL), data=json.dumps(self.serialize()), auth=(Config.USERNAME, Config.PASSWORD), headers=Config.HEADERS['json']).json()) for payment_method in self.payment_methods: payment_method.save() return resp @staticmethod def retrieve(id): response = requests.get("%s/profile/%s//%s" % (Config.BASE_URL, id, Config.MERCHANT_ID), auth=(Config.USERNAME, Config.PASSWORD)).json() for account in response: if account.get('defaultacct') == 'Y': return Client(**account) return None @staticmethod def create(**kwargs): return Client(**kwargs)
def setVol(self, string=""): string = self.getText(string) address = Address(Config.setVol) EventEngine.root.getByAddress(address.__str__()).use(string)
def notify(self, string=""): string = self.getText(string) address = Address(Config.Notification) EventEngine.root.getByAddress(address.__str__()).use(string)
def routePoint(self, endType, pointName, nodeName=None, receive=None): """Find and route one of our bindings to appropriate callbacks""" #trace("Node.routePoint:" + str(self.owner.ownerName) + " " + str(nodeName) + " " + str(pointName)) if nodeName == None: # default to my owner/node nodeAddr = (self.owner.databaseId, self.nodeId) else: # eventually might want to override owner, so this will have to change nodeAddr = self.meta.getNodeAddr(self.owner.ownerId, nodeName) if nodeAddr == None: raise ValueError("Unknown node:" + str(nodeName)) # create the in-memory representation of the Point, LOCAL or REMOTE databaseId = nodeAddr[0] nodeId = nodeAddr[1] pointId = self.meta.getPointId(self.owner.ownerId, nodeId, pointName, databaseId=databaseId) if pointId == None: raise ValueError("Unknown point:" + str(pointName) + " owner:" + str(self.owner.ownerId) + " databaseId:" + str(databaseId) + " nodeId:"+ str(nodeId)) rec = self.meta.getPointRec(self.owner.ownerId, nodeId, pointId, databaseId=databaseId) pointType = rec["pointType"] p = Point.metaRestore(pointType, endType, self.owner.ownerId, nodeId, pointName, pointId, meta=self.meta, data=self.data, databaseId=databaseId) # Route any updates to this Point() through to the user supplied receive function. p.setCallbacks(receive) p.numBindings = 0 # Set up data routing, any messages for this pointId routed to this Point() instance # which ultimately goes to the user supplied receive function. if endType == Point.REMOTE: # receiving end of a follow: REMOTE ONE_TO_MANY src(o d.n p)->dst() #trace(" REMOTE FOLLOW (receiving end of follow)") src = Address(self.addr.ownerId, nodeId, pointId, databaseId=databaseId) #trace(" src:" + str(src)) bindings = self.meta.getBindingsFor(bindType=Point.ONE_TO_MANY, src=src) #trace(" bindings:" + str(bindings)) for b in bindings: src = Address(b["srcOwnerId"], b["srcNodeId"], b["srcPointId"], databaseId=b["srcDatabaseId"]) dst = Address(b["dstOwnerId"], b["dstNodeId"], databaseId=b["dstDatabaseId"]) anyAddr = Address.EMPTY #trace("FOLLOW LISTENER " + str(src) + "=>" + str(dst)) #trace("my addr:" + str(self.addr)) if Address.match(self.addr, dst): #trace(" found my binding") ####TODO, only if dst matches our address, should we register a callback #otherwise we'll get everyone else's registrations too! self.data.registerListener("data.payload", src, anyAddr, p.handleReceive) p.numBindings += 1 else: pass#trace("warning: must be a binding for someone else - ignoring") # sending end of an attach: REMOTE MANY_TO_ONE src(o d.n)->dst(o d.n p) #trace(" REMOTE ATTACH (sending end of attach)") #dst = Address(self.addr.ownerId, self.addr.nodeId, pointId, databaseId=databaseId) #trace(" dst:" + str(dst)) #bindings = self.meta.getBindingsFor(dst=dst, bindType=Point.MANY_TO_ONE) #trace(" bindings:" + str(bindings)) #for b in bindings: # src = Address(b["dstOwnerId"], b["dstNodeId"], b["dstPointId"], b["dstDatabaseId"]) # dst = Address.EMPTY # right for addressing, but wrong for bind table lookup, get too much back??? # #trace("attach sender " + str(src) + "=>" + str(dst)) # # no registrations to do, but would expect a binding # p.numBindings += 1 #if p.numBindings == 0: # raise ValueError("No REMOTE bindings were found in DB for:" + pointName) elif endType == Point.LOCAL: # receiving end of an attach: LOCAL MANY_TO_ONE src(o d.n)->dst(o d.n p) #trace(" LOCAL ATTACH (receiving end of attach)") dst = Address(self.addr.ownerId, self.addr.nodeId, pointId, databaseId=databaseId) #trace(" dst:" + str(dst)) bindings = self.meta.getBindingsFor(dst=dst, bindType=Point.MANY_TO_ONE) #trace(" bindings:" + str(bindings)) for b in bindings: src = Address(b["srcOwnerId"], b["srcNodeId"], databaseId=b["srcDatabaseId"]) dst = Address(b["dstOwnerId"], b["dstNodeId"], b["dstPointId"], databaseId=b["dstDatabaseId"]) #trace("ATTACH LISTENER " + str(src) + "=>" + str(dst)) self.data.registerListener("data.payload", src, dst, p.handleReceive) p.numBindings += 1 # receiving end of an attach: LOCAL MANY_TO_ONE src(o d.n)->dst(o d.n p) #trace(" LOCAL FOLLOW (sending end of follow)") #src = Address(self.owner.ownerId, self.addr.nodeId, pointId, databaseId=self.owner.databaseId) #trace(" src:" + str(src)) #bindings = self.meta.getBindingsFor(bindType=Point.ONE_TO_MANY, src=src) #trace(" bindings:" + str(bindings)) #for b in bindings: # src = Address(b["srcOwnerId"], b["srcNodeId"]) # dst = Address(b["dstOwnerId"], b["dstNodeId"], b["dstPointId"]) ####DATABASEID??? # #trace("FOLLOW SENDER " + str(src) + "=>" + str(dst)) # p.numBindings += 1 #if p.numBindings == 0: # trace("warning: no bindings found in DB for:" + pointName) else: trace("warning: endType was not known:" + str(endType)) raise ValueError("Unknown endType") self.points[pointName] = p return p
class Test_1_AddressTestSetters(unittest.TestCase): def setUp(self): testlog.debug('Instantiate null address, address.setter list') self._address = Address(user_text) self._address_setters = [i for i in dict(inspect.getmembers(Address, predicate=inspect.ismethod)) if i[:3]=='set'] #self._address_setters.remove('setAddressPositions') def tearDown(self): testlog.debug('Destroy null address') self._address = None self._address_setters = None def test10_instSetters(self): '''Tests that all the setters set a matching attribute i.e. setAttribute("X") -> self._Attribute = "X"''' #this no longer works since changing to full path attribute names eg _components_roadName return testlog.debug('Test_1.10 Instantiate all setters') for asttr in self._address_setters: aval = self._generateAttrVal(asttr) aname = self._generateAttrName(asttr) getattr(self._address, asttr)(aval) self.assertEqual(getattr(self._address, aname), aval, 'set* : Setter {} not setting correct attribute value {}'.format(asttr,aval)) #@unittest.skip("Test skipped awaiting finalisation of Address Class structure") def test30_checkPopulatedAddressChangeDict(self): '''Tests whether JSON object gets created correctly''' #this function has moved to addressfactory testlog.debug('Test_1.30 Attributes set to match JSON sample and compare') #return True for asm in self._address_setters: if asm == 'setAddressPositions': getattr(self._address, asm)([Position(),]) continue aval = self._generateAttrVal(asm) getattr(self._address, asm)(aval) self._address.setVersion(100) for at in (ActionType.ADD,ActionType.RETIRE,ActionType.UPDATE): jresult = AddressChangeFactory().convertAddress(self._address,at) self.assertEqual(jresult, getTestData(at), 'JSON Address constructed incorrectly {}'.format(jresult)) def test31_checkAddressDictNullRemoval(self): '''check whether JSON output is truncated correctly on null inputs''' pass def test32_checkAddressDictErrorRaisedOnNull(self): '''Check error raised if attempt to create JSON output on null address array''' pass #------------------------------------------------------------------------------ def _generateAttrVal(self,setmthd): s = self._special(setmthd) if s: return s setmthd = re.match('set_*(.*)',setmthd).group(1) return setmthd[:1].upper()+''.join([s for s in setmthd[1:] if ord(s)>64 and ord(s)<91]) def _generateAttrName(self,setmthd): setmthd = re.match('set_*(.*)',setmthd).group(1) return '_'+setmthd[:1].lower()+setmthd[1:] def _special(self,meth): if meth == 'setObjectType':return 'Parcel' if meth == 'setAddressType':return 'Road' if meth == 'setLifecycle':return 'Current' return
def createAddressFromLandonlineAddress( self, sad_id, status ): adr_id = Address.createFromLandonlineAddress( self, sad_id, status ) return Address( self, adr_id )