예제 #1
0
 def hash(self, password, salt):
     password = self.pre_hashing(password)
     # 1. Let S be the following byte sequence (called the padding):
     # (u = len(password) (in bytes))
     # S = H_(k−2−u)(salt || password || u)
     k = len(encode(self.n))
     u = len(password)
     # u must be such that u ≤ 255 and u ≤ k − 32
     if u > 255 or u > k - 32:
         raise ValueError('Password is too long')
     S = self.kdf(salt + password + pack('=B', u), k - 2 - u)
     # 2. Let X be the following byte sequence:
     # X = 0x00 | | S | | π | | u
     X = b'\x00' + S + password + pack('=B', u)
     # 3. Let x be the integer obtained by decoding X with OS2IP.
     x = decode(X)
     # 4. Compute:
     # y = x^(2^(w+1)) (mod n)
     # This computation is normally performed by repeatedly squaring x modulo n; this is
     # done w + 1 times.
     y = x
     for _ in range(self.w + 1):
         y = pow(y, 2, self.n)
     # 5. Encode y with I2OSP into the byte sequence Y of length k bytes.
     Y = encode(y, k)
     # The primary output of MAKWA is Y
     return self.post_hashing(Y)
예제 #2
0
def transmit(freqs, bit_rates, send_bits, **kwargs):
    # Compress ->bits

    # Freq Multiplex

    # Coding

    # Modulate

    print('Frequencies: {}'.format(freqs))
    print('Min freq: {}, Max freq: {}'.format(min(freqs), max(freqs)))
    print('bit_rates: {}'.format(bit_rates))

    hamming = False
    enc.encode('bin.wav',
               send_bits,
               freqs,
               bit_rates,
               hamming=hamming,
               plot_audio=False)

    print('Duration: {}'.format(utils.get_wav_duration('bin.wav')))
    print('No of bits: {}'.format(len(send_bits)))

    input('>>Press enter to play')
    am.play_wav('bin.wav')
    am.sd.wait()
예제 #3
0
def submit_audio(user_id, index, tick):
    payload = encoding.decode(request.data)

    segment = read_opus(payload['sound'])
    offset = payload['offset']
    offset_sign = payload['offset-sign']

    room_id = r.get('USER-ROOM:%s' % user_id).decode('utf-8')
    room_index = int(r.get('ROOM-INDEX:%s' % room_id))

    room_song = r.get('ROOM-SONG:%s' % room_id)

    if room_index != index or room_song is None:
        return encoding.encode({
            'success': False,
            'reason': 'Desynced with the bulletin'
        })

    if not offset_sign:
        segment = segment[offset:]
        offset = 0

    r.set('USER-AUDIO-%d:%s' % (tick % 2, user_id), encoding.encode(
        {
            'offset': offset,
            'sound': as_mp3(segment)
        })
    )
    r.set('USER-LAST-ACTIVE:%s' % user_id, int(time.time()))

    return encoding.encode({'success': True})
예제 #4
0
    def showitems(self):
        lines = []
        stats = hub.request(requests.getsongdbmanagerstats())
        indent = " " * 3
        for songdbstats in stats.songdbsstats:
            dbidstring = _("Database %s") % songdbstats.id + ":"
            dbstatstring = _("%d songs, %d albums, %d artists, %d tags") % (
                songdbstats.numberofsongs, songdbstats.numberofalbums,
                songdbstats.numberofartists, songdbstats.numberoftags)

            lines.append((dbidstring, dbstatstring))
            if songdbstats.type == "local":
                dbtypestring = _("local database (db file: %s)") % (
                    songdbstats.dbfile)
            else:
                dbtypestring = _("remote database (server: %s)") % (
                    songdbstats.location)
            lines.append((indent + _("type") + ":", dbtypestring))
            lines.append(
                (indent + _("base directory") + ":", songdbstats.basedir))
            dbcachesizestring = "%dkB" % songdbstats.cachesize
            lines.append((indent + _("cache size") + ":", dbcachesizestring))

        lines.append(("", ""))
        cachestatsstring = _("%d requests, %d / %d objects") % (
            stats.requestcacherequests, stats.requestcachesize,
            stats.requestcachemaxsize)
        if stats.requestcachemaxsize != 0:
            cachestatsstring = cachestatsstring + " (%d%%)" % (
                100 * stats.requestcachesize // stats.requestcachemaxsize)
        lines.append((_("Request cache size") + ":", cachestatsstring))
        totalrequests = stats.requestcachehits + stats.requestcachemisses
        if totalrequests != 0:
            percentstring = " (%d%%)" % (100 * stats.requestcachehits //
                                         totalrequests)
        else:
            percentstring = ""
        lines.append(
            (_("Request cache stats") + ":",
             (_("%d hits / %d requests") %
              (stats.requestcachehits, totalrequests)) + percentstring))

        wc1 = max([len(lc) for lc, rc in lines]) + 1
        if wc1 > 0.6 * self.iw:
            wc1 = int(0.6 * self.iw)
        wc2 = self.iw - wc1
        y = self.iy
        for lc, rc in lines:
            self.move(y, self.ix)
            self.addstr(
                encoding.encode(lc).ljust(wc1)[:wc1], self.colors.description)
            self.addstr(
                encoding.encode(rc).ljust(wc2)[:wc2], self.colors.content)
            y += 1
예제 #5
0
def get_bulletin(room_id):
    bulletin = encoding.decode(r.get('ROOM-BULLETIN:%s' % room_id))
    index = int(r.get('ROOM-INDEX:%s' % room_id))

    if bulletin is None:
        return encoding.encode({'success': False})
    
    return encoding.encode({
        'index': index,
        'bulletin': bulletin
    })
예제 #6
0
    def update(self):
        window.window.update(self)
        self.move(0,0)
        self.clrtoeol()

        if self.message:
            self.addstr(encoding.encode(self.message), config.colors.statusbar.key)
        else:
            for element in self.content[0]+separator+self.content[1]+separator+self.content[2]:
                if element==terminate[0]:
                    break
                self.addstr(encoding.encode(element[0]), element[1])
예제 #7
0
def enc():
    global statement, img_p, var1, path
    if img_p == '':
        messagebox.showerror("ERROR", "Select an image")
        return
    ec.encode(statement, img_p)
    r = messagebox.askyesno("Quit", "Do you wish to continue?")
    if r == 0:
        root.quit()
    else:
        top3.withdraw()
        guid()
예제 #8
0
파일: tests.py 프로젝트: Larbino1/Mercury
def record_f_er_br(am, filename, freq_params, br_params):
    min_freq, max_freq, freq_div = freq_params
    min_br, max_br, br_div = br_params

    frequencies = [
        min_freq + (max_freq - min_freq) * i / freq_div
        for i in range(freq_div)
    ]
    bit_rates = [
        min_br + (max_br - min_br) * i / br_div for i in range(br_div)
    ]

    fr = []
    er = []
    br = []
    for freq in frequencies:
        for phy_bit_rate in bit_rates:
            print('Frequency: {}'.format(freq))
            print('bit_rate: {}'.format(phy_bit_rate))

            hamming = False
            enc.encode('bin.wav',
                       testbits, [freq],
                       phy_bit_rate,
                       hamming=hamming)
            am.playrec('bin.wav', '_bin.wav', plot_ideal_signal=False)
            ans = dec.decode('_bin.wav',
                             phy_bit_rate,
                             len(testbits), [freq],
                             hamming=hamming,
                             plot_sync=False,
                             plot_main=False)

            # print(ans)
            # print(list(tests.testbits))

            error = utils.calc_error(testbits, ans)
            # utils.plot_smooth_error_graph(tests.testbits, ans)

            if list(ans) == list(testbits):
                print("YEET!")
            else:
                print("S***E")
            print('')

            fr.append(freq)
            br.append(phy_bit_rate)
            er.append(error)

    with open(filename, 'a') as f:
        for i in zip(fr, er, br):
            f.write('{}, {}, {}\n'.format(i[0], i[1], i[2]))
예제 #9
0
파일: helpwin.py 프로젝트: altendky/PyTone
 def showitems(self):
     y = self.iy
     for item in self.items[self.first:]:
         self.addstr(y, 1, " " * self.iw, self.colors.background)
         self.move(y, 1)
         for keyname in item[0][:-1]:
             self.addstr(encoding.encode(keyname), self.colors.key)
             self.addstr("/", self.colors.description)
         self.addstr(encoding.encode(item[0][-1]), self.colors.key)
         self.addnstr(y, 35, encoding.encode(item[1]), self.iw - 35)
         y += 1
         if y >= self.iy + self.ih:
             break
예제 #10
0
def create_room():
    bulletin = encoding.decode(request.data)

    room_id = generate_id();

    # Every room has three things:
    # a list of users, a song, and a current tick.

    #r.set('ROOM-USERS:%s' % room_id, []) # Created implicitly
    r.set('ROOM-BULLETIN:%s' % room_id, encoding.encode(bulletin))
    r.set('ROOM-INDEX:%s' % room_id, -1)

    return encoding.encode({'room_id': room_id})
예제 #11
0
파일: helpwin.py 프로젝트: indera/PyTone
 def showitems(self):
     y = self.iy
     for item in self.items[self.first:]:
         self.addstr(y, 1, " "*self.iw, self.colors.background)
         self.move(y, 1)
         for keyname in item[0][:-1]:
             self.addstr(encoding.encode(keyname), self.colors.key)
             self.addstr("/", self.colors.description)
         self.addstr(encoding.encode(item[0][-1]), self.colors.key)
         self.addnstr(y, 35, encoding.encode(item[1]), self.iw-35)
         y += 1
         if y>=self.iy+self.ih:
             break
예제 #12
0
def stop_song(room_id):
    users = r.lrange('ROOM-USERS:%s' % room_id, 0, -1)

    if users is None:
        return encoding.encode({'success': False})

    # Stop playing this song
    r.delete('ROOM-SONG:%s' % room_id)

    # Delete everyone's audio
    for user in users:
        r.delete('USER-AUDIO-0:%s' % user.decode('utf-8'))
        r.delete('USER-AUDIO-1:%s' % user.decode('utf-8'))

    return encoding.encode({'success': True})
예제 #13
0
파일: playerwin.py 프로젝트: indera/PyTone
    def playbackinfochanged(self, event):
        if event.playbackinfo.playerid == self.playerid:
            if self.song != event.playbackinfo.song and event.playbackinfo.song and self.songchangecommand:
                os.system(event.playbackinfo.song.format(self.songchangecommand, safe=True))
            self.song = event.playbackinfo.song
            self.paused = event.playbackinfo.ispaused()
            self.stopped = event.playbackinfo.isstopped()
            if self.song:
                self.settitle(u"%s%s" % (event.playbackinfo.iscrossfading() and "-> " or "", self.song.format(self.songformat)))
            else:
                self.settitle(_("Playback Info"))
            self.time = event.playbackinfo.time
            self.update()

            # update player info file, if configured
            if self.playerinfofd:
                try:
                    self.playerinfofd.seek(0)
                    if self.song:
                        info = "%s - %s (%s/%s)\n"  % ( self.song.artist,
                                                        self.song.title,
                                                        formattime(self.time),
                                                        formattime(self.song.length))
                    else:
                        info = _("Not playing") + "\n"
                    info = encoding.encode(info)
                    self.playerinfofd.write(info)
                    self.playerinfofd.truncate(len(info))
                except IOError, e:
                    log.error(_("error '%s' occured during write to playerinfofile") % e)
                    self.playerinfofd = None
예제 #14
0
 def change_wf(self, privkey, hash, diff):
     y = decode(hash)
     if diff == 0:
         return hash
     if diff > 0:
         return encode(pow(y, pow(2, diff), self.n))
     else:
         if privkey is None:
             raise ValueError("Cant decrease without private key")
         p = privkey.p
         q = privkey.q
         ep = sqrtExp(p, -diff)
         eq = sqrtExp(q, -diff)
         yp = pow((y % p), ep, p)
         yq = pow((y % q), eq, q)
         return encode(chinese_remainder(p, q, privkey.invQ, yp, yq))
def pipeline(host_image, payload_image, encoding_significant_digits,
             significant_digit_interval):
    # type: (
    #    PIL.Image, PIL.Image, int, Tuple[int, int]
    # ) -> Tuple[PIL.Image, Dict[int, PIL.Image]]
    """Encodes an image using some params, returning encoded and decoded images.

    Args:
        host_image: Host image.
        payload_image: Payload image.
        (Yeah, I know, and I don't care. These values are documented elsewhere.)
        encoding_significant_digits: The significant digits to use in the
            encoding.
        significant_digit_interval: The significant digits to scan over
            when decoding the image.
    Returns:
        A 2-tuple; the first item is the encoded image, the second item is a
        dictionary mapping from significant_digit to decoded PIL.Image.
    """
    encoded = encoding.encode(host_image, payload_image,
                              encoding_significant_digits)

    return (encoded,
            processing.process(
                image=encoded,
                significant_digit_interval=significant_digit_interval))
예제 #16
0
    def post(self):
        orig_user = self.request.get("username")
        username = cgi.escape(orig_user, quote=True)
        password = cgi.escape(self.request.get("password"), quote=True)

        name = validate_username(username)
        passw = validate_password(password)
        res = {
            "username": username,
            "error_name": "" if name else "That's not a valid username.",
            "password": password,
            "error_pass": "" if passw else "That wasn't a valid password.",
        }
        if name and passw:
            users = db.GqlQuery("SELECT * FROM User WHERE username=:1",
                                username)
            correct_passw = ""
            for user in users:
                correct_passw = user.password
            if correct_passw and enc.validate_passw(password, correct_passw):
                user_key = str(user.key().id())
                hidden_key = enc.encode(user_key)
                cookie_val = str("user_id=%s|%s; Path=/" %
                                 (user_key, hidden_key))
                self.response.headers.add_header('Set-Cookie', cookie_val)
                self.redirect('/')
            elif not correct_passw:
                res["error_name"] = "User '%s' not registered." % username
                self.render("login.html", **res)
            else:
                res["error_pass"] = "******"
                self.render("login.html", **res)
        else:
            self.render("login.html", **res)
def encode_data_response(data):
    output = {
        'resCode': '9000',
        'resMessage': 'OK',
        'data': encode(data),
    }
    return json.dumps(output)
def read_data_files(data_path, files_destination):
    letter_indices = make_encodings()
    os.makedirs(os.path.dirname(files_destination), exist_ok=True)

    wave_files = []
    encoded_labels = []

    reader_dirs = os.listdir(data_path)
    for reader_dir in reader_dirs:
        chapters_path = data_path + '/' + reader_dir
        chapter_dirs = os.listdir(chapters_path)
        for chapter_dir in chapter_dirs:
            speech_dir = chapters_path + '/' + chapter_dir
            files = os.listdir(speech_dir)

            meta_file = list(filter(lambda f: f.endswith('.txt'), files))[0]
            meta_file_path = speech_dir + '/' + meta_file
            with open(meta_file_path, 'r') as metafile:
                for line in metafile:
                    content = line.strip()
                    file, label = content.split(' ', 1)
                    file_path = speech_dir + '/' + file + '.flac'

                    wave_files.append(file_path)
                    encoded_labels.append(encode(label, letter_indices))

    return wave_files, encoded_labels
예제 #19
0
    def update(self):
        if self.playlist.autoplaymode == "repeat":
            autoplaymode = " [%s]" % _("Repeat")
        elif self.playlist.autoplaymode == "random":
            autoplaymode = " [%s]" % _("Random")
        else:
            autoplaymode = ""
        self.settitle("%s (-%s/%s)%s" %
                      (_("Playlist"),
                       formattime((self.playlist.ttime - self.playlist.ptime)),
                       formattime(self.playlist.ttime), autoplaymode))

        window.window.update(self)
        if self.hasfocus():
            self.updatestatusbar()

        for i in range(self.playlist.top, self.playlist.top + self.ih):
            attr = curses.A_NORMAL

            if i < len(self.playlist):
                item = self.playlist[i]
                if item.playstarttime is not None:
                    h, m, s = time.localtime(item.playstarttime)[3:6]
                else:
                    h = m = s = 0
                adddict = {
                    "playstarthours": h,
                    "playstartminutes": m,
                    "playstartseconds": s
                }
                name = encoding.encode(
                    item.song.format(self.songformat, adddict=adddict))
                if self.playlist.playingitem and item is self.playlist.playingitem:
                    if self.playlist.selected == i and self.hasfocus():
                        attr = self.colors.selected_playingsong
                    else:
                        attr = self.colors.playingsong
                elif item.hasbeenplayed():
                    if i == self.playlist.selected and self.hasfocus():
                        attr = self.colors.selected_playedsong
                    else:
                        attr = self.colors.playedsong
                else:
                    if i == self.playlist.selected and self.hasfocus():
                        attr = self.colors.selected_unplayedsong
                    else:
                        attr = self.colors.unplayedsong
            else:
                name = ""
            self.addnstr(i - self.playlist.top + self.iy, self.ix,
                         name.ljust(self.iw)[:self.iw], self.iw, attr)

        self.updatescrollbar()

        # move cursor to the right position in order to make it more
        # easy for users of Braille displays to track the current
        # position/selection
        if self.hasfocus() and self.playlist.selected is not None:
            self.win.move(self.playlist.selected - self.playlist.top + 1, 1)
예제 #20
0
파일: config.py 프로젝트: indera/PyTone
def usage():
    print "PyTone %s" % version.version
    print "Copyright %s" % encoding.encode(version.copyright)
    print "usage: pytone.py [options]"
    print "-h, --help: show this help"
    print "-c, --config <filename>: read config from filename"
    print "-d, --debug <filename>: enable debugging output (into filename)"
    print "-r, --rebuild: rebuild all databases"
 def __getitem__(self, idx):
     image_root = self.train_image_file_paths[idx]
     image_name = image_root.split(os.path.sep)[-1]
     image = Image.open(image_root)
     if self.transform is not None:
         image = self.transform(image)
     label = ohe.encode(image_name.split('_')[0])
     return image, label
예제 #22
0
def usage():
    print("PyTone %s" % version.version)
    print("Copyright %s" % encoding.encode(version.copyright))
    print("usage: pytone.py [options]")
    print("-h, --help: show this help")
    print("-c, --config <filename>: read config from filename")
    print("-d, --debug <filename>: enable debugging output (into filename)")
    print("-r, --rebuild: rebuild all databases")
예제 #23
0
 def showitems(self):
     self.clear()
     try:
         for lno, line in enumerate(self.lyrics[0][2].split("\n")[self.first:self.first+self.ih]):
             line = encoding.encode(line).strip().center(self.iw)
             self.addnstr(self.iy+lno, self.ix, line, self.iw, self.colors.content)
     except IndexError:
         pass
예제 #24
0
 def test_encoding(self):
     input = OrderedDict()
     input['foo'] = 'bar'
     input['baz'] = 'qux'
     input['zap'] = 'zazzle'
     output = encoding.encode(input)
     expected = 'foo=bar&baz=qux&zap=zazzle'
     self.assertEqual(expected, output)
예제 #25
0
    def update(self):
        if self.title and self.h>=2:
            if self.hasfocus():
                topborder = 0
                # uncomment this to get the "thick" border of the old times
                # topborder = ord("=")
                attr = self.colors.activeborder
                try:
                    titleattr = self.colors.activetitle
                except AttributeError:
                    titleattr = self.colors.title
            else:
                topborder = 0
                attr = self.colors.border
                titleattr = self.colors.title

            # draw configured borders

            if self.hastopborder():
                self.hline(0, self.ix, curses.ACS_HLINE, self.iw, attr)
                # self.win.border(0, 0, topborder)
                t = encoding.encode(self.title)[:self.w-4]
                pos = (self.w-4-len(t))/2 
                self.addstr(0, pos, "[ %s ]" % t, titleattr)
                if self.hasleftborder():
                    self.addch(0, 0, curses.ACS_ULCORNER, attr)
                if self.hasrightborder():
                    self.addch(0, self.ix+self.iw, curses.ACS_URCORNER, attr)
                else:
                    self.addch(0, self.ix+self.iw, curses.ACS_HLINE, attr)
            else:
                t = self.title[:self.w]
                self.addstr(0, 0, t.center(self.w), titleattr)

            if self.hasbottomborder():
                self.hline(self.iy+self.ih, self.ix, curses.ACS_HLINE, self.iw, attr)
                if self.hasleftborder():
                    self.addch(self.iy+self.ih, 0, curses.ACS_LLCORNER, attr)
                if self.hasrightborder():
                    self.addch(self.iy+self.ih, self.ix+self.iw, curses.ACS_LRCORNER, attr)
                else:
                    self.addch(self.iy+self.ih, self.ix+self.iw, curses.ACS_HLINE, attr)

            if self.hasleftborder():
                if self.hastopborder():
                    self.vline(self.iy, 0, curses.ACS_VLINE, self.ih, attr)
                else:
                    self.vline(0, 0, curses.ACS_VLINE, self.ih+1, attr)

            if self.hasrightborder():
                if self.hastopborder():
                    self.vline(self.iy, self.ix+self.iw, curses.ACS_VLINE, self.ih, attr)
                else:
                    self.vline(0, self.ix+self.iw, curses.ACS_VLINE, self.ih+1, attr)

            # draw additional border elements
            for y, x, c in self.borderelements:
                self.addch(y, x, c, attr)
예제 #26
0
    def showitems(self):
        lines = []
        stats = hub.request(requests.getsongdbmanagerstats())
        indent = " "*3
        for songdbstats in stats.songdbsstats:
            dbidstring = _("Database %s") % songdbstats.id + ":"
            dbstatstring = _("%d songs, %d albums, %d artists, %d tags") % (songdbstats.numberofsongs,
									    songdbstats.numberofalbums,
									    songdbstats.numberofartists,
									    songdbstats.numberoftags)

            lines.append((dbidstring, dbstatstring))
            if songdbstats.type == "local":
                dbtypestring = _("local database (db file: %s)") % (songdbstats.dbfile)
            else:
                dbtypestring = _("remote database (server: %s)") % (songdbstats.location)
            lines.append((indent + _("type") + ":", dbtypestring))
            lines.append((indent + _("base directory") + ":", songdbstats.basedir)) 
            dbcachesizestring =  "%dkB" % songdbstats.cachesize
            lines.append((indent + _("cache size") + ":", dbcachesizestring))

        lines.append(("", ""))
        cachestatsstring = _("%d requests, %d / %d objects") % (stats.requestcacherequests, stats.requestcachesize,
                                                                stats.requestcachemaxsize)
        if stats.requestcachemaxsize != 0:
            cachestatsstring = cachestatsstring + " (%d%%)" % (100*stats.requestcachesize//stats.requestcachemaxsize)
        lines.append((_("Request cache size") + ":", cachestatsstring))
        totalrequests = stats.requestcachehits + stats.requestcachemisses
        if totalrequests != 0:
            percentstring = " (%d%%)" % (100*stats.requestcachehits//totalrequests)
        else:
            percentstring = ""
        lines.append((_("Request cache stats") + ":",
                      (_("%d hits / %d requests") % (stats.requestcachehits, totalrequests)) + percentstring))

        wc1 = max([len(lc) for lc, rc in lines]) + 1
        if wc1 > 0.6*self.iw:
            wc1 = int(0.6*self.iw)
        wc2 = self.iw - wc1
        y = self.iy
        for lc, rc in lines:
            self.move(y, self.ix)
            self.addstr(encoding.encode(lc).ljust(wc1)[:wc1], self.colors.description)
            self.addstr(encoding.encode(rc).ljust(wc2)[:wc2], self.colors.content)
            y += 1
예제 #27
0
def encrypt(filename):
	encoded_message = ""
	with open(filename) as file:
		for word in file.read().split():
			message = encode(word)
			cipher = str(modexp(message, pub_key, n))
			encoded_message += cipher + "\r\n"
	cipher = open("cipher_text", "w+")
	cipher.write(encoded_message)		
예제 #28
0
def single_test(data, compression, freqs, coding, modulation, **kwargs):

    enc.encode(data, compression, freqs, coding, modulation, **kwargs)
    am.playrec('bin.wav', '_bin.wav')
    ans = dec.decode(len(data), compression, freqs, coding, modulation,
                     **kwargs)  # hamming plot_sync plot_main plot_conv

    error = utils.calc_error_per_freq(data, ans, freqs)

    if kwargs.get('plot_errors'):
        utils.plot_smooth_error_graph(data, ans)

    if list(ans) == list(data):
        print("YEET!")
    else:
        print("S***E")

    return ans
예제 #29
0
    def update(self):
        if self.playlist.autoplaymode == "repeat":
            autoplaymode = " [%s]" % _("Repeat")
        elif self.playlist.autoplaymode == "random":
            autoplaymode = " [%s]" % _("Random")
        else:
            autoplaymode = ""
        self.settitle("%s (-%s/%s)%s" % ( _("Playlist"),
                                        formattime((self.playlist.ttime-
                                                    self.playlist.ptime)),
                                        formattime(self.playlist.ttime),
                                        autoplaymode))

        window.window.update(self)
        if self.hasfocus():
            self.updatestatusbar()

        for i in range(self.playlist.top, self.playlist.top+self.ih):
            attr = curses.A_NORMAL

            if i<len(self.playlist):
                item = self.playlist[i]
                if item.playstarttime is not None:
                    h, m, s = time.localtime(item.playstarttime)[3:6]
                else:
                    h = m = s = 0
                adddict = {"playstarthours":   h,
                           "playstartminutes": m,
                           "playstartseconds": s}
                name = encoding.encode(item.song.format(self.songformat, adddict=adddict))
                if self.playlist.playingitem and item is self.playlist.playingitem:
                    if self.playlist.selected==i and self.hasfocus():
                        attr = self.colors.selected_playingsong
                    else:
                        attr = self.colors.playingsong
                elif item.hasbeenplayed():
                    if i==self.playlist.selected and self.hasfocus():
                        attr = self.colors.selected_playedsong
                    else:
                        attr = self.colors.playedsong
                else:
                    if i==self.playlist.selected and self.hasfocus():
                        attr = self.colors.selected_unplayedsong
                    else:
                        attr = self.colors.unplayedsong
            else:
                name = ""
            self.addnstr(i-self.playlist.top+self.iy, self.ix, name.ljust(self.iw)[:self.iw], self.iw, attr)

        self.updatescrollbar()

        # move cursor to the right position in order to make it more
        # easy for users of Braille displays to track the current
        # position/selection
        if self.hasfocus() and self.playlist.selected is not None:
            self.win.move(self.playlist.selected-self.playlist.top+1, 1)
예제 #30
0
 def __init__(self, n, h=sha256, pre_hashing=True, t=0, w=4096):
     # The modulus. Let n be a Blum integer, i.e. the product n = pq of two prime integers p and q such that:
     # p = 3 (mod 4)
     # q = 3 (mod 4
     self.n = n
     self.preHashing = pre_hashing
     self.t = t
     self.h = h
     self.w = w
     self.mod_id = self.kdf(encode(n), 8)
예제 #31
0
파일: mixerwin.py 프로젝트: indera/PyTone
    def update(self):
        self.level = self.mixer.get()
        self.top()
        window.window.update(self)
        self.addstr(self.iy, self.ix, encoding.encode(_("Volume:")), self.colors.description)
        self.addstr(" %3d " % round(self.level[0]), self.colors.content)
 
        percent = int(round(self.barlen*self.level[0]/100))
        self.addstr("#"*percent, self.colors.barhigh)
        self.addstr("#"*(self.barlen-percent), self.colors.bar)
예제 #32
0
def song_list():
    last_id = r.get('GLOBAL:last-song-id')

    result = []
    for i in range(last_id):
        result.append({
            'name': r.get('SONG-NAME:%d' % i),
            'id': i
        })

    return encoding.encode(result)
예제 #33
0
파일: mixerwin.py 프로젝트: altendky/PyTone
    def update(self):
        self.level = self.mixer.get()
        self.top()
        window.window.update(self)
        self.addstr(self.iy, self.ix, encoding.encode(_("Volume:")),
                    self.colors.description)
        self.addstr(" %3d " % round(self.level[0]), self.colors.content)

        percent = int(round(self.barlen * self.level[0] / 100))
        self.addstr("#" * percent, self.colors.barhigh)
        self.addstr("#" * (self.barlen - percent), self.colors.bar)
예제 #34
0
def join_room(room_id):
    user_id = generate_id()

    # TODO grab user name as well

    r.rpush('ROOM-USERS:%s' % room_id, user_id)
    r.set('USER-ROOM:%s' % user_id, room_id)
    r.set('USER-NAME:%s' % user_id, request.args.get('name'))
    r.set('USER-LAST-ACTIVE:%s' % user_id, int(time.time()))
    
    return encoding.encode({'user_id': user_id})
예제 #35
0
 def __init__(self, p, q, gen=None):
     if p<0 or q <0 or p & 3 != 3 or q & 3 != 3 or p == q:
         raise ValueError("Invalid Makwa private key")
     self.p = p
     self.q = q
     self.QRGen = gen
     self.modulus = p*q
     if len(encode(self.modulus))*8 < 1273:
         raise ValueError("Invalid Makwa private key")
     if gen is not None and (gen <= 1 or gen >= self.modulus):
         raise ValueError("Invalid Makwa private key")
     self.invQ = modInverse(q, p)
예제 #36
0
def list_songs():
    last_song_id = r.get('GLOBAL:last-song-id')
    if last_song_id is None:
        last_song_id = 0
    else:
        last_song_id = int(last_song_id)

    return encoding.encode([
        {
            'id': i,
            'name': r.get('SONG-NAME:%d' % i).decode('utf-8'),
            'credits': r.get('SONG-CREDITS:%d' % i).decode('utf-8')
        } for i in range(last_song_id)
    ])
예제 #37
0
def encodePrivate(p, q, QRGen = None):
    p_e = encode(p)
    q_e = encode(q)
    p_e_len = encode(len(p_e), 2)
    q_e_len = encode(len(q_e), 2)
    qrgen_e = None
    qrgen_e_len = None
    header = encode(MAGIC_PRIVKEY)
    if QRGen is not None:
        qrgen_e = encode(QRGen)
        qrgen_e_len = encode(len(qrgen_e), 2)
        header = encode(MAGIC_PRIVKEY_WITHGEN)
    ret = header + p_e_len + p_e + q_e_len + q_e
    if QRGen is not None:
        ret += qrgen_e_len + qrgen_e
    return ret
예제 #38
0
def encrypt(input_bytes, key, rounds=5, modulus=DEFAULT_MODULUS):
    """ usage: encrypt(input_bytes, key, 
                       rounds=5, modulus=DEFAULT_MODULUS) => ciphertext
        
        Given input_bytes and a key, returns a bytearray of ciphertext.
        input_bytes and key should be bytearrays.
        Ciphertexts are partially homomorphic with respect to addition. 
            - Can perform an unlimited number of additions
           
        Encrypts 1 byte at a time. Each (2 ** rounds)-bit ciphertext encodes one 8-bit byte.        
        design: iterated randomized encoding (secret sharing)
                    - represent m as r, (m - r) where r is a uniformly random value
                    - doubles message size
                    - apply iteratively until message size == desired key strength
                        - 256 bits of key material requires 256 bits of data to operate upon
                            - Not necessarily true, but keeps it nice and simple
                        - apply 5 rounds to a byte to produce a 8->16->32->64->128->256 bit ciphertext                                                
                multiplication key addition layer
                    - multiplication instead of addition facilitates performing an arbitrary # of additions
                        - an addition key layer would have to count the # of operations performed
                    - key values must have a multiplicative inverse, which depends upon the modulus used
                        - a modulus of 256 works nicely for 8-bit bytes, but only half the elements have inverses
                            - only using odd key bytes sidesteps the problem, at the expense of -1 bit of security per key byte 
                        - could use finite field arithmetic ? """
    # encryption process:
    # encoding step
    #r1 (m1 - r1)
    #r2 r3 (r1 - r2) ((m1 - r1) - r3)
    #r4 r5 r6 r7 (r2 - r4) (r3 - r5) (r1 - r2 - r6) (m1 - r1 - r3 - r7)
    #r8 r9 r10 r11 r12 r13 r14 r15 (r4 - r8) (r5 - r9) (r6 - 10) (r7 - r11) (r2 - r4 - r12) (r3 - r5 - r13) (r1 - r2 - r6 - r14) (m1 - r1 - r3 - r7 - r15)
    # key addition step       
    #r8k1 r9k2 r10k3 r11k4 r12k5 r13k6 r14k7 r15k8 (r4k9 - r8k9) (r5k10 - r9k10) (r6k11 - r10k11) (r7k12 - r11k12) (r2k12 - r4k12 - r12k12) (r3k13 - r5k13 - r13k13) (r1k14 - r2k14 - r6k14 - r14k14) (m1k15 - r1k15 - r3k15 - r7k15 - r15k15)                                        
    output = []
    for byte in input_bytes:
        data = [byte]        
        for round in range(rounds):
            data[:] = encode(data, modulus)               
             
        multiplication_subroutine(data, [item | 1 for item in key], modulus)
        assert len(data) == 2 ** rounds, (len(data), 2 ** rounds)
        output.extend(data[:])          
    return output
예제 #39
0
    def update(self):
        self.settitle(self.items.selectionpath())
        window.window.update(self)

        if self.hasfocus():
            self.updatestatusbar()

        showselectionbar = self.hasfocus() or self.searchpositions

        for i in range(self.items.top, self.items.top+self.ih):
            attr = curses.A_NORMAL
            if i<len(self.items):
                aitem = self.items[i]
                name = self.items[i].getname()
                if isinstance(aitem, item.song):
                    if i==self.items.selected and showselectionbar:
                        attr = self.colors.selected_song
                    else:
                        attr = self.colors.song
                elif isinstance(aitem, (item.artist, item.album)):
                    if i==self.items.selected and showselectionbar:
                        attr = self.colors.selected_artist_album
                    else:
                        attr = self.colors.artist_album
                else:
                    if i==self.items.selected and showselectionbar:
                        attr = self.colors.selected_directory
                    else:
                        attr = self.colors.directory
            else:
                name = ""
            name = encoding.encode(name)
            self.addstr(i-self.items.top+self.iy, self.ix, name.ljust(self.iw)[:self.iw], attr)

        self.updatescrollbar()

        # move cursor to the right position in order to make it more
        # easy for users of Braille displays to track the current
        # position/selection
        if self.hasfocus() and self.items.selected is not None:
            self.win.move(self.items.selected-self.items.top+1, 1)
예제 #40
0
파일: main.py 프로젝트: Darthfett/MIS-P2
def encoding_delegate(image, channels, *args):
    """
    Will need to get an array that contains:
        1. a value informing what encoding is needed.
        2. an array of values to encode. Assuming RGB values.

    Will return an array with encoded values.
    """

    channels = [[int(r) for r in channel] for channel in channels]

    scheme = None
    while scheme is None:
        scheme_input = raw_input("Choose encoding scheme (2: Shannon Fanno, 3: LZW): ")

        if not scheme_input:
            break

        try:
            scheme_int = int(scheme_input)
        except ValueError:
            print("Invalid input")
            continue

        if scheme_int not in (1, 2, 3):
            print("Invalid input")
            continue

        scheme = scheme_int

    t5_output = channels
    t5_output = [encoding.encode(channel, scheme) for channel in t5_output]
    # t5_output = [encoding.decode(enc, scheme) for enc in t5_output]

    t5_output = bin_seq_to_bytearray(''.join(t5_output))

    return t5_output
예제 #41
0
def fetchMails(args):
	# fetch emails:
	m = createMailer()
	mails = m.fetchMails()

	# connect to database & get enabled email addresses:
	db = connectToDatabase()
	addresses = db.getEnabledAddresses()

	# create message generator:
	messages = createMessageGenerator()

	# check received mails:
	for mail in mails:
		# validate sender:
		fromAddr = email.utils.parseaddr(mail['From'])
		sender = fromAddr[1].strip().lower()

		if sender in addresses:
			# parse email:
			subject = mail['Subject'].lower().strip()

			if subject == 'tweet':
				action = database.PUBLISH_TWEET
			elif subject == 'follow':
				action = database.FOLLOW_USER
			elif subject == 'unfollow':
				action = database.UNFOLLOW_USER
			else:
				action = -1

			if action <> -1:
				date = time.mktime(email.utils.parsedate(mail['Date']))

				if mail.is_multipart():
					body = mail.get_payload(0).get_payload().strip()
				else:
					body = mail.get_payload().strip()

				body = trimBody(encode(decodestring(body)))

				m = re.match('^<html>.*', body)

				if not m is None:
					r = createHtmlRenderer()
					body = r.render(body)

				# validate body & append message to queue on success:
				if action == database.PUBLISH_TWEET:
					if len(body) < 5:
						db.createMessage(addresses[sender], messages.tweetTooShort(body))
					elif len(body) > 140:
						db.createMessage(addresses[sender], messages.tweetTooLong(body))
					else:
						db.createMessage(addresses[sender], messages.tweetAccepted(body))
						db.appendToQueue(addresses[sender], action, body, date, time.time())
				else:
					for username in [u.strip() for u in body.split(',')]:
						if len(username) < 3 or len(username) > 24:
							if action == database.FOLLOW_USER:
								db.createMessage(addresses[sender], messages.followNotAccepted(username))
							else:
								db.createMessage(addresses[sender], messages.unfollowNotAccepted(username))
						else:
							if action == database.FOLLOW_USER:
								db.createMessage(addresses[sender], messages.followAccepted(username))
							else:
								db.createMessage(addresses[sender], messages.unfollowAccepted(username))
	
							db.appendToQueue(addresses[sender], action, username, date, time.time())
예제 #42
0
파일: termtitle.py 프로젝트: indera/PyTone
 def changetermtitle(self, event):
     prefix = (event.playbackinfo.iscrossfading() and '-> ' or '')
     song = encoding.encode(event.playbackinfo.song.format(self.config.songformat, safe=True))
     sys.stdout.write('\033]0;' + prefix + song + '\007')
예제 #43
0
    def update(self):
        # update window title
        aitem = self.items[self.activeview]
        title = _("No song")
        if isinstance(aitem, (item.song, services.playlist.playlistitem)):
            if isinstance(aitem, item.song):
                atype = aitem.type
            else:
                atype = aitem.song.type
            if atype == "mp3":
                title = _("MP3 Info")
            elif atype == "ogg":
                title = _("Ogg Info")
            else:
                title = _("Song Info")
        elif isinstance(aitem, item.diritem):
            title = _("Directory Info")
        if self.activeview != selection:
            title = title + " " + _("[Player: %s]") % self.activeview
        self.settitle(title)

        window.window.update(self)

        # get lines to display
        empty= [["", "", "", ""]]
        if aitem is not None:
            info = aitem.getinfo()
        else:
            info = []
        l = info + empty*(4-len(info))

        colsep = self.iw > 45

        # calculate width of columns
        wc1 = max( len(l[0][0]), len(l[1][0]), len(l[2][0]), len(l[3][0])) + colsep
        wc3 = max( len(l[0][2]), len(l[1][2]), len(l[2][2])) + colsep
        wc4 = 5
        wc4 = max( len(l[0][3]), len(l[1][3]), len(l[2][3]))
        wc2 = self.iw-wc1-wc3-wc4-1

        for lno in range(4):
            self.move(1+lno, self.ix)
            l0 = encoding.encode(l[lno][0])
            l1 = encoding.encode(l[lno][1])
            self.addstr(l0.ljust(wc1)[:wc1], self.colors.description)
            self.addstr(l1.ljust(wc2)[:wc2], self.colors.content)
            self.addch(" ")
            if lno != 3 or isinstance(aitem, item.diritem):
                l2 = encoding.encode(l[lno][2])
                l3 = encoding.encode(l[lno][3])
                self.addstr(l2.ljust(wc3)[:wc3], self.colors.description)
                self.addstr(l3.ljust(wc4)[:wc4], self.colors.content)
            else:
                l2 = encoding.encode(l[3][-2])
                l3 = encoding.encode(l[3][-1])
                # special handling of last line for songs
                wc3 = max(len(l2), 5) + colsep
                wc4 = max(len(l3), 5)

                self.move(1+lno, self.iw-wc3-wc4-1-self.ix)
                self.addch(" ")
                self.addstr(l2.ljust(wc3)[:wc3], self.colors.description)
                self.addstr(l3.ljust(wc4)[:wc4], self.colors.content)
예제 #44
0
import encoding
import protein_translation
import sys

switch = sys.argv[1]
filename = sys.argv[2]

with open(filename, 'r') as f:
    if switch == 'encoding':
        text = f.readline().strip()
        peptide = f.readline().strip()
        print('\n'.join(encoding.encode(text, peptide)))

    else:
        input = f.readline().strip()
        print(protein_translation.translate(input))
예제 #45
0
파일: main.py 프로젝트: Gebon/BMP
from encoding import encode
from decoding import decode
from additional import create_argument_parser

parser = create_argument_parser()
args = parser.parse_args()

if not args.encode is None:
    encode(args.encode[0], args.encode[1], args.encode[2],
           args.bit_count)
elif not args.decode is None:
    decode(args.decode[0], args.decode[1])
else:
    print("You don't specified neither -e nor -d option")
    exit(1)
예제 #46
0
파일: osdtitle.py 프로젝트: indera/PyTone
 def playbackinfochanged(self, event):
     if event.playbackinfo.song and event.playbackinfo.song != self.previoussong:
         song = encoding.encode(event.playbackinfo.song.format(self.config.songformat, safe=True))
         os.system('echo "%s" | %s &' % (song, self.command))
         self.previoussong = event.playbackinfo.song