def getpubs(): """Get Publisher initials and names from '__Publish Name and Initials'""" import html2text # pip install html2text import re from note import Note from models import ENNote id = 90 # in table title = '__Publish Name and Initials' pubinitialsguid = '97a296aa-9698-4e29-bf74-3baa8e131ca1' territorypoisguid = '658ad719-3492-4882-b0f7-f52f67a7f7fa' #note_pubinitials = ENNote.objects.get(guid=pubinitialsguid) note_pubinitials = ENNote.objects.get(id=90) NotePubInitials = Note(note_pubinitials.content) txt = NotePubInitials.parseNoteContentToMarkDown() reobj = re.compile(r"(?P<lastname>.+?)\s*,\s*(?P<firstname>.+?)\s*-\s*_(?P<initials>[A-Z]+)") match = reobj.search(txt) if not match: raise Exception("Failed to match publisher initials in: %s" % txt) publishers = {} for match in reobj.finditer(txt): publishers[match.group("initials")] = "%s, %s" % (match.group("lastname"), match.group("firstname")) return publishers
def main(): """ main() Purpose: This program builds an SVM model for Twitter classification """ parser = argparse.ArgumentParser() parser.add_argument("-t", dest="txt", help="The files that contain the training examples", default=os.path.join(BASE_DIR, 'data/train-cleansed-A.txt') #default = os.path.join(BASE_DIR, 'data/sample.txt') ) parser.add_argument("-m", dest="model", help="The file to store the pickled model", default=os.path.join(BASE_DIR, 'models/awesome')) parser.add_argument("-g", dest="grid", help="Perform Grid Search", action='store_true', default=False) # Parse the command line arguments args = parser.parse_args() grid = args.grid # Decode arguments txt_files = glob.glob(args.txt) model_path = args.model print model_path # Cannot train on empty list if not txt_files: print 'no training files :(' exit(1) # Read the data into a Note object notes = [] for txt in txt_files: note_tmp = Note() note_tmp.read(txt) notes.append(note_tmp) # Get data from notes X = [] Y = [] for n in notes: X += zip(n.getIDs(), n.getTweets()) Y += n.getLabels() # Build model feat_obj = FeaturesWrapper() vec, svc = train(X, Y, model_path, grid, feat_obj)
def reset(cls): """Reset to default state.""" Box.reset() Note.reset() Figure.reset() Table.reset() Video.reset()
def add_note(): cookie = request.cookies.get("cookie")[0:36] conn = sqlite3.connect('Notes.db') c = conn.cursor() c.execute("SELECT username FROM users WHERE cookie = (?)", (cookie, )) conn.commit() l = c.fetchall() usr = l[0][0] if request.form['sub'] == "" or request.form['body'] == "": c.execute("SELECT * FROM notes WHERE cookie = (?)", (cookie, )) conn.commit() l = c.fetchall() nts = [] for n in l: nts.append(Note(n[1], n[2], n[3])) nts.reverse() return render_template("account.html", notes=nts, error="subject and body cannot be empty", user=usr) uid = str(uuid.uuid4()) c.execute("INSERT INTO notes VALUES (?,?,?,?)", (cookie, request.form['sub'], request.form['body'], uid)) conn.commit() c.execute("SELECT * FROM notes WHERE cookie = (?)", (cookie, )) conn.commit() l = c.fetchall() nts = [] for n in l: nts.append(Note(n[1], n[2], n[3])) nts.reverse() return render_template("account.html", notes=nts, user=usr)
def new_note(self): note = Note("Title", "") note.lastUpdated = datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S") note.id = len(self.saved_notes) print(f"generating note {note.id}") return note
def processNote(url, title, dirname): root_note = Note(url) if root_note.isNewFormat(): notes = [Note(sub_url) for sub_url in root_note.evernote_urls] else: sub_url = root_note.next_url notes = [root_note] while sub_url: note = Note(sub_url) notes.append(note) sub_url = note.next_url mkdirs(dirname, 'txt', 'traditional', 'raw') content = getContent(notes) with open('%s/%s.md' % (dirname, title), 'w') as f: f.write(content) with open('txt/%s.txt' % title, 'w') as f: f.write(content) with open('traditional/%s.md' % cc.convert(title), 'w') as f: f.write(cc.convert(content)) with open('raw/%s.md' % title, 'w') as f: f.write(getRaw(notes)) if dirname in ['critics', 'original']: word_count = [note.word_count for note in notes] with open('other/word_count_detail.txt', 'a') as f: f.write('%s %d %s\n' % (title, sum(word_count), str(word_count)))
def getpubs(): """Get Publisher initials and names from '__Publish Name and Initials'""" import html2text # pip install html2text import re from note import Note from models import ENNote id = 90 # in table title = '__Publish Name and Initials' pubinitialsguid = '97a296aa-9698-4e29-bf74-3baa8e131ca1' territorypoisguid = '658ad719-3492-4882-b0f7-f52f67a7f7fa' #note_pubinitials = ENNote.objects.get(guid=pubinitialsguid) note_pubinitials = ENNote.objects.get(id=90) NotePubInitials = Note(note_pubinitials.content) txt = NotePubInitials.parseNoteContentToMarkDown() reobj = re.compile( r"(?P<lastname>.+?)\s*,\s*(?P<firstname>.+?)\s*-\s*_(?P<initials>[A-Z]+)" ) match = reobj.search(txt) if not match: raise Exception("Failed to match publisher initials in: %s" % txt) publishers = {} for match in reobj.finditer(txt): publishers[match.group("initials")] = "%s, %s" % ( match.group("lastname"), match.group("firstname")) return publishers
def build_scale(self): """Method to build scale - called by __init__. :return: Scale object :rtype: Scale object """ scale = [] scale_degree = self.key for i in range(self.num_octaves): for interval in self.intervals: if 0 <= scale_degree <= 127: scale.append( Note( scale_degree, 100, const.NOTE_LEN_DICT[4], const.NOTE_LEN_MOD_DICT["NONE"], )) scale_degree += interval if 0 <= scale_degree <= 127: scale.append( Note( scale_degree, 100, const.NOTE_LEN_DICT[4], const.NOTE_LEN_MOD_DICT["NONE"], )) return scale
def __init__(self, rawData, userRecord): # Default values set here. self.record = userRecord self.note = Note() self.note.octave = self.record.octave self.tweetText = rawData["text"] self.screenName = rawData["user"]["screen_name"]
def return_note(client_data): """ Create a promissory note from data, sign it with the private key, and send it back to the client. :param data: dictonnary (or json file?) containing data provided by the client :return: some object (json file?) representing the note, send to the client via internet """ # some formatting/checking of "client_data" pass # create note note = Note(client_data) # create first transaction and sign new_transaction = { 'cle': client_data['public_key'], 'hash_info_payment': None, 'signature': None } note.transactions.append(new_transaction) my_sig = sign(note, MY_PRIVATE_KEY) note.transactions[-1]['signature'] = my_sig # return to client return note.display_web_format( ) # dans un format qui va bien dans tuyau internet, genre json
def main(): """ main() Purpose: This program builds an SVM model for Twitter classification """ parser = argparse.ArgumentParser() parser.add_argument("-t", dest = "txt", help = "The files that contain the training examples", default = os.path.join(BASE_DIR, 'data/twitter-train-cleansed-B.tsv') ) parser.add_argument("-m", dest = "model", help = "The file to store the pickled model", default = os.path.join(BASE_DIR, 'models/awesome') ) parser.add_argument("-g", dest = "grid", help = "Perform Grid Search", action='store_true', default = False ) # Parse the command line arguments args = parser.parse_args() grid = args.grid # Decode arguments txt_files = glob.glob(args.txt) model_path = args.model if not txt_files: print 'no training files :(' sys.exit(1) # Read the data into a Note object notes = [] for txt in txt_files: note_tmp = Note() note_tmp.read(txt) notes.append(note_tmp) # Get data from notes X = [] Y = [] for n in notes: X += zip(n.sid_list(), n.text_list()) Y += n.label_list() # Build model train(X, Y, model_path, grid)
class TestNote(unittest.TestCase): note_1 = Note(name="A5") note_2 = Note() note_3 = Note(freq=82.4) note_4 = Note() def test_str(self): self.assertEqual(str(TestNote.note_1), 'A5') def test_eq(self): print("the note is: " + str(TestNote.note_4)) self.assertTrue(TestNote.note_2 == TestNote.note_4) self.assertFalse(TestNote.note_1 == TestNote.note_3) # different notes self.assertFalse( TestNote.note_2 == TestNote.note_1) # different octaves def test_equals(self): self.assertTrue( TestNote.note_1.equals(other=TestNote.note_2)) # different octaves self.assertFalse( TestNote.note_1.equals(other=TestNote.note_3)) # different notes def test_set_length(self): TestNote.note_3.set_length(7) self.assertEqual(TestNote.note_3.length, 7) # check that set_length raises value errors with self.assertRaises(ValueError): TestNote.note_3.set_length("apple")
class Melody(object): notes = [ ] def __init__(self): self.NOTE = Note() def transpose(self, k): value = [ ] for note in self.notes: i = self.NOTE.index(note) j = i + k note2 = self.NOTE.note(j) value.append(note2) return value def reverse(self): value = [ ] for note in self.notes: value = [note] + value return value def invert(self): base = self.NOTE.index(self.notes[0]) value = [ ] for note in self.notes: k = self.NOTE.index(note) kk = 2*base - k note2 = self.NOTE.note(kk) value.append(note2) return value
def select_notes(self, melody): allowed_notes = [] tonic = melody.key if "m" in melody.key: tonic = tonic[0:-1] allowed_notes.append(tonic) start_note = tonic + '4' # arbitrary octave for computing notes current_note = Note(name=start_note) scale_steps = scales[melody.scale]['halfsteps'] for steps in scale_steps: interval = Interval(note_1=current_note, halfsteps=steps) next_note = interval.get_topnote() note_name = next_note.get_name()[0:-1] allowed_notes.append(note_name) current_note = next_note octave = randint(melody.octave_range[0], melody.octave_range[1]) for x in range(16): # pick note and add to melody note_name = choice(allowed_notes) note_name += str(octave) melody.append(Note(name=note_name)) # pick next octave in range bottom = max(melody.octave_range[0], octave - 1) top = min(melody.octave_range[1], octave + 1) if randint(1, 10) < 2: octave = choice([bottom, top]) return melody
def save_note(self, title: str, body: str): note = Note(title, body) note.lastUpdated = datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S") note.id = len(self.saved_notes) self.saved_notes.append(note) print(f"saving note {note.id}") return note
def test_a3_b4_c2_is_sorted_to_c2_a3_b4(self): a_3 = Note('a3') b_4 = Note('b4') c_2 = Note('c2') u = Unit([a_3, b_4, c_2], Fraction(1, 2)) print(u) self.assertEqual(u.notes, [c_2, a_3, b_4])
def save(self): buff = self.get_buffer() text = buff.get_text(buff.get_start_iter(), buff.get_end_iter()) if not self.note: import utils self.note = Note(utils.generate_filename(), utils.user_configurations['TIXPATH'], text) self.note.write_text_to_file(text) return self.note
def update_note_selection_info(self, note_id, selector_id, selected_time, post_time): _note_id = int(note_id) if selector_id != None: _selector_id = int(selector_id) else: _selector_id = None _note = Note(note_id) _note.update_selection_info(selector_id=_selector_id, selected_time=selected_time, post_time=post_time) ## CLEAN_OLD_CACHE ## cache.delete("entity_key_note_id_%s" % self.entity_id) cache.delete("entity_note_context_list_%s" % self.entity_id) cache.delete("note_context_%s" % note_id) if _selector_id == None: for _doc in NoteSelection.objects.filter(note_id=_note_id): _doc.delete() else: _doc = NoteSelection.objects.filter(note_id=_note_id).first() if _doc == None: self.__ensure_entity_obj() _doc = NoteSelection( selector_id=_selector_id, selected_time=selected_time, post_time=post_time, entity_id=self.entity_id, note_id=_note_id, root_category_id=self.entity_obj.category.pid, category_id=self.entity_obj.category_id, neo_category_group_id=Category( self.entity_obj.neo_category_id).get_group_id(), neo_category_id=self.entity_obj.neo_category_id, ) _doc.save() _weight = None if self.entity_obj.weight <= 0: self.update(weight=1, ) _note_context = _note.read() CreateNoteSelectionMessageTask.delay( user_id=_note_context['creator_id'], user_unread_message_count=User( _note_context['creator_id']).get_unread_message_count( ), entity_id=self.entity_id, note_id=_note_id, ) else: _doc.selector_id = _selector_id _doc.selected_time = selected_time _doc.post_time = post_time _doc.save()
def add_note(self): print "adding note" if len(self.notes) == self.max_notes: return notes = [note.midi for note in self.notes] next_note = get_next_note(notes, self.chord, key=self.key) n = Note(next_note, volume=.05) n.play(-1, fade_ms=500) self.notes.append(n)
def find_all(self): res = self.__firebase.get('/' + self.__collection, None) jsoncontent = json.loads(str(res).replace("\'", "\"")) notes = [] for note_id, value in res.items(): n = Note("") n.from_json(jsoncontent[note_id]) notes.append(n) return notes
def parse_metadata(root): notes = {} for page in root.find('pageList').findall('page'): pg = int(page.attrib['number']) annotlist = page.find('annotationList') for annot in annotlist.findall('annotation'): if ( annot.attrib['type'] == "1" and pg <= self.ui.documentWidget.num_pages ): base = annot.find('base') try: author = base.attrib['author'] except KeyError: author = '' try: text = base.attrib['contents'] except KeyError: text = '' try: cdate = base.attrib['creationDate'] except KeyError: cdate = '' try: mdate = base.attrib['modifyDate'] except KeyError: mdate = '' try: preamble = base.attrib['preamble'] except KeyError: preamble = PREAMBLE try: uname = base.attrib['uniqueName'] # notorius-1-0 becomes 0 uid = int(uname.rsplit('-')[-1]) except KeyError: try: uid = max(notes.keys()) except ValueError: uid = 0 boundary = base.find('boundary') x = float(boundary.attrib['l']) y = float(boundary.attrib['t']) size = self.ui.documentWidget.Document.page( pg).pageSizeF() pos = QtCore.QPointF(x*size.width(), y*size.height()) note = Note(text, preamble, page = pg, pos = pos, uid = uid) notes[uid] = note note.cdate = datetime.datetime.strptime(cdate, "%Y-%m-%dT%H:%M:%S") note.mdate = datetime.datetime.strptime(mdate, "%Y-%m-%dT%H:%M:%S") note.update() else: self.okular_notes.append(annot) return notes
def print_notes(self, detailed: bool): print('---------- Printing Notes ----------') print('Chord Name: ' ) # Add the Root Note modded by whatever to find the right note if detailed: for i, note in enumerate(self.notes): Note.print_note_all(self.notes[i]) else: for i, note in enumerate(self.notes): Note.print_note_pitch(self.notes[i]) print('------------------------------------')
def generate_tact(self): while self.length > 0: note = Note(self.length, self.scale, self.time, self.key, self.octaves_range) note.generate_note() new_note = list(note.note) self.notes.append(new_note) self.time += note.duration self.length -= note.duration
def note_list(): note = Note() df = note.get_deta() note_list = df p = re.compile(r"<[^>]*?>") q = re for a in note_list: a["body"] = p.sub("", a["body"]).replace(" ", "") a["publishAt"] = re.sub("-", "/", a["publishAt"]) return render_template('note.html', note_list=note_list,)
def get_note(id): note = Note() note_body = note.get_note(id) name = note_body["name"] body = note_body["body"] publishAt = note_body["publish_at"] publishAt = re.sub("-", "/", publishAt) eyecatch = note_body["eyecatch"] style = """<style type = "text/css" >.nav-item >a{color:#252525;} .nav-item>a:after{background-color:#252525;} </style>""" return render_template('note_body.html', name=name, body=body, publishAt=publishAt, eyecatch=eyecatch, style=style)
def find_all(self): response = requests.get(self.__url) jsoncontent = json.loads(response.content) notes = [] if response.json(): for note_id in response.json(): n = Note("") n.from_json(jsoncontent[note_id]) notes.append(n) return notes
def load_from_file(self, file): with open(file, 'r') as json_file: notes_to_load = json.load(json_file) for id in notes_to_load: json_note = notes_to_load[id] note = Note(json_note['text'], json_note['title'], json_note['group'], json_note['tags']) note.date = json_note['date'] note.update_date = json_note['update'] note.id = json_note['id'] self.notes[id] = note
def test_delete(): db = Database(":memory:") n = Note("hello, world #t1 #t2 #t1", datetime.now()) n2 = Note("goodbye #t1 #3", datetime.now()) db.insert_note(n) db.insert_note(n2) assert (db.count() == 2) db.delete_note(1) assert (db.count() == 1) db.delete_note(2) assert (db.count() == 0) db.close()
def __str__(self): note_list = [] note = Note(self._note_id) note_list.append(str(note)) #pdb.set_trace() for ch in self._pattern: if ch == 'W': note = note.whole(True) else: note = note.half(True) note_list.append(str(note)) return str(note_list)
def getAll(): cursor = getCollection().find({}) notes = [] for document in cursor: try: note = Note(document['name']) note.contents = document['contents'] note.id = document['_id'] notes.append(note) except KeyError: print("Invalid note entry") return notes
def main(): """ main() Purpose: This program builds an SVM model for Twitter classification """ parser = argparse.ArgumentParser() parser.add_argument("-t", dest = "txt", help = "Files that contain the training examples (e.g. data/demo.tsv)", ) parser.add_argument("-m", dest = "model", help = "The file to store the pickled model (e.g. models/demo.model)", ) # Parse the command line arguments args = parser.parse_args() if (not args.txt) or (not args.model): parser.print_help() exit(1) # Decode arguments txt_files = glob.glob(args.txt) model_path = args.model if not txt_files: print 'no training files :(' sys.exit(1) # Read the data into a Note object notes = [] for txt in txt_files: note_tmp = Note() note_tmp.read(txt) notes.append(note_tmp) # Get data from notes X = [] Y = [] for n in notes: X += zip(n.sid_list(), n.text_list()) Y += n.label_list() # Build model train(X, Y, model_path)
def interval_guess(self, num_of_games): start = time.time() num_correct = 0 for _ in range(num_of_games): low_note = Note(random.choice(NOTES)) semitones = random.choice(range(len(INTERVALS))) note_to_guess = Note(low_note.up(semitones)) question = self.ask_interval_question(low_note, semitones) if self.handle_interval_response(low_note, note_to_guess, question, semitones): num_correct += 1 print(f"Answered {num_correct} correct in {round(time.time()-start, 2)} seconds.")
def index(): index = "index" note = Note() df = note.get_deta() note_list = df[0:3] p = re.compile(r"<[^>]*?>") q = re for a in note_list: a["body"] = p.sub("", a["body"]).replace(" ", "") a["publishAt"] = re.sub("-", "/", a["publishAt"]) return render_template('index.html', note_list=note_list, index=index)
def cleanup_unread(): """Destroy unread notes older than 30 days.""" import time while True: seek_time = time.time() for note in os.listdir('%s/data/' % HERE): file_mtime = os.stat('%s/data/%s' % (HERE, note))[8] if ((seek_time - file_mtime) >= 2592000 and 'hashcash.db' not in note): Note.secure_remove('%s/data/%s' % (HERE, note)) time.sleep(86400) # wait for 1 day
def kick_drum_line(composition, drop_number): new_note_list = [] duration = 44100 / 8 drop_increment = duration / drop_number for i, note in enumerate(composition.get_notes()): effect_start_time = note.get_start_time() - duration effect_end_time = note.get_start_time() if effect_start_time < 0 : new_note_list.append(note) continue if i != 0: if note.is_kick(): rollback = 0 indices_in_notes_list = len(new_note_list) - 1 #keep rolling back until "in drop time" notes are popped off while True: last_note = new_note_list[-1] if last_note.get_start_time() > (last_note.get_end_time() - duration): new_note_list.pop() else: break last_note = new_note_list[-1] last_note.set_end_time(effect_start_time) scale = composition.get_scale() closest = utilities.find_closest(scale, note.get_frequency()) index = scale.index(closest) + drop_number ampl = note.get_amplitude() for x in range(0, drop_number): new_s_time = int(effect_start_time + x * drop_increment) new_e_time = int(effect_start_time + (x+1) * drop_increment) new_freq = scale[index] nn = Note(new_s_time, new_e_time, new_freq, ampl) nn.set_kick(True) new_note_list.append(nn) index -=1 new_note_list.append(note) else: new_note_list.append(note) composition.notes = new_note_list
def edit_notes(mn, config_store, args): """ Display search results and allow edits. :param Mininote mn: Mininote instance :param ConfigStore config_store: User configuration :param argparse.Namespace args: Command line options """ from match_notes import match_notes text_editor = args.text_editor before_notes = list(mn.search(args.note)) before_formatted_notes = '\r\n'.join(map(str, before_notes)) after_formatted_notes = text_editor.edit(before_formatted_notes) try: nonblank_lines = filter(lambda line: len(line.strip()) > 0, after_formatted_notes.splitlines()) after_notes = map(Note.parse_from_str, nonblank_lines) except NoteParseError: logger.error("Unable to parse changes to notes. Session is saved in {}".format(text_editor.path)) return text_editor.cleanup() before_notes_reparsed = map(lambda n: Note.parse_from_str(str(n)), before_notes) pairs = match_notes(before_notes_reparsed, after_notes) for before, after in pairs: if before is None: mn.add_note(after_notes[after]) elif after is None: mn.delete_note(before_notes[before]) elif before_notes[before].text != after_notes[after].text: before_notes[before].text = after_notes[after].text mn.update_note(before_notes[before])
def main(): parser = argparse.ArgumentParser() parser.add_argument("-i", dest = "txt", help = "The files to be predicted on (e.g. data/demo.tsv)", ) parser.add_argument("-m", dest = "model", help = "The file to store the pickled model (e.g. models/demo.model)", ) parser.add_argument("-o", dest = "out", help = "The directory to output predicted files (e.g. data/predictions)", ) # Parse the command line arguments args = parser.parse_args() if (not args.txt) or (not args.model) or (not args.out): parser.print_help() exit(1) # Decode arguments txt_files = glob.glob(args.txt) model_path = args.model out_dir = args.out # Available data if not txt_files: print 'no predicting files :(' exit(1) # Load model with open(model_path+'.model', 'rb') as fid: clf = pickle.load(fid) with open(model_path+'.dict', 'rb') as fid: vec = pickle.load(fid) # Predict labels for each file for pfile in txt_files: note = Note() note.read(pfile) XNotNormalized = zip(note.sid_list(), note.text_list()) X = XNotNormalized #X = normalize_data_matrix(XNotNormalized) # Predict labels = predict( X, clf, vec ) # output predictions outfile = os.path.join(out_dir, os.path.basename(pfile)) note.write( outfile, labels )
def get_all_notes(): G_ = Note('G#', 'Ab', None) G = Note('G', '', G_) F_ = Note('F#', 'Gb', G) F = Note('F', '', F_) E = Note('E', '', F) D_ = Note('D#', 'Eb', E) D = Note('D', '', D_) C_ = Note('C#', 'Db', D) C = Note('C', 'C', C_) B = Note('B', '', C) A_ = Note('A#', 'Bb', B) A = Note('A', '', A_) G_.NextNote = A A.PrevNote = G_ return [A, A_, B, C, C_, D, D_, E, F, F_, G, G_]
def _import(self): self.noteList = {} for infile in glob.glob(os.path.join(os.path.expanduser("~/.conboy"), "*.note")): try: parser = xml.sax.make_parser() handler = textHandler() parser.setContentHandler(handler) parser.parse(infile) except Exception: import traceback print traceback.format_exc() try: note = Note() uuid = handler._content.split("\n", 1)[0].strip(" \t\r\n") uuid = getValidFilename(uuid) path = os.path.join(note.NOTESPATH, uuid) if os.path.exists(path + ".txt"): index = 2 while os.path.exists(os.path.join(note.NOTESPATH, "%s %s.txt" % (path, unicode(index)))): index = index + 1 uuid = "%s %s" % (os.path.basename(path), unicode(index)) note.uuid = uuid + ".txt" note.write(handler._content) try: from rfc3339.rfc3339 import strtotimestamp mtime = strtotimestamp(handler._last_change) lpath = os.path.join(Note.NOTESPATH, note.uuid) os.utime(lpath, (-1, mtime)) except Exception: import traceback print traceback.format_exc() except Exception: import traceback print traceback.format_exc() self._set_running(False) self.on_finished.emit()
def _import(self): self.noteList = {} for infile in glob.glob( \ os.path.join(os.path.expanduser('~/.conboy'), '*.note')): try: parser = xml.sax.make_parser() handler = textHandler() parser.setContentHandler(handler) parser.parse(infile) except Exception, err: import traceback print traceback.format_exc() try: note = Note() uuid = handler._content.split('\n', 1)[0].strip(' \t\r\n') uuid = getValidFilename(uuid) path = os.path.join(note.NOTESPATH, uuid) if os.path.exists(path + '.txt'): index = 2 while (os.path.exists(os.path.join( \ note.NOTESPATH,'%s %s.txt' \ % (path, \ unicode(index))))): index = index + 1 uuid = ('%s %s' \ % (os.path.basename(path), \ unicode(index))) note.uuid = uuid + '.txt' note.write(handler._content) try: from rfc3339.rfc3339 import strtotimestamp mtime = strtotimestamp(handler._last_change) lpath = os.path.join(Note.NOTESPATH, note.uuid) os.utime(lpath, (-1, mtime)) except Exception, err: import traceback print traceback.format_exc() except Exception, err: import traceback print traceback.format_exc()
def show_notes(noteId=None): if noteId: notes = (list(db.notes.find({'noteId': noteId}))) print notes if notes: note = Note.from_json(notes[0]) # convert to python object note_title = note.title content = note.content noteId = note.noteId return render_template('show_note.html', title=note_title, content=content, noteId=noteId)
def __init__(self): logging.debug('Initializing Data class') self.DueDate = DueDate() self.Reminder = Reminder() self.Note = Note() self.ID = 'Database' self.dbDict = { 'Database':{ 'DueDate':{ DueDate.returndDict() }, 'Reminder':{ Reminder.returnrDict() }, 'Note':{ Note.returnnDict() } } }
def from_interval_shorthand(self, startnote, shorthand, up=True): """Empty the container and add the note described in the startnote and shorthand. See core.intervals for the recognized format. Examples: >>> nc = NoteContainer() >>> nc.from_interval_shorthand('C', '5') ['C-4', 'G-4'] >>> nc.from_interval_shorthand('C', '5', False) ['F-3', 'C-4'] """ self.empty() if type(startnote) == str: startnote = Note(startnote) n = Note(startnote.name, startnote.octave, startnote.dynamics) n.transpose(shorthand, up) self.add_notes([startnote, n]) return self
def show_post(): """Return the random URL after posting the plaintext.""" new_url = request.form["new_url"] note = Note(new_url) note.plaintext = request.form['paste'] passphrase = request.form.get('pass', False) token = request.form['hashcash'] if not utils.verify_hashcash(token): return redirect(url_for('index', error='hashcash')) if passphrase: note.set_passphrase(passphrase) note.encrypt() note.duress_key() return render_template('post.html', random=note.url, passphrase=note.passphrase, duress=note.dkey) else: note.encrypt() return render_template('post.html', random=note.url)
def emit_note(t): if t in punctuation: return _emit_rest(t) fv = _word_to_fv(t) sorted_scores = _score_notes_no_octave(fv) note = '' top_scores = selection.choose_top_score(sorted_scores) if(len(top_scores) > 1): note = random.choice(top_scores) else: note = top_scores[0] note_to_emit = Note(note+str(octave.choose_octave(t))) note_to_emit.accidental = accidental.choose_accidental(fv, note_to_emit.pitch) note_to_emit.duration = duration.calculate_duration(t) note_to_emit.fv = fv note_to_emit.text = t return note_to_emit
def read_file(self, filename): mid = MidiFile(filename) # An internal clock that keeps track of current time based on the # cumulative elapsed time delta of each note current_time = 0 elapsed_time = 0 for _, track in enumerate(mid.tracks): for message in track: # Increment internal clock current_time += message.time current_time if message.type == 'note_on': # Create a new note for this note_on (no time information # yet) note = Note( message.channel, message.note, message.velocity, elapsed_time, current_time) self.notes.append(note) elapsed_time = 0 elif message.type == 'note_off': end_note = Note( message.channel, message.note, message.velocity) for note in reversed(self.notes): if note == end_note and note.duration == None: note.add_duration(current_time) break # If we haven't started a new note, we need to increment # the elapsed time since the last note if message.type != 'note_on': elapsed_time += message.time
def post(self, user_id): note_id = self.get_argument('note_id', None) if note_id is None or re.match(r'[a-z0-9]{32}', str(note_id)): note = Note( note_id, user_id, Note.STATUS_ACTIVE, self.get_argument('title'), self.get_argument('text'), datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') ) self.get_manager().save(note) self.write(tornado.web.escape.json_encode({ 'code': 'OK', 'note': note.as_dict() })) else: self.write(tornado.web.escape.json_encode({ 'code': 'WRONG_PARAMS', 'note': None }))
def update_note(): data = request.get_json(force=True, silent=True) print "POST data received" print data title = data.get("title") content = data.get("content") noteId = int(data.get("noteId")) the_note = db.notes.find_one({'noteId': noteId}) if the_note: print type(the_note) my_note = Note.from_json(the_note) my_note.title = title my_note.content = content else: my_note = Note(title, content, noteId=noteId) print the_note db.notes.find_and_modify(query={'noteId': noteId}, update=my_note.to_json(), upsert=True) return json.dumps({"success": True})
def fetch_url(random_url): """Return the decrypted note. Begin short destruction timer. Keyword arguments: random_url -- Random URL representing the encrypted note.""" note = Note(random_url) if not note.exists(): return render_template('404.html'), 404 elif not note.decrypt() and request.method != 'POST': return render_template('key.html', random=note.url) elif request.method == 'POST': passphrase = request.form['pass'] note.set_passphrase(passphrase) if passphrase == note.dkey: note.secure_remove() return render_template('note.html', text=utils.duress_text()) if note.decrypt(): note.secure_remove() return render_template('note.html', text=note.plaintext) else: return render_template('keyerror.html', random=note.url)
def __init__(self, SCALE): NOTES, FREQ_DICT = SCALE self.note = Note(NOTES, FREQ_DICT) self.rhythm = Rhythm() self.dynamics = Dynamics() self.equalizerFactor = { } self.equalizerFactor[-0.1] = 1.0 self.equalizerFactor[220] = 1.0 self.equalizerFactor[440] = 0.7 self.equalizerFactor[880] = 0.35 self.equalizerFactor[1760] = 0.15 self.equalizerFactor[3520] = 0.15 self.equalizerFactor[7040] = 0.15 self.equalizerFactor[14080] = 0.15 self.equalizerFactor[28160] = 0.15 self.equalizerFactor[56320] = 0.15 self.equalizerBreakPoints = [-0.1, 220, 440, 880, 1760, 3520, 7040, 14080, 28160, 56320]
def _emit_rest(t): note_to_emit = Note(globals.REST_NOTE) note_to_emit.text = t note_to_emit.duration = None # from Michelle if(t == ','): note_to_emit.duration = 0.25 if(t == '.'): note_to_emit.duration = 1.0 if(t == '?'): note_to_emit.duration = 1.0 if(t == '!'): note_to_emit.duration = 1.0 if(t == '-'): note_to_emit.duration = 0.25 if(t == ':'): note_to_emit.duration = 0.125 if(t == ';'): note_to_emit.duration = 0.5 # for joe: TILDEROCK if(t == '~'): note_to_emit.duration = 0.03125 if note_to_emit.duration == None: return None return note_to_emit
def __init__(self): self.DueDate = DueDate() self.Reminder = Reminder() self.Note = Note() self.ID = 'Database' self.dbDict = { 'Database':{ 'DueDate':{ 'Name': self.DueDate.returnName(), 'Date': self.DueDate.returnDate(), 'Time': self.DueDate.returnTime() }, 'Reminder':{ 'Date': self.Reminder.returnDate(), 'Time': self.Reminder.returnTime() }, 'Note':{ 'Note': self.Note.returnNote() } } } logging.debug('Initializing Data class')
class Main(gtk.Window): def __init__(self): self.worker = None self.flags_correo = True self.flags_buffer = True gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL) gtk.Window.set_position(self, gtk.WIN_POS_CENTER_ALWAYS) self.set_resizable(False) self.set_title(_("Documenting of Failures")) self.connect("delete_event", self.on_delete) # Icono de la ventana if os.path.isfile(ICON_PATH): self.set_icon_from_file(ICON_PATH) # Banner superior >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> if os.path.isfile(TOP_BANNER_PATH): self.img_top_banner = gtk.Image() self.img_top_banner.set_from_file(TOP_BANNER_PATH) size = self.img_top_banner.size_request() self.set_size_request(size[0], -1) # -1 porque no importa el alto # Identificación >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> self.lbl_titulo = gtk.Label(_("titulo:")) self.lbl_autor = gtk.Label(_("autor:")) self.lbl_correo = gtk.Label(_("correo:")) self.txt_titulo = gtk.Entry(20) self.txt_autor = gtk.Entry(30) self.txt_correo = gtk.Entry() self.txt_correo.set_text(_("email@xxxxxxxxxxx")) self.txt_correo.connect('event', self.on_txt_correo_clicked) self.tbl_indetif = gtk.Table(2, 6, True) self.tbl_indetif.attach(self.lbl_titulo, 0, 1, 0, 1) self.tbl_indetif.attach(self.txt_titulo, 1, 5, 0, 1) self.tbl_indetif.attach(self.lbl_autor, 0, 1, 1, 2) self.tbl_indetif.attach(self.txt_autor, 1, 2, 1, 2) self.tbl_indetif.attach(self.lbl_correo, 2, 3, 1, 2) self.tbl_indetif.attach(self.txt_correo, 3, 5, 1, 2) self.tbl_indetif.show() # Descripcion de la falla >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> self.textview = gtk.TextView() self.textbuffer = self.textview.get_buffer() self.textview.set_editable(True) self.textbuffer.set_text(_("\n\n\t\t\t\tWrite the problem happened \ on your computer")) self.textview.connect('event', self.on_entry_buffer_clicked) self.scrolledwindow = gtk.ScrolledWindow() self.scrolledwindow.set_size_request(-1,100) self.scrolledwindow.set_policy(gtk.POLICY_AUTOMATIC, \ gtk.POLICY_AUTOMATIC) self.scrolledwindow.add(self.textview) self.alineacion = gtk.Alignment(xalign=0.5, yalign=0.3, xscale=0.98, \ yscale=0.5) self.alineacion.add(self.scrolledwindow) marco = gtk.Frame(_("Enter the details of the fault (be as \ specific as possible):")) marco.set_border_width(2) marco.add(self.alineacion) # Pestañas >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> # Sección de dispositivos self.tabla = gtk.Table(4, 4, True) self.check_lspci = gtk.CheckButton("PCI-PUERTOS") self.check_lspci.set_active(True) self.check_lsusb = gtk.CheckButton("dispositivo USB") self.check_lsusb.set_active(True) self.check_ram = gtk.CheckButton("RAM/SWAP/Buffers-MEMORIA") self.check_ram.set_active(True) self.check_df = gtk.CheckButton(_("Disk Space")) self.check_df.set_active(True) self.check_cpu = gtk.CheckButton("CPU-----") self.check_cpu.set_active(True) self.check_tm = gtk.CheckButton(_("Motherboard-TARJETA-MADRE")) self.check_tm.set_active(True) self.check_all = gtk.CheckButton(_("Select All")) self.check_all.connect("toggled", self.selectalldis, "Todos") self.check_all.set_active(False) self.tabla.attach(self.check_lspci, 0, 1, 0, 1) self.tabla.attach(self.check_lsusb, 0, 1, 1, 2) self.tabla.attach(self.check_ram, 0, 1, 2, 3) self.tabla.attach(self.check_df, 1, 2, 0, 1) self.tabla.attach(self.check_cpu, 1, 2, 1, 2) self.tabla.attach(self.check_tm, 1, 2, 2, 3) self.tabla.attach(self.check_all, 3, 4, 0, 1) self.tabla.show() # Seccion de informaión del sistema self.tabla1 = gtk.Table(4, 4, True) self.check_acelgraf = gtk.CheckButton(_("Graphics Acceleration")) self.check_acelgraf.set_active(True) self.check_xorg = gtk.CheckButton(_("Screen Server")) self.check_xorg.set_active(True) self.check_repo = gtk.CheckButton(_("Repositories")) self.check_repo.set_active(True) self.check_tpart = gtk.CheckButton(_("Partition table")) self.check_tpart.set_active(True) self.check_prefe = gtk.CheckButton(_("Priority APT")) self.check_prefe.set_active(True) self.check_ired = gtk.CheckButton(_("Network Interfaces")) self.check_ired.set_active(True) self.check_all2 = gtk.CheckButton(_("Select All")) self.check_all2.connect("toggled", self.selectalldis2, "Todos") self.check_all2.set_active(True) self.tabla1.attach(self.check_acelgraf, 0, 1, 0, 1) self.tabla1.attach(self.check_xorg, 0, 1, 1, 2) self.tabla1.attach(self.check_repo, 0, 1, 2, 3) self.tabla1.attach(self.check_tpart, 1, 2, 0, 1) self.tabla1.attach(self.check_prefe, 1, 2, 1, 2) self.tabla1.attach(self.check_ired, 1, 2, 2, 3) self.tabla1.attach(self.check_all2, 3, 4, 0, 1) self.tabla1.show() # Sección del Kernel self.tabla2 = gtk.Table(4, 4, True) self.check_vers = gtk.CheckButton(_("Version")) self.check_vers.set_active(True) self.check_modu = gtk.CheckButton(_("Modules")) self.check_modu.set_active(True) self.check_all3 = gtk.CheckButton(_("Select All")) self.check_all3.connect("toggled", self.selectalldis3, "Todos") self.check_all3.set_active(True) self.tabla2.attach(self.check_vers, 0, 1, 0, 1) self.tabla2.attach(self.check_modu, 0, 1, 1, 2) self.tabla2.attach(self.check_all3, 3, 4, 0, 1) self.tabla2.show() self.notebook = gtk.Notebook() self.notebook.set_tab_pos(gtk.POS_TOP) label = gtk.Label(_("Devices")) self.notebook.insert_page(self.tabla, label, 1) label = gtk.Label(_("System Information")) self.notebook.insert_page(self.tabla1, label, 2) label = gtk.Label(_("Kernel")) self.notebook.insert_page(self.tabla2, label, 3) marco_1 = gtk.Frame(_("Select the data to be sent:")) marco_1.set_border_width(2) marco_1.add(self.notebook) # Envío >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> self.check_gdocum = gtk.CheckButton(_("See document (not send).")) self.check_gdocum.set_active(False) self.tbl_envio = gtk.Table(1, 5, True) self.tbl_envio.attach(self.check_gdocum, 0, 5, 0, 1) self.tbl_envio.show() # Caja botones >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> self.btn_cerrar = gtk.Button(stock=gtk.STOCK_CLOSE) self.btn_cerrar.connect("clicked", self.__close) self.btn_ayuda = gtk.Button(stock=gtk.STOCK_HELP) self.btn_ayuda.connect("clicked", self.on_btn_ayuda_clicked) self.btn_aceptar = gtk.Button(stock=gtk.STOCK_OK) self.btn_aceptar.connect("clicked", self.on_btn_aceptar_clicked) button_box = gtk.HBox(False, False) button_box.pack_start(self.btn_cerrar, False, False, 10) button_box.pack_start(self.btn_ayuda, False, False, 5) button_box.pack_start(self.btn_aceptar, False, False, 315) #---------------------------------------------------------------------- # Ensamblaje de la ventana vbox = gtk.VBox(False, 0) if os.path.isfile(TOP_BANNER_PATH): vbox.add(self.img_top_banner) # Separadores self.separator1 = gtk.HSeparator() self.separator2 = gtk.HSeparator() vbox.add(self.separator1) vbox.add(self.tbl_indetif) vbox.add(marco) vbox.add(marco_1) vbox.add(self.tbl_envio) vbox.add(self.separator2) vbox.pack_start(button_box, False, False, 0) self.add(vbox) self.show_all() # Accesibilidad atk_acc(self.txt_titulo, self.lbl_titulo) atk_acc(self.txt_autor, self.lbl_autor) atk_acc(self.txt_correo, self.lbl_correo) def selectalldis(self, widget, data=None): if self.check_all.get_active() == True: self.check_lspci.set_active(True) self.check_lsusb.set_active(True) self.check_ram.set_active(True) self.check_df.set_active(True) self.check_cpu.set_active(True) self.check_tm.set_active(True) else: self.check_lspci.set_active(False) self.check_lsusb.set_active(False) self.check_ram.set_active(False) self.check_df.set_active(False) self.check_cpu.set_active(False) self.check_tm.set_active(False) def selectalldis2(self, widget, data=None): if self.check_all2.get_active() == True: self.check_acelgraf.set_active(True) self.check_xorg.set_active(True) self.check_repo.set_active(True) self.check_tpart.set_active(True) self.check_prefe.set_active(True) self.check_ired.set_active(True) else: self.check_acelgraf.set_active(False) self.check_xorg.set_active(False) self.check_repo.set_active(False) self.check_tpart.set_active(False) self.check_prefe.set_active(False) self.check_ired.set_active(False) def selectalldis3(self, widget, data=None): if self.check_all3.get_active() == True: self.check_vers.set_active(True) self.check_modu.set_active(True) else: self.check_vers.set_active(False) self.check_modu.set_active(False) # Eventos ----------------------------------------------------------------- def on_btn_ayuda_clicked(self, widget=None): hilo = threading.Thread(target=launch_help, args=(self)) hilo.start() def on_btn_aceptar_clicked(self, widget): errors = self.__validate_form() # Si la lista de errores contiene algo entonces no es valido. if errors != []: message_error(list_to_lines(errors)) return False if self.__is_viewonly(): self.note.write_to_file() worker = ThreadTxtEditor(self) worker.start() else: self.note.send_note() worker = ThreadWebBrowser(self) worker.start() message_info(_("The sending of the note was successful...!\n\n")+str(self.note.msg)) self.txt_correo.set_text("") return True def on_txt_correo_clicked(self, widget, event, data=None): if (self.flags_correo): if event.type == gtk.gdk.BUTTON_RELEASE: self.txt_correo.set_text("") self.flags_correo = False def on_entry_buffer_clicked(self, widget, event, data=None): if (self.flags_buffer): if event.type == gtk.gdk.BUTTON_RELEASE: self.textbuffer.set_text("") self.flags_buffer = False def on_delete(self, widget, data=None): return not self.__close() # Funciones Internas ------------------------------------------------------ def __validate_form(self): messages = [] #TODO: Cambiar este textbuffer por un Entry con multilineas self.textbuffer = self.textview.get_buffer() start, end = self.textbuffer.get_bounds() self.dnota = self.textbuffer.get_text(start, end) # Validar título if is_empty_string(self.txt_titulo.get_text()): messages.append(_("- You need to enter a title.")) # Validar Autor if is_empty_string(self.txt_autor.get_text()): messages.append(_("- You need to enter your name.")) # Validar correo if not is_valid_email(self.txt_correo.get_text()): messages.append(_("- You need to enter your address \ email.")) # Validar descipción if is_empty_string(self.dnota): messages.append(_("- Take a moment and describe the failure.")) # Validar opciones seleccionadas if not self.__build_note(): messages.append(_("- Select at least 1 option box \ Data to Send.")) # Validaciones sólo para el caso de enviar if not self.__is_viewonly(): # Chequear internet if not have_internet_access(): messages.append(_("- It has an active internet connection. \ Select the Do not Send.")) return messages def __is_viewonly(self): return self.check_gdocum.get_active() def __build_note(self): selection = False self.note = Note(self.txt_titulo.get_text(), self.txt_autor.get_text(), self.txt_correo.get_text(), self.dnota) self.note.is_viewonly = self.__is_viewonly() self.note.append_defaults() #TODO: Ordenar estos comandos desde lo mas general a lo mas especifico if self.check_lspci.get_active() == True: command = "lspci -nn" subtitle = _("Devices connected by PCI") self.note.add_log_output(command, subtitle) selection = True if self.check_tm.get_active() == True: command = "lspci | grep 'Host bridge:'" subtitle = _("Motherboard") self.note.add_log_output(command, subtitle) selection = True if self.check_lsusb.get_active() == True: command = "lsusb" subtitle = _("Devices connected by USB port") self.note.add_log_output(command, subtitle) selection = True if self.check_acelgraf.get_active() == True: command = "glxinfo | grep -A4 'name of display:'" subtitle = _("Graphics Acceleration") self.note.add_log_output(command, subtitle) selection = True if self.check_ired.get_active() == True: command = "cat /etc/network/interfaces" subtitle = _("Information Network interfaces") self.note.add_log_output(command, subtitle) selection = True if self.check_prefe.get_active() == True: command = "cat /etc/apt/preferences" subtitle = _("Information /etc/apt/preferences") self.note.add_log_output(command, subtitle) selection = True if self.check_ram.get_active() == True: command = "free -m" subtitle = _("RAM Memory, Swap, and Buffer (in MB)") self.note.add_log_output(command, subtitle) selection = True if self.check_df.get_active() == True: command = "df -h" subtitle = _("Free space on storage devices:") self.note.add_log_output(command, subtitle) selection = True if self.check_tpart.get_active() == True: command = "fdisk -l" subtitle = _("Partition Table") self.note.add_log_output(command, subtitle) selection = True if self.check_cpu.get_active() == True: command = "cat /proc/cpuinfo" subtitle = _("Information processor") self.note.add_log_output(command, subtitle) self.vdis = True if self.check_xorg.get_active() == True: command = "cat /var/log/Xorg.0.log | grep 'error'" subtitle = _("Xorg error information") self.note.add_log_output(command, subtitle) selection = True if self.check_repo.get_active() == True: command = "cat /etc/apt/sources.list" subtitle = _("Information repositories") self.note.add_log_output(command, subtitle) selection = True if self.check_modu.get_active() == True: command = "lsmod" subtitle = _("List of kernel modules") self.note.add_log_output(command, subtitle) selection = True if self.check_vers.get_active() == True: command = "uname -a" subtitle = _("Kernel version") self.note.add_log_output(command, subtitle) selection = True return selection def __close(self, widget=None): if self.txt_titulo.get_text() or self.txt_autor.get_text(): response = message_question(_("In closing, all procedures \ that is generating Documenting of Failures will be closed. \n\n\t \ Do you want to exit the application?"), self) if response == gtk.RESPONSE_YES: self.destroy() gtk.main_quit() else: self.destroy() gtk.main_quit()
def __build_note(self): selection = False self.note = Note(self.txt_titulo.get_text(), self.txt_autor.get_text(), self.txt_correo.get_text(), self.dnota) self.note.is_viewonly = self.__is_viewonly() self.note.append_defaults() #TODO: Ordenar estos comandos desde lo mas general a lo mas especifico if self.check_lspci.get_active() == True: command = "lspci -nn" subtitle = _("Devices connected by PCI") self.note.add_log_output(command, subtitle) selection = True if self.check_tm.get_active() == True: command = "lspci | grep 'Host bridge:'" subtitle = _("Motherboard") self.note.add_log_output(command, subtitle) selection = True if self.check_lsusb.get_active() == True: command = "lsusb" subtitle = _("Devices connected by USB port") self.note.add_log_output(command, subtitle) selection = True if self.check_acelgraf.get_active() == True: command = "glxinfo | grep -A4 'name of display:'" subtitle = _("Graphics Acceleration") self.note.add_log_output(command, subtitle) selection = True if self.check_ired.get_active() == True: command = "cat /etc/network/interfaces" subtitle = _("Information Network interfaces") self.note.add_log_output(command, subtitle) selection = True if self.check_prefe.get_active() == True: command = "cat /etc/apt/preferences" subtitle = _("Information /etc/apt/preferences") self.note.add_log_output(command, subtitle) selection = True if self.check_ram.get_active() == True: command = "free -m" subtitle = _("RAM Memory, Swap, and Buffer (in MB)") self.note.add_log_output(command, subtitle) selection = True if self.check_df.get_active() == True: command = "df -h" subtitle = _("Free space on storage devices:") self.note.add_log_output(command, subtitle) selection = True if self.check_tpart.get_active() == True: command = "fdisk -l" subtitle = _("Partition Table") self.note.add_log_output(command, subtitle) selection = True if self.check_cpu.get_active() == True: command = "cat /proc/cpuinfo" subtitle = _("Information processor") self.note.add_log_output(command, subtitle) self.vdis = True if self.check_xorg.get_active() == True: command = "cat /var/log/Xorg.0.log | grep 'error'" subtitle = _("Xorg error information") self.note.add_log_output(command, subtitle) selection = True if self.check_repo.get_active() == True: command = "cat /etc/apt/sources.list" subtitle = _("Information repositories") self.note.add_log_output(command, subtitle) selection = True if self.check_modu.get_active() == True: command = "lsmod" subtitle = _("List of kernel modules") self.note.add_log_output(command, subtitle) selection = True if self.check_vers.get_active() == True: command = "uname -a" subtitle = _("Kernel version") self.note.add_log_output(command, subtitle) selection = True return selection
def getNote(link): response = sendMessage('GET', link) return Note.fromXml(response.note.element)
response = sendMessage('POST', index, note) return response.notelink.href def updateNote(link, note): sendMessage('PUT', link, note) def deleteNote(link): sendMessage('DELETE', link) if __name__ == '__main__': print getAllNotes() newNote = Note('thing 2', 'title', 'body') newLink = addNote(newNote) print getAllNotes() for title, link in getAllNotes(): note = getNote(link) print note.id print note.title print note.body print newNote.title = 'this is the new title' updateNote(newLink, newNote) print getAllNotes()
class SFM(object): # pitch registers transpositionSemitones = 0 octaveNumber = 3 # tempo registers tempo = 60 currentBeatValue = 60.0/tempo currentBeat = 0 totalDuration = 0.0 # dynamics registers crescendoSpeed = 1.1 currentCrescendoSpeed = crescendoSpeed crescendoBeatsRemaining = 0.0 maximumAmplitude = 0.0 # tuple registers duration = 60.0/tempo amplitude = 1.0 decay = 1.0 # I/O input = "" ######################################################### # initialize Note, Rhythm, and Dynamics objects def __init__(self, SCALE): NOTES, FREQ_DICT = SCALE self.note = Note(NOTES, FREQ_DICT) self.rhythm = Rhythm() self.dynamics = Dynamics() self.equalizerFactor = { } self.equalizerFactor[-0.1] = 1.0 self.equalizerFactor[220] = 1.0 self.equalizerFactor[440] = 0.7 self.equalizerFactor[880] = 0.35 self.equalizerFactor[1760] = 0.15 self.equalizerFactor[3520] = 0.15 self.equalizerFactor[7040] = 0.15 self.equalizerFactor[14080] = 0.15 self.equalizerFactor[28160] = 0.15 self.equalizerFactor[56320] = 0.15 self.equalizerBreakPoints = [-0.1, 220, 440, 880, 1760, 3520, 7040, 14080, 28160, 56320] # self.tempo = 60 # self.currentBeatValue = 60.0/self.tempo # self.octaveNumber = 3 def equalize(self, freq): a, b = interval(freq, self.equalizerBreakPoints) f = mapInterval(freq, a,b, self.equalizerFactor[a], self.equalizerFactor[b]) # print freq, a, b, f return f # return tuple as string given frequency, # duration, decay, and amplitude def _tuple(self, freq, duration): output = `freq` output += " "+`duration` a = self.amplitude a = a*self.equalize(freq) output += " "+`a` output += " "+`self.decay` return output # return tuple as string from frequency of token # and root and suffix of token def tuple(self, freq, root, suffix): if suffix.find(",") > -1: thisDuration = self.duration*(1 - self.rhythm.breath) output = self._tuple(freq, thisDuration) output += "\n" output += self._tuple(0, self.duration - thisDuration) else: output = self._tuple(freq, self.duration) return output def updateRhythm(self, cmd): self.currentBeatValue, self.duration = self.rhythm.value(cmd, self) def emitNote(self, token): if self.crescendoBeatsRemaining > 0: self.amplitude = self.amplitude*self.currentCrescendoSpeed self.crescendoBeatsRemaining -= self.currentBeatValue freq, root, suffix = self.note.freq(token, self.transpositionSemitones, self.octaveNumber) self.output += self.tuple(freq, root, suffix) + "\n" # summary data self.totalDuration += self.duration self.currentBeat += self.currentBeatValue if self.amplitude > self.maximumAmplitude: self.maximumAmplitude = self.amplitude def executeCommand(self, ops): cmd = ops[0] # if cmd is a rhythm symbol, change value of duration register if self.rhythm.isRhythmOp(cmd): self.updateRhythm(cmd) # if cmd is a tempo command, change value of the tempo register if self.rhythm.isTempoOp(cmd): self.tempo = self.rhythm.tempo[cmd] self.updateRhythm(cmd) if cmd == "tempo": self.tempo = float(ops[1]) self.updateRhythm(cmd) # if cmd is an articulation command, change value of the decay register if self.rhythm.isArticulationOp(cmd): self.decay = self.rhythm.decay[cmd] # if cmd is a dynamics command, change value of the amplitude register if self.dynamics.isDynamicsConstant(cmd): self.amplitude = self.dynamics.value[cmd] # crescendo and decrescendo if cmd == "crescendo" or cmd == "cresc": self.crescendoBeatsRemaining = float(ops[1]) self.currentCrescendoSpeed = self.crescendoSpeed if cmd == "decrescendo" or cmd == "decresc": self.crescendoBeatsRemaining = float(ops[1]) self.currentCrescendoSpeed = 1.0/self.crescendoSpeed # pitch transposition if cmd == "octave": self.octaveNumber = int(ops[1]) if cmd == "transpose": self.transpositionSemitones = int(ops[1]) # pass special commands through if cmd[0] == '@': CMD = catList2(ops) CMD = CMD[:len(CMD)]+"\n" self.output += CMD # tuples: returns a string of tuples from input = solfa text def tuples(self): # split intput into list of tokens self.input = self.input.replace("\n", " ") tokens = self.input.split(" ") # make sure there are not empty list elements tokens = filter( lambda x: len(x), tokens) # initialize output self.output = "" for token in tokens: if self.note.isNote(token): self.emitNote(token) else: ops = token.split(":") ops = filter(lambda x: len(x) > 0, ops) if DEBUG == ON: self.output += "cmd: "+ `ops`+"\n" self.executeCommand(ops) return self.output