def parse_file(self): try: with open(self.flac_file, 'rb') as f: data = f.read() except Exception as exception: sys.exit("Error! {}".format(exception)) pattern = Pattern(self.flac_file, self.output) flac_parser = FlacParser(data, pattern) flac_parser.parse() pattern.write() self.text_edit.setText(pattern.get_output_string())
def enter(): global pattern, bacteria global bullet pattern = Pattern() bacteria = Bacteria() game_world.add_object(pattern, 0) game_world.add_object(bacteria, 1) global background background = Background() game_world.add_object(background, 0)
def console_version(flac_file, output): try: with open(flac_file, 'rb') as f: data = f.read() except Exception as exception: sys.exit("Error! {}".format(exception)) pattern = Pattern(flac_file, output) flac_parser = FlacParser(data, pattern) flac_parser.parse() pattern.write()
def loadPattern(self, file): im = cv2.imread(self.load_directory + file) segments = self.getFinalSegments(im) creases = [] dims = im.shape[:2] for s in segments: c = Crease(s[0], s[1]) creases.append(c) return Pattern(file, dims, creases)
def getNextPattern(self): if self.currentEntry < len(self.entries): bank = int(b2a_hex(self.entries[self.currentEntry][0]), 16) loc = int(b2a_hex(self.entries[self.currentEntry][1]), 16) pattern = Pattern(self.entries[self.currentEntry][2:ENTRY_SIZE]) self.currentEntry += 1 return [bank, loc, pattern] else: raise PatternFileException( 'Attempt to access out of bounds pattern.')
def parsePatterns(self, file): lineno, pat, cont = 0, [], True while cont: str = '' for i in range(9): str += file.readline() lineno += 9 pat.append(Pattern(str)) s = file.readline() if (s.strip().lower() != "or"): lineno += 1 cont = False return [lineno, pat]
def siatechf(d, min_cr): """ SIATECH that only returns TECs that have compression ratio of at least min_cr. """ d = Dataset.sort_ascending(d) # Map of difference vector, index list pairs. mtp_map = {} # Compute the difference vectors between points and add both # the starting and ending index as pair to the lists corresponding to the # difference vector. for i in range(len(d)): for j in range(i + 1, len(d)): diff = d[j] - d[i] if diff in mtp_map: mtp_map[diff].append((i, j)) else: mtp_map[diff] = [(i, j)] tecs = [] handled_patterns = set() for diff_vec in mtp_map: pattern = [] pattern_indices = [] mtp = mtp_map[diff_vec] for index_pair in mtp: pattern_indices.append(index_pair[0]) pattern.append(d[index_pair[0]]) vectorized_pattern = Pattern(vec(pattern)) if vectorized_pattern not in handled_patterns: if cr_upper_bound(pattern, mtp_map, d) >= min_cr: translators = [] if len(pattern) == 1: for point in d: translators.append(point - pattern[0]) else: translators = find_translators_h(pattern, vectorized_pattern, mtp_map, d) tec = TEC(pattern, pattern_indices, translators) if heuristics.compression_ratio(tec) >= min_cr: tecs.append(tec) handled_patterns.add(vectorized_pattern) return tecs
def get_patterns(file_name: str) -> List[Pattern]: patterns = [] with open(file_name, 'r') as file: for line in file: if line == '\n': pass else: patterns.append( Pattern(vuln_type=line.strip('\n'), entries=file.readline().strip('\n').split(','), sanitizers=file.readline().strip('\n').split(','), sinks=file.readline().strip('\n').split(','))) return patterns
def comboChanged(self, text): # First of all clear the board self.clearBoard() patternSetter = Pattern(self.grid) # lookign for pattern class if text == 'Glider': patternSetter.Glider() if text == 'Small Exploder': patternSetter.smallExploder() if text == 'Exploder': patternSetter.exploder() if text == '10 Cell Row': patternSetter.cellRow() if text == 'Tumbler': patternSetter.tumbler()
def _to_location(ps=None, in_region=None, align='top_left'): """Transform pattern or string to location :param ps: Pattern or string input :param in_region: Region object in order to minimize the area :param align: Alignment could be top_left, center :return: Location object """ # TODO: Add multiple alignments if needed # TODO fix this (isinstance str or Pattern) if isinstance(ps, Location): return ps elif isinstance(Pattern(ps), Pattern): location = image_search(Pattern(ps), Settings.MinSimilarity, in_region) if align == 'center': width, height = get_image_size(Pattern(ps)) return Location(location.getX() + width / 2, location.getY() + height / 2) else: return location
def __init__(self, input, function=None, mul=1, add=0): PyoObject.__init__(self, mul, add) self._input = input if callable(function): self._function = getWeakMethodRef(function) else: self._function = None self._in_fader = InputFader(input) in_fader, mul, add, lmax = convertArgsToLists(self._in_fader, mul, add) self._base_objs = [ PeakAmp_base(wrap(in_fader, i), wrap(mul, i), wrap(add, i)) for i in range(lmax) ] sr = self.getSamplingRate() bs = self.getBufferSize() self._timer = Pattern(self._buildList, bs / sr).play()
def __init__(self, input, length=0.05, gain=0.67): PyoObject.__init__(self) self.points = None self.viewFrame = None self._input = input self._length = length self._gain = gain self._width = 500 self._height = 400 self._in_fader = InputFader(input) in_fader, lmax = convertArgsToLists(self._in_fader) self._base_objs = [ Scope_base(wrap(in_fader, i), length) for i in range(lmax) ] self.view() self._timer = Pattern(self.refreshView, length).play()
def hover(where=None, duration=0, in_region=None): """Hover over a Location, Pattern or image :param where: Location, Pattern or image name for hover target :param duration: speed of hovering from current location to target :param in_region: Region object in order to minimize the area :return: None """ if isinstance(where, str) and is_ocr_text(where): a_match = text_search_by(where, True, in_region) if a_match is not None: pyautogui.moveTo(a_match['x'] + a_match['width'] / 2, a_match['y'] + a_match['height'] / 2) else: raise FindError('Unable to find text %s' % where) elif isinstance(where, Location): pyautogui.moveTo(where.x, where.y, duration) elif isinstance(where, str) or isinstance(where, Pattern): try: pattern = Pattern(where) except Exception: pattern = where pos = image_search(pattern, region=in_region) if pos.x != -1: needle_width, needle_height = get_image_size(pattern.getFilename()) if isinstance(where, Pattern): possible_offset = where.getTargetOffset() if possible_offset is not None: move_to = Location(pos.getX() + possible_offset.getX(), pos.getY() + possible_offset.getY()) pyautogui.moveTo(move_to.getX(), move_to.y) else: move_to = Location(pos.x, pos.y) pyautogui.moveTo(move_to.getX() + needle_width / 2, move_to.getY() + needle_height / 2) else: pyautogui.moveTo(pos.x + needle_width / 2, pos.y + needle_height / 2) else: raise FindError('Unable to find image %s' % pattern.getFilename()) else: raise ValueError(INVALID_GENERIC_INPUT)
def __init__( self, uri, path=None, revision=None, remote=None, # pylint: disable=W0613 pattern=None, *args, **kws): self.uri = self._safepath(uri) self.path = self._safepath(path) self.revision = revision self.remote = remote self.source = kws.get('source') or remote self.pattern = pattern or Pattern() self.args = args self.kws = kws
def sendReadPatternMessage(self, bank, loc): self.s.flushInput() self.sendBasicPacket(READ_PATTERN_MSG, content=chr(bank) + chr(loc)) packet = self.getBasicPacket() if packet.isCorrect: packet.printMe() else: packet.printMe() print 'Bad packet!' if packet.isCorrect and packet.messageType() == X0X_PATT_MSG: pat = Pattern(packet.content()) return pat else: print 'Error: Received a bad pattern.' raise BadPacketException('Received a bad pattern.')
def read_pattern(bank_letter, pad_number): hex_data = get_hex_character_row_representation(bank_letter, pad_number) note_list = hex_data[:-2] pattern_length = int(str(hex_data[-1][2] + hex_data[-1][3]), base=16) pattern = Pattern(pattern_length) current_time = 0 for chunk_index, note in enumerate(note_list): #if str(note[2] + note[3]) != '80' or len(pattern.notes) == 0: if str(note[2] + note[3]) != '80': ticks_till_next_note = int(str(note[0] + note[1]), 16) velocity = int(str(note[8] + note[9]), 16) length_ticks = int(str(note[12] + note[13] + note[14] + note[15]), 16) pad, bank = gen_pad_bank(pad_code=str(note[2] + note[3]), bank_switch=note[5]) pattern.add_note(Note(bank=bank, pad=pad, velocity=velocity, length=length_ticks, start_tick=current_time)) current_time += ticks_till_next_note return pattern
def __init__(self, filename=None, fill=False): self.fill = fill # stitches is the stitches that have yet to be added to the pattern self.stitches = [] self.attributes = [] self.all_paths = [] self.fill_color = None self.last_color = None self.last_stitch = None self.pattern = Pattern() if not filename: return self.filecontents = open(join("workspace", filename), "r").read() if filename.split(".")[-1] != "svg": self.image_to_pattern() else: self.svg_to_pattern()
def test_pattern_to_svg(): filename = "test_pattern_to_svg.svg" stitches = [ Stitch(x=0, y=0, tags=["JUMP"]), Stitch(x=0, y=100, tags=["STITCH"]), Stitch(x=100, y=100, tags=["STITCH"]), Stitch(x=100, y=0, tags=["STITCH"]), Stitch(x=0, y=0, tags=["STITCH"]) ] pattern = Pattern() block = Block(stitches=stitches) pattern.add_block(block) pattern_to_svg(pattern, filename=filename) root = parse(filename).getroot() filename2 = "test_pattern_to_svg.csv" pattern_to_csv(pattern, filename=filename2) assert False
def respond_to_key(self, k): GestureClassifier.respond_to_key(self, k) if k == 'w': if self.recording: self.recording = False print "STOPPED RECORDING" name = raw_input("Enter a name for this gesture: ") self.patterns.append(Pattern(name, self.pattern_points)) #print self.patterns[-1].normalize() self.reset() else: print "STARTED RECORDING" self.recording = True self.reset() elif k == 's': if len(self.patterns) > 0: self.write_to_file() return
def siatech(d): d = Dataset.sort_ascending(d) # Map of difference vector, index list pairs. mtp_map = {} # Compute the difference vectors between points and add both # the starting and ending index as pair to the lists corresponding to the # difference vector. for i in range(len(d)): for j in range(i + 1, len(d)): diff = d[j] - d[i] if diff in mtp_map: mtp_map[diff].append((i, j)) else: mtp_map[diff] = [(i, j)] tecs = [] handled_patterns = set() for diff_vec in mtp_map: pattern = [] pattern_indices = [] mtp = mtp_map[diff_vec] for index_pair in mtp: pattern_indices.append(index_pair[0]) pattern.append(d[index_pair[0]]) vectorized_pattern = Pattern(vec(pattern)) if vectorized_pattern not in handled_patterns: translators = [] if len(pattern) == 1: for point in d: translators.append(point - pattern[0]) else: translators = find_translators_h(pattern, vectorized_pattern, mtp_map, d) tecs.append(TEC(pattern, pattern_indices, translators)) handled_patterns.add(vectorized_pattern) return tecs
def boom(self): '''遍历所有的pattern,将5格,4格,3格的情况找出来,返回每种格数每种颜色消除的次数 ''' pt = Pattern() pts_5 = pt.get_by_name("5") pts_4 = pt.get_by_name("4") pts_3 = pt.get_by_name("3") pts_list = [pts_5, pts_4, pts_3] #结果存放每种pattern下,每种颜色消除的次数,作为返回值 cnt_boom = np.zeros((3, 5), np.int) #分格数(5,4,3格),颜色,统计当前消去各多少 for i, pts in enumerate(pts_list): for j, color in enumerate(COLOR): for cnt in self.match(pts, color): pass cnt_boom[i][j] = cnt #print(cnt_boom) return cnt_boom
def load_from(path: str): collection = PatternCollection() with open(path, 'r', encoding='utf8') as csv: next(csv) for line in csv: line = line.strip() parts = line.split(';') tool = None sentiment = None for t in Tool: if parts[0] == t.name: tool = t break for s in Sentiment: if parts[1] == s.name: sentiment = s break change = parts[2] collection.append(Pattern(sentiment, tool, '', change)) return collection
def make_double_leaf_pattern(self): dlp = Pattern('DoubleLeafPattern') dlp.add_row(['p8','p2tog','k1','yo','k1','yo','k1','k1fb','k1''k1fb','k1','yo','k1','yo','k1','p2tog','p8']) dlp.add_row(['k9','p5','k1','p3','k1','p5','p9']) dlp.add_row(['p7','p2tog','k2','yo','k1','yo','k2','p1fb','k3','p1fb','k2','yo','k1','yo','k2','p2tog','p7')] dlp.add_row(['k8','p7','k2','p3','k2','p7','k8']) dlp.add_row(['p6','p2tog','k3','yo','k1','yo','k3','p1fb','p1','k3','p1','p1fb','k3','yo','k1','yo','k3','p2tog','p6']) dlp.add_row(['k7','p9','k3','p3','k3','p9','k7']) dlp.add_row(['p5','p2tog','k4','yo','k1','yo','k4','p1fb','p2','k3','p2','p1fb','k4','yo','k1','yo','k4','p2tog','p5']) dlp.add_row(['k6','p11','k4','p3','k4','p11','k6']) dlp.add_row(['p4','p2tog','ssk','k7','k2tog','p1fb','p3','k3','p3','p1fb','ssk','k7','k2tog','p2tog','p4']) dlp.add_row(['k5','p9','k5','p3','k5','p9','k5']) dlp.add_row(['p3','p2tog','ssk','k5','k2tog','p1fb','p4','k3','p4','p1fb','ssk','k5','k2tog','p2tog','p3']) dlp.add_row(['k4','p7','k6','p3','k6','p7','k4']) dlp.add_row(['p2','p2tog','ssk','k3','k2tog','p1fb','p5','k2','m1','k1','m1','k1','p5','p1fb','ssk','k2','k2tog','p2tog','p2']) dlp.add_row(['k3','p5','k7','p5','k7','p5','k3']) dlp.add_row(['p1','p2tog','ssk','k2','k2tog','p1fb','p6','k1','m1','k3','m1','k1','p6','p1fb','ssk','k2','k2tog','p2tog','p1']) dlp.add_row(['k2','p3','k8','p7','k7','p3','k2']) dlp.add_row(['p2','sl2','k1','p2 sso','p6','p2tog','k1','m1','k5','m1','k1','p2tog','p6','sl2','k1','p2 sso','p2']) dlp.add_row(['k10','p9','k10']) return dlp
def read_bytes(self, data): try: self.name = data[0:20].rstrip(b'\0').decode() except UnicodeDecodeError: self.name = 'invalid' for offset in range(20, 950, 30): sample = Sample(data[offset:offset + 30]) self.samples.append(sample) if sample.name: self.vanity += '\n' + sample.name length = data[950] self.positions = [byte for byte in data[952:1080]][:length] self.mk = data[1080:1084] num_patterns = max(self.positions) + 1 dex = 1024 * num_patterns + 1084 for offset in range(1084, dex, 1024): self.patterns.append(Pattern(data[offset:offset + 1024])) for sample in self.samples[1:]: dex2 = dex + sample.length sample.wave = data[dex:dex2] dex = dex2
def __fetch_webkit(self, task_entry): p = Pattern(task_entry, self.__getCurrentShell(task_entry), self.global_data) import cwebbrowser task_entry['datas'] = [] urls = p.convertPattern('url') timeout = task_entry.get('timeout', 120) delay = task_entry.get('delay', 0) for url in urls: self.logger.info("fetching " + url) data = "" if not url: # do not fetch null url continue browser = cwebbrowser.CWebBrowser() browser.setHeaders(task_entry.get('headers', [])) #browser.show(); try: browser.load(url=url, load_timeout=timeout, delay=delay) except cwebbrowser.Timeout: self.logger.error("fetch " + url + " timeout ") except Exception, exception: self.logger.error("fetch " + url + " error ") print "Exception message:", exception else: html = browser.html() if html: html = html.encode('utf-8') data = html else: self.logger.error("fetch " + url + " failed with no response") task_entry['datas'].append(data) browser.close()
def wait(image_name, timeout=None, precision=None, in_region=None): """Wait for a Pattern or image to appear :param image_name: String or Pattern :param timeout: Number as maximum waiting time in seconds. :param precision: Matching similarity :param in_region: Region object in order to minimize the area :return: True if found """ if isinstance(image_name, str) and is_ocr_text(image_name): a_match = text_search_by(image_name, True, in_region) if a_match is not None: return True else: raise FindError('Unable to find text %s' % image_name) elif isinstance(image_name, str) or isinstance(image_name, Pattern): if timeout is None: timeout = Settings.AutoWaitTimeout if precision is None: precision = Settings.MinSimilarity try: pattern = Pattern(image_name) except Exception: pattern = image_name image_found = positive_image_search(pattern, timeout, precision, in_region) if image_found is not None: return True else: raise FindError('Unable to find image %s' % image_name) else: raise ValueError(INVALID_GENERIC_INPUT)
def _general_click(where=None, clicks=None, duration=None, in_region=None, button=None): """General Mouse Click :param where: Location , image name or Pattern :param clicks: Number of mouse clicks :param duration: speed of hovering from current location to target :param in_region: Region object in order to minimize the area :param button: Mouse button clicked (can be left, right, middle, 1, 2, 3) :return: None """ if duration is None: duration = Settings.MoveMouseDelay if isinstance(where, str) and is_ocr_text(where): a_match = text_search_by(where, True, in_region) if a_match is not None: click_location = Location(a_match['x'] + a_match['width'] / 2, a_match['y'] + a_match['height'] / 2) _click_at(click_location, clicks, duration, button) elif isinstance(where, Location): _click_at(where, clicks, duration, button) elif isinstance(where, str) or isinstance(where, Pattern): try: pattern = Pattern(where) except Exception: pattern = where _click_pattern(pattern, clicks, duration, in_region, button) else: raise ValueError(INVALID_GENERIC_INPUT)
def waitVanish(image_name, timeout=None, precision=None, in_region=None): """Wait until a Pattern or image disappears :param image_name: Image, Pattern or string :param timeout: Number as maximum waiting time in seconds. :param precision: Matching similarity :param in_region: Region object in order to minimize the area :return: True if vanished """ if timeout is None: timeout = Settings.AutoWaitTimeout if precision is None: precision = Settings.MinSimilarity pattern = Pattern(image_name) image_found = negative_image_search(pattern, timeout, precision, in_region) if image_found is not None: return True else: raise FindError('%s did not vanish' % image_name)
def extract_patterns_unitary(ld_graph: rdflib.Graph): """Extracts from the linked data graph the patterns of length 1 together with the instance nodes that are involved in such pattern. The information for each semantic relation is represented in a Pattern object. See the Pattern class docs for more details about the information handling. Parameters ---------- ld_graph: rdflib.Graph The graph object containing the triples of the Linked data Returns ------- list List of patterns (class Pattern) of length 1 """ qres = ld_graph.query(queries.length_1_triples) P1 = dict() i = 0 for row in qres: (x, c1, p, y, c2) = row semantic_relation = (str(c1), str(p), str(c2)) if semantic_relation not in P1.keys(): # Create pattern graph and Pattern object new_p = Pattern(i, 1, 0) P1[semantic_relation] = new_p i += 1 pattern = P1[semantic_relation] pattern.add_relation(c1, c2, p) pattern.add_relation_instance(c1, x, c2, y, p) pattern.frequency += 1 #pickle.dump(P1, open('P1.pkl', 'wb'), protocol=pickle.HIGHEST_PROTOCOL) return list(P1.values())
def write_dists(n, nr, group_name): p = Pattern(n) p.group(group_name) p.to_fractional_coordinate() lattice_vectors = np.array([p.a1, p.a2]) center_cell_fracts = np.mod(p.xys + .5, 1) - .5 rmax = np.max([ np.linalg.norm(np.dot(ij, lattice_vectors)) for ij in product((-1, 1), repeat=2) ]) num_layer = 36 x = range(-num_layer, num_layer + 1) I, J = np.meshgrid(x, x) I, J = I.flatten(), J.flatten() xys = I[:, None] * p.a1 + J[:, None] * p.a2 mask = xys[:, 0]**2 + xys[:, 1]**2 <= rmax * rmax * 4 I, J = I[mask], J[mask] image_cell_fracts = np.concatenate( [center_cell_fracts + np.array(ij) for ij in zip(I, J)]) center_cell_carts = np.array( [np.dot(fract, lattice_vectors) for fract in center_cell_fracts]) image_cell_carts = np.array( [np.dot(fract, lattice_vectors) for fract in image_cell_fracts]) dists = cdist(center_cell_carts, image_cell_carts) dists = dists[np.logical_and(dists > 0, dists <= rmax)] bins = np.linspace(0, rmax, nr) hist = np.histogram(dists, bins) counts = hist[0] rho = (len(center_cell_carts) / np.linalg.norm(np.cross(p.a1, p.a2))) return counts / counts.sum() / rho / (2 * np.pi * bins[1:]) / (bins[1] - bins[0])