def render_all(): notes = set() static_pages = set() Path(output_directory).mkdir(parents=True, exist_ok=True) Path(image_directory).mkdir(parents=True, exist_ok=True) for file in os.listdir(input_directory): filename = os.fsdecode(file) clean_filename = os.path.splitext(filename)[0] file_path = f"{input_directory}{filename}" if filename.endswith(RENDERER_CONFIG["input_file_extensions"]): output_file = f"{output_directory}{clean_filename}.html" pypandoc.convert_file( file_path, "html5", outputfile=output_file, extra_args=(RENDERER_CONFIG["pandoc_extra_args"])) update_img_tags(output_file) add_toc(file_path, output_file) metadata = get_metadata(file_path) if "summary" not in metadata: metadata["summary"] = get_summary_from_html(output_file) if "static_url" in metadata: static_pages.add(Note(output_file, clean_filename, **metadata)) else: notes.add(Note(output_file, clean_filename, **metadata)) elif filename.endswith(RENDERER_CONFIG["image_file_extensions"]): try: os.symlink(file_path, f"{image_directory}/{filename}") # link already exists, so we can skip except FileExistsError: pass tag_set = get_tags(notes) published_notes = (note for note in notes if note.publication_date is not None) published_notes = sorted(published_notes, reverse=True, key=lambda n: n.publication_date) return published_notes, tag_set, static_pages
def __init__(self, summary, filename): Note.__init__(self) self.title = "Image" self.summary = summary path, ext = os.path.splitext(filename) with open(filename, 'rb') as fp: data = fp.read() self.image_data = "data:image/%s;base64,%s" % (ext, base64.b64encode(data))
def __init__(self): self.notes = [] inbox = Note() self.inbox = Inbox(inbox) taskl = Note() self.tasklist = TaskList(taskl)
def note_creator(arg: Union[str, int, PCls]) -> Note_: """ """ if type(arg) is str: name, acc = n.name_acc(arg[:-1]) octave = int(arg[-1:]) # 0 <= octave <= 9 return Note(n.name_to_id[name] + nn.accidental_to_id[acc] + octave * 12) elif type(arg) is int: return Note(arg) else: raise TypeError
def print_fitness_vals(fq_curr, fq_trgt, fitness): for f in range(len(fq_trgt)): curr_trgt = Note(fq_trgt[f],1) curr_freq = Note(fq_curr[f][0],2) app.logger.critical(f"Midis | {round(curr_trgt.midi, 3)} - {round(curr_freq.midi, 3)} | = {round(abs(curr_trgt.midi - curr_freq.midi), 3)}") app.logger.critical(f"\n\nFitness: {fitness}\n") for f in range(len(fq_trgt)): curr_trgt = Note(fq_trgt[f],1) curr_freq = Note(fq_curr[f][0],2) app.logger.critical(f"Freqs | {round(curr_trgt.freq, 3)} - {round(curr_freq.freq, 3)} | = {round(abs(curr_trgt.freq - curr_freq.freq), 3)}") return
def fitness_from_sampled_freqs(fr, tr): ky_in_d = {} ch_v = np.ones((len(tr),1)) * (1.0 * 10) tr_as_m = [] m_out = np.ones((len(tr),1)) * (1.0 * 10) s_ini = 0 for t in tr: tr_as_m.append(Note(t,1).midi) for t in range(len(tr_as_m)): k = tr_as_m[t] s_mod, k_collect = sub_search(fr[s_ini:], k) s_ini += s_mod ky_in_d[k] = np.array(k_collect) temp = ky_in_d[k] - k if len(temp) > 0: ch_v[t] = (np.min(np.abs(temp))) if ch_v[t] in temp: m_out[t] = ch_v[t] + k else: m_out[t] = -1*ch_v[t] + k else: m_out[t] = -1 assert len(ch_v) == len(tr) ch_v = np.transpose(ch_v) x = np.mean( (ch_v**2)/tr_as_m ) x *= 100 # return x, ch_v return x, m_out
def __getitem__(self, uid: str) -> Note: if uid not in self.keys(): raise KeyError return Note( EncryptedDocument(storage=self._storage, uid=uid, doc_key=self._doc_key))
def note_detection(image, templates): """ It takes whole picture and detect each staff and all notes :param image: Image with music notation :param templates: Images with templates :return: List of objects of class Note """ ind = 0 notes = [] repeat = False scale = 1 for im in crop(image): extent = im.shape[1]/800. notes_aux = [] coordinates = lines_detection(im, scale) imag = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) for temp in templates: if 'half' in temp: length = 1./2 else: length = 1./4 template = cv2.imread(temp, 0) w, h = template.shape[::-1] res = cv2.matchTemplate(imag, template, cv2.TM_CCOEFF_NORMED) threshold = 0.8 loc = np.where(res >= threshold) loc = np.asarray(loc) c = list(zip(loc[1], loc[0])) c = sorted(c, key=lambda x: x[0]) for pt in c: pitch = pitch_define(int(pt[1] + h/2), coordinates) note = Note(pitch_dict[pitch], ind, length, pt[0], pt[1]) for n in notes_aux: if abs(pt[0] - n.x) < 6*extent: repeat = True break if not repeat: notes_aux.append(note) ind += 1 repeat = False notes_aux = sorted(notes_aux, key=lambda no: no.x) notes += notes_aux for pt in notes_aux: cv2.rectangle(im, (pt.x, pt.y), (pt.x + w, pt.y + h), (0, 0, 255), 1) plt.imshow(im) plt.show() return notes
def create_note(self) -> Note: """ Creates a new note with a random uid, inserts it into the index and returns it :return: """ # Create new empty document at a new uid doc = EncryptedDocument(self._storage, self._storage.generate_uid()) # Push note into index self._document[doc.uid] = None # Create a note instance to wrap the document, and return it return Note(doc, new=True)
def readSimpleNote(fname): n = Note() f = open(fname, "r") tmp = f.read() f.close() tmp = tmp.splitlines() n.setTitle(tmp[0]) # collect body msg = "" for i in range(1, len(tmp)): msg += tmp[i] + "\n" n.setBody(msg) return n
def sub_search(fr_set, tr): note_tol = 12 # allowance of one octave # note_tol = 6 # allowance of half an octave f_pot = [] ini_id = -1 for i in range(len(fr_set)): m = Note(fr_set[i],1).midi if (-1*note_tol <= (m - tr) <= 0): f_pot.append(m) elif (0 < (m - tr) <= note_tol): if ini_id == -1: ini_id = i f_pot.append(m) elif ((m - tr) > note_tol): break # print("potential f: ") # print(f_pot) return (ini_id, f_pot)
def add_note(self): text = input("Enter the text of the note: ") tag = input("Enter the tag of the note: ") self.notebook.new_note(Note(text, tag))
def __init__(self, summary, data, header=False): Note.__init__(self) self.title = "Table" self.summary = summary self.header = header self.data = data
def __init__(self, summary, scope_data): Note.__init__(self) self.title = "Scope Screenshot" self.summary = summary self.image_data = "data:image/png;base64,%s" % (base64.b64encode(scope_data))
def installParcel(parcel, oldVersion=None): view = parcel.itsView # Create our one collection of indexDefinition mappings; when each gets # created, its __init__ will add it to this collection automagically. AllIndexDefinitions.update(parcel, "allIndexDefinitions") Reference.update(parcel, "currentContact") MailPreferences.update(parcel, "MailPrefs") Reference.update(parcel, "currentMeEmailAddress") cur = Reference.update(parcel, "currentIncomingAccount") cur1 = Reference.update(parcel, "currentOutgoingAccount") if cur.item is None: cur.item = IMAPAccount( itsView=view, displayName=_(u"Incoming Mail"), replyToAddress=EmailAddress(itsView=view), password=password.Password(itsView=view), ) if cur1.item is None: cur1.item = SMTPAccount(itsView=view, displayName=_(u"Outgoing Mail"), password=password.Password(itsView=view)) trashCollection = ListCollection.update(parcel, "trashCollection", displayName=_(u"Trash")) notes = KindCollection.update(parcel, "noteCollection", kind=Note.getKind(view), recursive=True) mine = UnionCollection.update(parcel, "mine") # it would be nice to get rid of these intermediate fully-fledged # item collections, and replace them with lower level Set objects mineNotes = IntersectionCollection.update(parcel, "mineNotes", sources=[mine, notes]) nonOccurrenceFilter = NonOccurrenceFilter(None, parcel) nonRecurringNotes = FilteredCollection.update( parcel, "nonRecurringNotes", source=mineNotes, filterMethod=(nonOccurrenceFilter, "isNonOccurrence"), filterAttributes=[EventStamp.occurrenceFor.name, EventStamp.modificationFor.name, EventStamp.occurrences.name], ) nonRecurringNotes.addIndex("__adhoc__", "numeric") allContentItems = KindCollection.update(parcel, "allContentItems", kind=ContentItem.getKind(view), recursive=True) contentItems = FilteredCollection.update( parcel, "contentItems", source=allContentItems, filterMethod=(nonOccurrenceFilter, "isNotPureOccurrence"), filterAttributes=[EventStamp.occurrenceFor.name, EventStamp.modificationFor.name], ) allReminders = KindCollection.update(parcel, "allReminders", kind=Reminder.getKind(view), recursive=True) allFutureReminders = FilteredCollection.update( parcel, "allFutureReminders", source=allReminders, filterMethod=(UnexpiredFilter(None, parcel), "notExpired"), filterAttributes=[UnexpiredFilter.findValuePair[0]], ) allFutureReminders.addIndex( "reminderPoll", "method", method=(UnexpiredFilter(None, parcel), "compare"), monitor=[UnexpiredFilter.findValuePair[0]], ) # the "All" / "My" collection allCollection = SmartCollection.update( parcel, "allCollection", displayName=_(u"Dashboard"), source=nonRecurringNotes, exclusions=trashCollection, trash=None, ) # kludge to improve on bug 4144 (not a good long term fix but fine for 0.6) allCollection.addIndex("__adhoc__", "numeric") events = EventStamp.getCollection(view) eventComparator = EventComparator.update(parcel, "eventComparator") EventStamp.addIndex( events, "effectiveStart", "method", method=(eventComparator, "cmpStartTime"), monitor=(EventStamp.startTime, EventStamp.allDay, EventStamp.anyTime), kind=ContentItem.getKind(view), ) EventStamp.addIndex( events, "effectiveEnd", "method", method=(eventComparator, "cmpEndTime"), monitor=(EventStamp.startTime, EventStamp.allDay, EventStamp.anyTime, EventStamp.duration), kind=ContentItem.getKind(view), ) # floatingEvents need to be reindexed in effectiveStart and effectiveEnd # when the floating timezone changes filterAttributes = [entry[0] for entry in _FILTER_ATTRIBUTES] floatingEvents = FilteredCollection.update( parcel, "floatingEvents", source=events, filterMethod=(FloatingEventFilter(None, parcel), "isFloatingEvent"), filterAttributes=filterAttributes, ) floatingEvents.addIndex("__adhoc__", "numeric") # UTCEvents need to be reindexed in effectiveStartNoTZ and effectiveEndNoTZ # when the floating timezone changes, because UTC events are treated # specially UTCEvents = FilteredCollection.update( parcel, "UTCEvents", source=events, filterMethod=(UTCEventFilter(None, parcel), "isUTCEvent"), filterAttributes=filterAttributes, ) UTCEvents.addIndex("__adhoc__", "numeric") longEvents = FilteredCollection.update( parcel, "longEvents", source=events, filterMethod=(LongEventFilter(None, parcel), "isLongEvent"), filterAttributes=[EventStamp.duration.name], ) longEvents.addIndex("effectiveStart", "subindex", superindex=(events, events.__collection__, "effectiveStart")) longEvents.addIndex("effectiveEnd", "subindex", superindex=(events, events.__collection__, "effectiveEnd")) filterAttributes = (EventStamp.rruleset.name, EventStamp.occurrences.name) masterFilter = "view.hasTrueValues(uuid, '%s', '%s')" % filterAttributes nonMasterFilter = "not " + masterFilter masterEvents = FilteredCollection.update( parcel, "masterEvents", source=events, filterExpression=masterFilter, filterAttributes=list(filterAttributes) ) nonMasterEvents = FilteredCollection.update( parcel, "nonMasterEvents", source=events, filterExpression=nonMasterFilter, filterAttributes=list(filterAttributes), ) MasterEventWatcher.update(parcel, "masterEventWatcher", targetCollection=masterEvents) EventStamp.addIndex( masterEvents, "recurrenceEnd", "method", method=(eventComparator, "cmpRecurEnd"), monitor=(EventStamp.recurrenceEnd,), ) EventStamp.addIndex( masterEvents, "effectiveStart", "subindex", superindex=(events, events.__collection__, "effectiveStart") ) locations = KindCollection.update(parcel, "locations", kind=Location.getKind(view), recursive=True) locations.addIndex("locationName", "value", attribute="displayName", nodefer=True) mailCollection = mail.MailStamp.getCollection(view) kind = mail.EmailAddress.getKind(view) emailAddressCollection = KindCollection.update(parcel, "emailAddressCollection", kind=kind, recursive=True) emailComparator = EmailComparator.update(parcel, "emailComparator") emailAddressCollection.addIndex( "emailAddress", "method", method=(emailComparator, "cmpAddress"), monitor="emailAddress", nodefer=True ) emailAddressCollection.addIndex( "fullName", "method", method=(emailComparator, "cmpFullName"), monitor="fullName", nodefer=True ) emailAddressCollection.addIndex( "both", "method", method=(emailComparator, "cmpBoth"), monitor=("emailAddress", "fullName"), nodefer=True, kind=kind, ) # Contains all current me addresses (that is, referenced by an account) currentMeEmailAddresses = ListCollection.update(parcel, "currentMeEmailAddresses") currentMeEmailAddresses.addIndex( "emailAddress", "method", method=(emailComparator, "cmpAddress"), monitor="emailAddress" ) # Contains all current and former me addresses meEmailAddressCollection = ListCollection.update(parcel, "meEmailAddressCollection") meEmailAddressCollection.addIndex( "emailAddress", "method", method=(emailComparator, "cmpAddress"), monitor="emailAddress" ) inSource = ToMeFilter.makeCollection(parcel, "inSource", mailCollection) # this index must be added to shield from the duplicate # source (mailCollection) that is going to be in mine inSource.addIndex("__adhoc__", "numeric") # The "In" collection inCollection = SmartCollection.update( parcel, "inCollection", displayName=_(u"In"), source=inSource, trash=trashCollection, visible=True ) mine.addSource(inCollection) outSource = FromMeFilter.makeCollection(parcel, "outSource", mailCollection) # this index must be added to shield from the duplicate # source (mailCollection) that is going to be in mine outSource.addIndex("__adhoc__", "numeric") # The "Out" collection outCollection = SmartCollection.update( parcel, "outCollection", displayName=_(u"Out"), visible=True, source=outSource, trash=trashCollection ) mine.addSource(outCollection) allEventsCollection = IntersectionCollection.update(parcel, "allEventsCollection", sources=[allCollection, events]) searchResultsUnfiltered = SmartCollection.update(parcel, "searchResultsUnfiltered", displayName=messages.UNTITLED) searchResults = DifferenceCollection.update( parcel, "searchResults", sources=[searchResultsUnfiltered, masterEvents], displayName=messages.UNTITLED ) TriageStatusReminder.update(parcel, "triageStatusReminder") startup.Startup.update(parcel, "installWatchers", invoke=__name__ + ".installWatchers") tzInstallParcel(parcel)
def readTodoFile(fname): nbtmp = NoteBook() nbtmp.setTitle("Updated TODO") nbtmp.tmpNoteFile = "notebook-tmp-C.md" f = open(fname, "r") tmp = f.read() f.close() # print("tmp file content--------------") tmp = tmp.splitlines() # print(tmp) # add trailing newlines for easier parsing # for i in range(len(tmp)): # tmp[i] += "\n" # filter header out c = 0 while True: if c >= len(tmp): break line = tmp[c] # print("skipping {}".format(line)) mtitle = regexes.REtitle.match(line) if mtitle: break c += 1 # print("skipping {}".format(c)) ns = [] hashes = [] bodys = [] body = "" while c < len(tmp): line = tmp[c] # print("{}".format( line )) mtitle = regexes.REtitle.match(line) mhash = regexes.REhash.match(line) mdate = regexes.REdate.match(line) mmdate = regexes.REmdate.match(line) mdiv = regexes.REdiv.match(line) if mtitle: n = Note() bodys.append(body) body = "" s = mtitle.group(1) s = s.replace("'", "") # strip ' from title (causes problems with rm) n.setTitle(s) ns.append(n) # ni += 1 elif mdiv: # do nothing True elif mhash: s = mhash.group(1) hashes.append(s) elif mdate: n.setDate(mdate.group(1)) elif mmdate: n.setDate(mmdate.group(1)) else: body += line + "\n" c += 1 bodys.append(body) # append last hanging body # print("###########################################") for i, n in enumerate(ns): body = bodys[i + 1] # print("last char: vvv{}vvv".format(body[-2:])) # if (body[-2:] == "\n"): # print("newline detected") # body = body[:-2] # body = body[:-2] #strip trailing newline # body = body.rstrip() # body += "\n" # body += "\n" n.setBody(body) # print("{} -- {}".format(i, n.title)) # print("{} hash is {}".format(i, n.hash() )) # print("----") # print("{}".format(n.body)) # print("----") # print("{}".format(body)) nbtmp.addNote(n) return nbtmp
def process_message(msg, user): """ Aqui ocorre o processamento de fato das mensagens. No momento em que o programa chega aqui, já é garantido que o user é o usuário atual. Checa-se se a mensagem é algum dos comandos; se não for, tenta parsear as notas. Se não forem notas, envia uma mensagem de erro ao usuário. """ global current_user global user_timestamp text = msg['text'] # Em primeiro lugar, atualizar a timestamp do usuário user_timestamp = msg['date'] # Verificar se a mensagem é um dos comandos: end, notas, tempo ou musicas if NOTES_COMMAND_PATTERN.match(text): notes = get_available_notes() bot.sendMessage(user.id, 'As notas disponíveis são:') bot.sendMessage(user.id, '\n'.join(notes)) bot.sendMessage(user.id, 'Podem ser escritas em maiúsculo ou minúsculo.') return elif END_COMMAND_PATTERN.match(text): bot.sendMessage(user.id, 'Sessão finalizada.') shift_users() return m = TEMPO_COMMAND_PATTERN.match(text) if m: tempo = int(m.group(1) or user.tempo) user.tempo = tempo bot.sendMessage(user.id, 'Tempo: %d' % user.tempo) return m = SONGS_COMMAND_PATTERN.match(text) if m: song = m.group(1) if song: song = int(song) - 1 song = songs[song] bot.sendMessage(user.id, 'Ajustando tempo para %d...' % song.tempo, reply_markup={'hide_keyboard': True}) user.tempo = song.tempo bot.sendMessage(user.id, song.name) bot.sendMessage(user.id, song.seq) text = song.seq else: song_list = list(enumerate(songs, 1)) text = '\n'.join('%d. %s' % (i, s.name) for i, s in song_list) kb_columns = 3 kb_rows = math.ceil(len(songs) / kb_columns) bot.sendMessage( user.id, text, reply_markup={'keyboard':[ ['/musica %d' % i for i, _ in song_list if math.ceil(i / kb_columns) == row] for row in range(1, kb_rows+1) ], 'one_time_keyboard': True}) return # Neste ponto, o usuário deve ter enviado notas de fato note_list = [] for note in text.split(): if not NOTE_PATTERN.match(note): bot.sendMessage(user.id, 'Nota inválida: ' + note) continue note, length = note.split(',') note_list.append(Note(note, int(length))) arduino_notes = ' '.join(n.to_arduino(user.tempo) for n in note_list) + ' \n' arduino.write(arduino_notes)
def installParcel(parcel, oldVersion=None): view = parcel.itsView # Create our one collection of indexDefinition mappings; when each gets # created, its __init__ will add it to this collection automagically. AllIndexDefinitions.update(parcel, "allIndexDefinitions") Reference.update(parcel, 'currentContact') MailPreferences.update(parcel, 'MailPrefs') Reference.update(parcel, 'currentMeEmailAddress') cur = Reference.update(parcel, 'currentIncomingAccount') cur1 = Reference.update(parcel, 'currentOutgoingAccount') if cur.item is None: cur.item = IMAPAccount(itsView=view, displayName=_(u'Incoming Mail'), replyToAddress=EmailAddress(itsView=view), password=password.Password(itsView=view)) if cur1.item is None: cur1.item = SMTPAccount( itsView=view, displayName=_(u'Outgoing Mail'), password=password.Password(itsView=view), ) trashCollection = ListCollection.update(parcel, 'trashCollection', displayName=_(u"Trash")) notes = KindCollection.update(parcel, 'noteCollection', kind=Note.getKind(view), recursive=True) mine = UnionCollection.update(parcel, 'mine') # it would be nice to get rid of these intermediate fully-fledged # item collections, and replace them with lower level Set objects mineNotes = IntersectionCollection.update(parcel, 'mineNotes', sources=[mine, notes]) nonOccurrenceFilter = NonOccurrenceFilter(None, parcel) nonRecurringNotes = FilteredCollection.update( parcel, 'nonRecurringNotes', source=mineNotes, filterMethod=(nonOccurrenceFilter, 'isNonOccurrence'), filterAttributes=[ EventStamp.occurrenceFor.name, EventStamp.modificationFor.name, EventStamp.occurrences.name ]) nonRecurringNotes.addIndex('__adhoc__', 'numeric') allContentItems = KindCollection.update(parcel, 'allContentItems', kind=ContentItem.getKind(view), recursive=True) contentItems = FilteredCollection.update( parcel, 'contentItems', source=allContentItems, filterMethod=(nonOccurrenceFilter, 'isNotPureOccurrence'), filterAttributes=[ EventStamp.occurrenceFor.name, EventStamp.modificationFor.name ]) allReminders = KindCollection.update(parcel, 'allReminders', kind=Reminder.getKind(view), recursive=True) allFutureReminders = FilteredCollection.update( parcel, 'allFutureReminders', source=allReminders, filterMethod=(UnexpiredFilter(None, parcel), 'notExpired'), filterAttributes=[UnexpiredFilter.findValuePair[0]], ) allFutureReminders.addIndex('reminderPoll', 'method', method=(UnexpiredFilter(None, parcel), 'compare'), monitor=[UnexpiredFilter.findValuePair[0]]) # the "All" / "My" collection allCollection = SmartCollection.update( parcel, 'allCollection', displayName=_(u"Dashboard"), source=nonRecurringNotes, exclusions=trashCollection, trash=None, ) # kludge to improve on bug 4144 (not a good long term fix but fine for 0.6) allCollection.addIndex('__adhoc__', 'numeric') events = EventStamp.getCollection(view) eventComparator = EventComparator.update(parcel, 'eventComparator') EventStamp.addIndex(events, 'effectiveStart', 'method', method=(eventComparator, 'cmpStartTime'), monitor=(EventStamp.startTime, EventStamp.allDay, EventStamp.anyTime), kind=ContentItem.getKind(view)) EventStamp.addIndex(events, 'effectiveEnd', 'method', method=(eventComparator, 'cmpEndTime'), monitor=(EventStamp.startTime, EventStamp.allDay, EventStamp.anyTime, EventStamp.duration), kind=ContentItem.getKind(view)) # floatingEvents need to be reindexed in effectiveStart and effectiveEnd # when the floating timezone changes filterAttributes = [entry[0] for entry in _FILTER_ATTRIBUTES] floatingEvents = FilteredCollection.update( parcel, 'floatingEvents', source=events, filterMethod=(FloatingEventFilter(None, parcel), 'isFloatingEvent'), filterAttributes=filterAttributes) floatingEvents.addIndex('__adhoc__', 'numeric') # UTCEvents need to be reindexed in effectiveStartNoTZ and effectiveEndNoTZ # when the floating timezone changes, because UTC events are treated # specially UTCEvents = FilteredCollection.update(parcel, 'UTCEvents', source=events, filterMethod=(UTCEventFilter( None, parcel), 'isUTCEvent'), filterAttributes=filterAttributes) UTCEvents.addIndex('__adhoc__', 'numeric') longEvents = FilteredCollection.update( parcel, 'longEvents', source=events, filterMethod=(LongEventFilter(None, parcel), 'isLongEvent'), filterAttributes=[EventStamp.duration.name]) longEvents.addIndex('effectiveStart', 'subindex', superindex=(events, events.__collection__, 'effectiveStart')) longEvents.addIndex('effectiveEnd', 'subindex', superindex=(events, events.__collection__, 'effectiveEnd')) filterAttributes = (EventStamp.rruleset.name, EventStamp.occurrences.name) masterFilter = "view.hasTrueValues(uuid, '%s', '%s')" % filterAttributes nonMasterFilter = "not " + masterFilter masterEvents = FilteredCollection.update( parcel, 'masterEvents', source=events, filterExpression=masterFilter, filterAttributes=list(filterAttributes)) nonMasterEvents = FilteredCollection.update( parcel, 'nonMasterEvents', source=events, filterExpression=nonMasterFilter, filterAttributes=list(filterAttributes)) MasterEventWatcher.update(parcel, 'masterEventWatcher', targetCollection=masterEvents) EventStamp.addIndex(masterEvents, "recurrenceEnd", 'method', method=(eventComparator, 'cmpRecurEnd'), monitor=(EventStamp.recurrenceEnd, )) EventStamp.addIndex(masterEvents, 'effectiveStart', 'subindex', superindex=(events, events.__collection__, 'effectiveStart')) locations = KindCollection.update(parcel, 'locations', kind=Location.getKind(view), recursive=True) locations.addIndex('locationName', 'value', attribute='displayName', nodefer=True) mailCollection = mail.MailStamp.getCollection(view) kind = mail.EmailAddress.getKind(view) emailAddressCollection = \ KindCollection.update(parcel, 'emailAddressCollection', kind=kind, recursive=True) emailComparator = EmailComparator.update(parcel, 'emailComparator') emailAddressCollection.addIndex('emailAddress', 'method', method=(emailComparator, 'cmpAddress'), monitor='emailAddress', nodefer=True) emailAddressCollection.addIndex('fullName', 'method', method=(emailComparator, 'cmpFullName'), monitor='fullName', nodefer=True) emailAddressCollection.addIndex('both', 'method', method=(emailComparator, 'cmpBoth'), monitor=('emailAddress', 'fullName'), nodefer=True, kind=kind) # Contains all current me addresses (that is, referenced by an account) currentMeEmailAddresses = ListCollection.update(parcel, 'currentMeEmailAddresses') currentMeEmailAddresses.addIndex('emailAddress', 'method', method=(emailComparator, 'cmpAddress'), monitor='emailAddress') # Contains all current and former me addresses meEmailAddressCollection = ListCollection.update( parcel, 'meEmailAddressCollection') meEmailAddressCollection.addIndex('emailAddress', 'method', method=(emailComparator, 'cmpAddress'), monitor='emailAddress') inSource = ToMeFilter.makeCollection(parcel, 'inSource', mailCollection) # this index must be added to shield from the duplicate # source (mailCollection) that is going to be in mine inSource.addIndex('__adhoc__', 'numeric') # The "In" collection inCollection = SmartCollection.update(parcel, 'inCollection', displayName=_(u"In"), source=inSource, trash=trashCollection, visible=True) mine.addSource(inCollection) outSource = FromMeFilter.makeCollection(parcel, 'outSource', mailCollection) # this index must be added to shield from the duplicate # source (mailCollection) that is going to be in mine outSource.addIndex('__adhoc__', 'numeric') # The "Out" collection outCollection = SmartCollection.update( parcel, 'outCollection', displayName=_(u"Out"), visible=True, source=outSource, trash=trashCollection, ) mine.addSource(outCollection) allEventsCollection = IntersectionCollection.update( parcel, 'allEventsCollection', sources=[allCollection, events]) searchResultsUnfiltered = SmartCollection.update( parcel, 'searchResultsUnfiltered', displayName=messages.UNTITLED) searchResults = DifferenceCollection.update( parcel, 'searchResults', sources=[searchResultsUnfiltered, masterEvents], displayName=messages.UNTITLED) TriageStatusReminder.update(parcel, 'triageStatusReminder') startup.Startup.update(parcel, "installWatchers", invoke=__name__ + ".installWatchers") tzInstallParcel(parcel)
def __init__(self, link, name=None, body=None): Note.__init__(self) self.title = "Link" self.link = link self.name = name or link self.summary_body = body
def __init__(self, cmd, summary, stdout, stderr): Note.__init__(self) self.stdout = stdout self.stderr = stderr self.title = cmd self.summary = summary
# -*- coding: utf-8 -*- from notes import Note CHROMATIC_SCALE_ASC = [ Note('C'), Note('C', '#'), Note('D'), Note('D', '#'), Note('E'), Note('F'), Note('F', '#'), Note('G'), Note('G', '#'), Note('A'), Note('A', '#'), Note('B') ] CHROMATIC_SCALE_DESC = [ Note('B'), Note('B', 'b'), Note('A'), Note('A', 'b'), Note('G'), Note('G', 'b'), Note('F'), Note('E'), Note('E', 'b'), Note('D'), Note('D', 'b'),
def pitchclass_to_note(arg: PCls, octave: int = 4) -> Note_: arg = Note(arg.id + octave * 12) return arg
def __init__(self, summary, data): Note.__init__(self) self.title = "Table" self.summary = summary self.data = data
def new_note(self, memo, tags=''): n = Note(memo, tags) self.notes.append(n)
def render_in_png(self, rescale=1.0): def trans_paste(bg, fg, box=(0, 0)): if fg.mode == 'RGBA': if bg.mode != 'RGBA': bg = bg.convert('RGBA') fg_trans = Image.new('RGBA', bg.size) fg_trans.paste(fg, box, mask=fg) # transparent foreground return Image.alpha_composite(bg, fg_trans) else: if bg.mode == 'RGBA': bg = bg.convert('RGB') bg.paste(fg, box) return bg harp_silent = self.get_is_silent() harp_broken = self.get_is_broken() harp_file = Image.open(self.unhighlighted_chord_png ) # loads default harp image into memory harp_size = harp_file.size harp_render = Image.new('RGB', harp_file.size, self.song_bkg) # Empty image # Get a typical note to check that the size of the note png is consistent with the harp png note_size = Note(self).get_png_size() note_rel_width = note_size[0] / harp_size[0] # percentage of harp if note_rel_width > 1.0 / self.get_column_count( ) or note_rel_width < 0.05: note_rescale = 0.153 / note_rel_width else: note_rescale = 1 if harp_broken: # '?' in the middle of the image (no harp around) symbol = Image.open(self.broken_png) harp_render = trans_paste(harp_render, symbol, (int( (harp_size[0] - symbol.size[0]) / 2.0), int((harp_size[1] - symbol.size[1]) / 2.0))) elif harp_silent: # '.' in the middle of the image (no harp around) symbol = Image.open(self.silent_png) harp_render = trans_paste(harp_render, symbol, (int( (harp_size[0] - symbol.size[0]) / 2.0), int((harp_size[1] - symbol.size[1]) / 2.0))) else: harp_render = trans_paste(harp_render, harp_file) # default harp image for row in range(self.get_row_count()): for col in range(self.get_column_count()): note = self.get_note_from_position((row, col)) # note.set_position(row, col) # NOTE RENDER if len(note.get_highlighted_frames() ) > 0: # Only paste highlighted notes xn = (0.13 + col * (1 - 2 * 0.13) / (self.get_column_count() - 1) ) * harp_size[0] - note_size[0] / 2.0 yn = (0.17 + row * (1 - 2 * 0.17) / (self.get_row_count() - 1) ) * harp_size[1] - note_size[1] / 2.0 note_render = note.render_in_png(note_rescale) harp_render = trans_paste( harp_render, note_render, (int(round(xn)), int(round(yn)))) if rescale != 1: harp_render = harp_render.resize( (int(harp_render.size[0] * rescale), int(harp_render.size[1] * rescale)), resample=Image.LANCZOS) return harp_render
msg = note.print(msg) msg = msg.rstrip() # remove all trailing newlines msg += "\n" msg += "\n" f = open(self.tmpNoteFile, "w") f.write(msg) f.close() # -------------------------------------------------- # Testing if __name__ == "__main__": note1 = Note() note1.setTitle("note number 1") note1.setBody("Blaablaa, this is comment.") note2 = Note() note2.setTitle("note number 2") note2.setBody("blaablaa, this is another comment.") note3 = Note() note3.setTitle("Lenghty note") note3.setBody("This is a note with a very long text body.\n" + "it continues all the way to here. and to \n" + "here: Seems long, right?. Now it finally almost.\n" + "here: Seems long, right?. xxx xxx xxx xxx xxx x.\n" + "here: Seems long, right?. Now it finally ends.")