def test_between(self): assert_true(between(23.4, 20, 40)) assert_true(between(1, 1, 10)) assert_true(between(10, 1, 10)) assert_true(between(230.928, 215, 500)) assert_true(between(17.5, 10, 20)) assert_false(between(1, 2, 4)) assert_false(between(1.12, 1.2, 2)) assert_false(between(100, 1, 99)) assert_false(between(5.99999, 6, 10)) assert_false(between(31, 5, 30))
def ether2ip(find_ether): find_ether = find_ether.upper() netmask = '.'.join( getIP().split('.')[0:3] ) reply = Popen(split('nmap -sP '+netmask+'.1-245'), stdout=PIPE).communicate()[0] for line in reply.split('\n'): if ' scan report ' in line: ip = between(line, '(', ')') elif 'MAC Address:' in line: ether = between(line, ': ', ' ') if ether.upper() == find_ether: return ip return None
def __init__(self, layer_size, prev_layer_size): self.id = id self.n_neurons = layer_size self.bias_val = 1 # this is how you init an array of zeroes based on self.n_neurons # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # input vector self.input = [0] * self.n_neurons # output vector # it's not that bias enters this layer, it exists it # it will be used in next layer but exists in this layer self.output = [0] * (self.n_neurons + use_bias) # first vector is our bias value self.output[0] = self.bias_val # error vector self.error = [0] * self.n_neurons # weight matrix self.weight = make_matrix(prev_layer_size + use_bias, self.n_neurons) for i in range(len(self.weight)): for j in range(len(self.weight[i])): self.weight[i][j] = between(-0.2, 0.2)
def checkForAnyoneNearby(self): edge = [self.current_node, self.next_node] nearbyAgents = [] busyLanes = [] danger = False for agentIndex in self.map.agents: agent = self.map.agents[agentIndex] if agent.current_node in edge and agent.next_node in edge\ and between(agent.distance, self.distance, self.distance+self.NEARBY_LIMIT*self.direction): nearbyAgents.append(agentIndex) if not agent.lane in busyLanes: busyLanes.append(agent.lane) if between(agent.distance, self.distance, self.distance + self.SAFETY_LIMIT * self.direction): danger = True someoneInTheWay = True if self.lane in busyLanes else False return someoneInTheWay, busyLanes, danger
def modify_configuration(): """ Rewrites the Python statements in config.txt so that their execution results in the proper recording format. """ buffer = ask_for("Enter a buffer size (samples): ", int, BUFFER_SIZE) time = ask_for("Enter a file length (seconds): ", float, RECORD_SECONDS) channels = ask_for("Enter number of channels (1 for mono, 2 for stereo): ", int, CHANNELS) devices() src = between(ask_for("Enter the index of the recording source: ", int, SOURCE), 0, p.get_device_count() - 1) samplesize = ask_for("Enter a sample rate (44100, 48000, 96000...): ", int, RATE) # Quote nesting to prevent Python from directly evaluating the response to the prompt. wav_filename = '"{0}"'.format(add_suffix(ask_for("Enter .wav filename of output: ", str), ".wav")) print("Audio output will be saved to " + wav_filename) txt_filename = '"{0}"'.format(add_suffix(ask_for("Enter .txt filename of output: ", str), ".txt")) print("Text output will be saved to " + txt_filename) iterations = between(ask_for("Enter number of iterations (leave blank for infinity): ", int, 2147483647), 1, 2147483647) output = True if txt_filename else False config = open("config.txt", "w") config.write(\ "\ BUFFER_SIZE = {0}\n\ RECORD_SECONDS = {1}\n\ FORMAT = pyaudio.paInt16\n\ CHANNELS = {2}\n\ SOURCE = {3}\n\ RATE = {4}\n\ OUTPUT = {5}\n\ TXT_OUTPUT_FILENAME = {6}\n\ WAVE_OUTPUT_FILENAME = {7}\n\ ITERATIONS = {8}"\ .strip().format(buffer, time, channels, src, samplesize, output, txt_filename, wav_filename, iterations \ ))
def get_term(): """returns the current term""" r = br.open(get_schedule_page_url()) #opens schdule page soup = BeautifulSoup(r) terms = soup.findAll('th', {'class':'scheduleHeader'}, align='center') count = 0 for term in terms: if "(" in term.text: count += 1 date_begin, date_end = utils.between('(', ')', term.text).split('-') string_to_date = lambda string: datetime.strptime(string, '%m/%d/%y') if string_to_date(date_begin) <= datetime.now() <= string_to_date(date_end): return count raise StandardError("Couldn't find current term")
def get_term(): """returns the current term""" r = br.open(get_schedule_page_url()) #opens schdule page soup = BeautifulSoup(r) terms = soup.findAll('th', {'class': 'scheduleHeader'}, align='center') count = 0 for term in terms: if "(" in term.text: count += 1 date_begin, date_end = utils.between('(', ')', term.text).split('-') string_to_date = lambda string: datetime.strptime( string, '%m/%d/%y') if string_to_date(date_begin) <= datetime.now() <= string_to_date( date_end): return count raise StandardError("Couldn't find current term")
def collides(self, x, y): return between(self.x1, x, self.x2) and between(self.y1, y, self.y2)
def query(): """ This is a route for ALL NODES. The client sends a get request to this route, so that the value of a key-value pair is retrieved. """ key = request.form['key'] hash_key = hashing(key) if (key == '*'): # The user wants to GET all key-value pairs from the database, # so we send a request to the BOOTSTRAP server. The BOOTSTRAP # server "knows" each node in the ring network. url_next = "http://" + bootstrap_ip + ":" + str(bootstrap_port) + \ "/bootstrap/queryall" r = requests.get(url_next) return r.text[:-1], 200 if between(hash_key, node.my_id, node.prev_id): # If we are the node that owns the hash key. if key not in node.storage: # The key-value pair doesn't exist in the toy-chord database. response = "Sorry, we don't have that song." status = 404 return response, status if type_replicas == "linearizability": if key not in node.storage: url_next = "http://" + node.next_ip + ":" + str(node.next_port) \ + "/query" data = { 'key' : key } r = requests.post(url_next, data) response = r.text status = r.status_code else: data_to_next = { 'id': node.my_id, 'key': key } url_next = "http://" + node.next_ip + ":" + str(node.next_port) \ + "/query/replicas" print("Submitting the query to the next node.") r = requests.post(url_next, data_to_next) if r.status_code == 418: response = node.storage[key] status = 200 else: response = r.text status = r.status_code elif type_replicas == "eventual consistency": if key not in node.storage: url_next = "http://" + node.next_ip + ":" + str(node.next_port) \ + "/query" data = { 'key': key } r = requests.post(url_next, data) response = r.text status = r.status_code else: response = node.storage[key] status = 200 return response, status
def insert(): """ This is a route for ALL NODES. The client sends POST requests to this route so that new key-value pairs are inserted. In the case of "eventual consistency", the client gets a response to the request after the primary replica of the key-value pair is inserted. The other replicas are inserted by a thread, without blocking the response to the client. """ # Extract the key and value from the data of the 'insert' request. key = request.form['key'] value = request.form['value'] # Hash the key of the inserted key-value pair in order to find the node # that it's owned by. hash_key = hashing(key) if between(hash_key, node.my_id, node.prev_id): # If we are the node that owns this hask key, # we insert the key-value pair in our database. node.storage[key] = value print( "A key-value pair with key: '" + key + "' and hash:", hash_key, "was inserted/updated." ) # If we aren't the only Node in the Ring, we forward the key-value pair # to the next node while decreasing the replication factor by 1. if (node.next_id != node.my_id and K_replicas > 1): if type_replicas == "eventual consistency": # In this case, we start a thread that handles the # forwarding of the key-value pair to the next nodes thread = Thread( target=forward_replicas_to_next_node, args=(key, value, node) ) thread.start() # We don't care if the forwarding of the key-value pair has # completed. We return a response and a status code to the # user. message = "The key-value pair was successfully inserted." status_code = 200 elif type_replicas == "linearizability": # In this case, we wait until the key-value pair is inserted # in the next nodes and then we return a response to the user. message, status_code = forward_replicas_to_next_node( key=key, value=value, node=node ) return message, status_code return "The key-value pair was successfully inserted.", 200 else: # Otherwise, if we don't own the hash key, we forward the data # to the NEXT node. The data will be forwarded by the next nodes # until they reach the node that is responsible for the hash key. url_next = "http://" + node.next_ip + ":" + \ str(node.next_port) + "/insert" data = { 'key': key, 'value': value, } r = requests.post(url_next, data) if r.status_code != 200: message = "Error while retransmitting the key-value pair." print(message) return message, 500 return r.text
def delete(): """ This is a route for ALL NODES. The client sends sequests to this route so that a key-value pair is deleted. In the case of "eventual consistency", the client gets a response to the request after the primary replica of the key-value pair is deleted. The other replicas are deleted by a thread, without blocking the response to the client. """ # Extract the key of the 'delete' request. key = request.form['key'] hash_key = hashing(key) if between(hash_key, node.my_id, node.prev_id): # We are the node that owns that hash key. if (key in node.storage): # Delete the key-value pair from our database. del node.storage[key] print("The key:", key, "was deleted from our database.") response = "The key-value pair was successfully deleted." status = 200 if (node.next_id != node.my_id and K_replicas > 1): if (type_replicas == "eventual consistency"): thread = Thread( target=delete_replicas_in_next_nodes, args=(key, node) ) thread.start() elif type_replicas == "linearizability": response, status = delete_replicas_in_next_nodes( key, node ) else: response = "There isn't such a key-value pair." status = 404 else: # We are NOT the node that owns that hash key. # So we retransmit the request until we find the # node-owner of the key. url_next = "http://" + node.next_ip + ":" + \ str(node.next_port) + "/delete" data = { 'key': key, } r = requests.post(url_next, data) if r.status_code != 200: print("Something went wrong with the request to the next node.") response = r.text status = r.status_code return response, status
def getIP(): output = Popen(['ifconfig'], stdout=PIPE).communicate()[0] print output return between( between(output, 'eth0', '\n\n'), 'inet addr:', ' ' )