rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
assert len(divvy) == 2 x = ht.do_subset_partition(divvy[0], divvy[1]) y = ht.do_subset_partition(divvy[1], 0)
assert len(divvy) == 4 x = ht.do_subset_partition(divvy[0], divvy[2]) y = ht.do_subset_partition(divvy[2], 0)
def test_random_20_a_succ_II(self): ht = khmer.new_hashbits(20, 4**13+1) filename = os.path.join(thisdir, 'test-data/random-20-a.fa') outfile = filename + '.out'
assert len(divvy) == 2, len(divvy) x = ht.do_subset_partition(divvy[0], divvy[1]) y = ht.do_subset_partition(divvy[1], 0)
assert len(divvy) == 4, len(divvy) x = ht.do_subset_partition(divvy[0], divvy[2]) y = ht.do_subset_partition(divvy[2], 0)
def test_random_20_a_succ_III(self): ht = khmer.new_hashbits(20, 4**13+1) filename = os.path.join(thisdir, 'test-data/random-20-a.fa') outfile = filename + '.out'
(a, b, c) = divvy
print divvy (a, _, b, _, c) = divvy
def test_save_load_merge(self): ht = khmer.new_hashbits(20, 4**14+1) filename = os.path.join(thisdir, 'test-graph2.fa')
assert n == (103, 1, 0), n
assert n == (102, 1, 0), n
def test_complex6_32_12(self): ht = khmer.new_hashtable(20, 4**12+1)
assert n == 106, n
assert n == 103, n
def test_complex6_32_12(self): ht = khmer.new_hashtable(20, 4**12+1)
ht = khmer.new_hashtable(K, 1)
ht = khmer.new_hashbits(K, 1, 1)
def main(dir1, dir2, n_threads): # detect all of the relevant partitionmap files subset_filenames = glob.glob(os.path.join(dir1, '*.pmap')) # create empty hashtable structure ht = khmer.new_hashtable(K, 1) # put jobs on queue merge_queue = Queue.Queue() for filename in subset_filenames: merge_queue.put((ht, filename)) print 'starting threads' threads = [] for n in range(n_threads): t = threading.Thread(target=pull_pair, args=(merge_queue,)) threads.append(t) t.start() # wait for threads for t in threads: t.join() # done! if merge_queue.qsize() == 1: ht, merge_file = merge_queue.get() shutil.copy(merge_file, os.path.join(dir2, os.path.basename(merge_file))) assert merge_queue.qsize() == 0
print 'gorup_d', partition_id, group_n
print 'group_d', partition_id, group_n
def read_partition_file(fp): for n, line in enumerate(fp): if n % 2 == 0: surrendered = False name, partition_id = line[1:].strip().rsplit('\t', 1) if '*' in partition_id: partition_id = int(partition_id[:-1]) surrendered = True else: partition_id = int(partition_id) else: sequence = line.strip() yield name, partition_id, surrendered, sequence
ht = khmer.new_hashtable(K, 1)
def main(dir1, dir2, n_threads): # detect all of the relevant partitionmap files subset_filenames = glob.glob(os.path.join(dir1, '*.pmap')) # put on queue merge_queue = Queue.Queue() for filename in subset_filenames: merge_queue.put((ht, filename)) print 'starting threads' threads = [] for n in range(n_threads): t = threading.Thread(target=pull_pair, args=(merge_queue,)) threads.append(t) t.start() # wait for threads for t in threads: t.join() # done! if merge_queue.qsize() == 1: ht, merge_file = merge_queue.get() shutil.copy(merge_file, os.path.join(dir2, os.path.basename(merge_file))) assert merge_queue.qsize() == 0
assert len(divvy) == 2
assert len(divvy) == 2, len(divvy)
def test_random_20_a_succ_III(self): ht = khmer.new_hashbits(20, 4**13+1) filename = os.path.join(thisdir, 'test-data/random-20-a.fa') outfile = filename + '.out'
assert n_unassigned == 1, n_unassigned assert n_surrendered == 16, n_surrendered
assert n_unassigned == 2, n_unassigned assert n_surrendered == 15, n_surrendered
def test_surrendered(self): ht = khmer.new_hashtable(32, 4**15+1)
name, partition_id = line[1:].strip().split('\t')
name, partition_id = line[1:].strip().rsplit('\t', 1)
def read_partition_file(fp): for n, line in enumerate(fp): if n % 2 == 0: surrendered = False name, partition_id = line[1:].strip().split('\t') if '*' in partition_id: partition_id = int(partition_id[:-1]) surrendered = True else: partition_id = int(partition_id) else: sequence = line.strip() yield name, partition_id, surrendered, sequence
partition = int(record['name'].split('\t')[1].rstrip('*'))
partition = int(record['name'].rsplit('\t', 1)[1].rstrip('*'))
def read_partition_file(fp): for n, line in enumerate(fp): if n % 2 == 0: surrendered = False name, partition_id = line[1:].strip().split('\t') if '*' in partition_id: partition_id = int(partition_id[:-1]) surrendered = True else: partition_id = int(partition_id) else: sequence = line.strip() yield name, partition_id, surrendered, sequence
del count[0]
if 0 in count: del count[0]
def read_partition_file(fp): for n, line in enumerate(fp): if n % 2 == 0: surrendered = False name, partition_id = line[1:].strip().split('\t') if '*' in partition_id: partition_id = int(partition_id[:-1]) surrendered = True else: partition_id = int(partition_id) else: sequence = line.strip() yield name, partition_id, surrendered, sequence
def threaded_calc(ht, filename, start, stop): x = ht.do_subset_partition(filename, start, stop)
def threaded_calc(ht, start, stop): x = ht.do_subset_partition(start, stop)
def threaded_calc(ht, filename, start, stop): x = ht.do_subset_partition(filename, start, stop) print 'done!' results.append(x)
for i in range(N_THREADS - 1): start = subset_size * i end = start + subset_size t = threading.Thread(target=threaded_calc, args=(ht, FILENAME, start, end))
for i in range(n_subsets): start = divvy[i] end = divvy[i+1] t = threading.Thread(target=threaded_calc, args=(ht, start, end))
def threaded_calc(ht, filename, start, stop): x = ht.do_subset_partition(filename, start, stop) print 'done!' results.append(x)
start = subset_size * (N_THREADS - 1) end = total_reads t = threading.Thread(target=threaded_calc, args=(ht, FILENAME, start, end)) threads.append(t) t.start()
def threaded_calc(ht, filename, start, stop): x = ht.do_subset_partition(filename, start, stop) print 'done!' results.append(x)
n = ht.do_partition2(filename, "")
n = ht.do_partition3(filename, "")
def test_simple_20_12(self): ht = khmer.new_hashtable(20, 4**12+1)
n = ht.do_partition2(filename, "")
n = ht.do_partition3(filename, "")
def test_simple_30_12(self): ht = khmer.new_hashtable(32, 4**12+1)
n = ht.do_partition2(filename, "")
n = ht.do_partition3(filename, "")
def test_merge_20_12(self): ht = khmer.new_hashtable(20, 4**12+1)
n = ht.do_partition2(filename, "")
n = ht.do_partition3(filename, "")
def test_merge_32_12(self): ht = khmer.new_hashtable(32, 4**12+1)
n = ht.do_partition2(filename, "")
n = ht.do_partition3(filename, "")
def test_complex_20_12(self): ht = khmer.new_hashtable(20, 4**12+1)
n = ht.do_partition2(filename, "")
n = ht.do_partition3(filename, "")
def test_complex_31_12(self): ht = khmer.new_hashtable(31, 4**12+1)
n = ht.do_partition2(filename, "")
n = ht.do_partition3(filename, "")
def test_complex_32_12(self): ht = khmer.new_hashtable(32, 4**12+1)
ht.consume_fasta_and_tag(filename, callback)
ht.consume_fasta(filename, 0, 0, None, True, callback)
def main(filename): basename = os.path.basename(filename) # populate the hash table and tag set ht.consume_fasta_and_tag(filename, callback)
'size': number_to_human_size(build['size']),
'size': format_byte_size(build['size']),
def update_params(self, d): super(SourceDownloadsWidget, self).update_params(d) sources = [] releases = [] dist_tags = {}
redirect('/', anchor='/'.join(args), params=kwds)
url = pylons.url('/', anchor='/'.join(args), **kwds) if url.startswith('/community'): url = url[10:] redirect(url)
def default(self, *args, **kwds): identity = request.environ.get('repoze.who.identity') if identity: csrf = identity.get('_csrf_token') if csrf: kwds['_csrf_token'] = csrf
def default(self, *args, **kwds):
def _default(self, *args, **kwds):
def default(self, *args, **kwds): identity = request.environ.get('repoze.who.identity') if identity: csrf = identity.get('_csrf_token') if csrf: kwds['_csrf_token'] = csrf
url = pylons.url('/', anchor='/'.join(args), **kwds) if url.startswith('/community'): url = url[10:]
anchor='/'.join(args) if anchor: kwds['anchor'] = anchor
def default(self, *args, **kwds): identity = request.environ.get('repoze.who.identity') if identity: csrf = identity.get('_csrf_token') if csrf: kwds['_csrf_token'] = csrf
redirect(url)
redirect(url, **kwds)
def default(self, *args, **kwds): identity = request.environ.get('repoze.who.identity') if identity: csrf = identity.get('_csrf_token') if csrf: kwds['_csrf_token'] = csrf
def changed_saved(self, current, previous): if current is None:
def changed_saved(self): items = self.saved_items.selectedItems() if len(items) == 0:
def changed_saved(self, current, previous): if current is None: return d = current.data(QtCore.Qt.UserRole).toMap() username = d[QtCore.QString('username')].toString() password = d[QtCore.QString('password')].toString() host = d[QtCore.QString('host')].toString() port = d[QtCore.QString('port')].toString() self.username_edit.setText(username) self.password_edit.setText(password) self.host_edit.setText(host) self.port_edit.setText(port)
print item.text()
def remove_entry(self): items = self.saved_items.selectedItems() for item in items: print item.text() config = SafeConfig(os.path.join(sys.path[0], 'saved.ini')) config.remove_section(str(item.text())) config.write() self.load_saved_items()
self.host_edit.textChanged.connect(self.clear_saved_selection)
self.host_edit.textEdited.connect(self.clear_saved_selection)
def show_connection_page(self): page_hlayout = QtGui.QHBoxLayout() page_vlayout = QtGui.QVBoxLayout() page_layout = QtGui.QGridLayout() new_group = QtGui.QGroupBox("New Connection") layout = QtGui.QFormLayout()
self.port_edit.textChanged.connect(self.clear_saved_selection)
self.port_edit.textEdited.connect(self.clear_saved_selection)
def show_connection_page(self): page_hlayout = QtGui.QHBoxLayout() page_vlayout = QtGui.QVBoxLayout() page_layout = QtGui.QGridLayout() new_group = QtGui.QGroupBox("New Connection") layout = QtGui.QFormLayout()
self.username_edit.textChanged.connect(self.clear_saved_selection)
self.username_edit.textEdited.connect(self.clear_saved_selection)
def show_connection_page(self): page_hlayout = QtGui.QHBoxLayout() page_vlayout = QtGui.QVBoxLayout() page_layout = QtGui.QGridLayout() new_group = QtGui.QGroupBox("New Connection") layout = QtGui.QFormLayout()
self.password_edit.textChanged.connect(self.clear_saved_selection)
self.password_edit.textEdited.connect(self.clear_saved_selection)
def show_connection_page(self): page_hlayout = QtGui.QHBoxLayout() page_vlayout = QtGui.QVBoxLayout() page_layout = QtGui.QGridLayout() new_group = QtGui.QGroupBox("New Connection") layout = QtGui.QFormLayout()
self.saved_items.currentItemChanged.connect(self.changed_saved)
self.saved_items.itemSelectionChanged.connect(self.changed_saved) self.saved_items.itemDoubleClicked.connect(self.connect)
def show_connection_page(self): page_hlayout = QtGui.QHBoxLayout() page_vlayout = QtGui.QVBoxLayout() page_layout = QtGui.QGridLayout() new_group = QtGui.QGroupBox("New Connection") layout = QtGui.QFormLayout()
def __init__(self, terminal):
def __init__(self, terminal, index):
def __init__(self, terminal): QtCore.QThread.__init__(self) self.terminal = terminal
th = ConnectionThread(term)
th = ConnectionThread(term, idx)
def run(self): self.terminal.connect()
scroll_bottom = self.get_scroll_bottom() - 1
scroll_top = self.get_scroll_top() scroll_bottom = self.get_scroll_bottom()
def insert_row(self, num=1): buf = self.get_buffer() (row, col) = self.cursor.get_row_col() new_rows = [TerminalRow(self.width, self) for x in range(0, num)] buf.insert(row, '') buf[row:row + 1] = new_rows self.log.debug("Inserted %s row(s): %s" % (num, len(buf)))
self.parent.set_dirty()
repaint_buf = buf[scroll_top - 1:scroll_bottom - 1] for row in repaint_buf: row.set_dirty()
def insert_row(self, num=1): buf = self.get_buffer() (row, col) = self.cursor.get_row_col() new_rows = [TerminalRow(self.width, self) for x in range(0, num)] buf.insert(row, '') buf[row:row + 1] = new_rows self.log.debug("Inserted %s row(s): %s" % (num, len(buf)))
for cnt in range(0, times): row = buf.pop(scroll_top - 1) row.reset() buf.insert(scroll_bottom - 1, row) self.parent.set_dirty() self.print_debug() return
first = scroll_top - 1 last = scroll_bottom - 1 rows = [TerminalRow(self.width, self) for x in range(0, times)] del buf[first:first + times] buf.insert(last, '') buf[last:last + 1] = rows repaint_buf = buf[first:last] for row in repaint_buf: row.set_dirty() return
def scroll(self, times=1): self.log.debug("screen scroll") if self.alternate_active: scroll_top = self.get_scroll_top() scroll_bottom = self.get_scroll_bottom() buf = self.get_buffer() for cnt in range(0, times): row = buf.pop(scroll_top - 1) row.reset() buf.insert(scroll_bottom - 1, row) self.parent.set_dirty() self.print_debug() return self.base += times self.log.debug("Scrolling screen buffer, base = %s, row = %s" % (self.base, self.cursor.row)) #if (self.base + self.height) - 1 >= self.scrollback: if (self.base - times) >= self.scrollback: self.log.debug("Scrollback exceeded...rolling over buffer.") self.base -= times for cnt in range(0, times): row = self.buffer.pop(0) row.reset() self.buffer.append(row) self.parent.set_dirty() self.parent.set_scroll_value(self.base)
try: interface = autobus.lookup_interface(message["interface_name"]) function = interface.lookup_function(message["function"])
interface_name = message["interface_name"] function_name = message["function"] print ("Attempting to dispatch function call from " + sender + " to interface " + interface_name + " and function " + function_name) try: interface = autobus.lookup_interface(interface_name) function = interface.lookup_function(function_name)
def process_call_function_command(message, sender, connection): try: interface = autobus.lookup_interface(message["interface_name"]) function = interface.lookup_function(message["function"]) except (autobus.NoSuchInterfaceException, autobus.NoSuchFunctionException) as e: connection.send_error(message, text=str(e)) return if function.special: function.invoke_special(message, connection) return invoke_message = create_message(RunFunctionCommand, interface_name=interface.name, function=function.name, arguments=message["arguments"]) interface.connection.send(invoke_message) print ("Sending run command to " + str(interface.connection.id) + " with message id " + str(invoke_message["message_id"]) + " whose response is to be forwarded with id " + str(message["message_id"])) # FIXME: This causes a response to a function invocation sent as a notification # to still be sent when the function returns on the remote side. We need to # somehow not add the message to this list and perhaps suppress the "sporadic # message received" warning that would consequently be printed to stdout once # the remote client sends back the return value if the incoming message here # is a notification. interface.connection.pending_responses[invoke_message["message_id"]] = ( sender, message["message_id"])
repeat = (address == last_plc_address and (last_plc_time + PLC_DELAY) > now)
repeat = (last_plc_time + PLC_DELAY) > now
def do_GET(self): global last_plc_time global last_plc_address global last_rf_time global last_rf_address path = self.path if "?" not in path: # Serve the script page print "Serving script page for url " + path self.send_response(200) self.send_header("Content-Type", "text/html") self.end_headers() with open("src/activehomed/receive_ie.html") as file: for line in file: self.wfile.write(line + " ") else: # Incoming event from the script page print "Inbound event for url " + path params = dict(parse_qsl(path.split("?")[1], True)) mode, address, command, sequence, timestamp, _, _ = (params["a"], params["b"], params["c"], params["d"], params["e"], params["f"], params["g"]) receive_action_event(mode, address, command, sequence, timestamp) repeat = False if mode.startswith("send") or mode.startswith("recv"): mode = mode[4:] now = time() if mode == "plc": repeat = (address == last_plc_address and (last_plc_time + PLC_DELAY) > now) last_plc_time = now last_plc_address = address elif mode == "rf": repeat = (address == last_rf_address and (last_rf_time + RF_DELAY) > now) last_rf_time = now last_rf_address = address house, unit = address[0], address[1:] if sequence == "": sequence = None else: try: sequence = int(sequence) except ValueError: print ("WARNING: Sequence number " + str(sequence) + " couldn't be converted to an integer.") if timestamp == "": timestamp = None receive_event(mode, house, unit, address, command, sequence, timestamp, repeat) self.send_response(200) self.send_header("Content-Type", "text/plain") self.end_headers() self.wfile.write("ok")
last_plc_address = address
def do_GET(self): global last_plc_time global last_plc_address global last_rf_time global last_rf_address path = self.path if "?" not in path: # Serve the script page print "Serving script page for url " + path self.send_response(200) self.send_header("Content-Type", "text/html") self.end_headers() with open("src/activehomed/receive_ie.html") as file: for line in file: self.wfile.write(line + " ") else: # Incoming event from the script page print "Inbound event for url " + path params = dict(parse_qsl(path.split("?")[1], True)) mode, address, command, sequence, timestamp, _, _ = (params["a"], params["b"], params["c"], params["d"], params["e"], params["f"], params["g"]) receive_action_event(mode, address, command, sequence, timestamp) repeat = False if mode.startswith("send") or mode.startswith("recv"): mode = mode[4:] now = time() if mode == "plc": repeat = (address == last_plc_address and (last_plc_time + PLC_DELAY) > now) last_plc_time = now last_plc_address = address elif mode == "rf": repeat = (address == last_rf_address and (last_rf_time + RF_DELAY) > now) last_rf_time = now last_rf_address = address house, unit = address[0], address[1:] if sequence == "": sequence = None else: try: sequence = int(sequence) except ValueError: print ("WARNING: Sequence number " + str(sequence) + " couldn't be converted to an integer.") if timestamp == "": timestamp = None receive_event(mode, house, unit, address, command, sequence, timestamp, repeat) self.send_response(200) self.send_header("Content-Type", "text/plain") self.end_headers() self.wfile.write("ok")
function(*args, **kwargs)
return function(*args, **kwargs)
def wrapper(*args, **kwargs): with lock: function(*args, **kwargs)
return "objects.path like ? escape ?", [self.path.replace("/", "//") + "///%", "/"]
return "objects.path like ? escape ?", [self.path.replace("/", "//") .replace("%", "/%") .replace("_", "/_") + "//%", "/"]
def sql(self): return "objects.path like ? escape ?", [self.path.replace("/", "//") + "///%", "/"]
display_type = client.propget("svnweb:display", path).values[0]
display_type = client.propget("svnweb:display", path).values()[0]
def do_GET(self): path = self.path if ".." in path: raise Exception("Path can't contain two dots in a row") print "Initial path: " + path if path == "": path = "/" if path[0] != "/": raise Exception("Path doesn't start with a forward slash. It's " + path) path = root_path + path print "Getting result for path " + path try: result = client.cat(path) except: print "Result not there; trying index.html under it" if path[-1] != "/": path += "/" path += "index.html" try: result = client.cat(path) except: print "Couldn't find index.html either" print_exc() result = None if result == None: self.send_response(404) self.send_header("Content-Type", "text/html") self.no_cache() self.end_headers() self.wfile.write(error_response) return print "Got it! Propgetting..." # We have the file. Now we go figure out if we're supposed to use an # alternate displayer. try: display_type = client.propget("svnweb:display", path).values[0] except: display_type = None print "svnweb:display is " + str(display_type) if display_type == "mediawiki": print "Forwarding to mediawiki renderer" mime_type, result = display_mediawiki(self, path, result) else: print "No known renderer set with svnweb:display, displaying directly" try: mime_type = client.propget("svn:mime-type", path).values[0] except: print "Couldn't propget, looking up dynamically" mime_type, _ = mimetypes.guess_type(path) if mime_type is None: print "Dynamic lookup didn't find anything. Using text/plain." mime_type = "text/plain" print "Mime type is " + mime_type self.send_response(200) print "Response sent" if mime_type != None: print "Sending mime type" self.send_header("Content-Type", mime_type) print "Sending no-cache headers" self.no_cache() print "Ending headers" self.end_headers() print "Writing..." self.wfile.write(result) print "Output sent!" # That's it!
mime_type = client.propget("svn:mime-type", path).values[0]
mime_type = client.propget("svn:mime-type", path).values()[0]
def do_GET(self): path = self.path if ".." in path: raise Exception("Path can't contain two dots in a row") print "Initial path: " + path if path == "": path = "/" if path[0] != "/": raise Exception("Path doesn't start with a forward slash. It's " + path) path = root_path + path print "Getting result for path " + path try: result = client.cat(path) except: print "Result not there; trying index.html under it" if path[-1] != "/": path += "/" path += "index.html" try: result = client.cat(path) except: print "Couldn't find index.html either" print_exc() result = None if result == None: self.send_response(404) self.send_header("Content-Type", "text/html") self.no_cache() self.end_headers() self.wfile.write(error_response) return print "Got it! Propgetting..." # We have the file. Now we go figure out if we're supposed to use an # alternate displayer. try: display_type = client.propget("svnweb:display", path).values[0] except: display_type = None print "svnweb:display is " + str(display_type) if display_type == "mediawiki": print "Forwarding to mediawiki renderer" mime_type, result = display_mediawiki(self, path, result) else: print "No known renderer set with svnweb:display, displaying directly" try: mime_type = client.propget("svn:mime-type", path).values[0] except: print "Couldn't propget, looking up dynamically" mime_type, _ = mimetypes.guess_type(path) if mime_type is None: print "Dynamic lookup didn't find anything. Using text/plain." mime_type = "text/plain" print "Mime type is " + mime_type self.send_response(200) print "Response sent" if mime_type != None: print "Sending mime type" self.send_header("Content-Type", mime_type) print "Sending no-cache headers" self.no_cache() print "Ending headers" self.end_headers() print "Writing..." self.wfile.write(result) print "Output sent!" # That's it!
and self.db is other.db)
and self.db is other.db and self.operation_list is other.operation_list)
def __eq__(self, other): return (isinstance(other, Changeset) and self.path == other.path and self.db is other.db)
bus = AutobusConnection(host, port, print_exceptions=True) bus.add_interface(interface_name, RPC()) speech_queue_object = bus.add_object(interface_name, "speech_queue", """ This doesn't work yet. """, {}) bus.start_connecting()
def time_format_weekday_month_day(self, time): """ Returns time_format_weekday(time) + " " + time_format_month_day(time) """ return (self.time_format_weekday(time) + " " + self.time_format_month_day(time))
print "" print "Speakd has successfully started up. PID is " + str(os.getpid()) try: while not is_shutting_down: sentence_tuple = get_next_sentence() if sentence_tuple is None: time.sleep(0.5) continue priority, sentence = sentence_tuple print "Something to say: " + str(sentence.components) if sentence.voice is not None: voice = voices[sentence.voice] else: voice = voices[default_voice] voice_path = voice.path print "Saying with voice " + voice.name audio_stream.start_stream() for item in sentence.components: if isinstance(item, basestring): file = sanitize_file(item) print "Saying word " + file try: wave_file = wave.open(os.path.join(voice_path, file + ".wav"), "r") except: print "File " + file + " does not exist for voice " + voice.name + ". It will be silently ignored." continue data = wave_file.readframes(1024) while data != "": audio_stream.write(data)
print "Opening audio device..." def main(): global audio_device global autio_stream global bus global speech_queue_object audio_device = pyaudio.PyAudio() audio_stream = audio_device.open(format=audio_device.get_format_from_width(2), channels=1, rate=44100, output=True, frames_per_buffer=1024) audio_stream.stop_stream() bus = AutobusConnection(host, port, print_exceptions=True) bus.add_interface(interface_name, RPC()) speech_queue_object = bus.add_object(interface_name, "speech_queue", """ This doesn't work yet. """, {}) bus.start_connecting() print "" print "Speakd has successfully started up. PID is " + str(os.getpid()) try: while not is_shutting_down: sentence_tuple = get_next_sentence() if sentence_tuple is None: time.sleep(0.5) continue priority, sentence = sentence_tuple print "Something to say: " + str(sentence.components) if sentence.voice is not None: voice = voices[sentence.voice] else: voice = voices[default_voice] voice_path = voice.path print "Saying with voice " + voice.name audio_stream.start_stream() for item in sentence.components: if isinstance(item, basestring): file = sanitize_file(item) print "Saying word " + file try: wave_file = wave.open(os.path.join(voice_path, file + ".wav"), "r") except: print "File " + file + " does not exist for voice " + voice.name + ". It will be silently ignored." continue
def sanitize_file(name): return name.replace(".", "").replace("\\", "").replace("/", "")
elif isinstance(item, int): print "Pausing for " + str(item) + " milliseconds" time.sleep((item * 1.0) / 1000.0) print "Flushing bus outbound queue" bus.flush() print "Waiting..." time.sleep(1) print "Closing audio stream" audio_stream.stop_stream() print "Done." except KeyboardInterrupt: print "Interrupted, shutting down" bus.shutdown()
while data != "": audio_stream.write(data) data = wave_file.readframes(1024) elif isinstance(item, int): print "Pausing for " + str(item) + " milliseconds" time.sleep((item * 1.0) / 1000.0) print "Flushing bus outbound queue" bus.flush() print "Waiting..." time.sleep(1) print "Closing audio stream" audio_stream.stop_stream() print "Done." except KeyboardInterrupt: print "Interrupted, shutting down" bus.shutdown()
def sanitize_file(name): return name.replace(".", "").replace("\\", "").replace("/", "")
if self.receive_queues is None:
if self.receive_queues is None or self.input_thread is None:
def query(self, message, timeout=30): """ Sends the specified message from the server, waiting up to the specified timeout for a response. When a response is received, it is returned. If a response is not received within the specified amount of time, a TimeoutException will be raised. Otherwise, the response sent by the server will be returned. """ queue = Queue() if self.receive_queues is None: raise NotConnectedException() self.receive_queues[message["message_id"]] = queue self.send(message) try: response = queue.get(block=True, timeout=timeout) except Empty: try: del self.receive_queues[message["message_id"]] except KeyError: pass raise TimeoutException() # If we don't get a KeyError, it's guaranteed that the input thread # will already have removed the queue, so we don't need to worry about # removing it. return response
return PrefixFilter("not", SQLFilter(*self.get_filter_sql()))
query = Query(self.db) query.filters.append(PrefixFilter("not", SQLFilter(*self.get_filter_sql()))) return query
def inverse(self): """ Returns a new query that selects objects only if they would not be selected by this query. If you only want to invert a small part of the overall query, you can do that by constructing everything else in your query, creating a separate query, filtering it by the part you want to invert, inverting it, and then using the & operator to get a new query that only inverts the one query. """ return PrefixFilter("not", SQLFilter(*self.get_filter_sql()))
except KeyError:
except (KeyError, IndexError):
def foreign_get(object, item): if object is None or object is Null: return None try: return foreign_translate(object[item]) except KeyError: return None
print "Usage: ./cmeansMultiGPU.py INPUT_FILE NUM_CLUSTERS [THRESHOLD=0.0001] [MIN_ITERS=0] [MAX_ITERS=100] [DEVICE=0] [FUZZINESS=2] [DISTANCE_MEASURE=0] [K1=1.0] [K2=0.01] [K3=1.5] [MEMBER_THRESHOLD=0.05] [TABU_ITER=100] [TABU_TENURE=5] [MDL=0] [CPU_ONLY=0]"
print "Usage: ./cmeansMultiGPU.py INPUT_FILE NUM_CLUSTERS [THRESHOLD=0.0001] [MIN_ITERS=0] [MAX_ITERS=100] [DEVICE=0] [FUZZINESS=2] [DISTANCE_MEASURE=0] [K1=1.0] [K2=0.01] [K3=1.5] [MEMBER_THRESHOLD=0.05] [TABU_ITER=100] [TABU_TENURE=5] [MDL=0] [CPU_ONLY=0] [TRUNCATE=1] [RANDOM_SEED=1]"
def usage(): print "Usage: ./cmeansMultiGPU.py INPUT_FILE NUM_CLUSTERS [THRESHOLD=0.0001] [MIN_ITERS=0] [MAX_ITERS=100] [DEVICE=0] [FUZZINESS=2] [DISTANCE_MEASURE=0] [K1=1.0] [K2=0.01] [K3=1.5] [MEMBER_THRESHOLD=0.05] [TABU_ITER=100] [TABU_TENURE=5] [MDL=0] [CPU_ONLY=0]" print print " INPUT_FILE and NUM_CLUSTERS are required." print " The rest of the parameters can be specified in NAME=VALUE form" print " Alternatively, the parameters can be provided positionally if all are provided"
if key in ['K1','K2','K3','MEMBER_THRESHOLD','THRESHOLD']:
if key in ['K1','K2','K3','MEMBER_THRESHOLD','THRESHOLD','FUZZINESS']:
def parseInputArgs(): args = sys.argv num_args = len(args) params = { 'INPUT_FILE' : '', 'NUM_CLUSTERS' : 0, 'THRESHOLD' : 0.0001, 'MIN_ITERS' : 0, 'MAX_ITERS' : 100, 'DEVICE' : 0, 'FUZZINESS' : 2, 'DISTANCE_MEASURE': 0, 'K1': 1.0, 'K2': 0.01, 'K3': 1.5, 'MEMBER_THRESHOLD': 0.05, 'TABU_ITER': 100, 'TABU_TENURE': 5, 'MDL': 0, 'CPU_ONLY': 0, } num_params = len(params.keys()) if num_args == num_params: params['INPUT_FILE'] = args[1] params['NUM_CLUSTERS'] = args[2] params['THRESHOLD'] = args[3] params['MIN_ITERS'] = args[4] params['MAX_ITERS'] = args[5] params['DEVICE'] = args[6] params['FUZZINESS'] = args[7] params['DISTANCE_MEASURE'] = args[8] params['K1'] = args[9] params['K2'] = args[10] params['K3'] = args[11] params['MEMBER_THRESHOLD'] = args[12] params['TABU_ITER'] = args[13] params['TABU_TENURE'] = args[14] params['MDL'] = args[15] params['CPU_ONLY'] = args[16] elif num_args == 3: params['INPUT_FILE'] = args[1] params['NUM_CLUSTERS'] = args[2] elif 3 < num_args < num_params: params['INPUT_FILE'] = args[1] params['NUM_CLUSTERS'] = args[2] for arg in args[3:]: try: key,val = arg.split("=") key = key.upper() assert key in params.keys() if key in ['K1','K2','K3','MEMBER_THRESHOLD','THRESHOLD']: params[key] = float(val) else: params[key] = int(val) except AssertionError: print "Error: Found invalid parameter '%s'" % key except ValueError: print "Error: Invalid value '%s' for parameter '%s'" % (val,key) print usage() sys.exit(1) else: print "Invalid command line arguments." print usage() sys.exit(1) if os.path.exists(params['INPUT_FILE']): if params['INPUT_FILE'].lower().endswith(".bin"): input = open(params['INPUT_FILE'],'rb') import struct params['NUM_EVENTS'] = struct.unpack('i',input.read(4))[0] params['NUM_DIMENSIONS'] = struct.unpack('i',input.read(4))[0] else: input = open(params['INPUT_FILE']) line = input.readline() # Read the header line num_dimensions = len(line.split(DELIMITER)) num_events = 0 for line in input: num_events += 1 params['NUM_DIMENSIONS'] = num_dimensions params['NUM_EVENTS'] = num_events params['NUM_EVENTS'] -= params['NUM_EVENTS'] % 16 print "%d events removed to ensure memory alignment" % (params['NUM_EVENTS'] % 16) else: print "Invalid input file." sys.exit(1) return params
params['NUM_EVENTS'] -= params['NUM_EVENTS'] % 16 print "%d events removed to ensure memory alignment" % (params['NUM_EVENTS'] % 16)
if params['TRUNCATE']: params['NUM_EVENTS'] -= params['NUM_EVENTS'] % (16*num_gpus) print "%d events removed to ensure memory alignment" % (params['NUM_EVENTS'] % (16*num_gpus))
def parseInputArgs(): args = sys.argv num_args = len(args) params = { 'INPUT_FILE' : '', 'NUM_CLUSTERS' : 0, 'THRESHOLD' : 0.0001, 'MIN_ITERS' : 0, 'MAX_ITERS' : 100, 'DEVICE' : 0, 'FUZZINESS' : 2, 'DISTANCE_MEASURE': 0, 'K1': 1.0, 'K2': 0.01, 'K3': 1.5, 'MEMBER_THRESHOLD': 0.05, 'TABU_ITER': 100, 'TABU_TENURE': 5, 'MDL': 0, 'CPU_ONLY': 0, } num_params = len(params.keys()) if num_args == num_params: params['INPUT_FILE'] = args[1] params['NUM_CLUSTERS'] = args[2] params['THRESHOLD'] = args[3] params['MIN_ITERS'] = args[4] params['MAX_ITERS'] = args[5] params['DEVICE'] = args[6] params['FUZZINESS'] = args[7] params['DISTANCE_MEASURE'] = args[8] params['K1'] = args[9] params['K2'] = args[10] params['K3'] = args[11] params['MEMBER_THRESHOLD'] = args[12] params['TABU_ITER'] = args[13] params['TABU_TENURE'] = args[14] params['MDL'] = args[15] params['CPU_ONLY'] = args[16] elif num_args == 3: params['INPUT_FILE'] = args[1] params['NUM_CLUSTERS'] = args[2] elif 3 < num_args < num_params: params['INPUT_FILE'] = args[1] params['NUM_CLUSTERS'] = args[2] for arg in args[3:]: try: key,val = arg.split("=") key = key.upper() assert key in params.keys() if key in ['K1','K2','K3','MEMBER_THRESHOLD','THRESHOLD']: params[key] = float(val) else: params[key] = int(val) except AssertionError: print "Error: Found invalid parameter '%s'" % key except ValueError: print "Error: Invalid value '%s' for parameter '%s'" % (val,key) print usage() sys.exit(1) else: print "Invalid command line arguments." print usage() sys.exit(1) if os.path.exists(params['INPUT_FILE']): if params['INPUT_FILE'].lower().endswith(".bin"): input = open(params['INPUT_FILE'],'rb') import struct params['NUM_EVENTS'] = struct.unpack('i',input.read(4))[0] params['NUM_DIMENSIONS'] = struct.unpack('i',input.read(4))[0] else: input = open(params['INPUT_FILE']) line = input.readline() # Read the header line num_dimensions = len(line.split(DELIMITER)) num_events = 0 for line in input: num_events += 1 params['NUM_DIMENSIONS'] = num_dimensions params['NUM_EVENTS'] = num_events params['NUM_EVENTS'] -= params['NUM_EVENTS'] % 16 print "%d events removed to ensure memory alignment" % (params['NUM_EVENTS'] % 16) else: print "Invalid input file." sys.exit(1) return params
current_path = os.getcwd() print "Current Directory: %s" % current_path print "PROJECT_PATH: %s" % PROJECT_PATH print "Compiling C-means for target file" os.chdir(PROJECT_PATH)
def parseInputArgs(): args = sys.argv num_args = len(args) params = { 'INPUT_FILE' : '', 'NUM_CLUSTERS' : 0, 'THRESHOLD' : 0.0001, 'MIN_ITERS' : 0, 'MAX_ITERS' : 100, 'DEVICE' : 0, 'FUZZINESS' : 2, 'DISTANCE_MEASURE': 0, 'K1': 1.0, 'K2': 0.01, 'K3': 1.5, 'MEMBER_THRESHOLD': 0.05, 'TABU_ITER': 100, 'TABU_TENURE': 5, 'MDL': 0, 'CPU_ONLY': 0, } num_params = len(params.keys()) if num_args == num_params: params['INPUT_FILE'] = args[1] params['NUM_CLUSTERS'] = args[2] params['THRESHOLD'] = args[3] params['MIN_ITERS'] = args[4] params['MAX_ITERS'] = args[5] params['DEVICE'] = args[6] params['FUZZINESS'] = args[7] params['DISTANCE_MEASURE'] = args[8] params['K1'] = args[9] params['K2'] = args[10] params['K3'] = args[11] params['MEMBER_THRESHOLD'] = args[12] params['TABU_ITER'] = args[13] params['TABU_TENURE'] = args[14] params['MDL'] = args[15] params['CPU_ONLY'] = args[16] elif num_args == 3: params['INPUT_FILE'] = args[1] params['NUM_CLUSTERS'] = args[2] elif 3 < num_args < num_params: params['INPUT_FILE'] = args[1] params['NUM_CLUSTERS'] = args[2] for arg in args[3:]: try: key,val = arg.split("=") key = key.upper() assert key in params.keys() if key in ['K1','K2','K3','MEMBER_THRESHOLD','THRESHOLD']: params[key] = float(val) else: params[key] = int(val) except AssertionError: print "Error: Found invalid parameter '%s'" % key except ValueError: print "Error: Invalid value '%s' for parameter '%s'" % (val,key) print usage() sys.exit(1) else: print "Invalid command line arguments." print usage() sys.exit(1) if os.path.exists(params['INPUT_FILE']): if params['INPUT_FILE'].lower().endswith(".bin"): input = open(params['INPUT_FILE'],'rb') import struct params['NUM_EVENTS'] = struct.unpack('i',input.read(4))[0] params['NUM_DIMENSIONS'] = struct.unpack('i',input.read(4))[0] else: input = open(params['INPUT_FILE']) line = input.readline() # Read the header line num_dimensions = len(line.split(DELIMITER)) num_events = 0 for line in input: num_events += 1 params['NUM_DIMENSIONS'] = num_dimensions params['NUM_EVENTS'] = num_events params['NUM_EVENTS'] -= params['NUM_EVENTS'] % 16 print "%d events removed to ensure memory alignment" % (params['NUM_EVENTS'] % 16) else: print "Invalid input file." sys.exit(1) return params
print "CWD:",os.getcwd()
def parseInputArgs(): args = sys.argv num_args = len(args) params = { 'INPUT_FILE' : '', 'NUM_CLUSTERS' : 0, 'THRESHOLD' : 0.0001, 'MIN_ITERS' : 0, 'MAX_ITERS' : 100, 'DEVICE' : 0, 'FUZZINESS' : 2, 'DISTANCE_MEASURE': 0, 'K1': 1.0, 'K2': 0.01, 'K3': 1.5, 'MEMBER_THRESHOLD': 0.05, 'TABU_ITER': 100, 'TABU_TENURE': 5, 'MDL': 0, 'CPU_ONLY': 0, } num_params = len(params.keys()) if num_args == num_params: params['INPUT_FILE'] = args[1] params['NUM_CLUSTERS'] = args[2] params['THRESHOLD'] = args[3] params['MIN_ITERS'] = args[4] params['MAX_ITERS'] = args[5] params['DEVICE'] = args[6] params['FUZZINESS'] = args[7] params['DISTANCE_MEASURE'] = args[8] params['K1'] = args[9] params['K2'] = args[10] params['K3'] = args[11] params['MEMBER_THRESHOLD'] = args[12] params['TABU_ITER'] = args[13] params['TABU_TENURE'] = args[14] params['MDL'] = args[15] params['CPU_ONLY'] = args[16] elif num_args == 3: params['INPUT_FILE'] = args[1] params['NUM_CLUSTERS'] = args[2] elif 3 < num_args < num_params: params['INPUT_FILE'] = args[1] params['NUM_CLUSTERS'] = args[2] for arg in args[3:]: try: key,val = arg.split("=") key = key.upper() assert key in params.keys() if key in ['K1','K2','K3','MEMBER_THRESHOLD','THRESHOLD']: params[key] = float(val) else: params[key] = int(val) except AssertionError: print "Error: Found invalid parameter '%s'" % key except ValueError: print "Error: Invalid value '%s' for parameter '%s'" % (val,key) print usage() sys.exit(1) else: print "Invalid command line arguments." print usage() sys.exit(1) if os.path.exists(params['INPUT_FILE']): if params['INPUT_FILE'].lower().endswith(".bin"): input = open(params['INPUT_FILE'],'rb') import struct params['NUM_EVENTS'] = struct.unpack('i',input.read(4))[0] params['NUM_DIMENSIONS'] = struct.unpack('i',input.read(4))[0] else: input = open(params['INPUT_FILE']) line = input.readline() # Read the header line num_dimensions = len(line.split(DELIMITER)) num_events = 0 for line in input: num_events += 1 params['NUM_DIMENSIONS'] = num_dimensions params['NUM_EVENTS'] = num_events params['NUM_EVENTS'] -= params['NUM_EVENTS'] % 16 print "%d events removed to ensure memory alignment" % (params['NUM_EVENTS'] % 16) else: print "Invalid input file." sys.exit(1) return params
cmd = '../../bin/linux/release/cmeansMultiGPU "%s"' % params['INPUT_FILE']
cmd = '%s/../../bin/linux/release/cmeansMultiGPU "%s"' % (PROJECT_PATH,params['INPUT_FILE'])
def parseInputArgs(): args = sys.argv num_args = len(args) params = { 'INPUT_FILE' : '', 'NUM_CLUSTERS' : 0, 'THRESHOLD' : 0.0001, 'MIN_ITERS' : 0, 'MAX_ITERS' : 100, 'DEVICE' : 0, 'FUZZINESS' : 2, 'DISTANCE_MEASURE': 0, 'K1': 1.0, 'K2': 0.01, 'K3': 1.5, 'MEMBER_THRESHOLD': 0.05, 'TABU_ITER': 100, 'TABU_TENURE': 5, 'MDL': 0, 'CPU_ONLY': 0, } num_params = len(params.keys()) if num_args == num_params: params['INPUT_FILE'] = args[1] params['NUM_CLUSTERS'] = args[2] params['THRESHOLD'] = args[3] params['MIN_ITERS'] = args[4] params['MAX_ITERS'] = args[5] params['DEVICE'] = args[6] params['FUZZINESS'] = args[7] params['DISTANCE_MEASURE'] = args[8] params['K1'] = args[9] params['K2'] = args[10] params['K3'] = args[11] params['MEMBER_THRESHOLD'] = args[12] params['TABU_ITER'] = args[13] params['TABU_TENURE'] = args[14] params['MDL'] = args[15] params['CPU_ONLY'] = args[16] elif num_args == 3: params['INPUT_FILE'] = args[1] params['NUM_CLUSTERS'] = args[2] elif 3 < num_args < num_params: params['INPUT_FILE'] = args[1] params['NUM_CLUSTERS'] = args[2] for arg in args[3:]: try: key,val = arg.split("=") key = key.upper() assert key in params.keys() if key in ['K1','K2','K3','MEMBER_THRESHOLD','THRESHOLD']: params[key] = float(val) else: params[key] = int(val) except AssertionError: print "Error: Found invalid parameter '%s'" % key except ValueError: print "Error: Invalid value '%s' for parameter '%s'" % (val,key) print usage() sys.exit(1) else: print "Invalid command line arguments." print usage() sys.exit(1) if os.path.exists(params['INPUT_FILE']): if params['INPUT_FILE'].lower().endswith(".bin"): input = open(params['INPUT_FILE'],'rb') import struct params['NUM_EVENTS'] = struct.unpack('i',input.read(4))[0] params['NUM_DIMENSIONS'] = struct.unpack('i',input.read(4))[0] else: input = open(params['INPUT_FILE']) line = input.readline() # Read the header line num_dimensions = len(line.split(DELIMITER)) num_events = 0 for line in input: num_events += 1 params['NUM_DIMENSIONS'] = num_dimensions params['NUM_EVENTS'] = num_events params['NUM_EVENTS'] -= params['NUM_EVENTS'] % 16 print "%d events removed to ensure memory alignment" % (params['NUM_EVENTS'] % 16) else: print "Invalid input file." sys.exit(1) return params
if not isinstance(region.parsed, TestCase): return
def evaluate(region, document, globs): try: old_compile = doctest.compile except AttributeError: old_compile = compile doctest.compile = monkey_compile if not isinstance(region.parsed, TestCase): return result = manuel.doctest.DocTestResult() if region.parsed.group: test_name = region.parsed.group else: test_name = os.path.split(document.location)[1] exc_msg = None output = region.parsed.output if output: match = doctest.DocTestParser._EXCEPTION_RE.match(output) if match: exc_msg = match.group('msg') test_options = {doctest.ELLIPSIS: True, doctest.IGNORE_EXCEPTION_DETAIL: True, doctest.DONT_ACCEPT_TRUE_FOR_1: True, } options = region.parsed.options if options: for x in options.split(','): x = x.strip() sign = x[0] value = eval('doctest.' + x[1:]) test_options[value] = sign == '+' example = doctest.Example(region.parsed.code, output, exc_msg=exc_msg, lineno=region.lineno, options=test_options) test = doctest.DocTest([example], globs, test_name, document.location, region.lineno-1, None) runner = doctest.DocTestRunner() runner.DIVIDER = '' # disable unwanted result formatting runner.run(test, clear_globs=False) region.evaluated = result doctest.compile = old_compile
if s[-1] != '\n':
if s == '' or s[-1] != '\n':
def newlineify(s): if s[-1] != '\n': s += '\n' return s
globs = GlobWrapper(globs)
wrapped_globs = GlobWrapper(globs)
def evaluate_with(self, m, globs): globs = GlobWrapper(globs) for region in list(self): for evaluater in sort_handlers(m.evaluaters): evaluater(region, self, globs)
evaluater(region, self, globs)
evaluater(region, self, wrapped_globs) globs.update(wrapped_globs)
def evaluate_with(self, m, globs): globs = GlobWrapper(globs) for region in list(self): for evaluater in sort_handlers(m.evaluaters): evaluater(region, self, globs)
return manuel.testing.TestSuite(m, *tests, globs={'path_to_test': os.path.join(here, 'bugs.txt')})
return manuel.testing.TestSuite(m, *tests, **dict( globs={'path_to_test': os.path.join(here, 'bugs.txt')}))
def test_suite(): optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS checker = renormalizing.RENormalizing([ (re.compile(r'<zope\.testing\.doctest\.'), '<doctest.'), ]) tests = ['../index.txt', 'table-example.txt', 'README.txt', 'bugs.txt', 'capture.txt'] m = manuel.ignore.Manuel() m += manuel.doctest.Manuel(optionflags=optionflags, checker=checker) m += manuel.codeblock.Manuel() m += manuel.capture.Manuel() return manuel.testing.TestSuite(m, *tests, globs={'path_to_test': os.path.join(here, 'bugs.txt')})
self.stc.encoding = detectEncoding(self.utf8)
text = self.utf8 self.stc.encoding, self.stc.refstc.bom = detectEncoding(text)
def testUTF8(self): self.stc.encoding = detectEncoding(self.utf8) print self.stc.encoding self.stc.decodeText(self.utf8) self.stc.prepareEncoding() assert self.utf8 == self.stc.refstc.encoded
self.stc.decodeText(self.utf8)
self.stc.decodeText(text)
def testUTF8(self): self.stc.encoding = detectEncoding(self.utf8) print self.stc.encoding self.stc.decodeText(self.utf8) self.stc.prepareEncoding() assert self.utf8 == self.stc.refstc.encoded
assert self.utf8 == self.stc.refstc.encoded
assert text == self.stc.refstc.encoded def testUTF8BOM(self): text = self.utf8_bom self.stc.encoding, self.stc.refstc.bom = detectEncoding(text) print self.stc.encoding self.stc.decodeText(text) self.stc.prepareEncoding() assert text == self.stc.refstc.encoded
def testUTF8(self): self.stc.encoding = detectEncoding(self.utf8) print self.stc.encoding self.stc.decodeText(self.utf8) self.stc.prepareEncoding() assert self.utf8 == self.stc.refstc.encoded
self.stc.refstc.encoding = detectEncoding(self.utf8)
self.stc.refstc.encoding, self.stc.refstc.bom = detectEncoding(self.utf8)
def testChangeLatin(self): self.stc.refstc.encoding = detectEncoding(self.utf8) print self.stc.refstc.encoding self.stc.decodeText(self.utf8) unicode1 = self.stc.GetLine(1) print repr(unicode1) start = self.stc.FindText(0, self.stc.GetLength(), 'UTF-8') self.stc.SetTargetStart(start) self.stc.SetTargetEnd(start+5) self.stc.ReplaceTarget('latin-1') self.stc.prepareEncoding() print self.stc.refstc.encoded unicode2 = self.stc.GetLine(1) print repr(unicode2) assert unicode1 == unicode2
self.stc.refstc.encoding = detectEncoding(self.latin1)
self.stc.refstc.encoding, self.stc.refstc.bom = detectEncoding(self.latin1)
def testLatin1(self): self.stc.refstc.encoding = detectEncoding(self.latin1) print repr(self.latin1) utf8 = unicode(self.latin1, "iso-8859-1").encode('utf-8') print repr(utf8) print repr(utf8.decode('utf-8')) print repr(self.latin1.decode('latin-1')) self.stc.decodeText(self.latin1) print repr(self.stc.GetText()) print self.stc.refstc.encoding self.stc.prepareEncoding() print "encoded: " + repr(self.stc.refstc.encoded) assert self.latin1 == self.stc.refstc.encoded
self.mode.buffer.stc.setRemappedAccelerator(self.action, accelerator_text, self.append) wx.CallAfter(self.mode.resetList)
if accelerator_text: self.mode.buffer.stc.setRemappedAccelerator(self.action, accelerator_text, self.append) wx.CallAfter(self.mode.resetList) else: self.mode.setStatusText("No keystrokes recorded, so no key binding created.")
def finishRecordingHook(self, accelerator_text): self.mode.buffer.stc.setRemappedAccelerator(self.action, accelerator_text, self.append) wx.CallAfter(self.mode.resetList)
def startupFailureCallback(self, p): dprint("Couldn't run %s" % p.cmd)
def startupFailureCallback(self, job, text): dprint("Couldn't run '%s':\n error: %s" % (job.cmd, text))
def startupFailureCallback(self, p): dprint("Couldn't run %s" % p.cmd)
def startupFailureCallback(self, p):
def startupFailureCallback(self, p, text):
def startupFailureCallback(self, p): self.callback(self)
wx.CallAfter(self._job.jobout.startupFailureCallback, msg)
wx.CallAfter(self._job.jobout.startupFailureCallback, self._job, err)
def run(self): """Run the process until finished or aborted. Don't call this directly instead call self.start() to start the thread else this will run in the context of the current thread. @note: overridden from Thread
try: key = str(url) if key in cls.layout[major_mode_keyword]: cls.layout[major_mode_keyword][ukey] = cls.layout[major_mode_keyword][key] del cls.layout[major_mode_keyword][key] except UnicodeEncodeError: pass
if major_mode_keyword in cls.layout: try: key = str(url) if key in cls.layout[major_mode_keyword]: cls.layout[major_mode_keyword][ukey] = cls.layout[major_mode_keyword][key] del cls.layout[major_mode_keyword][key] except UnicodeEncodeError: pass
def getLayoutSubsequent(cls, major_mode_keyword, url): #dprint("getLayoutSubsequent") ukey = unicode(url) try: key = str(url) # Convert old style string keyword to unicode keyword if key in cls.layout[major_mode_keyword]: cls.layout[major_mode_keyword][ukey] = cls.layout[major_mode_keyword][key] del cls.layout[major_mode_keyword][key] except UnicodeEncodeError: pass try: return cls.layout[major_mode_keyword][ukey] except KeyError: return {}
self.mode.buffer.revert(text)
self.mode.buffer.revert(encoding=text)
def processMinibuffer(self, minibuffer, mode, text): #dprint("Revert to encoding %s" % text) # see if it's a known encoding try: 'test'.encode(text) # if we get here, it's valid self.mode.buffer.revert(text) if text != self.mode.buffer.stc.encoding: self.mode.setStatusText("Failed converting to %s; loaded as binary (probably not what you want)" % text) except LookupError: self.mode.setStatusText("Unknown encoding %s" % text)
print("sending %s to %s" % (result, callback))
def _do_callback(self, result, callback): # Ignore encoding errors and return an empty line instead try: result = result.decode(sys.getfilesystemencoding()) except UnicodeDecodeError: result = os.linesep
print("Windows command: %s" % command)
def run(self): """Run the process until finished or aborted. Don't call this directly instead call self.start() to start the thread else this will run in the context of the current thread. @note: overridden from Thread
print("Unix command: %s" % command)
def run(self): """Run the process until finished or aborted. Don't call this directly instead call self.start() to start the thread else this will run in the context of the current thread. @note: overridden from Thread
return cls.layout[major_mode_keyword][str(url)]
key = str(url) if key in cls.layout[major_mode_keyword]: cls.layout[major_mode_keyword][ukey] = cls.layout[major_mode_keyword][key] del cls.layout[major_mode_keyword][key] except UnicodeEncodeError: pass try: return cls.layout[major_mode_keyword][ukey]
def getLayoutSubsequent(cls, major_mode_keyword, url): #dprint("getLayoutSubsequent") try: #dprint(cls.layout[major_mode_keyword]) return cls.layout[major_mode_keyword][str(url)] except KeyError: return {}
cls.layout[major_mode_keyword][str(url)] = perspective
cls.layout[major_mode_keyword][unicode(url)] = perspective
def updateLayoutSubsequent(cls, major_mode_keyword, url, perspective): #dprint("updateLayoutSubsequent") if major_mode_keyword not in cls.layout: cls.layout[major_mode_keyword] = {} cls.layout[major_mode_keyword][str(url)] = perspective
def reportSuccess(self, text, data):
def reportSuccess(self, text, data=None):
def reportSuccess(self, text, data): import wx wx.CallAfter(self.reportSuccessGUI, text, data)
if self._stdin is not None: stdin = subprocess.PIPE else: stdin = None
def run(self): """Run the process until finished or aborted. Don't call this directly instead call self.start() to start the thread else this will run in the context of the current thread. @note: overridden from Thread
stdin=stdin,
stdin=subprocess.PIPE,
def run(self): """Run the process until finished or aborted. Don't call this directly instead call self.start() to start the thread else this will run in the context of the current thread. @note: overridden from Thread
how_likely = mode.verifyLanguage(header) cls.dprint("%s: %d" % (mode, how_likely)) if how_likely > 0: likely.append((how_likely, mode))
try: how_likely = mode.verifyLanguage(header) cls.dprint("%s: %d" % (mode, how_likely)) if how_likely > 0: likely.append((how_likely, mode)) except UnicodeDecodeError: eprint("Encoding error: file likely not marked with the correct encoding. File type may be incorrectly idendified.")
def scanLanguage(cls, header, modes): """Scan for a pattern match in the first bytes of the file. Determine if there is a 'magic' pattern in the first n bytes of the file that can associate it with a major mode.
self.heatmap = HSI.createCube('bsq', self.lines, self.samples, 1, self.dtype) data = self.heatmap.getBandRaw(0)
self.euclidean = HSI.createCube('bsq', self.lines, self.samples, 1, self.dtype) data = self.euclidean.getBandRaw(0)
def getEuclideanDistanceByBand(self,nbins=500): """Calculate the euclidean distance for every pixel in two cubes using bands Fast for BSQ cubes, slow for BIL, and extremely slow for BIP. """ self.heatmap = HSI.createCube('bsq', self.lines, self.samples, 1, self.dtype) data = self.heatmap.getBandRaw(0) working = numpy.zeros((self.lines, self.samples), dtype=numpy.float32) for i in range(self.bands): if self.bbl[i]: band1 = self.cube1.getBand(i) band2 = self.cube2.getBand(i) band = band1 - band2 working += numpy.square(band) data = numpy.sqrt(working) self.dprint(data) return self.euclidean
ctrl = CommaSeparatedListCtrl(frame, -1, initialValue=", ".join([str(i) for i in range(300)]))
ctrl = CSVCtrl(frame, -1, initialValue=", ".join([str(i) for i in range(300)]))
def SetLabel(self, value): """ Set the label's current text """ rvalue = self.label.SetLabel(value) self.Refresh(True) return rvalue
wx.PopupWindow.__init__(self, frame, style)
PopupClass.__init__(self, frame, style)
def __init__(self, frame, delay=5000, style=wx.BORDER_SIMPLE): """Creates (but doesn't show) the PopupStatusBar @param frame: the parent frame @kwarg delay: (optional) delay in milliseconds before each message decays """ wx.PopupWindow.__init__(self, frame, style) self.SetBackgroundColour("#B6C1FF") self.stack = wx.BoxSizer(wx.VERTICAL) self.SetSizer(self.stack) self.timer = wx.Timer(self) self.delay = delay self.Bind(wx.EVT_TIMER, self.OnTimer) # Take over the frame's EVT_MENU_HIGHLIGHT frame.Bind(wx.EVT_MENU_HIGHLIGHT, self.OnMenuHighlight) # List of display times self.display_times = [] self.last_is_status = False self.Hide()
if remaining < 0:
if remaining < 1:
def OnTimer(self, evt): if not self.display_times: # It is possible the timer could go off after the call to clear(), # so if the list is empty, return without restarting the timer return current = time.time() * 1000 #print("Timer at %f" % current) remove = True if (self.last_is_status and len(self.display_times) == 1): last_time, last_text = self.display_times[0] expires = last_time + self.delay #print("expires at: %d current=%d" % (expires, current)) if last_time + self.delay > current: remove = False if remove: expired_time, expired_text = self.display_times.pop(0) self.stack.Remove(expired_text) expired_text.Destroy() if self.display_times: remaining = self.delay - (current - self.display_times[0][0]) #print("Next timer: %d" % remaining) #print("\n".join("%f" % d[0] for d in self.display_times)) if remaining < 0: remaining = 1 self.timer.Start(remaining, True) self.positionAndShow() else: self.clear()
while end < length and utext[end].isalpha():
while end < length and (utext[end].isalpha() or utext[end] == "'"):
def findNextWord(self, utext, index, length): """Find the next valid word to check. Designed to be overridden in subclasses, this method takes a starting position in an array of text and returns a tuple indicating the next valid word in the string. @param utext: array of unicode chars @param i: starting index within the array to search @param length: length of the text @return: tuple indicating the word start and end indexes, or (-1, -1) indicating that the end of the array was reached and no word was found """ while index < length: if utext[index].isalpha(): end = index + 1 while end < length and utext[end].isalpha(): end += 1 return (index, end) index += 1 return (-1, -1)
end = self.stc.WordEndPosition(pos, True) start = self.stc.WordStartPosition(pos, True)
end = self.getLikelyWordEnd(pos) start = self.getLikelyWordStart(pos)
def checkWord(self, pos=None, atend=False): """Check the word at the current or specified position. @param pos: position of a character in the word (or at the start or end of the word), or None to use the current position @param atend: True if you know the cursor is at the end of the word """ if pos is None: pos = self.stc.GetCurrentPos() if atend: end = pos else: end = self.stc.WordEndPosition(pos, True) start = self.stc.WordStartPosition(pos, True) if self._spelling_debug: print("%d-%d: %s" % (start, end, self.stc.GetTextRange(start, end))) self.checkRange(start, end)
word_start = self.stc.WordStartPosition(cursor, True) word_end = self.stc.WordEndPosition(cursor, True)
word_start = self.getLikelyWordStart(cursor) word_end = self.getLikelyWordEnd(cursor) if self._spelling_debug: print("cursor in middle of word, removing styling %d-%d" % (word_start, word_end))
def processDirtyRanges(self): cursor = self.stc.GetCurrentPos() # Check that the cursor has moved off the current word and if so check # its spelling if self.current_word_start > 0: if cursor < self.current_word_start or cursor > self.current_word_end: self.checkRange(self.current_word_start, self.current_word_end) self.current_word_start = -1 # Check spelling around the region currently being typed if self.current_dirty_start >= 0: range_start, range_end = self.processDirtyRange(self.current_dirty_start, self.current_dirty_end) # If the cursor is in the middle of a word, remove the spelling # markers if cursor >= range_start and cursor <= range_end: word_start = self.stc.WordStartPosition(cursor, True) word_end = self.stc.WordEndPosition(cursor, True) mask = self._spelling_indicator_mask self.stc.StartStyling(word_start, mask) self.stc.SetStyling(word_end - word_start, 0) if word_start != word_end: self.current_word_start = word_start self.current_word_end = word_end else: self.current_word_start = -1 self.current_dirty_start = self.current_dirty_end = -1 # Process a chunk of dirty ranges needed = min(len(self.dirty_ranges), self.dirty_range_count_per_idle) ranges = self.dirty_ranges[0:needed] self.dirty_ranges = self.dirty_ranges[needed:] for start, end in ranges: if self._spelling_debug: print("processing %d-%d" % (start, end)) self.processDirtyRange(start, end)
range_start = self.stc.WordStartPosition(start, True) range_end = self.stc.WordEndPosition(end, True)
range_start = self.getLikelyWordStart(start) range_end = self.getLikelyWordEnd(end)
def processDirtyRange(self, start, end): range_start = self.stc.WordStartPosition(start, True) range_end = self.stc.WordEndPosition(end, True) if self._spelling_debug: print("processing dirty range %d-%d (modified from %d-%d): %s" % (range_start, range_end, start, end, repr(self.stc.GetTextRange(range_start, range_end)))) self.checkRange(range_start, range_end) return range_start, range_end
fh = open(url, "rb") return matcher.iterMatches(url, fh)
try: fh = open(url, "rb") return matcher.iterMatches(url, fh) except: dprint("Failed opening %s" % url) return iter([])
def getMatchGenerator(self, url, matcher): if isinstance(url, vfs.Reference): if url.scheme != "file": dprint("vfs not threadsafe; skipping %s" % unicode(url).encode("utf-8")) return url = unicode(url.path).encode("utf-8") fh = open(url, "rb") return matcher.iterMatches(url, fh)
default_menu = (("File/Print Options", 995.6), 100)
default_menu = (("File/Print Options", 995.5), 200)
def action(self, index=-1, multiplier=1): self.mode.classprefs.print_style = index
if value == d[keyword]:
if keyword in d and value == d[keyword]:
def convertSection(cls, section):
return stc.GetIndentString(7)
return stc.GetIndentString(6)
def getNewLineIndentString(self, stc, col, ind): """Return the number of characters to be indented on a new line @param stc: stc of interest @param col: column position of cursor on line @param ind: indentation in characters of cursor on line """ return stc.GetIndentString(7)
connection_cache = TimeExpiringDict(10)
connection_cache = {}
def get_transport(transport_key): t = paramiko.Transport(transport_key) t.start_client() if not t.is_active(): raise OSError("Failure to connect to: '%s'" % str(transport_key)) pub_key = t.get_remote_server_key() return t
else:
transport = client.get_channel().get_transport() if not transport.is_active(): dprint("Cached channel closed. Opening new connection for %s" % ref) client = None if client is None:
def _get_client(cls, ref): newref = cls._copy_root_reference_without_username(ref) if newref in cls.connection_cache: client = cls.connection_cache[newref] if cls.debug: dprint("Found cached sftp connection: %s" % client) else: client = cls._get_sftp(ref) if cls.debug: dprint("Creating sftp connection: %s" % client) cls.connection_cache[newref] = client return client