def get_segments(self, size=65, quantity=500): seed() imgToCut = Picture.cutMiddleSquare(self.original_image) imgToCheck = Picture.cutMiddleSquare(self.target) imgToCheckBinary = imgToCheck / 255 h, w = imgToCheck.shape segments = [] positive = 0 negative = 0 while positive != quantity or negative != quantity: x = randint(0, w - size) y = randint(0, w - size) value = int(imgToCheckBinary[x][y]) if value and positive != quantity: segments.append( Segment(imgToCut[x:x + size, y:y + size], value)) positive += 1 elif not value and negative != quantity: segments.append( Segment(imgToCut[x:x + size, y:y + size], value)) negative += 1 return segments
def start(self): self.addSegment(Segment(self, 9, 120, "mid")) self.addSegment(Segment(self, 120, 240, "end")) thread.start_new_thread(self.listenToInput, ()) thread.start_new_thread(self.serverSetup, ()) for x in range(0, 240): self.pixels.append(Led(self, x)) self.strip = Adafruit_NeoPixel(240, 18, 800000, 11, False, 255) self.strip.begin() self.strip.show() self.loadSceiptsNew("") #self.loadScripts("./scripts") self.loadPackets("./packets") self.segments[0].setScript(self.scripts[8]) self.strip.setPixelColorRGB(120, 250, 0, 0) self.strip.show() print self.scripts print len(self.scripts) #print("starting..") while self.running: try: self.sleep(1) except KeyboardInterrupt: self.running = False print("Stop running") except: print("Error Caught") raise
def __init__(self): Segment.__init__(self) self.fieldCount = 2 self.id = Element(name="IEA", description="Interchange Control Trailer Code", required=True, minLength=3, maxLength=3, content="") self.fields.append(self.id) self.iea01 = Element(name="IEA01", description="Number of Included Groups", required=True, minLength=1, maxLength=5, content="") self.fields.append(self.iea01) self.iea02 = Element(name="IEA02", description="Interchange Control Number", required=True, minLength=1, maxLength=9, content="") self.fields.append(self.iea02)
def __init__(self): Segment.__init__(self) self.fieldCount = 2 self.element_separator = "|" self.segment_terminator = "\n" self.id = Element(name="MOCK", description="Mock Segment ID", required=True, minLength=2, maxLength=3, content="MCK") self.fields.append(self.id) self.test01 = Element(name="TEST01", description="TEST 01 Segment", required=False, minLength=1, maxLength=4, content="TST1") self.fields.append(self.test01) self.test02 = Element(name="TEST02", description="TEST 02 Segment", required=False, minLength=1, maxLength=4, content="") self.fields.append(self.test02)
def __init__(self): Segment.__init__(self) self.fieldCount = 2 self.id = Element(name="SE", description="Transaction Set Trailer", required=True, minLength=2, maxLength=2, content="SE") self.fields.append(self.id) self.se01 = Element(name="SE01", description="Number of Included Segments", required=True, minLength=1, maxLength=6, content="") self.fields.append(self.se01) self.se02 = Element(name="SE02", description="Transaction Set Control Number", required=True, minLength=4, maxLength=9, content="") self.fields.append(self.se02)
def read_subwindow(self, file_path): """ read a SubWindow from a file all tweets in given file belong to the subwindow """ segments = {} tweet_count = 0 f = open(file_path, 'r') for line in f: line = line.replace('\n', '') if line == '': continue json_tweet = json.loads(line) tweet_count += 1 user_id = json_tweet['user']['id'] retweet_count = json_tweet['retweet_count'] followers_count = json_tweet['user']['followers_count'] segmentation = self.segmenter.tweet_segmentation(json_tweet) tweet_text = ' '.join( list(OrderedDict.fromkeys(segmentation)) ) # because of hashtag_wt, some segments might be multiple in tweet text after joining so remove them tweet_text = ''.join( [c for c in tweet_text if ord(c) < 256] ) # dont know why but some non ascii chars like \u0441='c'still survived segmentation!!! for seg in segmentation: if not seg in segments: new_seg = Segment(seg) new_seg.newsworthiness = self.get_segment_newsworthiness( seg) segments[seg] = new_seg segments[seg].add_tweet(user_id, tweet_text, retweet_count, followers_count) f.close() sw = SubWindow(segments, tweet_count) return sw
def __init__(self): Segment.__init__(self) self.fieldCount = 3 self.id = Element(name="ST", description="Transaction Set Header", required=True, minLength=2, maxLength=2, content="ST") self.fields.append(self.id) self.st01 = Element(name="ST01", description="Transaction Set ID Code", required=True, minLength=3, maxLength=3, content="") self.fields.append(self.st01) self.st02 = Element(name="ST02", description="Transaction Set Control Number", required=True, minLength=4, maxLength=9, content="") self.fields.append(self.st02) self.st03 = Element(name="ST03", description="Implementation Convention Reference", required=False, minLength=1, maxLength=35, content="") self.fields.append(self.st03)
def fill_segment_list(self, board): """ A function to define and record the location of Wriggler segments on a board. """ # check if Wriggler present if not self.segments: print('Error: no Wriggler present!') exit(1) # get location of all Wriggler segments additional_segments = True while additional_segments: next_segment_location = self.segments[ -1].get_next_segment_location(board) next_symbol = board[next_segment_location[0]][ next_segment_location[1]] # create segment object seg = Segment(next_segment_location, next_symbol, Segment.id_counter) # add segment to 'body' self.segments.append(seg) # check if were done if next_symbol.isdigit(): additional_segments = False seg.set_tail() # set other parameters for later use self.length = len(self.segments) self.wriggler_id = self.segments[-1].get_symbol()
def zderzenie(gracze): """ obsługuje zderzenie dwóch graczy :param gracze: słownik :return: None """ posortowani_gracze = sorted(gracze, key=lambda x: gracze[x]["punkty"]) for x, gracz1 in enumerate(posortowani_gracze): for gracz2 in posortowani_gracze[x + 1:]: for seg1 in gracze[gracz1]["segmenty"]: for seg2 in gracze[gracz2]["segmenty"]: glowa1x = gracze[gracz1]["segmenty"][0].x glowa1y = gracze[gracz1]["segmenty"][0].y glowa2x = gracze[gracz2]["segmenty"][0].x glowa2y = gracze[gracz2]["segmenty"][0].y if seg1.x != glowa1x and seg1.y != glowa1y and seg2.x != glowa2x and seg2.y != glowa2y: gr1_x = seg1.x gr1_y = seg1.y gr2_x = seg2.x gr2_y = seg2.y odleglosc = math.sqrt((glowa1x - gr2_x)**2 + (glowa1y - gr2_y)**2) if odleglosc <= seg2.size + seg1.size: gracze[gracz2]["punkty"] = math.sqrt( gracze[gracz2]["punkty"]**2 + gracze[gracz1]["punkty"]** 2) # dodawanie powierzchni gracze[gracz1]["punkty"] = -10 kolor = gracze[gracz1]["segmenty"][0].color x, y = tutaj_ulokuj_gracza(gracze) segmenty = [] for i in range(3): seg = Segment(x, y, R_STARTOWE, kolor) segmenty.append(seg) gracze[gracz1]["segmenty"] = segmenty print(f"[GRA] " + gracze[gracz2]["nazwa"] + " POKONAŁ " + gracze[gracz1]["nazwa"]) odleglosc = math.sqrt((glowa2x - gr1_x)**2 + (glowa2y - gr1_y)**2) if odleglosc <= seg2.size + seg1.size: gracze[gracz1]["punkty"] = math.sqrt( gracze[gracz2]["punkty"]**2 + gracze[gracz1]["punkty"]** 2) # dodawanie powierzchni gracze[gracz2]["punkty"] = -10 kolor = gracze[gracz2]["segmenty"][0].color x, y = tutaj_ulokuj_gracza(gracze) segmenty = [] for i in range(3): seg = Segment(x, y, R_STARTOWE, kolor) segmenty.append(seg) gracze[gracz2]["segmenty"] = segmenty print(f"[GRA] " + gracze[gracz1]["nazwa"] + " POKONAŁ " + gracze[gracz2]["nazwa"])
def receive_segment(self): data, addr = self.recvfrom(MESSAGE_SIZE) data = data.decode() segment = Segment(segment=data) print('received:') segment.print() return segment, addr
def growSnake(self): lastSegment = Segment( self.theSnake[self.len- 1].x, self.theSnake[self.len- 1].y, self.theSnake[self.len- 1].z) lastSegment.moveSegment( self.moveX * -1, self.moveY * -1, self.moveZ * -1) self.theSnake.append(lastSegment) self.len += 1
def generate_random_paths(self): # print("start generating random paths") for path_points in self.pcb_data_object.pcb_path_points: x_actual = path_points[0] y_actual = path_points[1] x_end = path_points[2] y_end = path_points[3] path = Path() last_used_direction = None path_points_connected = False path_segments = random.randint(2, MAX_SEGMENTS) while not path_points_connected: if path_segments > 2: while True: step_direction = random.sample([-2, -1, 1, 2], 1)[0] if last_used_direction is None or last_used_direction != - step_direction: break last_used_direction = step_direction step_length = random.randint(1, self.get_height_or_width_pcb(step_direction)) new_segment = Segment(step_direction, step_length) path.segments.append(new_segment) if step_direction == Direction.NORTH.value: y_actual += step_length if step_direction == Direction.SOUTH.value: y_actual -= step_length if step_direction == Direction.WEST.value: x_actual -= step_length if step_direction == Direction.EAST.value: x_actual += step_length else: if x_actual != x_end: step_length = x_end - x_actual step_direction = numpy.sign(step_length) * 2 # east and west have 2 and -2 x_actual += step_length path.segments.append(Segment(step_direction, abs(step_length))) elif y_actual != y_end: step_length = y_end - y_actual step_direction = numpy.sign(step_length) y_actual += step_length path.segments.append(Segment(step_direction, abs(step_length))) path_segments -= 1 if x_actual == x_end and y_actual == y_end: path_points_connected = True self.paths.append(path)
def __init__(self, x, y): self.x = x self.y = y self.direction = Constants.KEY["UP"] self.stack = [] self.stack.append(self) blackBox = Segment(self.x, self.y + Constants.SEPARATION) blackBox.direction = Constants.KEY["UP"] blackBox.color = "NULL" self.stack.append(blackBox)
def __init__(self): Segment.__init__(self) self.fieldCount = 8 self.id = Element(name="GS", description="Functional Group Header Code", required=True, minLength=2, maxLength=2, content="GS") self.fields.append(self.id) self.gs01 = Element(name="GS01", description="Functional Identifier Code", required=True, minLength=2, maxLength=2, content="") self.fields.append(self.gs01) self.gs02 = Element(name="GS02", description="Application Senders Code", required=True, minLength=2, maxLength=15, content="") self.fields.append(self.gs02) self.gs03 = Element(name="GS03", description="Application Receiver Code", required=True, minLength=2, maxLength=15, content="") self.fields.append(self.gs03) self.gs04 = Element(name="GS04", description="Group Date", required=True, minLength=8, maxLength=8, content="") self.fields.append(self.gs04) self.gs05 = Element(name="GS05", description="Group Time", required=True, minLength=4, maxLength=4, content="") self.fields.append(self.gs05) self.gs06 = Element(name="GS06", description="Group Control Number", required=True, minLength=1, maxLength=9, content="") self.fields.append(self.gs06) self.gs07 = Element(name="GS07", description="Responsible Agency Code", required=True, minLength=1, maxLength=2, content="") self.fields.append(self.gs07) self.gs08 = Element(name="GS08", description="Version Indicator ID Code", required=True, minLength=1, maxLength=12, content="") self.fields.append(self.gs08)
def __init__(self, tube1, tube2, tube3, f, q, q_0, Tol, method): # method 1,2 ---> bvp and ivp self.accuracy = Tol self.eps = 1.e-4 self.method = method # method 1,2 ---> bvp and ivp self.tube1, self.tube2, self.tube3, self.q, self.q_0 = tube1, tube2, tube3, q.astype( float), q_0.astype(float) # position of tubes' base from template (i.e., s=0) self.beta = self.q[0:3] + self.q_0[0:3] self.f = f.astype(float) self.segment = Segment(self.tube1, self.tube2, self.tube3, self.beta) self.span = np.append([0], self.segment.S) self.r_0 = np.array([0, 0, 0]).reshape(3, 1) # initial position of robot self.alpha_1_0 = self.q[3] + self.q_0[ 3] # initial twist angle for tube 1 self.R_0 = np.array( [[np.cos(self.alpha_1_0), -np.sin(self.alpha_1_0), 0], [np.sin(self.alpha_1_0), np.cos(self.alpha_1_0), 0], [0, 0, 1]]) \ .reshape(9, 1) # initial rotation matrix self.alpha_0 = q[3:].reshape(3, 1) + q_0[3:].reshape( 3, 1) - self.alpha_1_0 # initial twist angle for all tubes self.Length = np.empty(0) self.r = np.empty((0, 3)) self.u_z = np.empty((0, 3)) self.alpha = np.empty((0, 3))
def __init__(self): self.root = tk.Tk() self.root.title("Reverse Kinematic") self.can = tk.Canvas(self.root, width=600, height=600, bg="black", highlightthickness=0) self.can.pack() self.root.bind_all("<Escape>", self.quit) self.can.bind('<Motion>', self.handle_mose_motion) self.segment = Segment(300, 300, 100) self.segment.draw(self.can)
def form_wrigglers(board): """ A function for associating segments of a Wriggler with each other. """ wrigglers = [] for i in range(len(Wrigglers.initial_wrigglers_head_locations)): # create wriggler object wrigg = Wrigglers() # grab relevant info segment_location = Wrigglers.initial_wrigglers_head_locations[i][:2] head_symbol = Wrigglers.initial_wrigglers_head_locations[i][2] # create a segment object head_segment = Segment(segment_location, head_symbol, Segment.id_counter, True) Segment.id_counter += 1 # add to wriggler's 'body' wrigg.segments.append(head_segment) # complete the rest of the links wrigg.fill_segment_list(board.get_board()) wrigg.connect_segments() wrigglers.append(wrigg) return wrigglers
def compareIntersectionMethods(): from random import random from time import clock # Initializes 100 random segments in [0,1]x[0,1] segments = [] for i in range(100): x1, y1, x2, y2 = random(), random(), random(), random() segments.append(Segment(x1, y1, x2, y2)) # Initializes 100 random circles of center in [0,1]x[0,1] # and of radius in [0,1] circles = [] for i in range(100): xc, yc, r = random(), random(), random() circles.append(Circle(xc, yc, r)) # Times the old intersection function start = clock() for s in segments: for c in circles: inter = c.oldIntersectionWithSegment(s) old = clock()-start # Times the new intersection function start = clock() for s in segments: for c in circles: inter = c.intersectionWithSegment(s) new = clock()-start print("Computing the intersections between 100 random segments"+ " in [0,1]x[0,1].\n"+ " and 100 random circles in [0,1]x[0,1] of radius at most 1\n" "Old function took {} s\n".format(old)+ "New function took {} s\n".format(new)+ "Speed up : x{}".format(old/new))
def GenerateWordNet(self, wordNetStorage): """ 生成一元词网 :@param wordNetStorage """ charArray = wordNetStorage.charArray # 核心词典查询 searcher = CoreDictionary.trie.getSearcher(charArray, 0) while searcher.next_obj(): s = '' for i in range(searcher.begin, searcher.begin + searcher.length): s += charArray[i] q = Vertex().init2(s, searcher.value, searcher.index) wordNetStorage.add(searcher.begin + 1, q) # 原子分词,保证图连通 vertexes = wordNetStorage.getVertexes() i = 1 while i < len(vertexes): if len(vertexes[i]) == 0: j = i + 1 while j < len(vertexes) - 1: if not len(vertexes[j]) == 0: break j += 1 wordNetStorage.add1( i, Segment.quickAtomSegment(charArray, i - 1, j - 1)) i = j else: i += len(vertexes[i][len(vertexes[i]) - 1].realword)
def jedz(gracze, jedzenie): """ sprawdza czy gracz napotkał jedzenie :param gracze: słownik graczy :param jedzenie: lista jedzenia :return: None """ for gracz in gracze: gr = gracze[gracz] x = gr["segmenty"][0].x y = gr["segmenty"][0].y for kuleczka in jedzenie: kulka_x = kuleczka[0] kulka_y = kuleczka[1] odleglosc = math.sqrt((x - kulka_x)**2 + (y - kulka_y)**2) if (odleglosc <= gr["segmenty"][0].size): gr["punkty"] = gr["punkty"] + 0.5 if gr["punkty"] % 3 == 0: seg = Segment( gr["segmenty"][len(gr["segmenty"]) - 1].x, gr["segmenty"][len(gr["segmenty"]) - 1].y, gr["segmenty"][len(gr["segmenty"]) - 1].size, gr["segmenty"][len(gr["segmenty"]) - 1].color) gr["segmenty"].append(seg) jedzenie.remove(kuleczka)
def send_ack(self, ack_nunmber, dest_addr): if random.randint(0, 100) >= 50: # perda de ACK!! ack = Segment(ack_number=ack_nunmber) self.sendto(ack.segment.encode(), dest_addr) print('ACK', ack_nunmber, 'enviado') else: print('ACK', ack_nunmber, 'perdido')
def __init__(self, x, y, z): self.moveX = 0 self.moveY = 0 self.moveZ = 0 self.len = 1 self.theSnake = [Segment(x, y, z)] self.isAlive = True
def process(self): start = self.data.split(",")[0] end = self.data.split(",")[1] segment = Segment(self.main, start, end, self.getString(self.data.split(",")[2])) self.main.segments.append(segment) thread.start_new_thread(self.main.proccessSegment, (segment, ))
def __init__(self): Segment.__init__(self) self.fieldCount = 2 self.id = Element(name="GE", description="Functional Group Trailer Identifier", required=True, minLength=2, maxLength=2, content="GE") self.fields.append(self.id) self.ge01 = Element(name="GE01", description="Number of Transaction Sets", required=True, minLength=1, maxLength=6, content="") self.fields.append(self.ge01) self.ge02 = Element(name="GE02", description="Group Control Number", required=True, minLength=1, maxLength=9, content="") self.fields.append(self.ge02)
def transmute(self, head_location, board): """ A function that allows a Wriggler object to take control of Wriggler board symbols. """ # Segment(location, symbol, segment_id, head=False, tail=False) head = Segment(head_location[:2], head_location[2], Segment.id_counter, True) self.segments = [head] self.fill_segment_list(board)
def addNewSegment(self): segment = Segment(60) # segment length if (self.previousSegment == 0): segment.startX = self.startX segment.startY = self.startY else: segment.startX = self.previousSegment.endX segment.startY = self.previousSegment.endY segment.setPreviousSegment(self.previousSegment) self.previousSegment = segment self.segments.append(segment)
def bestFit(self, pid): if pid in self.jobs: # keep track of smallest fit smallest = None segment_ref = None # get job to do first fit on job = self.jobs[pid] # get temp variable to hold first segment in linkedlist segment = self.segments # loop all segments in linkedlist while segment is not None: # make sure segment is a hole if int(segment.pid) == 0: # make sure the difference between the spaces is the smallest or not zero # e.g. if you have 25 space in one segment, and 27 in another, and job takes up 24 # 25 - 24 == 1 and 27 - 24 == 3, so the one with smallest difference is the best fit if smallest == None or int(smallest) > ( int(segment.length) - int(job.size)): # must also make sure it is not zero if int(segment.length) - int(job.size) >= 0: # set variables to keep record smallest = (int(segment.length) - int(job.size)) segment_ref = segment # get next reference segment = segment.next #save current hole size for later use size = segment_ref.length # get current segment, change the pid to act as if new segment was added segment_ref.pid = pid # get current segment, change the start to act as if new segment was added # in this case, start can stay the same # segment.start = # get current segment, change the len to act as if new segment was added # the len should be the size of the new job segment_ref.length = int(job.size) # set next segment to be the hole but with the new changes to its space # check if there is even room for another hole at end or not # if (size - segment_ref.length) == 0: # segment_ref.next = None # else: # segment_ref.next = Segment(0, (segment_ref.start + segment_ref.length), (size - segment_ref.length), None) if (size - segment_ref.length) == 0: if (segment_ref.next is not None): temp_seg = segment_ref.next.next else: temp_seg = segment_ref.next segment_ref.next = temp_seg print("DEBUG 6") else: temp_seg = segment_ref.next segment_ref.next = Segment( 0, (segment_ref.start + segment_ref.length), (size - segment_ref.length), temp_seg) self.next_fit_marker = segment_ref.next
def fragment_message(self, msg): segments = [] while len(msg) > 0: if len(msg) < DATA_SIZE: segment = Segment(self.next_seq, data=msg[:(DATA_SIZE - 1)]) else: segment = Segment(self.next_seq, last_frag='0', data=msg[:(DATA_SIZE - 1)]) if self.next_seq == 0: self.next_seq = 1 else: self.next_seq = 0 segments.append(segment) msg = msg[DATA_SIZE:] return segments
def __init__(self): Segment.__init__(self) self.fieldCount = 2 self.element_separator = "|" self.segment_terminator = "\n" self.id = Element(name="MOCK", description="Mock Segment ID", required=True, minLength=2, maxLength=3, content="") self.fields.append(self.id) self.test01 = Element(name="TEST01", description="TEST 01 Segment", required=False, minLength=1, maxLength=4, content="TST1") self.fields.append(self.test01) self.test02 = Element(name="TEST02", description="TEST 02 Segment", required=False, minLength=1, maxLength=4, content="") self.fields.append(self.test02)
def __parse_unknown_body(self, segment): if segment: generic_segment = Segment() generic_field_list = segment.split( self.ediDocument.document_configuration.element_separator) self.__parse__unknown_segment(generic_segment, generic_field_list) try: self.current_transaction.transaction_body.append( generic_segment) except AttributeError: pass
class Drawer: def __init__(self): self.root = tk.Tk() self.root.title("Reverse Kinematic") self.can = tk.Canvas(self.root, width=600, height=600, bg="black", highlightthickness=0) self.can.pack() self.root.bind_all("<Escape>", self.quit) self.can.bind('<Motion>', self.handle_mose_motion) self.segment = Segment(300, 300, 100) self.segment.draw(self.can) def run(self): self.root.mainloop() def redraw(self): self.can.delete("all") self.segment.draw(self.can) def handle_mose_motion(self, event): x = event.x y = event.y self.segment.head_to(x, y) self.redraw() def quit(self, event=None): self.root.quit() self.root.destroy()
def transfer_file(filename, des_ip, des_port): global host_ip global host_port global routing_table global MSS global proxy_server_list global packetTracker if (des_ip, des_port) not in routing_table.get_keySet(): print 'Sorry, cannot route to the destination' return fp = open(filename, 'r+b') hop_ip = routing_table.get_edge_through(host_ip, host_port, des_ip, des_port)[0] hop_port = routing_table.get_edge_through(host_ip, host_port, des_ip, des_port)[1] print 'Next hop = ' + hop_ip + ':' + str(hop_port) if (hop_ip, hop_port) in proxy_server_list.keys() and proxy_server_list[(hop_ip, hop_port)]: hop_ip = proxy_server_list[(hop_ip, hop_port)][0] hop_port = proxy_server_list[(hop_ip, hop_port)][1] packetTracker.start(filename) try: data = 'y' count = 1 while data != '': data = fp.read(MSS) segment = Segment(filename, data, host_ip, host_port, des_ip, des_port, count, False) packetTracker.add(segment.read(), hop_ip, hop_port, server_sock) server_sock.sendto(segment.read(), (hop_ip, hop_port)) count += 1 segment = Segment(filename, data, host_ip, host_port, des_ip, des_port, count, True) packetTracker.add(segment.read(), hop_ip, hop_port, server_sock) server_sock.sendto(segment.read(), (hop_ip, hop_port)) finally: fp.close() return
def peucker_reduction(points, error_tolerance): if not points: return None dmax = 0 index = 0 fitting_line = Segment(points[0], points[-1]) i = 1 for point in points[1:-1]: d = fitting_line.distance_to_point(point) if d > dmax: index = i dmax = d i += 1 if dmax > error_tolerance: res1 = peucker_reduction(points[0: index+1], error_tolerance) res2 = peucker_reduction(points[index:], error_tolerance) result = res1[:-1] + res2 else: result = [points[0], points[-1]] return result
def compareDataStructuresPerformance(testPrefix, data_structures, limit): N = 1 times = [] counter = 0 for i in data_structures: times.append([]) counter +=1 for i in range(limit): N = N*10 segments = Segment.readFromFile(data_folder + testPrefix + str(N) + ".txt") index = 0 for data_structure in data_structures: #t = clock() structure = deepcopy(data_structure) result, t = hasIntersectionOnSet(segments, structure) #t = clock() - t times[index].append(t) index = (index + 1)%counter return times
class Envelope(object): def __init__(self): self.header = Segment() self.trailer = Segment() self.body = [] def format_as_edi(self, document_configuration): """ Format the envelope as an EDI string. :param document_configuration: configuration for formatting. :return: document as a string of EDI. """ document = self.header.format_as_edi(document_configuration) document += self.__format_body_as_edi(document_configuration) document += self.trailer.format_as_edi(document_configuration) return document def __format_body_as_edi(self, document_configuration): """ Format the body of the envelope as an EDI string. This calls format_as_edi in all the children. :param document_configuration: configuration for formatting. :return: document as a string of EDI. """ document = "" for item in self.body: document += item.format_as_edi(document_configuration) return document def validate(self, report): """ Performs validation of the envelope and its components. :param report: the validation report to append errors. """ self.header.validate(report) self.__validate_body(report) self.trailer.validate(report) def __validate_body(self, report): """ Validates each of the children of the envelope. :param report: the validation report to append errors. """ for item in self.body: item.validate(report) def number_of_segments(self): return len(self.body)
def __init__(self): self.header = Segment() self.trailer = Segment() self.body = []
def _similar_fonts(self, segment1, segment2): return math.fabs(segment1.font_size - segment2.font_size) < 1.0 and Segment.contains_similar_fonts( segment1, segment2 )
def segment_sentences(): usage = ''' Usage of segment_sentences: python segment_sentences.py [options] [arg] Options and arguments: -d, --debug print the debug information of the segmentation, default is not -f, --file [filename] segment sentences from the specified file -h, --help display this help info and exit -i, --interactive go into interactive mode -o, --out [filename] write the segment result into the specified file -s, --separator specified the separator of the segmentation result -t, --train [filename] use the training set to train the algorithm -v, --version output version info and exit ''' paser = OptionParser(usage) paser.version = 'Version 0.1' paser.add_option('-d', '--debug', action='store_true', dest='debug', help='print the debug information of the segmentation, default is not') paser.add_option('-f', '--file', action='store', dest='file', help='segment sentences from the specified file') paser.add_option('-i', '--interactive', action='store_true', dest='interactive', help='go into interactive mode') paser.add_option('-o', '--out', action='store', dest='out', help='write the segment result into the specified file') paser.add_option('-s', '--separator', action='store', dest='separator', help='specified the separator of the segmentation result') paser.add_option('-t', '--train', action='store', dest='train', help='use the training set to train the algorithm') paser.add_option('-v', '--version', action='store_true', dest='version', help='output version info and exit') seg = Segment() operation, arg = paser.parse_args(sys.argv) if operation.version: # print 'Version info: ', operation.version print paser.version if operation.debug: print 'Debug: ', operation.debug seg.debug = True if operation.separator: print 'Specify the separator: ', operation.separator seg.separator = operation.separator if operation.out: print 'Save the output to file: ', operation.out if operation.interactive: print 'Interactive Mode:' if operation.file: print 'Sentences input from file: ', operation.file if operation.train: print 'Train from file: ', operation.train if operation.train: pro_dic = ProDict(operation.train) print 'Train the algorithm successfully!' elif operation.interactive or operation.file: pro_dic = ProDict() seg.pro_dictionary = pro_dic if operation.interactive: interactive_mode(seg, operation) elif operation.file: print 'Read the input file...' input_file = open(operation.file) sens = input_file.readlines() input_file.close() print 'Start segment the input lines...' results = seg.segment(sens) print 'Segment outcome:' for result in results: print result # write the result to the specified file # print results if operation.out: write_result = open(operation.out, 'aw') for result in results: result = result.encode('utf-8') write_result.write(result) write_result.close()
segmentRectQueue = deque() segSize = snakey.theSnake[0].size # configure pygame window pygame.init() screenSize = width, height screen = pygame.display.set_mode(screenSize, pygame.DOUBLEBUF) screen.fill((255, 255, 255)) backgroundBlit = pygame.Surface((segSize, segSize)) backgroundBlit.fill((255, 255, 255)) pygame.display.set_caption('pySnake by bogu') # make target alive target = Segment( random.randrange(segSize, width - segSize, segSize), random.randrange(segSize, height - segSize, segSize), random.randrange(0, len(colors))) targetRect = makeRectSegment(target) targetSurface = pygame.Surface((targetRect.width, targetRect.height)) targetSurface.fill(colors[target.z]) screen.blit(targetSurface, targetRect) pygame.display.update(targetRect) # make snake recognize human overlord eventManager = KeyboardManager(snakey) # enter game loop while snakey.isAlive: frameStart = time.perf_counter() # check for overlord orders
def get_ortho_sample(image, position, dst): direction = dst - position incx = 1 incy = 1 if direction.x > 0: #-> start_col = int(position.x)+1 end_col = image.width-1 elif direction.x < 0: #<- start_col = int(position.x)-1 end_col = 0 incx = -1 else: start_col = int(position.x) end_col = start_col + 1 #print("cols: ", start_col, end_col) if direction.y > 0: #-> start_row = int(position.y)+1 end_row = image.height-1 #print("start row", start_row) elif direction.y < 0: #<- start_row = int(position.y)-1 end_row = 0 incy = -1 else: start_row= int(position.y) end_row = start_row + 1 ray = Segment(position, dst) intersection = None #print(image.getpixel((398,398))) intersections = [] for j in range(start_row, end_row, incy): for i in range(start_col, end_col, incx): #print("pixel: ", i, j, image.getpixel((i,j))) t = ray.ray_intersection(Segment(Point2D(i, j), Point2D(i+1, j))) if t is not None and (image.getpixel((i,j)) == 0 and image.getpixel((i+1, j)) == 0): #intersections.append(t) return t t = ray.ray_intersection(Segment(Point2D(i+1, j), Point2D(i+1, j+1))) if t is not None and (image.getpixel((i+1,j)) == 0 and image.getpixel((i+1, j+1)) == 0): #intersections.append(t) return t t = ray.ray_intersection(Segment(Point2D(i+1, j+1), Point2D(i, j+1))) if t is not None and (image.getpixel((i+1,j+1)) == 0 and image.getpixel((i, j+1)) == 0): #intersections.append(t) return t t = ray.ray_intersection(Segment(Point2D(i, j+1), Point2D(i, j))) if t is not None and (image.getpixel((i,j+1)) == 0 and image.getpixel((i, j)) == 0): #intersections.append(t) return t # if intersections: # mind = 9999999 # for p in intersections: # d = Point2D.distance(position, p) # if d < mind: # mind = d # intersection = p # return intersection return None
def getsample(image, position, dst): direction = dst - position if direction.x > 0: #-> start_col = int(position.x) end_col = image.width elif direction.x < 0: #<- start_col = 0 end_col = int(position.x) else: start_col = int(position.x) end_col = start_col + 1 if direction.y > 0: #-> start_row = int(position.y) end_row = image.height elif direction.y < 0: #<- start_row = 0 end_row = int(position.y) else: start_row= int(position.y) end_row = start_row + 1 ray = Segment(position, dst) intersection = None #print(image.getpixel((398,398))) intersections = [] for j in range(start_row, end_row-2): for i in range(start_col, end_col-2): #print("pixel: ", i, j)#image.getpixel((i,j))) t = ray.ray_intersection(Segment(Point2D(i, j), Point2D(i+1, j))) if t is not None and (image.getpixel((i,j)) == 0 and image.getpixel((i+1, j)) == 0): intersections.append(t) t = ray.ray_intersection(Segment(Point2D(i+1, j), Point2D(i+1, j+1))) if t is not None and (image.getpixel((i+1,j)) == 0 and image.getpixel((i+1, j+1)) == 0): intersections.append(t) t = ray.ray_intersection(Segment(Point2D(i+1, j+1), Point2D(i, j+1))) if t is not None and (image.getpixel((i+1,j+1)) == 0 and image.getpixel((i, j+1)) == 0): intersections.append(t) t = ray.ray_intersection(Segment(Point2D(i, j+1), Point2D(i, j))) if t is not None and (image.getpixel((i,j+1)) == 0 and image.getpixel((i, j)) == 0): intersections.append(t) if intersections: mind = 9999999 for p in intersections: d = Point2D.distance(position, p) if d < mind: mind = d intersection = p return intersection # t = ray.intersects(Segment(Point2D(i, j), Point2D(i+1, j))) # if t :#and (image.getpixel((i,j)) == 0 and image.getpixel((i+1, j)) == 0): # intersections.append(Point2D(i,j)) # t = ray.intersects(Segment(Point2D(i+1, j), Point2D(i+1, j+1))) # if t :#and (image.getpixel((i+1,j)) == 0 and image.getpixel((i+1, j+1)) == 0): # intersections.append(Point2D(i+1,j)) # t = ray.intersects(Segment(Point2D(i+1, j+1), Point2D(i, j+1))) # if t :#and (image.getpixel((i+1,j+1)) == 0 and image.getpixel((i, j+1)) == 0): # intersections.append(Point2D(i+1,j+1)) # t = ray.intersects(Segment(Point2D(i, j+1), Point2D(i, j))) # if t :#and (image.getpixel((i,j+1)) == 0 and image.getpixel((i, j)) == 0): # intersections.append(Point2D(i,j+1)) # if intersections: # mind = 9999999 # for p in intersections: # d = Point2D.distance(position, p) # if d < mind: # mind = d # intersection = p # return intersection return None
def _parse_text(self, obj=None): if obj is None: obj = self.page for element in obj._objs: if isinstance(element, LTTextBox): for line in element._objs: segment = Segment() segment.page = self.page_num segment.addLine(line) self.segments.append(segment) elif isinstance(element, LTRect) or isinstance(element, LTCurve) or isinstance(element, LTImage): segment = Segment() segment.page = self.page_num segment.addLine(element) self.segments.append(segment) elif isinstance(element, LTFigure): for line in element._objs: if isinstance(line, LTFigure): self._parse_text(line) else: segment = Segment() segment.page = self.page_num segment.addLine(line) self.segments.append(segment)
def __init__(self): Segment.__init__(self) self.fieldCount = 16 self.id = Element(name="ISA", description="Interchange Control Header Code", required=True, minLength=3, maxLength=3, content="ISA") self.fields.append(self.id) self.isa01 = Element(name="ISA01", description="Authorization Information Qualifier", required=True, minLength=2, maxLength=2, content="") self.fields.append(self.isa01) self.isa02 = Element(name="ISA02", description="Authorization Information", required=True, minLength=10, maxLength=10, content="") self.fields.append(self.isa02) self.isa03 = Element(name="ISA03", description="Security Information Qualifier", required=True, minLength=2, maxLength=2, content="") self.fields.append(self.isa03) self.isa04 = Element(name="ISA04", description="Security Information", required=True, minLength=10, maxLength=10, content="") self.fields.append(self.isa04) self.isa05 = Element(name="ISA05", description="Interchange ID Qualifier", required=True, minLength=2, maxLength=2, content="") self.fields.append(self.isa05) self.isa06 = Element(name="ISA06", description="Interchange Sender ID", required=True, minLength=15, maxLength=15, content="") self.fields.append(self.isa06) self.isa07 = Element(name="ISA07", description="Interchange ID Qualifier", required=True, minLength=2, maxLength=2, content="") self.fields.append(self.isa07) self.isa08 = Element(name="ISA08", description="Interchange Receiver ID", required=True, minLength=15, maxLength=15, content="") self.fields.append(self.isa08) self.isa09 = Element(name="ISA09", description="Interchange Date", required=True, minLength=6, maxLength=6, content="") self.fields.append(self.isa09) self.isa10 = Element(name="ISA10", description="Interchange Time", required=True, minLength=4, maxLength=4, content="") self.fields.append(self.isa10) self.isa11 = Element(name="ISA11", description="Interchange Control Standard ID", required=True, minLength=1, maxLength=1, content="") self.fields.append(self.isa11) self.isa12 = Element(name="ISA12", description="Interchange Control Version Number", required=True, minLength=5, maxLength=5, content="") self.fields.append(self.isa12) self.isa13 = Element(name="ISA13", description="Interchange Control Number", required=True, minLength=9, maxLength=9, content="") self.fields.append(self.isa13) self.isa14 = Element(name="ISA14", description="Acknowledgement Requested Flag", required=True, minLength=1, maxLength=1, content="") self.fields.append(self.isa14) self.isa15 = Element(name="ISA15", description="Test Indicator", required=True, minLength=1, maxLength=1, content="") self.fields.append(self.isa15) self.isa16 = Element(name="ISA16", description="Sub-element Separator", required=True, minLength=1, maxLength=1, content="") self.fields.append(self.isa16)
def __init__(self): Segment.__init__(self, INDEX_SEGMENT) self.__nodes = [] self.__data_segment = DataSegment() self.__control_index = ControlIndex()
def __init__(self): Segment.__init__(self, DATA_SEGMENT) self.__data = []